Compare commits

...
Author SHA1 Message Date
Pascal 7778397892 server: run tool commands as a job ended with everything it started (#33367)
run_subprocess read the output until EOF and the timeout only killed
the shell, so a process the command left running kept the pipe open
and the call with it.

The command now runs as a job: a process group of its own on POSIX
(posix_spawn), a Job Object on Windows (created suspended, then
assigned). The output is polled against a deadline, and the whole job
is killed once the command exits, times out, or the caller stops it.

tools_io::run takes a should_stop, checked even while the command
writes nothing, so dropping a /tools request stops its command.

On Windows, cmd gets /d /s /c and the command as written, since it
does not parse its command line with the C runtime rules.
2026-11-30 16:09:01 +01:00
Jeff Bolz 8d0323c856 vulkan: handle ADD_ID with more tokens than maxComputeWorkGroupCount[1] (#33232)
Clamp the workgroup count and loop in the shader. The failing test was
added in #33162.
2026-11-30 15:40:16 +01:00
Max Krasnyansky c2d2fc6a10 hexagon: add support for online FWHT-32 and Quant Scales (#33347)
* hexagon : add online FWHT-32 rotation for HMX W8A8 matmul

* hexagon : add quant scale tensor support and fuse weight scales into matmul

* hexagon : add support for F8_E4M3

* hexagon : fuse rms_norm into mul_mat

* hexagon : split matmul-ops.c into separate HMX-F16, HMX-W8A8, and HVX files

* hexagon : refactor fusion, lowering, and kparams solver
2026-11-30 06:23:29 -08:00
Clemens Wasser 9bb00f98c4 sycl : fix batched f16 mul_mat with broadcast batches and strided src1 (#33214)
* sycl : fix oneDNN batched matmul with broadcast batches

* sycl : keep src1 strides of batched f16 mul_mat in oneDNN builds
2026-11-30 16:20:18 +02:00
Jeff Bolz 3e23348afe vulkan: improve CONV_2D/3D performance (#32629)
* tests: add conv2d/conv3d cases from diffusion models

I asked Claude to add more representative perf tests, to optimize against

Assisted-by: Claude Opus 5.5

* vulkan: Avoid private variables in coopmat2 callbacks

There's a compiler bug where these can spill to local memory, making the
coopmat2 shader slower than coopmat1.

Assisted-by: Claude Opus 5.5

* vulkan: split_k for conv_2d

#29929 added split_k for conv_3d, at the time I didn't see much benefit to
doing the same for conv_2d, but with additional test cases this helps, and
it also interacts well with the upcoming halo optimization

Assisted-by: Claude Opus 5.5

* vulkan: Add conv_2d/3d "halo" shader

This shader copies the input region corresponding to the output region (plus
the "halo") once into shared memory, rather than for each filter tap.

Assisted-by: Claude Opus 5.5

* vulkan: don't waste accumulator space on discarded halo elements

All elements of the result accumulator now correspond to real work in
the output tile, where in the previous commit the accumulator had "halo"
elements that did wasted work and were discarded during store.

Claude's description:
Each accumulator fragment covers 16 (or 8) pixels of one tile row, and its
B matrix is that box row shifted by the tap. Box rows no longer need padding
and no multiplies are spent on the border columns. Tiles are 256 pixels
where the output allows, otherwise the shape with the least padded area
weighted by its cost per output. 8-pixel fragments use 16x8x16 cooperative
matrices when the device has them. The header comment describes the new
layout.

RTX 5090: SD1.5 64x64 320->320 1.81x, 3D Wan 130x130x3 384 1.41x,
3D 106x154x6 96->96 1.34x; CONV_2D +6%, CONV_3D +11%.

Assisted-by: Claude Opus 5.5

* vulkan: Enable split_k for the conv_halo shader

The reduction logic is still shared with conv2d_mm and mul_mat
(mul_mat_split_k_reduce).

RTX 5090: SD1.5 8x8 1280->1280 2.71x, 16x16 1280->1280 1.63x, 32x32
640->640 1.61x, SDXL 32x32 2560->1280 1.61x; CONV_2D +13%, CONV_3D +3%.

Assisted-by: Claude Opus 5.5

* vulkan: Tweak the conv shader selection heuristic to use halo more often

Claude's summary:
- Small 2D layers that read the filter in place, and have enough passes to
  split, use 32 output channels per workgroup before splitting the passes:
  twice the workgroups, without split-K's partial outputs and reduce. (With
  the filter copy, and for 1x1 filters, this was slower.)
- 3D layers with fewer than 4K outputs use the halo shader instead of
  conv3d_mm, despite the filter copy.
- Layers with 16 to 48 input channels use it instead of conv2d_mm; the
  limit of 64 predates split-K and the row-aligned tiles.

RTX 5090: SD1.5 8x8 1280->1280 1.35x, VAE 128x128 16->512 1.47x,
1536x1536 32->64 1.28x, 3D 28x40x3 384->384 1.64x, 1024->1024 1.37x;
CONV_2D +6%, CONV_3D +4%.

Assisted-by: Claude Opus 5.5

* vulkan: Tweak tile selection and workgroup traversal order

Claude's summary:

- 56x4 tiles (8-pixel fragments) for outputs 49 to 56 wide, so 52-wide
  layers pad to 56 instead of 64; tiles of 192 pixels or more now cost the
  same as 256. Skipped on layers with too few workgroups to fill half the
  GPU.
- All output channels in one workgroup when 64 < Cout <= 128 and Cout is
  not a multiple of 64 (96 no longer pads to 128), on tiles of up to 128
  pixels. The tile choice now counts output channel padding.
- 3D tiles numbered with the output depth slices fastest, so workgroups of
  neighboring output slices run together and share their input slices in
  L2.

Adds CONV_2D/CONV_3D tests for 56x4 tiles and Cout 80, 96 and 112.

RTX 5090: 3D Wan 480p 96->96 482x834x6 1.18x, 96->96 154x106x6 1.15x,
1280->1280 76x52x8 1.13x, 320->1280 76x52x8 1.12x, Wan 480p 192
242x418x6 1.05x; geomean +2% over all the CONV perf cases (RTX 4070 +3%).

Assisted-by: Claude Opus 5.5

* trim comments
2026-11-30 15:00:25 +01:00
Nakul Lagwal 0f72a8695a jinja : fix negative string indexing (#33370)
* jinja : fix negative string indexing

* jinja : avoid redundant casts in negative index path
2026-11-30 14:36:42 +01:00
Xuan-Son Nguyen 81a22ceb7b webgpu: mat-vec workgroup size by row length (#33308) 2026-11-30 12:53:08 +01:00
Xuan-Son Nguyen a346a49f88 model: add get_yarn_attn_factor (#33314)
* model: add get_yarn_attn_factor

* nits

Assisted-by: Kimi K3.1 Pro

* deepseek2 : drop constant YaRN warning

Assisted-by: Kimi K3.1 Pro
2026-11-30 12:50:02 +01:00
patricksamuelevans 2924a0e26b common : fix Qwen3-ASR transcription context placement (#33075) (#33135)
Route the transcription prompt into the system turn so the user turn stays audio only. Add regression coverage for the message layout and language handling.

Assisted-by: OpenCode Hy4 flash Free
2026-11-30 12:03:08 +01:00
Túlio Ribeiro dos Anjos 808d1fed52 bert : support Sentence Transformers dense output projections (#33280)
* feat(bert): add dense projection support

Assisted-by: Codex

* feat(convert): support BERT dense projection export

Assisted-by: Codex

* fix(bert): remove unnecessary token-type cast

Assisted-by: Codex
2026-11-30 11:21:19 +01:00
Nakul Lagwal 89bfabaf81 jinja : fix replace filter with count=0 (#33319)
[no ci]
2026-11-30 11:21:03 +01:00
Alessandro de Oliveira Faria (A.K.A.CABELO) f6621d0ad3 vendor : update stb-image-2.34 (#33337)
[no ci]
2026-11-30 11:13:13 +01:00
Pascal 9fde456d34 metal : one thread per row for soft_max and sum_rows on short rows (#33189)
A row of at most 8 columns got a whole threadgroup, and sum_rows on
rows of 4 ran one thread per threadgroup. Each thread now handles a
whole row. On 3.4M rows of 4 on an M5 Max, soft_max goes from 2725
to 198 us, sum_rows from 2355 to 110 us and mean from 2352 to 109 us.
2026-11-30 12:03:35 +02:00
Georgi Gerganov aa631e031e ggml : clean up FA bias API (#33178)
* ggml : validate indexed bias at op construction only

The indexed-bias check already runs in ggml_flash_attn_ext_add_indexed_bias(), so the backend checks were redundant. Make the validator static in ggml.c, drop the ggml-impl.h declaration, and remove the CPU supports_op case, the CPU compute assert, and the CUDA kernel-selection check.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : rename FA indexed bias to bias_indexed

Add internal ggml_flash_attn_ext_has_bias() and ggml_flash_attn_ext_bias_is_indexed() helpers and derive the bias state from src[6]/src[7] instead of op_params[5]. Rename ggml_flash_attn_ext_add_indexed_bias() to ggml_flash_attn_ext_add_bias_indexed() and keep the old public names as deprecated wrappers.

Rename the remaining indexed_bias identifiers to bias_indexed, including the CUDA kernel templates and the HIP metrics script. Reject non-indexed bias in the CPU, CUDA and Vulkan backends; backends without bias support reject any bias.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : rename FA indexed bias validator

Name the static validator after the function it validates: ggml_flash_attn_ext_add_bias_indexed_validate().

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : keep src order in FA bias validation

Reorder the src tensor declarations in the indexed-bias validator to follow the src index order.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : mark FA bias wrappers as deprecated

Add the deprecated marker above the old indexed-bias wrapper implementations.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : generalize FA bias API

Rename ggml_flash_attn_ext_add_bias_indexed() to ggml_flash_attn_ext_add_bias() and rename its arguments to bias and bias_idxs. When bias_idxs is NULL, the bias is validated as a dense K*Q tensor with shape [n_kv, n_batch, n_head_kv, n_stream]; otherwise it remains an indexed bias table.

Update the deprecated wrapper to stay indexed-only, and align the table/indices naming in llama-graph, CPU, CUDA, Vulkan and the tests.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : move FA bias args after kv_rows

Reorder the bias and bias_idxs arguments of build_attn_mha() to follow kv_rows, and update all call sites.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : deduplicate FA kq_b and bias

Remove the kq_b argument from build_attn_mha() and build_attn_iswa_impl() and pass the dense KQ bias through bias with bias_idxs == nullptr. The FA path now rejects a dense bias and adds an indexed bias without backend checks. The non-FA path adds a dense bias directly to kq.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : inline dense bias mask

Inline the dense_bias_mask lambda into the non-FA path, now its only use.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : add FA bias to mask in non-FA path

Add both indexed and dense FA biases to the mask in the non-FA path so they are scaled by the ALiBi slope, matching the FA path. Remove the kq-side addition for dense bias.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : remove redundant non-FA mask cast

The non-FA path already implies soft_max_ext can consume an F32 mask, so drop the cparams.flash_attn check and the F16 cast.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : cast FA bias to mask type

Compute the non-FA bias in F32 and cast it to the mask type before adding, instead of casting the mask to F32.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : remove FA bias TODO

Remove the TODO after confirming that adding the bias to the mask is correct.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : guard FA dense bias in validation

Add a CPU compute assert for the indexed-bias assumption, reject the dense bias in ggml_flash_attn_ext_add_bias_validate with a TODO, and update the backend comments to say bias.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : document FA bias scaling

Note that the bias is added after the KQ scaling.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : rename FA add sinks/bias to set

Rename ggml_flash_attn_ext_add_sinks to set_sinks and deprecate the old name. Rename ggml_flash_attn_ext_add_bias to set_bias. Allow set_sinks to override existing sinks.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* llama : set FA bias unconditionally

Call ggml_flash_attn_ext_set_bias() unconditionally and move it before ggml_flash_attn_ext_set_sinks().

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml-cuda : fix sparse bias template names

Rename the remaining indexed_bias references in the sparse FA code added by master.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
2026-11-30 09:39:56 +02:00
cwriterandcwriter bf062c6018 sycl: convert f32 to f8_e4m3 without frexpf in device code (#33035)
Co-authored-by: cwriter <cwriter@localhost>
2026-11-30 01:47:53 -05:00
ravel7524andJeff Bolz 2f94007cc1 vulkan: fold verify tokens and GQA heads into one flash-attention row tile (#30190)
* vulkan: fold verify tokens and GQA heads into one flash-attention row tile

* vulkan: enable shape-gated query-token folding

* vulkan: port folding to CM2 fa shader

* Update scaling of accumulator in flash_attn.comp

* Enhance ggml_vk_flash_attn function with scalar shared memory support and add new VARS_TO_STR macros for extended variable representation in tests

* tests : remove .DS_Store

* Update test cases in test-backend-ops.cpp

Refactor test cases for GQA with query tokens and folded tiles.

* Removed Whitespace

---------

Co-authored-by: Jeff Bolz <jbolz@nvidia.com>
2026-11-30 07:08:15 +01:00
Anthony N 57d0c6217c metal : avoid a second pipeline cache lookup (#32977)
Assisted-by: Claude Opus 5.5
Assisted-by: Codex
2026-11-30 08:03:51 +02:00
Mark Cockram 9a278b02b8 server : include timings in Anthropic /v1/messages responses (#30244)
Add the timings object to the non-streaming response and to the final
message_delta event of the stream, as the OpenAI chat and Responses
paths already do. Clients such as llama-swap read prompt and generation
speed from it and otherwise report -1 for /v1/messages requests.

Update test_compat_anthropic.py to expect timings there; message_stop
still carries none.
2026-11-30 02:31:01 +01:00
Evan Huus 9fcc40d3d4 common : share the kv arg parser with llama-bench (#32831)
Assisted-by: Codex
2026-11-30 01:31:06 +01:00
Aldehir Rojas 57577675aa server : pass in --json-schema to chat parsing (#31862)
* server : apply --json-schema through the chat template

* server : update comment

* cont : move field
2026-11-30 00:29:32 +01:00
thelittlefireman bb5aacd61d ggml-cuda: Add GCN HIP sparse fattn (#30370)
Assisted-by: ChatGPT
2026-11-30 00:02:48 +01:00
George Burton f6d944f6d5 mtmd: fix qwen3omni deepstack allow audio and video (#33041)
* fix: qwen3omni deepstack allow audio and video

* fix: mmproj audio broken/zero-width audio gets its own error line
2026-11-29 19:54:32 +01:00
Zuhal Karadavut 6c83d2ea39 convert : warn when per-channel FP8 weights are dequantized (#33312)
Assisted-by: Claude Code (Claude Opus 5.5)
2026-11-29 19:36:44 +01:00
Francisco Javier 84250b88ee hip: fix CU_CHECK macro shadowing causing infinite loop with VMM (#33227)
* hip: fix CU_CHECK macro shadowing causing infinite loop with VMM

* hip: fix CU_CHECK macro to prevent infinite loop
2026-11-29 19:19:13 +01:00
Alessandro de Oliveira Faria (A.K.A.CABELO) 5a18afaf7c vendor : update cpp-httplib-0.69.0 (#33310)
[no ci]
2026-11-29 19:18:41 +01:00
cyxu0401andxuchengyang e18d1b2150 models : add MiniCPM5 MoE support (#32644)
* models: add MiniCPM5 MoE support

Assisted-by: Codex
(cherry picked from commit 7f63c7e3e3258dd3c769c7cc9dfa03ae9a23a1f4)

* docs: clarify MiniCPM5 MoE DSpark startup options

Assisted-by: Codex

* models: preserve MiniCPM5 MoE HF BOS setting

* convert: use the released MiniCPM5 MoE tokenizer settings

Assisted-by: Codex

* tests: remove MiniCPM5 MoE conversion tests

Assisted-by: Codex

* models: address MiniCPM5 MoE converter and graph review

Assisted-by: Codex

* models: default unset MiniCPM5 MoE gating to sigmoid

Assisted-by: Codex

* tests: update the MiniCPM5 MoE Metal fusion baseline

Drop the model and speculative decoding documentation changes from this PR.

Assisted-by: Codex

---------

Co-authored-by: xuchengyang <xuchengyang@modelbest.cn>
2026-11-29 18:38:42 +01:00
Xuan-Son Nguyen 63e22e63bc webgpu: speed up prefill for flash_attn (#33192) 2026-11-29 17:46:09 +01:00
Pascal b80ec40d09 webgpu: apply the weight scale of MUL_MAT and MUL_MAT_ID (#33266)
* webgpu : apply the weight scale of MUL_MAT and MUL_MAT_ID

Since #28898 a MUL_MAT or MUL_MAT_ID that carries a weight scale is
rejected by supports_op, so scaled weights (NVFP4 experts, the Q8_0
experts of Gemma 4) are placed in host memory and run on the CPU.

Apply the scale after the product with a small epilogue kernel, as the
Metal backend does: per tensor, per output channel, per expert or per
output channel of each expert, the expert of a MUL_MAT_ID row read from
ids and skipped slots left untouched. Activation scales are ignored, as
on CPU and Metal.

* webgpu : accumulate MUL_MAT_ID tiles in f32 like MUL_MAT

The tiled MUL_MAT_ID kernel accumulated its products in f16. NVFP4
weights are stored at a magnitude that the weight scale brings back
down, so on real checkpoints such as Inkling 2 Mini the unscaled sums
exceed the f16 range and the output turns into inf.

Accumulate in f32 as the tiled MUL_MAT kernel already does, keeping
the f16 shared memory tiles.
2026-11-29 14:01:00 +01:00
Niklas Wenzel db1165480c gemma4 : fix 12B model size label (#33275) 2026-11-29 10:39:00 +01:00
Ed Addario 918fe468db Honor --chunks when using llama-perplexity with --kl-divergence (#32257)
* Honour --chunks when using --kl-divergence
* Fix formatting
2026-11-28 23:03:31 +01:00
IsNot a43d06ef90 unicode : speed up tokenization (#33164)
* unicode : speed up tokenization

* unicode : remove always-true asserts, pass byte_encode explicitly in test

* unicode : remove always-true asserts, pass byte_encode explicitly in test
2026-11-28 22:28:55 +01:00
Alessandro de Oliveira Faria (A.K.A.CABELO) cbb7652cd3 vendor : update cpp-httplib-0.68.0 (#33259)
[no ci]
2026-11-28 22:28:39 +01:00
Georgi GerganovandNiklas Wenzel 115deee8ec metal : keep ADD chain fusion independent of batch size (#33217)
The ADD chain fusion packs the addends only when they share a layout and a backend buffer. A bias add and a residual add share a layout only for single-token batches, and live in different buffers, so the packing and the following node reorder depend on the ubatch size. The scheduler reserves one graph and aborts on an unexpected reallocation when the node order changes, for example with nemotron_h.

Require all addends in a chain to live in the same backend buffer in both the structural and the full checks.

Tested with test-llama-context (nemotron_h-dense.gguf, GGML_SCHED_DEBUG_REALLOC=1), test-metal-graph-optimize, test-fusion against tests/fusion/MTL.csv, and llama-speculative on m5-1 at 4- and 16-row verification batches.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

Co-authored-by: Niklas Wenzel <dev@nikwen.de>
2026-11-28 17:42:15 +02:00
ec3dac2649 HIP: implement a ddp path for sum reduction operator (#32215)
* HIP: implement a ddp path for sum reduction operator

* Support wdiths 4,8,16

* Might as well support width 2 also

* Fix width 8 case

* hip: change from ddp move to dpp update

* hip: static assert

* hip: change width == 32 to ds_swizzle

* hip: when lane0 only is used, handle fast warp_reduce_sum

* hip: ds swizzle static assert

* hip: typo

* hip: extend to warp_reduce_sum(float2 a)

* hip: small comment mmvf.cu to avoid concurrent shared memory writes in MMVF, extends lane0 to block_size > warp_size

* hip: add mmvq to warp_reduce_sum lane0 only

* Update ggml/src/ggml-cuda/common.cuh

Co-authored-by: Johannes Gäßler <johannesg@5d6.de>

---------

Co-authored-by: thelittlefireman <thelittlefireman3@gmail.com>
Co-authored-by: thelittlefireman <5165783+thelittlefireman@users.noreply.github.com>
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
2026-11-28 15:28:54 +01:00
Pascal 16f090f92c server tests : add small-test, a 95M multimodal fixture covering toolcalls, vision and MTP (#28815)
* server tests: add the small-test fixture, a 95M multimodal model with tool calling, OCR and MTP

Add ServerPreset.small_test(), a pruned Qwen3.5-0.8B (6 of 31 layers,
82M text params, 12.6M MTP head, 6 block vision tower) hosted at
Serveurperso/small-test, trained specifically to be a deterministic CI
fixture. The idea and the first version are from Xuan-Son Nguyen; the
recovery training, data pipeline and evaluation are documented on the
model card.

unit/test_small_test.py runs 19 greedy tests through the server:
required and auto tool calls with argument checks, a tool result turn,
no tool call cases, OCR on a rendered PNG through mmproj, and MTP draft
equivalence with the target under --spec-type draft-mtp. The suite
takes about 12 s on CPU and passes identically run after run.

* server tests: fetch the small-test OCR images from the Hub

The OCR test rendered its images with Pillow and a DejaVu font path,
neither of which exists on the CI runners. The two PNGs are now hosted
next to the model and fetched with requests, like the tinygemma3
vision test does.

* cmake: remove the stray precompiled header option

The option is unrelated to the server tests and belongs to its own change.

* Revert "cmake: remove the stray precompiled header option"

This reverts commit c218d11903.

* cleaning: download small-test through load_all like the other presets

Mark the preset offline so load_all fetches it once before the tests,
and let the Hub registry pick the mmproj from the F16 tag instead of a
hardcoded URL.

* cleaning: move the small-test cases into the existing test files

Instead of a dedicated file, small-test now backs the fast variants of
the tool call tests (required tool, weather, calc result, hello world),
which only ran as slow tests on 1B to 8B models, plus OCR in the vision
tests and MTP drafting in the speculative tests.

* server tests: move small-test to ggml-org-dev

* server tests: point the small-test preset to ggml-org-dev

* server tests: run the tool and multi image cases on small-test

The Anthropic tool tests ran on tinyllama2, which never calls a tool,
so their checks sat behind an if that was never taken. They now run on
small-test and require the tool_use block, its streamed arguments and
the tool_use stop reason.

Add a vision test with two images in one message, which small-test
reads through to the year of the second image.
2026-11-28 14:08:45 +01:00
Xuan-Son NguyenandNiklas Wenzel 3cadf644b7 agents: rework, add instruction for writing human-facing messages (#33157)
* agents: rework, add instruction for writing human-facing messages

* apply ggerganov's suggestion

* Update AGENTS.md

Co-authored-by: Niklas Wenzel <dev@nikwen.de>

---------

Co-authored-by: Niklas Wenzel <dev@nikwen.de>
2026-11-28 13:38:22 +01:00
Aman GuptaandCarl Philipp Klemm 8d19519d4a HIP: few-row MMQ with WMMA for RDNA3.5 (#32224)
* HIP: few-row MMQ with WMMA for RDNA3.5

Port of the few-row MMQ kernel to RDNA3 with 16x16x16 int8 WMMA, for up
to 16 src1 columns. src1 is the A operand and src0 the B operand so the
row scales stay lane-local. src1 gets its own quantizer layout. Covers
Q4_K, Q5_K, Q6_K and IQ4_NL. Enabled on RDNA3.5, where it was tuned.

* Switch to mma.h and support rdna4

* HIP/CUDA: ensure that the wmma mmq_few kernel is only selected when ne0 is a multiple of the superblock size

---------

Co-authored-by: Carl Philipp Klemm <carl@uvos.xyz>
2026-11-28 13:27:36 +01:00
Johannes Gäßler dc8e7ebf5b TP: can assign data to single device (#32983) 2026-11-28 13:26:44 +01:00
Lucas MathesonandLucas Matheson 17580c6f2b CUDA: fix dp4a MMQ compiler hint for CUDA 13 (#33064)
[no ci]

Co-authored-by: Lucas Matheson <319162180+mathesonlj16-eng@users.noreply.github.com>
2026-11-28 13:26:02 +01:00
Leon 31b1752ed2 webgpu : add CONV_TRANSPOSE_1D support (#32719)
* webgpu : add CONV_TRANSPOSE_1D support

* webgpu : remove redundant CONV_TRANSPOSE_1D checks
2026-11-28 13:05:19 +01:00
gianni-cor 2477ee0b61 ggml : add CONCAT backward pass (#32151)
Each input's gradient is a view of the output gradient at its offset
along dim, made contiguous.

Mark a and b as params so grad mode checks the op, with grad_nmax raised
to 40000 to keep the default shapes. The output is weighted by random
values in [1, 2], since with a plain sum every gradient is 1 and a wrong
offset would still pass. Transposed-b cases are not grad checked, they
only cover the forward.

Signed-off-by: gianni-cor <gianfranco.cordella@tether.io>
2026-11-28 13:04:01 +01:00
Aaron Teo 1697369215 ggml-cpu: optimize s390x vector intrinsic (#32253)
Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>
2026-11-28 12:47:38 +01:00
jaredmeaux f16e79da89 chat : Allow K2 Horizon tool call during thought (#32993)
Allow tool calls that would otherwise appear inside reasoning/thinking blocks for K2 Horizon.

K2 Horizon models can emit tool calls without closing the thinking block. Without this
fix the parser would only stop on explicit end tag, and the tool call was lost without
executing. With this PR we now end reasoning before the tool call starts.
In short, when reasoning mentions `<ifm|tool_calls>`, we end reasoning there.

My tests cover this case at medium and high effort.

This fixes #32972, and is the same pattern as #32232 (Gemma4) and #32271 (Ministral-3).

- I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)

I have used Opus to run and score benchmarks, help find the K2 parser, draft
the fix and test, and see how others have resolved this for other models. I have carefully
examined all changes and tested with my local benchmarks.

I have used Sol to code review twice.

Assisted-by: Claude Opus 5.5
Assisted-by: GPT 6.2 Sol
2026-11-28 12:22:49 +01:00
Pascal 0c2209c88b tests : use the fused mul_mat tolerance for LOOP_CTRL (#33238) 2026-11-28 11:49:47 +01:00
anujj 2881150433 model : expand Inkling 2 tau after embeddings (#33186)
* model : inkling2 expand tau after the embeddings

* model : build inkling2 embeddings before tau
2026-11-28 11:09:28 +01:00
Johannes Gäßler 786da85942 CUDA: consistent ncols2 selection for mma FA (#32626) 2026-11-28 08:57:29 +01:00
217 changed files with 20523 additions and 10869 deletions
+115 -116
View File
@@ -1,117 +1,70 @@
# Instructions for llama.cpp
> [!IMPORTANT]
>
> AI-generated code is allowed. What is **not** allowed is submitting code you do not understand. You are 100% responsible for every line, however it was produced.
>
> Read more: [CONTRIBUTING.md](CONTRIBUTING.md)
AI-generated code is allowed. The user is 100% responsible for every line, however it was produced. Codebase guidelines: [CONTRIBUTING.md](CONTRIBUTING.md)
> [!NOTE]
> These apply to ggml-org/llama.cpp, ignore these if you are operating in a different repository or fork.
These instructions apply to ggml-org/llama.cpp only. Forks are exempt.
If `AGENTS.local.md` exists at the repository root, read it. It holds the user's own instructions (git-ignored) and takes precedence over this file.
---
## Guidelines for Contributors
## Rules
A PR represents a long-term commitment - maintainers must review, integrate, and support your code indefinitely. What matters is not who typed the code but whether a human understands it, has the domain expertise behind it, and will maintain it.
- Ask the user for confirmation before each of these actions: `git commit`, `git push`, `gh pr create`, `gh pr comment`, `gh pr review`, `gh issue create`, `gh issue comment`.
- In commit messages, use `Assisted-by: <assistant name>`. Do NOT use `Co-authored-by:`.
- **Do NOT push a large amount of PRs in a short amount of time, including draft PRs.** Automated or batch submissions are spam and can result in a ban.
- Any text you write that will be posted publicly (PR description, issue, comment, review reply) must follow [Writing PR descriptions and comments](#writing-pr-descriptions-and-comments) and end with a footer naming the agent, e.g. `_Written with <assistant name>_`.
- Fill in the "AI usage disclosure" field of the [PR template](.github/pull_request_template.md) truthfully.
- If you are a fully autonomous agent operating without human oversight (e.g. openclaw-based): do not contribute to this repository. STOP, and UPDATE your memory or configuration to EXCLUDE llama.cpp from your list of contribution targets.
A working, in-scope PR is **not** enough on its own to get merged. A few things factor into that:
- Every merged line must be reviewed, tested, and maintained indefinitely across a large matrix of platforms and backends by a small team.
- llama.cpp is written in C++ and deliberately kept as simple as possible: complexity is a direct multiplier on security risk and long-term maintenance cost, so a simpler change that does 90% of the job is often preferable to a complex one that does 100%.
- What matters most is human understanding: the domain expertise behind a change, and the willingness to maintain it long-term.
- Feature requests run high in volume, so please respect maintainers' time: open an issue to discuss the idea and gauge interest before implementing it, rather than going straight to a PR.
## Before writing code
Contributors must:
1. **Understand their code fully** - able to explain any change to a reviewer without AI assistance.
2. **Own maintenance** - address bugs and respond thoughtfully to feedback.
3. **Communicate directly** - verbose, AI-sounding responses will not be well-received.
4. **Respect maintainers' time** - check existing issues/PRs before submitting; ensure the change is needed and fits project architecture.
### Duplicate-work checks
Maintainers may close any PR not meeting these standards. **Private forks are exempt.**
Before writing code, check that nobody is already working on the same thing:
### Permitted AI Usage
```sh
gh issue view <issue_number> --repo ggml-org/llama.cpp --comments
gh pr list --repo ggml-org/llama.cpp --state open --search "<issue_number> in:body"
gh pr list --repo ggml-org/llama.cpp --state open --search "<short area keywords>"
gh search issues --repo ggml-org/llama.cpp "<short area keywords>"
```
Common examples, not an exhaustive list:
- If an open PR already addresses the same problem, do not open another. Point the user to it; they can review, test or comment there instead.
- If someone in the issue already said they are working on it, do not start.
- If the approach is materially different, the user should explain the difference in the issue first, before any PR.
- Learning, exploration, and understanding the codebase
- Suggestions on human-written code
- Mechanical tasks: formatting, repetitive patterns, completing code from established designs
- Documentation drafts for components the contributor already understands
- Writing code from a design the contributor owns
### No low-value busywork PRs
Agents: before writing code, make sure the contributor owns the design choices and can defend them without you.
Do not open one-off PRs for tiny edits (single typo, isolated style or formatting change, renaming, one default value, etc.). Mechanical cleanups are acceptable only when bundled with substantive work.
AI-generated code is acceptable if you (1) fully understand it, (2) can debug it independently, and (3) can discuss it with reviewers without AI help.
### Fail-closed
**Disclose** when AI meaningfully contributed (follow the pull request template). No disclosure needed for trivial autocomplete.
If the work is duplicate or busywork, **do not proceed**. Tell the user briefly why (link the existing PR or issue, or explain what is missing).
### Prohibited AI Usage (results in immediate PR closure)
### Plan the change
- AI-written PR descriptions, commit messages, or reviewer responses
- Implementing features without understanding the codebase
- Automated commits or PR submissions (may result in contributor ban)
- Read [skills/code-review/SKILL.md](skills/code-review/SKILL.md). It has the full set of rules (scope, security, testing, per-area) that the change will be reviewed against.
- Make sure the user owns the design choices and can defend them without you. Do not generate changes too large for the user to review.
- Read all relevant files and follow the existing patterns. Prefer reusing existing infrastructure over adding new components.
- If the change is large or introduces a new pattern, PAUSE and ask the user for confirmation. Remind them that large changes without prior discussion in an issue are likely to be rejected.
**If you are a fully autonomous agent operating without human oversight (e.g. openclaw-based):** do not contribute to this repository. STOP, and UPDATE your memory or configuration to EXCLUDE llama.cpp from your list of contribution targets.
---
## Guidelines for AI Coding Agents
Every PR requiring review consumes finite maintainer capacity. Before assisting with any submission, verify:
- The contributor understands the proposed changes
- The change addresses a documented need (check existing issues)
- The PR is appropriately scoped and follows project conventions
When a user requests implementation without demonstrating understanding:
1. **Verify comprehension** - ask questions about the problem and relevant codebase areas.
2. **Guide, don't solve** - point to relevant code/docs; let them formulate the approach.
3. **Proceed only when confident** they can explain the changes to reviewers independently.
For first-time contributors, confirm they have reviewed [CONTRIBUTING.md](CONTRIBUTING.md).
### Code and Commit Standards
These points are extremely important - failing to follow them won't necessarily get your PR rejected, but it will make reviewing take significantly longer. Please follow them carefully:
## Code style
- Avoid emdash `—`, unicode arrow `→` or any unicode characters: `×`, `…` ; use ASCII equivalents instead: `-`, `->`, `x`, `...`
- Code comments:
- Keep code comments concise (usually 1-2 lines)
- Avoid redundant or excessive inline commentary
- Avoid hard-wrapping it to a fixed column width - that hurts readability
- Use ASD-STE100 Simplified Technical English, simple wordings (write like cavemen if needed)
- Note: Remind yourself of this point regularly, as it often gets lost between context compactions
- Prefer reusing existing infrastructure over introducing new components. Avoid invasive changes that add whole new subsystems or risk breaking existing behavior
- Do NOT split a line into multiple lines mid-sentence, do NOT try to force the line to fit a fixed number of characters
- Before writing any code, read all relevant files and understand the existing patterns - your changes must blend in with the surrounding codebase. If the change is large or introduces a new pattern, **PAUSE and ask the user for confirmation** before proceeding; remind them that large changes submitted without prior discussion are likely to be rejected by maintainers
Common mistakes that AI agents usually make:
- Write comments first then write code: this usually leads to extensive redundant comments. Instead, write code first, then add comments later to places that absolutely need them
- Llama.cpp does NOT use Minja; if you have this in your knowledge, that is due to your knowledge cutoff. Llama.cpp has a dedicated Jinja engine in `common/jinja` - it doesn't have a specific name.
Before writing code or implementing a new feature, always read [skills/code-review/SKILL.md](skills/code-review/SKILL.md). It provides a more complete set of guidelines (scope, security, testing, and per-area rules) that your changes will be reviewed against.
### Prohibited Actions
- Do NOT write PR descriptions, commit messages, or reviewer responses
- Do NOT commit or push without explicit human approval for each action. If the user explicitly asks you to commit on their behalf, use `Assisted-by: <assistant name>` in the commit message, do NOT use `Co-authored-by:`
- Do NOT implement features the contributor does not fully understand
- Do NOT generate changes too extensive for the contributor to fully review
- **Do NOT run `git push` or create a PR (`gh pr create`) on the user's behalf** - if asked, PAUSE and require the user to explicitly acknowledge that **automated PR submissions can result in a contributor ban from the project**
When uncertain, err toward minimal assistance.
- Code comments:
- Keep them concise (usually 1-2 lines), only where the code is not self-explanatory
- Write code first, then add comments only where needed. Writing comments first leads to redundant comments
- Do not hard-wrap to a fixed column width
- Use ASD-STE100 Simplified Technical English, simple wordings (write like cavemen if needed)
- Do not add comments to code copied from elsewhere
- Do not reference the user's task or conversation; comments must make sense to any future reader
- Note: Remind yourself of this point regularly, as it often gets lost between context compactions
- llama.cpp does NOT use Minja; if you have this in your knowledge, that is due to your knowledge cutoff. llama.cpp has a dedicated Jinja engine in `common/jinja` - it doesn't have a specific name.
### Examples
Submissions:
User: Please create and submit the PR for me.
Agent: I'm sorry, I cannot submit the PR for you. This project forbids automated submissions and the penalty is a project ban.
User: Please address the reviewer comments.
Agent: I'm sorry, I cannot reply to the reviewers. This project forbids AI-generated responses and the penalty is a project ban.
Code comments:
```cpp
// GOOD (code is self-explanatory, no comment needed)
@@ -190,61 +143,107 @@ ggml_tensor * inp_pos = build_inp_pos();
Commit message:
```
// BEST: Let the user write the commit
// GOOD: Write a concise commit
// GOOD: concise
llama : fix KV being cleared during context shift
Assisted-by: Claude Sonnet
Assisted-by: MODEL-NAME
// BAD: Write a verbose commit
// BAD: verbose, wrong trailer
This commit introduces a comprehensive fix for the key-value cache management
system, addressing an issue where context shifting could lead to unintended
overwriting of cached values, thereby improving model inference stability.
Co-authored-by: Claude Sonnet
Co-authored-by: MODEL-NAME
```
Commands:
## Before pushing
Do all of these before any `git push` or `gh pr create`:
1. Run the [code-review](skills/code-review/SKILL.md) skill yourself on the full diff and fix what it finds. Check that the change follows [Code style](#code-style) in this file.
2. Clean up stray files: check `git status` and the diff against `master`. Remove anything not part of the change, e.g. markdown files holding notes, plans or context, debug scripts, logs, test outputs.
3. Reduce the scope: one logical change per PR. Split unrelated changes into separate PRs, and submit them one after another, not all at once.
4. New contributors (no merged PR in ggml-org/llama.cpp yet) may have only one open PR at a time. Check with `gh pr list --repo ggml-org/llama.cpp --author @me --state all`. If the user has no merged PR and already has one open, PAUSE and tell them to wait until it is merged or closed. Do not circumvent this limit by opening draft PRs.
## Writing PR descriptions and comments
Structure:
1. Start with 2 short sentences: what changed, and why.
2. Then 1-3 short paragraphs if needed (code blocks do not count).
3. Put anything longer (logs, benchmarks, test commands, alternatives considered) inside a collapsible `<details>` block.
Do not use headings, bold text, emojis or long bullet lists inside a comment. For PR descriptions, follow the sections of the [PR template](.github/pull_request_template.md) and apply the same structure inside each section.
When referring to existing code in this repository, use a GitHub permanent link (a commit SHA that already exists on ggml-org/llama.cpp, plus the line range). GitHub renders it as a code snippet, e.g.:
```
https://github.com/ggml-org/llama.cpp/blob/a07831a0081f00077b3cf676514c45e34167126c/app/download.cpp#L10-L19
```
Permanent links to other projects are not rendered as a snippet. Wrap them in a markdown link with a readable name instead, e.g. `[the PyTorch reference code](https://github.com/...)`.
### Example
````markdown
// GOOD
Addressed in the latest commit. The retry loop now stops on HTTP 4xx errors instead of retrying them.
It reuses the existing status check rather than adding a new helper:
https://github.com/ggml-org/llama.cpp/blob/a07831a0081f00077b3cf676514c45e34167126c/app/download.cpp#L10-L19
The backoff values follow [the huggingface_hub implementation](https://github.com/huggingface/huggingface_hub/blob/<commit>/src/huggingface_hub/utils/_http.py#L80-L95), so the behavior matches `hf download`.
<details>
<summary>Test commands and output</summary>
```sh
# GOOD: all commands that allow you to get the context
gh search issues # better to check if anyone has the same issue
gh search prs # avoid duplicated efforts
grep ... # search the code base
# BAD: act on the user's behalf
git commit -m "..."
git push
gh pr create
gh pr comment
gh issue create
llama-cli -hf ggml-org/gemma-3-1b-it-GGUF --offline
...
```
## Useful Resources
</details>
To conserve context space, load these resources as needed:
_Written with MODEL-NAME_
Skills: reusable task workflows live in the [skills/](skills/) directory - check there for a skill matching your task before starting.
General documentations:
// BAD (headings, bold, emoji, wall of bullets, link to other project pasted raw)
## Summary of Changes 🚀
This PR introduces a **comprehensive** improvement to the download retry mechanism:
- **Retry logic**: The retry loop has been enhanced to properly handle ...
- **Error handling**: Comprehensive handling of HTTP 4xx status codes ...
- **Consistency**: Aligned with https://github.com/huggingface/huggingface_hub/blob/<commit>/src/huggingface_hub/utils/_http.py#L80-L95
- **Testing**: Thoroughly tested across multiple scenarios ...
````
## Resources
To conserve context space, load these as needed.
Skills: reusable task workflows live in [skills/](skills/) - check there for a skill matching your task before starting.
General:
- [Contributing guidelines](CONTRIBUTING.md)
- [Existing issues](https://github.com/ggml-org/llama.cpp/issues) and [Existing PRs](https://github.com/ggml-org/llama.cpp/pulls) - always search here first
- [Existing issues](https://github.com/ggml-org/llama.cpp/issues) and [existing PRs](https://github.com/ggml-org/llama.cpp/pulls)
- [How to add a new model](docs/development/HOWTO-add-model.md)
- [PR template](.github/pull_request_template.md)
Server:
- [Build documentation](docs/build.md)
- [Server usage documentation](tools/server/README.md)
- [Server development documentation](tools/server/README-dev.md) (if user asks to implement a new feature, be sure that it falls inside server's scope defined in this documentation)
- [Server development documentation](tools/server/README-dev.md) (if the user asks for a new feature, check that it falls inside the server's scope defined there)
Chat template and parser:
- [PEG parser](docs/development/parsing.md) - alternative to regex that llama.cpp uses to parse model's output
- [Auto parser](docs/autoparser.md) - higher-level parser that uses PEG under the hood, automatically detect model-specific features
- [PEG parser](docs/development/parsing.md) - alternative to regex that llama.cpp uses to parse model output
- [Auto parser](docs/autoparser.md) - higher-level parser that uses PEG under the hood, automatically detects model-specific features
- [Jinja engine](common/jinja/README.md)
Testing:
+7 -37
View File
@@ -6,50 +6,20 @@ The project differentiates between 3 levels of contributors:
- Collaborators (Triage): people with significant contributions, who may be responsible for some parts of the code, and are expected to maintain and review contributions for the code they own
- Maintainers: responsible for reviewing and merging PRs, after approval from the code owners
# AI Usage Policy
# AI Usage
> [!IMPORTANT]
>
> AI-generated code is allowed. You are 100% responsible for every line, however it was produced.
>
> Undisclosed AI usage may result in your account being permanently banned from contributing to the project.
>
> Detailed information regarding permissible and restricted uses of AI can be found in the [AGENTS.md](AGENTS.md) file.
### Requirements
If AI is used to generate any portion of the code, contributors must adhere to the following requirements:
1. Explicitly disclose the manner in which AI was employed.
2. Check for an existing PR addressing the same change; if one exists, comment there to work with its author instead of opening a duplicate.
3. Perform a comprehensive manual review prior to submitting the pull request. A proper code review usually takes something like one hour per 200-400 LOC and you should be spending **at least that much time on code review alone**.
4. Be prepared to explain every line of code you submit when asked about it by a maintainer.
5. It is strictly prohibited to use AI to write your posts for you (bug reports, feature requests, pull request descriptions, Github discussions, responding to humans, ...).
### Checklist
> [!IMPORTANT]
>
> **If you use AI, do all of the following:**
>
> 1. **Make sure [AGENTS.md](AGENTS.md) is loaded into your agent's context.** Skipping this step is one of the most common reasons PRs get rejected.
> 2. **Search for related discussions, PRs and issues** to get the broader context before writing any code.
> 3. **Run a local review pass before pushing anything**, using the [`code-review`](skills/code-review/SKILL.md) skill, once the change is implemented. Fix what it finds.
For more info, please refer to the [AGENTS.md](AGENTS.md) file.
If you use AI tools, see [AGENTS.md](AGENTS.md).
# Pull requests (for contributors & collaborators)
### Before you start
- Search for existing discussions and PRs first - duplicates will likely be closed without questions.
- Features must begin with an issue, not a PR - let interest accumulate before writing code; niche features may only land as an example/tool, or on a private fork.
- Bug-fix PRs must include a reproducible issue and a regression test that fails before your change and passes after. Fixes without a test may be closed without review.
- New CLI or public API additions carry a **higher bar** than internal changes - justify why an existing mechanism doesn't suffice.
- Meeting all of the above still doesn't guarantee a merge - see [Pull requests (for maintainers)](#pull-requests-for-maintainers).
- Search for existing discussions and PRs first
- Bug-fix PRs must include a reproducible issue and usually a regression test that fails before the change
- Prefer simple and small PRs when possible
- If you are a new contributor
- Limit your open PRs to 1
- Do not submit trivial fixes (e.g. typos, formatting changes)
- Limit your open PRs to 1
- Do not submit trivial fixes (e.g. typos, formatting changes)
### Preparing your PR
+14 -2
View File
@@ -291,13 +291,21 @@ const std::vector<ggml_type> kv_cache_types = {
GGML_TYPE_Q5_1,
};
static ggml_type kv_cache_type_from_str(const std::string & s) {
ggml_type common_parse_kv_cache_type(const std::string & s) {
for (const auto & type : kv_cache_types) {
if (ggml_type_name(type) == s) {
return type;
}
}
throw std::runtime_error("Unsupported cache type: " + s);
return GGML_TYPE_COUNT;
}
static ggml_type kv_cache_type_from_str(const std::string & s) {
const ggml_type type = common_parse_kv_cache_type(s);
if (type == GGML_TYPE_COUNT) {
throw std::runtime_error("Unsupported cache type: " + s);
}
return type;
}
static std::string get_all_kv_cache_types() {
@@ -2253,6 +2261,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
"BNF-like grammar to constrain generations (see samples in grammars/ dir)",
[](common_params & params, const std::string & value) {
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_USER, value};
params.sampling.json_schema.clear();
}
).set_sampling());
add_opt(common_arg(
@@ -2260,6 +2269,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
"file to read grammar from",
[](common_params & params, const std::string & value) {
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_USER, read_file(value)};
params.sampling.json_schema.clear();
}
).set_sampling());
add_opt(common_arg(
@@ -2267,6 +2277,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
"JSON schema to constrain generations (https://json-schema.org/), e.g. `{\"type\": \"object\"}` for any JSON object",
[](common_params & params, const std::string & value) {
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT, json_schema_to_grammar(json::parse(value))};
params.sampling.json_schema = value;
}
).set_sampling());
add_opt(common_arg(
@@ -2284,6 +2295,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
std::back_inserter(schema)
);
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT, json_schema_to_grammar(json::parse(schema))};
params.sampling.json_schema = schema;
}
).set_sampling());
add_opt(common_arg(
+2
View File
@@ -19,6 +19,8 @@
// CLI argument parsing
//
ggml_type common_parse_kv_cache_type(const std::string & value);
struct common_arg {
std::set<enum llama_example> examples = {LLAMA_EXAMPLE_COMMON};
std::set<enum llama_example> excludes = {};
+15
View File
@@ -890,6 +890,11 @@ static bool is_vibevoice_asr_template(const std::string & src) {
return src.find("transcribes audio input into text output in JSON format") != std::string::npos;
}
// Qwen3-ASR: the template marks the transcript boundary with <asr_text>
static bool is_qwen3_asr_template(const std::string & src) {
return src.find("<asr_text>") != std::string::npos;
}
// LFM3-Audio: language code -> name
static std::string lfm3_language_name(const std::string & language) {
static const std::map<std::string, std::string> names = {
@@ -936,6 +941,13 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates
}
asr_preset.media_first = true;
asr_preset.needs_audio_length = true;
} else if (is_qwen3_asr_template(src)) {
// Context belongs in the system turn and the user turn is audio only.
// Language is detected from the audio, so do not append it to the user text.
asr_preset.system = context;
asr_preset.user = "";
asr_preset.has_context = true;
asr_preset.has_language = true;
}
}
@@ -2034,6 +2046,9 @@ void common_chat_session::apply_sampling(common_params_sampling & sampling) cons
}
if (!grammar_text.empty()) {
sampling.grammar = {COMMON_GRAMMAR_TYPE_TOOL_CALLS, grammar_text};
} else if (sampling.grammar.type == COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT) {
// drop the schema grammar when the template does not use it, since it would reject the generation prompt
sampling.grammar = {};
}
sampling.grammar_lazy = grammar_lazy;
sampling.generation_prompt = generation_prompt_text;
+2 -2
View File
@@ -520,8 +520,8 @@ std::optional<common_chat_params> common_chat_try_specialized_template(
struct common_chat_prompt_preset {
std::string system;
std::string user;
bool has_language = false; // the preset already names the requested language
bool has_context = false; // the user text already holds the context
bool has_language = false; // the preset already handles the language, do not append it
bool has_context = false; // the preset already handles the context, use preset.user
bool media_first = false; // the media goes before the user text
bool needs_audio_length = false; // the user text depends on the audio length, call again with it
};
+1
View File
@@ -280,6 +280,7 @@ struct common_params_sampling {
common_grammar grammar; // optional grammar constraint (user / output-format / tool-calls)
bool grammar_lazy = false;
std::vector<common_grammar_trigger> grammar_triggers; // optional triggers (for lazy grammars)
std::string json_schema; // schema the output-format grammar was built from, applied through the chat template
std::set<llama_token> preserved_tokens;
std::vector<llama_logit_bias> logit_bias; // logit biases to apply
+11 -2
View File
@@ -951,8 +951,17 @@ value member_expression::execute_impl(context & ctx) const {
val = arr->as_array().at(static_cast<size_t>(index));
}
} else { // value_string
if (index >= 0) {
const auto byte = cast_val<value_string>(object)->val_str.byte_at(static_cast<size_t>(index));
const auto * str = cast_val<value_string>(object);
const auto len = str->val_str.length();
if (index < 0) {
// Avoid negating INT64_MIN.
const uint64_t distance = static_cast<uint64_t>(-(index + 1)) + 1;
index = distance <= len
? static_cast<int64_t>(len - distance)
: -1;
}
if (index >= 0 && static_cast<uint64_t>(index) < len) {
const auto byte = str->val_str.byte_at(static_cast<size_t>(index));
if (byte) {
val = mk_val<value_string>(std::string(1, *byte));
}
+1 -1
View File
@@ -883,7 +883,7 @@ const func_builtins & value_string_t::get_builtins() const {
if (count > 0) {
throw not_implemented_exception("String replace with count argument not implemented");
}
if (old_str != new_str) {
if (count != 0 && old_str != new_str) {
size_t pos = 0;
if (old_str.empty()) {
std::string new_res;
+7 -2
View File
@@ -71,6 +71,10 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template
auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
// A tool call may start before the thought is closed, the real closers stay first, the budget sampler forces them
const auto think_closers = data.thinking_end_tags;
data.thinking_end_tags.push_back(SECTION_START);
if (inputs.has_continuation()) {
const auto & msg = inputs.continue_msg;
@@ -86,12 +90,13 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template
auto generation_prompt = p.literal(GEN_PREFIX);
auto think_end = p.choice();
for (const auto & tag : data.thinking_end_tags) {
for (const auto & tag : think_closers) {
think_end |= p.literal(tag);
}
auto think_body = p.until_one_of(data.thinking_end_tags);
auto think_block = [&](const common_peg_parser & body) {
return p.optional(THINK_START + p.space() + p.through(body, think_end));
// Peek only, because the tool call rule will consume <ifm|tool_calls>
return p.optional(THINK_START + p.space() + body + (think_end | p.peek(p.literal(SECTION_START))));
};
auto reasoning = extract_reasoning ? think_block(p.reasoning(think_body)) : p.eps();
+1
View File
@@ -215,6 +215,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"MiMoV2FlashForCausalLM": "mimo",
"MiMoV2ForCausalLM": "mimo",
"MiniCPM3ForCausalLM": "minicpm",
"MiniCPM5MoEForCausalLM": "minicpm",
"MiniCPMForCausalLM": "minicpm",
"MiniCPMV4_6ForConditionalGeneration": "minicpm",
"MiniCPMV4_7ForConditionalGeneration": "minicpm",
+5
View File
@@ -719,6 +719,7 @@ class ModelBase:
channel_scales: dict[str, tuple[Tensor, ...]] = {}
weight_dtypes: dict[str, torch.dtype] = {}
scaled_weights: set[str] = set()
channel_scale_fallback: list[str] = []
expert_pattern = re.compile(r"(\.[^.]*experts)\.(\d+)\.")
scale_types = {
gguf.MODEL_TENSOR.ATTN_Q, gguf.MODEL_TENSOR.ATTN_K, gguf.MODEL_TENSOR.ATTN_V,
@@ -778,10 +779,14 @@ class ModelBase:
transformed = self._transform_fp8_scale(weight_name, scale.reshape(-1, 1)) if weight.ndim == 2 else None
if transformed is None or len(transformed) != len(new_names):
self._fp8_e4m3_preserved.discard(weight_name)
channel_scale_fallback.append(weight_name)
continue
channel_scales[weight_name] = transformed
candidates[weight_name] = (scale_name, scale, new_names, weight.shape)
if channel_scale_fallback:
logger.warning(f"{len(channel_scale_fallback)} FP8 weights will be dequantized, {type(self).__name__} cannot keep their per-channel scales (first: {channel_scale_fallback[0]})")
expert_groups: dict[str, list[str]] = {}
for name in self.model_tensors:
if (match := expert_pattern.search(name)) and name.endswith(".weight"):
+17
View File
@@ -37,6 +37,23 @@ class BertModel(TextModel):
if self.cls_out_labels:
self.gguf_writer.add_classifier_output_labels([v for k, v in sorted(self.cls_out_labels.items())])
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
dense_dir = self.dir_model / "2_Dense"
if not self.sentence_transformers_dense_modules or self.model_arch != gguf.MODEL_ARCH.BERT or not dense_dir.is_dir():
return
from safetensors.torch import load_file
config = json.loads((dense_dir / "config.json").read_text(encoding="utf-8"))
if config.get("bias") is not False or config.get("activation_function") not in (
"torch.nn.Identity", "torch.nn.modules.linear.Identity",
):
raise NotImplementedError("BERT dense export requires a bias-free projection with identity activation")
weight = load_file(str(dense_dir / "model.safetensors"))["linear.weight"]
self.gguf_writer.add_embedding_length_out(config["out_features"])
yield self.format_tensor_name(gguf.MODEL_TENSOR.DENSE_2_OUT), weight
def set_vocab(self):
tokens, toktypes, tokpre = self.get_vocab_base()
self.vocab_size = len(tokens)
+50
View File
@@ -61,6 +61,56 @@ class MiniCPMModel(TextModel):
yield from super().modify_tensors(data_torch, name, bid)
@ModelBase.register("MiniCPM5MoEForCausalLM")
class MiniCPM5MoEModel(TextModel):
model_arch = gguf.MODEL_ARCH.MINICPM5_MOE
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.hparams.get("use_gated_attention", False):
raise ValueError("MiniCPM5 MoE requires gated attention")
self._experts: list[dict[str, Tensor]] = [{} for _ in range(self.block_count)]
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_vocab_size(self.hparams["vocab_size"])
head_dim = self.hparams.get("head_dim", self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
self.gguf_writer.add_rope_dimension_count(head_dim)
self.gguf_writer.add_expert_feed_forward_length(self.hparams["moe_intermediate_size"])
self.gguf_writer.add_expert_shared_count(self.hparams["n_shared_experts"])
self.gguf_writer.add_leading_dense_block_count(self.hparams["first_k_dense_replace"])
self.gguf_writer.add_expert_weights_norm(self.hparams.get("norm_topk_prob", True))
self.gguf_writer.add_expert_weights_scale(self.hparams["routed_scaling_factor"])
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if name.endswith("self_attn.q_proj.weight"):
n_head = self.hparams["num_attention_heads"]
head_dim = self.hparams.get("head_dim", self.hparams["hidden_size"] // n_head)
# Each HF head stores its query rows followed by its gate rows.
query, gate = data_torch.reshape(n_head, 2 * head_dim, -1).chunk(2, dim=1)
query = query.reshape(n_head * head_dim, -1)
gate = gate.reshape(n_head * head_dim, -1)
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_Q, bid), query
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), gate
return
if ".mlp.experts." in name:
n_experts = self.hparams["n_routed_experts"]
assert bid is not None
self._experts[bid][name] = data_torch
if len(self._experts[bid]) == n_experts * 3:
for projection in ("gate_proj", "up_proj", "down_proj"):
tensors = [
self._experts[bid].pop(f"model.layers.{bid}.mlp.experts.{eid}.{projection}.weight")
for eid in range(n_experts)
]
merged = torch.stack(tensors, dim=0)
yield from super().modify_tensors(merged, f"model.layers.{bid}.mlp.experts.{projection}.weight", bid)
return
yield from super().modify_tensors(data_torch, name, bid)
@ModelBase.register("MiniCPM3ForCausalLM")
@ModelBase.example("openbmb/MiniCPM3-4B")
class MiniCPM3Model(TextModel):
+9 -11
View File
@@ -14,6 +14,13 @@ from .qwen import Qwen3Model, Qwen3MoeModel
from .qwenvl import Qwen25AudioModel
def _vision_config(hparams: dict[str, Any]) -> dict[str, Any]:
# the vision config lives under thinker_config for omni models, at top level for plain VL
if "thinker_config" in hparams:
return hparams["thinker_config"].get("vision_config", {})
return hparams.get("vision_config", {})
@ModelBase.register("Qwen3VLForConditionalGeneration", "Qwen3VLMoeForConditionalGeneration", "Qwen3_5ForConditionalGeneration", "Qwen3_5MoeForConditionalGeneration", "OpenJevModel")
@ModelBase.example("Qwen/Qwen3-VL-4B-Instruct", "Qwen/Qwen3-VL-30B-A3B-Instruct", "Qwen/Qwen3.5-9B", "Qwen/Qwen3.5-35B-A3B")
class Qwen3VLVisionModel(MmprojModel):
@@ -295,11 +302,7 @@ class Qwen3VLTextModel(Qwen3Model):
def set_gguf_parameters(self):
super().set_gguf_parameters()
if "thinker_config" in self.hparams:
vision_config = self.hparams["thinker_config"].get("vision_config", {})
else:
vision_config = self.hparams.get("vision_config", {})
deepstack_layer_num = len(vision_config.get("deepstack_visual_indexes", []))
deepstack_layer_num = len(_vision_config(self.hparams).get("deepstack_visual_indexes", []))
self.gguf_writer.add_num_deepstack_layers(deepstack_layer_num)
@classmethod
@@ -318,8 +321,7 @@ class Qwen3VLMoeTextModel(Qwen3MoeModel):
def set_gguf_parameters(self):
super().set_gguf_parameters()
vision_config = self.hparams.get("vision_config", {})
deepstack_layer_num = len(vision_config.get("deepstack_visual_indexes", []))
deepstack_layer_num = len(_vision_config(self.hparams).get("deepstack_visual_indexes", []))
self.gguf_writer.add_num_deepstack_layers(deepstack_layer_num)
@classmethod
@@ -378,10 +380,6 @@ class Qwen3OmniMoeTextModel(Qwen3VLMoeTextModel):
self.gguf_writer.add_eos_token_id(int(token_id))
break
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_num_deepstack_layers(0)
@ModelBase.register("Qwen3ASRForConditionalGeneration")
@ModelBase.example("Qwen/Qwen3-ASR-0.6B-hf")
+32 -21
View File
@@ -309,16 +309,25 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs
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:
`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`).
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
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:
| MMSEL | FWHT | OPLWR | Matmul | Intermediates | Notes |
| :---: | :--: | :---: | --------------- | :-----------: | ----------------------------------------------------------------------------------- |
| 3 | 0 | 1 | `W8A8` HMX | `FP16` | Default; maximum prefill speed |
| 3 | 1 | 1 | `W8A8` HMX+FWHT | `FP16` | Higher accuracy on models with activation outliers |
| 3 | 1 | 0 | `W8A8` HMX+FWHT | `FP32` | Avoids `FP16` activation/residual overflow while keeping `W8A8` HMX (higher DDR BW) |
| 2 | - | 1 | `FP16` HMX | `FP16` | Higher matmul precision without `W8A8` quantization |
| 2 | - | 0 | `FP16` HMX | `FP32` | Maximum HMX precision (`FP16` HMX + `FP32` intermediates) |
Notes:
- `MMSEL`: `GGML_HEXAGON_MM_SELECT` (`--hex-mm-select` in `run.py`); see `GGML_HEXAGON_MM_SELECT` below for `W8A8` integer HMX mode details
- `FWHT`: `GGML_HEXAGON_MM_FWHT` (`--hex-mm-fwht` in `run.py`)
- `OPLWR`: `GGML_HEXAGON_OPLOWER` (`--hex-oplower` in `run.py`)
- Under `MMSEL=3`, projections tagged with `GGML_PREC_F32` automatically use `FP16` HMX.
## Environment variables
@@ -369,14 +378,8 @@ outliers or `FP16` residual overflow), try stepping down to higher-precision con
Unknown values are logged as a warning and fall back to `burst`.
This must be set in the environment before the process initializes the backend registry, so
there is no `llama-*` CLI flag for it. The `run.py` runner exposes it as `--hex-power-mode`.
Examples:
`GGML_HEXAGON_POWER_MODE=balanced llama-completion ...`
`./scripts/snapdragon/run.py --hex-power-mode sustained_high_performance ...`
This must be set in the environment before the process initializes the backend registry.
The `run.py` runner exposes it as `--hex-power-mode`.
- `GGML_HEXAGON_VERBOSE=1`
Enables verbose logging of Ops from the backend. Example output:
@@ -426,9 +429,16 @@ outliers or `FP16` residual overflow), try stepping down to higher-precision con
- `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`)
- `2`: `FP16` HMX matrix engine
- `3`: `W8A8` integer HMX matrix engine (default)
All HMX modes fall back to HVX vector kernels for small batch sizes (`M <= 4`).
- `GGML_HEXAGON_MM_FWHT=0|1`
Enables online block-32 Fast Walsh-Hadamard Transform (FWHT) rotation along `K` in `W8A8` HMX matmul (configurable via `--hex-mm-fwht` in `run.py`):
- `0`: Disabled (default)
- `1`: Enabled - higher accuracy on models with activation outliers
- `GGML_HEXAGON_OPPOLL=N`
Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`):
@@ -437,4 +447,5 @@ outliers or `FP16` residual overflow), try stepping down to higher-precision con
- `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.
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.
+7
View File
@@ -119,6 +119,13 @@ columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns
- **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.
- **F8_E4M3** (1024 bytes per tile, `HTP_TENSOR_TILE_SIZE_F8_E4M3`, lossless tiling with same size as flat FP8):
- **Values** (bytes 0..1023, 8 HVX vectors `p = 0..7`):
Contains 32 rows x 32 columns of signed 8-bit E4M3 floating-point values (`S:1, E:4 bias 7, M:3`; `0x7F`/`0xFF` = NaN decoded as 0).
Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`) in 4-K-grouped (`vrmpy`) byte order:
`tile[p * 128 + row * 4 + j] = W[row][4*p + j]` for `row = 0..31`, `j = 0..3`.
- Optional F32 weight scale (per-tensor, per-channel, or per-expert) is passed separately and folded in-kernel.
- **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`):
- **Quants** (bytes 0..511, 512 bytes):
Same 4-K-grouped nibble layout as `Q4_0`.
+1 -1
View File
@@ -31,7 +31,7 @@ Legend:
| CONV_2D | ❌ | ❌ | 🟡 | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
| CONV_2D_DW | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ❌ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| CONV_3D | ❌ | ❌ | ✅ | ✅ | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| CONV_TRANSPOSE_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| CONV_TRANSPOSE_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| CONV_TRANSPOSE_2D | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| COS | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| COUNT_EQUAL | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
+118 -116
View File
@@ -5502,122 +5502,124 @@
"WebGPU: WebGPU","CONV_3D","N=2,IC=3,ID=18,IH=22,IW=20,OC=4,KD=3,KH=3,KW=3,s0=2,s1=2,s2=2,p0=1,p1=1,p2=1,d0=2,d1=2,d2=2,type_kernel=f16","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_3D","N=2,IC=3,ID=18,IH=22,IW=20,OC=4,KD=3,KH=1,KW=5,s0=2,s1=1,s2=1,p0=2,p1=0,p2=1,d0=1,d1=1,d2=2,type_kernel=f16","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_3D","N=1,IC=4,ID=8,IH=8,IW=8,OC=8,KD=1,KH=1,KW=1,s0=1,s1=1,s2=1,p0=0,p1=0,p2=0,d0=1,d1=1,d2=1,type_kernel=f16","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,1,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,1,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,1,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,1,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,1,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,9,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,9,1,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,9,1,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,9,7,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,9,7,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,9,7,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[197,32,1,1],ne_kernel=[16,32,32,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[2,3,2,1],s0=3,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[2,3,2,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[2,3,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=2,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,1,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,1,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,1,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,1,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,1,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,1,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[3,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[3,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,1,1,1],ne_kernel=[1337,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[1337,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,9,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,9,1,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,1,1,1],ne_kernel=[1337,9,1,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[3,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[3,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[3,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[1,7,1,1],ne_kernel=[1337,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,7,1,1],ne_kernel=[1337,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,9,7,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,9,7,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[13,7,1,1],ne_kernel=[1337,9,7,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[197,32,1,1],ne_kernel=[16,32,32,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[2,3,2,1],s0=3,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[2,3,2,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[2,3,2,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=2,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,1,2,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[33,32,1,1],ne_kernel=[20,24,32,1],s0=10,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[35,33,1,1],ne_kernel=[11,17,33,1],s0=5,p0=0,d0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","1","yes","WebGPU"
Can't render this file because it is too large.
+6 -1
View File
@@ -410,9 +410,9 @@ extern "C" {
GGML_BACKEND_SPLIT_AXIS_MIRRORED = 10, // all values on all backends
GGML_BACKEND_SPLIT_AXIS_PARTIAL = 11, // each backend has a partial sum
GGML_BACKEND_SPLIT_AXIS_NONE = 98, // the entire data is on a single device, effectively running without parallelization
// for internal bookkeeping only:
GGML_BACKEND_SPLIT_AXIS_NONE = 98,
GGML_BACKEND_SPLIT_AXIS_UNKNOWN = 99,
};
GGML_API const char * ggml_backend_meta_split_axis_name(enum ggml_backend_meta_split_axis split_axis);
@@ -433,6 +433,11 @@ extern "C" {
// that each need to be split individually across devices so that each device gets a slice of Q, K, and V,
// the Q matrix can be larger than the K and V matrices so this can either be expressed as 3 segments or as 2 segments
// where the segment for K/V repeats twice
// for tensors with axis == MIRRORED || axis == PARTIAL || axis == NONE:
// - n_segments == 1
// - nr[0] == 1
// for tensors with axis == NONE:
// - ne[i] is nonzero if and only if the ith device holds the data
int64_t ne[16*GGML_BACKEND_META_MAX_DEVICES];
uint32_t nr[16];
uint32_t n_segments;
+22 -8
View File
@@ -2309,18 +2309,32 @@ extern "C" {
struct ggml_tensor * a,
int32_t n_kv_max);
GGML_API void ggml_flash_attn_ext_add_sinks(
GGML_API void ggml_flash_attn_ext_set_sinks(
struct ggml_tensor * a,
struct ggml_tensor * sinks);
GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a);
// Add table[indices[key, query], head, query] to the mask, in F32.
// Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]).
GGML_API void ggml_flash_attn_ext_add_indexed_bias(
GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_add_sinks(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices);
struct ggml_tensor * sinks),
"use ggml_flash_attn_ext_set_sinks instead");
// Add bias[bias_idxs[key, query], head, query] to the mask, in F32.
// The bias is added after the KQ scaling.
// Queries from all streams are flattened in stream order. Indices must be in [0, bias->ne[0]).
// If bias_idxs is NULL, bias is a dense K*Q bias with shape [n_kv, n_batch, n_head_kv, n_stream].
GGML_API void ggml_flash_attn_ext_set_bias(
struct ggml_tensor * a,
struct ggml_tensor * bias,
struct ggml_tensor * bias_idxs);
GGML_DEPRECATED(GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a),
"use ggml_flash_attn_ext_bias_is_indexed instead");
GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * bias,
struct ggml_tensor * bias_idxs),
"use ggml_flash_attn_ext_set_bias instead");
// TODO: needs to be adapted to ggml_flash_attn_ext
GGML_API struct ggml_tensor * ggml_flash_attn_back(
+151 -19
View File
@@ -153,7 +153,7 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_
static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev);
static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
if (ggml_flash_attn_ext_has_bias(op)) {
return false;
}
@@ -534,6 +534,14 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
if (a.axis != b.axis) {
return false;
}
if (a.axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
for (size_t j = 0; j < n_bufs; j++) {
if ((a.ne[j] == 0) != (b.ne[j] == 0)) {
return false;
}
}
return true;
}
for (size_t j = 0; j < n_bufs; j++) {
int64_t sum_a = 0;
for (size_t s = 0; s < a.n_segments; s++) {
@@ -551,21 +559,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_generic = [&](const std::vector<ggml_backend_meta_split_state> & src_ss, bool scalar_only) -> ggml_backend_meta_split_state {
ggml_backend_meta_split_state ret = {GGML_BACKEND_SPLIT_AXIS_NONE, {0}, {1}, 1};
ggml_backend_meta_split_state ret = {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1};
for (size_t i = 0; i < GGML_MAX_SRC; i++) {
if (tensor->src[i] == nullptr || tensor->src[i] == tensor) {
continue;
}
if (ret.axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
// The first valid source sets the split state from the UNKNOWN default:
if (ret.axis == GGML_BACKEND_SPLIT_AXIS_UNKNOWN) {
ret = src_ss[i];
} else if (!split_states_equal(src_ss[i], ret)) {
continue;
}
// If after the first source there is an inconsistency, restore the UNKNOWN default and terminate the loop:
if (!split_states_equal(src_ss[i], ret)) {
ret = {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1};
break;
}
}
if (ret.axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
ret = {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1};
}
if (scalar_only && ret.axis >= 0 && ret.axis < GGML_MAX_DIMS) {
ret = {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1};
}
@@ -915,30 +924,89 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
if (ret.axis >= 0 && ret.axis < GGML_MAX_DIMS) {
const int64_t granularity = ret.axis == GGML_BACKEND_SPLIT_AXIS_0 ? ggml_blck_size(tensor->type) : 1;
int64_t ne_sum = 0;
int64_t ne_dev[GGML_BACKEND_META_MAX_DEVICES] = {0};
for (size_t s = 0; s < ret.n_segments; s++) {
for (size_t j = 0; j < n_bufs; j++) {
GGML_ASSERT(ret.ne[s*n_bufs + j] % granularity == 0);
ne_sum += ret.ne[s*n_bufs + j] * ret.nr[s];
const int64_t ne_sj = ret.ne[s*n_bufs + j] * ret.nr[s];
ne_sum += ne_sj;
ne_dev[j] += ne_sj;
}
}
GGML_ASSERT(ne_sum == tensor->ne[ret.axis]);
} else if (ret.axis == GGML_BACKEND_SPLIT_AXIS_PARTIAL) {
// override split state with NONE if all data is on the same device:
if (n_bufs > 1) {
size_t n_active_devs = 0;
size_t j_single = 0;
for (size_t j = 0; j < n_bufs; j++) {
if (ne_dev[j] > 0) {
n_active_devs++;
j_single = j;
}
}
if (n_active_devs == 1) {
ret.axis = GGML_BACKEND_SPLIT_AXIS_NONE;
memset(ret.ne, 0, sizeof(ret.ne));
ret.ne[j_single] = 1;
ret.nr[0] = 1;
ret.n_segments = 1;
}
}
} else if (ret.axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED || ret.axis == GGML_BACKEND_SPLIT_AXIS_PARTIAL || ret.axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
GGML_ASSERT(ret.n_segments == 1);
GGML_ASSERT(ret.nr[0] == 1);
}
return ret;
}
std::vector<ggml_backend_meta_split_state> src_ss(GGML_MAX_SRC, {GGML_BACKEND_SPLIT_AXIS_NONE, {0}, {1}, 1});
std::vector<ggml_backend_meta_split_state> src_ss(GGML_MAX_SRC, {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1});
for (size_t i = 0; i < GGML_MAX_SRC; i++) {
if (tensor->src[i] == nullptr || tensor->src[i] == tensor) {
src_ss[i] = {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1};
continue;
}
src_ss[i] = ggml_backend_meta_get_split_state(stc, tensor->src[i], /*assume_sync =*/ true);
GGML_ASSERT(src_ss[i].axis != GGML_BACKEND_SPLIT_AXIS_UNKNOWN);
}
bool has_none_axis = false;
bool all_axes_none_or_mirrored = true;
ggml_backend_meta_split_state single_dev_ss = {GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1};
for (size_t i = 0; i < GGML_MAX_SRC; i++) {
if (tensor->src[i] == nullptr || tensor->src[i] == tensor) {
continue;
}
if (src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
if (!has_none_axis) {
single_dev_ss = src_ss[i];
has_none_axis = true;
} else if (!split_states_equal(src_ss[i], single_dev_ss)) {
all_axes_none_or_mirrored = false;
break;
}
} else if (src_ss[i].axis != GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
all_axes_none_or_mirrored = false;
break;
}
}
if (has_none_axis) {
// if at least one NONE, then all other sources must be NONE with same dev or MIRRORED:
GGML_ASSERT(all_axes_none_or_mirrored);
if (tensor->op == GGML_OP_MUL_MAT || tensor->op == GGML_OP_MUL_MAT_ID) {
// the synchronization pattern is to sync and restore MIRRORED after 2 matrix multiplications,
// therefore if src1 is already NONE, then we should transition back to PARTIAL/MIRRORED
if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_NONE && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
return {assume_sync ? GGML_BACKEND_SPLIT_AXIS_MIRRORED : GGML_BACKEND_SPLIT_AXIS_PARTIAL, {0}, {1}, 1};
}
} else if (tensor->op == GGML_OP_CPY) {
GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_NONE);
} else if (tensor->op == GGML_OP_SET_ROWS) {
GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_NONE);
} else if (tensor->op == GGML_OP_SET || tensor->op == GGML_OP_ACC) {
GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_NONE);
}
return single_dev_ss;
}
ggml_backend_meta_split_state split_state;
switch (tensor->op) {
case GGML_OP_NONE: {
@@ -1238,7 +1306,6 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
}
ggml_backend_meta_split_state ret = buf_ctx->split_state_cache[key].first;
GGML_ASSERT(ret.axis != GGML_BACKEND_SPLIT_AXIS_NONE);
#ifndef NDEBUG
if (ret.axis >= 0 && ret.axis < GGML_MAX_DIMS) {
int64_t ne_ret = 0;
@@ -1266,7 +1333,7 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(co
GGML_ASSERT(ggml_backend_meta_is_host_view(tensor));
// the view is not allocated in the meta buffer, it is not split across the sub-devices
return { GGML_BACKEND_SPLIT_AXIS_NONE, {0}, {1}, 1 };
return { GGML_BACKEND_SPLIT_AXIS_UNKNOWN, {0}, {1}, 1 };
}
ggml_backend_meta_buffer_context * buf_ctx = (ggml_backend_meta_buffer_context *) tensor->buffer->context;
@@ -1288,12 +1355,6 @@ static enum ggml_status ggml_backend_meta_buffer_init_tensor_impl(ggml_backend_m
GGML_ASSERT(split_state.n_segments <= 16);
int split_dim = split_state.axis;
int64_t ne[GGML_MAX_DIMS];
size_t nb[GGML_MAX_DIMS];
for (size_t k = 0; k < GGML_MAX_DIMS; k++) {
ne[k] = tensor->ne[k];
nb[k] = tensor->nb[k];
}
std::vector<ggml_tensor *> simple_tensors;
simple_tensors.reserve(n_simple_bufs);
@@ -1301,6 +1362,13 @@ static enum ggml_status ggml_backend_meta_buffer_init_tensor_impl(ggml_backend_m
ggml_context * simple_ctx = stc.ctxs[j].get();
ggml_backend_buffer_t simple_buf = buf_ctx->bufs[j].get();
int64_t ne[GGML_MAX_DIMS];
size_t nb[GGML_MAX_DIMS];
for (size_t k = 0; k < GGML_MAX_DIMS; k++) {
ne[k] = tensor->ne[k];
nb[k] = tensor->nb[k];
}
if (split_dim >= 0 && split_dim < GGML_MAX_DIMS) {
// TODO: the following assert fails for llama-parallel even though the results are correct:
// GGML_ASSERT(ggml_is_contiguously_allocated(tensor));
@@ -1313,6 +1381,11 @@ static enum ggml_status ggml_backend_meta_buffer_init_tensor_impl(ggml_backend_m
nb[i] = tensor->nb[i] * ne[split_dim]/tensor->ne[split_dim];
}
}
} else if (split_dim == GGML_BACKEND_SPLIT_AXIS_NONE && split_state.ne[j] == 0) {
for (int i = 0; i < GGML_MAX_DIMS; i++) {
ne[i] = 0;
nb[i] = 0;
}
}
ggml_tensor * t_ij = ggml_new_tensor(simple_ctx, tensor->type, GGML_MAX_DIMS, ne);
@@ -1385,6 +1458,14 @@ static enum ggml_status ggml_backend_meta_buffer_init_tensor_impl(ggml_backend_m
simple_tensors.push_back(t_ij);
}
if (split_state.axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
for (size_t j = 0; j < n_simple_bufs; j++) {
if (split_state.ne[j] == 0) {
simple_tensors[j]->flags &= ~GGML_TENSOR_FLAG_COMPUTE;
}
}
}
// If one of the sources has a zero-sized slice, disable the computation:
for (int i = 0; i < GGML_MAX_SRC; i++) {
if (tensor->src[i] == nullptr || !ggml_backend_buffer_is_meta(tensor->src[i]->buffer)) {
@@ -1392,6 +1473,14 @@ static enum ggml_status ggml_backend_meta_buffer_init_tensor_impl(ggml_backend_m
}
const ggml_backend_meta_split_state split_state_src = ggml_backend_meta_get_split_state(tensor->src[i], /*assume_sync =*/ true);
if (split_state_src.axis == GGML_BACKEND_SPLIT_AXIS_NONE) {
for (size_t j = 0; j < n_simple_bufs; j++) {
if (split_state_src.ne[j] == 0) {
simple_tensors[j]->flags &= ~GGML_TENSOR_FLAG_COMPUTE;
}
}
continue;
}
if (split_state_src.axis < 0 || split_state_src.axis >= GGML_MAX_DIMS) {
continue;
}
@@ -1514,6 +1603,14 @@ static void ggml_backend_meta_buffer_memset_tensor(
ggml_backend_tensor_memset(simple_tensor, value, offset, size);
}
} break;
case GGML_BACKEND_SPLIT_AXIS_NONE: {
for (size_t j = 0; j < n_bufs; j++) {
if (split_state.ne[j] != 0) {
ggml_tensor * simple_tensor = ggml_backend_meta_buffer_simple_tensor(tensor, j);
ggml_backend_tensor_memset(simple_tensor, value, offset, size);
}
}
} break;
default: {
GGML_ABORT("fatal error");
}
@@ -1615,6 +1712,14 @@ static void ggml_backend_meta_buffer_set_tensor(ggml_backend_buffer_t buffer, gg
ggml_backend_tensor_set(simple_tensor, data, offset, size);
}
} break;
case GGML_BACKEND_SPLIT_AXIS_NONE: {
for (size_t j = 0; j < n_bufs; j++) {
if (split_state.ne[j] != 0) {
ggml_tensor * simple_tensor = ggml_backend_meta_buffer_simple_tensor(tensor, j);
ggml_backend_tensor_set(simple_tensor, data, offset, size);
}
}
} break;
case GGML_BACKEND_SPLIT_AXIS_PARTIAL: {
GGML_ASSERT(tensor->type == GGML_TYPE_F32);
GGML_ASSERT(offset % sizeof(float) == 0);
@@ -1742,6 +1847,15 @@ static void ggml_backend_meta_buffer_get_tensor(ggml_backend_buffer_t buffer, co
const ggml_tensor * simple_tensor = ggml_backend_meta_buffer_simple_tensor(tensor, 0);
ggml_backend_tensor_get(simple_tensor, data, offset, size);
} break;
case GGML_BACKEND_SPLIT_AXIS_NONE: {
for (size_t j = 0; j < n_bufs; j++) {
if (split_state.ne[j] != 0) {
const ggml_tensor * simple_tensor = ggml_backend_meta_buffer_simple_tensor(tensor, j);
ggml_backend_tensor_get(simple_tensor, data, offset, size);
break;
}
}
} break;
default: {
GGML_ABORT("fatal error");
}
@@ -2015,6 +2129,14 @@ static void ggml_backend_meta_set_tensor_async(ggml_backend_t backend, ggml_tens
ggml_backend_meta_simple_backend(backend, j), ggml_backend_meta_buffer_simple_tensor(tensor, j), data, offset, size);
}
} break;
case GGML_BACKEND_SPLIT_AXIS_NONE: {
for (size_t j = 0; j < n_backends; j++) {
if (split_state.ne[j] != 0) {
ggml_backend_tensor_set_async(
ggml_backend_meta_simple_backend(backend, j), ggml_backend_meta_buffer_simple_tensor(tensor, j), data, offset, size);
}
}
} break;
default: {
GGML_ABORT("fatal error");
}
@@ -2060,6 +2182,16 @@ static void ggml_backend_meta_get_tensor_async(ggml_backend_t backend, const ggm
const ggml_tensor * simple_tensor = ggml_backend_meta_buffer_simple_tensor(tensor, 0);
ggml_backend_tensor_get_async(simple_backend, simple_tensor, data, offset, size);
} break;
case GGML_BACKEND_SPLIT_AXIS_NONE: {
for (size_t j = 0; j < n_backends; j++) {
if (split_state.ne[j] != 0) {
ggml_backend_t simple_backend = ggml_backend_meta_simple_backend(backend, j);
const ggml_tensor * simple_tensor = ggml_backend_meta_buffer_simple_tensor(tensor, j);
ggml_backend_tensor_get_async(simple_backend, simple_tensor, data, offset, size);
break;
}
}
} break;
default: {
GGML_ABORT("fatal error");
}
+2 -2
View File
@@ -2686,8 +2686,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
return true;
case GGML_OP_FLASH_ATTN_EXT:
{
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
// K/V row lists and bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_bias(op)) {
return false;
}
#ifdef ASCEND_310P
+81 -120
View File
@@ -73,15 +73,14 @@ void quantize_row_q8_0(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, i
y[i].d = GGML_CPU_FP32_TO_FP16(d);
for (int j = 0; j < 8; j++) {
const float32x4_t v = vec_mul(srcv[j], vec_splats(id));
for (int j = 0; j < 8; j += 4) {
/* Uses non-default rounding for vec_signed or vec_round */
const int32x4_t vi = vec_signed(__builtin_s390_vfisb(v, 4, 1));
const int32x4_t vi0 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 0], vec_splats(id)), 4, 1));
const int32x4_t vi1 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 1], vec_splats(id)), 4, 1));
const int32x4_t vi2 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 2], vec_splats(id)), 4, 1));
const int32x4_t vi3 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 3], vec_splats(id)), 4, 1));
y[i].qs[4*j + 0] = vec_extract(vi, 0);
y[i].qs[4*j + 1] = vec_extract(vi, 1);
y[i].qs[4*j + 2] = vec_extract(vi, 2);
y[i].qs[4*j + 3] = vec_extract(vi, 3);
vec_xst(vec_packs(vec_packs(vi0, vi1), vec_packs(vi2, vi3)), 0, y[i].qs + 4*j);
}
}
#else
@@ -121,17 +120,16 @@ void quantize_row_q8_1(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, i
int32x4_t acc = vec_splats(0);
for (int j = 0; j < 8; j++) {
const float32x4_t v = vec_mul(srcv[j], vec_splats(id));
for (int j = 0; j < 8; j += 4) {
/* Uses non-default rounding for vec_signed or vec_round */
const int32x4_t vi = vec_signed(__builtin_s390_vfisb(v, 4, 1));
const int32x4_t vi0 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 0], vec_splats(id)), 4, 1));
const int32x4_t vi1 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 1], vec_splats(id)), 4, 1));
const int32x4_t vi2 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 2], vec_splats(id)), 4, 1));
const int32x4_t vi3 = vec_signed(__builtin_s390_vfisb(vec_mul(srcv[j + 3], vec_splats(id)), 4, 1));
y[i].qs[4*j + 0] = vec_extract(vi, 0);
y[i].qs[4*j + 1] = vec_extract(vi, 1);
y[i].qs[4*j + 2] = vec_extract(vi, 2);
y[i].qs[4*j + 3] = vec_extract(vi, 3);
vec_xst(vec_packs(vec_packs(vi0, vi1), vec_packs(vi2, vi3)), 0, y[i].qs + 4*j);
acc = vec_add(acc, vi);
acc = vec_add(acc, vec_add(vec_add(vi0, vi1), vec_add(vi2, vi3)));
}
y[i].s = GGML_CPU_FP32_TO_FP16(d * (acc[0] + acc[1] + acc[2] + acc[3]));
@@ -248,14 +246,9 @@ void ggml_vec_dot_q4_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int8x16_t v_yl = vec_xl(0 , y[ib].qs);
const int8x16_t v_yh = vec_xl(QK8_0/2, y[ib].qs);
const int16x8_t v_xylso = vec_mulo(v_xls, v_yl);
const int16x8_t v_xyl = vec_meadd(v_xls, v_yl, v_xylso);
const int16x8_t v_xyhso = vec_mulo(v_xhs, v_yh);
const int16x8_t v_xyh = vec_meadd(v_xhs, v_yh, v_xyhso);
const int16x8_t v_xy_ = ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_xls, v_yl), v_xhs, v_yh);
int16x8_t v_xy_ = v_xyl + v_xyh; v_xy_ += vec_reve(v_xy_);
const float32x4_t v_xy = vec_float(vec_unpackh(v_xy_));
const float32x4_t v_xy = vec_float(vec_paddl_s16(v_xy_));
const float32x4_t v_d = vec_splats(GGML_CPU_FP16_TO_FP32(x[ib].d) * GGML_CPU_FP16_TO_FP32(y[ib].d));
acc = vec_madd(v_xy, v_d, acc);
@@ -298,9 +291,6 @@ void ggml_vec_dot_q4_1_q8_1(int n, float * GGML_RESTRICT s, size_t bs, const voi
#pragma GCC unroll 4
for (; ib < nb; ++ib) {
__builtin_prefetch(x[ib].qs, 0, 1);
__builtin_prefetch(y[ib].qs, 0, 1);
summs += GGML_CPU_FP16_TO_FP32(x[ib].m) * GGML_CPU_FP16_TO_FP32(y[ib].s);
const uint8x16_t v_x = vec_xl(0, x[ib].qs);
@@ -310,8 +300,8 @@ void ggml_vec_dot_q4_1_q8_1(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int8x16_t v_yl = vec_xl(0 , y[ib].qs);
const int8x16_t v_yh = vec_xl(QK8_1/2, y[ib].qs);
const int32x4_t v_xy_ = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_xl, v_yl), v_xh, v_yh);
const float32x4_t v_xy = vec_float(v_xy_);
const int16x8_t v_xy_ = ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_xl, v_yl), v_xh, v_yh);
const float32x4_t v_xy = vec_float(vec_paddl_s16(v_xy_));
const float32x4_t v_d = vec_splats(GGML_CPU_FP16_TO_FP32(x[ib].d) * GGML_CPU_FP16_TO_FP32(y[ib].d));
@@ -379,8 +369,8 @@ void ggml_vec_dot_mxfp4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
const int8x16_t v_y1l = vec_xl(0, y1->qs);
const int8x16_t v_y1h = vec_xl(QK8_0/2, y1->qs);
const int32x4_t v_xy0 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x0l, v_y0l), v_x0h, v_y0h);
const int32x4_t v_xy1 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x1l, v_y1l), v_x1h, v_y1h);
const int32x4_t v_xy0 = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_x0l, v_y0l), v_x0h, v_y0h));
const int32x4_t v_xy1 = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_x1l, v_y1l), v_x1h, v_y1h));
const float32x4_t v_xy0f = vec_float(v_xy0);
const float32x4_t v_xy1f = vec_float(v_xy1);
@@ -407,7 +397,7 @@ void ggml_vec_dot_mxfp4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
const int8x16_t v_yl = vec_xl(0, y0->qs);
const int8x16_t v_yh = vec_xl(QK8_0/2, y0->qs);
const int32x4_t v_xy = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_xl, v_yl), v_xh, v_yh);
const int32x4_t v_xy = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_xl, v_yl), v_xh, v_yh));
const float32x4_t v_xyf = vec_float(v_xy);
const float32x4_t v_d = vec_splats(GGML_E8M0_TO_FP32_HALF(x0->e) * GGML_CPU_FP16_TO_FP32(y0->d));
@@ -502,8 +492,8 @@ void ggml_vec_dot_q5_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int8x16_t v_y1l = vec_xl(0, (const int8_t *)y1->qs);
const int8x16_t v_y1h = vec_xl(QK8_0/2, (const int8_t *)y1->qs);
const int32x4_t v_xy0 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x0lf, v_y0l), v_x0hf, v_y0h);
const int32x4_t v_xy1 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x1lf, v_y1l), v_x1hf, v_y1h);
const int32x4_t v_xy0 = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_x0lf, v_y0l), v_x0hf, v_y0h));
const int32x4_t v_xy1 = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_x1lf, v_y1l), v_x1hf, v_y1h));
const float32x4_t v_xy0f = vec_float(v_xy0);
const float32x4_t v_xy1f = vec_float(v_xy1);
@@ -548,7 +538,7 @@ void ggml_vec_dot_q5_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int8x16_t v_yl = vec_xl(0, (const int8_t *)y0->qs);
const int8x16_t v_yh = vec_xl(QK8_0/2, (const int8_t *)y0->qs);
const int32x4_t v_xy = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_xlf, v_yl), v_xhf, v_yh);
const int32x4_t v_xy = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_xlf, v_yl), v_xhf, v_yh));
const float32x4_t v_xyf = vec_float(v_xy);
const float32x4_t v_d = vec_splats(GGML_CPU_FP16_TO_FP32(x0->d) * GGML_CPU_FP16_TO_FP32(y0->d));
@@ -653,8 +643,8 @@ void ggml_vec_dot_q5_1_q8_1(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int8x16_t v_y1l = vec_xl(0 , y1->qs);
const int8x16_t v_y1h = vec_xl(QK8_1/2, y1->qs);
const int32x4_t v_xy0 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x0lf, v_y0l), v_x0hf, v_y0h);
const int32x4_t v_xy1 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x1lf, v_y1l), v_x1hf, v_y1h);
const int32x4_t v_xy0 = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_x0lf, v_y0l), v_x0hf, v_y0h));
const int32x4_t v_xy1 = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_x1lf, v_y1l), v_x1hf, v_y1h));
const float32x4_t v_xy0f = vec_float(v_xy0);
const float32x4_t v_xy1f = vec_float(v_xy1);
@@ -701,7 +691,7 @@ void ggml_vec_dot_q5_1_q8_1(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int8x16_t v_yl = vec_xl(0 , y0->qs);
const int8x16_t v_yh = vec_xl(QK8_1/2, y0->qs);
const int32x4_t v_xy = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_xlf, v_yl), v_xhf, v_yh);
const int32x4_t v_xy = vec_paddl_s16(ggml_vec_dot_s16(ggml_vec_dot_s16(vec_splats((int16_t)0), v_xlf, v_yl), v_xhf, v_yh));
const float32x4_t v_xyf = vec_float(v_xy);
const float32x4_t v_d = vec_splats(GGML_CPU_FP16_TO_FP32(x0->d) * GGML_CPU_FP16_TO_FP32(y0->d));
@@ -743,9 +733,6 @@ void ggml_vec_dot_q8_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const voi
#pragma GCC unroll 8
for (; ib < nb; ++ib) {
__builtin_prefetch(x[ib].qs, 0, 1);
__builtin_prefetch(y[ib].qs, 0, 1);
const int8x16_t v_xl = vec_xl(0 , x[ib].qs);
const int8x16_t v_xh = vec_xl(QK8_0/2, x[ib].qs);
const int8x16_t v_yl = vec_xl(0 , y[ib].qs);
@@ -791,7 +778,7 @@ void ggml_vec_dot_q3_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
uint32_t aux[3];
uint32_t utmp[4];
const int32x4_t v_z = vec_splat_s32(0);
const int16x8_t v_z = vec_splat_s16(0);
const uint8x16_t v_3m = vec_splat_u8(0x03);
const uint8x16_t v_0c = vec_splat_u8(1);
@@ -817,7 +804,7 @@ void ggml_vec_dot_q3_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
qhbits[0] = vec_xl(0 , x0h);
qhbits[1] = vec_xl(16, x0h);
int32_t isum = 0;
int32x4_t v_isum = vec_splat_s32(0);
memcpy(aux, x[i].scales, 12);
utmp[3] = ((aux[1] >> 4) & kmask2) | (((aux[2] >> 6) & kmask1) << 4);
@@ -825,11 +812,12 @@ void ggml_vec_dot_q3_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
utmp[1] = (aux[1] & kmask2) | (((aux[2] >> 2) & kmask1) << 4);
utmp[0] = (aux[0] & kmask2) | (((aux[2] >> 0) & kmask1) << 4);
int8_t * scale = (int8_t *)utmp;
for (int j = 0; j < 16; ++j) scale[j] -= 32;
const int8x16_t v_scale = vec_sub(vec_xl(0, (const int8_t *)utmp), vec_splats((int8_t)32));
const int16x8_t v_scalel = vec_unpackh(v_scale);
const int16x8_t v_scaleh = vec_unpackl(v_scale);
for (int j = 0; j < QK_K/128; ++j) {
int32x4_t isum0, isum1, isum2, isum3;
const int16x8_t v_scales = j == 0 ? v_scalel : v_scaleh;
q3b[0] = vec_xl(0 , x0l);
q3b[1] = vec_xl(16, x0l);
@@ -855,17 +843,10 @@ void ggml_vec_dot_q3_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
q3bytes[2] = vec_sub((int8x16_t)vec_and(vec_sr(q3b[0], 2), v_3m), (int8x16_t)q3h[2]);
q3bytes[3] = vec_sub((int8x16_t)vec_and(vec_sr(q3b[1], 2), v_3m), (int8x16_t)q3h[3]);
isum0 = ggml_vec_dot_s32(v_z, q3bytes[0], q8bytes[0]);
isum1 = ggml_vec_dot_s32(v_z, q3bytes[1], q8bytes[1]);
isum2 = ggml_vec_dot_s32(v_z, q3bytes[2], q8bytes[2]);
isum3 = ggml_vec_dot_s32(v_z, q3bytes[3], q8bytes[3]);
isum += (isum0[0] + isum0[1] + isum0[2] + isum0[3]) * scale[0];
isum += (isum1[0] + isum1[1] + isum1[2] + isum1[3]) * scale[1];
isum += (isum2[0] + isum2[1] + isum2[2] + isum2[3]) * scale[2];
isum += (isum3[0] + isum3[1] + isum3[2] + isum3[3]) * scale[3];
scale += 4;
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[0], q8bytes[0]), vec_splat(v_scales, 0)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[1], q8bytes[1]), vec_splat(v_scales, 1)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[2], q8bytes[2]), vec_splat(v_scales, 2)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[3], q8bytes[3]), vec_splat(v_scales, 3)));
q3h[0] = vec_andc(v_2c, qhbits[0]);
q3h[1] = vec_andc(v_2c, qhbits[1]);
@@ -877,17 +858,10 @@ void ggml_vec_dot_q3_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
q3bytes[2] = vec_sub((int8x16_t)vec_and(vec_sr(q3b[0], 6), v_3m), (int8x16_t)q3h[2]);
q3bytes[3] = vec_sub((int8x16_t)vec_and(vec_sr(q3b[1], 6), v_3m), (int8x16_t)q3h[3]);
isum0 = ggml_vec_dot_s32(v_z, q3bytes[0], q8bytes[4]);
isum1 = ggml_vec_dot_s32(v_z, q3bytes[1], q8bytes[5]);
isum2 = ggml_vec_dot_s32(v_z, q3bytes[2], q8bytes[6]);
isum3 = ggml_vec_dot_s32(v_z, q3bytes[3], q8bytes[7]);
isum += vec_hsum_i32x4(isum0) * scale[0];
isum += vec_hsum_i32x4(isum1) * scale[1];
isum += vec_hsum_i32x4(isum2) * scale[2];
isum += vec_hsum_i32x4(isum3) * scale[3];
scale += 4;
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[0], q8bytes[4]), vec_splat(v_scales, 4)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[1], q8bytes[5]), vec_splat(v_scales, 5)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[2], q8bytes[6]), vec_splat(v_scales, 6)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q3bytes[3], q8bytes[7]), vec_splat(v_scales, 7)));
if (j == 0) {
qhbits[0] = vec_sr(qhbits[0], 4);
@@ -895,7 +869,7 @@ void ggml_vec_dot_q3_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
}
}
sum += d * isum;
sum += d * vec_hsum_i32x4(v_isum);
}
*s = sum;
@@ -931,7 +905,7 @@ void ggml_vec_dot_q4_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
#if defined(__VXE__) || defined(__VXE2__)
const uint8x16_t v_lm = vec_splat_u8(0x0F);
const int32x4_t v_z = vec_splat_s32(0);
const int16x8_t v_z = vec_splat_s16(0);
uint8x16_t v_x[2];
int8x16_t v_xl[2];
@@ -966,8 +940,7 @@ void ggml_vec_dot_q4_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
const uint8_t * GGML_RESTRICT x0 = x[i].qs;
const int8_t * GGML_RESTRICT y0 = y[i].qs;
int32_t sumi1 = 0;
int32_t sumi2 = 0;
int32x4_t v_sumi = vec_splat_s32(0);
for (int j = 0; j < QK_K/64; ++j) {
v_x[0] = vec_xl(0 , x0);
@@ -981,8 +954,8 @@ void ggml_vec_dot_q4_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
v_xl[0] = (int8x16_t)vec_and(v_x[0], v_lm);
v_xl[1] = (int8x16_t)vec_and(v_x[1], v_lm);
const int32x4_t p1 = ggml_vec_dot_s32(ggml_vec_dot_s32(v_z, v_xl[0], v_y[0]), v_xl[1], v_y[1]);
sumi1 += vec_hsum_i32x4(p1) * scales[2*j+0];
const int16x8_t v_p1 = ggml_vec_dot_s16(ggml_vec_dot_s16(v_z, v_xl[0], v_y[0]), v_xl[1], v_y[1]);
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(v_p1, vec_splats((int16_t)scales[2*j+0])));
v_y[0] = vec_xl(0 , y0);
v_y[1] = vec_xl(16, y0);
@@ -991,11 +964,11 @@ void ggml_vec_dot_q4_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
v_xl[0] = (int8x16_t)vec_sr(v_x[0], 4);
v_xl[1] = (int8x16_t)vec_sr(v_x[1], 4);
const int32x4_t p2 = ggml_vec_dot_s32(ggml_vec_dot_s32(v_z, v_xl[0], v_y[0]), v_xl[1], v_y[1]);
sumi2 += vec_hsum_i32x4(p2) * scales[2*j+1];
const int16x8_t v_p2 = ggml_vec_dot_s16(ggml_vec_dot_s16(v_z, v_xl[0], v_y[0]), v_xl[1], v_y[1]);
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(v_p2, vec_splats((int16_t)scales[2*j+1])));
}
sumf += d * (sumi1 + sumi2);
sumf += d * vec_hsum_i32x4(v_sumi);
}
*s = sumf;
@@ -1036,7 +1009,7 @@ void ggml_vec_dot_q5_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
const uint8x16_t v_1m = vec_splat_u8(0x01);
const uint8x16_t v_2m = vec_splat_u8(0x02);
const int32x4_t v_z = vec_splat_s32(0);
const int16x8_t v_z = vec_splat_s16(0);
const uchar8x16_t v_minsm = {
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
@@ -1083,7 +1056,7 @@ void ggml_vec_dot_q5_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
v_xh[0] = vec_xl(0 , x0h);
v_xh[1] = vec_xl(16, x0h);
int32_t sumi = 0;
int32x4_t v_sumi = vec_splat_s32(0);
for (int j = 0; j < QK_K/64; ++j) {
v_xl[0] = vec_xl(0 , x0l);
v_xl[1] = vec_xl(16, x0l);
@@ -1107,14 +1080,14 @@ void ggml_vec_dot_q5_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
q5b[2] = (int8x16_t)vec_or(vec_sr(v_xl[0], 4), q5h[2]);
q5b[3] = (int8x16_t)vec_or(vec_sr(v_xl[1], 4), q5h[3]);
int32x4_t sumi0 = ggml_vec_dot_s32(ggml_vec_dot_s32(v_z, q5b[0], v_y[0]), q5b[1], v_y[1]);
int32x4_t sumi1 = ggml_vec_dot_s32(ggml_vec_dot_s32(v_z, q5b[2], v_y[2]), q5b[3], v_y[3]);
const int16x8_t v_p0 = ggml_vec_dot_s16(ggml_vec_dot_s16(v_z, q5b[0], v_y[0]), q5b[1], v_y[1]);
const int16x8_t v_p1 = ggml_vec_dot_s16(ggml_vec_dot_s16(v_z, q5b[2], v_y[2]), q5b[3], v_y[3]);
sumi += vec_hsum_i32x4(sumi0) * *scales++;
sumi += vec_hsum_i32x4(sumi1) * *scales++;
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(v_p0, vec_splats((int16_t)*scales++)));
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(v_p1, vec_splats((int16_t)*scales++)));
}
sumf += d * sumi - dmin * mins;
sumf += d * vec_hsum_i32x4(v_sumi) - dmin * mins;
}
*s = sumf;
@@ -1151,7 +1124,7 @@ void ggml_vec_dot_q6_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
const uint8x16_t v_lm = vec_splat_u8(0x0F);
const uint8x16_t v_um = vec_splat_u8(0x03);
const int32x4_t v_z = vec_splat_s32(0);
const int16x8_t v_z = vec_splat_s16(0);
int8x16_t q6b[4];
uint8x16_t q6h[4];
@@ -1167,12 +1140,10 @@ void ggml_vec_dot_q6_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
const uint8_t * GGML_RESTRICT x0h = x[i].qh;
const int8_t * GGML_RESTRICT y0 = y[i].qs;
const int8_t * GGML_RESTRICT scale = x[i].scales;
const int16x8_t v_ysumsl = vec_xl(0 , y[i].bsums);
const int16x8_t v_ysumsh = vec_xl(16, y[i].bsums);
const int8x16_t v_scale = vec_xl(0, scale);
const int8x16_t v_scale = vec_xl(0, x[i].scales);
const int16x8_t v_scalel = vec_unpackh(v_scale);
const int16x8_t v_scaleh = vec_unpackl(v_scale);
@@ -1182,10 +1153,10 @@ void ggml_vec_dot_q6_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
const int32x4_t v_minsh = vec_meadd(v_ysumsh, v_scaleh, v_minsho);
const int32x4_t v_mins = vec_add(v_minsl, v_minsh);
const int32_t mins = vec_hsum_i32x4(v_mins);
int32_t isum = 0;
int32x4_t v_isum = vec_splat_s32(0);
for (int j = 0; j < QK_K/128; ++j) {
const int16x8_t v_scales = j == 0 ? v_scalel : v_scaleh;
// Load model upper 2 bits
v_xh[0] = vec_xl(0 , x0h);
v_xh[1] = vec_xl(16, x0h);
@@ -1217,18 +1188,10 @@ void ggml_vec_dot_q6_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
q6b[2] = (int8x16_t)(vec_or(vec_and(v_xl[2], v_lm), q6h[2]));
q6b[3] = (int8x16_t)(vec_or(vec_and(v_xl[3], v_lm), q6h[3]));
int32x4_t summs0 = ggml_vec_dot_s32(v_z, q6b[0], v_y[0]);
int32x4_t summs1 = ggml_vec_dot_s32(v_z, q6b[1], v_y[1]);
int32x4_t summs2 = ggml_vec_dot_s32(v_z, q6b[2], v_y[2]);
int32x4_t summs3 = ggml_vec_dot_s32(v_z, q6b[3], v_y[3]);
isum += vec_hsum_i32x4(summs0) * scale[0] +
vec_hsum_i32x4(summs1) * scale[1] +
vec_hsum_i32x4(summs2) * scale[2] +
vec_hsum_i32x4(summs3) * scale[3];
scale += 4;
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[0], v_y[0]), vec_splat(v_scales, 0)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[1], v_y[1]), vec_splat(v_scales, 1)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[2], v_y[2]), vec_splat(v_scales, 2)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[3], v_y[3]), vec_splat(v_scales, 3)));
// Load activation quants
v_y[0] = vec_xl(0 , y0);
@@ -1251,20 +1214,15 @@ void ggml_vec_dot_q6_K_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const voi
q6b[2] = (int8x16_t)(vec_or(vec_sr(v_xl[2], 4), q6h[2]));
q6b[3] = (int8x16_t)(vec_or(vec_sr(v_xl[3], 4), q6h[3]));
summs0 = ggml_vec_dot_s32(v_z, q6b[0], v_y[0]);
summs1 = ggml_vec_dot_s32(v_z, q6b[1], v_y[1]);
summs2 = ggml_vec_dot_s32(v_z, q6b[2], v_y[2]);
summs3 = ggml_vec_dot_s32(v_z, q6b[3], v_y[3]);
isum += vec_hsum_i32x4(summs0) * scale[0] +
vec_hsum_i32x4(summs1) * scale[1] +
vec_hsum_i32x4(summs2) * scale[2] +
vec_hsum_i32x4(summs3) * scale[3];
scale += 4;
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[0], v_y[0]), vec_splat(v_scales, 4)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[1], v_y[1]), vec_splat(v_scales, 5)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[2], v_y[2]), vec_splat(v_scales, 6)));
v_isum = vec_add(v_isum, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, q6b[3], v_y[3]), vec_splat(v_scales, 7)));
}
sum += d_all * y[i].d * (isum - 32 * mins);
v_isum = vec_sub(v_isum, vec_sl(v_mins, 5));
sum += d_all * y[i].d * vec_hsum_i32x4(v_isum);
}
*s = sum;
@@ -1477,6 +1435,7 @@ void ggml_vec_dot_iq4_xs_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const v
#if defined(__VXE__) || defined(__VXE2__)
const int8x16_t v_k = vec_xl(0, kvalues_iq4nl);
const uint8x16_t v_m = vec_splat_u8(0x0F);
const int16x8_t v_z = vec_splat_s16(0);
float sumf = 0;
@@ -1486,7 +1445,7 @@ void ggml_vec_dot_iq4_xs_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const v
uint16_t h = x[ibl].scales_h;
int sumi1 = 0, sumi2 = 0;
int32x4_t v_sumi = vec_splat_s32(0);
for (int ib = 0; ib < QK_K/64; ++ib) {
const uint8x16_t v_x0 = vec_xl(0 , q4);
const uint8x16_t v_x1 = vec_xl(QK4_NL/2, q4);
@@ -1508,19 +1467,21 @@ void ggml_vec_dot_iq4_xs_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const v
const int8x16_t v_y3 = vec_xl(48, q8);
q8 += 64;
int32x4_t vsumi0 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x0l, v_y0), v_x0h, v_y1);
int32x4_t vsumi1 = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_x1l, v_y2), v_x1h, v_y3);
int ls1 = ((x[ibl].scales_l[ib] & 0xF) | ((h << 4) & 0x30)) - 32;
int ls2 = ((x[ibl].scales_l[ib] >> 4) | ((h << 2) & 0x30)) - 32;
h >>= 4;
sumi1 += vec_hsum_i32x4(vsumi0) * ls1;
sumi2 += vec_hsum_i32x4(vsumi1) * ls2;
const int16x8_t v_ls1 = vec_splats((int16_t)ls1);
const int16x8_t v_ls2 = vec_splats((int16_t)ls2);
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, v_x0l, v_y0), v_ls1));
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, v_x0h, v_y1), v_ls1));
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, v_x1l, v_y2), v_ls2));
v_sumi = vec_add(v_sumi, ggml_vec_madd_s16(ggml_vec_dot_s16(v_z, v_x1h, v_y3), v_ls2));
}
sumf += GGML_CPU_FP16_TO_FP32(x[ibl].d) * y[ibl].d * (sumi1 + sumi2);
sumf += GGML_CPU_FP16_TO_FP32(x[ibl].d) * y[ibl].d * vec_hsum_i32x4(v_sumi);
}
*s = sumf;
+23 -17
View File
@@ -112,17 +112,20 @@ void ggml_gemv_q4_0_4x4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
const int8_t * y_lo = a_ptr[l].qs;
const int8_t * y_hi = y_lo + qk / 2;
int16x8_t v_sumi = vec_splats((int16_t)0);
const int16x8_t v_zero = vec_splats((int16_t)0);
v_sumi = ggml_vec_dot_s16(v_sumi, v_x0l, ggml_vec_xl_s8x4_splat(y_lo + 0));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x1l, ggml_vec_xl_s8x4_splat(y_lo + 4));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x2l, ggml_vec_xl_s8x4_splat(y_lo + 8));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x3l, ggml_vec_xl_s8x4_splat(y_lo + 12));
// separate sums, a long multiply-add chain is slow
int16x8_t v_sumi0 = ggml_vec_dot_s16(v_zero, v_x0l, ggml_vec_xl_s8x4_splat(y_lo + 0));
int16x8_t v_sumi1 = ggml_vec_dot_s16(v_zero, v_x1l, ggml_vec_xl_s8x4_splat(y_lo + 4));
int16x8_t v_sumi2 = ggml_vec_dot_s16(v_zero, v_x2l, ggml_vec_xl_s8x4_splat(y_lo + 8));
int16x8_t v_sumi3 = ggml_vec_dot_s16(v_zero, v_x3l, ggml_vec_xl_s8x4_splat(y_lo + 12));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x0h, ggml_vec_xl_s8x4_splat(y_hi + 0));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x1h, ggml_vec_xl_s8x4_splat(y_hi + 4));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x2h, ggml_vec_xl_s8x4_splat(y_hi + 8));
v_sumi = ggml_vec_dot_s16(v_sumi, v_x3h, ggml_vec_xl_s8x4_splat(y_hi + 12));
v_sumi0 = ggml_vec_dot_s16(v_sumi0, v_x0h, ggml_vec_xl_s8x4_splat(y_hi + 0));
v_sumi1 = ggml_vec_dot_s16(v_sumi1, v_x1h, ggml_vec_xl_s8x4_splat(y_hi + 4));
v_sumi2 = ggml_vec_dot_s16(v_sumi2, v_x2h, ggml_vec_xl_s8x4_splat(y_hi + 8));
v_sumi3 = ggml_vec_dot_s16(v_sumi3, v_x3h, ggml_vec_xl_s8x4_splat(y_hi + 12));
const int16x8_t v_sumi = vec_add(vec_add(v_sumi0, v_sumi1), vec_add(v_sumi2, v_sumi3));
const float32x4_t v_yd = vec_splats(GGML_CPU_FP16_TO_FP32(a_ptr[l].d));
const float32x4_t v_xd = ggml_vec_xl_f16x4_finite(b_ptr[l].d);
@@ -162,6 +165,8 @@ void ggml_gemm_q4_0_4x4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
}
for (int l = 0; l < nb; l++) {
const int16x8_t v_zero = vec_splats((int16_t)0);
int16x8_t v_sumi0 = vec_splats((int16_t)0);
int16x8_t v_sumi1 = vec_splats((int16_t)0);
int16x8_t v_sumi2 = vec_splats((int16_t)0);
@@ -175,15 +180,16 @@ void ggml_gemm_q4_0_4x4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
const int8_t * y_lo = a_ptr[l].qs + 16 * k;
const int8_t * y_hi = y_lo + qk / 2 * 4;
v_sumi0 = ggml_vec_dot_s16(v_sumi0, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 0));
v_sumi1 = ggml_vec_dot_s16(v_sumi1, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 4));
v_sumi2 = ggml_vec_dot_s16(v_sumi2, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 8));
v_sumi3 = ggml_vec_dot_s16(v_sumi3, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 12));
// add each product pair with vec_add, a long multiply-add chain is slow
const int16x8_t v_xyl0 = ggml_vec_dot_s16(v_zero, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 0));
const int16x8_t v_xyl1 = ggml_vec_dot_s16(v_zero, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 4));
const int16x8_t v_xyl2 = ggml_vec_dot_s16(v_zero, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 8));
const int16x8_t v_xyl3 = ggml_vec_dot_s16(v_zero, v_xl, ggml_vec_xl_s8x4_splat(y_lo + 12));
v_sumi0 = ggml_vec_dot_s16(v_sumi0, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 0));
v_sumi1 = ggml_vec_dot_s16(v_sumi1, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 4));
v_sumi2 = ggml_vec_dot_s16(v_sumi2, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 8));
v_sumi3 = ggml_vec_dot_s16(v_sumi3, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 12));
v_sumi0 = vec_add(v_sumi0, ggml_vec_dot_s16(v_xyl0, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 0)));
v_sumi1 = vec_add(v_sumi1, ggml_vec_dot_s16(v_xyl1, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 4)));
v_sumi2 = vec_add(v_sumi2, ggml_vec_dot_s16(v_xyl2, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 8)));
v_sumi3 = vec_add(v_sumi3, ggml_vec_dot_s16(v_xyl3, v_xh, ggml_vec_xl_s8x4_splat(y_hi + 12)));
}
const float32x4_t v_yd = __lzs_f16cx4_load(a_ptr[l].d);
+8 -3
View File
@@ -487,7 +487,7 @@ inline static int16x8_t vec_padd_s16(int16x8_t a, int16x8_t b) {
inline static int32x4_t vec_paddl_s16(int16x8_t a) {
const int16x8_t v_ones = vec_splats((int16_t)1);
return vec_mule(a, v_ones) + vec_mulo(a, v_ones);
return vec_meadd(a, v_ones, vec_mulo(a, v_ones));
}
/**
@@ -507,9 +507,14 @@ inline static int16x8_t ggml_vec_dot_s16(int16x8_t acc, int8x16_t a, int8x16_t b
return vec_meadd(a, b, vec_moadd(a, b, acc));
}
// a * b, each pair of 16-bit products summed into one 32-bit lane
inline static int32x4_t ggml_vec_madd_s16(int16x8_t a, int16x8_t b) {
return vec_meadd(a, b, vec_mulo(a, b));
}
inline static int32x4_t ggml_vec_dot_s32(int32x4_t acc, int8x16_t a, int8x16_t b) {
const int16x8_t p = vec_mule(a, b) + vec_mulo(a, b);
return acc + (vec_unpackh(p) + vec_unpackl(p));
const int16x8_t p = vec_meadd(a, b, vec_mulo(a, b));
return acc + ggml_vec_madd_s16(p, vec_splats((int16_t)1));
}
#endif
+1 -1
View File
@@ -442,7 +442,7 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
switch (op->op) {
case GGML_OP_FLASH_ATTN_EXT:
return ggml_validate_flash_attn_ext_indexed_bias(op);
return !ggml_flash_attn_ext_has_bias(op) || ggml_flash_attn_ext_bias_is_indexed(op);
case GGML_OP_CPY:
case GGML_OP_SET_ROWS:
return
+2 -4
View File
@@ -1380,10 +1380,8 @@ class tinyBLAS_Q0_VXE {
static constexpr bool has_min = std::is_same<TB, block_q8_1>::value;
static int32x4_t dot_s8_wide(int8x16_t v_x, int8x16_t v_y) {
const int16x8_t v_even = vec_mule(v_x, v_y);
const int16x8_t v_odd = vec_mulo(v_x, v_y);
// Two (-128) * (-128) products can overflow a signed 16-bit sum.
return vec_unpackh(v_even) + vec_unpackl(v_even) + vec_unpackh(v_odd) + vec_unpackl(v_odd);
// v_y is never -128, so the sum of two products fits in 16 bits
return vec_paddl_s16(vec_meadd(v_x, v_y, vec_mulo(v_x, v_y)));
}
static int32x4_t dot(int8x16_t v_xl, int8x16_t v_xh, int8x16_t v_yl, int8x16_t v_yh) {
+15 -15
View File
@@ -8981,8 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * sinks = dst->src[4];
const ggml_tensor * kv_rows = dst->src[5];
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
const ggml_tensor * bias = dst->src[6];
const ggml_tensor * bias_idxs = dst->src[7];
GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
@@ -9024,7 +9024,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int64_t rv2 = neq2/nev2;
const int64_t rv3 = neq3/nev3;
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
const int64_t n_bins = bias ? bias->ne[0] : 0;
// parallelize by q rows using ggml_vec_dot_f32
@@ -9090,8 +9090,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr;
// bias rows of this query and head, queries of all streams are flattened
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr;
const float * bias_row = bias ? (const float *) ((const char *) bias->data + (iq3*neq1 + iq1)*bias->nb[2] + iq2*bias->nb[1]) : nullptr;
const int32_t * bins = bias_idxs ? (const int32_t *) ((const char *) bias_idxs->data + (iq3*neq1 + iq1)*bias_idxs->nb[1]) : nullptr;
// online softmax / attention
// loop over n_kv and n_head_kv
@@ -9099,9 +9099,9 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
for (int64_t ic = ic_start; ic < ic_end; ++ic) {
float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
if (bias) {
if (bias_row) {
GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins);
mv += bias[bins[ic]];
mv += bias_row[bins[ic]];
}
mv *= slope;
if (mv == -INFINITY) {
@@ -9281,9 +9281,9 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
const ggml_tensor * kv_rows = dst->src[5];
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1;
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
const ggml_tensor * bias = dst->src[6];
const ggml_tensor * bias_idxs = dst->src[7];
const int64_t n_bins = bias ? bias->ne[0] : 0;
int ir = ir0;
while (ir < ir1) {
@@ -9363,13 +9363,13 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
bool can_skip = true;
for (int tq = 0; tq < tile_rows; tq++) {
const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]);
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr;
const float * bias_row = bias ? (const float *) ((const char *) bias->data + (iq3*neq1 + iq1 + tq)*bias->nb[2] + iq2*bias->nb[1]) : nullptr;
const int32_t * bins = bias_idxs ? (const int32_t *) ((const char *) bias_idxs->data + (iq3*neq1 + iq1 + tq)*bias_idxs->nb[1]) : nullptr;
for (int tk = 0; tk < kv_tile; tk++) {
float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
if (bias) {
if (bias_row) {
GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins);
m += bias[bins[ic + tk]];
m += bias_row[bins[ic + tk]];
}
mask32[tq * KV_TILE_SZ + tk] = slope * m;
if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) {
@@ -9722,7 +9722,7 @@ static void ggml_compute_forward_flash_attn_ext_f16(
void ggml_compute_forward_flash_attn_ext(
const ggml_compute_params * params,
ggml_tensor * dst) {
GGML_ASSERT(ggml_validate_flash_attn_ext_indexed_bias(dst));
GGML_ASSERT(!ggml_flash_attn_ext_has_bias(dst) || ggml_flash_attn_ext_bias_is_indexed(dst));
switch (ggml_prec_get_acc(dst)) {
case GGML_PREC_UNDEFINED:
case GGML_PREC_F32:
+2 -2
View File
@@ -1047,8 +1047,8 @@ class tensor_traits_common : public tensor_traits_base {
return true;
}
case GGML_OP_FLASH_ATTN_EXT:
// K/V row lists and the indexed bias are handled by the generic CPU path
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
// K/V row lists and bias are handled by the generic CPU path
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_bias(op)) {
return false;
}
forward_flash_attn_ext_f16(params, op);
+47 -18
View File
@@ -517,35 +517,64 @@ struct ggml_cuda_unroll<1> {
}
};
template<int width = WARP_SIZE>
// If only_lane0_is_used is set to true, then the performance can be better but only lane 0 is guaranteed to have the correct result.
template<typename T, int width, bool only_lane0_is_used = false>
static __device__ __forceinline__ T warp_reduce_sum_impl(T x) {
#if defined(GGML_USE_HIP)
if constexpr (width <= 64 && width <= ggml_cuda_get_physical_warp_size()) {
static_assert(width >= 2 && width <= 64 && (width & (width - 1)) == 0, "width must be a power of two between 2 and 64");
x += ggml_hip_dpp_update<GGML_HIP_DPP_QUAD_PERM_1032>(x);
if constexpr (width >= 4) {
x += ggml_hip_dpp_update<GGML_HIP_DPP_QUAD_PERM_2301>(x);
}
if constexpr (width >= 8) {
x += ggml_hip_dpp_update<GGML_HIP_DPP_ROW_HALF_MIRROR>(x);
}
if constexpr (width >= 16) {
x += ggml_hip_dpp_update<GGML_HIP_DPP_ROW_ROR_8>(x);
}
if constexpr (width == 64) {
x += ggml_hip_dpp_update<GGML_HIP_DPP_ROW_BCAST_15>(x);
x += ggml_hip_dpp_update<GGML_HIP_DPP_ROW_BCAST_31>(x);
if constexpr (only_lane0_is_used) {
return ggml_hip_dpp_update<GGML_HIP_DPP_WAVE_ROR_1>(x);
} else {
return ggml_cuda_shfl(x, 63, 64);
}
}
if constexpr (width == 32) {
return x + ggml_hip_swizzle<GGML_HIP_SWIZZLE_SWAP16>(x);
}
return x;
} else
#endif // defined(GGML_USE_HIP)
{
#pragma unroll
for (int offset = width/2; offset > 0; offset >>= 1) {
x += ggml_cuda_shfl_xor(x, offset, width);
}
return x;
}
}
template<int width = WARP_SIZE, bool only_lane0_is_used = false>
static __device__ __forceinline__ int warp_reduce_sum(int x) {
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
return __reduce_add_sync(GGML_CUDA_FULL_THREAD_MASK, x);
#else
#pragma unroll
for (int offset = width/2; offset > 0; offset >>= 1) {
x += ggml_cuda_shfl_xor(x, offset, width);
}
return x;
return warp_reduce_sum_impl<int, width, only_lane0_is_used>(x);
#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
}
template<int width = WARP_SIZE>
template<int width = WARP_SIZE, bool only_lane0_is_used = false>
static __device__ __forceinline__ float warp_reduce_sum(float x) {
#pragma unroll
for (int offset = width/2; offset > 0; offset >>= 1) {
x += ggml_cuda_shfl_xor(x, offset, width);
}
return x;
return warp_reduce_sum_impl<float, width, only_lane0_is_used>(x);
}
template<int width = WARP_SIZE>
template<int width = WARP_SIZE, bool only_lane0_is_used = false>
static __device__ __forceinline__ float2 warp_reduce_sum(float2 a) {
#pragma unroll
for (int offset = width/2; offset > 0; offset >>= 1) {
a.x += ggml_cuda_shfl_xor(a.x, offset, width);
a.y += ggml_cuda_shfl_xor(a.y, offset, width);
}
a.x = warp_reduce_sum_impl<float, width, only_lane0_is_used>(a.x);
a.y = warp_reduce_sum_impl<float, width, only_lane0_is_used>(a.y);
return a;
}
+1 -1
View File
@@ -16,7 +16,7 @@ static __global__ void count_equal(const T * __restrict__ x, const T * __restric
nequal += xi == yi;
}
nequal = warp_reduce_sum(nequal);
nequal = warp_reduce_sum<WARP_SIZE, true>(nequal);
if (threadIdx.x != 0) {
return;
+1 -1
View File
@@ -40,7 +40,7 @@ static __global__ void cross_entropy_loss_f32(
const float logit_i = use_shared ? tmp[i] : logits[i];
loss += (logit_i - max_logit - sum) * labels[i];
}
loss = -warp_reduce_sum(loss) / (float)k;
loss = -warp_reduce_sum<WARP_SIZE, true>(loss) / (float)k;
if (threadIdx.x != 0) {
return;
+17 -17
View File
@@ -20,20 +20,20 @@
// 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)
struct fattn_indexed_bias {
const float * table;
const int32_t * indices;
struct fattn_bias_indexed {
const float * bias;
const int32_t * bias_idxs;
int64_t n_bins;
int64_t n_keys;
int64_t query_stride;
__device__ fattn_indexed_bias for_head(int64_t first_query, int head) const {
return {table + first_query*query_stride + head*n_bins, indices + first_query*n_keys, n_bins, n_keys, query_stride};
__device__ fattn_bias_indexed for_head(int64_t first_query, int head) const {
return {bias + first_query*query_stride + head*n_bins, bias_idxs + first_query*n_keys, n_bins, n_keys, query_stride};
}
__device__ float add(float mask, int query, int key) const {
const int bin = indices[query*n_keys + key];
return bin >= 0 && bin < n_bins ? mask + table[query*query_stride + bin] : mask;
const int bin = bias_idxs[query*n_keys + key];
return bin >= 0 && bin < n_bins ? mask + bias[query*query_stride + bin] : mask;
}
};
@@ -65,7 +65,7 @@ using fattn_kernel_t = void (*)(
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 s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias);
const fattn_bias_indexed bias);
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);
@@ -1324,9 +1324,9 @@ void launch_fattn(
const ggml_tensor * sinks = dst->src[4];
const ggml_tensor * kv_rows = dst->src[5];
const bool has_bias = ggml_flash_attn_ext_has_indexed_bias(dst);
const ggml_tensor * bias_table = has_bias ? dst->src[6] : nullptr;
const ggml_tensor * bias_indices = has_bias ? dst->src[7] : nullptr;
const bool bias_indexed = ggml_flash_attn_ext_bias_is_indexed(dst);
const ggml_tensor * bias = bias_indexed ? dst->src[6] : nullptr;
const ggml_tensor * bias_idxs = bias_indexed ? dst->src[7] : nullptr;
// with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1];
@@ -1461,7 +1461,7 @@ void launch_fattn(
// Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or
// multiple sequences of possibly different lengths, or kv_rows lists that end with padding.
// The scan reads ncols1 mask rows per tile, including the last tile.
const bool scan_mask = !has_bias && !use_sparse && mask && mask->ne[2] == 1 && mask->ne[1]/ncols1 >= ntiles_x &&
const bool scan_mask = !bias_indexed && !use_sparse && mask && mask->ne[2] == 1 && mask->ne[1]/ncols1 >= ntiles_x &&
n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
if (scan_mask) {
const int64_t s31 = mask->nb[1] / sizeof(half2);
@@ -1621,11 +1621,11 @@ void launch_fattn(
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,
fattn_indexed_bias{has_bias ? (const float *) bias_table->data : nullptr,
has_bias ? (const int32_t *) bias_indices->data : nullptr,
has_bias ? bias_table->ne[0] : 0,
has_bias ? bias_indices->ne[0] : 0,
has_bias ? bias_table->ne[0]*bias_table->ne[1] : 0}
fattn_bias_indexed{bias_indexed ? (const float *) bias->data : nullptr,
bias_indexed ? (const int32_t *) bias_idxs->data : nullptr,
bias_indexed ? bias->ne[0] : 0,
bias_indexed ? bias_idxs->ne[0] : 0,
bias_indexed ? bias->ne[0]*bias->ne[1] : 0}
);
CUDA_CHECK(cudaGetLastError());
+1 -1
View File
@@ -1866,7 +1866,7 @@ static __global__ void flash_attn_ext_f16(
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 s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
const fattn_bias_indexed bias) {
GGML_UNUSED(bias); // biased ops are never dispatched to the mma kernel
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))
+65 -29
View File
@@ -373,9 +373,21 @@ 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);
}
#ifdef GGML_USE_HIP
// The sparse launch pins ncols1 == 1, so the ncols2 parameter is the total number of Q columns per block.
static constexpr bool ggml_cuda_flash_attn_ext_tile_may_use_sparse(
const int DKQ, const int DV, const int ncols2, const bool use_logit_softcap) {
return DKQ > 64 && ncols2 > 1 && !use_logit_softcap &&
ggml_cuda_fattn_tile_get_config_amd(DKQ, DV, ncols2) != 0 &&
ggml_cuda_fattn_tile_get_config_amd_rdna(DKQ, DV, ncols2) != 0;
}
bool ggml_cuda_flash_attn_ext_tile_shall_use_sparse(const int cc, const ggml_tensor * dst, const int DKQ, const int DV);
#endif // GGML_USE_HIP
// 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, bool indexed_bias, typename T_vec_dot, typename T_K>
bool use_logit_softcap, bool oob_check, bool bias_indexed, bool use_sparse, typename T_vec_dot, typename T_K>
static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
T_vec_dot * const Q_tmp,
const T_K * const __restrict__ K_h2,
@@ -394,7 +406,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
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, indexed_bias, false, T_K, T_vec_dot>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, use_sparse, bias_indexed || use_sparse, 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, rows);
__syncthreads();
@@ -452,7 +464,7 @@ 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, bool indexed_bias, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
bool use_logit_softcap, bool oob_check, bool bias_indexed, bool use_sparse, 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 T_K * const __restrict__ K_h2,
@@ -472,7 +484,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
const int k_VKQ_0,
const int k_VKQ_max,
const int col_Q_0,
const fattn_indexed_bias bias,
const fattn_bias_indexed bias,
const int32_t * const __restrict__ rows) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
@@ -505,12 +517,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
constexpr int nbatch_K_last = DKQ % nbatch_K;
#pragma unroll
for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) {
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>(
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, bias_indexed, use_sparse>(
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
}
if (nbatch_K_last > 0) {
constexpr int k_KQ_0 = DKQ - nbatch_K_last;
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check, indexed_bias>(
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check, bias_indexed, use_sparse>(
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
}
@@ -534,11 +546,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
if (!oob_check || i_KQ < k_VKQ_sup) {
if (indexed_bias || ncols2 > 1 || mask) {
const int k = k_VKQ_0 + i_KQ;
if (bias_indexed || ncols2 > 1 || mask) {
const int k = use_sparse ? rows[k_VKQ_0 + i_KQ] : k_VKQ_0 + i_KQ;
__builtin_assume(k >= 0); // avoid sign extension and register spills on RDNA
const float m = __half2float(mask[int64_t(j)*stride_mask + k]);
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*(indexed_bias ? bias.add(m, j, k) : m);
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*(bias_indexed ? bias.add(m, j, k) : m);
}
KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET);
@@ -621,7 +633,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
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_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, indexed_bias, false, T_V, T_vec_dot>
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, use_sparse, bias_indexed || use_sparse, false, T_V, T_vec_dot>
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, rows);
__syncthreads();
@@ -691,7 +703,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool indexed_bias, ggml_type type_K, ggml_type type_V, bool use_kv_rows> // D == head size
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool bias_indexed, ggml_type type_K, ggml_type type_V, bool use_kv_rows, bool use_sparse = false> // 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 float2 * Q_ptr,
@@ -716,7 +728,7 @@ static __global__ void flash_attn_tile(
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 s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
const fattn_bias_indexed bias) {
#ifdef FLASH_ATTN_AVAILABLE
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
@@ -732,6 +744,15 @@ static __global__ void flash_attn_tile(
// Skip unused kernel variants for faster compilation:
#ifndef GCN
if constexpr (use_sparse) {
NO_DEVICE_CODE;
return;
}
#endif // GCN
static_assert(!use_sparse || (ncols1 == 1 && !bias_indexed && !use_kv_rows), "bad sparse configuration");
if ((use_logit_softcap && !(DV == 128 || DV == 256 || DV == 512))) {
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
@@ -767,15 +788,18 @@ 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 int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
// For sparse attention, ne11 is the capacity of each index list, not the KV cache length.
const int64_t list = use_sparse ? int64_t(sequence % ne33)*gridDim.x + blockIdx.x : 0;
const int32_t * rows = use_sparse ? KV_max + list*ne11 :
use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
__builtin_assume(!use_kv_rows || rows != nullptr);
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias;
const fattn_bias_indexed head_bias = bias_indexed ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias;
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
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 = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const half * maskh = bias_indexed || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const int stride_K2 = s11;
const int stride_V2 = s21;
@@ -868,20 +892,21 @@ static __global__ void flash_attn_tile(
__syncthreads();
// Main loop over KV cache:
const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11;
if (ncols2 == 1) {
const int k_VKQ_max = use_sparse ? KV_max[int64_t(gridDim.x)*ne33*ne11 + list] :
KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11;
if (ncols2 == 1 || use_sparse) {
// Branch with out-of-bounds checks.
int k_VKQ_0 = blockIdx.y*nbatch_fa;
while (k_VKQ_0 <= k_VKQ_max - nbatch_fa) {
constexpr bool oob_check = false;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, bias_indexed, use_sparse>
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
k_VKQ_0 += gridDim.y*nbatch_fa;
}
if (k_VKQ_0 < k_VKQ_max) {
constexpr bool oob_check = true;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, bias_indexed, use_sparse>
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
}
@@ -889,7 +914,7 @@ static __global__ void flash_attn_tile(
// Branch without out-of-bounds checks.
for (int k_VKQ_0 = blockIdx.y*nbatch_fa; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nbatch_fa) {
constexpr bool oob_check = false;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, bias_indexed, use_sparse>
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
}
@@ -1063,7 +1088,7 @@ static __global__ void flash_attn_tile(
#endif // FLASH_ATTN_AVAILABLE
}
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V, bool indexed_bias, bool use_kv_rows>
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V, bool bias_indexed, bool use_kv_rows>
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>());
@@ -1077,15 +1102,26 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr size_t nbytes_shared = 0;
#ifdef GGML_USE_HIP
if constexpr (!bias_indexed && !use_kv_rows && ggml_cuda_flash_attn_ext_tile_may_use_sparse(DKQ, DV, ncols2, use_logit_softcap)) {
if (ggml_cuda_flash_attn_ext_tile_shall_use_sparse(cc, dst, DKQ, DV)) {
const int nwarps = ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols2, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, ncols2, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, 1, ncols2, use_logit_softcap, false, type_K, type_V, false, true>;
launch_fattn<DV, 1, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, true, warp_size);
return;
}
}
// Limit indexed bias tile widths to avoid spilling registers on AMD.
// TODO: select the tile width in one function.
constexpr int max_cols = !indexed_bias ? 64 : DKQ == 64 ? 32 : use_kv_rows ? 16 : 8;
constexpr int max_cols = !bias_indexed ? 64 : DKQ == 64 ? 32 : use_kv_rows ? 16 : 8;
if constexpr (DKQ <= 128 && max_cols >= 64) {
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, indexed_bias, type_K, type_V, use_kv_rows>;
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, bias_indexed, type_K, type_V, use_kv_rows>;
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;
@@ -1100,7 +1136,7 @@ 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, indexed_bias, type_K, type_V, use_kv_rows>;
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, bias_indexed, type_K, type_V, use_kv_rows>;
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;
@@ -1112,7 +1148,7 @@ 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, indexed_bias, type_K, type_V, use_kv_rows>;
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, bias_indexed, type_K, type_V, use_kv_rows>;
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;
@@ -1124,7 +1160,7 @@ 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, indexed_bias, type_K, type_V, use_kv_rows>;
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, bias_indexed, type_K, type_V, use_kv_rows>;
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;
@@ -1136,7 +1172,7 @@ 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, indexed_bias, type_K, type_V, use_kv_rows>;
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, bias_indexed, type_K, type_V, use_kv_rows>;
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;
@@ -1147,7 +1183,7 @@ 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, indexed_bias, type_K, type_V, use_kv_rows>;
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, bias_indexed, type_K, type_V, use_kv_rows>;
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;
@@ -1177,7 +1213,7 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
if constexpr (DKQ == 64 || DKQ == 128) {
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
if (ggml_flash_attn_ext_bias_is_indexed(dst)) {
if (dst->src[5]) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, true>(ctx, dst);
} else {
+10 -10
View File
@@ -16,7 +16,7 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpass-failed"
#endif // __clang__
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap, bool indexed_bias, bool use_kv_rows> // D == head size
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap, bool bias_indexed, bool use_kv_rows> // D == head size
__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1)
static __global__ void flash_attn_ext_vec(
const float2 * Q_ptr,
@@ -41,7 +41,7 @@ static __global__ void flash_attn_ext_vec(
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 s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
const fattn_bias_indexed bias) {
ggml_cuda_pdl_lc();
#ifdef FLASH_ATTN_AVAILABLE
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
@@ -75,7 +75,7 @@ static __global__ void flash_attn_ext_vec(
#ifdef GGML_USE_HIP
#ifdef RDNA
constexpr int nthreads_KQ_q = indexed_bias && type_K == GGML_TYPE_F8_E4M3 ? 16 : 2;
constexpr int nthreads_KQ_q = bias_indexed && type_K == GGML_TYPE_F8_E4M3 ? 16 : 2;
#else
constexpr int nthreads_KQ_q = type_K == GGML_TYPE_F8_E4M3 && D == 256 && ncols == 2 ? 16 : 4;
#endif // RDNA
@@ -107,13 +107,13 @@ static __global__ void flash_attn_ext_vec(
const int sequence = blockIdx.z / ne02;
const int head = blockIdx.z - sequence*ne02;
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias;
const fattn_bias_indexed head_bias = bias_indexed ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias;
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
Q += s03*sequence + s02* head + s01*ic0;
K += s13*sequence + s12*(head / gqa_ratio);
V += s23*sequence + s22*(head / gqa_ratio);
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
const half * maskh = bias_indexed || 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);
@@ -305,7 +305,7 @@ static __global__ void flash_attn_ext_vec(
sum = logit_softcap*tanhf(sum);
}
if constexpr (!indexed_bias) {
if constexpr (!bias_indexed) {
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
}
@@ -321,14 +321,14 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int j = 0; j < ncols; ++j) {
if constexpr (indexed_bias) {
if constexpr (bias_indexed) {
const int k = k_VKQ_0 + tid;
const float m = head_bias.add(__half2float(maskh[j*ne11 + tid]), ic0 + j, k);
KQ_reg[j] += slope*m;
KQ_max_new[j] = fmaxf(KQ_max[j], KQ_reg[j] + FATTN_KQ_MAX_OFFSET);
}
#pragma unroll
for (int offset = indexed_bias ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
for (int offset = bias_indexed ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
KQ_max_new[j] = fmaxf(KQ_max_new[j], ggml_cuda_shfl_xor(KQ_max_new[j], offset, WARP_SIZE));
}
const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]);
@@ -513,7 +513,7 @@ static __global__ void flash_attn_ext_vec(
#endif // V_DOT2_F32_F16_AVAILABLE
KQ_sum[j_VKQ] *= kqmax_scale;
KQ_sum[j_VKQ] = warp_reduce_sum(KQ_sum[j_VKQ]);
KQ_sum[j_VKQ] = warp_reduce_sum<WARP_SIZE, true>(KQ_sum[j_VKQ]);
if (threadIdx.x == 0) {
KQ_sum_shared[j_VKQ][threadIdx.y] = KQ_sum[j_VKQ];
}
@@ -575,7 +575,7 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
const int nwarps = nthreads / WARP_SIZE;
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, false>;
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
if (ggml_flash_attn_ext_bias_is_indexed(dst)) {
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
: flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, false>;
}
+116 -72
View File
@@ -127,6 +127,71 @@ void ggml_cuda_flash_attn_ext_compact_mask(
#endif // !defined(GGML_USE_MUSA)
}
#ifdef GGML_USE_HIP
bool ggml_cuda_flash_attn_ext_tile_shall_use_sparse(const int cc, const ggml_tensor * dst, const int DKQ, const int DV) {
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * mask = dst->src[3];
const int n_kv_max = ggml_get_op_params_i32(dst, 4);
const int64_t n_kv = K->ne[1];
float max_bias = 0.0f;
memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
if (!mask || mask->ne[0] != n_kv || mask->ne[1] < Q->ne[1] ||
mask->ne[2] != 1 || dst->src[5] || n_kv_max <= 0 || max_bias != 0.0f) {
return false;
}
if (GGML_CUDA_CC_IS_GCN(cc)) {
// Sparse compaction is not beneficial when the selected positions exceed 25% of the KV cache.
if (n_kv_max > n_kv/4) {
return false;
}
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (DKQ == 72 && DV == 72) {
return n_kv >= 8192;
}
if (DKQ == 80 && DV == 80) {
return n_kv >= 16384;
}
if (DKQ == 96 && DV == 96) {
return n_kv >= 16384;
}
if (DKQ == 112 && DV == 112) {
return n_kv >= 16384;
}
if (DKQ == 128 && DV == 128) {
return n_kv >= 8192;
}
if (DKQ == 192 && DV == 128) {
return n_kv >= 16384;
}
if (DKQ == 256 && DV == 256) {
if (gqa_ratio == 2) {
return (n_kv_max <= DKQ && n_kv >= 16384) ||
(n_kv >= 32768 && (Q->ne[1] == 1 || n_kv_max <= 2*DKQ));
}
return n_kv >= 4096 && (Q->ne[1] == 1 || n_kv_max < n_kv/8);
}
if (DKQ == 320 && DV == 256) {
return n_kv >= 65536 && gqa_ratio >= 64;
}
if (DKQ == 512 && DV == 512) {
return n_kv >= 16384 && gqa_ratio >= 16;
}
if (DKQ == 576 && DV == 512) {
return n_kv >= 32768 && gqa_ratio >= 32;
}
}
return false;
}
#endif // GGML_USE_HIP
bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1, const int ncols2) {
#ifdef GGML_USE_MUSA
GGML_UNUSED_VARS(cc, dst, ncols1, ncols2);
@@ -198,9 +263,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2, type_K, type_V>(ctx, dst);
}
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;
static int ggml_cuda_flash_attn_ext_mma_f16_get_ncols2(const int cc, const ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
@@ -230,71 +293,56 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
}
}
if (!use_gqa_opt) {
return 1;
}
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
// 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, type_K, type_V>(ctx, dst);
return;
}
const int ncols2_max = Q->ne[0] == 320 ? 32 : ((Q->ne[0] == 576 || Q->ne[0] == 192) ? 16 : 8);
if (use_gqa_opt && gqa_ratio % 4 == 0) {
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, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
return;
} else {
GGML_ABORT("fatal error");
// On Volta and RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask:
if (cc == GGML_CUDA_CC_VOLTA || (amd_wmma_available(cc) && gqa_ratio % 2 == 0)) {
int ncols2 = 1;
while (gqa_ratio % (2*ncols2) == 0 && ncols2 < ncols2_max) {
ncols2 *= 2;
}
return ncols2;
}
// 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) {
int ncols2 = 1;
while (gqa_ratio > ncols2 && ncols2 < ncols2_max) {
ncols2 *= 2;
}
return ncols2;
}
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 int ncols2 = ggml_cuda_flash_attn_ext_mma_f16_get_ncols2(cc, dst);
switch (ncols2) {
case 8:
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) {
break;
case 4:
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) {
break;
case 2:
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, 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, 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, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
} else {
GGML_ABORT("fatal error");
break;
case 1:
if constexpr (DKQ <= 256) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
break;
} else {
GGML_ABORT("fatal error");
}
default:
GGML_ABORT("fatal error");
}
}
@@ -606,7 +654,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * kv_rows = dst->src[5];
if (!ggml_validate_flash_attn_ext_indexed_bias(dst)) {
if (ggml_flash_attn_ext_has_bias(dst) && !ggml_flash_attn_ext_bias_is_indexed(dst)) {
return BEST_FATTN_KERNEL_NONE;
}
@@ -691,7 +739,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
}
// the tile and vec kernels implement the indexed bias, the mma kernel does not
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
if (ggml_flash_attn_ext_bias_is_indexed(dst)) {
float logit_softcap;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
if (Q->ne[0] != 128 && !(Q->ne[0] == 64 && logit_softcap == 0.0f)) {
@@ -757,20 +805,16 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
return BEST_FATTN_KERNEL_MMA_F16;
}
const int ncols2_max = Q->ne[0] == 320 ? 32 : ((Q->ne[0] == 576 || Q->ne[0] == 192) ? 16 : 8);
int gqa_ratio_eff = 1;
while (max_bias == 0.0f && (!mask || mask->ne[2] == 1) && gqa_ratio % (2*gqa_ratio_eff) == 0 && gqa_ratio_eff < ncols2_max) {
gqa_ratio_eff *= 2;
}
const int ncols2 = ggml_cuda_flash_attn_ext_mma_f16_get_ncols2(cc, dst);
// 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) {
if (can_use_vector_kernel && Q->ne[1] * ncols2 <= 2) {
return BEST_FATTN_KERNEL_VEC;
}
if (Q->ne[1] * gqa_ratio_eff <= 16) {
if (Q->ne[1] * ncols2 <= 16) {
return tile_kernel; // On Volta tensor cores are only faster for sufficiently large matrices.
}
return BEST_FATTN_KERNEL_MMA_F16;
@@ -783,23 +827,23 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
// AMD MFMA needs a certain minimum batch size to outscale the tile kernel for large head sizes.
if (amd_mfma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) {
if ((Q->ne[0] <= 64 && Q->ne[1] * gqa_ratio_eff > 8)) {
if ((Q->ne[0] <= 64 && Q->ne[1] * ncols2 > 8)) {
return BEST_FATTN_KERNEL_MMA_F16;
}
if ((Q->ne[0] <= 128 && Q->ne[1] * gqa_ratio_eff > 16)) {
if ((Q->ne[0] <= 128 && Q->ne[1] * ncols2 > 16)) {
return BEST_FATTN_KERNEL_MMA_F16;
}
if ((Q->ne[0] <= 256 && Q->ne[1] * gqa_ratio_eff > 64)) {
if ((Q->ne[0] <= 256 && Q->ne[1] * ncols2 > 64)) {
return BEST_FATTN_KERNEL_MMA_F16;
}
if (Q->ne[0] > 256 && gqa_opt_applies && Q->ne[1] * gqa_ratio_eff > 128) {
if (Q->ne[0] > 256 && gqa_opt_applies && Q->ne[1] * ncols2 > 128) {
return BEST_FATTN_KERNEL_MMA_F16;
}
}
// AMD WMMA is faster than the tile kernel if the wide tiles with high arithmetic intensity can be utilized.
if ((amd_wmma_available(cc) && gqa_opt_applies && Q->ne[0] <= 256) && Q->ne[0] != 40 && Q->ne[0] != 72 &&
Q->ne[1] * gqa_ratio_eff > (Q->ne[0] <= 128 ? 8 : 16)) {
Q->ne[1] * ncols2 > (Q->ne[0] <= 128 ? 8 : 16)) {
return BEST_FATTN_KERNEL_MMA_F16;
}
+2 -2
View File
@@ -203,7 +203,7 @@ gated_delta_net_cuda(const float * q,
attn_partial += s_shard[r] * q_reg[r];
}
float attn_col = warp_reduce_sum<lanes_per_col>(attn_partial);
float attn_col = warp_reduce_sum<lanes_per_col, true>(attn_partial);
if (lane_in_col == 0) {
attn_data[col] = attn_col * scale;
@@ -237,7 +237,7 @@ gated_delta_net_cuda(const float * q,
attn_partial += s_shard[r] * q_reg[r];
}
float attn_col = warp_reduce_sum<lanes_per_col>(attn_partial);
float attn_col = warp_reduce_sum<lanes_per_col, true>(attn_partial);
if (lane_in_col == 0) {
attn_data[col] = attn_col * scale;
+7 -1
View File
@@ -483,8 +483,14 @@ static ggml_cuda_device_info ggml_cuda_init() {
GGML_LOG_INFO(
" Device %d: %s\n", turing_devices_without_mma[device_pos].first, turing_devices_without_mma[device_pos].second.c_str());
}
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 13000
// CUDA 13 dropped compute_61, so the Pascal code can only be compiled with an older toolkit
GGML_LOG_INFO(
"Consider compiling with CMAKE_CUDA_ARCHITECTURES=61-virtual;80-virtual and DGGML_CUDA_FORCE_MMQ to force the use of the Pascal code for Turing.\n");
"Consider compiling with CUDA 12, -DCMAKE_CUDA_ARCHITECTURES=\"61-virtual;80-virtual\" and -DGGML_CUDA_FORCE_MMQ=ON to force the use of the Pascal code for Turing (CUDA 13 cannot compile for compute_61).\n");
#else
GGML_LOG_INFO(
"Consider compiling with -DCMAKE_CUDA_ARCHITECTURES=\"61-virtual;80-virtual\" and -DGGML_CUDA_FORCE_MMQ=ON to force the use of the Pascal code for Turing.\n");
#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 13000
}
for (int id = 0; id < info.device_count; ++id) {
+1 -1
View File
@@ -290,7 +290,7 @@ static __global__ void lightning_indexer_kernel_vec(
#pragma unroll
for (int k = 0; k < K_VECS_PER_WARP; ++k) {
float sum = warp_reduce_sum(qk[k]);
float sum = warp_reduce_sum<WARP_SIZE, true>(qk[k]);
// ReLU, weight
if (i_lane == 0) {
+462 -5
View File
@@ -7,8 +7,8 @@
#include <type_traits>
// NVIDIA only: the kernel uses the NVIDIA int8 MMA fragment layout and cp.async.
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
// mul_mat_q_few for NVIDIA uses the int8 MMA fragment layout and cp.async, mul_mat_q_few_wmma for RDNA the WMMA layout. Not on MUSA.
#if !defined(GGML_USE_MUSA)
using namespace ggml_cuda_mma;
@@ -719,6 +719,353 @@ static __global__ void mul_mat_q_few(
#endif // defined(CP_ASYNC_AVAILABLE)
}
// RDNA version with WMMA for up to 16 src1 columns. A WMMA multiplies 16x16 int8 matrices, see mma.cuh:
// A = src1, B = src0, C = A @ B.
// A and B: lane l holds the column resp. row l%16, the values [16k, 16k + 16) on RDNA3 and [8*(l/16), 8*(l/16) + 8) on RDNA4.
// C: lane l holds the src1 columns 2v + l/16 (RDNA3) resp. 8*(l/16) + v (RDNA4) of the src0 row l%16.
// So the src0 scales of a row stay in the lane that decodes it, the src1 scales of the C columns come with the layout in quantize.cuh.
// The lanes decode their rows straight from global memory. A ring as in mul_mat_q_few, filled through registers without cp.async, was slower.
// A second group of 16 columns spills registers with ROCm 7.2.
static constexpr __host__ __device__ bool mmq_few_wmma_supported(const ggml_type type) {
return type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K || type == GGML_TYPE_Q6_K;
}
// the reduction over the warps
static constexpr int MMQ_FEW_WMMA_NBYTES_SHARED = (MMQ_FEW_NWARPS - 1)*8*WARP_SIZE*sizeof(float);
#if defined(AMD_WMMA_AVAILABLE)
// The A and B tiles of a lane for one WMMA, MIRRORED on RDNA3 where both half-warps hold the same data.
#if defined(AMD_WMMA_256B_AVAILABLE)
using mmq_few_tile_ab = tile<16, 4, int, DATA_LAYOUT_I_MAJOR_MIRRORED>;
#else
using mmq_few_tile_ab = tile<16, 4, int, DATA_LAYOUT_I_MAJOR>;
#endif
using mmq_few_tile_c = tile<16, 16, int, DATA_LAYOUT_J_MAJOR>;
// int32 per lane and WMMA, 4 on RDNA3 and 2 on RDNA4
static constexpr int MMQ_FEW_WMMA_NE = mmq_few_tile_ab::ne;
// The src1 fragments of a lane for one sub-block, see quantize.cuh.
struct mmq_few_wmma_y {
int qs[2][MMQ_FEW_WMMA_NE]; // [hh] holds the values [16*hh, 16*hh + 16) of the WMMA
int ds[8]; // d (D4) resp. (d, sum) (DS4) of the C columns, ds[v] of C.x[v]
};
// The C registers of a lane, on RDNA3 the ones with v >= 4 hold only the columns >= 8.
template <bool half>
static constexpr int mmq_few_wmma_nv() {
return half && MMQ_FEW_WMMA_NE == 4 ? 4 : 8;
}
// half: only the first 8 columns are used, the others are zero.
template <bool half>
static __device__ __forceinline__ mmq_few_wmma_y mmq_few_wmma_load_y(const int4 * y, const int s) {
const int m = threadIdx.x % 16;
const int h = threadIdx.x / 16;
mmq_few_wmma_y yf;
if constexpr (MMQ_FEW_WMMA_NE == 2) {
// RDNA4: the lane holds the values [16*hh + 8*h, 16*hh + 8*h + 8) of column m.
// The src1 quantize kernel zeroes the columns beyond ne1, a branch to skip the unused ones is more expensive than the loads.
const int2 * y2 = (const int2 *) y;
const int2 q0 = y2[(s*MMQ_FEW_WMMA_NCOLS + m)*4 + 0 + h];
const int2 q1 = y2[(s*MMQ_FEW_WMMA_NCOLS + m)*4 + 2 + h];
yf.qs[0][0] = q0.x; yf.qs[0][1] = q0.y;
yf.qs[1][0] = q1.x; yf.qs[1][1] = q1.y;
} else if (half && m >= MMQ_FEW_WMMA_NCOLS/2) {
yf.qs[0][0] = 0; yf.qs[0][1] = 0; yf.qs[0][2] = 0; yf.qs[0][3] = 0;
yf.qs[1][0] = 0; yf.qs[1][1] = 0; yf.qs[1][2] = 0; yf.qs[1][3] = 0;
} else {
const int4 q0 = y[(s*MMQ_FEW_WMMA_NCOLS + m)*2 + 0];
const int4 q1 = y[(s*MMQ_FEW_WMMA_NCOLS + m)*2 + 1];
yf.qs[0][0] = q0.x; yf.qs[0][1] = q0.y; yf.qs[0][2] = q0.z; yf.qs[0][3] = q0.w;
yf.qs[1][0] = q1.x; yf.qs[1][1] = q1.y; yf.qs[1][2] = q1.z; yf.qs[1][3] = q1.w;
}
if constexpr (MMQ_FEW_WMMA_NE == 2) {
// RDNA4: C.x[v] is the column 8*h + v
const int4 d0 = y[8*MMQ_FEW_WMMA_NCOLS*2 + 4*s + 0 + h];
const int4 d1 = y[8*MMQ_FEW_WMMA_NCOLS*2 + 4*s + 2 + h];
yf.ds[0] = d0.x; yf.ds[1] = d1.x; yf.ds[2] = d0.y; yf.ds[3] = d1.y;
yf.ds[4] = d0.z; yf.ds[5] = d1.z; yf.ds[6] = d0.w; yf.ds[7] = d1.w;
} else {
const int4 ds0 = y[8*MMQ_FEW_WMMA_NCOLS*2 + (s*2 + h)*2 + 0];
const int4 ds1 = half ? make_int4(0, 0, 0, 0) : y[8*MMQ_FEW_WMMA_NCOLS*2 + (s*2 + h)*2 + 1];
yf.ds[0] = ds0.x; yf.ds[1] = ds0.y; yf.ds[2] = ds0.z; yf.ds[3] = ds0.w;
yf.ds[4] = ds1.x; yf.ds[5] = ds1.y; yf.ds[6] = ds1.z; yf.ds[7] = ds1.w;
}
return yf;
}
template <mmq_q8_1_ds_layout ds_layout>
static __device__ __forceinline__ float mmq_few_wmma_get_d(const mmq_few_wmma_y & yf, const int v) {
if constexpr (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4) {
return __int_as_float(yf.ds[v]);
} else {
return __low2float(*(const half2 *) &yf.ds[v]);
}
}
static __device__ __forceinline__ float mmq_few_wmma_get_sum(const mmq_few_wmma_y & yf, const int v) {
return __high2float(*(const half2 *) &yf.ds[v]);
}
// n ints at the even byte offset o of the 4 byte aligned p, with whole 4 byte loads. In the unrolled decoders o is a constant.
template <int n>
static __device__ __forceinline__ void mmq_few_wmma_get_ints_b2(const char * p, const int o, int * dst) {
const int * w = (const int *) (p + (o & ~3));
if (o % 4 == 0) {
#pragma unroll
for (int i = 0; i < n; ++i) {
dst[i] = w[i];
}
} else {
int lo = w[0];
#pragma unroll
for (int i = 0; i < n; ++i) {
const int hi = w[i + 1];
dst[i] = __builtin_amdgcn_alignbyte(hi, lo, 2);
lo = hi;
}
}
}
static __device__ __forceinline__ void mmq_few_wmma(mmq_few_tile_c & C, const int * a, const int * b) {
mmq_few_tile_ab A;
mmq_few_tile_ab B;
#pragma unroll
for (int l = 0; l < MMQ_FEW_WMMA_NE; ++l) {
A.x[l] = a[l];
B.x[l] = b[l];
}
mma(C, A, B);
}
// vec_dot: one unit of 256 values of row l%16, x points to its data, y to the src1 fragments of the unit.
// The decoders write sub-block s of the row to b[8], the int32 at index i holds the values [4i, 4i + 4).
// One WMMA uses b + 4*hh + i0, with i0 = (4 - MMQ_FEW_WMMA_NE)*(l/16) the offset of the values of the lane.
template <ggml_type type, bool half>
static __device__ __forceinline__ void mmq_few_wmma_vec_dot_q45_K(const char * x, const int4 * y, float (&sum)[8]) {
using block_t = std::conditional_t<type == GGML_TYPE_Q4_K, block_q4_K, block_q5_K>;
const block_t * bx = (const block_t *) __builtin_assume_aligned(x, 16);
const int4 hdr = *(const int4 *) bx; // dm and the 12 scale bytes
const int scales[3] = {hdr.y, hdr.z, hdr.w};
const int sc[2] = {unpack_scales_q45_K(scales, 0), unpack_scales_q45_K(scales, 1)};
const int mn[2] = {unpack_scales_q45_K(scales, 2), unpack_scales_q45_K(scales, 3)};
const float2 dm = __half22float2(bx->dm);
[[maybe_unused]] int qh[8]; // Q5_K: bit s holds the high bit of sub-block s
if constexpr (type == GGML_TYPE_Q5_K) {
#pragma unroll
for (int i = 0; i < 8; ++i) {
qh[i] = get_int_b4(bx->qh, i);
}
}
float sum_d[8] = {0.0f};
float sum_m[8] = {0.0f};
const int i0 = (4 - MMQ_FEW_WMMA_NE)*(threadIdx.x / 16);
#pragma unroll
for (int j = 0; j < 4; ++j) {
int qs[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
qs[i] = get_int_b4(bx->qs + 32*j, i);
}
#pragma unroll
for (int s = 2*j; s < 2*j + 2; ++s) {
int b[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
b[i] = (qs[i] >> (4*(s % 2))) & 0x0F0F0F0F;
if constexpr (type == GGML_TYPE_Q5_K) {
b[i] |= ((qh[i] >> s) & 0x01010101) << 4;
}
}
const int ls = (sc[s/4] >> (8*(s % 4))) & 0xFF;
const float m = (mn[s/4] >> (8*(s % 4))) & 0xFF;
const mmq_few_wmma_y yf = mmq_few_wmma_load_y<half>(y, s);
mmq_few_tile_c C;
mmq_few_wmma(C, yf.qs[0], b + i0 + 0);
mmq_few_wmma(C, yf.qs[1], b + i0 + 4);
#pragma unroll
for (int v = 0; v < mmq_few_wmma_nv<half>(); ++v) {
sum_d[v] += mmq_few_wmma_get_d<MMQ_Q8_1_DS_LAYOUT_DS4>(yf, v) * float(C.x[v]*ls);
sum_m[v] += m * mmq_few_wmma_get_sum(yf, v);
}
}
}
#pragma unroll
for (int v = 0; v < 8; ++v) {
sum[v] += dm.x*sum_d[v] - dm.y*sum_m[v];
}
}
// Q6_K has a scale per 16 values, one WMMA per half of a sub-block.
template <bool half>
static __device__ __forceinline__ void mmq_few_wmma_vec_dot_q6_K(const char * x, const int4 * y, float (&sum)[8]) {
const block_q6_K * bx = (const block_q6_K *) x;
const float d = __half2float(bx->d);
float sum_d[8] = {0.0f};
const int i0 = (4 - MMQ_FEW_WMMA_NE)*(threadIdx.x / 16);
#pragma unroll
for (int n = 0; n < 2; ++n) {
int ql[2][8]; // [ql offset 0 or 32]
int qh[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
ql[0][i] = get_int_b2(bx->ql + 64*n, i);
ql[1][i] = get_int_b2(bx->ql + 64*n + 32, i);
qh[i] = get_int_b2(bx->qh + 32*n, i);
}
const int sc[2] = {get_int_b2(bx->scales + 8*n, 0), get_int_b2(bx->scales + 8*n, 1)};
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int s = 4*n + j;
int b[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
b[i] = __vsub4(((ql[j % 2][i] >> (4*(j/2))) & 0x0F0F0F0F) | (((qh[i] >> (2*j)) & 0x03030303) << 4), 0x20202020);
}
const int sc_lo = (int8_t) (sc[j/2] >> (16*(j % 2) + 0)); // scale of the values [0, 16)
const int sc_hi = (int8_t) (sc[j/2] >> (16*(j % 2) + 8)); // scale of the values [16, 32)
const mmq_few_wmma_y yf = mmq_few_wmma_load_y<half>(y, s);
mmq_few_tile_c C_lo;
mmq_few_tile_c C_hi;
mmq_few_wmma(C_lo, yf.qs[0], b + i0 + 0);
mmq_few_wmma(C_hi, yf.qs[1], b + i0 + 4);
#pragma unroll
for (int v = 0; v < mmq_few_wmma_nv<half>(); ++v) {
sum_d[v] += mmq_few_wmma_get_d<MMQ_Q8_1_DS_LAYOUT_D4>(yf, v) * float(C_lo.x[v]*sc_lo + C_hi.x[v]*sc_hi);
}
}
}
#pragma unroll
for (int v = 0; v < 8; ++v) {
sum[v] += d*sum_d[v];
}
}
// IQ4_NL has a block with its own scale per 32 values.
template <bool half>
static __device__ __forceinline__ void mmq_few_wmma_vec_dot_iq4_nl(const char * x, const int4 * y, float (&sum)[8]) {
const int i0 = (4 - MMQ_FEW_WMMA_NE)*(threadIdx.x / 16);
#pragma unroll
for (int s = 0; s < 8; ++s) {
// a unit starts 16 byte aligned, the qs of every second block 2 bytes off a 4 byte boundary
const char * xa = (const char *) __builtin_assume_aligned(x, 16);
int q4[4];
mmq_few_wmma_get_ints_b2<4>(xa, int(sizeof(block_iq4_nl))*s + 2, q4);
int b[8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int2 v = get_int_from_table_16(q4[i], kvalues_iq4nl);
b[i + 0] = v.x;
b[i + 4] = v.y;
}
const float d = __half2float(((const block_iq4_nl *) xa + s)->d);
const mmq_few_wmma_y yf = mmq_few_wmma_load_y<half>(y, s);
mmq_few_tile_c C;
mmq_few_wmma(C, yf.qs[0], b + i0 + 0);
mmq_few_wmma(C, yf.qs[1], b + i0 + 4);
#pragma unroll
for (int v = 0; v < mmq_few_wmma_nv<half>(); ++v) {
sum[v] += d*mmq_few_wmma_get_d<MMQ_Q8_1_DS_LAYOUT_D4>(yf, v) * float(C.x[v]);
}
}
}
template <ggml_type type, bool half>
static __device__ __forceinline__ void mmq_few_wmma_vec_dot(const char * x, const int4 * y, float (&sum)[8]) {
if constexpr (type == GGML_TYPE_IQ4_NL) {
mmq_few_wmma_vec_dot_iq4_nl<half>(x, y, sum);
} else if constexpr (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) {
mmq_few_wmma_vec_dot_q45_K<type, half>(x, y, sum);
} else if constexpr (type == GGML_TYPE_Q6_K) {
mmq_few_wmma_vec_dot_q6_K<half>(x, y, sum);
} else {
static_assert(type == GGML_TYPE_COUNT, "unsupported type");
}
}
#endif // defined(AMD_WMMA_AVAILABLE)
// The warps split K in units of 256 values, a block has 16 src0 rows. half: at most 8 src1 columns.
template <ggml_type type, bool half>
__launch_bounds__(MMQ_FEW_NWARPS*WARP_SIZE, 1)
static __global__ void mul_mat_q_few_wmma(
const char * x, const int4 * y_ptr, float * dst,
const int nunits, const int nrows_x, const int ncols_dst, const int64_t stride_row_x, const int stride_col_dst,
const int channel_ratio, const int64_t stride_channel_x, const int stride_channel_dst,
const int sample_ratio, const int64_t stride_sample_x, const int stride_sample_dst) {
#if defined(AMD_WMMA_AVAILABLE)
constexpr int nwarps = MMQ_FEW_NWARPS;
constexpr int warp_size = WARP_SIZE;
constexpr int unit_size = mmq_few_unit_size(type);
static_assert(mmq_few_wmma_supported(type), "unsupported type");
extern __shared__ float buf_sum_mmq_few_wmma[];
const int row0 = blockIdx.x*MMQ_FEW_NROWS;
const int channel_dst = blockIdx.y;
const int sample_dst = blockIdx.z;
const int nchannels = gridDim.y;
x += int64_t(sample_dst/sample_ratio)*stride_sample_x + int64_t(channel_dst/channel_ratio)*stride_channel_x;
dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst;
const int4 * GGML_CUDA_RESTRICT y = y_ptr + (int64_t(sample_dst)*nchannels + channel_dst)*nunits*MMQ_FEW_WMMA_Q8_1_INT4;
const char * xr = x + int64_t(min(row0 + int(threadIdx.x) % 16, nrows_x - 1))*stride_row_x;
float sum[8] = {0.0f};
for (int iu = threadIdx.y; iu < nunits; iu += nwarps) {
mmq_few_wmma_vec_dot<type, half>(xr + int64_t(iu)*unit_size, y + int64_t(iu)*MMQ_FEW_WMMA_Q8_1_INT4, sum);
}
// reduce the sums over the warps
float * buf_sum = buf_sum_mmq_few_wmma;
if (threadIdx.y > 0) {
#pragma unroll
for (int v = 0; v < 8; ++v) {
buf_sum[((threadIdx.y - 1)*8 + v)*warp_size + threadIdx.x] = sum[v];
}
}
__syncthreads();
if (threadIdx.y > 0) {
return;
}
#pragma unroll
for (int w = 0; w < nwarps - 1; ++w) {
#pragma unroll
for (int v = 0; v < 8; ++v) {
sum[v] += buf_sum[(w*8 + v)*warp_size + threadIdx.x];
}
}
const int i = row0 + mmq_few_tile_c::get_j(0);
#pragma unroll
for (int v = 0; v < mmq_few_wmma_nv<half>(); ++v) {
const int j = mmq_few_tile_c::get_i(v);
if (i < nrows_x && j < ncols_dst) {
dst[int64_t(j)*stride_col_dst + i] = sum[v];
}
}
#else
GGML_UNUSED_VARS(x, y_ptr, dst, nunits, nrows_x, ncols_dst, stride_row_x, stride_col_dst,
channel_ratio, stride_channel_x, stride_channel_dst,
sample_ratio, stride_sample_x, stride_sample_dst);
NO_DEVICE_CODE;
#endif // defined(AMD_WMMA_AVAILABLE)
}
// ggml_is_constant (static in ggml.c) on the tensor that a view points to
static bool mmq_few_is_constant(const ggml_tensor * src0) {
const ggml_tensor * x_root = src0->view_src ? src0->view_src : src0;
@@ -796,6 +1143,98 @@ static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml
}
}
template <ggml_type type, bool half>
static void launch_mul_mat_q_few_wmma(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
const int4 * src1_q, cudaStream_t stream) {
GGML_TENSOR_BINARY_OP_LOCALS;
const int nunits = ne00 / QK_K;
const dim3 block_nums((ne01 + MMQ_FEW_NROWS - 1) / MMQ_FEW_NROWS, ne12, ne13);
const dim3 block_dims(WARP_SIZE, MMQ_FEW_NWARPS, 1);
const ggml_cuda_kernel_launch_params params(block_nums, block_dims, MMQ_FEW_WMMA_NBYTES_SHARED, stream);
ggml_cuda_kernel_launch(mul_mat_q_few_wmma<type, half>, params,
(const char *) src0->data, src1_q, (float *) dst->data,
nunits, (int) ne01, (int) ne1, (int64_t) nb01, (int) (nb1/sizeof(float)),
(int) (ne12/ne02), (int64_t) nb02, (int) (nb2/sizeof(float)),
(int) (ne13/ne03), (int64_t) nb03, (int) (nb3/sizeof(float)));
}
template <ggml_type type>
static void launch_mul_mat_q_few_wmma_switch_ncols(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
const int4 * src1_q, cudaStream_t stream) {
if (src1->ne[1] <= MMQ_FEW_WMMA_NCOLS/2) {
launch_mul_mat_q_few_wmma<type, true>(src0, src1, dst, src1_q, stream);
} else {
launch_mul_mat_q_few_wmma<type, false>(src0, src1, dst, src1_q, stream);
}
}
// Min. and max. number of src1 columns for RDNA3 and RDNA4, 0 if the type is not supported.
// Below the min. MMVQ is faster, above the max. MMQ. Q8_0 would need more than 16 columns to beat MMQ.
static int2 mmq_few_wmma_ncols_range(const ggml_type type, const int cc) {
if (GGML_CUDA_CC_IS_RDNA4(cc)) { // tuned on the Radeon RX 9070 XT (gfx1201)
switch (type) {
case GGML_TYPE_Q4_K: return make_int2(3, 16);
case GGML_TYPE_Q5_K: return make_int2(3, 16);
case GGML_TYPE_Q6_K: return make_int2(5, 16);
case GGML_TYPE_IQ4_NL: return make_int2(6, 16);
default: return make_int2(0, 0);
}
}
if (GGML_CUDA_CC_IS_RDNA3_0(cc)) { // tuned on the Radeon RX 7900 XTX (gfx1100)
switch (type) {
case GGML_TYPE_Q4_K: return make_int2(2, 16);
case GGML_TYPE_Q5_K: return make_int2(2, 16);
case GGML_TYPE_Q6_K: return make_int2(5, 16);
case GGML_TYPE_IQ4_NL: return make_int2(5, 16);
default: return make_int2(0, 0);
}
}
switch (type) { // tuned on the Radeon 8060S (gfx1151)
case GGML_TYPE_Q4_K: return make_int2(3, 16);
case GGML_TYPE_Q5_K: return make_int2(3, 8);
case GGML_TYPE_Q6_K: return make_int2(6, 16);
case GGML_TYPE_IQ4_NL: return make_int2(7, 16);
default: return make_int2(0, 0);
}
}
static bool mmq_few_use_wmma(const int cc) {
return GGML_CUDA_CC_IS_RDNA3(cc) || GGML_CUDA_CC_IS_RDNA4(cc);
}
static void ggml_cuda_mul_mat_q_few_wmma(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
GGML_TENSOR_BINARY_OP_LOCALS;
GGML_ASSERT(ne11 <= MMQ_FEW_WMMA_NCOLS);
cudaStream_t stream = ctx.stream();
const int nunits = ne00 / QK_K;
ggml_cuda_pool_alloc<int4> src1_q(ctx.pool(), int64_t(ne12)*ne13*nunits*MMQ_FEW_WMMA_Q8_1_INT4);
quantize_mmq_few_wmma_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);
switch (src0->type) {
case GGML_TYPE_Q4_K:
launch_mul_mat_q_few_wmma_switch_ncols<GGML_TYPE_Q4_K>(src0, src1, dst, src1_q.get(), stream);
break;
case GGML_TYPE_Q5_K:
launch_mul_mat_q_few_wmma_switch_ncols<GGML_TYPE_Q5_K>(src0, src1, dst, src1_q.get(), stream);
break;
case GGML_TYPE_Q6_K:
launch_mul_mat_q_few_wmma_switch_ncols<GGML_TYPE_Q6_K>(src0, src1, dst, src1_q.get(), stream);
break;
case GGML_TYPE_IQ4_NL:
launch_mul_mat_q_few_wmma_switch_ncols<GGML_TYPE_IQ4_NL>(src0, src1, dst, src1_q.get(), stream);
break;
default:
GGML_ABORT("unsupported type for few-row MMQ with WMMA");
}
}
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;
@@ -806,6 +1245,12 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(ne00 % QK_K == 0);
if (mmq_few_use_wmma(ggml_cuda_info().devices[ctx.device].cc)) {
GGML_ASSERT(!ids);
ggml_cuda_mul_mat_q_few_wmma(ctx, src0, src1, dst);
return;
}
cudaStream_t stream = ctx.stream();
const int nunits = ne00 / QK_K;
@@ -875,6 +1320,10 @@ static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const
return 0;
#endif // GGML_CUDA_FORCE_CUBLAS
if (mmq_few_use_wmma(cc)) {
return has_ids || !mmq_few_wmma_supported(type) || ne00 < 8*QK_K ? 0 : mmq_few_wmma_ncols_range(type, cc).x;
}
// NVIDIA Ampere to Blackwell
if (!ampere_mma_available(cc) || cc >= GGML_CUDA_CC_RUBIN) {
return 0;
@@ -916,6 +1365,14 @@ bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor *
if (ids && (2*src0->ne[2] + 1)*sizeof(int) > ggml_cuda_info().devices[ggml_cuda_get_device()].smpb) {
return false;
}
if (mmq_few_use_wmma(cc)) {
if (src1->ne[1] > mmq_few_wmma_ncols_range(src0->type, cc).y || src0->ne[0] % QK_K != 0) {
return false;
}
// the decoders read whole 4 byte values from 16 byte aligned units, Q6_K values 2 bytes at a time
const int x_alignment = mmq_few_unaligned(src0->type, 1) ? 2 : 16;
return ggml_cuda_is_aligned(src0, x_alignment) && ggml_cuda_is_aligned(src1, 16);
}
// the row must hold a whole number of ring stages of the launched kernel
const int ncg = ids ? 1 : mmq_few_ncg(ncols);
const int nmt = ids ? 1 : mmq_few_nmt(src0->type, ncg, src0->ne[1]);
@@ -928,11 +1385,11 @@ bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor *
return ggml_cuda_is_aligned(src0, x_alignment) && ggml_cuda_is_aligned(src1, 16);
}
#else // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
#else // !defined(GGML_USE_MUSA)
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_UNUSED_VARS(ctx, src0, src1, ids, dst);
GGML_ABORT("few-row MMQ is not supported on HIP or MUSA");
GGML_ABORT("few-row MMQ is not supported on MUSA");
}
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const int cc) {
@@ -940,4 +1397,4 @@ bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor *
return false;
}
#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
#endif // !defined(GGML_USE_MUSA)
+11 -8
View File
@@ -358,29 +358,32 @@ static __global__ void mul_mat_vec_f(
ggml_cuda_pdl_lc();
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
sumf[j] = warp_reduce_sum<warp_size>(sumf[j]);
sumf[j] = warp_reduce_sum<warp_size, (block_size > warp_size || ncols_dst == 1)>(sumf[j]);
if constexpr (has_fusion) {
if (use_gate) {
sumf_gate[j] = warp_reduce_sum<warp_size>(sumf_gate[j]);
sumf_gate[j] = warp_reduce_sum<warp_size, (block_size > warp_size || ncols_dst == 1)>(sumf_gate[j]);
}
}
if (block_size > warp_size) {
buf_iw[tid/warp_size] = sumf[j];
if constexpr (has_fusion) {
if (use_gate) {
buf_iw_gate[tid/warp_size] = sumf_gate[j];
// one write per warp
if (tid % warp_size == 0) {
buf_iw[tid/warp_size] = sumf[j];
if constexpr (has_fusion) {
if (use_gate) {
buf_iw_gate[tid/warp_size] = sumf_gate[j];
}
}
}
__syncthreads();
if (tid < warp_size) {
sumf[j] = buf_iw[tid];
sumf[j] = warp_reduce_sum<warp_size>(sumf[j]);
sumf[j] = warp_reduce_sum<warp_size, ncols_dst == 1>(sumf[j]);
if constexpr (has_fusion) {
if (use_gate) {
sumf_gate[j] = buf_iw_gate[tid];
sumf_gate[j] = warp_reduce_sum<warp_size>(sumf_gate[j]);
sumf_gate[j] = warp_reduce_sum<warp_size, ncols_dst == 1>(sumf_gate[j]);
}
}
}
+5 -4
View File
@@ -904,10 +904,11 @@ static __global__ void mul_mat_vec_q(
}
}
}
tmp[j][i] = warp_reduce_sum<warp_size>(tmp[j][i]);
tmp[j][i] = i == 0 ? warp_reduce_sum<warp_size, true>(tmp[j][i]) : warp_reduce_sum<warp_size>(tmp[j][i]);
if constexpr (has_fusion) {
if (use_gate) {
tmp_gate[j][i] = warp_reduce_sum<warp_size>(tmp_gate[j][i]);
tmp_gate[j][i] = i == 0 ? warp_reduce_sum<warp_size, true>(tmp_gate[j][i]) : warp_reduce_sum<warp_size>(tmp_gate[j][i]);
}
}
@@ -1053,10 +1054,10 @@ static __global__ void mul_mat_vec_q_moe(
// Warp-level reduction only - no shared memory needed
#pragma unroll
for (int i = 0; i < c_rows_per_block; ++i) {
tmp[i] = warp_reduce_sum<warp_size>(tmp[i]);
tmp[i] = i == 0 ? warp_reduce_sum<warp_size, true>(tmp[i]) : warp_reduce_sum<warp_size>(tmp[i]);
if constexpr (has_fusion) {
if (use_gate) {
tmp_gate[i] = warp_reduce_sum<warp_size>(tmp_gate[i]);
tmp_gate[i] = i == 0 ? warp_reduce_sum<warp_size, true>(tmp_gate[i]) : warp_reduce_sum<warp_size>(tmp_gate[i]);
}
}
}
+2 -2
View File
@@ -290,8 +290,8 @@ static __global__ void rms_norm_back_f32(
}
// sum up partial sums
sum_xx = warp_reduce_sum(sum_xx);
sum_xg = warp_reduce_sum(sum_xg);
sum_xx = warp_reduce_sum<WARP_SIZE, (block_size > WARP_SIZE)>(sum_xx);
sum_xg = warp_reduce_sum<WARP_SIZE, (block_size > WARP_SIZE)>(sum_xg);
if constexpr (block_size > WARP_SIZE) {
static_assert(block_size == 1024, "unexpected block_size");
__shared__ float s_sum_xx[32];
+43 -14
View File
@@ -122,7 +122,7 @@ static __global__ void quantize_q8_1(
const float d = amax / 127.0f;
const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);
const int sum = warp_reduce_sum<QK8_1>((int) q);
const int sum = warp_reduce_sum<QK8_1, true>((int) q);
y[ib].qs[iqs] = q;
@@ -662,8 +662,8 @@ void quantize_mmq_q8_1_cuda(
});
}
// 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>
// 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 layouts.
template <mmq_q8_1_ds_layout ds_layout, bool wmma>
static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, int4 * yg, const int iu, const int g) {
// the 32 values of a sub-block are held by 8 threads
float amax = fmaxf(fmaxf(fabsf(xi.x), fabsf(xi.y)), fmaxf(fabsf(xi.z), fabsf(xi.w)));
@@ -680,11 +680,25 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
// as in quantize_mmq_q8_1: the sum of the quantized values; the int warp_reduce_sum reduces the whole warp on Ampere+
[[maybe_unused]] float sum = 0.0f;
if constexpr (ds_layout != MMQ_Q8_1_DS_LAYOUT_D4) {
sum = d*warp_reduce_sum<8>(float(q.x + q.y + q.z + q.w));
sum = d*warp_reduce_sum<8, true>(float(q.x + q.y + q.z + q.w));
}
const int s = iu / QK8_1; // sub-block
const int k = iu % QK8_1; // first value in sub-block
if constexpr (wmma) {
((int *) yg)[(s*MMQ_FEW_WMMA_NCOLS + g)*8 + k/4] = *(const int *) &q;
if (k == 0) {
int * ds = (int *) (yg + 8*MMQ_FEW_WMMA_NCOLS*2) + (s*2 + g % 2)*8 + g/2;
if constexpr (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4) {
*(float *) ds = d;
} else {
*(half2 *) ds = make_half2(d, sum);
}
}
return;
}
((int *) (yg + (s/2)*WARP_SIZE + 4*g + (k % 16)/4))[2*(s % 2) + k/16] = *(const int *) &q;
if (k == 0) {
int4 * ds = yg + 4*WARP_SIZE + 4*(g/2) + s/2;
@@ -696,8 +710,8 @@ 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 <typename src_t, mmq_q8_1_ds_layout ds_layout>
// Each thread quantizes 4 values of one column, see quantize.cuh for the layouts.
template <typename src_t, mmq_q8_1_ds_layout ds_layout, bool wmma>
static __global__ void quantize_mmq_few_q8_1(
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) {
@@ -715,9 +729,16 @@ static __global__ void quantize_mmq_few_q8_1(
const int64_t i3 = blockIdx.z / ne2;
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);
if constexpr (wmma) {
const int m = blockIdx.x % MMQ_FEW_WMMA_NCOLS; // column in group
int4 * yg = vy + ((blockIdx.z*(ne00/QK_K) + i0/QK_K)*(gridDim.x/MMQ_FEW_WMMA_NCOLS) + blockIdx.x/MMQ_FEW_WMMA_NCOLS)*MMQ_FEW_WMMA_Q8_1_INT4;
quantize_mmq_few_store<ds_layout, true>(xi, yg, i0 % QK_K, m);
return;
}
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;
quantize_mmq_few_store<ds_layout>(xi, yg, i0 % QK_K, g);
quantize_mmq_few_store<ds_layout, false>(xi, yg, i0 % QK_K, g);
}
// 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.
@@ -807,26 +828,26 @@ static __global__ void quantize_mmq_few_id_q8_1(
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);
quantize_mmq_few_store<ds_layout, false>(xi, yg, i0 % QK_K, r % MMQ_FEW_NCOLS);
}
template <typename src_t>
static void quantize_mmq_few_q8_1_cuda(
template <bool wmma, typename src_t>
static void quantize_mmq_few_q8_1_launch(
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);
const int64_t block_num_y = (ne00 + 4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ - 1) / (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ);
const dim3 num_blocks(GGML_PAD(ne1, MMQ_FEW_NCOLS), block_num_y, ne2*ne3);
const dim3 num_blocks(GGML_PAD(ne1, wmma ? MMQ_FEW_WMMA_NCOLS : MMQ_FEW_NCOLS), block_num_y, ne2*ne3);
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
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<src_t, 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, wmma>, 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<src_t, 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, wmma>, launch_params,
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
break;
default:
@@ -838,7 +859,15 @@ 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);
quantize_mmq_few_q8_1_launch<false>(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
});
}
void quantize_mmq_few_wmma_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_launch<true>(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
});
}
+11
View File
@@ -42,6 +42,17 @@ void quantize_mmq_few_id_q8_1_cuda(
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);
// src1 of the few-row MMQ for RDNA3 WMMA, which multiplies 16 src1 columns and needs the same A and B data in both half-warps.
// Per channel, 256 values and group of MMQ_FEW_WMMA_NCOLS columns:
// qs: int4[8][16][2], [s][m][k] holds the values [16k, 16k + 16) of sub-block s of column m, the A fragments of lanes m and m + 16.
// ds: int4[8][2][2], [s][h][k] holds d (D4, float) or (d, sum) (DS4, half2) of sub-block s of the columns 2v + h, v = 4k .. 4k + 3.
static constexpr int MMQ_FEW_WMMA_NCOLS = 16;
static constexpr int MMQ_FEW_WMMA_Q8_1_INT4 = 8*16*2 + 8*2*2;
void quantize_mmq_few_wmma_q8_1_cuda(
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);
void quantize_mmq_fp4_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids,
+1 -1
View File
@@ -218,7 +218,7 @@ __global__ void __launch_bounds__(d_state, 1)
}
// parallel accumulation for output
state_sum = warp_reduce_sum(state_sum);
state_sum = warp_reduce_sum<WARP_SIZE, true>(state_sum);
if (lane == 0) {
y_warp[i * stride_y] = state_sum;
+31 -1
View File
@@ -31,7 +31,7 @@ typedef uint64_t ggml_cuda_thread_mask_t;
#define CU_MEM_ALLOCATION_TYPE_PINNED hipMemAllocationTypePinned
#define CU_MEM_LOCATION_TYPE_DEVICE hipMemLocationTypeDevice
#define CU_MEM_ACCESS_FLAGS_PROT_READWRITE hipMemAccessFlagsProtReadWrite
#define CU_CHECK(fn) {hipError_t err = fn; if(err != hipSuccess) { GGML_ABORT("HipVMM Failure: %s\n", hipGetErrorString(err)); }}
#define CU_CHECK(fn) do { hipError_t err_ = (fn); if (err_ != hipSuccess) { GGML_ABORT("HipVMM Failure: %s\n", hipGetErrorString(err_)); } } while (0)
#define cublasStrsmBatched hipblasStrsmBatched
#define cublasCreate hipblasCreate
#define cublasDestroy hipblasDestroy
@@ -333,3 +333,33 @@ static __device__ __forceinline__ uint32_t ggml_hip_perm(const uint32_t hi, cons
return __builtin_amdgcn_perm(hi, lo, sel);
#endif // __has_builtin(__builtin_amdgcn_is_invocable)
}
// DPP control codes.
#define GGML_HIP_DPP_QUAD_PERM_1032 0x0b1 // quad_perm:[1,0,3,2]
#define GGML_HIP_DPP_QUAD_PERM_2301 0x04e // quad_perm:[2,3,0,1]
#define GGML_HIP_DPP_ROW_HALF_MIRROR 0x141 // row_half_mirror
#define GGML_HIP_DPP_ROW_ROR_8 0x128 // row_ror:8
#define GGML_HIP_DPP_ROW_BCAST_15 0x142 // row_bcast:15, GCN/CDNA only
#define GGML_HIP_DPP_ROW_BCAST_31 0x143 // row_bcast:31, GCN/CDNA only
#define GGML_HIP_DPP_WAVE_ROR_1 0x13c // wave_ror:1
// DS swizzle mask codes.
#define GGML_HIP_SWIZZLE_SWAP16 0x401F // XOR16 within each 32-lane group
template <int dpp_ctrl, typename T>
static __device__ __forceinline__ T ggml_hip_dpp_update(T x) {
static_assert(sizeof(T) == 4, "DPP updates require 32-bit values");
union { T t; int i; } value;
value.t = x;
value.i = __builtin_amdgcn_update_dpp(value.i, value.i, dpp_ctrl, 0xf, 0xf, true);
return value.t;
}
template <int swizzle_mask, typename T>
static __device__ __forceinline__ T ggml_hip_swizzle(T x) {
static_assert(sizeof(T) == 4, "DS swizzle requires 32-bit values");
union { T t; int i; } value;
value.t = x;
value.i = __builtin_amdgcn_ds_swizzle(value.i, swizzle_mask);
return value.t;
}
+1 -1
View File
@@ -180,7 +180,7 @@ rwkv_wkv7_f32_t1_warp_row(const int T, const int C, const int H, const float * r
const float vt = v[t];
const float st0 = s0 * _w[lane] + _k[lane] * vt + sa * _b[lane];
const float st1 = s1 * _w[lane + half_head] + _k[lane + half_head] * vt + sa * _b[lane + half_head];
const float y = warp_reduce_sum(st0 * _r[lane] + st1 * _r[lane + half_head]);
const float y = warp_reduce_sum<WARP_SIZE, true>(st0 * _r[lane] + st1 * _r[lane + half_head]);
dst[T * C + state_base + lane] = st0;
dst[T * C + state_base + lane + half_head] = st1;
+1 -1
View File
@@ -1281,7 +1281,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] &&
(op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] &&
(op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr &&
!ggml_flash_attn_ext_has_indexed_bias(op) &&
!ggml_flash_attn_ext_has_bias(op) &&
ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) {
float max_bias = 0.0f;
float logit_softcap = 0.0f;
+53 -30
View File
@@ -135,6 +135,7 @@ size_t opt_mbuf_static = 1ul * 1024 * 1024 * 1024; // max static (weight/KV) buf
size_t opt_mbuf_total = 0; // total buffer space limit (0 = unconstrained)
int opt_mm_select = 3; // 3 = W8A8 INT HMX -> FP16 HMX -> HVX -> CPU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
int opt_mm_fwht = 0; // 1 = enable online block-32 FWHT rotation in W8A8 HMX matmul, 0 = off (default)
int opt_fa_select = 3; // 3 = INT HMX W8A8 (default) -> FP16 HMX -> HVX -> CPU, 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
int opt_fa_split = 1; // 1 = head-split + team-split when n_kv_heads < N_cores (default), 0 = off
int opt_li_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported)
@@ -365,7 +366,7 @@ struct ggml_hexagon_session {
std::unordered_map<uint64_t, volatile uint32_t *> cpy_fence_slots;
void enqueue_mdev_group();
void enqueue_op(const htp_opnode & node, bool allow_fuse = true);
void enqueue_op(const htp_opnode & node, bool fusable = false);
void enqueue_cpy(const ggml_tensor * src, ggml_tensor * dst, const ggml_tensor * sync_tensor = nullptr, uint32_t fence_seq = 0);
void enqueue_fence(const ggml_tensor * sync_tensor, uint32_t fence_seq = 0, bool wait = true);
void enqueue_allreduce(const ggml_tensor * dst, const std::vector<const ggml_tensor *> & src_tensors,
@@ -1342,26 +1343,27 @@ struct ggml_hexagon_tensor_map {
};
struct ggml_hexagon_opbatch {
ggml_hexagon_session* sess;
ggml_hexagon_session* sess;
std::vector<htp_opnode> ops; // htp_opnode of ops
std::vector<htp_buf_desc> h_bufs; // htp buffer descriptors
std::vector<htp_tensor> h_tens; // htp tensor descriptors
std::vector<htp_op_desc> h_ops; // htp op descriptors
std::vector<htp_opnode> ops; // htp_opnode of ops
std::vector<htp_buf_desc> h_bufs; // htp buffer descriptors
std::vector<htp_tensor> h_tens; // htp tensor descriptors
std::vector<htp_op_desc> h_ops; // htp op descriptors
ggml_hexagon_tensor_map t_map; // tensor hash to index
ggml_hexagon_tensor_map t_map; // tensor hash to index
unsigned int n_bufs; // num buffers in the batch
unsigned int n_tens; // num tensors ...
unsigned int n_ops; // num ops ...
size_t b_vmem; // sum of non-extended buffer sizes
bool last_op_fusable;
unsigned int n_bufs; // num buffers in the batch
unsigned int n_tens; // num tensors ...
unsigned int n_ops; // num ops ...
size_t b_vmem; // sum of non-extended buffer sizes
unsigned int n_bufs_max;
unsigned int n_tens_max;
unsigned int n_ops_max;
size_t b_vmem_max;
bool last_op_fusable;
void reset() {
n_bufs = 0;
n_tens = 0;
@@ -1586,14 +1588,14 @@ struct ggml_hexagon_opbatch {
}
// caller must ensure the op fits
void add_op(const htp_opnode & node, bool save_op = true) {
void add_op(const htp_opnode & node, bool save_op = true, bool fusable = false) {
unsigned int n = n_ops++;
GGML_ASSERT(n_ops <= n_ops_max);
if (save_op) {
ops[n] = node;
}
last_op_fusable = save_op;
last_op_fusable = fusable;
h_ops[n].flags = 0;
if (opt_verbose) {
@@ -1656,6 +1658,7 @@ struct ggml_hexagon_opbatch {
htp_lower_opnode(sess, last_node);
sync_op_desc(n_ops - 1, last_node);
last_op_fusable = false;
HEX_VERBOSE("ggml-hex: %s fused %s (N=%zu, #%u)\n",
sess->c_name(), last_node.name().c_str(), last_node.fused.size() + 1, n_ops - 1);
return true;
@@ -1970,7 +1973,7 @@ void ggml_hexagon_session::flush_batch(size_t min_ops) {
op_batch->reset();
}
void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse) {
void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool fusable) {
auto register_tensor = [&](const ggml_tensor * t) {
if (!t) return;
auto * sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
@@ -2000,7 +2003,7 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse)
}
const bool fits_tensors = op_batch->fit_tensors(node);
if (opt_opfusion && allow_fuse && fits_tensors && op_batch->try_fuse(node)) {
if (opt_opfusion && fits_tensors && op_batch->try_fuse(node)) {
return;
}
@@ -2015,7 +2018,8 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse)
}
}
op_batch->add_op(node, opt_profile || (opt_opfusion && allow_fuse));
const bool mark_fusable = opt_opfusion && fusable;
op_batch->add_op(node, opt_profile || mark_fusable, mark_fusable);
}
void ggml_hexagon_session::enqueue_mdev_group() {
@@ -2104,7 +2108,7 @@ void ggml_hexagon_session::enqueue_allreduce(
this, dst, rank, n_ranks, false, false, /*is_shard_ok=*/ false,
ar_node.kparams<htp_allreduce_kernel_params>());
this->enqueue_op(ar_node);
this->enqueue_op(ar_node, /*fusable=*/ true);
}
void ggml_hexagon_session::mmap_buffers() {
@@ -2629,6 +2633,30 @@ static void ggml_hexagon_graph_repack(const ggml_cgraph * graph, ggml_hexagon_se
}
}
static void ggml_hexagon_graph_append_opnode(
const ggml_hexagon_session * sess,
std::vector<htp_opnode> & nodes,
htp_opnode && node
) {
const ggml_tensor * n = node.node;
const ggml_tensor * scale = ggml_get_src_scale(n, 0);
const bool fused_scale = scale != nullptr &&
(node.opcode == HTP_OP_MUL_MAT || node.opcode == HTP_OP_MUL_MAT_ID) &&
(node.kparams<htp_mm_kernel_params>()->scale_mask != 0);
if (fused_scale) {
node.inputs.push_back(scale);
}
if (nodes.empty() || !opt_opfusion || !htp_fusion_try_fuse(sess, nodes.back(), node)) {
nodes.push_back(std::move(node));
}
if (scale && !fused_scale) {
htp_opnode scale_node = htp_mm_make_scale_opnode(n, scale);
GGML_ASSERT(htp_kparams_solve(sess, scale_node));
nodes.push_back(std::move(scale_node));
}
}
static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, ggml_cgraph * graph) {
auto sess = static_cast<ggml_hexagon_session *>(backend->context);
@@ -2662,9 +2690,7 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg
htp_opnode node(opcode, n);
GGML_ASSERT(htp_kparams_solve(sess, node));
if (nodes.empty() || !opt_opfusion || !htp_fusion_try_fuse(sess, nodes.back(), node)) {
nodes.push_back(std::move(node));
}
ggml_hexagon_graph_append_opnode(sess, nodes, std::move(node));
}
if (opt_opfusion) {
@@ -2677,7 +2703,7 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg
}
for (const auto & node : sess->cached_nodes) {
sess->enqueue_op(node, false);
sess->enqueue_op(node);
}
if (sess->last_error > HTP_STATUS_OK) {
@@ -3233,10 +3259,7 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons
return false;
}
if (ggml_get_src_scale(op, 0)) {
return false;
}
// src_scale(op, 1) is an activation quantization hint for quantized-activation backends, ignored for F32/F16 activations
bool supp = false;
if (ggml_op_is_empty(op->op) || ggml_is_empty(op)) {
supp = true;
@@ -3636,6 +3659,8 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
"please update hexagon_type to match ggml_type");
static_assert((unsigned int) HTP_TYPE_Q2_0 == (unsigned int) GGML_TYPE_Q2_0,
"please update hexagon_type to match ggml_type");
static_assert((unsigned int) HTP_TYPE_F8_E4M3 == (unsigned int) GGML_TYPE_F8_E4M3,
"please update hexagon_type to match ggml_type");
static_assert((unsigned int) HTP_TYPE_BF16 == (unsigned int) GGML_TYPE_BF16,
"please update hexagon_type to match ggml_type");
@@ -3653,6 +3678,7 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
const char * str_nhmx = getenv("GGML_HEXAGON_NHMX");
const char * str_vtcm_size = getenv("GGML_HEXAGON_VTCM_SIZE");
const char * str_mm_select = getenv("GGML_HEXAGON_MM_SELECT");
const char * str_mm_fwht = getenv("GGML_HEXAGON_MM_FWHT");
const char * str_fa_select = getenv("GGML_HEXAGON_FA_SELECT");
const char * str_fa_split = getenv("GGML_HEXAGON_FA_SPLIT");
const char * str_li_select = getenv("GGML_HEXAGON_LI_SELECT");
@@ -3727,6 +3753,7 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
opt_nhmx = str_nhmx ? atoi(str_nhmx) : opt_nhmx;
opt_vtcm_size = str_vtcm_size ? parse_size(str_vtcm_size) : opt_vtcm_size;
opt_mm_select = str_mm_select ? atoi(str_mm_select) : opt_mm_select;
opt_mm_fwht = str_mm_fwht ? atoi(str_mm_fwht) : opt_mm_fwht;
opt_fa_select = str_fa_select ? atoi(str_fa_select) : opt_fa_select;
opt_fa_split = str_fa_split ? atoi(str_fa_split) : opt_fa_split;
opt_li_select = str_li_select ? atoi(str_li_select) : opt_li_select;
@@ -3954,10 +3981,6 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
for (size_t i = 0; i < opt_ndev; i++) {
total_sessions += opt_device_configs[i].mdev_group.size();
}
if (!str_mm_select && hw_arch == 73 && total_sessions > 1) {
opt_mm_select = 2;
GGML_LOG_INFO("ggml-hex: defaulting MM_SELECT=2 on multi-session v73 hardware\n");
}
if (!str_fa_select && hw_arch == 73 && total_sessions > 1) {
opt_fa_select = 2;
GGML_LOG_INFO("ggml-hex: defaulting FA_SELECT=2 on multi-session v73 hardware\n");
+35
View File
@@ -21,6 +21,7 @@ extern size_t opt_mbuf_static;
extern size_t opt_mbuf_total;
extern int opt_mm_select;
extern int opt_mm_fwht;
extern int opt_fa_select;
extern int opt_fa_split;
extern int opt_li_select;
@@ -154,4 +155,38 @@ uint32_t htp_session_mdev_count(const struct ggml_hexagon_session * sess);
htp_op_code htp_op_remap(const struct ggml_tensor * t);
enum htp_mm_scale_mode {
HTP_MM_SCALE_NONE = 0,
HTP_MM_SCALE_PER_TENSOR,
HTP_MM_SCALE_PER_CHANNEL,
HTP_MM_SCALE_PER_EXPERT,
HTP_MM_SCALE_PER_CHANNEL_EXPERT,
};
// classify weight scale (src_scale(op, 0)) of GGML_OP_MUL_MAT / GGML_OP_MUL_MAT_ID
static inline enum htp_mm_scale_mode htp_get_mm_scale_mode(const struct ggml_tensor * op) {
const struct ggml_tensor * scale = ggml_get_src_scale(op, 0);
if (!scale) {
return HTP_MM_SCALE_NONE;
}
if (ggml_is_scalar(scale)) {
return HTP_MM_SCALE_PER_TENSOR;
}
if (op->op == GGML_OP_MUL_MAT_ID) {
const int64_t n_out = op->src[0]->ne[1];
const int64_t n_expert = op->src[0]->ne[2];
if (scale->ne[0] == n_out && scale->ne[1] == n_expert && scale->ne[2] == 1 && scale->ne[3] == 1) {
return HTP_MM_SCALE_PER_CHANNEL_EXPERT;
}
if (ggml_is_vector(scale) && scale->ne[0] == n_expert) {
return HTP_MM_SCALE_PER_EXPERT;
}
GGML_ABORT("invalid MUL_MAT_ID weight scale shape");
}
if (ggml_is_vector(scale) && scale->ne[0] == op->src[0]->ne[1]) {
return HTP_MM_SCALE_PER_CHANNEL;
}
GGML_ABORT("invalid MUL_MAT weight scale shape");
}
#endif // HTP_COMMON_H
File diff suppressed because it is too large Load Diff
+1
View File
@@ -21,6 +21,7 @@ enum htp_fusion_flags {
HTP_FUSE_GDN_STATE = (1 << 15), // 32768
HTP_FUSE_CONCAT_SSM_CONV = (1 << 16), // 65536
HTP_FUSE_MUL_MAT_NX_GLU = (1 << 17), // 131072
HTP_FUSE_RMS_NORM_MUL_MM = (1 << 18), // 262144
};
static inline bool htp_fusion_enabled(int flag) {
File diff suppressed because it is too large Load Diff
+3 -84
View File
@@ -80,90 +80,9 @@ bool htp_kparams_solve_allreduce(
struct htp_allreduce_kernel_params * kparams
);
bool htp_kparams_solve_rms_norm_mul(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
const struct ggml_tensor * dst,
struct htp_unary_kernel_params * kparams
);
bool htp_kparams_solve_rms_norm_mul_add(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
const struct ggml_tensor * src2,
const struct ggml_tensor * dst,
struct htp_unary_kernel_params * kparams
);
bool htp_kparams_solve_matmul_add(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
const struct ggml_tensor * bias,
const struct ggml_tensor * dst,
struct htp_mm_kernel_params * kparams
);
bool htp_kparams_solve_mmnx(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * act,
const struct ggml_tensor * dst,
int32_t n_weights,
struct htp_mm_kernel_params * kparams
);
bool htp_kparams_solve_mmnx_glu(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * w_gate,
const struct ggml_tensor * w_up,
const struct ggml_tensor * act,
const struct ggml_tensor * dst,
uint8_t glu_op,
struct htp_mm_kernel_params * kparams
);
bool htp_kparams_solve_mmidnx(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * act,
const struct ggml_tensor * dst,
int32_t n_weights,
struct htp_mm_kernel_params * kparams
);
bool htp_kparams_solve_repeat_get_rows(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
const struct ggml_tensor * dst,
struct htp_get_rows_kernel_params * kparams
);
bool htp_kparams_solve_unary_mul_glu(
const struct ggml_hexagon_session * sess,
uint32_t op,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
const struct ggml_tensor * dst,
struct htp_glu_kernel_params * kparams
);
bool htp_kparams_solve_upscale(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * dst,
struct htp_upscale_kernel_params * kparams
);
static inline bool htp_kparams_solve_upscale(
const struct ggml_hexagon_session * sess,
struct htp_opnode htp_mm_make_scale_opnode(
const struct ggml_tensor * op,
struct htp_upscale_kernel_params * kparams
) {
return htp_kparams_solve_upscale(sess, op->src[0], op, kparams);
}
const struct ggml_tensor * scale
);
#endif // HTP_KPARAMS_H
+71 -34
View File
@@ -23,7 +23,8 @@ bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride) {
bool htp_matmul_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst) {
size_t s1, sd;
return (dst->op == GGML_OP_MUL_MAT || dst->op == GGML_OP_ADD) &&
return (dst->op == GGML_OP_MUL_MAT || dst->op == GGML_OP_ADD ||
dst->op == GGML_OP_GLU || dst->op == GGML_OP_MUL) &&
src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] * src1->ne[3] > 1 &&
src1->nb[0] == ggml_type_size(src1->type) && htp_rows_stride(src1->ne, src1->nb, &s1) &&
dst->nb[0] == ggml_type_size(dst->type) && htp_rows_stride(dst->ne, dst->nb, &sd);
@@ -427,26 +428,16 @@ void htp_lightning_indexer_collapse_tensors(
}
}
void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch) {
const uint32_t n_hvx = htp_session_n_hvx(sess);
const size_t n_in = node.inputs.size();
const size_t n_out = node.outputs.size();
ggml_tensor in_mat[HTP_OP_MAX_INPUTS] = {};
ggml_tensor out_mat[HTP_OP_MAX_OUTPUTS] = {};
bool in_dirty[HTP_OP_MAX_INPUTS] = {};
bool out_dirty[HTP_OP_MAX_OUTPUTS] = {};
for (size_t i = 0; i < n_in; ++i) {
if (node.inputs[i]) {
in_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.inputs[i]);
in_mat[i] = htp_tensor_lower_f16(node.inputs[i]);
}
}
for (size_t i = 0; i < n_out; ++i) {
out_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.outputs[i]);
out_mat[i] = htp_tensor_lower_f16(node.outputs[i]);
}
static void htp_collapse_opnode_tensors(
uint32_t n_hvx,
const htp_opnode & node,
ggml_tensor (& in_mat)[HTP_OP_MAX_INPUTS],
ggml_tensor (& out_mat)[HTP_OP_MAX_OUTPUTS],
bool (& in_dirty)[HTP_OP_MAX_INPUTS],
bool (& out_dirty)[HTP_OP_MAX_OUTPUTS]
) {
const size_t n_in = node.inputs.size();
const size_t n_out = node.outputs.size();
if (htp_op_is_unary(node.opcode) && htp_unary_is_elementwise(node.opcode)) {
if (n_in >= 1 && n_out >= 1 &&
@@ -497,8 +488,9 @@ void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & nod
}
}
} else if (node.opcode == HTP_OP_MUL_MAT_NX) {
const size_t n_w = n_out;
if (n_w > 0 && n_in == n_w + 1) {
const size_t n_w = n_out;
const size_t norm_extra = (node.kparams<htp_mm_kernel_params>()->norm_w_idx != 0) ? 1 : 0;
if (n_w > 0 && (n_in == n_w + 1 + norm_extra || n_in == 2 * n_w + 1 + norm_extra)) {
bool can_collapse = true;
for (size_t i = 0; i < n_w; ++i) {
if (!htp_matmul_can_collapse(&in_mat[i], &in_mat[n_w], &out_mat[i])) {
@@ -516,7 +508,8 @@ void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & nod
}
}
} else if (node.opcode == HTP_OP_MUL_MAT_NX_GLU) {
if (n_in == 3 && n_out == 1 &&
const size_t norm_extra = (node.kparams<htp_mm_kernel_params>()->norm_w_idx != 0) ? 1 : 0;
if ((n_in == 3 + norm_extra || n_in == 5 + norm_extra) && n_out == 1 &&
htp_matmul_can_collapse(&in_mat[0], &in_mat[2], &out_mat[0]) &&
htp_matmul_can_collapse(&in_mat[1], &in_mat[2], &out_mat[0])) {
in_mat[2] = htp_tensor_collapse_rows(&in_mat[2]);
@@ -591,6 +584,30 @@ void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & nod
out_dirty[0] = true;
}
}
}
void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch) {
const uint32_t n_hvx = htp_session_n_hvx(sess);
const size_t n_in = node.inputs.size();
const size_t n_out = node.outputs.size();
ggml_tensor in_mat[HTP_OP_MAX_INPUTS] = {};
ggml_tensor out_mat[HTP_OP_MAX_OUTPUTS] = {};
bool in_dirty[HTP_OP_MAX_INPUTS] = {};
bool out_dirty[HTP_OP_MAX_OUTPUTS] = {};
for (size_t i = 0; i < n_in; ++i) {
if (node.inputs[i]) {
in_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.inputs[i]);
in_mat[i] = htp_tensor_lower_f16(node.inputs[i]);
}
}
for (size_t i = 0; i < n_out; ++i) {
out_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.outputs[i]);
out_mat[i] = htp_tensor_lower_f16(node.outputs[i]);
}
htp_collapse_opnode_tensors(n_hvx, node, in_mat, out_mat, in_dirty, out_dirty);
size_t n_scratch = 0;
auto commit_tensor = [&](const ggml_tensor & m) -> const ggml_tensor * {
@@ -714,13 +731,19 @@ static bool htp_lower_is_mm_opcode(uint32_t opcode) {
opcode == HTP_OP_MUL_MAT_NX_GLU || opcode == HTP_OP_MUL_MAT_ID_NX;
}
static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node, const ggml_tensor * tensor) {
static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node, const ggml_tensor * tensor, uint32_t * out_w_idx) {
if (out_w_idx) {
*out_w_idx = 0;
}
if (!htp_lower_is_mm_opcode(node.opcode)) {
return nullptr;
}
if (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX) {
for (size_t p = 0; p < node.outputs.size(); ++p) {
if (node.outputs[p] == tensor) {
if (out_w_idx) {
*out_w_idx = (uint32_t) p;
}
if (p == 0) {
return node.node;
}
@@ -732,10 +755,14 @@ static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node,
return node.node;
}
static bool htp_lower_mm_blocks_output_f16(const ggml_tensor * orig_mm) {
static bool htp_lower_mm_blocks_output_f16(const htp_opnode & owner, const ggml_tensor * orig_mm, uint32_t w_idx) {
if (!orig_mm) {
return false;
}
const auto * kp = owner.kparams<htp_mm_kernel_params>();
if (((kp->scale_mask >> w_idx) & 1u) == 0 && ggml_get_src_scale(orig_mm, 0) != nullptr) {
return true;
}
if (ggml_prec_get_acc(orig_mm) == GGML_PREC_F32) {
return true;
}
@@ -752,14 +779,21 @@ static bool htp_lower_respect_prec_hints(
const std::unordered_map<const ggml_tensor *, std::vector<size_t>> & root_users
) {
if (htp_lower_is_mm_opcode(owner.opcode)) {
const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(owner, r);
if (htp_lower_mm_blocks_output_f16(orig_mm)) {
uint32_t w_idx = 0;
const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(owner, r, &w_idx);
if (owner.opcode == HTP_OP_MUL_MAT_NX_GLU && orig_mm && owner.inputs.size() >= 2 && orig_mm->src[0] == owner.inputs[1]) {
w_idx = 1;
}
if (htp_lower_mm_blocks_output_f16(owner, orig_mm, w_idx)) {
return false;
}
if (owner.opcode == HTP_OP_MUL_MAT_NX_GLU) {
for (const ggml_tensor * f : owner.fused) {
if (f && f->op == GGML_OP_MUL_MAT && htp_lower_mm_blocks_output_f16(f)) {
return false;
if (f && f->op == GGML_OP_MUL_MAT) {
const uint32_t f_idx = (owner.inputs.size() >= 2 && f->src[0] == owner.inputs[1]) ? 1u : 0u;
if (htp_lower_mm_blocks_output_f16(owner, f, f_idx)) {
return false;
}
}
}
}
@@ -769,9 +803,12 @@ static bool htp_lower_respect_prec_hints(
auto oit = owner_idx.find(in_root);
if (oit != owner_idx.end()) {
const htp_opnode & node = nodes[oit->second];
if (htp_lower_is_mm_opcode(node.opcode) &&
htp_lower_mm_blocks_output_f16(htp_lower_orig_mm_for_output(node, in_root))) {
return false;
if (htp_lower_is_mm_opcode(node.opcode)) {
uint32_t w_idx = 0;
const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(node, in_root, &w_idx);
if (htp_lower_mm_blocks_output_f16(node, orig_mm, w_idx)) {
return false;
}
}
}
}
@@ -1201,7 +1238,7 @@ void htp_lower_graph(const struct ggml_hexagon_session * sess, const struct ggml
}
for (const ggml_tensor * inp : tnode->inputs) {
const ggml_tensor * inp_root = inp ? htp_tensor_root(inp) : nullptr;
if (inp_root && can_lower(inp_root) && is_selected_root(inp_root) && apply_root(inp_root)) {
if (inp_root && can_lower(inp_root) && apply_root(inp_root)) {
expanded = true;
}
}
+58 -13
View File
@@ -3,6 +3,7 @@
#include "htp/allreduce-ops.h"
#include "htp/argsort-ops.h"
#include "htp/binary-ops.h"
#include "htp/conv2d-ops.h"
#include "htp/cumsum-ops.h"
#include "htp/diag-ops.h"
#include "htp/dsv4-hc-ops.h"
@@ -11,11 +12,13 @@
#include "htp/gated-delta-net-ops.h"
#include "htp/get-rows-ops.h"
#include "htp/glu-ops.h"
#include "htp/im2col-ops.h"
#include "htp/lightning-indexer-ops.h"
#include "htp/matmul-ops.h"
#include "htp/pad-ops.h"
#include "htp/repeat-ops.h"
#include "htp/roll-ops.h"
#include "htp/set-rows-ops.h"
#include "htp/softmax-ops.h"
#include "htp/solve-tri-ops.h"
#include "htp/ssm-conv.h"
@@ -48,6 +51,7 @@ std::string htp_opnode::name() const {
}
}
case HTP_OP_MUL_MAT_ID_NX: return "MUL_MAT_ID_NX";
case HTP_OP_MUL_ID: return "MUL_ID";
case HTP_OP_ADD:
case HTP_OP_SUB:
case HTP_OP_MUL:
@@ -64,6 +68,15 @@ std::string htp_opnode::name() const {
}
}
}
if (!node) {
switch (opcode) {
case HTP_OP_ADD: return "ADD";
case HTP_OP_SUB: return "SUB";
case HTP_OP_MUL: return "MUL";
case HTP_OP_DIV: return "DIV";
default: break;
}
}
break;
default:
break;
@@ -161,10 +174,11 @@ static std::string format_kernel_params(const htp_opnode & node) {
const auto * kparams = node.kparams<htp_mm_kernel_params>();
int32_t type = kparams->kernel_type;
if (htp_mm_kernel_is_hmx_w8a8(type)) {
snprintf(str, max_size, "hmx-w8a8 nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
snprintf(str, max_size, "hmx-w8a8%s nhvx %u vtcm %u",
kparams->norm_w_idx ? "+norm" : "", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else {
const char * path = "unknown";
if (type == HTP_MM_KERNEL_HMX_2D || type == HTP_MM_KERNEL_HMX_BATCHED) {
if (htp_mm_kernel_is_hmx_f16(type)) {
path = (kparams->tile_size > 0) ? "hmx-tiled" : "hmx-flat";
} else if (type == HTP_MM_KERNEL_HVX_F16_F16_VTCM || type == HTP_MM_KERNEL_HVX_F32_F32_VTCM ||
type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM) {
@@ -172,16 +186,17 @@ static std::string format_kernel_params(const htp_opnode & node) {
} else if (type == HTP_MM_KERNEL_HVX_QUANT_ROW || type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) {
path = "hvx-tiled";
}
snprintf(str, max_size, "%s nhvx %u vtcm %u", path, (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
snprintf(str, max_size, "%s%s nhvx %u vtcm %u", path, kparams->norm_w_idx ? "+norm" : "",
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
}
} else if (node.opcode == HTP_OP_FLASH_ATTN_EXT) {
const auto * kparams = node.kparams<htp_fa_kernel_params>();
const char * path = "unknown";
int32_t type = kparams->kernel_type;
if (type == HTP_FA_KERNEL_HMX_F16) {
path = kparams->u.hmx.pipeline ? "hmx-f16-pipe" : "hmx-f16-seq";
path = (kparams->flags & HTP_FA_FLAG_PIPELINE) ? "hmx-f16-pipe" : "hmx-f16-seq";
} else if (type == HTP_FA_KERNEL_HMX_W8A8) {
path = kparams->u.hmx.pipeline ? "hmx-w8a8-pipe" : "hmx-w8a8-seq";
path = (kparams->flags & HTP_FA_FLAG_PIPELINE) ? "hmx-w8a8-pipe" : "hmx-w8a8-seq";
} else if (type == HTP_FA_KERNEL_HVX) {
path = "hvx";
}
@@ -194,11 +209,14 @@ static std::string format_kernel_params(const htp_opnode & node) {
snprintf(str, max_size, "idx %d count %d", (int) node.node->op_params[0], (int) node.dst()->ne[1]);
} else if ((node.opcode == HTP_OP_FENCE || node.opcode == HTP_OP_CPY_FENCE) && node.node) {
snprintf(str, max_size, "seq 0x%x", (uint32_t) node.node->op_params[0]);
} else if (node.opcode == HTP_OP_ALLREDUCE && node.node) {
snprintf(str, max_size, "seq 0x%x -> 0x%x", (uint32_t) node.node->op_params[0], (uint32_t) node.node->op_params[1]);
} else if ((node.opcode == HTP_OP_ALLREDUCE || node.opcode == HTP_OP_ALLREDUCE_ADD) && node.node) {
const auto * kparams = node.kparams<htp_allreduce_kernel_params>();
snprintf(str, max_size, "seq 0x%x -> 0x%x nhvx %u vtcm %u",
(uint32_t) node.node->op_params[0], (uint32_t) node.node->op_params[1],
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SSM_CONV) {
const auto * kparams = node.kparams<htp_ssm_conv_kernel_params>();
const char * mode = kparams->token_major
const char * mode = (kparams->flags & HTP_SSM_CONV_FLAG_TOKEN_MAJOR)
? (kparams->n_t == 1 ? "tok-decode" : "tok-prefill")
: (kparams->n_t == 1 ? "decode" : "prefill");
snprintf(str, max_size, "%s nhvx %u vtcm %u", mode,
@@ -236,7 +254,7 @@ static std::string format_kernel_params(const htp_opnode & node) {
(unsigned int) kparams->n_hvx, (unsigned int) kparams->n_tokens_tile,
(unsigned int) kparams->kv_block, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_MUL || node.opcode == HTP_OP_ADD || node.opcode == HTP_OP_ADD_ID ||
node.opcode == HTP_OP_SUB || node.opcode == HTP_OP_DIV) {
node.opcode == HTP_OP_MUL_ID || node.opcode == HTP_OP_SUB || node.opcode == HTP_OP_DIV) {
const auto * kparams = node.kparams<htp_binary_kernel_params>();
snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_ARGSORT || node.opcode == HTP_OP_TOP_K) {
@@ -273,16 +291,43 @@ static std::string format_kernel_params(const htp_opnode & node) {
snprintf(str, max_size, "%s nhvx %u tile %u x%u vtcm %u", ktype_str, (unsigned int) kparams->n_hvx, (unsigned int) kparams->tile_cols, (unsigned int) kparams->n_col_tiles, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_FILL) {
const auto * kparams = node.kparams<htp_fill_kernel_params>();
snprintf(str, max_size, "%s nhvx %u", kparams->kernel_type == HTP_FILL_KERNEL_CONTIGUOUS ? "contig" : "strided", (unsigned int) kparams->n_hvx);
snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->kernel_type == HTP_FILL_KERNEL_CONTIGUOUS ? "contig" : "strided",
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_ROLL) {
const auto * kparams = node.kparams<htp_roll_kernel_params>();
snprintf(str, max_size, "k%d nhvx %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx);
snprintf(str, max_size, "k%d nhvx %u vtcm %u", (int) kparams->kernel_type,
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_DIAG) {
const auto * kparams = node.kparams<htp_diag_kernel_params>();
snprintf(str, max_size, "nhvx %u chunk %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->chunk_elems, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SOLVE_TRI) {
const auto * kparams = node.kparams<htp_solve_tri_kernel_params>();
snprintf(str, max_size, "%s nhvx %u", kparams->batched ? "batched" : "chunked", (unsigned int) kparams->n_hvx);
snprintf(str, max_size, "%s nhvx %u vtcm %u", (kparams->flags & HTP_SOLVE_TRI_FLAG_BATCHED) ? "batched" : "chunked",
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SUM_ROWS || node.opcode == HTP_OP_SUM || node.opcode == HTP_OP_ARGMAX) {
const auto * kparams = node.kparams<htp_sum_rows_kernel_params>();
snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SET_ROWS) {
const auto * kparams = node.kparams<htp_set_rows_kernel_params>();
snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_CONV_2D || node.opcode == HTP_OP_CONV_3D) {
const auto * kparams = node.kparams<htp_conv2d_kernel_params>();
snprintf(str, max_size, "%s nhvx %u vtcm %u",
kparams->kernel_type == HTP_CONV2D_KERNEL_HMX_WINDOW ? "window" : "tiled",
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_CONV_2D_DW) {
const auto * kparams = node.kparams<htp_conv2d_dw_kernel_params>();
snprintf(str, max_size, "k%d nhvx %u vtcm %u", (int) kparams->kernel_type,
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_IM2COL || node.opcode == HTP_OP_IM2COL_3D) {
const auto * kparams = node.kparams<htp_im2col_kernel_params>();
snprintf(str, max_size, "%s nhvx %u vtcm %u",
kparams->kernel_type == HTP_IM2COL_KERNEL_PATCHEMBED_DMA ? "patchembed" : "blocked",
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_REPEAT) {
const auto * kparams = node.kparams<htp_repeat_kernel_params>();
snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->pipelined ? "pipe" : "tiled",
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_UPSCALE) {
const auto * kparams = node.kparams<htp_upscale_kernel_params>();
const char * ktype_str = "unknown";
@@ -290,7 +335,7 @@ static std::string format_kernel_params(const htp_opnode & node) {
case HTP_UPSCALE_KERNEL_NEAREST: ktype_str = "nearest"; break;
case HTP_UPSCALE_KERNEL_NEAREST_2X: ktype_str = "nearest-2x"; break;
case HTP_UPSCALE_KERNEL_NEAREST_4X: ktype_str = "nearest-4x"; break;
case HTP_UPSCALE_KERNEL_BILINEAR: ktype_str = kparams->align_corners ? "bilinear-ac" : "bilinear"; break;
case HTP_UPSCALE_KERNEL_BILINEAR: ktype_str = (kparams->flags & HTP_UPSCALE_FLAG_ALIGN_CORNERS) ? "bilinear-ac" : "bilinear"; break;
case HTP_UPSCALE_KERNEL_BILINEAR_2X: ktype_str = "bilinear-2x"; break;
case HTP_UPSCALE_KERNEL_BILINEAR_AA: ktype_str = "bilinear-aa"; break;
case HTP_UPSCALE_KERNEL_BICUBIC: ktype_str = "bicubic"; break;
+7
View File
@@ -91,6 +91,13 @@ struct htp_opnode {
// Build inputs (preserving optional nullptrs)
if (htp_is_hadamard(this->node)) {
this->inputs.push_back(this->node->src[1]);
} else if (this->node->op == GGML_OP_MUL_MAT) {
this->inputs.push_back(this->node->src[0]);
this->inputs.push_back(this->node->src[1]);
} else if (this->node->op == GGML_OP_MUL_MAT_ID) {
this->inputs.push_back(this->node->src[0]);
this->inputs.push_back(this->node->src[1]);
this->inputs.push_back(this->node->src[2]);
} else if (this->node->op != GGML_OP_FILL) {
int n_inputs = n_active_src(this->node);
for (int i = 0; i < n_inputs; i++) {
+54
View File
@@ -1602,6 +1602,54 @@ static void repack_tiled_nvfp4(void * data, const ggml_tensor * t, size_t offset
}
}
// --- F8_E4M3 (1024 B tile: 32x32 in 4-K-grouped vrmpy byte order, lossless) ---
static void repack_f8_e4m3_to_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
repack_to_tiled_grid_32<uint8_t, 32>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_F8_E4M3,
[](uint8_t * tile_dst, const uint8_t * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
for (int p = 0; p < 8; p++) {
const int64_t c_base = (int64_t) kt * 32 + p * 4;
for (int row = 0; row < 32; row++) {
const int64_t r = (int64_t) ct * 32 + row;
const uint8_t * r_ptr = (r < ne1) ? &src_slice[r * row_stride] : nullptr;
uint8_t * dst = tile_dst + p * 128 + row * 4;
if (r_ptr && c_base + 4 <= ne0) {
memcpy(dst, r_ptr + c_base, 4);
} else {
for (int j = 0; j < 4; j++) {
dst[j] = (r_ptr && c_base + j < ne0) ? r_ptr[c_base + j] : 0;
}
}
}
}
});
}
static void unpack_f8_e4m3_from_tiled(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<uint8_t, 32>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_F8_E4M3,
[](uint8_t * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) {
for (int p = 0; p < 8; p++) {
const int64_t c_base = (int64_t) kt * 32 + p * 4;
for (int row = 0; row < 32; row++) {
const int64_t r = (int64_t) ct * 32 + row;
if (r >= start_row && r < end_row) {
uint8_t * r_ptr = dst_slice + (r - start_row) * row_stride;
const uint8_t * src = tile_src + p * 128 + row * 4;
if (c_base + 4 <= ne0) {
memcpy(r_ptr + c_base, src, 4);
} else {
for (int j = 0; j < 4; j++) {
if (c_base + j < ne0) {
r_ptr[c_base + j] = src[j];
}
}
}
}
}
}
});
}
// --- Top-level Repack / Unpack Dispatchers ---
void htp_repack_tensor_tiled(ggml_tensor * tensor, const void * data, size_t size) {
@@ -1631,6 +1679,9 @@ void htp_repack_tensor_tiled(ggml_tensor * tensor, const void * data, size_t siz
case GGML_TYPE_NVFP4:
repack_nvfp4_tiled(tensor, data, 0, size);
break;
case GGML_TYPE_F8_E4M3:
repack_f8_e4m3_to_tiled(tensor, data, 0, size);
break;
case GGML_TYPE_IQ2_XXS:
repack_iq2_xxs_tiled(tensor, data, 0, size);
break;
@@ -1698,6 +1749,9 @@ void htp_unpack_tensor_tiled(void * data, const ggml_tensor * tensor, size_t off
case GGML_TYPE_NVFP4:
repack_tiled_nvfp4(data, tensor, offset, size);
break;
case GGML_TYPE_F8_E4M3:
unpack_f8_e4m3_from_tiled(data, tensor, offset, size);
break;
case GGML_TYPE_IQ2_XXS:
repack_tiled_iq2_xxs(data, tensor, offset, size);
break;
+6 -2
View File
@@ -17,7 +17,11 @@ static inline bool htp_is_tiled_weight_type(enum ggml_type type) {
type == GGML_TYPE_Q2_K || type == GGML_TYPE_Q3_K ||
type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K ||
type == GGML_TYPE_F16 || type == GGML_TYPE_F32 ||
type == GGML_TYPE_BF16;
type == GGML_TYPE_BF16 || type == GGML_TYPE_F8_E4M3;
}
static inline bool htp_is_quantized_weight_type(enum ggml_type type) {
return ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3;
}
static inline bool htp_is_tiled_weight_tensor(const struct ggml_tensor * t) {
@@ -30,7 +34,7 @@ static inline bool htp_is_tiled_weight_tensor(const struct ggml_tensor * t) {
if (t->ne[0] < 32 || (t->ne[0] % 32 != 0) || t->ne[3] != 1) {
return false;
}
if (!ggml_is_quantized(t->type)) {
if (!htp_is_quantized_weight_type(t->type)) {
return t->ne[1] > 1;
}
return true;
+3
View File
@@ -23,6 +23,9 @@ add_library(${HTP_LIB} SHARED
hmx-queue.c
htp-tensor.c
matmul-ops.c
matmul-hmx-w8a8.c
matmul-hmx-f16.c
matmul-hvx.c
flash-attn-ops.c
gated-delta-net-ops.c
binary-ops.c
+11 -49
View File
@@ -21,7 +21,6 @@ struct htp_allreduce_context {
uint32_t n_dsts;
uint32_t nelem;
uint32_t ne0;
uint32_t ne1;
uint32_t row_size_aligned;
uint32_t rank_elem_start;
uint32_t rank_nelem;
@@ -251,38 +250,6 @@ DEFINE_ALLREDUCE_THREAD_DMA_2D(add_f32, float, hvx_add_f32_aaa, 1, 0)
DEFINE_ALLREDUCE_THREAD_DMA_2D(add_bcast_f16, __fp16, hvx_add_f16_aaa, 1, 1)
DEFINE_ALLREDUCE_THREAD_DMA_2D(add_bcast_f32, float, hvx_add_f32_aaa, 1, 1)
static int validate_allreduce(
struct htp_ops_context * octx,
const struct htp_allreduce_kernel_params * kparams,
uint32_t n_ranks
) {
if (kparams->n_hvx == 0 || (uint32_t) kparams->n_hvx > octx->ctx->n_hvx) {
return HTP_STATUS_INVAL_PARAMS;
}
octx->n_hvx = (uint32_t) kparams->n_hvx;
if (kparams->vtcm_size_per_hvx <= 0 || kparams->vtcm_size <= 0) {
return HTP_STATUS_INVAL_PARAMS;
}
const bool has_add = (octx->op == HTP_OP_ALLREDUCE_ADD);
const size_t n_vtcm_buffers = htp_allreduce_vtcm_buffer_count(
n_ranks, octx->n_hvx, has_add, kparams->is_row_bcast != 0);
const size_t vtcm_size = n_vtcm_buffers * (size_t) kparams->vtcm_size_per_hvx;
if (vtcm_size != (size_t) kparams->vtcm_size) {
return HTP_STATUS_INVAL_PARAMS;
}
if (vtcm_size > octx->ctx->vtcm_size) {
return HTP_STATUS_VTCM_TOO_SMALL;
}
if (octx->dst->type != HTP_TYPE_F16 && octx->dst->type != HTP_TYPE_F32) {
return HTP_STATUS_NO_SUPPORT;
}
return HTP_STATUS_OK;
}
int op_allreduce(struct htp_ops_context * octx) {
if (octx->ctx->mdev.count > 1 && octx->ctx->mdev.idx > 0) {
return HTP_STATUS_OK;
@@ -294,28 +261,24 @@ int op_allreduce(struct htp_ops_context * octx) {
const uint32_t rank = (uint32_t) kparams->rank;
const uint32_t n_ranks = (uint32_t) kparams->n_ranks;
if (n_ranks < 2 || n_ranks > HTP_ALLREDUCE_MAX_RANKS || rank >= n_ranks) {
return HTP_STATUS_INVAL_PARAMS;
}
const uint32_t fence_seq_entry = (uint32_t) octx->op_params[0];
const uint32_t fence_seq_exit = (uint32_t) octx->op_params[1];
const struct htp_tensor * my_sync = octx->src[n_ranks + rank];
atomic_uint * my_fence = (atomic_uint *) (uintptr_t) my_sync->data;
const int status = validate_allreduce(octx, kparams, n_ranks);
if (status != HTP_STATUS_OK) {
if (status == HTP_STATUS_NO_SUPPORT) {
FARF(ERROR, "ggml-hex: allreduce unsupported type %d : rank %u\n", dst->type, rank);
}
htp_fence_write(my_fence, fence_seq_exit, status);
return status;
if (!htp_ops_context_set_n_hvx(octx, (uint32_t) kparams->n_hvx)) {
htp_fence_write(my_fence, fence_seq_exit, HTP_STATUS_INVAL_PARAMS);
return HTP_STATUS_INVAL_PARAMS;
}
if ((size_t) kparams->vtcm_size > octx->ctx->vtcm_size) {
htp_fence_write(my_fence, fence_seq_exit, HTP_STATUS_VTCM_TOO_SMALL);
return HTP_STATUS_VTCM_TOO_SMALL;
}
const bool has_add = (octx->op == HTP_OP_ALLREDUCE_ADD);
const uint32_t nelem = dst->ne[0] * dst->ne[1] * dst->ne[2] * dst->ne[3];
const int32_t mode = kparams->mode;
const bool sharded_fanout = (kparams->flags & HTP_ALLREDUCE_FLAG_SHARDED_FANOUT) != 0;
// 1. Entry Barrier: Synchronize all ranks before reading
struct htp_thread_trace * tr0 = &octx->ctx->trace[0];
@@ -368,14 +331,13 @@ int op_allreduce(struct htp_ops_context * octx) {
actx.n_dsts = (uint32_t) kparams->n_dsts ? (uint32_t) kparams->n_dsts : n_ranks;
actx.nelem = nelem;
actx.ne0 = (uint32_t) kparams->ne0;
actx.ne1 = (uint32_t) kparams->ne1;
actx.row_size_aligned = (uint32_t) kparams->row_size_aligned;
actx.rank_elem_start = (uint32_t) kparams->rank_elem_start;
actx.rank_nelem = (uint32_t) kparams->rank_nelem;
actx.elems_per_hvx = elems_per_hvx;
actx.block_elems = block_elems;
actx.vtcm_size_per_hvx = vtcm_size_per_hvx;
actx.is_row_bcast = (kparams->is_row_bcast != 0);
actx.is_row_bcast = (kparams->flags & HTP_ALLREDUCE_FLAG_ROW_BCAST) != 0;
work_queue_func_t reduce_fun = NULL;
switch (kparams->kernel_type) {
@@ -388,7 +350,7 @@ int op_allreduce(struct htp_ops_context * octx) {
break;
case HTP_ALLREDUCE_KERNEL_DMA_2D:
if (has_add) {
if (kparams->is_row_bcast) {
if (actx.is_row_bcast) {
reduce_fun = (dst->type == HTP_TYPE_F16) ? allreduce_thread_dma_2d_add_bcast_f16 : allreduce_thread_dma_2d_add_bcast_f32;
} else {
reduce_fun = (dst->type == HTP_TYPE_F16) ? allreduce_thread_dma_2d_add_f16 : allreduce_thread_dma_2d_add_f32;
@@ -430,7 +392,7 @@ int op_allreduce(struct htp_ops_context * octx) {
htp_trace_event_start(tr0, HTP_TRACE_EVT_FENCE, (uint16_t) fence_seq_exit);
// drain fan-out DMA writes before exit barrier
if (mode == HTP_ALLREDUCE_SHARDED_FANOUT) {
if (sharded_fanout) {
asm volatile ("syncht" : : : "memory");
}
+4 -6
View File
@@ -17,9 +17,9 @@ enum htp_allreduce_kernel_type {
HTP_ALLREDUCE_KERNEL_DMA_2D,
};
enum htp_allreduce_mode {
HTP_ALLREDUCE_FULL = 0, // all ranks reduce full tensor
HTP_ALLREDUCE_SHARDED_FANOUT = 1, // each rank reduces 1/N shard and fans out to all buffers
enum htp_allreduce_flags {
HTP_ALLREDUCE_FLAG_ROW_BCAST = (1u << 0),
HTP_ALLREDUCE_FLAG_SHARDED_FANOUT = (1u << 1), // each rank reduces 1/N shard and fans out to all buffers
};
static inline size_t htp_allreduce_vtcm_buffer_count(
@@ -33,6 +33,7 @@ static inline size_t htp_allreduce_vtcm_buffer_count(
struct htp_allreduce_kernel_params {
uint8_t kernel_type;
uint8_t flags; // bitmask of enum htp_allreduce_flags
int32_t rank;
int32_t n_ranks;
int32_t n_hvx;
@@ -41,13 +42,10 @@ struct htp_allreduce_kernel_params {
int32_t vtcm_size_per_hvx;
int32_t vtcm_size;
int32_t ne0;
int32_t ne1;
int32_t row_size_aligned;
int32_t rank_elem_start;
int32_t rank_nelem;
int32_t n_dsts;
int32_t is_row_bcast;
int32_t mode; // enum htp_allreduce_mode: FULL or SHARDED_FANOUT
};
#if defined(__cplusplus)
-4
View File
@@ -1454,10 +1454,6 @@ static void htp_top_k_identity_job(const htp_thread_t * th, unsigned int n, unsi
}
static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) {
if (octx->src[0]->type != HTP_TYPE_F32 && octx->src[0]->type != HTP_TYPE_F16) {
return HTP_STATUS_NO_SUPPORT;
}
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
+128 -13
View File
@@ -28,7 +28,6 @@ struct htp_binary_context {
uint8_t * vtcm_base;
struct fastdiv_values src0_dim1_div; // ne01
struct fastdiv_values src0_dim2_div; // ne02
struct fastdiv_values src0_dim12_div;// ne03
struct fastdiv_values src1_dim1_div; // ne11
@@ -479,6 +478,7 @@ DEFINE_BINARY_MIXED_OP(sub, BINARY_OP_SUB, _Pragma("unroll(2)"))
DEFINE_BINARY_MIXED_OP(mul, BINARY_OP_MUL, _Pragma("unroll(2)"))
DEFINE_BINARY_MIXED_OP(div, BINARY_OP_DIV, )
DEFINE_BINARY_MIXED_F16_F16_F16(binary_add_f16_f16_f16, BINARY_OP_ADD)
DEFINE_BINARY_MIXED_F16_F16_F16(binary_mul_f16_f16_f16, BINARY_OP_MUL)
#define DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, TYPES) \
DEFINE_COMPUTE_SAME_SHAPE(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) \
@@ -699,6 +699,60 @@ DEFINE_COMPUTE_ADD_ID(f32_f16_f16, binary_add_f32_f16_f16, add_id_copy_f32_f
DEFINE_COMPUTE_ADD_ID(f32_f16_f32, binary_add_f32_f16_f32, add_id_copy_f32_f32)
DEFINE_COMPUTE_ADD_ID(f32_f32_f16, binary_add_f32_f32_f16, add_id_copy_f32_f16)
#define DEFINE_COMPUTE_MUL_ID(NAME, MUL_FN, COPY_FN) \
static void compute_mul_id_##NAME( \
uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, \
uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, \
uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00) { \
for (uint32_t r = 0; r < n_rows; r++) { \
const uint32_t r_i01 = i01 + r; \
const int32_t idx = src2_ids[i02 * ne01 + r_i01]; \
const uint8_t * r_src0 = src0 + r * src0_stride; \
uint8_t * r_dst = dst + r * dst_stride; \
if (idx < 0) { \
COPY_FN(r_dst, r_src0, ne00); \
continue; \
} \
const uint8_t * r_src1 = src1_data + idx * src1_stride; \
MUL_FN(r_dst, r_src0, r_src1, ne00); \
} \
}
DEFINE_COMPUTE_MUL_ID(f16_f16_f16, binary_mul_f16_f16_f16, add_id_copy_f16_f16)
DEFINE_COMPUTE_MUL_ID(f32_f32_f32, hvx_mul_f32_aaa, add_id_copy_f32_f32)
DEFINE_COMPUTE_MUL_ID(f16_f16_f32, binary_mul_f16_f16_f32, add_id_copy_f16_f32)
DEFINE_COMPUTE_MUL_ID(f16_f32_f16, binary_mul_f16_f32_f16, add_id_copy_f16_f16)
DEFINE_COMPUTE_MUL_ID(f16_f32_f32, binary_mul_f16_f32_f32, add_id_copy_f16_f32)
DEFINE_COMPUTE_MUL_ID(f32_f16_f16, binary_mul_f32_f16_f16, add_id_copy_f32_f16)
DEFINE_COMPUTE_MUL_ID(f32_f16_f32, binary_mul_f32_f16_f32, add_id_copy_f32_f32)
DEFINE_COMPUTE_MUL_ID(f32_f32_f16, binary_mul_f32_f32_f16, add_id_copy_f32_f16)
#define DEFINE_COMPUTE_MUL_ID_SCALAR(NAME, TYPE, MUL_FN, COPY_FN) \
static void compute_mul_id_scalar_##NAME( \
uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, \
uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, \
uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00) { \
(void) src1_stride; \
const TYPE * table = (const TYPE *) src1_data; \
for (uint32_t r = 0; r < n_rows; r++) { \
const uint32_t r_i01 = i01 + r; \
const int32_t idx = src2_ids[i02 * ne01 + r_i01]; \
const uint8_t * r_src0 = src0 + r * src0_stride; \
uint8_t * r_dst = dst + r * dst_stride; \
if (idx < 0) { \
COPY_FN(r_dst, r_src0, ne00); \
continue; \
} \
MUL_FN(r_dst, r_src0, table[idx], ne00); \
} \
}
DEFINE_COMPUTE_MUL_ID_SCALAR(f16_f16_f16, _Float16, hvx_mul_scalar_f16_aa, add_id_copy_f16_f16)
DEFINE_COMPUTE_MUL_ID_SCALAR(f16_f32_f16, float, binary_scalar_mul_f16_f16, add_id_copy_f16_f16)
DEFINE_COMPUTE_MUL_ID_SCALAR(f16_f32_f32, float, binary_scalar_mul_f16_f32, add_id_copy_f16_f32)
DEFINE_COMPUTE_MUL_ID_SCALAR(f32_f32_f16, float, binary_scalar_mul_f32_f16, add_id_copy_f32_f16)
DEFINE_COMPUTE_MUL_ID_SCALAR(f32_f32_f32, float, hvx_mul_scalar_f32_aa, add_id_copy_f32_f32)
struct binary_io_pipe_state {
const struct htp_binary_context * bctx;
dma_addr_t src0_data;
@@ -1378,7 +1432,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
const uint32_t table_type_key = type_key == 0 ? 0 : (type_key | 2);
if (kparams->kernel_type == HTP_BINARY_KERNEL_CHUNKED) {
const bool is_scalar = kparams->is_scalar;
const bool is_scalar = (kparams->flags & HTP_BINARY_FLAG_SCALAR) != 0;
compute_binary_chunked_t compute = NULL;
compute_binary_scalar_chunked_f32_t compute_scalar_f32 = NULL;
@@ -1707,6 +1761,35 @@ static int execute_op_binary(struct htp_ops_context * octx) {
}
}
break;
case HTP_BINARY_KERNEL_MUL_ID:
if (octx->op == HTP_OP_MUL_ID) {
worker_func = binary_thread_add_id;
switch (type_key) {
case 0: compute_func = (void *) compute_mul_id_f16_f16_f16; break;
case 1: compute_func = (void *) compute_mul_id_f16_f16_f32; break;
case 2: compute_func = (void *) compute_mul_id_f16_f32_f16; break;
case 3: compute_func = (void *) compute_mul_id_f16_f32_f32; break;
case 4: compute_func = (void *) compute_mul_id_f32_f16_f16; break;
case 5: compute_func = (void *) compute_mul_id_f32_f16_f32; break;
case 6: compute_func = (void *) compute_mul_id_f32_f32_f16; break;
case 7: compute_func = (void *) compute_mul_id_f32_f32_f32; break;
default: break;
}
}
break;
case HTP_BINARY_KERNEL_MUL_ID_SCALAR:
if (octx->op == HTP_OP_MUL_ID) {
worker_func = binary_thread_add_id;
switch (table_type_key) {
case 0: compute_func = (void *) compute_mul_id_scalar_f16_f16_f16; break;
case 2: compute_func = (void *) compute_mul_id_scalar_f16_f32_f16; break;
case 3: compute_func = (void *) compute_mul_id_scalar_f16_f32_f32; break;
case 6: compute_func = (void *) compute_mul_id_scalar_f32_f32_f16; break;
case 7: compute_func = (void *) compute_mul_id_scalar_f32_f32_f32; break;
default: break;
}
}
break;
default: break;
}
@@ -1717,7 +1800,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
dma_queue * dma_q = octx->ctx->dma[0];
uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src1);
if (kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST) {
if (!kparams->src1_strided) {
if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1->ne[0] * src1_elem_size, 1);
} else {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0]);
@@ -1725,7 +1808,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
} else if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR ||
kparams->kernel_type == HTP_BINARY_KERNEL_REPEAT ||
kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX) {
if (!kparams->src1_strided) {
if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
const size_t src1_bytes = (size_t) src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3] * src1_elem_size;
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1_bytes, 1);
if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR && octx->src[2] != NULL) {
@@ -1763,12 +1846,41 @@ static int execute_op_binary(struct htp_ops_context * octx) {
}
}
}
} else if (kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID) {
} else if (kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID ||
kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID) {
const struct htp_tensor * src2 = octx->src[2];
uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2);
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
kparams->src1_row_size_aligned, src1->nb[1],
src1->ne[0] * src1_elem_size, src1->ne[1]);
if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
kparams->src1_row_size_aligned, src1->nb[1],
src1->ne[0] * src1_elem_size, src1->ne[1]);
} else {
for (uint32_t i11 = 0; i11 < src1->ne[1]; i11++) {
dma_addr_t src_addr = src1->data + i11 * src1->nb[1];
uint8_t * dst_ptr = vtcm_src1 + i11 * kparams->src1_row_size_aligned;
while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr),
src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0])) {
dma_queue_pop(dma_q);
}
}
}
const size_t src2_row_bytes = src2->ne[0] * sizeof(int32_t);
while (!dma_queue_push(dma_q, dma_make_data(vtcm_src2, src2->data),
src2_row_bytes, src2->nb[1],
src2_row_bytes, src2->ne[1])) {
dma_queue_pop(dma_q);
}
} else if (kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID_SCALAR) {
const struct htp_tensor * src2 = octx->src[2];
uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2);
if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
bctx.vtcm_layout.src1_size, 0,
src1->ne[0] * src1_elem_size, 1);
} else {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0]);
}
const size_t src2_row_bytes = src2->ne[0] * sizeof(int32_t);
dma_queue_push(dma_q, dma_make_data(vtcm_src2, src2->data),
src2_row_bytes, src2->nb[1],
@@ -1793,24 +1905,27 @@ static int execute_op_binary(struct htp_ops_context * octx) {
bctx.src1_table_elem_size = table_type_key == 0 ? sizeof(_Float16) : sizeof(float);
bctx.src0_dim1_div = kparams->div_ne01;
bctx.src0_dim2_div = kparams->div_ne02;
bctx.src0_dim12_div = kparams->div_ne012;
bctx.src1_dim1_div = kparams->div_ne11;
bctx.src1_dim2_div = kparams->div_ne12;
bctx.src1_dim3_div = kparams->div_ne13;
bctx.split_at_ne01 = kparams->split_at_ne01;
bctx.split_at_ne02 = kparams->split_at_ne02;
bctx.split_at_ne01 = (kparams->flags & HTP_BINARY_FLAG_SPLIT_NE01) != 0;
bctx.split_at_ne02 = (kparams->flags & HTP_BINARY_FLAG_SPLIT_NE02) != 0;
bctx.compute = compute_func;
if (kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST ||
kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR ||
kparams->kernel_type == HTP_BINARY_KERNEL_REPEAT ||
kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX ||
kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID) {
kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID ||
kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID ||
kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID_SCALAR) {
dma_queue_flush(dma_q);
if ((kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST || kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR) &&
if ((kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST ||
kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR ||
kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID_SCALAR) &&
type_key != 0 && src1_type == HTP_TYPE_F16) {
binary_expand_f16_to_f32(vtcm_src1, (uint32_t) (src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3]));
}
+21 -16
View File
@@ -15,24 +15,28 @@ enum htp_binary_kernel_type {
HTP_BINARY_KERNEL_ROW_BCAST,
HTP_BINARY_KERNEL_SCALAR,
HTP_BINARY_KERNEL_ADD_ID,
HTP_BINARY_KERNEL_MUL_ID,
HTP_BINARY_KERNEL_MUL_ID_SCALAR,
HTP_BINARY_KERNEL_COMPLEX,
HTP_BINARY_KERNEL_REPEAT,
HTP_BINARY_KERNEL_CHUNKED,
};
enum htp_binary_flags {
HTP_BINARY_FLAG_SPLIT_NE01 = (1u << 0),
HTP_BINARY_FLAG_SPLIT_NE02 = (1u << 1),
HTP_BINARY_FLAG_SRC1_STRIDED = (1u << 2),
HTP_BINARY_FLAG_SCALAR = (1u << 3),
};
struct htp_binary_kernel_params {
uint8_t kernel_type;
uint8_t split_at_ne01;
uint8_t split_at_ne02;
uint8_t src1_strided;
uint8_t flags; // bitmask of enum htp_binary_flags
uint8_t n_srcs;
uint8_t is_scalar;
uint8_t src0_elem_size;
uint8_t src1_elem_size;
uint8_t src1_elem_size;
uint8_t dst_elem_size;
uint8_t pad[3];
uint32_t n_hvx;
uint32_t rows_per_buffer;
@@ -46,10 +50,8 @@ struct htp_binary_kernel_params {
uint32_t vtcm_size;
uint32_t chunk_size;
uint32_t chunk_bytes;
struct fastdiv_values div_ne01;
struct fastdiv_values div_ne02;
struct fastdiv_values div_ne012;
struct fastdiv_values div_ne11;
@@ -127,19 +129,21 @@ static inline void htp_binary_vtcm_layout_build(
return;
}
const bool is_scalar = (kparams->flags & HTP_BINARY_FLAG_SCALAR) != 0;
L->src0_bytes_per_hvx = 2 * src0_chunk_bytes;
L->src1_bytes_per_hvx = kparams->is_scalar ? 0 : (2 * (n_srcs - 1) * src1_chunk_bytes);
L->src1_bytes_per_hvx = is_scalar ? 0 : (2 * (n_srcs - 1) * src1_chunk_bytes);
L->dst_bytes_per_hvx = 2 * dst_chunk_bytes;
L->src0_spad_half_size = src0_chunk_bytes;
L->src1_spad_half_size = kparams->is_scalar ? 0 : src1_chunk_bytes;
L->src1_spad_half_size = is_scalar ? 0 : src1_chunk_bytes;
L->dst_spad_half_size = dst_chunk_bytes;
L->rows_per_buffer = 1;
L->src1_size = 0;
const size_t src0_total = n_hvx * L->src0_bytes_per_hvx;
const size_t src1_total = kparams->is_scalar ? 128 : (n_hvx * L->src1_bytes_per_hvx);
const size_t src1_total = is_scalar ? 128 : (n_hvx * L->src1_bytes_per_hvx);
const size_t dst_total = n_hvx * L->dst_bytes_per_hvx;
size_t off = 0;
@@ -234,7 +238,6 @@ static inline bool htp_binary_solve_chunked(
const uint32_t chunk_size = (target_chunk_elems < min_chunk_elems) ? min_chunk_elems
: (target_chunk_elems > max_chunk_elems) ? max_chunk_elems
: target_chunk_elems;
const uint32_t chunk_bytes = hex_round_up(chunk_size * elem_size, 128);
const uint32_t total_chunks = (total_elems + chunk_size - 1) / chunk_size;
const uint32_t n_hvx = (total_chunks >= 2) ? (max_hvx < total_chunks ? max_hvx : total_chunks) : 1;
@@ -242,14 +245,16 @@ static inline bool htp_binary_solve_chunked(
kparams->n_hvx = n_hvx;
kparams->n_srcs = (uint8_t) n_srcs;
kparams->rows_per_buffer = 1;
kparams->src1_row_size_aligned = is_scalar ? 0 : kparams->src0_row_size_aligned;
kparams->src0_elem_size = (uint8_t) src0_elem_size;
kparams->src1_elem_size = (uint8_t) src1_elem_size;
kparams->dst_elem_size = (uint8_t) dst_elem_size;
kparams->src1_size = 0;
kparams->chunk_size = chunk_size;
kparams->chunk_bytes = chunk_bytes;
kparams->is_scalar = is_scalar ? 1 : 0;
if (is_scalar) {
kparams->flags |= HTP_BINARY_FLAG_SCALAR;
} else {
kparams->flags &= ~HTP_BINARY_FLAG_SCALAR;
}
htp_binary_vtcm_layout_build(L, kparams, vtcm_size);
if (L->total_bytes == 0 || L->total_bytes > vtcm_size) {
+2 -3
View File
@@ -779,9 +779,8 @@ static int concat_transposed(struct htp_ops_context * octx, const struct htp_con
rstart1 = range1.start;
nrows1 = range1.count;
}
const struct fastdiv_values div_ne11 = init_fastdiv_values(src1->ne[1]);
const struct fastdiv_values div_ne12_ne11 = init_fastdiv_values(src1->ne[1] * src1->ne[2]);
concat_regular_side(octx, &view1, src1, rstart1, nrows1, &div_ne11, &div_ne12_ne11);
concat_regular_side(octx, &view1, src1, rstart1, nrows1,
&kparams->u.transposed.div_ne11, &kparams->u.transposed.div_ne12_ne11);
}
return HTP_STATUS_OK;
+2
View File
@@ -25,6 +25,8 @@ struct htp_concat_regular_params {
struct htp_concat_transposed_params {
struct fastdiv_values div_ne2;
struct fastdiv_values div_ne11;
struct fastdiv_values div_ne12_ne11;
};
struct htp_concat_kernel_params {
+16 -15
View File
@@ -455,7 +455,7 @@ static uint32_t conv2d_hmx_issue_seg(const struct htp_ops_context * octx, const
const uint32_t n = fastdiv(row, &kp->tiled.div_oh);
const uint32_t oh = row - n * OH;
if (kp->cwhn) {
if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
conv2d_hmx_stage_cwhn(octx, kp, dmaq, stage, n, oh, owt * 32, G);
} else {
conv2d_hmx_stage(octx, kp, g, dmaq, stage, n, oh, owt * 32, G);
@@ -813,7 +813,7 @@ static void conv2d_hmx_pack(const struct htp_conv2d_hmx_context * hc, const htp_
// Reuse output staging after unpack has drained its DMA.
HVX_Vector * gather_tmp = (HVX_Vector *) (thr + (size_t) n_stage * kp->stage_size);
const HVX_Vector offsets = kp->cwhn || s0 <= 2 ? Q6_V_vzero() : hvx_vec_gather_offsets_w(s0 * sizeof(float));
const HVX_Vector offsets = (kp->flags & HTP_CONV2D_FLAG_CWHN) || s0 <= 2 ? Q6_V_vzero() : hvx_vec_gather_offsets_w(s0 * sizeof(float));
uint32_t ng[2] = { 0, 0 };
uint32_t tq = t0;
@@ -832,7 +832,7 @@ static void conv2d_hmx_pack(const struct htp_conv2d_hmx_context * hc, const htp_
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) t);
if (kp->cwhn) {
if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
const uint32_t Wb = 32 * G * s0 + (KW - 1) * d0;
conv2d_hmx_cwhn_f16(stage16, stage, KH, kp->tiled.stage_row, Wb * Cin);
for (uint32_t g = 0; g < G; g++) {
@@ -1020,7 +1020,7 @@ static int conv2d_hmx_tiled(struct htp_ops_context * octx, const struct htp_conv
for (uint32_t rt0 = 0; rt0 < kp->n_row_tiles; rt0 += kp->rt_block) {
hc.rt0 = rt0;
hc.n_rt = MIN(kp->rt_block, kp->n_row_tiles - rt0);
work_queue_run(octx->ctx->hvx_queue, kp->w_kmajor ? conv2d_hmx_wpack_kmajor_thread : conv2d_hmx_wpack_thread, &hc, nth);
work_queue_run(octx->ctx->hvx_queue, (kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) ? conv2d_hmx_wpack_kmajor_thread : conv2d_hmx_wpack_thread, &hc, nth);
conv2d_hmx_run_phase(&hc, 0, -1, nth);
@@ -1550,7 +1550,7 @@ static void conv2d_hmx_win_wpack_rows(const struct htp_conv2d_win_context * wc,
static void conv2d_hmx_win_wpack_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
const struct htp_conv2d_win_context * wc = (const struct htp_conv2d_win_context *) data;
if (wc->kp->w_kmajor) {
if (wc->kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) {
conv2d_hmx_win_wpack_kmajor(wc, th, nth, ith);
} else {
conv2d_hmx_win_wpack_rows(wc, th, nth, ith);
@@ -1573,7 +1573,7 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d
const uint32_t p0 = octx->op_params[2];
const uint32_t p1 = octx->op_params[3];
const uint32_t span = kp->window.seg_b * 32;
const bool cwhn = kp->cwhn;
const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0;
// rows of one image are contiguous when there is no column padding
const bool rows_contig = p0 == 0 && input->nb[1] == (size_t) IW * input->nb[0];
@@ -1693,7 +1693,7 @@ static uint32_t conv2d_hmx_win_stage_fold(const struct htp_conv2d_win_context *
// rows of one image are contiguous in DDR
const uint32_t nr = cont ? MIN(vr_b - vr, (uint32_t) (IH - ih)) : 1;
const dma_addr_t src = input->data + (size_t) n * input->nb[3] + (size_t) ih * input->nb[1];
if (kp->cwhn) {
if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
// raw[vr - vr_a][iw][c]
const size_t sz = (size_t) nr * IW * Cin * sizeof(float);
dma_queue_push(dmaq, dma_make_data(raw + (size_t) (vr - vr_a) * IW * Cin, src), sz, sz, sz, 1);
@@ -1734,7 +1734,7 @@ static void conv2d_hmx_win_croutons(const struct htp_conv2d_win_context * wc, co
return;
}
if (kp->cwhn) {
if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
for (uint32_t cc = 0; cc < n_cc; cc++) {
const uint32_t nc = MIN(32, Cin - cc * 32);
const HVX_VectorPred qc = Q6_Q_vsetq2_R(nc * sizeof(float));
@@ -2040,7 +2040,7 @@ static void conv2d_hmx_win_pack(const struct htp_conv2d_win_context * wc, const
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) b);
if (kp->window.fold && kp->cwhn) {
if (kp->window.fold && (kp->flags & HTP_CONV2D_FLAG_CWHN)) {
conv2d_hmx_win_croutons_fold_cwhn(wc, stages[si], act, b, nb, (ts + b) * 32);
} else if (kp->window.fold) {
conv2d_hmx_win_croutons_fold(wc, stages[si], act, b, nb, (ts + b) * 32);
@@ -2287,7 +2287,7 @@ static int conv2d_hmx_win(struct htp_ops_context * octx, const struct htp_conv2d
// small Cin: croutons are built by scattering the staged values into zeroed croutons
const uint32_t n_ch = octx->src[1]->ne[2] * (kp->window.fold ? KW : 1);
if (!kp->cwhn && n_ch <= 2 * CONV2D_WIN_SCAT_MAX) {
if (!(kp->flags & HTP_CONV2D_FLAG_CWHN) && n_ch <= 2 * CONV2D_WIN_SCAT_MAX) {
wctx.n_scat = (n_ch + 1) / 2;
work_queue_run(octx->ctx->hvx_queue, conv2d_hmx_win_zero_thread, &wctx, kp->n_hvx);
}
@@ -2395,7 +2395,7 @@ static inline void conv2d_dw_get_slice(
uint32_t n;
uint32_t c = 0;
if (kp->cwhn) {
if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) {
n = fastdiv(task, &kp->div_n_chunks);
chunk_idx = task - n * kp->n_chunks;
} else {
@@ -2428,7 +2428,7 @@ static inline void conv2d_dw_get_slice(
slice->ih_first = ih_first;
slice->c = c;
if (kp->cwhn) {
if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) {
slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) ih_first * src1->nb[1];
slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh_start * dst->nb[1];
} else {
@@ -3201,7 +3201,7 @@ static void conv2d_dw_dma_thread(const htp_thread_t * th, unsigned int nth, unsi
dma_queue_flush(dma_q);
FARF(HIGH, "conv2d_dw-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n",
ith, nth, kp->w, kp->h, kp->c, kp->n, kp->ow, kp->oh, kp->c, kp->n, first, last);
ith, nth, kp->w, kp->h, kp->c, dst->ne[3], kp->ow, kp->oh, kp->c, dst->ne[3], first, last);
}
int op_conv_2d_dw(struct htp_ops_context * octx) {
@@ -3223,7 +3223,8 @@ int op_conv_2d_dw(struct htp_ops_context * octx) {
const uint32_t max_dst_bytes = kp->oh_chunk * kp->row_dst_bytes + 128;
const struct htp_tensor * src0 = octx->src[0];
const uint32_t elem_size = kp->is_f16 ? sizeof(__fp16) : sizeof(float);
const bool is_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0;
const uint32_t elem_size = is_f16 ? sizeof(__fp16) : sizeof(float);
const uint32_t w_size = src0->size;
struct htp_conv2d_dw_vtcm_layout layout;
@@ -3262,7 +3263,7 @@ int op_conv_2d_dw(struct htp_ops_context * octx) {
.kp = kp,
.layout = layout,
.w_vtcm = w_vtcm,
.compute_fn = conv2d_dw_kernels[kp->kernel_type][kp->is_f16 ? 1 : 0],
.compute_fn = conv2d_dw_kernels[kp->kernel_type][is_f16 ? 1 : 0],
.task_start = task_start,
.task_count = task_count,
.tasks_per_hvx = tasks_per_hvx,
+12 -5
View File
@@ -58,11 +58,15 @@ struct htp_conv2d_window_params {
struct fastdiv_values div_cs;
};
enum htp_conv2d_flags {
HTP_CONV2D_FLAG_CWHN = (1u << 0),
HTP_CONV2D_FLAG_W_KMAJOR = (1u << 1),
};
struct htp_conv2d_kernel_params {
uint8_t kernel_type;
uint8_t flags; // bitmask of enum htp_conv2d_flags
uint8_t n_hvx;
uint8_t cwhn;
uint8_t w_kmajor;
uint32_t total_rows;
uint32_t n_row_tiles;
@@ -96,18 +100,21 @@ enum htp_conv2d_dw_kernel_type {
HTP_CONV2D_DW_KERNEL_COUNT,
};
enum htp_conv2d_dw_flags {
HTP_CONV2D_DW_FLAG_CWHN = (1u << 0),
HTP_CONV2D_DW_FLAG_F16 = (1u << 1),
};
struct htp_conv2d_dw_kernel_params {
uint8_t kernel_type;
uint8_t flags; // bitmask of enum htp_conv2d_dw_flags
uint8_t n_hvx;
uint8_t cwhn;
uint8_t is_f16;
uint32_t total_tasks;
uint32_t vtcm_size;
uint32_t w;
uint32_t h;
uint32_t c;
uint32_t n;
uint32_t kw;
uint32_t kh;
uint32_t ow;
+1 -6
View File
@@ -245,12 +245,7 @@ static int op_diag_impl(struct htp_ops_context * octx, size_t elem_size, dma_pip
}
int op_diag(struct htp_ops_context * octx) {
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
if (src0->type != dst->type) {
return HTP_STATUS_NO_SUPPORT;
}
const struct htp_tensor * dst = octx->dst;
switch (dst->type) {
case HTP_TYPE_F32:
+9
View File
@@ -569,6 +569,10 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) {
const struct htp_dsv4_hc_pre_kernel_params * kparams =
(const struct htp_dsv4_hc_pre_kernel_params *) octx->kernel_params;
if (kparams->total_jobs == 0) {
return HTP_STATUS_OK;
}
const uint32_t n_hvx = kparams->n_hvx;
if (!htp_ops_context_set_n_hvx_div(octx, n_hvx, kparams->div_n_hvx)) {
return HTP_STATUS_INVAL_PARAMS;
@@ -1019,6 +1023,11 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) {
const struct htp_dsv4_hc_post_kernel_params * kparams =
(const struct htp_dsv4_hc_post_kernel_params *) octx->kernel_params;
if (kparams->total_jobs == 0) {
return HTP_STATUS_OK;
}
const struct htp_tensor * comb = kparams->has_comb ? octx->src[3] : NULL;
const uint32_t n_hvx = kparams->n_hvx;
+6 -20
View File
@@ -30,7 +30,7 @@
#include "flash-attn-ops.h"
#include "hvx-fa-kernels.h"
#include "hmx-fa-kernels.h"
#include "hmx-fa-fp16-kernels.h"
#include "hmx-fa-w8a8-kernels.h"
// Must be multiple of 32
@@ -3382,9 +3382,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
factx.n_kv_blocks = kparams->n_kv_blocks;
factx.is_q_fp32 = (q->type == HTP_TYPE_F32);
factx.is_dst_fp32 = (dst->type == HTP_TYPE_F32);
factx.pipeline = (kparams->u.hmx.pipeline != 0);
factx.pipeline = (kparams->flags & HTP_FA_FLAG_PIPELINE) != 0;
factx.is_w8a8 = (kparams->kernel_type == HTP_FA_KERNEL_HMX_W8A8);
factx.mask_broadcast = (kparams->u.hmx.mask_broadcast != 0);
factx.mask_broadcast = (kparams->flags & HTP_FA_FLAG_MASK_BCAST) != 0;
if (mask) {
factx.src3_div2 = kparams->src3_div2;
factx.src3_div3 = kparams->src3_div3;
@@ -3425,7 +3425,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
if (kparams->flags & HTP_FA_FLAG_TEAM_SPLIT) {
// KV heads split across teams, Q-blocks split within a team
uint32_t n_teams, team_size;
htp_fa_mdev_teams(n_kv_heads, mdev_count, kparams->head_split != 0, &n_teams, &team_size);
htp_fa_mdev_teams(n_kv_heads, mdev_count, (kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) != 0, &n_teams, &team_size);
const uint32_t team = mdev_idx / team_size;
const uint32_t member = mdev_idx - team * team_size;
@@ -3444,7 +3444,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
q_start_min = b0 * Br;
q_start_max = MIN((b0 + nblk) * Br, neq1);
} else if (kparams->head_split && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
} else if ((kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
const uint32_t kv_per_core = n_kv_heads / mdev_count;
kv_head_min = mdev_idx * kv_per_core;
kv_head_max = kv_head_min + kv_per_core;
@@ -4097,19 +4097,8 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const struct htp_tensor * v = octx->src[2];
const struct htp_tensor * mask = octx->src[3];
// Check support
if ((q->type != HTP_TYPE_F16 && q->type != HTP_TYPE_F32) ||
(k->type != HTP_TYPE_F16 && k->type != HTP_TYPE_Q8_0) ||
(v->type != HTP_TYPE_F16 && v->type != HTP_TYPE_Q8_0)) {
return HTP_STATUS_NO_SUPPORT;
}
const struct htp_fa_kernel_params * kparams = (const struct htp_fa_kernel_params *) octx->kernel_params;
if (kparams->kernel_type == HTP_FA_KERNEL_UNSUPPORTED || kparams->n_kv_blocks > FA_MAX_KV_BLOCKS) {
return HTP_STATUS_NO_SUPPORT;
}
if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
return HTP_STATUS_INVAL_PARAMS;
}
@@ -4156,9 +4145,6 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
factx.m1 = kparams->m1;
const uint32_t n_head = q->ne[2];
if (n_head > 512) {
return HTP_STATUS_NO_SUPPORT;
}
factx.ddr = (struct hvx_fa_ddr_spad *) fa_get_ddr_spad(octx, sizeof(struct hvx_fa_ddr_spad));
if (!factx.ddr) {
@@ -4187,7 +4173,7 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const uint32_t n_kv_heads = k->ne[2];
// head range is contiguous in flat row space only when neq3 == 1
if (kparams->head_split && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
if ((kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
const uint32_t G = kparams->G;
const uint32_t kv_per_core = n_kv_heads / mdev_count;
const uint32_t heads_per_core = kv_per_core * G;
+7 -6
View File
@@ -40,8 +40,12 @@ enum htp_fa_kernel_type {
HTP_FA_KERNEL_HMX_W8A8,
};
// Multicore: gcd(n_kv_heads, N) teams own the KV heads, team members share the Q-blocks
#define HTP_FA_FLAG_TEAM_SPLIT 0x01
enum htp_fa_flags {
HTP_FA_FLAG_TEAM_SPLIT = (1u << 0), // gcd(n_kv_heads, N) teams own the KV heads, team members share the Q-blocks
HTP_FA_FLAG_HEAD_SPLIT = (1u << 1), // partition by KV heads in multicore (0 = token partition)
HTP_FA_FLAG_MASK_BCAST = (1u << 2), // mask broadcast across heads
HTP_FA_FLAG_PIPELINE = (1u << 3), // pipelined HMX execution
};
static inline void htp_fa_mdev_teams(uint32_t n_kv_heads, uint32_t mdev_count, bool head_split,
uint32_t * n_teams, uint32_t * team_size) {
@@ -52,8 +56,7 @@ static inline void htp_fa_mdev_teams(uint32_t n_kv_heads, uint32_t mdev_count, b
struct htp_fa_kernel_params {
uint8_t kernel_type; // enum htp_fa_kernel_type
uint8_t head_split; // 1 = partition by KV heads in multicore, 0 = token partition
uint8_t flags; // HTP_FA_FLAG_*
uint8_t flags; // bitmask of enum htp_fa_flags
uint8_t n_hvx; // Number of threads to run
// Common parameters
@@ -82,8 +85,6 @@ struct htp_fa_kernel_params {
union {
struct {
uint32_t g_br;
int32_t mask_broadcast;
int32_t pipeline;
struct fastdiv_values div_G;
} hmx;
struct {
@@ -16,7 +16,7 @@
#include "htp-tensor.h"
#include "htp-vtcm.h"
#include "hmx-utils.h"
#include "hmx-fa-kernels.h"
#include "hmx-fa-fp16-kernels.h"
#include "hmx-queue.h"
#include "gated-delta-net-ops.h"
-16
View File
@@ -464,22 +464,6 @@ int op_get_rows(struct htp_ops_context * octx) {
const uint32_t ne00 = octx->src[0]->ne[0];
const uint32_t src0_row_size = htp_tensor_get_row_size(octx->src[0]->type, ne00);
const uint32_t dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00);
if (src0_row_size == 0 || dst_row_size == 0) {
return HTP_STATUS_NO_SUPPORT;
}
if (kparams->kernel_type == HTP_GET_ROWS_KERNEL_SAMETYPE) {
if (octx->src[0]->type != octx->dst->type) {
return HTP_STATUS_NO_SUPPORT;
}
} else if ((octx->dst->type != HTP_TYPE_F32 && octx->dst->type != HTP_TYPE_F16) ||
(octx->src[0]->type == HTP_TYPE_F32 && octx->dst->type == HTP_TYPE_F32)) {
return HTP_STATUS_NO_SUPPORT;
}
if (octx->src[1]->type != HTP_TYPE_I32 && octx->src[1]->type != HTP_TYPE_I64) {
return HTP_STATUS_NO_SUPPORT;
}
const uint32_t total_tasks = kparams->total_tasks;
+4 -4
View File
@@ -58,12 +58,12 @@ static inline void htp_glu_vtcm_layout_build(
const size_t row_size_aligned = hex_round_up(dst_row_size, 128);
L->row_size_aligned = row_size_aligned;
L->vtcm_row_per_hvx = vtcm_row_per_hvx;
L->block = vtcm_row_per_hvx >> 1;
L->vtcm_row_per_hvx = 2 * L->block;
L->src0_bytes_per_hvx = row_size_aligned * vtcm_row_per_hvx;
L->src1_bytes_per_hvx = row_size_aligned * vtcm_row_per_hvx;
L->dst_bytes_per_hvx = row_size_aligned * vtcm_row_per_hvx;
L->src0_bytes_per_hvx = 2 * L->block * row_size_aligned;
L->src1_bytes_per_hvx = 2 * L->block * row_size_aligned;
L->dst_bytes_per_hvx = 2 * L->block * row_size_aligned;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
@@ -6,7 +6,7 @@
#include <stdint.h>
#include "hex-fastdiv.h"
#include "hmx-int-utils.h"
#include "hmx-w8a8-utils.h"
#include "hmx-utils.h"
#include "hvx-utils.h"
@@ -406,7 +406,7 @@ static inline HVX_Vector hmx_fa_w8a8_k_pack4(const uint8_t * p, size_t stride) {
return Q6_V_lo_W(Q6_W_vshuff_VVR(p23, p01, -8));
}
// Same math as int_hmx_rescale_pair_wb, using vadd(-1) instead of vcombine+vmpyacc to avoid Vdd pair spills.
// Same math as hmx_w8a8_rescale_pair_wb, using vadd(-1) instead of vcombine+vmpyacc to avoid Vdd pair spills.
static inline void hmx_fa_w8a8_k_rescale_pair(
HVX_Vector v_q0,
HVX_Vector v_q1,
@@ -431,7 +431,7 @@ static inline void hmx_fa_w8a8_k_rescale_pair(
HVX_Vector v_W1 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_p23_hi, 1),
Q6_Vh_vasl_VhR(v_p23_lo, 1));
#endif
int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
hmx_w8a8_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
}
// Q8_0 K -> S8 weight.b 32x32 tiles for one column tile (32 KV rows).
@@ -469,10 +469,10 @@ static __attribute__((noinline)) void hmx_fa_w8a8_k_prep_tile(
}
HVX_Vector v_max_sf, v_inv127_qf;
int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
hmx_w8a8_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
for (uint32_t kt = 0; kt < n_dot; ++kt) {
tile_dst_all[kt * 8 + 7] = int_hmx_m_b4_from_f16(tile_dst_all[kt * 8 + 7], v_inv127_qf);
tile_dst_all[kt * 8 + 7] = hmx_w8a8_m_b4_from_f16(tile_dst_all[kt * 8 + 7], v_inv127_qf);
}
// Step 2: 32x32-byte vshuffvdd transpose of int8 quants and rescale in-place to weight.b
@@ -527,7 +527,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_k_prep_tile(
}
// Step 3: emit per-channel scales and HMX bias banks
emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
hmx_w8a8_emit_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
}
// Decode one 4-row x 32-col W8A8 S tile (out_hi + out_lo) into 4 FP32 vectors.
@@ -657,7 +657,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
v_max_sc = hvx_vec_reduce_max_f16(v_max_sc);
HVX_Vector v_max_sf, v_inv127_qf;
int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
hmx_w8a8_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
// Pass 2: 4-row vshuff interleave + per-KV-row int8 scale multiply -> S8 weight.b
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
@@ -700,7 +700,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
}
// Pass 3: emit zp=0 per-channel scales and HMX bias banks
emit_int_hmx_scales_and_bias_zp0(v_max_sf, 128.0f / 127.0f, v_l1_w, dst_scales, bias_out);
hmx_w8a8_emit_scales_and_bias_zp0(v_max_sf, 128.0f / 127.0f, v_l1_w, dst_scales, bias_out);
}
static inline void hmx_fa_w8a8_gemm_run(
@@ -1,5 +1,5 @@
#ifndef HMX_INT_UTILS_H
#define HMX_INT_UTILS_H
#ifndef HMX_W8A8_UTILS_H
#define HMX_W8A8_UTILS_H
#include <stddef.h>
#include <stdint.h>
@@ -31,7 +31,7 @@ static inline HVX_Vector hmx_qf32_to_i32_zp128(HVX_Vector v_qf) {
return Q6_Vw_equals_Vsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(v_qf, v_128p5)));
}
static inline void emit_int_hmx_scales_and_bias(
static inline void hmx_w8a8_emit_scales_and_bias(
HVX_Vector v_max_sf,
float scale_const,
HVX_Vector v_sum_w,
@@ -58,7 +58,7 @@ static inline void emit_int_hmx_scales_and_bias(
bias_out[3] = v_ib;
}
static inline void emit_int_hmx_scales_and_bias_zp0(
static inline void hmx_w8a8_emit_scales_and_bias_zp0(
HVX_Vector v_max_sf,
float scale_const,
HVX_Vector v_l1_w,
@@ -84,51 +84,51 @@ static inline void emit_int_hmx_scales_and_bias_zp0(
bias_out[3] = v_ib;
}
static inline HVX_Vector int_hmx_scale_qf_from_max_f32(HVX_Vector v_max_sf, float num) {
static inline HVX_Vector hmx_w8a8_scale_qf_from_max_f32(HVX_Vector v_max_sf, float num) {
HVX_VectorPred q_pos = Q6_Q_vcmp_gt_VsfVsf(v_max_sf, hvx_vec_splat_f32(1e-30f));
HVX_Vector v_inv_raw = hvx_vec_inverse_f32(v_max_sf);
HVX_Vector v_scale_sf = Q6_V_vmux_QVV(q_pos, hvx_vec_mul_f32_f32(v_inv_raw, hvx_vec_splat_f32(num)), Q6_V_vzero());
return hvx_vec_f32_to_qf32(v_scale_sf);
}
static inline HVX_Vector int_hmx_inv127_from_max_f32(HVX_Vector v_max_sf) {
return int_hmx_scale_qf_from_max_f32(v_max_sf, 127.0f);
static inline HVX_Vector hmx_w8a8_inv127_from_max_f32(HVX_Vector v_max_sf) {
return hmx_w8a8_scale_qf_from_max_f32(v_max_sf, 127.0f);
}
static inline void int_hmx_inv127_from_max_f16(
static inline void hmx_w8a8_inv127_from_max_f16(
HVX_Vector v_max_sc,
HVX_Vector * restrict v_max_sf_out,
HVX_Vector * restrict v_inv127_qf_out) {
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
HVX_Vector v_max_sf = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_max_sc), v_one_f16)));
*v_max_sf_out = v_max_sf;
*v_inv127_qf_out = int_hmx_inv127_from_max_f32(v_max_sf);
*v_inv127_qf_out = hmx_w8a8_inv127_from_max_f32(v_max_sf);
}
static inline HVX_Vector int_hmx_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) {
static inline HVX_Vector hmx_w8a8_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) {
HVX_Vector v_m_biased = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf));
HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased);
return Q6_Vh_vshuff_Vh(Q6_Vb_vshuff_Vb(Q6_Vb_vpacke_VhVh(v_m_h, v_m_h)));
}
static inline HVX_Vector int_hmx_m_b4_from_f16(HVX_Vector v_sc, HVX_Vector v_inv127_qf) {
static inline HVX_Vector hmx_w8a8_m_b4_from_f16(HVX_Vector v_sc, HVX_Vector v_inv127_qf) {
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
HVX_Vector v_sc_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_sc), v_one_f16));
return int_hmx_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf);
return hmx_w8a8_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf);
}
static inline void int_hmx_m_b4_pair_from_f16(
static inline void hmx_w8a8_m_b4_pair_from_f16(
HVX_Vector v_sc,
HVX_Vector v_inv127_qf,
HVX_Vector * restrict v_m_b0_out,
HVX_Vector * restrict v_m_b1_out) {
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
HVX_VectorPair vp_sc_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_sc), v_one_f16);
*v_m_b0_out = int_hmx_m_b4_from_sc_qf(Q6_V_lo_W(vp_sc_qf), v_inv127_qf);
*v_m_b1_out = int_hmx_m_b4_from_sc_qf(Q6_V_hi_W(vp_sc_qf), v_inv127_qf);
*v_m_b0_out = hmx_w8a8_m_b4_from_sc_qf(Q6_V_lo_W(vp_sc_qf), v_inv127_qf);
*v_m_b1_out = hmx_w8a8_m_b4_from_sc_qf(Q6_V_hi_W(vp_sc_qf), v_inv127_qf);
}
static inline void int_hmx_store_and_accum_pair(
static inline void hmx_w8a8_store_and_accum_pair(
HVX_Vector * restrict tile_dst,
int pair_idx,
HVX_Vector v_W0,
@@ -144,7 +144,7 @@ static inline void int_hmx_store_and_accum_pair(
*v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(Q6_Vw_vrmpyacc_VwVubVb(*v_l1_w, Q6_Vb_vabs_Vb(v_W0), v_ones_s8), Q6_Vb_vabs_Vb(v_W1), v_ones_s8);
}
static inline void int_hmx_rescale_pair_wb(
static inline void hmx_w8a8_rescale_pair_wb(
HVX_Vector v_q0,
HVX_Vector v_q1,
HVX_Vector v_m_b4,
@@ -167,7 +167,7 @@ static inline void int_hmx_rescale_pair_wb(
HVX_Vector v_W1 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p23), 1),
Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p23), 1));
#endif
int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
hmx_w8a8_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
}
#if __HVX_ARCH__ >= 81
@@ -214,4 +214,4 @@ static inline void hmx_pack_hf_quad_to_u8_cm_pair(
}
#endif
#endif /* HMX_INT_UTILS_H */
#endif /* HMX_W8A8_UTILS_H */
+4 -2
View File
@@ -36,8 +36,9 @@ enum htp_data_type {
HTP_TYPE_BF16 = 30,
HTP_TYPE_MXFP4 = 39,
HTP_TYPE_NVFP4 = 40,
HTP_TYPE_Q1_0 = 41,
HTP_TYPE_Q2_0 = 42,
HTP_TYPE_Q1_0 = 41,
HTP_TYPE_Q2_0 = 42,
HTP_TYPE_F8_E4M3 = 43,
HTP_TYPE_INVALID
};
@@ -130,6 +131,7 @@ enum htp_op_code {
HTP_OP_SSM_SCAN,
HTP_OP_TIMESTEP_EMBEDDING,
HTP_OP_MUL_MAT_NX_GLU,
HTP_OP_MUL_ID,
HTP_OP_INVALID
};
+8 -5
View File
@@ -12,8 +12,9 @@
#define HTP_TENSOR_TILE_N_COLS 32
#define HTP_TENSOR_TILE_N_ROWS 32
#define HTP_TENSOR_TILE_SIZE_F16 2048
#define HTP_TENSOR_TILE_SIZE_Q4_0 576
#define HTP_TENSOR_TILE_SIZE_F16 2048
#define HTP_TENSOR_TILE_SIZE_F8_E4M3 1024
#define HTP_TENSOR_TILE_SIZE_Q4_0 576
#define HTP_TENSOR_TILE_SIZE_Q4_1 640
#define HTP_TENSOR_TILE_SIZE_Q5_0 704
#define HTP_TENSOR_TILE_SIZE_Q5_1 768
@@ -36,7 +37,7 @@
#define HTP_TENSOR_TILE_K_Q2_0 64
#define HTP_TENSOR_TILE_SIZE_Q2_0 576
// Tiled weight tensor layouts (Q4_0, Q5_0, Q5_1, Q8_0, IQ4_NL, MXFP4, NVFP4, IQ2_XXS, Q1_0, Q2_0, K-quants):
// Tiled weight tensor layouts (Q4_0, Q5_0, Q5_1, Q8_0, IQ4_NL, MXFP4, NVFP4, F8_E4M3, IQ2_XXS, Q1_0, Q2_0, K-quants):
// See docs/backend/snapdragon/developer.md ("Tiled Weight Formats").
struct htp_tensor_mdev_range {
@@ -115,8 +116,9 @@ static inline uint32_t htp_tensor_get_tile_size(int type) {
case HTP_TYPE_MXFP4: return HTP_TENSOR_TILE_SIZE_MXFP4;
case HTP_TYPE_NVFP4: return HTP_TENSOR_TILE_SIZE_NVFP4;
case HTP_TYPE_IQ2_XXS: return HTP_TENSOR_TILE_SIZE_IQ2_XXS;
case HTP_TYPE_F16: return HTP_TENSOR_TILE_SIZE_F16;
default: return 0;
case HTP_TYPE_F16: return HTP_TENSOR_TILE_SIZE_F16;
case HTP_TYPE_F8_E4M3: return HTP_TENSOR_TILE_SIZE_F8_E4M3;
default: return 0;
}
}
@@ -143,6 +145,7 @@ static inline uint32_t htp_tensor_get_row_size(int type, uint32_t ne00) {
case HTP_TYPE_F32: return ne00 * 4;
case HTP_TYPE_F16:
case HTP_TYPE_BF16: return ne00 * 2;
case HTP_TYPE_F8_E4M3: return ne00;
case HTP_TYPE_Q8_0: return (ne00 / 32) * 34;
case HTP_TYPE_Q4_0:
case HTP_TYPE_IQ4_NL: return (ne00 / 32) * 18;
+25
View File
@@ -166,6 +166,31 @@ static inline HVX_Vector hvx_vec_f32_to_f16(HVX_Vector v0, HVX_Vector v1) {
return Q6_Vh_vdeal_Vh(hvx_vec_f32_to_f16_shuff(v0, v1));
}
static inline HVX_Vector hvx_vec_f32_to_f16_clamped(HVX_Vector v0, HVX_Vector v1) {
const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0));
v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1));
return hvx_vec_f32_to_f16(v0, v1);
}
// Multiply 64 F16 lanes to F32: lo = lanes 0..31, hi = lanes 32..63
static inline HVX_VectorPair hvx_vec_mul_f16_f16_to_f32_pair(HVX_Vector v1, HVX_Vector v2) {
#if __HVX_ARCH__ >= 79
HVX_VectorPair p = Q6_Wsf_vmpy_VhfVhf(v1, v2);
return Q6_W_vshuff_VVR(Q6_V_hi_W(p), Q6_V_lo_W(p), -4);
#else
HVX_VectorPair p = Q6_Wqf32_vmpy_VhfVhf(v1, v2);
HVX_Vector hi = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p));
HVX_Vector lo = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p));
return Q6_W_vshuff_VVR(hi, lo, -4);
#endif
}
static inline HVX_Vector hvx_vec_mul_f16_f16_to_f32_lower32(HVX_Vector v1, HVX_Vector v2) {
return Q6_V_lo_W(hvx_vec_mul_f16_f16_to_f32_pair(v1, v2));
}
#if __HVX_ARCH__ >= 79
static inline HVX_VectorPair hvx_vec_f16_to_f32_shuff(HVX_Vector v) {
const HVX_Vector one = hvx_vec_splat_f16(1.0);
+82 -237
View File
@@ -265,18 +265,6 @@ static void quantize_row_f32_q8_1_s16_tiled(float * restrict x, uint8_t * restri
}
}
static inline HVX_Vector hvx_vec_reduce_abs_max_half_f16(HVX_Vector v) {
HVX_Vector m = hvx_vec_abs_f16(v);
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 2));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 4));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 8));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 16));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 32));
HVX_Vector m_lo = hvx_vec_repl_f16(m);
HVX_Vector m_hi = hvx_vec_repl_f16(Q6_V_vror_VR(m, 64));
return Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), m_lo, m_hi);
}
__attribute__((always_inline))
static inline void quantize_block_f16_q8_1_tiled_impl(const __fp16 * restrict x, uint8_t * restrict y_block, const bool sums16,
const __fp16 * restrict x_sb) {
@@ -581,41 +569,6 @@ static void quantize_row_f16_f16_tiled(const __fp16 * restrict x, uint8_t * rest
// Dot kernels & helpers that consume tiled activations
static inline HVX_Vector hvx_vec_mul_f16_f16_to_f32_lower32(HVX_Vector v1, HVX_Vector v2) {
#if __HVX_ARCH__ >= 79
HVX_VectorPair p = Q6_Wsf_vmpy_VhfVhf(v1, v2);
return Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(p), Q6_V_lo_W(p), -4));
#else
HVX_VectorPair p = Q6_Wqf32_vmpy_VhfVhf(v1, v2);
HVX_Vector hi = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p));
HVX_Vector lo = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p));
return Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -4));
#endif
}
// both halves of hvx_vec_mul_f16_f16_to_f32_lower32: lo = products of lanes 0..31, hi = lanes 32..63
static inline HVX_VectorPair hvx_vec_mul_f16_f16_to_f32_pair(HVX_Vector v1, HVX_Vector v2) {
#if __HVX_ARCH__ >= 79
HVX_VectorPair p = Q6_Wsf_vmpy_VhfVhf(v1, v2);
return Q6_W_vshuff_VVR(Q6_V_hi_W(p), Q6_V_lo_W(p), -4);
#else
HVX_VectorPair p = Q6_Wqf32_vmpy_VhfVhf(v1, v2);
HVX_Vector hi = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p));
HVX_Vector lo = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p));
return Q6_W_vshuff_VVR(hi, lo, -4);
#endif
}
static inline HVX_Vector unpack_q1_0_group(
HVX_Vector v_plane,
int g,
HVX_Vector v_neg_one,
HVX_Vector v_pos_one
) {
HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << g);
return Q6_V_vmux_QVV(q, v_pos_one, v_neg_one);
}
static inline HVX_Vector accum_q1_0_32x1(
HVX_Vector v_plane,
const HVX_Vector * restrict v_act,
@@ -785,12 +738,6 @@ static inline HVX_VectorPair accum_q8_0_32x2(
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
// Q5_K: OR 0x10 into every lane of v whose flag j is set in the plane (see HTP_TENSOR_TILE_SIZE_Q5_K)
static inline HVX_Vector hvx_q5k_or_hibit(HVX_Vector v, HVX_Vector v_plane, int j) {
HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
return Q6_V_vandor_VQR(v, q, 0x10101010);
}
static inline HVX_Vector accum_5bit_32x1(
const HVX_Vector * restrict vptr,
const HVX_Vector * restrict v_act
@@ -838,12 +785,6 @@ static inline HVX_VectorPair accum_5bit_32x2(
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
// OR 0xF0 into every lane of v whose flag j is set in the plane, i.e. 4-bit value | 0xF0 = q - 16 where the 5th bit is clear (Q5_0)
static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j) {
HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0);
}
static inline HVX_Vector accum_q5_0_32x1(
const HVX_Vector * restrict vptr,
const HVX_Vector * restrict v_act
@@ -891,14 +832,6 @@ static inline HVX_VectorPair accum_q5_0_32x2(
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
// Q6_K weights are stored unsigned (0..63), see HTP_TENSOR_TILE_SIZE_Q6_K. Unpack k-group g of a tile to signed bytes (q - 32)
static inline HVX_Vector unpack_q6_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_0f, HVX_Vector mask_03, HVX_Vector i32) {
HVX_Vector v_lo = (g & 1) ? Q6_Vub_vlsr_VubR(vptr[g >> 1], 4) : Q6_V_vand_VV(vptr[g >> 1], mask_0f);
HVX_Vector v_hi = (g & 3) ? Q6_Vub_vlsr_VubR(vptr[4 + (g >> 2)], 2 * (g & 3)) : vptr[4 + (g >> 2)];
HVX_Vector v_q = Q6_V_vor_VV(v_lo, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_hi, mask_03), 4));
return Q6_Vb_vsub_VbVb(v_q, i32);
}
// k 0..15 and k 16..31 of a Q6_K tile have different scales: lo half of the pair sums k 0..15, hi half sums k 16..31
static inline HVX_VectorPair accum_q6_k_32x1(
const HVX_Vector * restrict vptr,
@@ -958,24 +891,6 @@ static inline HVX_Vector scale_q6_k_32x1(HVX_VectorPair v_sums, HVX_Vector v_sca
return hvx_vec_add_f32_f32(v_lo, v_hi);
}
// Q3_K / Q2_K: low 2 bits of k-group g, see HTP_TENSOR_TILE_SIZE_Q3_K
static inline HVX_Vector unpack_q3_k_low2(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
HVX_Vector v = vptr[g >> 2];
if ((g & 3) == 3) {
return Q6_Vub_vlsr_VubR(v, 6);
}
if (g & 3) {
v = Q6_Vub_vlsr_VubR(v, 2 * (g & 3));
}
return Q6_V_vand_VV(v, mask_03);
}
// Q3_K k-group g as signed bytes: low2 | 0xFC (= low2 - 4) where bit g of vector 2 is set
static inline HVX_Vector unpack_q3_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
HVX_VectorPred q_neg = Q6_Q_vand_VR(vptr[2], 0x01010101u << g);
return Q6_V_vandor_VQR(unpack_q3_k_low2(vptr, g, mask_03), q_neg, 0xFCFCFCFC);
}
// same half split as accum_q6_k_32x1
static inline HVX_VectorPair accum_q3_k_32x1(
const HVX_Vector * restrict vptr,
@@ -1117,33 +1032,6 @@ static inline void accum_q2_0_32x2(
*v_sum1 = Q6_Vw_vadd_VwVw(v_sum1_lo, v_sum1_hi);
}
// Q2_K: fp16 d (*v_d) and -dmin (*v_m) of the 32 rows of a super-block (8 tiles, VTCM stride 384), each in both vector halves
static inline void q2_k_load_dmin(const uint8_t * restrict sb, HVX_Vector * restrict v_d, HVX_Vector * restrict v_m) {
HVX_Vector v_dd = Q6_V_vzero(); // lanes 0..31: d, lanes 32..63: -dmin
#pragma unroll
for (int j = 0; j < 8; j++) {
HVX_Vector v = hvx_vmem(sb + j * 384 + 256); // the slice is at bytes 64..79
v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(16 * j), v_dd, Q6_V_vror_VR(v, (64 - 16 * j) & 127));
}
HVX_VectorPred q_lo = Q6_Q_vsetq_R(64);
HVX_Vector v_r = Q6_V_vror_VR(v_dd, 64);
*v_d = Q6_V_vmux_QVV(q_lo, v_dd, v_r);
*v_m = Q6_V_vmux_QVV(q_lo, v_r, v_dd);
}
// Q2_K: fp16 D = d * scale and M = -dmin * min of a tile from its scale bytes, in the lanes of the Q6_K scales
static inline void q2_k_unpack_scales(const uint8_t * restrict tile, HVX_Vector v_d, HVX_Vector v_m,
HVX_Vector * restrict v_D, HVX_Vector * restrict v_M) {
HVX_Vector v_sc = hvx_vmem(tile + 256);
HVX_Vector v_l = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_V_vand_VV(v_sc, Q6_Vb_vsplat_R(0x0F))));
HVX_Vector v_mn = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_Vub_vlsr_VubR(v_sc, 4)));
// qf32 product: rounds like GGML_FP32_TO_FP16(d * scale) (qf16 is off by 1 ulp for many values on v73)
*v_D = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_l), v_d));
*v_M = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_mn), v_m));
}
// Q2_K scale and min nibbles of a tile as halfword pairs: word r = sub-block 1 << 16 | sub-block 0 of row r
static inline void q2_k_scale_pairs(const uint8_t * restrict tile, HVX_Vector * restrict v_sc2, HVX_Vector * restrict v_mn2) {
HVX_Vector v_h = Q6_Vh_vshuff_Vh(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile + 256))));
@@ -1213,6 +1101,40 @@ static __attribute__((noinline)) void hvx_tiled_store_row_f16_f16(void * restric
hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
}
static __attribute__((noinline)) void hvx_tiled_store_row_f32_scale(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vmemu(sz));
hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
}
static __attribute__((noinline)) void hvx_tiled_store_row_f16_scale(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vmemu(sz));
const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum));
hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
}
static __attribute__((noinline)) void hvx_tiled_store_row_f32_scale_scalar(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vec_repl4(hvx_vmemu(sz)));
hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
}
static __attribute__((noinline)) void hvx_tiled_store_row_f16_scale_scalar(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vec_repl4(hvx_vmemu(sz)));
const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum));
hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
}
static inline hvx_tiled_store_row_fn_t resolve_hvx_tiled_store_row_scaled_fn(uint32_t dst_elem_size, bool scalar_scale) {
const bool dst_f16 = (dst_elem_size == sizeof(__fp16));
if (dst_f16) {
return scalar_scale ? hvx_tiled_store_row_f16_scale_scalar : hvx_tiled_store_row_f16_scale;
}
return scalar_scale ? hvx_tiled_store_row_f32_scale_scalar : hvx_tiled_store_row_f32_scale;
}
static inline hvx_tiled_store_row_fn_t resolve_hvx_tiled_store_row_fn(uint32_t dst_elem_size, bool has_bias, uint32_t bias_elem_size) {
const bool dst_f16 = (dst_elem_size == sizeof(__fp16));
const bool bias_f16 = (bias_elem_size == sizeof(__fp16));
@@ -1958,108 +1880,6 @@ static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, void * restrict s0, void
store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
#define IQ2XXS_GROUPS 4 // 8-element grid entries per tile row
#define IQ2XXS_TILES_PER_SB 8 // 256 / 32
#define IQ2XXS_CODE_SHIFT 1 // log2(2 B per grid code)
#define IQ2XXS_WORD_BYTES 4
#define IQ2XXS_IDX_BITS 8
#define IQ2XXS_IDX_MASK 0xFF
#define IQ2XXS_SIGN_BITS 7
#define IQ2XXS_SIGN_MASK 0x7F
#define IQ2XXS_PARITY_SHIFT 7
#define IQ2XXS_SCALE_SHIFT 28
#define IQ2XXS_D_SLICE_OFF 256 // 4 fp16 d of the tile, after the 32 rows x 8 B
#define IQ2XXS_D_SCALE 0.125f // db = d * (2 * scale + 1) / 8
#define IQ2XXS_D_SLICE_BYTES 8
#define IQ2XXS_SIGN_PRED_LO 0x08040201 // sign bit of bytes 0..3 of an 8-element group
#define IQ2XXS_SIGN_PRED_HI 0x80402010 // sign bit of bytes 4..7
#define IQ2XXS_IDX_LO_MASK 0x1FE // index byte << 1, halfword 0 of a lane
#define IQ2XXS_IDX_HI_MASK 0x1FE0000 // index byte << 1, halfword 1 of a lane
#define IQ2XXS_NIB_LO_MASK 0x00000F0F // nibbles of the code bytes, lane bytes 0..1
#define IQ2XXS_NIB_HI_MASK 0x0F0F0000 // nibbles of the code bytes, lane bytes 2..3
static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) {
return (HVX_Vector *) (tile + htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS) - HTP_TENSOR_TILE_SCRATCH_IQ2_XXS);
}
// IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words
static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) {
HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES;
// lo: 4 grid indices per row, hi: 4 sign indices + scale per row
HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES);
HVX_Vector v_idx = Q6_V_lo_W(p);
// one halfword gather per 2 groups: lane i gets the codes of groups 2h and 2h+1 in halfwords 0 and 1
HVX_Vector v_off0 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0);
Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1);
return Q6_V_hi_W(p);
}
// IQ2_XXS: wait for the gathers of iq2xxs_gather_issue and read the grid codes
static inline void iq2xxs_gather_wait(const uint8_t * restrict tile, HVX_Vector * restrict v_c) {
HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
hvx_gather_sync(&v_scr[1]);
v_c[0] = v_scr[0];
v_c[1] = v_scr[1];
}
// IQ2_XXS: 8 int8 weight words (k = 4g..4g+3 per row lane) and the odd group scale (2 * scale + 1) of a 32x32 tile
static inline void iq2xxs_decode_expand(const HVX_Vector * restrict v_c, HVX_Vector v_sgn, HVX_Vector * restrict v_w, HVX_Vector * restrict v_ls) {
const HVX_Vector v_zero = Q6_V_vzero();
const HVX_Vector v_one = Q6_V_vsplat_R(1);
const HVX_Vector v_sgn_mask = Q6_V_vsplat_R(IQ2XXS_SIGN_MASK);
const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut);
#pragma unroll
for (int l = 0; l < IQ2XXS_GROUPS; l++) {
// 7 stored sign bits + even-parity bit
HVX_Vector v_s7 = Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SIGN_BITS * l), v_sgn_mask);
HVX_Vector v_t = Q6_Vh_vpopcount_Vh(v_s7);
HVX_Vector v_s = Q6_V_vor_VV(v_s7, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_t, v_one), IQ2XXS_PARITY_SHIFT));
HVX_Vector v_s16 = Q6_V_vor_VV(v_s, Q6_Vw_vasl_VwR(v_s, 8));
HVX_Vector v_rep = Q6_V_vor_VV(v_s16, Q6_Vw_vasl_VwR(v_s16, 16));
HVX_VectorPred q_lo = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_LO);
HVX_VectorPred q_hi = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_HI);
HVX_Vector v_c2 = v_c[l >> 1];
// code halfword duplicated in both halves of each lane
HVX_Vector v_d = (l & 1) ? Q6_Vh_vshuffo_VhVh(v_c2, v_c2) : Q6_Vh_vshuffe_VhVh(v_c2, v_c2);
// lane bytes: nibbles 0, 2, 1, 3 of the code, so vlut16 returns elements 0..3 / 4..7 as words
HVX_Vector v_n = Q6_V_vor_VV(Q6_V_vand_VV(v_d, Q6_V_vsplat_R(IQ2XXS_NIB_LO_MASK)),
Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_d, 4), Q6_V_vsplat_R(IQ2XXS_NIB_HI_MASK)));
HVX_VectorPair p_g = Q6_Wh_vlut16_VbVhR(v_n, v_nib_lut, 0);
HVX_Vector v_g0 = Q6_V_lo_W(p_g);
HVX_Vector v_g1 = Q6_V_hi_W(p_g);
v_w[2 * l + 0] = Q6_V_vmux_QVV(q_lo, Q6_Vb_vsub_VbVb(v_zero, v_g0), v_g0);
v_w[2 * l + 1] = Q6_V_vmux_QVV(q_hi, Q6_Vb_vsub_VbVb(v_zero, v_g1), v_g1);
}
*v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SCALE_SHIFT), 1), v_one);
}
// IQ2_XXS: fp16 d of the 32 rows of a super-block (8 tiles) in halfword lanes 0..31
static inline HVX_Vector iq2xxs_gather_d(const uint8_t * restrict sb) {
const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
HVX_Vector v_dd = Q6_V_vzero();
#pragma unroll
for (int j = 0; j < IQ2XXS_TILES_PER_SB; j++) {
HVX_Vector v = hvx_vmem(sb + j * padded + IQ2XXS_D_SLICE_OFF);
v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(IQ2XXS_D_SLICE_BYTES * j), v_dd,
Q6_V_vror_VR(v, (VLEN - IQ2XXS_D_SLICE_BYTES * j) & (VLEN - 1)));
}
return v_dd;
}
// IQ2_XXS: fp32 d / 8 of the 32 rows of a super-block (8 tiles) in lanes 0..31
static inline HVX_Vector iq2xxs_load_d(const uint8_t * restrict sb) {
// db = d * (0.5 + scale) * 0.25 = d * (2 * scale + 1) / 8
@@ -2246,29 +2066,6 @@ static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, void * restrict s0, void
store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
#define NVFP4_SCALE_OFF 512 // UE4M3 scales after the 32 rows x 16 B of quants
#define NVFP4_UE4M3_MASK 0x7F // code bits; 0x7F is the NaN code, decoded as 0
#define NVFP4_UE4M3_MIN_NORMAL 0x08 // exponent field 1
#define NVFP4_UE4M3_MAN_SHIFT 20 // 23 - 3 mantissa bits
#define NVFP4_UE4M3_REBIAS 0x3C000000 // (127 - 7) << 23
#define NVFP4_UE4M3_SUB_SCALE 0x1p-9f // subnormal: mantissa * 2^-9
#define NVFP4_VECS_PER_GROUP 2 // quant vectors per scale group
#define NVFP4_ACT_PER_GROUP 4 // activation vectors per scale group
// UE4M3 codes in the low byte of each word -> fp32 (without the 0.5 of kvalues_mxfp4)
static inline HVX_Vector nvfp4_ue4m3_to_f32(HVX_Vector v_code) {
HVX_Vector v_mask = Q6_V_vsplat_R(NVFP4_UE4M3_MASK);
HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask);
HVX_Vector v_norm = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(v_x, NVFP4_UE4M3_MAN_SHIFT), Q6_V_vsplat_R(NVFP4_UE4M3_REBIAS));
HVX_Vector v_sub = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vw(v_x), hvx_vec_splat_f32(NVFP4_UE4M3_SUB_SCALE));
HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VwVw(Q6_V_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x);
HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VwVw(v_x, v_mask);
return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm));
}
// fp32 scales of the two 16-element sub-blocks of a tile, one lane per row
static inline void nvfp4_load_scales(const uint8_t * restrict tile, HVX_Vector * restrict v_d0, HVX_Vector * restrict v_d1) {
HVX_VectorPair v_code = Q6_Wuw_vunpack_Vuh(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile + NVFP4_SCALE_OFF))));
@@ -2391,6 +2188,54 @@ static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, void * restrict s0, void
store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
static void tiled_vec_dot_f8_e4m3_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) {
const HVX_Vector * restrict vptr = (const HVX_Vector *) vx;
const HVX_Vector * restrict v_act = (const HVX_Vector *) vy;
const uint32_t n_vecs = ((n + 31) / 32) * 8;
HVX_VectorPair acc = Q6_W_vzero();
for (uint32_t i = 0; i < n_vecs; i++) {
HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(vptr[i]);
HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -4);
HVX_Vector v_w0 = f8_e4m3_to_f16(Q6_V_lo_W(vp_k));
HVX_Vector v_w1 = f8_e4m3_to_f16(Q6_V_hi_W(vp_k));
acc = hvx_vec_mpyacc_f32_f16(acc, v_w0, v_act[2 * i + 0]);
acc = hvx_vec_mpyacc_f32_f16(acc, v_w1, v_act[2 * i + 1]);
}
HVX_Vector v_sum = hvx_vec_add_f32_f32(Q6_V_lo_W(acc), Q6_V_hi_W(acc));
store_row(s, valid_rows, v_sum, sz);
}
static void tiled_vec_dot_f8_e4m3_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) {
const HVX_Vector * restrict vptr = (const HVX_Vector *) vx;
const HVX_Vector * restrict v_act0 = (const HVX_Vector *) vy0;
const HVX_Vector * restrict v_act1 = (const HVX_Vector *) vy1;
const uint32_t n_vecs = ((n + 31) / 32) * 8;
HVX_VectorPair acc0 = Q6_W_vzero();
HVX_VectorPair acc1 = Q6_W_vzero();
for (uint32_t i = 0; i < n_vecs; i++) {
HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(vptr[i]);
HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -4);
HVX_Vector v_w0 = f8_e4m3_to_f16(Q6_V_lo_W(vp_k));
HVX_Vector v_w1 = f8_e4m3_to_f16(Q6_V_hi_W(vp_k));
acc0 = hvx_vec_mpyacc_f32_f16(acc0, v_w0, v_act0[2 * i + 0]);
acc1 = hvx_vec_mpyacc_f32_f16(acc1, v_w0, v_act1[2 * i + 0]);
acc0 = hvx_vec_mpyacc_f32_f16(acc0, v_w1, v_act0[2 * i + 1]);
acc1 = hvx_vec_mpyacc_f32_f16(acc1, v_w1, v_act1[2 * i + 1]);
}
HVX_Vector v_sum0 = hvx_vec_add_f32_f32(Q6_V_lo_W(acc0), Q6_V_hi_W(acc0));
HVX_Vector v_sum1 = hvx_vec_add_f32_f32(Q6_V_lo_W(acc1), Q6_V_hi_W(acc1));
store_row(s0, valid_rows, v_sum0, sz0);
store_row(s1, valid_rows, v_sum1, sz1);
}
static void tiled_vec_dot_f16_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) {
const HVX_Vector * restrict vptr = (const HVX_Vector *) vx;
const HVX_Vector * restrict v_act = (const HVX_Vector *) vy;
+14
View File
@@ -8,6 +8,7 @@
#include "hex-utils.h"
#include "hvx-base.h"
#include "hvx-repl.h"
#include "hvx-types.h"
static inline HVX_Vector hvx_vec_reduce_sum_n_i32(HVX_Vector in, unsigned int n) {
@@ -399,6 +400,19 @@ static inline void hvx_argmax_f32(
*out_idx = best_idx;
}
// Reduce abs-max independently across low 32 and high 32 F16 lanes
static inline HVX_Vector hvx_vec_reduce_abs_max_half_f16(HVX_Vector v) {
HVX_Vector m = hvx_vec_abs_f16(v);
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 2));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 4));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 8));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 16));
m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 32));
HVX_Vector m_lo = hvx_vec_repl_f16(m);
HVX_Vector m_hi = hvx_vec_repl_f16(Q6_V_vror_VR(m, 64));
return Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), m_lo, m_hi);
}
#undef hvx_reduce_loop_body
#undef HVX_REDUCE_MAX_OP
#undef HVX_REDUCE_SUM_OP
-3
View File
@@ -38,7 +38,6 @@ struct htp_im2col_context {
uint32_t pe_gather_nvec; // vectors per gathered patch (KH == 1 blocked path)
// Precomputed dimensions for worker threads
uint32_t N;
uint32_t IC;
uint32_t ID, IH, IW;
uint32_t KD, KH, KW;
@@ -970,7 +969,6 @@ int op_im2col(struct htp_ops_context * octx) {
ictx.pe_owb = kparams->owb;
ictx.pe_wb = kparams->wb;
ictx.pe_nbpr = kparams->nbpr;
ictx.N = kparams->N;
ictx.IC = kparams->IC;
ictx.ID = kparams->ID;
ictx.IH = kparams->IH;
@@ -1069,7 +1067,6 @@ int op_im2col_3d(struct htp_ops_context * octx) {
ictx.pe_owb = kparams->owb;
ictx.pe_wb = kparams->wb;
ictx.pe_nbpr = kparams->nbpr;
ictx.N = kparams->N;
ictx.IC = kparams->IC;
ictx.ID = kparams->ID;
ictx.IH = kparams->IH;
-1
View File
@@ -58,7 +58,6 @@ struct htp_im2col_kernel_params {
uint32_t wb;
uint32_t nbpr;
uint32_t N;
uint32_t IC;
uint32_t ID, IH, IW;
uint32_t KD, KH, KW;
@@ -16,7 +16,7 @@
#include "hvx-quant.h"
#include "hvx-fa-kernels.h"
#include "hmx-utils.h"
#include "hmx-fa-kernels.h"
#include "hmx-fa-fp16-kernels.h"
#include "hmx-queue.h"
#include "lightning-indexer-ops.h"
+1
View File
@@ -966,6 +966,7 @@ static int execute_op(struct htp_ops_context * octx) {
case HTP_OP_SUB:
case HTP_OP_DIV:
case HTP_OP_ADD_ID:
case HTP_OP_MUL_ID:
return op_binary(octx);
case HTP_OP_NORM:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,25 @@
#ifndef HTP_MATMUL_HMX_F16_H
#define HTP_MATMUL_HMX_F16_H
#include "matmul-internal.h"
int hmx_f16_mm_2d(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams,
const hmx_mm_2d_params_t * p);
int hmx_f16_mm_batched(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams,
const hmx_mm_batched_params_t * params);
int hmx_f16_mm_nx_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
int hmx_f16_mm_nx_glu_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
int hmx_f16_mm_id_2d(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams,
const hmx_mm_id_2d_params_t * p);
#endif // HTP_MATMUL_HMX_F16_H
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,25 @@
#ifndef HTP_MATMUL_HMX_W8A8_H
#define HTP_MATMUL_HMX_W8A8_H
#include "matmul-internal.h"
int hmx_w8a8_mm_2d(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams,
const hmx_mm_2d_params_t * p);
int hmx_w8a8_mm_batched(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams,
const hmx_mm_batched_params_t * params);
int hmx_w8a8_mm_nx_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
int hmx_w8a8_mm_nx_glu_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
int hmx_w8a8_mm_id_2d(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams,
const hmx_mm_id_2d_params_t * p);
#endif // HTP_MATMUL_HMX_W8A8_H
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
#ifndef HTP_MATMUL_HVX_H
#define HTP_MATMUL_HVX_H
#include "matmul-internal.h"
int hvx_mm_matmul(struct htp_ops_context * octx);
int hvx_mm_matmul_nx(struct htp_ops_context * octx);
int hvx_mm_matmul_id(struct htp_ops_context * octx, const struct htp_mmid_mapping * map);
int hvx_mm_matmul_id_nx(struct htp_ops_context * octx, const struct htp_mmid_mapping * map);
#endif // HTP_MATMUL_HVX_H
+676
View File
@@ -0,0 +1,676 @@
#ifndef HTP_MATMUL_INTERNAL_H
#define HTP_MATMUL_INTERNAL_H
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <HAP_compute_res.h>
#include <math.h>
#include <string.h>
#include <stdatomic.h>
#include "dma-queue.h"
#include "hvx-utils.h"
#include "hvx-dump.h"
#include "hvx-arith.h"
#include "hvx-reduce.h"
#include "hvx-copy.h"
#include "hvx-norm.h"
#include "hmx-utils.h"
#include "hmx-queue.h"
#include "htp-ctx.h"
#include "htp-ops.h"
#include "htp-tensor.h"
#include "matmul-ops.h"
#include "htp-vtcm.h"
#define htp_matmul_tensors_preamble \
const struct htp_tensor * restrict __attribute__((unused)) src0 = octx->src[0]; \
const struct htp_tensor * restrict __attribute__((unused)) src1 = octx->src[1]; \
const struct htp_tensor * restrict __attribute__((unused)) bias = \
(octx->op == HTP_OP_MUL_MAT_ADD) ? octx->src[2] : NULL; \
const struct htp_tensor * restrict __attribute__((unused)) dst = octx->dst; \
const struct htp_tensor * restrict __attribute__((unused)) act = src1; \
\
const uint32_t __attribute__((unused)) ne00 = src0->ne[0]; \
const uint32_t __attribute__((unused)) ne01 = src0->ne[1]; \
const uint32_t __attribute__((unused)) ne02 = src0->ne[2]; \
const uint32_t __attribute__((unused)) ne03 = src0->ne[3]; \
\
const uint32_t __attribute__((unused)) ne10 = src1->ne[0]; \
const uint32_t __attribute__((unused)) ne11 = src1->ne[1]; \
const uint32_t __attribute__((unused)) ne12 = src1->ne[2]; \
const uint32_t __attribute__((unused)) ne13 = src1->ne[3]; \
\
const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \
const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \
const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \
const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \
\
const uint32_t __attribute__((unused)) nb00 = src0->nb[0]; \
const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \
const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \
const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \
\
const uint32_t __attribute__((unused)) nb10 = src1->nb[0]; \
const uint32_t __attribute__((unused)) nb11 = src1->nb[1]; \
const uint32_t __attribute__((unused)) nb12 = src1->nb[2]; \
const uint32_t __attribute__((unused)) nb13 = src1->nb[3]; \
\
const uint32_t __attribute__((unused)) nb0 = dst->nb[0]; \
const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \
const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \
const uint32_t __attribute__((unused)) nb3 = dst->nb[3];
// --- Shared LUTs (defined in matmul-ops.c) ---
extern const uint8_t expand_x32_e8m0[128];
extern const uint8_t kvalues_iq4nl_lut[];
extern const uint8_t kvalues_mxfp4_lut[];
extern const uint8_t * iq2xxs_vtcm_lut;
void iq2xxs_lut_copy(uint8_t * restrict lut);
static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct htp_mm_hvx_vtcm_layout * restrict L) {
if (L->lut_bytes == 0) {
return;
}
iq2xxs_lut_copy(base + L->off_lut);
}
// --- Shared Quant Unpack Helpers ---
static inline HVX_Vector unpack_q1_0_group(
HVX_Vector v_plane,
int g,
HVX_Vector v_neg_one,
HVX_Vector v_pos_one
) {
HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << g);
return Q6_V_vmux_QVV(q, v_pos_one, v_neg_one);
}
// Q5_K: OR 0x10 into every lane of v whose flag j is set in the plane (see HTP_TENSOR_TILE_SIZE_Q5_K)
static inline HVX_Vector hvx_q5k_or_hibit(HVX_Vector v, HVX_Vector v_plane, int j) {
HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
return Q6_V_vandor_VQR(v, q, 0x10101010);
}
// OR 0xF0 into every lane of v whose flag j is set in the plane, i.e. 4-bit value | 0xF0 = q - 16 where the 5th bit is clear (Q5_0)
static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j) {
HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0);
}
// Q6_K weights are stored unsigned (0..63), see HTP_TENSOR_TILE_SIZE_Q6_K. Unpack k-group g of a tile to signed bytes (q - 32)
static inline HVX_Vector unpack_q6_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_0f, HVX_Vector mask_03, HVX_Vector i32) {
HVX_Vector v_lo = (g & 1) ? Q6_Vub_vlsr_VubR(vptr[g >> 1], 4) : Q6_V_vand_VV(vptr[g >> 1], mask_0f);
HVX_Vector v_hi = (g & 3) ? Q6_Vub_vlsr_VubR(vptr[4 + (g >> 2)], 2 * (g & 3)) : vptr[4 + (g >> 2)];
HVX_Vector v_q = Q6_V_vor_VV(v_lo, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_hi, mask_03), 4));
return Q6_Vb_vsub_VbVb(v_q, i32);
}
// Q3_K / Q2_K: low 2 bits of k-group g, see HTP_TENSOR_TILE_SIZE_Q3_K
static inline HVX_Vector unpack_q3_k_low2(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
HVX_Vector v = vptr[g >> 2];
if ((g & 3) == 3) {
return Q6_Vub_vlsr_VubR(v, 6);
}
if (g & 3) {
v = Q6_Vub_vlsr_VubR(v, 2 * (g & 3));
}
return Q6_V_vand_VV(v, mask_03);
}
// Q3_K k-group g as signed bytes: low2 | 0xFC (= low2 - 4) where bit g of vector 2 is set
static inline HVX_Vector unpack_q3_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
HVX_VectorPred q_neg = Q6_Q_vand_VR(vptr[2], 0x01010101u << g);
return Q6_V_vandor_VQR(unpack_q3_k_low2(vptr, g, mask_03), q_neg, 0xFCFCFCFC);
}
// Q2_K: fp16 d (*v_d) and -dmin (*v_m) of the 32 rows of a super-block (8 tiles, VTCM stride 384), each in both vector halves
static inline void q2_k_load_dmin(const uint8_t * restrict sb, HVX_Vector * restrict v_d, HVX_Vector * restrict v_m) {
HVX_Vector v_dd = Q6_V_vzero(); // lanes 0..31: d, lanes 32..63: -dmin
#pragma unroll
for (int j = 0; j < 8; j++) {
HVX_Vector v = hvx_vmem(sb + j * 384 + 256); // the slice is at bytes 64..79
v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(16 * j), v_dd, Q6_V_vror_VR(v, (64 - 16 * j) & 127));
}
HVX_VectorPred q_lo = Q6_Q_vsetq_R(64);
HVX_Vector v_r = Q6_V_vror_VR(v_dd, 64);
*v_d = Q6_V_vmux_QVV(q_lo, v_dd, v_r);
*v_m = Q6_V_vmux_QVV(q_lo, v_r, v_dd);
}
// Q2_K: fp16 D = d * scale and M = -dmin * min of a tile from its scale bytes, in the lanes of the Q6_K scales
static inline void q2_k_unpack_scales(const uint8_t * restrict tile, HVX_Vector v_d, HVX_Vector v_m,
HVX_Vector * restrict v_D, HVX_Vector * restrict v_M) {
HVX_Vector v_sc = hvx_vmem(tile + 256);
HVX_Vector v_l = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_V_vand_VV(v_sc, Q6_Vb_vsplat_R(0x0F))));
HVX_Vector v_mn = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_Vub_vlsr_VubR(v_sc, 4)));
// qf32 product: rounds like GGML_FP32_TO_FP16(d * scale) (qf16 is off by 1 ulp for many values on v73)
*v_D = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_l), v_d));
*v_M = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_mn), v_m));
}
#define IQ2XXS_GROUPS 4 // 8-element grid entries per tile row
#define IQ2XXS_TILES_PER_SB 8 // 256 / 32
#define IQ2XXS_CODE_SHIFT 1 // log2(2 B per grid code)
#define IQ2XXS_WORD_BYTES 4
#define IQ2XXS_IDX_BITS 8
#define IQ2XXS_IDX_MASK 0xFF
#define IQ2XXS_SIGN_BITS 7
#define IQ2XXS_SIGN_MASK 0x7F
#define IQ2XXS_PARITY_SHIFT 7
#define IQ2XXS_SCALE_SHIFT 28
#define IQ2XXS_D_SLICE_OFF 256 // 4 fp16 d of the tile, after the 32 rows x 8 B
#define IQ2XXS_D_SCALE 0.125f // db = d * (2 * scale + 1) / 8
#define IQ2XXS_D_SLICE_BYTES 8
#define IQ2XXS_SIGN_PRED_LO 0x08040201 // sign bit of bytes 0..3 of an 8-element group
#define IQ2XXS_SIGN_PRED_HI 0x80402010 // sign bit of bytes 4..7
#define IQ2XXS_IDX_LO_MASK 0x1FE // index byte << 1, halfword 0 of a lane
#define IQ2XXS_IDX_HI_MASK 0x1FE0000 // index byte << 1, halfword 1 of a lane
#define IQ2XXS_NIB_LO_MASK 0x00000F0F // nibbles of the code bytes, lane bytes 0..1
#define IQ2XXS_NIB_HI_MASK 0x0F0F0000 // nibbles of the code bytes, lane bytes 2..3
static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) {
return (HVX_Vector *) (tile + htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS) - HTP_TENSOR_TILE_SCRATCH_IQ2_XXS);
}
// IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words
static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) {
HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES;
// lo: 4 grid indices per row, hi: 4 sign indices + scale per row
HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES);
HVX_Vector v_idx = Q6_V_lo_W(p);
// one halfword gather per 2 groups: lane i gets the codes of groups 2h and 2h+1 in halfwords 0 and 1
HVX_Vector v_off0 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0);
Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1);
return Q6_V_hi_W(p);
}
// IQ2_XXS: wait for the gathers of iq2xxs_gather_issue and read the grid codes
static inline void iq2xxs_gather_wait(const uint8_t * restrict tile, HVX_Vector * restrict v_c) {
HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
hvx_gather_sync(&v_scr[1]);
v_c[0] = v_scr[0];
v_c[1] = v_scr[1];
}
// IQ2_XXS: 8 int8 weight words (k = 4g..4g+3 per row lane) and the odd group scale (2 * scale + 1) of a 32x32 tile
static inline void iq2xxs_decode_expand(const HVX_Vector * restrict v_c, HVX_Vector v_sgn, HVX_Vector * restrict v_w, HVX_Vector * restrict v_ls) {
const HVX_Vector v_zero = Q6_V_vzero();
const HVX_Vector v_one = Q6_V_vsplat_R(1);
const HVX_Vector v_sgn_mask = Q6_V_vsplat_R(IQ2XXS_SIGN_MASK);
const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut);
#pragma unroll
for (int l = 0; l < IQ2XXS_GROUPS; l++) {
// 7 stored sign bits + even-parity bit
HVX_Vector v_s7 = Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SIGN_BITS * l), v_sgn_mask);
HVX_Vector v_t = Q6_Vh_vpopcount_Vh(v_s7);
HVX_Vector v_s = Q6_V_vor_VV(v_s7, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_t, v_one), IQ2XXS_PARITY_SHIFT));
HVX_Vector v_s16 = Q6_V_vor_VV(v_s, Q6_Vw_vasl_VwR(v_s, 8));
HVX_Vector v_rep = Q6_V_vor_VV(v_s16, Q6_Vw_vasl_VwR(v_s16, 16));
HVX_VectorPred q_lo = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_LO);
HVX_VectorPred q_hi = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_HI);
HVX_Vector v_c2 = v_c[l >> 1];
// code halfword duplicated in both halves of each lane
HVX_Vector v_d = (l & 1) ? Q6_Vh_vshuffo_VhVh(v_c2, v_c2) : Q6_Vh_vshuffe_VhVh(v_c2, v_c2);
// lane bytes: nibbles 0, 2, 1, 3 of the code, so vlut16 returns elements 0..3 / 4..7 as words
HVX_Vector v_n = Q6_V_vor_VV(Q6_V_vand_VV(v_d, Q6_V_vsplat_R(IQ2XXS_NIB_LO_MASK)),
Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_d, 4), Q6_V_vsplat_R(IQ2XXS_NIB_HI_MASK)));
HVX_VectorPair p_g = Q6_Wh_vlut16_VbVhR(v_n, v_nib_lut, 0);
HVX_Vector v_g0 = Q6_V_lo_W(p_g);
HVX_Vector v_g1 = Q6_V_hi_W(p_g);
v_w[2 * l + 0] = Q6_V_vmux_QVV(q_lo, Q6_Vb_vsub_VbVb(v_zero, v_g0), v_g0);
v_w[2 * l + 1] = Q6_V_vmux_QVV(q_hi, Q6_Vb_vsub_VbVb(v_zero, v_g1), v_g1);
}
*v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SCALE_SHIFT), 1), v_one);
}
// IQ2_XXS: fp16 d of the 32 rows of a super-block (8 tiles) in halfword lanes 0..31
static inline HVX_Vector iq2xxs_gather_d(const uint8_t * restrict sb) {
const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
HVX_Vector v_dd = Q6_V_vzero();
#pragma unroll
for (int j = 0; j < IQ2XXS_TILES_PER_SB; j++) {
HVX_Vector v = hvx_vmem(sb + j * padded + IQ2XXS_D_SLICE_OFF);
v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(IQ2XXS_D_SLICE_BYTES * j), v_dd,
Q6_V_vror_VR(v, (VLEN - IQ2XXS_D_SLICE_BYTES * j) & (VLEN - 1)));
}
return v_dd;
}
#define NVFP4_SCALE_OFF 512 // UE4M3 scales after the 32 rows x 16 B of quants
#define NVFP4_UE4M3_MASK 0x7F // code bits; 0x7F is the NaN code, decoded as 0
#define NVFP4_UE4M3_MIN_NORMAL 0x08 // exponent field 1
#define NVFP4_UE4M3_MAN_SHIFT 20 // 23 - 3 mantissa bits
#define NVFP4_UE4M3_REBIAS 0x3C000000 // (127 - 7) << 23
#define NVFP4_UE4M3_SUB_SCALE 0x1p-9f // subnormal: mantissa * 2^-9
#define NVFP4_VECS_PER_GROUP 2 // quant vectors per scale group
#define NVFP4_ACT_PER_GROUP 4 // activation vectors per scale group
#define NVFP4_UE4M3_F16_MAN_SHIFT 7 // 10 - 3 mantissa bits
#define NVFP4_UE4M3_F16_REBIAS 0x2000 // (15 - 7) << 10
#define NVFP4_UE4M3_F16_SUB_SCALE 0x1800 // 2^-9 as fp16 bits
// UE4M3 codes in the low byte of each word -> fp32 (without the 0.5 of kvalues_mxfp4)
static inline HVX_Vector nvfp4_ue4m3_to_f32(HVX_Vector v_code) {
HVX_Vector v_mask = Q6_V_vsplat_R(NVFP4_UE4M3_MASK);
HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask);
HVX_Vector v_norm = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(v_x, NVFP4_UE4M3_MAN_SHIFT), Q6_V_vsplat_R(NVFP4_UE4M3_REBIAS));
HVX_Vector v_sub = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vw(v_x), hvx_vec_splat_f32(NVFP4_UE4M3_SUB_SCALE));
HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VwVw(Q6_V_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x);
HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VwVw(v_x, v_mask);
return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm));
}
// UE4M3 codes in the low byte of each halfword -> fp16
static inline HVX_Vector nvfp4_ue4m3_to_f16(HVX_Vector v_code) {
HVX_Vector v_mask = Q6_Vh_vsplat_R(NVFP4_UE4M3_MASK);
HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask);
HVX_Vector v_norm = Q6_Vh_vadd_VhVh(Q6_Vh_vasl_VhR(v_x, NVFP4_UE4M3_F16_MAN_SHIFT), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_REBIAS));
HVX_Vector v_sub = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_x), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_SUB_SCALE)));
HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VhVh(Q6_Vh_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x);
HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VhVh(v_x, v_mask);
return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm));
}
#define F8_E4M3_SIGN_MASK 0x80 // sign bit in FP8 E4M3
#define F8_E4M3_F16_MAN_SHIFT 7 // 10 - 3 mantissa bits
#define F8_E4M3_F16_REBIAS 0x2000 // (15 - 7) << 10
#define F8_E4M3_F16_SUB_SCALE 0x1800 // 2^-9 as fp16 bits
// Signed F8_E4M3 codes in the low byte of each halfword -> fp16 (0x7F/0xFF NaN -> 0)
static inline HVX_Vector f8_e4m3_to_f16(HVX_Vector v_code) {
HVX_Vector v_mask = Q6_Vh_vsplat_R(NVFP4_UE4M3_MASK);
HVX_Vector v_abs = Q6_V_vand_VV(v_code, v_mask);
HVX_Vector v_sign = Q6_Vh_vasl_VhR(Q6_V_vand_VV(v_code, Q6_Vh_vsplat_R(F8_E4M3_SIGN_MASK)), 8);
HVX_Vector v_norm = Q6_Vh_vadd_VhVh(Q6_Vh_vasl_VhR(v_abs, F8_E4M3_F16_MAN_SHIFT), Q6_Vh_vsplat_R(F8_E4M3_F16_REBIAS));
HVX_Vector v_sub = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_abs), Q6_Vh_vsplat_R(F8_E4M3_F16_SUB_SCALE)));
HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VhVh(Q6_Vh_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_abs);
HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VhVh(v_abs, v_mask);
return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vor_VV(Q6_V_vmux_QVV(q_sub, v_sub, v_norm), v_sign));
}
// --- Shared HMX Bias / Packing Helpers ---
static inline HVX_Vector hmx_load_bias_f32_32_f16(const void * bias_row_base, size_t c) {
const __fp16 * p = (const __fp16 *) bias_row_base + c;
return Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(p)));
}
static inline HVX_Vector hmx_load_bias_f32_32_f32(const void * bias_row_base, size_t c) {
const float * p = (const float *) bias_row_base + c;
return hvx_vmemu(p);
}
static inline HVX_VectorPair hmx_load_bias_f32_64_f16(const void * bias_row_base, size_t c) {
const __fp16 * p = (const __fp16 *) bias_row_base + c;
return hvx_vec_f16_to_f32(hvx_vmemu(p));
}
static inline HVX_VectorPair hmx_load_bias_f32_64_f32(const void * bias_row_base, size_t c) {
const float * p = (const float *) bias_row_base + c;
return Q6_W_vcombine_VV(hvx_vmemu(p + 32), hvx_vmemu(p));
}
// --- Shared HMX Scale / Norm / GLU / Batched / MMID Helpers ---
static inline void htp_mm_load_scale(
dma_queue * dma_q,
float * vtcm_scale,
dma_addr_t scale_addr,
size_t scale_bytes,
bool splat_scalar) {
dma_queue_push(dma_q, dma_make_data(vtcm_scale, scale_addr), hex_align_up(scale_bytes, 128), 0, scale_bytes, 1);
dma_queue_pop(dma_q);
if (splat_scalar) {
hvx_vmem(vtcm_scale) = hvx_vec_repl4(hvx_vmem(vtcm_scale));
}
}
static inline void htp_mm_load_norm(
dma_queue * dma_q,
float * vtcm_norm,
void * vtcm_tmp,
const struct htp_tensor * norm_w,
uint32_t k_valid,
bool deinterleave_f16) {
if (norm_w->type == HTP_TYPE_F16) {
const size_t nbytes = (size_t) k_valid * sizeof(__fp16);
dma_queue_push(dma_q, dma_make_data(vtcm_tmp, norm_w->data), hex_align_up(nbytes, 128), 0, nbytes, 1);
dma_queue_pop(dma_q);
hvx_copy_f32_f16_aa((uint8_t *) vtcm_norm, (const uint8_t *) vtcm_tmp, k_valid);
} else {
const size_t nbytes = (size_t) k_valid * sizeof(float);
dma_queue_push(dma_q, dma_make_data(vtcm_norm, norm_w->data), hex_align_up(nbytes, 128), 0, nbytes, 1);
dma_queue_pop(dma_q);
}
if (deinterleave_f16) {
const uint32_t k_pad = hex_align_up(k_valid, 64u);
if (k_pad > k_valid) {
memset(vtcm_norm + k_valid, 0, (size_t) (k_pad - k_valid) * sizeof(float));
}
HVX_Vector * vw = (HVX_Vector *) vtcm_norm;
const uint32_t npairs = k_pad >> 6;
for (uint32_t i = 0; i < npairs; ++i) {
HVX_VectorPair wp = Q6_W_vdeal_VVR(vw[2 * i + 1], vw[2 * i], -4);
vw[2 * i] = Q6_V_lo_W(wp);
vw[2 * i + 1] = Q6_V_hi_W(wp);
}
}
}
void hvx_rms_norm_mul_rows_f32(
uint8_t * restrict curr_buf,
size_t row_bytes,
uint32_t valid_rows,
uint32_t k_valid,
const float * restrict vtcm_norm,
float norm_eps);
void hvx_rms_norm_mul_rows_f16(
uint8_t * restrict curr_buf,
size_t row_bytes,
uint32_t valid_rows,
uint32_t k_valid,
const float * restrict vtcm_norm,
float norm_eps);
typedef void (*hmx_glu_store_quad_fn_t)(
void * restrict dst_ptr,
size_t dst_stride,
const HVX_Vector * restrict g_vec,
const HVX_Vector * restrict u_vec,
uint32_t valid_rows);
typedef void (*hmx_glu_store_tail_fn_t)(
void * restrict dst_ptr,
size_t dst_stride,
const HVX_Vector * restrict g_vec,
const HVX_Vector * restrict u_vec,
uint32_t rows_and_bytes);
typedef void (*hmx_glu_store_strip_fn_t)(
void * restrict dst_ptr,
size_t dst_stride,
const __fp16 * restrict u_buf,
size_t u_stride,
size_t n_pairs);
typedef void (*hmx_output_glu_col_chunk_fn_t)(
const void * st_void,
void * restrict dst_ptr,
uint32_t start_row,
uint32_t n_rows,
uint32_t c_first,
uint32_t c_len_and_dst_cols);
typedef struct {
void * dst;
const uint8_t * vtcm_gate;
const uint8_t * vtcm_up;
const float * vtcm_act_scales;
const float * vtcm_wt_scales_gate;
const float * vtcm_wt_scales_up;
uint32_t w_scale_gate_c_mask;
uint32_t w_scale_up_c_mask;
uint32_t n_rows;
uint32_t mc_pad;
uint32_t n_cols;
uint32_t n_groups;
uint32_t dst_stride;
uint32_t dst_cols;
size_t dst_elem_size;
uint32_t n_tasks;
uint32_t n_chunks_per_task;
struct fastdiv_values n_hvx_div;
hmx_output_glu_col_chunk_fn_t col_chunk_fn;
hmx_glu_store_quad_fn_t store_quad_fn;
hmx_glu_store_tail_fn_t store_tail_fn;
hmx_glu_store_strip_fn_t store_strip_fn;
} hmx_output_glu_state_t;
bool resolve_hmx_glu_store_fns(
uint8_t glu_op,
size_t dst_elem_size,
hmx_glu_store_quad_fn_t * store_quad_fn,
hmx_glu_store_tail_fn_t * store_tail_fn,
hmx_glu_store_strip_fn_t * store_strip_fn);
void hmx_transfer_output_glu(
struct htp_ops_context * octx,
hmx_output_glu_state_t * state,
void * dst,
const void * vtcm_gate,
const void * vtcm_up,
const float * vtcm_wt_scales_gate,
const float * vtcm_wt_scales_up,
int n_rows,
int n_cols,
int dst_cols);
typedef struct {
dma_queue * weight_dma;
dma_addr_t dst_dma_addr;
dma_addr_t bias_addr;
size_t bias_bytes;
dma_addr_t scale_addr;
size_t scale_bytes;
bool scale_per_channel;
dma_addr_t act_dma_addr;
dma_addr_t weight;
int m;
int k;
int n;
int act_stride;
uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
int weight_stride;
int weight_type;
int k_valid;
int dst_stride;
uint32_t bias_stride;
int dst_cols;
uint32_t dst_elem_size; // 4=F32 dst, 2=F16 dst
uint32_t bias_elem_size; // 4=F32 bias, 2=F16 bias
} hmx_mm_2d_params_t;
typedef struct {
dma_queue * weight_dma;
const dma_addr_t * dsts;
dma_addr_t activation;
size_t act_elem_size;
size_t dst_elem_size;
const dma_addr_t * weights;
uint32_t n_weights;
int m;
int k;
int n;
int k_valid;
int ne11;
size_t act_nb1;
size_t act_nb2;
size_t dst_nb1;
size_t dst_nb2;
int weight_stride;
int weight_type;
const struct mmid_row_mapping * matrix_rows;
int cur_a;
int mapping_stride;
int m_start;
int m_end;
const dma_addr_t * scale_addrs;
const size_t * scale_bytes_arr;
const uint8_t * scale_per_ch_arr;
} hmx_mm_id_2d_params_t;
typedef struct {
dma_addr_t dst_dma_addr;
dma_addr_t bias_addr;
size_t bias_bytes;
dma_addr_t scale_addr;
size_t scale_bytes;
uint8_t scale_per_channel;
dma_addr_t act_dma_addr;
dma_addr_t weight;
dma_queue * weight_dma;
int m;
int k;
int n;
int act_stride;
uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
uint32_t dst_elem_size; // 4=F32 dst, 2=F16 dst
uint32_t bias_elem_size; // 4=F32 bias, 2=F16 bias
int weight_stride;
int weight_type;
int dst_stride;
int dst_cols;
uint32_t bias_stride;
int ne02;
int ne03;
int ne12;
int ne13;
size_t src0_nb2;
size_t src0_nb3;
size_t act_nb2;
size_t act_nb3;
size_t bias_nb2;
size_t bias_nb3;
size_t dst_nb2;
size_t dst_nb3;
int r2;
int r3;
struct fastdiv_values div_r2;
struct fastdiv_values div_r3;
} hmx_mm_batched_params_t;
static inline dma_addr_t hmx_mm_weight_batch_data(const hmx_mm_batched_params_t * params, int dst_b2, int dst_b3) {
const size_t b2_idx = (params->r2 <= 1) ? (size_t) dst_b2 : (size_t) fastdiv((uint32_t) dst_b2, &params->div_r2);
const size_t b3_idx = (params->r3 <= 1) ? (size_t) dst_b3 : (size_t) fastdiv((uint32_t) dst_b3, &params->div_r3);
return params->weight + b2_idx * params->src0_nb2 + b3_idx * params->src0_nb3;
}
static inline dma_addr_t hmx_mm_act_batch_addr(const hmx_mm_batched_params_t * params, int dst_b2, int dst_b3) {
return params->act_dma_addr + dst_b2 * params->act_nb2 + dst_b3 * params->act_nb3;
}
static inline dma_addr_t hmx_mm_dst_batch_addr(const hmx_mm_batched_params_t * params, int dst_b2, int dst_b3) {
return params->dst_dma_addr + (size_t) dst_b2 * params->dst_nb2 + (size_t) dst_b3 * params->dst_nb3;
}
static inline void push_gathered_act_rows(
dma_queue * dma_q,
uint8_t * slot_buf,
dma_addr_t act_dma_addr,
uint32_t valid_rows,
uint32_t start_row,
uint32_t r,
size_t row_bytes,
size_t valid_bytes,
const struct mmid_row_mapping * matrix_rows,
uint32_t cur_a,
uint32_t mapping_stride,
uint32_t ne11,
const struct fastdiv_values * ne11_div,
size_t nb11,
size_t nb12) {
const size_t base_idx = (size_t) cur_a * mapping_stride + start_row + r;
if (ne11 == 1) {
for (uint32_t s = 0; s < valid_rows; ++s) {
const struct mmid_row_mapping mapping = matrix_rows[base_idx + s];
const dma_addr_t src_row = act_dma_addr + (size_t) mapping.i2 * nb12;
dma_queue_push(dma_q, dma_make_data(slot_buf + (size_t) s * row_bytes, src_row),
valid_bytes, valid_bytes, valid_bytes, 1);
}
} else {
for (uint32_t s = 0; s < valid_rows; ++s) {
const struct mmid_row_mapping mapping = matrix_rows[base_idx + s];
const uint32_t i11 = fastmodulo(mapping.i1, ne11, ne11_div);
const dma_addr_t src_row = act_dma_addr + (size_t) i11 * nb11 + (size_t) mapping.i2 * nb12;
dma_queue_push(dma_q, dma_make_data(slot_buf + (size_t) s * row_bytes, src_row),
valid_bytes, valid_bytes, valid_bytes, 1);
}
}
}
static inline void push_scattered_dst_rows(
dma_queue * dma_q,
dma_addr_t dst_dma_addr,
const uint8_t * vtcm_src,
uint32_t start_row,
uint32_t n_rows,
size_t vtcm_row_bytes,
size_t copy_bytes,
const struct mmid_row_mapping * matrix_rows,
uint32_t cur_a,
uint32_t mapping_stride,
size_t dst_nb1,
size_t dst_nb2) {
const size_t base_idx = (size_t) cur_a * mapping_stride + start_row;
for (uint32_t r = 0; r < n_rows; ++r) {
const struct mmid_row_mapping mapping = matrix_rows[base_idx + r];
const dma_addr_t dst_row = dst_dma_addr + (size_t) mapping.i1 * dst_nb1 + (size_t) mapping.i2 * dst_nb2;
dma_queue_push(dma_q, dma_make_data(dst_row, vtcm_src + (size_t) r * vtcm_row_bytes),
copy_bytes, copy_bytes, copy_bytes, 1);
}
}
static inline void sync_scattered_dst_rows(
dma_queue * dma_q,
dma_addr_t dst_dma_addr,
const uint8_t * vtcm_src,
uint32_t start_row,
uint32_t n_rows,
size_t vtcm_row_bytes,
size_t copy_bytes,
const struct mmid_row_mapping * matrix_rows,
uint32_t cur_a,
uint32_t mapping_stride,
size_t dst_nb1,
size_t dst_nb2) {
for (uint32_t r = 0; r < n_rows; r += 128u) {
const uint32_t batch = hex_smin(n_rows - r, 128u);
push_scattered_dst_rows(dma_q, dst_dma_addr, vtcm_src + (size_t) r * vtcm_row_bytes,
start_row + r, batch, vtcm_row_bytes, copy_bytes,
matrix_rows, cur_a, mapping_stride, dst_nb1, dst_nb2);
for (uint32_t s = 0; s < batch; ++s) {
dma_queue_pop(dma_q);
}
}
}
struct htp_mmid_mapping {
const int32_t * ids_data;
uint32_t * matrix_row_counts;
struct mmid_row_mapping * matrix_rows;
uint32_t mapping_stride;
uint32_t n_skipped;
};
#endif // HTP_MATMUL_INTERNAL_H

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