Compare commits

...
39 Commits
Author SHA1 Message Date
Aleksander Grygier fa9f928f25 ui: move the demo harness to ui/lib/demo and render videos on the Llama brand (#33125)
* ui: render demo videos in a window on a brand ground

A demo video is now rendered from the recorded frames: the app in a rounded window on a Llama brand ground, camera zooms with motion blur, captions under the window, and an optional logo card. DEMO_POLISH=0 gives the plain screencast as before.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: let demos mock llama-server and record Storybook stories

Assisted-by: Claude (Opus 5.5 Medium)

* ui: check chat search end to end against a mocked llama-server

Assisted-by: Claude (Opus 5.5 Medium)

* ui: add a skill to demo, test and document Llama Chat and Llama UI changes

Assisted-by: Claude (Opus 5.5 Medium)

* ui: describe the demo render in the README and the ui-demo skill

Assisted-by: Claude (Opus 5.5 Medium)

* ui: zoom the whole stage in demo videos, show taps on touch demos

The camera now moves over the stage, so the window comes closer with its corners and the ground round it. The render runs in a Chromium of its own at 1x. A touch device shows a fingertip tap in place of the cursor.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: make the demo camera moves shorter and snappier

Assisted-by: Claude (Opus 5.5 Medium)

* ui: fix tiled shadows when the demo camera zooms in

Each copy of the window is now laid out where the camera puts it instead of scaled with a transform: Chromium cut the scaled shadow into tiles, which left light rectangles round a zoomed window. The motion blur now spans half a frame, like a 180 degree shutter.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: draw the zoomed demo window on one canvas

The motion blur copies are drawn on one stage canvas, with the squircle corners and the shadow in 2D, instead of as one layer each: twelve large layers overran Chromium's tile memory while the camera moved, and the dropped tiles showed as light blocks round the window.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: leave phone demos unzoomed in the ui-demo skill and README

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show each demo video beside its description in the PR

A test's description annotation is written to the video manifest; when the tests have one, the Demo section puts one video to a row with its title and description.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: move the demo harness to ui/lib/demo

The recorder, the render, the Demo driver, storage and the pr and docs commands are now @ggml-org/llama-demo in ui/lib/demo, for any app in the suite. It imports only Playwright's types: the app passes in its page, so it runs from source with nothing installed. Llama Chat keeps its fixtures, servers and traces command in its demo folder.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: harden the demo render and the pr command

The render cleans up after a failure and removes the part-written mp4. A page the render cannot frame records plainly instead of losing its captions, demos fail early outside Chromium, and the render's extra time is added after the demo, so a test.setTimeout() in it cannot take it away. demo:pr finds the app in the worktree from git's own prefix, a description's line breaks stay inside its table cell, zoomIn scrolls its target into view, and a quick second tap keeps its fingertip.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: teach the ui-demo skill to shape, check and publish a demo

Assisted-by: Claude (Opus 5.5 Medium)

* ui: import the demo harness as @ggml-org/llama-demo

Llama Chat adds ui/lib/demo as a local file: dependency, which npm links, and imports it by name instead of by relative path. Nothing is published; npm ci leaves a link that only the demo commands follow.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 17:15:39 +01:00
Aman Gupta 0e4e925e8f CUDA: fuse the Inkling 2 short conv, depth mix, loop controller, L2 clip and situ chains (#33060)
* model : inkling2 order the conv ops so backends can fuse them

* CUDA: fuse the Inkling 2 short conv, depth mix, loop controller, L2 clip and situ chains
2026-11-26 23:15:36 +08:00
Gabor Nagy 6aad4c7efd nix : remove x86_64-darwin support (#33114)
26.05 is the last release to support x86_64-darwin and support for this
platform was dropped in 26.11.
2026-11-26 15:58:09 +01:00
Ruben Ortlam 46ba8b7008 vulkan: fix Windows driver RDNA1 architecture misclassification (#33123) 2026-11-26 15:56:30 +01:00
Jesse 436d7e81ca DPI setting for PDF as Images - Inkling-2-Mini-BF16's work (#33061) 2026-11-26 14:57:50 +01:00
Nick Towle a866b4ade6 ui: pass theme to toasts (#33082) 2026-11-26 14:12:27 +01:00
Radoslav Gerganov 4ba835c637 tests : add RPC support to test-llama-archs (#33112)
Running test-llama-archs with an RPC device is quite useful as an
integration test for the RPC backend. Here is a sample run with the
Vulkan backend:

ggml-rpc-server -d Vulkan1
test-llama-archs --rpc 127.0.0.1:50052 -b RPC0
2026-11-26 14:57:25 +02:00
Karlis 689194808a quantize : include clocale for std::setlocale (#33105)
[no ci]
2026-11-26 13:56:00 +01:00
thelittlefiremanandSigbjørn Skjæret fd4b137e38 CI: add Hip occupancy check and small static analysis report (#32365)
* ci: check for occupancy regressions vs master in HIP quality check

Add scripts/hip/gcn-cdna-occupancy-check.py, which compares per-kernel
occupancy between two GGML_HIP_EXPORT_METRICS build logs and fails when
a kernel drops occupancy. Wire it into the HIP quality check workflow:
the baseline (master) is built with the same target and flags, then
compared against the PR build.

Assisted-by: Hermes Agent

* ci: reuse spill-check build and cache master baseline for occupancy check

The PR-side metrics.log is shared with the VGPR spill check, so the
occupancy comparison adds no extra PR build. The master baseline metrics
log is cached by master-push runs and restored on PRs; it is only
rebuilt as a fallback when the master tip has no cached baseline.

* ci: report occupancy and spill changes as a markdown artifact

Extend gcn-cdna-occupancy-check.py to also compare per-kernel VGPR and
SGPR spills, and add a --report option that writes a markdown report
with all regressions and improvements. The workflow uploads the report
as an artifact on PRs, even when the check fails.

* ci: split metrics check and markdown report into separate scripts

gcn-cdna-metrics-check.py compares per-kernel occupancy and spills and
can dump all deltas as TSV; gcn-cdna-metrics-report.py generates the
markdown report from that dump. The workflow runs both on PRs and
uploads the report as an artifact.

* ci: consolidate HIP kernel metrics checks using Clang YAML remarks

Merge VGPR threshold, occupancy/spill comparison, and Markdown reporting
into one script with unchanged checking rules and output formats. Parse
per-kernel optimization records instead of interleaved text diagnostics.
Add unit tests and update the CI baseline cache to contain YAML records.

* ci: preserve comparison kernel selection and fix Python indentation

Count only kernels with occupancy or spill remarks, as before the YAML
migration. Add a regression test for VGPR-only records and fix flake8.

* ci: fix Python type checking for HIP metrics scripts

Cast metric entries to lists before appending and check the dynamic
module spec and loader are available before executing the tests.
Preserve existing checks and reports.

* ci: add blocking and warning HIP kernel regression rules

Preserve the VGPR limit and its exemptions, block spill increases and
occupancy drops with increasing VGPRs, and warn on occupancy-only drops.
Collect all findings and generate the report before failing CI.

Request device optimization records explicitly and bypass ccache during
metrics builds; print YAML diagnostics to investigate missing kernel
resource remarks in ROCm 7.2.1.

* ci: preserve device-only HIP optimization records

Do not enable host remarks: Clang writes host and device optimization
records to the same output path. Filter the device records to kernel
resource usage and validate the compiler output before expensive builds.
Invalidate old baseline caches and avoid reporting a missing TSV.

* ci: include HIP runtime in metrics probe

Assisted-by: ChatGPT

* ci: build only ggml-hip for kernel metrics and propagate build errors

Assisted-by: ChatGPT

* ci: match HIP baseline to merge commit and publish job summary

Assisted-by: ChatGPT

* ci: trust the HIP CI checkout directory before resolving baseline

Assisted-by: ChatGPT

* ci: cache HIP baseline metrics in HF buckets

Assisted-by: ChatGPT

* ci: publish HIP metrics report to logs and job summary

Assisted-by: ChatGPT

* Ci: hip auto clean every 30 days

Assisted-by: ChatGPT

* Update .github/workflows/hip-quality-check.yml

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>

* ci: fix conflits and rebase

Assisted-by: ChatGPT

---------

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
2026-11-26 14:50:32 +02:00
Ruixiang WangandNikita Belokopytov 55d482814b DFlash2: support Inkling-2-Mini DFlash2 (#33073)
* support inkling2 DFlash2

* address review comments

Assisted-by: Claude Opus 5.5
Co-authored-by: Nikita Belokopytov <belokopytov.n@gmail.com>

---------

Co-authored-by: Nikita Belokopytov <belokopytov.n@gmail.com>
2026-11-26 14:47:55 +02:00
PascalandGeorgi Gerganov 7365e4793c tests : take the test-fusion moe flag from the fixture name (#33104)
* tests : take the test-fusion moe flag from the fixture name

The moe flag came from the arch name, so the dense and MoE fixtures
of an arch shared a baseline key, and MoE-only archs were keyed as
dense. Read it from the -dense/-moe suffix written by
test-llama-archs and regenerate the Metal baseline. Only the moe
column changes, no count moves.

* Apply suggestion from ggerganov

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>

---------

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2026-11-26 14:44:02 +02:00
Sigbjørn Skjæret b16f15350a ci : move vulkan-nvidia runners to dgx spark (#33113)
* move vulkan-nvidia runners to dgx spark

* --sudo
2026-11-26 13:42:59 +01:00
Aman Gupta b671865c7b CUDA: move the fusion code out of ggml-cuda.cu (#33087)
Move the fusion matchers, ggml_cuda_can_fuse, ggml_cuda_try_fuse and the
fusion alloc deps of graph_optimize into fusion.cu, unchanged.
fusion.cuh exports ggml_cuda_try_fuse and ggml_cuda_fusion_add_alloc_deps.
The GGML_CUDA_DISABLE_FUSION check is done by the two callers, and
ggml_cuda_is_view_or_noop moves to common.cuh since the compute loop
also uses it.
2026-11-26 18:58:44 +08:00
Aleksander Grygier 8c6418001d ui: read the Enable MCP setting through one getter (#33067)
uiStore.isMcpEnabled and mcpStore.isFeatureEnabled read the same setting. The MCP store's getter stays, and the two callers of the UI store's use it.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 11:53:21 +01:00
anujj 09c1410642 ggml : support a BF16 src1 in MUL_MAT and MUL_MAT_ID (CPU, CUDA) (#32533)
* ggml : support a BF16 src1 in MUL_MAT and MUL_MAT_ID (CPU, CUDA)

* ggml : fix MMVF expert offset overflow and tighten BF16 src1 gates

* ggml : strided BF16 src1 tests, explicit MUSA Q2_K rule, MMVF offset fix moved to its own PR

* cuda : move the MUL_MAT_ID MMVF rule into ggml_cuda_should_use_mmvf

* cuda : read a BF16 src1 in MMVF through a template parameter, for BF16 and FP8 weights only

* cuda : MMVF src1 pairs via ggml_cuda_cast, rename type to type_src0
2026-11-26 15:59:27 +05:30
Aman Gupta 28148b5f06 llama : refuse SPLIT_MODE_TENSOR for Hadamard-folded models (#33080)
Prism Bonsai models (prism.hadamard) aborted in the meta backend with
GGML_ASSERT(split_state.ne[j] % div == 0) when loaded with -sm tensor:
the ssm_out input permutation from tiled to grouped GDN head order
reshapes the head-split activation to [hd, n_k, n_rep] and the split
lands on n_rep (3 for 2 devices). Past that, the explicit sign vectors
are mirrored while their inputs are split, and the 1024-wide rotation
blocks would straddle the device slices of ffn_down (17408 = 17 blocks).

Fail at load with a clear message instead.

Assisted-by: Claude Opus 5.5
2026-11-26 11:44:26 +02:00
Aman Gupta 51ab45e3c5 CUDA: fuse the top-k MoE weight norm with an additive sum bias (#32943)
Assisted-by: Claude Opus 5.5
2026-11-26 11:30:42 +02:00
Aman Gupta caea914e9d CUDA: loop over ne2/ne3 in non-contiguous concat (#33006)
The non-contiguous concat kernel mapped dst ne[2] and ne[3] directly to
gridDim.y and gridDim.z, which are limited to 65535. Larger tensors made
the launch fail with "invalid configuration argument". Cap the grid and
loop over the remaining rows in the kernel.

Fixes #32956

Assisted-by: Claude Opus 5.5
2026-11-26 11:29:58 +02:00
Pascal e38ea719bd CUDA: fix ROCm CI, do not pick the tile FA kernel for DKQ 576 with a GQA ratio not divisible by 4 (#33045)
* CUDA: flash attention tile kernel for DKQ 576 with a GQA ratio of 2

The tile kernel for 576/512 only had variants for GQA ratios that are
multiples of 4, while the kernel selection accepts any ratio from 2,
so an MLA attention with a ratio of 2 aborted on GPUs that use the
tile kernel, such as RDNA. Add the 2 column configuration, copied from
the 512/512 one of each table, and dispatch even ratios to it. Odd
ratios have no tile variant: the selection now reports them as
unsupported instead of picking the tile kernel. Cover the ratios 2
and 3 in test-backend-ops.

* CUDA: pass the K/V types to the tile kernel for 576 with a GQA ratio of 2

#32901 added the K and V types as template parameters of the tile kernel,
the ratio 2 dispatch for DKQ 576 still used the old parameter list.

* CUDA: report DKQ 576 with a GQA ratio not divisible by 4 as unsupported by the tile kernel

Use the selection instead of a new tile specialization, as suggested in
review: drop the 2 column variant and only pick the tile kernel for
576/512 when the GQA ratio is a multiple of 4, the ncols2 = 4 and 16
variants it has. The ncols2 = 4 variant cannot serve a ratio of 2, a
block reads a single K/V head.
2026-11-26 11:25:33 +02:00
Aleksander Grygier 074f1f3f73 ui: npx llama-chat talks to llama-server on :9931 by default (#33095)
Without --server, the CLI's config.json now points the app at
llama-server's default port on the host the page was opened from,
instead of the CLI's own address, which has no API and answered 404.
Bump @ggml-org/llama-chat and llama-chat to 0.3.1.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 08:52:24 +01:00
Georgi Gerganov 1715275226 sync : ggml 2026-11-26 09:38:27 +02:00
Georgi Gerganov 2a59da5bf2 ggml : bump version to 1.1.1 (ggml/1703)
* ggml : bump version to 1.1.1

* authors : update
2026-11-26 09:38:27 +02:00
Alan Zhai 07ba74babd sycl: update linux refer doc (#32583) 2026-11-26 00:41:32 -05:00
Todd Malsbary 267dda8180 sycl: Remove check for host waits in fattn-mkl from graph checks (#31208)
Signed-off-by: Todd Malsbary <todd.malsbary@intel.com>
2026-11-26 00:40:10 -05:00
Max Krasnyansky e0f884d405 ggml-hexagon 2.0 : support for int-hmx, automatic f32 -> f16 lowering, and generic dma pipelines (#32582)
* hexagon : add DMA pipeline, htp_tensor_read, and cache/mdev cleanup

- Add dma-proxy thread/ring for main-thread DMA offload (clamp n_hvx <= hw_nth - 2)
- Add syncht in hmx-queue after HMX VTCM stores

* hexagon : add F16/collapse graph lowering and fusion updates

* hexagon : update host kparams solver for W8A8 HMX, F16, and DMA

* hexagon : add INT-HMX W8A8 matmul, F16 support, and DMA writeback

- Use 64-col dual-acc (weight.b:deep + mxswapacc) across all arches and :cm activation layout
- Pre-issue chunk-0 weight DMA via dma_proxy, balance 4-row quad output threads, and defer output DMA pop

* hexagon : add HMX W8A8 Q8_0 KV flash attention and DMA writeback

hex-fa: cleanup dma_queue usage and mask buffers
hex-fa: fix new op tests and corner cases
hex-fa: cleanup kernel selection and solver
hex-fa: improve decode performance (split-kv)

* hexagon : add F16, DMA, and micro-kernel optimizations for unary/norm ops

* hexagon : add mixed F16/F32 and HVX optimizations for binary ops

* hexagon : add F16, DMA, and state fusion for gated-delta-net

Alsp pipeline GDN HMX/HVX with batched dispatch and spill-free inversion

* hexagon : add F16, token-major fusion, and DMA updates for SSM ops

* hexagon : add F16 and HVX optimizations for rope, softmax, and glu

rope: optimize init and add common fast-path

* hexagon : add F16, DMA, and spill fixes for argsort and top-k

* hexagon : add F16 lowering and optimizations for lightning-indexer and dsv4

* hexagon : add F16 and DMA updates for row and concat ops

* hexagon : convert simple ops to dma-pipeline, F16, and warning/mdev cleanup

* hexagon: add support for fusing MUL_MAT_NX with GLU ops (GEGLU,SWIGLU,...)

- Double-buffer vtcm_up/vtcm_wt_scales_up, add 0-spill direct loop0 FP16 GLU strip kernels, trim sub-ULP FP16 sigmoid terms
- Balance 4-row quad GLU threads, defer output DMA pop, and pre-issue chunk-0 weight DMA via dma_proxy

* tests : add F16/mixed-type and Hexagon op test cases

For now do not include ssm_conv tests that break ggml-metal

* hexagon : update trace and run scripts

* hexagon : update Snapdragon backend README and developer docs

Includes updated tensor tiling description (it is 32x4 now)

--
Co-authored-by: Ehsan Bateni <ebateni@qti.qualcomm.com>
Co-authored-by: Todor Boinovski <todorb@qti.qualcomm.com>
Co-authored-by: Trivikram Reddy <tamarnat@qti.qualcomm.com>
Co-authored-by: Yanzhao Wang <yanzhaow@qti.qualcomm.com>

Assisted-by: Antigravity
2026-11-25 20:59:59 -08:00
anujj f8b7ed5250 cuda : fix int overflow of the MMF matrix offsets (#33044) 2026-11-26 10:19:40 +05:30
gianni-cor 55b2238be8 ggml : add TANH backward pass (#32136)
Build the gradient dy * (1 - y^2) from the forward output with existing
ops, no new op is needed. Add TANH to the gradient-checked unary ops.

Signed-off-by: gianni-cor <gianfranco.cordella@tether.io>
2026-11-26 12:38:00 +08:00
Clemens Wasser a8ad690ca9 sycl: add gated delta net ESIMD kernel (#31762) 2026-11-25 21:38:28 -05:00
cwriter aee03fbe80 sycl: fuse recurrent convolution windows (#31355) 2026-11-25 21:12:07 -05:00
Aleksander Grygier 9c003a97ab ui: open settings, the + menu and the model picker as sheets on phones, and manage MCP from settings (#33036)
* ui: add inset lists, rounder bottom sheets and a native select to the design system

Inset lists (grouped rows with inset dividers, titles and captions) are surface utilities in llama-ui, documented in DESIGN.md and the Surfaces story. Bottom drawers get the sheet radius and rounder inset groups, switches a finger-sized variant, and SearchInput an inputClass prop.

NativeSelect is a trigger styled like the app's select that opens the OS's own picker, and useSheetPages a page stack with slide transitions for sheets.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: open settings and the add menu on phones as sheets of inset pages, and manage MCP from settings

On a phone, Settings is a full-height sheet over the sidebar: theme tiles, then a row per section that pushes the section's page, with Tools, tool groups and MCP servers as further pages. Changes apply as they are made. Selects open the OS picker, number fields are 16px so iOS does not zoom, and switches are finger-sized.

The + menu is a sheet of the same inset pages, which stays open while the file picker is up. Settings and a primary New chat button sit at the bottom of the phone sidebar, and Show less sticks to the bottom of the chat list.

Show MCP becomes Enable MCP: while it is off, no MCP server is connected and chats get no MCP tools. The servers are managed from Settings, in a dialog on the desktop and a page in the phone sheet; the sidebar entry and /mcp-servers are removed. Someone who already added a server gets Enable MCP on.

A setting can name the devices it applies to, and is listed only there. Switching sections scrolls back to the top, the system message has a placeholder, inputs offer no browser autofill, the desktop settings sidebar sits on the dialog's background, and the sidebar footer groups its rows only when it shows more than one.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: pick models on a phone from a short sheet, and list the desktop selector's models without a Local models section

On a phone, the model picker opens on a short view: the chat's model, the dictation model, loaded models, favorites and recent ones, marked In chat and Dictation. A tap switches the model; holding a row opens its menu, with More details and Unload for a loaded model. All models is a page of its own, in the same grouped rows. The reasoning effort keeps its list of levels, above the search, which is a SearchInput at the foot of the sheet in the chat form's surface.

On the desktop, the server's models are listed in their family groups without a Local models section around them. They sit in an Other models section only when favorites or loaded models are listed above them, and the section headings have no icons.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: let demos touch, hold and seed chats, and import traces through either settings section

demo.tap and demo.hold drive touch input on a phone viewport, a chats option seeds the sidebar with conversations, and trace imports find Data or Import/Export in the settings.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: release llama-ui 0.7.0 and llama-chat 0.3.0

Llama UI gains the sheet components (SheetHeader, SheetPages, InsetList and its rows) and NativeSelect; Llama Chat gains the phone sheets and Enable MCP.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 22:39:55 +01:00
PascalandGeorgi Gerganov 7135e2fd69 metal : spread the short mat-vec lanes over src1 rows (#33034)
* metal : spread the short mat-vec lanes over src1 rows

The short mat-vec kernel (K < 32) mapped its 32 lanes to 32 src0 rows
and handled one src1 row per threadgroup, so with few src0 rows most
lanes were idle. It now covers min(ne01, 32) src0 rows of 32/that src1
rows.

This is the weighted sum over the depth states of Inkling 2 since
#32855 (1-3 src0 rows, K = number of states, 2304 src1 rows).
Inkling-2-Mini UD-Q4_K_XL, M5 Max, master -> this PR:
  pp512 888 -> 1052 t/s, pp2048 771 -> 894 t/s, tg128 unchanged.
PPL and greedy output bit-identical, the graph is unchanged.

Tested: test-backend-ops -b MTL0 -o MUL_MAT (new small-K cases).

* cont : clean-up comment

---------

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2026-11-25 22:39:14 +01:00
Sergio Sánchez VallésandSergio Sanchez 5917b39ff7 convert : map the Inkling-2 LoRA tensor names (#33055)
PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention output gate (self_attn.o_proj.gate_proj.weight); neither is in the Inkling-2 tensor map, so convert_lora_to_gguf.py stops with 'Can not map tensor'. Strip the .linear. segment and map the gate to ATTN_GATE.

Co-authored-by: Sergio Sanchez <sergiosv96@users.noreply.github.com>
2026-11-25 20:49:09 +01:00
bri-prism 8d35ba4f7b metal : revert "metal: increase default command buffers on iPhone (#31815)" (#33050)
This reverts commit 1f3ea67fbf.
2026-11-25 20:28:59 +01:00
Gabor Nagy acb269e511 nix : fix build on darwin (#32955)
`darwin.apple_sdk` is deprecated and has been removed. It's not needed
anymore to build on darwin.
2026-11-25 20:27:14 +01:00
lhez d9dae03443 opencl: Adreno E17 compiler quirks off by default (#33013) 2026-11-25 11:20:30 -08:00
Aleksander Grygier eb56575095 ui: stop the streaming reply with Escape (#33051)
Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 20:02:31 +01:00
5a09582d80 model : add RAON-1-mini-preview support (#32176)
* vocab : add RAON pre-tokenizer and NFC normalization
* model : add RAON hybrid attention and mHC graph
* convert : add MXFP8 weight dequantization
* convert : add RAON HF to GGUF conversion and schema
* chat : add the RAON chat template
* tests : add RAON vocab regression files for test-tokenizer-0
* llama-quant : add RAON quantization rules for attention projections
* vocab : move RAON to the standard tokenizer list and remove its dedicated tokenizer test
* convert : move MTP layer check to filter_tensors and correct comment on _KEEP_UNQUANTIZED
* convert : add orphan-scale gurad for MXFP8 scales
* model : remove redundant graph expansion, use require() for RDA head size validation, and add comment for MLA latent normalization
* llama : share KDA conv1d between Raon and Kimi K3
* convert : remove redundant MXFP8 dequantization
* model : align RAON MoE call formatting with other models
* tests : remove RAON quantization test
* model : match RAON MoE weight normalization to the HF reference
* set expert_weights_norm_eps to 1e-20, which introduced in commit 5c008e0
* tests : add Metal fusion test for Raon

Assisted-by: Codex
Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Dong Won Kim <63934649+ddwkim@users.noreply.github.com>
Co-authored-by: Hyeonghwan Kim (김형환) <kim2h7903@krafton.com>
Co-authored-by: Seohyun Choi <seohyun.choi@krafton.com>
Co-authored-by: Piotr Wilkin <piotr.wilkin@syndatis.com>
2026-11-25 19:38:12 +01:00
Piotr Wilkin (ilintar) 2d5b3ddde3 model: use the indexed bias in the Inkling 2 graph (#33053)
* use the indexed bias in the Inkling 2 graph
* Remove RPC check
2026-11-25 19:01:27 +01:00
Johannes Gäßler 94a1e4b722 CUDA: refactor & deduplicate FA data loading (#32901)
* CUDA: refactor & deduplicate FA data loading

* fix float2 indexing

* fix hip quality check
2026-11-25 18:47:26 +01:00
417 changed files with 52930 additions and 19715 deletions
+1 -14
View File
@@ -13,7 +13,6 @@
blas,
cudaPackages,
autoAddDriverRunpath,
darwin,
rocmPackages,
vulkan-headers,
vulkan-loader,
@@ -104,17 +103,6 @@ let
ln -s /usr/bin/xcrun $out/bin
'';
# apple_sdk is supposed to choose sane defaults, no need to handle isAarch64
# separately
darwinBuildInputs =
with darwin.apple_sdk.frameworks;
[
Accelerate
CoreVideo
CoreGraphics
]
++ optionals useMetalKit [ MetalKit ];
cudaBuildInputs = with cudaPackages; [
cuda_cudart
cuda_nvml_dev
@@ -244,8 +232,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
++ optionals syclAot [ oclocAot ];
buildInputs =
optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs
++ optionals useCuda cudaBuildInputs
optionals useCuda cudaBuildInputs
++ optionals useMpi [ mpi ]
++ optionals useRocm rocmBuildInputs
++ optionals useBlas [ blas ]
+58 -58
View File
@@ -49,94 +49,94 @@ env:
jobs:
gpu-vulkan-nvidia-cm:
# runs-on: "hf-jobs-t4-small:ubuntu26_04"
runs-on: [self-hosted, Linux, NVIDIA]
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
# - name: Install dependencies
# run: |
# sudo apt update
# sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
- name: Install dependencies
run: |
apt update
apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
# - name: ccache
# uses: ggml-org/ccache-action@v1.2.24
# with:
# restore: false
# save: false
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
# - name: ccache-buckets-restore
# uses: ./.github/actions/ccache-buckets
# with:
# key: self-hosted-vulkan-nvidia-cm
# folder: llama.cpp
# hf_bucket: ggml-org/cache
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
with:
key: self-hosted-vulkan-nvidia-cm-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
- name: Test
id: ggml-ci
run: |
vulkaninfo --summary
GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp
GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
# - name: ccache-buckets-save
# if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
# uses: ./.github/actions/ccache-buckets
# env:
# HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
# with:
# key: self-hosted-vulkan-nvidia-cm
# folder: llama.cpp
# evict-old-files: 1d
# hf_bucket: ggml-org/cache
# save: true
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: self-hosted-vulkan-nvidia-cm-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
gpu-vulkan-nvidia-cm2:
# runs-on: "hf-jobs-t4-small:ubuntu26_04"
runs-on: [self-hosted, Linux, NVIDIA, COOPMAT2]
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
# - name: Install dependencies
# run: |
# sudo apt update
# sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
- name: Install dependencies
run: |
apt update
apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
# - name: ccache
# uses: ggml-org/ccache-action@v1.2.24
# with:
# restore: false
# save: false
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
# - name: ccache-buckets-restore
# uses: ./.github/actions/ccache-buckets
# with:
# key: self-hosted-vulkan-nvidia-cm2
# folder: llama.cpp
# hf_bucket: ggml-org/cache
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
with:
key: self-hosted-vulkan-nvidia-cm2-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
- name: Test
id: ggml-ci
run: |
vulkaninfo --summary
GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp
GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
# - name: ccache-buckets-save
# if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
# uses: ./.github/actions/ccache-buckets
# env:
# HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
# with:
# key: self-hosted-vulkan-nvidia-cm2
# folder: llama.cpp
# evict-old-files: 1d
# hf_bucket: ggml-org/cache
# save: true
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: self-hosted-vulkan-nvidia-cm2-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
gpu-vulkan-apple:
runs-on: [self-hosted, macOS, ARM64]
+204 -11
View File
@@ -11,7 +11,8 @@ on:
'**/*.cuh',
'ggml/src/ggml-hip/CMakeLists.txt',
'ggml/src/ggml-cuda/vendors/hip.h',
'scripts/hip/gcn-cdna-vgpr-check.py'
'scripts/hip/gcn-cdna-metrics.py',
'scripts/hip/test_gcn_cdna_metrics.py'
]
pull_request:
@@ -22,7 +23,8 @@ on:
'**/*.cuh',
'ggml/src/ggml-hip/CMakeLists.txt',
'ggml/src/ggml-cuda/vendors/hip.h',
'scripts/hip/gcn-cdna-vgpr-check.py'
'scripts/hip/gcn-cdna-metrics.py',
'scripts/hip/test_gcn_cdna_metrics.py'
]
cache-mode: none
@@ -45,15 +47,32 @@ jobs:
runs-on: ubuntu-22.04
container: rocm/dev-ubuntu-22.04:7.2.1
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
- name: Dependencies
id: depends
run: |
sudo apt-get update
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip jq
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip python3-yaml jq
- name: Clone
id: checkout
uses: actions/checkout@v6
with:
fetch-depth: 2
# The first parent of the tested merge commit is the exact baseline.
- name: Get baseline SHA
if: ${{ github.event_name == 'pull_request' }}
id: master_sha
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git rev-parse --verify HEAD^2 > /dev/null
baseline_sha=$(git rev-parse HEAD^1)
pr_sha=$(git rev-parse HEAD)
printf 'sha=%s\npr_sha=%s\n' "$baseline_sha" "$pr_sha" >> "$GITHUB_OUTPUT"
printf 'Baseline commit: %s\nPR merge commit: %s\n' "$baseline_sha" "$pr_sha"
- name: Test HIP kernel metrics scripts
run: python3 -m unittest discover -s scripts/hip -p 'test_gcn_cdna_metrics.py'
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
@@ -70,6 +89,21 @@ jobs:
folder: llama.cpp
hf_bucket: ggml-org/cache
# Verify device optimization records before starting the expensive builds.
- name: Validate HIP resource remarks
run: |
mkdir -p hip-metrics-probe
cd hip-metrics-probe
printf '%s\n' '#include <hip/hip_runtime.h>' '__global__ void metrics_probe(float * out) { *out = 1.0f; }' > probe.hip
"$(hipconfig -l)/clang" -x hip --offload-arch=gfx908 -O2 -c probe.hip -o probe.o \
-Rpass-analysis=kernel-resource-usage --save-temps \
-Xarch_device -fsave-optimization-record=yaml \
-Xarch_device -foptimization-record-passes=kernel-resource-usage
for metric in NumVGPR Occupancy VGPRSpill SGPRSpill; do
grep -q "Name: *$metric$" probe.opt.yaml || { echo "Missing $metric in GPU optimization records"; exit 1; }
done
python3 ../scripts/hip/gcn-cdna-metrics.py vgpr probe.opt.yaml
- name: Build with Werror
id: cmake_build
run: |
@@ -83,19 +117,178 @@ jobs:
cd build
make -j $(nproc)
- name: Check for major VGPR spills
- name: Build HIP kernel resource metrics
id: vgpr_check
shell: bash
run: |
cmake -B build -S . \
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
-DGPU_TARGETS=gfx908 \
-DGGML_HIP=ON \
-DGGML_HIP_EXPORT_METRICS=On \
-DCMAKE_HIP_FLAGS="" \
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
-DCMAKE_BUILD_TYPE=Release
cd build
make -j $(nproc) 2>&1 | tee metrics.log | grep -v 'Rpass-analysis=kernel-resource-usage\|remark:\|^$'
python3 ../scripts/hip/gcn-cdna-vgpr-check.py metrics.log
set -o pipefail
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
echo "Optimization record files:"
find . -type f -name '*.opt.yaml' | sed -n '1,10p'
echo "GPU kernel remarks in YAML:"
grep -rl --include='*.opt.yaml' 'kernel-resource-usage' . | sed -n '1,10p' || true
echo "First YAML record:"
first_yaml=$(find ggml/src/ggml-hip -type f -name '*.opt.yaml' -print -quit)
if [ -n "$first_yaml" ]; then head -n 35 "$first_yaml"; fi
echo "GPU resource diagnostics in compiler log:"
grep -m 3 'Function Name:' metrics.log || true
# The PR comparison evaluates every rule and reports all failures at the end.
- name: Check VGPR limit on master
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
run: python3 scripts/hip/gcn-cdna-metrics.py vgpr build/ggml/src/ggml-hip
# On master pushes, cache the device optimization records as the baseline for PR checks.
- name: Save master metrics baseline
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
run: |
mkdir -p hip-baseline-metrics
find build/ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} hip-baseline-metrics/ \;
- name: Cache master metrics baseline
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
run: |
if [ -n "$HF_TOKEN" ]; then
tar -czf hip-baseline-metrics.tar.gz -C hip-baseline-metrics .
.venv-hf/bin/hf buckets cp hip-baseline-metrics.tar.gz "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ github.sha }}.tar.gz" || echo "Failed to save HIP metrics baseline"
fi
- name: Remove old HIP metrics baselines
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
shell: bash
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
run: |
if [ -z "$HF_TOKEN" ]; then
exit 0
fi
if ! cache_files=$(.venv-hf/bin/hf buckets list "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-" --json | jq -r '
.[]
| select(.type == "file")
| select(.path | endswith(".tar.gz"))
| select(try ((.uploaded_at | .[:19]+"Z" | fromdateiso8601) < (now - 30 * 24 * 60 * 60)) catch false)
| .path
'); then
echo "Failed to list HIP metrics baselines"
exit 0
fi
while IFS= read -r cache_path; do
[ -n "$cache_path" ] || continue
.venv-hf/bin/hf buckets rm "hf://buckets/ggml-org/cache/$cache_path" -y || echo "Failed to remove $cache_path"
done <<< "$cache_files"
# Restore the device optimization records for the exact baseline commit.
- name: Restore master metrics baseline
if: ${{ github.event_name == 'pull_request' }}
id: baseline_cache
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
run: |
cache_url="hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ steps.master_sha.outputs.sha }}.tar.gz"
if .venv-hf/bin/hf buckets cp "$cache_url" hip-baseline-metrics.tar.gz; then
mkdir -p hip-baseline-metrics
if tar -xzf hip-baseline-metrics.tar.gz -C hip-baseline-metrics && [ -n "$(find hip-baseline-metrics -type f -name '*.opt.yaml' -print -quit)" ]; then
echo "cache-hit=true" >> "$GITHUB_OUTPUT"
echo "Restored HIP metrics baseline from HF Buckets"
else
rm -rf hip-baseline-metrics
echo "Invalid HIP metrics baseline cache"
fi
rm -f hip-baseline-metrics.tar.gz
else
echo "No HIP metrics baseline in HF Buckets; building from source"
fi
# Fallback when the baseline commit has no cached metrics.
- name: Checkout baseline (master)
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
uses: actions/checkout@v6
with:
ref: ${{ steps.master_sha.outputs.sha }}
path: hip-baseline
- name: Build master metrics baseline
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
shell: bash
run: |
cd hip-baseline
cmake -B build -S . \
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
-DGPU_TARGETS=gfx908 \
-DGGML_HIP=ON \
-DGGML_HIP_EXPORT_METRICS=On \
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
-DCMAKE_BUILD_TYPE=Release
cd build
set -o pipefail
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
mkdir -p ../../hip-baseline-metrics
find ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} ../../hip-baseline-metrics/ \;
- name: Check kernel resource rules vs master
if: ${{ github.event_name == 'pull_request' }}
id: occupancy_check
env:
BASELINE_SHA: ${{ steps.master_sha.outputs.sha }}
PR_SHA: ${{ steps.master_sha.outputs.pr_sha }}
run: |
# The PR optimization records come from the VGPR spill check build above, so
# this step adds no extra build when the baseline cache hits.
python3 scripts/hip/gcn-cdna-metrics.py compare hip-baseline-metrics build/ggml/src/ggml-hip \
--dump hip-kernel-metrics-deltas.tsv || check_failed=true
if [ ! -s hip-kernel-metrics-deltas.tsv ]; then
echo "Kernel metrics comparison failed before producing a TSV report"
exit 1
fi
python3 scripts/hip/gcn-cdna-metrics.py report hip-kernel-metrics-deltas.tsv \
-o hip-kernel-metrics-report.md
sed -i "3i\\- Baseline commit: $BASELINE_SHA\\n- PR merge commit: $PR_SHA" hip-kernel-metrics-report.md
if [ -n "$check_failed" ]; then
echo "check_failed=true" >> "$GITHUB_OUTPUT"
fi
exit 0
- name: Upload kernel metrics report
if: ${{ github.event_name == 'pull_request' }}
id: metrics_report
uses: actions/upload-artifact@v7
with:
name: hip-kernel-metrics-report
path: hip-kernel-metrics-report.md
- name: Publish kernel metrics summary
if: ${{ github.event_name == 'pull_request' }}
shell: bash
env:
ARTIFACT_URL: ${{ steps.metrics_report.outputs.artifact-url }}
run: |
{
if [ "$(wc -c < hip-kernel-metrics-report.md)" -le 1000000 ]; then
cat hip-kernel-metrics-report.md
else
sed -n -e '/^# /p' -e '/^- Baseline/p' -e '/^- PR/p' -e '/^Kernels compared:/p' -e 's/^## /- /p' hip-kernel-metrics-report.md
printf '\nThe full report exceeds the GitHub job summary size limit.\n'
fi
printf '\n[Download the full kernel metrics report](%s)\n' "$ARTIFACT_URL"
} | tee -a "$GITHUB_STEP_SUMMARY"
- name: Fail on blocking regressions
if: ${{ github.event_name == 'pull_request' && steps.occupancy_check.outputs.check_failed == 'true' }}
run: |
echo "Blocking kernel metrics regressions detected, see the job summary and hip-kernel-metrics-report artifact"
exit 1
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
BODY: ${{ github.event.pull_request.body }}
HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }}
run: |
# sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment
# sections written by demo:pr (see ui/lib/demo/src/cli.ts): the managed comment
# markers, or a preview linking to a demo video uploaded for this PR
has_demo=false
if { grep -qF '<!-- demo:start -->' <<< "$BODY" && grep -qF '<!-- demo:end -->' <<< "$BODY"; } ||
+23
View File
@@ -212,6 +212,29 @@ jobs:
run: npm run prepack
working-directory: ui/lib/harness
demo-checks:
name: Demo harness checks
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
package-manager-cache: false
- name: Install dependencies
run: npm ci
working-directory: ui/lib/demo
- name: Run type checking
run: npm run check
working-directory: ui/lib/demo
chat-only-build:
name: Chat-only build
runs-on: ubuntu-24.04
+1
View File
@@ -308,6 +308,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"RWForCausalLM": "falcon",
"RWKV6Qwen2ForCausalLM": "rwkv",
"RWKV7ForCausalLM": "rwkv",
"Raon1MiniForCausalLM": "raon1_mini",
"RobertaForSequenceClassification": "bert",
"RobertaModel": "bert",
"RuGPT3XLForCausalLM": "gpt2",
+3
View File
@@ -2473,6 +2473,9 @@ class TextModel(ModelBase):
if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3":
# ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF
res = "domyn-edge"
if chkhsh == "ffdae2f611dc6903980be2fbb108467cb97376d7d03cd332bb7e2602f87fa1f1":
# ref: https://huggingface.co/KRAFTON/Raon-1-mini-preview
res = "raon"
if res is None:
logger.warning("\n")
+6
View File
@@ -248,6 +248,12 @@ class Inkling2Model(TextModel):
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
# PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention
# output gate (self_attn.o_proj.gate_proj.weight); neither is in the tensor map.
name = name.replace(".linear.", ".")
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
+44 -14
View File
@@ -868,6 +868,22 @@ class Qwen3_5MoeTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
class DFlashModel(Qwen3Model):
model_arch = gguf.MODEL_ARCH.DFLASH
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._target_is_inkling2 = False
if self.target_model_dir is not None:
target_hparams = ModelBase.load_hparams(self.target_model_dir, False)
self._target_is_inkling2 = get_model_architecture(target_hparams, ModelType.TEXT).startswith("Inkling2")
if self._target_is_inkling2:
# the target GGUF keeps only the tokenizer rows of the padded vocab
target_hparams = {**target_hparams, **target_hparams.get("text_config", {})}
self.hparams["vocab_size"] = target_hparams["unpadded_vocab_size"]
self.hparams["eos_token_id"] = target_hparams["eos_token_id"]
# the loop core runs num_passes times, other looping targets need their own visit count
self._target_n_visits = target_hparams["num_hidden_layers"]
if (loop := target_hparams.get("loop_config")) is not None:
self._target_n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"])
def set_vocab(self):
if self.target_model_dir is None:
raise ValueError(
@@ -917,6 +933,11 @@ class DFlashModel(Qwen3Model):
self.gguf_writer.add_conv_group_size(int(dflash_config["conv_group_size"]))
self.gguf_writer.add_selector_rank(int(dflash_config["selector_rank"]))
self.gguf_writer.add_selector_top_k(int(dflash_config["selector_top_k"]))
softcap_mode = dflash_config.get("selector_softcap_mode", "before_correction")
if softcap_mode not in ("before_correction", "after_correction"):
raise ValueError(f"DFlash2: unknown selector_softcap_mode {softcap_mode!r}")
if softcap_mode == "after_correction":
self.gguf_writer.add_selector_softcap_after_correction(True)
output_multiplier = dflash_config.get(
"output_multiplier", self.hparams.get("output_multiplier")
@@ -942,7 +963,10 @@ class DFlashModel(Qwen3Model):
target_layer_ids = dflash_config.get("target_layer_ids", self.hparams.get("target_layer_ids", []))
if target_layer_ids:
extract_layer_ids = [i + 1 for i in target_layer_ids]
# Inkling ids count loop visits, the last one is the final norm output
if self._target_is_inkling2 and target_layer_ids[-1] != self._target_n_visits:
raise ValueError(f"Inkling2 DFlash2: target_layer_ids {target_layer_ids} must end at the Inkling final norm ({self._target_n_visits})")
extract_layer_ids = target_layer_ids if self._target_is_inkling2 else [i + 1 for i in target_layer_ids]
self.gguf_writer.add_target_layers(extract_layer_ids)
use_sliding_window = self.hparams.get("use_sliding_window", False) or dflash_config.get("use_swa", False)
@@ -969,19 +993,6 @@ class DFlashModel(Qwen3Model):
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
yield from super().generate_extra_tensors()
mask_path = self.dir_model / "mask_embedding.pt"
if not mask_path.is_file():
return
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
if mask_id is None or mask["mask_token_id"] != mask_id:
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
if not 0 <= mask_id < self.hparams["vocab_size"]:
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
def target_tensor(name: str) -> Tensor:
if self.target_model_dir is None:
raise ValueError("mask_embedding.pt requires --target-model-dir with the target embeddings and output head")
@@ -999,6 +1010,23 @@ class DFlashModel(Qwen3Model):
return LazyTorchTensor.from_local_tensor(part[name])
raise ValueError(f"Target tensor {name!r} was not found in safetensors")
if self._target_is_inkling2:
# the draft borrows the raw target embeddings, Inkling norms them before its first layer
yield "model.embed_norm.weight", target_tensor("model.llm.embed_norm.weight")
mask_path = self.dir_model / "mask_embedding.pt"
if not mask_path.is_file():
return
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
if mask_id is None or mask["mask_token_id"] != mask_id:
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
if not 0 <= mask_id < self.hparams["vocab_size"]:
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
embedding_name = "model.embed_tokens.weight"
if embedding_name in self.model_tensors:
embeddings = self.model_tensors.pop(embedding_name)()
@@ -1061,6 +1089,8 @@ class DFlashModel(Qwen3Model):
"model.candidate_selector.predecessor_codebook",
"model.candidate_selector.successor_codebook",
):
# padded vocabs (Inkling): the selector only indexes the draft vocab
data_torch = data_torch[:self.hparams["vocab_size"]]
name += ".weight"
yield from super().modify_tensors(data_torch, name, bid)
+206
View File
@@ -0,0 +1,206 @@
from __future__ import annotations
from typing import Any, Callable, Iterable
import torch
from torch import Tensor
from .base import ModelBase, TextModel, gguf
_REQUIRED = object()
def _renamed_key(config: dict[str, Any], new: str, old: str, default: Any = _REQUIRED) -> Any:
# the HF config accepts the older spellings (kda_layers, mhc_*): null counts as absent, a conflicting pair is an error
values = [config[key] for key in (new, old) if config.get(key) is not None]
if len(values) == 2 and values[0] != values[1]:
raise ValueError(f"Raon-1 mini config has conflicting {new}={values[0]!r} and {old}={values[1]!r}")
if values:
return values[0]
if default is _REQUIRED:
raise KeyError(f"Raon-1 mini config needs {new} (or the older spelling {old})")
return default
def _rda_config(hp: dict[str, Any]) -> dict[str, Any]:
# rda_config is the current spelling; older exports use linear_attn_config with short_conv_kernel_size / use_full_rank_gate / full_attn_layers / kda_layers
if hp.get("rda_config") is not None and hp.get("linear_attn_config") is not None:
raise ValueError("Raon-1 mini config has both rda_config and the older linear_attn_config")
config = hp["rda_config"] if hp.get("rda_config") is not None else hp["linear_attn_config"]
result = {
"num_heads": config["num_heads"],
"head_dim": config["head_dim"],
"conv_kernel_size": _renamed_key(config, "conv_kernel_size", "short_conv_kernel_size"),
"full_rank_gate": _renamed_key(config, "full_rank_gate", "use_full_rank_gate"),
"mla_layers": _renamed_key(config, "mla_layers", "full_attn_layers"),
"rda_layers": _renamed_key(config, "rda_layers", "kda_layers"),
}
# absent and null differ here (see set_gguf_parameters), so the key is copied only when present
if "gate_lower_bound" in config:
result["gate_lower_bound"] = config["gate_lower_bound"]
return result
@ModelBase.register("Raon1MiniForCausalLM")
@ModelBase.example("KRAFTON/Raon-1-mini-preview")
class Raon1MiniModel(TextModel):
model_arch = gguf.MODEL_ARCH.RAON1_MINI
# mHC sites: HF module name -> tensor prefix; each site has 10 parameters, packed into fn / base / scale
_MHC_SITES = (("self_attn_raon_mhc", "HC_ATTN"), ("mlp_raon_mhc", "HC_FFN"))
_MHC_PARTS = ("phi_pre", "phi_post", "res.phi_z", "b_pre", "b_post", "res.b_z",
"alpha_pre", "alpha_post", "res.alpha_z", "res.eta")
# Keep these tensors at F16 for direct conversion to Q8_0, TQ1_0 or TQ2_0.
_KEEP_UNQUANTIZED = ("hc_attn_fn", "hc_ffn_fn", "ssm_f_a", "ssm_f_b", "ssm_beta", "ssm_rda")
_KEEP_UNQUANTIZED_Q8_0 = ("attn_kv_a_mqa", "attn_k_b", "attn_v_b")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._experts: dict[tuple[int, str], dict[int, Tensor]] = {}
self._mhc: dict[tuple[int, str], dict[str, Tensor]] = {}
self._rda_layers = set(_rda_config(self.hparams)["rda_layers"])
def filter_tensors(self, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
filtered = super().filter_tensors(item)
if filtered is None:
return None
name, _ = filtered
if name.startswith("model.layers."):
layer = name.split(".", 3)[2]
# MTP layers follow the main model layers.
if layer.isdecimal() and int(layer) >= self.hparams["num_hidden_layers"]:
return None
return filtered
def set_gguf_parameters(self):
hp = self.hparams
rda_config = _rda_config(hp)
n_layer = hp["num_hidden_layers"]
# 1-based layer ids, as in the HF config (is_rda_layer: layer_idx + 1 in rda_layers)
rda = self._rda_layers
mla = set(rda_config["mla_layers"])
if rda & mla or rda | mla != set(range(1, n_layer + 1)):
raise ValueError("Raon-1 mini attention layer lists must partition all layers")
# the hybrid memory needs both layer kinds
if not rda or not mla:
raise ValueError("Raon-1 mini needs at least one RDA (rda_layers) and one MLA (mla_layers) layer")
if hp.get("tie_word_embeddings"):
raise ValueError("Raon-1 mini with tie_word_embeddings is not supported (the released model has a separate lm_head)")
if (not hp["mla_use_nope"] or not hp["mla_use_output_gate"]
or not rda_config["full_rank_gate"] or hp["hidden_act"] != "situ"
or hp["moe_router_activation_func"] != "sigmoid"
or hp.get("use_grouped_topk") or hp.get("routed_expert_hidden_size")
or hp.get("attn_res_block_size") or hp["moe_layer_freq"] != 1):
raise ValueError("Unsupported Raon-1 mini architecture variant")
if rda_config["num_heads"] != hp["num_attention_heads"]:
raise ValueError("Raon-1 mini RDA and MLA head counts must match")
super().set_gguf_parameters()
self.gguf_writer.add_vocab_size(hp["vocab_size"])
self.gguf_writer.add_head_count_kv([0 if i + 1 in rda else 1 for i in range(n_layer)])
self.gguf_writer.add_ssm_conv_kernel(rda_config["conv_kernel_size"])
# the .get() defaults below are the HF config defaults
self.gguf_writer.add_ssm_time_step_rank(_renamed_key(hp, "rda_decay_rank", "kda_decay_rank", 128))
self.gguf_writer.add_kda_head_dim(rda_config["head_dim"])
# HF uses -5.0 when the key is absent; an explicit null selects the unbounded gate
if (bound := rda_config.get("gate_lower_bound", -5.0)) is not None:
self.gguf_writer.add_kda_gate_lower_bound(bound)
self.gguf_writer.add_q_lora_rank(hp["q_lora_rank"])
self.gguf_writer.add_kv_lora_rank(hp["kv_lora_rank"])
self.gguf_writer.add_rope_dimension_count(hp["qk_rope_head_dim"])
self.gguf_writer.add_key_length(hp["kv_lora_rank"] + hp["qk_rope_head_dim"])
self.gguf_writer.add_value_length(hp["kv_lora_rank"])
self.gguf_writer.add_key_length_mla(hp["qk_nope_head_dim"] + hp["qk_rope_head_dim"])
self.gguf_writer.add_value_length_mla(hp["v_head_dim"])
self.gguf_writer.add_latent_norm_rms_eps(hp.get("mla_latent_norm_eps", 1e-6))
self.gguf_writer.add_expert_feed_forward_length(hp["moe_intermediate_size"])
self.gguf_writer.add_expert_shared_count(hp["num_shared_experts"])
self.gguf_writer.add_leading_dense_block_count(hp["first_k_dense_replace"])
self.gguf_writer.add_expert_weights_scale(hp["routed_scaling_factor"])
self.gguf_writer.add_expert_weights_norm(hp["moe_renormalize"])
self.gguf_writer.add_activation_situ_beta(hp["activation_situ_beta"])
self.gguf_writer.add_activation_situ_linear_beta(hp["activation_situ_linear_beta"])
self.gguf_writer.add_hyper_connection_count(_renamed_key(hp, "raon_mhc_streams", "mhc_streams", 4))
self.gguf_writer.add_hyper_connection_epsilon(_renamed_key(hp, "raon_mhc_selector_eps", "mhc_selector_eps", 1e-5))
self.gguf_writer.add_hyper_connection_magnitude(_renamed_key(hp, "raon_mhc_post_factor", "mhc_post_factor", 2.0))
def prepare_tensors(self):
super().prepare_tensors()
if self._experts or self._mhc:
raise ValueError(f"Incomplete Raon-1 mini tensor groups: experts={list(self._experts)}, mHC={list(self._mhc)}")
def tensor_force_quant(self, name, new_name, bid, n_dims):
if ".hc_" in new_name and not new_name.endswith("_fn.weight"):
return gguf.GGMLQuantizationType.F32
quantized = (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.LlamaFileType.MOSTLY_TQ1_0, gguf.LlamaFileType.MOSTLY_TQ2_0)
if self.ftype in quantized and new_name.startswith("blk."):
keep = self._KEEP_UNQUANTIZED
if self.ftype == gguf.LlamaFileType.MOSTLY_Q8_0:
keep += self._KEEP_UNQUANTIZED_Q8_0
if new_name.split(".")[2] in keep:
return gguf.GGMLQuantizationType.F16
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
for site, prefix in self._MHC_SITES:
marker = f".{site}."
if marker not in name:
continue
assert bid is not None
parts = self._mhc.setdefault((bid, site), {})
suffix = name.split(marker, 1)[1]
if suffix in parts:
raise ValueError(f"Duplicate tensor {name}")
parts[suffix] = data_torch
if len(parts) < len(self._MHC_PARTS):
return
fn = torch.cat([parts[k] for k in ("phi_pre", "phi_post", "res.phi_z")])
base = torch.cat([parts[k].float() for k in ("b_pre", "b_post", "res.b_z")])
scale = torch.stack([parts[k].float().reshape(()) for k in ("alpha_pre", "alpha_post", "res.alpha_z", "res.eta")])
for kind, tensor in (("FN", fn), ("BASE", base), ("SCALE", scale)):
yield from super().modify_tensors(tensor, self.format_tensor_name(getattr(gguf.MODEL_TENSOR, f"{prefix}_{kind}"), bid), bid)
del self._mhc[(bid, site)]
return
# moe.experts.{e}.{gate,down,up}_proj; older exports: block_sparse_moe.experts.{e}.{w1,w2,w3}
if ".moe.experts." in name or ".block_sparse_moe.experts." in name:
assert bid is not None
tail = name.split(".experts.", 1)[1].split(".")
eid, wid = int(tail[0]), tail[1]
group = self._experts.setdefault((bid, wid), {})
if eid in group or not 0 <= eid < self.hparams["num_experts"]:
raise ValueError(f"Invalid expert tensor {name}")
group[eid] = data_torch
if len(group) == self.hparams["num_experts"]:
tid = {"gate_proj": gguf.MODEL_TENSOR.FFN_GATE_EXP, "down_proj": gguf.MODEL_TENSOR.FFN_DOWN_EXP,
"up_proj": gguf.MODEL_TENSOR.FFN_UP_EXP, "w1": gguf.MODEL_TENSOR.FFN_GATE_EXP,
"w2": gguf.MODEL_TENSOR.FFN_DOWN_EXP, "w3": gguf.MODEL_TENSOR.FFN_UP_EXP}[wid]
yield from super().modify_tensors(torch.stack([group[i] for i in range(len(group))]), self.format_tensor_name(tid, bid), bid)
del self._experts[(bid, wid)]
return
if name.endswith("kv_b_proj.weight"):
n_head = self.hparams["num_attention_heads"]
qk_nope_head_dim, v_head_dim = self.hparams["qk_nope_head_dim"], self.hparams["v_head_dim"]
kv_b = data_torch.reshape(n_head, qk_nope_head_dim + v_head_dim, self.hparams["kv_lora_rank"])
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
yield from super().modify_tensors(k_b.transpose(1, 2).contiguous(), name.replace("kv_b_proj", "k_b_proj"), bid)
yield from super().modify_tensors(v_b.contiguous(), name.replace("kv_b_proj", "v_b_proj"), bid)
return
if name.endswith(".self_attn.g_proj.weight"):
assert bid is not None
rda = bid + 1 in self._rda_layers
tid = gguf.MODEL_TENSOR.SSM_G if rda else gguf.MODEL_TENSOR.ATTN_GATE
yield self.format_tensor_name(tid, bid), data_torch
return
if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")):
data_torch = data_torch.reshape(1, -1, 1, data_torch.shape[-1])
if name.endswith(".A_log"):
data_torch = -torch.exp(data_torch.float())
# dt_bias -> the name SSM_DT's mapping expects, as for qwen3next
if name.endswith(".dt_bias"):
name = name.removesuffix(".dt_bias") + ".dt_proj.bias"
yield from super().modify_tensors(data_torch, name, bid)
+1
View File
@@ -169,6 +169,7 @@ models = [
{"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", },
{"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", },
{"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", },
{"name": "raon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KRAFTON/Raon-1-mini-preview", },
]
# some models are known to be broken upstream, so we will skip them as exceptions
+1
View File
@@ -318,6 +318,7 @@ ninja
## Known Issues
- Adreno E17 compiler workarounds are disabled by default. If you encounter Flash Attention compilation failures or incorrect MoE results, set `GGML_OPENCL_ADRENO_E17_QUIRKS=1` before starting llama.cpp.
- Flash attention does not always improve performance.
- Currently OpenCL backend works on A6xx GPUs with recent drivers and compilers (usually found in IoT platforms).
However, it does not work on A6xx GPUs found in phones with old drivers and compilers.
+2 -1
View File
@@ -44,7 +44,7 @@ The following releases are verified and recommended:
### Ubuntu 24.04
The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#L713](../../.github/workflows/release.yml#L713): ubuntu-24-sycl -> Download & Install oneAPI.
The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#1447](../../.github/workflows/release.yml#L1447): `ubuntu-24-sycl` -> `Download & Install oneAPI`.
It is recommended to use them with [Intel Docker](https://hub.docker.com/r/intel/deep-learning-essentials).
@@ -822,6 +822,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
| GGML_SYCL_MEMTRACE_STEP | 64 (default) or positive integer | With GGML_SYCL_MEMTRACE=1, the minimum growth in memory usage to trigger another log record. |
| GGML_SYCL_MKL_FA_DIAG | 0 (default) or 1 | Enable output fingerprinting for MKL flash attention. Dumps the first 64 float output values for the first 6 FA calls with n_kv ≥ 1024, labeled with kernel type (MKL/TILE/VEC) for cross-kernel comparison. |
| GGML_SYCL_ENABLE_FUSION | 0 or 1 (default) | Enable fused-kernel dispatch in graph compute. Unsupported types and layouts fall back to the standalone op kernels. See `ggml_sycl_can_fuse()`. |
| GGML_SYCL_FUSE_CONV_WINDOW | 0 or 1 (default) | Fuse four-tap recurrent convolution windows, rollback cache updates and SiLU into one kernel. Other shapes use the existing kernels. |
| GGML_SYCL_ENABLE_ESIMD | 0 or 1 (default)| Enable ESIMD kernels when available. |
| GGML_SYCL_ENABLE_XMX_ESIMD | 0 or 1 (default) | Use the XMX (DPAS) multi-column mat-vec kernels for reordered Q2_K to Q6_K and Q8_0 weights on Xe2 GPUs. Speeds up speculative decoding and short prompt batches. |
| GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. |
+40
View File
@@ -304,6 +304,22 @@ Unlike host-level tensor-splitting, row-splitting is executed entirely inside th
You can also combine row-splitting with layer-splitting across multiple grouped devices (e.g. `--devices 'HTP0[0-1],HTP1[2-3]'`
on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs using virtual sessions 0 and 1).
## Numerical Precision and End-to-End Accuracy
By default, the Hexagon backend is tuned for higher NPU throughput and lower memory bandwidth while preserving strong
end-to-end accuracy across typical models. Specifically, batched matrix multiplications default to `W8A8` integer HMX
(`--hex-mm-select 3`), which dynamically quantizes activations into 8-bit (`uint8` x `int8`) blocks with a 2048-element
`K`-group scale (using HVX when `M <= 4`),
and internal `FP32` activation tensors within each HTP subgraph are automatically lowered in-place to `FP16`
(`--hex-oplower 1`). If a particular model or workload exhibits accuracy degradation (for example due to large activation
outliers or `FP16` residual overflow), try stepping down to higher-precision configurations in the following order:
1. `--hex-mm-select 4 --hex-oplower 1`: pure `W8A8` INT HMX everywhere + internal `FP16` lowering (maximum prefill speed)
2. `--hex-mm-select 3 --hex-oplower 1` (default): hybrid `W8A8` INT HMX (FP16 HMX on post-GLU / `GGML_PREC_F32` projections) + internal `FP16` lowering
3. `--hex-mm-select 3 --hex-oplower 0`: hybrid `W8A8` INT HMX + `FP32` intermediate activations
4. `--hex-mm-select 2 --hex-oplower 1`: `FP16` HMX everywhere + internal `FP16` lowering
5. `--hex-mm-select 2 --hex-oplower 0`: `FP16` HMX everywhere + `FP32` intermediate activations
## Environment variables
- `GGML_HEXAGON_DEVICES` (default: not set, defaults to HTP0 session)
@@ -398,3 +414,27 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs
# Disable ADD and SUB on Hexagon (fall back to CPU or GPU)
./scripts/snapdragon/run.py --target adb --hex-opfilter "ADD|SUB" -- llama-cli ...
```
- `GGML_HEXAGON_OPLOWER=N`
Controls internal FP32-to-FP16 activation tensor lowering inside HTP opbatches (configurable via `--hex-oplower` in `run.py`):
- `0`: Disabled - keep internal activations in FP32
- `1`: Enabled (default) - lower internal `FP32` activation tensors across the opbatch to `FP16` while respecting `GGML_PREC_F32` hints
- `GGML_HEXAGON_MM_SELECT=N`
Selects the matrix multiplication engine on HTP (configurable via `--hex-mm-select` in `run.py`):
- `0`: Disabled (falls back to CPU or GPU)
- `1`: HVX vector kernels only
- `2`: FP16 HMX matrix engine (`M > 4`) with HVX decode (`M <= 4`)
- `3`: Hybrid INT HMX `W8A8` (`uint8` activations x `int8` weights) with FP16 HMX fallback on post-GLU / `GGML_PREC_F32` projections and HVX decode (`M <= 4`) (default; automatically defaults to 2 on multi-session v73 hardware unless overridden)
- `4`: Pure INT HMX `W8A8` everywhere (`M > 4`) with HVX decode (`M <= 4`)
- `GGML_HEXAGON_OPPOLL=N`
Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`):
- `0`: Blocking wait (lowest host CPU usage)
- `1`: Full polling (keeps the host CPU awake for minimum wakeup latency; best for peak benchmarking and profiling)
- `> 1`: Hybrid polling budget in milliseconds - polls for up to `N` ms per opbatch before falling back to a blocking wait (default: `50` when supported by the FastRPC driver, `0` otherwise)
The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills). For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling.
+73 -96
View File
@@ -30,6 +30,10 @@ The Hexagon NPU backend takes advantage of Snapdragon unified memory where all D
The NPU has dedicated tightly-coupled memory called VTCM (Vector Tightly-Coupled Memory). VTCM is used for intermediate data (such as
dynamically quantized activations) and streaming buffers (chunks of weight and activation tensors fetched via DMA).
Both DDR and VTCM reserve trailing guard space so HVX kernels can issue full-width vector loads (`vmem` / `vmemu`) on tail elements without boundary branches:
- Shared DDR buffers pad allocations to 4 KB and append a 4 KB guard page.
- Usable VTCM (`htp_vtcm_usable_size`) reserves `HTP_VTCM_GUARD_SIZE` (128 bytes) at the end of the physical VTCM page.
## Large model handling
Hexagon NPU sessions have a 32-bit virtual address space window of around 3.5GB.
@@ -72,34 +76,29 @@ For a weight matrix of logical shape `[ne0, ne1]` (where `ne0 = K`, `ne1 = N`):
### Block-32 Quantized Formats
Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`).
Quants are stored in 4-K-grouped (`vrmpy`) byte order across 128-byte HVX vectors:
columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns (`j = k % 4`), stored at `4 * row + j` within each vector.
- **Q4_0** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_0`):
- **Quants** (bytes 0..511, 512 bytes):
- **Quants** (bytes 0..511, 512 bytes, 4 HVX vectors `p = 0..3`):
Contains 32 rows x 32 columns of 4-bit quants.
Divided into 16 column pairs `cp = 0..15` covering columns `2*cp` and `2*cp + 1`.
For each column pair `cp`, 32 bytes are stored consecutively for rows `row = 0..31`:
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
Low nibble holds the even column; high nibble holds the odd column.
Vector `p` packs column group `2*p` in the low nibble and group `2*p + 1` in the high nibble:
`tile[p * 128 + row * 4 + j]` holds `(quant[row][8*p + 4 + j] << 4) | quant[row][8*p + j]` for `row = 0..31`, `j = 0..3`.
- **Scales** (bytes 512..575, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **Q8_0** (1088 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q8_0`):
- **Quants** (bytes 0..1023, 1024 bytes):
- **Quants** (bytes 0..1023, 1024 bytes, 8 HVX vectors `p = 0..7`):
Contains 32 rows x 32 columns of signed 8-bit quants (`int8_t`).
Divided into 16 column pairs `cp = 0..15` covering columns `col0 = 2*cp` and `col1 = 2*cp + 1`.
For each column pair `cp`, 64 bytes store interleaved column elements for each row `row = 0..31`:
`tile[cp * 64 + 2 * row + 0] = quant[row][col0]`
`tile[cp * 64 + 2 * row + 1] = quant[row][col1]`
Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`):
`tile[p * 128 + row * 4 + j] = quant[row][4*p + j]` for `row = 0..31`, `j = 0..3`.
- **Scales** (bytes 1024..1087, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **IQ4_NL** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_IQ4_NL`):
- **Quants** (bytes 0..511, 512 bytes):
Same nibble transposition and storage layout as `Q4_0`.
Contains 32 rows x 32 columns of non-linear 4-bit indices (values 0..15).
Divided into 16 column pairs `cp = 0..15`:
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit non-linear indices (values 0..15).
- **Scales** (bytes 512..575, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **Dequantization**:
@@ -107,10 +106,7 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
- **MXFP4** (544 bytes per tile, `HTP_TENSOR_TILE_SIZE_MXFP4`):
- **Quants** (bytes 0..511, 512 bytes):
Same nibble transposition and storage layout as `Q4_0`.
Contains 32 rows x 32 columns of 4-bit OCP Microscaling FP4 (E2M1) values.
Divided into 16 column pairs `cp = 0..15`:
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit OCP Microscaling FP4 (E2M1) values.
- **Scales** (bytes 512..543, 32 bytes):
32 unsigned 8-bit values (`uint8_t`), storing one 8-bit biased exponent (E8M0, bias 127) scale `e` per row `row = 0..31`.
- **Dequantization**:
@@ -119,26 +115,25 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
- **NVFP4** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_NVFP4`, lossless tiling with same size as `block_nvfp4`):
- A 64-element block spans 2 consecutive k-tiles; k-tile `h` holds sub-blocks `2h` and `2h+1`.
- **Quants** (bytes 0..511): same nibble transposition as `Q4_0`, holding E2M1 values in element order
(within a 16-element sub-block, `qs` byte `j` holds elements `j` and `j+8`).
- **Quants** (bytes 0..511, 4 HVX vectors): 4-K-grouped nibble layout per 16-element sub-block `u = 0..1` (`tile[(2*u + 0)*128 + row*4 + j]` holds low nibbles of `qs_sub[j]` and `qs_sub[4+j]`; `tile[(2*u + 1)*128 + row*4 + j]` holds high nibbles).
- **Scales** (bytes 512..575): UE4M3 bytes, `tile[512 + 32*u + row]` for sub-block `u = 0..1` of the k-tile.
- The per-tensor F32 scale is not part of the tile.
- **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`):
- **Quants** (bytes 0..511, 512 bytes):
Same 4-bit nibble transposition and storage layout as `Q4_0`.
Same 4-K-grouped nibble layout as `Q4_0`.
- **Scales** (bytes 512..639, 128 bytes):
32 pairs of FP16 values (`ggml_half`): `scale[2 * row + 0] = d` (scale) and `scale[2 * row + 1] = m` (min) for each row `row = 0..31`.
- **Q5_0** (704 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_0`):
- **Quants** (bytes 0..511): same 4-bit nibble transposition and storage layout as `Q4_0`, holding the low 4 bits.
- **5th-bit plane** (bytes 512..639): byte `32*c + row` (`c = 0..3`) holds a flag for `k = 2*(4i + c)` at bit `2i` and for `k = 2*(4i + c) + 1` at bit `2i + 1`, for `i = 0..3`. The flag is set when the 5th bit of the quant is clear.
- **Quants** (bytes 0..511): same 4-K-grouped nibble layout as `Q4_0`, holding the low 4 bits.
- **5th-bit plane** (bytes 512..639, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds a flag at bit `g` (`0..7`) for `k = 4*g + j`. The flag is set when the 5th bit of the quant is clear.
- **Scales** (bytes 640..703, 64 bytes): 32 FP16 values, storing scale `d` for each row `row = 0..31`.
- **Dequantization**: `0xF0` is OR-ed into the nibble where the flag is set, giving the signed value `q - 16` (-16..15), scaled by `d`.
- **Q5_1** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_1`, same layout as the Q5_K tile):
- **Quants** (bytes 0..511) and **scales** (bytes 512..639): same as `Q4_1`, holding the low 4 bits and `(d, m)` pairs.
- **5th-bit plane** (bytes 640..767): same as `Q5_K`; a bit is set when the 5th bit of the quant is set.
- **5th-bit plane** (bytes 640..767, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds bit `g` (`0..7`) for `k = 4*g + j`, set when the 5th bit of the quant is set.
- Uses the `Q5_K` HVX/HMX kernels (Q8_1 activations with block sums).
### Q1_0 Format (1-Bit Quantization)
@@ -209,12 +204,12 @@ Byte ordering: `Q2_K`, `Q3_K`, and `Q6_K` use `vrmpy` byte order within each 128
- `bytes 384..511` (vec 3): FP16 scales `d * (scales[] - 32)`: `fp16[0..31]` for k 0..15, `fp16[32..63]` for k 16..31.
- **Q4_K** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_K`, same layout as Q4_1 tile; each 256-k super-block splits into 8 tiles of 32 k):
- `bytes 0..511` (vec 0..3): 4-bit quants; byte `32*cp + r` holds `k = 2*cp` (low nibble) and `2*cp + 1` (high nibble).
- `bytes 0..511` (vec 0..3): 4-bit quants in 4-K-grouped order; `tile[p * 128 + row * 4 + j]` holds `k = 8*p + j` (low nibble) and `k = 8*p + 4 + j` (high nibble).
- `bytes 512..639` (vec 4): 32x2 FP16 per row: `(d * sc, -dmin * m)`.
- **Q5_K** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_K`):
- `bytes 0..639` (vec 0..4): Q4_K tile (low 4 bits + FP16 scale/min pairs).
- `bytes 640..767` (vec 5): 5th-bit plane; byte `l` holds the 8 high bits for lane `l` across vec `i = 0..3` (`bit 2i = lo, 2i+1 = hi`).
- `bytes 640..767` (vec 5): 5th-bit plane in 4-K-grouped order; `plane[row * 4 + j]` holds bit `g` (`0..7`) for `k = 4*g + j`.
- **Q6_K** (896 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q6_K`):
- `bytes 0..511` (vec 0..3): low 4 bits; vec `i` holds group `2i` (low nibble) and `2i+1` (high nibble).
@@ -227,8 +222,9 @@ Writing high-performance operators for Hexagon requires following specific guide
### DDR -> DMA -> VTCM Execution Pipeline
- Strongly prefer the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
- Direct HVX reads/writes from/to DDR are less efficient and should only be used as a fallback.
- All operators must use the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
- **No direct reads or writes to `tensor->data`**: Do not dereference `tensor->data` pointers directly (scalar or HVX). All tensor transfers must go through DMA, because bypass DMA writes are not L1D/L2 coherent and tensors may reside in 40-bit extended address space.
- **Rare exception (small index/position tensors)**: For small metadata tensors that require scalar indexing (such as `ids`, `pos`, or row indices), use [`htp_tensor_read()`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h) to copy into a 128-byte aligned local DDR buffer (`ddr_spad_base` or stack). It handles extended addresses, arbitrary strides, and `dccleaninva` + `syncht` cache maintenance in one place.
- Use `dma_addr_t` only for DMA base and final addresses. Form a final address by adding a 32-bit byte offset to a
`dma_addr_t` tensor base address. This permits a 64-bit mapped base address on newer platforms while retaining 32-bit
relative addressing.
@@ -244,8 +240,12 @@ Writing high-performance operators for Hexagon requires following specific guide
properly. Flushing is only used in rare exceptions where a batch of operations is pushed without individual pops.
- Use the DMA queue interface from [`dma-queue.h`](../../../ggml/src/ggml-hexagon/htp/dma-queue.h)
(`dma_queue_push()`, `dma_queue_pop()`, and `dma_queue_flush()`).
See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c) and
[`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c) for reference implementations.
- For new simple ops, prefer the generic double-buffered pipeline drivers in
[`dma-pipeline.h`](../../../ggml/src/ggml-hexagon/htp/dma-pipeline.h) (`dma_pipe_io_run`, `dma_pipe_in_run`,
`dma_pipe_out_run`), which use dummy pushes, `dma_queue_pop().src`/`.dst` slot recycling, and `dma_queue_flush()`
at the end of the op. See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c),
[`diag-ops.c`](../../../ggml/src/ggml-hexagon/htp/diag-ops.c), and
[`pad-ops.c`](../../../ggml/src/ggml-hexagon/htp/pad-ops.c) for reference implementations.
### Avoid Scalar Reads and Writes to VTCM
@@ -256,22 +256,22 @@ Writing high-performance operators for Hexagon requires following specific guide
- Hexagon cores do not have hardware division instructions.
- For recurring divisions across iterations or threads, use `fastdiv` from
[`hex-fastdiv.h`](../../../ggml/src/ggml-hexagon/htp/hex-fastdiv.h) with precomputed divisors (such as
`octx->ctx->mdev.count_div` or `octx->n_threads_div`).
`octx->ctx->mdev.count_div` or `octx->n_hvx_div`).
- Do not call `init_fastdiv_values()` for single-use divisions; use standard compiler division (`/`) instead.
### Host-Side Precomputation via `kernel_params`
- Precompute tensor shapes, strides, scale conversions, tiling layouts, and validation checks on the host CPU during graph
preparation in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp).
preparation in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp).
- Pack precomputed parameters into the operator's fixed `kernel_params` structure in `htp_op_node` (such as
`htp_mm_kernel_params`, `htp_unary_kernel_params`, `htp_fa_kernel_params`, `htp_get_rows_kernel_params`).
- The NPU executes directly using `octx->kernel_params` without redundant runtime metadata extraction or validation.
- **Strict Host-Kernel Alignment**:
- Verify that parameters calculated by the host CPU are strictly honored by the NPU kernel.
- Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_threads` instead of
using `kparams->n_threads`, or ignoring precomputed `tasks_per_thread` and chunk counts).
- Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_hvx` instead of
using `kparams->n_hvx`, or ignoring precomputed `tasks_per_hvx` and chunk counts).
- Both human developers and coding agents must audit both sides of the interface: ensure fields populated in `kernel_params`
in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp) are actively and consistently utilized by the
in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp) are actively and consistently utilized by the
corresponding operator entry point and worker threads in `htp/*-ops.c`.
### Tracing Instrumentation
@@ -292,7 +292,7 @@ Writing high-performance operators for Hexagon requires following specific guide
- Distribute parallel work across NPU worker threads using the thread pool work queue:
```c
work_queue_run(ctx->work_queue, worker_func, &op_ctx, n_threads);
work_queue_run(ctx->hvx_queue, worker_func, &op_ctx, n_hvx);
```
- Keep worker functions independent and re-entrant. Worker threads should only operate on their designated chunk of rows or elements.
@@ -307,6 +307,12 @@ Writing high-performance operators for Hexagon requires following specific guide
- **Distinction**: `octx->src[N]` pointers *can* be NULL by design and must be checked when optional.
Examples include attention masks, optional bias or weights in fused kernels, and frequency factors.
### Prefer Early Dispatch and Specialized Micro-Kernels
- Avoid peppering micro-kernels, row or tile compute loops, or DMA worker loops with runtime checks for operand types, optional inputs, broadcast modes, or layout variants.
- Resolve execution variants early during operator setup (`op_*` / `execute_op_*`) via function pointers or dispatch tables so each micro-kernel and inner loop handles a single clean path that the compiler can unroll and software-pipeline without extra branch or register pressure.
- Prefer clean standalone specialized functions; use macros only to avoid genuine code duplication across type or mode instantiations.
### `supports_op` Independence from Buffer and Repack State
- `supports_op` (and op-specific checkers such as `supported_mul_mat()`, `supported_get_rows()`) runs during GGML graph scheduling **before** buffers are allocated and before tensor data is populated.
@@ -319,6 +325,10 @@ Writing high-performance operators for Hexagon requires following specific guide
- Repacking (converting weights to tiled layout) is an internal optimization applied during `set_tensor()` or rt-repack. Non-weight tensors or test harness tensors with the same type remain in flat layout.
- Therefore, any supported type (such as BF16, F16, quantized types) must be supported both when repacked into tiles and when stored flat in memory.
### FP16 and Mixed-Precision Operator Support
- New and updated Hexagon compute operators must support `F16` (and mixed `F16`/`F32` where applicable for graph lowering) across activation inputs and outputs, even when `ggml-cpu` only implements `F32`.
### Multiline Macro Formatting
- Keep trailing backslashes in multiline `#define` macros cleanly aligned to a consistent column.
@@ -361,56 +371,37 @@ python3 scripts/snapdragon/ggml-hexagon-inspect.py --addr2line 0x51a30 0x5ba54
Multi-device (mdev) mode enables row-level tensor parallel execution across multiple physical NPU cores or virtual NPU
sessions.
### 128-Byte Cache Line Alignment
### Non-Overlapping Output Ranges
- Shared tensor buffers reside in DDR (RPCMEM) with a 128-byte cache line granularity
(`HEX_L2_LINE_SIZE` = 128 bytes, `HTP_TENSOR_MDEV_LINE_SIZE`).
- **Rule**: Multi-device work partitions that write directly to DDR through HVX/L2 must align destination write regions to
128-byte cache line boundaries so distinct devices never share or overwrite the same cache line.
- DMA writes to DDR are not subject to this cache-line ownership rule. They may use smaller non-overlapping destination
ranges when the operator only writes through DMA.
- Because all DDR writes go through bypass DMA, multi-device partitions are **not** subject to 128-byte cache-line
alignment rules.
- Devices only need non-overlapping destination output ranges and any kernel-specific tile or vector granularity
(for example, 32 rows for tiled matmul or 128-byte vector chunks for flat 1D element-wise ops).
### Partitioning Helpers in `htp-tensor.h`
### Partitioning Helper in `htp-tensor.h`
Common partitioning logic is factored into reusable inline helpers in
[`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
Common partitioning logic is factored into [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h)
in [`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
1. [`htp_tensor_mdev_rows_per_chunk`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L104):
Determines the minimum number of rows per chunk so that the chunk byte size is a multiple of 128 bytes:
```
rows_per_chunk = 128 / hex_gcd_u32(row_size, 128)
```
If the active row and outer strides are already multiples of 128 bytes, `rows_per_chunk = 1`.
Returns `false` if the tensor cannot be safely row-partitioned (such as unaligned base pointer, permuted layout,
or non-128-byte aligned outer strides).
2. [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131):
Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
`total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
Handles chunk distribution across devices, assigns remainder units to the last device, and automatically triggers
single-device fallback when partitioning is unsafe.
- Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
`total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
- Handles chunk distribution across devices, assigns remainder units to the last device, and automatically falls back
to Device 0 when `units_per_chunk == 0` or `total_units / units_per_chunk < mdev_count`.
### Row-Partitioned Operators
For row-wise operators that write directly to DDR
(such as activations in [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c),
binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c),
For row-wise operators (such as binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c)
and unary ops in [`unary-ops.c`](../../../ggml/src/ggml-hexagon/htp/unary-ops.c)):
```c
const uint32_t total_rows = ne01 * ne02 * ne03;
const size_t dst_row_size = dst->ne[0] * elem_size;
const uint32_t total_rows = ne01 * ne02 * ne03;
uint32_t row_start = 0;
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
uint32_t rows_per_chunk = 0;
htp_tensor_mdev_rows_per_chunk(dst, elem_size, (uint32_t) dst_row_size, &rows_per_chunk);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -422,24 +413,16 @@ if (nrows == 0) {
### Element-Partitioned Operators
For flat element-wise operations that write directly to DDR:
- Partition total linear elements N = ne0 * ne1 * ne2 * ne3 in 128-byte cache line chunks (`elems_per_line = (elem_size == 4) ? 32 : 64`).
- Requires strict 1D contiguity:
[`htp_tensor_is_contiguous(dst, elem_size)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L65)
and 128-byte aligned destination pointer
[`htp_tensor_mdev_data_aligned(dst)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L84).
- If contiguous and aligned, pass `elems_per_line` to
[`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131);
otherwise pass 0 to trigger Device 0 fallback.
For flat 1D element-wise operations:
- Partition total linear elements `N = ne0 * ne1 * ne2 * ne3` in HVX vector-sized chunks (`elems_per_line = 128 / elem_size`).
- Requires 1D contiguity via [`htp_tensor_is_contiguous`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h); otherwise pass
`0` to trigger Device 0 fallback.
### Single-Device Fallback (Device 0)
- Fallback to Device 0 (`mdev.idx == 0`) when partitioning would cause cache line tearing or there are too few aligned chunks.
- Triggers:
1. Destination tensor cannot be safely partitioned (`rows_per_chunk == 0` or non-contiguous/unaligned buffer).
2. Total aligned chunks < `mdev_count`.
- Fallback to Device 0 (`mdev.idx == 0`) happens when `units_per_chunk == 0` or `total_chunks < mdev_count`.
- Device 0 processes the entire tensor `[0, total_units)`.
- Devices 1 ... N-1 receive `count = 0` and return `HTP_STATUS_OK` immediately.
- Devices `1 ... N-1` receive `count = 0` and return `HTP_STATUS_OK` immediately.
### Flatten Outer Dimensions Globally
@@ -494,10 +477,7 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
| |
Kernel Execution Kernel Execution
(Output Slice 0) (Output Slice 1)
| |
Tensor Cache Flush Tensor Cache Flush
(htp_dcache_flush_dirty_tensors) (htp_dcache_flush_dirty_tensors)
(Output Slice 0, via bypass DMA) (Output Slice 1, via bypass DMA)
| |
Post-Op/Batch Barrier ---------------------- Post-Op/Batch Barrier
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
@@ -532,11 +512,8 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
misaligned barrier arrivals across iterations.
- If any peer reports an error status (`peer_status > HTP_STATUS_OK`), the barrier propagates the error and unblocks immediately.
### Tensor Cache Flush and Pipeline Completion
### Pipeline Completion
- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order to drain the queue.
- Use [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) to flush specific dirty tensors back to DDR:
- [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) flushes modified tensor address ranges, or the
full D-cache when their total size exceeds the flush threshold, ensuring peer devices and the host CPU observe consistent
data in DDR.
- Never signal completion before all DMA transfers are drained and dirty tensor flushes have completed.
- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order (or flushed via `dma_queue_flush()`) to drain the queue.
- Because all DDR writes use bypass DMA, no per-tensor output cache flush is needed.
- Never signal completion before all DMA transfers are drained.
-1
View File
@@ -112,7 +112,6 @@
systems = [
"aarch64-darwin"
"aarch64-linux"
"x86_64-darwin" # x86_64-darwin isn't tested (and likely isn't relevant)
"x86_64-linux"
];
+1 -1
View File
@@ -5,7 +5,7 @@ project("ggml" C CXX ASM)
### GGML Version
set(GGML_VERSION_MAJOR 1)
set(GGML_VERSION_MINOR 1)
set(GGML_VERSION_PATCH 0)
set(GGML_VERSION_PATCH 1)
set(GGML_VERSION_BASE "${GGML_VERSION_MAJOR}.${GGML_VERSION_MINOR}.${GGML_VERSION_PATCH}")
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/")
+8 -2
View File
@@ -56,8 +56,8 @@ function(ggml_get_system_arch)
endif()
endfunction()
# Determines which FlashAttention vector kernel template instances to compile, returns them in OUT_SRCS.
function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
# Determines which FlashAttention kernel template instances to compile, returns them in OUT_SRCS.
function(ggml_cuda_fattn_instances DIR OUT_SRCS)
set(FA_TYPES q4_0 q4_1 q5_0 q5_1 q8_0 bf16 f16 f8_e4m3)
string(TOLOWER "${GGML_CUDA_FA_QUANTS}" FA_QUANTS)
@@ -122,6 +122,12 @@ function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
message(FATAL_ERROR "FlashAttention template instance \"${SRC}\" does not exist")
endif()
list(APPEND SRCS "${SRC}")
file(GLOB TILE_SRCS "${DIR}/template-instances/fattn-tile-instance-${COMBINATION}-*.cu")
list(APPEND SRCS ${TILE_SRCS})
file(GLOB MMA_SRCS "${DIR}/template-instances/fattn-mma-f16-instance-${COMBINATION}-*.cu")
list(APPEND SRCS ${MMA_SRCS})
endforeach()
set(${OUT_SRCS} ${SRCS} PARENT_SCOPE)
+5 -2
View File
@@ -2449,10 +2449,12 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
switch (op->src[0]->type) {
#ifndef ASCEND_310P
case GGML_TYPE_BF16:
return true;
#endif
case GGML_TYPE_F16:
case GGML_TYPE_F32:
return true;
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
return op->src[1]->type != GGML_TYPE_BF16;
case GGML_TYPE_Q8_0:
case GGML_TYPE_Q4_0:
#ifdef ASCEND_310P
@@ -2470,7 +2472,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
switch (op->src[0]->type) {
case GGML_TYPE_F16:
case GGML_TYPE_F32:
return true;
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
return op->src[1]->type != GGML_TYPE_BF16;
case GGML_TYPE_Q8_0:
case GGML_TYPE_Q4_0:
#ifdef ASCEND_310P
+31 -10
View File
@@ -1287,6 +1287,25 @@ static void ggml_compute_forward_mul_mat_one_chunk(
}
}
// converts n BF16 values (whole blocks of vec_dot_type) to vec_dot_type: widened directly to F32, otherwise via F32 in chunks
static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64_t n, enum ggml_type vec_dot_type) {
if (vec_dot_type == GGML_TYPE_F32) {
ggml_cpu_bf16_to_fp32(x, (float *) y, n);
return;
}
ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float;
const int64_t bs = ggml_blck_size(vec_dot_type);
float tmp[1024];
const int64_t chunk = (1024/bs)*bs;
for (int64_t i = 0; i < n; i += chunk) {
const int64_t nc = MIN(chunk, n - i);
ggml_cpu_bf16_to_fp32(x + i, tmp, nc);
from_float(tmp, (char *) y + (i/bs)*ggml_type_size(vec_dot_type), nc);
}
}
void ggml_compute_forward_mul_mat(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
@@ -1372,11 +1391,9 @@ UseGgmlGemm1:;
const size_t nbw3 = nbw2*ne12;
assert(params->wsize >= ne13*nbw3);
// src1 is either packed from F32 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
const bool widen = src1->type != GGML_TYPE_F32;
GGML_ASSERT(!widen || vec_dot_type == GGML_TYPE_F32);
GGML_ASSERT(!widen || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16);
// src1 is either packed from F32 or BF16 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
(src1->type == GGML_TYPE_F16 && vec_dot_type == GGML_TYPE_F32));
#if 0
for (int64_t i13 = 0; i13 < ne13; ++i13) {
@@ -1404,7 +1421,7 @@ UseGgmlGemm1:;
if (src1->type == GGML_TYPE_F16) {
ggml_cpu_fp16_to_fp32((const ggml_fp16_t *) src1_row, (float *) wdata_row, ne10_block_size);
} else if (src1->type == GGML_TYPE_BF16) {
ggml_cpu_bf16_to_fp32((const ggml_bf16_t *) src1_row, (float *) wdata_row, ne10_block_size);
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, ne10_block_size, vec_dot_type);
} else {
from_float((const float *) src1_row, wdata_row, ne10_block_size);
}
@@ -1656,7 +1673,7 @@ static void ggml_compute_forward_mul_mat_id(
const size_t nbw3 = nbw2*ne12;
assert(params->wsize >= ne13*nbw3);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
#if 0
for (int64_t i13 = 0; i13 < ne13; ++i13) {
@@ -1675,9 +1692,13 @@ static void ggml_compute_forward_mul_mat_id(
size_t bs = ggml_blck_size(vec_dot_type);
int64_t ne10_block_start = (ith * ne10/bs) / nth;
int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth;
from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10),
(void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0),
(ne10_block_end - ne10_block_start) * bs);
const void * src1_row = (const char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10;
void * wdata_row = wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0;
if (src1->type == GGML_TYPE_BF16) {
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs, vec_dot_type);
} else {
from_float((const float *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs);
}
}
}
}
+11 -6
View File
@@ -453,14 +453,19 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float
case GGML_OP_MUL_MAT:
if (ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD &&
src0->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) {
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16;
src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) {
// the hinted matmul is an FWHT of src1 for every src0 type, which reads F32 or F16 only;
// with use_ref it takes the general path instead, so src1 has to pass the check below too
return false;
}
// F16 or BF16 in src1 is widened into the F32 work buffer
return src1->type == GGML_TYPE_F32 ||
// F16 in src1 is widened into the F32 work buffer, BF16 is widened or converted to vec_dot_type
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type ||
((src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16) &&
ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
(src1->type == GGML_TYPE_F16 && ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
case GGML_OP_MUL_MAT_ID:
// src1 is converted to vec_dot_type from F32 or BF16 only
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type;
case GGML_OP_SOFT_MAX_BACK: {
if (op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32) {
return false;
+1 -1
View File
@@ -627,7 +627,7 @@ static bool ggml_tiled_supported(const struct ggml_tensor * src0,
case GGML_TYPE_IQ3_S:
case GGML_TYPE_IQ1_S:
case GGML_TYPE_IQ1_M:
return true;
break;
default:
return false;
}
+1 -5
View File
@@ -116,16 +116,12 @@ if (CUDAToolkit_FOUND)
list(APPEND GGML_HEADERS_CUDA "../../include/ggml-cuda.h")
file(GLOB GGML_SOURCES_CUDA "*.cu")
file(GLOB SRCS "template-instances/fattn-tile*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/fattn-mma*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/mmq*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/mmf*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
list(APPEND GGML_SOURCES_CUDA ${SRCS})
ggml_add_backend_library(ggml-cuda
+5
View File
@@ -412,6 +412,11 @@ static bool ggml_cuda_is_aligned(const ggml_tensor * tensor, const size_t alignm
tensor->nb[3] % alignment == 0;
}
static bool ggml_cuda_is_view_or_noop(const ggml_tensor * t) {
return ggml_is_empty(t) || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_TRANSPOSE ||
t->op == GGML_OP_VIEW || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_NONE;
}
static constexpr __device__ int ggml_cuda_get_physical_warp_size() {
#if defined(GGML_USE_HIP) && (defined(__GFX9__) || defined(__GFX8__))
return 64;
+24 -21
View File
@@ -104,38 +104,41 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE)
uint64_t nb13,
int64_t ne0,
int64_t /*ne1*/,
int64_t /*ne2*/,
int64_t /*ne3*/,
int64_t ne2,
int64_t ne3,
uint64_t nb0,
uint64_t nb1,
uint64_t nb2,
uint64_t nb3) {
static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]");
const int64_t i3 = blockIdx.z;
const int64_t i2 = blockIdx.y;
const int64_t i1 = blockIdx.x;
const T * x;
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
} else {
if constexpr (dim == 0) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
} else if constexpr (dim == 1) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
} else if constexpr (dim == 2) {
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
} else if constexpr (dim == 3) {
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
// gridDim.y and gridDim.z are capped at 65535, loop over the rest of ne2 and ne3
for (int64_t i3 = blockIdx.z; i3 < ne3; i3 += gridDim.z) {
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
} else {
if constexpr (dim == 0) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
} else if constexpr (dim == 1) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
} else if constexpr (dim == 2) {
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
} else if constexpr (dim == 3) {
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
}
}
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = *x;
}
}
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = *x;
}
}
@@ -163,7 +166,7 @@ static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml
} else {
GGML_ASSERT(!ggml_is_quantized(src0->type));
dim3 grid_dim(dst->ne[1], dst->ne[2], dst->ne[3]);
dim3 grid_dim(dst->ne[1], std::min<int64_t>(dst->ne[2], 65535), std::min<int64_t>(dst->ne[3], 65535));
auto launch_kernel = [&](auto dim) {
concat_non_cont<T, dim><<<grid_dim, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(
(const char *) src0->data, (const char *) src1->data, (char *) dst->data,
+2
View File
@@ -1,3 +1,5 @@
#pragma once
// Simplified API for asynchronous data loading.
#include "common.cuh"
+292 -25
View File
@@ -2,6 +2,8 @@
#include "common.cuh"
#include "convert.cuh"
#include "cp-async.cuh"
#include "mma.cuh"
#include "vecdotq.cuh"
#include <cstdint>
@@ -18,16 +20,16 @@
// The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 .
#define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f)
typedef void (* fattn_kernel_t)(
const char * __restrict__ Q,
const char * __restrict__ K,
const char * __restrict__ V,
const char * __restrict__ mask,
const char * __restrict__ sinks,
const int * __restrict__ KV_max,
const int * __restrict__ KV_rows,
float * __restrict__ dst,
float2 * __restrict__ dst_meta,
using fattn_kernel_t = void (*)(
const float2 * __restrict__ Q,
const char * __restrict__ K,
const char * __restrict__ V,
const half * __restrict__ mask,
const float * __restrict__ sinks,
const int * __restrict__ KV_max,
const int * __restrict__ KV_rows,
float * __restrict__ dst,
float2 * __restrict__ dst_meta,
const float scale,
const float max_bias,
const float m0,
@@ -35,16 +37,21 @@ typedef void (* fattn_kernel_t)(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33);
const int32_t s31, const int64_t s32, const int64_t s33);
typedef float (*vec_dot_KQ_t)(
const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds);
template <typename T_src, typename T_dst>
using fattn_load_tile_t = void (*)(
const T_src * __restrict__ KV, T_dst * __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * __restrict__ indices);
struct ggml_cuda_flash_attn_ext_f16_extra_data {
uintptr_t K;
uintptr_t V;
@@ -669,6 +676,253 @@ static __device__ __forceinline__ void dequantize_V_q8_0(const void * __restrict
}
}
template <int warp_size, int nwarps, int I, int J, int stride_tile,
bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle,
typename T_src, typename T_dst>
struct flash_attn_load_tile_impl;
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, true, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
static_assert(warp_size == 32, "bad warp_size");
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / cpy_ne;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
constexpr int preload = 64;
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
int64_t i_KV;
if constexpr (use_sparse) {
// padded slots gather row 0, the -inf mask removes their contribution
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
i_KV = index >= 0 ? index : 0;
} else if constexpr (KV_indirection) {
// K/V rows given per mask column, negative rows are padding
i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
} else {
i_KV = k_VKQ_0 + i;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
uint32_t offset = i*stride_tile*sizeof(half2) + k*cpy_nb;
if constexpr (use_swizzle) {
offset = ggml_cuda_mma::swizzle<stride_tile*sizeof(half2), char>(offset, i);
}
cp_async_cg_16<preload>(tile_KV_32 + offset, KV + i_KV*stride_KV + k*cpy_ne);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / cpy_ne;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*cpy_ne : zero;
} else if (!oob_check || i < i_sup) {
if constexpr (KV_indirection) {
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
src = KV + i_KV*stride_KV + k*cpy_ne;
} else {
src = KV + int64_t(k_VKQ_0 + i)*stride_KV + k*cpy_ne;
}
} else {
src = zero;
}
half2 * dst;
if constexpr (use_swizzle) {
dst = ggml_cuda_mma::swizzle<stride_tile>(tile_KV, i*stride_tile + k*cpy_ne, i);
} else {
dst = tile_KV + i*stride_tile + k*cpy_ne;
}
ggml_cuda_memcpy_1<cpy_nb>(dst, src);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, false, half2, float> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int h2_per_chunk = cpy_ne / 2;
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert(J % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / h2_per_chunk;
const half2 * const __restrict__ KV_0 = use_sparse || (KV_indirection && indices) ? KV : KV + int64_t(k_VKQ_0)*stride_KV;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
const __align__(16) half2 zero[h2_per_chunk] = {{0.0f, 0.0f}};
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
} else if (!oob_check || i < i_sup) {
if constexpr (KV_indirection) {
if (indices) {
const int64_t i_KV = max(indices[k_VKQ_0 + i], 0);
src = KV_0 + i_KV*stride_KV + k*h2_per_chunk;
} else {
src = KV_0 + i*stride_KV + k*h2_per_chunk;
}
} else {
src = KV_0 + i*stride_KV + k*h2_per_chunk;
}
} else {
src = zero;
}
__align__(16) half2 tmp_h2[h2_per_chunk];
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(tmp_h2, src);
__align__(16) float2 tmp_f2[h2_per_chunk];
#pragma unroll
for (int l = 0; l < h2_per_chunk; ++l) {
tmp_f2[l] = __half22float2(tmp_h2[l]);
}
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*stride_tile + k*cpy_ne, tmp_f2);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle, typename T_src, typename T_dst>
static __device__ __forceinline__ void flash_attn_load_tile(
const T_src * const __restrict__ KV, T_dst * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, use_cp_async, oob_check, use_sparse, KV_indirection, use_swizzle, T_src, T_dst>::load(
KV, tile_KV, D2, stride_KV, k_VKQ_0, i_sup, indices);
}
// Helper function to get a C++ type for calculating pointer offsets from a ggml type:
template <ggml_type type>
static __host__ __device__ auto ggml_cuda_fattn_kv_dtype() {
if constexpr (type == GGML_TYPE_F16) {
return half2{};
} else {
static_assert(type == -1, "bad type");
}
}
template <ggml_type type_K, int D, int nthreads>
constexpr __device__ vec_dot_KQ_t get_vec_dot_KQ() {
if constexpr (type_K == GGML_TYPE_F16) {
@@ -1028,9 +1282,10 @@ static __global__ void flash_attn_combine_results(
dst[tid] = VKQ_numerator / VKQ_denominator;
}
template <int DV, int ncols1, int ncols2>
template <int DV, int ncols1, int ncols2, typename T_K_stride, typename T_V_stride>
void launch_fattn(
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared,
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel,
const int nwarps, const size_t nbytes_shared,
const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse,
const int warp_size = WARP_SIZE, const bool async_kv_preload = false
) {
@@ -1148,6 +1403,14 @@ void launch_fattn(
}
}
GGML_ASSERT(nb11 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb12 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb13 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb21 % sizeof(T_V_stride) == 0);
GGML_ASSERT(nb22 % sizeof(T_V_stride) == 0);
GGML_ASSERT(nb23 % sizeof(T_V_stride) == 0);
const int ntiles_x = ((Q->ne[1] + ncols1 - 1) / ncols1);
const int gqa_ratio = Q->ne[2] / K->ne[2];
const int ntiles_z_gqa = ((gqa_ratio + ncols2 - 1) / ncols2);
@@ -1311,20 +1574,24 @@ void launch_fattn(
ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream);
ggml_cuda_kernel_launch(fattn_kernel, launch_params,
(const char *) Q->data,
K_data,
V_data,
mask ? ((const char *) mask->data) : nullptr,
sinks ? ((const char *) sinks->data) : nullptr,
(const float2 *) Q->data,
(const char *) K_data,
(const char *) V_data,
mask ? ((const half *) mask->data) : nullptr,
sinks ? ((const float *) sinks->data) : nullptr,
KV_max.ptr,
kv_rows ? (const int *) kv_rows->data : nullptr,
!stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr,
scale, max_bias, m0, m1, n_head_log2, logit_softcap,
Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3],
K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13,
nb21, nb22, nb23,
Q->ne[0], ne01, Q->ne[2], Q->ne[3],
int32_t(Q->nb[1] / sizeof(float2)), int32_t(Q->nb[2] / sizeof(float2)), int32_t(Q->nb[3] / sizeof(float2)),
K->ne[0], n_kv, K->ne[2], K->ne[3],
int32_t(nb11 / sizeof(T_K_stride)), int32_t(nb12 / sizeof(T_K_stride)), int64_t(nb13 / sizeof(T_K_stride)),
int32_t(nb21 / sizeof(T_V_stride)), int32_t(nb22 / sizeof(T_V_stride)), int64_t(nb23 / sizeof(T_V_stride)),
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0,
mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0
mask ? int32_t(mask->nb[1] / sizeof(half)) : 0,
mask ? int64_t(mask->nb[2] / sizeof(half)) : 0,
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0
);
CUDA_CHECK(cudaGetLastError());
+147 -241
View File
@@ -413,116 +413,6 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages(
// ------------------------------------------------------------------------------------------------------------------
template<int stride_tile, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
static __device__ __forceinline__ void flash_attn_ext_f16_load_tile(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
// The minimum granularity is 16 bytes.
constexpr int chunk_size = 16;
constexpr int h2_per_chunk = chunk_size / sizeof(half2);
const int chunks_per_row = D2 / h2_per_chunk;
if constexpr (use_cp_async) {
static_assert(warp_size == 32, "bad warp_size");
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
constexpr int preload = 64;
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
auto load = [&] __device__ (auto n) {
const int stride_k = warp_size >> n;
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
break;
}
int64_t i_KV;
if constexpr (use_sparse) {
// padded slots gather row 0, the -inf mask removes their contribution
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
i_KV = index >= 0 ? index : 0;
} else if (indices) {
// K/V rows given per mask column, negative rows are padding
i_KV = max(indices[k_VKQ_0 + i], 0);
} else {
i_KV = k_VKQ_0 + i;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
cp_async_cg_16<preload>(tile_KV_32 + swizzle<stride_tile*sizeof(half2), char>(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk);
}
}
};
// 1: max 32*16=512 bytes, 256 half
// 2: max 16*16=256 bytes, 128 half
// 3: max 8*16=128 bytes, 64 half
// 4: max 4*16= 64 bytes, 32 half
// 5: max 2*16= 32 bytes, 16 half
// 6: max 1*16= 16 bytes, 8 half
ggml_cuda_unroll<6>{}(load);
} else {
const half2 zero[4] = {{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}};
auto load = [&] __device__ (const int n) {
const int stride_k = 32 >> n;
const int k0_start = stride_k == 32 ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
break;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
} else if (!oob_check || i < i_sup) {
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
src = KV + i_KV*stride_KV + k*h2_per_chunk;
} else {
src = zero;
}
ggml_cuda_memcpy_1<16>(swizzle<stride_tile>(tile_KV, i*stride_tile + k*h2_per_chunk, i), src);
}
}
};
// 1: max 32*16=512 bytes, 256 half
// 2: max 16*16=256 bytes, 128 half
// 3: max 8*16=128 bytes, 64 half
// 4: max 4*16= 64 bytes, 32 half
// 5: max 2*16= 32 bytes, 16 half
// 6: max 1*16= 16 bytes, 8 half
ggml_cuda_unroll<6>{}(load);
}
}
template<int ncols1, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
const half * const __restrict__ mask_h, half * const __restrict__ tile_mask,
@@ -612,11 +502,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps,
bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, bool last_iter, bool oob_check,
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ>
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ,
typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const float2 * const __restrict__ Q_f2,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask_h,
const int32_t * const __restrict__ indices,
float2 * const __restrict__ dstk,
@@ -653,6 +544,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
// FIXME this is causing performance regressions on AMD/V100.
#ifdef TURING_MMA_AVAILABLE
constexpr bool KV_indirection = true;
#else
constexpr bool KV_indirection = use_sparse;
#endif // TURING_MMA_AVAILABLE
constexpr int DKQp = GGML_PAD(DKQ, 16);
constexpr int DVp = GGML_PAD(DV, 16);
@@ -676,7 +574,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
constexpr bool use_cp_async = true;
cp_async_wait_all();
__syncthreads();
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
(V_h2, tile_V, min(nbatch_V2, DV/2), stride_V, k_VKQ_0, k_VKQ_sup, indices);
} else {
// the sparse mask values are gathered per element, always load them synchronously
@@ -696,7 +594,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
if constexpr (nstages <= 1) {
const int k0_diff = min(k0_stop, DKQ/2) - k0_start; // Only load the real head size from global memory.
constexpr bool use_cp_async = nstages == 1;
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices);
if (use_cp_async) {
cp_async_wait_all();
@@ -1033,7 +931,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
(mask_h, tile_mask, stride_mask, kb0_next*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
}
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0_next*nbatch_fa, k_VKQ_sup, indices);
}
}
@@ -1049,7 +947,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const int i0_diff = min(i0_stop, DV) - i0_start; // Only load the real head size from global memory.
if (!V_is_K_view || i0_stop > 2*nbatch_K2) {
constexpr bool use_cp_async = nstages == 1;
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
(V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices);
if (use_cp_async) {
cp_async_wait_all();
@@ -1261,11 +1159,11 @@ template<int DKQ, int ncols> struct mma_tile_sizes {
};
#endif // defined(TURING_MMA_AVAILABLE)
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup>
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
const float2 * const __restrict__ Q_f2,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask_h,
const int32_t * const __restrict__ indices,
const float * const __restrict__ sinks_f,
@@ -1310,6 +1208,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
// FIXME this is causing performance regressions on AMD/V100.
#ifdef TURING_MMA_AVAILABLE
constexpr bool KV_indirection = true;
#else
constexpr bool KV_indirection = use_sparse;
#endif // TURING_MMA_AVAILABLE
constexpr int DKQp = GGML_PAD(DKQ, 16);
constexpr int DVp = GGML_PAD(DV, 16);
@@ -1459,7 +1364,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
(mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
}
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0*nbatch_fa, k_VKQ_sup, indices);
}
@@ -1472,7 +1377,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0_next, k_VKQ_sup);
@@ -1482,7 +1387,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1493,7 +1398,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
@@ -1502,7 +1407,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
const int k_VKQ_sup = ne11 - kb0*nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1513,7 +1418,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
@@ -1522,7 +1427,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1936,18 +1841,18 @@ static constexpr __host__ __device__ bool ggml_cuda_flash_attn_ext_mma_f16_may_u
(DKQ == 256 && DV == 256 && ncols1 == 8 && ncols2 == 8);
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse>
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, ggml_type type_K, ggml_type type_V>
__launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2))
static __global__ void flash_attn_ext_f16(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -1955,19 +1860,22 @@ static __global__ void flash_attn_ext_f16(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33) {
ggml_cuda_pdl_sync(); // TODO optimize placement
#if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
// sparse: one index list per (sequence, query tile), the live count of each list follows the lists
const int * GGML_CUDA_RESTRICT sparse_indices = use_sparse ? KV_max_ptr : nullptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
@@ -2024,12 +1932,7 @@ static __global__ void flash_attn_ext_f16(
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
const int stride_Q1 = nb01 / sizeof(float2);
const int stride_Q2 = nb02 / sizeof(float2);
const int stride_K = nb11 / sizeof(half2);
const int stride_mask = nb31 / sizeof(half);
const int stride_V = V_is_K_view ? stride_K : nb21 / sizeof(half2);
const int stride_V = V_is_K_view ? s11 : s21;
const int iter_k = (ne11 + (nbatch_fa - 1)) / nbatch_fa;
const int iter_j = (ne01.z + (ncols1 - 1)) / ncols1;
@@ -2072,14 +1975,14 @@ static __global__ void flash_attn_ext_f16(
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
@@ -2096,14 +1999,14 @@ static __global__ void flash_attn_ext_f16(
constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
if (kb0_start == 0) {
constexpr bool needs_fixup = false; // CUDA block is working on an entire tile.
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
} else {
constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile.
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
}
kbc += iter_k;
@@ -2126,14 +2029,14 @@ static __global__ void flash_attn_ext_f16(
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
@@ -2149,27 +2052,30 @@ static __global__ void flash_attn_ext_f16(
constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
constexpr bool needs_fixup = false;
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
#else
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
}
bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1, const int ncols2);
template <int DKQ, int DV, int ncols1, int ncols2>
template <int DKQ, int DV, int ncols1, int ncols2, ggml_type type_K = GGML_TYPE_F16, ggml_type type_V = GGML_TYPE_F16>
void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const ggml_tensor * KQV = dst;
const int id = ggml_cuda_get_device();
const int cc = ggml_cuda_info().devices[id].cc;
@@ -2223,7 +2129,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) {
if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) {
constexpr bool use_sparse_kernel = true;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
use_sparse = true;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
@@ -2233,7 +2139,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
}
} else {
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2245,7 +2151,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
#endif // !defined(GGML_USE_MUSA)
{
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2256,7 +2162,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
} else {
constexpr bool use_logit_softcap = true;
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2266,83 +2172,83 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
}
const bool async_kv_preload = nstages == 2 && !use_sparse;
launch_fattn<DV, ncols1, ncols2>
launch_fattn<DV, ncols1, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload);
}
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2) \
template void ggml_cuda_flash_attn_ext_mma_f16_case \
<DKQ, DV, ncols1, ncols2>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2, type_K, type_V) \
template void ggml_cuda_flash_attn_ext_mma_f16_case \
<DKQ, DV, ncols1, ncols2, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols) \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16); \
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols, type_K, type_V) \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16, type_K, type_V); \
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64, GGML_TYPE_F16, GGML_TYPE_F16)
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
// The number of viable configurations for Deepseek is very limited:
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
// Mistral Small 4 (DKQ=320, DV=256), GQA=32-only build:
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
// For GLM 4.7 Flash
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
+29 -13
View File
@@ -1,59 +1,75 @@
#include "common.cuh"
#include "fattn-tile.cuh"
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
template <ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_tile_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
switch (K->ne[0]) {
case 40: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 40, 40>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 40, 40, type_K, type_V>(ctx, dst);
} break;
case 64: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 64, 64>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 64, 64, type_K, type_V>(ctx, dst);
} break;
case 72: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 72, 72>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 72, 72, type_K, type_V>(ctx, dst);
} break;
case 80: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 80, 80>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 80, 80, type_K, type_V>(ctx, dst);
} break;
case 96: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 96, 96>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 96, 96, type_K, type_V>(ctx, dst);
} break;
case 112: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<112, 112>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<112, 112, type_K, type_V>(ctx, dst);
} break;
case 128: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<128, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<128, 128, type_K, type_V>(ctx, dst);
} break;
case 192: {
GGML_ASSERT(V->ne[0] == 128);
ggml_cuda_flash_attn_ext_tile_case<192, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<192, 128, type_K, type_V>(ctx, dst);
} break;
case 256: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<256, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<256, 256, type_K, type_V>(ctx, dst);
} break;
case 320: {
GGML_ASSERT(V->ne[0] == 256);
ggml_cuda_flash_attn_ext_tile_case<320, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<320, 256, type_K, type_V>(ctx, dst);
} break;
case 512: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<512, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<512, 512, type_K, type_V>(ctx, dst);
} break;
case 576: {
GGML_ASSERT(V->ne[0] == 512);
ggml_cuda_flash_attn_ext_tile_case<576, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<576, 512, type_K, type_V>(ctx, dst);
} break;
default:
GGML_ABORT("Unsupported head size");
}
}
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
if constexpr (GGML_CUDA_FA_F16_F16) {
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
return;
}
}
// Fallback: convert K and V to F16.
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
}
+109 -201
View File
@@ -373,133 +373,28 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
return (ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols) >> 23) & ((1 << 9) - 1);
}
// TODO: deduplicate with mma-f16
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
static __device__ __forceinline__ void flash_attn_tile_load_tile(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_ne = cpy_nb / 4;
auto load = [&] __device__ (const int n) {
const int stride_j = warp_size >> n;
if (stride_j == 0) {
return;
}
const int j0_start = stride_j == warp_size ? 0 : ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (2*stride_j);
const int j0_stop = ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (1*stride_j);
const int stride_i = warp_size / stride_j;
if (j0_start == j0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
if (i0 + nwarps*stride_i <= I || i < I) {
#pragma unroll
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne;
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
ggml_cuda_memcpy_1<cpy_nb>(
tile_KV + i*(J/2 + J_padding) + j,
!oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
}
}
}
};
// 1: max 64*16=512 bytes, 512 half
// 2: max 32*16=512 bytes, 256 half
// 3: max 16*16=256 bytes, 128 half
// 4: max 8*16=128 bytes, 64 half
// 5: max 4*16= 64 bytes, 32 half
// 6: max 2*16= 32 bytes, 16 half
// 7: max 1*16= 16 bytes, 8 half
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
ggml_cuda_unroll<7>{}(load);
}
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
static __device__ __forceinline__ void flash_attn_tile_load_tile(
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_ne = cpy_nb / 4;
auto load = [&] __device__ (const int n) {
const int stride_j = warp_size >> n;
if (stride_j == 0) {
return;
}
const int j0_start = stride_j == warp_size ? 0 : (J/cpy_ne) - (J/cpy_ne) % (2*stride_j);
const int j0_stop = (J/cpy_ne) - (J/cpy_ne) % (1*stride_j);
const int stride_i = warp_size / stride_j;
if (j0_start == j0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
if (i0 + nwarps*stride_i <= I || i < I) {
#pragma unroll
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2);
const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}};
__align__(16) half2 tmp_h2[cpy_ne/2];
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(
tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
__align__(16) float2 tmp_f2[cpy_ne/2];
#pragma unroll
for (int l = 0; l < cpy_ne/2; ++l) {
tmp_f2[l] = __half22float2(tmp_h2[l]);
}
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*(J + J_padding) + 2*j, tmp_f2);
}
}
}
};
// 1: max 32*16=512 bytes, 128 float
// 2: max 16*16=256 bytes, 64 float
// 3: max 8*16=128 bytes, 32 float
// 4: max 4*16= 64 bytes, 16 float
// 5: max 2*16= 32 bytes, 8 float
static_assert(J % 8 == 0, "bad J");
static_assert(J % cpy_ne == 0, "bad J");
ggml_cuda_unroll<5>{}(load);
}
// Function that performs a single iteration in for the KQ matrix multiplication:
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int nbatch_fa, int nbatch_K,
bool use_logit_softcap, bool oob_check, typename T_vec_dot>
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_K>
static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
T_vec_dot * const Q_tmp,
const half2 * const __restrict__ K_h2,
const T_K * const __restrict__ K_h2,
T_vec_dot * const KV_tmp,
const int stride_K2,
const int k_VKQ_0,
const int k_VKQ_sup,
const int k_KQ_0,
float * KQ_acc) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int ncols = ncols1*ncols2;
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, cpy_ne, oob_check>
(K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup);
constexpr int stride_tile_K = std::is_same_v<T_vec_dot, half2> ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne;
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, false, false, T_K, T_vec_dot>
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, nullptr);
__syncthreads();
#ifdef FAST_FP16_AVAILABLE
@@ -556,11 +451,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
// Function that performs a single iteration of the main loop over up to nbatch_fa tokens.
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int DV, int nbatch_fa, int nbatch_K,
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc>
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_tile_iter(
T_vec_dot * const Q_tmp,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask,
const uint3 ne01,
const float logit_softcap,
@@ -576,7 +471,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
const int k_VKQ_0,
const int k_VKQ_max,
const int col_Q_0) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int ncols = ncols1*ncols2;
@@ -716,10 +611,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
constexpr int nbatch_V = (DV % nbatch_K == 0 ? nbatch_K : nbatch_K*2/3) * nbatch_fa / DV; // Number of V columns that fit in SRAM for K.
static_assert(nbatch_fa % nbatch_V == 0, "bad nbatch_V");
static_assert(nbatch_V % np == 0, "bad nbatch_V");
constexpr int stride_tile_V = std::is_same_v<T_vec_dot, half2> ? DV/2 : DV;
#pragma unroll
for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) {
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_V, DV, 0, oob_check>
(V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0);
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, false, false, T_V, T_vec_dot>
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, nullptr);
__syncthreads();
#ifdef FAST_FP16_AVAILABLE
@@ -788,18 +684,18 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap> // D == head size
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V> // D == head size
__launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2))
static __global__ void flash_attn_tile(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -807,21 +703,24 @@ static __global__ void flash_attn_tile(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33) {
#ifdef FLASH_ATTN_AVAILABLE
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
GGML_UNUSED(KV_rows_ptr);
// Skip unused kernel variants for faster compilation:
@@ -830,15 +729,22 @@ static __global__ void flash_attn_tile(
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
return;
}
#ifdef AMD_MFMA_AVAILABLE
if (ncols1 == 64 && ncols2 == 1) {
// The tile kernel is suffering from register spills for ncols1 == 64 && ncols2 == 1.
NO_DEVICE_CODE;
return;
}
#endif // AMD_MFMA_AVAILABLE
static_assert(ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols1*ncols2) != 0, "kernel config not defined");
@@ -855,19 +761,19 @@ static __global__ void flash_attn_tile(
const int sequence = blockIdx.z / (ne02/ncols2);
const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2)
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio));
const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape
const float2 * Q_f2 = Q + s03*sequence + s02* head0;
const T_K * K_h2 = K + s13*sequence + s12*(head0 / gqa_ratio);
const T_V * V_h2 = V + s23*sequence + s22*(head0 / gqa_ratio); // K and V have same shape
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head0 % ne32)) : nullptr;
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const int stride_K2 = nb11 / sizeof(half2);
const int stride_V2 = nb21 / sizeof(half2);
const int stride_mask = nb31 / sizeof(half);
const int stride_K2 = s11;
const int stride_V2 = s21;
const int stride_mask = s31;
const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, head0, n_head_log2, m0, m1) : 1.0f;
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp.
@@ -919,8 +825,7 @@ static __global__ void flash_attn_tile(
if (i0 + np*warp_size*cpy_ne_D <= DKQ || i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D < DKQ) {
__align__(16) float tmp_f[cpy_ne_D] = {0.0f};
ggml_cuda_memcpy_1<sizeof(tmp_f)>
(tmp_f, &Q_f[c*(nb02/sizeof(float)) + fastmodulo(col_Q_0 + j, ne01)*(nb01/sizeof(float))
+ i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D]);
(tmp_f, Q_f2 + c*s02 + fastmodulo(col_Q_0 + j, ne01)*s01 + i0/2 + (threadIdx.y % np)*(warp_size*(cpy_ne_D/2)) + threadIdx.x*(cpy_ne_D/2));
#pragma unroll
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
@@ -1056,7 +961,7 @@ static __global__ void flash_attn_tile(
#pragma unroll
for (int jc0 = 0; jc0 < cpw; ++jc0) {
const int jc = jc0 + (threadIdx.y/np)*cpw;
const float sink = ((const float *) sinks)[head0 + jc % ncols2];
const float sink = sinks[head0 + jc % ncols2];
float KQ_max_new_j = fmaxf(KQ_max[jc0], sink);
const float KQ_max_scale = expf(KQ_max[jc0] - KQ_max_new_j);
@@ -1137,18 +1042,21 @@ static __global__ void flash_attn_tile(
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
template <int DKQ, int DV, int ncols2, bool use_logit_softcap>
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const ggml_tensor * Q = dst->src[0];
const int id = ggml_cuda_get_device();
@@ -1159,12 +1067,12 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
#ifdef GGML_USE_HIP
if constexpr (DKQ <= 128) {
if (Q->ne[1] > 32/ncols2) {
if (!(amd_mfma_available(cc) && ncols2 == 1) && Q->ne[1] > 32/ncols2) {
constexpr int cols_per_block = 64;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1179,8 +1087,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 32;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1191,8 +1099,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 16;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1203,8 +1111,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 8;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1215,8 +1123,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 4;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1226,8 +1134,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 2;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1235,7 +1143,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
GGML_ABORT("fatal error");
}
template <int DKQ, int DV, bool use_logit_softcap>
template <int DKQ, int DV, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
@@ -1262,12 +1170,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
// Therefore, use a GQA ratio of 16 with 16 columns / block to stay below 48 kiB of SRAM / block.
#ifdef GGML_USE_HIP
if (use_gqa_opt && gqa_ratio % 32 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
#else
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
#endif // GGML_USE_HIP
@@ -1276,11 +1184,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ == 576) {
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
}
@@ -1288,11 +1196,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ == 192) {
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 8 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
GGML_ABORT("flash-attn tile (192/128): expected GQA ratio multiple of 8");
@@ -1300,29 +1208,29 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ <= 512 && DKQ != 320 && DKQ != 192) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 2 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DV <= 256) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
}
GGML_ABORT("fatal error");
}
template <int DKQ, int DV>
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
@@ -1331,28 +1239,28 @@ void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_te
if (logit_softcap == 0.0f) {
constexpr bool use_logit_softcap = false;
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
} else {
constexpr bool use_logit_softcap = true;
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
}
}
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
#define DECL_FATTN_TILE_CASE(DKQ, DV) \
template void ggml_cuda_flash_attn_ext_tile_case \
<DKQ, DV>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_TILE_CASE(DKQ, DV, type_K, type_V) \
template void ggml_cuda_flash_attn_ext_tile_case \
<DKQ, DV, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
extern DECL_FATTN_TILE_CASE( 40, 40);
extern DECL_FATTN_TILE_CASE( 64, 64);
extern DECL_FATTN_TILE_CASE( 72, 72);
extern DECL_FATTN_TILE_CASE( 80, 80);
extern DECL_FATTN_TILE_CASE( 96, 96);
extern DECL_FATTN_TILE_CASE(112, 112);
extern DECL_FATTN_TILE_CASE(128, 128);
extern DECL_FATTN_TILE_CASE(192, 128);
extern DECL_FATTN_TILE_CASE(256, 256);
extern DECL_FATTN_TILE_CASE(320, 256);
extern DECL_FATTN_TILE_CASE(512, 512);
extern DECL_FATTN_TILE_CASE(576, 512);
extern DECL_FATTN_TILE_CASE( 40, 40, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 64, 64, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 72, 72, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 80, 80, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 96, 96, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16);
+46 -46
View File
@@ -19,15 +19,15 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() {
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap> // D == head size
__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1)
static __global__ void flash_attn_ext_vec(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -35,22 +35,22 @@ static __global__ void flash_attn_ext_vec(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33) {
ggml_cuda_pdl_lc();
#ifdef FLASH_ATTN_AVAILABLE
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
GGML_UNUSED(KV_rows_ptr);
// Skip unused kernel variants for faster compilation:
@@ -58,12 +58,12 @@ static __global__ void flash_attn_ext_vec(
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
return;
}
@@ -108,11 +108,11 @@ static __global__ void flash_attn_ext_vec(
const int sequence = blockIdx.z / ne02;
const int head = blockIdx.z - sequence*ne02;
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
Q += nb03*sequence + nb02* head + nb01*ic0;
K += nb13*sequence + nb12*(head / gqa_ratio);
V += nb23*sequence + nb22*(head / gqa_ratio);
Q += s03*sequence + s02* head + s01*ic0;
K += s13*sequence + s12*(head / gqa_ratio);
V += s23*sequence + s22*(head / gqa_ratio);
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head % ne32) + nb31*ic0) : nullptr;
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1);
@@ -176,7 +176,7 @@ static __global__ void flash_attn_ext_vec(
tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f);
}
} else {
const float * Q_f = (const float *) (Q + j*nb01);
const float * Q_f = (const float *) (Q + j*s01);
constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE;
#pragma unroll
for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) {
@@ -206,7 +206,7 @@ static __global__ void flash_attn_ext_vec(
} else if constexpr (type_K == GGML_TYPE_F8_E4M3) {
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float * Q_j = (const float *) (Q + j*nb01);
const float * Q_j = (const float *) (Q + j*s01);
#pragma unroll
for (int i0 = 0; i0 < D; i0 += nthreads_KQ*4) {
const int i = i0 + (threadIdx.x % nthreads_KQ)*4;
@@ -229,7 +229,7 @@ static __global__ void flash_attn_ext_vec(
const half2 scale_h2 = make_half2(scale, scale);
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float2 * Q_j = (const float2 *) (Q + j*nb01);
const float2 * Q_j = Q + j*s01;
#pragma unroll
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
@@ -252,7 +252,7 @@ static __global__ void flash_attn_ext_vec(
#else
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float2 * Q_j = (const float2 *) (Q + j*nb01);
const float2 * Q_j = Q + j*s01;
#pragma unroll
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
@@ -271,12 +271,12 @@ static __global__ void flash_attn_ext_vec(
}
const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11;
K += blockIdx.y*nthreads * nb11;
V += blockIdx.y*nthreads * nb21;
K += blockIdx.y*nthreads * s11;
V += blockIdx.y*nthreads * s21;
maskh += blockIdx.y*nthreads;
for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads,
// Increment pointers after each loop:
K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) {
K += gridDim.y*nthreads*s11, V += gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) {
// Calculate KQ tile and keep track of new maximum KQ values:
float KQ_reg[ncols]; // KQ in registers.
@@ -293,7 +293,7 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int j = 0; j < ncols; ++j) {
float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]);
float sum = vec_dot_KQ(K + i_KQ*s11, Q_reg[j], Q_i32[j], Q_ds[j]);
sum = warp_reduce_sum<nthreads_KQ>(sum);
if (use_logit_softcap) {
@@ -357,14 +357,14 @@ static __global__ void flash_attn_ext_vec(
half2 tmp[V_rows_per_thread/2];
if constexpr (type_V == GGML_TYPE_BF16) {
float2 tmp_f[V_rows_per_thread/2];
dequantize_V(V + k*nb21, tmp_f,
dequantize_V(V + k*s21, tmp_f,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
#pragma unroll
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]);
}
} else {
dequantize_V(V + k*nb21, tmp,
dequantize_V(V + k*s21, tmp,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
}
#pragma unroll
@@ -384,7 +384,7 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) {
float2 tmp[V_rows_per_thread/2];
dequantize_V(V + k*nb21, tmp,
dequantize_V(V + k*s21, tmp,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
#pragma unroll
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
@@ -402,7 +402,7 @@ static __global__ void flash_attn_ext_vec(
}
if (sinks && blockIdx.y == 0) {
const float sink = ((const float *) sinks)[head];
const float sink = sinks[head];
#pragma unroll
for (int j0 = 0; j0 < ncols; j0 += nwarps) {
@@ -540,12 +540,12 @@ static __global__ void flash_attn_ext_vec(
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
@@ -563,7 +563,7 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
const bool need_f16_K = type_K == GGML_TYPE_F16;
const bool need_f16_V = type_V == GGML_TYPE_F16;
constexpr size_t nbytes_shared = 0;
launch_fattn<D, cols_per_block, 1>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
launch_fattn<D, cols_per_block, 1, char, char>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
}
template <int D, ggml_type type_K, ggml_type type_V>
+72 -52
View File
@@ -159,7 +159,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_
#endif // !defined(GGML_USE_MUSA)
}
template <int DKQ, int DV, int ncols2>
template <int DKQ, int DV, int ncols2, ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * Q = dst->src[0];
@@ -169,7 +169,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
// a sparse variant at the full tile width gathers the union of its queries once, prefer it for large batches
constexpr bool has_wide_sparse = ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 64/ncols2, ncols2);
if (!(has_wide_sparse && Q->ne[1] > 32/ncols2) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, ncols2)) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
@@ -177,38 +177,39 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
if constexpr (ncols2 <= 8) {
if (turing_mma_available(cc) && Q->ne[1] <= 8/ncols2) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
if constexpr (ncols2 <= 16) {
if (Q->ne[1] <= 16/ncols2) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
if (Q->ne[1] <= 32/ncols2 || (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_TURING) ||
(GGML_CUDA_CC_IS_AMD(cc) && DKQ > 256)) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2, type_K, type_V>(ctx, dst);
}
template <int DKQ, int DV>
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * kv_rows = dst->src[5];
// with kv_rows the kernel iterates over the mask columns
const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1];
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
float max_bias = 0.0f;
memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
@@ -235,22 +236,22 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
// On Volta the GQA optimizations aren't as impactful vs. minimizing wasted compute:
if (cc == GGML_CUDA_CC_VOLTA) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
if (use_gqa_opt && gqa_ratio % 2 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
return;
} else {
GGML_ABORT("fatal error");
@@ -260,44 +261,45 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
// On RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask.
if (amd_wmma_available(cc)) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 2 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
}
if (use_gqa_opt && gqa_ratio > 4) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio > 2) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio > 1) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
} else {
GGML_ABORT("fatal error");
}
}
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
template <ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
@@ -308,31 +310,31 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
switch (Q->ne[0]) {
case 40:
GGML_ASSERT(V->ne[0] == 40);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40, type_K, type_V>(ctx, dst);
break;
case 64:
GGML_ASSERT(V->ne[0] == 64);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64, type_K, type_V>(ctx, dst);
break;
case 72:
GGML_ASSERT(V->ne[0] == 72);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72, type_K, type_V>(ctx, dst);
break;
case 80:
GGML_ASSERT(V->ne[0] == 80);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80, type_K, type_V>(ctx, dst);
break;
case 96:
GGML_ASSERT(V->ne[0] == 96);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96, type_K, type_V>(ctx, dst);
break;
case 112:
GGML_ASSERT(V->ne[0] == 112);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112, type_K, type_V>(ctx, dst);
break;
case 128:
GGML_ASSERT(V->ne[0] == 128);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128, type_K, type_V>(ctx, dst);
break;
case 192: {
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
@@ -344,15 +346,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (gqa_ratio % 16 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16, type_K, type_V>(ctx, dst);
} else {
GGML_ASSERT(gqa_ratio % 8 == 0);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8, type_K, type_V>(ctx, dst);
}
} break;
case 256:
GGML_ASSERT(V->ne[0] == 256);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256, type_K, type_V>(ctx, dst);
break;
case 320:
// For Mistral Small 4, go straight to the ncols1 switch (ncols2=32-only build).
@@ -367,12 +369,12 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
const int gqa_ratio = Q->ne[2] / K->ne[2];
GGML_ASSERT(gqa_ratio % 32 == 0);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32, type_K, type_V>(ctx, dst);
}
break;
case 512:
GGML_ASSERT(V->ne[0] == 512);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512, type_K, type_V>(ctx, dst);
break;
case 576: {
// For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels.
@@ -386,50 +388,50 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (amd_mfma_available(cc) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, 16)) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
} else if (gqa_ratio == 20 && GGML_CUDA_CC_IS_NVIDIA(cc)) { // GLM 4.7 Flash
if (cc >= GGML_CUDA_CC_GB10) {
if (Q->ne[1] <= 8) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_BLACKWELL) {
if (Q->ne[1] <= 4 && K->ne[1] >= 65536) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_ADA_LOVELACE) {
if (Q->ne[1] <= 4) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_TURING) {
if (Q->ne[1] <= 4) {
if (K->ne[1] <= 16384) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
// Volta:
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
} else if (gqa_ratio % 16 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
} else {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
}
} break;
default:
@@ -437,6 +439,21 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
}
}
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
if constexpr (GGML_CUDA_FA_F16_F16) {
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
return;
}
}
// Fallback: convert K and V to F16.
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
}
#define FATTN_VEC_CASE(D, type_K_case, type_V_case) \
if constexpr (GGML_CUDA_FA_##type_K_case##_##type_V_case) { \
if (head_size == (D) && type_K == GGML_TYPE_##type_K_case && type_V == GGML_TYPE_##type_V_case) { \
@@ -732,12 +749,15 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
gqa_ratio_eff *= 2;
}
// the tile kernel for DKQ=576 only has the ncols2 = 4 and 16 variants
const best_fattn_kernel tile_kernel = Q->ne[0] == 576 && gqa_ratio % 4 != 0 ? BEST_FATTN_KERNEL_NONE : BEST_FATTN_KERNEL_TILE;
if (volta_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) {
if (can_use_vector_kernel && Q->ne[1] * gqa_ratio_eff <= 2) {
return BEST_FATTN_KERNEL_VEC;
}
if (Q->ne[1] * gqa_ratio_eff <= 16) {
return BEST_FATTN_KERNEL_TILE; // On Volta tensor cores are only faster for sufficiently large matrices.
return tile_kernel; // On Volta tensor cores are only faster for sufficiently large matrices.
}
return BEST_FATTN_KERNEL_MMA_F16;
}
@@ -783,7 +803,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
}
}
}
return BEST_FATTN_KERNEL_TILE;
return tile_kernel;
}
size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst) {
+36 -19
View File
@@ -1,9 +1,11 @@
#include "convert.cuh"
#include "fp8.cuh"
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11080
template <typename src_t>
struct fp8_abs_src {
const float * x;
const src_t * x;
int64_t ne0;
int64_t ne1;
int64_t ne2;
@@ -18,12 +20,13 @@ struct fp8_abs_src {
i /= ne1;
const int64_t i2 = i % ne2;
const int64_t i3 = i / ne2;
const float value = fabsf(x[i0 + i1*s1 + i2*s2 + i3*s3]);
const float value = fabsf(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]));
return isfinite(value) ? value : 448.0f;
}
};
static __global__ void fp8_amax_partials(fp8_abs_src src, int64_t ne, float * partials) {
template <typename src_t>
static __global__ void fp8_amax_partials(fp8_abs_src<src_t> src, int64_t ne, float * partials) {
float amax = 0.0f;
for (int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; i < ne; i += (int64_t) blockDim.x*gridDim.x) {
amax = fmaxf(amax, src(i));
@@ -49,8 +52,9 @@ static __global__ void fp8_amax_final(const float * partials, int n, float * ama
}
}
template <typename src_t>
static __global__ void quantize_fp8_e4m3(
const float * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
const src_t * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
float * __restrict__ scale, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3) {
const int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x;
if (i >= ne) {
@@ -65,12 +69,26 @@ static __global__ void quantize_fp8_e4m3(
const int64_t i3 = tmp / ne2;
const float d = *amax > 0.0f ? *amax / 448.0f : 1.0f;
y[i] = ggml_cuda_fp32_to_f8_e4m3(x[i0 + i1*s1 + i2*s2 + i3*s3] / d);
y[i] = ggml_cuda_fp32_to_f8_e4m3(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]) / d);
if (i == 0) {
*scale = d;
}
}
// src1 (F32 or BF16) to FP8 with one scale for the whole tensor: amax / 448
template <typename src_t>
static void fp8_quantize_src1(
ggml_backend_cuda_context & ctx, const src_t * x, uint8_t * y, float * amax, float * scale,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3, cudaStream_t stream) {
const fp8_abs_src<src_t> abs_src = { x, ne0, ne1, ne2, s1, s2, s3 };
const int reduce_blocks = std::min<int64_t>((ne + 255)/256, 1024);
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne, reduce_tmp.ptr);
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, amax);
quantize_fp8_e4m3<<<(ne + 255)/256, 256, 0, stream>>>(x, y, amax, scale, ne0, ne1, ne2, ne, s1, s2, s3);
}
static void fp8_set_batch(cublasLtMatrixLayout_t desc, int32_t count, int64_t stride) {
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &count, sizeof(count)));
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride, sizeof(stride)));
@@ -89,9 +107,9 @@ bool ggml_cuda_mul_mat_fp8(
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
const ggml_tensor * weight_scale) {
const int cc = ggml_cuda_info().devices[ctx.device].cc;
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || src1->type != GGML_TYPE_F32 ||
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) ||
dst->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst) || src0->ne[0] % 16 != 0 || src0->ne[1] % 16 != 0 ||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != sizeof(float) ||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != ggml_type_size(src1->type) ||
!ggml_cuda_is_aligned(src0, 16) || !ggml_cuda_is_aligned(dst, 16)) {
return false;
}
@@ -110,18 +128,17 @@ bool ggml_cuda_mul_mat_fp8(
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool(), 1);
ggml_cuda_pool_alloc<float> src1_amax(ctx.pool(), 1);
const fp8_abs_src abs_src = {
(const float *) src1->data, ne10, ne11, ne12,
(int64_t) (nb11 / sizeof(float)), (int64_t) (nb12 / sizeof(float)), (int64_t) (nb13 / sizeof(float))
};
const int reduce_blocks = std::min<int64_t>((ne_src1 + 255)/256, 1024);
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne_src1, reduce_tmp.ptr);
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, src1_amax.ptr);
quantize_fp8_e4m3<<<(ne_src1 + 255)/256, 256, 0, stream>>>(
(const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, ne10, ne11, ne12, ne_src1,
nb11 / sizeof(float), nb12 / sizeof(float), nb13 / sizeof(float));
const int64_t s11 = nb11 / nb10;
const int64_t s12 = nb12 / nb10;
const int64_t s13 = nb13 / nb10;
if (src1->type == GGML_TYPE_BF16) {
fp8_quantize_src1(ctx, (const nv_bfloat16 *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
} else {
GGML_ASSERT(src1->type == GGML_TYPE_F32);
fp8_quantize_src1(ctx, (const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
}
CUDA_CHECK(cudaGetLastError());
cublasLtMatmulDesc_t op_desc;
File diff suppressed because it is too large Load Diff
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include "common.cuh"
#include "ggml-backend-impl.h"
// try and fuse nodes starting at node i and return the number of nodes to skip
int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i);
// add alloc deps for the fusions that need their inputs to stay alive (called from graph_optimize)
void ggml_cuda_fusion_add_alloc_deps(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params);
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
#pragma once
// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu
// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu and fusion.cu
#include "common.cuh"
+396
View File
@@ -0,0 +1,396 @@
#include "inkling2.cuh"
// the fused kernels keep the operation order of the unfused graph where it is cheap to do so,
// __fmul_rn/__fadd_rn stop the compiler from contracting a separate MUL and ADD into one FMA
static __global__ void situ_f32(
const float * gate, const float * up, float * dst, const int ne0, const int ne1, const int ne2, const int64_t nrows,
const int64_t g_s1, const int64_t g_s2, const int64_t g_s3, const int64_t u_s1, const int64_t u_s2, const int64_t u_s3,
const float s0, const float b0, const float s1, const float b1, const float s2, const float b2, const float s3, const float b3) {
ggml_cuda_pdl_lc();
const int i0 = blockIdx.x*blockDim.x + threadIdx.x;
ggml_cuda_pdl_sync();
if (i0 >= ne0) {
return;
}
for (int64_t row = blockIdx.y; row < nrows; row += gridDim.y) {
const int64_t i1 = row % ne1;
const int64_t i2 = (row / ne1) % ne2;
const int64_t i3 = row / ((int64_t) ne1*ne2);
const float g = gate[i3*g_s3 + i2*g_s2 + i1*g_s1 + i0];
const float u = up [i3*u_s3 + i2*u_s2 + i1*u_s1 + i0];
const float act = s1*tanhf(s0*g + b0) + b1;
const float sig = 1.0f/(1.0f + expf(-g));
const float lin = s3*tanhf(s2*u + b2) + b3;
dst[row*ne0 + i0] = __fmul_rn(__fmul_rn(act, sig), lin);
}
}
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
const float * s, const float * b, ggml_tensor * dst) {
GGML_ASSERT(gate->type == GGML_TYPE_F32 && up->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
GGML_ASSERT(gate->nb[0] == sizeof(float) && up->nb[0] == sizeof(float) && ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(gate, up) && ggml_are_same_shape(gate, dst));
const int64_t ne0 = gate->ne[0];
const int64_t nrows = ggml_nrows(gate);
const int block_size = 256;
const dim3 grid((ne0 + block_size - 1)/block_size, std::min<int64_t>(nrows, 65535), 1);
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
ggml_cuda_kernel_launch(situ_f32, params,
(const float *) gate->data, (const float *) up->data, (float *) dst->data, (int) ne0, (int) gate->ne[1], (int) gate->ne[2], nrows,
(int64_t) (gate->nb[1]/sizeof(float)), (int64_t) (gate->nb[2]/sizeof(float)), (int64_t) (gate->nb[3]/sizeof(float)),
(int64_t) (up->nb[1]/sizeof(float)), (int64_t) (up->nb[2]/sizeof(float)), (int64_t) (up->nb[3]/sizeof(float)),
s[0], b[0], s[1], b[1], s[2], b[2], s[3], b[3]);
}
// one thread per (channel, run of tokens of one sequence). the last K columns of x stay in registers, right-aligned in
// M = GGML_CUDA_SHORT_CONV_MAX_K slots with zero weights in front, so K needs no template and the sums keep their order.
// a thread reads cur at a token before it writes dst there and never again, so dst may be cur itself when a thread has
// the whole sequence
template <bool has_dyn, bool has_res>
static __global__ void short_conv_f32(const ggml_cuda_short_conv_args a) {
ggml_cuda_pdl_lc();
constexpr int M = GGML_CUDA_SHORT_CONV_MAX_K;
const int K = a.K;
const int K1 = K - 1;
const int c = blockIdx.x*blockDim.x + threadIdx.x;
ggml_cuda_pdl_sync();
if (c >= a.C) {
return;
}
float w[M];
#pragma unroll
for (int m = 0; m < M; ++m) {
w[m] = m >= M - K ? a.w[c*K + m - (M - K)] : 0.0f;
}
const int n_runs = (a.Ts + a.run - 1)/a.run;
for (int r = blockIdx.y; r < a.S*n_runs; r += gridDim.y) {
const int s = r / n_runs;
const int t0 = (r - s*n_runs)*a.run;
const int t1 = min(t0 + a.run, a.Ts);
const float * pc = a.past + c*a.past_s1 + s*a.past_s2;
const float * xc = a.cur + (int64_t) s*a.Ts*a.C + c;
// x[M - K + k] is column ts + k of [past; cur^T]
float x[M];
#pragma unroll
for (int m = 0; m < M - 1; ++m) {
const int j = t0 + m - (M - K);
x[m] = j < 0 ? 0.0f : j < K1 ? pc[j] : xc[(int64_t) (j - K1)*a.C];
}
for (int ts = t0; ts < t1; ++ts) {
const int64_t t = (int64_t) s*a.Ts + ts;
x[M - 1] = xc[(int64_t) ts*a.C];
float y = 0.0f;
#pragma unroll
for (int m = 0; m < M; ++m) {
y += x[m]*w[m];
}
if constexpr (has_dyn) {
const float * d = a.dyn + t*a.dyn_s1 + (c / (a.C / a.n_heads))*K;
#pragma unroll
for (int lag = 0; lag < M; ++lag) {
if (lag < K) {
y = __fadd_rn(y, __fmul_rn(x[M - 1 - lag], d[lag]));
}
}
}
float o = a.scale*__fadd_rn(x[M - 1], y) + a.bias;
if constexpr (has_res) {
o = __fadd_rn(a.res[t*a.C + c], o);
}
a.dst[t*a.C + c] = o;
#pragma unroll
for (int m = 0; m < M - 1; ++m) {
x[m] = x[m + 1];
}
// x now holds the K - 1 columns that end at token ts: the conv state of slot Ts - 1 - ts, if it is kept
if (ts >= a.Ts - a.kw) {
float * st = a.state + (a.Ts - 1 - ts)*a.state_slot_s + c*a.state_ch_s + s*a.state_seq_s;
#pragma unroll
for (int m = 0; m < M - 1; ++m) {
if (m >= M - K) {
st[m - (M - K)] = x[m];
}
}
}
}
}
}
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & a) {
GGML_ASSERT(a.K >= 2 && a.K <= GGML_CUDA_SHORT_CONV_MAX_K);
const int block_size = 128;
const int n_runs = (a.Ts + a.run - 1)/a.run;
const dim3 grid((a.C + block_size - 1)/block_size, std::min(a.S*n_runs, 65535), 1);
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
if (a.dyn) {
if (a.res) {
ggml_cuda_kernel_launch(short_conv_f32<true, true>, params, a);
} else {
ggml_cuda_kernel_launch(short_conv_f32<true, false>, params, a);
}
} else {
if (a.res) {
ggml_cuda_kernel_launch(short_conv_f32<false, true>, params, a);
} else {
ggml_cuda_kernel_launch(short_conv_f32<false, false>, params, a);
}
}
}
// one block per (query, token): the dot products of the B stack rows and of cur with the query, the softmax over the
// B + 1 rows and the weighted sum; the norm of cur is a scale of its dot product
template <int block_size>
static __global__ void depth_mix_f32(
const float * stack, const float * cur, const float * query, float * dst, const int n, const int B, const int Q,
const int64_t stack_s1, const int64_t stack_s2, const int64_t cur_s1, const int64_t query_s1,
const bool norm_cur, const float eps, const float scale) {
ggml_cuda_pdl_lc();
constexpr int MAX = GGML_CUDA_DEPTH_MIX_MAX_ROWS;
constexpr int NW = block_size/WARP_SIZE;
const int q = blockIdx.x;
const int t = blockIdx.y;
const int tid = threadIdx.x;
const int lane = tid % WARP_SIZE;
const int warp = tid / WARP_SIZE;
const float * qv = query + q*query_s1;
const float * st = stack + t*stack_s2;
const float * xc = cur + t*cur_s1;
// [0, B): the stack rows, MAX: cur, MAX + 1: the sum of squares of cur
float acc[MAX + 2];
#pragma unroll
for (int r = 0; r < MAX + 2; ++r) {
acc[r] = 0.0f;
}
ggml_cuda_pdl_sync();
for (int i = tid; i < n; i += block_size) {
const float qi = qv[i];
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] += st[r*stack_s1 + i]*qi;
}
}
const float xi = xc[i];
acc[MAX] += xi*qi;
acc[MAX + 1] += xi*xi;
}
__shared__ float s_acc[NW][MAX + 2];
#pragma unroll
for (int r = 0; r < MAX + 2; ++r) {
if (r < B || r >= MAX) {
acc[r] = warp_reduce_sum(acc[r]);
if (lane == 0) {
s_acc[warp][r] = acc[r];
}
}
}
__syncthreads();
#pragma unroll
for (int r = 0; r < MAX + 2; ++r) {
if (r < B || r >= MAX) {
acc[r] = 0.0f;
#pragma unroll
for (int w = 0; w < NW; ++w) {
acc[r] += s_acc[w][r];
}
}
}
const float sc = norm_cur ? rsqrtf(acc[MAX + 1]/n + eps) : 1.0f;
float mx = scale*(sc*acc[MAX]);
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] = scale*acc[r];
mx = fmaxf(mx, acc[r]);
}
}
float p_cur = expf(scale*(sc*acc[MAX]) - mx);
float sum = 0.0f;
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] = expf(acc[r] - mx);
sum += acc[r];
}
}
sum += p_cur;
const float inv = 1.0f/sum;
#pragma unroll
for (int r = 0; r < MAX; ++r) {
acc[r] *= inv;
}
p_cur *= inv*sc;
for (int i = tid; i < n; i += block_size) {
float o = 0.0f;
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
o += acc[r]*st[r*stack_s1 + i];
}
}
o += p_cur*xc[i];
dst[((int64_t) t*n + i)*Q + q] = o;
}
}
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst) {
const int64_t n = cur->ne[0];
const int64_t B = stack->ne[1];
const int64_t T = stack->ne[2];
const int64_t Q = query->ne[1];
GGML_ASSERT(B >= 1 && B <= GGML_CUDA_DEPTH_MIX_MAX_ROWS);
GGML_ASSERT(stack->nb[0] == sizeof(float) && cur->nb[0] == sizeof(float) && query->nb[0] == sizeof(float));
GGML_ASSERT(ggml_is_contiguous(dst) && dst->ne[0] == Q && dst->ne[1] == n && dst->ne[2] == T);
GGML_ASSERT(T <= 65535 && Q <= 65535);
const int block_size = 256;
const dim3 grid(Q, T, 1);
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
ggml_cuda_kernel_launch(depth_mix_f32<block_size>, params,
(const float *) stack->data, (const float *) cur->data, (const float *) query->data, (float *) dst->data,
(int) n, (int) B, (int) Q,
(int64_t) (stack->nb[1]/sizeof(float)), (int64_t) (stack->nb[2]/sizeof(float)),
(int64_t) (cur->nb[2]/sizeof(float)), (int64_t) (query->nb[1]/sizeof(float)),
norm_cur, eps, scale);
}
// one block per (rank row, token): the sums of squares of cur and msg and their dot products with the two halves of the row
template <int block_size>
static __global__ void loop_ctrl_down_f32(
const float * cur, const float * msg, const float * w, float * gate, const int n,
const int64_t cur_s1, const int64_t msg_s1, const int64_t w_s1, const int64_t gate_s1, const float eps) {
ggml_cuda_pdl_lc();
const int r = blockIdx.x;
const int t = blockIdx.y;
const int tid = threadIdx.x;
const float * xc = cur + t*cur_s1;
const float * xm = msg + t*msg_s1;
const float * wr = w + r*w_s1;
ggml_cuda_pdl_sync();
float2 ss = make_float2(0.0f, 0.0f);
float2 dd = make_float2(0.0f, 0.0f);
for (int i = tid; i < n; i += block_size) {
const float c = xc[i];
const float m = xm[i];
ss.x += c*c;
ss.y += m*m;
dd.x += wr[i]*c;
dd.y += wr[n + i]*m;
}
__shared__ float2 s_ss[32];
__shared__ float2 s_dd[32];
ss = block_reduce<block_reduce_method::SUM, block_size>(ss, s_ss);
dd = block_reduce<block_reduce_method::SUM, block_size>(dd, s_dd);
if (tid == 0) {
gate[t*gate_s1 + r] = rsqrtf(ss.x/n + eps)*dd.x + rsqrtf(ss.y/n + eps)*dd.y;
}
}
// one warp per (output channel, token): the gain and forget dot products over the rank and the combine
static __global__ void loop_ctrl_up_f32(
const float * cur, const float * msg, const float * gate, const float * wg, const float * wf, float * dst,
const int n, const int rank, const int64_t cur_s1, const int64_t msg_s1, const int64_t gate_s1,
const int64_t wg_s1, const int64_t wf_s1, const int64_t dst_s1) {
ggml_cuda_pdl_lc();
const int i = blockIdx.x*blockDim.y + threadIdx.y;
const int t = blockIdx.y;
const int lane = threadIdx.x;
ggml_cuda_pdl_sync();
if (i >= n) {
return;
}
const float * gt = gate + t*gate_s1;
float g = 0.0f;
float f = 0.0f;
for (int k = lane; k < rank; k += WARP_SIZE) {
const float x = gt[k];
g += wg[i*wg_s1 + k]*x;
f += wf[i*wf_s1 + k]*x;
}
g = warp_reduce_sum(g);
f = warp_reduce_sum(f);
if (lane == 0) {
const float c = cur[t*cur_s1 + i];
const float m = msg[t*msg_s1 + i];
const float a = __fsub_rn(c, __fmul_rn(tanhf(f), c));
dst[t*dst_s1 + i] = __fadd_rn(a, __fmul_rn(tanhf(g), m));
}
}
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst) {
const int64_t n = cur->ne[0];
const int64_t T = cur->ne[1];
const int64_t rank = w_down->ne[1];
GGML_ASSERT(cur->nb[0] == sizeof(float) && msg->nb[0] == sizeof(float) && gate->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float));
GGML_ASSERT(w_down->ne[0] == 2*n && w_gain->ne[0] == rank && w_forget->ne[0] == rank && w_gain->ne[1] == n && w_forget->ne[1] == n);
GGML_ASSERT(T <= GGML_CUDA_LOOP_CTRL_MAX_TOKENS);
cudaStream_t stream = ctx.stream();
{
const int block_size = 256;
const ggml_cuda_kernel_launch_params params(dim3(rank, T, 1), dim3(block_size, 1, 1), 0, stream);
ggml_cuda_kernel_launch(loop_ctrl_down_f32<block_size>, params,
(const float *) cur->data, (const float *) msg->data, (const float *) w_down->data, (float *) gate->data, (int) n,
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)),
(int64_t) (w_down->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)), eps);
}
{
const int rows_per_block = 8;
const ggml_cuda_kernel_launch_params params(dim3((n + rows_per_block - 1)/rows_per_block, T, 1), dim3(WARP_SIZE, rows_per_block, 1), 0, stream);
ggml_cuda_kernel_launch(loop_ctrl_up_f32, params,
(const float *) cur->data, (const float *) msg->data, (const float *) gate->data,
(const float *) w_gain->data, (const float *) w_forget->data, (float *) dst->data, (int) n, (int) rank,
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)),
(int64_t) (w_gain->nb[1]/sizeof(float)), (int64_t) (w_forget->nb[1]/sizeof(float)), (int64_t) (dst->nb[1]/sizeof(float)));
}
}
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "common.cuh"
// fused op chains of the Inkling 2 graph
// largest conv width and stack depth the fused kernels handle
#define GGML_CUDA_SHORT_CONV_MAX_K 8
#define GGML_CUDA_DEPTH_MIX_MAX_ROWS 16
// the most tokens the fused loop controller handles, larger batches use the matrix multiplications
#define GGML_CUDA_LOOP_CTRL_MAX_TOKENS 8
// situ(g, u) = (s1*tanh(s0*g + b0) + b1)*sigmoid(g)*(s3*tanh(s2*u + b2) + b3), with s and b of the four SCALE nodes
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
const float * s, const float * b, ggml_tensor * dst);
// causal short conv: x = [past; cur^T], y = conv(x, w) (+ input-dependent taps per head), dst = s*(cur + y) + b (+ res)
// the K - 1 columns of x that end at token Ts - 1 - slot are the conv state of slot, for the last kw slots (kw = 1 without rollback)
// each thread does `run` tokens of a sequence in order, run == Ts lets dst be cur
struct ggml_cuda_short_conv_args {
const float * past; // [K - 1, C, S], strides in elements
int64_t past_s1;
int64_t past_s2;
const float * cur; // [C, Ts*S], contiguous
const float * w; // [K, C], contiguous
const float * dyn; // [K*H, Ts*S] taps or nullptr
int64_t dyn_s1;
int n_heads;
const float * res; // [C, Ts*S], contiguous, or nullptr
float * dst; // [C, Ts*S], contiguous
float * state; // [K - 1, slot, C, S], strides in elements
int64_t state_slot_s;
int64_t state_ch_s;
int64_t state_seq_s;
int kw;
int run;
int C;
int K;
int Ts;
int S;
float scale;
float bias;
};
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & args);
// depth mix: states = [stack; rms_norm(cur)], p = softmax(scale*(states . query)), dst = p . states, written as [Q, n, T]
// norm_cur false: cur is already normalized
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst);
// loop controller: gate = w_down . [rms_norm(cur); rms_norm(msg)], dst = cur - tanh(w_forget . gate)*cur + tanh(w_gain . gate)*msg
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst);
+4 -4
View File
@@ -98,9 +98,9 @@ static __global__ void mul_mat_f(
const int sample_x = sample_dst / sample_ratio;
const int sample_y = sample_dst;
x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row ;
y += int64_t(sample_y) *stride_sample_y + channel_y *stride_channel_y;
dst += int64_t(sample_dst)*stride_sample_dst + channel_dst*stride_channel_dst;
x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x) *stride_channel_x + int64_t(row0)*stride_row;
y += int64_t(sample_y) *stride_sample_y + int64_t(channel_y) *stride_channel_y;
dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst;
[[maybe_unused]] const float2 * y2 = (const float2 *) y;
@@ -290,7 +290,7 @@ static __global__ void mul_mat_f_ids(
const int sample_x = sample_dst / sample_ratio;
const int sample_y = sample_dst;
x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row;
x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x) *stride_channel_x + int64_t(row0)*stride_row;
y += int64_t(sample_y) *stride_sample_y;
dst += int64_t(sample_dst)*stride_sample_dst;
+5 -5
View File
@@ -799,10 +799,10 @@ static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
GGML_TENSOR_BINARY_OP_LOCALS;
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
GGML_ASSERT(nb00 == ggml_type_size(src0->type));
GGML_ASSERT(nb10 == sizeof(float));
GGML_ASSERT(nb10 == ggml_type_size(src1->type));
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(ne00 % QK_K == 0);
@@ -828,14 +828,14 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
pairs.alloc(int64_t(npairs_max)*MMQ_FEW_PAIR_INTS);
src1_q.alloc(int64_t(npairs_max)*nunits*MMQ_FEW_Q8_1_INT4);
quantize_mmq_few_id_q8_1_cuda((const float *) src1->data, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
ne00, nb11/sizeof(float), nb12/sizeof(float), ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
quantize_mmq_few_id_q8_1_cuda(src1->data, src1->type, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
} else {
GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS);
GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0);
src1_q.alloc(int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4);
quantize_mmq_few_q8_1_cuda((const float *) src1->data, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/sizeof(float), nb12/sizeof(float), nb13/sizeof(float),
quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/nb10, nb12/nb10, nb13/nb10,
ne11, ne12, ne13, stream);
}
+7 -8
View File
@@ -164,7 +164,7 @@ static int ggml_cuda_mmq_get_J_best(
void ggml_cuda_mul_mat_q(
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
const ggml_cuda_mm_fusion_args_host * fusion) {
GGML_ASSERT( src1->type == GGML_TYPE_F32);
GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
@@ -210,7 +210,6 @@ void ggml_cuda_mul_mat_q(
GGML_ASSERT(!ids || ids->nb[0] == ggml_type_size(ids->type));
const char * src0_d = (const char *) src0->data;
const float * src1_d = (const float *) src1->data;
float * dst_d = (float *) dst->data;
// If src0 (or the fused gate weight) is a temporary compute buffer, clear any potential padding.
@@ -284,11 +283,11 @@ void ggml_cuda_mul_mat_q(
static constexpr size_t align_float8 = 32;
const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8);
static_assert(sizeof(block_fp4_mmq) == 4 * sizeof(block_q8_1));
quantize_mmq_fp4_cuda(src1_d, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded,
quantize_mmq_fp4_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded,
ne11, ne12, ne13, stream);
} else {
quantize_mmq_q8_1_cuda(src1_d, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded,
quantize_mmq_q8_1_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded,
ne11, ne12, ne13, stream);
}
CUDA_CHECK(cudaGetLastError());
@@ -359,17 +358,17 @@ void ggml_cuda_mul_mat_q(
static constexpr size_t align_float8 = 32;
const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8);
if (dedup_bcast) {
quantize_scatter_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10,
quantize_scatter_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10,
/*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream);
} else {
quantize_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13,
quantize_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13,
ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream);
}
} else if (dedup_bcast) {
quantize_scatter_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10,
quantize_scatter_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10,
/*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream);
} else {
quantize_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13,
quantize_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13,
ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream);
}
CUDA_CHECK(cudaGetLastError());
+66 -27
View File
@@ -13,15 +13,20 @@ static __device__ __forceinline__ float2 mmvf_load_fp8x2(const ggml_fp8_e4m3_t *
#endif
}
template <typename T, typename type_acc, int ncols_dst, int block_size, bool has_fusion = false, bool is_multi_token_id = false>
template <typename T, typename type_acc, int ncols_dst, int block_size, bool has_fusion = false, bool is_multi_token_id = false,
typename T_y = float>
static __global__ void mul_mat_vec_f(
const T * x_ptr, const float * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr,
const T * x_ptr, const T_y * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr,
const int ncols2, const uint3 nchannels_y, const int stride_row, const int stride_col_y2, const int stride_col_dst,
const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const int ids_stride) {
static_assert(std::is_same_v<T_y, float> || (std::is_same_v<T_y, nv_bfloat16> &&
(std::is_same_v<T, nv_bfloat16> || std::is_same_v<T, ggml_fp8_e4m3_t>)), "a BF16 src1 needs BF16 or FP8 weights");
using T_y2 = std::conditional_t<std::is_same_v<T_y, nv_bfloat16>, nv_bfloat162, float2>; // a pair of src1 values
const T * GGML_CUDA_RESTRICT x = x_ptr;
const float * GGML_CUDA_RESTRICT y = y_ptr;
const T_y * GGML_CUDA_RESTRICT y = y_ptr;
const int32_t * GGML_CUDA_RESTRICT ids = ids_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
const int row = blockIdx.x;
@@ -257,7 +262,7 @@ static __global__ void mul_mat_vec_f(
#endif // FP16_AVAILABLE
}
} else if constexpr (std::is_same_v<T, nv_bfloat16>) {
const float2 * y2 = (const float2 *) y;
const T_y2 * y2 = (const T_y2 *) y;
//TODO: add support for ggml_cuda_mad for hip_bfloat162
#if defined(GGML_USE_HIP)
const int * x2 = (const int *) x;
@@ -277,7 +282,7 @@ static __global__ void mul_mat_vec_f(
}
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
const float2 tmpy = y2[j*stride_col_y2 + col2];
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
const float tmpx0 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[0]);
const float tmpx1 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[1]);
ggml_cuda_mad(sumf[j], tmpx0, tmpy.x);
@@ -311,7 +316,7 @@ static __global__ void mul_mat_vec_f(
}
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
const float2 tmpy = y2[j*stride_col_y2 + col2];
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
@@ -325,7 +330,7 @@ static __global__ void mul_mat_vec_f(
}
#endif
} else if constexpr (std::is_same_v<T, ggml_fp8_e4m3_t>) {
const float2 * y2 = (const float2 *) y;
const T_y2 * y2 = (const T_y2 *) y;
for (int col2 = tid; col2 < ncols2; col2 += block_size) {
const float2 tmpx = mmvf_load_fp8x2(x, col2);
float2 tmpx_gate = {};
@@ -336,7 +341,7 @@ static __global__ void mul_mat_vec_f(
}
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
const float2 tmpy = y2[j*stride_col_y2 + col2];
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
ggml_cuda_mad(sumf[j], tmpx, tmpy);
if constexpr (has_fusion) {
@@ -439,9 +444,9 @@ static __global__ void mul_mat_vec_f(
}
}
template<typename T, typename type_acc, int ncols_dst, int block_size, bool is_multi_token_id = false>
template<typename T, typename type_acc, int ncols_dst, int block_size, bool is_multi_token_id = false, typename T_y = float>
static void mul_mat_vec_f_switch_fusion(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const uint3 nchannels_y,
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
@@ -454,7 +459,7 @@ static void mul_mat_vec_f_switch_fusion(
fusion.x_scale != nullptr || fusion.gate_scale != nullptr;
if constexpr (ncols_dst == 1) {
if (has_fusion) {
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, true, is_multi_token_id>, launch_params,
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, true, is_multi_token_id, T_y>, launch_params,
x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst,
channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst,
sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride);
@@ -464,16 +469,16 @@ static void mul_mat_vec_f_switch_fusion(
GGML_ASSERT(!has_fusion && "fusion only supported for ncols_dst=1");
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, false, is_multi_token_id>, launch_params,
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, false, is_multi_token_id, T_y>, launch_params,
x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst,
channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst,
sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride);
}
template <typename T, typename type_acc, int ncols_dst, bool is_multi_token_id = false>
template <typename T, typename type_acc, int ncols_dst, bool is_multi_token_id = false, typename T_y = float>
void launch_mul_mat_vec_f_cuda(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const int64_t nrows,
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
@@ -565,9 +570,9 @@ void launch_mul_mat_vec_f_cuda(
}
}
template <typename T, typename type_acc>
template <typename T, typename type_acc, typename T_y>
static void mul_mat_vec_f_cuda_switch_ncols_dst(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const int64_t nrows, const int64_t ncols_dst,
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
@@ -661,9 +666,9 @@ static void mul_mat_vec_f_cuda_switch_ncols_dst(
}
}
template<typename T>
template<typename T, typename T_y>
static void mul_mat_vec_f_cuda(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const int64_t nrows, const int64_t ncols_dst,
const int64_t stride_row, const int64_t stride_col_y, const int stride_col_dst,
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
@@ -688,7 +693,9 @@ static void mul_mat_vec_f_cuda(
void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
const ggml_cuda_mm_fusion_args_host * fusion) {
GGML_ASSERT( src1->type == GGML_TYPE_F32);
// a BF16 src1 only for BF16 and FP8 weights
GGML_ASSERT( src1->type == GGML_TYPE_F32 ||
(src1->type == GGML_TYPE_BF16 && (src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3)));
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
@@ -790,12 +797,24 @@ void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor
} break;
case GGML_TYPE_BF16: {
const nv_bfloat16 * src0_d = (const nv_bfloat16 *) src0->data;
if (src1->type == GGML_TYPE_BF16) {
mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01,
stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
break;
}
mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst,
ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
} break;
case GGML_TYPE_F8_E4M3: {
const ggml_fp8_e4m3_t * src0_d = (const ggml_fp8_e4m3_t *) src0->data;
if (src1->type == GGML_TYPE_BF16) {
mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01,
stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
break;
}
mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst,
ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
@@ -866,8 +885,8 @@ void ggml_cuda_op_mul_mat_vec_f(
GGML_UNUSED_VARS(ctx, src1, dst, src1_ddq_i, src1_ncols, src1_padded_row_size);
}
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11) {
const ggml_type type = src0->type;
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id) {
const ggml_type type_src0 = src0->type;
const int64_t * src0_ne = src0->ne;
const size_t * src0_nb = src0->nb;
@@ -875,7 +894,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
return false;
}
const size_t ts = ggml_type_size(type);
const size_t ts = ggml_type_size(type_src0);
if (src0_nb[0] != ts) {
return false;
}
@@ -884,7 +903,27 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
return false;
}
switch (type) {
// MMVF reads a BF16 src1 only for BF16 and FP8 weights
if (type_src1 == GGML_TYPE_BF16 && type_src0 != GGML_TYPE_BF16 && type_src0 != GGML_TYPE_F8_E4M3) {
return false;
}
if (mul_mat_id) {
// FP8 experts on all GPUs, F32/F16/BF16 experts on AMD, and BF16 experts with a BF16 src1, which MMF can not read
// (with an F32 src1 NVIDIA takes MMF where it supports the experts, otherwise the sorted fallback)
switch (type_src0) {
case GGML_TYPE_F32:
case GGML_TYPE_F16:
case GGML_TYPE_BF16:
return ne11 <= MMVF_MAX_BATCH_SIZE && (GGML_CUDA_CC_IS_AMD(cc) || type_src1 == GGML_TYPE_BF16);
case GGML_TYPE_F8_E4M3:
return ne11 <= MMVF_MAX_BATCH_SIZE;
default:
return false;
}
}
switch (type_src0) {
case GGML_TYPE_F32:
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
if (ampere_mma_available(cc)) {
@@ -905,7 +944,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1);
// MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size
if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
if (ampere_mma_available(cc)) {
@@ -919,7 +958,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
}
return ne11 <= MMVF_MAX_BATCH_SIZE;
} else if (GGML_CUDA_CC_IS_AMD(cc)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
if (fp16_mma_hardware_available(cc)) {
@@ -938,7 +977,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1);
// MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size
if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
// MMF tiles 32 rows per block, so a matrix of few rows leaves most SMs idle while MMVF runs a block
@@ -964,7 +1003,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
}
return ne11 <= MMVF_MAX_BATCH_SIZE;
} else if (GGML_CUDA_CC_IS_AMD(cc)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
if (bf16_mma_hardware_available(cc)) {
+1 -1
View File
@@ -11,4 +11,4 @@ void ggml_cuda_op_mul_mat_vec_f(
const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols,
const int64_t src1_padded_row_size, cudaStream_t stream);
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11);
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id);
+2 -3
View File
@@ -1538,7 +1538,7 @@ static void mul_mat_vec_q_switch_type(
void ggml_cuda_mul_mat_vec_q(
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
const ggml_cuda_mm_fusion_args_host * fusion) {
GGML_ASSERT( src1->type == GGML_TYPE_F32);
GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
@@ -1557,7 +1557,6 @@ void ggml_cuda_mul_mat_vec_q(
GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE);
const float * src1_d = (const float *) src1->data;
const int32_t * ids_d = ids ? (const int32_t *) ids->data : nullptr;
float * dst_d = (float *) dst->data;
@@ -1637,7 +1636,7 @@ void ggml_cuda_mul_mat_vec_q(
const int64_t s11 = src1->nb[1] / ts_src1;
const int64_t s12 = src1->nb[2] / ts_src1;
const int64_t s13 = src1->nb[3] / ts_src1;
quantize_row_q8_1_cuda(src1_d, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream);
quantize_row_q8_1_cuda(src1->data, src1->type, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream);
}
const int64_t s01 = src0->nb[1] / ts_src0;
+113
View File
@@ -399,6 +399,54 @@ static __global__ void l2_norm_f32(
}
}
// l2_norm with an optional per-column weight before it and SCALE (+ an optional MUL by a per-channel/sample factor) after it,
// with the reduction of l2_norm_f32
template <int block_size, bool has_w, bool has_f>
static __global__ void l2_clip_f32(
const float * x, const float * w, const float * f, float * dst, const int ncols, const int nchannels, const int nsamples,
const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample,
const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample,
const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias) {
ggml_cuda_pdl_lc();
const int nrows = gridDim.x;
const int row = blockIdx.x;
const int tid = threadIdx.x;
extern __shared__ float s_sum[];
ggml_cuda_pdl_sync();
for (int sample = blockIdx.z; sample < nsamples; sample += gridDim.z) {
for (int channel = blockIdx.y; channel < nchannels; channel += gridDim.y) {
const float * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row;
const float * wc = has_w ? w + sample*w_stride_sample + channel*w_stride_channel + row*w_stride_row : nullptr;
float * dstc = dst + ((sample*nchannels + channel)*nrows + row)*ncols;
float tmp = 0.0f;
for (int col = tid; col < ncols; col += block_size) {
const float xi = has_w ? xc[col]*wc[col] : xc[col];
tmp += xi * xi;
}
tmp = block_reduce<block_reduce_method::SUM, block_size>(tmp, s_sum);
const float l2 = rsqrtf(fmaxf(tmp, eps * eps));
const float fc = has_f ? f[sample*f_stride_sample + channel*f_stride_channel] : 1.0f;
for (int col = tid; col < ncols; col += block_size) {
const float xi = has_w ? xc[col]*wc[col] : xc[col];
const float yi = scale*(l2*xi) + bias;
dstc[col] = has_f ? yi*fc : yi;
}
if constexpr (block_size > WARP_SIZE) {
__syncthreads();
}
}
}
}
template <bool do_multiply = false, bool do_add = false>
static void norm_f32_cuda(const float * x,
float * dst,
@@ -623,6 +671,71 @@ static void l2_norm_f32_cuda(
}
}
template <bool has_w, bool has_f>
static void l2_clip_f32_cuda(
const float * x, const float * w, const float * f, float * dst, const int ncols, const int nrows, const int nchannels, const int nsamples,
const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample,
const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample,
const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias, cudaStream_t stream) {
const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX));
if (ncols < 1024) {
const ggml_cuda_kernel_launch_params params(blocks_num, dim3(WARP_SIZE, 1, 1), 0, stream);
ggml_cuda_kernel_launch(l2_clip_f32<WARP_SIZE, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples,
stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample,
f_stride_channel, f_stride_sample, eps, scale, bias);
} else {
const ggml_cuda_kernel_launch_params params(blocks_num, dim3(1024, 1, 1), 32 * sizeof(float), stream);
ggml_cuda_kernel_launch(l2_clip_f32<1024, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples,
stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample,
f_stride_channel, f_stride_sample, eps, scale, bias);
}
}
void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm,
const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst) {
GGML_ASSERT(x->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && x->nb[0] == sizeof(float));
GGML_ASSERT(ggml_is_contiguous(dst) && ggml_are_same_shape(x, dst));
GGML_TENSOR_LOCALS(int64_t, ne0, x, ne);
GGML_TENSOR_LOCALS(size_t, nb0, x, nb);
// broadcast dimensions of w and f have a stride of 0
auto bcast_stride = [](const ggml_tensor * t, int dim) -> int64_t {
return t->ne[dim] == 1 ? 0 : (int64_t) (t->nb[dim]/sizeof(float));
};
const int64_t ws1 = w ? bcast_stride(w, 1) : 0;
const int64_t ws2 = w ? bcast_stride(w, 2) : 0;
const int64_t ws3 = w ? bcast_stride(w, 3) : 0;
const int64_t fs2 = f ? bcast_stride(f, 2) : 0;
const int64_t fs3 = f ? bcast_stride(f, 3) : 0;
const float * x_d = (const float *) x->data;
const float * w_d = w ? (const float *) w->data : nullptr;
const float * f_d = f ? (const float *) f->data : nullptr;
float * d_d = (float *) dst->data;
const float eps = ggml_get_op_params_f32(l2_norm, 0);
const float s = ggml_get_op_params_f32(scale, 0);
const float b = ggml_get_op_params_f32(scale, 1);
const int64_t s01 = nb01/sizeof(float);
const int64_t s02 = nb02/sizeof(float);
const int64_t s03 = nb03/sizeof(float);
cudaStream_t stream = ctx.stream();
if (w && f) {
l2_clip_f32_cuda<true, true >(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
} else if (w) {
l2_clip_f32_cuda<true, false>(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
} else if (f) {
l2_clip_f32_cuda<false, true >(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
} else {
l2_clip_f32_cuda<false, false>(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
}
}
void ggml_cuda_op_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul, ggml_tensor * add) {
const ggml_tensor * src0 = dst->src[0];
const float * src0_d = (const float *) src0->data;
+4
View File
@@ -21,3 +21,7 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx,
void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
// [MUL by w ->] L2_NORM -> SCALE [-> MUL by f], w broadcasts over the rows, f is one value per channel/sample
void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm,
const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst);
+170 -59
View File
@@ -1,6 +1,21 @@
#include "quantize.cuh"
#include "convert.cuh"
#include <cstdint>
// 4 consecutive values of x as float4, x + 4*i is aligned to 4 values
template <typename src_t>
static __device__ __forceinline__ float4 quantize_load4(const src_t * x, const int64_t i) {
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
__align__(8) nv_bfloat162 v[2];
ggml_cuda_memcpy_1<sizeof(v)>(v, x + 4*i);
const float2 lo = ggml_cuda_cast<float2>(v[0]);
const float2 hi = ggml_cuda_cast<float2>(v[1]);
return make_float4(lo.x, lo.y, hi.x, hi.y);
} else {
return ((const float4 *) x)[i];
}
}
#if defined(BLACKWELL_MMA_AVAILABLE)
// this maps to 256-bit loads in PTX on supported devices,
// and otherwise falls back to 2 128-bit loads
@@ -9,6 +24,23 @@ struct __builtin_align__(32) float8 {
float p; float q; float r; float s;
};
// 8 consecutive values of x as float8, x is aligned to 8 values
// for float it returns a reference like a direct load, a copy changes the register allocation of the kernels
template <typename src_t>
static __device__ __forceinline__ decltype(auto) quantize_load8(const src_t * x) {
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
__align__(16) nv_bfloat162 v[4];
ggml_cuda_memcpy_1<sizeof(v)>(v, x);
const float2 a = ggml_cuda_cast<float2>(v[0]);
const float2 b = ggml_cuda_cast<float2>(v[1]);
const float2 c = ggml_cuda_cast<float2>(v[2]);
const float2 d = ggml_cuda_cast<float2>(v[3]);
return float8{a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y};
} else {
return reinterpret_cast<const float8 *>(x)[0];
}
}
#if CUDART_VERSION >= 12080
static __device__ __forceinline__ float nvfp4_native_scale_error(
const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float inv_scale, const float scale) {
@@ -50,13 +82,14 @@ static __device__ __forceinline__ float nvfp4_native_scale_error(
#endif // CUDART_VERSION >= 12080
#endif // defined(BLACKWELL_MMA_AVAILABLE)
template <typename src_t>
__launch_bounds__(CUDA_QUANTIZE_BLOCK_SIZE, 1)
static __global__ void quantize_q8_1(
const float * x_ptr, void * vy_ptr,
const src_t * x_ptr, void * vy_ptr,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const uint32_t ne1, const uint3 ne2) {
ggml_cuda_pdl_lc();
const float * GGML_CUDA_RESTRICT x = x_ptr;
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
void * GGML_CUDA_RESTRICT vy = vy_ptr;
const int64_t i0 = (int64_t)blockDim.x*blockIdx.x + threadIdx.x;
@@ -81,7 +114,7 @@ static __global__ void quantize_q8_1(
const int64_t iqs = i_cont % QK8_1; // quant index
ggml_cuda_pdl_sync();
const float xi = i0 < ne00 ? x[i03*s03 + i02*s02 + i01*s01 + i00] : 0.0f;
const float xi = i0 < ne00 ? ggml_cuda_cast<float>(x[i03*s03 + i02*s02 + i01*s01 + i00]) : 0.0f;
float amax = fabsf(xi);
amax = warp_reduce_max<QK8_1>(amax);
@@ -124,9 +157,9 @@ __device__ __forceinline__ uint8_t compute_e8m0_scale(float amax) {
}
// scatter: grid over tokens, quantize once, write to all the token's compact rows
template <bool scatter, bool use_aligned_float8>
template <typename src_t, bool scatter, bool use_aligned_float8>
static __global__ void quantize_mmq_nvfp4(
const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int n_expert_used) {
#if defined(BLACKWELL_MMA_AVAILABLE)
@@ -140,13 +173,12 @@ static __global__ void quantize_mmq_nvfp4(
const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x;
base_idx = i3 * s03 + i2 * s02 + i01 * s01;
}
const float * __restrict__ x_row = x + base_idx;
const src_t * __restrict__ x_row = x + base_idx;
float amax = 0.0f;
if constexpr (use_aligned_float8) {
for (int64_t i0 = 8 * threadIdx.x; i0 < ne00; i0 += 8 * blockDim.x) {
const float * x_base = x_row + i0;
const float8 v = reinterpret_cast<const float8 *>(x_base)[0];
const float8 v = quantize_load8(x_row + i0);
amax = fmaxf(amax, fabsf(v.x));
amax = fmaxf(amax, fabsf(v.y));
amax = fmaxf(amax, fabsf(v.z));
@@ -158,7 +190,7 @@ static __global__ void quantize_mmq_nvfp4(
}
} else {
for (int64_t i0 = threadIdx.x; i0 < ne00; i0 += blockDim.x) {
amax = fmaxf(amax, fabsf(x_row[i0]));
amax = fmaxf(amax, fabsf(ggml_cuda_cast<float>(x_row[i0])));
}
}
@@ -204,9 +236,9 @@ static __global__ void quantize_mmq_nvfp4(
float vals[QK_NVFP4_SUB];
if constexpr (use_aligned_float8) {
const float * x_base = x_row + i0_base;
const float8 v0 = i0_base + 7 < ne00 ? reinterpret_cast<const float8 *>(x_base)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const float8 v1 = i0_base + 15 < ne00 ? reinterpret_cast<const float8 *>(x_base + 8)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const src_t * x_base = x_row + i0_base;
const float8 v0 = i0_base + 7 < ne00 ? quantize_load8(x_base) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const float8 v1 = i0_base + 15 < ne00 ? quantize_load8(x_base + 8) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
vals[0] = v0.x; vals[1] = v0.y; vals[2] = v0.z; vals[3] = v0.w;
vals[4] = v0.p; vals[5] = v0.q; vals[6] = v0.r; vals[7] = v0.s;
vals[8] = v1.x; vals[9] = v1.y; vals[10] = v1.z; vals[11] = v1.w;
@@ -215,7 +247,7 @@ static __global__ void quantize_mmq_nvfp4(
#pragma unroll
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
const int64_t i00 = i0_base + k;
vals[k] = i00 < ne00 ? x_row[i00] : 0.0f;
vals[k] = i00 < ne00 ? ggml_cuda_cast<float>(x_row[i00]) : 0.0f;
}
}
@@ -333,8 +365,8 @@ static __global__ void quantize_mmq_nvfp4(
// quantize values in the format mxfp4 is stored which is interleaved nibbles
// i.e. a block a0-a31 is represented as a0a16,a1a17 ...a15a31
// scatter: grid over tokens, quantize once, write to all the token's compact rows
template <bool scatter>
static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
template <typename src_t, bool scatter>
static __global__ void quantize_mmq_mxfp4(const src_t * __restrict__ x,
const int32_t * __restrict__ ids,
void * __restrict__ vy,
const int64_t ne00,
@@ -384,7 +416,7 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
#pragma unroll
for (int b = 0; b < 2; ++b) {
const int64_t i0 = warp_start_offset + b * vals_per_scale + lane_id_32;
const float xi = (i0 < ne00) ? x[base_pos + i0] : 0.0f;
const float xi = (i0 < ne00) ? ggml_cuda_cast<float>(x[base_pos + i0]) : 0.0f;
float amax = fabsf(xi);
#pragma unroll
@@ -453,9 +485,9 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
}
// scatter: grid over tokens, quantize once, write to all the token's compact rows
template <mmq_q8_1_ds_layout ds_layout, bool scatter>
template <typename src_t, mmq_q8_1_ds_layout ds_layout, bool scatter>
static __global__ void quantize_mmq_q8_1(
const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int ne1, const int ne2, const int n_expert_used) {
@@ -481,14 +513,13 @@ static __global__ void quantize_mmq_q8_1(
base_idx = i3*s03 + i2*s02 + i01*s01;
}
const float4 * x4 = (const float4 *) x;
block_q8_1_mmq * y = (block_q8_1_mmq *) vy;
const int64_t k_block = i0 / QK8_1_MMQ; // column block in the channel
const int64_t iqs = i0 % QK8_1_MMQ; // quant index in block
// Load 4 floats per thread and calculate max. abs. value between them:
const float4 xi = i0 < ne00 ? x4[(base_idx + i00)/4] : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
const float4 xi = i0 < ne00 ? quantize_load4(x, (base_idx + i00)/4) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
float amax = fabsf(xi.x);
amax = fmaxf(amax, fabsf(xi.y));
amax = fmaxf(amax, fabsf(xi.z));
@@ -556,8 +587,20 @@ static __global__ void quantize_mmq_q8_1(
GGML_UNUSED(n_expert_used);
}
void quantize_row_q8_1_cuda(
const float * x, void * vy,
// calls launch with x as const float * or const nv_bfloat16 *, the src1 types that the quantize kernels read
template <typename F>
static void quantize_launch_typed(const void * x, const ggml_type type_src1, const F & launch) {
if (type_src1 == GGML_TYPE_BF16) {
launch((const nv_bfloat16 *) x);
} else {
GGML_ASSERT(type_src1 == GGML_TYPE_F32);
launch((const float *) x);
}
}
template <typename src_t>
static void quantize_row_q8_1_cuda(
const src_t * x, void * vy,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(ne0 % QK8_1 == 0);
@@ -568,11 +611,21 @@ void quantize_row_q8_1_cuda(
const dim3 num_blocks(block_num_x, ne1, ne2*ne3);
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE, 1, 1);
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
ggml_cuda_kernel_launch(quantize_q8_1, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
ggml_cuda_kernel_launch(quantize_q8_1<src_t>, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
}
void quantize_mmq_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
void quantize_row_q8_1_cuda(
const void * x, const ggml_type type_src1, void * vy,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_row_q8_1_cuda(x_t, vy, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
});
}
template <typename src_t>
static void quantize_mmq_q8_1_cuda(
const src_t * x, const int32_t * ids, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(ne00 % 4 == 0);
@@ -584,15 +637,15 @@ void quantize_mmq_q8_1_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
switch (mmq_get_q8_1_ds_layout(type_src0)) {
case MMQ_Q8_1_DS_LAYOUT_D4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, false>
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, false>
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, false>
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, false>
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
break;
case MMQ_Q8_1_DS_LAYOUT_D2S6:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, false>
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D2S6, false>
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
break;
default:
@@ -600,6 +653,15 @@ void quantize_mmq_q8_1_cuda(
}
}
void quantize_mmq_q8_1_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_q8_1_cuda(x_t, ids, vy, type_src0, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
});
}
// Stores the 4 values xi of a thread, values [iu, iu + 4) of column g in a unit of 256 values, in the column group yg of the unit, see quantize.cuh for the layout.
template <mmq_q8_1_ds_layout ds_layout>
static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, int4 * yg, const int iu, const int g) {
@@ -635,12 +697,12 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
}
// Each thread quantizes 4 values of one column, see quantize.cuh for the layout.
template <mmq_q8_1_ds_layout ds_layout>
template <typename src_t, mmq_q8_1_ds_layout ds_layout>
static __global__ void quantize_mmq_few_q8_1(
const float * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const src_t * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int ne1, const int ne2) {
ggml_cuda_pdl_lc();
const float * GGML_CUDA_RESTRICT x = x_ptr;
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr;
const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4;
@@ -651,7 +713,7 @@ static __global__ void quantize_mmq_few_q8_1(
const int64_t i2 = blockIdx.z % ne2;
const int64_t i3 = blockIdx.z / ne2;
const float4 xi = (int) blockIdx.x < ne1 ? *(const float4 *) (x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
const float4 xi = (int) blockIdx.x < ne1 ? quantize_load4(x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0, 0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
const int g = blockIdx.x % MMQ_FEW_NCOLS; // column in group
int4 * yg = vy + ((blockIdx.z*(ne00/QK_K) + i0/QK_K)*(gridDim.x/MMQ_FEW_NCOLS) + blockIdx.x/MMQ_FEW_NCOLS)*MMQ_FEW_Q8_1_INT4;
@@ -660,9 +722,9 @@ static __global__ void quantize_mmq_few_q8_1(
// MUL_MAT_ID: block x is the (token, slot) entry, ids are as in mm_ids_helper. Each block finds the pair of its entry in shared memory, block (0, 0) also writes all pairs.
// Entry rank r = number of earlier tokens with the same expert, pair = first pair of the expert + r/MMQ_FEW_NCOLS, column = r % MMQ_FEW_NCOLS.
template <mmq_q8_1_ds_layout ds_layout>
template <typename src_t, mmq_q8_1_ds_layout ds_layout>
static __global__ void quantize_mmq_few_id_q8_1(
const float * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
const src_t * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
const int ne11, const int n_experts, const int n_expert_used, const int64_t si1, const int npairs_max) {
// per expert: bit t set if token t uses it and the index of its first pair; then the total number of pairs
extern __shared__ unsigned int data_mmq_few_id[];
@@ -671,7 +733,7 @@ static __global__ void quantize_mmq_few_id_q8_1(
int & npairs = pair0[n_experts];
ggml_cuda_pdl_lc();
const float * GGML_CUDA_RESTRICT x = x_ptr;
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr;
ggml_cuda_pdl_sync();
@@ -741,15 +803,16 @@ static __global__ void quantize_mmq_few_id_q8_1(
}
const int it = blockIdx.x / n_expert_used;
const int is = blockIdx.x % n_expert_used;
const float4 xi = *(const float4 *) (x + it*s12 + (is % ne11)*s11 + i0);
const float4 xi = quantize_load4(x + it*s12 + (is % ne11)*s11 + i0, 0);
const int r = rank(blockIdx.x, e);
int4 * yg = vy + (int64_t(pair0[e] + r/MMQ_FEW_NCOLS)*(ne00/QK_K) + i0/QK_K)*MMQ_FEW_Q8_1_INT4;
quantize_mmq_few_store<ds_layout>(xi, yg, i0 % QK_K, r % MMQ_FEW_NCOLS);
}
void quantize_mmq_few_q8_1_cuda(
const float * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
template <typename src_t>
static void quantize_mmq_few_q8_1_cuda(
const src_t * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(ne00 % QK_K == 0);
@@ -759,11 +822,11 @@ void quantize_mmq_few_q8_1_cuda(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
switch (ds_layout) {
case MMQ_Q8_1_DS_LAYOUT_D4:
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
break;
default:
@@ -771,8 +834,17 @@ void quantize_mmq_few_q8_1_cuda(
}
}
void quantize_mmq_few_id_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
void quantize_mmq_few_q8_1_cuda(
const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_few_q8_1_cuda(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
});
}
template <typename src_t>
static void quantize_mmq_few_id_q8_1_cuda(
const src_t * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
GGML_ASSERT(ne00 % QK_K == 0);
GGML_ASSERT(n_tokens <= 32); // one bit per token
@@ -785,11 +857,11 @@ void quantize_mmq_few_id_q8_1_cuda(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, nbytes_shared, stream);
switch (ds_layout) {
case MMQ_Q8_1_DS_LAYOUT_D4:
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
break;
default:
@@ -797,9 +869,18 @@ void quantize_mmq_few_id_q8_1_cuda(
}
}
void quantize_mmq_few_id_q8_1_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_few_id_q8_1_cuda(x_t, ids, vy, pairs, ds_layout, ne00, s11, s12, ne11, n_experts, n_expert_used, n_tokens, si1, npairs_max, stream);
});
}
// scatter=true reuses the quant kernel: grid over tokens, ids = inverse map (token slot -> compact row)
void quantize_scatter_mmq_q8_1_cuda(
const float * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
template <typename src_t>
static void quantize_scatter_mmq_q8_1_cuda(
const src_t * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
GGML_ASSERT(ne00 % 4 == 0);
@@ -810,15 +891,15 @@ void quantize_scatter_mmq_q8_1_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
switch (mmq_get_q8_1_ds_layout(type_src0)) {
case MMQ_Q8_1_DS_LAYOUT_D4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
break;
case MMQ_Q8_1_DS_LAYOUT_D2S6:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
break;
default:
@@ -826,9 +907,19 @@ void quantize_scatter_mmq_q8_1_cuda(
}
}
void quantize_scatter_mmq_q8_1_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_scatter_mmq_q8_1_cuda(x_t, ids_src1_inv, vy, type_src0, ne00, stride_token, ne0, n_tokens, nrows_dst, n_expert_used, stream);
});
}
// scatter=true reuses the quant kernels: grid over tokens, ids = inverse map (token slot -> compact row)
void quantize_scatter_mmq_fp4_cuda(
const float * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
template <typename src_t>
static void quantize_scatter_mmq_fp4_cuda(
const src_t * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
GGML_ASSERT(ne0 > 0);
@@ -838,10 +929,10 @@ void quantize_scatter_mmq_fp4_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
const dim3 num_blocks(n_tokens, 1, 1);
if (use_aligned_float8) {
quantize_mmq_nvfp4<true, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, true, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
} else {
quantize_mmq_nvfp4<true, false><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, true, false><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
}
} else {
@@ -851,13 +942,24 @@ void quantize_scatter_mmq_fp4_cuda(
const int64_t block_num_y = (ne0 + vals_per_block - 1) / vals_per_block;
const dim3 block_size(WARP_SIZE, nwarps, 1);
const dim3 num_blocks(n_tokens, block_num_y, 1);
quantize_mmq_mxfp4<true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_mxfp4<src_t, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
}
}
void quantize_mmq_fp4_cuda(
const float * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
void quantize_scatter_mmq_fp4_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0,
const bool use_aligned_float8, const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_scatter_mmq_fp4_cuda(x_t, ids_src1_inv, vy, scale, type_src0, use_aligned_float8, ne00, stride_token, ne0,
n_tokens, nrows_dst, n_expert_used, stream);
});
}
template <typename src_t>
static void quantize_mmq_fp4_cuda(
const src_t * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(type_src0 == GGML_TYPE_MXFP4 || type_src0 == GGML_TYPE_NVFP4);
@@ -869,10 +971,10 @@ void quantize_mmq_fp4_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
const dim3 num_blocks(ne1, ne2 * ne3, 1);
if (use_aligned_float8) {
quantize_mmq_nvfp4<false, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, false, true><<<num_blocks, block_size, 0, stream>>>(
x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
} else {
quantize_mmq_nvfp4<false, false><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, false, false><<<num_blocks, block_size, 0, stream>>>(
x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
}
} else {
@@ -886,6 +988,15 @@ void quantize_mmq_fp4_cuda(
const dim3 num_blocks(ne1, block_num_y, ne2 * ne3);
const dim3 block_size(WARP_SIZE, nwarps, 1);
quantize_mmq_mxfp4<false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
quantize_mmq_mxfp4<src_t, false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
}
}
void quantize_mmq_fp4_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0,
const bool use_aligned_float8, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_fp4_cuda(x_t, ids, vy, scale, type_src0, use_aligned_float8, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
});
}
+12 -7
View File
@@ -11,13 +11,15 @@
static_assert(MATRIX_ROW_PADDING % CUDA_QUANTIZE_BLOCK_SIZE == 0, "Risk of out-of-bounds access.");
static_assert(MATRIX_ROW_PADDING % (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ) == 0, "Risk of out-of-bounds access.");
// x holds the src1 values, type_src1 is GGML_TYPE_F32 or GGML_TYPE_BF16
void quantize_row_q8_1_cuda(
const float * x, void * vy,
const void * x, ggml_type type_src1, void * vy,
int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
void quantize_mmq_q8_1_cuda(
const float * x, const int32_t * ids, void * vy,
const void * x, ggml_type type_src1, const int32_t * ids, void * vy,
ggml_type type_src0, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
@@ -29,7 +31,7 @@ static constexpr int MMQ_FEW_NCOLS = 8; // src1 columns per column group
static constexpr int MMQ_FEW_Q8_1_INT4 = 4*WARP_SIZE + 4*4; // int4 per 256 values and column group
void quantize_mmq_few_q8_1_cuda(
const float * x, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
const void * x, ggml_type type_src1, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
// MUL_MAT_ID: a pair is an expert and one column group of up to MMQ_FEW_NCOLS of its (token, slot) entries. The src1 of pair p is channel p above, its columns past the entries are not written.
@@ -37,10 +39,11 @@ void quantize_mmq_few_q8_1_cuda(
static constexpr int MMQ_FEW_PAIR_INTS = 2 + MMQ_FEW_NCOLS;
void quantize_mmq_few_id_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
const void * x, ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
int64_t ne11, int64_t n_experts, int64_t n_expert_used, int64_t n_tokens, int64_t si1, int64_t npairs_max, cudaStream_t stream);
void quantize_mmq_fp4_cuda(const float * x,
void quantize_mmq_fp4_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids,
void * vy,
float * scale,
@@ -57,7 +60,8 @@ void quantize_mmq_fp4_cuda(const float * x,
cudaStream_t stream);
// quantize each token once and scatter the block to its compact rows (via the inverse map)
void quantize_scatter_mmq_fp4_cuda(const float * x,
void quantize_scatter_mmq_fp4_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids_src1_inv,
void * vy,
float * scale,
@@ -71,7 +75,8 @@ void quantize_scatter_mmq_fp4_cuda(const float * x,
int n_expert_used,
cudaStream_t stream);
void quantize_scatter_mmq_q8_1_cuda(const float * x,
void quantize_scatter_mmq_q8_1_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids_src1_inv,
void * vy,
ggml_type type_src0,
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 16);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 1, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 1, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 1, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 1, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 1, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 1, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 1, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 1, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 1);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 4);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 1);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 16);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 64, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 64, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 64, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 64, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 64, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 64, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 64, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 64, 1);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 1);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 8, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(320, 256);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(40, 40);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(512, 512);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(576, 512);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(64, 64);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(72, 72);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(80, 80);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(96, 96);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16);

Some files were not shown because too many files have changed in this diff Show More