Commit e0f884d40 for llama.cpp
commit e0f884d4058d7acc117eb768a0a1c5290d0a8b94
Author: Max Krasnyansky <maxk@qti.qualcomm.com>
Date: Wed Nov 25 20:59:59 2026 -0800
ggml-hexagon 2.0 : support for int-hmx, automatic f32 -> f16 lowering, and generic dma pipelines (#32582)
* hexagon : add DMA pipeline, htp_tensor_read, and cache/mdev cleanup
- Add dma-proxy thread/ring for main-thread DMA offload (clamp n_hvx <= hw_nth - 2)
- Add syncht in hmx-queue after HMX VTCM stores
* hexagon : add F16/collapse graph lowering and fusion updates
* hexagon : update host kparams solver for W8A8 HMX, F16, and DMA
* hexagon : add INT-HMX W8A8 matmul, F16 support, and DMA writeback
- Use 64-col dual-acc (weight.b:deep + mxswapacc) across all arches and :cm activation layout
- Pre-issue chunk-0 weight DMA via dma_proxy, balance 4-row quad output threads, and defer output DMA pop
* hexagon : add HMX W8A8 Q8_0 KV flash attention and DMA writeback
hex-fa: cleanup dma_queue usage and mask buffers
hex-fa: fix new op tests and corner cases
hex-fa: cleanup kernel selection and solver
hex-fa: improve decode performance (split-kv)
* hexagon : add F16, DMA, and micro-kernel optimizations for unary/norm ops
* hexagon : add mixed F16/F32 and HVX optimizations for binary ops
* hexagon : add F16, DMA, and state fusion for gated-delta-net
Alsp pipeline GDN HMX/HVX with batched dispatch and spill-free inversion
* hexagon : add F16, token-major fusion, and DMA updates for SSM ops
* hexagon : add F16 and HVX optimizations for rope, softmax, and glu
rope: optimize init and add common fast-path
* hexagon : add F16, DMA, and spill fixes for argsort and top-k
* hexagon : add F16 lowering and optimizations for lightning-indexer and dsv4
* hexagon : add F16 and DMA updates for row and concat ops
* hexagon : convert simple ops to dma-pipeline, F16, and warning/mdev cleanup
* hexagon: add support for fusing MUL_MAT_NX with GLU ops (GEGLU,SWIGLU,...)
- Double-buffer vtcm_up/vtcm_wt_scales_up, add 0-spill direct loop0 FP16 GLU strip kernels, trim sub-ULP FP16 sigmoid terms
- Balance 4-row quad GLU threads, defer output DMA pop, and pre-issue chunk-0 weight DMA via dma_proxy
* tests : add F16/mixed-type and Hexagon op test cases
For now do not include ssm_conv tests that break ggml-metal
* hexagon : update trace and run scripts
* hexagon : update Snapdragon backend README and developer docs
Includes updated tensor tiling description (it is 32x4 now)
--
Co-authored-by: Ehsan Bateni <ebateni@qti.qualcomm.com>
Co-authored-by: Todor Boinovski <todorb@qti.qualcomm.com>
Co-authored-by: Trivikram Reddy <tamarnat@qti.qualcomm.com>
Co-authored-by: Yanzhao Wang <yanzhaow@qti.qualcomm.com>
Assisted-by: Antigravity
diff --git a/docs/backend/snapdragon/README.md b/docs/backend/snapdragon/README.md
index bd9703705..aea52a067 100644
--- a/docs/backend/snapdragon/README.md
+++ b/docs/backend/snapdragon/README.md
@@ -304,6 +304,22 @@ Unlike host-level tensor-splitting, row-splitting is executed entirely inside th
You can also combine row-splitting with layer-splitting across multiple grouped devices (e.g. `--devices 'HTP0[0-1],HTP1[2-3]'`
on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs using virtual sessions 0 and 1).
+## Numerical Precision and End-to-End Accuracy
+
+By default, the Hexagon backend is tuned for higher NPU throughput and lower memory bandwidth while preserving strong
+end-to-end accuracy across typical models. Specifically, batched matrix multiplications default to `W8A8` integer HMX
+(`--hex-mm-select 3`), which dynamically quantizes activations into 8-bit (`uint8` x `int8`) blocks with a 2048-element
+`K`-group scale (using HVX when `M <= 4`),
+and internal `FP32` activation tensors within each HTP subgraph are automatically lowered in-place to `FP16`
+(`--hex-oplower 1`). If a particular model or workload exhibits accuracy degradation (for example due to large activation
+outliers or `FP16` residual overflow), try stepping down to higher-precision configurations in the following order:
+
+1. `--hex-mm-select 4 --hex-oplower 1`: pure `W8A8` INT HMX everywhere + internal `FP16` lowering (maximum prefill speed)
+2. `--hex-mm-select 3 --hex-oplower 1` (default): hybrid `W8A8` INT HMX (FP16 HMX on post-GLU / `GGML_PREC_F32` projections) + internal `FP16` lowering
+3. `--hex-mm-select 3 --hex-oplower 0`: hybrid `W8A8` INT HMX + `FP32` intermediate activations
+4. `--hex-mm-select 2 --hex-oplower 1`: `FP16` HMX everywhere + internal `FP16` lowering
+5. `--hex-mm-select 2 --hex-oplower 0`: `FP16` HMX everywhere + `FP32` intermediate activations
+
## Environment variables
- `GGML_HEXAGON_DEVICES` (default: not set, defaults to HTP0 session)
@@ -398,3 +414,27 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs
# Disable ADD and SUB on Hexagon (fall back to CPU or GPU)
./scripts/snapdragon/run.py --target adb --hex-opfilter "ADD|SUB" -- llama-cli ...
```
+
+- `GGML_HEXAGON_OPLOWER=N`
+ Controls internal FP32-to-FP16 activation tensor lowering inside HTP opbatches (configurable via `--hex-oplower` in `run.py`):
+
+ - `0`: Disabled - keep internal activations in FP32
+ - `1`: Enabled (default) - lower internal `FP32` activation tensors across the opbatch to `FP16` while respecting `GGML_PREC_F32` hints
+
+- `GGML_HEXAGON_MM_SELECT=N`
+ Selects the matrix multiplication engine on HTP (configurable via `--hex-mm-select` in `run.py`):
+
+ - `0`: Disabled (falls back to CPU or GPU)
+ - `1`: HVX vector kernels only
+ - `2`: FP16 HMX matrix engine (`M > 4`) with HVX decode (`M <= 4`)
+ - `3`: Hybrid INT HMX `W8A8` (`uint8` activations x `int8` weights) with FP16 HMX fallback on post-GLU / `GGML_PREC_F32` projections and HVX decode (`M <= 4`) (default; automatically defaults to 2 on multi-session v73 hardware unless overridden)
+ - `4`: Pure INT HMX `W8A8` everywhere (`M > 4`) with HVX decode (`M <= 4`)
+
+- `GGML_HEXAGON_OPPOLL=N`
+ Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`):
+
+ - `0`: Blocking wait (lowest host CPU usage)
+ - `1`: Full polling (keeps the host CPU awake for minimum wakeup latency; best for peak benchmarking and profiling)
+ - `> 1`: Hybrid polling budget in milliseconds - polls for up to `N` ms per opbatch before falling back to a blocking wait (default: `50` when supported by the FastRPC driver, `0` otherwise)
+
+ The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills). For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling.
diff --git a/docs/backend/snapdragon/developer.md b/docs/backend/snapdragon/developer.md
index c220ad08a..9602848c6 100644
--- a/docs/backend/snapdragon/developer.md
+++ b/docs/backend/snapdragon/developer.md
@@ -30,6 +30,10 @@ The Hexagon NPU backend takes advantage of Snapdragon unified memory where all D
The NPU has dedicated tightly-coupled memory called VTCM (Vector Tightly-Coupled Memory). VTCM is used for intermediate data (such as
dynamically quantized activations) and streaming buffers (chunks of weight and activation tensors fetched via DMA).
+Both DDR and VTCM reserve trailing guard space so HVX kernels can issue full-width vector loads (`vmem` / `vmemu`) on tail elements without boundary branches:
+- Shared DDR buffers pad allocations to 4 KB and append a 4 KB guard page.
+- Usable VTCM (`htp_vtcm_usable_size`) reserves `HTP_VTCM_GUARD_SIZE` (128 bytes) at the end of the physical VTCM page.
+
## Large model handling
Hexagon NPU sessions have a 32-bit virtual address space window of around 3.5GB.
@@ -72,34 +76,29 @@ For a weight matrix of logical shape `[ne0, ne1]` (where `ne0 = K`, `ne1 = N`):
### Block-32 Quantized Formats
-Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
+Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`).
+Quants are stored in 4-K-grouped (`vrmpy`) byte order across 128-byte HVX vectors:
+columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns (`j = k % 4`), stored at `4 * row + j` within each vector.
- **Q4_0** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_0`):
- - **Quants** (bytes 0..511, 512 bytes):
+ - **Quants** (bytes 0..511, 512 bytes, 4 HVX vectors `p = 0..3`):
Contains 32 rows x 32 columns of 4-bit quants.
- Divided into 16 column pairs `cp = 0..15` covering columns `2*cp` and `2*cp + 1`.
- For each column pair `cp`, 32 bytes are stored consecutively for rows `row = 0..31`:
- `tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
- Low nibble holds the even column; high nibble holds the odd column.
+ Vector `p` packs column group `2*p` in the low nibble and group `2*p + 1` in the high nibble:
+ `tile[p * 128 + row * 4 + j]` holds `(quant[row][8*p + 4 + j] << 4) | quant[row][8*p + j]` for `row = 0..31`, `j = 0..3`.
- **Scales** (bytes 512..575, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **Q8_0** (1088 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q8_0`):
- - **Quants** (bytes 0..1023, 1024 bytes):
+ - **Quants** (bytes 0..1023, 1024 bytes, 8 HVX vectors `p = 0..7`):
Contains 32 rows x 32 columns of signed 8-bit quants (`int8_t`).
- Divided into 16 column pairs `cp = 0..15` covering columns `col0 = 2*cp` and `col1 = 2*cp + 1`.
- For each column pair `cp`, 64 bytes store interleaved column elements for each row `row = 0..31`:
- `tile[cp * 64 + 2 * row + 0] = quant[row][col0]`
- `tile[cp * 64 + 2 * row + 1] = quant[row][col1]`
+ Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`):
+ `tile[p * 128 + row * 4 + j] = quant[row][4*p + j]` for `row = 0..31`, `j = 0..3`.
- **Scales** (bytes 1024..1087, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **IQ4_NL** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_IQ4_NL`):
- **Quants** (bytes 0..511, 512 bytes):
- Same nibble transposition and storage layout as `Q4_0`.
- Contains 32 rows x 32 columns of non-linear 4-bit indices (values 0..15).
- Divided into 16 column pairs `cp = 0..15`:
- `tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
+ Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit non-linear indices (values 0..15).
- **Scales** (bytes 512..575, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **Dequantization**:
@@ -107,10 +106,7 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
- **MXFP4** (544 bytes per tile, `HTP_TENSOR_TILE_SIZE_MXFP4`):
- **Quants** (bytes 0..511, 512 bytes):
- Same nibble transposition and storage layout as `Q4_0`.
- Contains 32 rows x 32 columns of 4-bit OCP Microscaling FP4 (E2M1) values.
- Divided into 16 column pairs `cp = 0..15`:
- `tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
+ Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit OCP Microscaling FP4 (E2M1) values.
- **Scales** (bytes 512..543, 32 bytes):
32 unsigned 8-bit values (`uint8_t`), storing one 8-bit biased exponent (E8M0, bias 127) scale `e` per row `row = 0..31`.
- **Dequantization**:
@@ -119,26 +115,25 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
- **NVFP4** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_NVFP4`, lossless tiling with same size as `block_nvfp4`):
- A 64-element block spans 2 consecutive k-tiles; k-tile `h` holds sub-blocks `2h` and `2h+1`.
- - **Quants** (bytes 0..511): same nibble transposition as `Q4_0`, holding E2M1 values in element order
- (within a 16-element sub-block, `qs` byte `j` holds elements `j` and `j+8`).
+ - **Quants** (bytes 0..511, 4 HVX vectors): 4-K-grouped nibble layout per 16-element sub-block `u = 0..1` (`tile[(2*u + 0)*128 + row*4 + j]` holds low nibbles of `qs_sub[j]` and `qs_sub[4+j]`; `tile[(2*u + 1)*128 + row*4 + j]` holds high nibbles).
- **Scales** (bytes 512..575): UE4M3 bytes, `tile[512 + 32*u + row]` for sub-block `u = 0..1` of the k-tile.
- The per-tensor F32 scale is not part of the tile.
- **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`):
- **Quants** (bytes 0..511, 512 bytes):
- Same 4-bit nibble transposition and storage layout as `Q4_0`.
+ Same 4-K-grouped nibble layout as `Q4_0`.
- **Scales** (bytes 512..639, 128 bytes):
32 pairs of FP16 values (`ggml_half`): `scale[2 * row + 0] = d` (scale) and `scale[2 * row + 1] = m` (min) for each row `row = 0..31`.
- **Q5_0** (704 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_0`):
- - **Quants** (bytes 0..511): same 4-bit nibble transposition and storage layout as `Q4_0`, holding the low 4 bits.
- - **5th-bit plane** (bytes 512..639): byte `32*c + row` (`c = 0..3`) holds a flag for `k = 2*(4i + c)` at bit `2i` and for `k = 2*(4i + c) + 1` at bit `2i + 1`, for `i = 0..3`. The flag is set when the 5th bit of the quant is clear.
+ - **Quants** (bytes 0..511): same 4-K-grouped nibble layout as `Q4_0`, holding the low 4 bits.
+ - **5th-bit plane** (bytes 512..639, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds a flag at bit `g` (`0..7`) for `k = 4*g + j`. The flag is set when the 5th bit of the quant is clear.
- **Scales** (bytes 640..703, 64 bytes): 32 FP16 values, storing scale `d` for each row `row = 0..31`.
- **Dequantization**: `0xF0` is OR-ed into the nibble where the flag is set, giving the signed value `q - 16` (-16..15), scaled by `d`.
- **Q5_1** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_1`, same layout as the Q5_K tile):
- **Quants** (bytes 0..511) and **scales** (bytes 512..639): same as `Q4_1`, holding the low 4 bits and `(d, m)` pairs.
- - **5th-bit plane** (bytes 640..767): same as `Q5_K`; a bit is set when the 5th bit of the quant is set.
+ - **5th-bit plane** (bytes 640..767, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds bit `g` (`0..7`) for `k = 4*g + j`, set when the 5th bit of the quant is set.
- Uses the `Q5_K` HVX/HMX kernels (Q8_1 activations with block sums).
### Q1_0 Format (1-Bit Quantization)
@@ -209,12 +204,12 @@ Byte ordering: `Q2_K`, `Q3_K`, and `Q6_K` use `vrmpy` byte order within each 128
- `bytes 384..511` (vec 3): FP16 scales `d * (scales[] - 32)`: `fp16[0..31]` for k 0..15, `fp16[32..63]` for k 16..31.
- **Q4_K** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_K`, same layout as Q4_1 tile; each 256-k super-block splits into 8 tiles of 32 k):
- - `bytes 0..511` (vec 0..3): 4-bit quants; byte `32*cp + r` holds `k = 2*cp` (low nibble) and `2*cp + 1` (high nibble).
+ - `bytes 0..511` (vec 0..3): 4-bit quants in 4-K-grouped order; `tile[p * 128 + row * 4 + j]` holds `k = 8*p + j` (low nibble) and `k = 8*p + 4 + j` (high nibble).
- `bytes 512..639` (vec 4): 32x2 FP16 per row: `(d * sc, -dmin * m)`.
- **Q5_K** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_K`):
- `bytes 0..639` (vec 0..4): Q4_K tile (low 4 bits + FP16 scale/min pairs).
- - `bytes 640..767` (vec 5): 5th-bit plane; byte `l` holds the 8 high bits for lane `l` across vec `i = 0..3` (`bit 2i = lo, 2i+1 = hi`).
+ - `bytes 640..767` (vec 5): 5th-bit plane in 4-K-grouped order; `plane[row * 4 + j]` holds bit `g` (`0..7`) for `k = 4*g + j`.
- **Q6_K** (896 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q6_K`):
- `bytes 0..511` (vec 0..3): low 4 bits; vec `i` holds group `2i` (low nibble) and `2i+1` (high nibble).
@@ -227,8 +222,9 @@ Writing high-performance operators for Hexagon requires following specific guide
### DDR -> DMA -> VTCM Execution Pipeline
-- Strongly prefer the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
-- Direct HVX reads/writes from/to DDR are less efficient and should only be used as a fallback.
+- All operators must use the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
+- **No direct reads or writes to `tensor->data`**: Do not dereference `tensor->data` pointers directly (scalar or HVX). All tensor transfers must go through DMA, because bypass DMA writes are not L1D/L2 coherent and tensors may reside in 40-bit extended address space.
+- **Rare exception (small index/position tensors)**: For small metadata tensors that require scalar indexing (such as `ids`, `pos`, or row indices), use [`htp_tensor_read()`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h) to copy into a 128-byte aligned local DDR buffer (`ddr_spad_base` or stack). It handles extended addresses, arbitrary strides, and `dccleaninva` + `syncht` cache maintenance in one place.
- Use `dma_addr_t` only for DMA base and final addresses. Form a final address by adding a 32-bit byte offset to a
`dma_addr_t` tensor base address. This permits a 64-bit mapped base address on newer platforms while retaining 32-bit
relative addressing.
@@ -244,8 +240,12 @@ Writing high-performance operators for Hexagon requires following specific guide
properly. Flushing is only used in rare exceptions where a batch of operations is pushed without individual pops.
- Use the DMA queue interface from [`dma-queue.h`](../../../ggml/src/ggml-hexagon/htp/dma-queue.h)
(`dma_queue_push()`, `dma_queue_pop()`, and `dma_queue_flush()`).
- See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c) and
- [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c) for reference implementations.
+- For new simple ops, prefer the generic double-buffered pipeline drivers in
+ [`dma-pipeline.h`](../../../ggml/src/ggml-hexagon/htp/dma-pipeline.h) (`dma_pipe_io_run`, `dma_pipe_in_run`,
+ `dma_pipe_out_run`), which use dummy pushes, `dma_queue_pop().src`/`.dst` slot recycling, and `dma_queue_flush()`
+ at the end of the op. See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c),
+ [`diag-ops.c`](../../../ggml/src/ggml-hexagon/htp/diag-ops.c), and
+ [`pad-ops.c`](../../../ggml/src/ggml-hexagon/htp/pad-ops.c) for reference implementations.
### Avoid Scalar Reads and Writes to VTCM
@@ -256,22 +256,22 @@ Writing high-performance operators for Hexagon requires following specific guide
- Hexagon cores do not have hardware division instructions.
- For recurring divisions across iterations or threads, use `fastdiv` from
[`hex-fastdiv.h`](../../../ggml/src/ggml-hexagon/htp/hex-fastdiv.h) with precomputed divisors (such as
- `octx->ctx->mdev.count_div` or `octx->n_threads_div`).
+ `octx->ctx->mdev.count_div` or `octx->n_hvx_div`).
- Do not call `init_fastdiv_values()` for single-use divisions; use standard compiler division (`/`) instead.
### Host-Side Precomputation via `kernel_params`
- Precompute tensor shapes, strides, scale conversions, tiling layouts, and validation checks on the host CPU during graph
- preparation in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp).
+ preparation in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp).
- Pack precomputed parameters into the operator's fixed `kernel_params` structure in `htp_op_node` (such as
`htp_mm_kernel_params`, `htp_unary_kernel_params`, `htp_fa_kernel_params`, `htp_get_rows_kernel_params`).
- The NPU executes directly using `octx->kernel_params` without redundant runtime metadata extraction or validation.
- **Strict Host-Kernel Alignment**:
- Verify that parameters calculated by the host CPU are strictly honored by the NPU kernel.
- - Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_threads` instead of
- using `kparams->n_threads`, or ignoring precomputed `tasks_per_thread` and chunk counts).
+ - Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_hvx` instead of
+ using `kparams->n_hvx`, or ignoring precomputed `tasks_per_hvx` and chunk counts).
- Both human developers and coding agents must audit both sides of the interface: ensure fields populated in `kernel_params`
- in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp) are actively and consistently utilized by the
+ in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp) are actively and consistently utilized by the
corresponding operator entry point and worker threads in `htp/*-ops.c`.
### Tracing Instrumentation
@@ -292,7 +292,7 @@ Writing high-performance operators for Hexagon requires following specific guide
- Distribute parallel work across NPU worker threads using the thread pool work queue:
```c
- work_queue_run(ctx->work_queue, worker_func, &op_ctx, n_threads);
+ work_queue_run(ctx->hvx_queue, worker_func, &op_ctx, n_hvx);
```
- Keep worker functions independent and re-entrant. Worker threads should only operate on their designated chunk of rows or elements.
@@ -307,6 +307,12 @@ Writing high-performance operators for Hexagon requires following specific guide
- **Distinction**: `octx->src[N]` pointers *can* be NULL by design and must be checked when optional.
Examples include attention masks, optional bias or weights in fused kernels, and frequency factors.
+### Prefer Early Dispatch and Specialized Micro-Kernels
+
+- Avoid peppering micro-kernels, row or tile compute loops, or DMA worker loops with runtime checks for operand types, optional inputs, broadcast modes, or layout variants.
+- Resolve execution variants early during operator setup (`op_*` / `execute_op_*`) via function pointers or dispatch tables so each micro-kernel and inner loop handles a single clean path that the compiler can unroll and software-pipeline without extra branch or register pressure.
+- Prefer clean standalone specialized functions; use macros only to avoid genuine code duplication across type or mode instantiations.
+
### `supports_op` Independence from Buffer and Repack State
- `supports_op` (and op-specific checkers such as `supported_mul_mat()`, `supported_get_rows()`) runs during GGML graph scheduling **before** buffers are allocated and before tensor data is populated.
@@ -319,6 +325,10 @@ Writing high-performance operators for Hexagon requires following specific guide
- Repacking (converting weights to tiled layout) is an internal optimization applied during `set_tensor()` or rt-repack. Non-weight tensors or test harness tensors with the same type remain in flat layout.
- Therefore, any supported type (such as BF16, F16, quantized types) must be supported both when repacked into tiles and when stored flat in memory.
+### FP16 and Mixed-Precision Operator Support
+
+- New and updated Hexagon compute operators must support `F16` (and mixed `F16`/`F32` where applicable for graph lowering) across activation inputs and outputs, even when `ggml-cpu` only implements `F32`.
+
### Multiline Macro Formatting
- Keep trailing backslashes in multiline `#define` macros cleanly aligned to a consistent column.
@@ -361,56 +371,37 @@ python3 scripts/snapdragon/ggml-hexagon-inspect.py --addr2line 0x51a30 0x5ba54
Multi-device (mdev) mode enables row-level tensor parallel execution across multiple physical NPU cores or virtual NPU
sessions.
-### 128-Byte Cache Line Alignment
-
-- Shared tensor buffers reside in DDR (RPCMEM) with a 128-byte cache line granularity
- (`HEX_L2_LINE_SIZE` = 128 bytes, `HTP_TENSOR_MDEV_LINE_SIZE`).
-- **Rule**: Multi-device work partitions that write directly to DDR through HVX/L2 must align destination write regions to
- 128-byte cache line boundaries so distinct devices never share or overwrite the same cache line.
-- DMA writes to DDR are not subject to this cache-line ownership rule. They may use smaller non-overlapping destination
- ranges when the operator only writes through DMA.
-
-### Partitioning Helpers in `htp-tensor.h`
+### Non-Overlapping Output Ranges
-Common partitioning logic is factored into reusable inline helpers in
-[`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
+- Because all DDR writes go through bypass DMA, multi-device partitions are **not** subject to 128-byte cache-line
+ alignment rules.
+- Devices only need non-overlapping destination output ranges and any kernel-specific tile or vector granularity
+ (for example, 32 rows for tiled matmul or 128-byte vector chunks for flat 1D element-wise ops).
-1. [`htp_tensor_mdev_rows_per_chunk`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L104):
- Determines the minimum number of rows per chunk so that the chunk byte size is a multiple of 128 bytes:
+### Partitioning Helper in `htp-tensor.h`
- ```
- rows_per_chunk = 128 / hex_gcd_u32(row_size, 128)
- ```
+Common partitioning logic is factored into [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h)
+in [`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
- If the active row and outer strides are already multiples of 128 bytes, `rows_per_chunk = 1`.
- Returns `false` if the tensor cannot be safely row-partitioned (such as unaligned base pointer, permuted layout,
- or non-128-byte aligned outer strides).
-
-2. [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131):
- Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
- `total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
- Handles chunk distribution across devices, assigns remainder units to the last device, and automatically triggers
- single-device fallback when partitioning is unsafe.
+- Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
+ `total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
+- Handles chunk distribution across devices, assigns remainder units to the last device, and automatically falls back
+ to Device 0 when `units_per_chunk == 0` or `total_units / units_per_chunk < mdev_count`.
### Row-Partitioned Operators
-For row-wise operators that write directly to DDR
-(such as activations in [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c),
-binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c),
+For row-wise operators (such as binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c)
and unary ops in [`unary-ops.c`](../../../ggml/src/ggml-hexagon/htp/unary-ops.c)):
```c
-const uint32_t total_rows = ne01 * ne02 * ne03;
-const size_t dst_row_size = dst->ne[0] * elem_size;
+const uint32_t total_rows = ne01 * ne02 * ne03;
uint32_t row_start = 0;
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, elem_size, (uint32_t) dst_row_size, &rows_per_chunk);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -422,24 +413,16 @@ if (nrows == 0) {
### Element-Partitioned Operators
-For flat element-wise operations that write directly to DDR:
-- Partition total linear elements N = ne0 * ne1 * ne2 * ne3 in 128-byte cache line chunks (`elems_per_line = (elem_size == 4) ? 32 : 64`).
-- Requires strict 1D contiguity:
- [`htp_tensor_is_contiguous(dst, elem_size)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L65)
- and 128-byte aligned destination pointer
- [`htp_tensor_mdev_data_aligned(dst)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L84).
-- If contiguous and aligned, pass `elems_per_line` to
- [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131);
- otherwise pass 0 to trigger Device 0 fallback.
+For flat 1D element-wise operations:
+- Partition total linear elements `N = ne0 * ne1 * ne2 * ne3` in HVX vector-sized chunks (`elems_per_line = 128 / elem_size`).
+- Requires 1D contiguity via [`htp_tensor_is_contiguous`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h); otherwise pass
+ `0` to trigger Device 0 fallback.
### Single-Device Fallback (Device 0)
-- Fallback to Device 0 (`mdev.idx == 0`) when partitioning would cause cache line tearing or there are too few aligned chunks.
-- Triggers:
- 1. Destination tensor cannot be safely partitioned (`rows_per_chunk == 0` or non-contiguous/unaligned buffer).
- 2. Total aligned chunks < `mdev_count`.
+- Fallback to Device 0 (`mdev.idx == 0`) happens when `units_per_chunk == 0` or `total_chunks < mdev_count`.
- Device 0 processes the entire tensor `[0, total_units)`.
-- Devices 1 ... N-1 receive `count = 0` and return `HTP_STATUS_OK` immediately.
+- Devices `1 ... N-1` receive `count = 0` and return `HTP_STATUS_OK` immediately.
### Flatten Outer Dimensions Globally
@@ -494,10 +477,7 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
| |
Kernel Execution Kernel Execution
- (Output Slice 0) (Output Slice 1)
- | |
- Tensor Cache Flush Tensor Cache Flush
- (htp_dcache_flush_dirty_tensors) (htp_dcache_flush_dirty_tensors)
+ (Output Slice 0, via bypass DMA) (Output Slice 1, via bypass DMA)
| |
Post-Op/Batch Barrier ---------------------- Post-Op/Batch Barrier
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
@@ -532,11 +512,8 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
misaligned barrier arrivals across iterations.
- If any peer reports an error status (`peer_status > HTP_STATUS_OK`), the barrier propagates the error and unblocks immediately.
-### Tensor Cache Flush and Pipeline Completion
+### Pipeline Completion
-- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order to drain the queue.
-- Use [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) to flush specific dirty tensors back to DDR:
- - [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) flushes modified tensor address ranges, or the
- full D-cache when their total size exceeds the flush threshold, ensuring peer devices and the host CPU observe consistent
- data in DDR.
-- Never signal completion before all DMA transfers are drained and dirty tensor flushes have completed.
+- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order (or flushed via `dma_queue_flush()`) to drain the queue.
+- Because all DDR writes use bypass DMA, no per-tensor output cache flush is needed.
+- Never signal completion before all DMA transfers are drained.
diff --git a/ggml/src/ggml-hexagon/CMakeLists.txt b/ggml/src/ggml-hexagon/CMakeLists.txt
index fea5770c1..f388e3335 100644
--- a/ggml/src/ggml-hexagon/CMakeLists.txt
+++ b/ggml/src/ggml-hexagon/CMakeLists.txt
@@ -59,6 +59,8 @@ ggml_add_backend_library(${TARGET_NAME}
htp-opnode.h
htp-fusion.cpp
htp-fusion.h
+ htp-lower.cpp
+ htp-lower.h
htp-repack.cpp
htp-repack.h
htp-drv.cpp
diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp
index aa6e6d9a0..966219e52 100644
--- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp
+++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp
@@ -56,12 +56,14 @@
#include "ggml-quants.h"
#include "htp-opnode.h"
#include "htp/htp-ops.h"
+#include "htp/htp-vtcm.h"
#include "htp_iface.h"
#include "htp-drv.h"
#include "htp-repack.h"
#include "htp-common.h"
#include "htp-kparams.h"
#include "htp-fusion.h"
+#include "htp-lower.h"
using intvec = std::vector<int>;
using uintvec = std::vector<unsigned int>;
@@ -132,8 +134,8 @@ size_t opt_mbuf_dyn = 512ul * 1024 * 1024; // max dynamic (compute) buff
size_t opt_mbuf_static = 1ul * 1024 * 1024 * 1024; // max static (weight/KV) buffer size
size_t opt_mbuf_total = 0; // total buffer space limit (0 = unconstrained)
-int opt_mm_select = 2; // 2 = HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU (unsupported)
-int opt_fa_select = 2; // 2 = HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU (unsupported)
+int opt_mm_select = 3; // 4 = pure W8A8, 3 = hybrid W8A8 + FP16 post-GLU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
+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)
int opt_gdn_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported)
@@ -151,6 +153,7 @@ int opt_opqueue = 8; // max number of pending batches
int opt_optrace = 0; // trace buffer size per thread (0 means default)
int opt_oppoll = 0; // polling for batch completions
int opt_opfusion = 1; // enable/disable op fusion
+int opt_oplower = 1; // lower internal F32 ops to F16 (0: off, 1: on)
int opt_rt_repack = 1; // runtime repacking: 0 = disabled, 1 = all tileable weights (default)
static std::regex* opt_opfilter = NULL; // regex of ops to not claim
@@ -362,7 +365,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);
+ void enqueue_op(const htp_opnode & node, bool allow_fuse = true);
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,
@@ -391,7 +394,7 @@ struct ggml_hexagon_session {
};
const char * htp_session_name(const struct ggml_hexagon_session * sess) { return sess->c_name(); }
-size_t htp_session_vtcm_size(const struct ggml_hexagon_session * sess) { return sess->vtcm_size; }
+size_t htp_session_vtcm_size(const struct ggml_hexagon_session * sess) { return htp_vtcm_usable_size(sess->vtcm_size); }
uint32_t htp_session_n_hvx(const struct ggml_hexagon_session * sess) { return sess->n_hvx; }
uint32_t htp_session_n_hmx(const struct ggml_hexagon_session * sess) { return sess->n_hmx; }
uint32_t htp_session_mdev_count(const struct ggml_hexagon_session * sess) { return sess->mdev.count; }
@@ -697,6 +700,11 @@ static void ggml_backend_hexagon_buffer_set_tensor(ggml_backend_buffer_t buffer,
HEX_VERBOSE("ggml-hex: %s set-tensor %s : data %p offset %zu size %zu usage %d flags 0x%x\n",
sess->c_name(), tensor->name, data, offset, size, (int) buffer->usage, ggml_hexagon_tensor_get_flags(tensor));
+ if (htp_tensor_is_stored_f16(tensor)) {
+ htp_pack_tensor_lowered_f16(tensor, data, offset, size);
+ return;
+ }
+
memcpy((char *) tensor->data + offset, data, size);
}
@@ -712,12 +720,16 @@ static void ggml_backend_hexagon_buffer_get_tensor(ggml_backend_buffer_t buffer,
HEX_VERBOSE("ggml-hex: %s get-tensor %s : data %p offset %zu size %zu usage %d flags 0x%x\n",
sess->c_name(), tensor->name, data, offset, size, (int) buffer->usage, flags);
- if ((flags & HTP_TENSOR_TILED) == 0) {
- memcpy(data, (const char *) tensor->data + offset, size);
+ if (flags & HTP_TENSOR_TILED) {
+ htp_unpack_tensor_tiled(data, tensor, offset, size);
+ return;
+ }
+ if (htp_tensor_is_stored_f16(tensor)) {
+ htp_unpack_tensor_lowered_f16(data, tensor, offset, size);
return;
}
- htp_unpack_tensor_tiled(data, tensor, offset, size);
+ memcpy(data, (const char *) tensor->data + offset, size);
}
static bool ggml_backend_hexagon_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
@@ -751,6 +763,13 @@ static void ggml_backend_hexagon_buffer_set_tensor_2d(ggml_backend_buffer_t buff
HEX_VERBOSE("ggml-hex: %s set-tensor-2d %s : data %p offset %zu size %zu n_copies %zu stride_tensor %zu stride_data %zu usage %d flags 0x%x\n",
sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, (int) buffer->usage, ggml_hexagon_tensor_get_flags(tensor));
+ if (htp_tensor_is_stored_f16(tensor)) {
+ for (size_t i = 0; i < n_copies; i++) {
+ htp_pack_tensor_lowered_f16(tensor, (const uint8_t *) data + i * stride_data, offset + i * stride_tensor, size);
+ }
+ return;
+ }
+
for (size_t i = 0; i < n_copies; i++) {
memcpy((uint8_t *) tensor->data + offset + i * stride_tensor, (const uint8_t *) data + i * stride_data, size);
}
@@ -772,6 +791,12 @@ static void ggml_backend_hexagon_buffer_get_tensor_2d(ggml_backend_buffer_t buff
sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, (int) buffer->usage);
if ((flags & HTP_TENSOR_TILED) == 0) {
+ if (htp_tensor_is_stored_f16(tensor)) {
+ for (size_t i = 0; i < n_copies; i++) {
+ htp_unpack_tensor_lowered_f16((uint8_t *) data + i * stride_data, tensor, offset + i * stride_tensor, size);
+ }
+ return;
+ }
for (size_t i = 0; i < n_copies; i++) {
memcpy((uint8_t *)data + i * stride_data, (const uint8_t *)tensor->data + offset + i * stride_tensor, size);
}
@@ -814,6 +839,10 @@ static void ggml_backend_hexagon_buffer_set_tensor_n(ggml_backend_buffer_t buffe
if (is_weights) {
ggml_hexagon_tensor_set_flags(tensors[i], HTP_TENSOR_WEIGHT);
}
+ if (htp_tensor_is_stored_f16(tensors[i])) {
+ htp_pack_tensor_lowered_f16(tensors[i], data[i], offsets[i], sizes[i]);
+ continue;
+ }
memcpy((char *) tensors[i]->data + offsets[i], data[i], sizes[i]);
}
}
@@ -854,6 +883,11 @@ static void ggml_backend_hexagon_host_buffer_set_tensor(ggml_backend_buffer_t bu
sess->flush_sync();
+ if (htp_tensor_is_stored_f16(tensor)) {
+ htp_pack_tensor_lowered_f16(tensor, data, offset, size);
+ return;
+ }
+
memcpy((char *) tensor->data + offset, data, size);
}
@@ -862,6 +896,10 @@ static void ggml_backend_hexagon_host_buffer_get_tensor(ggml_backend_buffer_t bu
void * data,
size_t offset,
size_t size) {
+ if (htp_tensor_is_stored_f16(tensor)) {
+ htp_unpack_tensor_lowered_f16(data, tensor, offset, size);
+ return;
+ }
memcpy(data, (const char *) tensor->data + offset, size);
GGML_UNUSED(buffer);
}
@@ -881,6 +919,10 @@ static void ggml_backend_hexagon_host_buffer_set_tensor_n(ggml_backend_buffer_t
if (sizes[i] == 0) {
continue;
}
+ if (htp_tensor_is_stored_f16(tensors[i])) {
+ htp_pack_tensor_lowered_f16(tensors[i], data[i], offsets[i], sizes[i]);
+ continue;
+ }
memcpy((char *) tensors[i]->data + offsets[i], data[i], sizes[i]);
}
}
@@ -1247,6 +1289,58 @@ static bool ggml_backend_buffer_is_hexagon(const struct ggml_backend_buffer * b)
return b->buft->iface.get_alignment == ggml_backend_hexagon_buffer_type_get_alignment;
}
+struct ggml_hexagon_tensor_map {
+ struct slot {
+ uint64_t key;
+ uint32_t gen;
+ int32_t val;
+ };
+
+ std::vector<slot> slots;
+ uint32_t mask = 0;
+ uint32_t gen = 1;
+
+ void init(size_t max_entries) {
+ size_t cap = 64;
+ while (cap < max_entries * 2) {
+ cap <<= 1;
+ }
+ slots.assign(cap, { 0, 0, 0 });
+ mask = (uint32_t) (cap - 1);
+ gen = 1;
+ }
+
+ void clear() {
+ if (++gen == 0) {
+ for (auto & s : slots) { s.gen = 0; }
+ gen = 1;
+ }
+ }
+
+ bool contains(uint64_t key) const {
+ uint32_t i = (uint32_t) key & mask;
+ while (slots[i].gen == gen) {
+ if (slots[i].key == key) { return true; }
+ i = (i + 1) & mask;
+ }
+ return false;
+ }
+
+ int find_or_insert(uint64_t key, int new_val, bool & inserted) {
+ uint32_t i = (uint32_t) key & mask;
+ while (slots[i].gen == gen) {
+ if (slots[i].key == key) {
+ inserted = false;
+ return slots[i].val;
+ }
+ i = (i + 1) & mask;
+ }
+ slots[i] = { key, gen, new_val };
+ inserted = true;
+ return new_val;
+ }
+};
+
struct ggml_hexagon_opbatch {
ggml_hexagon_session* sess;
@@ -1255,12 +1349,13 @@ struct ggml_hexagon_opbatch {
std::vector<htp_tensor> h_tens; // htp tensor descriptors
std::vector<htp_op_desc> h_ops; // htp op descriptors
- std::unordered_map<uint64_t, int> 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_max;
unsigned int n_tens_max;
@@ -1272,9 +1367,9 @@ struct ggml_hexagon_opbatch {
n_tens = 0;
n_ops = 0;
b_vmem = 0;
+ last_op_fusable = false;
t_map.clear();
- ops.resize(n_ops_max);
}
ggml_hexagon_opbatch(ggml_hexagon_session *sess, size_t batch_size, size_t max_vmem) {
@@ -1292,7 +1387,7 @@ struct ggml_hexagon_opbatch {
h_tens.resize(n_tens_max);
h_ops.resize(n_ops_max);
- t_map.reserve(n_tens_max);
+ t_map.init(n_tens_max);
GGML_LOG_INFO("ggml-hex: %s op batching: n-bufs %u n-tensors %u n-ops %u vmem %zu\n",
sess->c_name(), n_bufs_max, n_tens_max, n_ops_max, b_vmem_max);
@@ -1371,20 +1466,16 @@ struct ggml_hexagon_opbatch {
}
static uint64_t hash_tensor(const ggml_tensor * t, const htp_tensor & shape) {
- uint64_t hash = 1469598103934665603ull;
- auto hash_value = [&hash](uint64_t value) {
- hash ^= value;
- hash *= 1099511628211ull;
- };
-
- hash_value((uintptr_t) t->data);
- hash_value(shape.type);
- hash_value(shape.size);
- hash_value(shape.flags);
- for (int i = 0; i < GGML_MAX_DIMS; ++i) {
- hash_value(shape.ne[i]);
- hash_value(shape.nb[i]);
- }
+ uint64_t h1 = (uintptr_t) t->data ^ ((uint64_t) shape.type << 48) ^ ((uint64_t) shape.flags << 32) ^ shape.size;
+ uint64_t h2 = (uint64_t) shape.ne[0]
+ ^ ((uint64_t) shape.ne[1] * 0x9e3779b97f4a7c15ull)
+ ^ ((uint64_t) shape.ne[2] * 0xbf58476d1ce4e5b9ull)
+ ^ ((uint64_t) shape.ne[3] * 0x94d049bb133111ebull);
+ uint64_t h3 = (uint64_t) shape.nb[0]
+ ^ ((uint64_t) shape.nb[1] * 0x9e3779b97f4a7c15ull)
+ ^ ((uint64_t) shape.nb[2] * 0xbf58476d1ce4e5b9ull)
+ ^ ((uint64_t) shape.nb[3] * 0x94d049bb133111ebull);
+ uint64_t hash = (h1 * 0xff51afd7ed558ccdull) ^ (h2 * 0xc4ceb9fe1a85ec53ull) ^ h3;
// avalanche high bits down to low bits for power-of-two table indexing
hash ^= hash >> 33;
@@ -1400,19 +1491,16 @@ struct ggml_hexagon_opbatch {
init_tensor_shape(shape, t);
const uint64_t hash = hash_tensor(t, shape);
- auto it = t_map.find(hash);
- if (it != t_map.end()) {
- return it->second;
+ bool inserted = false;
+ int ti = t_map.find_or_insert(hash, (int) n_tens, inserted);
+ if (!inserted) {
+ return ti;
}
- auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
-
- // Add new tensor to the batch
- int ti = n_tens++;
+ n_tens++;
GGML_ASSERT(n_tens <= n_tens_max);
- t_map[hash] = ti;
-
+ auto sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
uint64_t t_offset = (uint8_t *) t->data - sbuf->base();
htp_tensor & h = h_tens[ti];
@@ -1445,7 +1533,7 @@ struct ggml_hexagon_opbatch {
if (check_tens) {
htp_tensor shape {};
init_tensor_shape(shape, t);
- if (t_map.count(hash_tensor(t, shape))) return;
+ if (t_map.contains(hash_tensor(t, shape))) return;
extra_tens++;
}
@@ -1479,8 +1567,7 @@ struct ggml_hexagon_opbatch {
return true;
}
- void sync_op_desc(unsigned int n) {
- const htp_opnode & node = ops[n];
+ void sync_op_desc(unsigned int n, const htp_opnode & node) {
htp_op_desc & o = h_ops[n];
memcpy(o.params, node.params, sizeof(o.params));
@@ -1499,24 +1586,29 @@ struct ggml_hexagon_opbatch {
}
// caller must ensure the op fits
- void add_op(const htp_opnode & node) {
+ void add_op(const htp_opnode & node, bool save_op = true) {
unsigned int n = n_ops++;
GGML_ASSERT(n_ops <= n_ops_max);
- ops[n] = node;
+ if (save_op) {
+ ops[n] = node;
+ }
+ last_op_fusable = save_op;
h_ops[n].flags = 0;
- ggml_hexagon_dump_op_exec(sess->c_name(), ops[n], h_ops[n].flags);
- sync_op_desc(n);
+ if (opt_verbose) {
+ ggml_hexagon_dump_op_exec(sess->c_name(), node, h_ops[n].flags);
+ }
+ sync_op_desc(n, node);
}
void sort_buffers() {
if (n_bufs <= 1) return;
- std::vector<int> order(n_bufs);
+ int order[HTP_OP_MAX_BUFS];
for (unsigned int i = 0; i < n_bufs; i++) { order[i] = (int) i; }
- std::stable_sort(order.begin(), order.end(), [&](int a, int b) {
+ std::stable_sort(order, order + n_bufs, [&](int a, int b) {
return h_bufs[a].size > h_bufs[b].size;
});
@@ -1529,8 +1621,8 @@ struct ggml_hexagon_opbatch {
}
if (already_sorted) return;
- std::vector<uint16_t> remap(n_bufs);
- std::vector<htp_buf_desc> sorted_bufs(n_bufs);
+ uint16_t remap[HTP_OP_MAX_BUFS];
+ htp_buf_desc sorted_bufs[HTP_OP_MAX_BUFS];
for (unsigned int new_bi = 0; new_bi < n_bufs; new_bi++) {
int old_bi = order[new_bi];
remap[old_bi] = (uint16_t) new_bi;
@@ -1553,7 +1645,7 @@ struct ggml_hexagon_opbatch {
}
bool try_fuse(const htp_opnode & node) {
- if (n_ops == 0) {
+ if (n_ops == 0 || !last_op_fusable) {
return false;
}
@@ -1562,7 +1654,8 @@ struct ggml_hexagon_opbatch {
return false;
}
- sync_op_desc(n_ops - 1);
+ htp_lower_opnode(sess, last_node);
+ sync_op_desc(n_ops - 1, last_node);
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;
@@ -1776,12 +1869,20 @@ void ggml_hexagon_session::flush_pending(bool all) {
struct dspqueue_buffer dbuf;
uint32_t n_dbufs;
- // Read response packet from queue
- const uint32_t timeo = opt_oppoll ? 0 : DSPQUEUE_TIMEOUT;
+ // opt_oppoll: 0 = block, 1 = poll, >1 = hybrid poll budget in ms
+ const auto poll_deadline = opt_oppoll > 1
+ ? std::chrono::steady_clock::now() + std::chrono::milliseconds(opt_oppoll)
+ : std::chrono::steady_clock::time_point::max();
- int err = dspqueue_read(this->queue, &flags, 1, &n_dbufs, &dbuf, sizeof(rsp), &rsp_size, (uint8_t *) &rsp, timeo);
- if (err == AEE_EEXPIRED || err == AEE_EWOULDBLOCK) {
- continue;
+ int err = 0;
+ for (;;) {
+ const uint32_t timeo = (opt_oppoll == 1 || (opt_oppoll > 1 && std::chrono::steady_clock::now() < poll_deadline))
+ ? 0 : DSPQUEUE_TIMEOUT;
+
+ err = dspqueue_read(this->queue, &flags, 1, &n_dbufs, &dbuf, sizeof(rsp), &rsp_size, (uint8_t *) &rsp, timeo);
+ if (err != AEE_EEXPIRED && err != AEE_EWOULDBLOCK) {
+ break;
+ }
}
if (err != 0) {
@@ -1869,10 +1970,13 @@ void ggml_hexagon_session::flush_batch(size_t min_ops) {
op_batch->reset();
}
-void ggml_hexagon_session::enqueue_op(const htp_opnode & node) {
+void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse) {
auto register_tensor = [&](const ggml_tensor * t) {
if (!t) return;
auto * sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
+ if (sbuf->sess == this && sbuf->mapped && this->mdev.sessions.empty()) {
+ return;
+ }
if (ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
sbuf->extended = opt_dma64;
}
@@ -1896,7 +2000,7 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node) {
}
const bool fits_tensors = op_batch->fit_tensors(node);
- if (opt_opfusion && fits_tensors && op_batch->try_fuse(node)) {
+ if (opt_opfusion && allow_fuse && fits_tensors && op_batch->try_fuse(node)) {
return;
}
@@ -1911,7 +2015,7 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node) {
}
}
- op_batch->add_op(node);
+ op_batch->add_op(node, opt_profile || (opt_opfusion && allow_fuse));
}
void ggml_hexagon_session::enqueue_mdev_group() {
@@ -2299,6 +2403,7 @@ void ggml_hexagon_session::allocate(const ggml_hexagon_device_config & config) n
this->n_hmx = (opt_nhmx != 0) ? 1 : 0;
this->vtcm_size = opt_vtcm_size > 0 ? opt_vtcm_size : 8 * 1024 * 1024;
}
+ GGML_ASSERT(this->n_hvx > 0 && this->vtcm_size >= 2 * HTP_VTCM_GUARD_SIZE);
}
// Enable FastRPC QoS mode
@@ -2533,18 +2638,16 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg
HEX_VERBOSE("ggml-hex: %s graph-compute n_nodes %d\n", sess->c_name(), graph->n_nodes);
- const std::vector<htp_opnode> * nodes_ptr = nullptr;
- std::vector<htp_opnode> computed_nodes;
-
- bool cache_hit = (graph->uid != 0 && sess->cached_uid == graph->uid);
- if (cache_hit) {
- nodes_ptr = &sess->cached_nodes;
- } else {
+ const bool cache_hit = graph->uid != 0 && sess->cached_uid == graph->uid;
+ if (!cache_hit) {
ggml_hexagon_graph_repack(graph, sess);
+ htp_lower_reset_graph(graph);
htp_fusion_tag_graph(graph);
- computed_nodes.reserve(graph->n_nodes);
+ auto & nodes = sess->cached_nodes;
+ nodes.clear();
+ nodes.reserve(graph->n_nodes);
for (int i = 0; i < graph->n_nodes; ++i) {
ggml_tensor * n = graph->nodes[i];
@@ -2559,21 +2662,22 @@ 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));
-
- computed_nodes.push_back(std::move(node));
+ if (nodes.empty() || !opt_opfusion || !htp_fusion_try_fuse(sess, nodes.back(), node)) {
+ nodes.push_back(std::move(node));
+ }
}
- if (graph->uid != 0) {
- sess->cached_uid = graph->uid;
- sess->cached_nodes = std::move(computed_nodes);
- nodes_ptr = &sess->cached_nodes;
- } else {
- nodes_ptr = &computed_nodes;
+ if (opt_opfusion) {
+ htp_fusion_optimize_nodes(sess, graph, nodes);
}
+
+ htp_lower_graph(sess, graph, nodes);
+
+ sess->cached_uid = graph->uid;
}
- for (const auto & node : *nodes_ptr) {
- sess->enqueue_op(node);
+ for (const auto & node : sess->cached_nodes) {
+ sess->enqueue_op(node, false);
}
if (sess->last_error > HTP_STATUS_OK) {
@@ -2737,7 +2841,7 @@ static std::vector<int> ggml_hexagon_graph_optimize_reorder(const std::vector<no
}
// that many nodes forward to search for stackable nodes that can reuse VTCM
- constexpr int N_FORWARD = 64;
+ constexpr int N_FORWARD = 128;
htp_opvec<int, N_FORWARD> stack;
stack.push_back(i0);
@@ -3536,6 +3640,7 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
const char * str_opqueue = getenv("GGML_HEXAGON_OPQUEUE");
const char * str_oppoll = getenv("GGML_HEXAGON_OPPOLL");
const char * str_opfusion = getenv("GGML_HEXAGON_OPFUSION");
+ const char * str_oplower = getenv("GGML_HEXAGON_OPLOWER");
const char * str_rt_repack = getenv("GGML_HEXAGON_RT_REPACK");
const char * str_opfilter = getenv("GGML_HEXAGON_OPFILTER");
const char * str_profile = getenv("GGML_HEXAGON_PROFILE");
@@ -3561,12 +3666,14 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
const char * str_power_mode = getenv("GGML_HEXAGON_POWER_MODE");
// Init Arch first since it affects other defaults
+ int hw_arch = 0;
+ int arch_err = htpdrv_get_arch(CDSP_DOMAIN_ID, &hw_arch);
if (!str_arch) {
- int err = htpdrv_get_arch(CDSP_DOMAIN_ID, &opt_arch);
- if (err != 0) {
- GGML_LOG_ERROR("ggml-hex: failed to query HTP version (err %d) defaulting to v73\n", err);
+ if (arch_err != 0) {
+ GGML_LOG_ERROR("ggml-hex: failed to query HTP version (err %d) defaulting to v73\n", arch_err);
opt_arch = 73;
} else {
+ opt_arch = hw_arch;
if (opt_arch < 73) {
GGML_LOG_WARN("ggml-hex: Hexagon arch v%d is under supported range, capping at v73\n", opt_arch);
opt_arch = 73;
@@ -3581,6 +3688,9 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
}
opt_arch = strtoul(str_arch, NULL, 0);
}
+ if (arch_err != 0) {
+ hw_arch = opt_arch;
+ }
size_t MiB = 1024 * 1024;
@@ -3595,8 +3705,9 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
opt_opbatch = str_opbatch ? strtoul(str_opbatch, NULL, 0) : opt_opbatch;
opt_opqueue = str_opqueue ? strtoul(str_opqueue, NULL, 0) : opt_opqueue;
opt_optrace = str_optrace ? strtoul(str_optrace, NULL, 0) : (opt_opbatch * HTP_TRACE_MAX_EVENTS + 131072);
- opt_oppoll = str_oppoll ? strtoul(str_oppoll, NULL, 0) : opt_oppoll;
+ opt_oppoll = str_oppoll ? strtoul(str_oppoll, NULL, 0) : (htpdrv_has_read_noblock() ? 50 : 0);
opt_opfusion = str_opfusion ? atoi(str_opfusion) : opt_opfusion;
+ opt_oplower = str_oplower ? (atoi(str_oplower) != 0 ? 1 : 0) : opt_oplower;
opt_rt_repack = str_rt_repack ? atoi(str_rt_repack) : opt_rt_repack;
opt_profile = str_profile ? atoi(str_profile) : 0;
opt_etm = str_etm ? atoi(str_etm) : 0;
@@ -3835,6 +3946,19 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
// Resolve domain info for all configured devices
ggml_hexagon_discover_devices();
+ size_t total_sessions = opt_ndev;
+ 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");
+ }
+
if (str_profile) {
opt_pmu_evt = [&]() -> std::vector<uint32_t> {
auto v = str_to_vec<uint32_t>(str_profile);
diff --git a/ggml/src/ggml-hexagon/htp-common.h b/ggml/src/ggml-hexagon/htp-common.h
index 235b99c13..5b76b97bd 100644
--- a/ggml/src/ggml-hexagon/htp-common.h
+++ b/ggml/src/ggml-hexagon/htp-common.h
@@ -34,6 +34,7 @@ extern int opt_opqueue;
extern int opt_optrace;
extern int opt_oppoll;
extern int opt_opfusion;
+extern int opt_oplower;
extern int opt_rt_repack;
#ifndef HEX_VERBOSE
@@ -61,10 +62,66 @@ static inline bool ggml_hexagon_tensor_is_tiled(const struct ggml_tensor * t) {
return (ggml_hexagon_tensor_get_flags(t) & HTP_TENSOR_TILED) != 0;
}
+static inline const struct ggml_tensor * htp_tensor_root(const struct ggml_tensor * t) {
+ while (t && t->view_src) {
+ t = t->view_src;
+ }
+ return t;
+}
+
+static inline void ggml_hexagon_tensor_clear_lowered(struct ggml_tensor * t) {
+ for (; t != nullptr; t = t->view_src) {
+ ggml_hexagon_tensor_clear_flags(t, HTP_TENSOR_LOWERED_F16);
+ }
+}
+
+static inline bool ggml_hexagon_tensor_is_lowered_f16(const struct ggml_tensor * t) {
+ return t && (ggml_hexagon_tensor_get_flags(t) & HTP_TENSOR_LOWERED_F16) != 0;
+}
+
+static inline bool htp_tensor_is_stored_f16(const struct ggml_tensor * t) {
+ return t && t->type == GGML_TYPE_F32 &&
+ (ggml_hexagon_tensor_is_lowered_f16(t) || ggml_hexagon_tensor_is_lowered_f16(htp_tensor_root(t)));
+}
+
+static inline enum ggml_type htp_effective_type(const struct ggml_tensor * t) {
+ return ggml_hexagon_tensor_is_lowered_f16(t) ? GGML_TYPE_F16 : t->type;
+}
+
+static inline uint8_t * htp_tensor_data_ptr(const struct ggml_tensor * t) {
+ if (!ggml_hexagon_tensor_is_lowered_f16(t) || !t->view_src) {
+ return (uint8_t *) t->data;
+ }
+ const struct ggml_tensor * root = htp_tensor_root(t);
+ return (uint8_t *) root->data + ((const uint8_t *) t->data - (const uint8_t *) root->data) / 2;
+}
+
+static inline size_t htp_tensor_nbytes(const struct ggml_tensor * t) {
+ return ggml_hexagon_tensor_is_lowered_f16(t) ? (ggml_nbytes(t) / 2) : ggml_nbytes(t);
+}
+
+// Lower a tagged F32 tensor to F16 on the stack and clear HTP_TENSOR_LOWERED_F16 so lowering is idempotent.
+static inline struct ggml_tensor htp_tensor_lower_f16(const struct ggml_tensor * t) {
+ struct ggml_tensor m = *t;
+ if (ggml_hexagon_tensor_is_lowered_f16(t)) {
+ m.type = GGML_TYPE_F16;
+ for (int d = 0; d < GGML_MAX_DIMS; ++d) {
+ m.nb[d] /= 2;
+ }
+ m.view_offs /= 2;
+ m.data = htp_tensor_data_ptr(t);
+ m.extra = (void *) (uintptr_t) (ggml_hexagon_tensor_get_flags(t) & ~HTP_TENSOR_LOWERED_F16);
+ }
+ return m;
+}
+
static inline bool ggml_hexagon_tensor_can_tile(const struct ggml_tensor * t) {
if (opt_rt_repack == 0) {
return false;
}
+ if (!ggml_op_is_empty(t->op)) {
+ return false;
+ }
if (t->buffer) {
if (ggml_backend_buft_is_host(t->buffer->buft) ||
ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE) {
@@ -79,38 +136,14 @@ static inline bool ggml_hexagon_tensor_will_tile(const struct ggml_tensor * t) {
}
static inline bool htp_tensors_overlap(const struct ggml_tensor * a, const struct ggml_tensor * b) {
- const uintptr_t a0 = (uintptr_t) a->data;
- const uintptr_t b0 = (uintptr_t) b->data;
- const uintptr_t a1 = a0 + ggml_nbytes(a);
- const uintptr_t b1 = b0 + ggml_nbytes(b);
+ const uintptr_t a0 = (uintptr_t) htp_tensor_data_ptr(a);
+ const uintptr_t b0 = (uintptr_t) htp_tensor_data_ptr(b);
+ const uintptr_t a1 = a0 + htp_tensor_nbytes(a);
+ const uintptr_t b1 = b0 + htp_tensor_nbytes(b);
return a0 < b1 && b0 < a1;
}
-static inline bool htp_can_row_partition(const struct ggml_tensor * t) {
- if (t->ne[1] > 1 && (t->nb[1] & 127) != 0) return false;
- if (t->ne[2] > 1 && (t->nb[2] & 127) != 0) return false;
- if (t->ne[3] > 1 && (t->nb[3] & 127) != 0) return false;
- return true;
-}
-
-static inline uint32_t htp_mdev_rows_per_chunk(const struct ggml_tensor * t) {
- if ((t->data && ((uintptr_t) t->data & 127) != 0) || (t->view_offs & 127) != 0) return 0;
- const size_t elem_size = ggml_type_size(t->type);
- if (t->ne[0] != 1 && t->nb[0] != elem_size) return 0;
- if (ggml_is_permuted(t)) return 0;
- if (t->ne[2] > 1 && (t->nb[2] & 127) != 0) return 0;
- if (t->ne[3] > 1 && (t->nb[3] & 127) != 0) return 0;
- if (t->ne[1] > 1 && (t->nb[1] & 127) == 0) return 1;
- const size_t row_size = (size_t) t->ne[0] * elem_size;
- if (t->nb[1] == row_size &&
- (t->ne[2] <= 1 || t->nb[2] == t->nb[1] * (size_t) t->ne[1]) &&
- (t->ne[3] <= 1 || t->nb[3] == t->nb[2] * (size_t) t->ne[2])) {
- return (row_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32((uint32_t) row_size, HEX_L2_LINE_SIZE)) : 1;
- }
- return 0;
-}
-
struct ggml_hexagon_session;
const char * htp_session_name(const struct ggml_hexagon_session * sess);
diff --git a/ggml/src/ggml-hexagon/htp-drv.cpp b/ggml/src/ggml-hexagon/htp-drv.cpp
index 9ae4ea727..224e3e432 100644
--- a/ggml/src/ggml-hexagon/htp-drv.cpp
+++ b/ggml/src/ggml-hexagon/htp-drv.cpp
@@ -174,6 +174,10 @@ AEEResult dspqueue_write(dspqueue_t queue,
return dspqueue_write_pfn(queue, flags, num_buffers, buffers, message_length, message, timeout_us);
}
+bool htpdrv_has_read_noblock(void) {
+ return dspqueue_read_noblock_pfn != nullptr;
+}
+
AEEResult dspqueue_read(dspqueue_t queue,
uint32_t * flags,
uint32_t max_buffers,
@@ -183,12 +187,10 @@ AEEResult dspqueue_read(dspqueue_t queue,
uint32_t * message_length,
uint8_t * message,
uint32_t timeout_us) {
-#ifdef _WIN32
- if (timeout_us == 0) {
+ if (timeout_us == 0 && dspqueue_read_noblock_pfn != nullptr) {
return dspqueue_read_noblock_pfn(queue, flags, max_buffers, num_buffers, buffers, max_message_length,
- message_length, message);
+ message_length, message);
}
-#endif
return dspqueue_read_pfn(queue, flags, max_buffers, num_buffers, buffers, max_message_length, message_length,
message, timeout_us);
}
@@ -378,7 +380,7 @@ int htpdrv_init() {
dlsym(handle.get(), dspqueue_export_pfn_t, dspqueue_export_pfn, dspqueue_export, false);
dlsym(handle.get(), dspqueue_write_pfn_t, dspqueue_write_pfn, dspqueue_write, false);
dlsym(handle.get(), dspqueue_read_pfn_t, dspqueue_read_pfn, dspqueue_read, false);
- dlsym(handle.get(), dspqueue_read_noblock_pfn_t, dspqueue_read_noblock_pfn, dspqueue_read_noblock, false);
+ dlsym(handle.get(), dspqueue_read_noblock_pfn_t, dspqueue_read_noblock_pfn, dspqueue_read_noblock, true);
dlsym(handle.get(), remote_handle64_open_pfn_t, remote_handle64_open_pfn, remote_handle64_open, false);
dlsym(handle.get(), remote_handle64_invoke_pfn_t, remote_handle64_invoke_pfn, remote_handle64_invoke, false);
dlsym(handle.get(), remote_handle_control_pfn_t, remote_handle_control_pfn, remote_handle_control, false);
diff --git a/ggml/src/ggml-hexagon/htp-drv.h b/ggml/src/ggml-hexagon/htp-drv.h
index c88a72940..4aa34a21f 100644
--- a/ggml/src/ggml-hexagon/htp-drv.h
+++ b/ggml/src/ggml-hexagon/htp-drv.h
@@ -117,6 +117,7 @@ HTPDRV_API domain * htpdrv_get_domain(int domain_id);
HTPDRV_API int htpdrv_get_arch(int domain, int * arch);
HTPDRV_API int remote_system_request(system_req_payload * req);
+HTPDRV_API bool htpdrv_has_read_noblock(void);
#ifdef __cplusplus
}
diff --git a/ggml/src/ggml-hexagon/htp-fusion.cpp b/ggml/src/ggml-hexagon/htp-fusion.cpp
index eb0862669..35972964f 100644
--- a/ggml/src/ggml-hexagon/htp-fusion.cpp
+++ b/ggml/src/ggml-hexagon/htp-fusion.cpp
@@ -51,14 +51,15 @@ static inline bool htp_match_consumer(
static bool is_supported_mul_mat_nx_kernel(const ggml_tensor * src0, const struct htp_mm_kernel_params * kparams) {
if (kparams->n_hmx) {
- return kparams->kernel_type == HTP_MM_KERNEL_HMX_2D;
+ return htp_mm_kernel_is_hmx_2d(kparams->kernel_type);
}
- return ggml_hexagon_tensor_is_tiled(src0) && (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW);
+ return ggml_hexagon_tensor_is_tiled(src0) &&
+ (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK);
}
static bool is_supported_mul_mat_id_nx_kernel(const ggml_tensor * src0, const struct htp_mm_kernel_params * kparams) {
if (kparams->n_hmx) {
- return kparams->kernel_type == HTP_MM_KERNEL_HMX_2D;
+ return htp_mm_kernel_is_hmx_2d(kparams->kernel_type);
}
return ggml_hexagon_tensor_is_tiled(src0) &&
(kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK);
@@ -76,21 +77,23 @@ static bool fuse_allreduce_add(const ggml_hexagon_session * sess, htp_opnode & p
const ggml_tensor * ar_local = prev.inputs[rank];
if (!ggml_hexagon_tensor_is_fuseable(ar_local)) return false;
+ if (cur.inputs.size() < 2) return false;
+ const ggml_tensor * cur_src0 = cur.inputs[0];
+ const ggml_tensor * cur_src1 = cur.inputs[1];
const ggml_tensor * add_dst = cur.dst();
const ggml_tensor * res_tensor = nullptr;
- if (htp_same_tensor_data(cur.src0(), ar_local)) {
- res_tensor = cur.src1();
- } else if (htp_same_tensor_data(cur.src1(), ar_local)) {
- res_tensor = cur.src0();
+ if (htp_same_tensor_data(cur_src0, ar_local)) {
+ res_tensor = cur_src1;
+ } else if (htp_same_tensor_data(cur_src1, ar_local)) {
+ res_tensor = cur_src0;
} else {
return false;
}
- if (ar_local->type != res_tensor->type) return false;
+ if (ar_local->type != res_tensor->type || ar_local->type != add_dst->type) return false;
const bool is_same_shape = ggml_are_same_shape(ar_local, res_tensor);
- const bool is_row_bcast = !is_same_shape && (ar_local->ne[0] == res_tensor->ne[0] &&
- res_tensor->ne[1] == 1 && res_tensor->ne[2] == 1 && res_tensor->ne[3] == 1);
+ const bool is_row_bcast = !is_same_shape && (ar_local->ne[0] == res_tensor->ne[0] && ggml_is_vector(res_tensor));
if (!is_same_shape && !is_row_bcast) return false;
if (is_same_shape && !ggml_are_same_stride(ar_local, res_tensor)) {
@@ -135,12 +138,15 @@ static bool fuse_rms_norm_mul(const ggml_hexagon_session * sess, htp_opnode & pr
const ggml_tensor * src0 = prev.src0();
const ggml_tensor * dst = cur.dst();
- if (src0->type != GGML_TYPE_F32 || src0->ne[0] != weight->ne[0] || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false;
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (weight->type != GGML_TYPE_F32 && weight->type != GGML_TYPE_F16) ||
+ src0->ne[0] != weight->ne[0] || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false;
if (htp_inputs_overlap_unsafe(prev, dst, weight)) return false;
- const bool is_row_bcast = (weight->ne[1] == 1 && weight->ne[2] == 1 && weight->ne[3] == 1);
+ const bool is_row_bcast = ggml_is_vector(weight);
+ const bool is_dim1_bcast = (weight->ne[1] == src0->ne[1] && ggml_is_matrix(weight));
const bool is_same_shape = ggml_are_same_shape(src0, weight);
- if (!is_row_bcast && !is_same_shape) return false;
+ if (!is_row_bcast && !is_dim1_bcast && !is_same_shape) return false;
struct htp_unary_kernel_params kparams;
if (!htp_kparams_solve_rms_norm_mul(sess, src0, weight, dst, &kparams)) {
@@ -167,11 +173,13 @@ static bool fuse_rms_norm_mul_add(const ggml_hexagon_session * sess, htp_opnode
const ggml_tensor * src0 = prev.src0();
const ggml_tensor * weight = prev.inputs[1];
const ggml_tensor * dst = cur.dst();
- if (!ggml_are_same_layout(src0, r)) return false;
+ if ((r->type != GGML_TYPE_F32 && r->type != GGML_TYPE_F16) ||
+ (weight->type != GGML_TYPE_F32 && weight->type != GGML_TYPE_F16)) return false;
+ if (!ggml_are_same_shape(src0, r) || (ggml_is_contiguous(src0) != ggml_is_contiguous(r))) return false;
if (htp_inputs_overlap_unsafe(prev, dst, r)) return false;
struct htp_unary_kernel_params kparams;
- if (!htp_kparams_solve_rms_norm_mul_add(sess, src0, weight, dst, &kparams)) return false;
+ if (!htp_kparams_solve_rms_norm_mul_add(sess, src0, weight, r, dst, &kparams)) return false;
prev.opcode = HTP_OP_RMS_NORM_MUL_ADD;
prev.inputs.push_back(r);
@@ -188,7 +196,7 @@ static bool fuse_rms_norm_scale(const ggml_hexagon_session * sess, htp_opnode &
const ggml_tensor * src0 = prev.src0();
const ggml_tensor * dst = cur.dst();
- if (src0->type != GGML_TYPE_F32 || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false;
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false;
if (htp_inputs_overlap_unsafe(prev, dst)) return false;
float scale = 0.0f;
@@ -214,13 +222,27 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre
const ggml_tensor * src2 = nullptr;
if (!htp_match_consumer(prev, cur, /*commutative=*/ true, &src2)) return false;
- if (src2->type != GGML_TYPE_F32) return false;
+ if ((src2->type != GGML_TYPE_F32 && src2->type != GGML_TYPE_F16) ||
+ !ggml_is_contiguous_to_2(src2)) {
+ return false;
+ }
const ggml_tensor * src0 = prev.node->src[0];
const ggml_tensor * src1 = prev.node->src[1];
const ggml_tensor * dst = cur.node;
if (!ggml_are_same_shape(prev.node, dst)) return false;
+ // Require matching ne[0], valid broadcast dims (1 or equal), and no unsafe overlap.
+ if (src2->ne[0] != dst->ne[0] ||
+ (src2->ne[1] != 1 && src2->ne[1] != dst->ne[1]) ||
+ (src2->ne[2] != 1 && src2->ne[2] != dst->ne[2]) ||
+ (src2->ne[3] != 1 && src2->ne[3] != dst->ne[3])) {
+ return false;
+ }
+ if (htp_tensors_overlap(dst, src0) || htp_tensors_overlap(dst, src1) || htp_inplace_overlap_unsafe(dst, src2)) {
+ return false;
+ }
+
const bool prev_collapsed = htp_matmul_can_collapse(src0, src1, prev.node);
const bool cur_collapsed = htp_matmul_add_can_collapse(src0, src1, src2, dst);
if (prev_collapsed != cur_collapsed) {
@@ -233,12 +255,12 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre
return false;
}
- const int src1_nrows = src1->ne[1] * src1->ne[2] * src1->ne[3];
- if (kparams.n_hmx == 0 && src1_nrows != 1) return false;
+ const int src1_nrows = (int) ggml_nrows(src1);
+ const bool is_batched = (!ggml_is_matrix(src0) || !ggml_is_matrix(src1));
+ if (kparams.n_hmx == 0 && (src1_nrows != 1 || is_batched)) return false;
if (kparams.n_hmx > 0 && orig_kparams->n_hmx > 0) {
if (kparams.m_chunk < orig_kparams->m_chunk ||
- kparams.n_chunk < orig_kparams->n_chunk ||
kparams.n_act_hvx < orig_kparams->n_act_hvx) {
HEX_VERBOSE("ggml-hex: %s skip MUL_MAT_ADD fusion: HMX efficiency reduced (m %d->%d, n %d->%d, hvx %d->%d)\n",
htp_session_name(sess), orig_kparams->m_chunk, kparams.m_chunk,
@@ -251,7 +273,6 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre
prev.opcode = HTP_OP_MUL_MAT_ADD;
prev.inputs = { src0, src1, src2 };
prev.outputs = { dst };
- htp_opnode_collapse(sess, prev);
prev.fused.push_back(cur.node);
prev.set_kparams(kparams);
return true;
@@ -273,21 +294,36 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev
const auto * cur_kparams = cur.kparams<htp_mm_kernel_params>();
if (x_in != x_orig || w_in->type != w0->type || w_in->ne[0] != w0->ne[0] ||
- w0->ne[2] != 1 || w0->ne[3] != 1 || w_in->ne[2] != 1 || w_in->ne[3] != 1 ||
+ !ggml_is_matrix(w0) || !ggml_is_matrix(w_in) ||
ggml_hexagon_tensor_is_tiled(w_in) != ggml_hexagon_tensor_is_tiled(w0) ||
- orig_kparams->n_hmx != cur_kparams->n_hmx) {
+ orig_kparams->n_hmx != cur_kparams->n_hmx ||
+ orig_kparams->kernel_type != cur_kparams->kernel_type) {
return false;
}
const bool collapse = htp_matmul_can_collapse(w0, x_orig, prev.node) && htp_matmul_can_collapse(w_in, x_in, d_in);
- if ((x_orig->ne[2] > 1 || x_orig->ne[3] > 1) && !collapse) return false;
+ if (!ggml_is_matrix(x_orig) && !collapse) return false;
+
+ const ggml_tensor * prev_w = prev.inputs[0];
+ ggml_type prev_dst_type = prev.outputs[0]->type;
+ for (size_t i = 1; i < curr_n; ++i) {
+ if (prev.inputs[i]->ne[1] > prev_w->ne[1]) prev_w = prev.inputs[i];
+ if (ggml_type_size(prev.outputs[i]->type) > ggml_type_size(prev_dst_type)) {
+ prev_dst_type = prev.outputs[i]->type;
+ }
+ }
+ const ggml_tensor * w_for_solve = (w_in->ne[1] > prev_w->ne[1]) ? w_in : prev_w;
+ const ggml_type max_dst_type = (ggml_type_size(d_in->type) > ggml_type_size(prev_dst_type)) ? d_in->type : prev_dst_type;
- if (prev.opcode == HTP_OP_MUL_MAT_NX) {
+ if (prev.opcode == HTP_OP_MUL_MAT_NX && w_for_solve == prev_w &&
+ ggml_type_size(max_dst_type) == ggml_type_size(prev_dst_type)) {
orig_kparams->n_weights = curr_n + 1;
} else {
struct htp_mm_kernel_params kparams;
const ggml_tensor x_collapsed = collapse ? htp_tensor_collapse_rows(x_orig) : *x_orig;
- if (!htp_kparams_solve_mmnx(sess, w0, &x_collapsed, curr_n + 1, &kparams)) return false;
+ ggml_tensor d_collapsed = collapse ? htp_tensor_collapse_rows(prev.outputs[0]) : *prev.outputs[0];
+ d_collapsed.type = max_dst_type;
+ if (!htp_kparams_solve_mmnx(sess, w_for_solve, &x_collapsed, &d_collapsed, curr_n + 1, &kparams)) return false;
if (!is_supported_mul_mat_nx_kernel(w0, &kparams)) return false;
prev.set_kparams(kparams);
@@ -295,8 +331,98 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev
}
prev.inputs.insert(prev.inputs.begin() + curr_n, w_in);
- prev.outputs.push_back(collapse ? prev.add_dummy(htp_tensor_collapse_rows(d_in)) : d_in);
+ prev.outputs.push_back(d_in);
+ prev.fused.push_back(cur.node);
+ return true;
+}
+
+static bool htp_is_fuseable_mmnx_glu_op(uint32_t op) {
+ return op == HTP_OP_GLU_SWIGLU || op == HTP_OP_GLU_GEGLU ||
+ op == HTP_OP_GLU_GEGLU_QUICK || op == HTP_OP_GLU_REGLU;
+}
+
+static bool fuse_mul_mat_nx_glu(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) {
+ if (prev.opcode != HTP_OP_MUL_MAT_NX || prev.outputs.size() != 2 || prev.inputs.size() != 3) {
+ return false;
+ }
+ if (!htp_is_fuseable_mmnx_glu_op(cur.opcode) || cur.inputs.size() != 2 || cur.outputs.size() != 1 || !cur.src1()) {
+ return false;
+ }
+ if (prev.fused.size() + 1 + cur.fused.size() > HTP_OP_MAX_FUSED) {
+ return false;
+ }
+
+ const auto * orig_kparams = prev.kparams<htp_mm_kernel_params>();
+ if (!orig_kparams->n_hmx || !htp_mm_kernel_is_hmx_2d(orig_kparams->kernel_type)) {
+ return false;
+ }
+
+ const ggml_tensor * out0 = prev.outputs[0];
+ const ggml_tensor * out1 = prev.outputs[1];
+ if (!ggml_hexagon_tensor_is_fuseable(out0) || !ggml_hexagon_tensor_is_fuseable(out1) ||
+ (out0->flags & GGML_TENSOR_FLAG_OUTPUT) || (out1->flags & GGML_TENSOR_FLAG_OUTPUT)) {
+ return false;
+ }
+ if (ggml_prec_get_acc(out0) == GGML_PREC_F32 || ggml_prec_get_acc(out1) == GGML_PREC_F32) {
+ return false;
+ }
+
+ const ggml_tensor * w_gate = nullptr;
+ const ggml_tensor * w_up = nullptr;
+ const ggml_tensor * out_gate = nullptr;
+ const ggml_tensor * out_up = nullptr;
+ if (htp_same_tensor_data(cur.src0(), out0) && htp_same_tensor_data(cur.src1(), out1)) {
+ w_gate = prev.inputs[0];
+ w_up = prev.inputs[1];
+ out_gate = out0;
+ out_up = out1;
+ } else if (htp_same_tensor_data(cur.src0(), out1) && htp_same_tensor_data(cur.src1(), out0)) {
+ w_gate = prev.inputs[1];
+ w_up = prev.inputs[0];
+ out_gate = out1;
+ out_up = out0;
+ } else {
+ return false;
+ }
+
+ const ggml_tensor * act = prev.inputs[2];
+ const ggml_tensor * dst = cur.dst();
+ if (w_gate->ne[1] != w_up->ne[1] || w_gate->ne[0] != w_up->ne[0] ||
+ !ggml_is_contiguous(out_gate) || !ggml_is_contiguous(out_up) || !ggml_is_contiguous(dst) ||
+ out_gate->type != cur.src0()->type || out_up->type != cur.src1()->type ||
+ !ggml_are_same_shape(out_gate, cur.src0()) || !ggml_are_same_stride(out_gate, cur.src0()) ||
+ !ggml_are_same_shape(out_up, cur.src1()) || !ggml_are_same_stride(out_up, cur.src1()) ||
+ !ggml_are_same_shape(out_gate, dst)) {
+ return false;
+ }
+ if (dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_F32) {
+ return false;
+ }
+ if (htp_tensors_overlap(dst, w_gate) || htp_tensors_overlap(dst, w_up) || htp_tensors_overlap(dst, act)) {
+ return false;
+ }
+
+ const bool collapse = htp_matmul_can_collapse(w_gate, act, dst) && htp_matmul_can_collapse(w_up, act, dst);
+ if (!ggml_is_matrix(act) && !collapse) {
+ return false;
+ }
+
+ const ggml_tensor x_collapsed = collapse ? htp_tensor_collapse_rows(act) : *act;
+ const ggml_tensor d_collapsed = collapse ? htp_tensor_collapse_rows(dst) : *dst;
+
+ struct htp_mm_kernel_params kparams;
+ if (!htp_kparams_solve_mmnx_glu(sess, w_gate, w_up, &x_collapsed, &d_collapsed, (uint8_t) cur.opcode, &kparams)) {
+ return false;
+ }
+
+ prev.opcode = HTP_OP_MUL_MAT_NX_GLU;
+ prev.inputs = { w_gate, w_up, act };
+ prev.outputs = { dst };
prev.fused.push_back(cur.node);
+ for (const ggml_tensor * f : cur.fused) {
+ prev.fused.push_back(f);
+ }
+ prev.set_kparams(kparams);
return true;
}
@@ -380,7 +506,6 @@ static bool fuse_gdn_cpy(const ggml_hexagon_session * sess, htp_opnode & prev, c
}
static bool fuse_ssm_conv_silu(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) {
- GGML_UNUSED(sess);
if (prev.opcode != HTP_OP_SSM_CONV) return false;
auto * kparams = prev.kparams<htp_ssm_conv_kernel_params>();
@@ -389,12 +514,17 @@ static bool fuse_ssm_conv_silu(const ggml_hexagon_session * sess, htp_opnode & p
const ggml_tensor * conv_dst = prev.dst();
const ggml_tensor * dst = cur.dst();
- if (!ggml_are_same_layout(conv_dst, dst)) return false;
+ if (!ggml_are_same_shape(conv_dst, cur.src0()) || !ggml_are_same_stride(conv_dst, cur.src0())) return false;
+ if (!ggml_are_same_shape(conv_dst, dst)) return false;
if (htp_tensors_overlap(dst, prev.src0()) || htp_tensors_overlap(dst, prev.src1())) return false;
- kparams->silu = 1;
- prev.outputs[0] = dst;
- prev.fused.push_back(cur.node);
+ htp_opnode cand = prev;
+ cand.outputs[0] = dst;
+ cand.fused.push_back(cur.node);
+ cand.kparams<htp_ssm_conv_kernel_params>()->silu = 1;
+ if (!htp_kparams_solve(sess, cand)) return false;
+
+ prev = std::move(cand);
return true;
}
@@ -421,6 +551,97 @@ static bool fuse_repeat_get_rows(const ggml_hexagon_session * sess, htp_opnode &
return true;
}
+static inline bool htp_is_scale_bias_unary(uint32_t opcode) {
+ switch (opcode) {
+ case HTP_OP_UNARY_EXP:
+ case HTP_OP_UNARY_SIGMOID:
+ case HTP_OP_UNARY_SILU:
+ case HTP_OP_UNARY_GELU:
+ case HTP_OP_UNARY_GELU_QUICK:
+ case HTP_OP_UNARY_GELU_ERF:
+ case HTP_OP_UNARY_SOFTPLUS:
+ case HTP_OP_UNARY_TANH:
+ return true;
+ default:
+ return false;
+ }
+}
+
+static bool fuse_scale_unary(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) {
+ if (prev.opcode != HTP_OP_SCALE || !prev.fused.empty() || !htp_is_scale_bias_unary(cur.opcode)) return false;
+ if (cur.kparams<htp_unary_kernel_params>()->has_scale_bias) return false;
+ if (!htp_match_consumer(prev, cur, /*commutative=*/ false)) return false;
+
+ const ggml_tensor * src0 = prev.src0();
+ const ggml_tensor * dst = cur.dst();
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ dst->type != src0->type || !htp_same_shape_and_contiguity(prev.dst(), dst)) {
+ return false;
+ }
+ if (htp_inputs_overlap_unsafe(prev, dst)) return false;
+
+ float in_scale = 0.0f;
+ float in_bias = 0.0f;
+ memcpy(&in_scale, (const float *) prev.params + 0, sizeof(float));
+ memcpy(&in_bias, (const float *) prev.params + 1, sizeof(float));
+
+ htp_opnode cand = prev;
+ cand.opcode = cur.opcode;
+ cand.outputs = { dst };
+ memcpy(cand.params, cur.params, sizeof(cand.params));
+
+ auto * kp = cand.kparams<htp_unary_kernel_params>();
+ kp->has_scale_bias = 1;
+ kp->in_scale = in_scale;
+ kp->in_bias = in_bias;
+ kp->out_scale = 1.0f;
+ kp->out_bias = 0.0f;
+ if (!htp_kparams_solve(sess, cand)) return false;
+
+ prev = std::move(cand);
+ prev.fused.push_back(cur.node);
+ return true;
+}
+
+static bool fuse_unary_scale(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) {
+ if (!htp_is_scale_bias_unary(prev.opcode) || prev.fused.size() >= HTP_OP_MAX_FUSED) return false;
+ if (!htp_match_consumer(prev, cur, /*commutative=*/ false)) return false;
+
+ const ggml_tensor * src0 = prev.src0();
+ const ggml_tensor * dst = cur.dst();
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ dst->type != src0->type || !htp_same_shape_and_contiguity(prev.dst(), dst)) {
+ return false;
+ }
+ if (htp_inputs_overlap_unsafe(prev, dst)) return false;
+
+ float s_out = 0.0f;
+ float b_out = 0.0f;
+ memcpy(&s_out, (const float *) cur.params + 0, sizeof(float));
+ memcpy(&b_out, (const float *) cur.params + 1, sizeof(float));
+
+ const auto * prev_kp = prev.kparams<htp_unary_kernel_params>();
+ const float in_scale = prev_kp->has_scale_bias ? prev_kp->in_scale : 1.0f;
+ const float in_bias = prev_kp->has_scale_bias ? prev_kp->in_bias : 0.0f;
+ const float out_scale = (prev_kp->has_scale_bias ? prev_kp->out_scale : 1.0f) * s_out;
+ const float out_bias = (prev_kp->has_scale_bias ? prev_kp->out_bias : 0.0f) * s_out + b_out;
+
+ htp_opnode cand = prev;
+ cand.outputs = { dst };
+
+ auto * kp = cand.kparams<htp_unary_kernel_params>();
+ kp->has_scale_bias = 1;
+ kp->in_scale = in_scale;
+ kp->in_bias = in_bias;
+ kp->out_scale = out_scale;
+ kp->out_bias = out_bias;
+ if (!htp_kparams_solve(sess, cand)) return false;
+
+ prev = std::move(cand);
+ prev.fused.push_back(cur.node);
+ return true;
+}
+
static bool fuse_unary_mul_glu(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) {
htp_op_code glu_op = HTP_OP_INVALID;
switch (prev.opcode) {
@@ -432,6 +653,7 @@ static bool fuse_unary_mul_glu(const ggml_hexagon_session * sess, htp_opnode & p
case HTP_OP_UNARY_SIGMOID: glu_op = HTP_OP_GLU_SIGMOID; break;
default: return false;
}
+ if (prev.kparams<htp_unary_kernel_params>()->has_scale_bias) return false;
const ggml_tensor * up = nullptr;
if (!htp_match_consumer(prev, cur, /*commutative=*/ true, &up)) return false;
@@ -440,11 +662,13 @@ static bool fuse_unary_mul_glu(const ggml_hexagon_session * sess, htp_opnode & p
const ggml_tensor * dst = cur.dst();
if (htp_inputs_overlap_unsafe(prev, dst, up)) return false;
- prev.opcode = glu_op;
- prev.inputs = { gate, up };
- prev.outputs = { dst };
- if (!htp_kparams_solve(sess, prev)) return false;
+ htp_opnode cand = prev;
+ cand.opcode = glu_op;
+ cand.inputs = { gate, up };
+ cand.outputs = { dst };
+ if (!htp_kparams_solve(sess, cand)) return false;
+ prev = std::move(cand);
prev.fused.push_back(cur.node);
memset(prev.params, 0, sizeof(prev.params));
return true;
@@ -463,6 +687,7 @@ static bool fuse_mul_mul_scalar(const ggml_hexagon_session * sess, htp_opnode &
const ggml_tensor * src1 = prev.src1();
const ggml_tensor * dst = cur.dst();
+ if (prev.src0()->type != src1->type || prev.dst()->type != src1->type || src2->type != src1->type || dst->type != src1->type) return false;
if (!ggml_are_same_shape(src1, src2) || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false;
if (htp_inputs_overlap_unsafe(prev, dst, src2)) return false;
@@ -506,6 +731,10 @@ static bool fuse_binary_nx(const ggml_hexagon_session * sess, htp_opnode & prev,
const ggml_tensor * src0 = prev.inputs[0];
const ggml_tensor * dst = cur.dst();
+ if (prev.dst()->type != src0->type || new_src->type != src0->type || dst->type != src0->type) return false;
+ for (const auto * in : prev.inputs) {
+ if (in->type != src0->type) return false;
+ }
if (!ggml_are_same_shape(src0, prev.inputs[1]) ||
!ggml_are_same_shape(src0, new_src) ||
!htp_same_shape_and_contiguity(prev.dst(), dst)) {
@@ -547,7 +776,7 @@ static bool fuse_binary_nx(const ggml_hexagon_session * sess, htp_opnode & prev,
const uint32_t total_elems = (uint32_t) ggml_nelements(src0);
const uint32_t elem_size = (uint32_t) ggml_type_size(src0->type);
const uint32_t max_hvx = htp_session_n_hvx(sess);
- if (!htp_binary_solve_chunked(&L, &kparams, total_elems, elem_size, max_hvx, n_srcs, false, vtcm_size)) {
+ if (!htp_binary_solve_chunked(&L, &kparams, total_elems, elem_size, elem_size, elem_size, max_hvx, n_srcs, false, vtcm_size)) {
return false;
}
}
@@ -569,7 +798,8 @@ bool htp_fusion_can_stack(const struct ggml_tensor * a) {
if (!htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX)) return false;
if (htp_is_hadamard(a)) return false;
if (a->src[0]->ne[2] != 1 || a->src[0]->ne[3] != 1) return false;
- return ggml_is_quantized(a->src[0]->type);
+ return ggml_is_quantized(a->src[0]->type) ||
+ (a->src[0]->type == GGML_TYPE_F16 && a->src[0]->ne[0] % 32 == 0);
case GGML_OP_MUL_MAT_ID:
if (!htp_fusion_enabled(HTP_FUSE_MUL_MAT_ID_NX)) return false;
return a->src[2] != nullptr && ggml_is_quantized(a->src[0]->type);
@@ -639,6 +869,7 @@ void htp_fusion_tag_graph(struct ggml_cgraph * graph) {
bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_opnode & prev, const struct htp_opnode & cur) {
if (!opt_opfusion) return false;
+ if (!cur.fused.empty()) return false;
switch (cur.opcode) {
case HTP_OP_ADD:
@@ -655,9 +886,19 @@ bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_op
case HTP_OP_DIV:
return htp_fusion_enabled(HTP_FUSE_BINARY_NX) && fuse_binary_nx(sess, prev, cur);
case HTP_OP_SCALE:
- return htp_fusion_enabled(HTP_FUSE_RMS_NORM_SCALE) && fuse_rms_norm_scale(sess, prev, cur);
+ return (htp_fusion_enabled(HTP_FUSE_RMS_NORM_SCALE) && fuse_rms_norm_scale(sess, prev, cur)) ||
+ (htp_fusion_enabled(HTP_FUSE_UNARY_SCALE) && fuse_unary_scale(sess, prev, cur));
case HTP_OP_UNARY_SILU:
- return htp_fusion_enabled(HTP_FUSE_SSM_CONV_SILU) && fuse_ssm_conv_silu(sess, prev, cur);
+ return (htp_fusion_enabled(HTP_FUSE_SSM_CONV_SILU) && fuse_ssm_conv_silu(sess, prev, cur)) ||
+ (htp_fusion_enabled(HTP_FUSE_UNARY_SCALE) && fuse_scale_unary(sess, prev, cur));
+ case HTP_OP_UNARY_EXP:
+ case HTP_OP_UNARY_SIGMOID:
+ case HTP_OP_UNARY_GELU:
+ case HTP_OP_UNARY_GELU_QUICK:
+ case HTP_OP_UNARY_GELU_ERF:
+ case HTP_OP_UNARY_SOFTPLUS:
+ case HTP_OP_UNARY_TANH:
+ return htp_fusion_enabled(HTP_FUSE_UNARY_SCALE) && fuse_scale_unary(sess, prev, cur);
case HTP_OP_GET_ROWS:
return htp_fusion_enabled(HTP_FUSE_REPEAT_GET_ROWS) && fuse_repeat_get_rows(sess, prev, cur);
case HTP_OP_CPY:
@@ -666,7 +907,396 @@ bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_op
return htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX) && fuse_mul_mat_nx(sess, prev, cur);
case HTP_OP_MUL_MAT_ID:
return htp_fusion_enabled(HTP_FUSE_MUL_MAT_ID_NX) && fuse_mul_mat_id_nx(sess, prev, cur);
+ case HTP_OP_GLU_SWIGLU:
+ case HTP_OP_GLU_GEGLU:
+ case HTP_OP_GLU_GEGLU_QUICK:
+ case HTP_OP_GLU_REGLU:
+ return htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX_GLU) && fuse_mul_mat_nx_glu(sess, prev, cur);
default:
return false;
}
}
+
+static void htp_fuse_gdn_state(const struct ggml_hexagon_session * sess, std::vector<struct htp_opnode> & nodes) {
+ for (size_t c = 0; c < nodes.size(); ++c) {
+ if (nodes[c].opcode != HTP_OP_GATED_DELTA_NET || nodes[c].inputs.size() != 6 ||
+ nodes[c].fused.size() >= HTP_OP_MAX_FUSED) {
+ continue;
+ }
+ const ggml_tensor * v = nodes[c].inputs[2];
+ const ggml_tensor * s = nodes[c].inputs[5];
+
+ const ggml_tensor * base_s = s;
+ while (base_s->view_src &&
+ (base_s->op == GGML_OP_RESHAPE || (base_s->op == GGML_OP_VIEW && base_s->view_offs == 0)) &&
+ ggml_is_contiguous(base_s)) {
+ base_s = base_s->view_src;
+ }
+ if (base_s->flags & GGML_TENSOR_FLAG_OUTPUT) continue;
+
+ size_t p = c;
+ for (size_t i = 0; i < c; ++i) {
+ if (nodes[i].opcode == HTP_OP_GET_ROWS && nodes[i].fused.empty() &&
+ nodes[i].outputs.size() == 1 && nodes[i].dst() == base_s) {
+ p = i;
+ break;
+ }
+ }
+ if (p == c) continue;
+
+ const ggml_tensor * gr_src0 = nodes[p].src0();
+ const ggml_tensor * gr_src1 = nodes[p].src1();
+ const int64_t n_seqs = v->ne[3];
+ if (htp_tensors_overlap(nodes[c].outputs[0], gr_src0) || htp_tensors_overlap(nodes[c].outputs[0], gr_src1)) {
+ continue;
+ }
+ if (nodes[c].outputs.size() > 1 && nodes[c].outputs[1]) {
+ const ggml_tensor * dst_cache = nodes[c].outputs[1];
+ if (htp_tensors_overlap(dst_cache, gr_src1)) continue;
+ if (htp_tensors_overlap(gr_src0, dst_cache)) {
+ const uintptr_t src0_ptr = (uintptr_t) htp_tensor_data_ptr(gr_src0);
+ const uintptr_t dst_ptr = (uintptr_t) htp_tensor_data_ptr(dst_cache);
+ const bool slot_aligned = (n_seqs == 1) &&
+ (dst_cache->type == gr_src0->type) &&
+ (dst_ptr >= src0_ptr) &&
+ (gr_src0->nb[1] > 0) &&
+ ((dst_ptr - src0_ptr) % gr_src0->nb[1] == 0) &&
+ (dst_cache->ne[2] == 1 || gr_src0->nb[1] == dst_cache->nb[2]);
+ if (!slot_aligned) continue;
+ }
+ }
+
+ bool safe = true;
+ for (size_t k = 0; k < nodes.size() && safe; ++k) {
+ if (k == p) continue;
+ if (k != c) {
+ for (const ggml_tensor * in : nodes[k].inputs) {
+ for (const ggml_tensor * t = in; t != nullptr; t = t->view_src) {
+ if (t == base_s) { safe = false; break; }
+ }
+ if (!safe) break;
+ }
+ }
+ if (k > p && k < c) {
+ for (const ggml_tensor * out : nodes[k].outputs) {
+ if (out && (htp_tensors_overlap(out, gr_src0) || htp_tensors_overlap(out, gr_src1) ||
+ htp_tensors_overlap(out, base_s))) {
+ safe = false;
+ break;
+ }
+ }
+ }
+ }
+ if (!safe) continue;
+
+ htp_opnode cand = nodes[c];
+ cand.inputs[5] = gr_src0;
+ cand.inputs.push_back(gr_src1);
+ cand.fused.insert(cand.fused.begin(), nodes[p].node);
+ if (!htp_kparams_solve(sess, cand)) continue;
+
+ nodes[c] = std::move(cand);
+ nodes.erase(nodes.begin() + (ptrdiff_t) p);
+ --c;
+ }
+}
+
+static bool htp_unwrap_transpose_01(const ggml_tensor * t, const ggml_tensor ** out_src) {
+ if (!t || !t->view_src || t->view_offs != 0) {
+ return false;
+ }
+ if (t->op == GGML_OP_TRANSPOSE) {
+ *out_src = t->view_src;
+ return true;
+ }
+ if (t->op == GGML_OP_PERMUTE) {
+ if (ggml_get_op_params_i32(t, 0) == 1 &&
+ ggml_get_op_params_i32(t, 1) == 0 &&
+ ggml_get_op_params_i32(t, 2) == 2 &&
+ ggml_get_op_params_i32(t, 3) == 3) {
+ *out_src = t->view_src;
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool htp_tensor_is_view_of(const ggml_tensor * in, const ggml_tensor * target) {
+ if (!in || !target) {
+ return false;
+ }
+ for (const ggml_tensor * t = in; t != nullptr; t = t->view_src) {
+ if (t == target) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool htp_tensor_reads_from(const ggml_tensor * in, const ggml_tensor * target) {
+ if (!in || !target) {
+ return false;
+ }
+ if (htp_tensor_is_view_of(in, target)) {
+ return true;
+ }
+ return htp_tensors_overlap(in, target);
+}
+
+static void htp_fuse_concat_ssm_conv(const struct ggml_hexagon_session * sess, std::vector<struct htp_opnode> & nodes) {
+ for (size_t c = 0; c < nodes.size(); ++c) {
+ if (nodes[c].opcode != HTP_OP_SSM_CONV || nodes[c].inputs.size() != 2 ||
+ nodes[c].outputs.size() != 1 || nodes[c].fused.size() >= HTP_OP_MAX_FUSED) {
+ continue;
+ }
+
+ const ggml_tensor * conv_x = nodes[c].src0();
+ const ggml_tensor * conv_weight = nodes[c].src1();
+ const ggml_tensor * conv_dst = nodes[c].dst();
+ if (conv_x->flags & GGML_TENSOR_FLAG_OUTPUT) {
+ continue;
+ }
+
+ size_t p = c;
+ for (size_t i = 0; i < c; ++i) {
+ if (nodes[i].opcode == HTP_OP_CONCAT && nodes[i].fused.empty() &&
+ nodes[i].outputs.size() == 1 && nodes[i].dst() == conv_x &&
+ ggml_get_op_params_i32(nodes[i].node, 0) == 0) {
+ p = i;
+ break;
+ }
+ }
+ if (p == c) {
+ continue;
+ }
+
+ const ggml_tensor * cat_state = nodes[p].src0();
+ const ggml_tensor * cat_xT = nodes[p].src1();
+ const ggml_tensor * cat_x = nullptr;
+ if (!htp_unwrap_transpose_01(cat_xT, &cat_x)) {
+ continue;
+ }
+
+ const int64_t d_conv = conv_weight->ne[0];
+ const int64_t d_inner = conv_weight->ne[1];
+ const int64_t n_t = conv_dst->ne[1];
+ const int64_t n_s = conv_dst->ne[2];
+ const int64_t S = d_conv - 1;
+
+ size_t q = nodes.size();
+ size_t n_other = 0;
+ for (size_t k = 0; k < nodes.size(); ++k) {
+ if (k == p || k == c) {
+ continue;
+ }
+ bool uses_conv_x = false;
+ for (const ggml_tensor * in : nodes[k].inputs) {
+ if (htp_tensor_is_view_of(in, conv_x)) {
+ uses_conv_x = true;
+ break;
+ }
+ }
+ if (uses_conv_x) {
+ q = k;
+ ++n_other;
+ }
+ }
+ if (n_other > 1) {
+ continue;
+ }
+
+ const bool has_cpy = (n_other == 1);
+ const ggml_tensor * cpy_dst = nullptr;
+ if (has_cpy) {
+ if (q <= p || nodes[q].opcode != HTP_OP_CPY || !nodes[q].fused.empty() ||
+ nodes[q].outputs.size() != 1 || (nodes[q].node->flags & GGML_TENSOR_FLAG_OUTPUT)) {
+ continue;
+ }
+ if (nodes[c].fused.size() + 2 > HTP_OP_MAX_FUSED) {
+ continue;
+ }
+ const ggml_tensor * cpy_src = nodes[q].src0();
+ cpy_dst = nodes[q].dst();
+ const size_t conv_x_es = ggml_type_size(conv_x->type);
+ if (cpy_src->op != GGML_OP_VIEW ||
+ !htp_same_tensor_data(cpy_src->view_src, conv_x) ||
+ cpy_src->ne[0] != S || cpy_src->ne[1] != d_inner || cpy_src->ne[2] != n_s || cpy_src->ne[3] != 1 ||
+ cpy_src->nb[0] != conv_x_es || cpy_src->nb[1] != conv_x->nb[1] ||
+ (n_s > 1 && cpy_src->nb[2] != conv_x->nb[2]) ||
+ cpy_src->view_offs != (size_t) n_t * conv_x_es) {
+ continue;
+ }
+ }
+
+ const bool inplace_x_dst = htp_same_tensor_data(conv_dst, cat_x) &&
+ conv_dst->type == cat_x->type &&
+ ggml_are_same_shape(conv_dst, cat_x) &&
+ ggml_are_same_stride(conv_dst, cat_x);
+ if (htp_tensors_overlap(conv_dst, cat_state) ||
+ (htp_tensors_overlap(conv_dst, cat_x) && !inplace_x_dst) ||
+ htp_tensors_overlap(conv_dst, conv_weight)) {
+ continue;
+ }
+ if (has_cpy) {
+ if (htp_tensors_overlap(conv_dst, cpy_dst) ||
+ htp_tensors_overlap(cpy_dst, cat_x) ||
+ htp_tensors_overlap(cpy_dst, conv_weight)) {
+ continue;
+ }
+ if (htp_tensors_overlap(cpy_dst, cat_state)) {
+ const bool inplace_state = (n_s == 1) &&
+ htp_same_tensor_data(cpy_dst, cat_state) &&
+ cpy_dst->type == cat_state->type;
+ if (!inplace_state) {
+ continue;
+ }
+ }
+ }
+
+ bool safe = true;
+ for (size_t k = p + 1; k < c && safe; ++k) {
+ if (has_cpy && k == q) {
+ continue;
+ }
+ for (const ggml_tensor * out : nodes[k].outputs) {
+ if (!out) {
+ continue;
+ }
+ if (htp_tensors_overlap(out, cat_state) ||
+ htp_tensors_overlap(out, cat_x) ||
+ htp_tensors_overlap(out, conv_x) ||
+ htp_tensors_overlap(out, conv_weight) ||
+ (has_cpy && htp_tensors_overlap(out, cpy_dst))) {
+ safe = false;
+ break;
+ }
+ }
+ }
+ if (has_cpy && safe) {
+ const size_t lo = (q < c) ? (q + 1) : (c + 1);
+ const size_t hi = (q < c) ? c : q;
+ for (size_t k = lo; k < hi && safe; ++k) {
+ for (const ggml_tensor * in : nodes[k].inputs) {
+ if (htp_tensor_reads_from(in, cpy_dst)) {
+ safe = false;
+ break;
+ }
+ }
+ for (const ggml_tensor * out : nodes[k].outputs) {
+ if (out && (htp_tensors_overlap(out, cpy_dst) || (q > c && htp_tensors_overlap(out, conv_x)))) {
+ safe = false;
+ break;
+ }
+ }
+ }
+ }
+ if (!safe) {
+ continue;
+ }
+
+ htp_opnode cand = nodes[c];
+ cand.inputs = { cat_state, conv_weight, cat_x };
+ if (has_cpy) {
+ cand.outputs = { conv_dst, cpy_dst };
+ cand.fused.insert(cand.fused.begin(), nodes[q].node);
+ }
+ cand.fused.insert(cand.fused.begin(), nodes[p].node);
+ if (!htp_kparams_solve(sess, cand)) {
+ continue;
+ }
+
+ nodes[c] = std::move(cand);
+ if (has_cpy) {
+ nodes.erase(nodes.begin() + (ptrdiff_t) q);
+ if (q < c) {
+ --c;
+ }
+ }
+ nodes.erase(nodes.begin() + (ptrdiff_t) p);
+ --c;
+ }
+}
+
+static void htp_fuse_mul_mat_nx_glu(const struct ggml_hexagon_session * sess, std::vector<struct htp_opnode> & nodes) {
+ for (size_t c = 0; c < nodes.size(); ++c) {
+ if (!htp_is_fuseable_mmnx_glu_op(nodes[c].opcode) || nodes[c].inputs.size() != 2 ||
+ nodes[c].outputs.size() != 1 || !nodes[c].src1()) {
+ continue;
+ }
+
+ const ggml_tensor * s0 = nodes[c].src0();
+ const ggml_tensor * s1 = nodes[c].src1();
+
+ size_t p = c;
+ for (size_t i = 0; i < c; ++i) {
+ if (nodes[i].opcode != HTP_OP_MUL_MAT_NX || nodes[i].outputs.size() != 2 || nodes[i].inputs.size() != 3) {
+ continue;
+ }
+ const ggml_tensor * o0 = nodes[i].outputs[0];
+ const ggml_tensor * o1 = nodes[i].outputs[1];
+ if ((htp_same_tensor_data(s0, o0) && htp_same_tensor_data(s1, o1)) ||
+ (htp_same_tensor_data(s0, o1) && htp_same_tensor_data(s1, o0))) {
+ p = i;
+ break;
+ }
+ }
+ if (p == c) {
+ continue;
+ }
+
+ const ggml_tensor * w0 = nodes[p].inputs[0];
+ const ggml_tensor * w1 = nodes[p].inputs[1];
+ const ggml_tensor * act = nodes[p].inputs[2];
+ const ggml_tensor * o0 = nodes[p].outputs[0];
+ const ggml_tensor * o1 = nodes[p].outputs[1];
+
+ bool safe = true;
+ for (size_t k = 0; k < nodes.size() && safe; ++k) {
+ if (k == p || k == c) {
+ continue;
+ }
+ for (const ggml_tensor * in : nodes[k].inputs) {
+ if (htp_tensor_reads_from(in, o0) || htp_tensor_reads_from(in, o1)) {
+ safe = false;
+ break;
+ }
+ }
+ if (safe && k > p && k < c) {
+ for (const ggml_tensor * out : nodes[k].outputs) {
+ if (out && (htp_tensors_overlap(out, w0) || htp_tensors_overlap(out, w1) ||
+ htp_tensors_overlap(out, act) || htp_tensors_overlap(out, o0) ||
+ htp_tensors_overlap(out, o1))) {
+ safe = false;
+ break;
+ }
+ }
+ }
+ }
+ if (!safe) {
+ continue;
+ }
+
+ htp_opnode cand = nodes[p];
+ if (!fuse_mul_mat_nx_glu(sess, cand, nodes[c])) {
+ continue;
+ }
+
+ nodes[c] = std::move(cand);
+ nodes.erase(nodes.begin() + (ptrdiff_t) p);
+ --c;
+ }
+}
+
+void htp_fusion_optimize_nodes(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector<struct htp_opnode> & nodes) {
+ GGML_UNUSED(graph);
+
+ if (htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX_GLU)) {
+ htp_fuse_mul_mat_nx_glu(sess, nodes);
+ }
+ if (htp_fusion_enabled(HTP_FUSE_GDN_STATE)) {
+ htp_fuse_gdn_state(sess, nodes);
+ }
+ if (htp_fusion_enabled(HTP_FUSE_CONCAT_SSM_CONV)) {
+ htp_fuse_concat_ssm_conv(sess, nodes);
+ }
+}
diff --git a/ggml/src/ggml-hexagon/htp-fusion.h b/ggml/src/ggml-hexagon/htp-fusion.h
index e4f711c87..6a2b39196 100644
--- a/ggml/src/ggml-hexagon/htp-fusion.h
+++ b/ggml/src/ggml-hexagon/htp-fusion.h
@@ -15,8 +15,12 @@ enum htp_fusion_flags {
HTP_FUSE_MUL_MUL_SCALAR = (1 << 9), // 512
HTP_FUSE_BINARY_NX = (1 << 10), // 1024
HTP_FUSE_RMS_NORM_SCALE = (1 << 11), // 2048
- HTP_FUSE_SSM_CONV_SILU = (1 << 12), // 4096
+ HTP_FUSE_SSM_CONV_SILU = (1 << 12), // 4096
HTP_FUSE_RMS_NORM_MUL_ADD = (1 << 13), // 8192
+ HTP_FUSE_UNARY_SCALE = (1 << 14), // 16384
+ HTP_FUSE_GDN_STATE = (1 << 15), // 32768
+ HTP_FUSE_CONCAT_SSM_CONV = (1 << 16), // 65536
+ HTP_FUSE_MUL_MAT_NX_GLU = (1 << 17), // 131072
};
static inline bool htp_fusion_enabled(int flag) {
@@ -30,5 +34,6 @@ bool htp_fusion_can_stack(const struct ggml_tensor * a, const struct ggml_tensor
int htp_fusion_max(const struct ggml_cgraph * graph, int idx);
void htp_fusion_tag_graph(struct ggml_cgraph * graph);
bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_opnode & prev, const struct htp_opnode & cur);
+void htp_fusion_optimize_nodes(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector<struct htp_opnode> & nodes);
#endif // HTP_FUSION_H
diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp
index 122d6aee8..97ca56e3f 100644
--- a/ggml/src/ggml-hexagon/htp-kparams.cpp
+++ b/ggml/src/ggml-hexagon/htp-kparams.cpp
@@ -108,39 +108,6 @@ htp_op_code htp_op_remap(const struct ggml_tensor * t) {
return HTP_OP_INVALID;
}
-bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride) {
- size_t s = 0, next = 0;
- for (int i = 1; i < GGML_MAX_DIMS; i++) {
- if (ne[i] == 1) continue;
- if (s == 0) { s = nb[i]; next = s * ne[i]; continue; }
- if (nb[i] != next) return false;
- next *= ne[i];
- }
- *stride = s ? s : nb[1];
- return true;
-}
-
-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) &&
- 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);
-}
-
-ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t) {
- size_t stride = 0;
- htp_rows_stride(t->ne, t->nb, &stride);
- ggml_tensor c = *t;
- c.ne[1] = t->ne[1] * t->ne[2] * t->ne[3];
- c.ne[2] = 1;
- c.ne[3] = 1;
- c.nb[1] = stride;
- c.nb[2] = c.nb[1] * c.ne[1];
- c.nb[3] = c.nb[2];
- return c;
-}
-
bool htp_kparams_solve_allreduce(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * dst,
@@ -164,7 +131,7 @@ bool htp_kparams_solve_allreduce(
const bool is_contiguous = ggml_is_contiguous(dst);
const uint32_t ne0 = (uint32_t) dst->ne[0];
- const uint32_t ne1 = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]);
+ const uint32_t ne1 = (uint32_t) ggml_nrows(dst);
kparams->ne0 = (int32_t) ne0;
kparams->ne1 = (int32_t) ne1;
@@ -306,7 +273,7 @@ static bool htp_flash_attn_is_hmx_eligible(
GGML_UNUSED(sinks);
- if (opt_fa_select > 2) {
+ if (opt_fa_select >= 4) {
return true;
}
@@ -322,7 +289,16 @@ static bool htp_flash_attn_is_hmx_eligible(
const uint32_t S = k->ne[1];
const uint32_t total_threads = n_hvx * htp_session_mdev_count(sess);
- if (DK > 256 || (DK == 256 && (DV > 256 || n_kv_heads < total_threads))) {
+ if (DK > 256 || DV > 256) {
+ return true;
+ }
+
+ // W8A8 HMX pads M=1 decode rows to 64, so HVX is much faster for Q8_0 KV decode.
+ if (k->type == GGML_TYPE_Q8_0 || v->type == GGML_TYPE_Q8_0) {
+ return false;
+ }
+
+ if (DK == 256 && n_kv_heads < total_threads) {
return true;
}
@@ -431,14 +407,33 @@ static bool htp_kparams_solve_flash_attn(
kparams->n_head_log2 = 1u << (uint32_t) std::floor(std::log2(n_head));
kparams->m0 = std::pow(2.0f, -(max_bias) / kparams->n_head_log2);
kparams->m1 = std::pow(2.0f, -(max_bias / 2.0f) / kparams->n_head_log2);
+ kparams->broadcast_rk2 = init_fastdiv_values(q->ne[2] / k->ne[2]);
+ kparams->broadcast_rk3 = init_fastdiv_values(q->ne[3] / k->ne[3]);
+ kparams->broadcast_rv2 = init_fastdiv_values(q->ne[2] / v->ne[2]);
+ kparams->broadcast_rv3 = init_fastdiv_values(q->ne[3] / v->ne[3]);
if (htp_flash_attn_is_hmx_eligible(sess, q, k, v, sinks)) {
const uint32_t DK_pad = hex_round_up(DK, 64);
const uint32_t DV_pad = hex_round_up(DV, 64);
- size_t Br = 0, Bc = 0;
- int ret = hmx_fa_find_chunk_size(&Br, &Bc, G, DK_pad, DV_pad, neq1, nek1, vtcm_size, n_hvx, (q->type == GGML_TYPE_F32), sinks != nullptr, n_head, fa_team_size);
- if (ret == 0) {
- kparams->kernel_type = HTP_FA_KERNEL_HMX;
+ const bool use_w8a8 = (opt_fa_select >= 3 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0 &&
+ DK % 32 == 0 && DV % 32 == 0 && DK <= 768);
+ const bool has_mask = (mask != nullptr);
+ const bool mask_broadcast = (has_mask && mask->ne[2] == 1);
+
+ struct hmx_fa_layout_params lp = {};
+ lp.kernel_type = use_w8a8 ? HTP_FA_KERNEL_HMX_W8A8 : HTP_FA_KERNEL_HMX_F16;
+ lp.q_type = q->type;
+ lp.gqa_factor = G;
+ lp.DK = DK_pad;
+ lp.DV = DV_pad;
+ lp.n_hvx = n_hvx;
+ lp.n_heads = n_head;
+ lp.has_mask = has_mask;
+ lp.mask_broadcast = mask_broadcast;
+ lp.has_sinks = (sinks != nullptr);
+
+ if (hmx_fa_find_chunk_size(&lp, neq1, nek1, vtcm_size, fa_team_size) == 0) {
+ kparams->kernel_type = lp.kernel_type;
if (logit_softcap == 0.0f) {
kparams->scale = scale * (float) M_LOG2E;
kparams->logit_softcap = 0.0f;
@@ -446,15 +441,18 @@ static bool htp_kparams_solve_flash_attn(
kparams->scale = scale;
kparams->logit_softcap = logit_softcap * (float) M_LOG2E;
}
- kparams->Br = Br;
- kparams->Bc = Bc;
- kparams->n_kv_blocks = (nek1 + Bc - 1) / Bc;
- kparams->n_hvx = (kparams->n_kv_blocks >= 3 && n_hvx >= 2) ? n_hvx : 1;
- kparams->u.hmx.g_br = hex_align_up(G * Br, 32);
- kparams->u.hmx.pipeline = (kparams->n_kv_blocks >= 3 && n_hvx >= 2) ? 1 : 0;
- kparams->vtcm_size = hmx_fa_compute_vtcm_usage(G, DK_pad, DV_pad, Br, Bc, kparams->n_hvx, kparams->u.hmx.pipeline != 0, (q->type == GGML_TYPE_F32), sinks != nullptr, n_head);
- kparams->u.hmx.mask_broadcast = (mask != nullptr && mask->ne[2] == 1) ? 1 : 0;
- kparams->u.hmx.div_G = init_fastdiv_values(G);
+ kparams->Br = lp.Br;
+ kparams->Bc = lp.Bc;
+ kparams->n_kv_blocks = (nek1 + lp.Bc - 1) / lp.Bc;
+ kparams->n_hvx = (kparams->n_kv_blocks >= 3 && n_hvx >= 2) ? n_hvx : 1;
+ kparams->u.hmx.g_br = hex_align_up(G * lp.Br, use_w8a8 ? HMX_W8A8_ACT_TILE_N_ROWS : HMX_FP16_TILE_N_ROWS);
+ kparams->u.hmx.mask_broadcast = mask_broadcast ? 1 : 0;
+ // vtcm_mask_buf is single-buffered for non-broadcast masks, so disable block pipelining.
+ kparams->u.hmx.pipeline = (kparams->n_kv_blocks >= 3 && n_hvx >= 2 && (!has_mask || mask_broadcast)) ? 1 : 0;
+ lp.n_hvx = kparams->n_hvx;
+ lp.pipeline = (kparams->u.hmx.pipeline != 0);
+ kparams->vtcm_size = hmx_fa_compute_vtcm_usage(&lp);
+ kparams->u.hmx.div_G = init_fastdiv_values(G);
if (mask) {
kparams->src3_div2 = init_fastdiv_values(mask->ne[2]);
kparams->src3_div3 = init_fastdiv_values(mask->ne[3]);
@@ -469,11 +467,20 @@ static bool htp_kparams_solve_flash_attn(
kparams->n_kv_blocks = (k->ne[1] + 64 - 1) / 64;
kparams->n_hvx = n_hvx;
- const size_t size_q_row_padded = hex_round_up(q->ne[0] * ((q->type == GGML_TYPE_F32) ? 4 : 2), 128);
+ const size_t size_q_row_padded = hex_round_up(htp_tensor_get_row_size(q->type, q->ne[0]), 128);
const size_t size_k_row_padded = hex_round_up(k->ne[0] * 2, 128);
const size_t size_v_row_padded = hex_round_up(v->ne[0] * 2, 128);
- kparams->vtcm_size = hvx_fa_compute_vtcm_usage(DK, DV, (q->type == GGML_TYPE_F32), mask != nullptr, sinks != nullptr, n_head, n_hvx);
+ struct hvx_fa_layout_params hvx_lp = {};
+ hvx_lp.q_type = q->type;
+ hvx_lp.DK = DK;
+ hvx_lp.DV = DV;
+ hvx_lp.n_heads = n_head;
+ hvx_lp.n_hvx = n_hvx;
+ hvx_lp.has_mask = (mask != nullptr);
+ hvx_lp.has_sinks = (sinks != nullptr);
+
+ kparams->vtcm_size = hvx_fa_compute_vtcm_usage(&hvx_lp);
if ((size_t) kparams->vtcm_size > vtcm_size) {
HEX_VERBOSE("ggml-hex: skip flash_attn_ext because VTCM needed (%d) > budget (%zu)\n",
kparams->vtcm_size, vtcm_size);
@@ -500,6 +507,7 @@ static bool htp_kparams_solve_flash_attn(
static bool htp_kparams_solve_gated_delta_net(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * op,
+ const struct ggml_tensor * dst_cache,
struct htp_gdn_kernel_params * kparams
) {
if (opt_gdn_select < 1) {
@@ -514,21 +522,33 @@ static bool htp_kparams_solve_gated_delta_net(
const struct ggml_tensor * g = op->src[3];
const struct ggml_tensor * beta = op->src[4];
const struct ggml_tensor * state = op->src[5];
- const struct ggml_tensor * pend_k = op->src[6];
+ const bool has_ids = op->src[6] != nullptr && op->src[7] == nullptr &&
+ (op->src[6]->type == GGML_TYPE_I32 || op->src[6]->type == GGML_TYPE_I64);
+ const struct ggml_tensor * ids = has_ids ? op->src[6] : nullptr;
+ const struct ggml_tensor * pend_k = has_ids ? nullptr : op->src[6];
const struct ggml_tensor * pend_v = op->src[7];
const struct ggml_tensor * pend_gb = op->src[8];
const struct ggml_tensor * n_rep = op->src[9];
- const struct ggml_tensor * dst = op;
+ const struct ggml_tensor * dst = op;
const bool replay = pend_k != nullptr;
- if (q->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || v->type != GGML_TYPE_F32 ||
- g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32 ||
- dst->type != GGML_TYPE_F32) {
+ auto is_act_type = [](ggml_type t) {
+ return t == GGML_TYPE_F32 || t == GGML_TYPE_F16;
+ };
+
+ if (!is_act_type(q->type) || !is_act_type(k->type) || !is_act_type(v->type) ||
+ g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32) {
+ return false;
+ }
+ if (dst_cache && (dst_cache->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst_cache))) {
+ return false;
+ }
+ if (dst->type != GGML_TYPE_F32 && !(dst_cache != nullptr && dst->type == GGML_TYPE_F16)) {
return false;
}
if (!ggml_is_contiguous_rows(q) || !ggml_is_contiguous_rows(k) || !ggml_is_contiguous_rows(v) ||
- !ggml_is_contiguous(g) || !ggml_is_contiguous(beta) || !ggml_is_contiguous(state) ||
+ !ggml_is_contiguous(g) || !ggml_is_contiguous(beta) || (!ids && !ggml_is_contiguous(state)) ||
!ggml_is_contiguous(dst)) {
return false;
}
@@ -550,11 +570,19 @@ static bool htp_kparams_solve_gated_delta_net(
if ((g->ne[0] != 1 && g->ne[0] != S_v) || beta->ne[0] != 1) {
return false;
}
- if (state->ne[0] != S_v || state->ne[1] != S_v || state->ne[2] != H || state->ne[3] != n_seqs) {
+ if (ids) {
+ if ((ids->type != GGML_TYPE_I32 && ids->type != GGML_TYPE_I64) ||
+ !ggml_is_contiguous_rows(ids) ||
+ ids->ne[0] < n_seqs || !ggml_is_vector(ids) ||
+ state->ne[0] != S_v * S_v * H || !ggml_is_contiguous_rows(state) ||
+ (state->nb[1] % sizeof(float)) != 0 || !ggml_is_matrix(state)) {
+ return false;
+ }
+ } else if (state->ne[0] != S_v || state->ne[1] != S_v || state->ne[2] != H || state->ne[3] != n_seqs) {
return false;
}
if (dst->ne[0] != S_v * H || dst->ne[1] != n_tokens * n_seqs + S_v * n_seqs * K ||
- dst->ne[2] != 1 || dst->ne[3] != 1) {
+ !ggml_is_matrix(dst)) {
return false;
}
if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) {
@@ -591,9 +619,8 @@ static bool htp_kparams_solve_gated_delta_net(
struct htp_gdn_vtcm_layout hvx_layout;
uint32_t n_heads_batch = 1;
- if (can_use_hmx && htp_gdn_hmx_solve_layout(&hmx_layout, (uint32_t) S_v, HTP_GDN_CHUNK_SIZE, total_rows, vtcm_size, n_hvx, true, &n_heads_batch)) {
+ if (can_use_hmx && htp_gdn_hmx_solve_layout(&hmx_layout, (uint32_t) S_v, HTP_GDN_CHUNK_SIZE, total_rows, vtcm_size, n_hvx, &n_heads_batch)) {
kparams->kernel_type = HTP_GDN_KERNEL_HMX_CHUNKED;
- kparams->pipeline = hmx_layout.pipeline ? 1 : 0;
kparams->chunk_size = HTP_GDN_CHUNK_SIZE;
kparams->n_chunks = ((uint32_t) n_tokens + HTP_GDN_CHUNK_SIZE - 1) / HTP_GDN_CHUNK_SIZE;
kparams->n_heads_batch = (uint16_t) n_heads_batch;
@@ -604,7 +631,6 @@ static bool htp_kparams_solve_gated_delta_net(
return false;
}
kparams->kernel_type = HTP_GDN_KERNEL_HVX_RECURRENT;
- kparams->pipeline = 0;
kparams->n_heads_batch = 1;
kparams->vtcm_size = (uint32_t) hvx_layout.total_bytes;
}
@@ -617,7 +643,7 @@ static bool htp_kparams_solve_gated_delta_net(
kparams->K = (uint32_t) K;
kparams->total_rows = total_rows;
kparams->kda = (g->ne[0] == S_v) ? 1 : 0;
- kparams->state_seq_stride = (uint32_t) (state->nb[3] / sizeof(float));
+ kparams->state_seq_stride = (uint32_t) ((ids ? state->nb[1] : state->nb[3]) / sizeof(float));
kparams->state_size_per_snap = (uint32_t) (S_v * S_v * H * n_seqs);
kparams->scale = 1.0f / sqrtf((float) S_v);
@@ -638,7 +664,7 @@ static bool htp_matmul_is_hmx_eligible(
) {
GGML_UNUSED(dst);
- if (src1->type != GGML_TYPE_F32 && (src1->type != GGML_TYPE_F16 || is_matmul_id)) {
+ if (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) {
return false;
}
@@ -668,7 +694,7 @@ static bool htp_matmul_is_hmx_eligible(
return false;
}
- if (src0->nb[0] > src0->nb[1] || src1->nb[0] > src1->nb[1]) {
+ if (ggml_is_transposed(src0) || ggml_is_transposed(src1)) {
return false;
}
@@ -680,10 +706,34 @@ static bool htp_matmul_is_hmx_eligible(
return true;
}
+// Post-GLU/gated projections (e.g. ffn_down, gated attn_output) have sharp channel outliers
+// that degrade W8A8 activation quantization; route them to FP16 HMX under MM_SELECT=3.
+static bool htp_mm_is_post_glu(const struct ggml_tensor * act) {
+ while (act && (act->op == GGML_OP_VIEW || act->op == GGML_OP_RESHAPE || act->op == GGML_OP_CONT || act->op == GGML_OP_CPY)) {
+ act = act->view_src ? act->view_src : act->src[0];
+ }
+ if (!act) {
+ return false;
+ }
+ if (act->op == GGML_OP_GLU) {
+ return true;
+ }
+ if (act->op == GGML_OP_MUL) {
+ const struct ggml_tensor * a0 = act->src[0];
+ const struct ggml_tensor * a1 = act->src[1];
+ if ((a0 && (a0->op == GGML_OP_UNARY || a0->op == GGML_OP_GLU)) ||
+ (a1 && (a1->op == GGML_OP_UNARY || a1->op == GGML_OP_GLU))) {
+ return true;
+ }
+ }
+ return false;
+}
+
static bool htp_kparams_solve_hmx_mm(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * act,
+ const struct ggml_tensor * bias,
const struct ggml_tensor * dst,
int wtype,
int ne00_padded,
@@ -694,28 +744,24 @@ static bool htp_kparams_solve_hmx_mm(
int ne11_padded,
bool is_matmul_id,
bool is_batched,
- size_t src2_size,
size_t vtcm_budget,
- struct htp_mm_kernel_params * kparams
+ struct htp_mm_kernel_params * kparams,
+ bool is_glu = false
) {
+ const bool bias_is_2d = bias && (bias->ne[1] > 1);
+ const bool bias_batched = bias && (bias->ne[2] > 1 || bias->ne[3] > 1);
const bool is_tiled = ggml_hexagon_tensor_will_tile(src0);
const int aligned_tile_size = is_tiled ? htp_tensor_get_tile_padded_size(wtype) : 0;
const int n_hvx = (int) htp_session_n_hvx(sess);
const uint32_t mdev_count = htp_session_mdev_count(sess);
- const int ne10 = act->ne[0];
int m_for_solver = ne11;
int m_for_solver_padded = ne11_padded;
if (!is_matmul_id && mdev_count > 1 && ((uint32_t) ne11 >= mdev_count)) {
- const uint32_t rows_per_chunk = dst ? htp_mdev_rows_per_chunk(dst) : 1;
- const uint32_t total_chunks = rows_per_chunk ? ((uint32_t) ne11 / rows_per_chunk) : 0;
- if (total_chunks >= mdev_count) {
- const uint32_t chunks_per_mdev = (total_chunks + mdev_count - 1) / mdev_count;
- const uint32_t m_dev0 = chunks_per_mdev * rows_per_chunk;
- const uint32_t m_last = (uint32_t) ne11 > (mdev_count - 1) * m_dev0 ? (uint32_t) ne11 - (mdev_count - 1) * m_dev0 : 0;
- m_for_solver = (int) std::max(m_dev0, m_last);
- m_for_solver_padded = hex_round_up(std::max(m_for_solver, 32), 32);
- }
+ const uint32_t m_dev0 = ((uint32_t) ne11 + mdev_count - 1) / mdev_count;
+ const uint32_t m_last = (uint32_t) ne11 > (mdev_count - 1) * m_dev0 ? (uint32_t) ne11 - (mdev_count - 1) * m_dev0 : 0;
+ m_for_solver = (int) std::max(m_dev0, m_last);
+ m_for_solver_padded = hex_round_up(std::max(m_for_solver, 32), 32);
}
const bool pipeline = is_matmul_id ? false : htp_mm_hmx_pipeline(m_for_solver);
const bool is_batched_val = is_matmul_id ? false : is_batched;
@@ -727,30 +773,79 @@ static bool htp_kparams_solve_hmx_mm(
bool use_grouped = false;
int act_hvx_selected = 0;
- if (is_batched_val && wtype == GGML_TYPE_F16 && !is_tiled && group_size > 1) {
- if (htp_mm_hmx_solve_batched_params(wtype, ne00_padded, ne01_padded, m_for_solver, group_size, n_hvx, pipeline, src2_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
+ const uint8_t fp16_kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_BATCHED : HTP_MM_KERNEL_HMX_2D;
+ uint8_t kernel_type = fp16_kernel_type;
+ const uint32_t min_k = htp_int_hmx_min_k((int) wtype);
+ const bool allow_w8a8 = (opt_mm_select >= 4) ||
+ (opt_mm_select == 3 && !htp_mm_is_post_glu(act) &&
+ (!dst || ggml_prec_get_acc(dst) != GGML_PREC_F32));
+ if (is_tiled && htp_is_int_hmx_weight_type((int) wtype) && allow_w8a8 &&
+ ne00_padded >= (int) min_k && (ne00_padded % min_k) == 0) {
+ kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_W8A8_BATCHED : HTP_MM_KERNEL_HMX_W8A8_2D;
+ }
+
+ if (is_glu && !htp_mm_kernel_is_hmx_2d(kernel_type)) {
+ return false;
+ }
+
+ size_t bias_size = bias ? hex_round_up(ggml_nbytes(bias), 128) : 0;
+ const size_t res_out_elem_size = dst ? ggml_type_size(dst->type) : sizeof(float);
+ if (!is_glu && is_batched_val && wtype == GGML_TYPE_F16 && !is_tiled && group_size > 1 && !bias_batched) {
+ if (htp_mm_hmx_solve_batched_params(wtype, ne00_padded, ne01_padded, m_for_solver, group_size, n_hvx, pipeline, bias_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
use_grouped = true;
}
}
if (!use_grouped) {
+ // HMX 2D DMA-writes output slices per (mc, nc) chunk and streams 2D residual slices when pipelined.
+ const size_t res_in_elem_size = (pipeline && !is_matmul_id && bias_is_2d) ? ggml_type_size(bias->type) : 0;
+ if (res_in_elem_size > 0) {
+ bias_size = 0;
+ }
+
int m_id_rows = 0;
if (dst && is_matmul_id) {
const int n_experts = ne02 > 0 ? ne02 : 1;
const size_t total_expert_rows = (size_t) dst->ne[1] * dst->ne[2];
int m_per_expert = (int) ((total_expert_rows + n_experts - 1) / n_experts);
- if (mdev_count > 1 && htp_can_row_partition(dst)) {
+ if (mdev_count > 1) {
m_per_expert = (m_per_expert + (int) mdev_count - 1) / (int) mdev_count;
}
m_id_rows = hex_round_up(std::max(m_per_expert, 32), 32);
}
const uint32_t cost_m = is_matmul_id ? (uint32_t) m_id_rows : (uint32_t) m_for_solver;
- if (!htp_mm_hmx_solve_2d_params(wtype, ne00_padded, m_id_rows, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, is_matmul_id, aligned_tile_size, src2_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
- return false;
+ // Non-grouped HMX_BATCHED dispatches to hmx_mm_2d_f32 (full 2D layout, not grouped-batched layout).
+ const uint8_t solve_ktype = htp_mm_kernel_is_hmx_int(kernel_type) ? kernel_type : HTP_MM_KERNEL_HMX_2D;
+ if (is_glu) {
+ if (!htp_mm_hmx_solve_2d_params_glu(solve_ktype, wtype, ne00_padded, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, aligned_tile_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
+ if (htp_mm_kernel_is_hmx_int(kernel_type)) {
+ kernel_type = HTP_MM_KERNEL_HMX_2D;
+ if (!htp_mm_hmx_solve_2d_params_glu(HTP_MM_KERNEL_HMX_2D, wtype, ne00_padded, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, aligned_tile_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ } else if (!htp_mm_hmx_solve_2d_params_ex(solve_ktype, wtype, ne00_padded, m_id_rows, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
+ if (htp_mm_kernel_is_hmx_int(kernel_type)) {
+ kernel_type = fp16_kernel_type;
+ if (!htp_mm_hmx_solve_2d_params_ex(HTP_MM_KERNEL_HMX_2D, wtype, ne00_padded, m_id_rows, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
+ return false;
+ }
+ } else {
+ return false;
+ }
}
}
+ const uint32_t hmx_n_groups = htp_mm_kernel_is_hmx_int(kernel_type)
+ ? (((uint32_t) ne00_padded + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP)
+ : 1u;
+ const uint32_t n_k_tiles = std::max(1, ne00_padded / 32);
+
kparams->n_hmx = 1;
+ kparams->hmx_n_groups = (int32_t) hmx_n_groups;
kparams->pipeline = pipeline ? 1 : 0;
kparams->m_chunk = m_chunk;
kparams->n_chunk = n_chunk;
@@ -758,12 +853,13 @@ static bool htp_kparams_solve_hmx_mm(
kparams->n_act_hvx = act_hvx_selected;
kparams->tile_size = is_tiled ? htp_tensor_get_tile_size(wtype) : 0;
kparams->aligned_tile_size = aligned_tile_size;
- kparams->act_row_size = htp_mm_tiled_act_row_size(wtype, ne10);
kparams->vtcm_size = vtcm_size;
kparams->div_n_act_hvx = init_fastdiv_values(act_hvx_selected);
kparams->div_ne00_padded = init_fastdiv_values(ne00_padded);
- kparams->vtcm_bias_size = (int32_t) src2_size;
- kparams->kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_BATCHED : HTP_MM_KERNEL_HMX_2D;
+ kparams->div_hmx_n_groups = init_fastdiv_values(hmx_n_groups);
+ kparams->div_n_k_tiles = init_fastdiv_values(n_k_tiles);
+ kparams->vtcm_bias_size = (int32_t) bias_size;
+ kparams->kernel_type = kernel_type;
return true;
}
@@ -781,7 +877,7 @@ static void htp_kparams_solve_hvx_mm(
int ne12,
int ne13,
bool is_matmul_id,
- const size_t src2_row_size,
+ const size_t bias_row_size,
size_t vtcm_budget,
struct htp_mm_kernel_params * kparams
) {
@@ -798,6 +894,8 @@ static void htp_kparams_solve_hvx_mm(
GGML_UNUSED(ne03);
const int src1_nrows = ne11 * ne12 * ne13;
+ const size_t act_elem_size = ggml_type_size(src1->type);
+ const size_t dst_row_size = dst ? (size_t) dst->ne[0] * sizeof(float) : 0;
if (is_tiled) {
kparams->tile_size = htp_tensor_get_tile_size(wtype);
@@ -816,7 +914,7 @@ static void htp_kparams_solve_hvx_mm(
for (uint32_t d = max_prefetch; d >= 2; d /= 2) {
htp_mm_hvx_vtcm_layout_build(
&L, kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx,
- 0, src0->nb[1], kparams->act_row_size, 0, d, true, false
+ dst_row_size, src0->nb[1], act_elem_size, 0, d, true, false
);
if (L.total_bytes <= vtcm_budget) {
best_n_prefetch = d;
@@ -843,7 +941,7 @@ static void htp_kparams_solve_hvx_mm(
for (uint32_t d = max_prefetch; d >= 2; d /= 2) {
htp_mm_hvx_vtcm_layout_build(
&L, kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx,
- dst->nb[1], src0->nb[1], src1->nb[1], src2_row_size, d, false, false
+ dst_row_size, src0->nb[1], act_elem_size, bias_row_size, d, false, false
);
if (L.total_bytes <= vtcm_budget) {
best_n_prefetch = d;
@@ -854,7 +952,7 @@ static void htp_kparams_solve_hvx_mm(
uint32_t m_chunk = 0;
if (htp_mm_hvx_solve_vtcm_params(
kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx,
- dst->nb[1], src0->nb[1], src1->nb[1], src2_row_size, best_n_prefetch, vtcm_budget,
+ dst_row_size, src0->nb[1], act_elem_size, bias_row_size, best_n_prefetch, vtcm_budget,
&L, &m_chunk)) {
kparams->n_prefetch = best_n_prefetch;
kparams->m_chunk = (m_chunk < (uint32_t) src1_nrows) ? m_chunk : 0;
@@ -884,7 +982,7 @@ static void htp_kparams_solve_hvx_mm(
uint32_t m_chunk = 0;
if (htp_mm_hvx_solve_vtcm_params(
ktype, wtype, ne10, src1_nrows, n_hvx,
- dst->nb[1], src0->nb[1], src1->nb[1], src2_row_size, 16, vtcm_budget,
+ dst_row_size, src0->nb[1], act_elem_size, bias_row_size, 16, vtcm_budget,
&L, &m_chunk)) {
kparams->kernel_type = ktype;
kparams->m_chunk = (m_chunk < (uint32_t) src1_nrows) ? m_chunk : 0;
@@ -903,9 +1001,8 @@ static bool htp_kparams_solve_matmul_impl(
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,
- const size_t src2_row_size,
- const size_t src2_size,
struct htp_mm_kernel_params * kparams
) {
memset(kparams, 0, sizeof(*kparams));
@@ -932,12 +1029,12 @@ static bool htp_kparams_solve_matmul_impl(
const bool hmx_enabled = (htp_session_n_hmx(sess) > 0) && (opt_mm_select >= 2);
if (hmx_enabled && htp_matmul_is_hmx_eligible(src0, src1, dst, is_matmul_id, is_batched)) {
- if (htp_kparams_solve_hmx_mm(sess, src0, src1, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, is_matmul_id, is_batched, src2_size, vtcm_budget, kparams)) {
+ if (htp_kparams_solve_hmx_mm(sess, src0, src1, bias, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, is_matmul_id, is_batched, vtcm_budget, kparams)) {
goto finalize;
}
}
- htp_kparams_solve_hvx_mm(sess, src0, src1, dst, wtype, is_tiled, ne02, ne03, ne10, ne11, ne12, ne13, is_matmul_id, src2_row_size, vtcm_budget, kparams);
+ htp_kparams_solve_hvx_mm(sess, src0, src1, dst, wtype, is_tiled, ne02, ne03, ne10, ne11, ne12, ne13, is_matmul_id, bias ? bias->nb[1] : 0, vtcm_budget, kparams);
finalize:
kparams->div_ne12_ne1 = init_fastdiv_values(ne12 * ne11);
@@ -961,7 +1058,7 @@ static bool htp_matmul_check_types(
) {
const bool is_matmul_id = (dst->op == GGML_OP_MUL_MAT_ID);
- if (dst->type != GGML_TYPE_F32) {
+ if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) {
return false;
}
@@ -971,7 +1068,8 @@ static bool htp_matmul_check_types(
if (is_matmul_id) {
const struct ggml_tensor * src2 = dst->src[2];
- if (src1->type != GGML_TYPE_F32 || !src2 || src2->type != GGML_TYPE_I32) {
+ const bool src1_ok = (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
+ if (!src1_ok || !src2 || src2->type != GGML_TYPE_I32) {
return false;
}
switch (src0->type) {
@@ -1043,11 +1141,6 @@ static bool htp_matmul_check_types(
return src0->ne[0] % ggml_blck_size(src0->type) == 0;
case GGML_TYPE_F32:
- if (src1->type != GGML_TYPE_F32) {
- return false;
- }
- return src0->nb[1] >= src0->nb[0];
-
case GGML_TYPE_F16:
case GGML_TYPE_BF16:
return src0->nb[1] >= src0->nb[0];
@@ -1072,59 +1165,36 @@ static bool htp_kparams_solve_matmul(
if (htp_matmul_can_collapse(src0, src1, dst)) {
const ggml_tensor src1_collapsed = htp_tensor_collapse_rows(src1);
const ggml_tensor dst_collapsed = htp_tensor_collapse_rows(dst);
- return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, &dst_collapsed, 0, 0, kparams);
+ return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, nullptr, &dst_collapsed, kparams);
}
- return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, 0, 0, kparams);
-}
-
-bool htp_matmul_add_can_collapse(
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * src2,
- const struct ggml_tensor * dst
-) {
- if (!htp_matmul_can_collapse(src0, src1, dst)) {
- return false;
- }
- if (!src2) {
- return true;
- }
- const int64_t src2_nrows = src2->ne[1] * src2->ne[2] * src2->ne[3];
- if (src2_nrows == 1) {
- return true;
- }
- size_t s2;
- return src2->nb[0] == ggml_type_size(src2->type) &&
- ggml_are_same_shape(src2, dst) &&
- htp_rows_stride(src2->ne, src2->nb, &s2);
+ return htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, 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 * src2,
+ const struct ggml_tensor * bias,
const struct ggml_tensor * dst,
struct htp_mm_kernel_params * kparams
) {
- if (htp_matmul_add_can_collapse(src0, src1, src2, dst)) {
+ if (htp_matmul_add_can_collapse(src0, src1, bias, dst)) {
const ggml_tensor src1_collapsed = htp_tensor_collapse_rows(src1);
const ggml_tensor dst_collapsed = htp_tensor_collapse_rows(dst);
- const ggml_tensor src2_collapsed = (src2 && (src2->ne[1] * src2->ne[2] * src2->ne[3] > 1))
- ? htp_tensor_collapse_rows(src2)
- : (src2 ? *src2 : ggml_tensor{});
- const struct ggml_tensor * p_src2 = src2 ? &src2_collapsed : nullptr;
- const size_t src2_size = p_src2 ? hex_round_up(ggml_nbytes(p_src2), 128) : 0;
- return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, &dst_collapsed, p_src2 ? p_src2->nb[1] : 0, src2_size, kparams);
- }
- const size_t src2_size = src2 ? hex_round_up(ggml_nbytes(src2), 128) : 0;
- return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, src2 ? src2->nb[1] : 0, src2_size, kparams);
+ const ggml_tensor bias_collapsed = (bias && (ggml_nrows(bias) > 1))
+ ? htp_tensor_collapse_rows(bias)
+ : (bias ? *bias : ggml_tensor{});
+ const struct ggml_tensor * p_bias = bias ? &bias_collapsed : nullptr;
+ return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, p_bias, &dst_collapsed, kparams);
+ }
+ return htp_kparams_solve_matmul_impl(sess, src0, src1, bias, dst, 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
) {
@@ -1147,36 +1217,40 @@ bool htp_kparams_solve_mmnx(
const bool is_tiled = ggml_hexagon_tensor_will_tile(src0);
const int wtype = (is_tiled && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : src0->type;
- const int ne00_padded = is_tiled ? hex_round_up(ne00, 32) : ne00;
+ const int ne00_padded = is_tiled ? hex_round_up(ne00, htp_tensor_get_tile_k(wtype)) : ne00;
const int ne11_padded = hex_round_up(ne11, 32);
const int ne01_tiled = hex_round_up(ne01, 32);
const bool is_batched = (ne02 * ne03 > 1 || ne12 * ne13 > 1);
const bool hmx_enabled = (n_hmx > 0) && (opt_mm_select >= 2);
- if (hmx_enabled && htp_matmul_is_hmx_eligible(src0, act, nullptr, false, is_batched)) {
- if (htp_kparams_solve_hmx_mm(sess, src0, act, nullptr, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, false, is_batched, 0, vtcm_budget, kparams)) {
+ if (hmx_enabled && htp_matmul_is_hmx_eligible(src0, act, dst, false, is_batched)) {
+ if (htp_kparams_solve_hmx_mm(sess, src0, act, nullptr, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, false, is_batched, vtcm_budget, kparams)) {
kparams->n_weights = n_weights;
goto finalize;
}
}
- if (!is_tiled || act->type != GGML_TYPE_F32 || ne10 % 32 != 0) {
+ if (!is_tiled || (act->type != GGML_TYPE_F32 && act->type != GGML_TYPE_F16) || ne10 % 32 != 0) {
kparams->kernel_type = HTP_MM_KERNEL_UNSUPPORTED;
return false;
}
{
- const int act_nrows = ne11 * ne12 * ne13;
- const size_t act_row_size = htp_mm_tiled_act_row_size(wtype, ne10);
- const size_t src0_row_size = src0->nb[1];
+ const int act_nrows = ne11 * ne12 * ne13;
+ const int32_t hvx_ktype = (act_nrows < (int) n_hvx)
+ ? HTP_MM_KERNEL_HVX_QUANT_BLOCK : HTP_MM_KERNEL_HVX_QUANT_ROW;
+ const size_t act_row_size = htp_mm_tiled_act_row_size(wtype, ne10);
+ const size_t act_elem_size = ggml_type_size(act->type);
+ const size_t src0_row_size = src0->nb[1];
+ const size_t dst_row_size = (size_t) src0->ne[1] * sizeof(float);
const uint32_t max_prefetch = (act_nrows > HTP_MM_HMX_MIN_NROWS) ? 2 : 16;
uint32_t best_n_prefetch = 2;
for (uint32_t d = max_prefetch; d >= 2; d /= 2) {
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(
- &L, HTP_MM_KERNEL_HVX_QUANT_ROW, wtype, ne10, act_nrows, n_hvx,
- 0, src0_row_size, act_row_size, 0, d, false, true
+ &L, hvx_ktype, wtype, ne10, act_nrows, n_hvx,
+ dst_row_size, src0_row_size, act_elem_size, 0, d, false, true
);
if (L.total_bytes <= vtcm_budget) {
best_n_prefetch = d;
@@ -1186,12 +1260,12 @@ bool htp_kparams_solve_mmnx(
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(
- &L, HTP_MM_KERNEL_HVX_QUANT_ROW, wtype, ne10, act_nrows, n_hvx,
- 0, src0_row_size, act_row_size, 0, best_n_prefetch, false, true
+ &L, hvx_ktype, wtype, ne10, act_nrows, n_hvx,
+ dst_row_size, src0_row_size, act_elem_size, 0, best_n_prefetch, false, true
);
if (opt_mm_select >= 1 && L.total_bytes <= vtcm_budget) {
- kparams->kernel_type = HTP_MM_KERNEL_HVX_QUANT_ROW;
+ kparams->kernel_type = hvx_ktype;
kparams->tile_size = htp_tensor_get_tile_size(wtype);
kparams->aligned_tile_size = htp_tensor_get_tile_padded_size(wtype);
kparams->act_row_size = act_row_size;
@@ -1214,6 +1288,67 @@ finalize:
return (size_t) kparams->vtcm_size <= vtcm_budget;
}
+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
+) {
+ if (htp_session_n_hmx(sess) == 0 || opt_mm_select < 2) {
+ return false;
+ }
+ if (w_gate->type != w_up->type || w_gate->ne[0] != w_up->ne[0] || w_gate->ne[1] != w_up->ne[1] ||
+ !ggml_is_matrix(w_gate) || !ggml_is_matrix(w_up) ||
+ !ggml_is_contiguous(w_up) || w_gate->nb[1] != w_up->nb[1] ||
+ ggml_hexagon_tensor_will_tile(w_gate) != ggml_hexagon_tensor_will_tile(w_up)) {
+ return false;
+ }
+ if (!htp_matmul_check_types(w_gate, act, dst) || !htp_matmul_check_types(w_up, act, dst)) {
+ return false;
+ }
+
+ const size_t vtcm_budget = htp_session_vtcm_size(sess);
+ memset(kparams, 0, sizeof(*kparams));
+ kparams->n_hvx = htp_session_n_hvx(sess);
+
+ const int ne00 = w_gate->ne[0];
+ const int ne01 = w_gate->ne[1];
+ const int ne02 = w_gate->ne[2];
+ const int ne03 = w_gate->ne[3];
+ const int ne11 = act->ne[1];
+ const int ne12 = act->ne[2];
+ const int ne13 = act->ne[3];
+
+ const bool is_tiled = ggml_hexagon_tensor_will_tile(w_gate);
+ const int wtype = (is_tiled && (w_gate->type == GGML_TYPE_F32 || w_gate->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : w_gate->type;
+ const int tile_k = htp_tensor_get_tile_k(wtype);
+ const int ne00_padded = is_tiled ? hex_round_up(ne00, tile_k) : ne00;
+ const int ne11_padded = hex_round_up(ne11, 32);
+ const int ne01_tiled = hex_round_up(ne01, 32);
+ const bool is_batched = (ne02 * ne03 > 1 || ne12 * ne13 > 1);
+
+ const bool k_ok = is_tiled ? (tile_k > 0 && (ne00 % tile_k) == 0) : ((ne00 & 31) == 0);
+ if (is_batched || !k_ok ||
+ !htp_matmul_is_hmx_eligible(w_gate, act, dst, false, false)) {
+ return false;
+ }
+ if (!htp_kparams_solve_hmx_mm(sess, w_gate, act, nullptr, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, false, false, vtcm_budget, kparams, /*is_glu=*/ true)) {
+ return false;
+ }
+
+ kparams->n_weights = 2;
+ kparams->glu_op = glu_op;
+ kparams->div_ne12_ne1 = init_fastdiv_values(ne12 * ne11);
+ kparams->div_ne1 = init_fastdiv_values(ne11);
+ kparams->div_r2 = init_fastdiv_values(ne02 > 0 ? ne12 / ne02 : 1);
+ kparams->div_r3 = init_fastdiv_values(ne03 > 0 ? ne13 / ne03 : 1);
+ kparams->div_ne12 = init_fastdiv_values(ne12);
+ return kparams->n_hmx == 1 && htp_mm_kernel_is_hmx_2d(kparams->kernel_type) && (size_t) kparams->vtcm_size <= vtcm_budget;
+}
+
bool htp_kparams_solve_mmidnx(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
@@ -1222,7 +1357,7 @@ bool htp_kparams_solve_mmidnx(
int32_t n_weights,
struct htp_mm_kernel_params * kparams
) {
- const bool ok = htp_kparams_solve_matmul_impl(sess, src0, act, dst, 0, 0, kparams);
+ const bool ok = htp_kparams_solve_matmul_impl(sess, src0, act, nullptr, dst, kparams);
kparams->n_weights = n_weights;
return ok;
}
@@ -1240,12 +1375,15 @@ static bool htp_kparams_solve_binary(
const struct ggml_tensor * src2 = (op == HTP_OP_ADD_ID) ? op_tensor->src[2] : nullptr;
const struct ggml_tensor * dst = op_tensor;
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
+ return false;
+ }
+
const bool is_add_id = (op == HTP_OP_ADD_ID);
if (is_add_id) {
- if (!src2) {
- return false;
- }
- if (src0->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src2->type != GGML_TYPE_I32) {
+ if (src2->type != GGML_TYPE_I32) {
return false;
}
if (!ggml_are_same_shape(src0, dst)) {
@@ -1257,24 +1395,24 @@ static bool htp_kparams_solve_binary(
if (src2->ne[0] != src0->ne[1] || src2->ne[1] != src0->ne[2]) {
return false;
}
- if (src0->nb[0] != sizeof(float) || src1->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float) || src2->nb[0] != sizeof(int32_t)) {
+ if (!ggml_is_contiguous_rows(src0) || !ggml_is_contiguous_rows(src1) ||
+ !ggml_is_contiguous_rows(dst) || !ggml_is_contiguous_rows(src2)) {
return false;
}
if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) {
return false;
}
- if (src2->nb[1] < src2->ne[0] * sizeof(int32_t)) {
+ if (src2->nb[1] < ggml_row_size(src2->type, src2->ne[0])) {
return false;
}
} else {
- if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
- src1->type != src0->type || dst->type != src0->type) {
+ if (ggml_is_permuted(src0) || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) {
return false;
}
- if (ggml_is_permuted(src0) || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) {
+ if (!ggml_can_repeat(src1, src0)) {
return false;
}
- if (!ggml_can_repeat(src1, src0) || ggml_is_permuted(src1)) {
+ if (!ggml_is_contiguous_rows(src1) && !ggml_is_permuted(src1)) {
return false;
}
}
@@ -1282,25 +1420,32 @@ static bool htp_kparams_solve_binary(
const uint32_t max_hvx_sess = htp_session_n_hvx(sess);
const size_t vtcm_size = htp_session_vtcm_size(sess);
- const size_t elem_size = ggml_type_size(src0->type);
- const size_t src0_row_size = src0->ne[0] * elem_size;
- const size_t src1_row_size = src1->ne[0] * elem_size;
- const size_t dst_row_size = dst->ne[0] * elem_size;
+ const size_t src0_elem_size = ggml_type_size(src0->type);
+ const size_t src1_elem_size = ggml_type_size(src1->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
+ const size_t src0_row_size = src0->ne[0] * src0_elem_size;
+ const size_t src1_row_size = src1->ne[0] * src1_elem_size;
+ const size_t dst_row_size = dst->ne[0] * dst_elem_size;
const size_t src0_row_size_aligned = hex_round_up(src0_row_size, 128);
const size_t src1_row_size_aligned = hex_round_up(src1_row_size, 128);
const size_t dst_row_size_aligned = hex_round_up(dst_row_size, 128);
- if (!htp_binary_strides_safe(src0, src1, dst, elem_size)) {
+ if (!htp_binary_strides_safe(src0, src1, dst, src0_elem_size, src1_elem_size, dst_elem_size)) {
return false;
}
+ 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;
+
const bool is_scalar = !is_add_id && src1->ne[0] == 1;
const bool is_row_bcast = !is_add_id && !is_scalar &&
src1->ne[0] == src0->ne[0] &&
- (src0->ne[1] > 1 || src0->ne[2] > 1 || src0->ne[3] > 1) &&
- src1->ne[1] == 1 && src1->ne[2] == 1 && src1->ne[3] == 1;
+ ggml_nrows(src0) > 1 &&
+ ggml_is_vector(src1);
const bool is_same_shape = !is_add_id && !is_scalar &&
+ src1->nb[0] == src1_elem_size &&
src1->ne[0] == src0->ne[0] &&
src1->ne[1] == src0->ne[1] &&
(src1->ne[2] == src0->ne[2] || src1->ne[2] == 1) &&
@@ -1310,35 +1455,13 @@ static bool htp_kparams_solve_binary(
const bool is_scalar_broadcast = !is_add_id && (ggml_nelements(src1) == 1);
if (!is_add_id && is_contig && (ggml_are_same_shape(src0, src1) || is_scalar_broadcast)) {
- const uint32_t total_elems = (uint32_t) ggml_nelements(src0);
- const uint32_t max_chunk_elems = 32768 / elem_size;
- const uint32_t min_chunk_elems = 256;
- const uint32_t target_chunk_elems = hex_round_up((total_elems + (2 * max_hvx_sess) - 1) / (2 * max_hvx_sess), 32);
- const uint32_t chunk_size = (std::min)(max_chunk_elems, (std::max)(target_chunk_elems, min_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) ? (std::min)(max_hvx_sess, total_chunks) : 1;
-
- kparams->kernel_type = HTP_BINARY_KERNEL_CHUNKED;
- kparams->n_hvx = n_hvx;
- kparams->n_srcs = 2;
- kparams->rows_per_buffer = 1;
kparams->src0_row_size_aligned = src0_row_size_aligned;
- kparams->src1_row_size_aligned = is_scalar_broadcast ? 0 : src1_row_size_aligned;
+ kparams->src1_row_size_aligned = src1_row_size_aligned;
kparams->dst_row_size_aligned = dst_row_size_aligned;
- kparams->src1_size = 0;
- kparams->chunk_size = chunk_size;
- kparams->chunk_bytes = chunk_bytes;
- kparams->is_scalar = is_scalar_broadcast ? 1 : 0;
-
struct htp_binary_vtcm_layout L;
- htp_binary_vtcm_layout_build(&L, kparams, vtcm_size);
- if (L.total_bytes == 0 || L.total_bytes > vtcm_size) {
- return false;
- }
-
- kparams->vtcm_size = L.total_bytes;
- return true;
+ return htp_binary_solve_chunked(&L, kparams, (uint32_t) ggml_nelements(src0),
+ (uint32_t) src0_elem_size, (uint32_t) src1_elem_size, (uint32_t) dst_elem_size,
+ max_hvx_sess, 2, is_scalar_broadcast, vtcm_size);
}
enum htp_binary_kernel_type kernel_type;
@@ -1354,9 +1477,10 @@ static bool htp_kparams_solve_binary(
}
} else if (is_row_bcast) {
kernel_type = HTP_BINARY_KERNEL_ROW_BCAST;
- src1_size = src1_row_size_aligned;
+ src1_size = hex_round_up(src1->ne[0] * ((src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) ? sizeof(ggml_fp16_t) : sizeof(float)), 128);
+ kparams->src1_strided = src1->nb[0] != src1_elem_size ? 1 : 0;
} else if (is_scalar) {
- src1_size = hex_round_up(ggml_nelements(src1) * elem_size, 128);
+ src1_size = hex_round_up(ggml_nelements(src1) * ((src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) ? sizeof(ggml_fp16_t) : sizeof(float)), 128);
if (src1_size > vtcm_size) {
return false;
}
@@ -1365,14 +1489,14 @@ static bool htp_kparams_solve_binary(
} else if (is_same_shape) {
kernel_type = HTP_BINARY_KERNEL_SAME_SHAPE;
} else if (is_complex) {
- src1_size = hex_round_up(ggml_nelements(src1) * elem_size + 128, 128);
+ src1_size = hex_round_up(ggml_nelements(src1) * src1_elem_size + 128, 128);
if (src1_size > vtcm_size) {
return false;
}
kernel_type = HTP_BINARY_KERNEL_COMPLEX;
kparams->src1_strided = !ggml_is_contiguous(src1) ? 1 : 0;
} else {
- src1_size = hex_round_up(ggml_nelements(src1) * elem_size + 128, 128);
+ src1_size = hex_round_up(ggml_nelements(src1) * src1_elem_size + 128, 128);
if (src1_size > vtcm_size) {
return false;
}
@@ -1380,7 +1504,7 @@ static bool htp_kparams_solve_binary(
kparams->src1_strided = !ggml_is_contiguous(src1) ? 1 : 0;
}
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const uint32_t src0_nrows = ggml_nrows(src0);
const uint32_t min_rows_per_hvx = (uint32_t) (std::max<size_t>(1, (128 + dst_row_size - 1) / dst_row_size));
const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx);
@@ -1437,7 +1561,8 @@ static bool htp_kparams_solve_binary(
if (L.rows_per_buffer == 0 || L.total_bytes > vtcm_size) {
if (!is_add_id && is_contig && (ggml_are_same_shape(src0, src1) || is_scalar_broadcast)) {
const uint32_t total_elems = (uint32_t) ggml_nelements(src0);
- return htp_binary_solve_chunked(&L, kparams, total_elems, (uint32_t) elem_size,
+ return htp_binary_solve_chunked(&L, kparams, total_elems,
+ (uint32_t) src0_elem_size, (uint32_t) src1_elem_size, (uint32_t) dst_elem_size,
max_hvx_sess, 2, is_scalar_broadcast, vtcm_size);
}
return false;
@@ -1449,106 +1574,106 @@ static bool htp_kparams_solve_binary(
return true;
}
-// collapse contiguous dims of elementwise ops so that rows fill at least one HVX vector
-static void htp_collapse_dims(struct ggml_tensor ** tensors, size_t n_tensors, size_t elem_size, uint32_t n_hvx) {
- if (n_tensors == 0 || !tensors[0]) {
- return;
- }
- for (size_t t = 0; t < n_tensors; t++) {
- if (!tensors[t] || tensors[t]->nb[0] != elem_size) {
- return;
- }
- if (t > 0 && !ggml_are_same_shape(tensors[0], tensors[t])) {
- return;
- }
+static bool htp_kparams_solve_binary_nx(
+ const struct ggml_hexagon_session * sess,
+ const htp_opnode & node,
+ struct htp_binary_kernel_params * kparams
+) {
+ const uint32_t n_srcs = (uint32_t) node.inputs.size();
+ if (n_srcs <= 2 || n_srcs > HTP_OP_MAX_INPUTS || node.outputs.size() != 1) {
+ return false;
}
- struct ggml_tensor * t0 = tensors[0];
+ const struct ggml_tensor * src0 = node.inputs[0];
+ const struct ggml_tensor * src1 = node.inputs[1];
+ const struct ggml_tensor * dst = node.outputs[0];
- while (t0->ne[1] > 1 || t0->ne[2] > 1 || t0->ne[3] > 1) {
- const size_t row_size = (size_t) t0->ne[0] * elem_size;
- bool rows_contig = true;
- for (size_t t = 0; t < n_tensors; t++) {
- if (tensors[t]->nb[1] != (size_t) tensors[t]->ne[0] * elem_size) {
- rows_contig = false;
- break;
- }
- }
- bool all_ne1_one = true;
- for (size_t t = 0; t < n_tensors; t++) {
- if (tensors[t]->ne[1] != 1) {
- all_ne1_one = false;
- break;
- }
- }
- const bool can_merge = all_ne1_one ||
- (rows_contig && (t0->ne[0] == 1 || (row_size < 128 && row_size * t0->ne[1] <= 2048)));
- if (!can_merge) {
- break;
+ if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) {
+ return false;
+ }
+ if (dst->type != src0->type || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) {
+ return false;
+ }
+
+ const size_t elem_size = ggml_type_size(src0->type);
+ bool all_contig = ggml_is_contiguous(dst);
+ for (uint32_t s = 0; s < n_srcs; ++s) {
+ const struct ggml_tensor * in = node.inputs[s];
+ if (in->type != src0->type || ggml_is_permuted(in) || !ggml_are_same_shape(src0, in)) {
+ return false;
}
- for (size_t t = 0; t < n_tensors; t++) {
- tensors[t]->ne[0] *= tensors[t]->ne[1];
- tensors[t]->ne[1] = tensors[t]->ne[2];
- tensors[t]->ne[2] = tensors[t]->ne[3];
- tensors[t]->ne[3] = 1;
- tensors[t]->nb[1] = tensors[t]->nb[2];
- tensors[t]->nb[2] = tensors[t]->nb[3];
- tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2];
+ if (!htp_binary_strides_safe(src0, in, dst, elem_size, elem_size, elem_size) ||
+ !htp_binary_strides_safe(in, src0, dst, elem_size, elem_size, elem_size)) {
+ return false;
}
+ all_contig = all_contig && ggml_is_contiguous(in);
+ }
+ if (!all_contig && src0->ne[0] <= 1) {
+ return false;
}
- // ne1 too big to merge in full: merge it in chunks of k rows (k divides ne1)
- const size_t row_size = (size_t) t0->ne[0] * elem_size;
- bool rows_contig = true;
- for (size_t t = 0; t < n_tensors; t++) {
- if (tensors[t]->nb[1] != row_size) {
- rows_contig = false;
- break;
- }
+ memset(kparams, 0, sizeof(*kparams));
+
+ const uint32_t max_hvx_sess = htp_session_n_hvx(sess);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ const size_t row_size = src0->ne[0] * elem_size;
+ const size_t row_size_aligned = hex_round_up(row_size, 128);
+
+ kparams->src0_elem_size = (uint8_t) elem_size;
+ kparams->src1_elem_size = (uint8_t) elem_size;
+ kparams->dst_elem_size = (uint8_t) elem_size;
+ kparams->src0_row_size_aligned = (uint32_t) row_size_aligned;
+ kparams->src1_row_size_aligned = (uint32_t) row_size_aligned;
+ kparams->dst_row_size_aligned = (uint32_t) row_size_aligned;
+
+ if (all_contig) {
+ struct htp_binary_vtcm_layout L;
+ return htp_binary_solve_chunked(&L, kparams, (uint32_t) ggml_nelements(src0),
+ (uint32_t) elem_size, (uint32_t) elem_size, (uint32_t) elem_size,
+ max_hvx_sess, n_srcs, false, vtcm_size);
}
- if (t0->ne[1] > 1 && row_size < 128 && rows_contig) {
- int64_t k = 2048 / row_size;
- while (k > 1 && t0->ne[1] % k != 0) {
- k--;
+
+ const uint32_t src0_nrows = ggml_nrows(src0);
+ const uint32_t min_rows_per_hvx = (uint32_t) (std::max<size_t>(1, (128 + row_size - 1) / row_size));
+ const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx);
+
+ kparams->kernel_type = HTP_BINARY_KERNEL_SAME_SHAPE;
+ kparams->n_hvx = (std::min)(max_hvx_sess, max_hvx);
+ kparams->n_srcs = (uint8_t) n_srcs;
+
+ for (uint32_t s = 0; s < n_srcs; ++s) {
+ const struct ggml_tensor * in = node.inputs[s];
+ if (src0->ne[2] > 1 && in->nb[2] != in->ne[1] * in->nb[1]) {
+ kparams->split_at_ne01 = 1;
}
- if (k > 1) {
- for (size_t t = 0; t < n_tensors; t++) {
- tensors[t]->ne[0] *= k;
- tensors[t]->ne[1] /= k;
- tensors[t]->nb[1] *= k;
- tensors[t]->nb[2] = tensors[t]->nb[1] * tensors[t]->ne[1];
- tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2];
- }
+ if (src0->ne[3] > 1 && in->nb[3] != in->ne[2] * in->nb[2]) {
+ kparams->split_at_ne02 = 1;
}
}
-
- // nrows too small to saturate threads: split ne0 into k rows (k divides ne0)
- const size_t row_size_curr = (size_t) t0->ne[0] * elem_size;
- const uint32_t nrows = (uint32_t) (t0->ne[1] * t0->ne[2] * t0->ne[3]);
- rows_contig = true;
- for (size_t t = 0; t < n_tensors; t++) {
- if (tensors[t]->ne[1] != 1 && tensors[t]->nb[1] != row_size_curr) {
- rows_contig = false;
- break;
- }
+ if (src0->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) {
+ kparams->split_at_ne01 = 1;
}
- if (nrows < n_hvx && rows_contig && row_size_curr >= 4096) {
- const size_t vec_elems = 128 / elem_size;
- int64_t k = std::max<int64_t>(row_size_curr / 16384, (n_hvx * 4 + nrows - 1) / nrows);
- k = std::min<int64_t>(k, row_size_curr / 2048);
- while (k > 1 && t0->ne[0] % (k * vec_elems) != 0) {
- k--;
- }
- if (k > 1) {
- for (size_t t = 0; t < n_tensors; t++) {
- tensors[t]->ne[0] /= k;
- tensors[t]->ne[1] *= k;
- tensors[t]->nb[1] = tensors[t]->ne[0] * elem_size;
- tensors[t]->nb[2] = tensors[t]->nb[1] * tensors[t]->ne[1];
- tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2];
- }
- }
+ if (src0->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) {
+ kparams->split_at_ne02 = 1;
}
+
+ kparams->div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]);
+ kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]);
+ kparams->div_ne012 = init_fastdiv_values((uint32_t) (src0->ne[1] * src0->ne[2]));
+ kparams->div_ne11 = init_fastdiv_values((uint32_t) src1->ne[1]);
+ kparams->div_ne12 = init_fastdiv_values((uint32_t) src1->ne[2]);
+ kparams->div_ne13 = init_fastdiv_values((uint32_t) src1->ne[3]);
+
+ struct htp_binary_vtcm_layout L;
+ htp_binary_vtcm_layout_build(&L, kparams, vtcm_size);
+ if (L.rows_per_buffer == 0 || L.total_bytes > vtcm_size) {
+ return false;
+ }
+
+ kparams->rows_per_buffer = L.rows_per_buffer;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
+
+ return true;
}
static bool htp_kparams_solve_unary_impl(
@@ -1556,6 +1681,7 @@ static bool htp_kparams_solve_unary_impl(
uint32_t op,
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
) {
@@ -1565,15 +1691,34 @@ static bool htp_kparams_solve_unary_impl(
return false;
}
+ const bool is_rms_norm = (op == HTP_OP_RMS_NORM || op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+
if (op == HTP_OP_HADAMARD) {
const int64_t n = src0->ne[0];
if (n < 32 || (n & (n - 1)) != 0) {
return false;
}
- if (!dst->src[0] || dst->src[0]->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 ||
+ if (dst->src[0]->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 ||
(src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16)) {
return false;
}
+ } else if (is_rms_norm) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
+ return false;
+ }
+ if (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD) {
+ if ((src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
+ !ggml_is_contiguous_rows(src1) || src1->ne[0] != src0->ne[0]) {
+ return false;
+ }
+ }
+ if (op == HTP_OP_RMS_NORM_MUL_ADD) {
+ if ((src2->type != GGML_TYPE_F32 && src2->type != GGML_TYPE_F16) ||
+ !ggml_is_contiguous_rows(src2) || !ggml_are_same_shape(src0, src2)) {
+ return false;
+ }
+ }
} else {
if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) {
return false;
@@ -1584,14 +1729,24 @@ static bool htp_kparams_solve_unary_impl(
if (src0->type == GGML_TYPE_F16) {
switch (op) {
case HTP_OP_NORM:
- case HTP_OP_RMS_NORM:
case HTP_OP_L2_NORM:
case HTP_OP_SCALE:
case HTP_OP_CLAMP:
+ case HTP_OP_LEAKY_RELU:
case HTP_OP_SQR:
case HTP_OP_SQRT:
+ case HTP_OP_UNARY_NEG:
+ case HTP_OP_UNARY_EXP:
+ case HTP_OP_UNARY_SIGMOID:
+ case HTP_OP_UNARY_SILU:
+ case HTP_OP_UNARY_GELU:
+ case HTP_OP_UNARY_GELU_QUICK:
+ case HTP_OP_UNARY_GELU_ERF:
+ case HTP_OP_UNARY_SOFTPLUS:
+ case HTP_OP_UNARY_TANH:
case HTP_OP_UNARY_LOG:
case HTP_OP_UNARY_ABS:
+ case HTP_OP_UNARY_RELU:
case HTP_OP_UNARY_STEP:
case HTP_OP_UNARY_CEIL:
case HTP_OP_UNARY_SGN:
@@ -1606,11 +1761,12 @@ static bool htp_kparams_solve_unary_impl(
return false;
}
- const size_t elem_size = ggml_type_size(src0->type);
+ const size_t src0_elem_size = ggml_type_size(src0->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
- const size_t dst_data_row_size = dst->ne[0] * ggml_type_size(dst->type);
+ const size_t dst_data_row_size = dst->ne[0] * dst_elem_size;
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const uint32_t src0_nrows = (uint32_t) ggml_nrows(src0);
const uint32_t min_rows_per_hvx = (uint32_t) (std::max<size_t>(1, (128 + dst_data_row_size - 1) / dst_data_row_size));
const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx);
const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
@@ -1618,32 +1774,57 @@ static bool htp_kparams_solve_unary_impl(
kparams->n_hvx = n_hvx;
- const bool has_weight = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
- const bool broadcast_weight = has_weight && (src1->ne[1] * src1->ne[2] * src1->ne[3] == 1);
- if (op == HTP_OP_RMS_NORM_MUL_ADD && !broadcast_weight) {
- return false;
+ const bool has_src1_mul = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src2_add = (op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool is_row_bcast = has_src1_mul && ggml_is_vector(src1);
+ bool broadcast_src1 = false;
+ if (op == HTP_OP_RMS_NORM_MUL) {
+ const bool is_dim1_bcast = (src1->ne[1] == src0->ne[1] && ggml_is_matrix(src1) && !ggml_is_matrix(src0));
+ if (!is_row_bcast && !is_dim1_bcast && !ggml_are_same_shape(src0, src1)) {
+ return false;
+ }
+ broadcast_src1 = is_row_bcast || is_dim1_bcast;
+ } else if (op == HTP_OP_RMS_NORM_MUL_ADD) {
+ if (!is_row_bcast && !(src1->ne[1] == src0->ne[1] && ggml_is_matrix(src1))) {
+ return false;
+ }
+ broadcast_src1 = true;
}
- kparams->broadcast_weight = broadcast_weight;
+ const uint32_t src1_nrows = broadcast_src1 ? (uint32_t) src1->ne[1] : 0;
+ kparams->broadcast_src1 = broadcast_src1;
- const bool src0_contig = ggml_is_contiguous_1(src0);
- const bool src1_contig = (has_weight && !broadcast_weight) ? ggml_is_contiguous_1(src1) : true;
+ const size_t src0_data_row_size = (size_t) src0->ne[0] * src0_elem_size;
+ const uint32_t ne01 = (uint32_t) src0->ne[1];
+ const bool src0_contig = ggml_is_contiguous_1(src0) && (!has_src2_add || ggml_is_contiguous_1(src2));
+ const bool src1_contig = (has_src1_mul && !broadcast_src1) ? ggml_is_contiguous_1(src1) : true;
+ const bool src0_slice_dma = !src0_contig && !has_src2_add && (!has_src1_mul || broadcast_src1) &&
+ ne01 > 1 && src0->ne[2] > 1 && src0->ne[3] == 1 &&
+ src0->nb[1] == src0_data_row_size && (src0_data_row_size & 127) == 0;
const uint32_t src0_nrows_per_hvx = (src0_nrows + n_hvx - 1) / n_hvx;
const uint32_t min_block_rows = (uint32_t) (std::max<size_t>(1, 2048 / dst_data_row_size));
- uint32_t max_block = (src0_contig && src1_contig) ? src0_nrows : (uint32_t) src0->ne[1];
+ uint32_t max_block = ((src0_contig && src1_contig) || src0_slice_dma) ? src0_nrows : ne01;
if (src0_nrows_per_hvx >= 2 * min_block_rows) {
max_block = (std::min)(max_block, (std::max)(min_block_rows, src0_nrows_per_hvx / 4));
}
+ if (src0_slice_dma && max_block > ne01) {
+ max_block = (max_block / ne01) * ne01;
+ }
- kparams->src0_contig = src0_contig ? 1 : 0;
- kparams->src1_contig = src1_contig ? 1 : 0;
+ kparams->src0_contig = src0_contig ? 1 : 0;
+ kparams->src1_contig = src1_contig ? 1 : 0;
+ kparams->src0_slice_dma = src0_slice_dma ? 1 : 0;
+
+ const size_t src1_elem_size = has_src1_mul ? ggml_type_size(src1->type) : sizeof(float);
+ const size_t src2_elem_size = has_src2_add ? ggml_type_size(src2->type) : sizeof(float);
struct htp_unary_vtcm_layout L;
uint32_t col_tile = 0;
uint32_t vtcm_row_per_hvx = 0;
htp_unary_solve_layout(&L, op, src0->ne[0], dst->ne[0],
- has_weight ? src1->ne[0] : 0,
- max_block, broadcast_weight, n_hvx, vtcm_size, elem_size,
+ has_src1_mul ? src1->ne[0] : 0,
+ max_block, broadcast_src1, src1_nrows, n_hvx, vtcm_size,
+ src0_elem_size, dst_elem_size, src1_elem_size, src2_elem_size,
&col_tile, &vtcm_row_per_hvx);
kparams->col_tile = col_tile;
@@ -1660,17 +1841,6 @@ static bool htp_kparams_solve_unary_impl(
return (col_tile > 0 || vtcm_row_per_hvx > 0) && L.total_bytes <= vtcm_size;
}
-static bool htp_kparams_solve_unary(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * op,
- struct htp_unary_kernel_params * kparams
-) {
- const htp_op_code opcode = htp_op_remap(op);
- const struct ggml_tensor * src0 = (opcode == HTP_OP_HADAMARD) ? op->src[1] : op->src[0];
- const struct ggml_tensor * src1 = (opcode == HTP_OP_HADAMARD) ? nullptr : op->src[1];
- return htp_kparams_solve_unary_impl(sess, opcode, src0, src1, op, kparams);
-}
-
bool htp_kparams_solve_rms_norm_mul(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
@@ -1678,17 +1848,18 @@ bool htp_kparams_solve_rms_norm_mul(
const struct ggml_tensor * dst,
struct htp_unary_kernel_params * kparams
) {
- return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL, src0, src1, dst, kparams);
+ return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL, src0, src1, nullptr, dst, 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
) {
- return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL_ADD, src0, src1, dst, kparams);
+ return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL_ADD, src0, src1, src2, dst, kparams);
}
bool htp_kparams_solve_repeat_get_rows(
@@ -1714,13 +1885,13 @@ bool htp_kparams_solve_repeat_get_rows(
return false;
}
- if (src0->type == dst->type) {
- if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_I32 && src0->type != GGML_TYPE_F16) {
+ const bool tiled = ggml_hexagon_tensor_is_tiled(src0);
+
+ if (src0->type == GGML_TYPE_I32) {
+ if (dst->type != GGML_TYPE_I32 || tiled) {
return false;
}
- } else if (src0->type == GGML_TYPE_I32) {
- return false;
- } else if (dst->type != GGML_TYPE_F32) {
+ } else if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) {
return false;
}
@@ -1733,8 +1904,7 @@ bool htp_kparams_solve_repeat_get_rows(
const uint32_t ne12 = src1->ne[2];
const uint32_t nr = ne10 * ne11 * ne12;
- const bool tiled = ggml_hexagon_tensor_is_tiled(src0);
- const int wtype = (tiled && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : src0->type;
+ const int wtype = (tiled && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : src0->type;
if (tiled) {
kparams->kernel_type = HTP_GET_ROWS_KERNEL_TILED;
@@ -1753,7 +1923,7 @@ bool htp_kparams_solve_repeat_get_rows(
struct htp_get_rows_vtcm_layout vtcm_layout = {};
while (kparams->n_hvx > 0) {
- htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, ne00, total_tasks, src1->type, kparams->n_hvx);
+ htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, dst->type, ne00, kparams->n_hvx);
if (vtcm_layout.total_bytes <= vtcm_size) {
break;
}
@@ -1761,7 +1931,7 @@ bool htp_kparams_solve_repeat_get_rows(
}
if (kparams->n_hvx == 0 && total_tasks > 0) {
- htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, ne00, total_tasks, src1->type, 1);
+ htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, dst->type, ne00, 1);
}
kparams->vtcm_size = (total_tasks == 0) ? 0 : vtcm_layout.total_bytes;
@@ -1800,7 +1970,7 @@ static bool htp_kparams_solve_set_rows(
if (dst->type == GGML_TYPE_Q8_0 && src0->ne[0] < 32) {
return false;
}
- if (src0->type != GGML_TYPE_F32) {
+ if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) {
return false;
}
if (src1->type != GGML_TYPE_I32 && src1->type != GGML_TYPE_I64) {
@@ -1816,7 +1986,7 @@ static bool htp_kparams_solve_set_rows(
kparams->total_tasks = nr;
struct htp_set_rows_vtcm_layout vtcm_layout;
- htp_set_rows_vtcm_layout_build(&vtcm_layout, dst->type, src0->ne[0], kparams->n_hvx);
+ htp_set_rows_vtcm_layout_build(&vtcm_layout, src0->type, dst->type, src0->ne[0], kparams->n_hvx);
kparams->vtcm_size = vtcm_layout.total_bytes;
return vtcm_layout.total_bytes <= htp_session_vtcm_size(sess);
@@ -1834,10 +2004,11 @@ static bool htp_kparams_solve_softmax(
const struct ggml_tensor * src2 = op->src[2];
const struct ggml_tensor * dst = op;
- if (src2) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
return false;
}
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src0->ne[2] > 512) {
+ if (src0->ne[2] > 512) {
return false;
}
if (src1) {
@@ -1848,11 +2019,19 @@ static bool htp_kparams_solve_softmax(
return false;
}
}
+ if (src2) {
+ if (src2->type != GGML_TYPE_F32 ||
+ src2->ne[0] != src0->ne[2] ||
+ src2->ne[1] != 1 || src2->ne[2] != 1 || src2->ne[3] != 1 ||
+ !ggml_is_contiguous(src2)) {
+ return false;
+ }
+ }
if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) {
return false;
}
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const uint32_t src0_nrows = ggml_nrows(src0);
const size_t dst_data_row_size = op->ne[0] * ggml_type_size(op->type);
const uint32_t min_rows_per_hvx = (uint32_t) (std::max<size_t>(1, (128 + dst_data_row_size - 1) / dst_data_row_size));
const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx);
@@ -1879,14 +2058,26 @@ static bool htp_kparams_solve_softmax(
kparams->m1 = 1.0f;
}
+ kparams->src0_f16 = (src0->type == GGML_TYPE_F16) ? 1 : 0;
+ kparams->dst_f16 = (dst->type == GGML_TYPE_F16) ? 1 : 0;
kparams->use_src1 = (src1 != nullptr) ? 1 : 0;
kparams->use_f16 = (src1 != nullptr && src1->type == GGML_TYPE_F16) ? 1 : 0;
+ kparams->use_src2 = (src2 != nullptr) ? 1 : 0;
const uint32_t ne00 = src0->ne[0];
const uint32_t ne10 = src1 ? src1->ne[0] : 1;
struct htp_softmax_vtcm_layout layout;
- htp_softmax_vtcm_layout_build(&layout, ne00, ne10, kparams->use_src1 != 0, kparams->use_f16 != 0, n_hvx);
+ htp_softmax_vtcm_layout_build(&layout,
+ ne00,
+ ne10,
+ n_head,
+ kparams->src0_f16 != 0,
+ kparams->dst_f16 != 0,
+ kparams->use_src1 != 0,
+ kparams->use_f16 != 0,
+ kparams->use_src2 != 0,
+ n_hvx);
if (layout.total_bytes > htp_session_vtcm_size(sess)) {
return false;
}
@@ -1894,12 +2085,22 @@ static bool htp_kparams_solve_softmax(
kparams->n_hvx = n_hvx;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
- if (!kparams->use_src1) {
- kparams->kernel_type = HTP_SOFTMAX_KERNEL_NOMASK;
- } else if (kparams->use_f16) {
- kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F16;
+ if (kparams->src0_f16) {
+ if (!kparams->use_src1) {
+ kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_NOMASK;
+ } else if (kparams->use_f16) {
+ kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_MASK_F16;
+ } else {
+ kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_MASK_F32;
+ }
} else {
- kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F32;
+ if (!kparams->use_src1) {
+ kparams->kernel_type = HTP_SOFTMAX_KERNEL_NOMASK;
+ } else if (kparams->use_f16) {
+ kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F16;
+ } else {
+ kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F32;
+ }
}
if (src0->ne[1] > 0) kparams->div_ne01 = init_fastdiv_values(src0->ne[1]);
@@ -1931,14 +2132,16 @@ static bool htp_kparams_solve_rope(
if (!ggml_are_same_shape(src0, dst)) {
return false;
}
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_I32) {
+ const bool is_f32 = (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
+ const bool is_f16 = (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16);
+ if ((!is_f32 && !is_f16) || src1->type != GGML_TYPE_I32) {
return false;
}
if (src0->ne[0] <= 0) {
return false;
}
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const uint32_t src0_nrows = ggml_nrows(src0);
if (src0_nrows == 0) {
return false;
}
@@ -1992,8 +2195,9 @@ static bool htp_kparams_solve_rope(
}
}
- if (src0->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float) ||
- src0->nb[1] < src0->ne[0] * sizeof(float) || dst->nb[1] < dst->ne[0] * sizeof(float)) {
+ const size_t elem_size = is_f16 ? sizeof(ggml_fp16_t) : sizeof(float);
+ if (src0->nb[0] != elem_size || dst->nb[0] != elem_size ||
+ src0->nb[1] < src0->ne[0] * elem_size || dst->nb[1] < dst->ne[0] * elem_size) {
return false;
}
@@ -2001,15 +2205,29 @@ static bool htp_kparams_solve_rope(
const uint32_t n_freq_factors = src2 ? (uint32_t) src2->ne[0] : 0;
struct htp_rope_vtcm_layout layout;
- htp_rope_vtcm_layout_build(&layout, src0->ne[0], n_hvx, n_freq_factors);
+ htp_rope_vtcm_layout_build(&layout, src0->ne[0], elem_size, n_hvx, n_freq_factors);
if (layout.total_bytes > htp_session_vtcm_size(sess)) {
return false;
}
- kparams->n_hvx = n_hvx;
- kparams->vtcm_size = (uint32_t) layout.total_bytes;
- kparams->div_ne2_ne1 = init_fastdiv_values(dst->ne[2] * dst->ne[1]);
- kparams->div_ne1 = init_fastdiv_values(dst->ne[1]);
+ const int n_ctx_orig = op_params[4];
+ float beta_fast, beta_slow;
+ memcpy(&beta_fast, op_params + 9, sizeof(float));
+ memcpy(&beta_slow, op_params + 10, sizeof(float));
+
+ kparams->n_hvx = n_hvx;
+ kparams->vtcm_size = (uint32_t) layout.total_bytes;
+ kparams->theta_scale = (n_dims > 0) ? std::pow(freq_base, -2.0f / n_dims) : 0.0f;
+ kparams->theta_scale_32 = (n_dims > 0) ? std::pow(freq_base, -64.0f / n_dims) : 0.0f;
+ {
+ const float inv_2log_fb = 1.0f / (2.0f * std::log(freq_base));
+ const float start = std::floor(n_dims * std::log(n_ctx_orig / (beta_fast * 2.0f * (float) M_PI)) * inv_2log_fb);
+ const float end = std::ceil(n_dims * std::log(n_ctx_orig / (beta_slow * 2.0f * (float) M_PI)) * inv_2log_fb);
+ kparams->corr_dims[0] = std::max(0.0f, start);
+ kparams->corr_dims[1] = std::min((float) (n_dims - 1), end);
+ }
+ kparams->div_ne2_ne1 = init_fastdiv_values(dst->ne[2] * dst->ne[1]);
+ kparams->div_ne1 = init_fastdiv_values(dst->ne[1]);
return true;
}
@@ -2024,42 +2242,173 @@ static bool htp_kparams_solve_sum_rows(
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * dst = op;
- if (src0->type != GGML_TYPE_F32) {
+ const uint32_t ne00 = src0->ne[0];
+ const uint32_t src0_nrows = ggml_nrows(src0);
+ const uint32_t max_hvx_sess = htp_session_n_hvx(sess);
+
+ if (op->op == GGML_OP_SUM_ROWS) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
+ return false;
+ }
+ if (dst->ne[0] != 1 ||
+ dst->ne[1] != src0->ne[1] ||
+ dst->ne[2] != src0->ne[2] ||
+ dst->ne[3] != src0->ne[3]) {
+ return false;
+ }
+ if (!ggml_is_contiguous_rows(src0) || !ggml_is_contiguous(dst)) {
+ return false;
+ }
+
+ const size_t src0_elem_size = ggml_type_size(src0->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
+ const size_t src0_data_row_size = (size_t) ne00 * src0_elem_size;
+ const size_t src0_row_size_aligned = hex_round_up(src0_data_row_size, 128);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+
+ const uint32_t min_rpt = (src0_data_row_size < 1024) ? 32 : 1;
+ const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rpt);
+ uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx);
+
+ while (n_hvx > 1 && 2 * (src0_row_size_aligned + 128) * n_hvx > vtcm_size) {
+ n_hvx--;
+ }
+ if (n_hvx == 0 || 2 * (src0_row_size_aligned + 128) * n_hvx > vtcm_size) {
+ return false;
+ }
+
+ const bool can_2d_dma = (src0_nrows > 1) &&
+ (src0->nb[1] >= src0_data_row_size);
+ const bool src0_contig = can_2d_dma && ggml_is_contiguous_1(src0);
+
+ const uint32_t src0_nrows_per_hvx = (src0_nrows + n_hvx - 1) / n_hvx;
+ const uint32_t min_block_rows = (uint32_t) (std::max<size_t>(1, 2048 / src0_data_row_size));
+ uint32_t max_block = !can_2d_dma ? 1u : (src0_contig ? src0_nrows : (uint32_t) src0->ne[1]);
+ if (max_block > 1 && src0_nrows_per_hvx >= 2 * min_block_rows) {
+ max_block = (std::min)(max_block, (std::max)(min_block_rows, src0_nrows_per_hvx / 4));
+ }
+ max_block = (std::min)(max_block, 512u);
+ max_block = (std::max)(max_block, 1u);
+
+ const size_t per_hvx_budget = vtcm_size / (2 * n_hvx);
+ uint32_t block = (per_hvx_budget > 128)
+ ? (uint32_t) ((per_hvx_budget - 128) / (src0_row_size_aligned + dst_elem_size))
+ : 1u;
+ block = (std::min)(block, max_block);
+ block = (std::max)(block, 1u);
+
+ struct htp_sum_rows_vtcm_layout L;
+ htp_sum_rows_vtcm_layout_build(&L, src0_data_row_size, dst_elem_size, block, n_hvx);
+ while (block > 1 && L.total_bytes > vtcm_size) {
+ block--;
+ htp_sum_rows_vtcm_layout_build(&L, src0_data_row_size, dst_elem_size, block, n_hvx);
+ }
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
+
+ kparams->n_hvx = n_hvx;
+ kparams->block = block;
+ kparams->src0_contig = src0_contig ? 1 : 0;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
+ kparams->div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]);
+ kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]);
+ kparams->div_ne012 = init_fastdiv_values((uint32_t) (src0->ne[1] * src0->ne[2]));
+
+ return true;
+ }
+
+ if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) {
return false;
}
if (op->op == GGML_OP_ARGMAX) {
if (dst->type != GGML_TYPE_I32) {
return false;
}
- } else if (dst->type != GGML_TYPE_F32) {
+ } else if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) {
return false;
}
if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) {
return false;
}
- const uint32_t ne00 = src0->ne[0];
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
- const uint32_t max_hvx_sess = htp_session_n_hvx(sess);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ const size_t src0_elem_size = ggml_type_size(src0->type);
+ const uint32_t elems_per_vec = (uint32_t) (128 / src0_elem_size);
if (op->op == GGML_OP_SUM) {
const uint32_t total_elems = (uint32_t) ggml_nelements(src0);
- const uint32_t n_hvx = (total_elems >= 1024) ? max_hvx_sess : 1;
- const uint32_t raw_chunk = (total_elems + n_hvx - 1) / n_hvx;
+ uint32_t n_hvx = (total_elems >= 1024) ? max_hvx_sess : 1;
+ uint32_t chunk_elems = (std::min)(4096u, (uint32_t) hex_round_up((std::max)(1u, total_elems), elems_per_vec));
+
+ struct htp_sum_vtcm_layout L;
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ while (L.total_bytes > vtcm_size && chunk_elems > elems_per_vec) {
+ chunk_elems = (std::max)(elems_per_vec, (chunk_elems / 2) & ~(elems_per_vec - 1));
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ }
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ }
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
+
+ const uint32_t raw_chunk = (total_elems + n_hvx - 1) / n_hvx;
kparams->n_hvx = n_hvx;
- kparams->elems_per_hvx = hex_round_up(raw_chunk, 32);
+ kparams->elems_per_hvx = hex_round_up(raw_chunk, elems_per_vec);
+ kparams->chunk_elems = chunk_elems;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
} else if (op->op == GGML_OP_ARGMAX && src0_nrows <= 1) {
- const uint32_t n_hvx = (ne00 >= 1024) ? max_hvx_sess : 1;
+ uint32_t n_hvx = (ne00 >= 1024) ? max_hvx_sess : 1;
+ uint32_t chunk_elems = (std::min)(4096u, (uint32_t) hex_round_up((std::max)(1u, ne00), elems_per_vec));
+
+ struct htp_sum_vtcm_layout L;
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ while (L.total_bytes > vtcm_size && chunk_elems > elems_per_vec) {
+ chunk_elems = (std::max)(elems_per_vec, (chunk_elems / 2) & ~(elems_per_vec - 1));
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ }
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ }
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
+
const uint32_t raw_chunk = (ne00 + n_hvx - 1) / n_hvx;
kparams->n_hvx = n_hvx;
- kparams->elems_per_hvx = hex_round_up(raw_chunk, 32);
+ kparams->elems_per_hvx = hex_round_up(raw_chunk, elems_per_vec);
+ kparams->chunk_elems = chunk_elems;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
} else {
- const uint32_t min_rpt = (src0->nb[1] < 1024) ? 32 : 1;
- const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rpt);
+ const uint32_t min_rpt = (src0->nb[1] < 1024) ? 32 : 1;
+ const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rpt);
+ uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx);
+ uint32_t chunk_elems = (std::min)(4096u, (uint32_t) hex_round_up((std::max)(1u, ne00), elems_per_vec));
+
+ struct htp_sum_vtcm_layout L;
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ while (L.total_bytes > vtcm_size && chunk_elems > elems_per_vec) {
+ chunk_elems = (std::max)(elems_per_vec, (chunk_elems / 2) & ~(elems_per_vec - 1));
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ }
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx);
+ }
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
- kparams->n_hvx = (std::min)(max_hvx_sess, max_hvx);
+ kparams->n_hvx = n_hvx;
+ kparams->chunk_elems = chunk_elems;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
}
return true;
@@ -2099,7 +2448,7 @@ bool htp_kparams_solve_unary_mul_glu(
}
const size_t dst_row_size = dst->ne[0] * elem_size;
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const uint32_t src0_nrows = ggml_nrows(src0);
const uint32_t min_rows_per_hvx = (uint32_t) (std::max<size_t>(1, (128 + dst_row_size - 1) / dst_row_size));
const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx);
const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
@@ -2127,14 +2476,6 @@ bool htp_kparams_solve_unary_mul_glu(
return true;
}
-static bool htp_kparams_solve_glu(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * op,
- struct htp_glu_kernel_params * kparams
-) {
- return htp_kparams_solve_unary_mul_glu(sess, htp_op_remap(op), op->src[0], op->src[1], op, kparams);
-}
-
static bool htp_kparams_solve_repeat(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * op,
@@ -2145,24 +2486,97 @@ static bool htp_kparams_solve_repeat(
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * dst = op;
- if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || src0->type != dst->type) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (dst->type != src0->type && !(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16))) {
return false;
}
+ const size_t src_elem_size = ggml_type_size(src0->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
+
if (!ggml_can_repeat(src0, dst) || ggml_is_transposed(src0) || ggml_is_transposed(dst)) {
return false;
}
+ if (src0->nb[0] != src_elem_size || dst->nb[0] != dst_elem_size) {
+ return false;
+ }
- const uint32_t total_dst_rows = dst->ne[1] * dst->ne[2] * dst->ne[3];
- const size_t dst_row_size = dst->ne[0] * ggml_type_size(dst->type);
+ const uint32_t ne00 = (uint32_t) src0->ne[0];
+ const uint32_t nr0 = (uint32_t) (dst->ne[0] / src0->ne[0]);
+ const uint32_t total_dst_rows = (uint32_t) ggml_nrows(dst);
+ const size_t src_row_size = (size_t) ne00 * src_elem_size;
+ const size_t dst_row_size = (size_t) dst->ne[0] * dst_elem_size;
const uint32_t min_rows_per_hvx = (uint32_t) (std::max<size_t>(1, (128 + dst_row_size - 1) / dst_row_size));
const uint32_t max_hvx = (std::max)(1u, total_dst_rows / min_rows_per_hvx);
- const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ const uint32_t orig_n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
- kparams->n_hvx = n_hvx;
- kparams->nr0 = dst->ne[0] / src0->ne[0];
- kparams->nr1 = dst->ne[1] / src0->ne[1];
- kparams->nr2 = dst->ne[2] / src0->ne[2];
- kparams->nr3 = dst->ne[3] / src0->ne[3];
+ uint32_t n_hvx = orig_n_hvx;
+ uint32_t tile_elems = ne00;
+ uint32_t dst_reps = nr0;
+ uint32_t pipelined = 1;
+
+ struct htp_repeat_vtcm_layout L;
+ htp_repeat_vtcm_layout_build(&L, src_row_size, dst_row_size, 2, n_hvx);
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_repeat_vtcm_layout_build(&L, src_row_size, dst_row_size, 2, n_hvx);
+ }
+
+ if (L.total_bytes > vtcm_size) {
+ // Fallback to single-buffered row or column-tiled DMA
+ pipelined = 0;
+ n_hvx = orig_n_hvx;
+ const size_t dst_unit_bytes = (size_t) ne00 * dst_elem_size;
+
+ htp_repeat_vtcm_layout_build(&L, src_row_size, dst_unit_bytes, 1, n_hvx);
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_repeat_vtcm_layout_build(&L, src_row_size, dst_unit_bytes, 1, n_hvx);
+ }
+
+ if (L.total_bytes <= vtcm_size) {
+ tile_elems = ne00;
+ const size_t per_hvx_budget = vtcm_size / n_hvx;
+ const size_t dst_budget = per_hvx_budget > L.src_buf_bytes ? (per_hvx_budget - L.src_buf_bytes) : dst_unit_bytes;
+ dst_reps = (uint32_t) (std::min<size_t>(nr0, (std::max<size_t>(1, dst_budget / dst_unit_bytes))));
+ htp_repeat_vtcm_layout_build(&L, src_row_size, (size_t) dst_reps * dst_unit_bytes, 1, n_hvx);
+ while (L.total_bytes > vtcm_size && dst_reps > 1) {
+ dst_reps = (std::max)(1u, dst_reps / 2);
+ htp_repeat_vtcm_layout_build(&L, src_row_size, (size_t) dst_reps * dst_unit_bytes, 1, n_hvx);
+ }
+ } else {
+ // Single src row exceeds VTCM: column-tile along dim0
+ dst_reps = 1;
+ n_hvx = orig_n_hvx;
+ tile_elems = (std::min)(ne00, 4096u);
+ if (tile_elems > 64) {
+ tile_elems = (tile_elems / 64) * 64;
+ }
+ htp_repeat_vtcm_layout_build(&L, (size_t) tile_elems * src_elem_size, (size_t) tile_elems * dst_elem_size, 1, n_hvx);
+ while (L.total_bytes > vtcm_size && tile_elems > 64) {
+ tile_elems = (std::max)(64u, ((tile_elems / 2) / 64) * 64);
+ htp_repeat_vtcm_layout_build(&L, (size_t) tile_elems * src_elem_size, (size_t) tile_elems * dst_elem_size, 1, n_hvx);
+ }
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_repeat_vtcm_layout_build(&L, (size_t) tile_elems * src_elem_size, (size_t) tile_elems * dst_elem_size, 1, n_hvx);
+ }
+ }
+ }
+
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
+
+ kparams->n_hvx = n_hvx;
+ kparams->nr0 = nr0;
+ kparams->nr1 = dst->ne[1] / src0->ne[1];
+ kparams->nr2 = dst->ne[2] / src0->ne[2];
+ kparams->nr3 = dst->ne[3] / src0->ne[3];
+ kparams->tile_elems = tile_elems;
+ kparams->dst_reps = dst_reps;
+ kparams->pipelined = pipelined;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
kparams->div_ne1 = init_fastdiv_values(dst->ne[1]);
kparams->div_ne12 = init_fastdiv_values(dst->ne[1] * dst->ne[2]);
@@ -2175,16 +2589,17 @@ static bool htp_kparams_solve_repeat(
static bool htp_kparams_solve_ssm_conv(
const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * op,
+ const struct ggml_tensor * src0,
+ const struct ggml_tensor * src1,
+ const struct ggml_tensor * dst,
struct htp_ssm_conv_kernel_params * kparams
) {
memset(kparams, 0, sizeof(*kparams));
- const struct ggml_tensor * src0 = op->src[0];
- const struct ggml_tensor * src1 = op->src[1];
- const struct ggml_tensor * dst = op;
-
- if (src0->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ const auto is_valid_type = [](ggml_type t) {
+ return t == GGML_TYPE_F32 || t == GGML_TYPE_F16;
+ };
+ if (!is_valid_type(src0->type) || !is_valid_type(src1->type) || !is_valid_type(dst->type)) {
return false;
}
if (src0->ne[3] != 1 || src1->ne[2] != 1 || src1->ne[3] != 1 || dst->ne[3] != 1) {
@@ -2208,10 +2623,23 @@ static bool htp_kparams_solve_ssm_conv(
if (dst->ne[0] != d_inner_64 || dst->ne[1] != n_t_64 || dst->ne[2] != n_s_64) {
return false;
}
- if (src0->nb[0] != sizeof(float) || src1->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) {
+
+ const size_t src0_elem_size = ggml_type_size(src0->type);
+ const size_t src1_elem_size = ggml_type_size(src1->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
+
+ if (src0->nb[0] != src0_elem_size || src1->nb[0] != src1_elem_size || dst->nb[0] != dst_elem_size) {
return false;
}
- if (src0->nb[1] != src0->ne[0] * sizeof(float) || src1->nb[1] != src1->ne[0] * sizeof(float)) {
+ if (src1->nb[1] != (size_t) src1->ne[0] * src1_elem_size) {
+ return false;
+ }
+ if ((d_inner_64 > 1 && src0->nb[1] < (size_t) src0->ne[0] * src0_elem_size) ||
+ (n_s_64 > 1 && src0->nb[2] < (size_t) d_inner_64 * src0->nb[1])) {
+ return false;
+ }
+ if ((n_t_64 > 1 && dst->nb[1] < (size_t) d_inner_64 * dst_elem_size) ||
+ (n_s_64 > 1 && dst->nb[2] < (size_t) n_t_64 * dst->nb[1])) {
return false;
}
@@ -2240,7 +2668,7 @@ static bool htp_kparams_solve_ssm_conv(
const uint32_t src1_T_bytes = hex_round_up(d_conv * d_inner_per_hvx * sizeof(float), 128);
const uint32_t vtcm_src1_per_hvx = src1_raw_bytes + src1_T_bytes;
- const size_t vtcm_budget = (vtcm_size > 0 ? vtcm_size / n_hvx : (1024 * 1024));
+ const size_t vtcm_budget = vtcm_size / n_hvx;
const uint32_t src0_block_T = hex_round_up(ncs * 32 * sizeof(float), 128);
const size_t fixed_bytes = vtcm_src1_per_hvx + src0_block_T;
const size_t avail_for_tiles = vtcm_budget > fixed_bytes ? vtcm_budget - fixed_bytes : (128 * 1024);
@@ -2249,7 +2677,7 @@ static bool htp_kparams_solve_ssm_conv(
target_max_tile = (std::max)(target_max_tile, 32u);
target_max_tile = (std::min)(target_max_tile, 128u);
- const size_t raw_stride_bytes = ncs * sizeof(float) + sizeof(float);
+ const size_t raw_stride_bytes = htp_ssm_conv_raw_stride_bytes(ncs, src0_elem_size);
uint32_t d_inner_tile = (uint32_t) (avail_for_tiles / (2 * (raw_stride_bytes + n_t * sizeof(float))));
d_inner_tile = (d_inner_tile / 32) * 32;
if (d_inner_tile == 0) {
@@ -2265,7 +2693,7 @@ static bool htp_kparams_solve_ssm_conv(
}
struct htp_ssm_conv_vtcm_layout L;
- htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, d_conv, n_t, kparams->d_inner_tile, n_hvx);
+ htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, d_conv, n_t, kparams->d_inner_tile, n_hvx, src0_elem_size);
kparams->vtcm_size = (uint32_t) L.total_bytes;
kparams->div_d_inner_tile = init_fastdiv_values(kparams->d_inner_tile);
@@ -2273,6 +2701,131 @@ static bool htp_kparams_solve_ssm_conv(
return L.total_bytes <= vtcm_size;
}
+static bool htp_kparams_solve_ssm_conv_token_major(
+ const struct ggml_hexagon_session * sess,
+ const struct ggml_tensor * state,
+ const struct ggml_tensor * weight,
+ const struct ggml_tensor * x,
+ const struct ggml_tensor * dst,
+ const struct ggml_tensor * dst_state,
+ struct htp_ssm_conv_kernel_params * kparams
+) {
+ memset(kparams, 0, sizeof(*kparams));
+
+ const auto is_valid_type = [](ggml_type t) {
+ return t == GGML_TYPE_F32 || t == GGML_TYPE_F16;
+ };
+ if (!is_valid_type(state->type) || !is_valid_type(weight->type) ||
+ !is_valid_type(x->type) || !is_valid_type(dst->type)) {
+ return false;
+ }
+ if (dst_state && !is_valid_type(dst_state->type)) {
+ return false;
+ }
+ if (state->ne[3] != 1 || weight->ne[2] != 1 || weight->ne[3] != 1 ||
+ x->ne[3] != 1 || dst->ne[3] != 1) {
+ return false;
+ }
+
+ const int64_t d_conv_64 = weight->ne[0];
+ const int64_t d_inner_64 = weight->ne[1];
+ const int64_t n_t_64 = dst->ne[1];
+ const int64_t n_s_64 = dst->ne[2];
+ const int64_t S_64 = d_conv_64 - 1;
+
+ if (d_conv_64 < 2 || d_conv_64 > 32 || d_inner_64 <= 0 || n_t_64 <= 0 || n_s_64 <= 0) {
+ return false;
+ }
+ if (state->ne[0] != S_64 || state->ne[1] != d_inner_64 || state->ne[2] != n_s_64) {
+ return false;
+ }
+ if (x->ne[0] != d_inner_64 || x->ne[1] != n_t_64 || x->ne[2] != n_s_64) {
+ return false;
+ }
+ if (dst->ne[0] != d_inner_64) {
+ return false;
+ }
+
+ const size_t state_elem_size = ggml_type_size(state->type);
+ const size_t weight_elem_size = ggml_type_size(weight->type);
+ const size_t x_elem_size = ggml_type_size(x->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
+
+ if (state->nb[0] != state_elem_size || weight->nb[0] != weight_elem_size ||
+ x->nb[0] != x_elem_size || dst->nb[0] != dst_elem_size) {
+ return false;
+ }
+ if (weight->nb[1] != (size_t) d_conv_64 * weight_elem_size) {
+ return false;
+ }
+ if ((d_inner_64 > 1 && state->nb[1] != (size_t) S_64 * state_elem_size) ||
+ (n_s_64 > 1 && state->nb[2] < (size_t) d_inner_64 * state->nb[1])) {
+ return false;
+ }
+ if ((n_t_64 > 1 && x->nb[1] < (size_t) d_inner_64 * x_elem_size) ||
+ (n_s_64 > 1 && x->nb[2] < (size_t) n_t_64 * x->nb[1])) {
+ return false;
+ }
+ if ((n_t_64 > 1 && dst->nb[1] < (size_t) d_inner_64 * dst_elem_size) ||
+ (n_s_64 > 1 && dst->nb[2] < (size_t) n_t_64 * dst->nb[1])) {
+ return false;
+ }
+
+ if (dst_state) {
+ const size_t dst_state_elem_size = ggml_type_size(dst_state->type);
+ if (dst_state->ne[0] != S_64 * d_inner_64 || dst_state->ne[1] != n_s_64 ||
+ dst_state->ne[2] != 1 || dst_state->ne[3] != 1 ||
+ dst_state->nb[0] != dst_state_elem_size ||
+ (n_s_64 > 1 && dst_state->nb[1] < (size_t) S_64 * d_inner_64 * dst_state_elem_size)) {
+ return false;
+ }
+ }
+
+ const uint32_t d_conv = (uint32_t) d_conv_64;
+ const uint32_t d_inner = (uint32_t) d_inner_64;
+ const uint32_t n_t = (uint32_t) n_t_64;
+ const uint32_t n_s = (uint32_t) n_s_64;
+
+ const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), (d_inner + 31) / 32);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+
+ const uint32_t raw_rpt = (d_inner + n_hvx - 1) / n_hvx;
+ const uint32_t d_inner_per_hvx = hex_round_up(raw_rpt, 32);
+
+ uint32_t d_inner_tile = hex_round_up(d_inner_per_hvx, 64);
+ uint32_t n_t_tile = (std::min)(n_t, 64u);
+
+ struct htp_ssm_conv_vtcm_layout L;
+ while (true) {
+ htp_ssm_conv_token_vtcm_layout_build(&L, d_inner_per_hvx, d_conv, n_t_tile, d_inner_tile, n_hvx, x_elem_size, dst_elem_size);
+ if (L.total_bytes <= vtcm_size) {
+ break;
+ }
+ if (n_t_tile > 8) {
+ n_t_tile /= 2;
+ } else if (d_inner_tile > 64) {
+ d_inner_tile = hex_round_up(d_inner_tile / 2, 64);
+ } else if (n_t_tile > 1) {
+ n_t_tile /= 2;
+ } else {
+ return false;
+ }
+ }
+
+ kparams->n_hvx = n_hvx;
+ kparams->d_conv = d_conv;
+ kparams->d_inner = d_inner;
+ kparams->n_t = n_t;
+ kparams->n_s = n_s;
+ kparams->d_inner_tile = d_inner_tile;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
+ kparams->token_major = 1;
+ kparams->n_t_tile = n_t_tile;
+ kparams->n_t_blocks = (n_t + n_t_tile - 1) / n_t_tile;
+
+ return true;
+}
+
static bool htp_kparams_solve_ssm_scan(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * op,
@@ -2430,15 +2983,15 @@ static bool htp_kparams_solve_sort(
const struct ggml_tensor * dst = op;
const bool is_top_k = (op->op == GGML_OP_TOP_K);
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_I32) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != GGML_TYPE_I32) {
return false;
}
- const uint32_t total_rows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const uint32_t total_rows = ggml_nrows(src0);
const uint32_t ne00 = src0->ne[0];
const uint32_t k = dst->ne[0];
- const uint32_t n_hvx_max = htp_session_n_hvx(sess) > 0 ? htp_session_n_hvx(sess) : 4;
- const size_t vtcm_budget = htp_session_vtcm_size(sess) > 0 ? htp_session_vtcm_size(sess) : (8 * 1024 * 1024);
+ const uint32_t n_hvx_max = htp_session_n_hvx(sess);
+ const size_t vtcm_budget = htp_session_vtcm_size(sess);
int32_t order = GGML_SORT_ORDER_DESC;
if (!is_top_k) {
@@ -2524,12 +3077,10 @@ static bool htp_kparams_solve_pool_2d(
const uint32_t src_y = is_pool_1d ? 1 : (uint32_t) src0->ne[1];
const uint32_t dst_x = (uint32_t) dst->ne[0];
const uint32_t dst_y = is_pool_1d ? 1 : (uint32_t) dst->ne[1];
- const uint32_t dst_plane_bytes = dst_x * dst_y * sizeof(float);
const uint32_t planes = (uint32_t) (is_pool_1d
? (uint64_t) src0->ne[1] * (uint64_t) src0->ne[2] * (uint64_t) src0->ne[3]
: (uint64_t) src0->ne[2] * (uint64_t) src0->ne[3]);
const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), planes > 0 ? planes : 1);
- const uint32_t planes_per_chunk = (dst_plane_bytes > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(dst_plane_bytes, HEX_L2_LINE_SIZE)) : 1;
struct htp_pool_vtcm_layout layout;
if (!htp_pool_solve_layout(&layout, src_x, src_y, dst_x, dst_y, n_hvx, htp_session_vtcm_size(sess))) {
@@ -2548,7 +3099,6 @@ static bool htp_kparams_solve_pool_2d(
kparams->pad_y = pad_y;
kparams->n_hvx = n_hvx;
kparams->planes = planes;
- kparams->planes_per_chunk = planes_per_chunk;
kparams->pool_op = (uint32_t) params[0];
const bool exact_tiling = (kparams->pad_x == 0 && kparams->pad_y == 0 &&
@@ -2613,8 +3163,7 @@ bool htp_kparams_solve_upscale(
const bool is_src_contig_row = (src0->nb[0] == sizeof(float));
const bool is_src_strided_2d = (src0->nb[0] > sizeof(float)) &&
(src0->nb[0] % sizeof(float) == 0) &&
- (src0->nb[1] == (size_t) src_x * src0->nb[0]) &&
- ((size_t) src_x * src_y <= 0xFFFFu);
+ (src0->nb[1] == (size_t) src_x * src0->nb[0]);
if ((!is_src_contig_row && !is_src_strided_2d) || dst->nb[0] != sizeof(float)) {
return false;
@@ -2693,24 +3242,6 @@ bool htp_kparams_solve_upscale(
n_hvx = (std::min)(n_hvx, total_chunks > 0 ? total_chunks : 1);
htp_upscale_vtcm_layout_build(&layout, src_x, src_y, dst_x, dst_y, dst_nrows_per_chunk, inv_sf1, filter_radius1, n_hvx);
- const uint32_t slice_dst_bytes = dst_x * dst_y * sizeof(float);
- const uint32_t chunk_dst_bytes = dst_x * dst_nrows_per_chunk * sizeof(float);
- const bool dst_contig = (dst->nb[1] == (size_t) dst_x * sizeof(float)) &&
- (dst_z <= 1 || dst->nb[2] == (size_t) dst_y * dst->nb[1]) &&
- (dst_w <= 1 || dst->nb[3] == (size_t) dst_z * dst->nb[2]);
-
- uint32_t chunks_per_group = 0;
- if (dst_contig) {
- const uint32_t slices_per_group = (slice_dst_bytes > 0)
- ? (HEX_L2_LINE_SIZE / hex_gcd_u32(slice_dst_bytes, HEX_L2_LINE_SIZE))
- : 1;
- if (slices_per_group == 1 && (chunk_dst_bytes % HEX_L2_LINE_SIZE == 0)) {
- chunks_per_group = 1;
- } else {
- chunks_per_group = slices_per_group * chunks_per_slice;
- }
- }
-
uint8_t kernel_type = HTP_UPSCALE_KERNEL_BILINEAR;
if (mode_raw == HTP_UPSCALE_MODE_NEAREST) {
if (dst_x == 2 * src_x && dst_y == 2 * src_y && !align_corners) {
@@ -2747,7 +3278,6 @@ bool htp_kparams_solve_upscale(
kparams->invscale1 = invscale1;
kparams->n_hvx = n_hvx;
- kparams->chunks_per_group = chunks_per_group;
kparams->dst_nrows_per_chunk = dst_nrows_per_chunk;
kparams->chunks_per_slice = chunks_per_slice;
@@ -2772,24 +3302,26 @@ static bool htp_kparams_solve_concat(
const struct ggml_tensor * src1 = op->src[1];
const struct ggml_tensor * dst = op;
- if (!src0 || !src1 || !dst) {
- return false;
- }
-
int dim = ((const int32_t *) op->op_params)[0];
if (dim < 0 || dim >= GGML_MAX_DIMS) {
return false;
}
kparams->dim = dim;
- if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_I32) {
- return false;
- }
- if (src0->type != dst->type || src1->type != dst->type) {
+ const bool all_same = (src0->type == dst->type && src1->type == dst->type);
+ if (dst->type == GGML_TYPE_I32) {
+ if (!all_same) {
+ return false;
+ }
+ } else if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
return false;
}
- const uint32_t type_size = ggml_type_size(dst->type);
+ const uint32_t src0_es = ggml_type_size(src0->type);
+ const uint32_t src1_es = ggml_type_size(src1->type);
+ const uint32_t dst_es = ggml_type_size(dst->type);
const uint32_t n_hvx = htp_session_n_hvx(sess);
const uint32_t mdev_count = htp_session_mdev_count(sess);
const size_t vtcm_size = htp_session_vtcm_size(sess);
@@ -2801,30 +3333,30 @@ static bool htp_kparams_solve_concat(
}
}
- const uint32_t max_gather_ne0 = 128 / type_size;
- const uint32_t total_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]);
- const bool b_dense = (src1->nb[0] == type_size);
+ const uint32_t max_gather_ne0 = 128 / dst_es;
+ const uint32_t total_rows = (uint32_t) ggml_nrows(dst);
+ const bool b_dense = (src1->nb[0] == src1_es);
const bool gather_strides_ok =
- src0->nb[1] >= (size_t) src0->ne[0] * type_size &&
- (b_dense ? src1->nb[1] >= (size_t) src1->ne[0] * type_size
- : src1->nb[0] >= (size_t) src1->ne[1] * type_size);
+ src0->nb[1] >= (size_t) src0->ne[0] * src0_es &&
+ (b_dense ? src1->nb[1] >= (size_t) src1->ne[0] * src1_es
+ : src1->nb[0] >= (size_t) src1->ne[1] * src1_es);
if (dim == 0 &&
(dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16) &&
dst->ne[0] <= max_gather_ne0 &&
- dst->nb[0] == type_size && dst->nb[1] == (size_t) dst->ne[0] * type_size &&
- src0->nb[0] == type_size &&
- (src1->nb[0] == type_size || src1->nb[1] == type_size) &&
+ dst->nb[0] == dst_es && dst->nb[1] == (size_t) dst->ne[0] * dst_es &&
+ src0->nb[0] == src0_es &&
+ (src1->nb[0] == src1_es || src1->nb[1] == src1_es) &&
gather_strides_ok &&
htp_gather_rows_tensor_outer_contiguous(dst) &&
htp_gather_rows_tensor_outer_contiguous(src0) &&
htp_gather_rows_tensor_outer_contiguous(src1)) {
- if (htp_gather_rows_solve_layout(&kparams->u.gather,
- (uint32_t) src0->ne[0], (uint32_t) src0->nb[1],
- (uint32_t) src1->ne[0], (uint32_t) src1->nb[1], b_dense,
- type_size, total_rows,
- n_hvx, mdev_count, vtcm_size)) {
+ if (htp_concat_gather_rows_solve_layout(&kparams->u.gather,
+ (uint32_t) src0->ne[0], (uint32_t) src0->nb[1],
+ (uint32_t) src1->ne[0], (uint32_t) src1->nb[1], b_dense,
+ src0_es, src1_es, dst_es, total_rows,
+ n_hvx, mdev_count, vtcm_size)) {
kparams->kernel_type = HTP_CONCAT_KERNEL_GATHER_ROWS;
kparams->n_hvx = (uint8_t) n_hvx;
kparams->vtcm_size = kparams->u.gather.slice * n_hvx;
@@ -2832,31 +3364,67 @@ static bool htp_kparams_solve_concat(
}
}
- const bool dma_strides_ok = (src0->nb[0] == type_size && src1->nb[0] == type_size && dst->nb[0] == type_size);
+ const bool dma_strides_ok = (src0->nb[0] == src0_es && src1->nb[0] == src1_es && dst->nb[0] == dst_es);
if (dma_strides_ok) {
kparams->kernel_type = HTP_CONCAT_KERNEL_REGULAR;
- kparams->n_hvx = 1;
+ if (all_same) {
+ kparams->n_hvx = 1;
+ kparams->vtcm_size = 0;
+ } else {
+ const uint32_t req_vt = n_hvx * 4 * HTP_CONCAT_REG_BLK_BYTES;
+ if (req_vt > vtcm_size) {
+ return false;
+ }
+ kparams->n_hvx = (uint8_t) n_hvx;
+ kparams->vtcm_size = req_vt;
+ kparams->u.regular.div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]);
+ kparams->u.regular.div_ne02_ne01 = init_fastdiv_values((uint32_t) (src0->ne[1] * src0->ne[2]));
+ kparams->u.regular.div_ne11 = init_fastdiv_values((uint32_t) src1->ne[1]);
+ kparams->u.regular.div_ne12_ne11 = init_fastdiv_values((uint32_t) (src1->ne[1] * src1->ne[2]));
+ }
return true;
}
- const bool is_src1_transposed = (src1->nb[0] > src1->nb[1]);
- const bool is_src0_transposed = (src0->nb[0] > src0->nb[1]);
- const bool transposed_rows_ok = (src0->nb[0] == type_size && src1->nb[1] == type_size && dst->nb[0] == type_size);
+ const bool is_src1_transposed = ggml_is_transposed(src1);
+ const bool is_src0_transposed = ggml_is_transposed(src0);
+ const bool src0_trans_ok = is_src0_transposed ? (src0->nb[1] == src0_es) : (src0->nb[0] == src0_es);
+ const bool src1_trans_ok = is_src1_transposed ? (src1->nb[1] == src1_es) : (src1->nb[0] == src1_es);
- if (dim == 0 && is_src1_transposed && !is_src0_transposed && transposed_rows_ok &&
+ if (dim == 0 && (is_src0_transposed || is_src1_transposed) &&
+ src0_trans_ok && src1_trans_ok && dst->nb[0] == dst_es &&
(dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16)) {
- const uint32_t nth = n_hvx > 0 ? n_hvx : 8;
- struct htp_concat_transposed_vtcm_layout layout;
- htp_concat_transposed_vtcm_layout_build(&layout, (uint32_t) src0->ne[0], (uint32_t) src1->ne[0], type_size, nth);
+ uint32_t req_vtcm = 0;
- if (vtcm_size > 0 && layout.total_bytes > vtcm_size) {
+ if (!is_src0_transposed && is_src1_transposed) {
+ struct htp_concat_transposed_vtcm_layout layout;
+ htp_concat_transposed_vtcm_layout_build(&layout, (uint32_t) src0->ne[0], (uint32_t) src1->ne[0], src0_es, src1_es, dst_es, n_hvx);
+ req_vtcm = layout.total_bytes;
+ } else {
+ struct htp_concat_transposed_vtcm_layout layout0;
+ htp_concat_transposed_vtcm_layout_build(&layout0, 0, (uint32_t) src0->ne[0], dst_es, src0_es, dst_es, n_hvx);
+ req_vtcm = layout0.total_bytes;
+ if (is_src1_transposed) {
+ struct htp_concat_transposed_vtcm_layout layout1;
+ htp_concat_transposed_vtcm_layout_build(&layout1, 0, (uint32_t) src1->ne[0], dst_es, src1_es, dst_es, n_hvx);
+ if (layout1.total_bytes > req_vtcm) {
+ req_vtcm = layout1.total_bytes;
+ }
+ } else if (src1_es != dst_es) {
+ const uint32_t reg_vtcm = n_hvx * 4 * HTP_CONCAT_REG_BLK_BYTES;
+ if (reg_vtcm > req_vtcm) {
+ req_vtcm = reg_vtcm;
+ }
+ }
+ }
+
+ if (req_vtcm > vtcm_size) {
return false;
}
kparams->kernel_type = HTP_CONCAT_KERNEL_TRANSPOSED;
- kparams->n_hvx = nth;
- kparams->vtcm_size = layout.total_bytes;
+ kparams->n_hvx = (uint8_t) n_hvx;
+ kparams->vtcm_size = req_vtcm;
kparams->u.transposed.div_ne2 = init_fastdiv_values((uint32_t) dst->ne[2]);
return true;
}
@@ -3045,9 +3613,9 @@ static bool htp_kparams_solve_cpy(
const bool sametype = (src0->type == dst->type);
const bool same_extents = ggml_are_same_shape(src0, dst);
- const bool transposed = (src0->nb[0] > src0->nb[1]) || (dst->nb[0] > dst->nb[1]) ||
+ const bool transposed = ggml_is_transposed(src0) || ggml_is_transposed(dst) ||
(src0->nb[0] != src_type_size) || (dst->nb[0] != dst_type_size) ||
- (src0->nb[1] < (size_t) src0->ne[0] * src_type_size) || (dst->nb[1] < (size_t) dst->ne[0] * dst_type_size);
+ (src0->nb[1] < ggml_row_size(src0->type, src0->ne[0])) || (dst->nb[1] < ggml_row_size(dst->type, dst->ne[0]));
const bool sameshape = same_extents && !transposed;
const bool src_is_contiguous = ggml_is_contiguous(src0);
@@ -3057,45 +3625,46 @@ static bool htp_kparams_solve_cpy(
const uint32_t mdev_count = htp_session_mdev_count(sess);
const size_t vtcm_size = htp_session_vtcm_size(sess);
- if (sametype) {
- if (src_is_contiguous && dst_is_contiguous) {
- kparams->kernel_type = HTP_COPY_KERNEL_1D_CONTIG;
- return true;
- }
+ if (sametype && src_is_contiguous && dst_is_contiguous) {
+ kparams->kernel_type = HTP_COPY_KERNEL_1D_CONTIG;
+ return true;
+ }
- const uint32_t max_gather_ne0 = 128 / src_type_size;
- const uint32_t total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]);
- if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) &&
- dst_is_contiguous && !src_is_contiguous &&
- src0->nb[0] == src_type_size && src0->ne[0] <= max_gather_ne0 &&
- src0->nb[1] >= (size_t) src0->ne[0] * src_type_size &&
- total_rows > 1 &&
- htp_gather_rows_tensor_outer_contiguous(src0)) {
-
- if (htp_gather_rows_solve_layout(&kparams->u.gather,
- (uint32_t) src0->ne[0], (uint32_t) src0->nb[1],
- 0, 0, false,
- src_type_size, total_rows,
- n_hvx, mdev_count, vtcm_size)) {
- kparams->kernel_type = HTP_COPY_KERNEL_GATHER_ROWS;
- kparams->n_hvx = (uint8_t) n_hvx;
- kparams->vtcm_size = kparams->u.gather.slice * n_hvx;
- return true;
- }
+ const uint32_t max_gather_ne0 = 128 / src_type_size;
+ const uint32_t total_rows = (uint32_t) ggml_nrows(src0);
+ if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) &&
+ (dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16) &&
+ dst_is_contiguous && !src_is_contiguous &&
+ src0->nb[0] == src_type_size && src0->ne[0] <= max_gather_ne0 &&
+ src0->nb[1] >= (size_t) src0->ne[0] * src_type_size &&
+ total_rows > 1 &&
+ htp_gather_rows_tensor_outer_contiguous(src0)) {
+
+ if (htp_gather_rows_solve_layout(&kparams->u.gather,
+ (uint32_t) src0->ne[0], (uint32_t) src0->nb[1],
+ 0, 0, false,
+ src_type_size, dst_type_size, total_rows,
+ n_hvx, mdev_count, vtcm_size)) {
+ kparams->kernel_type = HTP_COPY_KERNEL_GATHER_ROWS;
+ kparams->n_hvx = (uint8_t) n_hvx;
+ kparams->vtcm_size = kparams->u.gather.slice * n_hvx;
+ return true;
}
+ }
+ if (sametype) {
if (htp_kparams_solve_cpy_transpose(sess, src0, dst, src_type_size, kparams)) {
return true;
}
if (sameshape) {
kparams->kernel_type = HTP_COPY_KERNEL_SAMESHAPE_SAMETYPE;
- kparams->total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]);
+ kparams->total_rows = (uint32_t) ggml_nrows(src0);
return true;
}
kparams->kernel_type = HTP_COPY_KERNEL_RESHAPE;
- kparams->n_hvx = n_hvx > 0 ? (uint8_t) n_hvx : 4;
+ kparams->n_hvx = (uint8_t) n_hvx;
kparams->u.reshape.div_ne0 = init_fastdiv_values((uint32_t) dst->ne[0]);
kparams->u.reshape.div_ne1_ne0 = init_fastdiv_values((uint32_t) (dst->ne[1] * dst->ne[0]));
kparams->u.reshape.div_ne2_ne1_ne0 = init_fastdiv_values((uint32_t) (dst->ne[2] * dst->ne[1] * dst->ne[0]));
@@ -3117,17 +3686,16 @@ static bool htp_kparams_solve_cpy(
return false;
}
- const uint32_t nth = n_hvx > 0 ? n_hvx : 4;
struct htp_copy_convert_vtcm_layout layout;
- htp_copy_convert_solve_layout(&layout, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1], src_type_size, dst_type_size, nth);
+ htp_copy_convert_solve_layout(&layout, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1], src_type_size, dst_type_size, n_hvx);
- if (vtcm_size > 0 && layout.total_bytes > vtcm_size) {
+ if (layout.total_bytes > vtcm_size) {
return false;
}
kparams->kernel_type = HTP_COPY_KERNEL_SAMESHAPE_CONVERT;
- kparams->total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]);
- kparams->n_hvx = (uint8_t) nth;
+ kparams->total_rows = (uint32_t) ggml_nrows(src0);
+ kparams->n_hvx = (uint8_t) n_hvx;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
kparams->u.convert.blk_rows = layout.blk_rows;
kparams->u.convert.div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]);
@@ -3227,11 +3795,9 @@ static bool htp_kparams_solve_im2col(
is_patchembed = is_patchembed && (s1 == (int32_t) KH && p1 == 0 && d1 == 1);
}
- const uint32_t max_hvx = (sess && htp_session_n_hvx(sess) > 0) ? htp_session_n_hvx(sess) : 8;
+ const uint32_t max_hvx = htp_session_n_hvx(sess);
const uint32_t n_hvx = (total_rows < max_hvx) ? total_rows : max_hvx;
- const uint32_t vtcm_size = (sess && htp_session_vtcm_size(sess) > 0) ? (uint32_t) htp_session_vtcm_size(sess) : 0;
- const uint32_t row_size = (uint32_t) dst->nb[2];
- const uint32_t rows_per_chunk = (row_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(row_size, HEX_L2_LINE_SIZE)) : 1;
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
if (is_patchembed) {
const uint64_t src_row_bytes_raw = (uint64_t) IC * KH * IW * sizeof(float);
@@ -3244,7 +3810,7 @@ static bool htp_kparams_solve_im2col(
htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, n_hvx,
htp_im2col_scratch_bytes(HTP_IM2COL_KERNEL_PATCHEMBED_DMA, KH, patch_stride));
- if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) {
+ if (layout.total_bytes <= vtcm_size) {
kparams->kernel_type = HTP_IM2COL_KERNEL_PATCHEMBED_DMA;
kparams->n_hvx = (uint8_t) n_hvx;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
@@ -3266,7 +3832,6 @@ static bool htp_kparams_solve_im2col(
kparams->OW = OW;
kparams->patch_stride = patch_stride;
kparams->total_rows = total_rows;
- kparams->rows_per_chunk = rows_per_chunk;
kparams->div_OH = init_fastdiv_values(OH);
kparams->div_OD = init_fastdiv_values(1);
return true;
@@ -3300,7 +3865,7 @@ static bool htp_kparams_solve_im2col(
htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, blk_threads,
htp_im2col_scratch_bytes(HTP_IM2COL_KERNEL_BLOCKED_DMA, KH, patch_stride));
- if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) {
+ if (layout.total_bytes <= vtcm_size) {
kparams->kernel_type = HTP_IM2COL_KERNEL_BLOCKED_DMA;
kparams->n_hvx = (uint8_t) blk_threads;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
@@ -3322,7 +3887,6 @@ static bool htp_kparams_solve_im2col(
kparams->OW = OW;
kparams->patch_stride = patch_stride;
kparams->total_rows = total_rows;
- kparams->rows_per_chunk = rows_per_chunk;
kparams->div_OH = init_fastdiv_values(OH);
kparams->div_OD = init_fastdiv_values(1);
kparams->div_nbpr = init_fastdiv_values(nbpr);
@@ -3413,11 +3977,9 @@ static bool htp_kparams_solve_im2col_3d(
p0 == 0 && p1 == 0 && p2 == 0 &&
d0 == 1 && d1 == 1 && d2 == 1);
- const uint32_t max_hvx = (sess && htp_session_n_hvx(sess) > 0) ? htp_session_n_hvx(sess) : 8;
+ const uint32_t max_hvx = htp_session_n_hvx(sess);
const uint32_t n_hvx = (total_rows < max_hvx) ? total_rows : max_hvx;
- const uint32_t vtcm_size = (sess && htp_session_vtcm_size(sess) > 0) ? (uint32_t) htp_session_vtcm_size(sess) : 0;
- const uint32_t row_size = (uint32_t) dst->nb[2];
- const uint32_t rows_per_chunk = (row_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(row_size, HEX_L2_LINE_SIZE)) : 1;
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
if (is_patchembed) {
const uint64_t src_row_bytes_raw = (uint64_t) IC * KD * KH * IW * sizeof(float);
@@ -3429,7 +3991,7 @@ static bool htp_kparams_solve_im2col_3d(
struct htp_im2col_vtcm_layout layout;
htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, n_hvx, 256);
- if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) {
+ if (layout.total_bytes <= vtcm_size) {
kparams->kernel_type = HTP_IM2COL_KERNEL_PATCHEMBED_DMA;
kparams->n_hvx = (uint8_t) n_hvx;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
@@ -3451,7 +4013,6 @@ static bool htp_kparams_solve_im2col_3d(
kparams->OW = OW;
kparams->patch_stride = patch_stride;
kparams->total_rows = total_rows;
- kparams->rows_per_chunk = rows_per_chunk;
kparams->div_OH = init_fastdiv_values(OH);
kparams->div_OD = init_fastdiv_values(OD);
return true;
@@ -3479,7 +4040,7 @@ static bool htp_kparams_solve_im2col_3d(
struct htp_im2col_vtcm_layout layout;
htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, n_hvx, 256);
- if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) {
+ if (layout.total_bytes <= vtcm_size) {
kparams->kernel_type = HTP_IM2COL_KERNEL_BLOCKED_DMA;
kparams->n_hvx = (uint8_t) n_hvx;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
@@ -3501,7 +4062,6 @@ static bool htp_kparams_solve_im2col_3d(
kparams->OW = OW;
kparams->patch_stride = patch_stride;
kparams->total_rows = total_rows;
- kparams->rows_per_chunk = rows_per_chunk;
kparams->div_OH = init_fastdiv_values(OH);
kparams->div_OD = init_fastdiv_values(OD);
return true;
@@ -3522,7 +4082,7 @@ static bool htp_kparams_solve_pad(
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * dst = op;
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) {
return false;
}
@@ -3535,32 +4095,41 @@ static bool htp_kparams_solve_pad(
}
const uint32_t type_size = (uint32_t) ggml_type_size(src0->type);
- const uint32_t total_dst_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]);
- const uint32_t max_hvx = (std::max)(1u, total_dst_rows);
- const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
-
- struct htp_pad_vtcm_layout layout;
- htp_pad_vtcm_layout_build(&layout, (uint32_t) src0->ne[0] * type_size, (uint32_t) dst->ne[0] * type_size, n_hvx);
+ if (src0->nb[0] != type_size || dst->nb[0] != type_size) {
+ return false;
+ }
- const bool use_dma = (src0->nb[0] == type_size) && (src0->ne[0] >= 512) &&
- (htp_session_vtcm_size(sess) >= layout.total_bytes);
+ const uint32_t total_dst_rows = (uint32_t) ggml_nrows(dst);
+ const uint32_t max_hvx = (std::max)(1u, total_dst_rows);
+ uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ const uint32_t elems_per_vec = 128u / type_size;
+ const uint32_t row_elems_aligned = (uint32_t) hex_round_up((std::max)(1u, (uint32_t) dst->ne[0]), elems_per_vec);
- kparams->n_hvx = n_hvx;
- kparams->total_rows = total_dst_rows;
- kparams->use_dma = use_dma ? 1 : 0;
- kparams->elem_size = type_size;
- kparams->vtcm_size = use_dma ? (uint32_t) layout.total_bytes : 0;
-
- if (circular && use_dma) {
- kparams->kernel_type = HTP_PAD_KERNEL_HVX_CIRCULAR_DMA;
- } else if (circular) {
- kparams->kernel_type = HTP_PAD_KERNEL_HVX_CIRCULAR;
- } else if (use_dma) {
- kparams->kernel_type = HTP_PAD_KERNEL_HVX_DMA;
- } else {
- kparams->kernel_type = HTP_PAD_KERNEL_HVX;
+ uint32_t chunk_elems = row_elems_aligned;
+ struct htp_pad_vtcm_layout layout;
+ while (true) {
+ const size_t max_chunk_bytes = (vtcm_size / (4 * n_hvx)) & ~(size_t) 127;
+ if (max_chunk_bytes >= 128) {
+ chunk_elems = (std::min)(row_elems_aligned, (uint32_t) (max_chunk_bytes / type_size));
+ htp_pad_vtcm_layout_build(&layout, (size_t) chunk_elems * type_size, n_hvx);
+ if (layout.total_bytes <= vtcm_size) {
+ break;
+ }
+ }
+ if (n_hvx == 1) {
+ return false;
+ }
+ n_hvx--;
}
+ kparams->n_hvx = n_hvx;
+ kparams->total_rows = total_dst_rows;
+ kparams->chunk_elems = chunk_elems;
+ kparams->elem_size = type_size;
+ kparams->vtcm_size = (uint32_t) layout.total_bytes;
+ kparams->kernel_type = circular ? HTP_PAD_KERNEL_HVX_CIRCULAR : HTP_PAD_KERNEL_HVX;
+
kparams->div_ne1 = init_fastdiv_values((uint32_t) dst->ne[1]);
kparams->div_ne1_ne2 = init_fastdiv_values((uint32_t) (dst->ne[1] * dst->ne[2]));
kparams->div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]);
@@ -3580,26 +4149,44 @@ static bool htp_kparams_solve_cumsum(
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * dst = op;
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
return false;
}
if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) {
return false;
}
- const uint32_t total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]);
- const uint32_t max_hvx = (std::max)(1u, total_rows);
- const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ const size_t src_elem_size = ggml_type_size(src0->type);
+ const size_t dst_elem_size = ggml_type_size(dst->type);
+ const uint32_t align_elems = (src0->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F16) ? 64u : 32u;
+ const uint32_t total_rows = (uint32_t) ggml_nrows(src0);
+ const uint32_t max_hvx = (std::max)(1u, total_rows);
+ uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ const uint32_t row_elems_aligned = (uint32_t) hex_round_up((std::max)(1u, (uint32_t) src0->ne[0]), align_elems);
+ uint32_t chunk_elems = row_elems_aligned;
struct htp_cumsum_vtcm_layout layout;
- htp_cumsum_vtcm_layout_build(&layout, (uint32_t) src0->nb[1], (uint32_t) dst->nb[1], n_hvx);
-
- const bool use_dma = (htp_session_vtcm_size(sess) >= layout.total_bytes);
+ while (true) {
+ const size_t max_elems = (vtcm_size / (2 * n_hvx * (src_elem_size + dst_elem_size))) & ~(size_t) (align_elems - 1);
+ if (max_elems >= align_elems) {
+ chunk_elems = (std::min)(row_elems_aligned, (uint32_t) max_elems);
+ htp_cumsum_vtcm_layout_build(&layout, (size_t) chunk_elems * src_elem_size, (size_t) chunk_elems * dst_elem_size, n_hvx);
+ if (layout.total_bytes <= vtcm_size) {
+ break;
+ }
+ }
+ if (n_hvx == 1) {
+ return false;
+ }
+ n_hvx--;
+ }
- kparams->n_hvx = n_hvx;
- kparams->total_rows = total_rows;
- kparams->use_dma = use_dma ? 1 : 0;
- kparams->vtcm_size = use_dma ? (uint32_t) layout.total_bytes : 0;
+ kparams->n_hvx = n_hvx;
+ kparams->total_rows = total_rows;
+ kparams->chunk_elems = chunk_elems;
+ kparams->vtcm_size = (uint32_t) layout.total_bytes;
return true;
}
@@ -3811,19 +4398,37 @@ static bool htp_kparams_solve_fill(
const uint32_t ne1 = (uint32_t) dst->ne[1];
const uint32_t ne2 = (uint32_t) dst->ne[2];
const uint32_t ne3 = (uint32_t) dst->ne[3];
- const uint32_t nb1 = (uint32_t) dst->nb[1];
const uint32_t total_rows = ne1 * ne2 * ne3;
const uint32_t max_hvx = (std::max)(1u, total_rows);
- const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
const uint32_t elem_size = (uint32_t) ggml_type_size(dst->type);
- const uint32_t rows_per_chunk = (nb1 > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(nb1, HEX_L2_LINE_SIZE)) : 1;
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ const bool is_contig = ggml_is_contiguous(dst);
+ const size_t row_bytes = (size_t) dst->ne[0] * elem_size;
+ const size_t max_bytes = is_contig ? ((size_t) ((total_rows + n_hvx - 1) / n_hvx) * row_bytes) : row_bytes;
+ size_t tile_bytes = (std::min<size_t>)(16384u, hex_round_up((std::max<size_t>)(128u, max_bytes), 128));
+
+ struct htp_fill_vtcm_layout L;
+ htp_fill_vtcm_layout_build(&L, tile_bytes, n_hvx);
+ while (L.total_bytes > vtcm_size && tile_bytes > 128) {
+ tile_bytes = (std::max<size_t>)(128u, (tile_bytes / 2) & ~(size_t) 127);
+ htp_fill_vtcm_layout_build(&L, tile_bytes, n_hvx);
+ }
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_fill_vtcm_layout_build(&L, tile_bytes, n_hvx);
+ }
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
kparams->n_hvx = n_hvx;
kparams->total_rows = total_rows;
kparams->elem_size = elem_size;
- kparams->kernel_type = ggml_is_contiguous(dst) ? HTP_FILL_KERNEL_CONTIGUOUS : HTP_FILL_KERNEL_STRIDED;
- kparams->rows_per_chunk = rows_per_chunk;
+ kparams->kernel_type = is_contig ? HTP_FILL_KERNEL_CONTIGUOUS : HTP_FILL_KERNEL_STRIDED;
+ kparams->tile_bytes = (uint32_t) L.tile_bytes;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
kparams->div_ne1 = init_fastdiv_values(ne1);
kparams->div_ne1_ne2 = init_fastdiv_values(ne1 * ne2);
@@ -3928,7 +4533,7 @@ static bool htp_kparams_solve_roll(
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * dst = op;
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) {
return false;
}
if (!ggml_are_same_shape(src0, dst)) {
@@ -3938,6 +4543,7 @@ static bool htp_kparams_solve_roll(
return false;
}
+ const uint32_t elem_size = (uint32_t) ggml_type_size(src0->type);
const uint32_t ne0 = (uint32_t) dst->ne[0];
const uint32_t ne1 = (uint32_t) dst->ne[1];
const uint32_t ne2 = (uint32_t) dst->ne[2];
@@ -3955,12 +4561,13 @@ static bool htp_kparams_solve_roll(
const uint32_t total_rows = ne1 * ne2 * ne3;
const uint32_t max_hvx = (std::max)(1u, total_rows);
- const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
- kparams->n_hvx = n_hvx;
kparams->total_rows = total_rows;
kparams->i0_src0 = i0_src0;
kparams->n0 = ne0 - i0_src0;
+ kparams->elem_size = elem_size;
if (htp_session_mdev_count(sess) <= 1) {
if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) {
@@ -3968,10 +4575,20 @@ static bool htp_kparams_solve_roll(
} else {
kparams->kernel_type = HTP_ROLL_KERNEL_DMA_STRIDED;
}
+ kparams->vtcm_size = 0;
} else {
kparams->kernel_type = HTP_ROLL_KERNEL_HVX;
+ struct htp_roll_vtcm_layout L;
+ htp_roll_vtcm_layout_build(&L, (size_t) ne0 * elem_size, n_hvx);
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_roll_vtcm_layout_build(&L, (size_t) ne0 * elem_size, n_hvx);
+ }
+ kparams->vtcm_size = (L.total_bytes <= vtcm_size) ? (uint32_t) L.total_bytes : 0;
}
+ kparams->n_hvx = n_hvx;
+
kparams->div_ne1 = init_fastdiv_values(ne1);
kparams->div_ne2_ne1 = init_fastdiv_values(ne2 * ne1);
@@ -3988,7 +4605,7 @@ static bool htp_kparams_solve_diag(
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * dst = op;
- if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) {
return false;
}
if (src0->ne[1] != 1 || dst->ne[0] != dst->ne[1] || dst->ne[0] != src0->ne[0]) {
@@ -3999,39 +4616,37 @@ static bool htp_kparams_solve_diag(
return false;
}
+ const uint32_t elem_size = (uint32_t) ggml_type_size(src0->type);
+ const uint32_t elems_per_vec = 128u / elem_size;
const uint32_t total_batches = (uint32_t) (src0->ne[2] * src0->ne[3]);
const uint32_t max_hvx = (std::max)(1u, total_batches);
const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx);
- const uint32_t dst_batch_size = (uint32_t) (dst->ne[1] * dst->nb[1]);
-
- bool can_split = (dst->ne[0] == 1 || dst->nb[0] == sizeof(float)) && !ggml_is_permuted(dst);
- uint32_t batches_per_chunk = 1;
- if (can_split) {
- if (dst->ne[2] > 1 && (dst->nb[2] & (HEX_L2_LINE_SIZE - 1)) == 0 &&
- (dst->ne[3] <= 1 || (dst->nb[3] & (HEX_L2_LINE_SIZE - 1)) == 0)) {
- batches_per_chunk = 1;
- } else if (dst->nb[2] == dst_batch_size &&
- (dst->ne[3] <= 1 || dst->nb[3] == dst->nb[2] * dst->ne[2])) {
- batches_per_chunk = (dst_batch_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(dst_batch_size, HEX_L2_LINE_SIZE)) : 1;
- } else {
- can_split = false;
- }
- }
-
- const uint32_t src_batch_size = (uint32_t) (src0->ne[0] * sizeof(float));
- const uint32_t dst_row_size = (uint32_t) (dst->ne[0] * sizeof(float));
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ const uint32_t row_elems_aligned = (uint32_t) hex_round_up((std::max)(1u, (uint32_t) dst->ne[0]), elems_per_vec);
+ uint32_t diag_n_hvx = n_hvx;
+ uint32_t chunk_elems = row_elems_aligned;
struct htp_diag_vtcm_layout layout;
- htp_diag_vtcm_layout_build(&layout, src_batch_size, dst_row_size, n_hvx);
-
- const bool use_dma = (htp_session_vtcm_size(sess) >= layout.total_bytes);
+ while (true) {
+ const size_t per_hvx = vtcm_size / diag_n_hvx;
+ if (per_hvx >= 512) {
+ const size_t max_chunk_bytes = ((per_hvx - 256) / 2) & ~(size_t) 127;
+ chunk_elems = (std::min)(row_elems_aligned, (uint32_t) (max_chunk_bytes / elem_size));
+ htp_diag_vtcm_layout_build(&layout, (size_t) chunk_elems * elem_size, diag_n_hvx);
+ if (layout.total_bytes <= vtcm_size) {
+ break;
+ }
+ }
+ if (diag_n_hvx == 1) {
+ return false;
+ }
+ diag_n_hvx--;
+ }
- kparams->n_hvx = n_hvx;
+ kparams->n_hvx = diag_n_hvx;
kparams->total_batches = total_batches;
- kparams->use_dma = use_dma ? 1 : 0;
- kparams->can_split = can_split ? 1 : 0;
- kparams->batches_per_chunk = batches_per_chunk;
- kparams->vtcm_size = use_dma ? (uint32_t) layout.total_bytes : 0;
+ kparams->chunk_elems = chunk_elems;
+ kparams->vtcm_size = (uint32_t) layout.total_bytes;
kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]);
return true;
@@ -4048,7 +4663,9 @@ static bool htp_kparams_solve_solve_tri(
const struct ggml_tensor * src1 = op->src[1];
const struct ggml_tensor * dst = op;
- if (src0->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
+ (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
return false;
}
if (src0->ne[0] != src0->ne[1] || src0->ne[1] != src1->ne[1] ||
@@ -4056,8 +4673,14 @@ static bool htp_kparams_solve_solve_tri(
!ggml_are_same_shape(src1, dst)) {
return false;
}
+ if (src0->nb[0] != ggml_type_size(src0->type) ||
+ src1->nb[0] != ggml_type_size(src1->type) ||
+ dst->nb[0] != ggml_type_size(dst->type)) {
+ return false;
+ }
const uint32_t max_hvx_sess = htp_session_n_hvx(sess);
+ const uint32_t n = (uint32_t) src0->ne[0];
const uint32_t k = (uint32_t) src1->ne[0];
const uint32_t col_block = 32;
const uint32_t k_chunks = (k + col_block - 1) / col_block;
@@ -4065,9 +4688,23 @@ static bool htp_kparams_solve_solve_tri(
const bool batched = total_batches >= max_hvx_sess;
const uint32_t total_jobs = batched ? total_batches : (total_batches * k_chunks);
const uint32_t max_hvx = (std::max)(1u, total_jobs);
- const uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx);
- const uint32_t batch_size = (uint32_t) dst->nb[2];
- const uint32_t batches_per_chunk = (batch_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(batch_size, HEX_L2_LINE_SIZE)) : 1;
+ uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx);
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+
+ uint32_t a_full = 1;
+ struct htp_solve_tri_vtcm_layout L;
+ htp_solve_tri_vtcm_layout_build(&L, n, a_full, n_hvx);
+ if (L.total_bytes > vtcm_size) {
+ a_full = 0;
+ htp_solve_tri_vtcm_layout_build(&L, n, a_full, n_hvx);
+ while (L.total_bytes > vtcm_size && n_hvx > 1) {
+ n_hvx--;
+ htp_solve_tri_vtcm_layout_build(&L, n, a_full, n_hvx);
+ }
+ }
+ if (L.total_bytes > vtcm_size) {
+ return false;
+ }
kparams->n_hvx = n_hvx;
kparams->total_batches = total_batches;
@@ -4075,7 +4712,8 @@ static bool htp_kparams_solve_solve_tri(
kparams->k_chunks = k_chunks;
kparams->col_block = col_block;
kparams->batched = batched ? 1 : 0;
- kparams->batches_per_chunk = batches_per_chunk;
+ kparams->a_full = a_full;
+ kparams->vtcm_size = (uint32_t) L.total_bytes;
kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]);
kparams->div_k_chunks = init_fastdiv_values(k_chunks > 0 ? k_chunks : 1);
@@ -4570,7 +5208,7 @@ static bool htp_kparams_solve_conv2d_unchecked(
) {
memset(kparams, 0, sizeof(*kparams));
- const uint32_t total_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]);
+ const uint32_t total_rows = (uint32_t) ggml_nrows(dst);
kparams->total_rows = total_rows;
kparams->n_hvx = total_rows == 0 ? 1 : (std::min)((uint32_t) htp_session_n_hvx(sess), total_rows);
@@ -4710,10 +5348,7 @@ static bool htp_kparams_solve_conv2d_dw(
const uint32_t pad_rows = fast_k3x3 ? 4 : 0;
const uint32_t pad_top_stride = fast_k3x3 ? w : 0;
- const size_t vtcm_budget = (sess && htp_session_vtcm_size(sess) > 0) ? htp_session_vtcm_size(sess) : 0;
- if (vtcm_budget == 0) {
- return false;
- }
+ const size_t vtcm_budget = htp_session_vtcm_size(sess);
const uint32_t w_size = (uint32_t) (kw * kh * c * ggml_type_size(src0->type));
@@ -4823,14 +5458,11 @@ static bool htp_kparams_solve_conv3d(
}
}
- const size_t es = ggml_type_size(src0->type);
- const bool w_rows = src0->nb[0] == es && src0->nb[1] == src0->ne[0] * es && src0->nb[2] == src0->ne[1] * src0->nb[1] &&
- ((int64_t) IC * OC == 1 || src0->nb[3] == src0->ne[2] * src0->nb[2]);
- if (!w_rows || src1->nb[0] != sizeof(float) || dst->nb[2] != dst->ne[1] * dst->nb[1]) {
+ if (!ggml_is_contiguous(src0) || !ggml_is_contiguous_rows(src1) || dst->nb[2] != dst->ne[1] * dst->nb[1]) {
return false;
}
- const int64_t total_rows = dst->ne[1] * dst->ne[2] * dst->ne[3];
+ const int64_t total_rows = ggml_nrows(dst);
if (total_rows > UINT32_MAX) {
return false;
}
@@ -4840,90 +5472,6 @@ static bool htp_kparams_solve_conv3d(
return htp_kparams_conv2d_tiled(sess, op, kparams);
}
-static bool htp_dsv4_hc_pre_can_collapse(
- const struct ggml_tensor * x,
- const struct ggml_tensor * weights,
- const struct ggml_tensor * dst
-) {
- if (!x || !weights || !dst) {
- return false;
- }
- if (x->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
- return false;
- }
- if (x->nb[0] != sizeof(float) || weights->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) {
- return false;
- }
- if (x->ne[1] != 4 || dst->ne[0] != x->ne[0]) {
- return false;
- }
-
- const bool gated = ggml_get_op_params_i32(dst, 1) != 0;
- const int64_t x_tokens = x->ne[2] * x->ne[3];
- const int64_t d_tokens = dst->ne[1] * dst->ne[2] * dst->ne[3];
- const int64_t w_tokens = gated ? (weights->ne[2] * weights->ne[3]) : (weights->ne[1] * weights->ne[2] * weights->ne[3]);
-
- if (x_tokens != d_tokens || x_tokens != w_tokens) {
- return false;
- }
-
- if (x->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 &&
- (gated ? (weights->ne[3] == 1) : (weights->ne[2] == 1 && weights->ne[3] == 1))) {
- return false;
- }
-
- if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false;
-
- if (dst->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) return false;
- if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false;
-
- if (gated) {
- if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false;
- } else {
- if (weights->ne[2] > 1 && weights->nb[2] != weights->ne[1] * weights->nb[1]) return false;
- if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false;
- }
-
- return true;
-}
-
-static void htp_dsv4_hc_pre_collapse_tensors(
- const struct ggml_tensor * x,
- const struct ggml_tensor * weights,
- const struct ggml_tensor * dst,
- struct ggml_tensor * x_c,
- struct ggml_tensor * w_c,
- struct ggml_tensor * d_c
-) {
- const int64_t n_tokens = x->ne[2] * x->ne[3];
- const bool gated = ggml_get_op_params_i32(dst, 1) != 0;
-
- *x_c = *x;
- x_c->ne[2] = n_tokens;
- x_c->ne[3] = 1;
- x_c->nb[3] = x_c->ne[2] * x_c->nb[2];
-
- *d_c = *dst;
- d_c->ne[1] = n_tokens;
- d_c->ne[2] = 1;
- d_c->ne[3] = 1;
- d_c->nb[2] = d_c->ne[1] * d_c->nb[1];
- d_c->nb[3] = d_c->nb[2];
-
- *w_c = *weights;
- if (gated) {
- w_c->ne[2] = n_tokens;
- w_c->ne[3] = 1;
- w_c->nb[3] = w_c->ne[2] * w_c->nb[2];
- } else {
- w_c->ne[1] = n_tokens;
- w_c->ne[2] = 1;
- w_c->ne[3] = 1;
- w_c->nb[2] = w_c->ne[1] * w_c->nb[1];
- w_c->nb[3] = w_c->nb[2];
- }
-}
-
static bool htp_kparams_solve_dsv4_hc_pre_impl(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * x,
@@ -4933,7 +5481,10 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl(
) {
memset(kparams, 0, sizeof(*kparams));
- if (x->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ const auto is_valid_type = [](const ggml_tensor * t) {
+ return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type);
+ };
+ if (!is_valid_type(x) || !is_valid_type(weights) || !is_valid_type(dst)) {
return false;
}
if (x->ne[1] != 4 || x->ne[3] != 1) {
@@ -4945,9 +5496,6 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl(
if (dst->ne[0] != x->ne[0] || dst->ne[1] != x->ne[2] || dst->ne[2] != 1 || dst->ne[3] != 1) {
return false;
}
- if (x->nb[0] != sizeof(float) || weights->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) {
- return false;
- }
if (ggml_is_permuted(x) || ggml_is_permuted(weights) || ggml_is_permuted(dst)) {
return false;
}
@@ -4974,11 +5522,16 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl(
kparams->n_hvx = (std::min)(htp_session_n_hvx(sess), kparams->total_jobs);
kparams->jobs_per_hvx = (kparams->total_jobs + kparams->n_hvx - 1) / kparams->n_hvx;
+ const uint32_t x_es = (uint32_t) ggml_type_size(x->type);
+ const uint32_t w_es = (uint32_t) ggml_type_size(weights->type);
+ const uint32_t dst_es = (uint32_t) ggml_type_size(dst->type);
+ const uint32_t max_es = gated ? std::max({ x_es, w_es, dst_es }) : std::max(x_es, dst_es);
+
const size_t vtcm_budget = htp_session_vtcm_size(sess);
const uint32_t n_rows = gated ? HTP_DSV4_HC_PRE_GATED_ROWS : HTP_DSV4_HC_PRE_PLAIN_ROWS;
uint32_t block_chunks = (std::min)((uint32_t) HTP_DSV4_HC_MAX_CHUNKS, kparams->n_chunks);
while (block_chunks > 16) {
- const uint32_t stride = block_chunks * 128;
+ const uint32_t stride = std::max<uint32_t>(128, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128));
const uint32_t buf_sz = n_rows * stride;
if (2 * buf_sz * kparams->n_hvx <= vtcm_budget) {
break;
@@ -4987,7 +5540,7 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl(
}
kparams->dma_block_chunks = block_chunks;
- kparams->dma_row_stride = block_chunks * 128;
+ kparams->dma_row_stride = std::max<uint32_t>(128, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128));
kparams->dma_buffer_size = n_rows * kparams->dma_row_stride;
kparams->vtcm_size = 2 * kparams->dma_buffer_size * kparams->n_hvx;
if (kparams->vtcm_size > vtcm_budget) {
@@ -5013,114 +5566,6 @@ static inline bool htp_kparams_solve_dsv4_hc_pre(
return htp_kparams_solve_dsv4_hc_pre_impl(sess, op->src[0], op->src[1], op, kparams);
}
-static bool htp_dsv4_hc_post_can_collapse(
- const struct ggml_tensor * x,
- const struct ggml_tensor * residual,
- const struct ggml_tensor * post,
- const struct ggml_tensor * comb,
- const struct ggml_tensor * dst
-) {
- if (!x || !residual || !post || !dst) {
- return false;
- }
- if (x->type != GGML_TYPE_F32 || residual->type != GGML_TYPE_F32 || post->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
- return false;
- }
- if (comb && comb->type != GGML_TYPE_F32) {
- return false;
- }
- if (x->nb[0] != sizeof(float) || residual->nb[0] != sizeof(float) || post->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) {
- return false;
- }
- if (comb && comb->nb[0] != sizeof(float)) {
- return false;
- }
- if (residual->ne[0] != x->ne[0] || residual->ne[1] != 4 || dst->ne[0] != x->ne[0] || dst->ne[1] != 4 || post->ne[0] != 4) {
- return false;
- }
- if (comb && (comb->ne[0] != 4 || comb->ne[1] != 4)) {
- return false;
- }
-
- const int64_t x_tokens = x->ne[1] * x->ne[2] * x->ne[3];
- const int64_t r_tokens = residual->ne[2] * residual->ne[3];
- const int64_t p_tokens = post->ne[1] * post->ne[2] * post->ne[3];
- const int64_t d_tokens = dst->ne[2] * dst->ne[3];
- if (x_tokens != r_tokens || x_tokens != p_tokens || x_tokens != d_tokens) {
- return false;
- }
- if (comb && (comb->ne[2] * comb->ne[3] != x_tokens)) {
- return false;
- }
-
- if (x->ne[2] == 1 && x->ne[3] == 1 &&
- residual->ne[3] == 1 &&
- post->ne[2] == 1 && post->ne[3] == 1 &&
- dst->ne[3] == 1 &&
- (!comb || comb->ne[3] == 1)) {
- return false;
- }
-
- if (x->ne[2] > 1 && x->nb[2] != x->ne[1] * x->nb[1]) return false;
- if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false;
-
- if (residual->ne[3] > 1 && residual->nb[3] != residual->ne[2] * residual->nb[2]) return false;
- if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false;
-
- if (post->ne[2] > 1 && post->nb[2] != post->ne[1] * post->nb[1]) return false;
- if (post->ne[3] > 1 && post->nb[3] != post->ne[2] * post->nb[2]) return false;
-
- if (comb && comb->ne[3] > 1 && comb->nb[3] != comb->ne[2] * comb->nb[2]) return false;
-
- return true;
-}
-
-static void htp_dsv4_hc_post_collapse_tensors(
- const struct ggml_tensor * x,
- const struct ggml_tensor * residual,
- const struct ggml_tensor * post,
- const struct ggml_tensor * comb,
- const struct ggml_tensor * dst,
- struct ggml_tensor * x_c,
- struct ggml_tensor * r_c,
- struct ggml_tensor * p_c,
- struct ggml_tensor * c_c,
- struct ggml_tensor * d_c
-) {
- const int64_t n_tokens = x->ne[1] * x->ne[2] * x->ne[3];
-
- *x_c = *x;
- x_c->ne[1] = n_tokens;
- x_c->ne[2] = 1;
- x_c->ne[3] = 1;
- x_c->nb[2] = x_c->ne[1] * x_c->nb[1];
- x_c->nb[3] = x_c->nb[2];
-
- *r_c = *residual;
- r_c->ne[2] = n_tokens;
- r_c->ne[3] = 1;
- r_c->nb[3] = r_c->ne[2] * r_c->nb[2];
-
- *d_c = *dst;
- d_c->ne[2] = n_tokens;
- d_c->ne[3] = 1;
- d_c->nb[3] = d_c->ne[2] * d_c->nb[2];
-
- *p_c = *post;
- p_c->ne[1] = n_tokens;
- p_c->ne[2] = 1;
- p_c->ne[3] = 1;
- p_c->nb[2] = p_c->ne[1] * p_c->nb[1];
- p_c->nb[3] = p_c->nb[2];
-
- if (comb && c_c) {
- *c_c = *comb;
- c_c->ne[2] = n_tokens;
- c_c->ne[3] = 1;
- c_c->nb[3] = c_c->ne[2] * c_c->nb[2];
- }
-}
-
static bool htp_kparams_solve_dsv4_hc_post_impl(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * x,
@@ -5132,10 +5577,13 @@ static bool htp_kparams_solve_dsv4_hc_post_impl(
) {
memset(kparams, 0, sizeof(*kparams));
- if (x->type != GGML_TYPE_F32 || residual->type != GGML_TYPE_F32 || post->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
+ const auto is_valid_type = [](const ggml_tensor * t) {
+ return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type);
+ };
+ if (!is_valid_type(x) || !is_valid_type(residual) || !is_valid_type(post) || !is_valid_type(dst)) {
return false;
}
- if (comb && comb->type != GGML_TYPE_F32) {
+ if (comb && !is_valid_type(comb)) {
return false;
}
if (x->ne[2] != 1 || x->ne[3] != 1) {
@@ -5156,12 +5604,6 @@ static bool htp_kparams_solve_dsv4_hc_post_impl(
if (dst->ne[0] != x->ne[0] || dst->ne[1] != 4 || dst->ne[2] != x->ne[1] || dst->ne[3] != 1) {
return false;
}
- if (x->nb[0] != sizeof(float) || residual->nb[0] != sizeof(float) || post->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) {
- return false;
- }
- if (comb && comb->nb[0] != sizeof(float)) {
- return false;
- }
if (ggml_is_permuted(x) || ggml_is_permuted(residual) || ggml_is_permuted(post) || ggml_is_permuted(dst) || (comb && ggml_is_permuted(comb))) {
return false;
}
@@ -5178,10 +5620,15 @@ static bool htp_kparams_solve_dsv4_hc_post_impl(
kparams->n_hvx = (std::min)(htp_session_n_hvx(sess), kparams->total_jobs);
kparams->jobs_per_hvx = (kparams->total_jobs + kparams->n_hvx - 1) / kparams->n_hvx;
+ const uint32_t x_es = (uint32_t) ggml_type_size(x->type);
+ const uint32_t r_es = (uint32_t) ggml_type_size(residual->type);
+ const uint32_t dst_es = (uint32_t) ggml_type_size(dst->type);
+ const uint32_t max_es = std::max({ x_es, r_es, dst_es });
+
const size_t vtcm_budget = htp_session_vtcm_size(sess);
uint32_t block_chunks = (std::min)((uint32_t) HTP_DSV4_HC_MAX_CHUNKS, kparams->n_chunks);
while (block_chunks > 16) {
- const uint32_t stride = block_chunks * 128;
+ const uint32_t stride = std::max<uint32_t>(256, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128));
const uint32_t buf_sz = HTP_DSV4_HC_POST_ROWS * stride;
if (2 * buf_sz * kparams->n_hvx <= vtcm_budget) {
break;
@@ -5190,7 +5637,7 @@ static bool htp_kparams_solve_dsv4_hc_post_impl(
}
kparams->dma_block_chunks = block_chunks;
- kparams->dma_row_stride = block_chunks * 128;
+ kparams->dma_row_stride = std::max<uint32_t>(256, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128));
kparams->dma_buffer_size = HTP_DSV4_HC_POST_ROWS * kparams->dma_row_stride;
kparams->vtcm_size = 2 * kparams->dma_buffer_size * kparams->n_hvx;
if (kparams->vtcm_size > vtcm_budget) {
@@ -5216,92 +5663,6 @@ static inline bool htp_kparams_solve_dsv4_hc_post(
return htp_kparams_solve_dsv4_hc_post_impl(sess, op->src[0], op->src[1], op->src[2], op->src[3], op, kparams);
}
-static bool htp_lightning_indexer_can_collapse(
- const struct ggml_tensor * q,
- const struct ggml_tensor * k,
- const struct ggml_tensor * w,
- const struct ggml_tensor * m,
- const struct ggml_tensor * dst
-) {
- if (!q || !k || !w || !m || !dst) {
- return false;
- }
-
- // 2D K normalization: ne[1] is n_kv, ne[2] is 1
- const bool can_collapse_k = (k->ne[1] > 1 && k->ne[2] == 1);
-
- // Stream-to-token collapse across q, w, dst (and m)
- bool can_collapse_stream = false;
- if (q->ne[3] > 1 && k->ne[3] == 1) {
- const bool q_ok = (q->nb[3] == (size_t) q->ne[2] * q->nb[2]);
- const bool dst_ok = (dst->ne[3] == q->ne[3] && dst->ne[2] == 1 && dst->ne[1] == q->ne[2] &&
- dst->nb[3] == (size_t) dst->ne[1] * dst->nb[1]);
- const bool w_ok = (w->ne[3] == q->ne[3] && w->ne[2] == 1 && w->ne[1] == q->ne[2] &&
- w->nb[3] == (size_t) w->ne[1] * w->nb[1]) ||
- (w->ne[3] == 1 && w->ne[1] == q->ne[2] * q->ne[3]);
- const bool m_ok = (m->ne[3] == q->ne[3] && m->ne[2] == 1 && m->ne[1] == q->ne[2] &&
- m->nb[3] == (size_t) m->ne[1] * m->nb[1]) ||
- (m->ne[3] == 1 && m->ne[1] == q->ne[2] * q->ne[3]);
- can_collapse_stream = q_ok && dst_ok && w_ok && m_ok;
- }
-
- return can_collapse_k || can_collapse_stream;
-}
-
-static void htp_lightning_indexer_collapse_tensors(
- const struct ggml_tensor * q,
- const struct ggml_tensor * k,
- const struct ggml_tensor * w,
- const struct ggml_tensor * m,
- const struct ggml_tensor * dst,
- struct ggml_tensor * q_c,
- struct ggml_tensor * k_c,
- struct ggml_tensor * w_c,
- struct ggml_tensor * m_c,
- struct ggml_tensor * dst_c
-) {
- *q_c = *q;
- *k_c = *k;
- *w_c = *w;
- *m_c = *m;
- *dst_c = *dst;
-
- if (k->ne[1] > 1 && k->ne[2] == 1) {
- k_c->ne[2] = k->ne[1];
- k_c->ne[1] = 1;
- k_c->nb[1] = k->nb[1];
- k_c->nb[2] = k->nb[1];
- k_c->nb[3] = k->nb[2];
- }
-
- if (q->ne[3] > 1 && k->ne[3] == 1) {
- const int64_t n_tokens_collapsed = (int64_t) q->ne[2] * q->ne[3];
-
- q_c->ne[2] = n_tokens_collapsed;
- q_c->ne[3] = 1;
- q_c->nb[3] = (size_t) q_c->ne[2] * q_c->nb[2];
-
- if (w->ne[3] == q->ne[3]) {
- w_c->ne[1] = n_tokens_collapsed;
- w_c->ne[3] = 1;
- w_c->nb[2] = (size_t) w_c->ne[1] * w_c->nb[1];
- w_c->nb[3] = w_c->nb[2];
- }
-
- dst_c->ne[1] = n_tokens_collapsed;
- dst_c->ne[3] = 1;
- dst_c->nb[2] = (size_t) dst_c->ne[1] * dst_c->nb[1];
- dst_c->nb[3] = dst_c->nb[2];
-
- if (m->ne[3] == q->ne[3] && m->ne[1] == q->ne[2]) {
- m_c->ne[1] = n_tokens_collapsed;
- m_c->ne[3] = 1;
- m_c->nb[2] = (size_t) m_c->ne[1] * m_c->nb[1];
- m_c->nb[3] = m_c->nb[2];
- }
- }
-}
-
static bool htp_kparams_solve_lightning_indexer_impl(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * q,
@@ -5315,7 +5676,11 @@ static bool htp_kparams_solve_lightning_indexer_impl(
return false;
}
- if (k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_Q8_0 && k->type != GGML_TYPE_Q4_0) {
+ if ((q->type != GGML_TYPE_F32 && q->type != GGML_TYPE_F16) ||
+ (k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_Q8_0 && k->type != GGML_TYPE_Q4_0) ||
+ (w->type != GGML_TYPE_F32 && w->type != GGML_TYPE_F16) ||
+ m->type != GGML_TYPE_F16 ||
+ op->type != GGML_TYPE_F32) {
return false;
}
@@ -5365,7 +5730,7 @@ static bool htp_kparams_solve_lightning_indexer_impl(
while (nt2 > 32 && vtcm_usage(nt2, 64, 2) > htp_session_vtcm_size(sess)) {
nt2 /= 2;
}
- const size_t q_bytes = (size_t) nt2 * n_head * D * sizeof(float);
+ const size_t q_bytes = (size_t) nt2 * n_head * ggml_row_size(q->type, D);
const size_t k_bytes = (size_t) k->ne[2] * ggml_row_size(k->type, D);
if (vtcm_usage(nt2, 64, 2) <= htp_session_vtcm_size(sess) && q_bytes >= k_bytes) {
n_tok = nt2;
@@ -5454,217 +5819,207 @@ static inline bool htp_kparams_invoke(
return SolveFn(sess, op, kparams ? (KParams *) kparams : &tmp);
}
-void htp_opnode_collapse(const struct ggml_hexagon_session * sess, htp_opnode & node) {
- const uint32_t n_hvx = htp_session_n_hvx(sess);
+bool htp_kparams_solve(
+ const struct ggml_hexagon_session * sess,
+ htp_opnode & node
+) {
+ ggml_tensor scratch[HTP_OP_MAX_INPUTS + HTP_OP_MAX_OUTPUTS];
+ htp_opnode tmp = node;
+ htp_lower_opnode(sess, tmp, scratch);
- if (htp_op_is_unary(node.opcode) && htp_unary_is_elementwise(node.opcode)) {
- if (node.inputs.empty() || !node.inputs[0] || node.outputs.empty() || !node.outputs[0]) {
- return;
- }
- if (!ggml_are_same_shape(node.inputs[0], node.outputs[0])) {
- return;
- }
- const size_t elem_size = ggml_type_size(node.inputs[0]->type);
- struct ggml_tensor src0_c = *node.inputs[0];
- struct ggml_tensor dst_c = *node.outputs[0];
- struct ggml_tensor * tensors[2] = { &src0_c, &dst_c };
- htp_collapse_dims(tensors, 2, elem_size, n_hvx);
- if (src0_c.ne[0] != node.inputs[0]->ne[0] || src0_c.ne[1] != node.inputs[0]->ne[1]) {
- node.inputs[0] = node.add_dummy(src0_c);
- node.outputs[0] = node.add_dummy(dst_c);
- }
- return;
- }
+ const ggml_tensor * src0 = tmp.inputs.empty() ? nullptr : tmp.inputs[0];
+ const ggml_tensor * src1 = tmp.inputs.size() > 1 ? tmp.inputs[1] : nullptr;
+ const ggml_tensor * dst = tmp.dst();
- if (htp_op_is_glu(node.opcode)) {
- if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) {
- return;
- }
- if (!ggml_are_same_shape(node.inputs[0], node.outputs[0]) ||
- !ggml_are_same_shape(node.inputs[1], node.outputs[0])) {
- return;
+ auto commit = [&](bool ok) {
+ if (ok) {
+ memcpy(node.kernel_params, tmp.kernel_params, sizeof(node.kernel_params));
}
- const size_t elem_size = ggml_type_size(node.inputs[0]->type);
- struct ggml_tensor src0_c = *node.inputs[0];
- struct ggml_tensor src1_c = *node.inputs[1];
- struct ggml_tensor dst_c = *node.outputs[0];
- struct ggml_tensor * tensors[3] = { &src0_c, &src1_c, &dst_c };
- htp_collapse_dims(tensors, 3, elem_size, n_hvx);
- if (src0_c.ne[0] != node.inputs[0]->ne[0] || src0_c.ne[1] != node.inputs[0]->ne[1]) {
- node.inputs[0] = node.add_dummy(src0_c);
- node.inputs[1] = node.add_dummy(src1_c);
- node.outputs[0] = node.add_dummy(dst_c);
+ return ok;
+ };
+
+ if (htp_op_is_unary(tmp.opcode)) {
+ auto * kp = tmp.kparams<htp_unary_kernel_params>();
+ const uint32_t has_scale_bias = kp->has_scale_bias;
+ const float in_scale = kp->in_scale;
+ const float in_bias = kp->in_bias;
+ const float out_scale = kp->out_scale;
+ const float out_bias = kp->out_bias;
+ const ggml_tensor * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr;
+ const bool ok = htp_kparams_solve_unary_impl(sess, tmp.opcode, src0, src1, src2, dst, kp);
+ if (has_scale_bias) {
+ kp->has_scale_bias = has_scale_bias;
+ kp->in_scale = in_scale;
+ kp->in_bias = in_bias;
+ kp->out_scale = out_scale;
+ kp->out_bias = out_bias;
+ }
+ return commit(ok);
+ }
+ if (htp_op_is_glu(tmp.opcode)) {
+ return commit(htp_kparams_solve_unary_mul_glu(sess, tmp.opcode, src0, src1, dst, tmp.kparams<htp_glu_kernel_params>()));
+ }
+ if (tmp.opcode == HTP_OP_MUL_MAT || tmp.opcode == HTP_OP_MUL_MAT_ID) {
+ if (!htp_matmul_check_types(src0, src1, dst)) {
+ return false;
}
- return;
+ return commit(htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, tmp.kparams<htp_mm_kernel_params>()));
}
-
- if (node.opcode == HTP_OP_MUL_MAT) {
- if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) {
- return;
+ if (tmp.opcode == HTP_OP_MUL_MAT_ADD) {
+ if (tmp.inputs.size() != 3) {
+ return false;
}
- const struct ggml_tensor * src0 = node.inputs[0];
- const struct ggml_tensor * src1 = node.inputs[1];
- const struct ggml_tensor * dst = node.outputs[0];
- if (htp_matmul_can_collapse(src0, src1, dst)) {
- node.inputs[1] = node.add_dummy(htp_tensor_collapse_rows(src1));
- node.outputs[0] = node.add_dummy(htp_tensor_collapse_rows(dst));
+ const ggml_tensor * bias = tmp.inputs[2];
+ if ((bias->type != GGML_TYPE_F32 && bias->type != GGML_TYPE_F16) ||
+ bias->nb[0] != ggml_type_size(bias->type) ||
+ !htp_matmul_check_types(src0, src1, dst)) {
+ return false;
}
- return;
+ return commit(htp_kparams_solve_matmul_impl(sess, src0, src1, bias, dst, tmp.kparams<htp_mm_kernel_params>()));
}
-
- if (node.opcode == HTP_OP_MUL_MAT_ADD) {
- if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) {
- return;
+ if (tmp.opcode == HTP_OP_MUL_MAT_NX) {
+ const size_t n_w = tmp.outputs.size();
+ if (n_w == 0 || tmp.inputs.size() != n_w + 1) {
+ return false;
}
- const struct ggml_tensor * src0 = node.inputs[0];
- const struct ggml_tensor * src1 = node.inputs[1];
- const struct ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr;
- const struct ggml_tensor * dst = node.outputs[0];
- if (htp_matmul_add_can_collapse(src0, src1, src2, dst)) {
- node.inputs[1] = node.add_dummy(htp_tensor_collapse_rows(src1));
- node.outputs[0] = node.add_dummy(htp_tensor_collapse_rows(dst));
- if (src2 && (src2->ne[1] * src2->ne[2] * src2->ne[3] > 1)) {
- node.inputs[2] = node.add_dummy(htp_tensor_collapse_rows(src2));
+ const ggml_tensor * act = tmp.inputs[n_w];
+ const ggml_tensor * w_for_solve = tmp.inputs[0];
+ const ggml_tensor * dst_for_solve = tmp.outputs[0];
+ ggml_type max_dst_type = tmp.outputs[0]->type;
+ for (size_t i = 0; i < n_w; ++i) {
+ if (!htp_matmul_check_types(tmp.inputs[i], act, tmp.outputs[i])) {
+ return false;
+ }
+ if (tmp.inputs[i]->ne[1] > w_for_solve->ne[1]) {
+ w_for_solve = tmp.inputs[i];
+ }
+ if (ggml_type_size(tmp.outputs[i]->type) > ggml_type_size(max_dst_type)) {
+ max_dst_type = tmp.outputs[i]->type;
}
}
- return;
- }
-
- if (node.opcode == HTP_OP_UPSCALE) {
- if (node.inputs.empty() || !node.inputs[0] || node.outputs.empty() || !node.outputs[0]) {
- return;
- }
- const struct ggml_tensor * src0 = node.inputs[0];
- const struct ggml_tensor * dst = node.outputs[0];
-
- if ((src0->ne[3] > 1 || dst->ne[3] > 1) &&
- src0->ne[2] == dst->ne[2] && src0->ne[3] == dst->ne[3] &&
- src0->nb[3] == (size_t) src0->ne[2] * src0->nb[2] &&
- dst->nb[3] == (size_t) dst->ne[2] * dst->nb[2]) {
- struct ggml_tensor src0_c = *src0;
- struct ggml_tensor dst_c = *dst;
- src0_c.ne[2] *= src0_c.ne[3];
- src0_c.ne[3] = 1;
- src0_c.nb[3] = (size_t) src0_c.ne[2] * src0_c.nb[2];
- dst_c.ne[2] *= dst_c.ne[3];
- dst_c.ne[3] = 1;
- dst_c.nb[3] = (size_t) dst_c.ne[2] * dst_c.nb[2];
- node.inputs[0] = node.add_dummy(src0_c);
- node.outputs[0] = node.add_dummy(dst_c);
+ ggml_tensor d_for_solve = *dst_for_solve;
+ d_for_solve.type = max_dst_type;
+ if (!htp_kparams_solve_mmnx(sess, w_for_solve, act, &d_for_solve, (int32_t) n_w, tmp.kparams<htp_mm_kernel_params>())) {
+ return false;
}
- return;
+ const auto * kp = tmp.kparams<htp_mm_kernel_params>();
+ const bool ok = kp->n_hmx ? htp_mm_kernel_is_hmx_2d(kp->kernel_type)
+ : (ggml_hexagon_tensor_is_tiled(tmp.inputs[0]) &&
+ (kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK));
+ return commit(ok);
}
-
- if (node.opcode == HTP_OP_DSV4_HC_PRE) {
- if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) {
- return;
- }
- const struct ggml_tensor * x = node.inputs[0];
- const struct ggml_tensor * weights = node.inputs[1];
- const struct ggml_tensor * dst = node.outputs[0];
-
- if (htp_dsv4_hc_pre_can_collapse(x, weights, dst)) {
- struct ggml_tensor x_c, w_c, d_c;
- htp_dsv4_hc_pre_collapse_tensors(x, weights, dst, &x_c, &w_c, &d_c);
- node.inputs[0] = node.add_dummy(x_c);
- node.inputs[1] = node.add_dummy(w_c);
- node.outputs[0] = node.add_dummy(d_c);
+ if (tmp.opcode == HTP_OP_MUL_MAT_NX_GLU) {
+ if (tmp.inputs.size() != 3 || tmp.outputs.size() != 1) {
+ return false;
}
- return;
+ const uint8_t glu_op = tmp.kparams<htp_mm_kernel_params>()->glu_op;
+ return commit(htp_kparams_solve_mmnx_glu(sess, tmp.inputs[0], tmp.inputs[1], tmp.inputs[2], tmp.outputs[0], glu_op, tmp.kparams<htp_mm_kernel_params>()));
}
-
- if (node.opcode == HTP_OP_DSV4_HC_POST) {
- if (node.inputs.size() < 3 || !node.inputs[0] || !node.inputs[1] || !node.inputs[2] || node.outputs.empty() || !node.outputs[0]) {
- return;
+ if (tmp.opcode == HTP_OP_MUL_MAT_ID_NX) {
+ const size_t n_w = tmp.outputs.size();
+ if (n_w == 0 || tmp.inputs.size() != n_w + 2) {
+ return false;
}
- const struct ggml_tensor * x = node.inputs[0];
- const struct ggml_tensor * residual = node.inputs[1];
- const struct ggml_tensor * post = node.inputs[2];
- const struct ggml_tensor * comb = node.inputs.size() > 3 ? node.inputs[3] : nullptr;
- const struct ggml_tensor * dst = node.outputs[0];
-
- if (htp_dsv4_hc_post_can_collapse(x, residual, post, comb, dst)) {
- struct ggml_tensor x_c, r_c, p_c, c_c, d_c;
- htp_dsv4_hc_post_collapse_tensors(x, residual, post, comb, dst, &x_c, &r_c, &p_c, comb ? &c_c : nullptr, &d_c);
- node.inputs[0] = node.add_dummy(x_c);
- node.inputs[1] = node.add_dummy(r_c);
- node.inputs[2] = node.add_dummy(p_c);
- if (comb) {
- node.inputs[3] = node.add_dummy(c_c);
+ const ggml_tensor * act = tmp.inputs[n_w];
+ const ggml_tensor * w_for_solve = tmp.inputs[0];
+ const ggml_tensor * dst_for_solve = tmp.outputs[0];
+ ggml_type max_dst_type = tmp.outputs[0]->type;
+ for (size_t i = 0; i < n_w; ++i) {
+ if (!htp_matmul_check_types(tmp.inputs[i], act, tmp.outputs[i])) {
+ return false;
+ }
+ if (tmp.inputs[i]->ne[1] > w_for_solve->ne[1]) {
+ w_for_solve = tmp.inputs[i];
+ }
+ if (ggml_type_size(tmp.outputs[i]->type) > ggml_type_size(max_dst_type)) {
+ max_dst_type = tmp.outputs[i]->type;
}
- node.outputs[0] = node.add_dummy(d_c);
}
- return;
- }
-
- if (node.opcode == HTP_OP_LIGHTNING_INDEXER) {
- if (node.inputs.size() < 4 || !node.inputs[0] || !node.inputs[1] || !node.inputs[2] || !node.inputs[3] || node.outputs.empty() || !node.outputs[0]) {
- return;
+ ggml_tensor d_for_solve = *dst_for_solve;
+ d_for_solve.type = max_dst_type;
+ if (!htp_kparams_solve_mmidnx(sess, w_for_solve, act, &d_for_solve, (int32_t) n_w, tmp.kparams<htp_mm_kernel_params>())) {
+ return false;
+ }
+ const auto * kp = tmp.kparams<htp_mm_kernel_params>();
+ const bool ok = kp->n_hmx ? htp_mm_kernel_is_hmx_2d(kp->kernel_type)
+ : (ggml_hexagon_tensor_is_tiled(tmp.inputs[0]) &&
+ (kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK));
+ return commit(ok);
+ }
+ if (tmp.opcode == HTP_OP_UPSCALE) {
+ return commit(htp_kparams_solve_upscale(sess, src0, dst, tmp.kparams<htp_upscale_kernel_params>()));
+ }
+ if (tmp.opcode == HTP_OP_DSV4_HC_PRE) {
+ return commit(htp_kparams_solve_dsv4_hc_pre_impl(sess, src0, src1, dst, tmp.kparams<htp_dsv4_hc_pre_kernel_params>()));
+ }
+ if (tmp.opcode == HTP_OP_DSV4_HC_POST) {
+ const ggml_tensor * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr;
+ const ggml_tensor * src3 = tmp.inputs.size() > 3 ? tmp.inputs[3] : nullptr;
+ return commit(htp_kparams_solve_dsv4_hc_post_impl(sess, src0, src1, src2, src3, dst, tmp.kparams<htp_dsv4_hc_post_kernel_params>()));
+ }
+ if (tmp.opcode == HTP_OP_LIGHTNING_INDEXER) {
+ const ggml_tensor * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr;
+ const ggml_tensor * src3 = tmp.inputs.size() > 3 ? tmp.inputs[3] : nullptr;
+ return commit(htp_kparams_solve_lightning_indexer_impl(sess, src0, src1, src2, src3, dst, tmp.kparams<htp_lid_kernel_params>()));
+ }
+ if (tmp.opcode == HTP_OP_GET_ROWS) {
+ return commit(htp_kparams_solve_repeat_get_rows(sess, src0, src1, dst, tmp.kparams<htp_get_rows_kernel_params>()));
+ }
+ if (tmp.opcode == HTP_OP_SSM_CONV) {
+ auto * kp = tmp.kparams<htp_ssm_conv_kernel_params>();
+ const uint32_t silu = kp->silu;
+ bool ok = false;
+ if (tmp.inputs.size() == 3 && !tmp.outputs.empty() && tmp.outputs.size() <= 2) {
+ const ggml_tensor * dst_state = (tmp.outputs.size() == 2) ? tmp.outputs[1] : nullptr;
+ ok = htp_kparams_solve_ssm_conv_token_major(sess, src0, src1, tmp.inputs[2], tmp.outputs[0], dst_state, kp);
+ } else if (tmp.inputs.size() == 2 && tmp.outputs.size() == 1) {
+ ok = htp_kparams_solve_ssm_conv(sess, src0, src1, dst, kp);
+ }
+ kp->silu = silu;
+ return commit(ok);
+ }
+ if (tmp.opcode == HTP_OP_GATED_DELTA_NET) {
+ if ((tmp.inputs.size() != 6 && tmp.inputs.size() != 7 && tmp.inputs.size() != 10) ||
+ tmp.outputs.empty() || tmp.outputs.size() > 2) {
+ return false;
}
- const struct ggml_tensor * q = node.inputs[0];
- const struct ggml_tensor * k = node.inputs[1];
- const struct ggml_tensor * w = node.inputs[2];
- const struct ggml_tensor * m = node.inputs[3];
- const struct ggml_tensor * dst = node.outputs[0];
-
- if (htp_lightning_indexer_can_collapse(q, k, w, m, dst)) {
- struct ggml_tensor q_c, k_c, w_c, m_c, d_c;
- htp_lightning_indexer_collapse_tensors(q, k, w, m, dst, &q_c, &k_c, &w_c, &m_c, &d_c);
- node.inputs[0] = node.add_dummy(q_c);
- node.inputs[1] = node.add_dummy(k_c);
- node.inputs[2] = node.add_dummy(w_c);
- node.inputs[3] = node.add_dummy(m_c);
- node.outputs[0] = node.add_dummy(d_c);
+ ggml_tensor op_view = *tmp.outputs[0];
+ op_view.op = tmp.node->op;
+ op_view.flags = tmp.node->flags;
+ memcpy(op_view.op_params, tmp.params, sizeof(op_view.op_params));
+ for (size_t i = 6; i < GGML_MAX_SRC; ++i) {
+ op_view.src[i] = nullptr;
}
- return;
+ for (size_t i = 0; i < tmp.inputs.size(); ++i) {
+ op_view.src[i] = const_cast<ggml_tensor *>(tmp.inputs[i]);
+ }
+ const ggml_tensor * dst_cache = (tmp.outputs.size() == 2) ? tmp.outputs[1] : nullptr;
+ return commit(htp_kparams_solve_gated_delta_net(sess, &op_view, dst_cache, tmp.kparams<htp_gdn_kernel_params>()));
}
-}
-
-bool htp_kparams_solve(
- const struct ggml_hexagon_session * sess,
- htp_opnode & node
-) {
- htp_opnode_collapse(sess, node);
-
- const ggml_tensor * src0 = node.inputs.empty() ? nullptr : node.inputs[0];
- const ggml_tensor * src1 = node.inputs.size() > 1 ? node.inputs[1] : nullptr;
- const ggml_tensor * dst = node.dst();
- if (htp_op_is_unary(node.opcode)) {
- return htp_kparams_solve_unary_impl(sess, node.opcode, src0, src1, dst, node.kparams<htp_unary_kernel_params>());
- }
- if (htp_op_is_glu(node.opcode)) {
- return htp_kparams_solve_unary_mul_glu(sess, node.opcode, src0, src1, dst, node.kparams<htp_glu_kernel_params>());
- }
- if (node.opcode == HTP_OP_MUL_MAT) {
- if (!htp_matmul_check_types(src0, src1, dst)) {
- return false;
+ if (!tmp.fused.empty() &&
+ (tmp.opcode == HTP_OP_ADD || tmp.opcode == HTP_OP_SUB ||
+ tmp.opcode == HTP_OP_MUL || tmp.opcode == HTP_OP_DIV)) {
+ auto * kp = tmp.kparams<htp_binary_kernel_params>();
+ if (kp->kernel_type != HTP_BINARY_KERNEL_SCALAR && kp->n_srcs > 2 &&
+ tmp.inputs.size() == kp->n_srcs && tmp.outputs.size() == 1) {
+ return commit(htp_kparams_solve_binary_nx(sess, tmp, kp));
}
- return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, 0, 0, node.kparams<htp_mm_kernel_params>());
- }
- if (node.opcode == HTP_OP_MUL_MAT_ADD) {
- const ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr;
- const size_t src2_size = src2 ? hex_round_up(ggml_nbytes(src2), 128) : 0;
- return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, src2 ? src2->nb[1] : 0, src2_size, node.kparams<htp_mm_kernel_params>());
- }
- if (node.opcode == HTP_OP_UPSCALE) {
- return htp_kparams_solve_upscale(sess, src0, dst, node.kparams<htp_upscale_kernel_params>());
}
- if (node.opcode == HTP_OP_DSV4_HC_PRE) {
- return htp_kparams_solve_dsv4_hc_pre_impl(sess, src0, src1, dst, node.kparams<htp_dsv4_hc_pre_kernel_params>());
- }
- if (node.opcode == HTP_OP_DSV4_HC_POST) {
- const ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr;
- const ggml_tensor * src3 = node.inputs.size() > 3 ? node.inputs[3] : nullptr;
- return htp_kparams_solve_dsv4_hc_post_impl(sess, src0, src1, src2, src3, dst, node.kparams<htp_dsv4_hc_post_kernel_params>());
+
+ if (!tmp.fused.empty()) {
+ return false;
}
- if (node.opcode == HTP_OP_LIGHTNING_INDEXER) {
- const ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr;
- const ggml_tensor * src3 = node.inputs.size() > 3 ? node.inputs[3] : nullptr;
- return htp_kparams_solve_lightning_indexer_impl(sess, src0, src1, src2, src3, dst, node.kparams<htp_lid_kernel_params>());
+
+ ggml_tensor op_view = *tmp.dst();
+ op_view.op = tmp.node->op;
+ op_view.flags = tmp.node->flags;
+ memcpy(op_view.op_params, tmp.params, sizeof(op_view.op_params));
+ for (size_t i = 0; i < tmp.inputs.size(); ++i) {
+ op_view.src[i] = const_cast<ggml_tensor *>(tmp.inputs[i]);
}
- return htp_kparams_solve(sess, node.node, node.kernel_params);
+ return commit(htp_kparams_solve(sess, &op_view, tmp.kernel_params));
}
bool htp_kparams_solve(
@@ -5709,7 +6064,11 @@ bool htp_kparams_solve(
return htp_kparams_invoke<htp_kparams_solve_rope>(sess, op, kparams);
case HTP_OP_SSM_CONV:
- return htp_kparams_invoke<htp_kparams_solve_ssm_conv>(sess, op, kparams);
+ {
+ struct htp_ssm_conv_kernel_params tmp;
+ return htp_kparams_solve_ssm_conv(sess, op->src[0], op->src[1], op,
+ kparams ? (struct htp_ssm_conv_kernel_params *) kparams : &tmp);
+ }
case HTP_OP_SSM_SCAN:
return htp_kparams_invoke<htp_kparams_solve_ssm_scan>(sess, op, kparams);
@@ -5718,7 +6077,11 @@ bool htp_kparams_solve(
return htp_kparams_invoke<htp_kparams_solve_softmax>(sess, op, kparams);
case HTP_OP_GATED_DELTA_NET:
- return htp_kparams_invoke<htp_kparams_solve_gated_delta_net>(sess, op, kparams);
+ {
+ struct htp_gdn_kernel_params tmp;
+ return htp_kparams_solve_gated_delta_net(sess, op, nullptr,
+ kparams ? (struct htp_gdn_kernel_params *) kparams : &tmp);
+ }
case HTP_OP_ARGSORT:
case HTP_OP_TOP_K:
@@ -5792,12 +6155,6 @@ bool htp_kparams_solve(
return htp_kparams_invoke<htp_kparams_solve_dsv4_hc_post>(sess, op, kparams);
default:
- if (htp_op_is_unary(opcode)) {
- return htp_kparams_invoke<htp_kparams_solve_unary>(sess, op, kparams);
- }
- if (htp_op_is_glu(opcode)) {
- return htp_kparams_invoke<htp_kparams_solve_glu>(sess, op, kparams);
- }
return false;
}
}
diff --git a/ggml/src/ggml-hexagon/htp-kparams.h b/ggml/src/ggml-hexagon/htp-kparams.h
index bae41ef1b..1927c7d7b 100644
--- a/ggml/src/ggml-hexagon/htp-kparams.h
+++ b/ggml/src/ggml-hexagon/htp-kparams.h
@@ -2,6 +2,7 @@
#define HTP_KPARAMS_H
#include "htp-common.h"
+#include "htp-lower.h"
#include "htp/allreduce-ops.h"
#include "htp/argsort-ops.h"
@@ -39,11 +40,6 @@
#include <type_traits>
#include <utility>
-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);
-bool htp_matmul_add_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * src2, const struct ggml_tensor * dst);
-ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t);
-
template <typename... Args>
auto htp_kparams_type(bool (*)(Args...)) -> std::remove_pointer_t<std::remove_reference_t<decltype((std::declval<Args>(), ...))>>;
@@ -60,11 +56,6 @@ bool htp_kparams_solve(
struct htp_opnode & node
);
-void htp_opnode_collapse(
- const struct ggml_hexagon_session * sess,
- struct htp_opnode & node
-);
-
bool htp_kparams_solve(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * op,
@@ -101,6 +92,7 @@ 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
);
@@ -109,7 +101,7 @@ 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 * src2,
+ const struct ggml_tensor * bias,
const struct ggml_tensor * dst,
struct htp_mm_kernel_params * kparams
);
@@ -118,10 +110,21 @@ 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,
diff --git a/ggml/src/ggml-hexagon/htp-lower.cpp b/ggml/src/ggml-hexagon/htp-lower.cpp
new file mode 100644
index 000000000..372bccb26
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp-lower.cpp
@@ -0,0 +1,1260 @@
+#include "htp-lower.h"
+
+#include "htp-common.h"
+#include "htp-kparams.h"
+#include "htp-opnode.h"
+
+#include <algorithm>
+#include <cstring>
+#include <unordered_map>
+#include <unordered_set>
+
+bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride) {
+ size_t s = 0, next = 0;
+ for (int i = 1; i < GGML_MAX_DIMS; i++) {
+ if (ne[i] == 1) continue;
+ if (s == 0) { s = nb[i]; next = s * ne[i]; continue; }
+ if (nb[i] != next) return false;
+ next *= ne[i];
+ }
+ *stride = s ? s : nb[1];
+ return true;
+}
+
+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) &&
+ 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);
+}
+
+bool htp_matmul_add_can_collapse(
+ const struct ggml_tensor * src0,
+ const struct ggml_tensor * src1,
+ const struct ggml_tensor * src2,
+ const struct ggml_tensor * dst
+) {
+ if (!htp_matmul_can_collapse(src0, src1, dst)) {
+ return false;
+ }
+ if (!src2) {
+ return true;
+ }
+ const int64_t src2_nrows = src2->ne[1] * src2->ne[2] * src2->ne[3];
+ if (src2_nrows == 1) {
+ return true;
+ }
+ size_t s2;
+ return src2->nb[0] == ggml_type_size(src2->type) &&
+ ggml_are_same_shape(src2, dst) &&
+ htp_rows_stride(src2->ne, src2->nb, &s2);
+}
+
+ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t) {
+ size_t stride = 0;
+ htp_rows_stride(t->ne, t->nb, &stride);
+ ggml_tensor c = *t;
+ c.ne[1] = t->ne[1] * t->ne[2] * t->ne[3];
+ c.ne[2] = 1;
+ c.ne[3] = 1;
+ c.nb[1] = stride;
+ c.nb[2] = c.nb[1] * c.ne[1];
+ c.nb[3] = c.nb[2];
+ return c;
+}
+
+// Collapse contiguous dims of elementwise ops so that rows fill at least one HVX vector
+static void htp_collapse_dims(struct ggml_tensor ** tensors, size_t n_tensors, size_t elem_size, uint32_t n_hvx) {
+ if (n_tensors == 0 || !tensors[0]) {
+ return;
+ }
+ for (size_t t = 0; t < n_tensors; t++) {
+ if (!tensors[t] || tensors[t]->nb[0] != elem_size) {
+ return;
+ }
+ if (t > 0 && !ggml_are_same_shape(tensors[0], tensors[t])) {
+ return;
+ }
+ }
+
+ struct ggml_tensor * t0 = tensors[0];
+
+ while (t0->ne[1] > 1 || t0->ne[2] > 1 || t0->ne[3] > 1) {
+ const size_t row_size = (size_t) t0->ne[0] * elem_size;
+ bool rows_contig = true;
+ for (size_t t = 0; t < n_tensors; t++) {
+ if (tensors[t]->nb[1] != (size_t) tensors[t]->ne[0] * elem_size) {
+ rows_contig = false;
+ break;
+ }
+ }
+ bool all_ne1_one = true;
+ for (size_t t = 0; t < n_tensors; t++) {
+ if (tensors[t]->ne[1] != 1) {
+ all_ne1_one = false;
+ break;
+ }
+ }
+ const bool can_merge = all_ne1_one ||
+ (rows_contig && (t0->ne[0] == 1 || (row_size < 128 && row_size * t0->ne[1] <= 2048)));
+ if (!can_merge) {
+ break;
+ }
+ for (size_t t = 0; t < n_tensors; t++) {
+ tensors[t]->ne[0] *= tensors[t]->ne[1];
+ tensors[t]->ne[1] = tensors[t]->ne[2];
+ tensors[t]->ne[2] = tensors[t]->ne[3];
+ tensors[t]->ne[3] = 1;
+ tensors[t]->nb[1] = tensors[t]->nb[2];
+ tensors[t]->nb[2] = tensors[t]->nb[3];
+ tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2];
+ }
+ }
+
+ // ne1 too big to merge in full: merge it in chunks of k rows (k divides ne1)
+ const size_t row_size = (size_t) t0->ne[0] * elem_size;
+ bool rows_contig = true;
+ for (size_t t = 0; t < n_tensors; t++) {
+ if (tensors[t]->nb[1] != row_size) {
+ rows_contig = false;
+ break;
+ }
+ }
+ if (t0->ne[1] > 1 && row_size < 128 && rows_contig) {
+ int64_t k = 2048 / row_size;
+ while (k > 1 && t0->ne[1] % k != 0) {
+ k--;
+ }
+ if (k > 1) {
+ for (size_t t = 0; t < n_tensors; t++) {
+ tensors[t]->ne[0] *= k;
+ tensors[t]->ne[1] /= k;
+ tensors[t]->nb[1] *= k;
+ }
+ }
+ }
+
+ // nrows too small to saturate HVX units: split ne0 into k rows (k divides ne0)
+ const size_t row_size_curr = (size_t) t0->ne[0] * elem_size;
+ const uint32_t nrows = (uint32_t) (t0->ne[1] * t0->ne[2] * t0->ne[3]);
+ rows_contig = true;
+ for (size_t t = 0; t < n_tensors; t++) {
+ if (tensors[t]->ne[1] != 1 && tensors[t]->nb[1] != row_size_curr) {
+ rows_contig = false;
+ break;
+ }
+ }
+ if (nrows < n_hvx && rows_contig && row_size_curr >= 4096) {
+ const size_t vec_elems = 128 / elem_size;
+ int64_t k = std::max<int64_t>(row_size_curr / 16384, (n_hvx * 4 + nrows - 1) / nrows);
+ k = std::min<int64_t>(k, row_size_curr / 2048);
+ while (k > 1 && t0->ne[0] % (k * vec_elems) != 0) {
+ k--;
+ }
+ if (k > 1) {
+ for (size_t t = 0; t < n_tensors; t++) {
+ tensors[t]->ne[0] /= k;
+ tensors[t]->ne[1] *= k;
+ tensors[t]->nb[1] = tensors[t]->ne[0] * elem_size;
+ }
+ }
+ }
+}
+
+bool htp_dsv4_hc_pre_can_collapse(
+ const struct ggml_tensor * x,
+ const struct ggml_tensor * weights,
+ const struct ggml_tensor * dst
+) {
+ const auto is_valid_type = [](const ggml_tensor * t) {
+ return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type);
+ };
+ if (!is_valid_type(x) || !is_valid_type(weights) || !is_valid_type(dst)) {
+ return false;
+ }
+ if (x->ne[1] != 4 || dst->ne[0] != x->ne[0]) {
+ return false;
+ }
+
+ const bool gated = ggml_get_op_params_i32(dst, 1) != 0;
+ const int64_t x_tokens = x->ne[2] * x->ne[3];
+ const int64_t d_tokens = dst->ne[1] * dst->ne[2] * dst->ne[3];
+ const int64_t w_tokens = gated ? (weights->ne[2] * weights->ne[3]) : (weights->ne[1] * weights->ne[2] * weights->ne[3]);
+
+ if (x_tokens != d_tokens || x_tokens != w_tokens) {
+ return false;
+ }
+
+ if (x->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 &&
+ (gated ? (weights->ne[3] == 1) : (weights->ne[2] == 1 && weights->ne[3] == 1))) {
+ return false;
+ }
+
+ if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false;
+
+ if (dst->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) return false;
+ if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false;
+
+ if (gated) {
+ if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false;
+ } else {
+ if (weights->ne[2] > 1 && weights->nb[2] != weights->ne[1] * weights->nb[1]) return false;
+ if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false;
+ }
+
+ return true;
+}
+
+void htp_dsv4_hc_pre_collapse_tensors(
+ const struct ggml_tensor * x,
+ const struct ggml_tensor * weights,
+ const struct ggml_tensor * dst,
+ struct ggml_tensor * x_c,
+ struct ggml_tensor * w_c,
+ struct ggml_tensor * d_c
+) {
+ const int64_t n_tokens = x->ne[2] * x->ne[3];
+ const bool gated = ggml_get_op_params_i32(dst, 1) != 0;
+
+ *x_c = *x;
+ x_c->ne[2] = n_tokens;
+ x_c->ne[3] = 1;
+ x_c->nb[3] = x_c->ne[2] * x_c->nb[2];
+
+ *d_c = *dst;
+ d_c->ne[1] = n_tokens;
+ d_c->ne[2] = 1;
+ d_c->ne[3] = 1;
+ d_c->nb[2] = d_c->ne[1] * d_c->nb[1];
+ d_c->nb[3] = d_c->nb[2];
+
+ *w_c = *weights;
+ if (gated) {
+ w_c->ne[2] = n_tokens;
+ w_c->ne[3] = 1;
+ w_c->nb[3] = w_c->ne[2] * w_c->nb[2];
+ } else {
+ w_c->ne[1] = n_tokens;
+ w_c->ne[2] = 1;
+ w_c->ne[3] = 1;
+ w_c->nb[2] = w_c->ne[1] * w_c->nb[1];
+ w_c->nb[3] = w_c->nb[2];
+ }
+}
+
+bool htp_dsv4_hc_post_can_collapse(
+ const struct ggml_tensor * x,
+ const struct ggml_tensor * residual,
+ const struct ggml_tensor * post,
+ const struct ggml_tensor * comb,
+ const struct ggml_tensor * dst
+) {
+ const auto is_valid_type = [](const ggml_tensor * t) {
+ return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type);
+ };
+ if (!is_valid_type(x) || !is_valid_type(residual) || !is_valid_type(post) || !is_valid_type(dst)) {
+ return false;
+ }
+ if (comb && !is_valid_type(comb)) {
+ return false;
+ }
+ if (residual->ne[0] != x->ne[0] || residual->ne[1] != 4 || dst->ne[0] != x->ne[0] || dst->ne[1] != 4 || post->ne[0] != 4) {
+ return false;
+ }
+ if (comb && (comb->ne[0] != 4 || comb->ne[1] != 4)) {
+ return false;
+ }
+
+ const int64_t x_tokens = x->ne[1] * x->ne[2] * x->ne[3];
+ const int64_t r_tokens = residual->ne[2] * residual->ne[3];
+ const int64_t p_tokens = post->ne[1] * post->ne[2] * post->ne[3];
+ const int64_t d_tokens = dst->ne[2] * dst->ne[3];
+ if (x_tokens != r_tokens || x_tokens != p_tokens || x_tokens != d_tokens) {
+ return false;
+ }
+ if (comb && (comb->ne[2] * comb->ne[3] != x_tokens)) {
+ return false;
+ }
+
+ if (x->ne[2] == 1 && x->ne[3] == 1 &&
+ residual->ne[3] == 1 &&
+ post->ne[2] == 1 && post->ne[3] == 1 &&
+ dst->ne[3] == 1 &&
+ (!comb || comb->ne[3] == 1)) {
+ return false;
+ }
+
+ if (x->ne[2] > 1 && x->nb[2] != x->ne[1] * x->nb[1]) return false;
+ if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false;
+
+ if (residual->ne[3] > 1 && residual->nb[3] != residual->ne[2] * residual->nb[2]) return false;
+ if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false;
+
+ if (post->ne[2] > 1 && post->nb[2] != post->ne[1] * post->nb[1]) return false;
+ if (post->ne[3] > 1 && post->nb[3] != post->ne[2] * post->nb[2]) return false;
+
+ if (comb && comb->ne[3] > 1 && comb->nb[3] != comb->ne[2] * comb->nb[2]) return false;
+
+ return true;
+}
+
+void htp_dsv4_hc_post_collapse_tensors(
+ const struct ggml_tensor * x,
+ const struct ggml_tensor * residual,
+ const struct ggml_tensor * post,
+ const struct ggml_tensor * comb,
+ const struct ggml_tensor * dst,
+ struct ggml_tensor * x_c,
+ struct ggml_tensor * r_c,
+ struct ggml_tensor * p_c,
+ struct ggml_tensor * c_c,
+ struct ggml_tensor * d_c
+) {
+ const int64_t n_tokens = x->ne[1] * x->ne[2] * x->ne[3];
+
+ *x_c = *x;
+ x_c->ne[1] = n_tokens;
+ x_c->ne[2] = 1;
+ x_c->ne[3] = 1;
+ x_c->nb[2] = x_c->ne[1] * x_c->nb[1];
+ x_c->nb[3] = x_c->nb[2];
+
+ *r_c = *residual;
+ r_c->ne[2] = n_tokens;
+ r_c->ne[3] = 1;
+ r_c->nb[3] = r_c->ne[2] * r_c->nb[2];
+
+ *d_c = *dst;
+ d_c->ne[2] = n_tokens;
+ d_c->ne[3] = 1;
+ d_c->nb[3] = d_c->ne[2] * d_c->nb[2];
+
+ *p_c = *post;
+ p_c->ne[1] = n_tokens;
+ p_c->ne[2] = 1;
+ p_c->ne[3] = 1;
+ p_c->nb[2] = p_c->ne[1] * p_c->nb[1];
+ p_c->nb[3] = p_c->nb[2];
+
+ if (comb && c_c) {
+ *c_c = *comb;
+ c_c->ne[2] = n_tokens;
+ c_c->ne[3] = 1;
+ c_c->nb[3] = c_c->ne[2] * c_c->nb[2];
+ }
+}
+
+bool htp_lightning_indexer_can_collapse(
+ const struct ggml_tensor * q,
+ const struct ggml_tensor * k,
+ const struct ggml_tensor * w,
+ const struct ggml_tensor * m,
+ const struct ggml_tensor * dst
+) {
+ // 2D K normalization: ne[1] is n_kv, ne[2] is 1
+ const bool can_collapse_k = (k->ne[1] > 1 && k->ne[2] == 1);
+
+ // Stream-to-token collapse across q, w, dst (and m)
+ bool can_collapse_stream = false;
+ if (q->ne[3] > 1 && k->ne[3] == 1) {
+ const bool q_ok = (q->nb[3] == (size_t) q->ne[2] * q->nb[2]);
+ const bool dst_ok = (dst->ne[3] == q->ne[3] && dst->ne[2] == 1 && dst->ne[1] == q->ne[2] &&
+ dst->nb[3] == (size_t) dst->ne[1] * dst->nb[1]);
+ const bool w_ok = (w->ne[3] == q->ne[3] && w->ne[2] == 1 && w->ne[1] == q->ne[2] &&
+ w->nb[3] == (size_t) w->ne[1] * w->nb[1]) ||
+ (w->ne[3] == 1 && w->ne[1] == q->ne[2] * q->ne[3]);
+ const bool m_ok = (m->ne[3] == q->ne[3] && m->ne[2] == 1 && m->ne[1] == q->ne[2] &&
+ m->nb[3] == (size_t) m->ne[1] * m->nb[1]) ||
+ (m->ne[3] == 1 && m->ne[1] == q->ne[2] * q->ne[3]);
+ can_collapse_stream = q_ok && dst_ok && w_ok && m_ok;
+ }
+
+ return can_collapse_k || can_collapse_stream;
+}
+
+void htp_lightning_indexer_collapse_tensors(
+ const struct ggml_tensor * q,
+ const struct ggml_tensor * k,
+ const struct ggml_tensor * w,
+ const struct ggml_tensor * m,
+ const struct ggml_tensor * dst,
+ struct ggml_tensor * q_c,
+ struct ggml_tensor * k_c,
+ struct ggml_tensor * w_c,
+ struct ggml_tensor * m_c,
+ struct ggml_tensor * dst_c
+) {
+ *q_c = *q;
+ *k_c = *k;
+ *w_c = *w;
+ *m_c = *m;
+ *dst_c = *dst;
+
+ if (k->ne[1] > 1 && k->ne[2] == 1) {
+ k_c->ne[2] = k->ne[1];
+ k_c->ne[1] = 1;
+ k_c->nb[1] = k->nb[1];
+ k_c->nb[2] = k->nb[1];
+ k_c->nb[3] = k->nb[2];
+ }
+
+ if (q->ne[3] > 1 && k->ne[3] == 1) {
+ const int64_t n_tokens_collapsed = (int64_t) q->ne[2] * q->ne[3];
+
+ q_c->ne[2] = n_tokens_collapsed;
+ q_c->ne[3] = 1;
+ q_c->nb[3] = (size_t) q_c->ne[2] * q_c->nb[2];
+
+ if (w->ne[3] == q->ne[3]) {
+ w_c->ne[1] = n_tokens_collapsed;
+ w_c->ne[3] = 1;
+ w_c->nb[2] = (size_t) w_c->ne[1] * w_c->nb[1];
+ w_c->nb[3] = w_c->nb[2];
+ }
+
+ dst_c->ne[1] = n_tokens_collapsed;
+ dst_c->ne[3] = 1;
+ dst_c->nb[2] = (size_t) dst_c->ne[1] * dst_c->nb[1];
+ dst_c->nb[3] = dst_c->nb[2];
+
+ if (m->ne[3] == q->ne[3] && m->ne[1] == q->ne[2]) {
+ m_c->ne[1] = n_tokens_collapsed;
+ m_c->ne[3] = 1;
+ m_c->nb[2] = (size_t) m_c->ne[1] * m_c->nb[1];
+ m_c->nb[3] = m_c->nb[2];
+ }
+ }
+}
+
+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]);
+ }
+
+ if (htp_op_is_unary(node.opcode) && htp_unary_is_elementwise(node.opcode)) {
+ if (n_in >= 1 && n_out >= 1 &&
+ ggml_are_same_shape(&in_mat[0], &out_mat[0])) {
+ const int64_t old_ne0 = in_mat[0].ne[0];
+ const int64_t old_ne1 = in_mat[0].ne[1];
+ const size_t elem_size = ggml_type_size(in_mat[0].type);
+ struct ggml_tensor * tensors[2] = { &in_mat[0], &out_mat[0] };
+ htp_collapse_dims(tensors, 2, elem_size, n_hvx);
+ if (in_mat[0].ne[0] != old_ne0 || in_mat[0].ne[1] != old_ne1) {
+ in_dirty[0] = true;
+ out_dirty[0] = true;
+ }
+ }
+ } else if (htp_op_is_glu(node.opcode)) {
+ if (n_in >= 2 && n_out >= 1 &&
+ ggml_are_same_shape(&in_mat[0], &out_mat[0]) &&
+ ggml_are_same_shape(&in_mat[1], &out_mat[0])) {
+ const int64_t old_ne0 = in_mat[0].ne[0];
+ const int64_t old_ne1 = in_mat[0].ne[1];
+ const size_t elem_size = ggml_type_size(in_mat[0].type);
+ struct ggml_tensor * tensors[3] = { &in_mat[0], &in_mat[1], &out_mat[0] };
+ htp_collapse_dims(tensors, 3, elem_size, n_hvx);
+ if (in_mat[0].ne[0] != old_ne0 || in_mat[0].ne[1] != old_ne1) {
+ in_dirty[0] = true;
+ in_dirty[1] = true;
+ out_dirty[0] = true;
+ }
+ }
+ } else if (node.opcode == HTP_OP_MUL_MAT) {
+ if (n_in >= 2 && n_out >= 1 &&
+ htp_matmul_can_collapse(&in_mat[0], &in_mat[1], &out_mat[0])) {
+ in_mat[1] = htp_tensor_collapse_rows(&in_mat[1]);
+ out_mat[0] = htp_tensor_collapse_rows(&out_mat[0]);
+ in_dirty[1] = true;
+ out_dirty[0] = true;
+ }
+ } else if (node.opcode == HTP_OP_MUL_MAT_ADD) {
+ if (n_in >= 3 && n_out >= 1 &&
+ htp_matmul_add_can_collapse(&in_mat[0], &in_mat[1], &in_mat[2], &out_mat[0])) {
+ in_mat[1] = htp_tensor_collapse_rows(&in_mat[1]);
+ out_mat[0] = htp_tensor_collapse_rows(&out_mat[0]);
+ in_dirty[1] = true;
+ out_dirty[0] = true;
+ if (in_mat[2].ne[1] * in_mat[2].ne[2] * in_mat[2].ne[3] > 1) {
+ in_mat[2] = htp_tensor_collapse_rows(&in_mat[2]);
+ in_dirty[2] = true;
+ }
+ }
+ } 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) {
+ 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])) {
+ can_collapse = false;
+ break;
+ }
+ }
+ if (can_collapse) {
+ in_mat[n_w] = htp_tensor_collapse_rows(&in_mat[n_w]);
+ in_dirty[n_w] = true;
+ for (size_t i = 0; i < n_w; ++i) {
+ out_mat[i] = htp_tensor_collapse_rows(&out_mat[i]);
+ out_dirty[i] = true;
+ }
+ }
+ }
+ } else if (node.opcode == HTP_OP_MUL_MAT_NX_GLU) {
+ if (n_in == 3 && 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]);
+ in_dirty[2] = true;
+ out_mat[0] = htp_tensor_collapse_rows(&out_mat[0]);
+ out_dirty[0] = true;
+ }
+ } else if (node.opcode == HTP_OP_UPSCALE) {
+ if (n_in >= 1 && n_out >= 1) {
+ if ((in_mat[0].ne[3] > 1 || out_mat[0].ne[3] > 1) &&
+ in_mat[0].ne[2] == out_mat[0].ne[2] && in_mat[0].ne[3] == out_mat[0].ne[3] &&
+ in_mat[0].nb[3] == (size_t) in_mat[0].ne[2] * in_mat[0].nb[2] &&
+ out_mat[0].nb[3] == (size_t) out_mat[0].ne[2] * out_mat[0].nb[2]) {
+ in_mat[0].ne[2] *= in_mat[0].ne[3];
+ in_mat[0].ne[3] = 1;
+ in_mat[0].nb[3] = (size_t) in_mat[0].ne[2] * in_mat[0].nb[2];
+ out_mat[0].ne[2] *= out_mat[0].ne[3];
+ out_mat[0].ne[3] = 1;
+ out_mat[0].nb[3] = (size_t) out_mat[0].ne[2] * out_mat[0].nb[2];
+ in_dirty[0] = true;
+ out_dirty[0] = true;
+ }
+ }
+ } else if (node.opcode == HTP_OP_DSV4_HC_PRE) {
+ if (n_in >= 2 && n_out >= 1 &&
+ htp_dsv4_hc_pre_can_collapse(&in_mat[0], &in_mat[1], &out_mat[0])) {
+ struct ggml_tensor x_c, w_c, d_c;
+ htp_dsv4_hc_pre_collapse_tensors(&in_mat[0], &in_mat[1], &out_mat[0], &x_c, &w_c, &d_c);
+ in_mat[0] = x_c;
+ in_mat[1] = w_c;
+ out_mat[0] = d_c;
+ in_dirty[0] = true;
+ in_dirty[1] = true;
+ out_dirty[0] = true;
+ }
+ } else if (node.opcode == HTP_OP_DSV4_HC_POST) {
+ if (n_in >= 3 && n_out >= 1) {
+ const struct ggml_tensor * comb = (n_in > 3 && node.inputs[3]) ? &in_mat[3] : nullptr;
+ if (htp_dsv4_hc_post_can_collapse(&in_mat[0], &in_mat[1], &in_mat[2], comb, &out_mat[0])) {
+ struct ggml_tensor x_c, r_c, p_c, c_c, d_c;
+ htp_dsv4_hc_post_collapse_tensors(&in_mat[0], &in_mat[1], &in_mat[2], comb, &out_mat[0],
+ &x_c, &r_c, &p_c, comb ? &c_c : nullptr, &d_c);
+ in_mat[0] = x_c;
+ in_mat[1] = r_c;
+ in_mat[2] = p_c;
+ out_mat[0] = d_c;
+ in_dirty[0] = true;
+ in_dirty[1] = true;
+ in_dirty[2] = true;
+ out_dirty[0] = true;
+ if (comb) {
+ in_mat[3] = c_c;
+ in_dirty[3] = true;
+ }
+ }
+ }
+ } else if (node.opcode == HTP_OP_LIGHTNING_INDEXER) {
+ if (n_in >= 4 && n_out >= 1 &&
+ htp_lightning_indexer_can_collapse(&in_mat[0], &in_mat[1], &in_mat[2], &in_mat[3], &out_mat[0])) {
+ struct ggml_tensor q_c, k_c, w_c, m_c, d_c;
+ htp_lightning_indexer_collapse_tensors(&in_mat[0], &in_mat[1], &in_mat[2], &in_mat[3], &out_mat[0],
+ &q_c, &k_c, &w_c, &m_c, &d_c);
+ in_mat[0] = q_c;
+ in_mat[1] = k_c;
+ in_mat[2] = w_c;
+ in_mat[3] = m_c;
+ out_mat[0] = d_c;
+ in_dirty[0] = true;
+ in_dirty[1] = true;
+ in_dirty[2] = true;
+ in_dirty[3] = true;
+ out_dirty[0] = true;
+ }
+ }
+
+ size_t n_scratch = 0;
+ auto commit_tensor = [&](const ggml_tensor & m) -> const ggml_tensor * {
+ if (scratch) {
+ scratch[n_scratch] = m;
+ return &scratch[n_scratch++];
+ }
+ return node.add_dummy(m);
+ };
+
+ const ggml_tensor * orig_in[HTP_OP_MAX_INPUTS] = {};
+ for (size_t i = 0; i < n_in; ++i) {
+ orig_in[i] = node.inputs[i];
+ if (in_dirty[i]) {
+ node.inputs[i] = commit_tensor(in_mat[i]);
+ }
+ }
+ for (size_t j = 0; j < n_out; ++j) {
+ if (!out_dirty[j]) {
+ continue;
+ }
+ const ggml_tensor * reused = nullptr;
+ for (size_t i = 0; i < n_in; ++i) {
+ if (orig_in[i] == node.outputs[j] && in_dirty[i] &&
+ in_mat[i].type == out_mat[j].type &&
+ ggml_are_same_shape(&in_mat[i], &out_mat[j]) &&
+ ggml_are_same_stride(&in_mat[i], &out_mat[j])) {
+ reused = node.inputs[i];
+ break;
+ }
+ }
+ node.outputs[j] = reused ? reused : commit_tensor(out_mat[j]);
+ }
+}
+
+static bool htp_lower_is_view(const ggml_tensor * tensor) {
+ return tensor->op == GGML_OP_VIEW || tensor->op == GGML_OP_RESHAPE || tensor->op == GGML_OP_PERMUTE || tensor->op == GGML_OP_TRANSPOSE;
+}
+
+static bool htp_lower_is_root_candidate(const ggml_tensor * root, const std::unordered_set<const ggml_tensor *> & produced) {
+ return produced.count(root) && root->type == GGML_TYPE_F32 && root->buffer &&
+ !ggml_backend_buffer_is_host(root->buffer) &&
+ ggml_backend_buffer_get_usage(root->buffer) != GGML_BACKEND_BUFFER_USAGE_WEIGHTS &&
+ (root->flags & (GGML_TENSOR_FLAG_INPUT | GGML_TENSOR_FLAG_OUTPUT | GGML_TENSOR_FLAG_PARAM)) == 0;
+}
+
+static bool htp_lower_is_partial_write(const ggml_tensor * tensor) {
+ if (tensor->op == GGML_OP_SET || tensor->op == GGML_OP_SET_ROWS) {
+ return true;
+ }
+ return tensor->op == GGML_OP_CPY && !ggml_is_contiguous(tensor);
+}
+
+static bool htp_lower_safe_class(
+ const ggml_cgraph * graph,
+ const ggml_tensor * root,
+ const std::vector<const ggml_tensor *> & tensors,
+ const std::unordered_map<const ggml_tensor *, int> & node_idx,
+ const std::unordered_map<const ggml_tensor *, int> & internal_uses
+) {
+ int total_internal_uses = 0;
+ for (const ggml_tensor * tensor : tensors) {
+ if (tensor->type != GGML_TYPE_F32) {
+ return false;
+ }
+ if (tensor != root && !htp_lower_is_view(tensor)) {
+ return false;
+ }
+ const ptrdiff_t offset = (const uint8_t *) tensor->data - (const uint8_t *) root->data;
+ if (offset % 4 != 0 || (tensor->flags & GGML_TENSOR_FLAG_OUTPUT)) {
+ return false;
+ }
+ for (int d = 0; d < GGML_MAX_DIMS; ++d) {
+ if (tensor->nb[d] % 4 != 0) {
+ return false;
+ }
+ }
+ auto it = node_idx.find(tensor);
+ if (it == node_idx.end() || htp_lower_is_partial_write(tensor)) {
+ return false;
+ }
+ const int total_uses = ggml_node_get_use_count(graph, it->second);
+ auto uit = internal_uses.find(tensor);
+ const int uses = (uit != internal_uses.end()) ? uit->second : 0;
+ if (uses != total_uses) {
+ return false;
+ }
+ total_internal_uses += uses;
+ }
+ return total_internal_uses >= 1;
+}
+
+static bool htp_lower_inplace_types_ok(const htp_opnode & node) {
+ for (const ggml_tensor * inp : node.inputs) {
+ if (!inp) {
+ continue;
+ }
+ const ggml_type inp_type = htp_effective_type(inp);
+ if (inp_type != GGML_TYPE_F32 && inp_type != GGML_TYPE_F16) {
+ continue;
+ }
+ for (const ggml_tensor * out : node.outputs) {
+ if (!out) {
+ continue;
+ }
+ const ggml_type out_type = htp_effective_type(out);
+ if (out_type != GGML_TYPE_F32 && out_type != GGML_TYPE_F16) {
+ continue;
+ }
+ if (inp_type != out_type && htp_tensors_overlap(inp, out)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+static bool htp_lower_is_mm_opcode(uint32_t opcode) {
+ return opcode == HTP_OP_MUL_MAT || opcode == HTP_OP_MUL_MAT_ADD ||
+ opcode == HTP_OP_MUL_MAT_ID || opcode == HTP_OP_MUL_MAT_NX ||
+ 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) {
+ 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 (p == 0) {
+ return node.node;
+ }
+ return (p - 1 < node.fused.size()) ? node.fused[p - 1] : nullptr;
+ }
+ }
+ return nullptr;
+ }
+ return node.node;
+}
+
+static bool htp_lower_mm_blocks_output_f16(const ggml_tensor * orig_mm) {
+ if (!orig_mm) {
+ return false;
+ }
+ if (ggml_prec_get_acc(orig_mm) == GGML_PREC_F32) {
+ return true;
+ }
+ const ggml_prec src1_prec = ggml_prec_get_src(orig_mm, 1);
+ return src1_prec == GGML_PREC_BF16 || src1_prec == GGML_PREC_F32;
+}
+
+static bool htp_lower_respect_prec_hints(
+ const htp_opnode & owner,
+ const ggml_tensor * r,
+ const std::vector<const ggml_tensor *> & cls,
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ 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)) {
+ 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 (owner.opcode == HTP_OP_SOFTMAX && !owner.inputs.empty() && owner.inputs[0]) {
+ const ggml_tensor * in_root = htp_tensor_root(owner.inputs[0]);
+ 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;
+ }
+ }
+ }
+ auto uit = root_users.find(r);
+ if (uit == root_users.end()) {
+ return true;
+ }
+ for (size_t idx : uit->second) {
+ const htp_opnode & node = nodes[idx];
+ if (!htp_lower_is_mm_opcode(node.opcode)) {
+ continue;
+ }
+ const size_t act_idx = (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX)
+ ? node.outputs.size()
+ : (node.opcode == HTP_OP_MUL_MAT_NX_GLU ? 2 : 1);
+ if (act_idx >= node.inputs.size()) {
+ continue;
+ }
+ const ggml_tensor * act = node.inputs[act_idx];
+ bool uses_cls = false;
+ for (const ggml_tensor * tensor : cls) {
+ if (act == tensor) {
+ uses_cls = true;
+ break;
+ }
+ }
+ if (!uses_cls && (!act || htp_tensor_root(act) != r)) {
+ continue;
+ }
+ auto blocks_src1 = [](const ggml_tensor * orig_mm) -> bool {
+ if (!orig_mm) {
+ return false;
+ }
+ const ggml_prec src1_prec = ggml_prec_get_src(orig_mm, 1);
+ return src1_prec == GGML_PREC_BF16 || src1_prec == GGML_PREC_F32;
+ };
+ if (blocks_src1(node.node)) {
+ return false;
+ }
+ if (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_NX_GLU || node.opcode == HTP_OP_MUL_MAT_ID_NX) {
+ for (const ggml_tensor * f : node.fused) {
+ if (f && (f->op == GGML_OP_MUL_MAT || f->op == GGML_OP_MUL_MAT_ID) && blocks_src1(f)) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+}
+
+static bool htp_lower_is_mm_root(
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ const ggml_tensor * root
+) {
+ auto it = owner_idx.find(root);
+ return it != owner_idx.end() && htp_lower_is_mm_opcode(nodes[it->second].opcode);
+}
+
+static bool htp_lower_is_fa_root(
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ const ggml_tensor * root
+) {
+ auto it = owner_idx.find(root);
+ return it != owner_idx.end() && nodes[it->second].opcode == HTP_OP_FLASH_ATTN_EXT;
+}
+
+static bool htp_lower_is_rms_root(
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ const ggml_tensor * root
+) {
+ auto it = owner_idx.find(root);
+ if (it == owner_idx.end()) {
+ return false;
+ }
+ const uint32_t opcode = nodes[it->second].opcode;
+ return opcode == HTP_OP_RMS_NORM || opcode == HTP_OP_RMS_NORM_MUL ||
+ opcode == HTP_OP_RMS_NORM_MUL_ADD;
+}
+
+static bool htp_lower_is_ssm_conv_root(
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ const ggml_tensor * root
+) {
+ auto it = owner_idx.find(root);
+ return it != owner_idx.end() && nodes[it->second].opcode == HTP_OP_SSM_CONV &&
+ !nodes[it->second].outputs.empty() && nodes[it->second].outputs[0] == root;
+}
+
+static bool htp_lower_is_get_rows_root(
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ const ggml_tensor * root
+) {
+ auto it = owner_idx.find(root);
+ if (it == owner_idx.end()) {
+ return false;
+ }
+ const htp_opnode & owner = nodes[it->second];
+ return owner.opcode == HTP_OP_GET_ROWS && !owner.inputs.empty() && owner.inputs[0] &&
+ (owner.inputs[0]->type != GGML_TYPE_F32 || ggml_hexagon_tensor_is_tiled(owner.inputs[0]));
+}
+
+static bool htp_lower_is_repeat_root(
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, size_t> & owner_idx,
+ const ggml_tensor * root
+) {
+ auto it = owner_idx.find(root);
+ return it != owner_idx.end() && nodes[it->second].opcode == HTP_OP_REPEAT;
+}
+
+static bool htp_lower_safe_gdn_output(
+ const htp_opnode & owner,
+ const ggml_tensor * root,
+ const std::vector<htp_opnode> & nodes,
+ const std::unordered_map<const ggml_tensor *, std::vector<size_t>> & root_users
+) {
+ if (owner.outputs.size() != 2 || root != owner.outputs[0] || owner.inputs.size() < 3) {
+ return false;
+ }
+ auto uit = root_users.find(root);
+ if (uit == root_users.end()) {
+ return false;
+ }
+ const ggml_tensor * v = owner.inputs[2];
+ const size_t tail_off = (size_t) v->ne[0] * v->ne[1] * v->ne[2] * v->ne[3] * sizeof(float);
+ bool has_consumer = false;
+ for (size_t idx : uit->second) {
+ const htp_opnode & node = nodes[idx];
+ for (const ggml_tensor * input : node.inputs) {
+ if (!input || htp_tensor_root(input) != root) {
+ continue;
+ }
+ const ptrdiff_t offset = (const uint8_t *) input->data - (const uint8_t *) root->data;
+ if (offset < 0 || (size_t) offset + ggml_nbytes(input) > tail_off) {
+ return false;
+ }
+ has_consumer = true;
+ }
+ }
+ return has_consumer;
+}
+
+void htp_lower_reset_graph(const struct ggml_cgraph * graph) {
+ for (int i = 0; i < graph->n_nodes; ++i) {
+ ggml_tensor * node = graph->nodes[i];
+ for (int j = 0; j < GGML_MAX_SRC; ++j) {
+ ggml_hexagon_tensor_clear_lowered(node->src[j]);
+ }
+ ggml_hexagon_tensor_clear_lowered(node);
+ }
+}
+
+void htp_pack_tensor_lowered_f16(struct ggml_tensor * t, const void * src, size_t offset, size_t size) {
+ if (size == 0) {
+ return;
+ }
+ GGML_ASSERT(t->type == GGML_TYPE_F32);
+ GGML_ASSERT(offset % sizeof(float) == 0 && size % sizeof(float) == 0);
+ const struct ggml_tensor * root = htp_tensor_root(t);
+ uint8_t * base = (uint8_t *) root->data + ((const uint8_t *) t->data - (const uint8_t *) root->data) / 2;
+ ggml_fp16_t * dst = (ggml_fp16_t *) (base + offset / 2);
+ const int64_t n = (int64_t) (size / sizeof(float));
+ if ((uintptr_t) src % alignof(float) == 0) {
+ ggml_fp32_to_fp16_row((const float *) src, dst, n);
+ } else {
+ std::vector<float> tmp((size_t) n);
+ memcpy(tmp.data(), src, size);
+ ggml_fp32_to_fp16_row(tmp.data(), dst, n);
+ }
+}
+
+void htp_unpack_tensor_lowered_f16(void * dst, const struct ggml_tensor * t, size_t offset, size_t size) {
+ if (size == 0) {
+ return;
+ }
+ GGML_ASSERT(t->type == GGML_TYPE_F32);
+ GGML_ASSERT(offset % sizeof(float) == 0 && size % sizeof(float) == 0);
+ const struct ggml_tensor * root = htp_tensor_root(t);
+ const uint8_t * base = (const uint8_t *) root->data + ((const uint8_t *) t->data - (const uint8_t *) root->data) / 2;
+ const ggml_fp16_t * src = (const ggml_fp16_t *) (base + offset / 2);
+ const int64_t n = (int64_t) (size / sizeof(float));
+ if ((uintptr_t) dst % alignof(float) == 0) {
+ ggml_fp16_to_fp32_row(src, (float *) dst, n);
+ } else {
+ std::vector<float> tmp((size_t) n);
+ ggml_fp16_to_fp32_row(src, tmp.data(), n);
+ memcpy(dst, tmp.data(), size);
+ }
+}
+
+void htp_lower_graph(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector<htp_opnode> & nodes) {
+ if (opt_oplower <= 0) {
+ for (htp_opnode & node : nodes) {
+ htp_lower_opnode(sess, node);
+ }
+ return;
+ }
+
+ std::vector<const ggml_tensor *> roots;
+ std::unordered_map<const ggml_tensor *, std::vector<const ggml_tensor *>> classes;
+ std::unordered_set<const ggml_tensor *> seen;
+ std::unordered_map<const ggml_tensor *, int> node_idx;
+ std::unordered_map<const ggml_tensor *, int> internal_uses;
+ std::unordered_set<const ggml_tensor *> produced;
+
+ auto add_to_class = [&](const ggml_tensor * tensor) {
+ if (!tensor || !seen.insert(tensor).second) {
+ return;
+ }
+ ggml_hexagon_tensor_clear_flags(const_cast<ggml_tensor *>(tensor), HTP_TENSOR_LOWERED_F16);
+ const ggml_tensor * root = htp_tensor_root(tensor);
+ auto & cls = classes[root];
+ if (cls.empty()) {
+ roots.push_back(root);
+ }
+ cls.push_back(tensor);
+ };
+
+ for (int i = 0; i < graph->n_nodes; ++i) {
+ const ggml_tensor * tensor = graph->nodes[i];
+ node_idx[tensor] = i;
+ produced.insert(tensor);
+ for (int j = 0; j < GGML_MAX_SRC; ++j) {
+ if (tensor->src[j]) {
+ ++internal_uses[tensor->src[j]];
+ }
+ add_to_class(tensor->src[j]);
+ }
+ add_to_class(tensor);
+ }
+
+ std::unordered_map<const ggml_tensor *, size_t> owner_idx;
+ std::unordered_map<const ggml_tensor *, std::vector<size_t>> root_users;
+
+ for (size_t idx = 0; idx < nodes.size(); ++idx) {
+ const htp_opnode & node = nodes[idx];
+ auto add_user = [&](const ggml_tensor * t) {
+ if (!t) {
+ return;
+ }
+ auto & vec = root_users[htp_tensor_root(t)];
+ if (vec.empty() || vec.back() != idx) {
+ vec.push_back(idx);
+ }
+ };
+ for (const ggml_tensor * inp : node.inputs) {
+ add_user(inp);
+ }
+ for (const ggml_tensor * out : node.outputs) {
+ if (out) {
+ owner_idx.emplace(out, idx);
+ add_user(out);
+ }
+ }
+ }
+
+ size_t n_candidates = 0;
+ size_t n_lowered_roots = 0;
+ size_t n_lowered_mm = 0;
+ size_t bytes_saved = 0;
+
+ auto find_owner = [&](const ggml_tensor * r) -> htp_opnode * {
+ auto it = owner_idx.find(r);
+ return (it != owner_idx.end()) ? &nodes[it->second] : nullptr;
+ };
+
+ std::unordered_map<const ggml_tensor *, bool> root_safe_class;
+ for (const ggml_tensor * root : roots) {
+ auto it = classes.find(root);
+ const bool safe = it != classes.end() &&
+ htp_lower_is_root_candidate(root, produced) &&
+ htp_lower_safe_class(graph, root, it->second, node_idx, internal_uses);
+ root_safe_class[root] = safe;
+ if (safe && find_owner(root)) {
+ ++n_candidates;
+ }
+ }
+
+ auto is_f16_tensor = [&](const ggml_tensor * t) -> bool {
+ return t && (htp_effective_type(t) == GGML_TYPE_F16 || ggml_hexagon_tensor_is_lowered_f16(htp_tensor_root(t)));
+ };
+
+ auto can_lower = [&](const ggml_tensor * r) -> bool {
+ auto it = classes.find(r);
+ if (it == classes.end() || ggml_hexagon_tensor_is_lowered_f16(r)) {
+ return false;
+ }
+ auto sit = root_safe_class.find(r);
+ if (sit == root_safe_class.end() || !sit->second) {
+ return false;
+ }
+ htp_opnode * owner = find_owner(r);
+ if (!owner) {
+ return false;
+ }
+ if (!htp_lower_respect_prec_hints(*owner, r, it->second, nodes, owner_idx, root_users)) {
+ return false;
+ }
+ if (owner->opcode == HTP_OP_GATED_DELTA_NET && !htp_lower_safe_gdn_output(*owner, r, nodes, root_users)) {
+ return false;
+ }
+ if (owner->opcode == HTP_OP_SSM_CONV && (owner->outputs.empty() || r != owner->outputs[0])) {
+ return false;
+ }
+ return true;
+ };
+
+ auto is_selected_root = [&](const ggml_tensor * r) -> bool {
+ if (htp_lower_is_mm_root(nodes, owner_idx, r) || htp_lower_is_fa_root(nodes, owner_idx, r) ||
+ htp_lower_is_rms_root(nodes, owner_idx, r) || htp_lower_is_ssm_conv_root(nodes, owner_idx, r) ||
+ htp_lower_is_get_rows_root(nodes, owner_idx, r) || htp_lower_is_repeat_root(nodes, owner_idx, r)) {
+ return true;
+ }
+ for (const ggml_tensor * tensor : classes[r]) {
+ auto oit = owner_idx.find(tensor);
+ if (oit != owner_idx.end()) {
+ for (const ggml_tensor * input : nodes[oit->second].inputs) {
+ if (is_f16_tensor(input)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ };
+
+ auto has_real_inputs = [](const htp_opnode & node) -> bool {
+ for (const ggml_tensor * inp : node.inputs) {
+ if (inp && inp->type != GGML_TYPE_I32 && inp->type != GGML_TYPE_I64) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ auto is_f16_consumer_seed = [&](const ggml_tensor * r) -> bool {
+ const htp_opnode * owner = find_owner(r);
+ if (!owner || has_real_inputs(*owner)) {
+ return false;
+ }
+ auto uit = root_users.find(r);
+ if (uit == root_users.end()) {
+ return false;
+ }
+ for (size_t idx : uit->second) {
+ const htp_opnode & user = nodes[idx];
+ if (&user == owner) {
+ continue;
+ }
+ for (const ggml_tensor * out : user.outputs) {
+ if (is_f16_tensor(out)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ struct saved_node {
+ size_t idx;
+ htp_opnode * node;
+ bool dirty;
+ int32_t kernel_params[HTP_OP_MAX_KERN_PARAMS];
+ };
+
+ std::vector<int> touched_pos(nodes.size(), -1);
+
+ auto try_lower_root = [&](const ggml_tensor * root) {
+ std::vector<const ggml_tensor *> tx_roots;
+ std::vector<saved_node> touched;
+
+ auto apply_root = [&](const ggml_tensor * r) -> bool {
+ if (ggml_hexagon_tensor_is_lowered_f16(r)) {
+ return false;
+ }
+ tx_roots.push_back(r);
+ for (const ggml_tensor * tensor : classes[r]) {
+ ggml_hexagon_tensor_set_flags(const_cast<ggml_tensor *>(tensor), HTP_TENSOR_LOWERED_F16);
+ }
+
+ auto uit = root_users.find(r);
+ if (uit != root_users.end()) {
+ for (size_t idx : uit->second) {
+ const int pos = touched_pos[idx];
+ if (pos < 0) {
+ touched_pos[idx] = (int) touched.size();
+ saved_node s;
+ s.idx = idx;
+ s.node = &nodes[idx];
+ s.dirty = true;
+ memcpy(s.kernel_params, nodes[idx].kernel_params, sizeof(s.kernel_params));
+ touched.push_back(s);
+ } else {
+ touched[pos].dirty = true;
+ }
+ }
+ }
+ return true;
+ };
+
+ apply_root(root);
+
+ bool solved = false;
+ while (true) {
+ solved = true;
+ bool expanded = false;
+ for (size_t i = 0; i < touched.size(); ++i) {
+ if (!touched[i].dirty) {
+ continue;
+ }
+ htp_opnode * tnode = touched[i].node;
+ if (htp_lower_inplace_types_ok(*tnode) && htp_kparams_solve(sess, *tnode)) {
+ touched[i].dirty = false;
+ continue;
+ }
+ solved = false;
+ for (const ggml_tensor * out : tnode->outputs) {
+ const ggml_tensor * out_root = out ? htp_tensor_root(out) : nullptr;
+ if (out_root && can_lower(out_root) && apply_root(out_root)) {
+ expanded = true;
+ }
+ }
+ 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)) {
+ expanded = true;
+ }
+ }
+ if (expanded) {
+ break;
+ }
+ }
+ if (solved || !expanded) {
+ break;
+ }
+ }
+
+ for (const saved_node & s : touched) {
+ touched_pos[s.idx] = -1;
+ }
+
+ if (!solved) {
+ for (const ggml_tensor * r : tx_roots) {
+ for (const ggml_tensor * tensor : classes[r]) {
+ ggml_hexagon_tensor_clear_flags(const_cast<ggml_tensor *>(tensor), HTP_TENSOR_LOWERED_F16);
+ }
+ }
+ for (saved_node & s : touched) {
+ memcpy(s.node->kernel_params, s.kernel_params, sizeof(s.kernel_params));
+ }
+ return;
+ }
+
+ for (const ggml_tensor * r : tx_roots) {
+ ++n_lowered_roots;
+ bytes_saved += ggml_nbytes(r) / 2;
+ if (htp_lower_is_mm_root(nodes, owner_idx, r)) {
+ ++n_lowered_mm;
+ }
+ }
+ };
+
+ for (const ggml_tensor * root : roots) {
+ if (can_lower(root) && is_selected_root(root)) {
+ try_lower_root(root);
+ }
+ }
+
+ for (const ggml_tensor * root : roots) {
+ if (can_lower(root) && is_f16_consumer_seed(root)) {
+ try_lower_root(root);
+ }
+ }
+
+ for (htp_opnode & node : nodes) {
+ htp_lower_opnode(sess, node);
+ }
+
+ HEX_VERBOSE("ggml-hex: %s lower oplower=%d roots=%zu/%zu mm_out=%zu saved=%zuB\n",
+ htp_session_name(sess), opt_oplower, n_lowered_roots, n_candidates, n_lowered_mm, bytes_saved);
+}
diff --git a/ggml/src/ggml-hexagon/htp-lower.h b/ggml/src/ggml-hexagon/htp-lower.h
new file mode 100644
index 000000000..becb5532e
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp-lower.h
@@ -0,0 +1,37 @@
+#ifndef HTP_LOWER_H
+#define HTP_LOWER_H
+
+#include "ggml.h"
+
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+struct ggml_cgraph;
+struct ggml_hexagon_session;
+struct htp_opnode;
+
+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);
+bool htp_matmul_add_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * src2, const struct ggml_tensor * dst);
+ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t);
+
+bool htp_dsv4_hc_pre_can_collapse(const struct ggml_tensor * x, const struct ggml_tensor * weights, const struct ggml_tensor * dst);
+void htp_dsv4_hc_pre_collapse_tensors(const struct ggml_tensor * x, const struct ggml_tensor * weights, const struct ggml_tensor * dst,
+ struct ggml_tensor * x_c, struct ggml_tensor * w_c, struct ggml_tensor * d_c);
+
+bool htp_dsv4_hc_post_can_collapse(const struct ggml_tensor * x, const struct ggml_tensor * residual, const struct ggml_tensor * post, const struct ggml_tensor * comb, const struct ggml_tensor * dst);
+void htp_dsv4_hc_post_collapse_tensors(const struct ggml_tensor * x, const struct ggml_tensor * residual, const struct ggml_tensor * post, const struct ggml_tensor * comb, const struct ggml_tensor * dst,
+ struct ggml_tensor * x_c, struct ggml_tensor * r_c, struct ggml_tensor * p_c, struct ggml_tensor * c_c, struct ggml_tensor * d_c);
+
+bool htp_lightning_indexer_can_collapse(const struct ggml_tensor * q, const struct ggml_tensor * k, const struct ggml_tensor * w, const struct ggml_tensor * m, const struct ggml_tensor * dst);
+void htp_lightning_indexer_collapse_tensors(const struct ggml_tensor * q, const struct ggml_tensor * k, const struct ggml_tensor * w, const struct ggml_tensor * m, const struct ggml_tensor * dst,
+ struct ggml_tensor * q_c, struct ggml_tensor * k_c, struct ggml_tensor * w_c, struct ggml_tensor * m_c, struct ggml_tensor * dst_c);
+
+void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch = nullptr);
+void htp_lower_graph(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector<htp_opnode> & nodes);
+void htp_lower_reset_graph(const struct ggml_cgraph * graph);
+void htp_pack_tensor_lowered_f16(struct ggml_tensor * t, const void * src, size_t offset, size_t size);
+void htp_unpack_tensor_lowered_f16(void * dst, const struct ggml_tensor * t, size_t offset, size_t size);
+
+#endif // HTP_LOWER_H
diff --git a/ggml/src/ggml-hexagon/htp-opnode.cpp b/ggml/src/ggml-hexagon/htp-opnode.cpp
index b7be0cea2..f9b98cdbf 100644
--- a/ggml/src/ggml-hexagon/htp-opnode.cpp
+++ b/ggml/src/ggml-hexagon/htp-opnode.cpp
@@ -36,8 +36,18 @@ std::string htp_opnode::name() const {
case HTP_OP_ALLREDUCE: return "ALLREDUCE";
case HTP_OP_ALLREDUCE_ADD: return "ALLREDUCE+ADD";
case HTP_OP_HADAMARD: return "MUL_MAT_HADAMARD";
- case HTP_OP_MUL_MAT_NX: return "MUL_MAT_NX";
- case HTP_OP_MUL_MAT_ID_NX: return "MUL_MAT_ID_NX";
+ case HTP_OP_MUL_MAT_NX: return "MUL_MAT_NX";
+ case HTP_OP_MUL_MAT_NX_GLU: {
+ const auto * kp = kparams<htp_mm_kernel_params>();
+ switch (kp->glu_op) {
+ case HTP_OP_GLU_SWIGLU: return "MUL_MAT_NX_SWIGLU";
+ case HTP_OP_GLU_GEGLU: return "MUL_MAT_NX_GEGLU";
+ case HTP_OP_GLU_GEGLU_QUICK: return "MUL_MAT_NX_GEGLU_QUICK";
+ case HTP_OP_GLU_REGLU: return "MUL_MAT_NX_REGLU";
+ default: return "MUL_MAT_NX_GLU";
+ }
+ }
+ case HTP_OP_MUL_MAT_ID_NX: return "MUL_MAT_ID_NX";
case HTP_OP_ADD:
case HTP_OP_SUB:
case HTP_OP_MUL:
@@ -146,26 +156,32 @@ static std::string format_kernel_params(const htp_opnode & node) {
const size_t max_size = sizeof(str);
if (node.opcode == HTP_OP_MUL_MAT || node.opcode == HTP_OP_MUL_MAT_ID ||
- node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX ||
- node.opcode == HTP_OP_MUL_MAT_ADD) {
+ node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_NX_GLU ||
+ node.opcode == HTP_OP_MUL_MAT_ID_NX || node.opcode == HTP_OP_MUL_MAT_ADD) {
const auto * kparams = node.kparams<htp_mm_kernel_params>();
- const char * path = "unknown";
int32_t type = kparams->kernel_type;
- if (type == HTP_MM_KERNEL_HMX_2D || type == HTP_MM_KERNEL_HMX_BATCHED) {
- 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) {
- path = "hvx-flat";
- } else if (type == HTP_MM_KERNEL_HVX_QUANT_ROW || type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) {
- path = "hvx-tiled";
+ 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);
+ } else {
+ const char * path = "unknown";
+ if (type == HTP_MM_KERNEL_HMX_2D || type == HTP_MM_KERNEL_HMX_BATCHED) {
+ 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) {
+ path = "hvx-flat";
+ } 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 nhvx %u vtcm %u", path, (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) {
- path = kparams->u.hmx.pipeline ? "hmx-pipe" : "hmx-seq";
+ if (type == HTP_FA_KERNEL_HMX_F16) {
+ path = kparams->u.hmx.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";
} else if (type == HTP_FA_KERNEL_HVX) {
path = "hvx";
}
@@ -182,7 +198,10 @@ static std::string format_kernel_params(const htp_opnode & 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_SSM_CONV) {
const auto * kparams = node.kparams<htp_ssm_conv_kernel_params>();
- snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->n_t == 1 ? "decode" : "prefill",
+ const char * mode = kparams->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,
(unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SSM_SCAN) {
const auto * kparams = node.kparams<htp_ssm_scan_kernel_params>();
@@ -240,10 +259,10 @@ static std::string format_kernel_params(const htp_opnode & node) {
snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_PAD) {
const auto * kparams = node.kparams<htp_pad_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);
+ snprintf(str, max_size, "k%d nhvx %u chunk %u vtcm %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx, (unsigned int) kparams->chunk_elems, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_CUMSUM) {
const auto * kparams = node.kparams<htp_cumsum_kernel_params>();
- snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->use_dma ? "dma" : "hvx", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ 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_TOP_K_MASK) {
const auto * kparams = node.kparams<htp_top_k_mask_kernel_params>();
const char * ktype_str = "?";
@@ -260,7 +279,7 @@ static std::string format_kernel_params(const htp_opnode & node) {
snprintf(str, max_size, "k%d nhvx %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx);
} else if (node.opcode == HTP_OP_DIAG) {
const auto * kparams = node.kparams<htp_diag_kernel_params>();
- snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->use_dma ? "dma" : "hvx", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ 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);
diff --git a/ggml/src/ggml-hexagon/htp-opnode.h b/ggml/src/ggml-hexagon/htp-opnode.h
index a30c5b600..904c9f5a9 100644
--- a/ggml/src/ggml-hexagon/htp-opnode.h
+++ b/ggml/src/ggml-hexagon/htp-opnode.h
@@ -91,7 +91,7 @@ struct htp_opnode {
// Build inputs (preserving optional nullptrs)
if (htp_is_hadamard(this->node)) {
this->inputs.push_back(this->node->src[1]);
- } else {
+ } else if (this->node->op != GGML_OP_FILL) {
int n_inputs = n_active_src(this->node);
for (int i = 0; i < n_inputs; i++) {
this->inputs.push_back(this->node->src[i]);
diff --git a/ggml/src/ggml-hexagon/htp-repack.cpp b/ggml/src/ggml-hexagon/htp-repack.cpp
index b60c1da63..57c3363ef 100644
--- a/ggml/src/ggml-hexagon/htp-repack.cpp
+++ b/ggml/src/ggml-hexagon/htp-repack.cpp
@@ -15,169 +15,67 @@
# include <arm_neon.h>
#endif
-// --- 4-bit block-32 nibble helpers (shared by Q4_0, IQ4_NL, Q4_1, Q5_0, Q5_1, MXFP4) ---
-
-static inline void unpack_nibbles_32(uint8_t * dst, const uint8_t * qs) {
- for (unsigned int i = 0; i < 16; ++i) {
- dst[i + 0] = qs[i] & 0x0F;
- dst[i + 16] = qs[i] >> 4;
- }
-}
-
-static inline void pack_nibbles_32(uint8_t * qs, const uint8_t * src) {
- for (unsigned int i = 0; i < 16; ++i) {
- qs[i] = src[i + 0] | (src[i + 16] << 4);
- }
-}
-
-static inline void transpose_nibbles_to_tile(uint8_t * tile_dst, const uint8_t tile_quants[32][32]) {
- for (int cp = 0; cp < 16; cp++) {
- for (int row = 0; row < 32; row++) {
- tile_dst[cp * 32 + row] = (tile_quants[row][2 * cp + 1] << 4) | tile_quants[row][2 * cp];
- }
- }
-}
-
-static inline void transpose_tile_to_nibbles(uint8_t tile_quants[32][32], const uint8_t * tile_src) {
- for (int cp = 0; cp < 16; cp++) {
- for (int row = 0; row < 32; row++) {
- const uint8_t val = tile_src[cp * 32 + row];
- tile_quants[row][2 * cp + 0] = val & 0x0F;
- tile_quants[row][2 * cp + 1] = val >> 4;
- }
- }
-}
-
-// 5th-bit plane of one row (qh bit k = quant k), same bit layout as the Q5_K plane
+// 5th-bit plane of one row (qh bit k = quant k), 4-K-grouped layout matching wb planes
static inline void pack_q5_plane(uint8_t * plane, int row, uint32_t qh) {
- for (int c = 0; c < 4; c++) {
+ for (int j = 0; j < 4; j++) {
uint32_t v = 0;
- for (int i = 0; i < 4; i++) {
- v |= ((qh >> (8 * i + 2 * c)) & 3) << (2 * i);
+ for (int g = 0; g < 8; g++) {
+ v |= ((qh >> (4 * g + j)) & 1u) << g;
}
- plane[c * 32 + row] = (uint8_t) v;
+ plane[row * 4 + j] = (uint8_t) v;
}
}
static inline uint32_t unpack_q5_plane(const uint8_t * plane, int row) {
uint32_t qh = 0;
- for (int c = 0; c < 4; c++) {
- const uint32_t v = plane[c * 32 + row];
- for (int i = 0; i < 4; i++) {
- qh |= ((v >> (2 * i)) & 3) << (8 * i + 2 * c);
+ for (int j = 0; j < 4; j++) {
+ const uint32_t v = plane[row * 4 + j];
+ for (int g = 0; g < 8; g++) {
+ qh |= ((v >> g) & 1u) << (4 * g + j);
}
}
return qh;
}
#if defined(__ARM_NEON) || defined(__aarch64__)
-static void repack_neon_transpose8x8(const uint8x8_t rows[8], uint8x8_t columns[8]) {
- const uint8x8x2_t t0 = vtrn_u8(rows[0], rows[1]);
- const uint8x8x2_t t1 = vtrn_u8(rows[2], rows[3]);
- const uint8x8x2_t t2 = vtrn_u8(rows[4], rows[5]);
- const uint8x8x2_t t3 = vtrn_u8(rows[6], rows[7]);
- const uint16x4x2_t t4 = vtrn_u16(vreinterpret_u16_u8(t0.val[0]), vreinterpret_u16_u8(t1.val[0]));
- const uint16x4x2_t t5 = vtrn_u16(vreinterpret_u16_u8(t0.val[1]), vreinterpret_u16_u8(t1.val[1]));
- const uint16x4x2_t t6 = vtrn_u16(vreinterpret_u16_u8(t2.val[0]), vreinterpret_u16_u8(t3.val[0]));
- const uint16x4x2_t t7 = vtrn_u16(vreinterpret_u16_u8(t2.val[1]), vreinterpret_u16_u8(t3.val[1]));
- const uint32x2x2_t t8 = vtrn_u32(vreinterpret_u32_u16(t4.val[0]), vreinterpret_u32_u16(t6.val[0]));
- const uint32x2x2_t t9 = vtrn_u32(vreinterpret_u32_u16(t4.val[1]), vreinterpret_u32_u16(t6.val[1]));
- const uint32x2x2_t ta = vtrn_u32(vreinterpret_u32_u16(t5.val[0]), vreinterpret_u32_u16(t7.val[0]));
- const uint32x2x2_t tb = vtrn_u32(vreinterpret_u32_u16(t5.val[1]), vreinterpret_u32_u16(t7.val[1]));
- columns[0] = vreinterpret_u8_u32(t8.val[0]);
- columns[1] = vreinterpret_u8_u32(ta.val[0]);
- columns[2] = vreinterpret_u8_u32(t9.val[0]);
- columns[3] = vreinterpret_u8_u32(tb.val[0]);
- columns[4] = vreinterpret_u8_u32(t8.val[1]);
- columns[5] = vreinterpret_u8_u32(ta.val[1]);
- columns[6] = vreinterpret_u8_u32(t9.val[1]);
- columns[7] = vreinterpret_u8_u32(tb.val[1]);
-}
-
-static uint8x8_t repack_neon_pack_4bit_pairs(uint8x8_t first, uint8x8_t second, bool high) {
- const uint8x8x2_t separated = vuzp_u8(first, second);
- const uint8x8_t mask = vdup_n_u8(0x0F);
- uint8x8_t even = separated.val[0];
- uint8x8_t odd = separated.val[1];
-
- if (high) {
- even = vshr_n_u8(even, 4);
- odd = vshr_n_u8(odd, 4);
- }
-
- even = vand_u8(even, mask);
- odd = vand_u8(odd, mask);
- return vorr_u8(vshl_n_u8(odd, 4), even);
-}
-
-static void repack_neon_4bit_rows(const uint8_t * qs[8], uint8_t * tile_dst, int row0) {
- uint8x8_t low_rows[8];
- uint8x8_t high_rows[8];
- uint8x8_t columns[8];
-
- for (int rr = 0; rr < 8; ++rr) {
- const uint8x16_t packed = vld1q_u8(qs[rr]);
- const uint8x8_t first = vget_low_u8(packed);
- const uint8x8_t second = vget_high_u8(packed);
- low_rows[rr] = repack_neon_pack_4bit_pairs(first, second, false);
- high_rows[rr] = repack_neon_pack_4bit_pairs(first, second, true);
- }
-
- repack_neon_transpose8x8(low_rows, columns);
- for (int cp = 0; cp < 8; ++cp) {
- vst1_u8(tile_dst + cp * 32 + row0, columns[cp]);
- }
-
- repack_neon_transpose8x8(high_rows, columns);
- for (int cp = 0; cp < 8; ++cp) {
- vst1_u8(tile_dst + (cp + 8) * 32 + row0, columns[cp]);
- }
-}
-
-static void repack_neon_k4_rows(const uint8_t * qs[8], uint8_t * tile_dst, int row0, bool high) {
- uint8x8_t first_rows[8];
- uint8x8_t second_rows[8];
- uint8x8_t columns[8];
-
- for (int rr = 0; rr < 8; ++rr) {
- first_rows[rr] = repack_neon_pack_4bit_pairs(vld1_u8(qs[rr]), vld1_u8(qs[rr] + 8), high);
- second_rows[rr] = repack_neon_pack_4bit_pairs(vld1_u8(qs[rr] + 16), vld1_u8(qs[rr] + 24), high);
- }
-
- repack_neon_transpose8x8(first_rows, columns);
- for (int cp = 0; cp < 8; ++cp) {
- vst1_u8(tile_dst + cp * 32 + row0, columns[cp]);
- }
-
- repack_neon_transpose8x8(second_rows, columns);
- for (int cp = 0; cp < 8; ++cp) {
- vst1_u8(tile_dst + (cp + 8) * 32 + row0, columns[cp]);
- }
-}
-
-static void repack_neon_q8_rows(const uint8_t * qs[8], uint8_t * tile_dst, int row0) {
- uint8x8_t rows[8];
- uint8x8_t columns[8];
-
- for (int cp = 0; cp < 16; cp += 4) {
- for (int rr = 0; rr < 8; ++rr) {
- rows[rr] = vld1_u8(qs[rr] + 2 * cp);
- }
- repack_neon_transpose8x8(rows, columns);
-
- for (int pair = 0; pair < 4; ++pair) {
- const uint8x8x2_t interleaved = vzip_u8(columns[2 * pair], columns[2 * pair + 1]);
- uint8_t * dst = tile_dst + (cp + pair) * 64 + 2 * row0;
- vst1_u8(dst, interleaved.val[0]);
- vst1_u8(dst + 8, interleaved.val[1]);
- }
- }
-}
-
static inline void repack_store_u32(uint8_t * dst, uint32_t v) {
memcpy(dst, &v, sizeof(v));
}
+static inline void repack_neon_4bit_wb_row(const uint8_t * qs, uint8_t * tile_dst, int row) {
+ const uint32x4_t w = vreinterpretq_u32_u8(vld1q_u8(qs));
+ const uint32x2x2_t u = vuzp_u32(vget_low_u32(w), vget_high_u32(w));
+ const uint8x8_t even = vreinterpret_u8_u32(u.val[0]);
+ const uint8x8_t odd = vreinterpret_u8_u32(u.val[1]);
+ const uint32x2_t lo = vreinterpret_u32_u8(vorr_u8(vand_u8(even, vdup_n_u8(0x0F)), vshl_n_u8(odd, 4)));
+ const uint32x2_t hi = vreinterpret_u32_u8(vorr_u8(vshr_n_u8(even, 4), vand_u8(odd, vdup_n_u8(0xF0))));
+ repack_store_u32(tile_dst + 0 * 128 + row * 4, vget_lane_u32(lo, 0));
+ repack_store_u32(tile_dst + 1 * 128 + row * 4, vget_lane_u32(lo, 1));
+ repack_store_u32(tile_dst + 2 * 128 + row * 4, vget_lane_u32(hi, 0));
+ repack_store_u32(tile_dst + 3 * 128 + row * 4, vget_lane_u32(hi, 1));
+}
+
+static inline void repack_neon_k4_wb_row(const uint8_t * qs_sub, uint8_t * tile_dst, int row, bool high) {
+ const uint32x4_t w0 = vreinterpretq_u32_u8(vld1q_u8(qs_sub));
+ const uint32x4_t w1 = vreinterpretq_u32_u8(vld1q_u8(qs_sub + 16));
+ const uint32x2x2_t u0 = vuzp_u32(vget_low_u32(w0), vget_high_u32(w0));
+ const uint32x2x2_t u1 = vuzp_u32(vget_low_u32(w1), vget_high_u32(w1));
+ const uint8x8_t even0 = vreinterpret_u8_u32(u0.val[0]);
+ const uint8x8_t odd0 = vreinterpret_u8_u32(u0.val[1]);
+ const uint8x8_t even1 = vreinterpret_u8_u32(u1.val[0]);
+ const uint8x8_t odd1 = vreinterpret_u8_u32(u1.val[1]);
+ const uint32x2_t p01 = vreinterpret_u32_u8(high
+ ? vorr_u8(vshr_n_u8(even0, 4), vand_u8(odd0, vdup_n_u8(0xF0)))
+ : vorr_u8(vand_u8(even0, vdup_n_u8(0x0F)), vshl_n_u8(odd0, 4)));
+ const uint32x2_t p23 = vreinterpret_u32_u8(high
+ ? vorr_u8(vshr_n_u8(even1, 4), vand_u8(odd1, vdup_n_u8(0xF0)))
+ : vorr_u8(vand_u8(even1, vdup_n_u8(0x0F)), vshl_n_u8(odd1, 4)));
+ repack_store_u32(tile_dst + 0 * 128 + row * 4, vget_lane_u32(p01, 0));
+ repack_store_u32(tile_dst + 1 * 128 + row * 4, vget_lane_u32(p01, 1));
+ repack_store_u32(tile_dst + 2 * 128 + row * 4, vget_lane_u32(p23, 0));
+ repack_store_u32(tile_dst + 3 * 128 + row * 4, vget_lane_u32(p23, 1));
+}
+
static inline uint32x4_t repack_neon_transpose_2bit_4x4(uint32x4_t w) {
uint32x4_t t = vandq_u32(veorq_u32(w, vshrq_n_u32(w, 6)), vdupq_n_u32(0x00CC00CCu));
w = veorq_u32(w, veorq_u32(t, vshlq_n_u32(t, 6)));
@@ -262,19 +160,16 @@ static inline void repack_neon_q6_k(const block_q6_K * b, int kt_local, uint8_t
}
static inline void repack_neon_q5_k_qh(const uint8_t * qh, uint8_t hbit, uint8_t * plane, int row) {
- static const uint8_t mask_bytes[16] = { 1, 2, 1, 2, 1, 2, 1, 2, 4, 8, 4, 8, 4, 8, 4, 8 };
- const uint8x16_t m0 = vld1q_u8(mask_bytes);
+ static const uint32_t mask_words[4] = { 0x01010101u, 0x02020202u, 0x04040404u, 0x08080808u };
+ const uint8x16_t m0 = vreinterpretq_u8_u32(vld1q_u32(mask_words));
const uint8x16_t m1 = vshlq_n_u8(m0, 4);
const uint8x16_t vbit = vdupq_n_u8(hbit);
const uint8x16_t b0 = vandq_u8(vtstq_u8(vld1q_u8(qh + 0), vbit), m0);
const uint8x16_t b1 = vandq_u8(vtstq_u8(vld1q_u8(qh + 16), vbit), m1);
- const uint8x16_t b01 = vorrq_u8(b0, b1);
- const uint8x8_t fold = vorr_u8(vget_low_u8(b01), vget_high_u8(b01));
- const uint8x8_t out = vpadd_u8(fold, fold);
- plane[0 * 32 + row] = vget_lane_u8(out, 0);
- plane[1 * 32 + row] = vget_lane_u8(out, 1);
- plane[2 * 32 + row] = vget_lane_u8(out, 2);
- plane[3 * 32 + row] = vget_lane_u8(out, 3);
+ const uint32x4_t b01 = vreinterpretq_u32_u8(vorrq_u8(b0, b1));
+ const uint32x2_t f0 = vorr_u32(vget_low_u32(b01), vget_high_u32(b01));
+ const uint32x2_t f1 = vpadd_u32(f0, f0);
+ repack_store_u32(plane + row * 4, vget_lane_u32(f1, 0));
}
static inline uint16x8_t repack_neon_load_f16x8(const uint16_t * src) {
@@ -457,53 +352,62 @@ static void unpack_from_tiled_grid_32(void * data, const ggml_tensor * t, size_t
// --- Block-32 Quantized Types (Q4_0, IQ4_NL, Q4_1, Q5_0, Q5_1, Q8_0, MXFP4) ---
+static inline void repack_4bit_wb_row(const uint8_t * qs, uint8_t * tile_dst, int row) {
+#if defined(__ARM_NEON) || defined(__aarch64__)
+ repack_neon_4bit_wb_row(qs, tile_dst, row);
+#else
+ for (int j = 0; j < 4; ++j) {
+ tile_dst[0 * 128 + row * 4 + j] = (uint8_t) (((qs[4 + j] & 0x0F) << 4) | (qs[0 + j] & 0x0F));
+ tile_dst[1 * 128 + row * 4 + j] = (uint8_t) (((qs[12 + j] & 0x0F) << 4) | (qs[8 + j] & 0x0F));
+ tile_dst[2 * 128 + row * 4 + j] = (uint8_t) ((qs[4 + j] & 0xF0) | (qs[0 + j] >> 4));
+ tile_dst[3 * 128 + row * 4 + j] = (uint8_t) ((qs[12 + j] & 0xF0) | (qs[8 + j] >> 4));
+ }
+#endif
+}
+
+static inline void unpack_4bit_wb_row(uint8_t * qs, const uint8_t * tile_src, int row) {
+ for (int j = 0; j < 4; ++j) {
+ const uint8_t p0 = tile_src[0 * 128 + row * 4 + j];
+ const uint8_t p1 = tile_src[1 * 128 + row * 4 + j];
+ const uint8_t p2 = tile_src[2 * 128 + row * 4 + j];
+ const uint8_t p3 = tile_src[3 * 128 + row * 4 + j];
+ qs[0 + j] = (uint8_t) ((p0 & 0x0F) | ((p2 & 0x0F) << 4));
+ qs[4 + j] = (uint8_t) ((p0 >> 4) | (p2 & 0xF0));
+ qs[8 + j] = (uint8_t) ((p1 & 0x0F) | ((p3 & 0x0F) << 4));
+ qs[12 + j] = (uint8_t) ((p1 >> 4) | (p3 & 0xF0));
+ }
+}
+
static void repack_q4_0_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
repack_to_tiled_grid_32<block_q4_0, 1>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_0,
[](uint8_t * tile_dst, const block_q4_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
ggml_half * scale_dst = (ggml_half *) (tile_dst + 512);
-#if defined(__ARM_NEON) || defined(__aarch64__)
- if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) {
- for (int row0 = 0; row0 < 32; row0 += 8) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs;
- }
- repack_neon_4bit_rows(qs, tile_dst, row0);
- }
-
- for (int row = 0; row < 32; ++row) {
- scale_dst[row] = src_slice[(ct * 32 + row) * row_stride + kt].d;
- }
- return;
- }
-#endif
- uint8_t tile_quants[32][32];
+ const bool valid_kt = kt < ne0 / 32;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
- if (r < ne1 && kt < ne0 / 32) {
+ if (r < ne1 && valid_kt) {
const block_q4_0 & b = src_slice[r * row_stride + kt];
- unpack_nibbles_32(tile_quants[row], b.qs);
+ repack_4bit_wb_row(b.qs, tile_dst, row);
scale_dst[row] = b.d;
} else {
- memset(tile_quants[row], 8, 32);
+ for (int i = 0; i < 4; ++i) {
+ memset(tile_dst + i * 128 + row * 4, 0x88, 4);
+ }
scale_dst[row] = 0;
}
}
- transpose_nibbles_to_tile(tile_dst, tile_quants);
});
}
static void repack_tiled_q4_0(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<block_q4_0, 1>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q4_0,
[](block_q4_0 * 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) {
- uint8_t tile_quants[32][32];
- transpose_tile_to_nibbles(tile_quants, tile_src);
const ggml_half * scale_src = (const ggml_half *) (tile_src + 512);
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
if (r >= start_row && r < end_row && kt < ne0 / 32) {
block_q4_0 & b = dst_slice[(r - start_row) * row_stride + kt];
- pack_nibbles_32(b.qs, tile_quants[row]);
+ unpack_4bit_wb_row(b.qs, tile_src, row);
b.d = scale_src[row];
}
}
@@ -514,53 +418,34 @@ static void repack_q4_1_tiled(ggml_tensor * t, const void * data, size_t offset,
repack_to_tiled_grid_32<block_q4_1, 1>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_1,
[](uint8_t * tile_dst, const block_q4_1 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
ggml_half * scale_dst = (ggml_half *) (tile_dst + 512);
-#if defined(__ARM_NEON) || defined(__aarch64__)
- if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) {
- for (int row0 = 0; row0 < 32; row0 += 8) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs;
- }
- repack_neon_4bit_rows(qs, tile_dst, row0);
- }
-
- for (int row = 0; row < 32; ++row) {
- const block_q4_1 & src_block = src_slice[(ct * 32 + row) * row_stride + kt];
- scale_dst[2 * row + 0] = src_block.d;
- scale_dst[2 * row + 1] = src_block.m;
- }
- return;
- }
-#endif
- uint8_t tile_quants[32][32];
+ const bool valid_kt = kt < ne0 / 32;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
- if (r < ne1 && kt < ne0 / 32) {
+ if (r < ne1 && valid_kt) {
const block_q4_1 & b = src_slice[r * row_stride + kt];
- unpack_nibbles_32(tile_quants[row], b.qs);
+ repack_4bit_wb_row(b.qs, tile_dst, row);
scale_dst[2 * row + 0] = b.d;
scale_dst[2 * row + 1] = b.m;
} else {
- memset(tile_quants[row], 0, 32);
+ for (int i = 0; i < 4; ++i) {
+ memset(tile_dst + i * 128 + row * 4, 0, 4);
+ }
scale_dst[2 * row + 0] = 0;
scale_dst[2 * row + 1] = 0;
}
}
- transpose_nibbles_to_tile(tile_dst, tile_quants);
});
}
static void repack_tiled_q4_1(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<block_q4_1, 1>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q4_1,
[](block_q4_1 * 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) {
- uint8_t tile_quants[32][32];
- transpose_tile_to_nibbles(tile_quants, tile_src);
const ggml_half * scale_src = (const ggml_half *) (tile_src + 512);
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
if (r >= start_row && r < end_row && kt < ne0 / 32) {
block_q4_1 & b = dst_slice[(r - start_row) * row_stride + kt];
- pack_nibbles_32(b.qs, tile_quants[row]);
+ unpack_4bit_wb_row(b.qs, tile_src, row);
b.d = scale_src[2 * row + 0];
b.m = scale_src[2 * row + 1];
}
@@ -573,58 +458,37 @@ static void repack_q5_0_tiled(ggml_tensor * t, const void * data, size_t offset,
[](uint8_t * tile_dst, const block_q5_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
uint8_t * plane_dst = tile_dst + 512;
ggml_half * scale_dst = (ggml_half *) (tile_dst + 640);
-#if defined(__ARM_NEON) || defined(__aarch64__)
- if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) {
- for (int row0 = 0; row0 < 32; row0 += 8) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs;
- }
- repack_neon_4bit_rows(qs, tile_dst, row0);
- }
-
- for (int row = 0; row < 32; ++row) {
- const block_q5_0 & src_block = src_slice[(ct * 32 + row) * row_stride + kt];
- uint32_t qh;
- memcpy(&qh, src_block.qh, sizeof(qh));
- pack_q5_plane(plane_dst, row, ~qh);
- scale_dst[row] = src_block.d;
- }
- return;
- }
-#endif
- uint8_t tile_quants[32][32];
+ const bool valid_kt = kt < ne0 / 32;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
- if (r < ne1 && kt < ne0 / 32) {
+ if (r < ne1 && valid_kt) {
const block_q5_0 & b = src_slice[r * row_stride + kt];
- unpack_nibbles_32(tile_quants[row], b.qs);
+ repack_4bit_wb_row(b.qs, tile_dst, row);
uint32_t qh;
memcpy(&qh, b.qh, sizeof(qh));
pack_q5_plane(plane_dst, row, ~qh);
scale_dst[row] = b.d;
} else {
- memset(tile_quants[row], 0, 32);
- pack_q5_plane(plane_dst, row, 0);
+ for (int i = 0; i < 4; ++i) {
+ memset(tile_dst + i * 128 + row * 4, 0, 4);
+ }
+ memset(plane_dst + row * 4, 0, 4);
scale_dst[row] = 0;
}
}
- transpose_nibbles_to_tile(tile_dst, tile_quants);
});
}
static void repack_tiled_q5_0(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<block_q5_0, 1>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q5_0,
[](block_q5_0 * 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) {
- uint8_t tile_quants[32][32];
- transpose_tile_to_nibbles(tile_quants, tile_src);
const uint8_t * plane_src = tile_src + 512;
const ggml_half * scale_src = (const ggml_half *) (tile_src + 640);
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
if (r >= start_row && r < end_row && kt < ne0 / 32) {
block_q5_0 & b = dst_slice[(r - start_row) * row_stride + kt];
- pack_nibbles_32(b.qs, tile_quants[row]);
+ unpack_4bit_wb_row(b.qs, tile_src, row);
const uint32_t qh = ~unpack_q5_plane(plane_src, row);
memcpy(b.qh, &qh, sizeof(qh));
b.d = scale_src[row];
@@ -639,61 +503,39 @@ static void repack_q5_1_tiled(ggml_tensor * t, const void * data, size_t offset,
[](uint8_t * tile_dst, const block_q5_1 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
ggml_half * scale_dst = (ggml_half *) (tile_dst + 512);
uint8_t * plane_dst = tile_dst + 640;
-#if defined(__ARM_NEON) || defined(__aarch64__)
- if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) {
- for (int row0 = 0; row0 < 32; row0 += 8) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs;
- }
- repack_neon_4bit_rows(qs, tile_dst, row0);
- }
-
- for (int row = 0; row < 32; ++row) {
- const block_q5_1 & src_block = src_slice[(ct * 32 + row) * row_stride + kt];
- uint32_t qh;
- memcpy(&qh, src_block.qh, sizeof(qh));
- pack_q5_plane(plane_dst, row, qh);
- scale_dst[2 * row + 0] = src_block.d;
- scale_dst[2 * row + 1] = src_block.m;
- }
- return;
- }
-#endif
- uint8_t tile_quants[32][32];
+ const bool valid_kt = kt < ne0 / 32;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
- if (r < ne1 && kt < ne0 / 32) {
+ if (r < ne1 && valid_kt) {
const block_q5_1 & b = src_slice[r * row_stride + kt];
- unpack_nibbles_32(tile_quants[row], b.qs);
+ repack_4bit_wb_row(b.qs, tile_dst, row);
uint32_t qh;
memcpy(&qh, b.qh, sizeof(qh));
pack_q5_plane(plane_dst, row, qh);
scale_dst[2 * row + 0] = b.d;
scale_dst[2 * row + 1] = b.m;
} else {
- memset(tile_quants[row], 0, 32);
- pack_q5_plane(plane_dst, row, 0);
+ for (int i = 0; i < 4; ++i) {
+ memset(tile_dst + i * 128 + row * 4, 0, 4);
+ }
+ memset(plane_dst + row * 4, 0, 4);
scale_dst[2 * row + 0] = 0;
scale_dst[2 * row + 1] = 0;
}
}
- transpose_nibbles_to_tile(tile_dst, tile_quants);
});
}
static void repack_tiled_q5_1(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<block_q5_1, 1>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q5_1,
[](block_q5_1 * 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) {
- uint8_t tile_quants[32][32];
- transpose_tile_to_nibbles(tile_quants, tile_src);
const ggml_half * scale_src = (const ggml_half *) (tile_src + 512);
const uint8_t * plane_src = tile_src + 640;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
if (r >= start_row && r < end_row && kt < ne0 / 32) {
block_q5_1 & b = dst_slice[(r - start_row) * row_stride + kt];
- pack_nibbles_32(b.qs, tile_quants[row]);
+ unpack_4bit_wb_row(b.qs, tile_src, row);
const uint32_t qh = unpack_q5_plane(plane_src, row);
memcpy(b.qh, &qh, sizeof(qh));
b.d = scale_src[2 * row + 0];
@@ -706,50 +548,33 @@ static void repack_tiled_q5_1(void * data, const ggml_tensor * t, size_t offset,
static void repack_mxfp4_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
repack_to_tiled_grid_32<block_mxfp4, 1>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_MXFP4,
[](uint8_t * tile_dst, const block_mxfp4 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
- uint8_t * scale_dst = tile_dst + 512;
-#if defined(__ARM_NEON) || defined(__aarch64__)
- if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) {
- for (int row0 = 0; row0 < 32; row0 += 8) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs;
- }
- repack_neon_4bit_rows(qs, tile_dst, row0);
- }
-
- for (int row = 0; row < 32; ++row) {
- scale_dst[row] = src_slice[(ct * 32 + row) * row_stride + kt].e;
- }
- return;
- }
-#endif
- uint8_t tile_quants[32][32];
+ uint8_t * scale_dst = tile_dst + 512;
+ const bool valid_kt = kt < ne0 / 32;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
- if (r < ne1 && kt < ne0 / 32) {
+ if (r < ne1 && valid_kt) {
const block_mxfp4 & b = src_slice[r * row_stride + kt];
- unpack_nibbles_32(tile_quants[row], b.qs);
+ repack_4bit_wb_row(b.qs, tile_dst, row);
scale_dst[row] = b.e;
} else {
- memset(tile_quants[row], 0, 32);
+ for (int i = 0; i < 4; ++i) {
+ memset(tile_dst + i * 128 + row * 4, 0, 4);
+ }
scale_dst[row] = 0;
}
}
- transpose_nibbles_to_tile(tile_dst, tile_quants);
});
}
static void repack_tiled_mxfp4(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<block_mxfp4, 1>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_MXFP4,
[](block_mxfp4 * 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) {
- uint8_t tile_quants[32][32];
- transpose_tile_to_nibbles(tile_quants, tile_src);
const uint8_t * scale_src = tile_src + 512;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
if (r >= start_row && r < end_row && kt < ne0 / 32) {
block_mxfp4 & b = dst_slice[(r - start_row) * row_stride + kt];
- pack_nibbles_32(b.qs, tile_quants[row]);
+ unpack_4bit_wb_row(b.qs, tile_src, row);
b.e = scale_src[row];
}
}
@@ -760,35 +585,21 @@ static void repack_q8_0_tiled(ggml_tensor * t, const void * data, size_t offset,
repack_to_tiled_grid_32<block_q8_0, 1>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q8_0,
[](uint8_t * tile_dst, const block_q8_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
ggml_half * scale_dst = (ggml_half *) (tile_dst + 1024);
-#if defined(__ARM_NEON) || defined(__aarch64__)
- if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) {
- for (int row0 = 0; row0 < 32; row0 += 8) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = (const uint8_t *) src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs;
- }
- repack_neon_q8_rows(qs, tile_dst, row0);
- }
-
- for (int row = 0; row < 32; ++row) {
- scale_dst[row] = src_slice[(ct * 32 + row) * row_stride + kt].d;
- }
- return;
- }
-#endif
- for (int cp = 0; cp < 16; cp++) {
- const int col0 = cp * 2;
- const int col1 = col0 + 1;
- for (int row = 0; row < 32; row++) {
- const int64_t r = ct * 32 + row;
- const block_q8_0 * b = (r < ne1 && kt < ne0 / 32) ? &src_slice[r * row_stride + kt] : nullptr;
- tile_dst[cp * 64 + 2 * row + 0] = b ? b->qs[col0] : 0;
- tile_dst[cp * 64 + 2 * row + 1] = b ? b->qs[col1] : 0;
- }
- }
+ const bool valid_kt = kt < ne0 / 32;
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
- scale_dst[row] = (r < ne1 && kt < ne0 / 32) ? src_slice[r * row_stride + kt].d : 0;
+ if (r < ne1 && valid_kt) {
+ const block_q8_0 & b = src_slice[r * row_stride + kt];
+ for (int p = 0; p < 8; ++p) {
+ memcpy(tile_dst + p * 128 + row * 4, b.qs + p * 4, 4);
+ }
+ scale_dst[row] = b.d;
+ } else {
+ for (int p = 0; p < 8; ++p) {
+ memset(tile_dst + p * 128 + row * 4, 0, 4);
+ }
+ scale_dst[row] = 0;
+ }
}
});
}
@@ -796,23 +607,15 @@ static void repack_q8_0_tiled(ggml_tensor * t, const void * data, size_t offset,
static void repack_tiled_q8_0(void * data, const ggml_tensor * t, size_t offset, size_t size) {
unpack_from_tiled_grid_32<block_q8_0, 1>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q8_0,
[](block_q8_0 * 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 cp = 0; cp < 16; cp++) {
- const int col0 = cp * 2;
- const int col1 = col0 + 1;
- for (int row = 0; row < 32; row++) {
- const int64_t r = ct * 32 + row;
- if (r >= start_row && r < end_row && kt < ne0 / 32) {
- block_q8_0 & b = dst_slice[(r - start_row) * row_stride + kt];
- b.qs[col0] = tile_src[cp * 64 + 2 * row + 0];
- b.qs[col1] = tile_src[cp * 64 + 2 * row + 1];
- }
- }
- }
const ggml_half * scale_src = (const ggml_half *) (tile_src + 1024);
for (int row = 0; row < 32; row++) {
const int64_t r = ct * 32 + row;
if (r >= start_row && r < end_row && kt < ne0 / 32) {
- dst_slice[(r - start_row) * row_stride + kt].d = scale_src[row];
+ block_q8_0 & b = dst_slice[(r - start_row) * row_stride + kt];
+ for (int p = 0; p < 8; ++p) {
+ memcpy(b.qs + p * 4, tile_src + p * 128 + row * 4, 4);
+ }
+ b.d = scale_src[row];
}
}
});
@@ -1414,46 +1217,42 @@ static inline void pack_k4_scales_mins(uint8_t * scales, ggml_half * d, ggml_hal
}
}
-template <typename BlockT>
-static inline void repack_k4_quants(uint8_t * tile_dst, const BlockT * b, int row, int kt_local,
- int64_t sb_per_row, bool use_neon) {
+static inline void repack_k4_wb_row(const uint8_t * qs_sub, uint8_t * tile_dst, int row, bool high) {
#if defined(__ARM_NEON) || defined(__aarch64__)
- if (use_neon) {
- if ((row & 7) == 0) {
- const uint8_t * qs[8];
- for (int rr = 0; rr < 8; ++rr) {
- qs[rr] = b[rr * sb_per_row].qs + (kt_local / 2) * 32;
- }
- repack_neon_k4_rows(qs, tile_dst, row, (kt_local & 1) != 0);
+ repack_neon_k4_wb_row(qs_sub, tile_dst, row, high);
+#else
+ const int shift = high ? 4 : 0;
+ for (int p = 0; p < 4; ++p) {
+ for (int j = 0; j < 4; ++j) {
+ const uint8_t lo = (qs_sub[p * 8 + j] >> shift) & 0x0F;
+ const uint8_t hi = (qs_sub[p * 8 + 4 + j] >> shift) & 0x0F;
+ tile_dst[p * 128 + row * 4 + j] = (uint8_t) ((hi << 4) | lo);
}
- return;
}
-#else
- GGML_UNUSED(sb_per_row);
- GGML_UNUSED(use_neon);
#endif
- const uint8_t * qs_sub = b->qs + (kt_local / 2) * 32;
- const int shift = (kt_local & 1) ? 4 : 0;
+}
- for (int cp = 0; cp < 16; cp++) {
- const uint8_t q0 = (qs_sub[2 * cp + 0] >> shift) & 0x0F;
- const uint8_t q1 = (qs_sub[2 * cp + 1] >> shift) & 0x0F;
- tile_dst[cp * 32 + row] = (uint8_t) ((q1 << 4) | q0);
+static inline void unpack_k4_wb_row(uint8_t * qs_sub, const uint8_t * tile_src, int row, bool high) {
+ const int shift = high ? 4 : 0;
+ for (int p = 0; p < 4; ++p) {
+ for (int j = 0; j < 4; ++j) {
+ const uint8_t val = tile_src[p * 128 + row * 4 + j];
+ qs_sub[p * 8 + j] |= (uint8_t) ((val & 0x0F) << shift);
+ qs_sub[p * 8 + 4 + j] |= (uint8_t) ((val >> 4) << shift);
+ }
}
}
static void repack_q4_K_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
- const int64_t sb_per_row = t->ne[0] / QK_K;
- const bool use_neon = (t->ne[1] % 8 == 0);
repack_kquant_to_tiled_grid<block_q4_K>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_K,
- [sb_per_row, use_neon](uint8_t * tile_dst, const block_q4_K * b, int row, int kt_local) {
+ [](uint8_t * tile_dst, const block_q4_K * b, int row, int kt_local) {
const float d = GGML_FP16_TO_FP32(b->d);
const float dmin = GGML_FP16_TO_FP32(b->dmin);
uint8_t sc, m;
get_scale_min_k4(kt_local, b->scales, &sc, &m);
- repack_k4_quants(tile_dst, b, row, kt_local, sb_per_row, use_neon);
+ repack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_dst, row, (kt_local & 1) != 0);
ggml_half * scale_dst = (ggml_half *) (tile_dst + 512);
scale_dst[2 * row + 0] = GGML_FP32_TO_FP16(d * (float) sc);
@@ -1471,14 +1270,7 @@ static void repack_tiled_q4_K(void * data, const ggml_tensor * t, size_t offset,
const uint8_t * tile_src = sb_tiles + kt_local * tile_size;
const ggml_half * scale_src = (const ggml_half *) (tile_src + 512);
- uint8_t * qs_sub = b->qs + (kt_local / 2) * 32;
- const int shift = (kt_local & 1) ? 4 : 0;
-
- for (int cp = 0; cp < 16; cp++) {
- const uint8_t val = tile_src[cp * 32 + row];
- qs_sub[2 * cp + 0] |= (uint8_t) ((val & 0x0F) << shift);
- qs_sub[2 * cp + 1] |= (uint8_t) ((val >> 4) << shift);
- }
+ unpack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_src, row, (kt_local & 1) != 0);
const float D = GGML_FP16_TO_FP32(scale_src[2 * row + 0]);
const float M = GGML_FP16_TO_FP32(scale_src[2 * row + 1]);
@@ -1491,10 +1283,8 @@ static void repack_tiled_q4_K(void * data, const ggml_tensor * t, size_t offset,
}
static void repack_q5_K_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
- const int64_t sb_per_row = t->ne[0] / QK_K;
- const bool use_neon = (t->ne[1] % 8 == 0);
repack_kquant_to_tiled_grid<block_q5_K>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q5_K,
- [sb_per_row, use_neon](uint8_t * tile_dst, const block_q5_K * b, int row, int kt_local) {
+ [](uint8_t * tile_dst, const block_q5_K * b, int row, int kt_local) {
const float d = GGML_FP16_TO_FP32(b->d);
const float dmin = GGML_FP16_TO_FP32(b->dmin);
uint8_t * plane = tile_dst + 640;
@@ -1502,21 +1292,20 @@ static void repack_q5_K_tiled(ggml_tensor * t, const void * data, size_t offset,
uint8_t sc, m;
get_scale_min_k4(kt_local, b->scales, &sc, &m);
- repack_k4_quants(tile_dst, b, row, kt_local, sb_per_row, use_neon);
+ repack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_dst, row, (kt_local & 1) != 0);
const uint8_t hbit = (uint8_t) (1 << kt_local);
#if defined(__ARM_NEON) || defined(__aarch64__)
repack_neon_q5_k_qh(b->qh, hbit, plane, row);
#else
- for (int cp = 0; cp < 16; cp++) {
- const int i = cp / 4;
- const int lane = (cp % 4) * 32 + row;
- if (b->qh[2 * cp + 0] & hbit) {
- plane[lane] |= (uint8_t) (1 << (2 * i));
- }
- if (b->qh[2 * cp + 1] & hbit) {
- plane[lane] |= (uint8_t) (1 << (2 * i + 1));
+ for (int j = 0; j < 4; ++j) {
+ uint8_t v = 0;
+ for (int g = 0; g < 8; ++g) {
+ if (b->qh[4 * g + j] & hbit) {
+ v |= (uint8_t) (1u << g);
+ }
}
+ plane[row * 4 + j] = v;
}
#endif
@@ -1537,22 +1326,15 @@ static void repack_tiled_q5_K(void * data, const ggml_tensor * t, size_t offset,
const uint8_t * plane = tile_src + 640;
const ggml_half * scale_src = (const ggml_half *) (tile_src + 512);
- uint8_t * qs_sub = b->qs + (kt_local / 2) * 32;
- const int shift = (kt_local & 1) ? 4 : 0;
- const uint8_t hbit = (uint8_t) (1 << kt_local);
-
- for (int cp = 0; cp < 16; cp++) {
- const uint8_t val = tile_src[cp * 32 + row];
- qs_sub[2 * cp + 0] |= (uint8_t) ((val & 0x0F) << shift);
- qs_sub[2 * cp + 1] |= (uint8_t) ((val >> 4) << shift);
+ unpack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_src, row, (kt_local & 1) != 0);
- const int i = cp / 4;
- const int lane = (cp % 4) * 32 + row;
- if (plane[lane] & (1 << (2 * i))) {
- b->qh[2 * cp + 0] |= hbit;
- }
- if (plane[lane] & (1 << (2 * i + 1))) {
- b->qh[2 * cp + 1] |= hbit;
+ const uint8_t hbit = (uint8_t) (1 << kt_local);
+ for (int j = 0; j < 4; ++j) {
+ const uint8_t v = plane[row * 4 + j];
+ for (int g = 0; g < 8; ++g) {
+ if (v & (1u << g)) {
+ b->qh[4 * g + j] |= hbit;
+ }
}
}
@@ -1714,25 +1496,32 @@ static void repack_tiled_iq2_xxs(void * data, const ggml_tensor * t, size_t offs
});
}
-// --- NVFP4 (576 B tile: Q4_0-style nibble transpose + 2 UE4M3 scales per row, one block-64 = 2 k-tiles) ---
+// --- NVFP4 (576 B tile: 4-K-grouped wb nibbles + 2 UE4M3 scales per row, one block-64 = 2 k-tiles) ---
#define NVFP4_TILE_NIBBLE_BYTES 512
#define NVFP4_KT_PER_BLOCK (QK_NVFP4 / 32)
#define NVFP4_SUB_PER_KT (32 / QK_NVFP4_SUB)
-// element e (0..31) of k-tile kt_half lives in sub-block 2*kt_half + e/16, low nibble if (e%16) < 8
-static inline uint8_t nvfp4_get_nibble(const block_nvfp4 & b, int kt_half, int e) {
- const int sub = kt_half * NVFP4_SUB_PER_KT + e / QK_NVFP4_SUB;
- const int j = e % (QK_NVFP4_SUB / 2);
- const uint8_t q = b.qs[sub * (QK_NVFP4_SUB / 2) + j];
- return (e % QK_NVFP4_SUB) < QK_NVFP4_SUB / 2 ? (q & 0x0F) : (q >> 4);
+static inline void repack_nvfp4_wb_row(const uint8_t * qs, uint8_t * tile_dst, int row) {
+ for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) {
+ const uint8_t * qs_sub = qs + u * (QK_NVFP4_SUB / 2);
+ for (int j = 0; j < 4; ++j) {
+ tile_dst[(2 * u + 0) * 128 + row * 4 + j] = (uint8_t) (((qs_sub[4 + j] & 0x0F) << 4) | (qs_sub[j] & 0x0F));
+ tile_dst[(2 * u + 1) * 128 + row * 4 + j] = (uint8_t) ((qs_sub[4 + j] & 0xF0) | (qs_sub[j] >> 4));
+ }
+ }
}
-static inline void nvfp4_set_nibble(block_nvfp4 & b, int kt_half, int e, uint8_t v) {
- const int sub = kt_half * NVFP4_SUB_PER_KT + e / QK_NVFP4_SUB;
- const int j = e % (QK_NVFP4_SUB / 2);
- uint8_t & q = b.qs[sub * (QK_NVFP4_SUB / 2) + j];
- q |= (e % QK_NVFP4_SUB) < QK_NVFP4_SUB / 2 ? v : (uint8_t) (v << 4);
+static inline void unpack_nvfp4_wb_row(uint8_t * qs, const uint8_t * tile_src, int row) {
+ for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) {
+ uint8_t * qs_sub = qs + u * (QK_NVFP4_SUB / 2);
+ for (int j = 0; j < 4; ++j) {
+ const uint8_t p0 = tile_src[(2 * u + 0) * 128 + row * 4 + j];
+ const uint8_t p1 = tile_src[(2 * u + 1) * 128 + row * 4 + j];
+ qs_sub[j] = (uint8_t) ((p0 & 0x0F) | ((p1 & 0x0F) << 4));
+ qs_sub[4 + j] = (uint8_t) ((p0 >> 4) | (p1 & 0xF0));
+ }
+ }
}
static void repack_nvfp4_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
@@ -1752,7 +1541,7 @@ static void repack_nvfp4_tiled(ggml_tensor * t, const void * data, size_t offset
uint8_t * dst_slice = (uint8_t *) t->data + slice * matrix_size;
repack_parallel_for_ct(matrix_size, (int) n_col_tiles, [&](int ct0, int ct1) {
- // Padding rows and OR-ed nibbles require zeroed tiles
+ // Padding rows require zeroed tiles
memset(dst_slice + (size_t) ct0 * ct_bytes, 0, (size_t) (ct1 - ct0) * ct_bytes);
const int64_t r0 = (int64_t) ct0 * 32;
@@ -1764,9 +1553,7 @@ static void repack_nvfp4_tiled(ggml_tensor * t, const void * data, size_t offset
const block_nvfp4 & b = src_slice[r * blocks_per_row + blk];
for (int h = 0; h < NVFP4_KT_PER_BLOCK; ++h) {
uint8_t * tile = dst_slice + (ct * n_k_tiles + blk * NVFP4_KT_PER_BLOCK + h) * HTP_TENSOR_TILE_SIZE_NVFP4;
- for (int e = 0; e < 32; ++e) {
- tile[(e / 2) * 32 + row] |= (uint8_t) (nvfp4_get_nibble(b, h, e) << (4 * (e & 1)));
- }
+ repack_nvfp4_wb_row(b.qs + h * 16, tile, row);
for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) {
tile[NVFP4_TILE_NIBBLE_BYTES + u * 32 + row] = b.d[h * NVFP4_SUB_PER_KT + u];
}
@@ -1802,9 +1589,7 @@ static void repack_tiled_nvfp4(void * data, const ggml_tensor * t, size_t offset
for (int h = 0; h < NVFP4_KT_PER_BLOCK; ++h) {
const uint8_t * tile = (const uint8_t *) t->data + slice * matrix_size +
(ct * n_k_tiles + blk * NVFP4_KT_PER_BLOCK + h) * HTP_TENSOR_TILE_SIZE_NVFP4;
- for (int e = 0; e < 32; ++e) {
- nvfp4_set_nibble(b, h, e, (tile[(e / 2) * 32 + row] >> (4 * (e & 1))) & 0x0F);
- }
+ unpack_nvfp4_wb_row(b.qs + h * 16, tile, row);
for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) {
b.d[h * NVFP4_SUB_PER_KT + u] = tile[NVFP4_TILE_NIBBLE_BYTES + u * 32 + row];
}
diff --git a/ggml/src/ggml-hexagon/htp/CMakeLists.txt b/ggml/src/ggml-hexagon/htp/CMakeLists.txt
index 029f9df99..409adae2b 100644
--- a/ggml/src/ggml-hexagon/htp/CMakeLists.txt
+++ b/ggml/src/ggml-hexagon/htp/CMakeLists.txt
@@ -19,8 +19,9 @@ add_library(${HTP_LIB} SHARED
htp_iface_skel.c
work-queue.c
dma-queue.c
+ dma-proxy.c
hmx-queue.c
- htp-dcache.c
+ htp-tensor.c
matmul-ops.c
flash-attn-ops.c
gated-delta-net-ops.c
diff --git a/ggml/src/ggml-hexagon/htp/allreduce-ops.c b/ggml/src/ggml-hexagon/htp/allreduce-ops.c
index 1b95917ae..8af3b1e8f 100644
--- a/ggml/src/ggml-hexagon/htp/allreduce-ops.c
+++ b/ggml/src/ggml-hexagon/htp/allreduce-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <stdatomic.h>
diff --git a/ggml/src/ggml-hexagon/htp/argsort-ops.c b/ggml/src/ggml-hexagon/htp/argsort-ops.c
index af2605954..d8560e5ae 100644
--- a/ggml/src/ggml-hexagon/htp/argsort-ops.c
+++ b/ggml/src/ggml-hexagon/htp/argsort-ops.c
@@ -92,273 +92,518 @@ static void quicksort_values_indices_desc(float * values, int32_t * indices, int
}
}
-static inline uint32_t top_k_max_value_index(const float * values, uint32_t n, float * value) {
- int32_t max_idx = 0;
- hvx_argmax_f32(values, n, 0, value, &max_idx);
- return (uint32_t) max_idx;
-}
-
static const int32_t argsort_ramp_lut[32] __attribute__((aligned(VLEN))) = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
};
+static const uint32_t top_k_bit_lut[32] __attribute__((aligned(VLEN))) = {
+ 1u << 0, 1u << 1, 1u << 2, 1u << 3, 1u << 4, 1u << 5, 1u << 6, 1u << 7,
+ 1u << 8, 1u << 9, 1u << 10, 1u << 11, 1u << 12, 1u << 13, 1u << 14, 1u << 15,
+ 1u << 16, 1u << 17, 1u << 18, 1u << 19, 1u << 20, 1u << 21, 1u << 22, 1u << 23,
+ 1u << 24, 1u << 25, 1u << 26, 1u << 27, 1u << 28, 1u << 29, 1u << 30, 1u << 31
+};
+
static inline void init_indices_ramp(int32_t * indices_buf, uint32_t count, uint32_t base) {
const HVX_Vector ind_init_vec = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) argsort_ramp_lut, Q6_V_vsplat_R(base));
const HVX_Vector ind_diff_vec = Q6_V_vsplat_R(32);
HVX_Vector * indices_buf_vec = (HVX_Vector *) indices_buf;
- uint32_t num_vecs = count / 32;
+ uint32_t num_vecs = count >> 5;
HVX_Vector curr_ind_vec = ind_init_vec;
for (uint32_t j = 0; j < num_vecs; j++) {
indices_buf_vec[j] = curr_ind_vec;
curr_ind_vec = Q6_Vw_vadd_VwVw(curr_ind_vec, ind_diff_vec);
}
- uint32_t rem = count % 32;
+ uint32_t rem = count & 31u;
if (rem > 0) {
hvx_vec_store_a((void *) &indices_buf_vec[num_vecs], rem * sizeof(int32_t), curr_ind_vec);
}
}
+// Map IEEE-754 float lanes to signed int32 keys preserving +INF > finite > -INF (0x807fffff) > NaN (0x80000001) > pad (0x80000000).
+__attribute__((always_inline))
+static inline HVX_Vector float_to_ord_key_vec(HVX_Vector vf) {
+ const HVX_Vector v_abs = Q6_V_vand_VV(vf, Q6_V_vsplat_R(0x7fffffff));
+ const HVX_VectorPred q_nan = Q6_Q_vcmp_gt_VwVw(v_abs, Q6_V_vsplat_R(0x7f800000));
+ const HVX_Vector v_sign = Q6_Vw_vasr_VwR(vf, 31);
+ const HVX_Vector v_flip = Q6_Vuw_vlsr_VuwR(v_sign, 1);
+ const HVX_Vector v_key = Q6_V_vxor_VV(vf, v_flip);
+ return Q6_V_vmux_QVV(q_nan, Q6_V_vsplat_R((int32_t) 0x80000001u), v_key);
+}
+
+static inline float ord_key_to_float(int32_t key) {
+ const uint32_t u = ((uint32_t) key == 0x80000001u)
+ ? 0x7fc00000u
+ : ((key < 0) ? ((uint32_t) key ^ 0x7fffffffu) : (uint32_t) key);
+ union { uint32_t u; float f; } conv = { .u = u };
+ return conv.f;
+}
+
+__attribute__((always_inline))
+static inline uint32_t hvx_pred_i32_to_bits(HVX_VectorPred q, HVX_Vector v_bit_lut) {
+ HVX_Vector m = Q6_V_vand_QV(q, v_bit_lut);
+ m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 64));
+ m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 32));
+ m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 16));
+ m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 8));
+ m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 4));
+ return (uint32_t) Q6_R_vextract_VR(m, 0);
+}
+
+__attribute__((noinline))
+static int32_t top_k_argmax_hvx(const float * restrict vals, uint32_t n, uint32_t idx_base, float * restrict out_val) {
+ const HVX_Vector * restrict vvals = (const HVX_Vector *) vals;
+ const uint32_t n_full = n >> 5;
+ const uint32_t rem = n & 31u;
+ const HVX_Vector v_step = Q6_V_vsplat_R(32);
+ const HVX_Vector v_pad = Q6_V_vsplat_R((int32_t) 0x80000000u);
+
+ HVX_Vector v_idx = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) argsort_ramp_lut, Q6_V_vsplat_R((int32_t) idx_base));
+ HVX_Vector v_best_key = v_pad;
+ HVX_Vector v_best_idx = v_idx;
+
+ for (uint32_t v = 0; v < n_full; v++) {
+ const HVX_Vector vk = float_to_ord_key_vec(vvals[v]);
+ const HVX_VectorPred q = Q6_Q_vcmp_gt_VwVw(vk, v_best_key);
+ v_best_key = Q6_V_vmux_QVV(q, vk, v_best_key);
+ v_best_idx = Q6_V_vmux_QVV(q, v_idx, v_best_idx);
+ v_idx = Q6_Vw_vadd_VwVw(v_idx, v_step);
+ }
+ if (rem > 0) {
+ const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(rem * sizeof(int32_t));
+ const HVX_Vector vk = Q6_V_vmux_QVV(q_tail, float_to_ord_key_vec(vvals[n_full]), v_pad);
+ const HVX_VectorPred q = Q6_Q_vcmp_gt_VwVw(vk, v_best_key);
+ v_best_key = Q6_V_vmux_QVV(q, vk, v_best_key);
+ v_best_idx = Q6_V_vmux_QVV(q, v_idx, v_best_idx);
+ }
+
+ #pragma clang loop unroll(full)
+ for (int shift = 64; shift >= 4; shift >>= 1) {
+ const HVX_Vector rk = Q6_V_vror_VR(v_best_key, shift);
+ const HVX_Vector ri = Q6_V_vror_VR(v_best_idx, shift);
+ const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VwVw(rk, v_best_key);
+ const HVX_VectorPred q_eq = Q6_Q_vcmp_eq_VwVw(rk, v_best_key);
+ const HVX_VectorPred q_idx = Q6_Q_vcmp_gt_VwVw(v_best_idx, ri);
+ const HVX_VectorPred q_win = Q6_Q_or_QQ(q_gt, Q6_Q_and_QQ(q_eq, q_idx));
+ v_best_key = Q6_V_vmux_QVV(q_win, rk, v_best_key);
+ v_best_idx = Q6_V_vmux_QVV(q_win, ri, v_best_idx);
+ }
+
+ if (out_val) {
+ *out_val = ord_key_to_float((int32_t) Q6_R_vextract_VR(v_best_key, 0));
+ }
+ return (int32_t) Q6_R_vextract_VR(v_best_idx, 0);
+}
+
__attribute__((always_inline))
static inline void vec_cas(HVX_Vector * X_val, HVX_Vector * X_idx, HVX_Vector * Y_val, HVX_Vector * Y_idx, bool asc) {
- HVX_VectorPred pred = asc ? Q6_Q_vcmp_gt_VsfVsf(*X_val, *Y_val)
- : Q6_Q_vcmp_gt_VsfVsf(*Y_val, *X_val);
- HVX_Vector next_X_val = Q6_V_vmux_QVV(pred, *Y_val, *X_val);
- HVX_Vector next_Y_val = Q6_V_vmux_QVV(pred, *X_val, *Y_val);
- HVX_Vector next_X_idx = Q6_V_vmux_QVV(pred, *Y_idx, *X_idx);
- HVX_Vector Y_tmp_idx = Q6_V_vmux_QVV(pred, *X_idx, *Y_idx);
+ asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx));
+ const HVX_Vector lhs = asc ? *X_val : *Y_val;
+ const HVX_Vector rhs = asc ? *Y_val : *X_val;
+ const HVX_VectorPred pred = Q6_Q_vcmp_gt_VsfVsf(lhs, rhs);
+ const HVX_Vector next_X_val = Q6_V_vmux_QVV(pred, *Y_val, *X_val);
+ const HVX_Vector next_Y_val = Q6_V_vmux_QVV(pred, *X_val, *Y_val);
+ const HVX_Vector next_X_idx = Q6_V_vmux_QVV(pred, *Y_idx, *X_idx);
+ const HVX_Vector next_Y_idx = Q6_V_vmux_QVV(pred, *X_idx, *Y_idx);
*X_val = next_X_val;
*Y_val = next_Y_val;
*X_idx = next_X_idx;
- *Y_idx = Y_tmp_idx;
+ *Y_idx = next_Y_idx;
+ asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx));
}
__attribute__((always_inline))
-static inline void bitonic_cas_32(HVX_Vector * V, HVX_Vector * I, int d, HVX_VectorPred dir_mask, HVX_Vector idx_vec, HVX_Vector zero_vec) {
- HVX_VectorPred mask_left;
- HVX_Vector V_rot_left, V_rot_right;
- HVX_Vector I_rot_left, I_rot_right;
-
- if (d == 1) {
- mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(1)), zero_vec);
- V_rot_left = Q6_V_vror_VR(*V, 4);
- V_rot_right = Q6_V_vror_VR(*V, 124);
- I_rot_left = Q6_V_vror_VR(*I, 4);
- I_rot_right = Q6_V_vror_VR(*I, 124);
- } else if (d == 2) {
- mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(2)), zero_vec);
- V_rot_left = Q6_V_vror_VR(*V, 8);
- V_rot_right = Q6_V_vror_VR(*V, 120);
- I_rot_left = Q6_V_vror_VR(*I, 8);
- I_rot_right = Q6_V_vror_VR(*I, 120);
- } else if (d == 4) {
- mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(4)), zero_vec);
- V_rot_left = Q6_V_vror_VR(*V, 16);
- V_rot_right = Q6_V_vror_VR(*V, 112);
- I_rot_left = Q6_V_vror_VR(*I, 16);
- I_rot_right = Q6_V_vror_VR(*I, 112);
- } else if (d == 8) {
- mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(8)), zero_vec);
- V_rot_left = Q6_V_vror_VR(*V, 32);
- V_rot_right = Q6_V_vror_VR(*V, 96);
- I_rot_left = Q6_V_vror_VR(*I, 32);
- I_rot_right = Q6_V_vror_VR(*I, 96);
- } else {
- mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(16)), zero_vec);
- V_rot_left = Q6_V_vror_VR(*V, 64);
- V_rot_right = Q6_V_vror_VR(*V, 64);
- I_rot_left = Q6_V_vror_VR(*I, 64);
- I_rot_right = Q6_V_vror_VR(*I, 64);
- }
-
- HVX_Vector V_paired = Q6_V_vmux_QVV(mask_left, V_rot_left, V_rot_right);
- HVX_Vector I_paired = Q6_V_vmux_QVV(mask_left, I_rot_left, I_rot_right);
-
- HVX_VectorPred V_gt_Vpaired = Q6_Q_vcmp_gt_VsfVsf(*V, V_paired);
- HVX_VectorPred Vpaired_gt_V = Q6_Q_vcmp_gt_VsfVsf(V_paired, *V);
- HVX_VectorPred mask_right = Q6_Q_not_Q(mask_left);
- HVX_VectorPred Q_asc = Q6_Q_or_QQ(
- Q6_Q_and_QQ(mask_left, V_gt_Vpaired),
- Q6_Q_and_QQ(Vpaired_gt_V, mask_right)
- );
- HVX_VectorPred Q_swap = Q6_Q_or_QQ(
- Q6_Q_and_QQ(dir_mask, Q_asc),
- Q6_Q_and_QQ(Q6_Q_not_Q(dir_mask), Q6_Q_not_Q(Q_asc))
+static inline void bitonic_cas_32(HVX_Vector * V, HVX_Vector * I, int d, int s, int stage_d, bool asc, HVX_Vector idx_vec, HVX_Vector zero_vec) {
+ HVX_Vector idx = idx_vec;
+ int flip = asc ? 0 : d;
+ asm volatile("" : "+v"(*V), "+v"(*I), "+v"(idx), "+r"(d), "+r"(flip));
+
+ const HVX_Vector v_ctrl = Q6_Vb_vsplat_R(d << 2);
+ const HVX_Vector V_paired = Q6_V_vdelta_VV(*V, v_ctrl);
+ const HVX_Vector I_paired = Q6_V_vdelta_VV(*I, v_ctrl);
+
+ const HVX_Vector v_rhs = (s < 5) ? Q6_Vuw_vlsr_VuwR(idx, s - stage_d) : Q6_V_vsplat_R(flip);
+ const HVX_Vector v_lane_x = Q6_V_vxor_VV(idx, v_rhs);
+ const HVX_VectorPred want_max = Q6_Q_vcmp_gt_VwVw(Q6_V_vand_VV(v_lane_x, Q6_V_vsplat_R(d)), zero_vec);
+ const HVX_VectorPred V_gt_P = Q6_Q_vcmp_gt_VsfVsf(*V, V_paired);
+ const HVX_VectorPred P_gt_V = Q6_Q_vcmp_gt_VsfVsf(V_paired, *V);
+ const HVX_VectorPred Q_swap = Q6_Q_or_QQ(
+ Q6_Q_and_QQ(want_max, P_gt_V),
+ Q6_Q_and_QQn(V_gt_P, want_max)
);
*V = Q6_V_vmux_QVV(Q_swap, V_paired, *V);
*I = Q6_V_vmux_QVV(Q_swap, I_paired, *I);
+ asm volatile("" : "+v"(*V), "+v"(*I));
}
__attribute__((always_inline))
static inline void bitonic_sort_generic_hvx(uint8_t * values, uint8_t * indices, int K, bool asc_order) {
- HVX_Vector V[32];
- HVX_Vector I[32];
+ HVX_Vector V[8];
+ HVX_Vector I[8];
- HVX_Vector zero_vec = Q6_V_vzero();
- HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut;
+ const HVX_Vector zero_vec = Q6_V_vzero();
+ const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut;
+ #pragma clang loop unroll(full)
for (int v = 0; v < K; v++) {
V[v] = *(HVX_Vector *)(values + v * 128);
I[v] = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32));
}
- HVX_VectorPred pred_all_1s = Q6_Q_vcmp_eq_VwVw(zero_vec, zero_vec);
- HVX_VectorPred pred_all_0s = Q6_Q_not_Q(pred_all_1s);
-
int M = 5;
- while ((1 << (M - 5)) < K) M++;
+ while ((1 << (M - 5)) < K) {
+ M++;
+ }
+ #pragma clang loop unroll(full)
for (int s = 1; s <= M; s++) {
+ #pragma clang loop unroll(full)
for (int stage_d = s - 1; stage_d >= 0; stage_d--) {
- int d = 1 << stage_d;
+ const int d = 1 << stage_d;
if (d >= 32) {
- int v_dist = d / 32;
+ const int v_dist = d >> 5;
+ #pragma clang loop unroll(full)
for (int v1 = 0; v1 < K; v1++) {
if ((v1 & v_dist) == 0) {
- int v2 = v1 + v_dist;
- bool asc = (s < M) ? ((((v1 * 32) >> s) % 2) == 0) : asc_order;
+ const int v2 = v1 + v_dist;
+ const bool asc = (s < M) ? ((((v1 * 32) >> s) & 1) == 0) : asc_order;
vec_cas(&V[v1], &I[v1], &V[v2], &I[v2], asc);
}
}
} else {
- if (s < 5) {
- HVX_VectorPred dir_mask = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(1 << s)), zero_vec);
- for (int v = 0; v < K; v++) {
- bitonic_cas_32(&V[v], &I[v], d, dir_mask, idx_vec, zero_vec);
- }
- } else {
- for (int v = 0; v < K; v++) {
- bool asc = (s < M) ? ((((v * 32) >> s) % 2) == 0) : asc_order;
- HVX_VectorPred dir_mask = asc ? pred_all_1s : pred_all_0s;
- bitonic_cas_32(&V[v], &I[v], d, dir_mask, idx_vec, zero_vec);
- }
+ #pragma clang loop unroll(full)
+ for (int v = 0; v < K; v++) {
+ const bool asc = (s < M) ? ((((v * 32) >> s) & 1) == 0) : asc_order;
+ bitonic_cas_32(&V[v], &I[v], d, s, stage_d, asc, idx_vec, zero_vec);
}
}
}
}
+ #pragma clang loop unroll(full)
for (int v = 0; v < K; v++) {
*(HVX_Vector *)(values + v * 128) = V[v];
*(HVX_Vector *)(indices + v * 128) = I[v];
}
}
-static void bitonic_sort_vtcm_desc(uint8_t * values, uint8_t * indices, uint32_t n_vec, bool init_indices) {
- HVX_Vector zero_vec = Q6_V_vzero();
- HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut;
+__attribute__((always_inline))
+static inline void vec_cas_i32(HVX_Vector * X_val, HVX_Vector * X_idx, HVX_Vector * Y_val, HVX_Vector * Y_idx, bool asc) {
+ asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx));
+ const HVX_Vector lhs = asc ? *X_val : *Y_val;
+ const HVX_Vector rhs = asc ? *Y_val : *X_val;
+ const HVX_VectorPred pred = Q6_Q_vcmp_gt_VwVw(lhs, rhs);
+ const HVX_Vector next_X_val = Q6_V_vmux_QVV(pred, *Y_val, *X_val);
+ const HVX_Vector next_Y_val = Q6_V_vmux_QVV(pred, *X_val, *Y_val);
+ const HVX_Vector next_X_idx = Q6_V_vmux_QVV(pred, *Y_idx, *X_idx);
+ const HVX_Vector next_Y_idx = Q6_V_vmux_QVV(pred, *X_idx, *Y_idx);
+ *X_val = next_X_val;
+ *Y_val = next_Y_val;
+ *X_idx = next_X_idx;
+ *Y_idx = next_Y_idx;
+ asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx));
+}
- HVX_VectorPred pred_all_1s = Q6_Q_vcmp_eq_VwVw(zero_vec, zero_vec);
- HVX_VectorPred pred_all_0s = Q6_Q_not_Q(pred_all_1s);
+__attribute__((always_inline))
+static inline void bitonic_cas_32_i32(HVX_Vector * V, HVX_Vector * I, int d, int s, int stage_d, bool asc, HVX_Vector idx_vec, HVX_Vector zero_vec) {
+ HVX_Vector idx = idx_vec;
+ int flip = asc ? 0 : d;
+ asm volatile("" : "+v"(*V), "+v"(*I), "+v"(idx), "+r"(d), "+r"(flip));
+
+ const HVX_Vector v_ctrl = Q6_Vb_vsplat_R(d << 2);
+ const HVX_Vector V_paired = Q6_V_vdelta_VV(*V, v_ctrl);
+ const HVX_Vector I_paired = Q6_V_vdelta_VV(*I, v_ctrl);
+
+ const HVX_Vector v_rhs = (s < 5) ? Q6_Vuw_vlsr_VuwR(idx, s - stage_d) : Q6_V_vsplat_R(flip);
+ const HVX_Vector v_lane_x = Q6_V_vxor_VV(idx, v_rhs);
+ const HVX_VectorPred want_max = Q6_Q_vcmp_gt_VwVw(Q6_V_vand_VV(v_lane_x, Q6_V_vsplat_R(d)), zero_vec);
+ const HVX_VectorPred V_gt_P = Q6_Q_vcmp_gt_VwVw(*V, V_paired);
+ const HVX_VectorPred P_gt_V = Q6_Q_vcmp_gt_VwVw(V_paired, *V);
+ const HVX_VectorPred Q_swap = Q6_Q_or_QQ(
+ Q6_Q_and_QQ(want_max, P_gt_V),
+ Q6_Q_and_QQn(V_gt_P, want_max)
+ );
- if (init_indices) {
- for (uint32_t v = 0; v < n_vec; v++) {
- HVX_Vector idx = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32));
- *(HVX_Vector *)(indices + v * 128) = idx;
+ *V = Q6_V_vmux_QVV(Q_swap, V_paired, *V);
+ *I = Q6_V_vmux_QVV(Q_swap, I_paired, *I);
+ asm volatile("" : "+v"(*V), "+v"(*I));
+}
+
+__attribute__((always_inline))
+static inline void bitonic_sort_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k, int K) {
+ HVX_Vector V[8];
+ HVX_Vector I[8];
+
+ const HVX_Vector * restrict vvals = (const HVX_Vector *) values;
+ const HVX_Vector zero_vec = Q6_V_vzero();
+ const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut;
+ const HVX_Vector v_pad = Q6_V_vsplat_R((int32_t) 0x80000000u);
+ const uint32_t n_full = n >> 5;
+ const uint32_t rem = n & 31u;
+
+ #pragma clang loop unroll(full)
+ for (int v = 0; v < K; v++) {
+ if ((uint32_t) v < n_full) {
+ V[v] = float_to_ord_key_vec(vvals[v]);
+ } else if ((uint32_t) v == n_full && rem > 0u) {
+ const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(rem * sizeof(int32_t));
+ V[v] = Q6_V_vmux_QVV(q_tail, float_to_ord_key_vec(vvals[v]), v_pad);
+ } else {
+ V[v] = v_pad;
}
+ I[v] = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32));
}
int M = 5;
- while ((1u << (M - 5)) < n_vec) M++;
+ while ((1 << (M - 5)) < K) {
+ M++;
+ }
+ #pragma clang loop unroll(full)
for (int s = 1; s <= M; s++) {
+ #pragma clang loop unroll(full)
for (int stage_d = s - 1; stage_d >= 0; stage_d--) {
- int d = 1 << stage_d;
+ const int d = 1 << stage_d;
if (d >= 32) {
- uint32_t v_dist = d / 32;
- for (uint32_t v1 = 0; v1 < n_vec; v1++) {
+ const int v_dist = d >> 5;
+ #pragma clang loop unroll(full)
+ for (int v1 = 0; v1 < K; v1++) {
if ((v1 & v_dist) == 0) {
- uint32_t v2 = v1 + v_dist;
- bool asc = (s < M) ? ((((v1 * 32) >> s) % 2) == 0) : false;
+ const int v2 = v1 + v_dist;
+ const bool asc = (s < M) ? ((((v1 * 32) >> s) & 1) == 0) : false;
+ vec_cas_i32(&V[v1], &I[v1], &V[v2], &I[v2], asc);
+ }
+ }
+ } else {
+ #pragma clang loop unroll(full)
+ for (int v = 0; v < K; v++) {
+ const bool asc = (s < M) ? ((((v * 32) >> s) & 1) == 0) : false;
+ bitonic_cas_32_i32(&V[v], &I[v], d, s, stage_d, asc, idx_vec, zero_vec);
+ }
+ }
+ }
+ }
+
+ HVX_Vector * restrict vout = (HVX_Vector *) indices;
+ const uint32_t k_vecs = (k + 31u) >> 5;
+ #pragma clang loop unroll(full)
+ for (int v = 0; v < K; v++) {
+ if ((uint32_t) v < k_vecs) {
+ vout[v] = I[v];
+ }
+ }
+}
+
+__attribute__((noinline))
+static void sort32_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) {
+ bitonic_sort_top_k_hvx(values, indices, n, k, 1);
+}
- HVX_Vector Vv1 = *(HVX_Vector *)(values + v1 * 128);
- HVX_Vector Iv1 = *(HVX_Vector *)(indices + v1 * 128);
- HVX_Vector Vv2 = *(HVX_Vector *)(values + v2 * 128);
- HVX_Vector Iv2 = *(HVX_Vector *)(indices + v2 * 128);
+__attribute__((noinline))
+static void sort64_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) {
+ bitonic_sort_top_k_hvx(values, indices, n, k, 2);
+}
- vec_cas(&Vv1, &Iv1, &Vv2, &Iv2, asc);
+__attribute__((noinline))
+static void sort128_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) {
+ bitonic_sort_top_k_hvx(values, indices, n, k, 4);
+}
- *(HVX_Vector *)(values + v1 * 128) = Vv1;
- *(HVX_Vector *)(indices + v1 * 128) = Iv1;
- *(HVX_Vector *)(values + v2 * 128) = Vv2;
- *(HVX_Vector *)(indices + v2 * 128) = Iv2;
- }
- }
+__attribute__((noinline))
+static void sort256_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) {
+ bitonic_sort_top_k_hvx(values, indices, n, k, 8);
+}
+
+__attribute__((noinline))
+static void sort64_i32_desc(int32_t * restrict keys, int32_t * restrict indices) {
+ HVX_Vector * restrict vk = (HVX_Vector *) keys;
+ HVX_Vector * restrict vi = (HVX_Vector *) indices;
+ HVX_Vector V[2] = { vk[0], vk[1] };
+ HVX_Vector I[2] = { vi[0], vi[1] };
+
+ const HVX_Vector zero_vec = Q6_V_vzero();
+ const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut;
+
+ #pragma clang loop unroll(full)
+ for (int s = 1; s <= 6; s++) {
+ #pragma clang loop unroll(full)
+ for (int stage_d = s - 1; stage_d >= 0; stage_d--) {
+ const int d = 1 << stage_d;
+ if (d >= 32) {
+ vec_cas_i32(&V[0], &I[0], &V[1], &I[1], false);
} else {
- if (s < 5) {
- HVX_VectorPred dir_mask = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(1 << s)), zero_vec);
- for (uint32_t v = 0; v < n_vec; v++) {
- HVX_Vector Vv = *(HVX_Vector *)(values + v * 128);
- HVX_Vector Iv = *(HVX_Vector *)(indices + v * 128);
+ #pragma clang loop unroll(full)
+ for (int v = 0; v < 2; v++) {
+ const bool asc = (s < 6) ? (v == 0) : false;
+ bitonic_cas_32_i32(&V[v], &I[v], d, s, stage_d, asc, idx_vec, zero_vec);
+ }
+ }
+ }
+ }
- bitonic_cas_32(&Vv, &Iv, d, dir_mask, idx_vec, zero_vec);
+ vk[0] = V[0];
+ vk[1] = V[1];
+ vi[0] = I[0];
+ vi[1] = I[1];
+}
- *(HVX_Vector *)(values + v * 128) = Vv;
- *(HVX_Vector *)(indices + v * 128) = Iv;
- }
- } else {
- for (uint32_t v = 0; v < n_vec; v++) {
- bool asc = (s < M) ? ((((v * 32) >> s) % 2) == 0) : false;
- HVX_VectorPred dir_mask = asc ? pred_all_1s : pred_all_0s;
+__attribute__((noinline))
+static void bitonic_sort_vtcm(uint8_t * restrict values, uint8_t * restrict indices, uint32_t n_vec, bool init_indices, bool asc_order) {
+ const HVX_Vector zero_vec = Q6_V_vzero();
+ const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut;
- HVX_Vector Vv = *(HVX_Vector *)(values + v * 128);
- HVX_Vector Iv = *(HVX_Vector *)(indices + v * 128);
+ if (init_indices) {
+ for (uint32_t v = 0; v < n_vec; v++) {
+ *(HVX_Vector *)(indices + v * 128) = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32));
+ }
+ }
- bitonic_cas_32(&Vv, &Iv, d, dir_mask, idx_vec, zero_vec);
+ int M = 5;
+ while ((1u << (M - 5)) < n_vec) {
+ M++;
+ }
- *(HVX_Vector *)(values + v * 128) = Vv;
- *(HVX_Vector *)(indices + v * 128) = Iv;
- }
+ for (int s = 1; s <= M; s++) {
+ for (int stage_d = s - 1; stage_d >= 5; stage_d--) {
+ const uint32_t v_dist = 1u << (stage_d - 5);
+ for (uint32_t v1 = 0; v1 < n_vec; v1++) {
+ if ((v1 & v_dist) == 0u) {
+ const uint32_t v2 = v1 + v_dist;
+ const bool asc = (s < M) ? ((((v1 * 32u) >> s) & 1u) == 0u) : asc_order;
+
+ HVX_Vector Vv1 = *(HVX_Vector *)(values + v1 * 128);
+ HVX_Vector Iv1 = *(HVX_Vector *)(indices + v1 * 128);
+ HVX_Vector Vv2 = *(HVX_Vector *)(values + v2 * 128);
+ HVX_Vector Iv2 = *(HVX_Vector *)(indices + v2 * 128);
+
+ vec_cas(&Vv1, &Iv1, &Vv2, &Iv2, asc);
+
+ *(HVX_Vector *)(values + v1 * 128) = Vv1;
+ *(HVX_Vector *)(indices + v1 * 128) = Iv1;
+ *(HVX_Vector *)(values + v2 * 128) = Vv2;
+ *(HVX_Vector *)(indices + v2 * 128) = Iv2;
}
}
}
+
+ // Fuse intra-vector butterfly stages d = 16, 8, 4, 2, 1 into one VTCM load/store per vector.
+ for (uint32_t v = 0; v < n_vec; v++) {
+ HVX_Vector Vv = *(HVX_Vector *)(values + v * 128);
+ HVX_Vector Iv = *(HVX_Vector *)(indices + v * 128);
+ const bool asc = (s < M) ? ((((v * 32u) >> s) & 1u) == 0u) : asc_order;
+
+ if (s >= 5) {
+ bitonic_cas_32(&Vv, &Iv, 16, s, 4, asc, idx_vec, zero_vec);
+ }
+ if (s >= 4) {
+ bitonic_cas_32(&Vv, &Iv, 8, s, 3, asc, idx_vec, zero_vec);
+ }
+ if (s >= 3) {
+ bitonic_cas_32(&Vv, &Iv, 4, s, 2, asc, idx_vec, zero_vec);
+ }
+ if (s >= 2) {
+ bitonic_cas_32(&Vv, &Iv, 2, s, 1, asc, idx_vec, zero_vec);
+ }
+ bitonic_cas_32(&Vv, &Iv, 1, s, 0, asc, idx_vec, zero_vec);
+
+ *(HVX_Vector *)(values + v * 128) = Vv;
+ *(HVX_Vector *)(indices + v * 128) = Iv;
+ }
}
}
-// top-k of one row held in VTCM, k <= 64. Keeps a sorted list of the k best, rejects 256-float blocks with one max-reduce.
-// Writes k values and k indices (ties: first seen wins). Slots with no finite value get -INF and index 0.
-static void top_k_scan(const float * vals, uint32_t n, uint32_t k, float * out_v, int32_t * out_i) {
- float best_v[64];
- int32_t best_i[64];
+__attribute__((noinline))
+static void top_k_scan(const float * restrict vals, uint32_t n, uint32_t k, float * restrict out_v, int32_t * restrict out_i) {
+ float best_v[64];
+ int32_t best_i[64];
uint32_t cnt = 0;
float thr = -INFINITY;
- const uint32_t blk = 256;
+ const HVX_Vector v_one = Q6_V_vsplat_R(1);
+ const HVX_Vector v_bit_lut = *(const HVX_Vector *) top_k_bit_lut;
+ const HVX_Vector v_ninf = hvx_vec_splat_f32(-INFINITY);
+
+ const uint32_t blk = 256u;
for (uint32_t off = 0; off < n; off += blk) {
const uint32_t bn = MIN(blk, n - off);
- if (hvx_reduce_max_f32((const uint8_t *) (vals + off), bn) <= thr) {
+ const HVX_Vector v_thr_blk = hvx_vec_splat_f32(thr);
+ HVX_Vector v_any = Q6_V_vzero();
+
+ for (uint32_t vi = 0; vi < bn; vi += 32u) {
+ const uint32_t vn = MIN(32u, bn - vi);
+ HVX_Vector vv = *(const HVX_Vector *)(vals + off + vi);
+ if (vn < 32u) {
+ const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(vn * sizeof(float));
+ vv = Q6_V_vmux_QVV(q_tail, vv, v_ninf);
+ }
+ const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VsfVsf(vv, v_thr_blk);
+ v_any = Q6_V_vor_VV(v_any, Q6_V_vand_QV(q_gt, v_one));
+ }
+ v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 64));
+ v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 32));
+ v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 16));
+ v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 8));
+ v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 4));
+ if (Q6_R_vextract_VR(v_any, 0) == 0) {
continue;
}
- for (uint32_t vi = 0; vi < bn; vi += 32) {
- const uint32_t vn = MIN(32, bn - vi);
- HVX_VectorAlias v_local;
- v_local.v = hvx_vmem(vals + off + vi);
- for (uint32_t i = 0; i < vn; i++) {
- const float v = v_local.fp32[i];
- if (!(v > thr)) continue;
- uint32_t pos = cnt < k ? cnt++ : k - 1;
- while (pos > 0 && best_v[pos - 1] < v) {
- best_v[pos] = best_v[pos - 1];
- best_i[pos] = best_i[pos - 1];
+
+ for (uint32_t vi = 0; vi < bn; vi += 32u) {
+ const uint32_t vn = MIN(32u, bn - vi);
+ HVX_Vector vv = *(const HVX_Vector *)(vals + off + vi);
+ if (vn < 32u) {
+ const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(vn * sizeof(float));
+ vv = Q6_V_vmux_QVV(q_tail, vv, v_ninf);
+ }
+ const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VsfVsf(vv, hvx_vec_splat_f32(thr));
+ uint32_t mask = hvx_pred_i32_to_bits(q_gt, v_bit_lut);
+ while (mask != 0u) {
+ const uint32_t bit = (uint32_t) __builtin_ctz(mask);
+ mask &= mask - 1u;
+ union { int32_t i; float f; } u = { .i = Q6_R_vextract_VR(vv, (int) (bit * 4u)) };
+ const float v = u.f;
+ if (!(v > thr)) {
+ continue;
+ }
+ uint32_t pos = cnt < k ? cnt++ : k - 1u;
+ while (pos > 0u && best_v[pos - 1u] < v) {
+ best_v[pos] = best_v[pos - 1u];
+ best_i[pos] = best_i[pos - 1u];
pos--;
}
best_v[pos] = v;
- best_i[pos] = (int32_t) (off + vi + i);
- if (cnt == k) thr = best_v[k - 1];
+ best_i[pos] = (int32_t) (off + vi + bit);
+ if (cnt == k) {
+ thr = best_v[k - 1u];
+ }
}
}
}
- // fewer than k values above -INF: take -INF or NaN elements, then pad with index 0
- for (uint32_t off = 0; off < n && cnt < k; off += 32) {
- const uint32_t vn = MIN(32, n - off);
- HVX_VectorAlias v_local;
- v_local.v = hvx_vmem(vals + off);
- for (uint32_t j = 0; j < vn && cnt < k; j++) {
- if (!(v_local.fp32[j] > -INFINITY)) {
- best_v[cnt] = -INFINITY;
- best_i[cnt] = (int32_t) (off + j);
- cnt++;
+ if (cnt < k) {
+ for (uint32_t off = 0; off < n && cnt < k; off += 32u) {
+ const uint32_t vn = MIN(32u, n - off);
+ const HVX_Vector vv = *(const HVX_Vector *)(vals + off);
+ for (uint32_t j = 0; j < vn && cnt < k; j++) {
+ union { int32_t i; float f; } u = { .i = Q6_R_vextract_VR(vv, (int) (j * 4u)) };
+ if (u.f == -INFINITY) {
+ best_v[cnt] = -INFINITY;
+ best_i[cnt] = (int32_t) (off + j);
+ cnt++;
+ }
+ }
+ }
+ for (uint32_t off = 0; off < n && cnt < k; off += 32u) {
+ const uint32_t vn = MIN(32u, n - off);
+ const HVX_Vector vv = *(const HVX_Vector *)(vals + off);
+ for (uint32_t j = 0; j < vn && cnt < k; j++) {
+ union { int32_t i; float f; } u = { .i = Q6_R_vextract_VR(vv, (int) (j * 4u)) };
+ if (isnan(u.f)) {
+ best_v[cnt] = u.f;
+ best_i[cnt] = (int32_t) (off + j);
+ cnt++;
+ }
}
}
}
@@ -368,41 +613,300 @@ static void top_k_scan(const float * vals, uint32_t n, uint32_t k, float * out_v
}
for (uint32_t j = 0; j < k; j++) {
- out_v[j] = best_v[j];
+ if (out_v) {
+ out_v[j] = best_v[j];
+ }
out_i[j] = best_i[j];
}
}
-__attribute__((always_inline))
-static inline void sort32_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
+// O(N) HVX radix-narrowed top-k selection in-place over VTCM float buffer.
+__attribute__((noinline))
+static void top_k_select_hvx(
+ float * restrict buf,
+ int32_t * restrict out_idx,
+ float * restrict out_val,
+ int32_t * restrict cand_scratch,
+ uint32_t n,
+ uint32_t k,
+ uint32_t idx_base
+) {
+ const int32_t KEY_PAD = (int32_t) 0x80000000u;
+ const int32_t KEY_NINF = (int32_t) 0x807fffffu;
+ const int32_t KEY_MAX = (int32_t) 0x7fffffffu;
+
+ HVX_Vector * restrict vbuf = (HVX_Vector *) buf;
+ const uint32_t n_full = n >> 5;
+ const uint32_t rem = n & 31u;
+ const uint32_t n_vec = (n + 31u) >> 5;
+
+ const HVX_Vector v_pad = Q6_V_vsplat_R(KEY_PAD);
+ const HVX_Vector v_ninf = Q6_V_vsplat_R(KEY_NINF);
+ const HVX_Vector v_max = Q6_V_vsplat_R(KEY_MAX);
+ const HVX_Vector v_one = Q6_V_vsplat_R(1);
+
+ HVX_Vector v_min_all = v_max;
+ HVX_Vector v_max_all = v_pad;
+ HVX_Vector v_min_fin = v_max;
+ HVX_Vector v_cnt_fin = Q6_V_vzero();
+
+ for (uint32_t v = 0; v < n_full; v++) {
+ const HVX_Vector vk = float_to_ord_key_vec(vbuf[v]);
+ vbuf[v] = vk;
+ v_min_all = Q6_Vw_vmin_VwVw(v_min_all, vk);
+ v_max_all = Q6_Vw_vmax_VwVw(v_max_all, vk);
+ const HVX_VectorPred q_fin = Q6_Q_vcmp_gt_VwVw(vk, v_ninf);
+ v_cnt_fin = Q6_Vw_vadd_VwVw(v_cnt_fin, Q6_V_vand_QV(q_fin, v_one));
+ v_min_fin = Q6_Vw_vmin_VwVw(v_min_fin, Q6_V_vmux_QVV(q_fin, vk, v_max));
+ }
+ if (rem > 0u) {
+ const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(rem * sizeof(int32_t));
+ const HVX_Vector vk_raw = float_to_ord_key_vec(vbuf[n_full]);
+ const HVX_Vector vk = Q6_V_vmux_QVV(q_tail, vk_raw, v_pad);
+ vbuf[n_full] = vk;
+ v_min_all = Q6_Vw_vmin_VwVw(v_min_all, Q6_V_vmux_QVV(q_tail, vk_raw, v_max));
+ v_max_all = Q6_Vw_vmax_VwVw(v_max_all, vk);
+ const HVX_VectorPred q_fin = Q6_Q_vcmp_gt_VwVw(vk, v_ninf);
+ v_cnt_fin = Q6_Vw_vadd_VwVw(v_cnt_fin, Q6_V_vand_QV(q_fin, v_one));
+ v_min_fin = Q6_Vw_vmin_VwVw(v_min_fin, Q6_V_vmux_QVV(q_fin, vk, v_max));
+ }
+
+ #pragma clang loop unroll(full)
+ for (int shift = 64; shift >= 4; shift >>= 1) {
+ v_min_all = Q6_Vw_vmin_VwVw(v_min_all, Q6_V_vror_VR(v_min_all, shift));
+ v_max_all = Q6_Vw_vmax_VwVw(v_max_all, Q6_V_vror_VR(v_max_all, shift));
+ v_min_fin = Q6_Vw_vmin_VwVw(v_min_fin, Q6_V_vror_VR(v_min_fin, shift));
+ v_cnt_fin = Q6_Vw_vadd_VwVw(v_cnt_fin, Q6_V_vror_VR(v_cnt_fin, shift));
+ }
+
+ const int32_t min_key = (int32_t) Q6_R_vextract_VR(v_min_all, 0);
+ const int32_t max_key = (int32_t) Q6_R_vextract_VR(v_max_all, 0);
+ const int32_t min_fin_key = (int32_t) Q6_R_vextract_VR(v_min_fin, 0);
+ const uint32_t n_gt_ninf = (uint32_t) Q6_R_vextract_VR(v_cnt_fin, 0);
+
+ if (min_key == max_key) {
+ init_indices_ramp(out_idx, k, idx_base);
+ if (out_val) {
+ const float fv = ord_key_to_float(max_key);
+ for (uint32_t j = 0; j < k; j++) {
+ out_val[j] = fv;
+ }
+ }
+ return;
+ }
+
+ int32_t lo = min_key - 1;
+ uint32_t cnt_lo = n;
+ int32_t hi = max_key;
+ uint32_t cnt_hi = 0;
+
+ if (n_gt_ninf > k) {
+ lo = min_fin_key - 1;
+ cnt_lo = n_gt_ninf;
+ } else {
+ hi = KEY_NINF;
+ cnt_hi = n_gt_ninf;
+ if (min_key >= KEY_NINF) {
+ lo = KEY_NINF - 1;
+ }
+ }
+
+ while ((uint32_t) hi - (uint32_t) lo > 1u && (cnt_lo - cnt_hi) > 64u && cnt_hi < k) {
+ const uint32_t span = (uint32_t) hi - (uint32_t) lo;
+ int32_t p[7];
+ #pragma clang loop unroll(full)
+ for (int m = 0; m < 7; m++) {
+ uint32_t step = (uint32_t) (((uint64_t) span * (uint32_t) (m + 1)) >> 3);
+ if (step == 0u) {
+ step = 1u;
+ } else if (step >= span) {
+ step = span - 1u;
+ }
+ p[m] = (int32_t) ((uint32_t) lo + step);
+ }
+
+ const HVX_Vector vp0 = Q6_V_vsplat_R(p[0]);
+ const HVX_Vector vp1 = Q6_V_vsplat_R(p[1]);
+ const HVX_Vector vp2 = Q6_V_vsplat_R(p[2]);
+ const HVX_Vector vp3 = Q6_V_vsplat_R(p[3]);
+ const HVX_Vector vp4 = Q6_V_vsplat_R(p[4]);
+ const HVX_Vector vp5 = Q6_V_vsplat_R(p[5]);
+ const HVX_Vector vp6 = Q6_V_vsplat_R(p[6]);
+
+ HVX_Vector vc0 = Q6_V_vzero();
+ HVX_Vector vc1 = Q6_V_vzero();
+ HVX_Vector vc2 = Q6_V_vzero();
+ HVX_Vector vc3 = Q6_V_vzero();
+ HVX_Vector vc4 = Q6_V_vzero();
+ HVX_Vector vc5 = Q6_V_vzero();
+ HVX_Vector vc6 = Q6_V_vzero();
+
+ for (uint32_t v = 0; v < n_vec; v++) {
+ const HVX_Vector vk = vbuf[v];
+ vc0 = Q6_Vw_vadd_VwVw(vc0, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp0), v_one));
+ vc1 = Q6_Vw_vadd_VwVw(vc1, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp1), v_one));
+ vc2 = Q6_Vw_vadd_VwVw(vc2, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp2), v_one));
+ vc3 = Q6_Vw_vadd_VwVw(vc3, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp3), v_one));
+ vc4 = Q6_Vw_vadd_VwVw(vc4, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp4), v_one));
+ vc5 = Q6_Vw_vadd_VwVw(vc5, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp5), v_one));
+ vc6 = Q6_Vw_vadd_VwVw(vc6, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp6), v_one));
+ }
+
+ #pragma clang loop unroll(full)
+ for (int shift = 64; shift >= 4; shift >>= 1) {
+ vc0 = Q6_Vw_vadd_VwVw(vc0, Q6_V_vror_VR(vc0, shift));
+ vc1 = Q6_Vw_vadd_VwVw(vc1, Q6_V_vror_VR(vc1, shift));
+ vc2 = Q6_Vw_vadd_VwVw(vc2, Q6_V_vror_VR(vc2, shift));
+ vc3 = Q6_Vw_vadd_VwVw(vc3, Q6_V_vror_VR(vc3, shift));
+ vc4 = Q6_Vw_vadd_VwVw(vc4, Q6_V_vror_VR(vc4, shift));
+ vc5 = Q6_Vw_vadd_VwVw(vc5, Q6_V_vror_VR(vc5, shift));
+ vc6 = Q6_Vw_vadd_VwVw(vc6, Q6_V_vror_VR(vc6, shift));
+ }
+
+ const uint32_t c[7] = {
+ (uint32_t) Q6_R_vextract_VR(vc0, 0),
+ (uint32_t) Q6_R_vextract_VR(vc1, 0),
+ (uint32_t) Q6_R_vextract_VR(vc2, 0),
+ (uint32_t) Q6_R_vextract_VR(vc3, 0),
+ (uint32_t) Q6_R_vextract_VR(vc4, 0),
+ (uint32_t) Q6_R_vextract_VR(vc5, 0),
+ (uint32_t) Q6_R_vextract_VR(vc6, 0),
+ };
+
+ #pragma clang loop unroll(full)
+ for (int m = 0; m < 7; m++) {
+ if (c[m] >= k) {
+ lo = p[m];
+ cnt_lo = c[m];
+ } else if (p[m] < hi) {
+ hi = p[m];
+ cnt_hi = c[m];
+ }
+ }
+ }
+
+ const HVX_Vector v_bit_lut = *(const HVX_Vector *) top_k_bit_lut;
+ const HVX_Vector v_hi = Q6_V_vsplat_R(hi);
+ uint32_t out_cnt = 0;
+ uint32_t rem_k = k - cnt_hi;
+
+ if (rem_k == 0u) {
+ for (uint32_t v = 0; v < n_vec && out_cnt < k; v++) {
+ const HVX_Vector vk = vbuf[v];
+ uint32_t mask = hvx_pred_i32_to_bits(Q6_Q_vcmp_gt_VwVw(vk, v_hi), v_bit_lut);
+ const uint32_t base = idx_base + (v << 5);
+ while (mask != 0u && out_cnt < k) {
+ const uint32_t bit = (uint32_t) __builtin_ctz(mask);
+ mask &= mask - 1u;
+ if (out_val) {
+ out_val[out_cnt] = ord_key_to_float((int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u)));
+ }
+ out_idx[out_cnt] = (int32_t) (base + bit);
+ out_cnt++;
+ }
+ }
+ return;
+ }
+
+ if ((uint32_t) hi - (uint32_t) lo == 1u) {
+ const float hi_f = out_val ? ord_key_to_float(hi) : 0.0f;
+ for (uint32_t v = 0; v < n_vec && out_cnt < k; v++) {
+ const HVX_Vector vk = vbuf[v];
+ const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VwVw(vk, v_hi);
+ const HVX_VectorPred q_eq = Q6_Q_vcmp_eq_VwVw(vk, v_hi);
+ uint32_t mask_gt = hvx_pred_i32_to_bits(q_gt, v_bit_lut);
+ uint32_t mask_eq = (rem_k > 0u) ? hvx_pred_i32_to_bits(q_eq, v_bit_lut) : 0u;
+ const uint32_t base = idx_base + (v << 5);
+ while (mask_gt != 0u) {
+ const uint32_t bit = (uint32_t) __builtin_ctz(mask_gt);
+ mask_gt &= mask_gt - 1u;
+ if (out_val) {
+ out_val[out_cnt] = ord_key_to_float((int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u)));
+ }
+ out_idx[out_cnt] = (int32_t) (base + bit);
+ out_cnt++;
+ }
+ while (mask_eq != 0u && rem_k > 0u) {
+ const uint32_t bit = (uint32_t) __builtin_ctz(mask_eq);
+ mask_eq &= mask_eq - 1u;
+ if (out_val) {
+ out_val[out_cnt] = hi_f;
+ }
+ out_idx[out_cnt] = (int32_t) (base + bit);
+ out_cnt++;
+ rem_k--;
+ }
+ }
+ return;
+ }
+
+ const HVX_Vector v_lo = Q6_V_vsplat_R(lo);
+ int32_t * restrict cand_k = cand_scratch;
+ int32_t * restrict cand_i = cand_scratch + 64;
+ uint32_t m_cnt = 0;
+
+ for (uint32_t v = 0; v < n_vec; v++) {
+ const HVX_Vector vk = vbuf[v];
+ const HVX_VectorPred q_gt_hi = Q6_Q_vcmp_gt_VwVw(vk, v_hi);
+ const HVX_VectorPred q_gt_lo = Q6_Q_vcmp_gt_VwVw(vk, v_lo);
+ const HVX_VectorPred q_mid = Q6_Q_and_QQn(q_gt_lo, q_gt_hi);
+ uint32_t mask_gt = hvx_pred_i32_to_bits(q_gt_hi, v_bit_lut);
+ uint32_t mask_mid = hvx_pred_i32_to_bits(q_mid, v_bit_lut);
+ const uint32_t base = idx_base + (v << 5);
+ while (mask_gt != 0u) {
+ const uint32_t bit = (uint32_t) __builtin_ctz(mask_gt);
+ mask_gt &= mask_gt - 1u;
+ if (out_val) {
+ out_val[out_cnt] = ord_key_to_float((int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u)));
+ }
+ out_idx[out_cnt] = (int32_t) (base + bit);
+ out_cnt++;
+ }
+ while (mask_mid != 0u && m_cnt < 64u) {
+ const uint32_t bit = (uint32_t) __builtin_ctz(mask_mid);
+ mask_mid &= mask_mid - 1u;
+ cand_k[m_cnt] = (int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u));
+ cand_i[m_cnt] = (int32_t) (base + bit);
+ m_cnt++;
+ }
+ }
+
+ for (uint32_t j = m_cnt; j < 64u; j++) {
+ cand_k[j] = KEY_PAD;
+ cand_i[j] = 0;
+ }
+
+ sort64_i32_desc(cand_k, cand_i);
+
+ for (uint32_t j = 0; j < rem_k && out_cnt < k; j++) {
+ if (out_val) {
+ out_val[out_cnt] = ord_key_to_float(cand_k[j]);
+ }
+ out_idx[out_cnt] = cand_i[j];
+ out_cnt++;
+ }
+}
+
+__attribute__((noinline))
+static void sort32_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
bitonic_sort_generic_hvx(values, indices, 1, order == GGML_SORT_ORDER_ASC);
}
-__attribute__((always_inline))
-static inline void sort64_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
+__attribute__((noinline))
+static void sort64_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
bitonic_sort_generic_hvx(values, indices, 2, order == GGML_SORT_ORDER_ASC);
}
-__attribute__((always_inline))
-static inline void sort128_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
+__attribute__((noinline))
+static void sort128_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
bitonic_sort_generic_hvx(values, indices, 4, order == GGML_SORT_ORDER_ASC);
}
-__attribute__((always_inline))
-static inline void sort256_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
+__attribute__((noinline))
+static void sort256_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
bitonic_sort_generic_hvx(values, indices, 8, order == GGML_SORT_ORDER_ASC);
}
-__attribute__((always_inline))
-static inline void sort512_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
- bitonic_sort_generic_hvx(values, indices, 16, order == GGML_SORT_ORDER_ASC);
-}
-
-__attribute__((always_inline))
-static inline void sort1024_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) {
- bitonic_sort_generic_hvx(values, indices, 32, order == GGML_SORT_ORDER_ASC);
-}
-
static void merge_runs(
const float * restrict in_val0, const int32_t * restrict in_idx0, uint32_t n0,
const float * restrict in_val1, const int32_t * restrict in_idx1, uint32_t n1,
@@ -456,14 +960,33 @@ static void merge_runs(
}
}
+// Expand fp16 values in-place to fp32 backwards from the last vector so lower fp16 vectors are read before overwrite.
+__attribute__((noinline))
+static void sort_unpack_f16_to_f32_inplace(float * restrict values, uint32_t count) {
+ const HVX_Vector * vsrc = (const HVX_Vector *) values;
+ HVX_Vector * vdst = (HVX_Vector *) values;
+ const uint32_t n_vec_f32 = (count + 31) / 32;
+ const uint32_t n_vec_f16 = (n_vec_f32 + 1) / 2;
+
+ for (int32_t v = (int32_t) n_vec_f16 - 1; v >= 0; v--) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[v]);
+ if ((uint32_t) (2 * v + 1) < n_vec_f32) {
+ vdst[2 * v + 1] = Q6_V_hi_W(p);
+ }
+ vdst[2 * v] = Q6_V_lo_W(p);
+ }
+}
+
struct htp_sort_chunk_ctx {
struct htp_ops_context * octx;
const struct htp_sort_kernel_params * kparams;
uint8_t * phase1_base;
size_t phase1_slot_size;
+ size_t off_cand;
float * merge_values;
int32_t * merge_indices;
uint32_t real_count[HTP_OP_MAX_NHVX];
+ uint32_t cand_count[HTP_OP_MAX_NHVX];
};
static void htp_sort_chunk_job(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
@@ -488,63 +1011,55 @@ static void htp_sort_chunk_job(const htp_thread_t * th, unsigned int n, unsigned
int32_t * merge_indices = cctx->merge_indices;
struct htp_thread_trace * tr = th->trace;
- const dma_addr_t src_addr = src0->data + (size_t) chunk_base * sizeof(float);
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const size_t src_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float);
+ const dma_addr_t src_addr = src0->data + (size_t) chunk_base * src_elem_size;
if (kparams->is_top_k) {
- uint32_t k = dst->ne[0];
- uint32_t local_k = MIN(k, chunk_elems);
+ const uint32_t k = dst->ne[0];
+ const uint32_t local_k = MIN(k, chunk_elems);
+ const uint32_t take_k = MIN(local_k, real_count);
+ cctx->cand_count[i] = take_k;
- if (real_count == 0) {
- for (uint32_t j = 0; j < local_k; j++) {
- merge_values[i * local_k + j] = -INFINITY;
- merge_indices[i * local_k + j] = 0;
- }
+ if (take_k == 0u) {
return;
}
- if (local_k == 1 && ne00 >= 128*1024) {
- dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float));
+ float * out_val = &merge_values[i * local_k];
+ int32_t * out_idx = &merge_indices[i * local_k];
+ int32_t * cand_scratch = (int32_t *) (spad + cctx->off_cand);
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- float max_value;
- uint32_t max_index = top_k_max_value_index(values_buf, real_count, &max_value);
- merge_values[i] = max_value;
- merge_indices[i] = (int32_t) (max_index + chunk_base);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- return;
- }
-
- if (local_k > 1 && local_k <= 64 && chunk_elems > 1024) {
- dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float));
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- top_k_scan(values_buf, real_count, local_k, &merge_values[i * local_k], &merge_indices[i * local_k]);
- for (uint32_t j = 0; j < local_k; j++) {
- merge_indices[i * local_k + j] += (int32_t) chunk_base;
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- return;
- }
-
- dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float));
+ dma_sync_read(th->dma_q, values_buf, src_addr, real_count * src_elem_size);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- if (chunk_elems > real_count) {
- hvx_splat_f32_u((uint8_t *)(values_buf + real_count), -INFINITY, chunk_elems - real_count);
+ if (src0_f16) {
+ sort_unpack_f16_to_f32_inplace(values_buf, real_count);
}
- bitonic_sort_vtcm_desc((uint8_t *) values_buf, (uint8_t *) indices_buf, chunk_elems / 32, true);
-
- for (uint32_t j = 0; j < local_k; j++) {
- merge_values[i * local_k + j] = values_buf[j];
- merge_indices[i * local_k + j] = indices_buf[j] + (int32_t) chunk_base;
+ if (take_k == real_count) {
+ for (uint32_t j = 0; j < take_k; j++) {
+ out_val[j] = values_buf[j];
+ out_idx[j] = (int32_t) (chunk_base + j);
+ }
+ } else if (take_k == 1u) {
+ out_idx[0] = top_k_argmax_hvx(values_buf, real_count, chunk_base, &out_val[0]);
+ } else if (take_k <= 64u && chunk_elems > 1024u) {
+ top_k_scan(values_buf, real_count, take_k, out_val, out_idx);
+ for (uint32_t j = 0; j < take_k; j++) {
+ out_idx[j] += (int32_t) chunk_base;
+ }
+ } else {
+ top_k_select_hvx(values_buf, out_idx, out_val, cand_scratch, real_count, take_k, chunk_base);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
} else {
if (real_count > 0) {
- dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float));
+ dma_sync_read(th->dma_q, values_buf, src_addr, real_count * src_elem_size);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
+ if (src0_f16) {
+ sort_unpack_f16_to_f32_inplace(values_buf, real_count);
+ }
init_indices_ramp(indices_buf, real_count, chunk_base);
if (kparams->order == GGML_SORT_ORDER_ASC) {
@@ -630,6 +1145,10 @@ struct htp_sort_multi_row_ctx {
const struct htp_sort_kernel_params * kparams;
uint8_t * phase1_base;
size_t phase1_slot_size;
+ size_t row_values_size;
+ size_t row_indices_size;
+ size_t off_cand;
+ uint32_t batch_rows;
uint32_t row_start;
uint32_t row_end;
uint32_t nrows_per_hvx;
@@ -673,49 +1192,50 @@ static inline size_t coord_offset(struct htp_tensor_row_coord c, size_t nb1, siz
}
static inline void compute_row_sort(
- float * cur_values,
- int32_t * cur_indices,
- uint32_t ne00,
- uint32_t chunk_elems,
- bool is_top_k,
+ float * restrict cur_values,
+ int32_t * restrict cur_indices,
+ int32_t * restrict cand_scratch,
+ uint32_t ne00,
+ uint32_t chunk_elems,
+ bool src0_f16,
+ bool is_top_k,
enum ggml_sort_order order,
- uint32_t k
+ uint32_t k
) {
+ if (src0_f16) {
+ sort_unpack_f16_to_f32_inplace(cur_values, ne00);
+ }
if (is_top_k) {
- if (k > 1 && k <= 64 && ne00 > 1024) {
- float out_v[64];
- top_k_scan(cur_values, ne00, k, out_v, cur_indices);
- } else if (ne00 == 32 || ne00 == 64 || ne00 == 128 || ne00 == 256 || ne00 == 512 || ne00 == 1024) {
- switch (ne00) {
- case 32: sort32_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break;
- case 64: sort64_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break;
- case 128: sort128_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break;
- case 256: sort256_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break;
- case 512: sort512_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break;
- case 1024: sort1024_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break;
+ if (k == 1u) {
+ cur_indices[0] = top_k_argmax_hvx(cur_values, ne00, 0, NULL);
+ } else if (ne00 <= 256u) {
+ switch (chunk_elems) {
+ case 32: sort32_top_k_hvx(cur_values, cur_indices, ne00, k); break;
+ case 64: sort64_top_k_hvx(cur_values, cur_indices, ne00, k); break;
+ case 128: sort128_top_k_hvx(cur_values, cur_indices, ne00, k); break;
+ default: sort256_top_k_hvx(cur_values, cur_indices, ne00, k); break;
}
+ } else if (k <= 64u && ne00 > 1024u) {
+ top_k_scan(cur_values, ne00, k, NULL, cur_indices);
} else {
- if (chunk_elems > ne00) {
- hvx_splat_f32_u((uint8_t *)(cur_values + ne00), -INFINITY, chunk_elems - ne00);
- }
- bitonic_sort_vtcm_desc((uint8_t *) cur_values, (uint8_t *) cur_indices, chunk_elems / 32, true);
+ top_k_select_hvx(cur_values, cur_indices, NULL, cand_scratch, ne00, k, 0);
}
} else {
- if (ne00 == 32 || ne00 == 64 || ne00 == 128 || ne00 == 256 || ne00 == 512 || ne00 == 1024) {
+ if (ne00 == 32u || ne00 == 64u || ne00 == 128u || ne00 == 256u) {
switch (ne00) {
- case 32: sort32_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
- case 64: sort64_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
- case 128: sort128_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
- case 256: sort256_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
- case 512: sort512_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
- case 1024: sort1024_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
+ case 32: sort32_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
+ case 64: sort64_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
+ case 128: sort128_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
+ case 256: sort256_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break;
}
+ } else if (ne00 == 512u || ne00 == 1024u) {
+ bitonic_sort_vtcm((uint8_t *) cur_values, (uint8_t *) cur_indices, ne00 >> 5, true, order == GGML_SORT_ORDER_ASC);
} else {
init_indices_ramp(cur_indices, ne00, 0);
if (order == GGML_SORT_ORDER_ASC) {
- quicksort_values_indices_asc(cur_values, cur_indices, 0, ne00 - 1);
+ quicksort_values_indices_asc(cur_values, cur_indices, 0, (int) ne00 - 1);
} else {
- quicksort_values_indices_desc(cur_values, cur_indices, 0, ne00 - 1);
+ quicksort_values_indices_desc(cur_values, cur_indices, 0, (int) ne00 - 1);
}
}
}
@@ -745,123 +1265,209 @@ static void htp_sort_multi_row_job(const htp_thread_t * th, unsigned int n, unsi
uint32_t r_start = row_start + ith * mctx->nrows_per_hvx;
uint32_t r_end = MIN(r_start + mctx->nrows_per_hvx, row_end);
- if (r_start >= r_end) return;
+ if (r_start >= r_end) {
+ return;
+ }
+
+ const size_t slot_size = mctx->phase1_slot_size;
+ const size_t row_values_size = mctx->row_values_size;
+ const size_t row_indices_size = mctx->row_indices_size;
+ const size_t off_cand = mctx->off_cand;
+ const uint32_t batch_rows = mctx->batch_rows;
+ const size_t values_area_size = row_values_size * (size_t) batch_rows;
- size_t slot_size = mctx->phase1_slot_size;
- size_t spad_offset = ith * slot_size * (size_t) kparams->n_slots;
+ const size_t spad_offset = ith * slot_size * (size_t) kparams->n_slots;
uint8_t * hvx_spad = mctx->phase1_base + spad_offset;
- uint32_t chunk_elems = (uint32_t) kparams->chunk_elems;
- float * values_buf = (float *) hvx_spad;
- int32_t * indices_buf = (int32_t *) (hvx_spad + chunk_elems * sizeof(float));
-
+ const uint32_t chunk_elems = (uint32_t) kparams->chunk_elems;
dma_queue * dma_q = th->dma_q;
struct htp_thread_trace * tr = th->trace;
- bool is_top_k = kparams->is_top_k != 0;
- uint32_t k = dst->ne[0];
- enum ggml_sort_order order = (enum ggml_sort_order) kparams->order;
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const bool is_top_k = kparams->is_top_k != 0;
+ const uint32_t k = dst->ne[0];
+ const enum ggml_sort_order order = (enum ggml_sort_order) kparams->order;
- const uint32_t src_bytes = ne00 * sizeof(float);
+ const uint32_t src_bytes = ne00 * (src0_f16 ? sizeof(__fp16) : sizeof(float));
const uint32_t dst_bytes = (is_top_k ? k : ne00) * sizeof(int32_t);
if (kparams->n_slots == 2) {
- struct htp_tensor_row_coord prime_coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02);
- for (uint32_t r = r_start, spad_idx = 0; r < r_end && spad_idx < 2; r++, spad_idx++) {
- uint8_t * cur_spad = hvx_spad + spad_idx * slot_size;
- float * cur_values = (float *) cur_spad;
- int32_t * cur_indices = (int32_t *) (cur_spad + chunk_elems * sizeof(float));
-
- dma_addr_t dst_addr = dst->data + coord_offset(prime_coord, nb1, nb2, nb3);
- dma_addr_t src_addr = src0->data + coord_offset(prime_coord, nb01, nb02, nb03);
-
- // Dummy dst writeback to establish queue ordering
- dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices),
- dst_bytes, dst_bytes, dst_bytes, 0);
-
- // Prefetch input row
- dma_queue_push(dma_q, dma_make_data(cur_values, src_addr),
- src_bytes, src_bytes, src_bytes, 1);
-
- step_row_coord(&prime_coord, ne01, ne02);
+ struct htp_tensor_row_coord next_coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02);
+ struct htp_tensor_row_coord slot_coord[2];
+ uint32_t slot_cnt[2] = { 0, 0 };
+ uint32_t slot_r[2] = { 0, 0 };
+ uint32_t next_r = r_start;
+
+ for (uint32_t s = 0; s < 2 && next_r < r_end; s++) {
+ const uint32_t b_cnt = MIN(batch_rows, MIN(r_end - next_r, ne01 - next_coord.i01));
+ uint8_t * cur_spad = hvx_spad + s * slot_size;
+ float * cur_values_base = (float *) cur_spad;
+ int32_t * cur_indices_base = (int32_t *) (cur_spad + values_area_size);
+
+ const dma_addr_t dst_addr = dst->data + coord_offset(next_coord, nb1, nb2, nb3);
+ const dma_addr_t src_addr = src0->data + coord_offset(next_coord, nb01, nb02, nb03);
+
+ dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices_base),
+ nb1, row_indices_size, dst_bytes, 0);
+ dma_queue_push(dma_q, dma_make_data(cur_values_base, src_addr),
+ row_values_size, nb01, src_bytes, b_cnt);
+
+ slot_cnt[s] = b_cnt;
+ slot_r[s] = next_r;
+ slot_coord[s] = next_coord;
+
+ next_r += b_cnt;
+ for (uint32_t b = 0; b < b_cnt; b++) {
+ step_row_coord(&next_coord, ne01, ne02);
+ }
}
- struct htp_tensor_row_coord dst_coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02);
- struct htp_tensor_row_coord next_src_coord = init_row_coord(r_start + 2, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02);
-
- for (uint32_t r = r_start; r < r_end; r++) {
- uint32_t cur_slot = (r - r_start) & 1;
- uint8_t * cur_spad = hvx_spad + cur_slot * slot_size;
- float * cur_values = (float *) cur_spad;
- int32_t * cur_indices = (int32_t *) (cur_spad + chunk_elems * sizeof(float));
+ uint32_t cur_slot = 0;
+ while (slot_cnt[cur_slot] > 0) {
+ const uint32_t b_cnt = slot_cnt[cur_slot];
+ const uint32_t base_r = slot_r[cur_slot];
+ uint8_t * cur_spad = hvx_spad + cur_slot * slot_size;
+ float * cur_values_base = (float *) cur_spad;
+ int32_t * cur_indices_base = (int32_t *) (cur_spad + values_area_size);
+ int32_t * cand_scratch = (int32_t *) (cur_spad + off_cand);
- // Wait for previous writeback of this slot to complete
dma_queue_pop(dma_q);
-
- // Wait for input row DMA read into this slot to complete
dma_queue_pop(dma_q);
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
- compute_row_sort(cur_values, cur_indices, ne00, chunk_elems, is_top_k, order, k);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
-
- // Push writeback of current slot
- dma_addr_t dst_addr = dst->data + coord_offset(dst_coord, nb1, nb2, nb3);
- dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices),
- dst_bytes, dst_bytes, dst_bytes, 1);
- step_row_coord(&dst_coord, ne01, ne02);
-
- // Prefetch next row into this slot
- const uint32_t next_row = r + 2;
- if (next_row < r_end) {
- dma_addr_t next_src_addr = src0->data + coord_offset(next_src_coord, nb01, nb02, nb03);
- dma_queue_push(dma_q, dma_make_data(cur_values, next_src_addr),
- src_bytes, src_bytes, src_bytes, 1);
- step_row_coord(&next_src_coord, ne01, ne02);
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) base_r);
+ for (uint32_t b = 0; b < b_cnt; b++) {
+ float * row_val = (float *) (cur_spad + (size_t) b * row_values_size);
+ int32_t * row_idx = (int32_t *) (cur_spad + values_area_size + (size_t) b * row_indices_size);
+ compute_row_sort(row_val, row_idx, cand_scratch, ne00, chunk_elems, src0_f16, is_top_k, order, k);
}
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) base_r);
+
+ const dma_addr_t dst_addr = dst->data + coord_offset(slot_coord[cur_slot], nb1, nb2, nb3);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices_base),
+ nb1, row_indices_size, dst_bytes, b_cnt);
+
+ if (next_r < r_end) {
+ const uint32_t next_b = MIN(batch_rows, MIN(r_end - next_r, ne01 - next_coord.i01));
+ const dma_addr_t next_src_addr = src0->data + coord_offset(next_coord, nb01, nb02, nb03);
+ dma_queue_push(dma_q, dma_make_data(cur_values_base, next_src_addr),
+ row_values_size, nb01, src_bytes, next_b);
+ slot_cnt[cur_slot] = next_b;
+ slot_r[cur_slot] = next_r;
+ slot_coord[cur_slot] = next_coord;
+
+ next_r += next_b;
+ for (uint32_t b = 0; b < next_b; b++) {
+ step_row_coord(&next_coord, ne01, ne02);
+ }
+ } else {
+ slot_cnt[cur_slot] = 0;
+ }
+
+ cur_slot ^= 1u;
}
dma_queue_flush(dma_q);
} else {
struct htp_tensor_row_coord coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02);
- for (uint32_t r = r_start; r < r_end; r++) {
- dma_addr_t src_addr = src0->data + coord_offset(coord, nb01, nb02, nb03);
- dma_addr_t dst_addr = dst->data + coord_offset(coord, nb1, nb2, nb3);
+ int32_t * cand_scratch = (int32_t *) (hvx_spad + off_cand);
+ for (uint32_t r = r_start; r < r_end; ) {
+ const uint32_t b_cnt = MIN(batch_rows, MIN(r_end - r, ne01 - coord.i01));
+ const dma_addr_t src_addr = src0->data + coord_offset(coord, nb01, nb02, nb03);
+ const dma_addr_t dst_addr = dst->data + coord_offset(coord, nb1, nb2, nb3);
- dma_sync_read(dma_q, values_buf, src_addr, src_bytes);
+ dma_queue_push(dma_q, dma_make_data(hvx_spad, src_addr),
+ row_values_size, nb01, src_bytes, b_cnt);
+ dma_queue_flush(dma_q);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
- compute_row_sort(values_buf, indices_buf, ne00, chunk_elems, is_top_k, order, k);
+ for (uint32_t b = 0; b < b_cnt; b++) {
+ float * row_val = (float *) (hvx_spad + (size_t) b * row_values_size);
+ int32_t * row_idx = (int32_t *) (hvx_spad + values_area_size + (size_t) b * row_indices_size);
+ compute_row_sort(row_val, row_idx, cand_scratch, ne00, chunk_elems, src0_f16, is_top_k, order, k);
+ }
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
- dma_sync_write(dma_q, dst_addr, indices_buf, dst_bytes);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, hvx_spad + values_area_size),
+ nb1, row_indices_size, dst_bytes, b_cnt);
+ dma_queue_flush(dma_q);
+
+ r += b_cnt;
+ for (uint32_t b = 0; b < b_cnt; b++) {
+ step_row_coord(&coord, ne01, ne02);
+ }
+ }
+ }
+}
+
+struct htp_top_k_identity_ctx {
+ struct htp_ops_context * octx;
+ const struct htp_sort_kernel_params * kparams;
+ uint8_t * phase1_base;
+ size_t row_indices_size;
+ uint32_t batch_rows;
+ uint32_t row_start;
+ uint32_t row_end;
+ uint32_t nrows_per_hvx;
+};
+
+static void htp_top_k_identity_job(const htp_thread_t * th, unsigned int n, unsigned int ith, void * data) {
+ const struct htp_top_k_identity_ctx * ictx = (const struct htp_top_k_identity_ctx *) data;
+ const struct htp_ops_context * octx = ictx->octx;
+ const struct htp_sort_kernel_params * kparams = ictx->kparams;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
+
+ const uint32_t ne01 = src0->ne[1];
+ const uint32_t ne02 = src0->ne[2];
+ const uint32_t nb1 = dst->nb[1];
+ const uint32_t nb2 = dst->nb[2];
+ const uint32_t nb3 = dst->nb[3];
+
+ const uint32_t r_start = ictx->row_start + ith * ictx->nrows_per_hvx;
+ const uint32_t r_end = MIN(r_start + ictx->nrows_per_hvx, ictx->row_end);
+ if (r_start >= r_end) {
+ return;
+ }
+
+ const uint32_t dst_bytes = dst->ne[0] * sizeof(int32_t);
+ const size_t row_stride = ictx->row_indices_size;
+ const uint32_t batch_rows = ictx->batch_rows;
+ dma_queue * dma_q = th->dma_q;
+
+ struct htp_tensor_row_coord coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02);
+ for (uint32_t r = r_start; r < r_end; ) {
+ const uint32_t b_cnt = MIN(batch_rows, MIN(r_end - r, ne01 - coord.i01));
+ const dma_addr_t dst_addr = dst->data + coord_offset(coord, nb1, nb2, nb3);
+
+ if (dma_ring_depth(dma_q->ring0) >= 8u) {
+ dma_queue_pop(dma_q);
+ }
+ dma_queue_push(dma_q, dma_make_data(dst_addr, ictx->phase1_base),
+ nb1, row_stride, dst_bytes, b_cnt);
+
+ r += b_cnt;
+ for (uint32_t b = 0; b < b_cnt; b++) {
step_row_coord(&coord, ne01, ne02);
}
}
+ dma_queue_flush(dma_q);
}
static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) {
- if (octx->src[0]->type != HTP_TYPE_F32) {
+ 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;
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
const uint32_t total_rows = src0->ne[1] * src0->ne[2] * src0->ne[3];
- const size_t dst_row_size = dst->ne[0] * sizeof(int32_t);
uint32_t row_start = 0;
uint32_t row_end = total_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(int32_t), (uint32_t) dst_row_size, &rows_per_chunk);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
row_end = range.start + range.count;
}
@@ -882,12 +1488,15 @@ static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) {
struct htp_sort_vtcm_layout layout;
htp_sort_vtcm_layout_build(&layout,
+ ne00,
total_rows,
(uint32_t) kparams->chunk_elems,
(uint32_t) kparams->n_chunks,
(uint32_t) kparams->merge_elems,
(uint32_t) kparams->n_hvx,
- (uint32_t) kparams->n_slots);
+ (uint32_t) kparams->n_slots,
+ k,
+ is_top_k);
if (octx->ctx->vtcm_size < layout.total_bytes) {
FARF(ERROR, "sort: VTCM size too small. Needed %zu, have %zu", layout.total_bytes, octx->ctx->vtcm_size);
@@ -899,55 +1508,101 @@ static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) {
float * merge_values = VTCM_LAYOUT_PTR(float, vtcm_base, layout.off_merge_values);
int32_t * merge_indices = VTCM_LAYOUT_PTR(int32_t, vtcm_base, layout.off_merge_indices);
+ if (is_top_k && k >= ne00) {
+ init_indices_ramp((int32_t *) phase1_base, k, 0);
+ const uint32_t n_idx_vecs = (uint32_t) (layout.row_indices_size >> 7);
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) phase1_base;
+ for (uint32_t b = 1; b < layout.batch_rows; b++) {
+ HVX_Vector * restrict vdst_b = (HVX_Vector *) (phase1_base + (size_t) b * layout.row_indices_size);
+ for (uint32_t v = 0; v < n_idx_vecs; v++) {
+ vdst_b[v] = vsrc0[v];
+ }
+ }
+
+ const uint32_t dr = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div);
+
+ struct htp_top_k_identity_ctx ictx;
+ ictx.octx = octx;
+ ictx.kparams = kparams;
+ ictx.phase1_base = phase1_base;
+ ictx.row_indices_size = layout.row_indices_size;
+ ictx.batch_rows = layout.batch_rows;
+ ictx.row_start = row_start;
+ ictx.row_end = row_end;
+ ictx.nrows_per_hvx = dr;
+
+ work_queue_run(octx->ctx->hvx_queue, htp_top_k_identity_job, &ictx, octx->n_hvx);
+ return HTP_STATUS_OK;
+ }
+
if (total_rows == 1 && kparams->n_chunks > 1) {
struct htp_sort_chunk_ctx cctx;
cctx.octx = octx;
cctx.kparams = kparams;
cctx.phase1_base = phase1_base;
cctx.phase1_slot_size = layout.phase1_slot_size;
+ cctx.off_cand = layout.off_cand;
cctx.merge_values = merge_values;
cctx.merge_indices = merge_indices;
memset(cctx.real_count, 0, sizeof(cctx.real_count));
+ memset(cctx.cand_count, 0, sizeof(cctx.cand_count));
work_queue_run(octx->ctx->hvx_queue, htp_sort_chunk_job, &cctx, (uint32_t) kparams->n_chunks);
if (is_top_k) {
- uint32_t chunk_elems = (uint32_t) kparams->chunk_elems;
- uint32_t local_k = MIN(k, chunk_elems);
-
- if (k == 1 && ne00 >= 128*1024) {
- float * cand_vals = merge_values;
- int32_t * cand_idxs = merge_indices;
- float best_val = cand_vals[0];
- int32_t best_idx = cand_idxs[0];
- for (int32_t c = 1; c < kparams->n_chunks; c++) {
- if (cand_vals[c] > best_val) {
- best_val = cand_vals[c];
- best_idx = cand_idxs[c];
+ const uint32_t chunk_elems = (uint32_t) kparams->chunk_elems;
+ const uint32_t local_k = MIN(k, chunk_elems);
+
+ struct htp_thread_trace * tr = &octx->ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+
+ if (k == 1u) {
+ int32_t best_key = (int32_t) 0x80000000u;
+ int32_t best_idx = 0;
+ for (uint32_t c = 0; c < (uint32_t) kparams->n_chunks; c++) {
+ if (cctx.cand_count[c] == 0u) {
+ continue;
+ }
+ union { float f; uint32_t u; int32_t i; } u = { .f = merge_values[c * local_k] };
+ const int32_t key = ((u.u & 0x7fffffffu) > 0x7f800000u)
+ ? (int32_t) 0x80000001u
+ : ((u.i < 0) ? (int32_t) (u.u ^ 0x7fffffffu) : u.i);
+ if (key > best_key) {
+ best_key = key;
+ best_idx = merge_indices[c * local_k];
}
}
- int32_t * dst_ptr = (int32_t *) dst->data;
- dst_ptr[0] = best_idx;
+ merge_indices[0] = best_idx;
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+ dma_sync_write(octx->ctx->dma[0], dst->data, merge_indices, sizeof(int32_t));
return HTP_STATUS_OK;
}
- uint32_t total_candidates = (uint32_t) kparams->n_chunks * local_k;
- float * cand_vals = merge_values;
- int32_t * cand_idxs = merge_indices;
- uint32_t merge_elems = (uint32_t) kparams->merge_elems;
-
- if (merge_elems > total_candidates) {
- hvx_splat_f32_u((uint8_t *) (cand_vals + total_candidates), -INFINITY, merge_elems - total_candidates);
- for (uint32_t j = total_candidates; j < merge_elems; j++) {
- cand_idxs[j] = 0;
+ uint32_t total_candidates = 0;
+ for (uint32_t c = 0; c < (uint32_t) kparams->n_chunks; c++) {
+ const uint32_t cnt = cctx.cand_count[c];
+ const uint32_t base = c * local_k;
+ if (total_candidates != base) {
+ for (uint32_t j = 0; j < cnt; j++) {
+ merge_values[total_candidates + j] = merge_values[base + j];
+ merge_indices[total_candidates + j] = merge_indices[base + j];
+ }
}
+ total_candidates += cnt;
}
- struct htp_thread_trace * tr = &octx->ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
- bitonic_sort_vtcm_desc((uint8_t *) cand_vals, (uint8_t *) cand_idxs, merge_elems / 32, false);
+ int32_t * pos_idx = (int32_t *) phase1_base;
+ const size_t pos_bytes = ((size_t) k * sizeof(int32_t) + 127u) & ~(size_t) 127u;
+ int32_t * cand_scratch = (int32_t *) (phase1_base + pos_bytes);
+
+ top_k_select_hvx(merge_values, pos_idx, NULL, cand_scratch, total_candidates, k, 0);
+
+ int32_t * final_idx = (int32_t *) merge_values;
+ for (uint32_t t = 0; t < k; t++) {
+ final_idx[t] = merge_indices[pos_idx[t]];
+ }
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
- dma_sync_write(octx->ctx->dma[0], dst->data, cand_idxs, k * sizeof(int32_t));
+ dma_sync_write(octx->ctx->dma[0], dst->data, final_idx, k * sizeof(int32_t));
} else {
bool asc = kparams->order == GGML_SORT_ORDER_ASC;
if (kparams->n_chunks == 8) {
@@ -1022,20 +1677,14 @@ static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) {
mctx.kparams = kparams;
mctx.phase1_base = phase1_base;
mctx.phase1_slot_size = layout.phase1_slot_size;
+ mctx.row_values_size = layout.row_values_size;
+ mctx.row_indices_size = layout.row_indices_size;
+ mctx.off_cand = layout.off_cand;
+ mctx.batch_rows = layout.batch_rows;
mctx.row_start = row_start;
mctx.row_end = row_end;
- uint32_t dst_row_bytes = (uint32_t) dst_row_size;
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(int32_t), dst_row_bytes, &rows_per_chunk);
- if (rows_per_chunk == 0) {
- rows_per_chunk = 1;
- }
- uint32_t dr = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div);
- if (rows_per_chunk > 1) {
- dr = hex_round_up(dr, rows_per_chunk);
- }
- mctx.nrows_per_hvx = dr;
+ mctx.nrows_per_hvx = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div);
work_queue_run(octx->ctx->hvx_queue, htp_sort_multi_row_job, &mctx, octx->n_hvx);
diff --git a/ggml/src/ggml-hexagon/htp/argsort-ops.h b/ggml/src/ggml-hexagon/htp/argsort-ops.h
index d1cb8087b..5cc4f2711 100644
--- a/ggml/src/ggml-hexagon/htp/argsort-ops.h
+++ b/ggml/src/ggml-hexagon/htp/argsort-ops.h
@@ -25,6 +25,9 @@ struct htp_sort_kernel_params {
struct htp_sort_vtcm_layout {
size_t total_bytes;
size_t phase1_slot_size;
+ size_t row_values_size;
+ size_t row_indices_size;
+ size_t off_cand;
size_t off_phase1;
size_t off_merge_values;
size_t off_merge_indices;
@@ -33,16 +36,20 @@ struct htp_sort_vtcm_layout {
uint32_t merge_elems;
uint32_t n_hvx;
uint32_t n_slots;
+ uint32_t batch_rows;
};
static inline void htp_sort_vtcm_layout_build(
struct htp_sort_vtcm_layout * L,
+ uint32_t ne00,
uint32_t total_rows,
uint32_t chunk_elems,
uint32_t n_chunks,
uint32_t merge_elems,
uint32_t n_hvx,
- uint32_t n_slots) {
+ uint32_t n_slots,
+ uint32_t k,
+ bool is_top_k) {
memset(L, 0, sizeof(*L));
L->chunk_elems = chunk_elems;
@@ -51,19 +58,65 @@ static inline void htp_sort_vtcm_layout_build(
L->n_hvx = n_hvx;
L->n_slots = n_slots;
- const size_t values_size = ((chunk_elems * sizeof(float)) + 127) & ~127;
- const size_t indices_size = ((chunk_elems * sizeof(int32_t)) + 127) & ~127;
- L->phase1_slot_size = ((values_size + indices_size) + 255) & ~255;
+ if (is_top_k && k >= ne00) {
+ const size_t idx_size = ((k * sizeof(int32_t)) + 127u) & ~(size_t) 127u;
+ uint32_t batch_rows = 1u;
+ if ((idx_size << 4) <= 65536u) {
+ batch_rows = 16u;
+ } else if ((idx_size << 2) <= 65536u) {
+ batch_rows = 4u;
+ }
+ if (batch_rows > total_rows && total_rows > 0u) {
+ batch_rows = total_rows;
+ }
+ L->row_indices_size = idx_size;
+ L->batch_rows = batch_rows;
+ L->phase1_slot_size = ((idx_size * batch_rows) + 255u) & ~(size_t) 255u;
+
+ size_t off = 0;
+ VTCM_LAYOUT_ALLOC(off, off_phase1, L->phase1_slot_size);
+ L->total_bytes = off;
+ return;
+ }
+
+ uint32_t indices_elems = chunk_elems;
+ if (is_top_k) {
+ if (total_rows == 1u && n_chunks > 1u) {
+ indices_elems = 0u;
+ } else if (k < chunk_elems) {
+ indices_elems = k;
+ }
+ }
+
+ uint32_t batch_rows = 1u;
+ if (total_rows > 1u && chunk_elems <= 256u) {
+ if (total_rows > 7u * n_hvx) {
+ batch_rows = 8u;
+ } else if (total_rows > 3u * n_hvx) {
+ batch_rows = 4u;
+ }
+ }
+
+ const size_t row_values_size = ((chunk_elems * sizeof(float)) + 127u) & ~(size_t) 127u;
+ const size_t row_indices_size = ((indices_elems * sizeof(int32_t)) + 127u) & ~(size_t) 127u;
+ const size_t off_cand = (row_values_size + row_indices_size) * batch_rows;
+ const size_t cand_size = (is_top_k && chunk_elems > 256u) ? 512u : 0u;
+
+ L->row_values_size = row_values_size;
+ L->row_indices_size = row_indices_size;
+ L->off_cand = off_cand;
+ L->batch_rows = batch_rows;
+ L->phase1_slot_size = ((off_cand + cand_size) + 255u) & ~(size_t) 255u;
size_t off = 0;
- if (total_rows > 1) {
+ if (total_rows > 1u) {
VTCM_LAYOUT_ALLOC(off, off_phase1, L->phase1_slot_size * n_slots * n_hvx);
} else {
VTCM_LAYOUT_ALLOC(off, off_phase1, L->phase1_slot_size * n_chunks * n_slots);
- const size_t merge_values_size = ((merge_elems * sizeof(float)) + 127) & ~127;
- const size_t merge_indices_size = ((merge_elems * sizeof(int32_t)) + 127) & ~127;
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_values, merge_values_size, n_chunks > 1);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_indices, merge_indices_size, n_chunks > 1);
+ const size_t merge_values_size = ((merge_elems * sizeof(float)) + 127u) & ~(size_t) 127u;
+ const size_t merge_indices_size = ((merge_elems * sizeof(int32_t)) + 127u) & ~(size_t) 127u;
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_values, merge_values_size, n_chunks > 1u);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_indices, merge_indices_size, n_chunks > 1u);
}
L->total_bytes = off;
}
@@ -79,79 +132,111 @@ static inline bool htp_sort_solve_layout(
memset(layout, 0, sizeof(*layout));
- if (total_rows > 1) {
- uint32_t n_hvx = total_rows < n_hvx_max ? total_rows : n_hvx_max;
-
- uint32_t n_vec = (ne00 + 31) / 32;
- uint32_t n_vec_pow2 = 1;
- while (n_vec_pow2 < n_vec) n_vec_pow2 <<= 1;
- uint32_t ne00_padded = n_vec_pow2 * 32;
+ if (is_top_k && k >= ne00) {
+ htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00, 1, 0, 1, 1, k, true);
+ if (layout->total_bytes > vtcm_budget) {
+ return false;
+ }
+ uint32_t n_hvx = 1u;
+ if (total_rows > 1u && (size_t) total_rows * k * sizeof(int32_t) > 16384u) {
+ const uint32_t b = layout->batch_rows > 0u ? layout->batch_rows : 1u;
+ const uint32_t max_w = (total_rows + b - 1u) / b;
+ n_hvx = max_w < n_hvx_max ? max_w : n_hvx_max;
+ }
+ htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00, 1, 0, n_hvx, 1, k, true);
+ return layout->total_bytes <= vtcm_budget;
+ }
- size_t values_size = ((ne00_padded * sizeof(float)) + 127) & ~127;
- size_t indices_size = ((ne00_padded * sizeof(int32_t)) + 127) & ~127;
- size_t spad_per_slot = ((values_size + indices_size) + 255) & ~255;
+ if (total_rows > 1u) {
+ uint32_t n_hvx = total_rows < n_hvx_max ? total_rows : n_hvx_max;
+ if (ne00 <= 128u) {
+ const uint32_t cap = (total_rows >= 4u) ? ((total_rows + 3u) >> 2) : 1u;
+ if (n_hvx > cap) {
+ n_hvx = cap;
+ }
+ }
- uint32_t n_slots = 2;
- if (spad_per_slot * 2 > vtcm_budget) {
- n_slots = 1;
+ uint32_t ne00_padded = 0u;
+ if (is_top_k && ne00 > 256u) {
+ ne00_padded = (ne00 + 31u) & ~31u;
+ } else {
+ const uint32_t n_vec = (ne00 + 31u) >> 5;
+ uint32_t n_vec_pow2 = 1u;
+ while (n_vec_pow2 < n_vec) {
+ n_vec_pow2 <<= 1;
+ }
+ ne00_padded = n_vec_pow2 * 32u;
}
- size_t spad_per_hvx = spad_per_slot * n_slots;
+ uint32_t n_slots = 2u;
+ htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, 1, n_slots, k, is_top_k);
+ if (layout->total_bytes > vtcm_budget) {
+ n_slots = 1u;
+ }
- while (n_hvx > 1 && (spad_per_hvx * n_hvx) > vtcm_budget) {
+ htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, n_hvx, n_slots, k, is_top_k);
+ while (n_hvx > 1u && layout->total_bytes > vtcm_budget) {
n_hvx--;
+ htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, n_hvx, n_slots, k, is_top_k);
+ }
+ if (layout->total_bytes > vtcm_budget && n_slots > 1u) {
+ n_slots = 1u;
+ htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, n_hvx, n_slots, k, is_top_k);
}
-
- htp_sort_vtcm_layout_build(layout, total_rows, ne00_padded, 1, 0, n_hvx, n_slots);
return layout->total_bytes <= vtcm_budget;
}
- uint32_t n_vec = (ne00 + 31) / 32;
- uint32_t n_vec_pow2 = 1;
- while (n_vec_pow2 < n_vec) n_vec_pow2 <<= 1;
-
- uint32_t n_chunks = 1;
- if (ne00 > 1024) {
- while (n_chunks * 2 <= n_hvx_max && n_chunks * 2 <= n_vec_pow2) {
- n_chunks *= 2;
- }
+ const uint32_t n_vec = (ne00 + 31u) >> 5;
+ uint32_t n_vec_pow2 = 1u;
+ while (n_vec_pow2 < n_vec) {
+ n_vec_pow2 <<= 1;
}
- uint32_t chunk_n_vec = n_vec_pow2 / n_chunks;
- uint32_t chunk_elems = chunk_n_vec * 32;
- uint32_t merge_elems = 0;
-
- if (n_chunks > 1) {
- if (is_top_k) {
- uint32_t local_k = k < chunk_elems ? k : chunk_elems;
- uint32_t total_candidates = n_chunks * local_k;
- uint32_t merge_n_vec = (total_candidates + 31) / 32;
- uint32_t merge_n_vec_pow2 = 1;
- while (merge_n_vec_pow2 < merge_n_vec) merge_n_vec_pow2 <<= 1;
- merge_elems = merge_n_vec_pow2 * 32;
- } else {
- merge_elems = n_vec_pow2 * 32;
+ if (is_top_k) {
+ uint32_t n_chunks = 1u;
+ if (ne00 > 2048u) {
+ while (n_chunks * 2u <= n_hvx_max && (n_chunks * 2u) * 32u <= n_vec) {
+ n_chunks *= 2u;
+ }
}
- }
- htp_sort_vtcm_layout_build(layout, 1, chunk_elems, n_chunks, merge_elems, n_chunks, 1);
+ while (n_chunks > 1u) {
+ const uint32_t chunk_n_vec = (n_vec + n_chunks - 1u) / n_chunks;
+ const uint32_t chunk_elems = chunk_n_vec * 32u;
+ const uint32_t local_k = k < chunk_elems ? k : chunk_elems;
+ const uint32_t merge_elems = ((n_chunks * local_k) + 31u) & ~31u;
+
+ htp_sort_vtcm_layout_build(layout, ne00, 1, chunk_elems, n_chunks, merge_elems, n_chunks, 1, k, true);
+ if (layout->total_bytes <= vtcm_budget) {
+ return true;
+ }
+ n_chunks >>= 1;
+ }
- if (layout->total_bytes > vtcm_budget && n_chunks > 1) {
- n_chunks = 1;
- chunk_elems = n_vec_pow2 * 32;
- merge_elems = 0;
- htp_sort_vtcm_layout_build(layout, 1, chunk_elems, n_chunks, merge_elems, 1, 1);
+ const uint32_t chunk_elems = (ne00 > 256u) ? (n_vec * 32u) : (n_vec_pow2 * 32u);
+ htp_sort_vtcm_layout_build(layout, ne00, 1, chunk_elems, 1, 0, 1, 1, k, true);
+ return layout->total_bytes <= vtcm_budget;
}
- if (layout->total_bytes > vtcm_budget) {
- return false;
+ uint32_t n_chunks = 1u;
+ if (ne00 > 1024u) {
+ while (n_chunks * 2u <= n_hvx_max && n_chunks * 2u <= n_vec_pow2) {
+ n_chunks *= 2u;
+ }
}
- if (n_chunks == 1 && layout->phase1_slot_size * 2 <= vtcm_budget) {
- htp_sort_vtcm_layout_build(layout, 1, chunk_elems, 1, 0, 1, 2);
+ while (n_chunks > 1u) {
+ const uint32_t chunk_elems = (n_vec_pow2 / n_chunks) * 32u;
+ const uint32_t merge_elems = n_vec_pow2 * 32u;
+ htp_sort_vtcm_layout_build(layout, ne00, 1, chunk_elems, n_chunks, merge_elems, n_chunks, 1, k, false);
+ if (layout->total_bytes <= vtcm_budget) {
+ return true;
+ }
+ n_chunks >>= 1;
}
- return true;
+ htp_sort_vtcm_layout_build(layout, ne00, 1, n_vec_pow2 * 32u, 1, 0, 1, 1, k, false);
+ return layout->total_bytes <= vtcm_budget;
}
#if defined(__cplusplus)
diff --git a/ggml/src/ggml-hexagon/htp/binary-ops.c b/ggml/src/ggml-hexagon/htp/binary-ops.c
index a5951556b..cb8d7b428 100644
--- a/ggml/src/ggml-hexagon/htp/binary-ops.c
+++ b/ggml/src/ggml-hexagon/htp/binary-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -9,6 +5,7 @@
#include <string.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hvx-utils.h"
#define GGML_COMMON_DECL_C
@@ -46,7 +43,13 @@ struct htp_binary_context {
size_t src0_row_size_aligned;
size_t src1_row_size_aligned;
size_t dst_row_size_aligned;
- size_t row_size_bytes;
+ size_t src0_row_size;
+ size_t src1_row_size;
+ size_t dst_row_size;
+ uint32_t src0_elem_size;
+ uint32_t src1_elem_size;
+ uint32_t dst_elem_size;
+ uint32_t src1_table_elem_size;
bool split_at_ne01;
bool split_at_ne02;
@@ -54,34 +57,34 @@ struct htp_binary_context {
void * compute;
};
-#define htp_binary_preamble \
- const struct htp_tensor * src0 = octx->src[0]; \
- const struct htp_tensor * src1 = octx->src[1]; \
- const struct htp_tensor * dst = octx->dst; \
- \
- const uint32_t ne00 = src0->ne[0]; \
- const uint32_t ne01 = src0->ne[1]; \
- const uint32_t ne02 = src0->ne[2]; \
- const uint32_t ne03 = src0->ne[3]; \
- \
- const uint32_t ne10 = src1->ne[0]; \
- const uint32_t ne11 = src1->ne[1]; \
- const uint32_t ne12 = src1->ne[2]; \
- const uint32_t ne13 = src1->ne[3]; \
- \
- const uint32_t nb01 = src0->nb[1]; \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t nb11 = src1->nb[1]; \
- const uint32_t nb12 = src1->nb[2]; \
- const uint32_t nb13 = src1->nb[3]; \
- \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
-
-static inline uint32_t calc_block_size(struct htp_binary_context * bctx, uint32_t ir, uint32_t end_row, uint32_t ne01, uint32_t ne02) {
+#define htp_binary_preamble \
+ const struct htp_tensor * src0 = octx->src[0]; \
+ const struct htp_tensor * src1 = octx->src[1]; \
+ const struct htp_tensor * dst = octx->dst; \
+ \
+ 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)) 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)) 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)) nb1 = dst->nb[1]; \
+ const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \
+ const uint32_t __attribute__((unused)) nb3 = dst->nb[3];
+
+static inline uint32_t calc_block_size(const struct htp_binary_context * bctx, uint32_t ir, uint32_t end_row, uint32_t ne01, uint32_t ne02) {
uint32_t i03, i02, i01, rem;
i03 = fastdiv(ir, &bctx->src0_dim12_div);
rem = ir - i03 * (ne02 * ne01);
@@ -236,125 +239,580 @@ DEFINE_COMPUTE_REPEAT(mul_f16, _Float16, hvx_mul_f16_uuu)
DEFINE_COMPUTE_REPEAT(div_f32, float, hvx_div_f32_uuu)
DEFINE_COMPUTE_REPEAT(div_f16, _Float16, hvx_div_f16_uuu)
+static inline HVX_Vector binary_clamp_f16_finite_vec(HVX_Vector v, HVX_Vector max_f16, HVX_Vector min_f16, HVX_Vector inf) {
+ const HVX_VectorPred finite = Q6_Q_vcmp_gt_VsfVsf(inf, hvx_vec_abs_f32(v));
+ const HVX_VectorPred high = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(v, max_f16));
+ const HVX_VectorPred low = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(min_f16, v));
+ v = Q6_V_vmux_QVV(high, max_f16, v);
+ return Q6_V_vmux_QVV(low, min_f16, v);
+}
+
+#define BINARY_OP_ADD(a, b, nan_inf_mask) ((void) (nan_inf_mask), hvx_vec_add_f32_f32(a, b))
+#define BINARY_OP_SUB(a, b, nan_inf_mask) ((void) (nan_inf_mask), hvx_vec_sub_f32_f32(a, b))
+#define BINARY_OP_MUL(a, b, nan_inf_mask) ((void) (nan_inf_mask), hvx_vec_mul_f32_f32(a, b))
+#define BINARY_OP_DIV(a, b, nan_inf_mask) hvx_vec_mul_f32_f32(a, hvx_vec_inverse_f32_guard(b, nan_inf_mask))
+
+#define BINARY_LOAD64_A_F16(vsrc, k, s_lo, s_hi) \
+ HVX_VectorPair p_##s_lo = hvx_vec_f16_to_f32((vsrc)[k]); \
+ HVX_Vector s_lo = Q6_V_lo_W(p_##s_lo); \
+ HVX_Vector s_hi = Q6_V_hi_W(p_##s_lo)
+
+#define BINARY_LOAD64_A_F32(vsrc, k, s_lo, s_hi) \
+ HVX_Vector s_lo = (vsrc)[2 * (k) + 0]; \
+ HVX_Vector s_hi = (vsrc)[2 * (k) + 1]
+
+#define BINARY_LOAD64_U_F16(src, k, s_lo, s_hi) \
+ HVX_VectorPair p_##s_lo = hvx_vec_f16_to_f32(hvx_vmemu((src) + (size_t) (k) * 128)); \
+ HVX_Vector s_lo = Q6_V_lo_W(p_##s_lo); \
+ HVX_Vector s_hi = Q6_V_hi_W(p_##s_lo)
+
+#define BINARY_LOAD64_U_F32(src, k, s_lo, s_hi) \
+ HVX_Vector s_lo = hvx_vmemu((src) + (size_t) (2 * (k) + 0) * 128); \
+ HVX_Vector s_hi = hvx_vmemu((src) + (size_t) (2 * (k) + 1) * 128)
+
+#define BINARY_TAIL_LO_A_F16(vsrc, nvec, s_lo, s_hi) \
+ BINARY_LOAD64_A_F16(vsrc, nvec, s_lo, s_hi)
+#define BINARY_TAIL_HI_A_F16(vsrc, nvec, s_hi) \
+ ((void) (vsrc), (void) (nvec), (void) (s_hi))
+
+#define BINARY_TAIL_LO_A_F32(vsrc, nvec, s_lo, s_hi) \
+ HVX_Vector s_lo = (vsrc)[2 * (nvec)]; \
+ HVX_Vector s_hi
+#define BINARY_TAIL_HI_A_F32(vsrc, nvec, s_hi) \
+ s_hi = (vsrc)[2 * (nvec) + 1]
+
+#define BINARY_TAIL_LO_U_F16(src, nvec, s_lo, s_hi) \
+ BINARY_LOAD64_U_F16(src, nvec, s_lo, s_hi)
+#define BINARY_TAIL_HI_U_F16(src, nvec, s_hi) \
+ ((void) (src), (void) (nvec), (void) (s_hi))
+
+#define BINARY_TAIL_LO_U_F32(src, nvec, s_lo, s_hi) \
+ HVX_Vector s_lo = hvx_vmemu((src) + (size_t) (2 * (nvec)) * 128); \
+ HVX_Vector s_hi
+#define BINARY_TAIL_HI_U_F32(src, nvec, s_hi) \
+ s_hi = hvx_vmemu((src) + (size_t) (2 * (nvec) + 1) * 128)
+
+#define DEFINE_BINARY_MIXED_F32(NAME, T0, T1, OP, UNROLL) \
+static void NAME(uint8_t * dst, const uint8_t * src0, const uint8_t * src1, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const uint32_t nvec = n / 64; \
+ const uint32_t nloe = n % 64; \
+ if (hex_is_aligned(dst, 128) && hex_is_aligned(src0, 128) && hex_is_aligned(src1, 128)) { \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ UNROLL \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ BINARY_LOAD64_A_##T0(vsrc0, k, s0_0, s0_1); \
+ BINARY_LOAD64_A_##T1(vsrc1, k, s1_0, s1_1); \
+ vdst[2 * k + 0] = OP(s0_0, s1_0, nan_inf_mask); \
+ vdst[2 * k + 1] = OP(s0_1, s1_1, nan_inf_mask); \
+ } \
+ if (nloe) { \
+ BINARY_TAIL_LO_A_##T0(vsrc0, nvec, s0_0, s0_1); \
+ BINARY_TAIL_LO_A_##T1(vsrc1, nvec, s1_0, s1_1); \
+ HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \
+ if (nloe <= 32) { \
+ hvx_vec_store_a(&vdst[2 * nvec], nloe * sizeof(float), out0); \
+ } else { \
+ vdst[2 * nvec] = out0; \
+ BINARY_TAIL_HI_A_##T0(vsrc0, nvec, s0_1); \
+ BINARY_TAIL_HI_A_##T1(vsrc1, nvec, s1_1); \
+ HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \
+ hvx_vec_store_a(&vdst[2 * nvec + 1], (nloe - 32) * sizeof(float), out1); \
+ } \
+ } \
+ return; \
+ } \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ BINARY_LOAD64_U_##T0(src0, k, s0_0, s0_1); \
+ BINARY_LOAD64_U_##T1(src1, k, s1_0, s1_1); \
+ *(HVX_UVector *) (dst + (size_t) (2 * k + 0) * 128) = OP(s0_0, s1_0, nan_inf_mask); \
+ *(HVX_UVector *) (dst + (size_t) (2 * k + 1) * 128) = OP(s0_1, s1_1, nan_inf_mask); \
+ } \
+ if (nloe) { \
+ BINARY_TAIL_LO_U_##T0(src0, nvec, s0_0, s0_1); \
+ BINARY_TAIL_LO_U_##T1(src1, nvec, s1_0, s1_1); \
+ HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \
+ if (nloe <= 32) { \
+ hvx_vec_store_u(dst + (size_t) (2 * nvec) * 128, nloe * sizeof(float), out0); \
+ } else { \
+ *(HVX_UVector *) (dst + (size_t) (2 * nvec) * 128) = out0; \
+ BINARY_TAIL_HI_U_##T0(src0, nvec, s0_1); \
+ BINARY_TAIL_HI_U_##T1(src1, nvec, s1_1); \
+ HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \
+ hvx_vec_store_u(dst + (size_t) (2 * nvec + 1) * 128, (nloe - 32) * sizeof(float), out1); \
+ } \
+ } \
+}
+
+#define DEFINE_BINARY_MIXED_F16(NAME, T0, T1, OP, UNROLL) \
+static void NAME(uint8_t * dst, const uint8_t * src0, const uint8_t * src1, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \
+ const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \
+ const uint32_t nvec = n / 64; \
+ const uint32_t nloe = n % 64; \
+ if (hex_is_aligned(dst, 128) && hex_is_aligned(src0, 128) && hex_is_aligned(src1, 128)) { \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ UNROLL \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ BINARY_LOAD64_A_##T0(vsrc0, k, s0_0, s0_1); \
+ BINARY_LOAD64_A_##T1(vsrc1, k, s1_0, s1_1); \
+ HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \
+ HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ vdst[k] = hvx_vec_f32_to_f16(out0, out1); \
+ } \
+ if (nloe) { \
+ BINARY_TAIL_LO_A_##T0(vsrc0, nvec, s0_0, s0_1); \
+ BINARY_TAIL_LO_A_##T1(vsrc1, nvec, s1_0, s1_1); \
+ HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ HVX_Vector out1 = Q6_V_vzero(); \
+ if (nloe > 32) { \
+ BINARY_TAIL_HI_A_##T0(vsrc0, nvec, s0_1); \
+ BINARY_TAIL_HI_A_##T1(vsrc1, nvec, s1_1); \
+ out1 = OP(s0_1, s1_1, nan_inf_mask); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ } \
+ HVX_Vector packed = hvx_vec_f32_to_f16(out0, out1); \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \
+ } \
+ return; \
+ } \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ BINARY_LOAD64_U_##T0(src0, k, s0_0, s0_1); \
+ BINARY_LOAD64_U_##T1(src1, k, s1_0, s1_1); \
+ HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \
+ HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ *(HVX_UVector *) (dst + (size_t) k * 128) = hvx_vec_f32_to_f16(out0, out1); \
+ } \
+ if (nloe) { \
+ BINARY_TAIL_LO_U_##T0(src0, nvec, s0_0, s0_1); \
+ BINARY_TAIL_LO_U_##T1(src1, nvec, s1_0, s1_1); \
+ HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ HVX_Vector out1 = Q6_V_vzero(); \
+ if (nloe > 32) { \
+ BINARY_TAIL_HI_U_##T0(src0, nvec, s0_1); \
+ BINARY_TAIL_HI_U_##T1(src1, nvec, s1_1); \
+ out1 = OP(s0_1, s1_1, nan_inf_mask); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ } \
+ HVX_Vector packed = hvx_vec_f32_to_f16(out0, out1); \
+ hvx_vec_store_u(dst + (size_t) nvec * 128, nloe * sizeof(_Float16), packed); \
+ } \
+}
+
+#define DEFINE_BINARY_MIXED_F16_F16_F16(NAME, OP) \
+static void NAME(uint8_t * dst, const uint8_t * src0, const uint8_t * src1, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \
+ const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \
+ const uint32_t nvec = n / 64; \
+ const uint32_t nloe = n % 64; \
+ if (hex_is_aligned(dst, 128) && hex_is_aligned(src0, 128) && hex_is_aligned(src1, 128)) { \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ _Pragma("unroll(2)") \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(vsrc0[k]); \
+ HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(vsrc1[k]); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \
+ HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ vdst[k] = hvx_vec_f32_to_f16_shuff(out0, out1); \
+ } \
+ if (nloe) { \
+ HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(vsrc0[nvec]); \
+ HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(vsrc1[nvec]); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \
+ HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ HVX_Vector packed = hvx_vec_f32_to_f16_shuff(out0, out1); \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \
+ } \
+ return; \
+ } \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + (size_t) k * 128)); \
+ HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src1 + (size_t) k * 128)); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \
+ HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ *(HVX_UVector *) (dst + (size_t) k * 128) = hvx_vec_f32_to_f16_shuff(out0, out1); \
+ } \
+ if (nloe) { \
+ HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + (size_t) nvec * 128)); \
+ HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src1 + (size_t) nvec * 128)); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \
+ HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ HVX_Vector packed = hvx_vec_f32_to_f16_shuff(out0, out1); \
+ hvx_vec_store_u(dst + (size_t) nvec * 128, nloe * sizeof(_Float16), packed); \
+ } \
+}
+
+#define DEFINE_BINARY_MIXED_OP(OP_NAME, OP, UNROLL) \
+ DEFINE_BINARY_MIXED_F16(binary_##OP_NAME##_f16_f32_f16, F16, F32, OP, UNROLL) \
+ DEFINE_BINARY_MIXED_F32(binary_##OP_NAME##_f16_f32_f32, F16, F32, OP, UNROLL) \
+ DEFINE_BINARY_MIXED_F16(binary_##OP_NAME##_f32_f16_f16, F32, F16, OP, UNROLL) \
+ DEFINE_BINARY_MIXED_F32(binary_##OP_NAME##_f32_f16_f32, F32, F16, OP, UNROLL) \
+ DEFINE_BINARY_MIXED_F32(binary_##OP_NAME##_f16_f16_f32, F16, F16, OP, UNROLL) \
+ DEFINE_BINARY_MIXED_F16(binary_##OP_NAME##_f32_f32_f16, F32, F32, OP, UNROLL)
+
+DEFINE_BINARY_MIXED_OP(add, BINARY_OP_ADD, _Pragma("unroll(2)"))
+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 DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, TYPES) \
+ DEFINE_COMPUTE_SAME_SHAPE(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) \
+ DEFINE_COMPUTE_ROW_BCAST(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) \
+ DEFINE_COMPUTE_COMPLEX(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES)
+
+#define DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, TYPES, DST_TYPE, SRC0_TYPE) \
+static void compute_repeat_##OP_NAME##_##TYPES( \
+ uint8_t * dst, const uint8_t * src0, const uint8_t * src1_plane, \
+ uint32_t i01, uint32_t ne11, const struct fastdiv_values * div11, uint32_t src1_stride, \
+ uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00, uint32_t ne10) { \
+ for (uint32_t r = 0; r < n_rows; r++) { \
+ uint32_t i11 = fastmodulo(i01 + r, ne11, div11); \
+ const uint8_t * r_src1 = src1_plane + i11 * src1_stride; \
+ for (uint32_t c = 0; c < ne00; c += ne10) { \
+ binary_##OP_NAME##_##TYPES(dst + r * dst_stride + (size_t) c * sizeof(DST_TYPE), \
+ src0 + r * src0_stride + (size_t) c * sizeof(SRC0_TYPE), r_src1, MIN(ne10, ne00 - c)); \
+ } \
+ } \
+}
+
+#define DEFINE_COMPUTE_MIXED_ALL(OP_NAME) \
+ DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f16_f32_f16) \
+ DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f16_f32_f32) \
+ DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f32_f16_f16) \
+ DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f32_f16_f32) \
+ DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f16_f16_f32) \
+ DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f32_f32_f16) \
+ DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f16_f32_f16, _Float16, _Float16) \
+ DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f16_f32_f32, float, _Float16) \
+ DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f32_f16_f16, _Float16, float) \
+ DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f32_f16_f32, float, float) \
+ DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f16_f16_f32, float, _Float16) \
+ DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f32_f32_f16, _Float16, float)
+
+DEFINE_COMPUTE_MIXED_ALL(add)
+DEFINE_COMPUTE_MIXED_ALL(sub)
+DEFINE_COMPUTE_MIXED_ALL(mul)
+DEFINE_COMPUTE_MIXED_ALL(div)
+
+#define DEFINE_BINARY_MIXED_SCALAR_F16_F16(NAME, OP) \
+static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const HVX_Vector val_vec = hvx_vec_splat_f32(val); \
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \
+ const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ const uint32_t nvec = n / 64; \
+ const uint32_t nloe = n % 64; \
+ _Pragma("unroll(2)") \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ HVX_VectorPair pair = hvx_vec_f16_to_f32_shuff(vsrc0[k]); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \
+ HVX_Vector out1 = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ vdst[k] = hvx_vec_f32_to_f16_shuff(out0, out1); \
+ } \
+ if (nloe) { \
+ HVX_VectorPair pair = hvx_vec_f16_to_f32_shuff(vsrc0[nvec]); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \
+ HVX_Vector out1 = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ HVX_Vector packed = hvx_vec_f32_to_f16_shuff(out0, out1); \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \
+ } \
+}
+
+#define DEFINE_BINARY_MIXED_SCALAR_F16_F32(NAME, OP) \
+static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const HVX_Vector val_vec = hvx_vec_splat_f32(val); \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ const uint32_t nvec = n / 64; \
+ const uint32_t nloe = n % 64; \
+ _Pragma("unroll(2)") \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ HVX_VectorPair pair = hvx_vec_f16_to_f32(vsrc0[k]); \
+ vdst[2 * k + 0] = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \
+ vdst[2 * k + 1] = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \
+ } \
+ if (nloe) { \
+ HVX_VectorPair pair = hvx_vec_f16_to_f32(vsrc0[nvec]); \
+ HVX_Vector out0 = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \
+ if (nloe <= 32) { \
+ hvx_vec_store_a(&vdst[2 * nvec], nloe * sizeof(float), out0); \
+ } else { \
+ vdst[2 * nvec] = out0; \
+ HVX_Vector out1 = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \
+ hvx_vec_store_a(&vdst[2 * nvec + 1], (nloe - 32) * sizeof(float), out1); \
+ } \
+ } \
+}
+
+#define DEFINE_BINARY_MIXED_SCALAR_F32_F16(NAME, OP) \
+static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const HVX_Vector val_vec = hvx_vec_splat_f32(val); \
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \
+ const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ const uint32_t nvec = n / 64; \
+ const uint32_t nloe = n % 64; \
+ _Pragma("unroll(2)") \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ HVX_Vector out0 = OP(vsrc0[2 * k + 0], val_vec, nan_inf_mask); \
+ HVX_Vector out1 = OP(vsrc0[2 * k + 1], val_vec, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ vdst[k] = hvx_vec_f32_to_f16(out0, out1); \
+ } \
+ if (nloe) { \
+ HVX_Vector out0 = OP(vsrc0[2 * nvec], val_vec, nan_inf_mask); \
+ out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \
+ HVX_Vector out1 = Q6_V_vzero(); \
+ if (nloe > 32) { \
+ out1 = OP(vsrc0[2 * nvec + 1], val_vec, nan_inf_mask); \
+ out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \
+ } \
+ HVX_Vector packed = hvx_vec_f32_to_f16(out0, out1); \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \
+ } \
+}
+
+#define DEFINE_BINARY_MIXED_SCALAR_F32_F32(NAME, OP) \
+static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \
+ const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \
+ const HVX_Vector val_vec = hvx_vec_splat_f32(val); \
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ const uint32_t nvec = n / 32; \
+ const uint32_t nloe = n % 32; \
+ _Pragma("unroll(2)") \
+ for (uint32_t k = 0; k < nvec; k++) { \
+ vdst[k] = OP(vsrc0[k], val_vec, nan_inf_mask); \
+ } \
+ if (nloe) { \
+ HVX_Vector out = OP(vsrc0[nvec], val_vec, nan_inf_mask); \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), out); \
+ } \
+}
+
+#define DEFINE_COMPUTE_MIXED_SCALAR(NAME, SRC0_TYPE, DST_TYPE, FN) \
+static void compute_scalar_##NAME( \
+ uint8_t * dst, const uint8_t * src0, const void * s1_table, \
+ uint32_t cur_i11, uint32_t ne11, uint32_t n_rows, \
+ size_t dst_stride, size_t src0_stride, uint32_t ne00) { \
+ const float * table = (const float *) s1_table; \
+ for (uint32_t r = 0; r < n_rows; r++) { \
+ FN(dst + r * dst_stride, src0 + r * src0_stride, table[cur_i11], ne00); \
+ if (ne11 > 1 && ++cur_i11 == ne11) cur_i11 = 0; \
+ } \
+}
+
+#define DEFINE_COMPUTE_MIXED_SCALAR_OP(OP_NAME, OP) \
+ DEFINE_BINARY_MIXED_SCALAR_F16_F16(binary_scalar_##OP_NAME##_f16_f16, OP) \
+ DEFINE_BINARY_MIXED_SCALAR_F16_F32(binary_scalar_##OP_NAME##_f16_f32, OP) \
+ DEFINE_BINARY_MIXED_SCALAR_F32_F16(binary_scalar_##OP_NAME##_f32_f16, OP) \
+ DEFINE_BINARY_MIXED_SCALAR_F32_F32(binary_scalar_##OP_NAME##_f32_f32, OP) \
+ DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f16_f32_f16, _Float16, _Float16, binary_scalar_##OP_NAME##_f16_f16) \
+ DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f16_f32_f32, _Float16, float, binary_scalar_##OP_NAME##_f16_f32) \
+ DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f32_f16_f16, float, _Float16, binary_scalar_##OP_NAME##_f32_f16) \
+ DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f32_f16_f32, float, float, binary_scalar_##OP_NAME##_f32_f32) \
+ DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f16_f16_f32, _Float16, float, binary_scalar_##OP_NAME##_f16_f32) \
+ DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f32_f32_f16, float, _Float16, binary_scalar_##OP_NAME##_f32_f16)
+
+DEFINE_COMPUTE_MIXED_SCALAR_OP(add, BINARY_OP_ADD)
+DEFINE_COMPUTE_MIXED_SCALAR_OP(sub, BINARY_OP_SUB)
+DEFINE_COMPUTE_MIXED_SCALAR_OP(mul, BINARY_OP_MUL)
+DEFINE_COMPUTE_MIXED_SCALAR_OP(div, BINARY_OP_DIV)
+
typedef void (*compute_add_id_t)(
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);
-static void compute_add_id_f32(
- 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++) {
- uint32_t r_i01 = i01 + r;
- const int32_t idx = src2_ids[i02 * ne01 + r_i01];
- if (idx < 0) {
- memcpy(dst + r * dst_stride, src0 + r * src0_stride, ne00 * sizeof(float));
- continue;
- }
- const uint8_t * r_src1 = src1_data + idx * src1_stride;
- const uint8_t * r_src0 = src0 + r * src0_stride;
- uint8_t * r_dst = dst + r * dst_stride;
- hvx_add_f32_aaa(r_dst, r_src0, r_src1, ne00);
- }
+#define DEFINE_ADD_ID_COPY(NAME, STMT) \
+static void add_id_copy_##NAME(uint8_t * dst, const uint8_t * src, uint32_t n) { \
+ STMT; \
}
-// 1. Scalar src1 in VTCM via DMA (ne10 == 1)
-static void binary_thread_scalar(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_binary_context * bctx = (struct htp_binary_context *) data;
- struct htp_ops_context * octx = bctx->octx;
- htp_binary_preamble;
+DEFINE_ADD_ID_COPY(f16_f16, hvx_copy_f16_aa(dst, src, n))
+DEFINE_ADD_ID_COPY(f32_f32, hvx_copy_f32_aa(dst, src, n))
+DEFINE_ADD_ID_COPY(f16_f32, binary_scalar_add_f16_f32(dst, src, 0.0f, n))
+DEFINE_ADD_ID_COPY(f32_f16, binary_scalar_add_f32_f16(dst, src, 0.0f, n))
+
+#define DEFINE_COMPUTE_ADD_ID(NAME, ADD_FN, COPY_FN) \
+static void compute_add_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; \
+ ADD_FN(r_dst, r_src0, r_src1, ne00); \
+ } \
+}
+
+DEFINE_COMPUTE_ADD_ID(f16_f16_f16, binary_add_f16_f16_f16, add_id_copy_f16_f16)
+DEFINE_COMPUTE_ADD_ID(f32_f32_f32, hvx_add_f32_aaa, add_id_copy_f32_f32)
+DEFINE_COMPUTE_ADD_ID(f16_f16_f32, binary_add_f16_f16_f32, add_id_copy_f16_f32)
+DEFINE_COMPUTE_ADD_ID(f16_f32_f16, binary_add_f16_f32_f16, add_id_copy_f16_f16)
+DEFINE_COMPUTE_ADD_ID(f16_f32_f32, binary_add_f16_f32_f32, add_id_copy_f16_f32)
+DEFINE_COMPUTE_ADD_ID(f32_f16_f16, binary_add_f32_f16_f16, add_id_copy_f32_f16)
+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)
+
+struct binary_io_pipe_state {
+ const struct htp_binary_context * bctx;
+ dma_addr_t src0_data;
+ dma_addr_t dst_data;
+ const uint8_t * vtcm_src1;
+ const int32_t * vtcm_src2;
+ size_t s1_row_stride;
+ size_t s1_plane_stride;
+ size_t s1_vol_stride;
+ uint32_t ne00, ne01, ne02;
+ uint32_t ne10, ne11, ne12, ne13;
+ uint32_t nb01, nb02, nb03;
+ uint32_t nb1, nb2, nb3;
+ uint32_t ir;
+ uint32_t ir_end;
+};
- const uint32_t elem_size = (src0->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16);
- const size_t plane_stride = (size_t) ne12 * ne11 * elem_size;
- const size_t row_stride = (size_t) ne11 * elem_size;
+static bool binary_io_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ if (s->ir >= s->ir_end) {
+ return false;
+ }
+ const uint32_t block_size = calc_block_size(s->bctx, s->ir, s->ir_end, s->ne01, s->ne02);
+ task->row = s->ir;
+ task->off = 0;
+ task->len = block_size;
+ task->aux = 0;
+ s->ir += block_size;
+ return true;
+}
- const uint32_t row_size_bytes = bctx->row_size_bytes;
- const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
- const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
- if (start_row >= end_row) return;
+static void binary_io_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div);
+ const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01);
+ const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
+ const uint32_t i01 = rem - i02 * s->ne01;
+ const dma_addr_t src0_addr = s->src0_data + (size_t) i03 * s->nb03 + (size_t) i02 * s->nb02 + (size_t) i01 * s->nb01;
+ dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr),
+ bctx->src0_row_size_aligned, s->nb01, bctx->src0_row_size, task->len);
+}
- FARF(HIGH, "binary-scalar: %d/%d (%u:%u) row-size %u (%u)",
- ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned);
+static void binary_io_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div);
+ const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01);
+ const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
+ const uint32_t i01 = rem - i02 * s->ne01;
+ const dma_addr_t dst_addr = s->dst_data + (size_t) i03 * s->nb3 + (size_t) i02 * s->nb2 + (size_t) i01 * s->nb1;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->nb1, bctx->dst_row_size_aligned, bctx->dst_row_size, task->len);
+}
+static void binary_io_run(const htp_thread_t * th, unsigned int ith, struct htp_binary_context * bctx,
+ struct binary_io_pipe_state * s, dma_pipe_compute_io_fn compute) {
const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout;
uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx);
uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx);
- size_t src0_spad_half = layout->src0_spad_half_size;
- size_t dst_spad_half = layout->dst_spad_half_size;
- const void * s1_table = VTCM_LAYOUT_PTR(const void, bctx->vtcm_base, layout->off_src1);
+ void * in_buf[2] = { src0_spad_base, src0_spad_base + layout->src0_spad_half_size };
+ void * out_buf[2] = { dst_spad_base, dst_spad_base + layout->dst_spad_half_size };
- dma_queue * dma_q = th->dma_q;
- uint32_t ir_prefetch = start_row;
- int spad_idx = 0;
-
- for (int k = 0; k < 2 && ir_prefetch < end_row; k++) {
- uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t i03, i02, i01, rem;
- i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- rem = ir_prefetch - i03 * (ne02 * ne01);
- i02 = fastdiv(rem, &bctx->src0_dim1_div);
- i01 = rem - i02 * ne01;
-
- dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
+ dma_pipe_io_run(th->dma_q, th->trace, s, in_buf, out_buf,
+ binary_io_next_task, binary_io_push_in, compute, binary_io_push_out);
+}
- uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half;
- uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half;
+static void binary_scalar_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div);
+ const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01);
+ const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
+ const uint32_t i01 = rem - i02 * s->ne01;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes,
- current_block_size);
- ir_prefetch += current_block_size;
- spad_idx ^= 1;
- }
+ const uint32_t i13 = fastmodulo(i03, s->ne13, &bctx->src1_dim3_div);
+ const uint32_t i12 = fastmodulo(i02, s->ne12, &bctx->src1_dim2_div);
+ const uint32_t i11 = fastmodulo(i01, s->ne11, &bctx->src1_dim1_div);
+ const uint8_t * scalar_table = s->vtcm_src1 + i13 * s->s1_plane_stride + i12 * s->s1_row_stride;
- struct htp_thread_trace * tr = th->trace;
compute_scalar_t compute = (compute_scalar_t) bctx->compute;
+ compute((uint8_t *) out_spad, (const uint8_t *) in_spad, scalar_table, i11, s->ne11, task->len,
+ bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00);
+}
- for (uint32_t ir = start_row; ir < end_row; ) {
- uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02);
-
- uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- uint32_t i03, i02, i01, rem;
- i03 = fastdiv(ir, &bctx->src0_dim12_div);
- rem = ir - i03 * (ne02 * ne01);
- i02 = fastdiv(rem, &bctx->src0_dim1_div);
- i01 = rem - i02 * ne01;
-
- uint32_t i13 = fastmodulo(i03, ne13, &bctx->src1_dim3_div);
- uint32_t i12 = fastmodulo(i02, ne12, &bctx->src1_dim2_div);
- uint32_t i11 = fastmodulo(i01, ne11, &bctx->src1_dim1_div);
- const uint8_t * scalar_table = (const uint8_t *) s1_table +
- i13 * plane_stride + i12 * row_stride;
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- compute(d_spad, s0_spad, scalar_table, i11, ne11, current_block_size,
- bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+// 1. Scalar src1 in VTCM via DMA (ne10 == 1)
+static void binary_thread_scalar(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_binary_context * bctx = (struct htp_binary_context *) data;
+ struct htp_ops_context * octx = bctx->octx;
+ htp_binary_preamble;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes,
- current_block_size);
+ const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
+ const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
+ if (start_row >= end_row) return;
- if (ir_prefetch < end_row) {
- uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t p03, p02, p01, prem;
- p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- prem = ir_prefetch - p03 * (ne02 * ne01);
- p02 = fastdiv(prem, &bctx->src0_dim1_div);
- p01 = prem - p02 * ne01;
- dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes,
- next_block_size);
- ir_prefetch += next_block_size;
- }
- ir += current_block_size;
- }
+ FARF(HIGH, "binary-scalar: %d/%d (%u:%u) row-size %u (%u)",
+ ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned);
- dma_queue_flush(dma_q);
+ struct binary_io_pipe_state s = {
+ .bctx = bctx,
+ .src0_data = src0->data,
+ .dst_data = dst->data,
+ .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1),
+ .s1_row_stride = (size_t) ne11 * bctx->src1_table_elem_size,
+ .s1_plane_stride = (size_t) ne12 * ne11 * bctx->src1_table_elem_size,
+ .ne00 = ne00, .ne01 = ne01, .ne02 = ne02,
+ .ne10 = ne10, .ne11 = ne11, .ne12 = ne12, .ne13 = ne13,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1, .nb2 = nb2, .nb3 = nb3,
+ .ir = start_row,
+ .ir_end = end_row,
+ };
+
+ binary_io_run(th, ith, bctx, &s, binary_scalar_compute);
}
// 2. Vector Same Shape (ne1x == ne0x) or Simple Broadcast
@@ -363,7 +821,9 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
struct htp_ops_context * octx = bctx->octx;
htp_binary_preamble;
- const uint32_t row_size_bytes = bctx->row_size_bytes;
+ const uint32_t src0_row_size = bctx->src0_row_size;
+ const uint32_t src1_row_size = bctx->src1_row_size;
+ const uint32_t dst_row_size = bctx->dst_row_size;
const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
if (start_row >= end_row) return;
@@ -400,8 +860,8 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
uint8_t * s1_spad = src1_spad_base + spad_idx * src1_spad_half;
uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size);
+ dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, dst_row_size, 0);
+ dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, src0_row_size, current_block_size);
for (uint32_t s = 1; s < n_srcs; s++) {
const struct htp_tensor * src_s = octx->src[s];
uint32_t is3 = (src_s->ne[3] == 1) ? 0 : i03;
@@ -409,7 +869,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
uint32_t is1 = (src_s->ne[1] == 1) ? 0 : i01;
dma_addr_t s_curr = src_s->data + is3 * src_s->nb[3] + is2 * src_s->nb[2] + is1 * src_s->nb[1];
uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_spad_half;
- dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), bctx->src1_row_size_aligned, src_s->nb[1], row_size_bytes, current_block_size);
+ dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), bctx->src1_row_size_aligned, src_s->nb[1], src1_row_size, current_block_size);
}
ir_prefetch += current_block_size;
spad_idx ^= 1;
@@ -440,7 +900,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
i02 = fastdiv(rem, &bctx->src0_dim1_div);
i01 = rem - i02 * ne01;
dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size);
+ dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, dst_row_size, current_block_size);
if (ir_prefetch < end_row) {
uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
@@ -451,7 +911,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
p01 = prem - p02 * ne01;
dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size);
+ dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, src0_row_size, next_block_size);
for (uint32_t s = 1; s < n_srcs; s++) {
const struct htp_tensor * src_s = octx->src[s];
@@ -460,7 +920,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
uint32_t ps1 = (src_s->ne[1] == 1) ? 0 : p01;
dma_addr_t s_next = src_s->data + ps3 * src_s->nb[3] + ps2 * src_s->nb[2] + ps1 * src_s->nb[1];
uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_spad_half;
- dma_queue_push(dma_q, dma_make_data(s_spad, s_next), bctx->src1_row_size_aligned, src_s->nb[1], row_size_bytes, next_block_size);
+ dma_queue_push(dma_q, dma_make_data(s_spad, s_next), bctx->src1_row_size_aligned, src_s->nb[1], src1_row_size, next_block_size);
}
ir_prefetch += next_block_size;
@@ -471,13 +931,20 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in
dma_queue_flush(dma_q);
}
+static void binary_row_bcast_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ compute_row_bcast_t compute = (compute_row_bcast_t) bctx->compute;
+ compute((uint8_t *) out_spad, (const uint8_t *) in_spad, s->vtcm_src1, task->len,
+ bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00);
+}
+
// 3. Row Broadcast (ne11 == 1, ne12 == 1, single row src1)
static void binary_thread_vector_row_broadcast(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_binary_context * bctx = (struct htp_binary_context *) data;
struct htp_ops_context * octx = bctx->octx;
htp_binary_preamble;
- const uint32_t row_size_bytes = bctx->row_size_bytes;
const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
if (start_row >= end_row) return;
@@ -485,73 +952,36 @@ static void binary_thread_vector_row_broadcast(const htp_thread_t * th, unsigned
FARF(HIGH, "binary-row-bcast: %d/%d (%u:%u) row-size %u (%u)",
ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned);
- const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout;
- uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx);
- uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx);
-
- size_t src0_spad_half = layout->src0_spad_half_size;
- size_t dst_spad_half = layout->dst_spad_half_size;
-
- dma_queue * dma_q = th->dma_q;
- uint32_t ir_prefetch = start_row;
- int spad_idx = 0;
-
- void * s1_ptr = VTCM_LAYOUT_PTR(void, bctx->vtcm_base, layout->off_src1);
-
- for (int k = 0; k < 2 && ir_prefetch < end_row; k++) {
- uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- uint32_t rem = ir_prefetch - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
-
- uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half;
- uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half;
-
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size);
- ir_prefetch += current_block_size;
- spad_idx ^= 1;
- }
-
- struct htp_thread_trace * tr = th->trace;
- compute_row_bcast_t compute = (compute_row_bcast_t) bctx->compute;
-
- for (uint32_t ir = start_row; ir < end_row; ) {
- uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02);
- uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
+ struct binary_io_pipe_state s = {
+ .bctx = bctx,
+ .src0_data = src0->data,
+ .dst_data = dst->data,
+ .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1),
+ .ne00 = ne00, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1, .nb2 = nb2, .nb3 = nb3,
+ .ir = start_row,
+ .ir_end = end_row,
+ };
+
+ binary_io_run(th, ith, bctx, &s, binary_row_bcast_compute);
+}
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- compute(d_spad, s0_spad, (const uint8_t *)s1_ptr, current_block_size,
- bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+static void binary_complex_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div);
+ const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01);
+ const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
+ const uint32_t i01 = rem - i02 * s->ne01;
- uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div);
- uint32_t rem = ir - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size);
+ const uint32_t i13 = fastmodulo(i03, s->ne13, &bctx->src1_dim3_div);
+ const uint32_t i12 = fastmodulo(i02, s->ne12, &bctx->src1_dim2_div);
+ const uint8_t * src1_plane = s->vtcm_src1 + i13 * s->s1_vol_stride + i12 * s->s1_plane_stride;
- if (ir_prefetch < end_row) {
- uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t p03, p02, p01, prem;
- p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- prem = ir_prefetch - p03 * (ne02 * ne01);
- p02 = fastdiv(prem, &bctx->src0_dim1_div);
- p01 = prem - p02 * ne01;
- dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size);
- ir_prefetch += next_block_size;
- }
- ir += current_block_size;
- }
-
- dma_queue_flush(dma_q);
+ compute_complex_t compute = (compute_complex_t) bctx->compute;
+ compute((uint8_t *) out_spad, (const uint8_t *) in_spad, src1_plane, i01, s->ne11, &bctx->src1_dim1_div,
+ s->s1_row_stride, task->len, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00);
}
// 4. Vector Complex (ne10 == ne00, complex broadcast)
@@ -560,7 +990,6 @@ static void binary_thread_vector_complex(const htp_thread_t * th, unsigned int n
struct htp_ops_context * octx = bctx->octx;
htp_binary_preamble;
- const uint32_t row_size_bytes = bctx->row_size_bytes;
const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
if (start_row >= end_row) return;
@@ -568,81 +997,43 @@ static void binary_thread_vector_complex(const htp_thread_t * th, unsigned int n
FARF(HIGH, "binary-complex: %d/%d (%u:%u) row-size %u (%u)",
ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned);
- const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout;
- uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx);
- uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx);
- size_t src0_spad_half = layout->src0_spad_half_size;
- size_t dst_spad_half = layout->dst_spad_half_size;
- const uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, layout->off_src1);
-
- const uint32_t elem_size = (src0->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16);
- const size_t vtcm_row_stride = (size_t) ne10 * elem_size;
+ const size_t vtcm_row_stride = (size_t) ne10 * bctx->src1_elem_size;
const size_t vtcm_plane_stride = (size_t) ne11 * vtcm_row_stride;
- const size_t vtcm_vol_stride = (size_t) ne12 * vtcm_plane_stride;
-
- dma_queue * dma_q = th->dma_q;
- uint32_t ir_prefetch = start_row;
- int spad_idx = 0;
- for (int k = 0; k < 2 && ir_prefetch < end_row; k++) {
- uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- uint32_t rem = ir_prefetch - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
-
- uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half;
- uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half;
-
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size);
- ir_prefetch += current_block_size;
- spad_idx ^= 1;
- }
-
- struct htp_thread_trace * tr = th->trace;
- compute_complex_t compute = (compute_complex_t) bctx->compute;
-
- for (uint32_t ir = start_row; ir < end_row; ) {
- uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02);
- uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div);
- uint32_t rem = ir - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- uint32_t i13 = fastmodulo(i03, ne13, &bctx->src1_dim3_div);
- uint32_t i12 = fastmodulo(i02, ne12, &bctx->src1_dim2_div);
- const uint8_t * src1_plane = vtcm_src1 + i13 * vtcm_vol_stride + i12 * vtcm_plane_stride;
+ struct binary_io_pipe_state s = {
+ .bctx = bctx,
+ .src0_data = src0->data,
+ .dst_data = dst->data,
+ .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1),
+ .s1_row_stride = vtcm_row_stride,
+ .s1_plane_stride = vtcm_plane_stride,
+ .s1_vol_stride = (size_t) ne12 * vtcm_plane_stride,
+ .ne00 = ne00, .ne01 = ne01, .ne02 = ne02,
+ .ne10 = ne10, .ne11 = ne11, .ne12 = ne12, .ne13 = ne13,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1, .nb2 = nb2, .nb3 = nb3,
+ .ir = start_row,
+ .ir_end = end_row,
+ };
+
+ binary_io_run(th, ith, bctx, &s, binary_complex_compute);
+}
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- compute(d_spad, s0_spad, src1_plane, i01, ne11, &bctx->src1_dim1_div, vtcm_row_stride,
- current_block_size, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+static void binary_repeat_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div);
+ const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01);
+ const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
+ const uint32_t i01 = rem - i02 * s->ne01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size);
+ const uint32_t i13 = fastmodulo(i03, s->ne13, &bctx->src1_dim3_div);
+ const uint32_t i12 = fastmodulo(i02, s->ne12, &bctx->src1_dim2_div);
+ const uint8_t * src1_plane = s->vtcm_src1 + i13 * s->s1_vol_stride + i12 * s->s1_plane_stride;
- if (ir_prefetch < end_row) {
- uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t p03, p02, p01, prem;
- p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- prem = ir_prefetch - p03 * (ne02 * ne01);
- p02 = fastdiv(prem, &bctx->src0_dim1_div);
- p01 = prem - p02 * ne01;
- dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size);
- ir_prefetch += next_block_size;
- }
- ir += current_block_size;
- }
-
- dma_queue_flush(dma_q);
+ compute_repeat_t compute = (compute_repeat_t) bctx->compute;
+ compute((uint8_t *) out_spad, (const uint8_t *) in_spad, src1_plane, i01, s->ne11, &bctx->src1_dim1_div,
+ s->s1_row_stride, task->len, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00, s->ne10);
}
// 5. Element Repeat (ne10 != ne00)
@@ -651,187 +1042,75 @@ static void binary_thread_element_repeat(const htp_thread_t * th, unsigned int n
struct htp_ops_context * octx = bctx->octx;
htp_binary_preamble;
- const uint32_t row_size_bytes = bctx->row_size_bytes;
const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
if (start_row >= end_row) return;
- const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout;
- uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx);
- uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx);
- size_t src0_spad_half = layout->src0_spad_half_size;
- size_t dst_spad_half = layout->dst_spad_half_size;
- const uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, layout->off_src1);
-
- const uint32_t elem_size = (src0->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16);
- const size_t vtcm_row_stride = (size_t) ne10 * elem_size;
- const size_t vtcm_plane_stride = (size_t) ne11 * vtcm_row_stride;
- const size_t vtcm_vol_stride = (size_t) ne12 * vtcm_plane_stride;
-
FARF(HIGH, "binary-repeat: %d/%d (%u:%u) row-size %u (%u)",
ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned);
- dma_queue * dma_q = th->dma_q;
- uint32_t ir_prefetch = start_row;
- int spad_idx = 0;
-
- for (int k = 0; k < 2 && ir_prefetch < end_row; k++) {
- uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- uint32_t rem = ir_prefetch - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
-
- uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half;
- uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half;
-
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size);
- ir_prefetch += current_block_size;
- spad_idx ^= 1;
- }
-
- struct htp_thread_trace * tr = th->trace;
- compute_repeat_t compute = (compute_repeat_t) bctx->compute;
-
- for (uint32_t ir = start_row; ir < end_row; ) {
- uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02);
- uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div);
- uint32_t rem = ir - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- uint32_t i13 = fastmodulo(i03, ne13, &bctx->src1_dim3_div);
- uint32_t i12 = fastmodulo(i02, ne12, &bctx->src1_dim2_div);
- const uint8_t * src1_plane = vtcm_src1 + i13 * vtcm_vol_stride + i12 * vtcm_plane_stride;
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- compute(d_spad, s0_spad, src1_plane, i01, ne11, &bctx->src1_dim1_div, vtcm_row_stride,
- current_block_size, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00, ne10);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
-
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size);
+ const size_t vtcm_row_stride = (size_t) ne10 * bctx->src1_elem_size;
+ const size_t vtcm_plane_stride = (size_t) ne11 * vtcm_row_stride;
- if (ir_prefetch < end_row) {
- uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t p03, p02, p01, prem;
- p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- prem = ir_prefetch - p03 * (ne02 * ne01);
- p02 = fastdiv(prem, &bctx->src0_dim1_div);
- p01 = prem - p02 * ne01;
- dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size);
- ir_prefetch += next_block_size;
- }
- ir += current_block_size;
- }
+ struct binary_io_pipe_state s = {
+ .bctx = bctx,
+ .src0_data = src0->data,
+ .dst_data = dst->data,
+ .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1),
+ .s1_row_stride = vtcm_row_stride,
+ .s1_plane_stride = vtcm_plane_stride,
+ .s1_vol_stride = (size_t) ne12 * vtcm_plane_stride,
+ .ne00 = ne00, .ne01 = ne01, .ne02 = ne02,
+ .ne10 = ne10, .ne11 = ne11, .ne12 = ne12, .ne13 = ne13,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1, .nb2 = nb2, .nb3 = nb3,
+ .ir = start_row,
+ .ir_end = end_row,
+ };
+
+ binary_io_run(th, ith, bctx, &s, binary_repeat_compute);
+}
- dma_queue_flush(dma_q);
+static void binary_add_id_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx;
+ const struct htp_binary_context * bctx = s->bctx;
+ const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div);
+ const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01);
+ const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
+ const uint32_t i01 = rem - i02 * s->ne01;
+
+ compute_add_id_t compute = (compute_add_id_t) bctx->compute;
+ compute((uint8_t *) out_spad, (const uint8_t *) in_spad, s->vtcm_src1, s->vtcm_src2,
+ i01, i02, s->ne01, bctx->src1_row_size_aligned,
+ task->len, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00);
}
// 6. ADD_ID (src1 gathered via src2 indices)
-static void binary_thread_add_id_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void binary_thread_add_id(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct htp_binary_context * bctx = (struct htp_binary_context *) data;
struct htp_ops_context * octx = bctx->octx;
-
const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * src1 = octx->src[1];
const struct htp_tensor * dst = octx->dst;
- const uint32_t ne00 = src0->ne[0];
- const uint32_t ne01 = src0->ne[1];
- const uint32_t ne02 = src0->ne[2];
- const uint32_t ne03 = src0->ne[3];
-
- const uint32_t nb01 = src0->nb[1];
- const uint32_t nb02 = src0->nb[2];
- const uint32_t nb03 = src0->nb[3];
- const uint32_t src1_stride = bctx->src1_row_size_aligned;
-
- const uint32_t nb1 = dst->nb[1];
- const uint32_t nb2 = dst->nb[2];
- const uint32_t nb3 = dst->nb[3];
-
- const uint32_t row_size_bytes = bctx->row_size_bytes;
const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith;
const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows);
if (start_row >= end_row) return;
- const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout;
- uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx);
- uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx);
- const uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, layout->off_src1);
- const int32_t * vtcm_src2 = VTCM_LAYOUT_PTR(const int32_t, bctx->vtcm_base, layout->off_src2);
- size_t src0_spad_half = layout->src0_spad_half_size;
- size_t dst_spad_half = layout->dst_spad_half_size;
-
- dma_queue * dma_q = th->dma_q;
- uint32_t ir_prefetch = start_row;
- int spad_idx = 0;
-
- for (int k = 0; k < 2 && ir_prefetch < end_row; k++) {
- uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- uint32_t rem = ir_prefetch - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01;
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
-
- uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half;
- uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half;
-
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size);
- ir_prefetch += current_block_size;
- spad_idx ^= 1;
- }
-
- struct htp_thread_trace * tr = th->trace;
-
- for (uint32_t ir = start_row; ir < end_row; ) {
- uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02);
- uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div);
- uint32_t rem = ir - i03 * (ne02 * ne01);
- uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div);
- uint32_t i01 = rem - i02 * ne01;
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- compute_add_id_t compute = (compute_add_id_t) bctx->compute;
- compute(d_spad, s0_spad, vtcm_src1, vtcm_src2,
- i01, i02, ne01, src1_stride,
- current_block_size, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
-
- dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size);
-
- if (ir_prefetch < end_row) {
- uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02);
- uint32_t p03, p02, p01, prem;
- p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div);
- prem = ir_prefetch - p03 * (ne02 * ne01);
- p02 = fastdiv(prem, &bctx->src0_dim1_div);
- p01 = prem - p02 * ne01;
- dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size);
- ir_prefetch += next_block_size;
- }
- ir += current_block_size;
- }
-
- dma_queue_flush(dma_q);
+ struct binary_io_pipe_state s = {
+ .bctx = bctx,
+ .src0_data = src0->data,
+ .dst_data = dst->data,
+ .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1),
+ .vtcm_src2 = VTCM_LAYOUT_PTR(const int32_t, bctx->vtcm_base, bctx->vtcm_layout.off_src2),
+ .ne00 = src0->ne[0], .ne01 = src0->ne[1], .ne02 = src0->ne[2],
+ .nb01 = src0->nb[1], .nb02 = src0->nb[2], .nb03 = src0->nb[3],
+ .nb1 = dst->nb[1], .nb2 = dst->nb[2], .nb3 = dst->nb[3],
+ .ir = start_row,
+ .ir_end = end_row,
+ };
+
+ binary_io_run(th, ith, bctx, &s, binary_add_id_compute);
}
static inline void hvx_div_scalar_f32(uint8_t * restrict dst, const uint8_t * restrict src, const float val, const uint32_t num_elems) {
@@ -842,6 +1121,81 @@ static inline void hvx_div_scalar_f16(uint8_t * restrict dst, const uint8_t * re
hvx_div_scalar_f16_aa(dst, src, val, num_elems);
}
+static void binary_expand_f16_to_f32(uint8_t * data, uint32_t n) {
+ uint32_t end = n;
+ while (end > 0) {
+ const uint32_t start = (end - 1) & ~63u;
+ const uint32_t count = end - start;
+ HVX_VectorPair pair = hvx_vec_f16_to_f32(hvx_vmemu(data + (size_t) start * sizeof(_Float16)));
+ hvx_vec_store_u(data + (size_t) start * sizeof(float), MIN(count, 32) * sizeof(float), Q6_V_lo_W(pair));
+ if (count > 32) {
+ hvx_vec_store_u(data + (size_t) (start + 32) * sizeof(float), (count - 32) * sizeof(float), Q6_V_hi_W(pair));
+ }
+ end = start;
+ }
+}
+
+#define SELECT_MIXED_COMPUTE(PREFIX, type_key, out) \
+ do { \
+ switch (type_key) { \
+ case 1: \
+ switch (octx->op) { \
+ case HTP_OP_ADD: out = PREFIX##_add_f16_f16_f32; break; \
+ case HTP_OP_SUB: out = PREFIX##_sub_f16_f16_f32; break; \
+ case HTP_OP_MUL: out = PREFIX##_mul_f16_f16_f32; break; \
+ case HTP_OP_DIV: out = PREFIX##_div_f16_f16_f32; break; \
+ default: break; \
+ } \
+ break; \
+ case 2: \
+ switch (octx->op) { \
+ case HTP_OP_ADD: out = PREFIX##_add_f16_f32_f16; break; \
+ case HTP_OP_SUB: out = PREFIX##_sub_f16_f32_f16; break; \
+ case HTP_OP_MUL: out = PREFIX##_mul_f16_f32_f16; break; \
+ case HTP_OP_DIV: out = PREFIX##_div_f16_f32_f16; break; \
+ default: break; \
+ } \
+ break; \
+ case 3: \
+ switch (octx->op) { \
+ case HTP_OP_ADD: out = PREFIX##_add_f16_f32_f32; break; \
+ case HTP_OP_SUB: out = PREFIX##_sub_f16_f32_f32; break; \
+ case HTP_OP_MUL: out = PREFIX##_mul_f16_f32_f32; break; \
+ case HTP_OP_DIV: out = PREFIX##_div_f16_f32_f32; break; \
+ default: break; \
+ } \
+ break; \
+ case 4: \
+ switch (octx->op) { \
+ case HTP_OP_ADD: out = PREFIX##_add_f32_f16_f16; break; \
+ case HTP_OP_SUB: out = PREFIX##_sub_f32_f16_f16; break; \
+ case HTP_OP_MUL: out = PREFIX##_mul_f32_f16_f16; break; \
+ case HTP_OP_DIV: out = PREFIX##_div_f32_f16_f16; break; \
+ default: break; \
+ } \
+ break; \
+ case 5: \
+ switch (octx->op) { \
+ case HTP_OP_ADD: out = PREFIX##_add_f32_f16_f32; break; \
+ case HTP_OP_SUB: out = PREFIX##_sub_f32_f16_f32; break; \
+ case HTP_OP_MUL: out = PREFIX##_mul_f32_f16_f32; break; \
+ case HTP_OP_DIV: out = PREFIX##_div_f32_f16_f32; break; \
+ default: break; \
+ } \
+ break; \
+ case 6: \
+ switch (octx->op) { \
+ case HTP_OP_ADD: out = PREFIX##_add_f32_f32_f16; break; \
+ case HTP_OP_SUB: out = PREFIX##_sub_f32_f32_f16; break; \
+ case HTP_OP_MUL: out = PREFIX##_mul_f32_f32_f16; break; \
+ case HTP_OP_DIV: out = PREFIX##_div_f32_f32_f16; break; \
+ default: break; \
+ } \
+ break; \
+ default: break; \
+ } \
+ } while (0)
+
typedef void (*compute_binary_chunked_t)(
uint8_t * restrict dst,
const uint8_t * restrict src0,
@@ -873,6 +1227,9 @@ struct binary_chunked_context {
uint32_t chunks_per_hvx;
uint32_t total_chunks;
uint32_t n_srcs;
+ uint32_t src0_elem_size;
+ uint32_t src1_elem_size;
+ uint32_t dst_elem_size;
bool is_scalar;
float scalar_f32;
_Float16 scalar_f16;
@@ -894,10 +1251,10 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns
return;
}
- const uint32_t src0_type = src0->type;
- const size_t elem_size = (src0_type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16);
const uint32_t chunk_size = ctx->chunk_size;
- const size_t chunk_bytes = ctx->vtcm_layout.src0_spad_half_size;
+ const size_t src0_chunk_bytes = ctx->vtcm_layout.src0_spad_half_size;
+ const size_t src1_chunk_bytes = ctx->vtcm_layout.src1_spad_half_size;
+ const size_t dst_chunk_bytes = ctx->vtcm_layout.dst_spad_half_size;
FARF(HIGH, "binary-chunked: %d/%d (%u:%u) chunks %u elems %u",
ith, nth, start_chunk, end_chunk, ctx->total_chunks, ctx->nelem);
@@ -916,22 +1273,24 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns
const uint32_t c_start = ctx->elem_start + prefetch_chunk * chunk_size;
const uint32_t c_end = MIN(c_start + chunk_size, ctx->elem_start + ctx->nelem);
const uint32_t cur_elems = c_end - c_start;
- const uint32_t cur_bytes = cur_elems * elem_size;
+ const uint32_t src0_bytes = cur_elems * ctx->src0_elem_size;
+ const uint32_t src1_bytes = cur_elems * ctx->src1_elem_size;
+ const uint32_t dst_bytes = cur_elems * ctx->dst_elem_size;
- dma_addr_t s0_curr = src0->data + (size_t) c_start * elem_size;
- dma_addr_t d_curr = dst->data + (size_t) c_start * elem_size;
+ dma_addr_t s0_curr = src0->data + (size_t) c_start * ctx->src0_elem_size;
+ dma_addr_t d_curr = dst->data + (size_t) c_start * ctx->dst_elem_size;
- uint8_t * s0_spad = src0_spad_base + spad_idx * chunk_bytes;
- uint8_t * d_spad = dst_spad_base + spad_idx * chunk_bytes;
+ uint8_t * s0_spad = src0_spad_base + spad_idx * src0_chunk_bytes;
+ uint8_t * d_spad = dst_spad_base + spad_idx * dst_chunk_bytes;
- dma_queue_push(dma_q, dma_make_data(d_curr, d_spad), chunk_bytes, chunk_bytes, cur_bytes, 0);
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_curr), chunk_bytes, chunk_bytes, cur_bytes, 1);
+ dma_queue_push(dma_q, dma_make_data(d_curr, d_spad), dst_chunk_bytes, dst_chunk_bytes, dst_bytes, 0);
+ dma_queue_push(dma_q, dma_make_data(s0_spad, s0_curr), src0_chunk_bytes, src0_chunk_bytes, src0_bytes, 1);
if (!ctx->is_scalar) {
- uint8_t * s1_spad = src1_spad_base + spad_idx * chunk_bytes;
+ uint8_t * s1_spad = src1_spad_base + spad_idx * src1_chunk_bytes;
for (uint32_t s = 1; s < n_srcs; s++) {
- dma_addr_t s_curr = octx->src[s]->data + (size_t) c_start * elem_size;
- uint8_t * s_spad = s1_spad + (s - 1) * 2 * chunk_bytes;
- dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), chunk_bytes, chunk_bytes, cur_bytes, 1);
+ dma_addr_t s_curr = octx->src[s]->data + (size_t) c_start * ctx->src1_elem_size;
+ uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_chunk_bytes;
+ dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), src1_chunk_bytes, src1_chunk_bytes, src1_bytes, 1);
}
}
@@ -945,7 +1304,7 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns
const uint32_t c_start = ctx->elem_start + c * chunk_size;
const uint32_t c_end = MIN(c_start + chunk_size, ctx->elem_start + ctx->nelem);
const uint32_t cur_elems = c_end - c_start;
- const uint32_t cur_bytes = cur_elems * elem_size;
+ const uint32_t dst_bytes = cur_elems * ctx->dst_elem_size;
uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src;
uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
@@ -953,7 +1312,7 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) c);
if (ctx->is_scalar) {
- if (src0_type == HTP_TYPE_F32) {
+ if (ctx->compute_scalar_f32) {
ctx->compute_scalar_f32(d_spad, s0_spad, ctx->scalar_f32, cur_elems);
} else {
ctx->compute_scalar_f16(d_spad, s0_spad, ctx->scalar_f16, cur_elems);
@@ -967,22 +1326,23 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) c);
- dma_addr_t dst_curr = dst->data + (size_t) c_start * elem_size;
- dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), chunk_bytes, chunk_bytes, cur_bytes, 1);
+ dma_addr_t dst_curr = dst->data + (size_t) c_start * ctx->dst_elem_size;
+ dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), dst_chunk_bytes, dst_chunk_bytes, dst_bytes, 1);
if (prefetch_chunk < end_chunk) {
const uint32_t pc_start = ctx->elem_start + prefetch_chunk * chunk_size;
const uint32_t pc_end = MIN(pc_start + chunk_size, ctx->elem_start + ctx->nelem);
const uint32_t p_elems = pc_end - pc_start;
- const uint32_t p_bytes = p_elems * elem_size;
+ const uint32_t p_src0_bytes = p_elems * ctx->src0_elem_size;
+ const uint32_t p_src1_bytes = p_elems * ctx->src1_elem_size;
- dma_addr_t s0_next = src0->data + (size_t) pc_start * elem_size;
- dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), chunk_bytes, chunk_bytes, p_bytes, 1);
+ dma_addr_t s0_next = src0->data + (size_t) pc_start * ctx->src0_elem_size;
+ dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), src0_chunk_bytes, src0_chunk_bytes, p_src0_bytes, 1);
if (!ctx->is_scalar) {
for (uint32_t s = 1; s < n_srcs; s++) {
- dma_addr_t s_next = octx->src[s]->data + (size_t) pc_start * elem_size;
- uint8_t * s_spad = s1_spad + (s - 1) * 2 * chunk_bytes;
- dma_queue_push(dma_q, dma_make_data(s_spad, s_next), chunk_bytes, chunk_bytes, p_bytes, 1);
+ dma_addr_t s_next = octx->src[s]->data + (size_t) pc_start * ctx->src1_elem_size;
+ uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_chunk_bytes;
+ dma_queue_push(dma_q, dma_make_data(s_spad, s_next), src1_chunk_bytes, src1_chunk_bytes, p_src1_bytes, 1);
}
}
@@ -1003,11 +1363,19 @@ static int execute_op_binary(struct htp_ops_context * octx) {
const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
// Use packed row sizes for VTCM allocation and alignment
- const uint32_t src0_type = octx->src[0]->type;
- const size_t elem_size = (src0_type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16);
- const size_t src0_row_size = src0->ne[0] * elem_size;
- const size_t src1_row_size = src1->ne[0] * elem_size;
- const size_t dst_row_size = dst->ne[0] * elem_size;
+ const uint32_t src0_type = src0->type;
+ const uint32_t src1_type = src1->type;
+ const uint32_t dst_type = dst->type;
+ const uint32_t src0_elem_size = kparams->src0_elem_size;
+ const uint32_t src1_elem_size = kparams->src1_elem_size;
+ const uint32_t dst_elem_size = kparams->dst_elem_size;
+ const size_t src0_row_size = src0->ne[0] * src0_elem_size;
+ const size_t src1_row_size = src1->ne[0] * src1_elem_size;
+ const size_t dst_row_size = dst->ne[0] * dst_elem_size;
+ const uint32_t type_key = (src0_type == HTP_TYPE_F32 ? 4 : 0) |
+ (src1_type == HTP_TYPE_F32 ? 2 : 0) |
+ (dst_type == HTP_TYPE_F32 ? 1 : 0);
+ 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;
@@ -1017,7 +1385,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
compute_binary_scalar_chunked_f16_t compute_scalar_f16 = NULL;
if (is_scalar) {
- if (src0_type == HTP_TYPE_F32) {
+ if (type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute_scalar_f32 = hvx_add_scalar_f32; break;
case HTP_OP_SUB: compute_scalar_f32 = hvx_sub_scalar_f32; break;
@@ -1025,7 +1393,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_scalar_f32 = hvx_div_scalar_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute_scalar_f16 = hvx_add_scalar_f16; break;
case HTP_OP_SUB: compute_scalar_f16 = hvx_sub_scalar_f16; break;
@@ -1033,12 +1401,44 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_scalar_f16 = hvx_div_scalar_f16; break;
default: break;
}
+ } else if (src0_type == HTP_TYPE_F16 && dst_type == HTP_TYPE_F16) {
+ switch (octx->op) {
+ case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f16_f16; break;
+ case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f16_f16; break;
+ case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f16_f16; break;
+ case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f16_f16; break;
+ default: break;
+ }
+ } else if (src0_type == HTP_TYPE_F16) {
+ switch (octx->op) {
+ case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f16_f32; break;
+ case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f16_f32; break;
+ case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f16_f32; break;
+ case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f16_f32; break;
+ default: break;
+ }
+ } else if (dst_type == HTP_TYPE_F16) {
+ switch (octx->op) {
+ case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f32_f16; break;
+ case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f32_f16; break;
+ case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f32_f16; break;
+ case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f32_f16; break;
+ default: break;
+ }
+ } else {
+ switch (octx->op) {
+ case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f32_f32; break;
+ case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f32_f32; break;
+ case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f32_f32; break;
+ case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f32_f32; break;
+ default: break;
+ }
}
if (!compute_scalar_f32 && !compute_scalar_f16) {
return HTP_STATUS_NO_SUPPORT;
}
} else {
- if (src0_type == HTP_TYPE_F32) {
+ if (type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute = hvx_add_f32; break;
case HTP_OP_SUB: compute = hvx_sub_f32; break;
@@ -1046,7 +1446,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute = hvx_div_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute = hvx_add_f16; break;
case HTP_OP_SUB: compute = hvx_sub_f16; break;
@@ -1054,6 +1454,8 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute = hvx_div_f16; break;
default: break;
}
+ } else {
+ SELECT_MIXED_COMPUTE(binary, type_key, compute);
}
if (!compute) {
return HTP_STATUS_NO_SUPPORT;
@@ -1067,18 +1469,14 @@ static int execute_op_binary(struct htp_ops_context * octx) {
uint32_t elem_start = 0;
uint32_t nelem = total_elems;
- const uint32_t elems_per_line = (src0_type == HTP_TYPE_F32) ? 32 : 64;
+ const uint32_t elems_per_line = 128 / dst_elem_size;
if (octx->ctx->mdev.count > 1) {
- bool can_split = htp_tensor_mdev_data_aligned(dst) &&
- htp_tensor_mdev_data_aligned(src0) &&
- (is_scalar || htp_tensor_mdev_data_aligned(src1)) &&
- htp_tensor_is_contiguous(dst, elem_size) &&
- htp_tensor_is_contiguous(src0, elem_size) &&
- (is_scalar || htp_tensor_is_contiguous(src1, elem_size));
+ bool can_split = htp_tensor_is_contiguous(dst, dst_elem_size) &&
+ htp_tensor_is_contiguous(src0, src0_elem_size) &&
+ (is_scalar || htp_tensor_is_contiguous(src1, src1_elem_size));
for (uint32_t s = 2; can_split && s < n_srcs; s++) {
- can_split = htp_tensor_mdev_data_aligned(octx->src[s]) &&
- htp_tensor_is_contiguous(octx->src[s], elem_size);
+ can_split = htp_tensor_is_contiguous(octx->src[s], src1_elem_size);
}
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
total_elems, can_split ? elems_per_line : 0,
@@ -1111,13 +1509,15 @@ static int execute_op_binary(struct htp_ops_context * octx) {
if (is_scalar) {
uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, vtcm_layout.off_src1);
dma_queue * dma_q = octx->ctx->dma[0];
- dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), 128, 0, elem_size, 1);
+ dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), 128, 0, src1_elem_size, 1);
dma_queue_pop(dma_q);
- if (src0_type == HTP_TYPE_F32) {
- scalar_f32 = ((const float *) vtcm_src1)[0];
+ const HVX_Vector v_src1 = hvx_vmem(vtcm_src1);
+ if (type_key != 0) {
+ const HVX_Vector v_f32 = (src1_type == HTP_TYPE_F16) ? Q6_V_lo_W(hvx_vec_f16_to_f32(v_src1)) : v_src1;
+ scalar_f32 = hvx_vec_get_f32(v_f32);
} else {
- scalar_f16 = ((const _Float16 *) vtcm_src1)[0];
+ scalar_f16 = hvx_vec_get_f16(v_src1);
}
}
@@ -1131,6 +1531,9 @@ static int execute_op_binary(struct htp_ops_context * octx) {
.chunks_per_hvx = chunks_per_hvx,
.total_chunks = total_chunks,
.n_srcs = n_srcs,
+ .src0_elem_size = src0_elem_size,
+ .src1_elem_size = src1_elem_size,
+ .dst_elem_size = dst_elem_size,
.is_scalar = is_scalar,
.scalar_f32 = scalar_f32,
.scalar_f16 = scalar_f16,
@@ -1147,9 +1550,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) elem_size, (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk,
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1,
octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
@@ -1182,7 +1583,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
switch (kparams->kernel_type) {
case HTP_BINARY_KERNEL_SAME_SHAPE:
worker_func = binary_thread_vector_same_shape;
- if (src0_type == HTP_TYPE_F32) {
+ if (type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_same_shape_add_f32; break;
case HTP_OP_SUB: compute_func = compute_same_shape_sub_f32; break;
@@ -1190,7 +1591,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_same_shape_div_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_same_shape_add_f16; break;
case HTP_OP_SUB: compute_func = compute_same_shape_sub_f16; break;
@@ -1198,11 +1599,13 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_same_shape_div_f16; break;
default: break;
}
+ } else {
+ SELECT_MIXED_COMPUTE(compute_same_shape, type_key, compute_func);
}
break;
case HTP_BINARY_KERNEL_ROW_BCAST:
worker_func = binary_thread_vector_row_broadcast;
- if (src0_type == HTP_TYPE_F32) {
+ if (table_type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_row_bcast_add_f32; break;
case HTP_OP_SUB: compute_func = compute_row_bcast_sub_f32; break;
@@ -1210,7 +1613,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_row_bcast_div_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_row_bcast_add_f16; break;
case HTP_OP_SUB: compute_func = compute_row_bcast_sub_f16; break;
@@ -1218,11 +1621,13 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_row_bcast_div_f16; break;
default: break;
}
+ } else {
+ SELECT_MIXED_COMPUTE(compute_row_bcast, table_type_key, compute_func);
}
break;
case HTP_BINARY_KERNEL_SCALAR:
worker_func = binary_thread_scalar;
- if (src0_type == HTP_TYPE_F32) {
+ if (table_type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_scalar_add_f32; break;
case HTP_OP_SUB: compute_func = compute_scalar_sub_f32; break;
@@ -1230,7 +1635,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_scalar_div_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_scalar_add_f16; break;
case HTP_OP_SUB: compute_func = compute_scalar_sub_f16; break;
@@ -1238,11 +1643,13 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_scalar_div_f16; break;
default: break;
}
+ } else {
+ SELECT_MIXED_COMPUTE(compute_scalar, table_type_key, compute_func);
}
break;
case HTP_BINARY_KERNEL_COMPLEX:
worker_func = binary_thread_vector_complex;
- if (src0_type == HTP_TYPE_F32) {
+ if (type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_complex_add_f32; break;
case HTP_OP_SUB: compute_func = compute_complex_sub_f32; break;
@@ -1250,7 +1657,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_complex_div_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_complex_add_f16; break;
case HTP_OP_SUB: compute_func = compute_complex_sub_f16; break;
@@ -1258,11 +1665,13 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_complex_div_f16; break;
default: break;
}
+ } else {
+ SELECT_MIXED_COMPUTE(compute_complex, type_key, compute_func);
}
break;
case HTP_BINARY_KERNEL_REPEAT:
worker_func = binary_thread_element_repeat;
- if (src0_type == HTP_TYPE_F32) {
+ if (type_key == 7) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_repeat_add_f32; break;
case HTP_OP_SUB: compute_func = compute_repeat_sub_f32; break;
@@ -1270,7 +1679,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_repeat_div_f32; break;
default: break;
}
- } else if (src0_type == HTP_TYPE_F16) {
+ } else if (type_key == 0) {
switch (octx->op) {
case HTP_OP_ADD: compute_func = compute_repeat_add_f16; break;
case HTP_OP_SUB: compute_func = compute_repeat_sub_f16; break;
@@ -1278,12 +1687,24 @@ static int execute_op_binary(struct htp_ops_context * octx) {
case HTP_OP_DIV: compute_func = compute_repeat_div_f16; break;
default: break;
}
+ } else {
+ SELECT_MIXED_COMPUTE(compute_repeat, type_key, compute_func);
}
break;
case HTP_BINARY_KERNEL_ADD_ID:
- if (octx->op == HTP_OP_ADD_ID && src0_type == HTP_TYPE_F32) {
- worker_func = binary_thread_add_id_f32;
- compute_func = (void *) compute_add_id_f32;
+ if (octx->op == HTP_OP_ADD_ID) {
+ worker_func = binary_thread_add_id;
+ switch (type_key) {
+ case 0: compute_func = (void *) compute_add_id_f16_f16_f16; break;
+ case 1: compute_func = (void *) compute_add_id_f16_f16_f32; break;
+ case 2: compute_func = (void *) compute_add_id_f16_f32_f16; break;
+ case 3: compute_func = (void *) compute_add_id_f16_f32_f32; break;
+ case 4: compute_func = (void *) compute_add_id_f32_f16_f16; break;
+ case 5: compute_func = (void *) compute_add_id_f32_f16_f32; break;
+ case 6: compute_func = (void *) compute_add_id_f32_f32_f16; break;
+ case 7: compute_func = (void *) compute_add_id_f32_f32_f32; break;
+ default: break;
+ }
}
break;
default: break;
@@ -1296,12 +1717,16 @@ 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) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1->ne[0] * elem_size, 1);
+ if (!kparams->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]);
+ }
} 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) {
- const size_t src1_bytes = (size_t) src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3] * elem_size;
+ 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) {
uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2);
@@ -1311,14 +1736,29 @@ static int execute_op_binary(struct htp_ops_context * octx) {
const uint32_t ne11 = src1->ne[1];
const uint32_t ne12 = src1->ne[2];
const uint32_t ne13 = src1->ne[3];
- const size_t row_bytes = src1->ne[0] * elem_size;
- for (uint32_t i13 = 0; i13 < ne13; i13++) {
- for (uint32_t i12 = 0; i12 < ne12; i12++) {
- dma_addr_t src_addr = src1->data + i13 * src1->nb[3] + i12 * src1->nb[2];
- uint8_t * dst_ptr = vtcm_src1 + (i13 * ne12 * ne11 + i12 * ne11) * row_bytes;
- while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr),
- row_bytes, src1->nb[1], row_bytes, ne11)) {
- dma_queue_pop(dma_q);
+ const size_t row_bytes = src1->ne[0] * src1_elem_size;
+ if (src1->nb[0] == src1_elem_size) {
+ for (uint32_t i13 = 0; i13 < ne13; i13++) {
+ for (uint32_t i12 = 0; i12 < ne12; i12++) {
+ dma_addr_t src_addr = src1->data + i13 * src1->nb[3] + i12 * src1->nb[2];
+ uint8_t * dst_ptr = vtcm_src1 + (i13 * ne12 * ne11 + i12 * ne11) * row_bytes;
+ while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr),
+ row_bytes, src1->nb[1], row_bytes, ne11)) {
+ dma_queue_pop(dma_q);
+ }
+ }
+ }
+ } else {
+ for (uint32_t i13 = 0; i13 < ne13; i13++) {
+ for (uint32_t i12 = 0; i12 < ne12; i12++) {
+ for (uint32_t i11 = 0; i11 < ne11; i11++) {
+ dma_addr_t src_addr = src1->data + i13 * src1->nb[3] + i12 * src1->nb[2] + i11 * src1->nb[1];
+ uint8_t * dst_ptr = vtcm_src1 + ((i13 * ne12 * ne11 + i12 * ne11 + i11) * src1->ne[0]) * src1_elem_size;
+ 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);
+ }
+ }
}
}
}
@@ -1328,7 +1768,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
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] * elem_size, src1->ne[1]);
+ src1->ne[0] * src1_elem_size, src1->ne[1]);
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],
@@ -1344,7 +1784,13 @@ static int execute_op_binary(struct htp_ops_context * octx) {
bctx.src0_row_size_aligned = src0_row_size_aligned;
bctx.src1_row_size_aligned = src1_row_size_aligned;
bctx.dst_row_size_aligned = dst_row_size_aligned;
- bctx.row_size_bytes = src0_row_size;
+ bctx.src0_row_size = src0_row_size;
+ bctx.src1_row_size = src1_row_size;
+ bctx.dst_row_size = dst_row_size;
+ bctx.src0_elem_size = src0_elem_size;
+ bctx.src1_elem_size = src1_elem_size;
+ bctx.dst_elem_size = dst_elem_size;
+ 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;
@@ -1364,6 +1810,10 @@ static int execute_op_binary(struct htp_ops_context * octx) {
kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX ||
kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID) {
dma_queue_flush(dma_q);
+ if ((kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST || kparams->kernel_type == HTP_BINARY_KERNEL_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]));
+ }
if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR && octx->src[2] != NULL && octx->op == HTP_OP_MUL) {
uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2);
const uint32_t n_scalars = src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3];
diff --git a/ggml/src/ggml-hexagon/htp/binary-ops.h b/ggml/src/ggml-hexagon/htp/binary-ops.h
index 6f849396c..b6706db05 100644
--- a/ggml/src/ggml-hexagon/htp/binary-ops.h
+++ b/ggml/src/ggml-hexagon/htp/binary-ops.h
@@ -28,7 +28,11 @@ struct htp_binary_kernel_params {
uint8_t n_srcs;
uint8_t is_scalar;
- uint8_t pad[2];
+ uint8_t src0_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;
@@ -61,16 +65,18 @@ static inline bool htp_binary_strides_safe(
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
const struct ggml_tensor * dst,
- size_t elem_size
+ size_t src0_elem_size,
+ size_t src1_elem_size,
+ size_t dst_elem_size
) {
- if ((src0->ne[0] != 1 && src0->nb[0] != elem_size) ||
- (src1->ne[0] != 1 && src1->nb[0] != elem_size) ||
- (dst->ne[0] != 1 && dst->nb[0] != elem_size)) {
+ (void) src1;
+ (void) src1_elem_size;
+ if ((src0->ne[0] != 1 && src0->nb[0] != src0_elem_size) ||
+ (dst->ne[0] != 1 && dst->nb[0] != dst_elem_size)) {
return false;
}
- if ((src0->ne[1] > 1 && src0->nb[1] < src0->ne[0] * elem_size) ||
- (src1->ne[1] > 1 && src1->nb[1] < src1->ne[0] * elem_size) ||
- (dst->ne[1] > 1 && dst->nb[1] < dst->ne[0] * elem_size)) {
+ if ((src0->ne[1] > 1 && src0->nb[1] < src0->ne[0] * src0_elem_size) ||
+ (dst->ne[1] > 1 && dst->nb[1] < dst->ne[0] * dst_elem_size)) {
return false;
}
return true;
@@ -114,18 +120,20 @@ static inline void htp_binary_vtcm_layout_build(
const uint32_t n_srcs = kparams->n_srcs > 2 ? kparams->n_srcs : 2;
if (kparams->kernel_type == HTP_BINARY_KERNEL_CHUNKED) {
- const size_t chunk_bytes = kparams->chunk_bytes;
- if (chunk_bytes == 0) {
+ const size_t src0_chunk_bytes = hex_round_up((size_t) kparams->chunk_size * kparams->src0_elem_size, 128);
+ const size_t src1_chunk_bytes = hex_round_up((size_t) kparams->chunk_size * kparams->src1_elem_size, 128);
+ const size_t dst_chunk_bytes = hex_round_up((size_t) kparams->chunk_size * kparams->dst_elem_size, 128);
+ if (src0_chunk_bytes == 0 || src1_chunk_bytes == 0 || dst_chunk_bytes == 0) {
return;
}
- L->src0_bytes_per_hvx = 2 * chunk_bytes;
- L->src1_bytes_per_hvx = kparams->is_scalar ? 0 : (2 * (n_srcs - 1) * chunk_bytes);
- L->dst_bytes_per_hvx = 2 * chunk_bytes;
+ 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->dst_bytes_per_hvx = 2 * dst_chunk_bytes;
- L->src0_spad_half_size = chunk_bytes;
- L->src1_spad_half_size = kparams->is_scalar ? 0 : chunk_bytes;
- L->dst_spad_half_size = chunk_bytes;
+ L->src0_spad_half_size = src0_chunk_bytes;
+ L->src1_spad_half_size = kparams->is_scalar ? 0 : src1_chunk_bytes;
+ L->dst_spad_half_size = dst_chunk_bytes;
L->rows_per_buffer = 1;
L->src1_size = 0;
@@ -199,13 +207,18 @@ static inline bool htp_binary_solve_chunked(
struct htp_binary_vtcm_layout * L,
struct htp_binary_kernel_params * kparams,
uint32_t total_elems,
- uint32_t elem_size,
+ uint32_t src0_elem_size,
+ uint32_t src1_elem_size,
+ uint32_t dst_elem_size,
uint32_t max_hvx,
uint32_t n_srcs,
bool is_scalar,
size_t vtcm_size
) {
const size_t n_bufs = is_scalar ? 2 : (size_t) n_srcs + 1;
+ const uint32_t elem_size = src0_elem_size > src1_elem_size ?
+ (src0_elem_size > dst_elem_size ? src0_elem_size : dst_elem_size) :
+ (src1_elem_size > dst_elem_size ? src1_elem_size : dst_elem_size);
const size_t scalar_bytes = is_scalar ? 128 : 0;
const size_t budget_per_buf = (max_hvx > 0 && vtcm_size > scalar_bytes)
? hex_align_down((vtcm_size - scalar_bytes) / (2 * max_hvx * n_bufs), 128)
@@ -230,6 +243,9 @@ static inline bool htp_binary_solve_chunked(
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;
diff --git a/ggml/src/ggml-hexagon/htp/concat-ops.c b/ggml/src/ggml-hexagon/htp/concat-ops.c
index a374a8fd6..7be12c55b 100644
--- a/ggml/src/ggml-hexagon/htp/concat-ops.c
+++ b/ggml/src/ggml-hexagon/htp/concat-ops.c
@@ -17,40 +17,244 @@
#include <string.h>
+static inline uint32_t concat_type_size(uint32_t type) {
+ return (type == HTP_TYPE_F16) ? 2 : 4;
+}
+
+static inline HVX_Vector hvx_vec_clamp_f16_f32(HVX_Vector x) {
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+ return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max);
+}
+
+static __attribute__((noinline)) void concat_cvt_f16_to_f32_aa(
+ uint8_t * restrict dst,
+ const uint8_t * restrict src,
+ uint32_t n) {
+
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ uint32_t i = 0;
+ for (; i + 64 <= n; i += 64) {
+ const HVX_VectorPair vp = hvx_vec_f16_to_f32(*vsrc++);
+ *vdst++ = Q6_V_lo_W(vp);
+ *vdst++ = Q6_V_hi_W(vp);
+ }
+ if (i < n) {
+ const HVX_VectorPair vp = hvx_vec_f16_to_f32(*vsrc);
+ const uint32_t rem = n - i;
+ if (rem >= 32) {
+ *vdst++ = Q6_V_lo_W(vp);
+ if (rem > 32) {
+ hvx_vec_store_a(vdst, (rem - 32) * sizeof(float), Q6_V_hi_W(vp));
+ }
+ } else {
+ hvx_vec_store_a(vdst, rem * sizeof(float), Q6_V_lo_W(vp));
+ }
+ }
+}
+
+static __attribute__((noinline)) void concat_cvt_f32_to_f16_aa(
+ uint8_t * restrict dst,
+ const uint8_t * restrict src,
+ uint32_t n) {
+
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ uint32_t i = 0;
+ for (; i + 64 <= n; i += 64) {
+ const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]);
+ const HVX_Vector v1 = hvx_vec_clamp_f16_f32(vsrc[1]);
+ vsrc += 2;
+ *vdst++ = hvx_vec_f32_to_f16(v0, v1);
+ }
+ if (i < n) {
+ const uint32_t rem = n - i;
+ const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]);
+ const HVX_Vector v1 = (rem > 32) ? hvx_vec_clamp_f16_f32(vsrc[1]) : Q6_V_vzero();
+ const HVX_Vector out = hvx_vec_f32_to_f16(v0, v1);
+ hvx_vec_store_a(vdst, rem * sizeof(__fp16), out);
+ }
+}
+
+static __attribute__((noinline)) void concat_cvt_src0_rows_f16_to_f32(
+ uint8_t * restrict spad0,
+ uint8_t * restrict spad2,
+ uint32_t spad0_stride,
+ uint32_t dst_lead_pre,
+ uint32_t lead_ne0,
+ uint32_t nrows) {
+
+ if (lead_ne0 == 0) {
+ return;
+ }
+ for (uint32_t r = 0; r < nrows; r++) {
+ uint8_t * row_ptr = spad0 + r * spad0_stride;
+ concat_cvt_f16_to_f32_aa(spad2, row_ptr, lead_ne0);
+ hvx_copy_f32_ua(row_ptr + dst_lead_pre, spad2, lead_ne0);
+ }
+}
+
+static __attribute__((noinline)) void concat_cvt_src0_rows_f32_to_f16(
+ uint8_t * restrict spad0,
+ uint8_t * restrict spad2,
+ uint32_t spad0_stride,
+ uint32_t dst_lead_pre,
+ uint32_t lead_ne0,
+ uint32_t nrows) {
+
+ if (lead_ne0 == 0) {
+ return;
+ }
+ for (uint32_t r = 0; r < nrows; r++) {
+ uint8_t * row_ptr = spad0 + r * spad0_stride;
+ concat_cvt_f32_to_f16_aa(spad2, row_ptr, lead_ne0);
+ hvx_copy_f16_ua(row_ptr + dst_lead_pre, spad2, lead_ne0);
+ }
+}
+
+static __attribute__((noinline)) void concat_transpose_f32(
+ uint8_t * restrict dst_base,
+ uint32_t dst_stride,
+ const uint8_t * restrict src_base,
+ uint32_t src_stride,
+ uint32_t nrows,
+ uint32_t ncols) {
+
+ const HVX_Vector offsets = hvx_vec_gather_offsets_w(src_stride);
+ for (uint32_t c = 0; c < ncols; c += 32) {
+ hvx_transpose_32x32_w_gather(dst_base + c * sizeof(float), dst_stride,
+ src_base + c * src_stride, src_stride,
+ offsets, nrows, MIN(ncols - c, 32));
+ }
+ hvx_gather_sync(dst_base);
+}
+
+static __attribute__((noinline)) void concat_transpose_f16(
+ uint8_t * restrict dst_base,
+ uint32_t dst_stride,
+ const uint8_t * restrict src_base,
+ uint32_t src_stride,
+ uint32_t nrows,
+ uint32_t ncols) {
+
+ const HVX_Vector offsets = hvx_vec_gather_offsets_h(src_stride);
+ for (uint32_t c = 0; c < ncols; c += 64) {
+ hvx_transpose_64x64_h_gather(dst_base + c * sizeof(__fp16), dst_stride,
+ src_base + c * src_stride, src_stride,
+ offsets, nrows, MIN(ncols - c, 64));
+ }
+ hvx_gather_sync(dst_base);
+}
+
+static __attribute__((noinline)) void concat_transpose_cvt_f16_to_f32(
+ uint8_t * restrict dst_base,
+ uint32_t dst_stride,
+ const uint8_t * restrict src_base,
+ uint32_t src_stride,
+ uint8_t * restrict spad2,
+ uint32_t nrows,
+ uint32_t ncols) {
+
+ const HVX_Vector offsets = hvx_vec_gather_offsets_h(src_stride);
+ for (uint32_t c = 0; c < ncols; c += 64) {
+ hvx_transpose_64x64_h_gather(spad2, 128,
+ src_base + c * src_stride, src_stride,
+ offsets, nrows, MIN(ncols - c, 64));
+ for (uint32_t r = 0; r < nrows; r++) {
+ const HVX_Vector v = *(const HVX_Vector *) (spad2 + r * 128);
+ const HVX_VectorPair vp = hvx_vec_f16_to_f32(v);
+ HVX_Vector * restrict vdst = (HVX_Vector *) (dst_base + r * dst_stride + c * sizeof(float));
+ vdst[0] = Q6_V_lo_W(vp);
+ vdst[1] = Q6_V_hi_W(vp);
+ }
+ }
+}
+
+static __attribute__((noinline)) void concat_transpose_cvt_f32_to_f16(
+ uint8_t * restrict dst_base,
+ uint32_t dst_stride,
+ const uint8_t * restrict src_base,
+ uint32_t src_stride,
+ uint8_t * restrict spad2,
+ uint32_t nrows,
+ uint32_t ncols) {
+
+ const HVX_Vector offsets = hvx_vec_gather_offsets_w(src_stride);
+ for (uint32_t c = 0; c < ncols; c += 64) {
+ const uint32_t chunk_cols = MIN(ncols - c, 64);
+ hvx_transpose_32x32_w_gather(spad2, 256,
+ src_base + c * src_stride, src_stride,
+ offsets, nrows, MIN(chunk_cols, 32));
+ if (chunk_cols > 32) {
+ hvx_transpose_32x32_w_gather(spad2 + 128, 256,
+ src_base + (c + 32) * src_stride, src_stride,
+ offsets, nrows, chunk_cols - 32);
+ }
+ if (chunk_cols > 32) {
+ for (uint32_t r = 0; r < nrows; r++) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) (spad2 + r * 256);
+ const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]);
+ const HVX_Vector v1 = hvx_vec_clamp_f16_f32(vsrc[1]);
+ *(HVX_Vector *) (dst_base + r * dst_stride + c * sizeof(__fp16)) = hvx_vec_f32_to_f16(v0, v1);
+ }
+ } else {
+ const HVX_Vector zero = Q6_V_vzero();
+ for (uint32_t r = 0; r < nrows; r++) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) (spad2 + r * 256);
+ const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]);
+ *(HVX_Vector *) (dst_base + r * dst_stride + c * sizeof(__fp16)) = hvx_vec_f32_to_f16(v0, zero);
+ }
+ }
+ }
+}
+
struct htp_concat_context {
- struct htp_ops_context * octx;
- uint8_t * spad0_base;
- uint8_t * spad1_base;
- uint32_t spad0_size_per_hvx;
- uint32_t spad1_size_per_hvx;
- uint32_t row_start;
- uint32_t nrows;
- uint32_t nrows_per_hvx;
- uint32_t nplanes;
- struct fastdiv_values div_ne2;
+ struct htp_ops_context * octx;
+ const struct htp_tensor * lead_src;
+ const struct htp_tensor * trans_src;
+ const struct htp_tensor * dst_view;
+ uint8_t * spad0_base;
+ uint8_t * spad1_base;
+ uint8_t * spad2_base;
+ uint32_t spad0_size_per_hvx;
+ uint32_t spad1_size_per_hvx;
+ uint32_t spad2_size_per_hvx;
+ uint32_t row_start;
+ uint32_t nrows;
+ uint32_t nrows_per_hvx;
+ uint32_t nplanes;
+ struct fastdiv_values div_ne2;
};
static inline dma_addr_t concat_plane_addr(const struct htp_tensor * t, uint32_t p, const struct fastdiv_values * div_ne2, uint32_t ne2) {
const uint32_t i3 = fastdiv(p, div_ne2);
const uint32_t i2 = p - i3 * ne2;
- return t->data + i2 * t->nb[2] + i3 * t->nb[3];
+ return t->data + (i2 * t->nb[2] + i3 * t->nb[3]);
}
-static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void concat_2d_transposed_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct htp_concat_context * cctx = (struct htp_concat_context *) data;
- struct htp_ops_context * octx = cctx->octx;
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * src1 = octx->src[1];
- const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * src0 = cctx->lead_src;
+ const struct htp_tensor * src1 = cctx->trans_src;
+ const struct htp_tensor * dst = cctx->dst_view;
- const uint32_t src0_ne0 = src0->ne[0];
+ const uint32_t src0_ne0 = src0 ? src0->ne[0] : 0;
const uint32_t src1_ne0 = src1->ne[0];
- // dst rows [row_begin, row_end) of this thread; a dst row is a src0 row followed by a src1 column
+ const uint32_t dst_es = concat_type_size(dst->type);
+ const uint32_t src0_es = src0 ? concat_type_size(src0->type) : dst_es;
+ const uint32_t src1_es = concat_type_size(src1->type);
+
const uint32_t row_begin = cctx->row_start + ith * cctx->nrows_per_hvx;
const uint32_t row_end = MIN(row_begin + cctx->nrows_per_hvx, cctx->row_start + cctx->nrows);
- if (row_begin >= row_end) return;
+ if (row_begin >= row_end) {
+ return;
+ }
dma_queue * dma_q = th->dma_q;
struct htp_thread_trace * tr = th->trace;
@@ -58,37 +262,39 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth,
const struct fastdiv_values * div_ne2 = &cctx->div_ne2;
const uint32_t ne2 = dst->ne[2];
- // tile: block_rows dst rows x block_cols src1 columns
const uint32_t block_rows = 128;
- const uint32_t block_cols = 256;
- // +1 element spreads the gather lanes across VTCM, so they do not serialize on one path
- const uint32_t spad1_stride = block_rows * sizeof(float) + sizeof(float);
-
- const HVX_Vector offsets = hvx_vec_gather_offsets_w(spad1_stride);
- const uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, 32), block_cols);
- const uint32_t src0_row_bytes = src0_ne0 * sizeof(float);
- const uint32_t src0_row_padded = hex_round_up(src0_row_bytes, VLEN);
- const uint32_t src0_pre = src0_row_padded - src0_row_bytes;
- const uint32_t spad0_stride = src0_row_padded + block_cols_padded * sizeof(float);
-
- // two slots per scratchpad: tile b gathers in slot b&1 while dst[b-1] and src1[b+1] DMA in the other
- uint8_t * spad0_base = cctx->spad0_base + ith * cctx->spad0_size_per_hvx;
- uint8_t * spad1_base = cctx->spad1_base + ith * cctx->spad1_size_per_hvx;
+ const uint32_t block_cols = (src1_es == 2 && dst_es == 2) ? 512 : 256;
+ const uint32_t col_align = (src1_es == 2 || dst_es == 2) ? 64 : 32;
+ const uint32_t spad1_stride = block_rows * src1_es + src1_es;
+
+ const uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, col_align), block_cols);
+ const uint32_t dst_src0_row_bytes = src0_ne0 * dst_es;
+ const uint32_t dst_src0_row_padded = hex_round_up(dst_src0_row_bytes, VLEN);
+ const uint32_t dst_src0_pre = dst_src0_row_padded - dst_src0_row_bytes;
+ const uint32_t raw_src0_row_bytes = src0_ne0 * src0_es;
+ const uint32_t raw_src0_row_padded = (src0_es != dst_es) ? hex_round_up(raw_src0_row_bytes, VLEN) : 0;
+ const uint32_t spad0_stride = MAX(dst_src0_row_padded + block_cols_padded * dst_es, raw_src0_row_padded);
+ const uint32_t src0_dma_off = (src0_es == dst_es) ? dst_src0_pre : 0;
+
+ uint8_t * spad0_base = cctx->spad0_base + (size_t) ith * cctx->spad0_size_per_hvx;
+ uint8_t * spad1_base = cctx->spad1_base + (size_t) ith * cctx->spad1_size_per_hvx;
+ uint8_t * spad2 = cctx->spad2_base ? (cctx->spad2_base + (size_t) ith * cctx->spad2_size_per_hvx) : NULL;
const uint32_t spad0_slot = block_rows * spad0_stride;
const uint32_t spad1_slot = block_cols_padded * spad1_stride;
- // tiles walk (plane, row, col) with col fastest; src0 goes out with the col == 0 tile only
uint32_t plane = 0;
uint32_t row = row_begin;
uint32_t col = 0;
uint32_t slot = 0;
- bool dst_pending = false;
const dma_addr_t src1_addr = concat_plane_addr(src1, plane, div_ne2, ne2) + row * src1->nb[1];
- dma_queue_push(dma_q, dma_make_data(spad1_base, src1_addr), spad1_stride, src1->nb[0], MIN(row_end - row, block_rows) * sizeof(float), MIN(src1_ne0, block_cols));
+ dma_queue_push(dma_q, dma_make_data(spad1_base, src1_addr), spad1_stride, src1->nb[0], MIN(row_end - row, block_rows) * src1_es, MIN(src1_ne0, block_cols));
- const dma_addr_t src0_addr = concat_plane_addr(src0, plane, div_ne2, ne2) + row * src0->nb[1];
- dma_queue_push(dma_q, dma_make_data(spad0_base + src0_pre, src0_addr), spad0_stride, src0->nb[1], src0_row_bytes, MIN(row_end - row, block_rows));
+ if (src0) {
+ const dma_addr_t src0_addr = concat_plane_addr(src0, plane, div_ne2, ne2) + row * src0->nb[1];
+ dma_queue_push(dma_q, dma_make_data(spad0_base + src0_dma_off, src0_addr), spad0_stride, src0->nb[1], raw_src0_row_bytes, MIN(row_end - row, block_rows));
+ }
+ dma_queue_push(dma_q, dma_make_data(dst->data, spad0_base), 0, 0, 0, 0);
while (plane < cctx->nplanes) {
const uint32_t nrows = MIN(row_end - row, block_rows);
@@ -98,7 +304,7 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth,
uint8_t * spad1 = spad1_base + slot * spad1_slot;
dma_queue_pop(dma_q); // src1
- if (col == 0) {
+ if (src0 && col == 0) {
dma_queue_pop(dma_q); // src0
}
@@ -117,33 +323,43 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth,
const uint32_t next_nrows = MIN(row_end - next_row, block_rows);
const uint32_t next_ncols = MIN(src1_ne0 - next_col, block_cols);
- // other spad1 slot is free since the previous gather sync
if (has_next) {
- const dma_addr_t addr = concat_plane_addr(src1, next_plane, div_ne2, ne2) + next_row * src1->nb[1] + next_col * src1->nb[0];
- dma_queue_push(dma_q, dma_make_data(spad1_base + (slot ^ 1) * spad1_slot, addr), spad1_stride, src1->nb[0], next_nrows * sizeof(float), next_ncols);
+ const dma_addr_t addr = concat_plane_addr(src1, next_plane, div_ne2, ne2) + (next_row * src1->nb[1] + next_col * src1->nb[0]);
+ dma_queue_push(dma_q, dma_make_data(spad1_base + (slot ^ 1) * spad1_slot, addr), spad1_stride, src1->nb[0], next_nrows * src1_es, next_ncols);
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row);
- for (uint32_t c = 0; c < ncols; c += 32) {
- hvx_transpose_32x32_w_gather(spad0 + src0_row_padded + c * sizeof(float), spad0_stride, spad1 + c * spad1_stride, spad1_stride, offsets, nrows, MIN(ncols - c, 32));
+ if (src0 && col == 0 && src0_es != dst_es) {
+ if (dst_es == 4) {
+ concat_cvt_src0_rows_f16_to_f32(spad0, spad2, spad0_stride, dst_src0_pre, src0_ne0, nrows);
+ } else {
+ concat_cvt_src0_rows_f32_to_f16(spad0, spad2, spad0_stride, dst_src0_pre, src0_ne0, nrows);
+ }
}
- hvx_gather_sync(spad0 + src0_row_padded);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row);
- // other spad0 slot is free once dst[b-1] is written
- if (dst_pending) {
- dma_queue_pop(dma_q); // dst
+ uint8_t * dst_trans = spad0 + dst_src0_row_padded;
+ if (src1_es == dst_es) {
+ if (dst_es == 4) {
+ concat_transpose_f32(dst_trans, spad0_stride, spad1, spad1_stride, nrows, ncols);
+ } else {
+ concat_transpose_f16(dst_trans, spad0_stride, spad1, spad1_stride, nrows, ncols);
+ }
+ } else if (dst_es == 4) {
+ concat_transpose_cvt_f16_to_f32(dst_trans, spad0_stride, spad1, spad1_stride, spad2, nrows, ncols);
+ } else {
+ concat_transpose_cvt_f32_to_f16(dst_trans, spad0_stride, spad1, spad1_stride, spad2, nrows, ncols);
}
- if (has_next && next_col == 0) {
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row);
+
+ dma_queue_pop(dma_q); // dst
+ if (src0 && has_next && next_col == 0) {
const dma_addr_t addr = concat_plane_addr(src0, next_plane, div_ne2, ne2) + next_row * src0->nb[1];
- dma_queue_push(dma_q, dma_make_data(spad0_base + (slot ^ 1) * spad0_slot + src0_pre, addr), spad0_stride, src0->nb[1], src0_row_bytes, next_nrows);
+ dma_queue_push(dma_q, dma_make_data(spad0_base + (slot ^ 1) * spad0_slot + src0_dma_off, addr), spad0_stride, src0->nb[1], raw_src0_row_bytes, next_nrows);
}
- // the col == 0 tile also carries the src0 columns in front
- const uint32_t lead = (col == 0) ? src0_row_bytes : 0;
- const dma_addr_t dst_addr = concat_plane_addr(dst, plane, div_ne2, ne2) + row * dst->nb[1] + src0_row_bytes + col * sizeof(float) - lead;
- dma_queue_push(dma_q, dma_make_data(dst_addr, spad0 + src0_row_padded - lead), dst->nb[1], spad0_stride, lead + ncols * sizeof(float), nrows);
- dst_pending = true;
+ const uint32_t lead = (src0 && col == 0) ? dst_src0_row_bytes : 0;
+ const dma_addr_t dst_addr = concat_plane_addr(dst, plane, div_ne2, ne2) + (row * dst->nb[1] + dst_src0_row_bytes + col * dst_es - lead);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, spad0 + dst_src0_row_padded - lead), dst->nb[1], spad0_stride, lead + ncols * dst_es, nrows);
plane = next_plane;
row = next_row;
@@ -153,127 +369,256 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth,
dma_queue_flush(dma_q);
}
-static void concat_2d_f16_transposed(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_concat_context * cctx = (struct htp_concat_context *) data;
- struct htp_ops_context * octx = cctx->octx;
+struct concat_regular_cvt_task {
+ struct htp_ops_context * octx;
+ const struct htp_tensor * src;
+ const struct htp_tensor * dst;
+ uint32_t r_start;
+ uint32_t nrows;
+ uint32_t rows_per_hvx;
+ uint32_t src_es;
+ uint32_t dst_es;
+ struct fastdiv_values div_ne1;
+ struct fastdiv_values div_ne2_ne1;
+};
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * src1 = octx->src[1];
- const struct htp_tensor * dst = octx->dst;
+static inline void concat_regular_row_addrs(
+ const struct concat_regular_cvt_task * task,
+ uint32_t r,
+ uint32_t * i1_out,
+ dma_addr_t * src_addr_out,
+ dma_addr_t * dst_addr_out) {
+
+ const struct htp_tensor * src = task->src;
+ const struct htp_tensor * dst = task->dst;
+ const uint32_t ne1 = src->ne[1];
+ const uint32_t ne2_ne1 = src->ne[2] * ne1;
+
+ const uint32_t i3 = fastdiv(r, &task->div_ne2_ne1);
+ const uint32_t rem = r - i3 * ne2_ne1;
+ const uint32_t i2 = fastdiv(rem, &task->div_ne1);
+ const uint32_t i1 = rem - i2 * ne1;
+
+ *i1_out = i1;
+ *src_addr_out = src->data + (i1 * src->nb[1] + i2 * src->nb[2] + i3 * src->nb[3]);
+ *dst_addr_out = dst->data + (i1 * dst->nb[1] + i2 * dst->nb[2] + i3 * dst->nb[3]);
+}
- const uint32_t src0_ne0 = src0->ne[0];
- const uint32_t src1_ne0 = src1->ne[0];
+static void concat_regular_cvt_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct concat_regular_cvt_task * task = (const struct concat_regular_cvt_task *) data;
+ const struct htp_tensor * src = task->src;
+ const struct htp_tensor * dst = task->dst;
+
+ const uint32_t r_offset = MIN(ith * task->rows_per_hvx, task->nrows);
+ const uint32_t r_beg = task->r_start + r_offset;
+ const uint32_t r_end = task->r_start + MIN(r_offset + task->rows_per_hvx, task->nrows);
+ if (r_beg >= r_end) {
+ return;
+ }
- // dst rows [row_begin, row_end) of this thread; a dst row is a src0 row followed by a src1 column
- const uint32_t row_begin = cctx->row_start + ith * cctx->nrows_per_hvx;
- const uint32_t row_end = MIN(row_begin + cctx->nrows_per_hvx, cctx->row_start + cctx->nrows);
- if (row_begin >= row_end) return;
+ const uint32_t ne0 = src->ne[0];
+ const uint32_t ne1 = src->ne[1];
+ if (ne0 == 0) {
+ return;
+ }
- dma_queue * dma_q = th->dma_q;
+ const uint32_t src_es = task->src_es;
+ const uint32_t dst_es = task->dst_es;
+ const uint32_t max_es = MAX(src_es, dst_es);
+
+ uint8_t * base = (uint8_t *) task->octx->ctx->vtcm_base + (size_t) ith * (4 * HTP_CONCAT_REG_BLK_BYTES);
+ uint8_t * sbuf[2] = {
+ base + 0 * HTP_CONCAT_REG_BLK_BYTES,
+ base + 1 * HTP_CONCAT_REG_BLK_BYTES,
+ };
+ uint8_t * dbuf[2] = {
+ base + 2 * HTP_CONCAT_REG_BLK_BYTES,
+ base + 3 * HTP_CONCAT_REG_BLK_BYTES,
+ };
+
+ dma_queue * q = th->dma_q;
struct htp_thread_trace * tr = th->trace;
- const struct fastdiv_values * div_ne2 = &cctx->div_ne2;
- const uint32_t ne2 = dst->ne[2];
+ const uint32_t row_max_bytes = ne0 * max_es;
+ if (row_max_bytes <= HTP_CONCAT_REG_BLK_BYTES) {
+ uint32_t max_rows_per_blk = HTP_CONCAT_REG_BLK_BYTES / row_max_bytes;
+ if (src->nb[1] > 65535 || dst->nb[1] > 65535) {
+ max_rows_per_blk = 1;
+ }
+ if (max_rows_per_blk > DMA_MAX_NROWS) {
+ max_rows_per_blk = DMA_MAX_NROWS;
+ }
- // tile: block_rows dst rows x block_cols src1 columns
- const uint32_t block_rows = 128;
- const uint32_t block_cols = 512;
- // +1 element spreads the gather lanes across VTCM, so they do not serialize on one path
- const uint32_t spad1_stride = block_rows * sizeof(__fp16) + sizeof(__fp16);
-
- const HVX_Vector offsets = hvx_vec_gather_offsets_h(spad1_stride);
- const uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, 64), block_cols);
- const uint32_t src0_row_bytes = src0_ne0 * sizeof(__fp16);
- const uint32_t src0_row_padded = hex_round_up(src0_row_bytes, VLEN);
- const uint32_t src0_pre = src0_row_padded - src0_row_bytes;
- const uint32_t spad0_stride = src0_row_padded + block_cols_padded * sizeof(__fp16);
-
- // two slots per scratchpad: tile b gathers in slot b&1 while dst[b-1] and src1[b+1] DMA in the other
- uint8_t * spad0_base = cctx->spad0_base + ith * cctx->spad0_size_per_hvx;
- uint8_t * spad1_base = cctx->spad1_base + ith * cctx->spad1_size_per_hvx;
- const uint32_t spad0_slot = block_rows * spad0_stride;
- const uint32_t spad1_slot = block_cols_padded * spad1_stride;
+ const uint32_t src_row_bytes = ne0 * src_es;
+ const uint32_t dst_row_bytes = ne0 * dst_es;
- // tiles walk (plane, row, col) with col fastest; src0 goes out with the col == 0 tile only
- uint32_t plane = 0;
- uint32_t row = row_begin;
- uint32_t col = 0;
- uint32_t slot = 0;
- bool dst_pending = false;
+ uint32_t cur_r = r_beg;
+ uint32_t cur_i1 = 0;
+ dma_addr_t cur_src_addr = 0;
+ dma_addr_t cur_dst_addr = 0;
+ concat_regular_row_addrs(task, cur_r, &cur_i1, &cur_src_addr, &cur_dst_addr);
+ uint32_t cur_nr = MIN(MIN(r_end - cur_r, max_rows_per_blk), ne1 - cur_i1);
- const dma_addr_t src1_addr = concat_plane_addr(src1, plane, div_ne2, ne2) + row * src1->nb[1];
- dma_queue_push(dma_q, dma_make_data(spad1_base, src1_addr), spad1_stride, src1->nb[0], MIN(row_end - row, block_rows) * sizeof(__fp16), MIN(src1_ne0, block_cols));
+ const size_t s_stride0 = (cur_nr > 1) ? src->nb[1] : src_row_bytes;
+ dma_queue_push(q, dma_make_data(sbuf[0], cur_src_addr), src_row_bytes, s_stride0, src_row_bytes, cur_nr);
+ dma_queue_push(q, dma_make_data(cur_dst_addr, dbuf[1]), 0, 0, 0, 0);
- const dma_addr_t src0_addr = concat_plane_addr(src0, plane, div_ne2, ne2) + row * src0->nb[1];
- dma_queue_push(dma_q, dma_make_data(spad0_base + src0_pre, src0_addr), spad0_stride, src0->nb[1], src0_row_bytes, MIN(row_end - row, block_rows));
+ uint32_t slot = 0;
- while (plane < cctx->nplanes) {
- const uint32_t nrows = MIN(row_end - row, block_rows);
- const uint32_t ncols = MIN(src1_ne0 - col, block_cols);
+ while (cur_r < r_end) {
+ const uint32_t next_r = cur_r + cur_nr;
+ uint32_t next_i1 = 0;
+ dma_addr_t next_src_addr = 0;
+ dma_addr_t next_dst_addr = 0;
+ uint32_t next_nr = 0;
- uint8_t * spad0 = spad0_base + slot * spad0_slot;
- uint8_t * spad1 = spad1_base + slot * spad1_slot;
+ dma_queue_pop(q); // sbuf[slot]
- dma_queue_pop(dma_q); // src1
- if (col == 0) {
- dma_queue_pop(dma_q); // src0
- }
+ if (next_r < r_end) {
+ concat_regular_row_addrs(task, next_r, &next_i1, &next_src_addr, &next_dst_addr);
+ next_nr = MIN(MIN(r_end - next_r, max_rows_per_blk), ne1 - next_i1);
+ const size_t s_stride_next = (next_nr > 1) ? src->nb[1] : src_row_bytes;
+ dma_queue_push(q, dma_make_data(sbuf[slot ^ 1], next_src_addr), src_row_bytes, s_stride_next, src_row_bytes, next_nr);
+ }
- uint32_t next_plane = plane;
- uint32_t next_row = row;
- uint32_t next_col = col + block_cols;
- if (next_col >= src1_ne0) {
- next_col = 0;
- next_row = row + block_rows;
- if (next_row >= row_end) {
- next_row = row_begin;
- next_plane++;
+ dma_queue_pop(q); // dbuf[slot ^ 1]
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur_r);
+ if (dst_es == 4) {
+ concat_cvt_f16_to_f32_aa(dbuf[slot], sbuf[slot], cur_nr * ne0);
+ } else {
+ concat_cvt_f32_to_f16_aa(dbuf[slot], sbuf[slot], cur_nr * ne0);
}
- }
- const bool has_next = next_plane < cctx->nplanes;
- const uint32_t next_nrows = MIN(row_end - next_row, block_rows);
- const uint32_t next_ncols = MIN(src1_ne0 - next_col, block_cols);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur_r);
- // other spad1 slot is free since the previous gather sync
- if (has_next) {
- const dma_addr_t addr = concat_plane_addr(src1, next_plane, div_ne2, ne2) + next_row * src1->nb[1] + next_col * src1->nb[0];
- dma_queue_push(dma_q, dma_make_data(spad1_base + (slot ^ 1) * spad1_slot, addr), spad1_stride, src1->nb[0], next_nrows * sizeof(__fp16), next_ncols);
- }
+ const size_t d_stride = (cur_nr > 1) ? dst->nb[1] : dst_row_bytes;
+ dma_queue_push(q, dma_make_data(cur_dst_addr, dbuf[slot]), d_stride, dst_row_bytes, dst_row_bytes, cur_nr);
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row);
- for (uint32_t c = 0; c < ncols; c += 64) {
- hvx_transpose_64x64_h_gather(spad0 + src0_row_padded + c * sizeof(__fp16), spad0_stride, spad1 + c * spad1_stride, spad1_stride, offsets, nrows, MIN(ncols - c, 64));
+ cur_r = next_r;
+ cur_i1 = next_i1;
+ cur_src_addr = next_src_addr;
+ cur_dst_addr = next_dst_addr;
+ cur_nr = next_nr;
+ slot ^= 1;
}
- hvx_gather_sync(spad0 + src0_row_padded);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row);
+ dma_queue_flush(q);
+ } else {
+ const uint32_t max_cols = HTP_CONCAT_REG_BLK_BYTES / max_es;
+ uint32_t r = r_beg;
+ uint32_t col = 0;
+ uint32_t i1 = 0;
+ dma_addr_t row_src_addr = 0;
+ dma_addr_t row_dst_addr = 0;
+ concat_regular_row_addrs(task, r, &i1, &row_src_addr, &row_dst_addr);
+
+ uint32_t cur_cols = MIN(ne0 - col, max_cols);
+ const uint32_t s_bytes0 = cur_cols * src_es;
+ dma_queue_push(q, dma_make_data(sbuf[0], row_src_addr), s_bytes0, s_bytes0, s_bytes0, 1);
+ dma_queue_push(q, dma_make_data(row_dst_addr, dbuf[1]), 0, 0, 0, 0);
+
+ uint32_t slot = 0;
+
+ while (r < r_end) {
+ uint32_t next_r = r;
+ uint32_t next_col = col + cur_cols;
+ uint32_t next_i1 = i1;
+ dma_addr_t next_row_src_addr = row_src_addr;
+ dma_addr_t next_row_dst_addr = row_dst_addr;
+ if (next_col >= ne0) {
+ next_col = 0;
+ next_r = r + 1;
+ if (next_r < r_end) {
+ concat_regular_row_addrs(task, next_r, &next_i1, &next_row_src_addr, &next_row_dst_addr);
+ }
+ }
- // other spad0 slot is free once dst[b-1] is written
- if (dst_pending) {
- dma_queue_pop(dma_q); // dst
- }
- if (has_next && next_col == 0) {
- const dma_addr_t addr = concat_plane_addr(src0, next_plane, div_ne2, ne2) + next_row * src0->nb[1];
- dma_queue_push(dma_q, dma_make_data(spad0_base + (slot ^ 1) * spad0_slot + src0_pre, addr), spad0_stride, src0->nb[1], src0_row_bytes, next_nrows);
+ dma_queue_pop(q); // sbuf[slot]
+
+ if (next_r < r_end) {
+ const uint32_t next_cols = MIN(ne0 - next_col, max_cols);
+ const uint32_t s_bytes_next = next_cols * src_es;
+ dma_queue_push(q, dma_make_data(sbuf[slot ^ 1], next_row_src_addr + next_col * src_es),
+ s_bytes_next, s_bytes_next, s_bytes_next, 1);
+ }
+
+ dma_queue_pop(q); // dbuf[slot ^ 1]
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
+ if (dst_es == 4) {
+ concat_cvt_f16_to_f32_aa(dbuf[slot], sbuf[slot], cur_cols);
+ } else {
+ concat_cvt_f32_to_f16_aa(dbuf[slot], sbuf[slot], cur_cols);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
+
+ const uint32_t d_bytes = cur_cols * dst_es;
+ dma_queue_push(q, dma_make_data(row_dst_addr + col * dst_es, dbuf[slot]),
+ d_bytes, d_bytes, d_bytes, 1);
+
+ r = next_r;
+ col = next_col;
+ i1 = next_i1;
+ row_src_addr = next_row_src_addr;
+ row_dst_addr = next_row_dst_addr;
+ cur_cols = MIN(ne0 - col, max_cols);
+ slot ^= 1;
}
+ dma_queue_flush(q);
+ }
+}
- // the col == 0 tile also carries the src0 columns in front
- const uint32_t lead = (col == 0) ? src0_row_bytes : 0;
- const dma_addr_t dst_addr = concat_plane_addr(dst, plane, div_ne2, ne2) + row * dst->nb[1] + src0_row_bytes + col * sizeof(__fp16) - lead;
- dma_queue_push(dma_q, dma_make_data(dst_addr, spad0 + src0_row_padded - lead), dst->nb[1], spad0_stride, lead + ncols * sizeof(__fp16), nrows);
- dst_pending = true;
+static void concat_regular_side(
+ struct htp_ops_context * octx,
+ const struct htp_tensor * dst_view,
+ const struct htp_tensor * src,
+ uint32_t rstart,
+ uint32_t nrows,
+ const struct fastdiv_values * div_ne1,
+ const struct fastdiv_values * div_ne2_ne1) {
+
+ if (nrows == 0 || src->ne[0] == 0) {
+ return;
+ }
- plane = next_plane;
- row = next_row;
- col = next_col;
- slot ^= 1;
+ const uint32_t dst_es = (dst_view->type == HTP_TYPE_F32 || dst_view->type == HTP_TYPE_I32) ? 4 : 2;
+ if (src->type == dst_view->type) {
+ dma_queue * q = octx->ctx->dma[0];
+ dma_cpy_sametype_sameshape_range(q, dst_view, src, dst_es, rstart, nrows);
+ dma_queue_flush(q);
+ return;
}
- dma_queue_flush(dma_q);
+
+ const uint32_t n_hvx = octx->n_hvx;
+ struct concat_regular_cvt_task task;
+ task.octx = octx;
+ task.src = src;
+ task.dst = dst_view;
+ task.r_start = rstart;
+ task.nrows = nrows;
+ task.rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
+ task.src_es = concat_type_size(src->type);
+ task.dst_es = dst_es;
+ task.div_ne1 = *div_ne1;
+ task.div_ne2_ne1 = *div_ne2_ne1;
+
+ work_queue_run(octx->ctx->hvx_queue, concat_regular_cvt_worker, &task, n_hvx);
}
-static int concat_regular(struct htp_ops_context * octx, int dim, uint32_t type_size) {
+static int concat_regular(struct htp_ops_context * octx, const struct htp_concat_kernel_params * kparams) {
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * src1 = octx->src[1];
const struct htp_tensor * dst = octx->dst;
+ const int dim = kparams->dim;
+
+ if (src0->type != dst->type || src1->type != dst->type) {
+ if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
+ if (kparams->vtcm_size > octx->ctx->vtcm_size) {
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+ }
struct htp_tensor view0 = *dst;
struct htp_tensor view1 = *dst;
@@ -301,27 +646,29 @@ static int concat_regular(struct htp_ops_context * octx, int dim, uint32_t type_
nrows1 = range1.count;
}
- dma_queue * q = octx->ctx->dma[0];
-
- dma_cpy_sametype_sameshape_range(q, &view0, src0, type_size, rstart0, nrows0);
- dma_cpy_sametype_sameshape_range(q, &view1, src1, type_size, rstart1, nrows1);
- dma_queue_flush(q);
+ concat_regular_side(octx, &view0, src0, rstart0, nrows0,
+ &kparams->u.regular.div_ne01, &kparams->u.regular.div_ne02_ne01);
+ concat_regular_side(octx, &view1, src1, rstart1, nrows1,
+ &kparams->u.regular.div_ne11, &kparams->u.regular.div_ne12_ne11);
return HTP_STATUS_OK;
}
-static int concat_transposed(struct htp_ops_context * octx, const struct htp_concat_kernel_params * kparams, uint32_t type_size) {
+static int concat_transposed(struct htp_ops_context * octx, const struct htp_concat_kernel_params * kparams) {
if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
return HTP_STATUS_INVAL_PARAMS;
}
- const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * src1 = octx->src[1];
+ const struct htp_tensor * dst = octx->dst;
const uint32_t total_rows = dst->ne[1];
uint32_t row_start = 0;
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -334,27 +681,492 @@ static int concat_transposed(struct htp_ops_context * octx, const struct htp_con
return HTP_STATUS_VTCM_TOO_SMALL;
}
- const uint32_t n_hvx = octx->n_hvx;
+ const uint32_t n_hvx = octx->n_hvx;
+ const uint32_t src0_es = concat_type_size(src0->type);
+ const uint32_t src1_es = concat_type_size(src1->type);
+ const uint32_t dst_es = concat_type_size(dst->type);
- struct htp_concat_transposed_vtcm_layout layout;
- htp_concat_transposed_vtcm_layout_build(&layout, octx->src[0]->ne[0], octx->src[1]->ne[0], type_size, n_hvx);
+ const bool is_src0_transposed = (src0->nb[0] > src0->nb[1]);
+ const bool is_src1_transposed = (src1->nb[0] > src1->nb[1]);
uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base;
- struct htp_concat_context cctx;
- cctx.octx = octx;
- cctx.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad0);
- cctx.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad1);
- cctx.spad0_size_per_hvx = layout.src0_spad_size_per_hvx;
- cctx.spad1_size_per_hvx = layout.src1_spad_size_per_hvx;
- cctx.row_start = row_start;
- cctx.nrows = nrows;
- cctx.nplanes = dst->ne[2] * dst->ne[3];
- cctx.div_ne2 = kparams->u.transposed.div_ne2;
- cctx.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
-
- work_queue_func_t worker_func = (type_size == 4) ? concat_2d_f32_transposed : concat_2d_f16_transposed;
- work_queue_run(octx->ctx->hvx_queue, worker_func, &cctx, n_hvx);
+ if (!is_src0_transposed && is_src1_transposed) {
+ struct htp_concat_transposed_vtcm_layout layout;
+ htp_concat_transposed_vtcm_layout_build(&layout, src0->ne[0], src1->ne[0], src0_es, src1_es, dst_es, n_hvx);
+
+ struct htp_concat_context cctx;
+ cctx.octx = octx;
+ cctx.lead_src = src0;
+ cctx.trans_src = src1;
+ cctx.dst_view = dst;
+ cctx.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad0);
+ cctx.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad1);
+ cctx.spad2_base = layout.cvt_spad_size_per_hvx > 0 ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad2) : NULL;
+ cctx.spad0_size_per_hvx = layout.src0_spad_size_per_hvx;
+ cctx.spad1_size_per_hvx = layout.src1_spad_size_per_hvx;
+ cctx.spad2_size_per_hvx = layout.cvt_spad_size_per_hvx;
+ cctx.row_start = row_start;
+ cctx.nrows = nrows;
+ cctx.nplanes = dst->ne[2] * dst->ne[3];
+ cctx.div_ne2 = kparams->u.transposed.div_ne2;
+ cctx.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
+
+ work_queue_run(octx->ctx->hvx_queue, concat_2d_transposed_worker, &cctx, n_hvx);
+ return HTP_STATUS_OK;
+ }
+
+ struct htp_tensor view0 = *dst;
+ struct htp_tensor view1 = *dst;
+ view0.ne[0] = src0->ne[0];
+ view1.ne[0] = src1->ne[0];
+ view1.data += src0->ne[0] * dst_es;
+
+ if (src0->ne[0] > 0) {
+ struct htp_concat_transposed_vtcm_layout layout0;
+ htp_concat_transposed_vtcm_layout_build(&layout0, 0, src0->ne[0], dst_es, src0_es, dst_es, n_hvx);
+
+ struct htp_concat_context cctx0;
+ cctx0.octx = octx;
+ cctx0.lead_src = NULL;
+ cctx0.trans_src = src0;
+ cctx0.dst_view = &view0;
+ cctx0.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout0.off_spad0);
+ cctx0.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout0.off_spad1);
+ cctx0.spad2_base = layout0.cvt_spad_size_per_hvx > 0 ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout0.off_spad2) : NULL;
+ cctx0.spad0_size_per_hvx = layout0.src0_spad_size_per_hvx;
+ cctx0.spad1_size_per_hvx = layout0.src1_spad_size_per_hvx;
+ cctx0.spad2_size_per_hvx = layout0.cvt_spad_size_per_hvx;
+ cctx0.row_start = row_start;
+ cctx0.nrows = nrows;
+ cctx0.nplanes = dst->ne[2] * dst->ne[3];
+ cctx0.div_ne2 = kparams->u.transposed.div_ne2;
+ cctx0.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
+
+ work_queue_run(octx->ctx->hvx_queue, concat_2d_transposed_worker, &cctx0, n_hvx);
+ }
+
+ if (is_src1_transposed) {
+ if (src1->ne[0] > 0) {
+ struct htp_concat_transposed_vtcm_layout layout1;
+ htp_concat_transposed_vtcm_layout_build(&layout1, 0, src1->ne[0], dst_es, src1_es, dst_es, n_hvx);
+
+ struct htp_concat_context cctx1;
+ cctx1.octx = octx;
+ cctx1.lead_src = NULL;
+ cctx1.trans_src = src1;
+ cctx1.dst_view = &view1;
+ cctx1.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout1.off_spad0);
+ cctx1.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout1.off_spad1);
+ cctx1.spad2_base = layout1.cvt_spad_size_per_hvx > 0 ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout1.off_spad2) : NULL;
+ cctx1.spad0_size_per_hvx = layout1.src0_spad_size_per_hvx;
+ cctx1.spad1_size_per_hvx = layout1.src1_spad_size_per_hvx;
+ cctx1.spad2_size_per_hvx = layout1.cvt_spad_size_per_hvx;
+ cctx1.row_start = row_start;
+ cctx1.nrows = nrows;
+ cctx1.nplanes = dst->ne[2] * dst->ne[3];
+ cctx1.div_ne2 = kparams->u.transposed.div_ne2;
+ cctx1.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
+
+ work_queue_run(octx->ctx->hvx_queue, concat_2d_transposed_worker, &cctx1, n_hvx);
+ }
+ } else if (src1->ne[0] > 0) {
+ const uint32_t total_rows_1 = src1->ne[1] * src1->ne[2] * src1->ne[3];
+ uint32_t rstart1 = 0, nrows1 = total_rows_1;
+ if (octx->ctx->mdev.count > 1) {
+ const struct htp_tensor_mdev_range range1 = htp_tensor_mdev_partition(
+ total_rows_1, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ 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);
+ }
+
+ return HTP_STATUS_OK;
+}
+
+typedef void (*concat_gather_compute_fn_t)(
+ uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec,
+ const struct htp_gather_rows_params * restrict kparams,
+ const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur);
+
+struct concat_gather_rows_mixed_task {
+ struct htp_ops_context * octx;
+ const struct htp_tensor * a;
+ const struct htp_tensor * b;
+ dma_addr_t dst;
+ uint32_t r_start;
+ uint32_t rows;
+ uint32_t rows_per_hvx;
+ uint32_t src0_es;
+ uint32_t src1_es;
+ uint32_t dst_es;
+ const struct htp_gather_rows_params * kparams;
+ concat_gather_compute_fn_t compute;
+};
+
+static __attribute__((noinline)) void concat_gather_rows_init_tables_f32(
+ HVX_Vector * tab, HVX_Vector * inc,
+ const struct htp_gather_rows_params * kparams,
+ uint32_t a_reg_nb1, uint32_t b_reg_nb1) {
+
+ const int32_t s_a = (int32_t) (kparams->rg * a_reg_nb1);
+ const int32_t s_b = (int32_t) (kparams->rg * b_reg_nb1);
+ uint32_t row = 0;
+ uint32_t col = 0;
+ int32_t t_buf[32] __attribute__((aligned(128)));
+ int32_t s_buf[32] __attribute__((aligned(128)));
+ for (uint32_t k = 0; k < kparams->vg; k++) {
+ for (uint32_t lane = 0; lane < 32; lane++) {
+ if (col < kparams->na) {
+ t_buf[lane] = (int32_t) (row * a_reg_nb1 + col * 4);
+ s_buf[lane] = s_a;
+ } else {
+ t_buf[lane] = (int32_t) (kparams->v1 + (col - kparams->na) * kparams->span1 + row * b_reg_nb1);
+ s_buf[lane] = s_b;
+ }
+ if (++col == kparams->ne) {
+ col = 0;
+ row++;
+ }
+ }
+ tab[k] = *(const HVX_Vector *) t_buf;
+ inc[k] = *(const HVX_Vector *) s_buf;
+ }
+}
+
+static __attribute__((noinline)) void concat_gather_rows_init_tables_f16(
+ HVX_Vector * tab, HVX_Vector * inc,
+ const struct htp_gather_rows_params * kparams,
+ uint32_t a_reg_nb1, uint32_t b_reg_nb1) {
+
+ const int16_t s_a = (int16_t) (kparams->rg * a_reg_nb1);
+ const int16_t s_b = (int16_t) (kparams->rg * b_reg_nb1);
+ uint32_t row = 0;
+ uint32_t col = 0;
+ int16_t t_buf[64] __attribute__((aligned(128)));
+ int16_t s_buf[64] __attribute__((aligned(128)));
+ for (uint32_t k = 0; k < kparams->vg; k++) {
+ for (uint32_t lane = 0; lane < 64; lane++) {
+ if (col < kparams->na) {
+ t_buf[lane] = (int16_t) (row * a_reg_nb1 + col * 2);
+ s_buf[lane] = s_a;
+ } else {
+ t_buf[lane] = (int16_t) (kparams->v1 + (col - kparams->na) * kparams->span1 + row * b_reg_nb1);
+ s_buf[lane] = s_b;
+ }
+ if (++col == kparams->ne) {
+ col = 0;
+ row++;
+ }
+ }
+ tab[k] = *(const HVX_Vector *) t_buf;
+ inc[k] = *(const HVX_Vector *) s_buf;
+ }
+}
+
+static __attribute__((noinline)) void concat_gather_compute_f32_vg1(
+ uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec,
+ const struct htp_gather_rows_params * restrict kparams,
+ const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) {
+ (void) cur;
+ const uint32_t region_size = kparams->region_size;
+ HVX_Vector vcur = tab[0];
+ const HVX_Vector vinc = inc[0];
+ #pragma unroll(4)
+ for (uint32_t v = 0; v < nvec; v++) {
+ Q6_vgather_ARMVw((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur);
+ vcur = Q6_Vw_vadd_VwVw(vcur, vinc);
+ }
+}
+
+static __attribute__((noinline)) void concat_gather_compute_f32_vgn(
+ uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec,
+ const struct htp_gather_rows_params * restrict kparams,
+ const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) {
+ const uint32_t vg = kparams->vg;
+ const uint32_t region_size = kparams->region_size;
+ for (uint32_t k = 0; k < vg; k++) {
+ cur[k] = tab[k];
+ }
+ uint32_t k = 0;
+ #pragma unroll(4)
+ for (uint32_t v = 0; v < nvec; v++) {
+ Q6_vgather_ARMVw((HVX_Vector *) (out + v * 128), (size_t) region, region_size, cur[k]);
+ cur[k] = Q6_Vw_vadd_VwVw(cur[k], inc[k]);
+ if (++k == vg) {
+ k = 0;
+ }
+ }
+}
+
+static __attribute__((noinline)) void concat_gather_compute_f16_vg1(
+ uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec,
+ const struct htp_gather_rows_params * restrict kparams,
+ const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) {
+ (void) cur;
+ const uint32_t region_size = kparams->region_size;
+ HVX_Vector vcur = tab[0];
+ const HVX_Vector vinc = inc[0];
+ #pragma unroll(4)
+ for (uint32_t v = 0; v < nvec; v++) {
+ Q6_vgather_ARMVh((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur);
+ vcur = Q6_Vh_vadd_VhVh(vcur, vinc);
+ }
+}
+
+static __attribute__((noinline)) void concat_gather_compute_f16_vgn(
+ uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec,
+ const struct htp_gather_rows_params * restrict kparams,
+ const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) {
+ const uint32_t vg = kparams->vg;
+ const uint32_t region_size = kparams->region_size;
+ for (uint32_t k = 0; k < vg; k++) {
+ cur[k] = tab[k];
+ }
+ uint32_t k = 0;
+ #pragma unroll(4)
+ for (uint32_t v = 0; v < nvec; v++) {
+ Q6_vgather_ARMVh((HVX_Vector *) (out + v * 128), (size_t) region, region_size, cur[k]);
+ cur[k] = Q6_Vh_vadd_VhVh(cur[k], inc[k]);
+ if (++k == vg) {
+ k = 0;
+ }
+ }
+}
+
+static inline void concat_gather_rows_dma_in(
+ dma_queue * q,
+ const struct concat_gather_rows_mixed_task * task,
+ uint8_t * region, uint8_t * raw_a, uint8_t * raw_b,
+ uint32_t r, uint32_t nr) {
+
+ const struct htp_tensor * a = task->a;
+ const struct htp_tensor * b = task->b;
+ const struct htp_gather_rows_params * kparams = task->kparams;
+ const uint32_t src0_es = task->src0_es;
+ const uint32_t src1_es = task->src1_es;
+ const uint32_t dst_es = task->dst_es;
+
+ if (kparams->na > 0) {
+ uint8_t * dst_a = (src0_es == dst_es) ? region : raw_a;
+ const size_t a_size = (size_t) (nr - 1) * a->nb[1] + (size_t) kparams->na * src0_es;
+ dma_queue_push(q, dma_make_data(dst_a, a->data + r * a->nb[1]), a_size, a_size, a_size, 1);
+ }
+
+ if (b && kparams->nb > 0) {
+ uint8_t * dst_b = (src1_es == dst_es) ? (region + kparams->v1) : raw_b;
+ if (kparams->b_dense) {
+ const size_t b_size = (size_t) (nr - 1) * b->nb[1] + (size_t) kparams->nb * src1_es;
+ dma_queue_push(q, dma_make_data(dst_b, b->data + r * b->nb[1]), b_size, b_size, b_size, 1);
+ } else {
+ const size_t b_size = (size_t) (nr - 1) * b->nb[1] + src1_es;
+ const size_t dst_span1 = (src1_es == dst_es)
+ ? kparams->span1
+ : (((size_t) kparams->span1 / dst_es) * src1_es);
+ for (uint32_t k = 0; k < kparams->nb; k++) {
+ dma_queue_push(q, dma_make_data(dst_b + k * dst_span1,
+ b->data + (k * b->nb[0] + r * b->nb[1])),
+ b_size, b_size, b_size, 1);
+ }
+ }
+ }
+}
+
+static inline void concat_gather_rows_dma_out(
+ dma_queue * q,
+ const struct concat_gather_rows_mixed_task * task,
+ uint8_t * out, uint32_t r, uint32_t nr) {
+
+ const struct htp_gather_rows_params * kparams = task->kparams;
+ const size_t out_size = (size_t) nr * kparams->ne * task->dst_es;
+ dma_queue_push(q, dma_make_data(task->dst + r * kparams->ne * task->dst_es, out), out_size, out_size, out_size, 1);
+}
+
+static void concat_gather_rows_mixed_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct concat_gather_rows_mixed_task * task = (const struct concat_gather_rows_mixed_task *) data;
+ const struct htp_gather_rows_params * kparams = task->kparams;
+ const struct htp_tensor * a = task->a;
+ const struct htp_tensor * b = task->b;
+
+ const uint32_t r_offset = MIN(ith * task->rows_per_hvx, task->rows);
+ const uint32_t r_beg = task->r_start + r_offset;
+ const uint32_t r_end = task->r_start + MIN(r_offset + task->rows_per_hvx, task->rows);
+ if (r_beg >= r_end) {
+ return;
+ }
+
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint32_t src0_es = task->src0_es;
+ const uint32_t src1_es = task->src1_es;
+ const uint32_t dst_es = task->dst_es;
+
+ struct htp_concat_gather_rows_vtcm_layout layout;
+ htp_concat_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max,
+ kparams->na, a->nb[1],
+ kparams->nb, b ? b->nb[1] : 0, kparams->b_dense != 0, kparams->span1,
+ kparams->ne, src0_es, src1_es, dst_es);
+
+ uint8_t * base = VTCM_LAYOUT_PTR(uint8_t, task->octx->ctx->vtcm_base, (size_t) ith * kparams->slice);
+ HVX_Vector * tab = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_tab);
+ HVX_Vector * inc = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_inc);
+ HVX_Vector * cur = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_cur);
+
+ uint8_t * region[2] = {
+ VTCM_LAYOUT_PTR(uint8_t, base, layout.off_region0),
+ VTCM_LAYOUT_PTR(uint8_t, base, layout.off_region1),
+ };
+ uint8_t * out[2] = {
+ VTCM_LAYOUT_PTR(uint8_t, base, layout.off_out0),
+ VTCM_LAYOUT_PTR(uint8_t, base, layout.off_out1),
+ };
+ uint8_t * raw_a[2] = {
+ layout.off_raw_a0 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_a0) : NULL,
+ layout.off_raw_a1 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_a1) : NULL,
+ };
+ uint8_t * raw_b[2] = {
+ layout.off_raw_b0 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_b0) : NULL,
+ layout.off_raw_b1 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_b1) : NULL,
+ };
+
+ const uint32_t a_elem_stride = a->nb[1] / src0_es;
+ const uint32_t b_elem_stride = b ? (b->nb[1] / src1_es) : 0;
+ const uint32_t a_reg_nb1 = a_elem_stride * dst_es;
+ const uint32_t b_reg_nb1 = b_elem_stride * dst_es;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, (uint16_t) r_beg);
+ if (dst_es == 4) {
+ concat_gather_rows_init_tables_f32(tab, inc, kparams, a_reg_nb1, b_reg_nb1);
+ } else {
+ concat_gather_rows_init_tables_f16(tab, inc, kparams, a_reg_nb1, b_reg_nb1);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, (uint16_t) r_beg);
+
+ dma_queue * q = th->dma_q;
+ const uint32_t n_in = (kparams->na > 0 ? 1 : 0) + ((b && kparams->nb > 0) ? (kparams->b_dense ? 1 : kparams->nb) : 0);
+ const uint32_t nr_max = kparams->nr_max;
+ const uint32_t nr0 = MIN(nr_max, r_end - r_beg);
+
+ dma_queue_push(q, dma_make_data(task->dst, out[0]), 0, 0, 0, 0); // dummy out
+ concat_gather_rows_dma_in(q, task, region[0], raw_a[0], raw_b[0], r_beg, nr0);
+
+ const uint32_t r1 = r_beg + nr_max;
+ if (r1 < r_end) {
+ const uint32_t nr1 = MIN(nr_max, r_end - r1);
+ dma_queue_push(q, dma_make_data(task->dst, out[1]), 0, 0, 0, 0); // dummy out
+ concat_gather_rows_dma_in(q, task, region[1], raw_a[1], raw_b[1], r1, nr1);
+ }
+
+ uint32_t buf = 0;
+ for (uint32_t r = r_beg; r < r_end; r += nr_max) {
+ const uint32_t nr = MIN(nr_max, r_end - r);
+ const uint32_t next_buf = buf ^ 1;
+
+ dma_queue_pop(q); // complete out
+ for (uint32_t i = 0; i < n_in; i++) {
+ dma_queue_pop(q);
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
+ if (src0_es != dst_es && kparams->na > 0) {
+ const uint32_t a_elems = (nr - 1) * a_elem_stride + kparams->na;
+ if (dst_es == 4) {
+ concat_cvt_f16_to_f32_aa(region[buf], raw_a[buf], a_elems);
+ } else {
+ concat_cvt_f32_to_f16_aa(region[buf], raw_a[buf], a_elems);
+ }
+ }
+ if (src1_es != dst_es && b && kparams->nb > 0) {
+ const uint32_t b_elems = kparams->b_dense
+ ? ((nr - 1) * b_elem_stride + kparams->nb)
+ : (kparams->nb * (kparams->span1 / dst_es));
+ if (dst_es == 4) {
+ concat_cvt_f16_to_f32_aa(region[buf] + kparams->v1, raw_b[buf], b_elems);
+ } else {
+ concat_cvt_f32_to_f16_aa(region[buf] + kparams->v1, raw_b[buf], b_elems);
+ }
+ }
+
+ const uint32_t nvec = (dst_es == 4)
+ ? ((nr * kparams->ne + 31) >> 5)
+ : ((nr * kparams->ne + 63) >> 6);
+ task->compute(out[buf], region[buf], nvec, kparams, tab, inc, cur);
+ hvx_gather_sync(out[buf]);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
+
+ concat_gather_rows_dma_out(q, task, out[buf], r, nr);
+
+ const uint32_t r_prefetch = r + 2 * nr_max;
+ if (r_prefetch < r_end) {
+ const uint32_t nr_prefetch = MIN(nr_max, r_end - r_prefetch);
+ concat_gather_rows_dma_in(q, task, region[buf], raw_a[buf], raw_b[buf], r_prefetch, nr_prefetch);
+ }
+
+ buf = next_buf;
+ }
+ dma_queue_flush(q);
+}
+
+static int concat_gather_rows(
+ struct htp_ops_context * octx,
+ const struct htp_tensor * src0,
+ const struct htp_tensor * src1,
+ const struct htp_gather_rows_params * kparams,
+ uint32_t n_hvx) {
+
+ const struct htp_tensor * dst = octx->dst;
+ if (src0->type == dst->type && src1->type == dst->type) {
+ return htp_gather_rows(octx, src0, src1, kparams, n_hvx);
+ }
+
+ if (!htp_ops_context_set_n_hvx(octx, n_hvx)) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
+
+ if (kparams->slice * octx->n_hvx > octx->ctx->vtcm_size) {
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ const uint32_t total_rows = kparams->total_rows;
+ uint32_t r_start = 0;
+ uint32_t r_count = total_rows;
+ if (octx->ctx->mdev.count > 1) {
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ total_rows, kparams->rg, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ r_start = range.start;
+ r_count = range.count;
+ }
+
+ if (r_count == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ const uint32_t dst_es = concat_type_size(dst->type);
+
+ struct concat_gather_rows_mixed_task task;
+ task.octx = octx;
+ task.a = src0;
+ task.b = src1;
+ task.dst = dst->data;
+ task.r_start = r_start;
+ task.rows = r_count;
+ task.rows_per_hvx = kparams->rows_per_hvx;
+ task.src0_es = concat_type_size(src0->type);
+ task.src1_es = concat_type_size(src1->type);
+ task.dst_es = dst_es;
+ task.kparams = kparams;
+
+ if (dst_es == 2) {
+ task.compute = (kparams->vg == 1) ? concat_gather_compute_f16_vg1 : concat_gather_compute_f16_vgn;
+ } else {
+ task.compute = (kparams->vg == 1) ? concat_gather_compute_f32_vg1 : concat_gather_compute_f32_vgn;
+ }
+
+ work_queue_run(octx->ctx->hvx_queue, concat_gather_rows_mixed_worker, &task, octx->n_hvx);
return HTP_STATUS_OK;
}
@@ -362,22 +1174,20 @@ int op_concat(struct htp_ops_context * octx) {
const struct htp_concat_kernel_params * kparams = (const struct htp_concat_kernel_params *) octx->kernel_params;
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * src1 = octx->src[1];
- const struct htp_tensor * dst = octx->dst;
int status = HTP_STATUS_OK;
- const uint32_t type_size = (dst->type == HTP_TYPE_F32 || dst->type == HTP_TYPE_I32) ? 4 : 2;
switch (kparams->kernel_type) {
case HTP_CONCAT_KERNEL_REGULAR:
- status = concat_regular(octx, kparams->dim, type_size);
+ status = concat_regular(octx, kparams);
break;
case HTP_CONCAT_KERNEL_TRANSPOSED:
- status = concat_transposed(octx, kparams, type_size);
+ status = concat_transposed(octx, kparams);
break;
case HTP_CONCAT_KERNEL_GATHER_ROWS:
- status = htp_gather_rows(octx, src0, src1, &kparams->u.gather, kparams->n_hvx);
+ status = concat_gather_rows(octx, src0, src1, &kparams->u.gather, kparams->n_hvx);
break;
default:
diff --git a/ggml/src/ggml-hexagon/htp/concat-ops.h b/ggml/src/ggml-hexagon/htp/concat-ops.h
index 580fe0e15..228cd81bb 100644
--- a/ggml/src/ggml-hexagon/htp/concat-ops.h
+++ b/ggml/src/ggml-hexagon/htp/concat-ops.h
@@ -14,6 +14,15 @@ enum htp_concat_kernel_type {
HTP_CONCAT_KERNEL_GATHER_ROWS = 3,
};
+#define HTP_CONCAT_REG_BLK_BYTES (32 * 1024)
+
+struct htp_concat_regular_params {
+ struct fastdiv_values div_ne01;
+ struct fastdiv_values div_ne02_ne01;
+ struct fastdiv_values div_ne11;
+ struct fastdiv_values div_ne12_ne11;
+};
+
struct htp_concat_transposed_params {
struct fastdiv_values div_ne2;
};
@@ -27,6 +36,7 @@ struct htp_concat_kernel_params {
uint32_t vtcm_size;
union {
+ struct htp_concat_regular_params regular;
struct htp_concat_transposed_params transposed;
struct htp_gather_rows_params gather;
} u;
@@ -38,11 +48,198 @@ static_assert(sizeof(struct htp_concat_kernel_params) <= 128, "htp_concat_kernel
_Static_assert(sizeof(struct htp_concat_kernel_params) <= 128, "htp_concat_kernel_params is too large for kernel_params blob");
#endif
+struct htp_concat_gather_rows_vtcm_layout {
+ size_t off_tab;
+ size_t off_inc;
+ size_t off_cur;
+ size_t off_region0;
+ size_t off_out0;
+ size_t off_region1;
+ size_t off_out1;
+ size_t off_raw_a0;
+ size_t off_raw_a1;
+ size_t off_raw_b0;
+ size_t off_raw_b1;
+ size_t total_per_hvx;
+};
+
+static inline void htp_concat_gather_rows_vtcm_layout_build(
+ struct htp_concat_gather_rows_vtcm_layout * L,
+ uint32_t vg,
+ uint32_t region_size,
+ uint32_t nr_max,
+ uint32_t na, uint32_t a_nb1,
+ uint32_t nb, uint32_t b_nb1, bool b_dense, uint32_t span1,
+ uint32_t ne,
+ uint32_t src0_es, uint32_t src1_es, uint32_t dst_es) {
+
+ const size_t vec_bytes = (size_t) vg * 128;
+ const size_t region_aligned = hex_round_up(region_size, 128);
+ const size_t out_aligned = hex_round_up(region_aligned + (size_t) nr_max * ne * dst_es, 128) - region_aligned;
+
+ size_t raw_a_aligned = 0;
+ if (src0_es != dst_es && na > 0) {
+ raw_a_aligned = hex_round_up((size_t) (nr_max - 1) * a_nb1 + (size_t) na * src0_es, 128);
+ }
+
+ size_t raw_b_aligned = 0;
+ if (src1_es != dst_es && nb > 0) {
+ const size_t raw_span1 = ((size_t) span1 / dst_es) * src1_es;
+ const size_t raw_b_bytes = b_dense
+ ? ((size_t) (nr_max - 1) * b_nb1 + (size_t) nb * src1_es)
+ : ((size_t) nb * raw_span1);
+ raw_b_aligned = hex_round_up(raw_b_bytes, 128);
+ }
+
+ size_t off = 0;
+ VTCM_LAYOUT_ALLOC(off, off_tab, vec_bytes);
+ VTCM_LAYOUT_ALLOC(off, off_inc, vec_bytes);
+ VTCM_LAYOUT_ALLOC(off, off_cur, vec_bytes);
+ VTCM_LAYOUT_ALLOC(off, off_region0, region_aligned);
+ VTCM_LAYOUT_ALLOC(off, off_out0, out_aligned);
+ VTCM_LAYOUT_ALLOC(off, off_region1, region_aligned);
+ VTCM_LAYOUT_ALLOC(off, off_out1, out_aligned);
+ if (raw_a_aligned > 0) {
+ VTCM_LAYOUT_ALLOC(off, off_raw_a0, raw_a_aligned);
+ VTCM_LAYOUT_ALLOC(off, off_raw_a1, raw_a_aligned);
+ } else {
+ L->off_raw_a0 = 0;
+ L->off_raw_a1 = 0;
+ }
+ if (raw_b_aligned > 0) {
+ VTCM_LAYOUT_ALLOC(off, off_raw_b0, raw_b_aligned);
+ VTCM_LAYOUT_ALLOC(off, off_raw_b1, raw_b_aligned);
+ } else {
+ L->off_raw_b0 = 0;
+ L->off_raw_b1 = 0;
+ }
+ L->total_per_hvx = off;
+}
+
+static inline bool htp_concat_gather_rows_solve_layout(
+ struct htp_gather_rows_params * kparams,
+ uint32_t na, uint32_t a_nb1,
+ uint32_t nb, uint32_t b_nb1, bool b_dense,
+ uint32_t src0_es, uint32_t src1_es, uint32_t dst_es,
+ uint32_t total_rows,
+ uint32_t n_hvx,
+ uint32_t mdev_count,
+ uint32_t vtcm_size) {
+
+ if (src0_es == dst_es && src1_es == dst_es) {
+ return htp_gather_rows_solve_layout(kparams, na, a_nb1, nb, b_nb1, b_dense, dst_es, dst_es, total_rows, n_hvx, mdev_count, vtcm_size);
+ }
+
+ const uint32_t max_ne0 = 128 / dst_es;
+ const uint32_t ne = na + nb;
+ if (ne == 0 || ne > max_ne0) {
+ return false;
+ }
+
+ if ((dst_es != 4 && dst_es != 2) || (src0_es != 4 && src0_es != 2) || (src1_es != 4 && src1_es != 2)) {
+ return false;
+ }
+ if ((a_nb1 % src0_es) != 0 || (b_nb1 % src1_es) != 0) {
+ return false;
+ }
+
+ const uint32_t a_reg_nb1 = (a_nb1 / src0_es) * dst_es;
+ const uint32_t b_reg_nb1 = (b_nb1 / src1_es) * dst_es;
+
+ const uint32_t v_lanes = 128 / dst_es;
+ const uint32_t g = hex_gcd_u32(ne, v_lanes);
+ const uint32_t rg = v_lanes / g;
+ const uint32_t vg = ne / g;
+
+ const uint32_t slice = (vtcm_size / n_hvx) & ~127u;
+ const uint32_t total_chunks = total_rows / rg;
+ const uint32_t chunks_per_dev = (total_chunks + mdev_count - 1) / mdev_count;
+ const uint32_t max_rows_per_dev = (mdev_count > 1 && total_chunks >= mdev_count)
+ ? (chunks_per_dev * rg + (total_rows % rg))
+ : total_rows;
+ const uint32_t rows_per_hvx = hex_round_up((max_rows_per_dev + n_hvx - 1) / n_hvx, rg);
+
+ const uint32_t fixed = 3 * vg * 128;
+ const uint32_t per_row_reg_a = na > 0 ? a_reg_nb1 : 0;
+ const uint32_t per_row_reg_b = nb > 0 ? (b_dense ? b_reg_nb1 : nb * b_reg_nb1) : 0;
+ const uint32_t per_row_raw_a = (src0_es != dst_es && na > 0) ? a_nb1 : 0;
+ const uint32_t per_row_raw_b = (src1_es != dst_es && nb > 0) ? (b_dense ? b_nb1 : nb * b_nb1) : 0;
+ const uint32_t per_row = per_row_reg_a + per_row_reg_b + per_row_raw_a + per_row_raw_b + ne * dst_es;
+ if (slice <= fixed + 2 * per_row * rg) {
+ return false;
+ }
+
+ const uint32_t avail_per_buf = (slice - fixed) / 2;
+ uint32_t nr_max = MIN(avail_per_buf / per_row, rows_per_hvx);
+ if (dst_es == 2) {
+ const uint32_t per_row_region = per_row_reg_a + per_row_reg_b;
+ if (per_row_region > 0) {
+ nr_max = MIN(nr_max, (32768u - 256u) / per_row_region);
+ }
+ }
+ nr_max = (nr_max / rg) * rg;
+
+ uint32_t v1 = 0;
+ uint32_t span1 = 0;
+ uint32_t region_size = 0;
+
+ while (nr_max > 0) {
+ v1 = na > 0 ? hex_round_up((nr_max - 1) * a_reg_nb1 + na * dst_es, 128) : 0;
+ if (nb > 0) {
+ if (b_dense) {
+ span1 = dst_es;
+ region_size = v1 + (nr_max - 1) * b_reg_nb1 + nb * dst_es;
+ } else {
+ span1 = (nr_max - 1) * b_reg_nb1 + dst_es;
+ region_size = v1 + nb * span1;
+ }
+ } else {
+ span1 = 0;
+ region_size = v1;
+ }
+
+ struct htp_concat_gather_rows_vtcm_layout layout;
+ htp_concat_gather_rows_vtcm_layout_build(&layout, vg, region_size, nr_max,
+ na, a_nb1, nb, b_nb1, b_dense, span1, ne,
+ src0_es, src1_es, dst_es);
+
+ if ((dst_es != 2 || region_size <= 32768) && layout.total_per_hvx <= slice) {
+ break;
+ }
+
+ nr_max -= rg;
+ }
+
+ if (nr_max == 0) {
+ return false;
+ }
+
+ kparams->na = na;
+ kparams->nb = nb;
+ kparams->ne = ne;
+ kparams->rg = rg;
+ kparams->vg = vg;
+ kparams->nr_max = nr_max;
+ kparams->v1 = v1;
+ kparams->span1 = span1;
+ kparams->region_size = region_size;
+ kparams->slice = slice;
+ kparams->total_rows = total_rows;
+ kparams->rows_per_hvx = rows_per_hvx;
+ kparams->b_dense = b_dense ? 1 : 0;
+ kparams->pad[0] = 0;
+ kparams->pad[1] = 0;
+ kparams->pad[2] = 0;
+ return true;
+}
+
struct htp_concat_transposed_vtcm_layout {
uint32_t src0_spad_size_per_hvx;
uint32_t src1_spad_size_per_hvx;
+ uint32_t cvt_spad_size_per_hvx;
size_t off_spad0;
size_t off_spad1;
+ size_t off_spad2;
uint32_t total_bytes;
};
@@ -50,24 +247,39 @@ static inline void htp_concat_transposed_vtcm_layout_build(
struct htp_concat_transposed_vtcm_layout * L,
uint32_t src0_ne0,
uint32_t src1_ne0,
- uint32_t type_size,
+ uint32_t src0_es,
+ uint32_t src1_es,
+ uint32_t dst_es,
uint32_t n_hvx) {
// src1_ne0 is processed in chunks of block_cols tokens, so VTCM does not grow with the batch
uint32_t block_rows = 128;
- uint32_t block_cols = (type_size == 4) ? 256 : 512;
+ uint32_t block_cols = (src1_es == 2 && dst_es == 2) ? 512 : 256;
+ uint32_t col_align = (src1_es == 2 || dst_es == 2) ? 64 : 32;
// +1 element spreads the gather lanes across VTCM, so they do not serialize on one path
- uint32_t spad1_stride = block_rows * type_size + type_size;
- uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, (type_size == 4) ? 32 : 64), block_cols);
- uint32_t spad0_row_bytes = hex_round_up(src0_ne0 * type_size, 128) + block_cols_padded * type_size;
+ uint32_t spad1_stride = block_rows * src1_es + src1_es;
+ uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, col_align), block_cols);
+
+ uint32_t dst_src0_row_padded = hex_round_up(src0_ne0 * dst_es, 128);
+ uint32_t raw_src0_row_padded = (src0_es != dst_es) ? hex_round_up(src0_ne0 * src0_es, 128) : 0;
+ uint32_t spad0_row_bytes = MAX(dst_src0_row_padded + block_cols_padded * dst_es, raw_src0_row_padded);
+
+ uint32_t cvt1_bytes = (src1_es != dst_es) ? (block_rows * 64 * src1_es) : 0;
+ uint32_t cvt0_bytes = (src0_es != dst_es) ? dst_src0_row_padded : 0;
// double-buffered: two slots per thread
L->src0_spad_size_per_hvx = 2 * block_rows * spad0_row_bytes;
L->src1_spad_size_per_hvx = 2 * block_cols_padded * spad1_stride;
+ L->cvt_spad_size_per_hvx = hex_round_up(MAX(cvt1_bytes, cvt0_bytes), 128);
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_spad0, (size_t) n_hvx * L->src0_spad_size_per_hvx);
VTCM_LAYOUT_ALLOC(off, off_spad1, (size_t) n_hvx * L->src1_spad_size_per_hvx);
+ if (L->cvt_spad_size_per_hvx > 0) {
+ VTCM_LAYOUT_ALLOC(off, off_spad2, (size_t) n_hvx * L->cvt_spad_size_per_hvx);
+ } else {
+ L->off_spad2 = 0;
+ }
L->total_bytes = (uint32_t) off;
}
diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-ops.c
index 67e8ec67b..1bcab08fd 100644
--- a/ggml/src/ggml-hexagon/htp/conv2d-ops.c
+++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.c
@@ -1,6 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-
#include <HAP_farf.h>
#include <stdint.h>
#include <string.h>
@@ -1406,9 +1403,8 @@ static void conv2d_hmx_win_wrows_dma(const struct htp_conv2d_win_context * wc, d
}
// K-contiguous kernel (k = cin * T + t): transpose the 32 cout rows of a packing unit to k rows of 32 cout, then into tiles
-__attribute__((noinline))
-static void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin,
- HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) {
+static inline void conv2d_hmx_win_wrows_pack_impl(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin,
+ HVX_Vector * scratch, uint32_t unit, uint32_t n_cs, const bool is_f16) {
const struct htp_conv2d_kernel_params * kp = wc->kp;
const struct htp_tensor * kernel = wc->octx->src[0];
@@ -1419,7 +1415,6 @@ static void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc,
const uint32_t T = KW * KH;
const uint32_t n_cc = kp->window.n_cc;
const uint32_t CS = kp->window.w_cs;
- const bool is_f16 = kernel->type == HTP_TYPE_F16;
const uint32_t kpw = is_f16 ? 64 : 32; // k per vector
const uint32_t rstep = is_f16 ? 64 : 128; // bytes per transposed k row
@@ -1491,6 +1486,27 @@ static void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc,
}
}
+__attribute__((noinline))
+static void conv2d_hmx_win_wrows_pack_f16(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin,
+ HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) {
+ conv2d_hmx_win_wrows_pack_impl(wc, raw, xr, vin, scratch, unit, n_cs, true);
+}
+
+__attribute__((noinline))
+static void conv2d_hmx_win_wrows_pack_f32(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin,
+ HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) {
+ conv2d_hmx_win_wrows_pack_impl(wc, raw, xr, vin, scratch, unit, n_cs, false);
+}
+
+static inline void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin,
+ HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) {
+ if (wc->octx->src[0]->type == HTP_TYPE_F16) {
+ conv2d_hmx_win_wrows_pack_f16(wc, raw, xr, vin, scratch, unit, n_cs);
+ } else {
+ conv2d_hmx_win_wrows_pack_f32(wc, raw, xr, vin, scratch, unit, n_cs);
+ }
+}
+
static void conv2d_hmx_win_wpack_rows(const struct htp_conv2d_win_context * wc, const htp_thread_t * th, unsigned int nth, unsigned int ith) {
struct htp_ops_context * octx = wc->octx;
const struct htp_conv2d_kernel_params * kp = wc->kp;
@@ -1807,7 +1823,6 @@ static void conv2d_hmx_win_croutons_fold(const struct htp_conv2d_win_context * w
const uint32_t Cin = input->ne[2];
const uint32_t N = input->ne[3];
const uint32_t KW = octx->src[0]->ne[0];
- const uint32_t nch = KW * Cin;
const uint32_t SR = kp->window.sr;
const uint32_t IHS = kp->window.ihs;
const int32_t p0 = octx->op_params[2];
@@ -1984,7 +1999,6 @@ static void conv2d_hmx_win_croutons_fold_cwhn(const struct htp_conv2d_win_contex
}
static void conv2d_hmx_win_pack(const struct htp_conv2d_win_context * wc, const htp_thread_t * th, unsigned int nth, unsigned int ith) {
- struct htp_ops_context * octx = wc->octx;
const struct htp_conv2d_kernel_params * kp = wc->kp;
uint32_t ts;
diff --git a/ggml/src/ggml-hexagon/htp/cpy-ops.c b/ggml/src/ggml-hexagon/htp/cpy-ops.c
index cdf4d8ec6..8f37fc703 100644
--- a/ggml/src/ggml-hexagon/htp/cpy-ops.c
+++ b/ggml/src/ggml-hexagon/htp/cpy-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <qurt_memory.h>
@@ -13,6 +9,7 @@
#include "ggml-common.h"
#include "cpy-ops.h"
#include "dma-copy.h"
+#include "dma-pipeline.h"
#include "htp-ctx.h"
#include "htp-fence.h"
#include "htp-ops.h"
@@ -20,9 +17,19 @@
#include "hvx-utils.h"
#include "gather-rows.h"
+typedef void (*cpy_convert_block_fn_t)(
+ uint8_t * restrict dst_spad,
+ const uint8_t * restrict src_spad,
+ uint32_t nr,
+ uint32_t ne00,
+ uint32_t dst_row_stride,
+ uint32_t src0_row_stride
+);
+
struct htp_copy_context {
struct htp_ops_context * octx;
const struct htp_copy_kernel_params * kparams;
+ cpy_convert_block_fn_t convert_block;
uint32_t row_start;
uint32_t nrows;
@@ -41,29 +48,29 @@ struct htp_copy_context {
uint32_t tiles_per_hvx;
};
-#define cpy_preamble \
- const struct htp_tensor *src0 = octx->src[0]; \
- const struct htp_tensor *dst = octx->dst; \
- \
- const uint32_t ne00 = src0->ne[0]; \
- const uint32_t ne01 = src0->ne[1]; \
- const uint32_t ne02 = src0->ne[2]; \
- const uint32_t ne03 = src0->ne[3]; \
- \
- const uint32_t nb00 = src0->nb[0]; \
- const uint32_t nb01 = src0->nb[1]; \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb0 = dst->nb[0]; \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
+#define cpy_preamble \
+ const struct htp_tensor *src0 = octx->src[0]; \
+ const struct htp_tensor *dst = octx->dst; \
+ \
+ 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)) 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)) 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)) 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];
#define DEFINE_CPY_RESHAPE(NAME, ELEM_TYPE, ELEM_SIZE) \
static void cpy_thread_##NAME##_reshape(const htp_thread_t * th, unsigned int nth, unsigned int ith, \
@@ -332,85 +339,120 @@ static void cpy_thread_transpose(const htp_thread_t * th, unsigned int nth, unsi
dma_queue_flush(dma_q);
}
-#define DEFINE_CPY_CONVERT_SAMESHAPE(NAME, CONV_FUNC) \
-static void cpy_thread_##NAME##_sameshape(const htp_thread_t * th, unsigned int nth, \
- unsigned int ith, void * data) { \
- struct htp_copy_context * ct = (struct htp_copy_context *) data; \
- struct htp_ops_context * octx = ct->octx; \
- cpy_preamble; \
- \
- const uint32_t dr = ct->src0_nrows_per_hvx; \
- const uint32_t ir0 = ct->row_start + dr * ith; \
- const uint32_t ir1 = MIN(ir0 + dr, ct->row_start + ct->nrows); \
- if (ir0 >= ir1) return; \
- \
- dma_queue * dma_q = th->dma_q; \
- struct htp_thread_trace * tr = th->trace; \
- \
- const struct htp_copy_convert_params * cvt = &ct->kparams->u.convert; \
- const struct htp_copy_convert_vtcm_layout * L = &ct->layout; \
- const uint32_t src0_buf_size = L->src0_buf_size; \
- const uint32_t dst_buf_size = L->dst_buf_size; \
- const uint32_t src0_row_stride = L->src0_row_stride; \
- const uint32_t dst_row_stride = L->dst_row_stride; \
- const uint32_t blk_rows = L->blk_rows; \
- uint8_t * vtcm_src0_base = ct->vtcm_src0 + ith * L->spad0_size_per_hvx; \
- uint8_t * vtcm_dst_base = ct->vtcm_dst + ith * L->spad1_size_per_hvx; \
- const uint32_t src0_row_size = ne00 * ct->kparams->src0_type_size; \
- const uint32_t dst_row_size = ne00 * ct->kparams->dst_type_size; \
- \
- const uint32_t ne02_ne01 = ne02 * ne01; \
- uint32_t i03 = fastdiv(ir0, &cvt->div_ne02_ne01); \
- uint32_t rem = ir0 - i03 * ne02_ne01; \
- uint32_t i02 = fastdiv(rem, &cvt->div_ne01); \
- uint32_t i01 = rem - i02 * ne01; \
- \
- struct cpy_row_cursor f = { ir0, i01, i02, i03 }; \
- struct cpy_row_cursor c = f; \
- \
- for (uint32_t b = 0; b < 2 && f.r < ir1; ++b) { \
- uint8_t * src_spad = vtcm_src0_base + b * src0_buf_size; \
- uint8_t * dst_spad = vtcm_dst_base + b * dst_buf_size; \
- const uint32_t nr = MIN(blk_rows, MIN(ne01 - f.i01, ir1 - f.r)); \
- dma_addr_t f_src0_addr = src0->data + f.i01*nb01 + f.i02*nb02 + f.i03*nb03; \
- dma_queue_push(dma_q, dma_make_data(dst->data, dst_spad), \
- dst_row_size, dst_buf_size, dst_row_size, 0); \
- dma_queue_push(dma_q, dma_make_data(src_spad, f_src0_addr), \
- src0_row_stride, nb01, src0_row_size, nr); \
- cpy_cursor_advance(&f, nr, ne01, ne02); \
- } \
- \
- for (uint32_t blk = 0; c.r < ir1; ++blk) { \
- const uint32_t nr = MIN(blk_rows, MIN(ne01 - c.i01, ir1 - c.r)); \
- uint8_t * dst_spad = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).src; \
- uint8_t * src_spad = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; \
- \
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) blk); \
- for (uint32_t r = 0; r < nr; ++r) { \
- CONV_FUNC(dst_spad + r * dst_row_stride, src_spad + r * src0_row_stride, ne00); \
- } \
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) blk); \
- \
- dma_addr_t c_dst_addr = dst->data + c.i01*nb1 + c.i02*nb2 + c.i03*nb3; \
- dma_queue_push(dma_q, dma_make_data(c_dst_addr, dst_spad), \
- nb1, dst_row_stride, dst_row_size, nr); \
- cpy_cursor_advance(&c, nr, ne01, ne02); \
- \
- if (f.r < ir1) { \
- const uint32_t fnr = MIN(blk_rows, MIN(ne01 - f.i01, ir1 - f.r)); \
- dma_addr_t f_src0_addr = src0->data + f.i01*nb01 + f.i02*nb02 + f.i03*nb03; \
- dma_queue_push(dma_q, dma_make_data(src_spad, f_src0_addr), \
- src0_row_stride, nb01, src0_row_size, fnr); \
- cpy_cursor_advance(&f, fnr, ne01, ne02); \
- } \
- } \
- dma_queue_flush(dma_q); \
+#define DEFINE_CPY_CONVERT_BLOCK(NAME, CONV_FUNC) \
+static void __attribute__((noinline)) cpy_convert_block_##NAME( \
+ uint8_t * restrict dst_spad, \
+ const uint8_t * restrict src_spad, \
+ uint32_t nr, \
+ uint32_t ne00, \
+ uint32_t dst_row_stride, \
+ uint32_t src0_row_stride \
+) { \
+ for (uint32_t r = 0; r < nr; ++r) { \
+ CONV_FUNC(dst_spad + r * dst_row_stride, src_spad + r * src0_row_stride, ne00); \
+ } \
}
-DEFINE_CPY_CONVERT_SAMESHAPE(f16_f32, hvx_copy_f16_f32_aa)
-DEFINE_CPY_CONVERT_SAMESHAPE(f32_f16, hvx_copy_f32_f16_aa)
-DEFINE_CPY_CONVERT_SAMESHAPE(i32_f32, hvx_copy_i32_f32_aa)
-DEFINE_CPY_CONVERT_SAMESHAPE(f32_i32, hvx_copy_f32_i32_aa)
+DEFINE_CPY_CONVERT_BLOCK(f16_f32, hvx_copy_f16_f32_aa)
+DEFINE_CPY_CONVERT_BLOCK(f32_f16, hvx_copy_f32_f16_aa)
+DEFINE_CPY_CONVERT_BLOCK(i32_f32, hvx_copy_i32_f32_aa)
+DEFINE_CPY_CONVERT_BLOCK(f32_i32, hvx_copy_f32_i32_aa)
+
+struct cpy_convert_pipe_state {
+ dma_addr_t src0_data;
+ dma_addr_t dst_data;
+ cpy_convert_block_fn_t convert_block;
+ uint32_t ne00, ne01, ne02;
+ uint32_t nb01, nb02, nb03;
+ uint32_t nb1, nb2, nb3;
+ uint32_t src0_row_size;
+ uint32_t dst_row_size;
+ uint32_t src0_row_stride;
+ uint32_t dst_row_stride;
+ uint32_t blk_rows;
+ uint32_t ir1;
+ struct cpy_row_cursor cur;
+};
+
+static bool cpy_convert_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx;
+ if (s->cur.r >= s->ir1) {
+ return false;
+ }
+ const uint32_t nr = MIN(s->blk_rows, MIN(s->ne01 - s->cur.i01, s->ir1 - s->cur.r));
+ task->row = s->cur.i01;
+ task->off = s->cur.i02;
+ task->len = nr;
+ task->aux = s->cur.i03;
+ cpy_cursor_advance(&s->cur, nr, s->ne01, s->ne02);
+ return true;
+}
+
+static void cpy_convert_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx;
+ const dma_addr_t src0_addr = s->src0_data + (size_t) task->row * s->nb01 + (size_t) task->off * s->nb02 + (size_t) task->aux * s->nb03;
+ dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr),
+ s->src0_row_stride, s->nb01, s->src0_row_size, task->len);
+}
+
+static void cpy_convert_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx;
+ s->convert_block((uint8_t *) out_spad, (const uint8_t *) in_spad, task->len, s->ne00, s->dst_row_stride, s->src0_row_stride);
+}
+
+static void cpy_convert_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx;
+ const dma_addr_t dst_addr = s->dst_data + (size_t) task->row * s->nb1 + (size_t) task->off * s->nb2 + (size_t) task->aux * s->nb3;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->nb1, s->dst_row_stride, s->dst_row_size, task->len);
+}
+
+static void cpy_thread_convert_sameshape(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ struct htp_copy_context * ct = (struct htp_copy_context *) data;
+ struct htp_ops_context * octx = ct->octx;
+ cpy_preamble;
+
+ const uint32_t dr = ct->src0_nrows_per_hvx;
+ const uint32_t ir0 = ct->row_start + dr * ith;
+ const uint32_t ir1 = MIN(ir0 + dr, ct->row_start + ct->nrows);
+ if (ir0 >= ir1) {
+ return;
+ }
+
+ const struct htp_copy_convert_params * cvt = &ct->kparams->u.convert;
+ const struct htp_copy_convert_vtcm_layout * L = &ct->layout;
+
+ uint8_t * vtcm_src0_base = ct->vtcm_src0 + ith * L->spad0_size_per_hvx;
+ uint8_t * vtcm_dst_base = ct->vtcm_dst + ith * L->spad1_size_per_hvx;
+ void * in_buf[2] = { vtcm_src0_base, vtcm_src0_base + L->src0_buf_size };
+ void * out_buf[2] = { vtcm_dst_base, vtcm_dst_base + L->dst_buf_size };
+
+ const uint32_t ne02_ne01 = ne02 * ne01;
+ uint32_t i03 = fastdiv(ir0, &cvt->div_ne02_ne01);
+ uint32_t rem = ir0 - i03 * ne02_ne01;
+ uint32_t i02 = fastdiv(rem, &cvt->div_ne01);
+ uint32_t i01 = rem - i02 * ne01;
+
+ struct cpy_convert_pipe_state s = {
+ .src0_data = src0->data,
+ .dst_data = dst->data,
+ .convert_block = ct->convert_block,
+ .ne00 = ne00, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1, .nb2 = nb2, .nb3 = nb3,
+ .src0_row_size = ne00 * ct->kparams->src0_type_size,
+ .dst_row_size = ne00 * ct->kparams->dst_type_size,
+ .src0_row_stride = L->src0_row_stride,
+ .dst_row_stride = L->dst_row_stride,
+ .blk_rows = L->blk_rows,
+ .ir1 = ir1,
+ .cur = { ir0, i01, i02, i03 },
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ cpy_convert_next_task, cpy_convert_push_in, cpy_convert_compute, cpy_convert_push_out);
+}
static int cpy_scalar(struct htp_ops_context * octx, const struct htp_copy_kernel_params * kparams) {
if (octx->ctx->mdev.count > 1 && octx->ctx->mdev.idx > 0) {
@@ -550,26 +592,24 @@ static int cpy_sameshape_convert(struct htp_ops_context * octx, const struct htp
ct.vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, ct.layout.off_src0);
ct.vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, ct.layout.off_dst);
- work_queue_func_t copy_fun = NULL;
if (dst->type == HTP_TYPE_F16 && src0->type == HTP_TYPE_F32) {
- copy_fun = cpy_thread_f16_f32_sameshape;
+ ct.convert_block = cpy_convert_block_f16_f32;
} else if (dst->type == HTP_TYPE_F32 && src0->type == HTP_TYPE_F16) {
- copy_fun = cpy_thread_f32_f16_sameshape;
+ ct.convert_block = cpy_convert_block_f32_f16;
} else if (dst->type == HTP_TYPE_I32 && src0->type == HTP_TYPE_F32) {
- copy_fun = cpy_thread_i32_f32_sameshape;
+ ct.convert_block = cpy_convert_block_i32_f32;
} else if (dst->type == HTP_TYPE_F32 && src0->type == HTP_TYPE_I32) {
- copy_fun = cpy_thread_f32_i32_sameshape;
+ ct.convert_block = cpy_convert_block_f32_i32;
} else {
return HTP_STATUS_NO_SUPPORT;
}
- work_queue_run(octx->ctx->hvx_queue, copy_fun, &ct, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, cpy_thread_convert_sameshape, &ct, n_hvx);
return HTP_STATUS_OK;
}
static int cpy_reshape(struct htp_ops_context * octx, const struct htp_copy_kernel_params * kparams) {
const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
return HTP_STATUS_INVAL_PARAMS;
diff --git a/ggml/src/ggml-hexagon/htp/cumsum-ops.c b/ggml/src/ggml-hexagon/htp/cumsum-ops.c
index 292a05455..08be5134b 100644
--- a/ggml/src/ggml-hexagon/htp/cumsum-ops.c
+++ b/ggml/src/ggml-hexagon/htp/cumsum-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -16,48 +12,44 @@
#include "hvx-types.h"
#include "hvx-utils.h"
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "cumsum-ops.h"
-#define htp_cumsum_tensors_preamble \
- const struct htp_tensor * restrict src0 = octx->src[0]; \
- const struct htp_tensor * restrict dst = octx->dst; \
- \
- const uint32_t ne00 = src0->ne[0]; \
- const uint32_t ne01 = src0->ne[1]; \
- const uint32_t ne02 = src0->ne[2]; \
- const uint32_t ne03 = src0->ne[3]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb00 = src0->nb[0]; \
- const uint32_t nb01 = src0->nb[1]; \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t nb0 = dst->nb[0]; \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
-
struct htp_cumsum_context {
struct htp_ops_context * octx;
- size_t src_row_size;
- size_t dst_row_size;
- size_t src_row_size_aligned;
- size_t dst_row_size_aligned;
- uint32_t rows_per_hvx;
- uint32_t total_rows;
- uint32_t row_start;
+ dma_pipe_compute_io_fn compute;
+ uint8_t * vtcm_src0;
+ uint8_t * vtcm_dst;
+ size_t src0_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
+ size_t src_elem_size;
+ size_t dst_elem_size;
+ size_t src_row_size;
+ size_t dst_row_size;
+ size_t src_chunk_bytes_aligned;
+ size_t dst_chunk_bytes_aligned;
+ uint32_t chunk_elems;
+ uint32_t rows_per_hvx;
+ uint32_t total_rows;
+ uint32_t row_start;
};
-#define htp_cumsum_preamble \
- struct htp_cumsum_context * cctx = (struct htp_cumsum_context *) data; \
- struct htp_ops_context * octx = cctx->octx; \
- htp_cumsum_tensors_preamble; \
- dma_queue * dma_q = th->dma_q;
+struct cumsum_pipe_state {
+ dma_addr_t src_data;
+ dma_addr_t dst_data;
+ size_t src_elem_size;
+ size_t dst_elem_size;
+ size_t src_row_size;
+ size_t dst_row_size;
+ size_t src_chunk_bytes_aligned;
+ size_t dst_chunk_bytes_aligned;
+ uint32_t ne00;
+ uint32_t chunk_elems;
+ uint32_t row;
+ uint32_t row_end;
+ uint32_t off;
+ uint32_t carry_bits;
+};
// ---------------------------------------------------------------------------
// HVX prefix scan helpers
@@ -71,7 +63,7 @@ static inline HVX_Vector hvx_cumsum_vadd(HVX_Vector a, HVX_Vector b) {
static inline HVX_Vector hvx_cumsum_vadd(HVX_Vector a, HVX_Vector b) {
return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(a, b));
}
-#endif // __HVX_ARCH__ > 75
+#endif // __HVX_ARCH__ > 75
static inline HVX_Vector hvx_prefix_scan_f32(HVX_Vector v, HVX_Vector carry_in) {
const HVX_Vector zero = Q6_V_vsplat_R(0);
@@ -90,126 +82,229 @@ static inline HVX_Vector hvx_splat_last_f32(HVX_Vector v) {
return hvx_vec_repl4(Q6_V_vror_VR(v, 124));
}
-static inline void hvx_cumsum_row_f32(const float * restrict src, float * restrict dst, uint32_t n) {
+static inline HVX_Vector hvx_cumsum_clamp_f16(HVX_Vector v) {
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ return Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v));
+}
+
+static void __attribute__((noinline)) cumsum_compute_f32_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
+
+ const float * restrict src = (const float *) in_spad;
+ float * restrict dst = (float *) out_spad;
+
+ const uint32_t n = task->len;
const uint32_t nvec = n >> 5;
const uint32_t nloe = n & (VLEN_FP32 - 1);
- HVX_Vector carry = Q6_V_vsplat_R(0);
+ HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits);
for (uint32_t i = 0; i < nvec; i++) {
- HVX_Vector v = *((const HVX_UVector *) (src + i * VLEN_FP32));
+ HVX_Vector v = *((const HVX_Vector *) (src + i * VLEN_FP32));
v = hvx_prefix_scan_f32(v, carry);
- hvx_vec_store_u(dst + i * VLEN_FP32, VLEN, v);
+ *((HVX_Vector *) (dst + i * VLEN_FP32)) = v;
carry = hvx_splat_last_f32(v);
}
if (nloe) {
- float acc = hvx_vec_get_f32(carry);
- const float * src_tail = src + nvec * VLEN_FP32;
- float * dst_tail = dst + nvec * VLEN_FP32;
- for (uint32_t i = 0; i < nloe; i++) {
- acc += src_tail[i];
- dst_tail[i] = acc;
- }
+ HVX_Vector v = *((const HVX_Vector *) (src + nvec * VLEN_FP32));
+ v = hvx_prefix_scan_f32(v, carry);
+ hvx_vec_store_a(dst + nvec * VLEN_FP32, nloe * sizeof(float), v);
}
+
+ s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0);
}
-// ---------------------------------------------------------------------------
-// Per thread worker: Double-buffered DMA
-// ---------------------------------------------------------------------------
+static void __attribute__((noinline)) cumsum_compute_f16_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
-static void cumsum_thread_f32_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_cumsum_preamble;
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) in_spad;
+ HVX_Vector * restrict vdst = (HVX_Vector *) out_spad;
- const uint32_t ir0 = cctx->row_start + cctx->rows_per_hvx * ith;
- const uint32_t ir1 = MIN(ir0 + cctx->rows_per_hvx, cctx->row_start + cctx->total_rows);
+ const uint32_t n = task->len;
+ const uint32_t nvec = n >> 6;
+ const uint32_t nloe = n & (VLEN_FP16 - 1);
- if (ir0 >= ir1) {
- return;
+ HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits);
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[i]);
+ const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry);
+ carry = hvx_splat_last_f32(v0);
+ const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry);
+ carry = hvx_splat_last_f32(v1);
+ vdst[i] = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1));
+ }
+
+ if (nloe) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[nvec]);
+ const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry);
+ carry = hvx_splat_last_f32(v0);
+ const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry);
+ const HVX_Vector out = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1));
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(__fp16), out);
}
- const size_t src_row_size = cctx->src_row_size;
- const size_t dst_row_size = cctx->dst_row_size;
- const size_t src_row_size_aligned = cctx->src_row_size_aligned;
- const size_t dst_row_size_aligned = cctx->dst_row_size_aligned;
+ s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0);
+}
+
+static void __attribute__((noinline)) cumsum_compute_f16_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
+
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) in_spad;
+ HVX_Vector * restrict vdst = (HVX_Vector *) out_spad;
- const dma_addr_t src_data = src0->data;
- const dma_addr_t dst_data = dst->data;
+ const uint32_t n = task->len;
+ const uint32_t nvec = n >> 6;
+ const uint32_t nloe = n & (VLEN_FP16 - 1);
- uint8_t * src_spad = octx->src0_spad.data + (ith * src_row_size_aligned * 2);
- uint8_t * dst_spad = octx->dst_spad.data + (ith * dst_row_size_aligned * 2);
+ HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits);
- for (uint32_t ir = ir0, spad_idx = 0; ir < ir1 && spad_idx < 2; ir++, spad_idx++) {
- // Dummy dst writeback to establish queue ordering
- dma_queue_push(dma_q,
- dma_make_data(dst_data, dst_spad + (spad_idx * dst_row_size_aligned)),
- dst_row_size, dst_row_size_aligned, dst_row_size, 0);
+ for (uint32_t i = 0; i < nvec; i++) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[i]);
+ const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry);
+ carry = hvx_splat_last_f32(v0);
+ const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry);
+ carry = hvx_splat_last_f32(v1);
+ vdst[2 * i] = v0;
+ vdst[2 * i + 1] = v1;
+ }
- dma_queue_push(dma_q,
- dma_make_data(src_spad + (spad_idx * src_row_size_aligned),
- src_data + (ir * src_row_size)),
- src_row_size_aligned, src_row_size, src_row_size, 1);
+ if (nloe) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[nvec]);
+ const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry);
+ if (nloe > VLEN_FP32) {
+ vdst[2 * nvec] = v0;
+ carry = hvx_splat_last_f32(v0);
+ const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry);
+ hvx_vec_store_a(&vdst[2 * nvec + 1], (nloe - VLEN_FP32) * sizeof(float), v1);
+ } else {
+ hvx_vec_store_a(&vdst[2 * nvec], nloe * sizeof(float), v0);
+ }
}
- struct htp_thread_trace * tr = th->trace;
+ s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0);
+}
- for (uint32_t ir = ir0; ir < ir1; ir++) {
- float * dst_spad_row = (float *) dma_queue_pop(dma_q).src;
- float * src_spad_row = (float *) dma_queue_pop(dma_q).dst;
+static void __attribute__((noinline)) cumsum_compute_f32_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- hvx_cumsum_row_f32(src_spad_row, dst_spad_row, ne00);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) in_spad;
+ HVX_Vector * restrict vdst = (HVX_Vector *) out_spad;
- dma_queue_push(dma_q,
- dma_make_data(dst_data + (ir * dst_row_size), dst_spad_row),
- dst_row_size, dst_row_size_aligned, dst_row_size, 1);
+ const uint32_t n = task->len;
+ const uint32_t nvec = n >> 6;
+ const uint32_t nloe = n & (VLEN_FP16 - 1);
- const uint32_t next_row = ir + 2;
- if (next_row < ir1) {
- dma_queue_push(dma_q,
- dma_make_data(src_spad_row, src_data + (next_row * src_row_size)),
- src_row_size_aligned, src_row_size, src_row_size, 1);
- }
+ HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits);
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ const HVX_Vector v0 = hvx_prefix_scan_f32(vsrc[2 * i], carry);
+ carry = hvx_splat_last_f32(v0);
+ const HVX_Vector v1 = hvx_prefix_scan_f32(vsrc[2 * i + 1], carry);
+ carry = hvx_splat_last_f32(v1);
+ vdst[i] = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1));
}
- dma_queue_flush(dma_q);
+ if (nloe) {
+ const HVX_Vector v0 = hvx_prefix_scan_f32(vsrc[2 * nvec], carry);
+ carry = hvx_splat_last_f32(v0);
+ const HVX_Vector v1 = (nloe > VLEN_FP32) ? hvx_prefix_scan_f32(vsrc[2 * nvec + 1], carry) : Q6_V_vzero();
+ const HVX_Vector out = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1));
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(__fp16), out);
+ }
- FARF(HIGH, "cumsum-f32-dma %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n",
- ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ir0, ir1,
- dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]);
+ s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0);
}
// ---------------------------------------------------------------------------
-// Per thread worker: Direct HVX (no DMA)
+// Per thread worker: Double-buffered DMA pipeline
// ---------------------------------------------------------------------------
-static void cumsum_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_cumsum_preamble;
+static bool cumsum_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
+ if (s->row >= s->row_end) {
+ return false;
+ }
+
+ const uint32_t rem = s->ne00 - s->off;
+ const uint32_t len = MIN(s->chunk_elems, rem);
+
+ task->row = s->row;
+ task->off = s->off;
+ task->len = len;
+ task->aux = 0;
+
+ s->off += len;
+ if (s->off >= s->ne00) {
+ s->off = 0;
+ s->row++;
+ }
+ return true;
+}
+
+static void cumsum_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
+
+ const size_t bytes = (size_t) task->len * s->src_elem_size;
+ const dma_addr_t src = s->src_data + (size_t) task->row * s->src_row_size + (size_t) task->off * s->src_elem_size;
+
+ dma_queue_push(dma_q, dma_make_data(in_spad, src), s->src_chunk_bytes_aligned, bytes, bytes, 1);
+}
+
+static void cumsum_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx;
+
+ const size_t bytes = (size_t) task->len * s->dst_elem_size;
+ const dma_addr_t dst = s->dst_data + (size_t) task->row * s->dst_row_size + (size_t) task->off * s->dst_elem_size;
- const uint8_t * src_data = (const uint8_t *) src0->data;
- uint8_t * dst_data = (uint8_t *) dst->data;
+ dma_queue_push(dma_q, dma_make_data(dst, out_spad), bytes, s->dst_chunk_bytes_aligned, bytes, 1);
+}
+
+static void cumsum_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_cumsum_context * cctx = (struct htp_cumsum_context *) data;
+ struct htp_ops_context * octx = cctx->octx;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
const uint32_t ir0 = cctx->row_start + cctx->rows_per_hvx * ith;
const uint32_t ir1 = MIN(ir0 + cctx->rows_per_hvx, cctx->row_start + cctx->total_rows);
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0);
-
- for (uint32_t ir = ir0; ir < ir1; ir++) {
- const float * restrict src_row = (const float *) (src_data + ir * cctx->src_row_size);
- float * restrict dst_row = (float *) (dst_data + ir * cctx->dst_row_size);
- hvx_cumsum_row_f32(src_row, dst_row, ne00);
+ if (ir0 >= ir1) {
+ return;
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0);
+ uint8_t * src_spad = cctx->vtcm_src0 + ith * cctx->src0_bytes_per_hvx;
+ uint8_t * dst_spad = cctx->vtcm_dst + ith * cctx->dst_bytes_per_hvx;
+ void * in_buf[2] = { src_spad, src_spad + cctx->src_chunk_bytes_aligned };
+ void * out_buf[2] = { dst_spad, dst_spad + cctx->dst_chunk_bytes_aligned };
+
+ struct cumsum_pipe_state s = {
+ .src_data = src0->data,
+ .dst_data = dst->data,
+ .src_elem_size = cctx->src_elem_size,
+ .dst_elem_size = cctx->dst_elem_size,
+ .src_row_size = cctx->src_row_size,
+ .dst_row_size = cctx->dst_row_size,
+ .src_chunk_bytes_aligned = cctx->src_chunk_bytes_aligned,
+ .dst_chunk_bytes_aligned = cctx->dst_chunk_bytes_aligned,
+ .ne00 = src0->ne[0],
+ .chunk_elems = cctx->chunk_elems,
+ .row = ir0,
+ .row_end = ir1,
+ .off = 0,
+ .carry_bits = 0,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, cumsum_next_task, cumsum_push_in, cctx->compute, cumsum_push_out);
- FARF(HIGH, "cumsum-f32 %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n",
+ FARF(HIGH, "cumsum %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n",
ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ir0, ir1,
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]);
}
-int op_cumsum_f32(struct htp_ops_context * octx) {
+static int op_cumsum_impl(struct htp_ops_context * octx, size_t src_elem_size, size_t dst_elem_size, dma_pipe_compute_io_fn compute) {
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
const struct htp_cumsum_kernel_params * kparams =
@@ -223,9 +318,7 @@ int op_cumsum_f32(struct htp_ops_context * octx) {
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -240,51 +333,48 @@ int op_cumsum_f32(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
- if (!kparams->use_dma && (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst))) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
struct htp_cumsum_vtcm_layout layout = { 0 };
- if (kparams->use_dma) {
- htp_cumsum_vtcm_layout_build(&layout, src_row_size, dst_row_size, n_hvx);
-
- octx->src0_spad.size_per_hvx = layout.src0_bytes_per_hvx;
- octx->dst_spad.size_per_hvx = layout.dst_bytes_per_hvx;
- octx->src0_spad.size = n_hvx * layout.src0_bytes_per_hvx;
- octx->dst_spad.size = n_hvx * layout.dst_bytes_per_hvx;
- octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0);
- octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst);
- octx->src0_spad.src = NULL;
- octx->dst_spad.src = NULL;
- }
+ htp_cumsum_vtcm_layout_build(&layout, (size_t) kparams->chunk_elems * src_elem_size, (size_t) kparams->chunk_elems * dst_elem_size, n_hvx);
struct htp_cumsum_context cctx = {
- .octx = octx,
- .src_row_size = src_row_size,
- .dst_row_size = dst_row_size,
- .src_row_size_aligned = layout.src_row_size_aligned,
- .dst_row_size_aligned = layout.dst_row_size_aligned,
- .rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
- .total_rows = nrows,
- .row_start = row_start,
+ .octx = octx,
+ .compute = compute,
+ .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0),
+ .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst),
+ .src0_bytes_per_hvx = layout.src0_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
+ .src_elem_size = src_elem_size,
+ .dst_elem_size = dst_elem_size,
+ .src_row_size = src_row_size,
+ .dst_row_size = dst_row_size,
+ .src_chunk_bytes_aligned = layout.src_chunk_bytes_aligned,
+ .dst_chunk_bytes_aligned = layout.dst_chunk_bytes_aligned,
+ .chunk_elems = kparams->chunk_elems,
+ .rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
+ .total_rows = nrows,
+ .row_start = row_start,
};
- if (kparams->use_dma) {
- work_queue_run(octx->ctx->hvx_queue, cumsum_thread_f32_dma, &cctx, n_hvx);
- } else {
- work_queue_run(octx->ctx->hvx_queue, cumsum_thread_f32, &cctx, n_hvx);
- }
+ work_queue_run(octx->ctx->hvx_queue, cumsum_thread, &cctx, n_hvx);
return HTP_STATUS_OK;
}
int op_cumsum(struct htp_ops_context * octx) {
- const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
- switch (dst->type) {
- case HTP_TYPE_F32:
- return op_cumsum_f32(octx);
- default:
- return HTP_STATUS_NO_SUPPORT;
+ if (src0->type == HTP_TYPE_F32 && dst->type == HTP_TYPE_F32) {
+ return op_cumsum_impl(octx, sizeof(float), sizeof(float), cumsum_compute_f32_f32);
+ }
+ if (src0->type == HTP_TYPE_F16 && dst->type == HTP_TYPE_F16) {
+ return op_cumsum_impl(octx, sizeof(__fp16), sizeof(__fp16), cumsum_compute_f16_f16);
+ }
+ if (src0->type == HTP_TYPE_F16 && dst->type == HTP_TYPE_F32) {
+ return op_cumsum_impl(octx, sizeof(__fp16), sizeof(float), cumsum_compute_f16_f32);
+ }
+ if (src0->type == HTP_TYPE_F32 && dst->type == HTP_TYPE_F16) {
+ return op_cumsum_impl(octx, sizeof(float), sizeof(__fp16), cumsum_compute_f32_f16);
}
+ return HTP_STATUS_NO_SUPPORT;
}
diff --git a/ggml/src/ggml-hexagon/htp/cumsum-ops.h b/ggml/src/ggml-hexagon/htp/cumsum-ops.h
index 48f4053ed..457357eeb 100644
--- a/ggml/src/ggml-hexagon/htp/cumsum-ops.h
+++ b/ggml/src/ggml-hexagon/htp/cumsum-ops.h
@@ -9,22 +9,22 @@ struct htp_cumsum_vtcm_layout {
size_t total_bytes;
size_t off_src0;
size_t off_dst;
- size_t src_row_size_aligned;
- size_t dst_row_size_aligned;
+ size_t src_chunk_bytes_aligned;
+ size_t dst_chunk_bytes_aligned;
size_t src0_bytes_per_hvx;
size_t dst_bytes_per_hvx;
};
static inline void htp_cumsum_vtcm_layout_build(
struct htp_cumsum_vtcm_layout * L,
- size_t src_row_size,
- size_t dst_row_size,
+ size_t src_chunk_bytes,
+ size_t dst_chunk_bytes,
uint32_t n_hvx
) {
- L->src_row_size_aligned = hex_round_up(src_row_size, 128);
- L->dst_row_size_aligned = hex_round_up(dst_row_size, 128);
- L->src0_bytes_per_hvx = 2 * L->src_row_size_aligned;
- L->dst_bytes_per_hvx = 2 * L->dst_row_size_aligned;
+ L->src_chunk_bytes_aligned = hex_round_up(src_chunk_bytes, 128);
+ L->dst_chunk_bytes_aligned = hex_round_up(dst_chunk_bytes, 128);
+ L->src0_bytes_per_hvx = 2 * L->src_chunk_bytes_aligned;
+ L->dst_bytes_per_hvx = 2 * L->dst_chunk_bytes_aligned;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
@@ -36,7 +36,7 @@ static inline void htp_cumsum_vtcm_layout_build(
struct htp_cumsum_kernel_params {
uint32_t n_hvx;
uint32_t total_rows;
- uint32_t use_dma;
+ uint32_t chunk_elems;
uint32_t vtcm_size;
};
diff --git a/ggml/src/ggml-hexagon/htp/diag-ops.c b/ggml/src/ggml-hexagon/htp/diag-ops.c
index ea1a50316..1f1aae281 100644
--- a/ggml/src/ggml-hexagon/htp/diag-ops.c
+++ b/ggml/src/ggml-hexagon/htp/diag-ops.c
@@ -1,5 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -15,149 +13,189 @@
#include "hex-utils.h"
#include "hvx-copy.h"
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "diag-ops.h"
-#define htp_diag_tensors_preamble \
- const struct htp_tensor * restrict src0 = octx->src[0]; \
- const struct htp_tensor * restrict dst = octx->dst; \
- \
- const uint32_t ne02 = src0->ne[2]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
-
struct htp_diag_context {
- struct htp_ops_context * octx;
+ struct htp_ops_context * octx;
const struct htp_diag_kernel_params * kparams;
- size_t src_batch_size;
- size_t dst_row_size;
- size_t src_batch_size_aligned;
- size_t dst_row_size_aligned;
- uint32_t batches_per_hvx;
- uint32_t total_batches;
- uint32_t batch_start;
+ dma_pipe_compute_io_fn compute;
+ uint8_t * vtcm_src0;
+ uint8_t * vtcm_dst;
+ size_t src0_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
+ size_t elem_size;
+ size_t dst_chunk_bytes_aligned;
+ uint32_t chunk_elems;
+ uint32_t batches_per_hvx;
+ uint32_t total_batches;
+ uint32_t batch_start;
};
-#define htp_diag_preamble \
- struct htp_diag_context * dctx = (struct htp_diag_context *) data; \
- struct htp_ops_context * octx = dctx->octx; \
- htp_diag_tensors_preamble;
-
-static inline void hvx_diag_row_f32(const float * restrict src, float * restrict dst,
- uint32_t row_idx, uint32_t n) {
- hvx_splat_f32_a((uint8_t *) dst, 0.0f, n);
- dst[row_idx] = src[row_idx];
-}
+struct diag_pipe_state {
+ dma_addr_t src_data;
+ dma_addr_t dst_data;
+ size_t elem_size;
+ size_t dst_chunk_bytes_aligned;
+ uint32_t ne0;
+ uint32_t ne1;
+ uint32_t ne02;
+ uint32_t nb02;
+ uint32_t nb03;
+ uint32_t nb1;
+ uint32_t nb2;
+ uint32_t nb3;
+ uint32_t chunk_elems;
+ uint32_t ib;
+ uint32_t ib_end;
+ uint32_t i1;
+ uint32_t off;
+ const struct fastdiv_values * div_ne02;
+};
-// ---------------------------------------------------------------------------
-// Per thread worker: DMA src fetch, compute in VTCM, DMA dst writeback
-// ---------------------------------------------------------------------------
+static void __attribute__((noinline)) diag_compute_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ (void) ctx;
-static void diag_thread_f32_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_diag_preamble;
- dma_queue * dma_q = th->dma_q;
+ uint8_t * restrict dst = (uint8_t *) out_spad;
+ const uint8_t * restrict src = (const uint8_t *) in_spad;
- const uint32_t ib0 = dctx->batch_start + dctx->batches_per_hvx * ith;
- const uint32_t ib1 = MIN(ib0 + dctx->batches_per_hvx, dctx->batch_start + dctx->total_batches);
+ hvx_splat_f32_a(dst, 0.0f, task->len);
- if (ib0 >= ib1) {
- return;
+ if (task->row >= task->off && task->row < task->off + task->len) {
+ const uint32_t local_idx = task->row - task->off;
+ const uint32_t vec_idx = local_idx >> 5;
+ const uint32_t b_off = (local_idx & 31u) * sizeof(float);
+ const HVX_Vector src_v = *((const HVX_Vector *) src);
+ const HVX_Vector val_v = Q6_V_vsplat_R(Q6_R_vextract_VR(src_v, 0));
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(float));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &((HVX_Vector *) dst)[vec_idx], val_v);
}
+}
- const size_t src_batch_size = dctx->src_batch_size;
- const size_t dst_row_size = dctx->dst_row_size;
- const size_t src_batch_size_aligned = dctx->src_batch_size_aligned;
- const size_t dst_row_size_aligned = dctx->dst_row_size_aligned;
-
- const dma_addr_t src_data = src0->data;
- const dma_addr_t dst_data = dst->data;
+static void __attribute__((noinline)) diag_compute_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ (void) ctx;
- // 1 src buffer + 1 dst row buffer per thread in VTCM
- uint8_t * src_spad = octx->src0_spad.data + (ith * src_batch_size_aligned);
- uint8_t * dst_spad = octx->dst_spad.data + (ith * dst_row_size_aligned);
+ uint8_t * restrict dst = (uint8_t *) out_spad;
+ const uint8_t * restrict src = (const uint8_t *) in_spad;
- struct htp_thread_trace * tr = th->trace;
+ hvx_splat_u16_a(dst, 0, task->len);
- for (uint32_t ib = ib0; ib < ib1; ib++) {
- const uint32_t i3 = fastdiv(ib, &dctx->kparams->div_ne02);
- const uint32_t i2 = ib - i3 * ne02;
+ if (task->row >= task->off && task->row < task->off + task->len) {
+ const uint32_t local_idx = task->row - task->off;
+ const uint32_t vec_idx = local_idx >> 6;
+ const uint32_t b_off = (local_idx & 63u) * sizeof(__fp16);
+ const HVX_Vector src_v = *((const HVX_Vector *) src);
+ const HVX_Vector val_v = Q6_Vh_vsplat_R(Q6_R_vextract_VR(src_v, 0));
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(__fp16));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &((HVX_Vector *) dst)[vec_idx], val_v);
+ }
+}
- const dma_addr_t src_batch = src_data + i3 * nb03 + i2 * nb02;
+// ---------------------------------------------------------------------------
+// Per thread worker: Double-buffered DMA pipeline
+// ---------------------------------------------------------------------------
- // Fetch source vector into VTCM
- dma_queue_push(dma_q,
- dma_make_data(src_spad, src_batch),
- src_batch_size_aligned, src_batch_size, src_batch_size, 1);
- dma_queue_flush(dma_q);
+static bool diag_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct diag_pipe_state * s = (struct diag_pipe_state *) ctx;
+ if (s->ib >= s->ib_end) {
+ return false;
+ }
- const float * src_spad_f32 = (const float *) src_spad;
- float * dst_spad_f32 = (float *) dst_spad;
+ const uint32_t rem = s->ne0 - s->off;
+ const uint32_t len = MIN(s->chunk_elems, rem);
+
+ task->row = s->i1;
+ task->off = s->off;
+ task->len = len;
+ task->aux = s->ib;
+
+ s->off += len;
+ if (s->off >= s->ne0) {
+ s->off = 0;
+ s->i1++;
+ if (s->i1 >= s->ne1) {
+ s->i1 = 0;
+ s->ib++;
+ }
+ }
+ return true;
+}
- for (uint32_t i1 = 0; i1 < ne1; i1++) {
- // Compute row in VTCM
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (ib * ne1 + i1));
- hvx_diag_row_f32(src_spad_f32, dst_spad_f32, i1, ne0);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (ib * ne1 + i1));
+static void diag_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct diag_pipe_state * s = (struct diag_pipe_state *) ctx;
- // Write completed row back to DDR
- const dma_addr_t dst_row = dst_data + i3 * nb3 + i2 * nb2 + i1 * nb1;
- dma_queue_push(dma_q,
- dma_make_data(dst_row, dst_spad),
- dst_row_size, dst_row_size_aligned, dst_row_size, 1);
- dma_queue_flush(dma_q);
- }
+ if (task->row < task->off || task->row >= task->off + task->len) {
+ dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0);
+ return;
}
- FARF(HIGH, "diag-f32-dma %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n",
- ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ib0, ib1,
- dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]);
+ const uint32_t i3 = fastdiv(task->aux, s->div_ne02);
+ const uint32_t i2 = task->aux - i3 * s->ne02;
+ const dma_addr_t src_elem = s->src_data + (size_t) i3 * s->nb03 + (size_t) i2 * s->nb02 + (size_t) task->row * s->elem_size;
+
+ dma_queue_push(dma_q, dma_make_data(in_spad, src_elem), s->elem_size, s->elem_size, s->elem_size, 1);
}
-// ---------------------------------------------------------------------------
-// Per thread worker: Direct HVX (no DMA)
-// ---------------------------------------------------------------------------
+static void diag_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct diag_pipe_state * s = (struct diag_pipe_state *) ctx;
-static void diag_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_diag_preamble;
+ const uint32_t i3 = fastdiv(task->aux, s->div_ne02);
+ const uint32_t i2 = task->aux - i3 * s->ne02;
+ const size_t bytes = (size_t) task->len * s->elem_size;
+ const dma_addr_t dst = s->dst_data + (size_t) i3 * s->nb3 + (size_t) i2 * s->nb2 + (size_t) task->row * s->nb1 + (size_t) task->off * s->elem_size;
- const uint8_t * src_data = (const uint8_t *) src0->data;
- uint8_t * dst_data = (uint8_t *) dst->data;
+ dma_queue_push(dma_q, dma_make_data(dst, out_spad), bytes, s->dst_chunk_bytes_aligned, bytes, 1);
+}
+
+static void diag_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_diag_context * dctx = (struct htp_diag_context *) data;
+ struct htp_ops_context * octx = dctx->octx;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
const uint32_t ib0 = dctx->batch_start + dctx->batches_per_hvx * ith;
const uint32_t ib1 = MIN(ib0 + dctx->batches_per_hvx, dctx->batch_start + dctx->total_batches);
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ib0);
-
- for (uint32_t ib = ib0; ib < ib1; ib++) {
- const uint32_t i3 = fastdiv(ib, &dctx->kparams->div_ne02);
- const uint32_t i2 = ib - i3 * ne02;
-
- const float * restrict src_batch = (const float *)(src_data + i3 * nb03 + i2 * nb02);
-
- for (uint32_t i1 = 0; i1 < ne1; i1++) {
- float * restrict dst_row = (float *)(dst_data + i3 * nb3 + i2 * nb2 + i1 * nb1);
- hvx_diag_row_f32(src_batch, dst_row, i1, ne0);
- }
+ if (ib0 >= ib1) {
+ return;
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ib0);
+ uint8_t * src_spad = dctx->vtcm_src0 + ith * dctx->src0_bytes_per_hvx;
+ uint8_t * dst_spad = dctx->vtcm_dst + ith * dctx->dst_bytes_per_hvx;
+ void * in_buf[2] = { src_spad, src_spad + 128 };
+ void * out_buf[2] = { dst_spad, dst_spad + dctx->dst_chunk_bytes_aligned };
+
+ struct diag_pipe_state s = {
+ .src_data = src0->data,
+ .dst_data = dst->data,
+ .elem_size = dctx->elem_size,
+ .dst_chunk_bytes_aligned = dctx->dst_chunk_bytes_aligned,
+ .ne0 = dst->ne[0],
+ .ne1 = dst->ne[1],
+ .ne02 = src0->ne[2],
+ .nb02 = src0->nb[2],
+ .nb03 = src0->nb[3],
+ .nb1 = dst->nb[1],
+ .nb2 = dst->nb[2],
+ .nb3 = dst->nb[3],
+ .chunk_elems = dctx->chunk_elems,
+ .ib = ib0,
+ .ib_end = ib1,
+ .i1 = 0,
+ .off = 0,
+ .div_ne02 = &dctx->kparams->div_ne02,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, diag_next_task, diag_push_in, dctx->compute, diag_push_out);
- FARF(HIGH, "diag-f32 %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n",
+ FARF(HIGH, "diag %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n",
ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ib0, ib1,
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]);
}
-int op_diag_f32(struct htp_ops_context * octx) {
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
+static int op_diag_impl(struct htp_ops_context * octx, size_t elem_size, dma_pipe_compute_io_fn compute) {
const struct htp_diag_kernel_params * kparams =
(const struct htp_diag_kernel_params *) octx->kernel_params;
@@ -167,8 +205,7 @@ int op_diag_f32(struct htp_ops_context * octx) {
uint32_t nbatches = total_batches;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = (kparams->can_split != 0) && htp_tensor_mdev_data_aligned(dst);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_batches, can_split ? kparams->batches_per_chunk : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_batches, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
batch_start = range.start;
nbatches = range.count;
}
@@ -183,61 +220,44 @@ int op_diag_f32(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
- if (!kparams->use_dma && (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst))) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- const size_t src_batch_size = src0->ne[0] * sizeof(float);
- const size_t dst_row_size = dst->ne[0] * sizeof(float);
-
struct htp_diag_vtcm_layout layout = { 0 };
- if (kparams->use_dma) {
- htp_diag_vtcm_layout_build(&layout, src_batch_size, dst_row_size, n_hvx);
-
- octx->src0_spad.size_per_hvx = layout.src0_bytes_per_hvx;
- octx->dst_spad.size_per_hvx = layout.dst_bytes_per_hvx;
- octx->src0_spad.size = n_hvx * layout.src0_bytes_per_hvx;
- octx->dst_spad.size = n_hvx * layout.dst_bytes_per_hvx;
- octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0);
- octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst);
- octx->src0_spad.src = NULL;
- octx->dst_spad.src = NULL;
- }
+ htp_diag_vtcm_layout_build(&layout, (size_t) kparams->chunk_elems * elem_size, n_hvx);
struct htp_diag_context dctx = {
- .octx = octx,
- .kparams = kparams,
- .src_batch_size = src_batch_size,
- .dst_row_size = dst_row_size,
- .src_batch_size_aligned = layout.src_batch_size_aligned,
- .dst_row_size_aligned = layout.dst_row_size_aligned,
- .batches_per_hvx = fastdiv(nbatches + n_hvx - 1, &octx->n_hvx_div),
- .total_batches = nbatches,
- .batch_start = batch_start,
+ .octx = octx,
+ .kparams = kparams,
+ .compute = compute,
+ .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0),
+ .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst),
+ .src0_bytes_per_hvx = layout.src0_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
+ .elem_size = elem_size,
+ .dst_chunk_bytes_aligned = layout.dst_chunk_bytes_aligned,
+ .chunk_elems = kparams->chunk_elems,
+ .batches_per_hvx = fastdiv(nbatches + n_hvx - 1, &octx->n_hvx_div),
+ .total_batches = nbatches,
+ .batch_start = batch_start,
};
- if (kparams->use_dma) {
- work_queue_run(octx->ctx->hvx_queue, diag_thread_f32_dma, &dctx, n_hvx);
- } else {
- work_queue_run(octx->ctx->hvx_queue, diag_thread_f32, &dctx, n_hvx);
- }
+ work_queue_run(octx->ctx->hvx_queue, diag_thread, &dctx, n_hvx);
return HTP_STATUS_OK;
}
int op_diag(struct htp_ops_context * octx) {
- const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
- int err = HTP_STATUS_OK;
+ if (src0->type != dst->type) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
switch (dst->type) {
case HTP_TYPE_F32:
- err = op_diag_f32(octx);
- break;
+ return op_diag_impl(octx, sizeof(float), diag_compute_f32);
+ case HTP_TYPE_F16:
+ return op_diag_impl(octx, sizeof(__fp16), diag_compute_f16);
default:
- err = HTP_STATUS_NO_SUPPORT;
- break;
+ return HTP_STATUS_NO_SUPPORT;
}
-
- return err;
}
diff --git a/ggml/src/ggml-hexagon/htp/diag-ops.h b/ggml/src/ggml-hexagon/htp/diag-ops.h
index 609a061c5..ac7cd7cb6 100644
--- a/ggml/src/ggml-hexagon/htp/diag-ops.h
+++ b/ggml/src/ggml-hexagon/htp/diag-ops.h
@@ -10,22 +10,19 @@ struct htp_diag_vtcm_layout {
size_t total_bytes;
size_t off_src0;
size_t off_dst;
- size_t src_batch_size_aligned;
- size_t dst_row_size_aligned;
+ size_t dst_chunk_bytes_aligned;
size_t src0_bytes_per_hvx;
size_t dst_bytes_per_hvx;
};
static inline void htp_diag_vtcm_layout_build(
struct htp_diag_vtcm_layout * L,
- size_t src_batch_size,
- size_t dst_row_size,
+ size_t dst_chunk_bytes,
uint32_t n_hvx
) {
- L->src_batch_size_aligned = hex_round_up(src_batch_size, 128);
- L->dst_row_size_aligned = hex_round_up(dst_row_size, 128);
- L->src0_bytes_per_hvx = L->src_batch_size_aligned;
- L->dst_bytes_per_hvx = L->dst_row_size_aligned;
+ L->dst_chunk_bytes_aligned = hex_round_up(dst_chunk_bytes, 128);
+ L->src0_bytes_per_hvx = 2 * 128;
+ L->dst_bytes_per_hvx = 2 * L->dst_chunk_bytes_aligned;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
@@ -37,9 +34,7 @@ static inline void htp_diag_vtcm_layout_build(
struct htp_diag_kernel_params {
uint32_t n_hvx;
uint32_t total_batches;
- uint32_t use_dma;
- uint32_t can_split;
- uint32_t batches_per_chunk;
+ uint32_t chunk_elems;
uint32_t vtcm_size;
struct fastdiv_values div_ne02;
diff --git a/ggml/src/ggml-hexagon/htp/dma-pipeline.h b/ggml/src/ggml-hexagon/htp/dma-pipeline.h
new file mode 100644
index 000000000..ea898148c
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/dma-pipeline.h
@@ -0,0 +1,200 @@
+#ifndef HTP_DMA_PIPELINE_H
+#define HTP_DMA_PIPELINE_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "dma-queue.h"
+#include "htp-trace.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct dma_pipe_task {
+ uint32_t row;
+ uint32_t off;
+ uint32_t len;
+ uint32_t aux;
+};
+
+typedef bool (*dma_pipe_next_task_fn)(void * ctx, struct dma_pipe_task * task);
+typedef void (*dma_pipe_push_in_fn)(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad);
+typedef void (*dma_pipe_push_in2_fn)(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad);
+typedef void (*dma_pipe_compute_io_fn)(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad);
+typedef void (*dma_pipe_compute_io2_fn)(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad);
+typedef void (*dma_pipe_compute_1_fn)(void * ctx, const struct dma_pipe_task * task, void * spad);
+typedef void (*dma_pipe_push_out_fn)(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad);
+
+// Double-buffered DDR -> VTCM -> HVX -> VTCM -> DDR pipeline.
+// Uses dummy output pushes in the prologue and dma_queue_pop().src/.dst to
+// recycle VTCM slot pointers directly through the DMA ring.
+// push_in/push_out must always push exactly one descriptor per task (use a
+// zero-nrows dummy push carrying the VTCM pointer when skipping a transfer).
+static inline void dma_pipe_io_run(
+ dma_queue * dma_q,
+ struct htp_thread_trace * tr,
+ void * ctx,
+ void * in_buf[2],
+ void * out_buf[2],
+ dma_pipe_next_task_fn next_task,
+ dma_pipe_push_in_fn push_in,
+ dma_pipe_compute_io_fn compute,
+ dma_pipe_push_out_fn push_out
+) {
+ struct dma_pipe_task t[2];
+ uint32_t head = 0, tail = 0;
+
+ for (uint32_t b = 0; b < 2; ++b) {
+ if (!next_task(ctx, &t[tail & 1])) {
+ break;
+ }
+ dma_queue_push(dma_q, dma_make_data(0, out_buf[b]), 0, 0, 0, 0);
+ push_in(dma_q, ctx, &t[tail & 1], in_buf[b]);
+ tail++;
+ }
+
+ while (head != tail) {
+ const struct dma_pipe_task cur = t[head & 1];
+ head++;
+
+ void * out_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
+ void * in_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+ compute(ctx, &cur, out_spad, in_spad);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+
+ push_out(dma_q, ctx, &cur, out_spad);
+
+ if (next_task(ctx, &t[tail & 1])) {
+ push_in(dma_q, ctx, &t[tail & 1], in_spad);
+ tail++;
+ }
+ }
+
+ dma_queue_flush(dma_q);
+}
+
+// Double-buffered 2-input DDR -> VTCM -> HVX -> VTCM -> DDR pipeline.
+static inline void dma_pipe_io2_run(
+ dma_queue * dma_q,
+ struct htp_thread_trace * tr,
+ void * ctx,
+ void * in0_buf[2],
+ void * in1_buf[2],
+ void * out_buf[2],
+ dma_pipe_next_task_fn next_task,
+ dma_pipe_push_in2_fn push_in,
+ dma_pipe_compute_io2_fn compute,
+ dma_pipe_push_out_fn push_out
+) {
+ struct dma_pipe_task t[2];
+ uint32_t head = 0, tail = 0;
+
+ for (uint32_t b = 0; b < 2; ++b) {
+ if (!next_task(ctx, &t[tail & 1])) {
+ break;
+ }
+ dma_queue_push(dma_q, dma_make_data(0, out_buf[b]), 0, 0, 0, 0);
+ push_in(dma_q, ctx, &t[tail & 1], in0_buf[b], in1_buf[b]);
+ tail++;
+ }
+
+ while (head != tail) {
+ const struct dma_pipe_task cur = t[head & 1];
+ head++;
+
+ void * out_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
+ void * in0_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+ void * in1_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+ compute(ctx, &cur, out_spad, in0_spad, in1_spad);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+
+ push_out(dma_q, ctx, &cur, out_spad);
+
+ if (next_task(ctx, &t[tail & 1])) {
+ push_in(dma_q, ctx, &t[tail & 1], in0_spad, in1_spad);
+ tail++;
+ }
+ }
+
+ dma_queue_flush(dma_q);
+}
+
+// Double-buffered DDR -> VTCM -> HVX pipeline for input-only reductions.
+static inline void dma_pipe_in_run(
+ dma_queue * dma_q,
+ struct htp_thread_trace * tr,
+ void * ctx,
+ void * in_buf[2],
+ dma_pipe_next_task_fn next_task,
+ dma_pipe_push_in_fn push_in,
+ dma_pipe_compute_1_fn compute
+) {
+ struct dma_pipe_task t[2];
+ uint32_t head = 0, tail = 0;
+
+ for (uint32_t b = 0; b < 2; ++b) {
+ if (!next_task(ctx, &t[tail & 1])) {
+ break;
+ }
+ push_in(dma_q, ctx, &t[tail & 1], in_buf[b]);
+ tail++;
+ }
+
+ while (head != tail) {
+ const struct dma_pipe_task cur = t[head & 1];
+ head++;
+
+ void * in_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+ compute(ctx, &cur, in_spad);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+
+ if (next_task(ctx, &t[tail & 1])) {
+ push_in(dma_q, ctx, &t[tail & 1], in_spad);
+ tail++;
+ }
+ }
+
+ dma_queue_flush(dma_q);
+}
+
+// Bounded in-flight HVX -> VTCM -> DDR pipeline for output-only generators.
+static inline void dma_pipe_out_run(
+ dma_queue * dma_q,
+ struct htp_thread_trace * tr,
+ void * ctx,
+ void * const * out_bufs,
+ uint32_t n_bufs,
+ dma_pipe_next_task_fn next_task,
+ dma_pipe_compute_1_fn compute,
+ dma_pipe_push_out_fn push_out
+) {
+ for (uint32_t b = 0; b < n_bufs; ++b) {
+ dma_queue_push(dma_q, dma_make_data(0, out_bufs[b]), 0, 0, 0, 0);
+ }
+
+ struct dma_pipe_task cur;
+ while (next_task(ctx, &cur)) {
+ void * out_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+ compute(ctx, &cur, out_spad);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row);
+
+ push_out(dma_q, ctx, &cur, out_spad);
+ }
+
+ dma_queue_flush(dma_q);
+}
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // HTP_DMA_PIPELINE_H
diff --git a/ggml/src/ggml-hexagon/htp/dma-proxy.c b/ggml/src/ggml-hexagon/htp/dma-proxy.c
new file mode 100644
index 000000000..b28bb100c
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/dma-proxy.c
@@ -0,0 +1,188 @@
+#include "dma-proxy.h"
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <qurt_thread.h>
+#include <qurt_futex.h>
+
+#define QURT_LOWEST_PRIO (254)
+
+static bool __attribute__((noinline)) dma_proxy_reap_completed(dma_proxy_t p, bool wait_one) {
+ dma_ring * r = p->th.dma_q->ring0;
+ uint32_t id = atomic_load_explicit(&p->idx_done, memory_order_relaxed);
+ if (id == p->idx_submit) {
+ return false;
+ }
+
+ bool reaped = false;
+ dmpoll();
+ #pragma clang loop vectorize(disable) interleave(disable)
+ while (id != p->idx_submit) {
+ volatile dma_descriptor_2d * hw_desc = &r->desc[r->pop_idx];
+ if (!hw_desc->done) {
+ if (!wait_one) {
+ break;
+ }
+ while (!hw_desc->done) {
+ dmpoll();
+ }
+ }
+ dma_ring_pop_nowait(r);
+ id++;
+ atomic_store_explicit(&p->idx_done, id, memory_order_release);
+ wait_one = false;
+ reaped = true;
+ }
+ return reaped;
+}
+
+static void dma_proxy_thread(void * arg) {
+ dma_proxy_t p = (dma_proxy_t) arg;
+
+ FARF(HIGH, "dma-proxy-thread (tid %u): started", p->th.tid);
+
+ const uint32_t max_inflight = dma_queue_capacity(p->th.dma_q) - 1;
+ unsigned int poll_cnt = DMA_PROXY_POLL_COUNT;
+ unsigned int prev_seqn = 0;
+
+ while (1) {
+ bool did_work = false;
+
+ uint32_t iw = atomic_load_explicit(&p->idx_write, memory_order_acquire);
+ #pragma clang loop vectorize(disable) interleave(disable)
+ while (p->idx_submit != iw) {
+ uint32_t id = atomic_load_explicit(&p->idx_done, memory_order_relaxed);
+ if ((p->idx_submit - id) >= max_inflight) {
+ dma_proxy_reap_completed(p, true);
+ }
+ const struct dma_proxy_desc * d = &p->desc[p->idx_submit & p->idx_mask];
+ const size_t nrows = (d->nrows != 0 && d->row_size != 0) ? d->nrows : 0;
+ dma_queue_push(p->th.dma_q, d->ddata, d->dst_stride, d->src_stride, d->row_size, nrows);
+ p->idx_submit++;
+ did_work = true;
+ }
+
+ if (atomic_load_explicit(&p->idx_done, memory_order_relaxed) != p->idx_submit) {
+ if (!dma_proxy_reap_completed(p, false) && !did_work) {
+ hex_pause();
+ }
+ poll_cnt = DMA_PROXY_POLL_COUNT;
+ continue;
+ }
+
+ if (did_work) {
+ poll_cnt = DMA_PROXY_POLL_COUNT;
+ continue;
+ }
+
+ if (atomic_load_explicit(&p->killed, memory_order_acquire)) {
+ break;
+ }
+
+ unsigned int seqn = atomic_load_explicit(&p->seqn, memory_order_acquire);
+ if (seqn != prev_seqn) {
+ prev_seqn = seqn;
+ poll_cnt = DMA_PROXY_POLL_COUNT;
+ continue;
+ }
+
+ if (--poll_cnt) {
+ hex_pause();
+ continue;
+ }
+
+ FARF(HIGH, "dma-proxy-thread: sleeping");
+ qurt_futex_wait(&p->seqn, prev_seqn);
+ poll_cnt = DMA_PROXY_POLL_COUNT;
+ }
+
+ FARF(HIGH, "dma-proxy-thread (tid %u): stopped", p->th.tid);
+}
+
+size_t dma_proxy_sizeof(size_t capacity, uint32_t stack_size) {
+ capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1);
+ size_t size_p = hex_align_up(sizeof(struct dma_proxy_s), HEX_L2_LINE_SIZE);
+ size_t size_desc = hex_align_up(capacity * sizeof(struct dma_proxy_desc), HEX_L2_LINE_SIZE);
+ size_t size_stack = stack_size;
+ return size_p + size_desc + size_stack;
+}
+
+size_t dma_proxy_alignof(void) {
+ return HEX_L2_LINE_SIZE;
+}
+
+dma_proxy_t dma_proxy_init(void * ptr, size_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace) {
+ capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1);
+ size_t size_p = hex_align_up(sizeof(struct dma_proxy_s), HEX_L2_LINE_SIZE);
+ size_t size_desc = hex_align_up(capacity * sizeof(struct dma_proxy_desc), HEX_L2_LINE_SIZE);
+
+ uint8_t * block = (uint8_t *) ptr;
+
+ dma_proxy_t p = (dma_proxy_t) block;
+ block += size_p;
+ memset(p, 0, sizeof(struct dma_proxy_s));
+
+ p->capacity = (uint32_t) capacity;
+ p->idx_mask = (uint32_t) (capacity - 1);
+ p->idx_pop = 0;
+ p->idx_submit = 0;
+ atomic_init(&p->idx_write, 0);
+ atomic_init(&p->idx_done, 0);
+ atomic_init(&p->seqn, 0);
+ atomic_init(&p->killed, false);
+
+ p->desc = (struct dma_proxy_desc *) block;
+ block += size_desc;
+ memset(p->desc, 0, capacity * sizeof(struct dma_proxy_desc));
+
+ p->stack = block;
+ memset(p->stack, 0, stack_size);
+
+ htp_thread_init(&p->th, dma, trace);
+
+ int prio = qurt_thread_get_priority(qurt_thread_get_id());
+ if (prio < 1) {
+ prio = 1;
+ }
+ if (prio > QURT_LOWEST_PRIO) {
+ prio = QURT_LOWEST_PRIO;
+ }
+
+ qurt_thread_attr_t attr;
+ qurt_thread_attr_init(&attr);
+ qurt_thread_attr_set_stack_addr(&attr, p->stack);
+ qurt_thread_attr_set_stack_size(&attr, stack_size);
+ qurt_thread_attr_set_priority(&attr, prio);
+ qurt_thread_attr_set_name(&attr, "dma-proxy");
+
+ int err = qurt_thread_create(&p->thread, &attr, dma_proxy_thread, p);
+ if (err) {
+ FARF(ERROR, "dma-proxy: thread create failed (%d)", err);
+ return NULL;
+ }
+
+ FARF(HIGH, "dma-proxy: capacity %u\n", (unsigned) capacity);
+
+ return p;
+}
+
+void dma_proxy_free(dma_proxy_t p) {
+ if (!p) {
+ return;
+ }
+
+ dma_proxy_flush(p);
+ atomic_store_explicit(&p->killed, true, memory_order_release);
+
+ unsigned int seqn = atomic_load_explicit(&p->seqn, memory_order_relaxed) + 1;
+ atomic_store_explicit(&p->seqn, seqn, memory_order_release);
+ qurt_futex_wake(&p->seqn, 1);
+
+ if (p->thread) {
+ int status = 0;
+ (void) qurt_thread_join(p->thread, &status);
+ p->thread = 0;
+ }
+}
diff --git a/ggml/src/ggml-hexagon/htp/dma-proxy.h b/ggml/src/ggml-hexagon/htp/dma-proxy.h
new file mode 100644
index 000000000..1e276cdcf
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/dma-proxy.h
@@ -0,0 +1,117 @@
+#ifndef HTP_DMA_PROXY_H
+#define HTP_DMA_PROXY_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdatomic.h>
+
+#include <qurt_thread.h>
+#include <qurt_futex.h>
+#include <HAP_farf.h>
+
+#include "dma-queue.h"
+#include "hex-utils.h"
+#include "htp-thread.h"
+#include "htp-trace.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if __HVX_ARCH__ > 79
+#define DMA_PROXY_POLL_COUNT 2000
+#else
+#define DMA_PROXY_POLL_COUNT 1
+#endif
+
+struct dma_proxy_desc {
+ dma_data ddata;
+ uint32_t dst_stride;
+ uint32_t src_stride;
+ uint32_t row_size;
+ uint32_t nrows;
+};
+
+struct dma_proxy_s {
+ struct dma_proxy_desc * desc;
+ atomic_uint idx_write; // monotonic, updated by producer (push)
+ uint32_t idx_pop; // monotonic, updated by producer (pop)
+ uint32_t idx_mask;
+ uint32_t capacity;
+ atomic_uint seqn; // incremented on push/kill, used with futex
+ atomic_bool killed;
+
+ atomic_uint idx_done __attribute__((aligned(HEX_L2_LINE_SIZE))); // monotonic, updated by consumer
+ uint32_t idx_submit; // monotonic, private to consumer
+
+ qurt_thread_t thread;
+ htp_thread_t th;
+ void * stack;
+};
+
+typedef struct dma_proxy_s * dma_proxy_t;
+
+size_t dma_proxy_sizeof(size_t capacity, uint32_t stack_size);
+size_t dma_proxy_alignof(void);
+dma_proxy_t dma_proxy_init(void * ptr, size_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace);
+void dma_proxy_free(dma_proxy_t p);
+
+static inline bool dma_proxy_empty(dma_proxy_t p) {
+ return p->idx_pop == atomic_load_explicit(&p->idx_write, memory_order_relaxed);
+}
+
+static inline bool dma_proxy_push(dma_proxy_t p, dma_data ddata, size_t dst_stride, size_t src_stride, size_t row_size, size_t nrows) {
+ uint32_t iw = atomic_load_explicit(&p->idx_write, memory_order_relaxed);
+ if ((iw - p->idx_pop) >= p->capacity) {
+ FARF(HIGH, "dma-proxy-push: queue is full\n");
+ return false;
+ }
+
+ struct dma_proxy_desc * d = &p->desc[iw & p->idx_mask];
+ d->ddata = ddata;
+ d->dst_stride = (uint32_t) dst_stride;
+ d->src_stride = (uint32_t) src_stride;
+ d->row_size = (uint32_t) row_size;
+ d->nrows = (uint32_t) nrows;
+
+ atomic_store_explicit(&p->idx_write, iw + 1, memory_order_release);
+
+ // wake up proxy thread
+ unsigned int seqn = atomic_load_explicit(&p->seqn, memory_order_relaxed) + 1;
+ atomic_store_explicit(&p->seqn, seqn, memory_order_release);
+ qurt_futex_wake(&p->seqn, 1);
+
+ return true;
+}
+
+static inline dma_data dma_proxy_pop(dma_proxy_t p) {
+ uint32_t ip = p->idx_pop;
+ uint32_t iw = atomic_load_explicit(&p->idx_write, memory_order_relaxed);
+
+ dma_data ddata = { 0 };
+ if (ip == iw) {
+ return ddata;
+ }
+
+ while ((int32_t) (atomic_load_explicit(&p->idx_done, memory_order_relaxed) - ip) <= 0) {
+ hex_pause();
+ }
+ atomic_thread_fence(memory_order_acquire);
+
+ ddata = p->desc[ip & p->idx_mask].ddata;
+ p->idx_pop = ip + 1;
+ return ddata;
+}
+
+static inline void dma_proxy_flush(dma_proxy_t p) {
+ while (!dma_proxy_empty(p)) {
+ dma_proxy_pop(p);
+ }
+}
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif /* HTP_DMA_PROXY_H */
diff --git a/ggml/src/ggml-hexagon/htp/dma-queue.c b/ggml/src/ggml-hexagon/htp/dma-queue.c
index 11d52a919..f8bd1ec22 100644
--- a/ggml/src/ggml-hexagon/htp/dma-queue.c
+++ b/ggml/src/ggml-hexagon/htp/dma-queue.c
@@ -4,8 +4,6 @@
#include <stdlib.h>
#include <string.h>
-#pragma clang diagnostic ignored "-Wunused-function"
-
static inline uint32_t pow2_ceil(uint32_t x) {
if (x <= 1) {
return 1;
diff --git a/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c b/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c
index b7123923c..247f8bbc1 100644
--- a/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c
+++ b/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c
@@ -1,6 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-
#include <HAP_farf.h>
#include <stdint.h>
@@ -51,6 +48,117 @@ static inline HVX_Vector dsv4_hc_sigmoid_f32(HVX_Vector v, HVX_Vector max_exp, H
return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v3, r));
}
+typedef void (*dsv4_hc_unpack_fn_t)(uint8_t * p);
+
+static void dsv4_hc_unpack_noop(uint8_t * p) {
+ (void) p;
+}
+
+static void dsv4_hc_unpack_f16_0(uint8_t * p) {
+ *(HVX_Vector *) p = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) p));
+}
+
+static void dsv4_hc_unpack_f16_128(uint8_t * p) {
+ *(HVX_Vector *) (p + 128) = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) (p + 128)));
+}
+
+static void dsv4_hc_unpack_f16_0_128(uint8_t * p) {
+ *(HVX_Vector *) p = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) p));
+ *(HVX_Vector *) (p + 128) = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) (p + 128)));
+}
+
+#define DSV4_HC_LOAD2_f32(lo, hi, ptr) \
+ do { \
+ lo = *(const HVX_Vector *) (ptr); \
+ hi = *(const HVX_Vector *) ((ptr) + VLEN); \
+ } while (0)
+
+#define DSV4_HC_LOAD2_f16(lo, hi, ptr) \
+ do { \
+ const HVX_VectorPair _p = hvx_vec_f16_to_f32(*(const HVX_Vector *) (ptr)); \
+ lo = Q6_V_lo_W(_p); \
+ hi = Q6_V_hi_W(_p); \
+ } while (0)
+
+#define DSV4_HC_LOAD2_f16s(lo, hi, ptr) \
+ do { \
+ const HVX_VectorPair _p = hvx_vec_f16_to_f32_shuff(*(const HVX_Vector *) (ptr)); \
+ lo = Q6_V_lo_W(_p); \
+ hi = Q6_V_hi_W(_p); \
+ } while (0)
+
+#define DSV4_HC_STORE2_f32(ptr, lo, hi) \
+ do { \
+ *(HVX_Vector *) (ptr) = (lo); \
+ *(HVX_Vector *) ((ptr) + VLEN) = (hi); \
+ } while (0)
+
+#define DSV4_HC_STORE2_f16(ptr, lo, hi) \
+ do { \
+ *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16((lo), (hi)); \
+ } while (0)
+
+#define DSV4_HC_STORE2_f16s(ptr, lo, hi) \
+ do { \
+ *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16_shuff((lo), (hi)); \
+ } while (0)
+
+#define DSV4_HC_STORE2_TAIL_f16s(ptr, lo, hi, has_hi) \
+ do { \
+ (void) (has_hi); \
+ *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16_shuff((lo), (hi)); \
+ } while (0)
+
+#define DSV4_HC_STORE2_TAIL_f32s(ptr, lo, hi, has_hi) \
+ do { \
+ const HVX_VectorPair _p = Q6_W_vshuff_VVR((hi), (lo), -4); \
+ *(HVX_Vector *) (ptr) = Q6_V_lo_W(_p); \
+ if (has_hi) { \
+ *(HVX_Vector *) ((ptr) + VLEN) = Q6_V_hi_W(_p); \
+ } \
+ } while (0)
+
+#define DSV4_HC_LOAD1_f32(v, ptr) \
+ do { \
+ v = *(const HVX_Vector *) (ptr); \
+ } while (0)
+
+#define DSV4_HC_LOAD1_f16(v, ptr) \
+ do { \
+ v = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) (ptr))); \
+ } while (0)
+
+#define DSV4_HC_LOAD1_f16s(v, ptr) DSV4_HC_LOAD1_f16(v, ptr)
+
+#define DSV4_HC_STORE1_f32(ptr, v) \
+ do { \
+ *(HVX_Vector *) (ptr) = (v); \
+ } while (0)
+
+#define DSV4_HC_STORE1_f16(ptr, v) \
+ do { \
+ *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16((v), (v)); \
+ } while (0)
+
+#define DSV4_HC_STORE1_f16s(ptr, v) DSV4_HC_STORE1_f16(ptr, v)
+
+struct dsv4_hc_pre_context;
+struct dsv4_hc_block;
+
+typedef void (*dsv4_hc_pre_plain_fn_t)(
+ const struct dsv4_hc_pre_context * dctx,
+ const struct dsv4_hc_block * block,
+ const uint8_t * x_spad,
+ uint8_t * d_spad,
+ const float * wb);
+
+typedef void (*dsv4_hc_pre_gated_fn_t)(
+ const struct dsv4_hc_pre_context * dctx,
+ const struct dsv4_hc_block * block,
+ const uint8_t * x_spad,
+ const uint8_t * g_spad,
+ uint8_t * d_spad);
+
struct dsv4_hc_pre_context {
struct htp_ops_context * octx;
const struct htp_dsv4_hc_pre_kernel_params * kparams;
@@ -63,6 +171,13 @@ struct dsv4_hc_pre_context {
uint32_t dma_block_chunks;
uint32_t dma_row_stride;
uint32_t dma_buffer_size;
+ uint32_t x_chunk_bytes;
+ uint32_t w_chunk_bytes;
+ uint32_t w_row_bytes;
+ uint32_t dst_chunk_bytes;
+ dsv4_hc_unpack_fn_t unpack_weights;
+ dsv4_hc_pre_plain_fn_t compute_plain;
+ dsv4_hc_pre_gated_fn_t compute_gated;
};
struct dsv4_hc_block {
@@ -93,10 +208,12 @@ static inline void dsv4_hc_pre_push_plain(
const struct htp_tensor * x = dctx->octx->src[0];
const struct htp_tensor * weights = dctx->octx->src[1];
const uint32_t row_stride = dctx->dma_row_stride;
- const uint32_t row_size = block->count * VLEN;
+ const uint32_t x_cb = dctx->x_chunk_bytes;
+ const uint32_t w_bytes = dctx->w_row_bytes;
+ const uint32_t x_size = block->count * x_cb;
- dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*VLEN)), row_stride, x->nb[1], row_size, 4);
- dma_queue_push(dma_q, dma_make_data(spad + 5*row_stride, weights->data + (block->it*weights->nb[1])), 16, 16, 16, 1);
+ dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*x_cb)), row_stride, x->nb[1], x_size, 4);
+ dma_queue_push(dma_q, dma_make_data(spad + 5*row_stride, weights->data + (block->it*weights->nb[1])), w_bytes, w_bytes, w_bytes, 1);
}
static inline void dsv4_hc_pre_push_gated(
@@ -107,78 +224,203 @@ static inline void dsv4_hc_pre_push_gated(
const struct htp_tensor * x = dctx->octx->src[0];
const struct htp_tensor * g = dctx->octx->src[1];
const uint32_t row_stride = dctx->dma_row_stride;
- const uint32_t row_size = block->count * VLEN;
+ const uint32_t x_cb = dctx->x_chunk_bytes;
+ const uint32_t g_cb = dctx->w_chunk_bytes;
+ const uint32_t x_size = block->count * x_cb;
+ const uint32_t g_size = block->count * g_cb;
- dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*VLEN)), row_stride, x->nb[1], row_size, 4);
- dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, g->data + (block->it*g->nb[2] + block->chunk*VLEN)), row_stride, g->nb[1], row_size, 4);
+ dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*x_cb)), row_stride, x->nb[1], x_size, 4);
+ dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, g->data + (block->it*g->nb[2] + block->chunk*g_cb)), row_stride, g->nb[1], g_size, 4);
}
-static __attribute__((noinline)) void dsv4_hc_pre_plain_block_f32(
- const struct dsv4_hc_pre_context * dctx,
- const struct dsv4_hc_block * block,
- const uint8_t * x_spad,
- uint8_t * d_spad,
- const float * wb) {
- const uint32_t row_stride = dctx->dma_row_stride;
- const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale);
- const HVX_Vector w0 = hvx_vec_splat_f32(wb[0]);
- const HVX_Vector w1 = hvx_vec_splat_f32(wb[1]);
- const HVX_Vector w2 = hvx_vec_splat_f32(wb[2]);
- const HVX_Vector w3 = hvx_vec_splat_f32(wb[3]);
-
- for (uint32_t c = 0; c < block->count; ++c) {
- const uint8_t * xb = x_spad + c*VLEN;
-
- HVX_Vector x0 = *(const HVX_Vector *) xb;
- HVX_Vector x1 = *(const HVX_Vector *) (xb + row_stride);
- HVX_Vector x2 = *(const HVX_Vector *) (xb + 2*row_stride);
- HVX_Vector x3 = *(const HVX_Vector *) (xb + 3*row_stride);
-
- HVX_Vector acc = hvx_vec_mul_f32_f32(x0, w0);
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(x1, w1));
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(x2, w2));
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(x3, w3));
-
- *(HVX_Vector *) (d_spad + c*VLEN) = hvx_vec_mul_f32_f32(acc, scale_v);
- }
+#define DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(SUFFIX, TX, TDST, X_CB, D_CB) \
+static __attribute__((noinline)) void dsv4_hc_pre_plain_block_##SUFFIX( \
+ const struct dsv4_hc_pre_context * dctx, \
+ const struct dsv4_hc_block * block, \
+ const uint8_t * x_spad, \
+ uint8_t * d_spad, \
+ const float * wb) { \
+ const uint32_t row_stride = dctx->dma_row_stride; \
+ const float scale = dctx->scale; \
+ const HVX_Vector w0 = hvx_vec_splat_f32(wb[0] * scale); \
+ const HVX_Vector w1 = hvx_vec_splat_f32(wb[1] * scale); \
+ const HVX_Vector w2 = hvx_vec_splat_f32(wb[2] * scale); \
+ const HVX_Vector w3 = hvx_vec_splat_f32(wb[3] * scale); \
+ const uint32_t count = block->count; \
+ uint32_t c = 0; \
+ for (; c + 2 <= count; c += 2) { \
+ const uint8_t * xb = x_spad + c * (X_CB); \
+ HVX_Vector x0, x1; \
+ DSV4_HC_LOAD2_##TX(x0, x1, xb); \
+ HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, w0); \
+ HVX_Vector acc1 = hvx_vec_mul_f32_f32(x1, w0); \
+ DSV4_HC_LOAD2_##TX(x0, x1, xb + row_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w1)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(x1, w1)); \
+ DSV4_HC_LOAD2_##TX(x0, x1, xb + 2 * row_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w2)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(x1, w2)); \
+ DSV4_HC_LOAD2_##TX(x0, x1, xb + 3 * row_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w3)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(x1, w3)); \
+ DSV4_HC_STORE2_##TDST(d_spad + c * (D_CB), acc0, acc1); \
+ } \
+ if (c < count) { \
+ const uint8_t * xb = x_spad + c * (X_CB); \
+ HVX_Vector x0; \
+ DSV4_HC_LOAD1_##TX(x0, xb); \
+ HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, w0); \
+ DSV4_HC_LOAD1_##TX(x0, xb + row_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w1)); \
+ DSV4_HC_LOAD1_##TX(x0, xb + 2 * row_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w2)); \
+ DSV4_HC_LOAD1_##TX(x0, xb + 3 * row_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w3)); \
+ DSV4_HC_STORE1_##TDST(d_spad + c * (D_CB), acc0); \
+ } \
}
-static __attribute__((noinline)) void dsv4_hc_pre_gated_block_f32(
- const struct dsv4_hc_pre_context * dctx,
- const struct dsv4_hc_block * block,
- const uint8_t * x_spad,
- const uint8_t * g_spad,
- uint8_t * d_spad) {
- const uint32_t row_stride = dctx->dma_row_stride;
- const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale);
- const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f);
- const HVX_Vector min_exp = hvx_vec_splat_f32(-87.0f);
-
- for (uint32_t c = 0; c < block->count; ++c) {
- const uint8_t * xb = x_spad + c*VLEN;
- const uint8_t * gb = g_spad + c*VLEN;
-
- HVX_Vector xv = *(const HVX_Vector *) xb;
- HVX_Vector gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) gb, max_exp, min_exp);
- HVX_Vector acc = hvx_vec_mul_f32_f32(xv, gv);
-
- xv = *(const HVX_Vector *) (xb + row_stride);
- gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (gb + row_stride), max_exp, min_exp);
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(xv, gv));
-
- xv = *(const HVX_Vector *) (xb + 2*row_stride);
- gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (gb + 2*row_stride), max_exp, min_exp);
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(xv, gv));
-
- xv = *(const HVX_Vector *) (xb + 3*row_stride);
- gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (gb + 3*row_stride), max_exp, min_exp);
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(xv, gv));
+DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f32_f32, f32, f32, 128, 128)
+DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f32_f16, f32, f16, 128, 64)
+DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f16_f32, f16, f32, 64, 128)
+DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f16_f16, f16s, f16s, 64, 64)
+
+#define DSV4_HC_SIGMOID2_f32(lo, hi, ptr, max_exp, min_exp) \
+ do { \
+ lo = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (ptr), max_exp, min_exp); \
+ hi = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) ((ptr) + VLEN), max_exp, min_exp); \
+ } while (0)
+
+#define DSV4_HC_SIGMOID2_f16(lo, hi, ptr, max_exp, min_exp) \
+ do { \
+ (void) (max_exp); \
+ (void) (min_exp); \
+ const HVX_VectorPair _p = hvx_vec_f16_to_f32(hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (ptr))); \
+ lo = Q6_V_lo_W(_p); \
+ hi = Q6_V_hi_W(_p); \
+ } while (0)
+
+#define DSV4_HC_SIGMOID1_f32(v, ptr, max_exp, min_exp) \
+ do { \
+ v = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (ptr), max_exp, min_exp); \
+ } while (0)
+
+#define DSV4_HC_SIGMOID1_f16(v, ptr, max_exp, min_exp) \
+ do { \
+ (void) (max_exp); \
+ (void) (min_exp); \
+ v = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (ptr)))); \
+ } while (0)
+
+#define DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, off, acc0, acc1, max_exp, min_exp) \
+ do { \
+ const uint8_t * _xp = (xb) + (off); \
+ const uint8_t * _gp = (gb) + (off); \
+ asm volatile("" : "+v"(acc0), "+v"(acc1), "+r"(_xp), "+r"(_gp)); \
+ HVX_Vector _x0, _x1, _g0, _g1; \
+ DSV4_HC_LOAD2_##TX(_x0, _x1, _xp); \
+ DSV4_HC_SIGMOID2_##TG(_g0, _g1, _gp, max_exp, min_exp); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(_x0, _g0)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(_x1, _g1)); \
+ } while (0)
+
+#define DEFINE_DSV4_HC_PRE_GATED_BLOCK(SUFFIX, TX, TG, TDST, X_CB, G_CB, D_CB) \
+static __attribute__((noinline)) void dsv4_hc_pre_gated_block_##SUFFIX( \
+ const struct dsv4_hc_pre_context * dctx, \
+ const struct dsv4_hc_block * block, \
+ const uint8_t * x_spad, \
+ const uint8_t * g_spad, \
+ uint8_t * d_spad) { \
+ const uint32_t row_stride = dctx->dma_row_stride; \
+ const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale); \
+ const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f); \
+ const HVX_Vector min_exp = hvx_vec_splat_f32(-87.0f); \
+ const uint32_t count = block->count; \
+ uint32_t c = 0; \
+ for (; c + 2 <= count; c += 2) { \
+ const uint8_t * xb = x_spad + c * (X_CB); \
+ const uint8_t * gb = g_spad + c * (G_CB); \
+ HVX_Vector x0, x1, g0, g1; \
+ DSV4_HC_LOAD2_##TX(x0, x1, xb); \
+ DSV4_HC_SIGMOID2_##TG(g0, g1, gb, max_exp, min_exp); \
+ HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, g0); \
+ HVX_Vector acc1 = hvx_vec_mul_f32_f32(x1, g1); \
+ DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, row_stride, acc0, acc1, max_exp, \
+ min_exp); \
+ DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, 2 * row_stride, acc0, acc1, max_exp, \
+ min_exp); \
+ DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, 3 * row_stride, acc0, acc1, max_exp, \
+ min_exp); \
+ acc0 = hvx_vec_mul_f32_f32(acc0, scale_v); \
+ acc1 = hvx_vec_mul_f32_f32(acc1, scale_v); \
+ DSV4_HC_STORE2_##TDST(d_spad + c * (D_CB), acc0, acc1); \
+ } \
+ if (c < count) { \
+ const uint8_t * xb = x_spad + c * (X_CB); \
+ const uint8_t * gb = g_spad + c * (G_CB); \
+ HVX_Vector x0, g0; \
+ DSV4_HC_LOAD1_##TX(x0, xb); \
+ DSV4_HC_SIGMOID1_##TG(g0, gb, max_exp, min_exp); \
+ HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, g0); \
+ DSV4_HC_LOAD1_##TX(x0, xb + row_stride); \
+ DSV4_HC_SIGMOID1_##TG(g0, gb + row_stride, max_exp, min_exp); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, g0)); \
+ DSV4_HC_LOAD1_##TX(x0, xb + 2 * row_stride); \
+ DSV4_HC_SIGMOID1_##TG(g0, gb + 2 * row_stride, max_exp, min_exp); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, g0)); \
+ DSV4_HC_LOAD1_##TX(x0, xb + 3 * row_stride); \
+ DSV4_HC_SIGMOID1_##TG(g0, gb + 3 * row_stride, max_exp, min_exp); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, g0)); \
+ acc0 = hvx_vec_mul_f32_f32(acc0, scale_v); \
+ DSV4_HC_STORE1_##TDST(d_spad + c * (D_CB), acc0); \
+ } \
+}
- *(HVX_Vector *) (d_spad + c*VLEN) = hvx_vec_mul_f32_f32(acc, scale_v);
- }
+#define DSV4_HC_PRE_GATED_EVAL_F16(xb, gb, row_stride, scale_v, acc0, acc1) \
+ do { \
+ const uint8_t * _xb = (xb); \
+ const uint8_t * _gb = (gb); \
+ const HVX_Vector _s0 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) _gb); \
+ const HVX_Vector _s1 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (_gb + (row_stride))); \
+ const HVX_Vector _s2 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (_gb + 2 * (row_stride))); \
+ const HVX_Vector _s3 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (_gb + 3 * (row_stride))); \
+ asm volatile("" : "+r"(_xb) : "v"(_s0), "v"(_s1), "v"(_s2), "v"(_s3)); \
+ HVX_VectorPair _acc = hvx_vec_mpy_f32_f16(*(const HVX_Vector *) _xb, _s0); \
+ _acc = hvx_vec_mpyacc_f32_f16(_acc, *(const HVX_Vector *) (_xb + (row_stride)), _s1); \
+ _acc = hvx_vec_mpyacc_f32_f16(_acc, *(const HVX_Vector *) (_xb + 2 * (row_stride)), _s2); \
+ _acc = hvx_vec_mpyacc_f32_f16(_acc, *(const HVX_Vector *) (_xb + 3 * (row_stride)), _s3); \
+ acc0 = hvx_vec_mul_f32_f32(Q6_V_lo_W(_acc), scale_v); \
+ acc1 = hvx_vec_mul_f32_f32(Q6_V_hi_W(_acc), scale_v); \
+ } while (0)
+
+#define DEFINE_DSV4_HC_PRE_GATED_F16_BLOCK(SUFFIX, TDST, D_CB) \
+static __attribute__((noinline)) void dsv4_hc_pre_gated_block_##SUFFIX( \
+ const struct dsv4_hc_pre_context * dctx, \
+ const struct dsv4_hc_block * block, \
+ const uint8_t * x_spad, \
+ const uint8_t * g_spad, \
+ uint8_t * d_spad) { \
+ const uint32_t row_stride = dctx->dma_row_stride; \
+ const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale); \
+ const uint32_t count = block->count; \
+ for (uint32_t c = 0; c < count; c += 2) { \
+ HVX_Vector acc0, acc1; \
+ DSV4_HC_PRE_GATED_EVAL_F16(x_spad + c * 64, g_spad + c * 64, row_stride, \
+ scale_v, acc0, acc1); \
+ DSV4_HC_STORE2_TAIL_##TDST(d_spad + c * (D_CB), acc0, acc1, c + 1 < count); \
+ } \
}
-static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f32_f32, f32, f32, f32, 128, 128, 128)
+DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f32_f16, f32, f32, f16, 128, 128, 64)
+DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f16_f32, f32, f16, f32, 128, 64, 128)
+DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f16_f16, f32, f16, f16, 128, 64, 64)
+DEFINE_DSV4_HC_PRE_GATED_BLOCK(f16_f32_f32, f16, f32, f32, 64, 128, 128)
+DEFINE_DSV4_HC_PRE_GATED_BLOCK(f16_f32_f16, f16, f32, f16, 64, 128, 64)
+DEFINE_DSV4_HC_PRE_GATED_F16_BLOCK(f16_f16_f32, f32s, 128)
+DEFINE_DSV4_HC_PRE_GATED_F16_BLOCK(f16_f16_f16, f16s, 64)
+
+static void dsv4_hc_pre_thread_plain(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct dsv4_hc_pre_context * dctx = (struct dsv4_hc_pre_context *) data;
struct htp_ops_context * octx = dctx->octx;
@@ -187,6 +429,7 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n
const uint32_t row_stride = dctx->dma_row_stride;
const uint32_t buffer_size = dctx->dma_buffer_size;
+ const uint32_t dst_cb = dctx->dst_chunk_bytes;
const uint32_t start = dctx->jobs_per_hvx * ith;
const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs);
if (start >= end) {
@@ -202,13 +445,16 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n
uint32_t prefetch_job = start;
for (uint32_t i = 0; i < 2 && prefetch_job < end; ++i) {
const struct dsv4_hc_block block = dsv4_hc_pre_block_make(dctx, prefetch_job, end);
+ const uint32_t d_bytes = block.count * dst_cb;
// empty dst writeback keeps pop order dst, x, weights in loop
- dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 4*row_stride), block.count*VLEN, block.count*VLEN, 0, 0);
+ dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 4*row_stride), d_bytes, d_bytes, 0, 0);
dsv4_hc_pre_push_plain(dma_q, dctx, &block, spad[i]);
prefetch_job += block.count;
}
struct htp_thread_trace * tr = th->trace;
+ const dsv4_hc_unpack_fn_t unpack = dctx->unpack_weights;
+ const dsv4_hc_pre_plain_fn_t compute = dctx->compute_plain;
uint32_t job = start;
uint32_t curr = 0;
@@ -219,15 +465,17 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n
dma_queue_pop(dma_q);
dma_queue_pop(dma_q);
- const float * wb = (const float *) (spad[curr] + 5*row_stride);
+ uint8_t * w_spad = spad[curr] + 5*row_stride;
uint8_t * d_spad = spad[curr] + 4*row_stride;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- dsv4_hc_pre_plain_block_f32(dctx, &block, spad[curr], d_spad, wb);
+ unpack(w_spad);
+ compute(dctx, &block, spad[curr], d_spad, (const float *) w_spad);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*VLEN);
- dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), block.count*VLEN, block.count*VLEN, block.count*VLEN, 1);
+ const uint32_t d_bytes = block.count * dst_cb;
+ const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*dst_cb);
+ dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), d_bytes, d_bytes, d_bytes, 1);
if (prefetch_job < end) {
const struct dsv4_hc_block next = dsv4_hc_pre_block_make(dctx, prefetch_job, end);
@@ -244,7 +492,7 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n
(void) nth;
}
-static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void dsv4_hc_pre_thread_gated(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct dsv4_hc_pre_context * dctx = (struct dsv4_hc_pre_context *) data;
struct htp_ops_context * octx = dctx->octx;
@@ -253,6 +501,7 @@ static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int n
const uint32_t row_stride = dctx->dma_row_stride;
const uint32_t buffer_size = dctx->dma_buffer_size;
+ const uint32_t dst_cb = dctx->dst_chunk_bytes;
const uint32_t start = dctx->jobs_per_hvx * ith;
const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs);
if (start >= end) {
@@ -268,13 +517,15 @@ static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int n
uint32_t prefetch_job = start;
for (uint32_t i = 0; i < 2 && prefetch_job < end; ++i) {
const struct dsv4_hc_block block = dsv4_hc_pre_block_make(dctx, prefetch_job, end);
+ const uint32_t d_bytes = block.count * dst_cb;
// empty dst writeback keeps pop order dst, x, g in loop
- dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 8*row_stride), block.count*VLEN, block.count*VLEN, 0, 0);
+ dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 8*row_stride), d_bytes, d_bytes, 0, 0);
dsv4_hc_pre_push_gated(dma_q, dctx, &block, spad[i]);
prefetch_job += block.count;
}
struct htp_thread_trace * tr = th->trace;
+ const dsv4_hc_pre_gated_fn_t compute = dctx->compute_gated;
uint32_t job = start;
uint32_t curr = 0;
@@ -288,11 +539,12 @@ static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int n
uint8_t * d_spad = spad[curr] + 8*row_stride;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- dsv4_hc_pre_gated_block_f32(dctx, &block, spad[curr], spad[curr] + 4*row_stride, d_spad);
+ compute(dctx, &block, spad[curr], spad[curr] + 4*row_stride, d_spad);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*VLEN);
- dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), block.count*VLEN, block.count*VLEN, block.count*VLEN, 1);
+ const uint32_t d_bytes = block.count * dst_cb;
+ const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*dst_cb);
+ dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), d_bytes, d_bytes, d_bytes, 1);
if (prefetch_job < end) {
const struct dsv4_hc_block next = dsv4_hc_pre_block_make(dctx, prefetch_job, end);
@@ -327,8 +579,7 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) {
uint32_t total_jobs = kparams->total_jobs;
uint32_t jobs_per_hvx = kparams->jobs_per_hvx;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_mdev_data_aligned(dst) && ((dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
token_start = range.start;
n_tokens = range.count;
total_jobs = n_tokens * kparams->n_chunks;
@@ -342,6 +593,28 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) {
float scale;
memcpy(&scale, octx->op_params, sizeof(scale));
+ const uint32_t x_f16 = (x->type == HTP_TYPE_F16) ? 1u : 0u;
+ const uint32_t w_f16 = (weights->type == HTP_TYPE_F16) ? 1u : 0u;
+ const uint32_t d_f16 = (dst->type == HTP_TYPE_F16) ? 1u : 0u;
+
+ static const dsv4_hc_pre_plain_fn_t plain_fns[4] = {
+ dsv4_hc_pre_plain_block_f32_f32,
+ dsv4_hc_pre_plain_block_f32_f16,
+ dsv4_hc_pre_plain_block_f16_f32,
+ dsv4_hc_pre_plain_block_f16_f16,
+ };
+
+ static const dsv4_hc_pre_gated_fn_t gated_fns[8] = {
+ dsv4_hc_pre_gated_block_f32_f32_f32,
+ dsv4_hc_pre_gated_block_f32_f32_f16,
+ dsv4_hc_pre_gated_block_f32_f16_f32,
+ dsv4_hc_pre_gated_block_f32_f16_f16,
+ dsv4_hc_pre_gated_block_f16_f32_f32,
+ dsv4_hc_pre_gated_block_f16_f32_f16,
+ dsv4_hc_pre_gated_block_f16_f16_f32,
+ dsv4_hc_pre_gated_block_f16_f16_f16,
+ };
+
struct dsv4_hc_pre_context dctx = {
.octx = octx,
.kparams = kparams,
@@ -354,12 +627,19 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) {
.dma_block_chunks = kparams->dma_block_chunks,
.dma_row_stride = kparams->dma_row_stride,
.dma_buffer_size = kparams->dma_buffer_size,
+ .x_chunk_bytes = x_f16 ? 64u : 128u,
+ .w_chunk_bytes = w_f16 ? 64u : 128u,
+ .w_row_bytes = w_f16 ? 8u : 16u,
+ .dst_chunk_bytes = d_f16 ? 64u : 128u,
+ .unpack_weights = w_f16 ? dsv4_hc_unpack_f16_0 : dsv4_hc_unpack_noop,
+ .compute_plain = plain_fns[(x_f16 << 1) | d_f16],
+ .compute_gated = gated_fns[(x_f16 << 2) | (w_f16 << 1) | d_f16],
};
work_queue_func_t worker = NULL;
switch (kparams->kernel_type) {
- case HTP_DSV4_HC_PRE_KERNEL_PLAIN: worker = dsv4_hc_pre_thread_plain_f32; break;
- case HTP_DSV4_HC_PRE_KERNEL_GATED: worker = dsv4_hc_pre_thread_gated_f32; break;
+ case HTP_DSV4_HC_PRE_KERNEL_PLAIN: worker = dsv4_hc_pre_thread_plain; break;
+ case HTP_DSV4_HC_PRE_KERNEL_GATED: worker = dsv4_hc_pre_thread_gated; break;
default: return HTP_STATUS_INVAL_PARAMS;
}
@@ -375,6 +655,16 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) {
// DSV4_HC_POST
// ---------------------------------------------------------------------------
+typedef void (*dsv4_hc_post_compute_fn_t)(
+ const uint8_t * xb,
+ const uint8_t * rb,
+ size_t r_stride,
+ uint8_t * db,
+ size_t d_stride,
+ uint32_t count,
+ const float * p,
+ const float * c);
+
struct dsv4_hc_post_context {
struct htp_ops_context * octx;
const struct htp_dsv4_hc_post_kernel_params * kparams;
@@ -382,6 +672,13 @@ struct dsv4_hc_post_context {
uint32_t total_jobs;
uint32_t jobs_per_hvx;
uint8_t * vtcm;
+ uint32_t x_chunk_bytes;
+ uint32_t r_chunk_bytes;
+ uint32_t dst_chunk_bytes;
+ uint32_t post_bytes;
+ uint32_t comb_row_bytes;
+ dsv4_hc_unpack_fn_t unpack_params;
+ dsv4_hc_post_compute_fn_t compute;
};
static inline struct dsv4_hc_block dsv4_hc_post_block_make(
@@ -399,56 +696,138 @@ static inline struct dsv4_hc_block dsv4_hc_post_block_make(
};
}
-static __attribute__((noinline)) void dsv4_hc_post_identity_block_f32(
- const uint8_t * xb,
- const uint8_t * rb,
- size_t r_stride,
- uint8_t * db,
- size_t d_stride,
- uint32_t count,
- const float * p) {
- for (uint32_t id = 0; id < 4; ++id) {
- const HVX_Vector pv = hvx_vec_splat_f32(p[id]);
- const uint8_t * rr = rb + id*r_stride;
- uint8_t * dd = db + id*d_stride;
-
- for (uint32_t i = 0; i < count; ++i) {
- const HVX_Vector xv = *(const HVX_Vector *) (xb + i*VLEN);
- const HVX_Vector rv = *(const HVX_Vector *) (rr + i*VLEN);
- *(HVX_Vector *) (dd + i*VLEN) = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(xv, pv), rv);
- }
- }
+#define DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(SUFFIX, TX, TR, TDST, X_CB, R_CB, D_CB) \
+static __attribute__((noinline)) void dsv4_hc_post_identity_block_##SUFFIX( \
+ const uint8_t * xb, \
+ const uint8_t * rb, \
+ size_t r_stride, \
+ uint8_t * db, \
+ size_t d_stride, \
+ uint32_t count, \
+ const float * p, \
+ const float * c_unused) { \
+ (void) c_unused; \
+ const HVX_Vector pv0 = hvx_vec_splat_f32(p[0]); \
+ const HVX_Vector pv1 = hvx_vec_splat_f32(p[1]); \
+ const HVX_Vector pv2 = hvx_vec_splat_f32(p[2]); \
+ const HVX_Vector pv3 = hvx_vec_splat_f32(p[3]); \
+ uint32_t i = 0; \
+ for (; i + 2 <= count; i += 2) { \
+ HVX_Vector x0, x1, r0, r1; \
+ DSV4_HC_LOAD2_##TX(x0, x1, xb + i * (X_CB)); \
+ const uint8_t * rr = rb + i * (R_CB); \
+ uint8_t * dd = db + i * (D_CB); \
+ DSV4_HC_LOAD2_##TR(r0, r1, rr); \
+ DSV4_HC_STORE2_##TDST(dd, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv0), r0), \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv0), r1)); \
+ DSV4_HC_LOAD2_##TR(r0, r1, rr + r_stride); \
+ DSV4_HC_STORE2_##TDST(dd + d_stride, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv1), r0), \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv1), r1)); \
+ DSV4_HC_LOAD2_##TR(r0, r1, rr + 2 * r_stride); \
+ DSV4_HC_STORE2_##TDST(dd + 2 * d_stride, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv2), r0), \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv2), r1)); \
+ DSV4_HC_LOAD2_##TR(r0, r1, rr + 3 * r_stride); \
+ DSV4_HC_STORE2_##TDST(dd + 3 * d_stride, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv3), r0), \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv3), r1)); \
+ } \
+ if (i < count) { \
+ HVX_Vector x0, r0; \
+ DSV4_HC_LOAD1_##TX(x0, xb + i * (X_CB)); \
+ const uint8_t * rr = rb + i * (R_CB); \
+ uint8_t * dd = db + i * (D_CB); \
+ DSV4_HC_LOAD1_##TR(r0, rr); \
+ DSV4_HC_STORE1_##TDST(dd, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv0), r0)); \
+ DSV4_HC_LOAD1_##TR(r0, rr + r_stride); \
+ DSV4_HC_STORE1_##TDST(dd + d_stride, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv1), r0)); \
+ DSV4_HC_LOAD1_##TR(r0, rr + 2 * r_stride); \
+ DSV4_HC_STORE1_##TDST(dd + 2 * d_stride, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv2), r0)); \
+ DSV4_HC_LOAD1_##TR(r0, rr + 3 * r_stride); \
+ DSV4_HC_STORE1_##TDST(dd + 3 * d_stride, \
+ hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv3), r0)); \
+ } \
}
-static __attribute__((noinline)) void dsv4_hc_post_comb_block_f32(
- const uint8_t * xb,
- const uint8_t * rb,
- size_t r_stride,
- uint8_t * db,
- size_t d_stride,
- uint32_t count,
- const float * p,
- const float * c) {
- for (uint32_t id = 0; id < 4; ++id) {
- const HVX_Vector pv = hvx_vec_splat_f32(p[id]);
- const HVX_Vector c0 = hvx_vec_splat_f32(c[id]);
- const HVX_Vector c1 = hvx_vec_splat_f32(c[4 + id]);
- const HVX_Vector c2 = hvx_vec_splat_f32(c[8 + id]);
- const HVX_Vector c3 = hvx_vec_splat_f32(c[12 + id]);
- uint8_t * dd = db + id*d_stride;
-
- for (uint32_t i = 0; i < count; ++i) {
- const uint8_t * r = rb + i*VLEN;
- HVX_Vector acc = hvx_vec_mul_f32_f32(*(const HVX_Vector *) (xb + i*VLEN), pv);
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) r, c0));
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) (r + r_stride), c1));
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) (r + 2*r_stride), c2));
- acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) (r + 3*r_stride), c3));
- *(HVX_Vector *) (dd + i*VLEN) = acc;
- }
- }
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f32_f32, f32, f32, f32, 128, 128, 128)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f32_f16, f32, f32, f16, 128, 128, 64)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f16_f32, f32, f16, f32, 128, 64, 128)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f16_f16, f32, f16, f16, 128, 64, 64)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f32_f32, f16, f32, f32, 64, 128, 128)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f32_f16, f16, f32, f16, 64, 128, 64)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f16_f32, f16, f16, f32, 64, 64, 128)
+DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f16_f16, f16s, f16s, f16s, 64, 64, 64)
+
+#define DEFINE_DSV4_HC_POST_COMB_BLOCK(SUFFIX, TX, TR, TDST, X_CB, R_CB, D_CB) \
+static __attribute__((noinline)) void dsv4_hc_post_comb_block_##SUFFIX( \
+ const uint8_t * xb, \
+ const uint8_t * rb, \
+ size_t r_stride, \
+ uint8_t * db, \
+ size_t d_stride, \
+ uint32_t count, \
+ const float * p, \
+ const float * c) { \
+ for (uint32_t id = 0; id < 4; ++id) { \
+ const HVX_Vector pv = hvx_vec_splat_f32(p[id]); \
+ const HVX_Vector c0 = hvx_vec_splat_f32(c[id]); \
+ const HVX_Vector c1 = hvx_vec_splat_f32(c[4 + id]); \
+ const HVX_Vector c2 = hvx_vec_splat_f32(c[8 + id]); \
+ const HVX_Vector c3 = hvx_vec_splat_f32(c[12 + id]); \
+ uint8_t * dd = db + id * d_stride; \
+ uint32_t i = 0; \
+ for (; i + 2 <= count; i += 2) { \
+ HVX_Vector v0, v1; \
+ DSV4_HC_LOAD2_##TX(v0, v1, xb + i * (X_CB)); \
+ HVX_Vector acc0 = hvx_vec_mul_f32_f32(v0, pv); \
+ HVX_Vector acc1 = hvx_vec_mul_f32_f32(v1, pv); \
+ const uint8_t * r = rb + i * (R_CB); \
+ DSV4_HC_LOAD2_##TR(v0, v1, r); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c0)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c0)); \
+ DSV4_HC_LOAD2_##TR(v0, v1, r + r_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c1)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c1)); \
+ DSV4_HC_LOAD2_##TR(v0, v1, r + 2 * r_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c2)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c2)); \
+ DSV4_HC_LOAD2_##TR(v0, v1, r + 3 * r_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c3)); \
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c3)); \
+ DSV4_HC_STORE2_##TDST(dd + i * (D_CB), acc0, acc1); \
+ } \
+ if (i < count) { \
+ HVX_Vector v0; \
+ DSV4_HC_LOAD1_##TX(v0, xb + i * (X_CB)); \
+ HVX_Vector acc0 = hvx_vec_mul_f32_f32(v0, pv); \
+ const uint8_t * r = rb + i * (R_CB); \
+ DSV4_HC_LOAD1_##TR(v0, r); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c0)); \
+ DSV4_HC_LOAD1_##TR(v0, r + r_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c1)); \
+ DSV4_HC_LOAD1_##TR(v0, r + 2 * r_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c2)); \
+ DSV4_HC_LOAD1_##TR(v0, r + 3 * r_stride); \
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c3)); \
+ DSV4_HC_STORE1_##TDST(dd + i * (D_CB), acc0); \
+ } \
+ } \
}
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f32_f32, f32, f32, f32, 128, 128, 128)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f32_f16, f32, f32, f16, 128, 128, 64)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f16_f32, f32, f16, f32, 128, 64, 128)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f16_f16, f32, f16, f16, 128, 64, 64)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f32_f32, f16, f32, f32, 64, 128, 128)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f32_f16, f16, f32, f16, 64, 128, 64)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f16_f32, f16, f16, f32, 64, 64, 128)
+DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f16_f16, f16s, f16s, f16s, 64, 64, 64)
+
static inline void dsv4_hc_post_push_identity(
dma_queue * dma_q,
const struct dsv4_hc_post_context * dctx,
@@ -458,14 +837,18 @@ static inline void dsv4_hc_post_push_identity(
const struct htp_tensor * residual = dctx->octx->src[1];
const struct htp_tensor * post = dctx->octx->src[2];
const uint32_t row_stride = dctx->kparams->dma_row_stride;
- const uint32_t row_size = block->count * VLEN;
-
- dma_queue_push(dma_q, dma_make_data(spad, residual->data + (block->it*residual->nb[2] + block->chunk*VLEN)),
- row_stride, residual->nb[1], row_size, 4);
- dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, x->data + (block->it*x->nb[1] + block->chunk*VLEN)),
- row_stride, row_size, row_size, 1);
+ const uint32_t x_cb = dctx->x_chunk_bytes;
+ const uint32_t r_cb = dctx->r_chunk_bytes;
+ const uint32_t p_bytes = dctx->post_bytes;
+ const uint32_t x_size = block->count * x_cb;
+ const uint32_t r_size = block->count * r_cb;
+
+ dma_queue_push(dma_q, dma_make_data(spad, residual->data + (block->it*residual->nb[2] + block->chunk*r_cb)),
+ row_stride, residual->nb[1], r_size, 4);
+ dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, x->data + (block->it*x->nb[1] + block->chunk*x_cb)),
+ row_stride, x_size, x_size, 1);
dma_queue_push(dma_q, dma_make_data(spad + 9*row_stride, post->data + (block->it*post->nb[1])),
- 16, 16, 16, 1);
+ p_bytes, p_bytes, p_bytes, 1);
}
static inline void dsv4_hc_post_push_comb(
@@ -475,13 +858,14 @@ static inline void dsv4_hc_post_push_comb(
uint8_t * spad) {
const struct htp_tensor * comb = dctx->octx->src[3];
const uint32_t row_stride = dctx->kparams->dma_row_stride;
+ const uint32_t c_bytes = dctx->comb_row_bytes;
dsv4_hc_post_push_identity(dma_q, dctx, block, spad);
- dma_queue_push(dma_q, dma_make_data(spad + 9*row_stride + 64, comb->data + (block->it*comb->nb[2])),
- 16, comb->nb[1], 16, 4);
+ dma_queue_push(dma_q, dma_make_data(spad + 9*row_stride + 128, comb->data + (block->it*comb->nb[2])),
+ c_bytes, comb->nb[1], c_bytes, 4);
}
-static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void dsv4_hc_post_thread_identity(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct dsv4_hc_post_context * dctx = (struct dsv4_hc_post_context *) data;
struct htp_ops_context * octx = dctx->octx;
@@ -491,6 +875,7 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i
const uint32_t block_chunks = dctx->kparams->dma_block_chunks;
const uint32_t row_stride = dctx->kparams->dma_row_stride;
const uint32_t buffer_size = dctx->kparams->dma_buffer_size;
+ const uint32_t dst_cb = dctx->dst_chunk_bytes;
const uint32_t start = dctx->jobs_per_hvx * ith;
const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs);
if (start >= end) {
@@ -512,7 +897,9 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i
prefetch_job += block.count;
}
- struct htp_thread_trace * tr = th->trace;
+ struct htp_thread_trace * tr = th->trace;
+ const dsv4_hc_unpack_fn_t unpack = dctx->unpack_params;
+ const dsv4_hc_post_compute_fn_t compute = dctx->compute;
uint32_t job = start;
uint32_t curr = 0;
@@ -524,15 +911,16 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i
dma_queue_pop(dma_q);
dma_queue_pop(dma_q);
- const float * p = (const float *) (spad[curr] + 9*row_stride);
- uint8_t * d_spad = spad[curr] + 5*row_stride;
+ uint8_t * row9 = spad[curr] + 9*row_stride;
+ uint8_t * d_spad = spad[curr] + 5*row_stride;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- dsv4_hc_post_identity_block_f32(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, p);
+ unpack(row9);
+ compute(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, (const float *) row9, NULL);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*VLEN);
- dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*VLEN, 4);
+ const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*dst_cb);
+ dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*dst_cb, 4);
if (prefetch_job < end) {
const struct dsv4_hc_block next = dsv4_hc_post_block_make(dctx, prefetch_job, end, block_chunks);
@@ -549,7 +937,7 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i
(void) nth;
}
-static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void dsv4_hc_post_thread_comb(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct dsv4_hc_post_context * dctx = (struct dsv4_hc_post_context *) data;
struct htp_ops_context * octx = dctx->octx;
@@ -559,6 +947,7 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n
const uint32_t block_chunks = dctx->kparams->dma_block_chunks;
const uint32_t row_stride = dctx->kparams->dma_row_stride;
const uint32_t buffer_size = dctx->kparams->dma_buffer_size;
+ const uint32_t dst_cb = dctx->dst_chunk_bytes;
const uint32_t start = dctx->jobs_per_hvx * ith;
const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs);
if (start >= end) {
@@ -580,7 +969,9 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n
prefetch_job += block.count;
}
- struct htp_thread_trace * tr = th->trace;
+ struct htp_thread_trace * tr = th->trace;
+ const dsv4_hc_unpack_fn_t unpack = dctx->unpack_params;
+ const dsv4_hc_post_compute_fn_t compute = dctx->compute;
uint32_t job = start;
uint32_t curr = 0;
@@ -593,16 +984,17 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n
dma_queue_pop(dma_q);
dma_queue_pop(dma_q);
- const float * p = (const float *) (spad[curr] + 9*row_stride);
- const float * c = (const float *) (spad[curr] + 9*row_stride + 64);
- uint8_t * d_spad = spad[curr] + 5*row_stride;
+ uint8_t * row9 = spad[curr] + 9*row_stride;
+ uint8_t * d_spad = spad[curr] + 5*row_stride;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- dsv4_hc_post_comb_block_f32(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, p, c);
+ unpack(row9);
+ compute(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count,
+ (const float *) row9, (const float *) (row9 + 128));
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it);
- const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*VLEN);
- dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*VLEN, 4);
+ const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*dst_cb);
+ dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*dst_cb, 4);
if (prefetch_job < end) {
const struct dsv4_hc_block next = dsv4_hc_post_block_make(dctx, prefetch_job, end, block_chunks);
@@ -622,10 +1014,12 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n
int op_dsv4_hc_post(struct htp_ops_context * octx) {
const struct htp_tensor * x = octx->src[0];
const struct htp_tensor * residual = octx->src[1];
+ const struct htp_tensor * post = octx->src[2];
const struct htp_tensor * dst = octx->dst;
const struct htp_dsv4_hc_post_kernel_params * kparams =
(const struct htp_dsv4_hc_post_kernel_params *) octx->kernel_params;
+ const struct htp_tensor * comb = kparams->has_comb ? octx->src[3] : NULL;
const uint32_t n_hvx = kparams->n_hvx;
if (!htp_ops_context_set_n_hvx_div(octx, n_hvx, kparams->div_n_hvx)) {
@@ -637,8 +1031,7 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) {
uint32_t total_jobs = kparams->total_jobs;
uint32_t jobs_per_hvx = kparams->jobs_per_hvx;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_mdev_data_aligned(dst) && ((dst->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
token_start = range.start;
n_tokens = range.count;
total_jobs = n_tokens * kparams->n_chunks;
@@ -649,6 +1042,43 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
+ const uint32_t x_f16 = (x->type == HTP_TYPE_F16) ? 1u : 0u;
+ const uint32_t r_f16 = (residual->type == HTP_TYPE_F16) ? 1u : 0u;
+ const uint32_t d_f16 = (dst->type == HTP_TYPE_F16) ? 1u : 0u;
+ const uint32_t p_f16 = (post->type == HTP_TYPE_F16) ? 1u : 0u;
+ const uint32_t c_f16 = (comb && comb->type == HTP_TYPE_F16) ? 1u : 0u;
+
+ static const dsv4_hc_unpack_fn_t unpack_fns[4] = {
+ dsv4_hc_unpack_noop,
+ dsv4_hc_unpack_f16_0,
+ dsv4_hc_unpack_f16_128,
+ dsv4_hc_unpack_f16_0_128,
+ };
+
+ static const dsv4_hc_post_compute_fn_t identity_fns[8] = {
+ dsv4_hc_post_identity_block_f32_f32_f32,
+ dsv4_hc_post_identity_block_f32_f32_f16,
+ dsv4_hc_post_identity_block_f32_f16_f32,
+ dsv4_hc_post_identity_block_f32_f16_f16,
+ dsv4_hc_post_identity_block_f16_f32_f32,
+ dsv4_hc_post_identity_block_f16_f32_f16,
+ dsv4_hc_post_identity_block_f16_f16_f32,
+ dsv4_hc_post_identity_block_f16_f16_f16,
+ };
+
+ static const dsv4_hc_post_compute_fn_t comb_fns[8] = {
+ dsv4_hc_post_comb_block_f32_f32_f32,
+ dsv4_hc_post_comb_block_f32_f32_f16,
+ dsv4_hc_post_comb_block_f32_f16_f32,
+ dsv4_hc_post_comb_block_f32_f16_f16,
+ dsv4_hc_post_comb_block_f16_f32_f32,
+ dsv4_hc_post_comb_block_f16_f32_f16,
+ dsv4_hc_post_comb_block_f16_f16_f32,
+ dsv4_hc_post_comb_block_f16_f16_f16,
+ };
+
+ const uint32_t fn_idx = (x_f16 << 2) | (r_f16 << 1) | d_f16;
+
struct dsv4_hc_post_context dctx = {
.octx = octx,
.kparams = kparams,
@@ -656,12 +1086,19 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) {
.total_jobs = total_jobs,
.jobs_per_hvx = jobs_per_hvx,
.vtcm = (uint8_t *) octx->ctx->vtcm_base,
+ .x_chunk_bytes = x_f16 ? 64u : 128u,
+ .r_chunk_bytes = r_f16 ? 64u : 128u,
+ .dst_chunk_bytes = d_f16 ? 64u : 128u,
+ .post_bytes = p_f16 ? 8u : 16u,
+ .comb_row_bytes = c_f16 ? 8u : 16u,
+ .unpack_params = unpack_fns[p_f16 | (c_f16 << 1)],
+ .compute = (kparams->kernel_type == HTP_DSV4_HC_POST_KERNEL_COMB) ? comb_fns[fn_idx] : identity_fns[fn_idx],
};
work_queue_func_t worker = NULL;
switch (kparams->kernel_type) {
- case HTP_DSV4_HC_POST_KERNEL_IDENTITY: worker = dsv4_hc_post_thread_identity_f32; break;
- case HTP_DSV4_HC_POST_KERNEL_COMB: worker = dsv4_hc_post_thread_comb_f32; break;
+ case HTP_DSV4_HC_POST_KERNEL_IDENTITY: worker = dsv4_hc_post_thread_identity; break;
+ case HTP_DSV4_HC_POST_KERNEL_COMB: worker = dsv4_hc_post_thread_comb; break;
default: return HTP_STATUS_INVAL_PARAMS;
}
diff --git a/ggml/src/ggml-hexagon/htp/fill-ops.c b/ggml/src/ggml-hexagon/htp/fill-ops.c
index 620263063..de024492b 100644
--- a/ggml/src/ggml-hexagon/htp/fill-ops.c
+++ b/ggml/src/ggml-hexagon/htp/fill-ops.c
@@ -1,10 +1,7 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <string.h>
+#include "dma-queue.h"
#include "hex-common.h"
#include "htp-trace.h"
@@ -16,39 +13,67 @@
#include "htp-ctx.h"
#include "htp-ops.h"
#include "htp-tensor.h"
+#include "htp-vtcm.h"
#include "fill-ops.h"
// ggml op_params layout for FILL:
// op_params[0] (as float) - the scalar fill value
-#define fill_preamble \
- const struct htp_tensor * dst = octx->dst; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
+#define fill_preamble \
+ const struct htp_tensor * dst = octx->dst; \
+ \
+ const uint32_t 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)) nb1 = dst->nb[1]; \
+ const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \
+ const uint32_t __attribute__((unused)) nb3 = dst->nb[3];
struct htp_fill_context {
- struct htp_ops_context * octx;
+ struct htp_ops_context * octx;
const struct htp_fill_kernel_params * kparams;
- uint32_t nrows_per_hvx;
- uint32_t total_rows; // ne1 * ne2 * ne3
- uint32_t row_start;
- HVX_Vector splat_vec;
- uint32_t elem_size;
+ dma_addr_t data_dst;
+ uint8_t * vtcm_tile;
+ size_t tile_bytes;
+ uint32_t nrows_per_hvx;
+ uint32_t total_rows;
+ uint32_t row_start;
+ uint32_t splat_bits;
+ uint32_t elem_size;
};
+static void __attribute__((noinline)) fill_splat_vtcm(
+ uint8_t * vtcm_tile,
+ uint32_t splat_bits,
+ uint32_t n_bytes,
+ uint32_t elem_size
+) {
+ const HVX_Vector sv = (elem_size == 2) ? Q6_Vh_vsplat_R((int32_t) splat_bits) : Q6_V_vsplat_R((int32_t) splat_bits);
+ hvx_splat_a(vtcm_tile, sv, n_bytes, 1);
+}
+
+static inline void fill_dma_write_capped(
+ dma_queue * dma_q,
+ uint32_t * in_flight,
+ uint32_t max_in_flight,
+ dma_addr_t dst_addr,
+ const uint8_t * src_vtcm,
+ size_t nbytes
+) {
+ if (*in_flight >= max_in_flight) {
+ dma_queue_pop(dma_q);
+ (*in_flight)--;
+ }
+ dma_queue_push(dma_q, dma_make_data(dst_addr, src_vtcm), nbytes, nbytes, nbytes, 1);
+ (*in_flight)++;
+}
+
static void fill_thread_contiguous(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
const struct htp_fill_context * fctx = (const struct htp_fill_context *) data;
- struct htp_ops_context * octx = fctx->octx;
+ struct htp_ops_context * octx = fctx->octx;
fill_preamble;
- // Parallelise over the flat row index spanning ne1*ne2*ne3
const uint32_t ir0 = fctx->row_start + fctx->nrows_per_hvx * ith;
const uint32_t ir1 = MIN(ir0 + fctx->nrows_per_hvx, fctx->row_start + fctx->total_rows);
@@ -56,25 +81,40 @@ static void fill_thread_contiguous(const htp_thread_t * th, unsigned int nth, un
return;
}
+ const size_t tile_bytes = fctx->tile_bytes;
+ const uint32_t elem_size = fctx->elem_size;
+ const size_t total_bytes = (size_t) (ir1 - ir0) * ne0 * elem_size;
+ const size_t splat_bytes = MIN(tile_bytes, hex_round_up(total_bytes, 128));
+ uint8_t * vtcm_tile = fctx->vtcm_tile + ith * tile_bytes;
+
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0);
+ fill_splat_vtcm(vtcm_tile, fctx->splat_bits, (uint32_t) splat_bytes, elem_size);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1);
- const uint32_t elem_start = ir0 * ne0;
- const uint32_t elem_end = ir1 * ne0;
- uint8_t * dst_ptr = (uint8_t *) dst->data + elem_start * fctx->elem_size;
- hvx_splat_u(dst_ptr, fctx->splat_vec, elem_end - elem_start, fctx->elem_size);
+ dma_queue * dma_q = th->dma_q;
+ const uint32_t max_in_flight = MIN(8u, dma_queue_capacity(dma_q) - 1);
+ uint32_t in_flight = 0;
+ const dma_addr_t dst_base = fctx->data_dst + (size_t) ir0 * ne0 * elem_size;
+
+ for (size_t off = 0; off < total_bytes; off += tile_bytes) {
+ const size_t chunk = MIN(tile_bytes, total_bytes - off);
+ fill_dma_write_capped(dma_q, &in_flight, max_in_flight, dst_base + off, vtcm_tile, chunk);
+ }
+
+ while (in_flight--) {
+ dma_queue_pop(dma_q);
+ }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1);
FARF(HIGH, "fill-contig %u/%u: rows %u:%u\n", ith, nth, ir0, ir1);
}
static void fill_thread_strided(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- const struct htp_fill_context * fctx = (const struct htp_fill_context *) data;
- struct htp_ops_context * octx = fctx->octx;
+ const struct htp_fill_context * fctx = (const struct htp_fill_context *) data;
+ struct htp_ops_context * octx = fctx->octx;
const struct htp_fill_kernel_params * kparams = fctx->kparams;
fill_preamble;
- // Parallelise over the flat row index spanning ne1*ne2*ne3
const uint32_t ir0 = fctx->row_start + fctx->nrows_per_hvx * ith;
const uint32_t ir1 = MIN(ir0 + fctx->nrows_per_hvx, fctx->row_start + fctx->total_rows);
@@ -82,19 +122,38 @@ static void fill_thread_strided(const htp_thread_t * th, unsigned int nth, unsig
return;
}
+ const size_t tile_bytes = fctx->tile_bytes;
+ const uint32_t elem_size = fctx->elem_size;
+ const size_t row_bytes = (size_t) ne0 * elem_size;
+ const size_t splat_bytes = MIN(tile_bytes, hex_round_up(row_bytes, 128));
+ uint8_t * vtcm_tile = fctx->vtcm_tile + ith * tile_bytes;
+
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0);
+ fill_splat_vtcm(vtcm_tile, fctx->splat_bits, (uint32_t) splat_bytes, elem_size);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1);
+
+ dma_queue * dma_q = th->dma_q;
+ const uint32_t max_in_flight = MIN(8u, dma_queue_capacity(dma_q) - 1);
+ uint32_t in_flight = 0;
for (uint32_t ir = ir0; ir < ir1; ++ir) {
- const uint32_t i3 = fastdiv(ir, &kparams->div_ne1_ne2);
- const uint32_t rem = ir - i3 * (ne1 * ne2);
- const uint32_t i2 = fastdiv(rem, &kparams->div_ne1);
- const uint32_t i1 = rem - i2 * ne1;
- uint8_t * dst_ptr = (uint8_t *) dst->data + i1*nb1 + i2*nb2 + i3*nb3;
- hvx_splat_u(dst_ptr, fctx->splat_vec, ne0, fctx->elem_size);
+ const uint32_t i3 = fastdiv(ir, &kparams->div_ne1_ne2);
+ const uint32_t rem = ir - i3 * (ne1 * ne2);
+ const uint32_t i2 = fastdiv(rem, &kparams->div_ne1);
+ const uint32_t i1 = rem - i2 * ne1;
+ const dma_addr_t dst_row = fctx->data_dst + (size_t) i1 * nb1 + (size_t) i2 * nb2 + (size_t) i3 * nb3;
+
+ for (size_t off = 0; off < row_bytes; off += tile_bytes) {
+ const size_t chunk = MIN(tile_bytes, row_bytes - off);
+ fill_dma_write_capped(dma_q, &in_flight, max_in_flight, dst_row + off, vtcm_tile, chunk);
+ }
+ }
+
+ while (in_flight--) {
+ dma_queue_pop(dma_q);
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1);
FARF(HIGH, "fill-strided %u/%u: rows %u:%u\n", ith, nth, ir0, ir1);
}
@@ -103,15 +162,13 @@ int op_fill(struct htp_ops_context * octx) {
const struct htp_fill_kernel_params * kparams =
(const struct htp_fill_kernel_params *) octx->kernel_params;
- if (htp_tensor_is_extended(dst)) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
uint32_t row_start = 0;
uint32_t nrows = kparams->total_rows;
if (octx->ctx->mdev.count > 1) {
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(kparams->total_rows, htp_tensor_mdev_data_aligned(dst) ? kparams->rows_per_chunk : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ kparams->total_rows, 1,
+ octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -126,6 +183,13 @@ int op_fill(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
+ struct htp_fill_vtcm_layout layout;
+ htp_fill_vtcm_layout_build(&layout, kparams->tile_bytes, n_hvx);
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "fill: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
FARF(HIGH, "fill: (%ux%ux%ux%u) type=%u ktype=%u\n",
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], dst->type, kparams->kernel_type);
@@ -133,21 +197,28 @@ int op_fill(struct htp_ops_context * octx) {
memcpy(&val_f32, &octx->op_params[0], sizeof(float));
struct htp_fill_context fctx = {
- .octx = octx,
- .kparams = kparams,
- .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
- .total_rows = nrows,
- .row_start = row_start,
- .elem_size = kparams->elem_size,
+ .octx = octx,
+ .kparams = kparams,
+ .data_dst = (dma_addr_t) dst->data,
+ .vtcm_tile = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_tile),
+ .tile_bytes = layout.tile_bytes,
+ .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
+ .total_rows = nrows,
+ .row_start = row_start,
+ .elem_size = kparams->elem_size,
};
switch (dst->type) {
case HTP_TYPE_F32:
- fctx.splat_vec = hvx_vec_splat_f32(val_f32);
+ memcpy(&fctx.splat_bits, &val_f32, sizeof(uint32_t));
break;
- case HTP_TYPE_F16:
- fctx.splat_vec = hvx_vec_splat_f16((_Float16) val_f32);
+ case HTP_TYPE_F16: {
+ const _Float16 val_f16 = (_Float16) val_f32;
+ uint16_t bits16 = 0;
+ memcpy(&bits16, &val_f16, sizeof(uint16_t));
+ fctx.splat_bits = bits16;
break;
+ }
default:
return HTP_STATUS_NO_SUPPORT;
}
diff --git a/ggml/src/ggml-hexagon/htp/fill-ops.h b/ggml/src/ggml-hexagon/htp/fill-ops.h
index 06fe08209..b19f23e1f 100644
--- a/ggml/src/ggml-hexagon/htp/fill-ops.h
+++ b/ggml/src/ggml-hexagon/htp/fill-ops.h
@@ -1,7 +1,10 @@
#ifndef HTP_FILL_OPS_H
#define HTP_FILL_OPS_H
+#include "hex-common.h"
#include "hex-fastdiv.h"
+#include "htp-vtcm.h"
+#include <stddef.h>
#include <stdint.h>
enum htp_fill_kernel_type {
@@ -9,12 +12,31 @@ enum htp_fill_kernel_type {
HTP_FILL_KERNEL_STRIDED = 1,
};
+struct htp_fill_vtcm_layout {
+ size_t tile_bytes;
+ size_t off_tile;
+ size_t total_bytes;
+};
+
+static inline void htp_fill_vtcm_layout_build(
+ struct htp_fill_vtcm_layout * L,
+ size_t tile_bytes,
+ uint32_t n_hvx
+) {
+ size_t off = 0;
+
+ L->tile_bytes = hex_round_up(tile_bytes, 128);
+ VTCM_LAYOUT_ALLOC(off, off_tile, (size_t) n_hvx * L->tile_bytes);
+ L->total_bytes = off;
+}
+
struct htp_fill_kernel_params {
uint8_t kernel_type;
uint32_t n_hvx;
uint32_t total_rows;
uint32_t elem_size;
- uint32_t rows_per_chunk;
+ uint32_t tile_bytes;
+ uint32_t vtcm_size;
struct fastdiv_values div_ne1;
struct fastdiv_values div_ne1_ne2;
diff --git a/ggml/src/ggml-hexagon/htp/flash-attn-ops.c b/ggml/src/ggml-hexagon/htp/flash-attn-ops.c
index 6506f28fc..bb0cd2c9e 100644
--- a/ggml/src/ggml-hexagon/htp/flash-attn-ops.c
+++ b/ggml/src/ggml-hexagon/htp/flash-attn-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <assert.h>
#include <HAP_compute_res.h>
#include <HAP_farf.h>
@@ -35,6 +31,7 @@
#include "flash-attn-ops.h"
#include "hvx-fa-kernels.h"
#include "hmx-fa-kernels.h"
+#include "hmx-fa-w8a8-kernels.h"
// Must be multiple of 32
#define FLASH_ATTN_BLOCK_SIZE (32 * 2)
@@ -45,6 +42,8 @@ struct hvx_fa_ddr_spad {
__fp16 slopes[512];
uint16_t active_blocks[FA_MAX_KV_BLOCKS];
uint16_t thread_active_blocks[HTP_MAX_NHVX][FA_MAX_KV_BLOCKS] __attribute__((aligned(128)));
+ float split_m[HTP_MAX_NHVX][FA_HVX_G_MAX] __attribute__((aligned(128)));
+ float split_s[HTP_MAX_NHVX][FA_HVX_G_MAX] __attribute__((aligned(128)));
};
struct hmx_fa_ddr_spad {
@@ -98,6 +97,11 @@ struct htp_fa_context {
uint32_t qrows_per_hvx;
uint32_t qrow_start;
+ uint32_t kv_head_start;
+ uint32_t n_kv_local;
+ uint32_t G;
+ uint32_t splits_per_kv;
+
bool is_q_fp32;
size_t size_q_block;
@@ -123,10 +127,12 @@ struct hmx_fa_context {
const struct htp_tensor * k;
const struct htp_tensor * v;
bool pipeline; // true when n_kv_blocks >= FA_MIN_KV_BLOCKS && n_hvx >= 2
+ bool is_w8a8;
uint32_t n_hvx;
// Op parameters
__fp16 scale;
+ float scale_f32;
float max_bias;
bool has_softcap;
__fp16 logit_softcap;
@@ -177,6 +183,18 @@ struct hmx_fa_context {
__fp16 * vtcm_mask_buf; // VTCM mask buffer [Br * m_line], DMA'd per KV block
__fp16 * vtcm_slopes; // ALiBi slopes [g_br]
float * vtcm_sinks; // Attention sinks
+ float * vtcm_q_scales; // W8A8 Q per-row scales [g_br]
+ float * vtcm_k_scales[2]; // W8A8 K per-col scales [Bc]
+ uint8_t * vtcm_k_bias[2]; // W8A8 K HMX bias banks [n_col_tiles * 2 * 256]
+ float * vtcm_o_f32; // W8A8 FP32 O accumulator [g_br, DV]
+ uint8_t * vtcm_do_tiles; // W8A8 PV output tiles [n_row_tiles_64, DV/32, 2]
+ float * vtcm_v_scales[2]; // W8A8 V per-col scales [DV]
+ uint8_t * vtcm_v_bias[2]; // W8A8 V HMX bias banks [DV/32 * 2 * 256]
+ float * vtcm_p_scales[2]; // W8A8 P per-row scales [g_br]
+ float * vtcm_exp_mdiff[2]; // W8A8 exp2(m_prev - m_curr) [g_br]
+ size_t k_raw_row_padded; // W8A8 raw Q8_0 K row stride in VTCM
+ size_t v_raw_row_padded; // W8A8 raw Q8_0 V row stride in VTCM
+ size_t o_f32_bytes;
__fp16 * ddr_slopes; // ALiBi slopes staging buffer in DDR [g_br]
size_t row_buf_stride; // HVX vectors per row buffer (Bc/64)
size_t mask_buf_row_stride; // elements (__fp16) per row in mask buffer
@@ -260,6 +278,332 @@ static uint32_t fa_scan_active_blocks(
return n_active;
}
+static __attribute__((noinline)) void fa_hvx_zero_acc(float * dst, uint32_t n) {
+ hvx_splat_f32_a((uint8_t *) dst, 0, n);
+}
+
+static __attribute__((noinline)) void fa_hvx_q_f32_to_f16(uint8_t * dst, uint32_t DK) {
+ hvx_copy_f16_f32_aa(dst, dst, DK);
+}
+
+static __attribute__((noinline)) float fa_hvx_exp_scalar(float x) {
+ return hvx_vec_get_f32(hvx_vec_exp_f32(hvx_vec_splat_f32(x)));
+}
+
+static __attribute__((noinline)) void fa_hvx_split_exp_weights(float * dst, const float * src) {
+ *(HVX_Vector *) dst = hvx_vec_exp_f32(*(const HVX_Vector *) src);
+}
+
+static __attribute__((noinline)) void fa_hvx_dequant_q8_0_block(
+ uint8_t * base,
+ size_t row_stride,
+ uint32_t n_rows,
+ uint32_t dim) {
+ for (uint32_t r = 0; r < n_rows; ++r) {
+ __fp16 * row = (__fp16 *) (base + r * row_stride);
+ hvx_dequantize_row_flat_q8_0_f16(row, row, dim);
+ }
+}
+
+// Accumulate PV in dealt HVX_VectorPair order.
+static __attribute__((always_inline)) inline void fa_hvx_pv_accum_fixed(
+ float * restrict vkq,
+ const uint8_t * restrict v_base,
+ size_t v_stride,
+ HVX_Vector P,
+ HVX_Vector ms_vec,
+ uint32_t block_size,
+ const uint32_t n_pairs) {
+ HVX_VectorPair * restrict vp = (HVX_VectorPair *) vkq;
+ HVX_VectorPair acc[4];
+
+ #pragma clang loop unroll(full)
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ acc[p] = Q6_W_vcombine_VV(
+ HVX_OP_MUL_F32(Q6_V_hi_W(vp[p]), ms_vec),
+ HVX_OP_MUL_F32(Q6_V_lo_W(vp[p]), ms_vec)
+ );
+ }
+
+ const uint8_t * v_ptr = v_base;
+ const size_t stride2 = v_stride * 2;
+ uint32_t j = 0;
+ for (; j + 1 < block_size; j += 2) {
+ const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
+ const HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2));
+ const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
+ const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + v_stride);
+
+ #pragma clang loop unroll(full)
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ acc[p] = hvx_vec_mpyacc_f32_f16(acc[p], vx0[p], S0);
+ acc[p] = hvx_vec_mpyacc_f32_f16(acc[p], vx1[p], S1);
+ }
+ v_ptr += stride2;
+ }
+ if (j < block_size) {
+ const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
+ const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
+ #pragma clang loop unroll(full)
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ acc[p] = hvx_vec_mpyacc_f32_f16(acc[p], vx0[p], S0);
+ }
+ }
+
+ #pragma clang loop unroll(full)
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ vp[p] = acc[p];
+ }
+}
+
+static __attribute__((noinline)) void fa_hvx_pv_accum_64(
+ float * restrict vkq, const uint8_t * restrict v_base, size_t v_stride,
+ HVX_Vector P, HVX_Vector ms_vec, uint32_t block_size) {
+ fa_hvx_pv_accum_fixed(vkq, v_base, v_stride, P, ms_vec, block_size, 1);
+}
+
+static __attribute__((noinline)) void fa_hvx_pv_accum_128(
+ float * restrict vkq, const uint8_t * restrict v_base, size_t v_stride,
+ HVX_Vector P, HVX_Vector ms_vec, uint32_t block_size) {
+ fa_hvx_pv_accum_fixed(vkq, v_base, v_stride, P, ms_vec, block_size, 2);
+}
+
+static __attribute__((noinline)) void fa_hvx_pv_accum_256(
+ float * restrict vkq, const uint8_t * restrict v_base, size_t v_stride,
+ HVX_Vector P, HVX_Vector ms_vec, uint32_t block_size) {
+ fa_hvx_pv_accum_fixed(vkq, v_base, v_stride, P, ms_vec, block_size, 4);
+}
+
+static __attribute__((noinline)) void fa_hvx_pv_accum_generic(
+ float * restrict vkq,
+ const uint8_t * restrict v_base,
+ size_t v_stride,
+ HVX_Vector P,
+ HVX_Vector ms_vec,
+ uint32_t block_size,
+ uint32_t DV) {
+ const uint32_t n_pairs = (DV + 63) / 64;
+ HVX_VectorPair * restrict vp = (HVX_VectorPair *) vkq;
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ HVX_VectorPair v = vp[p];
+ vp[p] = Q6_W_vcombine_VV(
+ HVX_OP_MUL_F32(Q6_V_hi_W(v), ms_vec),
+ HVX_OP_MUL_F32(Q6_V_lo_W(v), ms_vec)
+ );
+ }
+
+ const uint8_t * v_ptr = v_base;
+ const size_t stride2 = v_stride * 2;
+ uint32_t j = 0;
+ for (; j + 1 < block_size; j += 2) {
+ const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
+ const HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2));
+ const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
+ const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + v_stride);
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ HVX_VectorPair acc = vp[p];
+ acc = hvx_vec_mpyacc_f32_f16(acc, vx0[p], S0);
+ acc = hvx_vec_mpyacc_f32_f16(acc, vx1[p], S1);
+ vp[p] = acc;
+ }
+ v_ptr += stride2;
+ }
+ if (j < block_size) {
+ const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
+ const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ vp[p] = hvx_vec_mpyacc_f32_f16(vp[p], vx0[p], S0);
+ }
+ }
+}
+
+static inline void fa_hvx_pv_accum(
+ float * restrict vkq,
+ const uint8_t * restrict v_base,
+ size_t v_stride,
+ HVX_Vector P,
+ HVX_Vector ms_vec,
+ uint32_t block_size,
+ uint32_t DV) {
+ if (DV == 64) {
+ fa_hvx_pv_accum_64(vkq, v_base, v_stride, P, ms_vec, block_size);
+ } else if (DV == 128) {
+ fa_hvx_pv_accum_128(vkq, v_base, v_stride, P, ms_vec, block_size);
+ } else if (DV == 256) {
+ fa_hvx_pv_accum_256(vkq, v_base, v_stride, P, ms_vec, block_size);
+ } else {
+ fa_hvx_pv_accum_generic(vkq, v_base, v_stride, P, ms_vec, block_size, DV);
+ }
+}
+
+static __attribute__((noinline)) void fa_hvx_finalize_dealt_row_f32(
+ void * dst,
+ const float * src,
+ uint32_t DV,
+ float scale_out) {
+ const uint32_t n_pairs = (DV + 63) / 64;
+ const HVX_Vector v_scale = hvx_vec_splat_f32(scale_out);
+ const HVX_VectorPair * vp_src = (const HVX_VectorPair *) src;
+ HVX_VectorPair * vp_dst = (HVX_VectorPair *) dst;
+
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ const HVX_VectorPair vp = vp_src[p];
+ const HVX_Vector lo = HVX_OP_MUL_F32(Q6_V_lo_W(vp), v_scale);
+ const HVX_Vector hi = HVX_OP_MUL_F32(Q6_V_hi_W(vp), v_scale);
+ vp_dst[p] = Q6_W_vshuff_VVR(hi, lo, -4);
+ }
+}
+
+static __attribute__((noinline)) void fa_hvx_finalize_dealt_row_f16(
+ void * dst,
+ const float * src,
+ uint32_t DV,
+ float scale_out) {
+ const uint32_t n_pairs = (DV + 63) / 64;
+ const HVX_Vector v_scale = hvx_vec_splat_f32(scale_out);
+ const HVX_VectorPair * vp_src = (const HVX_VectorPair *) src;
+ HVX_Vector * v_dst = (HVX_Vector *) dst;
+
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ const HVX_VectorPair vp = vp_src[p];
+ const HVX_Vector lo = HVX_OP_MUL_F32(Q6_V_lo_W(vp), v_scale);
+ const HVX_Vector hi = HVX_OP_MUL_F32(Q6_V_hi_W(vp), v_scale);
+ v_dst[p] = hvx_vec_f32_to_f16_shuff(lo, hi);
+ }
+}
+
+static __attribute__((always_inline)) inline HVX_VectorPair fa_hvx_merge_dealt_pair(
+ const uint8_t * restrict src_ptr,
+ size_t worker_stride,
+ uint32_t n_splits,
+ const float * restrict scales) {
+ HVX_Vector v_lo = Q6_V_vzero();
+ HVX_Vector v_hi = Q6_V_vzero();
+ for (uint32_t s = 0; s < n_splits; ++s) {
+ const HVX_VectorPair vp = *(const HVX_VectorPair *) src_ptr;
+ const HVX_Vector vs = hvx_vec_splat_f32(scales[s]);
+ v_lo = HVX_OP_ADD_F32(v_lo, HVX_OP_MUL_F32(Q6_V_lo_W(vp), vs));
+ v_hi = HVX_OP_ADD_F32(v_hi, HVX_OP_MUL_F32(Q6_V_hi_W(vp), vs));
+ src_ptr += worker_stride;
+ }
+ return Q6_W_vcombine_VV(v_hi, v_lo);
+}
+
+static __attribute__((noinline)) void fa_hvx_merge_and_store_row_f32(
+ void * restrict dst,
+ const uint8_t * restrict spad_a_base,
+ size_t worker_stride,
+ uint32_t n_splits,
+ const float * restrict scales,
+ uint32_t DV) {
+ const uint32_t n_pairs = (DV + 63) / 64;
+ HVX_VectorPair * restrict vp_dst = (HVX_VectorPair *) dst;
+
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ const HVX_VectorPair sum = fa_hvx_merge_dealt_pair(spad_a_base + p * sizeof(HVX_VectorPair), worker_stride, n_splits, scales);
+ vp_dst[p] = Q6_W_vshuff_VVR(Q6_V_hi_W(sum), Q6_V_lo_W(sum), -4);
+ }
+}
+
+static __attribute__((noinline)) void fa_hvx_merge_and_store_row_f16(
+ void * restrict dst,
+ const uint8_t * restrict spad_a_base,
+ size_t worker_stride,
+ uint32_t n_splits,
+ const float * restrict scales,
+ uint32_t DV) {
+ const uint32_t n_pairs = (DV + 63) / 64;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ for (uint32_t p = 0; p < n_pairs; ++p) {
+ const HVX_VectorPair sum = fa_hvx_merge_dealt_pair(spad_a_base + p * sizeof(HVX_VectorPair), worker_stride, n_splits, scales);
+ v_dst[p] = hvx_vec_f32_to_f16_shuff(Q6_V_lo_W(sum), Q6_V_hi_W(sum));
+ }
+}
+
+static __attribute__((noinline)) void fa_hvx_qk_block(
+ const struct htp_fa_context * factx,
+ const uint8_t * restrict q_ptr,
+ const uint8_t * restrict k_base,
+ const __fp16 * restrict m_base,
+ uint32_t block_size,
+ uint16_t slope_bits,
+ void * restrict out_scores) {
+ const uint32_t DK = factx->k->ne[0];
+ const size_t k_stride = factx->size_k_row_padded;
+
+ HVX_Vector scores_f16 = Q6_V_vzero();
+ if (block_size > 0) {
+ HVX_Vector scores0 = hvx_dot_f16_f16_aa_rx32(q_ptr, k_base, k_stride, DK, factx->scale);
+ HVX_Vector scores1 = (block_size > 32)
+ ? hvx_dot_f16_f16_aa_rx32(q_ptr, k_base + 32 * k_stride, k_stride, DK, factx->scale)
+ : Q6_V_vzero();
+ scores_f16 = hvx_vec_f32_to_f16(scores0, scores1);
+ }
+
+ if (factx->has_softcap) {
+ scores_f16 = hvx_vec_tanh_f16(scores_f16);
+ scores_f16 = hvx_vec_mul_f16_f16(scores_f16, hvx_vec_splat_f16(factx->logit_softcap));
+ }
+
+ const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff);
+ const HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(block_size * sizeof(__fp16));
+
+ if (m_base) {
+ const HVX_Vector vinf = Q6_Vh_vsplat_R(0xFC00);
+ const HVX_Vector vmin = Q6_Vh_vsplat_R(0xFBFF);
+ HVX_Vector m_vals_f16 = *(const HVX_UVector *) m_base;
+ HVX_VectorPred is_inf = Q6_Q_vcmp_eq_VhVh(m_vals_f16, vinf);
+ m_vals_f16 = Q6_V_vmux_QVV(is_inf, vmin, m_vals_f16);
+
+ HVX_Vector m_scaled = hvx_vec_mul_f16_f16(m_vals_f16, Q6_Vh_vsplat_R(slope_bits));
+ scores_f16 = Q6_V_vmux_QVV(q_tail_keep, hvx_vec_add_f16_f16(scores_f16, m_scaled), v_neg_inf);
+ } else {
+ scores_f16 = Q6_V_vmux_QVV(q_tail_keep, scores_f16, v_neg_inf);
+ }
+
+ *(HVX_Vector *) out_scores = scores_f16;
+}
+
+static __attribute__((noinline)) void fa_hvx_sfm_pv_block(
+ const struct htp_fa_context * factx,
+ float * restrict vkq,
+ const uint8_t * restrict v_base,
+ const void * restrict in_scores,
+ uint32_t block_size,
+ float * restrict io_m,
+ float * restrict io_s) {
+ const HVX_Vector scores_f16 = *(const HVX_Vector *) in_scores;
+ const HVX_Vector v_log2e = hvx_vec_splat_f16(EXP_LOG2E_F);
+ const HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(block_size * sizeof(__fp16));
+
+ const HVX_Vector v_max_f16 = hvx_vec_reduce_max_f16(scores_f16);
+ const HVX_Vector v_max = Q6_V_lo_W(hvx_vec_f16_to_f32(v_max_f16));
+
+ const HVX_Vector m_prev = hvx_vec_splat_f32(*io_m);
+ const HVX_Vector s_prev = hvx_vec_splat_f32(*io_s);
+ const HVX_Vector m_new = Q6_Vsf_vmax_VsfVsf(v_max, m_prev);
+ const HVX_Vector diff_vec = HVX_OP_SUB_F32(m_prev, m_new);
+ const HVX_Vector diff_f16 = hvx_vec_f32_to_f16(diff_vec, diff_vec);
+ const HVX_Vector ms_f16 = hvx_vec_exp2_neg_f16(hvx_vec_mul_f16_f16(diff_f16, v_log2e));
+ const HVX_Vector ms_vec = Q6_V_lo_W(hvx_vec_f16_to_f32(ms_f16));
+
+ const HVX_Vector v_m_f16 = hvx_vec_f32_to_f16(m_new, m_new);
+ const HVX_Vector v_sm = Q6_Vqf16_vsub_VhfVhf(scores_f16, v_m_f16);
+ const HVX_Vector v_sm_b2 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vqf16(v_sm), v_log2e);
+ HVX_Vector P = hvx_vec_exp2_neg_f16(v_sm_b2);
+ P = Q6_V_vmux_QVV(q_tail_keep, P, Q6_V_vzero());
+
+ const HVX_VectorPair P_pair = hvx_vec_f16_to_f32(P);
+ const HVX_Vector p_sum_vec = hvx_vec_reduce_sum_f32(HVX_OP_ADD_F32(Q6_V_lo_W(P_pair), Q6_V_hi_W(P_pair)));
+ const HVX_Vector s_new = HVX_OP_ADD_F32(HVX_OP_MUL_F32(s_prev, ms_vec), p_sum_vec);
+
+ *io_m = hvx_vec_get_f32(m_new);
+ *io_s = hvx_vec_get_f32(s_new);
+
+ fa_hvx_pv_accum(vkq, v_base, factx->size_v_row_padded, P, ms_vec, block_size, factx->v->ne[0]);
+}
+
static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_fa_context * factx = (struct htp_fa_context *) data;
const struct htp_ops_context * octx = factx->octx;
@@ -270,20 +614,13 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
const struct htp_tensor * sinks = octx->src[4];
const struct htp_tensor * dst = octx->dst;
- const uint32_t neq0 = q->ne[0];
const uint32_t neq1 = q->ne[1];
const uint32_t neq2 = q->ne[2];
- const uint32_t neq3 = q->ne[3];
const uint32_t nek0 = k->ne[0];
const uint32_t nek1 = k->ne[1];
- const uint32_t nek2 = k->ne[2];
- const uint32_t nek3 = k->ne[3];
const uint32_t nev0 = v->ne[0];
- const uint32_t nev1 = v->ne[1];
- const uint32_t nev2 = v->ne[2];
- const uint32_t nev3 = v->ne[3];
const uint32_t nbq1 = q->nb[1];
const uint32_t nbq2 = q->nb[2];
@@ -297,14 +634,6 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
const uint32_t nbv2 = v->nb[2];
const uint32_t nbv3 = v->nb[3];
- const uint32_t ne1 = dst->ne[1];
- const uint32_t ne2 = dst->ne[2];
- const uint32_t ne3 = dst->ne[3];
-
- const uint32_t nb1 = dst->nb[1];
- const uint32_t nb2 = dst->nb[2];
- const uint32_t nb3 = dst->nb[3];
-
// total rows in q
const uint32_t dr = factx->qrows_per_hvx;
const uint32_t ir0 = factx->qrow_start + dr * ith;
@@ -319,7 +648,7 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
const uint32_t DK = nek0;
const uint32_t DV = nev0;
- const size_t size_q_row = DK * ((q->type == HTP_TYPE_F32) ? 4 : 2);
+ const size_t size_q_row = htp_tensor_get_row_size(q->type, DK);
const size_t size_k_row = htp_tensor_get_row_size(k->type, DK);
const size_t size_v_row = htp_tensor_get_row_size(v->type, DV);
@@ -345,7 +674,8 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
}
}
- const size_t size_vkq_acc_single = hex_round_up(DV * sizeof(float), 128);
+ const size_t size_vkq_acc_single = hex_round_up(DV * sizeof(float), 256);
+ const uint32_t dv_zero_elems = ((DV + 63) / 64) * 64;
uint32_t ir = ir0;
while (ir < ir1) {
@@ -393,12 +723,13 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
}
}
- uint32_t heads[FA_HVX_G_MAX];
- HVX_Vector slope_vecs[FA_HVX_G_MAX] __attribute__((aligned(128)));
- HVX_Vector S_vec[FA_HVX_G_MAX] __attribute__((aligned(128)));
- HVX_Vector M_vec[FA_HVX_G_MAX] __attribute__((aligned(128)));
+ uint8_t scores_buf[128] __attribute__((aligned(128)));
+ uint32_t heads[FA_HVX_G_MAX];
+ uint16_t slopes[FA_HVX_G_MAX];
+ float S_vals[FA_HVX_G_MAX];
+ float M_vals[FA_HVX_G_MAX];
uint8_t * q_ptrs[FA_HVX_G_MAX];
- float * vkq_ptrs[FA_HVX_G_MAX];
+ float * vkq_ptrs[FA_HVX_G_MAX];
for (uint32_t g = 0; g < G_local; ++g) {
const uint32_t r = ir + g;
@@ -406,19 +737,17 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
const uint32_t r_iq2 = fastdiv(r - r_iq3*neq2*neq1, &factx->src0_div1);
const uint32_t r_iq1 = (r - r_iq3*neq2*neq1 - r_iq2 * neq1);
- heads[g] = r_iq2;
- const __fp16 slope = factx->ddr->slopes[r_iq2];
- slope_vecs[g] = hvx_vec_splat_f16(slope);
-
- S_vec[g] = hvx_vec_splat_f32(0.0f);
- M_vec[g] = hvx_vec_splat_f32(HTP_FA_M_INITIAL_VAL);
+ heads[g] = r_iq2;
+ memcpy(&slopes[g], &factx->ddr->slopes[r_iq2], sizeof(uint16_t));
+ S_vals[g] = 0.0f;
+ M_vals[g] = HTP_FA_M_INITIAL_VAL;
uint8_t * q_dst = spad_q + g * factx->size_q_row_padded;
q_ptrs[g] = q_dst;
float * vkq_dst = (float *)(spad_a + g * size_vkq_acc_single);
vkq_ptrs[g] = vkq_dst;
- hvx_splat_f32_a((uint8_t *) vkq_dst, 0, DV);
+ fa_hvx_zero_acc(vkq_dst, dv_zero_elems);
// Fetch Q row g
const dma_addr_t q_row_ptr = q->data + r_iq1*nbq1 + r_iq2*nbq2 + r_iq3*nbq3;
@@ -452,18 +781,10 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
for (uint32_t g = 0; g < G_local; ++g) {
uint8_t * q_ptr_vtcm = (void *) dma_queue_pop(dma_q).dst;
if (factx->is_q_fp32) {
- hvx_copy_f16_f32_aa(q_ptr_vtcm, q_ptr_vtcm, DK);
+ fa_hvx_q_f32_to_f16(q_ptr_vtcm, DK);
}
}
- const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff);
- const bool has_softcap = factx->has_softcap;
- const HVX_Vector v_cap = has_softcap ? hvx_vec_splat_f16(factx->logit_softcap) : Q6_V_vzero();
- const HVX_Vector vinf = Q6_Vh_vsplat_R(0xFC00);
- const HVX_Vector vmin = Q6_Vh_vsplat_R(0xFBFF);
- const HVX_Vector v_log2e = hvx_vec_splat_f16(EXP_LOG2E_F);
- const uint32_t stride_v2 = factx->size_v_row_padded * 2;
-
for (uint32_t step = 0; step < n_active_blocks; ++step) {
const uint32_t ib = active_blocks[step];
const uint32_t ic_start = ib * FLASH_ATTN_BLOCK_SIZE;
@@ -476,56 +797,20 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
if (factx->k->type == HTP_TYPE_Q8_0) {
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, ir);
- for (uint32_t r = 0; r < current_block_size; ++r) {
- __fp16 * row_k = (__fp16 *)(k_base + r * factx->size_k_row_padded);
- hvx_dequantize_row_flat_q8_0_f16(row_k, row_k, DK);
- }
+ fa_hvx_dequant_q8_0_block(k_base, factx->size_k_row_padded, current_block_size, DK);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, ir);
}
if (factx->v->type == HTP_TYPE_Q8_0) {
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, ir);
- for (uint32_t r = 0; r < current_block_size; ++r) {
- __fp16 * row_v = (__fp16 *)(v_base + r * factx->size_v_row_padded);
- hvx_dequantize_row_flat_q8_0_f16(row_v, row_v, DV);
- }
+ fa_hvx_dequant_q8_0_block(v_base, factx->size_v_row_padded, current_block_size, DV);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, ir);
}
for (uint32_t g = 0; g < G_local; ++g) {
const uint32_t head_ir = ir + g;
- uint8_t * q_ptr_vtcm = q_ptrs[g];
- float * VKQ32 = vkq_ptrs[g];
- const HVX_Vector slope_vec = slope_vecs[g];
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir);
-
- HVX_Vector scores_f16 = Q6_V_vzero();
- if (current_block_size > 0) {
- HVX_Vector scores0 = hvx_dot_f16_f16_aa_rx32(q_ptr_vtcm, k_base, factx->size_k_row_padded, DK, factx->scale);
- HVX_Vector scores1 = (current_block_size > 32) ? hvx_dot_f16_f16_aa_rx32(q_ptr_vtcm, k_base + 32 * factx->size_k_row_padded, factx->size_k_row_padded, DK, factx->scale) : Q6_V_vzero();
- scores_f16 = hvx_vec_f32_to_f16(scores0, scores1);
- }
-
- if (has_softcap) {
- scores_f16 = hvx_vec_tanh_f16(scores_f16);
- scores_f16 = hvx_vec_mul_f16_f16(scores_f16, v_cap);
- }
-
- HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(current_block_size * sizeof(__fp16));
-
- if (mask) {
- HVX_Vector m_vals_f16 = *(const HVX_UVector *) m_base;
- HVX_VectorPred is_inf = Q6_Q_vcmp_eq_VhVh(m_vals_f16, vinf);
- m_vals_f16 = Q6_V_vmux_QVV(is_inf, vmin, m_vals_f16);
-
- HVX_Vector m_scaled = hvx_vec_mul_f16_f16(m_vals_f16, slope_vec);
- scores_f16 = Q6_V_vmux_QVV(q_tail_keep, hvx_vec_add_f16_f16(scores_f16, m_scaled), v_neg_inf);
- } else {
- scores_f16 = Q6_V_vmux_QVV(q_tail_keep, scores_f16, v_neg_inf);
- }
-
- HVX_Vector v_max_f16 = hvx_vec_reduce_max_f16(scores_f16);
- HVX_Vector v_max = Q6_V_lo_W(hvx_vec_f16_to_f32(v_max_f16));
+ fa_hvx_qk_block(factx, q_ptrs[g], k_base, m_base, current_block_size, slopes[g], scores_buf);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir);
// prefetch K for step + 2 after last head finished QK
@@ -539,156 +824,7 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir);
- {
- HVX_Vector M_new_vec = Q6_Vsf_vmax_VsfVsf(v_max, M_vec[g]);
- HVX_Vector diff_vec = HVX_OP_SUB_F32(M_vec[g], M_new_vec);
-
- HVX_Vector diff_f16 = hvx_vec_f32_to_f16(diff_vec, diff_vec);
- HVX_Vector diff_base2 = hvx_vec_mul_f16_f16(diff_f16, v_log2e);
- HVX_Vector ms_f16 = hvx_vec_exp2_f16(diff_base2);
- HVX_Vector ms_vec = Q6_V_lo_W(hvx_vec_f16_to_f32(ms_f16));
-
- M_vec[g] = M_new_vec;
-
- HVX_Vector v_m_vec_f16 = hvx_vec_f32_to_f16(M_vec[g], M_vec[g]);
- HVX_Vector v_s_minus_m = Q6_Vqf16_vsub_VhfVhf(scores_f16, v_m_vec_f16);
- HVX_Vector v_s_minus_m_base2 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m), v_log2e);
-
- HVX_Vector P = hvx_vec_exp2_f16(v_s_minus_m_base2);
- P = Q6_V_vmux_QVV(q_tail_keep, P, Q6_V_vzero());
-
- HVX_VectorPair P_pair = hvx_vec_f16_to_f32(P);
- HVX_Vector P0 = Q6_V_lo_W(P_pair);
- HVX_Vector P1 = Q6_V_hi_W(P_pair);
- HVX_Vector p_sum_vec = hvx_vec_reduce_sum_f32(HVX_OP_ADD_F32(P0, P1));
-
- S_vec[g] = HVX_OP_ADD_F32(HVX_OP_MUL_F32(S_vec[g], ms_vec), p_sum_vec);
-
- const uint8_t * v_ptr = v_base;
-
- if (DV == 64) {
- HVX_VectorPair vkq0 = *((const HVX_VectorPair *) VKQ32);
- vkq0 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq0), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq0), ms_vec)
- );
-
- for (uint32_t j = 0; j < current_block_size; j += 2) {
- HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
- const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
- if (j + 1 == current_block_size) {
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0);
- break;
- }
-
- HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2));
- const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + factx->size_v_row_padded);
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0);
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx1[0]), S1);
- v_ptr += stride_v2;
- }
-
- *((HVX_VectorPair *) VKQ32) = vkq0;
- } else if (DV == 128) {
- HVX_VectorPair vkq0 = ((const HVX_VectorPair *) VKQ32)[0];
- HVX_VectorPair vkq1 = ((const HVX_VectorPair *) VKQ32)[1];
- vkq0 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq0), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq0), ms_vec)
- );
- vkq1 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq1), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq1), ms_vec)
- );
-
- for (uint32_t j = 0; j < current_block_size; j += 2) {
- HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
- const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
- if (j + 1 == current_block_size) {
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0);
- vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0);
- break;
- }
-
- HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2));
- const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + factx->size_v_row_padded);
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0);
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx1[0]), S1);
- vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0);
- vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx1[1]), S1);
- v_ptr += stride_v2;
- }
-
- ((HVX_VectorPair *) VKQ32)[0] = vkq0;
- ((HVX_VectorPair *) VKQ32)[1] = vkq1;
- } else if (DV == 256) {
- HVX_VectorPair vkq0 = ((const HVX_VectorPair *) VKQ32)[0];
- HVX_VectorPair vkq1 = ((const HVX_VectorPair *) VKQ32)[1];
- HVX_VectorPair vkq2 = ((const HVX_VectorPair *) VKQ32)[2];
- HVX_VectorPair vkq3 = ((const HVX_VectorPair *) VKQ32)[3];
- vkq0 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq0), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq0), ms_vec)
- );
- vkq1 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq1), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq1), ms_vec)
- );
- vkq2 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq2), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq2), ms_vec)
- );
- vkq3 = Q6_W_vcombine_VV(
- HVX_OP_MUL_F32(Q6_V_hi_W(vkq3), ms_vec),
- HVX_OP_MUL_F32(Q6_V_lo_W(vkq3), ms_vec)
- );
-
- for (uint32_t j = 0; j < current_block_size; j += 2) {
- HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
- const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr;
- if (j + 1 == current_block_size) {
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0);
- vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0);
- vkq2 = hvx_vec_mpyacc_f32_f16(vkq2, Q6_Vh_vshuff_Vh(vx0[2]), S0);
- vkq3 = hvx_vec_mpyacc_f32_f16(vkq3, Q6_Vh_vshuff_Vh(vx0[3]), S0);
- break;
- }
-
- HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2));
- const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + factx->size_v_row_padded);
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0);
- vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx1[0]), S1);
- vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0);
- vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx1[1]), S1);
- vkq2 = hvx_vec_mpyacc_f32_f16(vkq2, Q6_Vh_vshuff_Vh(vx0[2]), S0);
- vkq2 = hvx_vec_mpyacc_f32_f16(vkq2, Q6_Vh_vshuff_Vh(vx1[2]), S1);
- vkq3 = hvx_vec_mpyacc_f32_f16(vkq3, Q6_Vh_vshuff_Vh(vx0[3]), S0);
- vkq3 = hvx_vec_mpyacc_f32_f16(vkq3, Q6_Vh_vshuff_Vh(vx1[3]), S1);
- v_ptr += stride_v2;
- }
-
- ((HVX_VectorPair *) VKQ32)[0] = vkq0;
- ((HVX_VectorPair *) VKQ32)[1] = vkq1;
- ((HVX_VectorPair *) VKQ32)[2] = vkq2;
- ((HVX_VectorPair *) VKQ32)[3] = vkq3;
- } else {
- hvx_scale_vec_f32_aa((uint8_t *) VKQ32, (const uint8_t *) VKQ32, DV, ms_vec);
-
- for (uint32_t j = 0; j < current_block_size; j += 2) {
- if (j + 1 == current_block_size) {
- HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
- hvx_mad_f32_f16_aa_vec(VKQ32, v_ptr, S0, DV);
- break;
- }
-
- HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2));
- HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2));
-
- hvx_mad_f32_f16_aa_rx2_vec(VKQ32, v_ptr, v_ptr + factx->size_v_row_padded, S0, S1, DV);
- v_ptr += stride_v2;
- }
- }
- }
+ fa_hvx_sfm_pv_block(factx, vkq_ptrs[g], v_base, scores_buf, current_block_size, &M_vals[g], &S_vals[g]);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir);
// prefetch V and mask for step + 2 after last head finished V accumulation
@@ -717,49 +853,334 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth,
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, head_ir);
- float M = hvx_vec_get_f32(M_vec[g]);
- float S = hvx_vec_get_f32(S_vec[g]);
+ float M = M_vals[g];
+ float S = S_vals[g];
+ float scale_out = 1.0f;
if (sinks) {
const float s = factx->spad_sinks[h];
- float vs = 1.0f;
-
if (s > M) {
- HVX_Vector diff_vec = hvx_vec_splat_f32(M - s);
- HVX_Vector ms_vec = hvx_vec_exp_f32(diff_vec);
- hvx_scale_vec_f32_aa((uint8_t *) VKQ32, (const uint8_t *) VKQ32, DV, ms_vec);
-
- float ms = hvx_vec_get_f32(ms_vec);
- S = S * ms + vs;
+ const float ms = fa_hvx_exp_scalar(M - s);
+ S = S * ms + 1.0f;
+ scale_out = ms;
} else {
- HVX_Vector diff_vec = hvx_vec_splat_f32(s - M);
- vs = hvx_vec_get_f32(hvx_vec_exp_f32(diff_vec));
+ const float vs = fa_hvx_exp_scalar(s - M);
S += vs;
}
}
- const float S_inv = S == 0.0f ? 0.0f : 1.0f/S;
- hvx_scale_f32_aa((uint8_t *) VKQ32, (const uint8_t *) VKQ32, DV, S_inv);
+ scale_out = (S == 0.0f) ? 0.0f : (scale_out / S);
const uint32_t r_iq3 = fastdiv(head_ir, &factx->src0_div21);
const uint32_t r_iq2 = fastdiv(head_ir - r_iq3*neq2*neq1, &factx->src0_div1);
const uint32_t r_iq1 = (head_ir - r_iq3*neq2*neq1 - r_iq2 * neq1);
- uint8_t * dst_ptr = (uint8_t *) dst->data + r_iq2 * dst->nb[1] + r_iq1 * dst->nb[2] + r_iq3 * dst->nb[3];
+ const dma_addr_t dst_addr = dst->data + r_iq2 * dst->nb[1] + r_iq1 * dst->nb[2] + r_iq3 * dst->nb[3];
if (dst->type == HTP_TYPE_F32) {
- hvx_copy_f32_ua(dst_ptr, (uint8_t *) VKQ32, DV);
+ fa_hvx_finalize_dealt_row_f32(VKQ32, VKQ32, DV, scale_out);
+ const size_t row_bytes = DV * sizeof(float);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, VKQ32), row_bytes, row_bytes, row_bytes, 1);
} else if (dst->type == HTP_TYPE_F16) {
- hvx_copy_f16_f32_ua(dst_ptr, (uint8_t *) VKQ32, DV);
+ fa_hvx_finalize_dealt_row_f16(VKQ32, VKQ32, DV, scale_out);
+ const size_t row_bytes = DV * sizeof(__fp16);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, VKQ32), row_bytes, row_bytes, row_bytes, 1);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, head_ir);
}
+ dma_queue_flush(dma_q);
+
ir += G_local;
}
}
+static void flash_attn_ext_f16_split_kv_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_fa_context * factx = (struct htp_fa_context *) data;
+ const struct htp_ops_context * octx = factx->octx;
+ const struct htp_tensor * q = octx->src[0];
+ const struct htp_tensor * k = octx->src[1];
+ const struct htp_tensor * v = octx->src[2];
+ const struct htp_tensor * mask = octx->src[3];
+
+ const uint32_t splits_per_kv = factx->splits_per_kv;
+ const uint32_t n_workers = factx->n_kv_local * splits_per_kv;
+ if (ith >= n_workers) {
+ return;
+ }
+
+ const uint32_t kv_local = ith / splits_per_kv;
+ const uint32_t split_idx = ith % splits_per_kv;
+ const uint32_t kv_head = factx->kv_head_start + kv_local;
+ const uint32_t G = factx->G;
+ const uint32_t q_base = kv_head * G;
+
+ const uint32_t base_blocks = factx->n_active_blocks / splits_per_kv;
+ const uint32_t rem_blocks = factx->n_active_blocks % splits_per_kv;
+ const uint32_t step_start = split_idx * base_blocks + MIN(split_idx, rem_blocks);
+ const uint32_t step_count = base_blocks + (split_idx < rem_blocks ? 1 : 0);
+ const uint32_t step_end = step_start + step_count;
+
+ const uint32_t DK = k->ne[0];
+ const uint32_t DV = v->ne[0];
+ const uint32_t nek1 = k->ne[1];
+
+ const uint32_t nbq1 = q->nb[1];
+ const uint32_t nbq2 = q->nb[2];
+ const uint32_t nbk1 = k->nb[1];
+ const uint32_t nbk2 = k->nb[2];
+ const uint32_t nbv1 = v->nb[1];
+ const uint32_t nbv2 = v->nb[2];
+
+ const size_t size_q_row = htp_tensor_get_row_size(q->type, DK);
+ const size_t size_k_row = htp_tensor_get_row_size(k->type, DK);
+ const size_t size_v_row = htp_tensor_get_row_size(v->type, DV);
+
+ struct htp_thread_trace * tr = th->trace;
+ dma_queue * dma_q = th->dma_q;
+
+ uint8_t * spad_q = factx->spad_q + factx->size_q_block * ith;
+ uint8_t * spad_k = factx->spad_k + factx->size_k_block * 2 * ith;
+ uint8_t * spad_v = factx->spad_v + factx->size_v_block * 2 * ith;
+ uint8_t * spad_m = factx->spad_m + (mask ? factx->size_m_block * HVX_FA_DMA_CACHE_SIZE : 0) * ith;
+ uint8_t * spad_a = factx->spad_a + factx->size_vkq_acc * ith;
+
+ dma_cache_dm * m_cache = &factx->m_cache[ith];
+ dma_cache_dm_init(m_cache, spad_m, factx->size_m_block, HVX_FA_DMA_CACHE_SIZE);
+
+ const uint16_t * active_blocks = factx->shared_active_blocks ? factx->ddr->active_blocks : NULL;
+ const dma_addr_t mp_base = mask ? mask->data : 0;
+
+ const size_t size_vkq_acc_single = hex_round_up(DV * sizeof(float), 256);
+ const uint32_t dv_zero_elems = ((DV + 63) / 64) * 64;
+
+ uint8_t scores_buf[128] __attribute__((aligned(128)));
+ uint16_t slopes[FA_HVX_G_MAX];
+ float S_vals[FA_HVX_G_MAX];
+ float M_vals[FA_HVX_G_MAX];
+ uint8_t * q_ptrs[FA_HVX_G_MAX];
+ float * vkq_ptrs[FA_HVX_G_MAX];
+
+ for (uint32_t g = 0; g < G; ++g) {
+ const uint32_t qh = q_base + g;
+ memcpy(&slopes[g], &factx->ddr->slopes[qh], sizeof(uint16_t));
+ S_vals[g] = 0.0f;
+ M_vals[g] = HTP_FA_M_INITIAL_VAL;
+
+ uint8_t * q_dst = spad_q + g * factx->size_q_row_padded;
+ q_ptrs[g] = q_dst;
+
+ float * vkq_dst = (float *) (spad_a + g * size_vkq_acc_single);
+ vkq_ptrs[g] = vkq_dst;
+ fa_hvx_zero_acc(vkq_dst, dv_zero_elems);
+
+ const dma_addr_t q_row_ptr = q->data + qh * nbq2;
+ dma_queue_push(dma_q, dma_make_data(q_dst, q_row_ptr), factx->size_q_row_padded, nbq1, size_q_row, 1);
+ }
+
+ const uint32_t n_prefetch = MIN(step_count, 2);
+ for (uint32_t p = 0; p < n_prefetch; ++p) {
+ const uint32_t step = step_start + p;
+ const uint32_t ib = active_blocks ? active_blocks[step] : step;
+ const uint32_t ic_start = ib * FLASH_ATTN_BLOCK_SIZE;
+ const uint32_t current_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - ic_start);
+
+ const dma_addr_t k_src = k->data + ic_start * nbk1 + kv_head * nbk2;
+ uint8_t * k_dst = spad_k + (p & 1) * factx->size_k_block;
+ dma_queue_push(dma_q, dma_make_data(k_dst, k_src), factx->size_k_row_padded, nbk1, size_k_row, current_block_size);
+
+ const dma_addr_t v_src = v->data + ic_start * nbv1 + kv_head * nbv2;
+ uint8_t * v_dst = spad_v + (p & 1) * factx->size_v_block;
+ dma_queue_push(dma_q, dma_make_data(v_dst, v_src), factx->size_v_row_padded, nbv1, size_v_row, current_block_size);
+
+ if (mask) {
+ const dma_addr_t m_src = mp_base + ic_start * sizeof(__fp16);
+ dma_cache_dm_push(dma_q, m_cache, ib, m_src, current_block_size * 2, current_block_size * 2, current_block_size * 2, 1);
+ }
+ }
+
+ for (uint32_t g = 0; g < G; ++g) {
+ uint8_t * q_ptr_vtcm = (void *) dma_queue_pop(dma_q).dst;
+ if (factx->is_q_fp32) {
+ fa_hvx_q_f32_to_f16(q_ptr_vtcm, DK);
+ }
+ }
+
+ for (uint32_t step = step_start; step < step_end; ++step) {
+ const uint32_t ib = active_blocks ? active_blocks[step] : step;
+ const uint32_t ic_start = ib * FLASH_ATTN_BLOCK_SIZE;
+ const uint32_t current_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - ic_start);
+
+ uint8_t * k_base = (void *) dma_queue_pop(dma_q).dst;
+ uint8_t * v_base = (void *) dma_queue_pop(dma_q).dst;
+ __fp16 * m_base = mask ? (__fp16 *) dma_queue_pop(dma_q).dst : NULL;
+
+ if (factx->k->type == HTP_TYPE_Q8_0) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, q_base);
+ fa_hvx_dequant_q8_0_block(k_base, factx->size_k_row_padded, current_block_size, DK);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, q_base);
+ }
+ if (factx->v->type == HTP_TYPE_Q8_0) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, q_base);
+ fa_hvx_dequant_q8_0_block(v_base, factx->size_v_row_padded, current_block_size, DV);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, q_base);
+ }
+
+ for (uint32_t g = 0; g < G; ++g) {
+ const uint32_t head_ir = q_base + g;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir);
+ fa_hvx_qk_block(factx, q_ptrs[g], k_base, m_base, current_block_size, slopes[g], scores_buf);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir);
+
+ if (g + 1 == G && step + 2 < step_end) {
+ const uint32_t next_ib = active_blocks ? active_blocks[step + 2] : (step + 2);
+ const uint32_t next_ic_start = next_ib * FLASH_ATTN_BLOCK_SIZE;
+ const uint32_t next_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - next_ic_start);
+
+ const dma_addr_t k_src = k->data + next_ic_start * nbk1 + kv_head * nbk2;
+ dma_queue_push(dma_q, dma_make_data(k_base, k_src), factx->size_k_row_padded, nbk1, size_k_row, next_block_size);
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir);
+ fa_hvx_sfm_pv_block(factx, vkq_ptrs[g], v_base, scores_buf, current_block_size, &M_vals[g], &S_vals[g]);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir);
+
+ if (g + 1 == G && step + 2 < step_end) {
+ const uint32_t next_ib = active_blocks ? active_blocks[step + 2] : (step + 2);
+ const uint32_t next_ic_start = next_ib * FLASH_ATTN_BLOCK_SIZE;
+ const uint32_t next_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - next_ic_start);
+
+ const dma_addr_t v_src = v->data + next_ic_start * nbv1 + kv_head * nbv2;
+ dma_queue_push(dma_q, dma_make_data(v_base, v_src), factx->size_v_row_padded, nbv1, size_v_row, next_block_size);
+
+ if (mask) {
+ const dma_addr_t m_src = mp_base + next_ic_start * sizeof(__fp16);
+ dma_cache_dm_push(dma_q, m_cache, next_ib, m_src, next_block_size * 2, next_block_size * 2, next_block_size * 2, 1);
+ }
+ }
+ }
+ }
+
+ for (uint32_t g = 0; g < G; ++g) {
+ factx->ddr->split_m[ith][g] = M_vals[g];
+ factx->ddr->split_s[ith][g] = S_vals[g];
+ }
+
+ (void) nth;
+}
+
+static void flash_attn_ext_f16_split_merge_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_fa_context * factx = (struct htp_fa_context *) data;
+ const struct htp_ops_context * octx = factx->octx;
+ const struct htp_tensor * v = octx->src[2];
+ const struct htp_tensor * sinks = octx->src[4];
+ const struct htp_tensor * dst = octx->dst;
+
+ const uint32_t G = factx->G;
+ const uint32_t splits_per_kv = factx->splits_per_kv;
+ const uint32_t n_q_local = factx->n_kv_local * G;
+ const uint32_t h_per_t = (n_q_local + nth - 1) / nth;
+ const uint32_t h_start = ith * h_per_t;
+ const uint32_t h_end = MIN(h_start + h_per_t, n_q_local);
+
+ if (h_start >= h_end) {
+ return;
+ }
+
+ const uint32_t DV = v->ne[0];
+ const size_t row_bytes = htp_tensor_get_row_size(dst->type, DV);
+ const size_t out_stride = hex_round_up(row_bytes, 256);
+ const size_t acc_stride = hex_round_up(DV * sizeof(float), 256);
+
+ // spad_v is unused during merge and has 128 * size_v_row_padded bytes per thread.
+ uint8_t * out_base = factx->spad_v + ith * factx->size_v_block * 2;
+
+ struct htp_thread_trace * tr = th->trace;
+ dma_queue * dma_q = th->dma_q;
+
+ float diffs[32] __attribute__((aligned(128)));
+ float weights[32] __attribute__((aligned(128)));
+ float scales[HTP_MAX_NHVX];
+
+ uint32_t kv_local = h_start / G;
+ uint32_t g = h_start % G;
+
+ for (uint32_t hl = h_start; hl < h_end; ++hl) {
+ const uint32_t q_head = (factx->kv_head_start + kv_local) * G + g;
+ const uint32_t w_base = kv_local * splits_per_kv;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, q_head);
+
+ bool has_valid = false;
+ float m_global = HTP_FA_M_INITIAL_VAL;
+ for (uint32_t s = 0; s < splits_per_kv; ++s) {
+ if (factx->ddr->split_s[w_base + s][g] > 0.0f) {
+ const float ms = factx->ddr->split_m[w_base + s][g];
+ if (!has_valid || ms > m_global) {
+ m_global = ms;
+ has_valid = true;
+ }
+ }
+ }
+
+ float sink_val = 0.0f;
+ if (sinks) {
+ sink_val = factx->spad_sinks[q_head];
+ if (!has_valid || sink_val > m_global) {
+ m_global = sink_val;
+ has_valid = true;
+ }
+ }
+
+ memset(diffs, 0, sizeof(diffs));
+ for (uint32_t s = 0; s < splits_per_kv; ++s) {
+ if (factx->ddr->split_s[w_base + s][g] > 0.0f) {
+ diffs[s] = factx->ddr->split_m[w_base + s][g] - m_global;
+ }
+ }
+ if (sinks) {
+ diffs[splits_per_kv] = sink_val - m_global;
+ }
+
+ fa_hvx_split_exp_weights(weights, diffs);
+
+ float l_global = sinks ? weights[splits_per_kv] : 0.0f;
+ for (uint32_t s = 0; s < splits_per_kv; ++s) {
+ const float ls = factx->ddr->split_s[w_base + s][g];
+ if (ls > 0.0f) {
+ l_global += ls * weights[s];
+ }
+ }
+
+ const float inv_l = (l_global == 0.0f) ? 0.0f : (1.0f / l_global);
+ for (uint32_t s = 0; s < splits_per_kv; ++s) {
+ scales[s] = (factx->ddr->split_s[w_base + s][g] > 0.0f) ? (weights[s] * inv_l) : 0.0f;
+ }
+
+ uint8_t * out_ptr = out_base + (hl - h_start) * out_stride;
+ const uint8_t * spad_a_base = factx->spad_a + w_base * factx->size_vkq_acc + g * acc_stride;
+ if (dst->type == HTP_TYPE_F32) {
+ fa_hvx_merge_and_store_row_f32(out_ptr, spad_a_base, factx->size_vkq_acc, splits_per_kv, scales, DV);
+ } else {
+ fa_hvx_merge_and_store_row_f16(out_ptr, spad_a_base, factx->size_vkq_acc, splits_per_kv, scales, DV);
+ }
+
+ const dma_addr_t dst_addr = dst->data + q_head * dst->nb[1];
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_ptr), row_bytes, row_bytes, row_bytes, 1);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, q_head);
+
+ if (++g == G) {
+ g = 0;
+ ++kv_local;
+ }
+ }
+
+ dma_queue_flush(dma_q);
+}
+
// ============================================================================
// HMX Phase args and thread logic
// ============================================================================
@@ -781,32 +1202,71 @@ static void fa_k_interleave_thread(const htp_thread_t * th, unsigned int n, unsi
const uint32_t total_rows = args->kv_rows;
const uint32_t rows_per_t = args->rows_per_t;
const uint32_t start = i * rows_per_t;
- const uint32_t end = (uint32_t) hex_smin(start + rows_per_t, total_rows);
if (start >= total_rows) {
return;
}
+ const uint32_t end_valid = (uint32_t) hex_smin(start + rows_per_t, total_rows);
+ const uint32_t end_tiled = (uint32_t) hex_smin(start + rows_per_t, hex_align_up(total_rows, HMX_FP16_TILE_N_ROWS));
+
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + start));
if (factx->k->type == HTP_TYPE_Q8_0) {
- for (uint32_t r = start; r < end; ++r) {
+ for (uint32_t r = start; r < end_valid; ++r) {
__fp16 * row_k = (__fp16 *)((char *)args->curr_k + r * args->src_stride * sizeof(__fp16));
hvx_dequantize_row_flat_q8_0_f16(row_k, row_k, factx->DK);
}
}
hmx_interleave_rows_to_tiles(factx->vtcm_k_tiles[args->buf_idx], (const __fp16 *) args->curr_k, total_rows, factx->DK_pad,
- args->src_stride, start, end);
+ args->src_stride, start, end_tiled);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + start));
}
+static void fa_w8a8_k_prep_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_k_int_args_t * args = (fa_k_int_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
+
+ const uint32_t total_rows = args->kv_rows;
+ const uint32_t n_col_tiles = hmx_ceil_div(total_rows, HMX_W8A8_TILE_N_COLS);
+ const uint32_t tiles_per_t = hmx_ceil_div(n_col_tiles, n);
+ const uint32_t ct_start = i * tiles_per_t;
+ const uint32_t ct_end = (uint32_t) hex_smin(ct_start + tiles_per_t, n_col_tiles);
+
+ if (ct_start >= n_col_tiles) {
+ return;
+ }
+
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + ct_start * HMX_W8A8_TILE_N_COLS));
+
+ const uint32_t n_dot = factx->DK / 32;
+ const size_t buf_idx = args->buf_idx;
+
+ for (uint32_t ct = ct_start; ct < ct_end; ++ct) {
+ const uint32_t valid_rows = (uint32_t) hex_smin(HMX_W8A8_TILE_N_COLS, total_rows - ct * HMX_W8A8_TILE_N_COLS);
+ const uint8_t * k_raw = (const uint8_t *) args->curr_k + (size_t) ct * HMX_W8A8_TILE_N_COLS * factx->k_raw_row_padded;
+ uint8_t * dst_wt = (uint8_t *) factx->vtcm_k_tiles[buf_idx] + (size_t) ct * n_dot * HMX_W8A8_WT_TILE_SIZE;
+ float * dst_sc = factx->vtcm_k_scales[buf_idx] + (size_t) ct * HMX_W8A8_TILE_N_COLS;
+ HVX_Vector * bias_out = (HVX_Vector *) (factx->vtcm_k_bias[buf_idx] + (size_t) ct * 2 * HMX_W8A8_BIAS_BANK_SIZE);
+ hmx_fa_w8a8_k_prep_tile(k_raw, dst_wt, dst_sc, bias_out, valid_rows, n_dot, factx->k_raw_row_padded);
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + ct_start * HMX_W8A8_TILE_N_COLS));
+}
+
static void fa_phase_k_interleave(struct hmx_fa_context * factx, uint32_t kv_rows, size_t src_stride, void * curr_k, uint32_t kv_start, size_t buf_idx) {
work_queue_t wp = factx->octx->ctx->hvx_queue;
- uint32_t n = 1;
- if (factx->n_hvx > 1 && kv_rows >= factx->n_hvx * 2) {
- n = factx->n_hvx;
+ if (factx->is_w8a8) {
+ const uint32_t n_col_tiles = hmx_ceil_div(kv_rows, HMX_W8A8_TILE_N_COLS);
+ const uint32_t n = (uint32_t) hex_smin(factx->n_hvx, n_col_tiles);
+ fa_k_int_args_t args = { factx, kv_rows, src_stride, curr_k, kv_start, 0, buf_idx };
+ work_queue_run(wp, fa_w8a8_k_prep_thread, &args, n);
+ return;
}
- uint32_t rows_per_t = hex_align_up(hmx_ceil_div(kv_rows, n), 2);
+ const uint32_t n_col_tiles = hmx_ceil_div(kv_rows, HMX_FP16_TILE_N_ROWS);
+ const uint32_t n = (uint32_t) hex_smin(factx->n_hvx, n_col_tiles);
+ const uint32_t rows_per_t = hmx_ceil_div(n_col_tiles, n) * HMX_FP16_TILE_N_ROWS;
fa_k_int_args_t args = { factx, kv_rows, src_stride, curr_k, kv_start, rows_per_t, buf_idx };
work_queue_run(wp, fa_k_interleave_thread, &args, n);
}
@@ -820,6 +1280,7 @@ typedef struct {
size_t n_col_tiles;
uint32_t kv_start;
uint32_t rows_per_t;
+ size_t buf_idx;
} fa_v_int_args_t;
static void fa_v_interleave_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
@@ -850,34 +1311,70 @@ static void fa_v_interleave_thread(const htp_thread_t * th, unsigned int n, unsi
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, (uint16_t) (args->kv_start + start));
}
+static void fa_w8a8_v_prep_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_v_int_args_t * args = (fa_v_int_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
+
+ const uint32_t n_v_tiles = factx->DV / HMX_W8A8_TILE_N_COLS;
+ const uint32_t tiles_per_t = hmx_ceil_div(n_v_tiles, n);
+ const uint32_t dv_start = i * tiles_per_t;
+ const uint32_t dv_end = (uint32_t) hex_smin(dv_start + tiles_per_t, n_v_tiles);
+
+ if (dv_start >= n_v_tiles) {
+ return;
+ }
+
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, (uint16_t) (args->kv_start + dv_start * HMX_W8A8_TILE_N_COLS));
+
+ const uint32_t kv_rows = args->kv_rows;
+ const uint32_t n_col_tiles = hmx_ceil_div(kv_rows, HMX_W8A8_TILE_N_COLS);
+ const size_t buf_idx = args->buf_idx;
+
+ for (uint32_t dv_tile = dv_start; dv_tile < dv_end; ++dv_tile) {
+ const uint8_t * v_base = (const uint8_t *) args->v_src + (size_t) dv_tile * 34;
+ uint8_t * dst_wt = (uint8_t *) args->v_tiles_dst + (size_t) dv_tile * n_col_tiles * HMX_W8A8_WT_TILE_SIZE;
+ float * dst_sc = factx->vtcm_v_scales[buf_idx] + (size_t) dv_tile * HMX_W8A8_TILE_N_COLS;
+ HVX_Vector * bias_out = (HVX_Vector *) (factx->vtcm_v_bias[buf_idx] + (size_t) dv_tile * 2 * HMX_W8A8_BIAS_BANK_SIZE);
+ hmx_fa_w8a8_v_prep_tile(v_base, dst_wt, dst_sc, bias_out, kv_rows, n_col_tiles, factx->v_raw_row_padded);
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, (uint16_t) (args->kv_start + dv_start * HMX_W8A8_TILE_N_COLS));
+}
+
static void fa_phase_v_interleave(struct hmx_fa_context * factx,
uint32_t kv_rows,
size_t src_stride,
void * v_src,
void * v_tiles_dst,
size_t n_col_tiles,
- uint32_t kv_start) {
+ uint32_t kv_start,
+ size_t buf_idx) {
work_queue_t wp = factx->octx->ctx->hvx_queue;
+ if (factx->is_w8a8) {
+ const uint32_t n_v_tiles = factx->DV / HMX_W8A8_TILE_N_COLS;
+ const uint32_t n = (uint32_t) hex_smin(factx->n_hvx, n_v_tiles);
+ fa_v_int_args_t args = { factx, kv_rows, src_stride, v_src, v_tiles_dst, n_col_tiles, kv_start, 0, buf_idx };
+ work_queue_run(wp, fa_w8a8_v_prep_thread, &args, n);
+ return;
+ }
uint32_t n = 1;
if (factx->n_hvx > 1 && kv_rows >= factx->n_hvx * 2) {
n = factx->n_hvx;
}
uint32_t rows_per_t = hex_align_up(hmx_ceil_div(kv_rows, n), 2);
- fa_v_int_args_t args = { factx, kv_rows, src_stride, v_src, v_tiles_dst, n_col_tiles, kv_start, rows_per_t };
+ fa_v_int_args_t args = { factx, kv_rows, src_stride, v_src, v_tiles_dst, n_col_tiles, kv_start, rows_per_t, buf_idx };
work_queue_run(wp, fa_v_interleave_thread, &args, n);
}
typedef struct {
- struct hmx_fa_context * factx;
- const struct htp_tensor * q;
- uint32_t q_start;
- uint32_t kv_head;
- uint32_t ib3;
- size_t n_rows_g;
- size_t rows_per_t;
- size_t n_rows_q;
- bool q_transposed;
- atomic_uint barrier;
+ struct hmx_fa_context * factx;
+ uint32_t q_start;
+ size_t n_rows_g;
+ size_t rows_per_t;
+ size_t n_rows_q;
+ bool q_transposed;
+ atomic_uint barrier;
} fa_q_load_args_t;
static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
@@ -899,9 +1396,6 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i
// Parallel initialization of per-block state
{
- const uint32_t g_br = factx->g_br;
- const uint32_t DV = factx->DV;
-
const size_t col_vec_bytes = factx->col_vec_bytes;
const size_t d_tile_bytes = factx->d_tile_bytes;
@@ -933,43 +1427,30 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i
}
if (start < factx->g_br) {
- const struct htp_tensor * q = args->q;
- const uint32_t q_start = args->q_start;
- const uint32_t kv_head = args->kv_head;
- const uint32_t ib3 = args->ib3;
-
- const bool use_q_dma = (factx->vtcm_q_dma != NULL);
-
- __fp16 * q_tiles = factx->vtcm_q_tiles;
- const size_t DK_pad = factx->DK_pad;
- if (use_q_dma) {
- const size_t g_rows_end = hex_smin(end, n_rows_g);
- const uint32_t d_limit = factx->is_q_fp32 ? DK / 32 : DK / 64;
-
- uint8_t * q_flat = (uint8_t *) factx->vtcm_q_dma;
- if (DK_pad != DK) {
- if (factx->is_q_fp32) {
- hmx_fa_q_prep_fp32_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed);
- } else {
- hmx_fa_q_prep_fp16_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed);
- }
- } else if (factx->is_q_fp32) {
- switch (d_limit) {
- case 2: hmx_fa_q_prep_fp32_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
- case 4: hmx_fa_q_prep_fp32_d4(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
- default: hmx_fa_q_prep_fp32( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break;
- }
+ __fp16 * q_tiles = factx->vtcm_q_tiles;
+ const size_t DK_pad = factx->DK_pad;
+ const size_t g_rows_end = hex_smin(end, n_rows_g);
+ const uint32_t d_limit = factx->is_q_fp32 ? DK / 32 : DK / 64;
+
+ uint8_t * q_flat = (uint8_t *) factx->vtcm_q_dma;
+ if (DK_pad != DK) {
+ if (factx->is_q_fp32) {
+ hmx_fa_q_prep_fp32_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed);
} else {
- switch (d_limit) {
- case 1: hmx_fa_q_prep_fp16_d1(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
- case 2: hmx_fa_q_prep_fp16_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
- default: hmx_fa_q_prep_fp16( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break;
- }
+ hmx_fa_q_prep_fp16_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed);
+ }
+ } else if (factx->is_q_fp32) {
+ switch (d_limit) {
+ case 2: hmx_fa_q_prep_fp32_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
+ case 4: hmx_fa_q_prep_fp32_d4(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
+ default: hmx_fa_q_prep_fp32( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break;
}
} else {
- // Fallback: direct-from-DDR/L2 path
- hmx_fa_q_prep_fallback(q_tiles, q->data, q->nb[1], q->nb[2], q->nb[3],
- q_start, kv_head, ib3, start, end, n_rows_g, G, DK, DK_pad, factx->is_q_fp32, &factx->div_G);
+ switch (d_limit) {
+ case 1: hmx_fa_q_prep_fp16_d1(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
+ case 2: hmx_fa_q_prep_fp16_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break;
+ default: hmx_fa_q_prep_fp16( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break;
+ }
}
}
@@ -983,8 +1464,6 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i
// Zero out vtcm_o_tiles[0] as it was used as temp_q_vtcm
{
- const uint32_t g_br = factx->g_br;
- const uint32_t DV = factx->DV;
const size_t o_tile_bytes = factx->o_tile_bytes;
const size_t o_bytes_per_t = hex_align_up(o_tile_bytes / n, 128);
const size_t o_start = i * o_bytes_per_t;
@@ -996,80 +1475,126 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_Q_PREP, (uint16_t) (args->q_start * G + start));
}
+static void fa_w8a8_q_prep_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_q_load_args_t * args = (fa_q_load_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
+
+ const size_t n_rows_g = args->n_rows_g;
+ const size_t G = factx->G;
+ const size_t DK = factx->DK;
+ const size_t rows_per_t = args->rows_per_t;
+ const size_t start = (size_t) i * rows_per_t;
+ const size_t end = hex_smin(start + rows_per_t, factx->g_br);
+
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_Q_PREP, (uint16_t) (args->q_start * G + start));
+
+ // Parallel initialization of per-block state
+ {
+ const size_t col_vec_bytes = factx->col_vec_bytes;
+ const size_t o_f32_bytes = factx->o_f32_bytes;
+
+ const size_t l_bytes_per_t = hex_align_up(col_vec_bytes / n, 128);
+ const size_t l_start = i * l_bytes_per_t;
+ const size_t l_end = hex_smin(l_start + l_bytes_per_t, col_vec_bytes);
+
+ const size_t m_bytes_per_t = hex_align_up(col_vec_bytes / n, 128);
+ const size_t m_start = i * m_bytes_per_t;
+ const size_t m_end = hex_smin(m_start + m_bytes_per_t, col_vec_bytes);
+
+ if (l_start < col_vec_bytes) {
+ hvx_splat_u8_a((char *) factx->vtcm_l_vec + l_start, 0, l_end - l_start);
+ }
+ if (m_start < col_vec_bytes) {
+ hvx_splat_f32_a((char *) factx->vtcm_m_vec + m_start, HTP_FA_M_INITIAL_VAL, (m_end - m_start) / sizeof(float));
+ }
+
+ const size_t o_bytes_per_t = hex_align_up(o_f32_bytes / n, 128);
+ const size_t o_start = i * o_bytes_per_t;
+ const size_t o_end = hex_smin(o_start + o_bytes_per_t, o_f32_bytes);
+ if (o_start < o_f32_bytes) {
+ hvx_splat_u8_a((char *) factx->vtcm_o_f32 + o_start, 0, o_end - o_start);
+ }
+ }
+
+ if (start < factx->g_br) {
+ const size_t g_rows_end = hex_smin(end, n_rows_g);
+ uint8_t * q_tiles = (uint8_t *) factx->vtcm_q_tiles;
+ const uint8_t * q_flat = (const uint8_t *) factx->vtcm_q_dma;
+ if (factx->is_q_fp32) {
+ hmx_fa_w8a8_q_prep_f32(q_tiles, factx->vtcm_q_scales, q_flat, start, end, g_rows_end,
+ DK, G, args->n_rows_q, &factx->div_G, args->q_transposed, factx->scale_f32);
+ } else {
+ hmx_fa_w8a8_q_prep_f16(q_tiles, factx->vtcm_q_scales, q_flat, start, end, g_rows_end,
+ DK, G, args->n_rows_q, &factx->div_G, args->q_transposed, factx->scale_f32);
+ }
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_Q_PREP, (uint16_t) (args->q_start * G + start));
+}
+
static void fa_phase_q_load(struct hmx_fa_context * factx,
const struct htp_tensor * q,
uint32_t q_start,
- uint32_t kv_head,
- uint32_t ib3,
size_t n_rows_g) {
work_queue_t wp = factx->octx->ctx->hvx_queue;
uint32_t n = 1;
- if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * 2)) {
+ const size_t row_align = factx->is_w8a8 ? 4 : 2;
+ if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * row_align)) {
n = factx->n_hvx;
}
- size_t rows_per_t = hex_align_up(hmx_ceil_div(factx->g_br, n), 2);
+ size_t rows_per_t = hex_align_up(hmx_ceil_div(factx->g_br, n), row_align);
const uint32_t n_rows_q = hex_smin(factx->Br, factx->neq1 - q_start);
fa_q_load_args_t args;
args.factx = factx;
- args.q = q;
args.q_start = q_start;
- args.kv_head = kv_head;
- args.ib3 = ib3;
args.n_rows_g = n_rows_g;
args.rows_per_t = rows_per_t;
args.n_rows_q = n_rows_q;
args.q_transposed = q->nb[1] < q->nb[2];
atomic_init(&args.barrier, n);
- work_queue_run(wp, fa_q_load_thread, &args, n);
+ work_queue_run(wp, factx->is_w8a8 ? fa_w8a8_q_prep_thread : fa_q_load_thread, &args, n);
}
typedef struct {
- struct hmx_fa_context * factx;
- const struct htp_tensor * dst;
- const __fp16 * o_tile_src;
- uint32_t q_start;
- uint32_t kv_head;
- uint32_t ib3;
- size_t n_rows_g;
- size_t rows_per_t;
+ struct hmx_fa_context * factx;
+ uint8_t * vtcm_dst;
+ const __fp16 * o_tile_src;
+ uint32_t q_start;
+ uint32_t kv_head;
+ size_t row_off;
+ size_t n_rows;
+ size_t rows_per_t;
} fa_o_store_args_t;
static void fa_o_store_thread_f32(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
fa_o_store_args_t * args = (fa_o_store_args_t *) data;
struct hmx_fa_context * factx = args->factx;
- const size_t n_rows_g = args->n_rows_g;
- const size_t G = factx->G;
- const size_t DV = factx->DV;
-
+ const size_t n_rows = args->n_rows;
+ const size_t G = factx->G;
+ const size_t DV = factx->DV;
const size_t rows_per_t = args->rows_per_t;
const size_t start = (size_t) i * rows_per_t;
- const size_t end = hex_smin(start + rows_per_t, n_rows_g);
+ const size_t end = hex_smin(start + rows_per_t, n_rows);
- if (start >= n_rows_g) {
+ if (start >= n_rows) {
return;
}
struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start));
-
- const struct htp_tensor * dst = args->dst;
- const __fp16 * o_tile_src = args->o_tile_src;
- const uint32_t q_start = args->q_start;
- const uint32_t kv_head = args->kv_head;
- const uint32_t ib3 = args->ib3;
-
- const size_t DV_pad = factx->DV_pad;
-
- size_t q_idx = fastdiv(start, &factx->div_G);
- size_t h_idx = fastmodulo(start, G, &factx->div_G);
-
- for (size_t r = start; r < end; ++r) {
- float * out = (float *) ((uint8_t *) dst->data + (kv_head * G + h_idx) * dst->nb[1] +
- (q_start + q_idx) * dst->nb[2] + ib3 * dst->nb[3]);
-
- size_t r0 = r / HMX_FP16_TILE_N_ROWS;
- size_t r1 = r % HMX_FP16_TILE_N_ROWS;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start));
+
+ uint8_t * vtcm_dst = args->vtcm_dst;
+ const __fp16 * o_tile_src = args->o_tile_src;
+ const size_t row_off = args->row_off;
+ const size_t DV_pad = factx->DV_pad;
+ const size_t row_bytes = DV * sizeof(float);
+
+ for (size_t rl = start; rl < end; ++rl) {
+ const size_t r = row_off + rl;
+ float * out = (float *) (vtcm_dst + rl * row_bytes);
+ const size_t r0 = r / HMX_FP16_TILE_N_ROWS;
+ const size_t r1 = r % HMX_FP16_TILE_N_ROWS;
const __fp16 * tile_row_base = o_tile_src + r0 * HMX_FP16_TILE_N_ROWS * DV_pad;
for (uint32_t d = 0; d < DV / 32; ++d) {
@@ -1081,8 +1606,6 @@ static void fa_o_store_thread_f32(const htp_thread_t * th, unsigned int n, unsig
*(HVX_UVector *) (out + d * 32) = Q6_V_hi_W(vp);
}
}
- // Ragged tail: DV not a multiple of 32 (e.g. 72 -> last 8 lanes). Partial vector-write
- // for the remaining (DV % 32) floats.
const uint32_t d_tail = DV / 32;
const uint32_t rem = DV - d_tail * 32;
if (rem) {
@@ -1091,52 +1614,39 @@ static void fa_o_store_thread_f32(const htp_thread_t * th, unsigned int n, unsig
HVX_Vector vd = (r1 % 2 == 0) ? Q6_V_lo_W(vp) : Q6_V_hi_W(vp);
hvx_vec_store_u((void *) (out + d_tail * 32), rem * sizeof(float), vd);
}
-
- h_idx++;
- if (h_idx == G) {
- h_idx = 0;
- q_idx++;
- }
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start));
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start));
}
static void fa_o_store_thread_f16(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
fa_o_store_args_t * args = (fa_o_store_args_t *) data;
struct hmx_fa_context * factx = args->factx;
- const size_t n_rows_g = args->n_rows_g;
+ const size_t n_rows = args->n_rows;
const size_t rows_per_t = args->rows_per_t;
const size_t G = factx->G;
const size_t DV = factx->DV;
const size_t start = (size_t) i * rows_per_t;
- const size_t end = hex_smin(start + rows_per_t, n_rows_g);
+ const size_t end = hex_smin(start + rows_per_t, n_rows);
- if (start >= n_rows_g) {
+ if (start >= n_rows) {
return;
}
struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start));
-
- const struct htp_tensor * dst = args->dst;
- const __fp16 * o_tile_src = args->o_tile_src;
- const uint32_t q_start = args->q_start;
- const uint32_t kv_head = args->kv_head;
- const uint32_t ib3 = args->ib3;
-
- // O-tiles use the padded head dim (DV_pad); dst holds the real DV lanes.
- const size_t DV_pad = factx->DV_pad;
-
- size_t q_idx = fastdiv(start, &factx->div_G);
- size_t h_idx = fastmodulo(start, G, &factx->div_G);
-
- for (size_t r = start; r < end; ++r) {
- __fp16 * out = (__fp16 *) ((uint8_t *) dst->data + (kv_head * G + h_idx) * dst->nb[1] +
- (q_start + q_idx) * dst->nb[2] + ib3 * dst->nb[3]);
-
- size_t r0 = r / HMX_FP16_TILE_N_ROWS;
- size_t r1 = r % HMX_FP16_TILE_N_ROWS;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start));
+
+ uint8_t * vtcm_dst = args->vtcm_dst;
+ const __fp16 * o_tile_src = args->o_tile_src;
+ const size_t row_off = args->row_off;
+ const size_t DV_pad = factx->DV_pad;
+ const size_t row_bytes = DV * sizeof(__fp16);
+
+ for (size_t rl = start; rl < end; ++rl) {
+ const size_t r = row_off + rl;
+ __fp16 * out = (__fp16 *) (vtcm_dst + rl * row_bytes);
+ const size_t r0 = r / HMX_FP16_TILE_N_ROWS;
+ const size_t r1 = r % HMX_FP16_TILE_N_ROWS;
const __fp16 * tile_row_base = o_tile_src + r0 * HMX_FP16_TILE_N_ROWS * DV_pad;
for (uint32_t d = 0; d < DV / 64; ++d) {
@@ -1150,7 +1660,6 @@ static void fa_o_store_thread_f16(const htp_thread_t * th, unsigned int n, unsig
*(HVX_UVector *) (out + d * 64) = Q6_V_hi_W(vp);
}
}
- // Ragged tail when DV is not a multiple of 64.
const uint32_t d_tail = DV / 64;
const uint32_t rem = DV - d_tail * 64;
if (rem) {
@@ -1161,32 +1670,99 @@ static void fa_o_store_thread_f16(const htp_thread_t * th, unsigned int n, unsig
HVX_Vector vd = (r1 % 2 == 0) ? Q6_V_lo_W(vp) : Q6_V_hi_W(vp);
hvx_vec_store_u((void *) (out + d_tail * 64), rem * sizeof(__fp16), vd);
}
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start));
+}
- h_idx++;
- if (h_idx == G) {
- h_idx = 0;
- q_idx++;
+// Push [row_off, row_off + n_rows) from vtcm_src to dst->data via bypass DMA.
+// Always leaves exactly 1 pending DMA descriptor on dma_q.
+static void fa_push_o_dma(dma_queue * dma_q,
+ const struct htp_tensor * dst,
+ const uint8_t * vtcm_src,
+ size_t vtcm_row_stride,
+ size_t row_bytes,
+ uint32_t q_start,
+ uint32_t kv_head,
+ uint32_t ib3,
+ uint32_t G,
+ const struct fastdiv_values * div_G,
+ size_t row_off,
+ size_t n_rows) {
+ const dma_addr_t dst_base = dst->data + ib3 * dst->nb[3] + (kv_head * G) * dst->nb[1];
+
+ if (G == 1) {
+ const dma_addr_t d = dst_base + (q_start + row_off) * dst->nb[2];
+ dma_queue_push(dma_q, dma_make_data(d, vtcm_src), dst->nb[2], vtcm_row_stride, row_bytes, n_rows);
+ return;
+ }
+
+ const size_t q0 = fastdiv(row_off, div_G);
+ const size_t h0 = fastmodulo(row_off, G, div_G);
+ if (h0 == 0 && (n_rows % G) == 0 && dst->nb[1] == row_bytes && vtcm_row_stride == row_bytes) {
+ const size_t n_q = n_rows / G;
+ const size_t g_bytes = (size_t) G * row_bytes;
+ const dma_addr_t d = dst_base + (q_start + q0) * dst->nb[2];
+ dma_queue_push(dma_q, dma_make_data(d, vtcm_src), dst->nb[2], g_bytes, g_bytes, n_q);
+ return;
+ }
+
+ size_t q_idx = q0;
+ size_t h_idx = h0;
+ size_t done = 0;
+ while (done < n_rows) {
+ const size_t cnt = hex_smin(G - h_idx, n_rows - done);
+ const dma_addr_t d = dst_base + h_idx * dst->nb[1] + (q_start + q_idx) * dst->nb[2];
+ const uint8_t * s = vtcm_src + done * vtcm_row_stride;
+ if (!dma_queue_push(dma_q, dma_make_data(d, s), dst->nb[1], vtcm_row_stride, row_bytes, cnt)) {
+ dma_queue_pop(dma_q);
+ dma_queue_push(dma_q, dma_make_data(d, s), dst->nb[1], vtcm_row_stride, row_bytes, cnt);
}
+ done += cnt;
+ h_idx = 0;
+ q_idx += 1;
+ }
+ while (dma_queue_depth(dma_q) > 1) {
+ dma_queue_pop(dma_q);
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start));
}
static void fa_phase_o_store(struct hmx_fa_context * factx,
+ dma_queue * dma_q,
const struct htp_tensor * dst,
const __fp16 * o_tile_src,
+ uint8_t * vtcm_dst,
uint32_t q_start,
uint32_t kv_head,
uint32_t ib3,
size_t n_rows_g) {
- work_queue_t wp = factx->octx->ctx->hvx_queue;
- uint32_t n = 1;
- if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * 2)) {
- n = factx->n_hvx;
+ work_queue_t wp = factx->octx->ctx->hvx_queue;
+ const size_t row_bytes = factx->DV * (factx->is_dst_fp32 ? sizeof(float) : sizeof(__fp16));
+ work_queue_func_t store_fn = factx->is_dst_fp32 ? fa_o_store_thread_f32 : fa_o_store_thread_f16;
+
+ size_t max_rows = factx->o_tile_bytes / row_bytes;
+ if (max_rows >= factx->G && max_rows < n_rows_g) {
+ max_rows = (max_rows / factx->G) * factx->G;
+ }
+ if (max_rows == 0) {
+ max_rows = 1;
+ }
+
+ for (size_t row_off = 0; row_off < n_rows_g; row_off += max_rows) {
+ if (row_off > 0) {
+ dma_queue_pop(dma_q);
+ }
+ const size_t n_rows = hex_smin(max_rows, n_rows_g - row_off);
+ uint32_t n = 1;
+ if (factx->n_hvx > 1 && n_rows >= (size_t) (factx->n_hvx * 2)) {
+ n = factx->n_hvx;
+ }
+ const size_t rows_per_t = hmx_ceil_div(n_rows, n);
+ fa_o_store_args_t args = { factx, vtcm_dst, o_tile_src, q_start, kv_head, row_off, n_rows, rows_per_t };
+ work_queue_run(wp, store_fn, &args, n);
+
+ fa_push_o_dma(dma_q, dst, vtcm_dst, row_bytes, row_bytes,
+ q_start, kv_head, ib3, factx->G, &factx->div_G, row_off, n_rows);
}
- size_t rows_per_t = hmx_ceil_div(n_rows_g, n);
- fa_o_store_args_t args = { factx, dst, o_tile_src, q_start, kv_head, ib3, n_rows_g, rows_per_t };
- work_queue_func_t store_fn = factx->is_dst_fp32 ? fa_o_store_thread_f32 : fa_o_store_thread_f16;
- work_queue_run(wp, store_fn, &args, n);
}
typedef struct {
@@ -1227,9 +1803,7 @@ static inline void fa_softmax_impl(
const size_t kv_rows = args->kv_rows;
const size_t Bc = args->Bc;
const size_t G = args->G;
- const size_t n_tiles_per_bc = args->n_tiles_per_bc;
const size_t n_row_vec_cnt = hmx_ceil_div(n_rows_g, 64);
- const uint32_t im3 = has_mask ? fastmodulo(args->ib3, args->mask->ne[3], &factx->src3_div3) : 0;
size_t vec_start = 0;
size_t vec_end = n_row_vec_cnt;
@@ -1479,10 +2053,10 @@ static inline void fa_softmax_impl(
HVX_Vector v_s_minus_m0_1 = Q6_Vqf16_vsub_VhfVhf(my_row_buf0[ci1], v_dup_m0);
HVX_Vector v_s_minus_m1_1 = Q6_Vqf16_vsub_VhfVhf(my_row_buf1[ci1], v_dup_m1);
- HVX_Vector v_p_row0_hf_0 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_0));
- HVX_Vector v_p_row1_hf_0 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_0));
- HVX_Vector v_p_row0_hf_1 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_1));
- HVX_Vector v_p_row1_hf_1 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_1));
+ HVX_Vector v_p_row0_hf_0 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_0));
+ HVX_Vector v_p_row1_hf_0 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_0));
+ HVX_Vector v_p_row0_hf_1 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_1));
+ HVX_Vector v_p_row1_hf_1 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_1));
__fp16 * out_dtile0 = p_st_base + ci0 * HMX_FP16_TILE_N_ELMS * 2;
__fp16 * out_dtile1 = p_st_base + ci1 * HMX_FP16_TILE_N_ELMS * 2;
@@ -1514,8 +2088,8 @@ static inline void fa_softmax_impl(
HVX_Vector v_s_minus_m0 = Q6_Vqf16_vsub_VhfVhf(my_row_buf0[ci], v_dup_m0);
HVX_Vector v_s_minus_m1 = Q6_Vqf16_vsub_VhfVhf(my_row_buf1[ci], v_dup_m1);
- HVX_Vector v_p_row0_hf = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0));
- HVX_Vector v_p_row1_hf = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1));
+ HVX_Vector v_p_row0_hf = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0));
+ HVX_Vector v_p_row1_hf = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1));
__fp16 * out_dtile = p_st_base + ci * HMX_FP16_TILE_N_ELMS * 2;
HVX_Vector * pv_p_out0 = ((HVX_Vector *) out_dtile) + r1 / 2;
HVX_Vector * pv_p_out1 = pv_p_out0 + 16;
@@ -1559,122 +2133,849 @@ static inline void fa_softmax_impl(
HVX_Vector v_m_diff1 = HVX_OP_SUB_F32(m_prev_v1, v_m_curr1);
HVX_Vector v_m_diff_f16 = hvx_vec_f32_to_f16(v_m_diff0, v_m_diff1);
- HVX_Vector exp_m_diff_f16 = hvx_vec_exp2_f16(v_m_diff_f16);
+ HVX_Vector exp_m_diff_f16 = hvx_vec_exp2_neg_f16(v_m_diff_f16);
HVX_VectorPair exp_m_diff_pair = hvx_vec_f16_to_f32(exp_m_diff_f16);
HVX_Vector exp_m_diff0 = Q6_V_lo_W(exp_m_diff_pair);
HVX_Vector exp_m_diff1 = Q6_V_hi_W(exp_m_diff_pair);
- HVX_VectorPair rowsum_acc_pair = hvx_vec_f16_to_f32(rowsum_acc_v);
- HVX_Vector v_rowsum_acc_f32_0 = Q6_V_lo_W(rowsum_acc_pair);
- HVX_Vector v_rowsum_acc_f32_1 = Q6_V_hi_W(rowsum_acc_pair);
+ HVX_VectorPair rowsum_acc_pair = hvx_vec_f16_to_f32(rowsum_acc_v);
+ HVX_Vector v_rowsum_acc_f32_0 = Q6_V_lo_W(rowsum_acc_pair);
+ HVX_Vector v_rowsum_acc_f32_1 = Q6_V_hi_W(rowsum_acc_pair);
+
+ HVX_Vector l_prev_v0 = factx->vtcm_l_vec[r_vec_idx * 2 + 0];
+ HVX_Vector l_prev_v1 = factx->vtcm_l_vec[r_vec_idx * 2 + 1];
+ HVX_Vector v_l_curr0 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v0, exp_m_diff0), v_rowsum_acc_f32_0);
+ HVX_Vector v_l_curr1 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v1, exp_m_diff1), v_rowsum_acc_f32_1);
+
+ factx->vtcm_m_vec[r_vec_idx * 2 + 0] = v_m_curr0;
+ factx->vtcm_m_vec[r_vec_idx * 2 + 1] = v_m_curr1;
+ factx->vtcm_l_vec[r_vec_idx * 2 + 0] = v_l_curr0;
+ factx->vtcm_l_vec[r_vec_idx * 2 + 1] = v_l_curr1;
+
+ // Build diagonal tile D = diag(exp(m_diff))
+ const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets;
+ const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16));
+ HVX_Vector v_exp_m_diff = exp_m_diff_f16;
+
+ __fp16 * const d_tiles_out = factx->vtcm_d_tiles[args->buf_idx];
+
+ size_t t0 = r_vec_idx * 2;
+ if (t0 < args->n_row_tiles) {
+ const HVX_Vector v_content = v_exp_m_diff;
+ __fp16 * out_base = d_tiles_out + t0 * HMX_FP16_TILE_N_ELMS;
+ Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content);
+ }
+
+ size_t t1 = r_vec_idx * 2 + 1;
+ if (t1 < args->n_row_tiles) {
+ const HVX_Vector v_content = Q6_V_vror_VR(v_exp_m_diff, 64);
+ __fp16 * out_base = d_tiles_out + t1 * HMX_FP16_TILE_N_ELMS;
+ Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content);
+ }
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, (uint16_t) (args->q_start * G + vec_start * 64));
+}
+
+static void fa_softmax_thread_nomask(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_softmax_impl(th, n, i, data,
+ /*has_mask=*/false,
+ /*mask_broadcast=*/false,
+ /*is_g1=*/false,
+ /*has_alibi=*/false,
+ /*has_softcap=*/false);
+}
+
+static void fa_softmax_thread_mask_broadcast_g1(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_softmax_impl(th, n, i, data,
+ /*has_mask=*/true,
+ /*mask_broadcast=*/true,
+ /*is_g1=*/true,
+ /*has_alibi=*/false,
+ /*has_softcap=*/false);
+}
+
+static void fa_softmax_thread_mask_broadcast_gn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_softmax_impl(th, n, i, data,
+ /*has_mask=*/true,
+ /*mask_broadcast=*/true,
+ /*is_g1=*/false,
+ /*has_alibi=*/false,
+ /*has_softcap=*/false);
+}
+
+static void fa_softmax_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_softmax_args_t * args = (fa_softmax_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
+
+ const bool has_mask = (args->mask != NULL);
+ const bool mask_broadcast = factx->mask_broadcast;
+ const bool is_g1 = (args->G == 1);
+ const bool has_alibi = args->has_alibi;
+ const bool has_softcap = factx->has_softcap;
+
+ fa_softmax_impl(th, n, i, data, has_mask, mask_broadcast, is_g1, has_alibi, has_softcap);
+}
+
+static inline HVX_Vector hvx_fa_load_sinks(const float * sinks_data, size_t idx, size_t count) {
+ const HVX_Vector * v_src = (const HVX_Vector *) sinks_data + (idx >> 5);
+ const size_t lane_off = idx & 31;
+ const size_t byte_off = lane_off * sizeof(float);
+ return (lane_off + count > 32)
+ ? Q6_V_valign_VVR(v_src[1], v_src[0], byte_off)
+ : Q6_V_vror_VR(v_src[0], byte_off);
+}
+
+static __attribute__((noinline)) void fa_build_d_diag_inv_l(struct hmx_fa_context * factx,
+ size_t n_row_tiles,
+ size_t n_row_tiles_g_br,
+ uint32_t kv_head,
+ size_t n_rows_g) {
+ (void) n_row_tiles_g_br;
+
+ // sinks: l += exp(sink - m * ln2) in f32, m and l are in the log2 domain
+ if (factx->sinks) {
+ const float * sinks_data = factx->vtcm_sinks;
+ const size_t G = factx->G;
+ const size_t head_base = (size_t) kv_head * G;
+ const HVX_Vector v_ln2 = Q6_V_vsplat_R(EXP_LOGN2);
+ const HVX_Vector v_head_sinks = (G <= 32) ? hvx_fa_load_sinks(sinks_data, head_base, G) : Q6_V_vzero();
+ HVX_Vector v_sink = Q6_V_vzero();
+ size_t g_prev = SIZE_MAX;
+
+ for (size_t i = 0; i < n_row_tiles; ++i) {
+ // the sink pattern of a tile only depends on (i * 32) % G, rebuild it when that changes
+ const size_t r0 = i * 32;
+ const size_t g0 = fastmodulo(r0, G, &factx->div_G);
+ if (g0 != g_prev) {
+ const size_t rem_g = G - g0;
+ if (G <= 32) {
+ const HVX_Vector v_lo = Q6_V_vror_VR(v_head_sinks, g0 * sizeof(float));
+ const HVX_Vector v_hi = Q6_V_vror_VR(v_head_sinks, 128 - rem_g * sizeof(float));
+ v_sink = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(rem_g * sizeof(float)), v_lo, v_hi);
+ for (size_t len = G; len < 32; len <<= 1) {
+ const HVX_VectorPred q_keep = Q6_Q_vsetq_R(len * sizeof(float));
+ const HVX_Vector v_shifted = Q6_V_vror_VR(v_sink, 128 - len * sizeof(float));
+ v_sink = Q6_V_vmux_QVV(q_keep, v_sink, v_shifted);
+ }
+ } else if (rem_g >= 32) {
+ v_sink = hvx_fa_load_sinks(sinks_data, head_base + g0, 32);
+ } else {
+ const HVX_Vector v_lo = hvx_fa_load_sinks(sinks_data, head_base + g0, rem_g);
+ const HVX_Vector v_hi = hvx_fa_load_sinks(sinks_data, head_base, 32 - rem_g);
+ v_sink = Q6_V_vmux_QVV(Q6_Q_vsetq_R(rem_g * sizeof(float)), v_lo, Q6_V_vror_VR(v_hi, 128 - rem_g * sizeof(float)));
+ }
+ g_prev = g0;
+ }
+
+ HVX_Vector v_d = HVX_OP_SUB_F32(v_sink, HVX_OP_MUL_F32(factx->vtcm_m_vec[i], v_ln2));
+ if (r0 + 32 > n_rows_g) {
+ const HVX_VectorPred q_valid = Q6_Q_vsetq_R((n_rows_g - r0) * sizeof(float));
+ v_d = Q6_V_vmux_QVV(q_valid, v_d, Q6_V_vzero());
+ }
+ factx->vtcm_l_vec[i] = HVX_OP_ADD_F32(factx->vtcm_l_vec[i], hvx_vec_exp_f32(v_d));
+ }
+ }
+
+ const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets;
+ const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16));
+ const HVX_Vector one = hvx_vec_splat_f32(1.0f);
+
+ HVX_Vector v_content = Q6_V_vzero();
+ for (size_t i = 0; i < n_row_tiles; ++i) {
+ if ((i % 2) == 0) {
+ HVX_Vector inv_lo = HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i]));
+ HVX_Vector inv_hi = (i + 1 < n_row_tiles) ? HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i + 1])) : Q6_V_vzero();
+ v_content = hvx_vec_f32_to_f16(inv_lo, inv_hi);
+ } else {
+ v_content = Q6_V_vror_VR(v_content, 64);
+ }
+
+ __fp16 * out_base = factx->vtcm_d_inv_l + i * HMX_FP16_TILE_N_ELMS;
+ Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content);
+ }
+}
+
+static __attribute__((always_inline)) inline void fa_w8a8_mask_and_rowmax_pair(
+ struct hmx_fa_context * factx,
+ fa_softmax_args_t * args,
+ HVX_Vector * row_buf0,
+ HVX_Vector * row_buf1,
+ uint32_t r,
+ uint32_t r_vec_off,
+ size_t n_rows_g,
+ size_t kv_rows,
+ const __fp16 * slopes_row64,
+ HVX_Vector * v_rowmax0_out,
+ HVX_Vector * v_rowmax1_out,
+ const bool has_mask,
+ const bool mask_broadcast,
+ const bool is_g1,
+ const bool has_alibi
+) {
+ int32_t slope0_u16 = 0;
+ int32_t slope1_u16 = 0;
+ if (has_alibi) {
+ const HVX_Vector v_sl = hvx_vmem(slopes_row64);
+ slope0_u16 = Q6_R_vextract_VR(v_sl, (int) (r_vec_off * 2));
+ if (r + 1 < n_rows_g) {
+ slope1_u16 = Q6_R_vextract_VR(v_sl, (int) ((r_vec_off + 1) * 2));
+ }
+ }
+
+ HVX_Vector v_s_rowmax0 = Q6_Vh_vsplat_R(0xfbff);
+ HVX_Vector v_s_rowmax1 = Q6_Vh_vsplat_R(0xfbff);
+
+ if (has_mask) {
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < kv_rows; c += 64) {
+ const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff);
+ const HVX_Vector v_threshold = Q6_Vh_vsplat_R(0xcc00); // fp16 -16.0
+ size_t ci = c / 64;
+ const size_t ne = hex_smin(kv_rows - c, 64);
+ HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(ne * sizeof(__fp16));
+
+ HVX_Vector v_mask0, v_mask1;
+ if (mask_broadcast) {
+ if (is_g1) {
+ const size_t qi0 = r + 0;
+ v_mask0 = *(const HVX_Vector *) (args->mask_vtcm + qi0 * args->mask_vtcm_row_stride + c);
+ v_mask1 = v_neg_inf;
+ if (r + 1 < n_rows_g) {
+ const size_t qi1 = r + 1;
+ v_mask1 = *(const HVX_Vector *) (args->mask_vtcm + qi1 * args->mask_vtcm_row_stride + c);
+ }
+ } else {
+ const size_t qi0 = fastdiv(r + 0, &factx->div_G);
+ v_mask0 = *(const HVX_Vector *) (args->mask_vtcm + qi0 * args->mask_vtcm_row_stride + c);
+ v_mask1 = v_neg_inf;
+ if (r + 1 < n_rows_g) {
+ const size_t qi1 = fastdiv(r + 1, &factx->div_G);
+ if (qi1 == qi0) {
+ v_mask1 = v_mask0;
+ } else {
+ v_mask1 = *(const HVX_Vector *) (args->mask_vtcm + qi1 * args->mask_vtcm_row_stride + c);
+ }
+ }
+ }
+ } else {
+ const size_t m0 = r + 0;
+ v_mask0 = *(const HVX_Vector *) (args->mask_vtcm + m0 * args->mask_vtcm_row_stride + c);
+ v_mask1 = v_neg_inf;
+ if (r + 1 < n_rows_g) {
+ const size_t m1 = r + 1;
+ v_mask1 = *(const HVX_Vector *) (args->mask_vtcm + m1 * args->mask_vtcm_row_stride + c);
+ }
+ }
+
+ const HVX_Vector v_log2e = hvx_vec_splat_f16(EXP_LOG2E_F);
+ {
+ HVX_VectorPred q_keep0 = Q6_Q_and_QQ(Q6_Q_vcmp_gt_VhfVhf(v_mask0, v_threshold), q_tail_keep);
+ HVX_Vector v_m0 = hvx_vec_mul_f16_f16(v_mask0, v_log2e);
+ if (has_alibi) {
+ v_m0 = hvx_vec_mul_f16_f16(v_m0, Q6_Vh_vsplat_R(slope0_u16));
+ }
+ HVX_Vector v_r0 = Q6_V_vmux_QVV(q_keep0, hvx_vec_add_f16_f16(row_buf0[ci], v_m0), v_neg_inf);
+ row_buf0[ci] = v_r0;
+ v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, v_r0);
+ }
+ {
+ HVX_VectorPred q_keep1 = Q6_Q_and_QQ(Q6_Q_vcmp_gt_VhfVhf(v_mask1, v_threshold), q_tail_keep);
+ HVX_Vector v_m1 = hvx_vec_mul_f16_f16(v_mask1, v_log2e);
+ if (has_alibi) {
+ v_m1 = hvx_vec_mul_f16_f16(v_m1, Q6_Vh_vsplat_R(slope1_u16));
+ }
+ HVX_Vector v_r1 = Q6_V_vmux_QVV(q_keep1, hvx_vec_add_f16_f16(row_buf1[ci], v_m1), v_neg_inf);
+ row_buf1[ci] = v_r1;
+ v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, v_r1);
+ }
+ }
+ } else {
+ size_t c = 0;
+ for (; c + 128 <= kv_rows; c += 128) {
+ size_t ci0 = c / 64;
+ size_t ci1 = ci0 + 1;
+ v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, row_buf0[ci0]);
+ v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, row_buf1[ci0]);
+ v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, row_buf0[ci1]);
+ v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, row_buf1[ci1]);
+ }
+ for (; c < kv_rows; c += 64) {
+ const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff);
+ size_t ci = c / 64;
+ const size_t ne = hex_smin(kv_rows - c, 64);
+ HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(ne * sizeof(__fp16));
+ if (ne < 64) {
+ row_buf0[ci] = Q6_V_vmux_QVV(q_tail_keep, row_buf0[ci], v_neg_inf);
+ row_buf1[ci] = Q6_V_vmux_QVV(q_tail_keep, row_buf1[ci], v_neg_inf);
+ }
+ v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, row_buf0[ci]);
+ v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, row_buf1[ci]);
+ }
+ }
+
+ const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff);
+ *v_rowmax0_out = (r + 0 < n_rows_g) ? hvx_vec_reduce_max_f16(v_s_rowmax0) : v_neg_inf;
+ *v_rowmax1_out = (r + 1 < n_rows_g) ? hvx_vec_reduce_max_f16(v_s_rowmax1) : v_neg_inf;
+}
+
+static __attribute__((noinline)) void fa_w8a8_exp_quant_quad(
+ HVX_Vector * restrict row_buf0,
+ HVX_Vector * restrict row_buf1,
+ HVX_Vector * restrict row_buf2,
+ HVX_Vector * restrict row_buf3,
+ uint8_t * restrict p_row64_base,
+ uint32_t rg,
+ size_t kv_rows,
+ uint32_t n_col_tiles,
+ int32_t smax0,
+ int32_t smax1,
+ int32_t smax2,
+ int32_t smax3,
+ uint32_t valid_mask,
+ float * restrict rowsum_dst,
+ uint32_t rmp0_bits,
+ uint32_t rmp1_bits,
+ uint32_t rmp2_bits,
+ uint32_t rmp3_bits
+) {
+ HVX_Vector * bufs[4] = { row_buf0, row_buf1, row_buf2, row_buf3 };
+ int32_t smaxs[4] = { smax0, smax1, smax2, smax3 };
+ uint32_t rmps[4] = { rmp0_bits, rmp1_bits, rmp2_bits, rmp3_bits };
+ int32_t sum_bits[4];
+
+ for (uint32_t k = 0; k < 4; ++k) {
+ HVX_Vector * rb = bufs[k];
+ const int32_t sm = smaxs[k];
+ HVX_Vector v_sum = Q6_V_vzero();
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < kv_rows; c += 64) {
+ const size_t ci = c / 64;
+ HVX_Vector v_p = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(rb[ci], Q6_Vh_vsplat_R(sm))));
+ rb[ci] = v_p;
+ HVX_VectorPair vp = hvx_vec_f16_to_f32_shuff(v_p);
+ v_sum = Q6_Vqf32_vadd_Vqf32Vqf32(v_sum, Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(vp), Q6_V_hi_W(vp)));
+ }
+ HVX_Vector v_s = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(v_sum)), rmps[k]));
+ sum_bits[k] = Q6_R_vextract_VR(v_s, 0);
+ }
+
+ {
+ HVX_Vector v02 = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_vsplat_R(sum_bits[2]), Q6_V_vsplat_R(sum_bits[0]), -4));
+ HVX_Vector v13 = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_vsplat_R(sum_bits[3]), Q6_V_vsplat_R(sum_bits[1]), -4));
+ hvx_vec_store_u(rowsum_dst, 4 * sizeof(float), Q6_V_lo_W(Q6_W_vshuff_VVR(v13, v02, -4)));
+ }
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < kv_rows; c += 64) {
+ const size_t ci = c / 64;
+ const uint32_t kt = (uint32_t) (ci * 2);
+ const bool write_hi = (kt + 1 < n_col_tiles);
+ const HVX_Vector v_255_hf = hvx_vec_splat_f16(255.0f);
+
+ HVX_Vector hf0 = (valid_mask & 1u) ? hvx_vec_mul_f16_f16(row_buf0[ci], v_255_hf) : Q6_V_vzero();
+ HVX_Vector hf1 = (valid_mask & 2u) ? hvx_vec_mul_f16_f16(row_buf1[ci], v_255_hf) : Q6_V_vzero();
+ HVX_Vector hf2 = (valid_mask & 4u) ? hvx_vec_mul_f16_f16(row_buf2[ci], v_255_hf) : Q6_V_vzero();
+ HVX_Vector hf3 = (valid_mask & 8u) ? hvx_vec_mul_f16_f16(row_buf3[ci], v_255_hf) : Q6_V_vzero();
+
+ hmx_fa_w8a8_pack_p_quad_u8_sm(p_row64_base, kt, rg, write_hi, hf0, hf1, hf2, hf3);
+ }
+}
+
+static __attribute__((noinline)) void fa_w8a8_decode_s_quad_rows_nocap(
+ const uint8_t * restrict tile_base,
+ const float * restrict dw_base,
+ HVX_Vector * restrict row_buf0,
+ HVX_Vector * restrict row_buf1,
+ HVX_Vector * restrict row_buf2,
+ HVX_Vector * restrict row_buf3,
+ size_t kv_rows,
+ uint32_t da0,
+ uint32_t da1,
+ uint32_t da2,
+ uint32_t da3
+) {
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < kv_rows; c += 64) {
+ const size_t ci = c / 64;
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80);
+ HVX_Vector s0_lo, s1_lo, s2_lo, s3_lo;
+ hmx_fa_w8a8_eval_s_tile_quad(tile_base, dw_base, c, da0, da1, da2, da3, sign_80,
+ &s0_lo, &s1_lo, &s2_lo, &s3_lo);
+
+ HVX_Vector s0_hi = Q6_V_vzero();
+ HVX_Vector s1_hi = Q6_V_vzero();
+ HVX_Vector s2_hi = Q6_V_vzero();
+ HVX_Vector s3_hi = Q6_V_vzero();
+ if (c + 32 < kv_rows) {
+ hmx_fa_w8a8_eval_s_tile_quad(tile_base, dw_base, c + 32, da0, da1, da2, da3, sign_80,
+ &s0_hi, &s1_hi, &s2_hi, &s3_hi);
+ }
+
+ row_buf0[ci] = hvx_vec_f32_to_f16(s0_lo, s0_hi);
+ row_buf1[ci] = hvx_vec_f32_to_f16(s1_lo, s1_hi);
+ row_buf2[ci] = hvx_vec_f32_to_f16(s2_lo, s2_hi);
+ row_buf3[ci] = hvx_vec_f32_to_f16(s3_lo, s3_hi);
+ }
+}
+
+static __attribute__((noinline)) void fa_w8a8_decode_s_quad_rows_cap(
+ const uint8_t * restrict tile_base,
+ const float * restrict dw_base,
+ HVX_Vector * restrict row_buf0,
+ HVX_Vector * restrict row_buf1,
+ HVX_Vector * restrict row_buf2,
+ HVX_Vector * restrict row_buf3,
+ size_t kv_rows,
+ uint32_t da0,
+ uint32_t da1,
+ uint32_t da2,
+ uint32_t da3,
+ const __fp16 * logit_softcap_ptr
+) {
+ fa_w8a8_decode_s_quad_rows_nocap(
+ tile_base, dw_base, row_buf0, row_buf1, row_buf2, row_buf3,
+ kv_rows, da0, da1, da2, da3);
+
+ HVX_Vector * bufs[4] = { row_buf0, row_buf1, row_buf2, row_buf3 };
+ const __fp16 cap = *logit_softcap_ptr;
+ for (uint32_t k = 0; k < 4; ++k) {
+ HVX_Vector * rb = bufs[k];
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < kv_rows; c += 64) {
+ const size_t ci = c / 64;
+ rb[ci] = hvx_vec_mul_f16_f16(hvx_vec_tanh_f16(rb[ci]), hvx_vec_splat_f16(cap));
+ }
+ }
+}
+
+static __attribute__((always_inline)) inline void fa_w8a8_softmax_impl(
+ const htp_thread_t * th, unsigned int n, unsigned int i, void * data,
+ const bool has_mask,
+ const bool mask_broadcast,
+ const bool is_g1,
+ const bool has_alibi,
+ const bool has_softcap
+) {
+ fa_softmax_args_t * args = (fa_softmax_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
+
+ const size_t n_rows_g = args->n_rows_g;
+ const size_t kv_rows = args->kv_rows;
+ const size_t G = args->G;
+ const size_t n_row_vec_cnt = hmx_ceil_div(n_rows_g, 64);
+
+ size_t vec_start = 0;
+ size_t vec_end = n_row_vec_cnt;
+ if (n > 1) {
+ const size_t vecs_per_t = fastdiv(n_row_vec_cnt + n - 1, &args->thread_div);
+ vec_start = i * vecs_per_t;
+ vec_end = hex_smin(vec_start + vecs_per_t, n_row_vec_cnt);
+ }
+
+ if (vec_start >= n_row_vec_cnt) {
+ return;
+ }
+
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_SFM, (uint16_t) (args->q_start * G + vec_start * 64));
+
+ const size_t row_buf_stride = factx->row_buf_stride;
+ HVX_Vector * my_row_buf0 = factx->vtcm_row_bufs + (size_t) i * 4 * row_buf_stride;
+ HVX_Vector * my_row_buf1 = my_row_buf0 + row_buf_stride;
+ HVX_Vector * my_row_buf2 = my_row_buf1 + row_buf_stride;
+ HVX_Vector * my_row_buf3 = my_row_buf2 + row_buf_stride;
+
+ const float * dw_base = factx->vtcm_k_scales[args->buf_idx];
+ const uint8_t * s_base = (const uint8_t *) factx->vtcm_s_tiles[args->buf_idx];
+ uint8_t * p_base = (uint8_t *) factx->vtcm_p_tiles[args->buf_idx];
+ float * p_scales = factx->vtcm_p_scales[args->buf_idx];
+ float * s_rowmax = (float *) factx->vtcm_s_rowmax;
+ float * p_rowsum = (float *) factx->vtcm_p_rowsum;
+ const uint32_t n_ct = (uint32_t) args->n_col_tiles;
+
+ for (size_t r_vec_idx = vec_start; r_vec_idx < vec_end; ++r_vec_idx) {
+ factx->vtcm_s_rowmax[r_vec_idx * 2 + 0] = factx->vtcm_m_vec[r_vec_idx * 2 + 0];
+ factx->vtcm_s_rowmax[r_vec_idx * 2 + 1] = factx->vtcm_m_vec[r_vec_idx * 2 + 1];
+ factx->vtcm_p_rowsum[r_vec_idx * 2 + 0] = Q6_V_vzero();
+ factx->vtcm_p_rowsum[r_vec_idx * 2 + 1] = Q6_V_vzero();
+
+ const uint8_t * s_row64_base = s_base + r_vec_idx * n_ct * 2 * HMX_W8A8_ACT_TILE_SIZE;
+ uint8_t * p_row64_base = p_base + r_vec_idx * n_ct * HMX_W8A8_ACT_TILE_SIZE;
+
+ #pragma clang loop unroll(disable)
+ for (uint32_t r_vec_off = 0; r_vec_off < 64; r_vec_off += 4) {
+ const uint32_t r = (uint32_t) (r_vec_idx * 64 + r_vec_off);
+ if (r >= n_rows_g) {
+ break;
+ }
+
+ const uint32_t rg = r_vec_off >> 2;
+ const uint8_t * tile_base = s_row64_base + (size_t) rg * 128;
+
+ const HVX_Vector v_da = hvx_vmem(factx->vtcm_q_scales + r_vec_idx * 64 + (r_vec_off & 32u));
+ const int doff = (int) ((r_vec_off & 31u) * 4u);
+ const uint32_t da0 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 0);
+ const uint32_t da1 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 4);
+ const uint32_t da2 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 8);
+ const uint32_t da3 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 12);
+
+ if (has_softcap) {
+ fa_w8a8_decode_s_quad_rows_cap(
+ tile_base, dw_base,
+ my_row_buf0, my_row_buf1, my_row_buf2, my_row_buf3,
+ kv_rows, da0, da1, da2, da3, &factx->logit_softcap);
+ } else {
+ fa_w8a8_decode_s_quad_rows_nocap(
+ tile_base, dw_base,
+ my_row_buf0, my_row_buf1, my_row_buf2, my_row_buf3,
+ kv_rows, da0, da1, da2, da3);
+ }
+
+ const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff);
+ const __fp16 * slopes_row64 = args->slopes + r_vec_idx * 64;
+ HVX_Vector v_smax0, v_smax1, v_smax2, v_smax3;
+ fa_w8a8_mask_and_rowmax_pair(
+ factx, args, my_row_buf0, my_row_buf1,
+ r + 0, r_vec_off + 0, n_rows_g, kv_rows, slopes_row64,
+ &v_smax0, &v_smax1, has_mask, mask_broadcast, is_g1, has_alibi);
+ if (r + 2 < n_rows_g) {
+ fa_w8a8_mask_and_rowmax_pair(
+ factx, args, my_row_buf2, my_row_buf3,
+ r + 2, r_vec_off + 2, n_rows_g, kv_rows, slopes_row64,
+ &v_smax2, &v_smax3, has_mask, mask_broadcast, is_g1, has_alibi);
+ } else {
+ v_smax2 = v_neg_inf;
+ v_smax3 = v_neg_inf;
+ }
+
+ // Compute m_new = max(m_prev, s_rowmax) and store to vtcm_s_rowmax
+ HVX_Vector m_src = factx->vtcm_m_vec[r_vec_idx * 2 + (r_vec_off >> 5)];
+ uint32_t m_off = r_vec_off & 31u;
+ HVX_Vector mp0 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 0) * 4));
+ HVX_Vector mp1 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 1) * 4));
+ HVX_Vector mp2 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 2) * 4));
+ HVX_Vector mp3 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 3) * 4));
+
+ HVX_Vector v_dup_m0 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp0, mp0), v_smax0);
+ HVX_Vector v_dup_m1 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp1, mp1), v_smax1);
+ HVX_Vector v_dup_m2 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp2, mp2), v_smax2);
+ HVX_Vector v_dup_m3 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp3, mp3), v_smax3);
+
+ {
+ HVX_Vector fm0 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m0));
+ HVX_Vector fm1 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m1));
+ HVX_Vector fm2 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m2));
+ HVX_Vector fm3 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m3));
+ HVX_Vector m02 = Q6_V_lo_W(Q6_W_vshuff_VVR(fm2, fm0, -4));
+ HVX_Vector m13 = Q6_V_lo_W(Q6_W_vshuff_VVR(fm3, fm1, -4));
+ hvx_vec_store_u(s_rowmax + r, 4 * sizeof(float), Q6_V_lo_W(Q6_W_vshuff_VVR(m13, m02, -4)));
+ }
+
+ // row_max_p = exp2(s_rowmax - m_new); zero if row is masked or out of bounds
+ HVX_VectorPred q_ok0 = Q6_Q_vcmp_gt_VhfVhf(v_smax0, v_neg_inf);
+ HVX_VectorPred q_ok1 = Q6_Q_vcmp_gt_VhfVhf(v_smax1, v_neg_inf);
+ HVX_VectorPred q_ok2 = Q6_Q_vcmp_gt_VhfVhf(v_smax2, v_neg_inf);
+ HVX_VectorPred q_ok3 = Q6_Q_vcmp_gt_VhfVhf(v_smax3, v_neg_inf);
+
+ const HVX_Vector v_one_i = Q6_V_vsplat_R(1);
+ uint32_t valid_mask = 0;
+ valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok0, v_one_i, Q6_V_vzero()), 0) & 1u) << 0;
+ valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok1, v_one_i, Q6_V_vzero()), 0) & 1u) << 1;
+ valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok2, v_one_i, Q6_V_vzero()), 0) & 1u) << 2;
+ valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok3, v_one_i, Q6_V_vzero()), 0) & 1u) << 3;
+
+ const int32_t smax0 = Q6_R_vextract_VR(v_smax0, 0);
+ const int32_t smax1 = Q6_R_vextract_VR(v_smax1, 0);
+ const int32_t smax2 = Q6_R_vextract_VR(v_smax2, 0);
+ const int32_t smax3 = Q6_R_vextract_VR(v_smax3, 0);
+
+ HVX_Vector v_rmp_hf0 = Q6_V_vmux_QVV(q_ok0, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax0, v_dup_m0))), Q6_V_vzero());
+ HVX_Vector v_rmp_hf1 = Q6_V_vmux_QVV(q_ok1, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax1, v_dup_m1))), Q6_V_vzero());
+ HVX_Vector v_rmp_hf2 = Q6_V_vmux_QVV(q_ok2, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax2, v_dup_m2))), Q6_V_vzero());
+ HVX_Vector v_rmp_hf3 = Q6_V_vmux_QVV(q_ok3, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax3, v_dup_m3))), Q6_V_vzero());
+
+ const uint32_t rmp0_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf0)), 0);
+ const uint32_t rmp1_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf1)), 0);
+ const uint32_t rmp2_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf2)), 0);
+ const uint32_t rmp3_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf3)), 0);
+
+ {
+ const HVX_Vector v_inv255 = hvx_vec_splat_f32(1.0f / 255.0f);
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp0_bits), v_inv255);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp1_bits), v_inv255);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp2_bits), v_inv255);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp3_bits), v_inv255);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_dp = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(p_scales + r, 4 * sizeof(float), v_dp);
+ }
+
+ fa_w8a8_exp_quant_quad(
+ my_row_buf0, my_row_buf1, my_row_buf2, my_row_buf3,
+ p_row64_base, rg, kv_rows, n_ct,
+ smax0, smax1, smax2, smax3, valid_mask,
+ p_rowsum + r, rmp0_bits, rmp1_bits, rmp2_bits, rmp3_bits);
+ }
+
+ HVX_Vector m_prev_v0 = factx->vtcm_m_vec[r_vec_idx * 2 + 0];
+ HVX_Vector m_prev_v1 = factx->vtcm_m_vec[r_vec_idx * 2 + 1];
+ HVX_Vector v_m_curr0 = Q6_Vsf_vmax_VsfVsf(m_prev_v0, factx->vtcm_s_rowmax[r_vec_idx * 2 + 0]);
+ HVX_Vector v_m_curr1 = Q6_Vsf_vmax_VsfVsf(m_prev_v1, factx->vtcm_s_rowmax[r_vec_idx * 2 + 1]);
+
+ HVX_Vector v_m_diff0 = HVX_OP_SUB_F32(m_prev_v0, v_m_curr0);
+ HVX_Vector v_m_diff1 = HVX_OP_SUB_F32(m_prev_v1, v_m_curr1);
+
+ HVX_Vector v_m_diff_f16 = hvx_vec_f32_to_f16(v_m_diff0, v_m_diff1);
+ HVX_Vector exp_m_diff_f16 = hvx_vec_exp2_neg_f16(v_m_diff_f16);
+ HVX_VectorPair exp_m_diff_pair = hvx_vec_f16_to_f32(exp_m_diff_f16);
+ HVX_Vector exp_m_diff0 = Q6_V_lo_W(exp_m_diff_pair);
+ HVX_Vector exp_m_diff1 = Q6_V_hi_W(exp_m_diff_pair);
HVX_Vector l_prev_v0 = factx->vtcm_l_vec[r_vec_idx * 2 + 0];
HVX_Vector l_prev_v1 = factx->vtcm_l_vec[r_vec_idx * 2 + 1];
- HVX_Vector v_l_curr0 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v0, exp_m_diff0), v_rowsum_acc_f32_0);
- HVX_Vector v_l_curr1 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v1, exp_m_diff1), v_rowsum_acc_f32_1);
+ HVX_Vector v_l_curr0 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v0, exp_m_diff0), factx->vtcm_p_rowsum[r_vec_idx * 2 + 0]);
+ HVX_Vector v_l_curr1 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v1, exp_m_diff1), factx->vtcm_p_rowsum[r_vec_idx * 2 + 1]);
factx->vtcm_m_vec[r_vec_idx * 2 + 0] = v_m_curr0;
factx->vtcm_m_vec[r_vec_idx * 2 + 1] = v_m_curr1;
factx->vtcm_l_vec[r_vec_idx * 2 + 0] = v_l_curr0;
factx->vtcm_l_vec[r_vec_idx * 2 + 1] = v_l_curr1;
- // Build diagonal tile D = diag(exp(m_diff))
- const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets;
- const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16));
- HVX_Vector v_exp_m_diff = exp_m_diff_f16;
-
- __fp16 * const d_tiles_out = factx->vtcm_d_tiles[args->buf_idx];
-
- size_t t0 = r_vec_idx * 2;
- if (t0 < args->n_row_tiles) {
- const HVX_Vector v_content = v_exp_m_diff;
- __fp16 * out_base = d_tiles_out + t0 * HMX_FP16_TILE_N_ELMS;
- Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content);
- }
-
- size_t t1 = r_vec_idx * 2 + 1;
- if (t1 < args->n_row_tiles) {
- const HVX_Vector v_content = Q6_V_vror_VR(v_exp_m_diff, 64);
- __fp16 * out_base = d_tiles_out + t1 * HMX_FP16_TILE_N_ELMS;
- Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content);
- }
+ HVX_Vector * exp_mdiff_out = (HVX_Vector *) (factx->vtcm_exp_mdiff[args->buf_idx] + r_vec_idx * 64);
+ exp_mdiff_out[0] = exp_m_diff0;
+ exp_mdiff_out[1] = exp_m_diff1;
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, (uint16_t) (args->q_start * G + vec_start * 64));
}
-static void fa_softmax_thread_nomask(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
- fa_softmax_impl(th, n, i, data,
- /*has_mask=*/false,
- /*mask_broadcast=*/false,
- /*is_g1=*/false,
- /*has_alibi=*/false,
- /*has_softcap=*/false);
+static void fa_w8a8_softmax_thread_nomask(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_w8a8_softmax_impl(th, n, i, data, false, false, false, false, false);
}
-static void fa_softmax_thread_mask_broadcast_g1(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
- fa_softmax_impl(th, n, i, data,
- /*has_mask=*/true,
- /*mask_broadcast=*/true,
- /*is_g1=*/true,
- /*has_alibi=*/false,
- /*has_softcap=*/false);
+static void fa_w8a8_softmax_thread_mask_broadcast_g1(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_w8a8_softmax_impl(th, n, i, data, true, true, true, false, false);
}
-static void fa_softmax_thread_mask_broadcast_gn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
- fa_softmax_impl(th, n, i, data,
- /*has_mask=*/true,
- /*mask_broadcast=*/true,
- /*is_g1=*/false,
- /*has_alibi=*/false,
- /*has_softcap=*/false);
+static void fa_w8a8_softmax_thread_mask_broadcast_gn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_w8a8_softmax_impl(th, n, i, data, true, true, false, false, false);
}
-static void fa_softmax_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+static void fa_w8a8_softmax_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
fa_softmax_args_t * args = (fa_softmax_args_t *) data;
struct hmx_fa_context * factx = args->factx;
+ fa_w8a8_softmax_impl(th, n, i, data,
+ args->mask != NULL, factx->mask_broadcast, args->G == 1,
+ args->has_alibi, factx->has_softcap);
+}
- const bool has_mask = (args->mask != NULL);
- const bool mask_broadcast = factx->mask_broadcast;
- const bool is_g1 = (args->G == 1);
- const bool has_alibi = args->has_alibi;
- const bool has_softcap = factx->has_softcap;
+static void fa_phase_softmax_and_build_d(struct hmx_fa_context * factx,
+ fa_softmax_args_t * sargs,
+ size_t n_row_tiles,
+ size_t n_row_tiles_g_br) {
+ work_queue_t wp = factx->octx->ctx->hvx_queue;
+ const size_t n_row_vec_cnt = hmx_ceil_div(sargs->n_rows_g, 64);
- fa_softmax_impl(th, n, i, data, has_mask, mask_broadcast, is_g1, has_alibi, has_softcap);
+ work_queue_func_t softmax_fn;
+ if (factx->is_w8a8) {
+ softmax_fn = fa_w8a8_softmax_thread;
+ if (sargs->mask == NULL && !factx->has_softcap && !sargs->has_alibi) {
+ softmax_fn = fa_w8a8_softmax_thread_nomask;
+ } else if (sargs->mask != NULL && factx->mask_broadcast && !factx->has_softcap && !sargs->has_alibi) {
+ softmax_fn = (sargs->G == 1) ? fa_w8a8_softmax_thread_mask_broadcast_g1 : fa_w8a8_softmax_thread_mask_broadcast_gn;
+ }
+ } else {
+ softmax_fn = fa_softmax_thread;
+ if (sargs->mask == NULL && !factx->has_softcap && !sargs->has_alibi) {
+ softmax_fn = fa_softmax_thread_nomask;
+ } else if (sargs->mask != NULL && factx->mask_broadcast && !factx->has_softcap && !sargs->has_alibi) {
+ softmax_fn = (sargs->G == 1) ? fa_softmax_thread_mask_broadcast_g1 : fa_softmax_thread_mask_broadcast_gn;
+ }
+ }
+
+ uint32_t n_use = 1;
+ if (factx->n_hvx > 1 && n_row_vec_cnt >= 2) {
+ n_use = (uint32_t) hex_smin((size_t) factx->n_hvx, n_row_vec_cnt);
+ sargs->thread_div = init_fastdiv_values(n_use);
+ }
+ work_queue_run(wp, softmax_fn, sargs, n_use);
}
-static inline HVX_Vector hvx_fa_load_sinks(const float * sinks_data, size_t idx, size_t count) {
- const HVX_Vector * v_src = (const HVX_Vector *) sinks_data + (idx >> 5);
- const size_t lane_off = idx & 31;
- const size_t byte_off = lane_off * sizeof(float);
- return (lane_off + count > 32)
- ? Q6_V_valign_VVR(v_src[1], v_src[0], byte_off)
- : Q6_V_vror_VR(v_src[0], byte_off);
+typedef struct {
+ struct hmx_fa_context * factx;
+ size_t buf_idx;
+ size_t n_rows_g;
+ uint32_t q_start;
+ bool is_first;
+} fa_w8a8_o_accum_args_t;
+
+static __attribute__((noinline)) void fa_w8a8_o_accum_quad_first(
+ const uint8_t * restrict tile_base,
+ const float * restrict dv_scales,
+ float * restrict o0,
+ float * restrict o1,
+ float * restrict o2,
+ float * restrict o3,
+ size_t DV,
+ uint32_t dp0,
+ uint32_t dp1,
+ uint32_t dp2,
+ uint32_t dp3) {
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80);
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < DV; c += 32) {
+ HVX_Vector do0, do1, do2, do3;
+ hmx_fa_w8a8_eval_s_tile_quad(tile_base, dv_scales, c, dp0, dp1, dp2, dp3, sign_80,
+ &do0, &do1, &do2, &do3);
+ *(HVX_Vector *) (o0 + c) = do0;
+ *(HVX_Vector *) (o1 + c) = do1;
+ *(HVX_Vector *) (o2 + c) = do2;
+ *(HVX_Vector *) (o3 + c) = do3;
+ }
}
-static __attribute__((noinline)) void fa_build_d_diag_inv_l(struct hmx_fa_context * factx,
- size_t n_row_tiles,
- size_t n_row_tiles_g_br,
- uint32_t kv_head,
- size_t n_rows_g) {
- (void) n_row_tiles_g_br;
+static __attribute__((noinline)) void fa_w8a8_o_accum_quad_update(
+ const uint8_t * restrict tile_base,
+ const float * restrict dv_scales,
+ float * restrict o0,
+ float * restrict o1,
+ float * restrict o2,
+ float * restrict o3,
+ size_t DV,
+ uint32_t dp0,
+ uint32_t dp1,
+ uint32_t dp2,
+ uint32_t dp3,
+ uint32_t em0,
+ uint32_t em1,
+ uint32_t em2,
+ uint32_t em3) {
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80);
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (size_t c = 0; c < DV; c += 32) {
+ HVX_Vector do0, do1, do2, do3;
+ hmx_fa_w8a8_eval_s_tile_quad(tile_base, dv_scales, c, dp0, dp1, dp2, dp3, sign_80,
+ &do0, &do1, &do2, &do3);
+ *(HVX_Vector *) (o0 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o0 + c), em0), do0));
+ *(HVX_Vector *) (o1 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o1 + c), em1), do1));
+ *(HVX_Vector *) (o2 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o2 + c), em2), do2));
+ *(HVX_Vector *) (o3 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o3 + c), em3), do3));
+ }
+}
- // sinks: l += exp(sink - m * ln2) in f32, m and l are in the log2 domain
- if (factx->sinks) {
- const float * sinks_data = factx->vtcm_sinks;
- const size_t G = factx->G;
- const size_t head_base = (size_t) kv_head * G;
- const HVX_Vector v_ln2 = Q6_V_vsplat_R(EXP_LOGN2);
- const HVX_Vector v_head_sinks = (G <= 32) ? hvx_fa_load_sinks(sinks_data, head_base, G) : Q6_V_vzero();
- HVX_Vector v_sink = Q6_V_vzero();
- size_t g_prev = SIZE_MAX;
+static void fa_w8a8_o_accum_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_w8a8_o_accum_args_t * args = (fa_w8a8_o_accum_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
- for (size_t i = 0; i < n_row_tiles; ++i) {
- // the sink pattern of a tile only depends on (i * 32) % G, rebuild it when that changes
- const size_t r0 = i * 32;
- const size_t g0 = fastmodulo(r0, G, &factx->div_G);
- if (g0 != g_prev) {
+ const size_t n_rows_g = args->n_rows_g;
+ const size_t n_quads = hmx_ceil_div(n_rows_g, 4);
+ const size_t quads_per_t = hmx_ceil_div(n_quads, n);
+ const size_t q_start_idx = (size_t) i * quads_per_t;
+ const size_t q_end_idx = hex_smin(q_start_idx + quads_per_t, n_quads);
+
+ if (q_start_idx >= n_quads) {
+ return;
+ }
+
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * factx->G + q_start_idx * 4));
+
+ const size_t DV = factx->DV;
+ const size_t n_v_tiles = DV / HMX_W8A8_TILE_N_COLS;
+ const uint8_t * do_tiles = factx->vtcm_do_tiles;
+ const float * dv_scales = factx->vtcm_v_scales[args->buf_idx];
+ const float * p_scales = factx->vtcm_p_scales[args->buf_idx];
+ const float * exp_mdiff = factx->vtcm_exp_mdiff[args->buf_idx];
+ float * o_f32 = factx->vtcm_o_f32;
+ const bool is_first = args->is_first;
+
+ for (size_t quad = q_start_idx; quad < q_end_idx; ++quad) {
+ const size_t r = quad * 4;
+ const size_t r_vec_idx = r >> 6;
+ const size_t r_tile = r >> 5;
+ const uint32_t r_vec_off = (uint32_t) (r & 63);
+ const uint32_t rg = r_vec_off >> 2;
+ const int off = (int) ((r & 31u) * 4u);
+
+ const HVX_Vector v_dp = hvx_vmem(p_scales + r_tile * 32);
+ const uint32_t dp0 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 0);
+ const uint32_t dp1 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 4);
+ const uint32_t dp2 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 8);
+ const uint32_t dp3 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 12);
+
+ const uint8_t * tile_base = do_tiles + r_vec_idx * n_v_tiles * 2 * HMX_W8A8_ACT_TILE_SIZE + (size_t) rg * 128;
+ float * o0 = o_f32 + (r + 0) * DV;
+ float * o1 = o_f32 + (r + 1) * DV;
+ float * o2 = o_f32 + (r + 2) * DV;
+ float * o3 = o_f32 + (r + 3) * DV;
+
+ if (is_first) {
+ fa_w8a8_o_accum_quad_first(tile_base, dv_scales, o0, o1, o2, o3, DV, dp0, dp1, dp2, dp3);
+ } else {
+ const HVX_Vector v_em = hvx_vmem(exp_mdiff + r_tile * 32);
+ const uint32_t em0 = (uint32_t) Q6_R_vextract_VR(v_em, off + 0);
+ const uint32_t em1 = (uint32_t) Q6_R_vextract_VR(v_em, off + 4);
+ const uint32_t em2 = (uint32_t) Q6_R_vextract_VR(v_em, off + 8);
+ const uint32_t em3 = (uint32_t) Q6_R_vextract_VR(v_em, off + 12);
+ fa_w8a8_o_accum_quad_update(tile_base, dv_scales, o0, o1, o2, o3, DV, dp0, dp1, dp2, dp3, em0, em1, em2, em3);
+ }
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * factx->G + q_start_idx * 4));
+}
+
+static void fa_phase_w8a8_o_accum(struct hmx_fa_context * factx,
+ size_t buf_idx,
+ size_t n_rows_g,
+ uint32_t q_start,
+ bool is_first) {
+ work_queue_t wp = factx->octx->ctx->hvx_queue;
+ const size_t n_q = hmx_ceil_div(n_rows_g, 4);
+ const uint32_t n = (uint32_t) hex_smin((size_t) factx->n_hvx, n_q);
+ fa_w8a8_o_accum_args_t args = { factx, buf_idx, n_rows_g, q_start, is_first };
+ work_queue_run(wp, fa_w8a8_o_accum_thread, &args, n);
+}
+
+static void fa_w8a8_o_store_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ fa_o_store_args_t * args = (fa_o_store_args_t *) data;
+ struct hmx_fa_context * factx = args->factx;
+
+ const size_t n_rows = args->n_rows;
+ const size_t rows_per_t = args->rows_per_t;
+ const size_t start = (size_t) i * rows_per_t;
+ const size_t end = hex_smin(start + rows_per_t, n_rows);
+
+ if (start >= n_rows) {
+ return;
+ }
+
+ const size_t G = factx->G;
+ const size_t DV = factx->DV;
+
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start));
+
+ const uint32_t kv_head = args->kv_head;
+ float * o_f32 = factx->vtcm_o_f32;
+ const bool has_sinks = (factx->sinks != NULL);
+ const bool is_f32 = factx->is_dst_fp32;
+ const size_t head_base = (size_t) kv_head * G;
+ const HVX_Vector v_ln2 = Q6_V_vsplat_R(EXP_LOGN2);
+ const HVX_Vector v_one = hvx_vec_splat_f32(1.0f);
+ const HVX_Vector v_head_sinks = (has_sinks && G <= 32) ? hvx_fa_load_sinks(factx->vtcm_sinks, head_base, G) : Q6_V_vzero();
+
+ size_t prev_r_tile = SIZE_MAX;
+ HVX_Vector v_sc = Q6_V_vzero();
+
+ for (size_t r = start; r < end; ++r) {
+ const size_t r_tile = r >> 5;
+ if (r_tile != prev_r_tile) {
+ HVX_Vector v_l = factx->vtcm_l_vec[r_tile];
+ if (has_sinks) {
+ const size_t g0 = fastmodulo(r_tile * 32, G, &factx->div_G);
const size_t rem_g = G - g0;
+ HVX_Vector v_sink;
if (G <= 32) {
const HVX_Vector v_lo = Q6_V_vror_VR(v_head_sinks, g0 * sizeof(float));
const HVX_Vector v_hi = Q6_V_vror_VR(v_head_sinks, 128 - rem_g * sizeof(float));
@@ -1685,67 +2986,74 @@ static __attribute__((noinline)) void fa_build_d_diag_inv_l(struct hmx_fa_contex
v_sink = Q6_V_vmux_QVV(q_keep, v_sink, v_shifted);
}
} else if (rem_g >= 32) {
- v_sink = hvx_fa_load_sinks(sinks_data, head_base + g0, 32);
+ v_sink = hvx_fa_load_sinks(factx->vtcm_sinks, head_base + g0, 32);
} else {
- const HVX_Vector v_lo = hvx_fa_load_sinks(sinks_data, head_base + g0, rem_g);
- const HVX_Vector v_hi = hvx_fa_load_sinks(sinks_data, head_base, 32 - rem_g);
+ const HVX_Vector v_lo = hvx_fa_load_sinks(factx->vtcm_sinks, head_base + g0, rem_g);
+ const HVX_Vector v_hi = hvx_fa_load_sinks(factx->vtcm_sinks, head_base, 32 - rem_g);
v_sink = Q6_V_vmux_QVV(Q6_Q_vsetq_R(rem_g * sizeof(float)), v_lo, Q6_V_vror_VR(v_hi, 128 - rem_g * sizeof(float)));
}
- g_prev = g0;
- }
- HVX_Vector v_d = HVX_OP_SUB_F32(v_sink, HVX_OP_MUL_F32(factx->vtcm_m_vec[i], v_ln2));
- if (r0 + 32 > n_rows_g) {
- const HVX_VectorPred q_valid = Q6_Q_vsetq_R((n_rows_g - r0) * sizeof(float));
- v_d = Q6_V_vmux_QVV(q_valid, v_d, Q6_V_vzero());
+ HVX_Vector v_me = HVX_OP_MUL_F32(factx->vtcm_m_vec[r_tile], v_ln2);
+ HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VsfVsf(v_sink, v_me);
+ HVX_Vector v_diff = Q6_V_vmux_QVV(q_gt, HVX_OP_SUB_F32(v_me, v_sink), HVX_OP_SUB_F32(v_sink, v_me));
+ HVX_Vector v_exp = hvx_vec_exp_f32(v_diff);
+ HVX_Vector v_l_new = Q6_V_vmux_QVV(q_gt, HVX_OP_ADD_F32(HVX_OP_MUL_F32(v_l, v_exp), v_one), HVX_OP_ADD_F32(v_l, v_exp));
+ HVX_Vector v_num = Q6_V_vmux_QVV(q_gt, v_exp, v_one);
+ HVX_VectorPred q_nz = Q6_Q_vcmp_gt_VsfVsf(v_l_new, Q6_V_vzero());
+ v_sc = Q6_V_vmux_QVV(q_nz, HVX_OP_MUL_F32(v_num, hvx_vec_inverse_f32(v_l_new)), Q6_V_vzero());
+ } else {
+ HVX_VectorPred q_nz = Q6_Q_vcmp_gt_VsfVsf(v_l, Q6_V_vzero());
+ v_sc = Q6_V_vmux_QVV(q_nz, hvx_vec_inverse_f32(v_l), Q6_V_vzero());
}
- factx->vtcm_l_vec[i] = HVX_OP_ADD_F32(factx->vtcm_l_vec[i], hvx_vec_exp_f32(v_d));
+ prev_r_tile = r_tile;
}
- }
- const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets;
- const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16));
- const HVX_Vector one = hvx_vec_splat_f32(1.0f);
+ const uint32_t sc_bits = (uint32_t) Q6_R_vextract_VR(v_sc, (int) ((r & 31u) * 4u));
+ float * o_row = o_f32 + r * DV;
- HVX_Vector v_content = Q6_V_vzero();
- for (size_t i = 0; i < n_row_tiles; ++i) {
- if ((i % 2) == 0) {
- HVX_Vector inv_lo = HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i]));
- HVX_Vector inv_hi = (i + 1 < n_row_tiles) ? HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i + 1])) : Q6_V_vzero();
- v_content = hvx_vec_f32_to_f16(inv_lo, inv_hi);
+ // Normalize in-place in VTCM; caller writes out via bypass DMA.
+ if (is_f32) {
+ for (size_t c = 0; c < DV; c += 32) {
+ *(HVX_Vector *) (o_row + c) = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c), sc_bits));
+ }
} else {
- v_content = Q6_V_vror_VR(v_content, 64);
+ __fp16 * out = (__fp16 *) o_row;
+ size_t c = 0;
+ for (; c + 64 <= DV; c += 64) {
+ HVX_Vector v0 = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c + 0), sc_bits));
+ HVX_Vector v1 = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c + 32), sc_bits));
+ *(HVX_Vector *) (out + c) = hvx_vec_f32_to_f16(v0, v1);
+ }
+ if (c < DV) {
+ HVX_Vector v0 = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c), sc_bits));
+ hvx_vec_store_a(out + c, 32 * sizeof(__fp16), hvx_vec_f32_to_f16(v0, Q6_V_vzero()));
+ }
}
-
- __fp16 * out_base = factx->vtcm_d_inv_l + i * HMX_FP16_TILE_N_ELMS;
- Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content);
}
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start));
}
-static void fa_phase_softmax_and_build_d(struct hmx_fa_context * factx,
- fa_softmax_args_t * sargs,
- size_t n_row_tiles,
- size_t n_row_tiles_g_br) {
+static void fa_phase_w8a8_o_store(struct hmx_fa_context * factx,
+ dma_queue * dma_q,
+ const struct htp_tensor * dst,
+ uint32_t q_start,
+ uint32_t kv_head,
+ uint32_t ib3,
+ size_t n_rows_g) {
work_queue_t wp = factx->octx->ctx->hvx_queue;
- const size_t n_row_vec_cnt = hmx_ceil_div(sargs->n_rows_g, 64);
-
- work_queue_func_t softmax_fn = fa_softmax_thread;
- if (sargs->mask == NULL && !factx->has_softcap && !sargs->has_alibi) {
- softmax_fn = fa_softmax_thread_nomask;
- } else if (sargs->mask != NULL && factx->mask_broadcast && !factx->has_softcap && !sargs->has_alibi) {
- if (sargs->G == 1) {
- softmax_fn = fa_softmax_thread_mask_broadcast_g1;
- } else {
- softmax_fn = fa_softmax_thread_mask_broadcast_gn;
- }
- }
-
- uint32_t n_use = 1;
- if (factx->n_hvx > 1 && n_row_vec_cnt >= 2) {
- n_use = (uint32_t) hex_smin((size_t) factx->n_hvx, n_row_vec_cnt);
- sargs->thread_div = init_fastdiv_values(n_use);
+ uint32_t n = 1;
+ if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * 2)) {
+ n = factx->n_hvx;
}
- work_queue_run(wp, softmax_fn, sargs, n_use);
+ const size_t rows_per_t = hmx_ceil_div(n_rows_g, n);
+ fa_o_store_args_t args = { factx, (uint8_t *) factx->vtcm_o_f32, NULL, q_start, kv_head, 0, n_rows_g, rows_per_t };
+ work_queue_run(wp, fa_w8a8_o_store_thread, &args, n);
+
+ const size_t vtcm_row_stride = factx->DV * sizeof(float);
+ const size_t row_bytes = factx->DV * (factx->is_dst_fp32 ? sizeof(float) : sizeof(__fp16));
+ fa_push_o_dma(dma_q, dst, (const uint8_t *) factx->vtcm_o_f32, vtcm_row_stride, row_bytes,
+ q_start, kv_head, ib3, factx->G, &factx->div_G, 0, n_rows_g);
}
// ============================================================================
@@ -1919,6 +3227,45 @@ static __attribute__((noinline)) void fa_compute_slopes(
hvx_copy_f16_aa((uint8_t *)slopes, (const uint8_t *)temp_slopes, n_rows_g);
}
+static inline void fa_push_q_dma(dma_queue * dma_q,
+ const struct htp_tensor * q,
+ void * vtcm_q_dma,
+ uint32_t q_start,
+ uint32_t kv_head,
+ uint32_t ib3,
+ uint32_t G,
+ uint32_t n_rows_q,
+ size_t q_elem_row_bytes,
+ bool q_transposed) {
+ const dma_addr_t q_ptr = q->data + q_start * q->nb[1] + (kv_head * G) * q->nb[2] + ib3 * q->nb[3];
+ const size_t q_inner_nb = q_transposed ? q->nb[1] : q->nb[2];
+ const size_t q_outer_nb = q_transposed ? q->nb[2] : q->nb[1];
+ const size_t n_inner = q_transposed ? n_rows_q : G;
+ const size_t n_outer = q_transposed ? G : n_rows_q;
+
+ if (__builtin_expect(q_inner_nb == q_elem_row_bytes, true)) {
+ const size_t row_bytes = n_inner * q_elem_row_bytes;
+ dma_queue_push(dma_q, dma_make_data(vtcm_q_dma, q_ptr), row_bytes, hex_smax(q_outer_nb, row_bytes), row_bytes, n_outer);
+ return;
+ }
+
+ // Non-contiguous inner dim: one 2D DMA per outer slice, keeping dma_q depth at 2 (prev O + Q).
+ uint8_t * dst_ptr = (uint8_t *) vtcm_q_dma;
+ const size_t dst_outer_stride = n_inner * q_elem_row_bytes;
+ const size_t src_inner_stride = hex_smax(q_inner_nb, q_elem_row_bytes);
+ for (size_t o = 0; o < n_outer; ++o) {
+ if (!dma_queue_push(dma_q, dma_make_data(dst_ptr + o * dst_outer_stride, q_ptr + o * q_outer_nb),
+ q_elem_row_bytes, src_inner_stride, q_elem_row_bytes, n_inner)) {
+ dma_queue_pop(dma_q);
+ dma_queue_push(dma_q, dma_make_data(dst_ptr + o * dst_outer_stride, q_ptr + o * q_outer_nb),
+ q_elem_row_bytes, src_inner_stride, q_elem_row_bytes, n_inner);
+ }
+ }
+ while (dma_queue_depth(dma_q) > 2) {
+ dma_queue_pop(dma_q);
+ }
+}
+
static void fa_push_mask_dma_gqa(
dma_queue * dma_q,
const struct htp_tensor * mask,
@@ -1993,7 +3340,6 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
const uint32_t neq2 = q->ne[2]; // n_heads
const uint32_t neq3 = q->ne[3]; // n_seqs
- const uint32_t nek0 = k->ne[0]; // head_dim
const uint32_t nek1 = k->ne[1]; // kv_len
const uint32_t nev0 = v->ne[0]; // head_dim (DV)
@@ -2037,6 +3383,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
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.is_w8a8 = (kparams->kernel_type == HTP_FA_KERNEL_HMX_W8A8);
factx.mask_broadcast = (kparams->u.hmx.mask_broadcast != 0);
if (mask) {
factx.src3_div2 = kparams->src3_div2;
@@ -2045,6 +3392,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
factx.has_softcap = (kparams->logit_softcap != 0.0f);
factx.scale = (__fp16) kparams->scale;
+ factx.scale_f32 = kparams->scale;
factx.max_bias = kparams->max_bias;
factx.logit_softcap = 0;
if (factx.has_softcap) {
@@ -2073,10 +3421,8 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
if (octx->ctx->mdev.count > 1) {
const uint32_t mdev_count = octx->ctx->mdev.count;
const uint32_t mdev_idx = octx->ctx->mdev.idx;
- const uint32_t dst_e_size = (dst->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(__fp16);
- const bool can_split = htp_tensor_can_row_partition(dst, dst_e_size);
- if ((kparams->flags & HTP_FA_FLAG_TEAM_SPLIT) && can_split) {
+ 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);
@@ -2098,12 +3444,12 @@ 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 && can_split && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
+ } else if (kparams->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;
} else {
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_q_blocks, can_split ? 1 : 0, mdev_idx, mdev_count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_q_blocks, 1, mdev_idx, mdev_count, &octx->ctx->mdev.count_div);
const uint32_t block_start = range.start;
const uint32_t block_end = range.start + range.count;
@@ -2121,26 +3467,41 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
// throughout the KV loop below. The DMA copies only the real DK/DV columns; the
// staging rows are padded to hold DK_pad/DV_pad columns (tail zero-filled below)
// so the HMX interleave/tile logic can operate on 64-aligned head dims.
- const size_t size_k_row = htp_tensor_get_row_size(k->type, DK);
- const size_t size_v_row = htp_tensor_get_row_size(v->type, DV);
- const size_t size_k_row_padded = hex_round_up(DK_pad * sizeof(__fp16), 128);
- const size_t size_v_row_padded = hex_round_up(DV_pad * sizeof(__fp16), 128);
-
// Build the VTCM layout once (shared with the host estimator) and place every
// scratch buffer at its computed offset. Padded head dims size the HMX tiles.
+ const struct hmx_fa_layout_params lp = {
+ .kernel_type = kparams->kernel_type,
+ .q_type = q->type,
+ .gqa_factor = G,
+ .DK = DK_pad,
+ .DV = DV_pad,
+ .Br = Br,
+ .Bc = Bc,
+ .n_hvx = n_hvx,
+ .n_heads = factx.n_heads,
+ .pipeline = pipeline,
+ .has_mask = mask != NULL,
+ .mask_broadcast = factx.mask_broadcast,
+ .has_sinks = factx.sinks != NULL,
+ };
struct hmx_fa_vtcm_layout L;
- hmx_fa_vtcm_layout_build(&L, G, DK_pad, DV_pad, Br, Bc, n_hvx, pipeline, factx.is_q_fp32, factx.sinks != NULL, factx.n_heads);
+ hmx_fa_vtcm_layout_build(&L, &lp);
if (L.total_bytes > ctx->vtcm_size) {
return HTP_STATUS_VTCM_TOO_SMALL;
}
+ const size_t size_k_row = htp_tensor_get_row_size(k->type, DK);
+ const size_t size_v_row = htp_tensor_get_row_size(v->type, DV);
+ const size_t size_k_row_padded = factx.is_w8a8 ? L.k_raw_row_padded : hex_round_up(DK_pad * sizeof(__fp16), 128);
+ const size_t size_v_row_padded = factx.is_w8a8 ? L.v_raw_row_padded : hex_round_up(DV_pad * sizeof(__fp16), 128);
+
uint8_t * const base = ctx->vtcm_base;
factx.vtcm_q_dma = VTCM_LAYOUT_PTR(__fp16, base, L.off_q_dma);
factx.vtcm_q_tiles = VTCM_LAYOUT_PTR(__fp16, base, L.off_q_tiles);
- factx.vtcm_o_tiles[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_o_tiles[0]);
- factx.vtcm_o_tiles[1] = VTCM_LAYOUT_PTR(__fp16, base, L.off_o_tiles[1]);
+ factx.vtcm_o_tiles[0] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_o_tiles[0], !factx.is_w8a8);
+ factx.vtcm_o_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_o_tiles[1], !factx.is_w8a8);
factx.vtcm_k_fp16[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_k_fp16[0]);
factx.vtcm_k_fp16[1] = VTCM_LAYOUT_PTR(__fp16, base, L.off_k_fp16[1]);
factx.vtcm_v_fp16[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_v_fp16[0]);
@@ -2153,9 +3514,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
factx.vtcm_s_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_s_tiles[1], pipeline);
factx.vtcm_p_tiles[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_p_tiles[0]);
factx.vtcm_p_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_p_tiles[1], pipeline);
- factx.vtcm_d_tiles[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_d_tiles[0]);
- factx.vtcm_d_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_tiles[1], pipeline);
- factx.vtcm_d_inv_l = VTCM_LAYOUT_PTR(__fp16, base, L.off_d_inv_l);
+ factx.vtcm_d_tiles[0] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_tiles[0], !factx.is_w8a8);
+ factx.vtcm_d_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_tiles[1], !factx.is_w8a8 && pipeline);
+ factx.vtcm_d_inv_l = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_inv_l, !factx.is_w8a8);
factx.vtcm_m_vec = VTCM_LAYOUT_PTR(HVX_Vector, base, L.off_m_vec);
factx.vtcm_l_vec = VTCM_LAYOUT_PTR(HVX_Vector, base, L.off_l_vec);
factx.vtcm_s_rowmax = VTCM_LAYOUT_PTR(HVX_Vector, base, L.off_s_rowmax);
@@ -2164,15 +3525,33 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
factx.row_buf_stride = L.row_buf_stride;
factx.vtcm_hmx_scales_id = VTCM_LAYOUT_PTR(uint8_t, base, L.off_hmx_scales_id);
factx.vtcm_hmx_scales_qk = VTCM_LAYOUT_PTR(uint8_t, base, L.off_hmx_scales_qk);
- factx.vtcm_mask_buf = VTCM_LAYOUT_PTR(__fp16, base, L.off_mask_buf);
+ factx.vtcm_mask_buf = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_mask_buf, mask != NULL);
factx.mask_buf_row_stride = L.mask_buf_row_stride;
factx.q_tile_bytes = L.q_tile_bytes;
factx.k_tile_bytes = L.k_tile_bytes;
factx.o_tile_bytes = L.o_tile_bytes;
factx.col_vec_bytes = L.col_vec_bytes;
factx.d_tile_bytes = L.d_tile_bytes;
+ factx.o_f32_bytes = L.o_f32_bytes;
factx.vtcm_slopes = VTCM_LAYOUT_PTR(__fp16, base, L.off_slopes);
factx.vtcm_sinks = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_sinks, factx.sinks != NULL);
+ factx.vtcm_q_scales = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_q_scales, factx.is_w8a8);
+ factx.vtcm_k_scales[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_k_scales[0], factx.is_w8a8);
+ factx.vtcm_k_scales[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_k_scales[1], factx.is_w8a8 && pipeline);
+ factx.vtcm_k_bias[0] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_k_bias[0], factx.is_w8a8);
+ factx.vtcm_k_bias[1] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_k_bias[1], factx.is_w8a8 && pipeline);
+ factx.vtcm_o_f32 = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_o_f32, factx.is_w8a8);
+ factx.vtcm_do_tiles = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_do_tiles, factx.is_w8a8);
+ factx.vtcm_v_scales[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_v_scales[0], factx.is_w8a8);
+ factx.vtcm_v_scales[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_v_scales[1], factx.is_w8a8 && pipeline);
+ factx.vtcm_v_bias[0] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_v_bias[0], factx.is_w8a8);
+ factx.vtcm_v_bias[1] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_v_bias[1], factx.is_w8a8 && pipeline);
+ factx.vtcm_p_scales[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_p_scales[0], factx.is_w8a8);
+ factx.vtcm_p_scales[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_p_scales[1], factx.is_w8a8 && pipeline);
+ factx.vtcm_exp_mdiff[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_exp_mdiff[0], factx.is_w8a8);
+ factx.vtcm_exp_mdiff[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_exp_mdiff[1], factx.is_w8a8 && pipeline);
+ factx.k_raw_row_padded = L.k_raw_row_padded;
+ factx.v_raw_row_padded = L.v_raw_row_padded;
const size_t m_line_bytes = L.m_line_bytes; // used by the mask DMAs in the KV loop
@@ -2183,7 +3562,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
factx.ddr_slopes = ddr->slopes;
factx.m_cache = &octx->dma_cache_fa[0];
- dma_cache_fa_init(factx.m_cache, (uint8_t *) factx.vtcm_mask_buf, L.m_buf_slot_bytes, HMX_FA_DMA_CACHE_SIZE);
+ if (mask && factx.mask_broadcast) {
+ dma_cache_fa_init(factx.m_cache, (uint8_t *) factx.vtcm_mask_buf, L.m_buf_slot_bytes, HMX_FA_DMA_CACHE_SIZE);
+ }
// Head-dim padding: the K/V DMA staging buffers and the flat-Q buffer are laid out
// with padded row strides (size_{k,v,q}_row_padded, covering D_pad columns) but the
@@ -2197,10 +3578,8 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
hvx_splat_u8_a((char *) factx.vtcm_v_fp16[0], 0, v_buf_bytes);
hvx_splat_u8_a((char *) factx.vtcm_v_fp16[1], 0, v_buf_bytes);
// Flat-Q DMA scratch
- if (factx.vtcm_q_dma) {
- const size_t q_dma_bytes = hex_align_up(factx.g_br * DK * (factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16)), 128);
- hvx_splat_u8_a((char *) factx.vtcm_q_dma, 0, q_dma_bytes);
- }
+ const size_t q_dma_bytes = hex_align_up(factx.g_br * DK * (factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16)), 128);
+ hvx_splat_u8_a((char *) factx.vtcm_q_dma, 0, q_dma_bytes);
}
// ======== Initialize HMX output scales ========
@@ -2221,15 +3600,14 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
const size_t n_row_tiles_g_br = g_br / HMX_FP16_TILE_N_ROWS;
const size_t n_tiles_per_bc = Bc / HMX_FP16_TILE_N_COLS;
- const size_t qo_element_size = factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16);
-
- const bool q_transposed = q->nb[1] < q->nb[2];
- const size_t q_src_stride = q_transposed ? q->nb[2] : q->nb[1];
- const size_t q_row_bytes_untransposed = factx.G * factx.DK * qo_element_size;
- const size_t q_row_bytes_trans_factor = factx.DK * qo_element_size;
+ const size_t qo_element_size = factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16);
+ const bool q_transposed = q->nb[1] < q->nb[2];
+ const size_t q_elem_row_bytes = factx.DK * qo_element_size;
// ======== Reusable job descriptors for pipeline ========
hmx_fa_qk_job_t qk_job;
+ hmx_fa_w8a8_qk_job_t w8a8_qk_job;
+ hmx_fa_w8a8_pv_job_t w8a8_pv_job;
hmx_fa_o_update_job_t ou_job;
hmx_fa_o_norm_job_t on_job;
@@ -2237,10 +3615,11 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
for (uint32_t ib3 = 0; ib3 < neq3; ++ib3) {
const uint32_t im3 = mask ? fastmodulo(ib3, mask->ne[3], &factx.src3_div3) : 0;
for (uint32_t q_start = q_start_min; q_start < q_start_max; q_start += Br) {
- const uint32_t n_rows_q = hex_smin(Br, neq1 - q_start);
- const size_t n_rows_g = n_rows_q * G;
- const size_t g_br_actual = hex_align_up(n_rows_g, HMX_FP16_TILE_N_ROWS);
- const size_t n_row_tiles = g_br_actual / HMX_FP16_TILE_N_ROWS;
+ const uint32_t n_rows_q = hex_smin(Br, neq1 - q_start);
+ const size_t n_rows_g = n_rows_q * G;
+ const size_t g_br_actual = hex_align_up(n_rows_g, HMX_FP16_TILE_N_ROWS);
+ const size_t n_row_tiles = g_br_actual / HMX_FP16_TILE_N_ROWS;
+ const uint32_t n_row_tiles_64 = (uint32_t) hmx_ceil_div(n_rows_g, HMX_W8A8_ACT_TILE_N_ROWS);
uint16_t * active_blocks = ddr->active_blocks;
uint32_t n_active_blocks = factx.n_kv_blocks;
@@ -2259,6 +3638,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
const uint32_t b0_start = b0 * Bc;
const uint32_t b0_rows = hex_smin(Bc, nek1 - b0_start);
+ // Dummy O writeback so every kv_head iteration pops prev O then curr Q unconditionally.
+ dma_queue_push(dma_q, dma_make_data(dst->data, factx.vtcm_o_tiles[0]), 0, 0, 0, 0);
+
for (uint32_t kv_head = kv_head_min; kv_head < kv_head_max; ++kv_head) {
const uint32_t ik2 = kv_head;
const uint32_t ik3 = fastdiv(ib3, &kparams->broadcast_rk3);
@@ -2268,11 +3650,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
// 1. Push Q and KV DMAs for the first kv_head of this q_start block.
// Subsequent kv_head iterations are enqueued early at the end of the previous iteration.
if (kv_head == kv_head_min) {
- const dma_addr_t q_ptr = q->data + q_start * q->nb[1] +
- (kv_head * factx.G) * q->nb[2] + ib3 * q->nb[3];
- const size_t q_row_bytes = q_transposed ? n_rows_q * q_row_bytes_trans_factor : q_row_bytes_untransposed;
- const size_t n_rows = q_transposed ? factx.G : n_rows_q;
- dma_queue_push(dma_q, dma_make_data(factx.vtcm_q_dma, q_ptr), q_row_bytes, hex_smax(q_src_stride, q_row_bytes), q_row_bytes, n_rows);
+ fa_push_q_dma(dma_q, q, factx.vtcm_q_dma, q_start, kv_head, ib3, factx.G, n_rows_q, q_elem_row_bytes, q_transposed);
if (n_active_blocks > 0) {
const dma_addr_t k_src = k->data + b0_start * k->nb[1] + ik2 * k->nb[2] + ik3 * k->nb[3];
@@ -2292,11 +3670,12 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
}
}
- // 2. Pop Q DMA (blocks until Q is loaded)
+ // 2. Pop previous kv_head's O writeback and current Q DMA.
+ dma_queue_pop(dma_q);
dma_queue_pop(dma_q);
// ---- Load Q block & Initialize per-block state ----
- fa_phase_q_load(&factx, q, q_start, kv_head, ib3, n_rows_g);
+ fa_phase_q_load(&factx, q, q_start, n_rows_g);
__fp16 * o_tile_prev = factx.vtcm_o_tiles[0];
__fp16 * o_tile_curr = factx.vtcm_o_tiles[1];
@@ -2316,6 +3695,8 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
if (factx.pipeline) {
// Double-buffered job structs because HMX queue runs asynchronously
hmx_fa_qk_job_t qk_job[2];
+ hmx_fa_w8a8_qk_job_t w8a8_qk_job[2];
+ hmx_fa_w8a8_pv_job_t w8a8_pv_job[2];
hmx_fa_o_update_job_t ou_job[2];
// Prefetch second active block early if there are multiple active blocks
@@ -2328,15 +3709,26 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
void * curr_k0 = (void *) dma_queue_pop(dma_q).dst;
fa_phase_k_interleave(&factx, b0_rows, k_src_stride, curr_k0, b0_start, 0);
- qk_job[0].q_tiles = factx.vtcm_q_tiles;
- qk_job[0].k_tiles = factx.vtcm_k_tiles[0];
- qk_job[0].s_tiles = factx.vtcm_s_tiles[0];
- qk_job[0].n_row_tiles = n_row_tiles;
- qk_job[0].n_col_tiles = hmx_ceil_div(b0_rows, HMX_FP16_TILE_N_COLS);
- qk_job[0].n_dot_tiles = DK_pad / 32;
- qk_job[0].n_tiles_per_bc = n_tiles_per_bc;
- qk_job[0].hmx_scales = factx.vtcm_hmx_scales_qk;
- hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[0]));
+ if (factx.is_w8a8) {
+ w8a8_qk_job[0].q_tiles = (const uint8_t *) factx.vtcm_q_tiles;
+ w8a8_qk_job[0].k_tiles = (const uint8_t *) factx.vtcm_k_tiles[0];
+ w8a8_qk_job[0].k_bias = factx.vtcm_k_bias[0];
+ w8a8_qk_job[0].s_tiles = (uint8_t *) factx.vtcm_s_tiles[0];
+ w8a8_qk_job[0].n_row_tiles_64 = n_row_tiles_64;
+ w8a8_qk_job[0].n_col_tiles = (uint32_t) hmx_ceil_div(b0_rows, HMX_W8A8_TILE_N_COLS);
+ w8a8_qk_job[0].n_dot_tiles = DK / 32;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_qk_dot_worker, &w8a8_qk_job[0]));
+ } else {
+ qk_job[0].q_tiles = factx.vtcm_q_tiles;
+ qk_job[0].k_tiles = factx.vtcm_k_tiles[0];
+ qk_job[0].s_tiles = factx.vtcm_s_tiles[0];
+ qk_job[0].n_row_tiles = n_row_tiles;
+ qk_job[0].n_col_tiles = hmx_ceil_div(b0_rows, HMX_FP16_TILE_N_COLS);
+ qk_job[0].n_dot_tiles = DK_pad / 32;
+ qk_job[0].n_tiles_per_bc = n_tiles_per_bc;
+ qk_job[0].hmx_scales = factx.vtcm_hmx_scales_qk;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[0]));
+ }
for (uint32_t step = 0; step < n_active_blocks; ++step) {
const uint32_t kv_blk = active_blocks[step];
@@ -2346,7 +3738,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
// ---- 1. Pop and run V-prep for current block ----
void * curr_v = (void *) dma_queue_pop(dma_q).dst;
- fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[buf_idx], n_tiles_per_bc, kv_start);
+ fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[buf_idx], n_tiles_per_bc, kv_start, buf_idx);
// ---- 2. Pop and run mask-prep for current block ----
__fp16 * current_mask_vtcm = NULL;
@@ -2359,28 +3751,36 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
}
}
- // ---- 3. Start HMX O update for step - 1 (reads P[1 - buf_idx], V[1 - buf_idx], D) ----
- // O update relies on the previous block's P and V tiles.
- // O update MUST be pushed before the next block's QK-dot: hmx_queue_pop() retires the
+ // ---- 3. Start HMX O update / PV for step - 1 (reads P[1 - buf_idx], V[1 - buf_idx]) ----
+ // MUST be pushed before the next block's QK-dot: hmx_queue_pop() retires the
// oldest descriptor, so push order alone decides which pop waits for which job.
- // If OU went in after QK(i+1), the pop below would retire QK(i+1) and leave
- // OU(i-1) in flight into the next iteration, where V-prep overwrites V[prev_buf].
if (step > 0) {
- const uint32_t prev_blk = active_blocks[step - 1];
- const size_t prev_buf = 1 - buf_idx;
- ou_job[prev_buf].o_curr = o_tile_curr;
- ou_job[prev_buf].o_prev = o_tile_prev;
- ou_job[prev_buf].p_tiles = factx.vtcm_p_tiles[prev_buf];
- ou_job[prev_buf].v_tiles = factx.vtcm_v_tiles[prev_buf];
- ou_job[prev_buf].d_tiles = factx.vtcm_d_tiles[prev_buf];
- ou_job[prev_buf].hmx_scales = factx.vtcm_hmx_scales_id;
- ou_job[prev_buf].n_row_tiles = n_row_tiles;
- ou_job[prev_buf].n_col_tiles =
- hmx_ceil_div(hex_smin(Bc, nek1 - prev_blk * Bc), HMX_FP16_TILE_N_COLS);
- ou_job[prev_buf].n_row_tiles_g_br = n_row_tiles_g_br;
- ou_job[prev_buf].n_tiles_per_bc = n_tiles_per_bc;
- ou_job[prev_buf].DV = DV_pad;
- hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[prev_buf]));
+ const uint32_t prev_blk = active_blocks[step - 1];
+ const size_t prev_buf = 1 - buf_idx;
+ const size_t prev_ct = hmx_ceil_div(hex_smin(Bc, nek1 - prev_blk * Bc), HMX_FP16_TILE_N_COLS);
+ if (factx.is_w8a8) {
+ w8a8_pv_job[prev_buf].p_tiles = (const uint8_t *) factx.vtcm_p_tiles[prev_buf];
+ w8a8_pv_job[prev_buf].v_tiles = (const uint8_t *) factx.vtcm_v_tiles[prev_buf];
+ w8a8_pv_job[prev_buf].v_bias = factx.vtcm_v_bias[prev_buf];
+ w8a8_pv_job[prev_buf].do_tiles = factx.vtcm_do_tiles;
+ w8a8_pv_job[prev_buf].n_row_tiles_64 = n_row_tiles_64;
+ w8a8_pv_job[prev_buf].n_v_tiles = DV / HMX_W8A8_TILE_N_COLS;
+ w8a8_pv_job[prev_buf].n_dot_tiles = (uint32_t) prev_ct;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_pv_worker, &w8a8_pv_job[prev_buf]));
+ } else {
+ ou_job[prev_buf].o_curr = o_tile_curr;
+ ou_job[prev_buf].o_prev = o_tile_prev;
+ ou_job[prev_buf].p_tiles = factx.vtcm_p_tiles[prev_buf];
+ ou_job[prev_buf].v_tiles = factx.vtcm_v_tiles[prev_buf];
+ ou_job[prev_buf].d_tiles = factx.vtcm_d_tiles[prev_buf];
+ ou_job[prev_buf].hmx_scales = factx.vtcm_hmx_scales_id;
+ ou_job[prev_buf].n_row_tiles = n_row_tiles;
+ ou_job[prev_buf].n_col_tiles = prev_ct;
+ ou_job[prev_buf].n_row_tiles_g_br = n_row_tiles_g_br;
+ ou_job[prev_buf].n_tiles_per_bc = n_tiles_per_bc;
+ ou_job[prev_buf].DV = DV_pad;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[prev_buf]));
+ }
}
// ---- 4. Pop and run K-prep for next active block & push next QK-dot ----
@@ -2393,15 +3793,26 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
void * next_k = (void *) dma_queue_pop(dma_q).dst;
fa_phase_k_interleave(&factx, next_rows, k_src_stride, next_k, next_start, next_buf);
- qk_job[next_buf].q_tiles = factx.vtcm_q_tiles;
- qk_job[next_buf].k_tiles = factx.vtcm_k_tiles[next_buf];
- qk_job[next_buf].s_tiles = factx.vtcm_s_tiles[next_buf];
- qk_job[next_buf].n_row_tiles = n_row_tiles;
- qk_job[next_buf].n_col_tiles = hmx_ceil_div(next_rows, HMX_FP16_TILE_N_COLS);
- qk_job[next_buf].n_dot_tiles = DK_pad / 32;
- qk_job[next_buf].n_tiles_per_bc = n_tiles_per_bc;
- qk_job[next_buf].hmx_scales = factx.vtcm_hmx_scales_qk;
- hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[next_buf]));
+ if (factx.is_w8a8) {
+ w8a8_qk_job[next_buf].q_tiles = (const uint8_t *) factx.vtcm_q_tiles;
+ w8a8_qk_job[next_buf].k_tiles = (const uint8_t *) factx.vtcm_k_tiles[next_buf];
+ w8a8_qk_job[next_buf].k_bias = factx.vtcm_k_bias[next_buf];
+ w8a8_qk_job[next_buf].s_tiles = (uint8_t *) factx.vtcm_s_tiles[next_buf];
+ w8a8_qk_job[next_buf].n_row_tiles_64 = n_row_tiles_64;
+ w8a8_qk_job[next_buf].n_col_tiles = (uint32_t) hmx_ceil_div(next_rows, HMX_W8A8_TILE_N_COLS);
+ w8a8_qk_job[next_buf].n_dot_tiles = DK / 32;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_qk_dot_worker, &w8a8_qk_job[next_buf]));
+ } else {
+ qk_job[next_buf].q_tiles = factx.vtcm_q_tiles;
+ qk_job[next_buf].k_tiles = factx.vtcm_k_tiles[next_buf];
+ qk_job[next_buf].s_tiles = factx.vtcm_s_tiles[next_buf];
+ qk_job[next_buf].n_row_tiles = n_row_tiles;
+ qk_job[next_buf].n_col_tiles = hmx_ceil_div(next_rows, HMX_FP16_TILE_N_COLS);
+ qk_job[next_buf].n_dot_tiles = DK_pad / 32;
+ qk_job[next_buf].n_tiles_per_bc = n_tiles_per_bc;
+ qk_job[next_buf].hmx_scales = factx.vtcm_hmx_scales_qk;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[next_buf]));
+ }
}
// ---- 5. Wait for current block's QK-dot to finish ----
@@ -2433,10 +3844,14 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
// Run Softmax on HVX (blocking call)
fa_phase_softmax_and_build_d(&factx, &sargs, n_row_tiles, n_row_tiles_g_br);
- // Wait for HMX O update for step - 1 to finish
+ // Wait for HMX O update / PV for step - 1 to finish
if (step > 0) {
hmx_queue_pop(hmx_q);
- hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev);
+ if (factx.is_w8a8) {
+ fa_phase_w8a8_o_accum(&factx, 1 - buf_idx, n_rows_g, q_start, step == 1);
+ } else {
+ hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev);
+ }
}
// Prefetch block step + 2
@@ -2450,28 +3865,42 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
// Epilogue
if (n_active_blocks > 0) {
- const uint32_t last_blk = active_blocks[n_active_blocks - 1];
- const size_t last_cols = hmx_ceil_div(hex_smin(Bc, nek1 - last_blk * Bc), HMX_FP16_TILE_N_COLS);
- ou_job[0].o_curr = o_tile_curr;
- ou_job[0].o_prev = o_tile_prev;
- ou_job[0].p_tiles = factx.vtcm_p_tiles[1 - buf_idx];
- ou_job[0].v_tiles = factx.vtcm_v_tiles[1 - buf_idx];
- ou_job[0].d_tiles = factx.vtcm_d_tiles[1 - buf_idx];
- ou_job[0].hmx_scales = factx.vtcm_hmx_scales_id;
- ou_job[0].n_row_tiles = n_row_tiles;
- ou_job[0].n_col_tiles = last_cols;
- ou_job[0].n_row_tiles_g_br = n_row_tiles_g_br;
- ou_job[0].n_tiles_per_bc = n_tiles_per_bc;
- ou_job[0].DV = DV_pad;
- hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[0]));
-
- // Overlapped: run HVX build diag inv L while HMX is busy executing the update
- htp_trace_event_start(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start);
- fa_build_d_diag_inv_l(&factx, n_row_tiles, n_row_tiles_g_br, kv_head, n_rows_g);
- htp_trace_event_stop(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start);
- hmx_queue_pop(hmx_q);
+ const uint32_t last_blk = active_blocks[n_active_blocks - 1];
+ const size_t last_cols = hmx_ceil_div(hex_smin(Bc, nek1 - last_blk * Bc), HMX_FP16_TILE_N_COLS);
+ const size_t last_buf = 1 - buf_idx;
+ if (factx.is_w8a8) {
+ w8a8_pv_job[0].p_tiles = (const uint8_t *) factx.vtcm_p_tiles[last_buf];
+ w8a8_pv_job[0].v_tiles = (const uint8_t *) factx.vtcm_v_tiles[last_buf];
+ w8a8_pv_job[0].v_bias = factx.vtcm_v_bias[last_buf];
+ w8a8_pv_job[0].do_tiles = factx.vtcm_do_tiles;
+ w8a8_pv_job[0].n_row_tiles_64 = n_row_tiles_64;
+ w8a8_pv_job[0].n_v_tiles = DV / HMX_W8A8_TILE_N_COLS;
+ w8a8_pv_job[0].n_dot_tiles = (uint32_t) last_cols;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_pv_worker, &w8a8_pv_job[0]));
+ hmx_queue_pop(hmx_q);
+ fa_phase_w8a8_o_accum(&factx, last_buf, n_rows_g, q_start, n_active_blocks == 1);
+ } else {
+ ou_job[0].o_curr = o_tile_curr;
+ ou_job[0].o_prev = o_tile_prev;
+ ou_job[0].p_tiles = factx.vtcm_p_tiles[last_buf];
+ ou_job[0].v_tiles = factx.vtcm_v_tiles[last_buf];
+ ou_job[0].d_tiles = factx.vtcm_d_tiles[last_buf];
+ ou_job[0].hmx_scales = factx.vtcm_hmx_scales_id;
+ ou_job[0].n_row_tiles = n_row_tiles;
+ ou_job[0].n_col_tiles = last_cols;
+ ou_job[0].n_row_tiles_g_br = n_row_tiles_g_br;
+ ou_job[0].n_tiles_per_bc = n_tiles_per_bc;
+ ou_job[0].DV = DV_pad;
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[0]));
+
+ // Overlapped: run HVX build diag inv L while HMX is busy executing the update
+ htp_trace_event_start(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start);
+ fa_build_d_diag_inv_l(&factx, n_row_tiles, n_row_tiles_g_br, kv_head, n_rows_g);
+ htp_trace_event_stop(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start);
+ hmx_queue_pop(hmx_q);
- hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev);
+ hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev);
+ }
}
} else {
@@ -2506,7 +3935,18 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
void * curr_k = (void *) dma_queue_pop(dma_q).dst;
fa_phase_k_interleave(&factx, kv_rows, k_src_stride, curr_k, kv_start, 0);
- {
+ if (factx.is_w8a8) {
+ w8a8_qk_job.q_tiles = (const uint8_t *) factx.vtcm_q_tiles;
+ w8a8_qk_job.k_tiles = (const uint8_t *) factx.vtcm_k_tiles[0];
+ w8a8_qk_job.k_bias = factx.vtcm_k_bias[0];
+ w8a8_qk_job.s_tiles = (uint8_t *) factx.vtcm_s_tiles[0];
+ w8a8_qk_job.n_row_tiles_64 = n_row_tiles_64;
+ w8a8_qk_job.n_col_tiles = (uint32_t) n_col_tiles;
+ w8a8_qk_job.n_dot_tiles = DK / 32;
+
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_w8a8_qk_dot_worker, &w8a8_qk_job));
+ hmx_queue_pop(ctx->hmx_queue);
+ } else {
qk_job.q_tiles = factx.vtcm_q_tiles;
qk_job.k_tiles = factx.vtcm_k_tiles[0];
qk_job.s_tiles = factx.vtcm_s_tiles[0];
@@ -2522,7 +3962,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
// Wait for current V DMA and interleave
void * curr_v = (void *) dma_queue_pop(dma_q).dst;
- fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[0], n_tiles_per_bc, kv_start);
+ fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[0], n_tiles_per_bc, kv_start, 0);
// ---- Phase 3: softmax + build_D ----
__fp16 * current_mask_vtcm = NULL;
@@ -2557,7 +3997,19 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
sargs.slopes = factx.vtcm_slopes;
fa_phase_softmax_and_build_d(&factx, &sargs, n_row_tiles, n_row_tiles_g_br);
- {
+ if (factx.is_w8a8) {
+ w8a8_pv_job.p_tiles = (const uint8_t *) factx.vtcm_p_tiles[0];
+ w8a8_pv_job.v_tiles = (const uint8_t *) factx.vtcm_v_tiles[0];
+ w8a8_pv_job.v_bias = factx.vtcm_v_bias[0];
+ w8a8_pv_job.do_tiles = factx.vtcm_do_tiles;
+ w8a8_pv_job.n_row_tiles_64 = n_row_tiles_64;
+ w8a8_pv_job.n_v_tiles = DV / HMX_W8A8_TILE_N_COLS;
+ w8a8_pv_job.n_dot_tiles = (uint32_t) n_col_tiles;
+
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_w8a8_pv_worker, &w8a8_pv_job));
+ hmx_queue_pop(ctx->hmx_queue);
+ fa_phase_w8a8_o_accum(&factx, 0, n_rows_g, q_start, step == 0);
+ } else {
ou_job.o_curr = o_tile_curr;
ou_job.o_prev = o_tile_prev;
ou_job.p_tiles = factx.vtcm_p_tiles[0];
@@ -2586,15 +4038,29 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
}
}
- // Enqueue DMAs for the next kv_head early so they overlap with O-PROC
+ // ---- Final normalization & Store O block (via bypass DMA) ----
+ if (factx.is_w8a8) {
+ fa_phase_w8a8_o_store(&factx, dma_q, dst, q_start, kv_head, ib3, n_rows_g);
+ } else {
+ on_job.o_curr = o_tile_curr;
+ on_job.o_prev = o_tile_prev;
+ on_job.d_tiles = factx.vtcm_d_inv_l;
+ on_job.hmx_scales = factx.vtcm_hmx_scales_id;
+ on_job.n_row_tiles = n_row_tiles;
+ on_job.n_row_tiles_g_br = n_row_tiles_g_br;
+ on_job.DV = DV_pad;
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_o_norm_worker, &on_job));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ fa_phase_o_store(&factx, dma_q, dst, o_tile_curr, (uint8_t *) o_tile_prev, q_start, kv_head, ib3, n_rows_g);
+ }
+
+ // Enqueue DMAs for the next kv_head behind O writeback on dma_q.
const uint32_t next_kv_head = kv_head + 1;
- const bool has_next = (next_kv_head < kv_head_max);
+ const bool has_next = (next_kv_head < kv_head_max);
if (has_next) {
- const dma_addr_t next_q_ptr = q->data + q_start * q->nb[1] + (next_kv_head * factx.G) * q->nb[2] + ib3 * q->nb[3];
- const size_t next_q_row_bytes = q_transposed ? n_rows_q * q_row_bytes_trans_factor : q_row_bytes_untransposed;
- const size_t next_n_rows = q_transposed ? factx.G : n_rows_q;
- dma_queue_push(dma_q, dma_make_data(factx.vtcm_q_dma, next_q_ptr), next_q_row_bytes, hex_smax(q_src_stride, next_q_row_bytes), next_q_row_bytes, next_n_rows);
+ fa_push_q_dma(dma_q, q, factx.vtcm_q_dma, q_start, next_kv_head, ib3, factx.G, n_rows_q, q_elem_row_bytes, q_transposed);
if (n_active_blocks > 0) {
const uint32_t next_ik2 = next_kv_head;
@@ -2616,23 +4082,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
}
}
}
-
- // ---- Final normalization ----
- {
- on_job.o_curr = o_tile_curr;
- on_job.o_prev = o_tile_prev;
- on_job.d_tiles = factx.vtcm_d_inv_l;
- on_job.hmx_scales = factx.vtcm_hmx_scales_id;
- on_job.n_row_tiles = n_row_tiles;
- on_job.n_row_tiles_g_br = n_row_tiles_g_br;
- on_job.DV = DV_pad;
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_o_norm_worker, &on_job));
- hmx_queue_pop(ctx->hmx_queue);
- }
-
- // ---- Store O block ----
- fa_phase_o_store(&factx, dst, o_tile_curr, q_start, kv_head, ib3, n_rows_g);
}
+
+ dma_queue_pop(dma_q);
}
}
@@ -2644,7 +4096,6 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const struct htp_tensor * k = octx->src[1];
const struct htp_tensor * v = octx->src[2];
const struct htp_tensor * mask = octx->src[3];
- const struct htp_tensor * dst = octx->dst;
// Check support
if ((q->type != HTP_TYPE_F16 && q->type != HTP_TYPE_F32) ||
@@ -2653,10 +4104,6 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
return HTP_STATUS_NO_SUPPORT;
}
- if (htp_tensor_is_extended(dst)) {
- 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) {
@@ -2667,7 +4114,7 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
return HTP_STATUS_INVAL_PARAMS;
}
- if (kparams->kernel_type == HTP_FA_KERNEL_HMX) {
+ if (kparams->kernel_type == HTP_FA_KERNEL_HMX_F16 || kparams->kernel_type == HTP_FA_KERNEL_HMX_W8A8) {
return hmx_flash_attn_ext(octx);
}
@@ -2729,28 +4176,31 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const uint32_t neq3 = q->ne[3];
const uint32_t total_qrows = neq1 * neq2 * neq3;
- uint32_t qrow_start = 0;
- uint32_t qrows = total_qrows;
+ uint32_t qrow_start = 0;
+ uint32_t qrows = total_qrows;
+ uint32_t kv_head_start = 0;
+ uint32_t n_kv_local = k->ne[2];
if (octx->ctx->mdev.count > 1) {
const uint32_t mdev_count = octx->ctx->mdev.count;
const uint32_t mdev_idx = octx->ctx->mdev.idx;
const uint32_t n_kv_heads = k->ne[2];
- const uint32_t dst_e_size = (dst->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(__fp16);
- const bool can_split = htp_tensor_can_row_partition(dst, dst_e_size);
// head range is contiguous in flat row space only when neq3 == 1
- if (kparams->head_split && can_split && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
+ if (kparams->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;
const uint32_t head_start = mdev_idx * heads_per_core;
- qrow_start = head_start * neq1;
- qrows = heads_per_core * neq1;
+ qrow_start = head_start * neq1;
+ qrows = heads_per_core * neq1;
+ kv_head_start = mdev_idx * kv_per_core;
+ n_kv_local = kv_per_core;
} else {
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_qrows, can_split ? 1 : 0, mdev_idx, mdev_count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_qrows, 1, mdev_idx, mdev_count, &octx->ctx->mdev.count_div);
qrow_start = range.start;
qrows = range.count;
+ n_kv_local = 0;
}
}
@@ -2760,14 +4210,27 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
- factx.qrows = qrows;
- factx.qrow_start = qrow_start;
- factx.qrows_per_hvx = fastdiv(qrows + n_hvx - 1, &octx->n_hvx_div);
+ factx.qrows = qrows;
+ factx.qrow_start = qrow_start;
+ factx.qrows_per_hvx = fastdiv(qrows + n_hvx - 1, &octx->n_hvx_div);
+ factx.kv_head_start = kv_head_start;
+ factx.n_kv_local = n_kv_local;
+ factx.G = kparams->G;
+ factx.splits_per_kv = 1;
const bool has_mask = (mask != NULL);
const bool has_sinks = (octx->src[4] != NULL);
+ const struct hvx_fa_layout_params lp = {
+ .q_type = q->type,
+ .DK = k->ne[0],
+ .DV = v->ne[0],
+ .n_heads = n_head,
+ .n_hvx = n_hvx,
+ .has_mask = has_mask,
+ .has_sinks = has_sinks,
+ };
struct hvx_fa_vtcm_layout L;
- hvx_fa_vtcm_layout_build(&L, k->ne[0], v->ne[0], factx.is_q_fp32, has_mask, has_sinks, n_head, n_hvx);
+ hvx_fa_vtcm_layout_build(&L, &lp);
if (L.total_bytes > octx->ctx->vtcm_size) {
return HTP_STATUS_VTCM_TOO_SMALL;
@@ -2804,6 +4267,27 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
dma_queue_pop(dma_q);
}
+ const bool can_split_kv =
+ (neq1 == 1) &&
+ (neq3 == 1) &&
+ (k->ne[2] == v->ne[2]) &&
+ (!has_mask || mask->ne[2] == 1) &&
+ (n_kv_local > 0 && n_kv_local < n_hvx) &&
+ (factx.G > 0 && factx.G <= FA_HVX_G_MAX) &&
+ (factx.n_active_blocks >= 4);
+
+ if (can_split_kv) {
+ const uint32_t max_splits = MIN(n_hvx / n_kv_local, factx.n_active_blocks / 2);
+ if (max_splits >= 2) {
+ factx.splits_per_kv = max_splits;
+ const uint32_t n_workers = n_kv_local * max_splits;
+ const uint32_t n_merge = MIN(n_hvx, n_kv_local * factx.G);
+ work_queue_run(octx->ctx->hvx_queue, flash_attn_ext_f16_split_kv_thread, &factx, n_workers);
+ work_queue_run(octx->ctx->hvx_queue, flash_attn_ext_f16_split_merge_thread, &factx, n_merge);
+ return HTP_STATUS_OK;
+ }
+ }
+
work_queue_run(octx->ctx->hvx_queue, flash_attn_ext_f16_thread, &factx, n_hvx);
return HTP_STATUS_OK;
diff --git a/ggml/src/ggml-hexagon/htp/flash-attn-ops.h b/ggml/src/ggml-hexagon/htp/flash-attn-ops.h
index 70cf3e41a..32f15dde2 100644
--- a/ggml/src/ggml-hexagon/htp/flash-attn-ops.h
+++ b/ggml/src/ggml-hexagon/htp/flash-attn-ops.h
@@ -7,6 +7,7 @@
#include "hex-fastdiv.h"
#include "hex-common.h"
+#include "htp-tensor.h"
#include "htp-vtcm.h"
#ifdef __cplusplus
@@ -14,11 +15,17 @@ extern "C" {
#endif
// Tile constants (mirrored from hmx-utils.h for use on host side if needed)
-#define HTP_FA_HMX_TILE_SIZE 2048
-#define HMX_FP16_TILE_SIZE 2048
-#define HMX_FP16_TILE_N_ROWS 32
-#define HMX_FP16_TILE_N_COLS 32
-#define HMX_FP16_TILE_N_ELMS 1024
+#define HTP_FA_HMX_TILE_SIZE 2048
+#define HMX_FP16_TILE_SIZE 2048
+#define HMX_FP16_TILE_N_ROWS 32
+#define HMX_FP16_TILE_N_COLS 32
+#define HMX_FP16_TILE_N_ELMS 1024
+
+#define HMX_W8A8_ACT_TILE_N_ROWS 64
+#define HMX_W8A8_TILE_N_COLS 32
+#define HMX_W8A8_ACT_TILE_SIZE 2048
+#define HMX_W8A8_WT_TILE_SIZE 1024
+#define HMX_W8A8_BIAS_BANK_SIZE 256
#define HVX_FA_DMA_CACHE_SIZE 128
#define HMX_FA_DMA_CACHE_SIZE 4
@@ -29,7 +36,8 @@ extern "C" {
enum htp_fa_kernel_type {
HTP_FA_KERNEL_UNSUPPORTED = 0,
HTP_FA_KERNEL_HVX,
- HTP_FA_KERNEL_HMX
+ HTP_FA_KERNEL_HMX_F16,
+ HTP_FA_KERNEL_HMX_W8A8,
};
// Multicore: gcd(n_kv_heads, N) teams own the KV heads, team members share the Q-blocks
@@ -129,68 +137,143 @@ struct hmx_fa_vtcm_layout {
size_t off_mask_buf;
size_t off_slopes;
size_t off_sinks;
+ size_t off_q_scales;
+ size_t off_k_scales[2];
+ size_t off_k_bias[2];
+ size_t off_o_f32;
+ size_t off_do_tiles;
+ size_t off_v_scales[2];
+ size_t off_v_bias[2];
+ size_t off_p_scales[2];
+ size_t off_exp_mdiff[2];
// Region byte sizes reused by the device at runtime (not just for allocation).
size_t q_tile_bytes;
size_t o_tile_bytes;
size_t k_tile_bytes;
- size_t s_tile_bytes; // S and P tiles (same size)
+ size_t s_tile_bytes; // S tiles (2x in W8A8 for hi+lo)
+ size_t p_tile_bytes; // P tiles
size_t d_tile_bytes; // d_tiles[0..1] + d_inv_l, allocated back to back
+ size_t o_f32_bytes; // W8A8 FP32 O accumulator
size_t m_line_bytes; // one mask row
size_t m_buf_slot_bytes; // one dma_cache slot = align_up(Br * m_line_bytes, 4096)
size_t col_vec_bytes;
size_t sinks_bytes;
+ size_t k_raw_row_padded;
+ size_t v_raw_row_padded;
// Derived strides.
size_t row_buf_stride; // HVX vectors (128B) per row buffer
size_t mask_buf_row_stride; // __fp16 elements per row in the mask buffer
bool pipeline;
+ bool is_w8a8;
size_t total_bytes;
};
#define FA_MAX_KV_BLOCKS 1024
+struct hmx_fa_layout_params {
+ int kernel_type;
+ int q_type;
+ size_t gqa_factor;
+ size_t DK;
+ size_t DV;
+ size_t Br;
+ size_t Bc;
+ size_t n_hvx;
+ size_t n_heads;
+ bool pipeline;
+ bool has_mask;
+ bool mask_broadcast;
+ bool has_sinks;
+};
+
// Build the VTCM layout.
static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L,
- size_t gqa_factor, size_t DK, size_t DV,
- size_t Br, size_t Bc, size_t n_hvx,
- bool pipeline, bool is_q_fp32,
- bool has_sinks, size_t n_heads) {
- const size_t g_br = hex_align_up(gqa_factor * Br, HMX_FP16_TILE_N_ROWS);
- const size_t q_tile_size = hex_align_up(g_br * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
- const size_t o_tile_size = hex_align_up(g_br * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
- const size_t k_tile_size = hex_align_up(Bc * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
- const size_t v_tile_size = hex_align_up(Bc * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
- const size_t s_tile_size = hex_align_up(g_br * Bc * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
+ const struct hmx_fa_layout_params * p) {
+ const bool is_w8a8 = (p->kernel_type == HTP_FA_KERNEL_HMX_W8A8);
+ const size_t gqa_factor = p->gqa_factor;
+ const size_t DK = p->DK;
+ const size_t DV = p->DV;
+ const size_t Br = p->Br;
+ const size_t Bc = p->Bc;
+ const size_t n_hvx = p->n_hvx;
+ const size_t n_heads = p->n_heads;
+ const bool pipeline = p->pipeline;
+ const bool has_mask = p->has_mask;
+ const bool mask_broadcast = p->mask_broadcast;
+ const bool has_sinks = p->has_sinks;
+
+ const size_t g_br = hex_align_up(gqa_factor * Br, is_w8a8 ? HMX_W8A8_ACT_TILE_N_ROWS : HMX_FP16_TILE_N_ROWS);
+ const size_t n_row_tiles_64 = g_br / HMX_W8A8_ACT_TILE_N_ROWS;
+ const size_t n_col_tiles = Bc / HMX_W8A8_TILE_N_COLS;
+ const size_t n_k_tiles = DK / HMX_W8A8_TILE_N_COLS;
+ const size_t n_v_tiles = DV / HMX_W8A8_TILE_N_COLS;
+
+ const size_t q_tile_size = is_w8a8
+ ? (n_row_tiles_64 * n_k_tiles * HMX_W8A8_ACT_TILE_SIZE)
+ : hex_align_up(g_br * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
+ const size_t o_tile_size = is_w8a8
+ ? 0
+ : hex_align_up(g_br * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
+ const size_t k_tile_size = is_w8a8
+ ? hex_align_up(n_col_tiles * n_k_tiles * HMX_W8A8_WT_TILE_SIZE, HTP_FA_HMX_TILE_SIZE)
+ : hex_align_up(Bc * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
+ const size_t v_tile_size = is_w8a8
+ ? hex_align_up(n_v_tiles * n_col_tiles * HMX_W8A8_WT_TILE_SIZE, HTP_FA_HMX_TILE_SIZE)
+ : hex_align_up(Bc * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
+ const size_t s_tile_size = is_w8a8
+ ? (n_row_tiles_64 * n_col_tiles * 2 * HMX_W8A8_ACT_TILE_SIZE)
+ : hex_align_up(g_br * Bc * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
+ const size_t p_tile_size = is_w8a8
+ ? (n_row_tiles_64 * n_col_tiles * HMX_W8A8_ACT_TILE_SIZE)
+ : hex_align_up(g_br * Bc * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE);
// The rescale matrices are diagonal: the HMX kernels only ever load the g_br/32
// tiles that sit on the diagonal, so store just those, packed back to back with
// a stride of one tile. The old [g_br, g_br] square layout allocated g_br/32
// times more than it used, which is also why a second D buffer was unaffordable.
- const size_t d_tile_size = (g_br / HMX_FP16_TILE_N_ROWS) * HTP_FA_HMX_TILE_SIZE;
-
- const size_t q_dma_size = hex_align_up(g_br * DK * (is_q_fp32 ? sizeof(float) : sizeof(__fp16)), 128);
- const size_t k_dma_size = hex_align_up(Bc * hex_round_up(DK * sizeof(__fp16), 128), 128);
- const size_t v_dma_size = hex_align_up(Bc * hex_round_up(DV * sizeof(__fp16), 128), 128);
- const size_t col_vec_size = hex_align_up(g_br * sizeof(float), 256);
- const size_t row_vec_size = hex_align_up(Bc * sizeof(__fp16), 256);
- const size_t m_line_size = hex_align_up(Bc * sizeof(__fp16), 128);
- const size_t m_buf_slot = hex_align_up(Br * m_line_size, 256);
- const size_t m_buf_size = m_buf_slot * HMX_FA_DMA_CACHE_SIZE;
- const size_t slopes_size = hex_align_up(g_br * sizeof(__fp16), 128);
- const size_t sinks_size = hex_round_up(n_heads * sizeof(float), 128);
+ const size_t d_tile_size = is_w8a8 ? 0 : (g_br / HMX_FP16_TILE_N_ROWS) * HTP_FA_HMX_TILE_SIZE;
+ const size_t o_f32_size = hex_align_up(g_br * DV * sizeof(float), 128);
+ const size_t do_tile_size = n_row_tiles_64 * n_v_tiles * 2 * HMX_W8A8_ACT_TILE_SIZE;
+
+ const size_t k_raw_row_padded = is_w8a8
+ ? hex_round_up((DK / 32) * 34, 128)
+ : hex_round_up(DK * sizeof(__fp16), 128);
+ const size_t v_raw_row_padded = is_w8a8
+ ? hex_round_up((DV / 32) * 34, 128)
+ : hex_round_up(DV * sizeof(__fp16), 128);
+
+ const size_t q_dma_size = hex_align_up(g_br * htp_tensor_get_row_size(p->q_type, DK), 128);
+ const size_t k_dma_size = hex_align_up(Bc * k_raw_row_padded, 128);
+ const size_t v_dma_size = hex_align_up(Bc * v_raw_row_padded, 128);
+ const size_t col_vec_size = hex_align_up(g_br * sizeof(float), 256);
+ const size_t row_vec_size = hex_align_up(Bc * sizeof(__fp16), 256);
+ const size_t m_line_size = hex_align_up(Bc * sizeof(__fp16), 128);
+ const size_t m_buf_slot = hex_align_up(Br * m_line_size, 256);
+ const size_t m_buf_slots = mask_broadcast ? HMX_FA_DMA_CACHE_SIZE : gqa_factor;
+ const size_t m_buf_size = m_buf_slot * m_buf_slots;
+ const size_t slopes_size = hex_align_up(g_br * sizeof(__fp16), 128);
+ const size_t sinks_size = hex_round_up(n_heads * sizeof(float), 128);
+ const size_t q_scales_size = hex_align_up(g_br * sizeof(float), 128);
+ const size_t k_scales_size = hex_align_up(Bc * sizeof(float), 128);
+ const size_t k_bias_size = hex_align_up(n_col_tiles * 2 * HMX_W8A8_BIAS_BANK_SIZE, HMX_W8A8_BIAS_BANK_SIZE);
+ const size_t v_scales_size = hex_align_up(DV * sizeof(float), 128);
+ const size_t v_bias_size = hex_align_up(n_v_tiles * 2 * HMX_W8A8_BIAS_BANK_SIZE, HMX_W8A8_BIAS_BANK_SIZE);
+ const size_t p_scales_size = hex_align_up(g_br * sizeof(float), 128);
+ const size_t exp_mdiff_size = hex_align_up(g_br * sizeof(float), 128);
size_t off = 0;
// Group A (Part 1 - HMX Tiled buffers)
- VTCM_LAYOUT_ALLOC(off, off_q_tiles, q_tile_size);
- VTCM_LAYOUT_ALLOC(off, off_o_tiles[0], o_tile_size);
- VTCM_LAYOUT_ALLOC(off, off_o_tiles[1], o_tile_size);
- VTCM_LAYOUT_ALLOC(off, off_d_tiles[0], d_tile_size);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_tiles[1], d_tile_size, pipeline);
- VTCM_LAYOUT_ALLOC(off, off_d_inv_l, d_tile_size);
+ VTCM_LAYOUT_ALLOC(off, off_q_tiles, q_tile_size);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_tiles[0], o_tile_size, !is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_tiles[1], o_tile_size, !is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_tiles[0], d_tile_size, !is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_tiles[1], d_tile_size, !is_w8a8 && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_inv_l, d_tile_size, !is_w8a8);
// Group B & C share start offset (Group B tiles must be 2KB aligned)
size_t off_group_b_c = hex_align_up(off, HTP_FA_HMX_TILE_SIZE);
@@ -203,11 +286,27 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L,
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_tiles[1], v_tile_size, pipeline);
VTCM_LAYOUT_ALLOC(off_group_b, off_s_tiles[0], s_tile_size);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_s_tiles[1], s_tile_size, pipeline);
- VTCM_LAYOUT_ALLOC(off_group_b, off_p_tiles[0], s_tile_size);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_tiles[1], s_tile_size, pipeline);
+ VTCM_LAYOUT_ALLOC(off_group_b, off_p_tiles[0], p_tile_size);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_tiles[1], p_tile_size, pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_do_tiles, do_tile_size, is_w8a8);
VTCM_LAYOUT_ALLOC(off_group_b, off_s_rowmax, col_vec_size);
VTCM_LAYOUT_ALLOC(off_group_b, off_p_rowsum, col_vec_size);
- VTCM_LAYOUT_ALLOC(off_group_b, off_row_bufs, row_vec_size * 2 * n_hvx);
+ VTCM_LAYOUT_ALLOC(off_group_b, off_row_bufs, row_vec_size * (is_w8a8 ? 4 : 2) * n_hvx);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_scales[0], k_scales_size, is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_scales[1], k_scales_size, is_w8a8 && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_scales[0], v_scales_size, is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_scales[1], v_scales_size, is_w8a8 && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_scales[0], p_scales_size, is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_scales[1], p_scales_size, is_w8a8 && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_exp_mdiff[0], exp_mdiff_size, is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_exp_mdiff[1], exp_mdiff_size, is_w8a8 && pipeline);
+ if (is_w8a8) {
+ off_group_b = hex_align_up(off_group_b, HMX_W8A8_BIAS_BANK_SIZE);
+ }
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_bias[0], k_bias_size, is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_bias[1], k_bias_size, is_w8a8 && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_bias[0], v_bias_size, is_w8a8);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_bias[1], v_bias_size, is_w8a8 && pipeline);
const size_t group_b_size = off_group_b - off_group_b_c;
@@ -220,6 +319,7 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L,
off = off_group_b_c + hex_smax(group_b_size, group_c_size);
// Group A (Part 2 - remaining non-HMX buffers)
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_f32, o_f32_size, is_w8a8);
VTCM_LAYOUT_ALLOC(off, off_k_fp16[0], k_dma_size);
VTCM_LAYOUT_ALLOC(off, off_k_fp16[1], k_dma_size);
VTCM_LAYOUT_ALLOC(off, off_v_fp16[0], v_dma_size);
@@ -228,8 +328,9 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L,
VTCM_LAYOUT_ALLOC(off, off_l_vec, col_vec_size);
VTCM_LAYOUT_ALLOC(off, off_hmx_scales_id, 256);
VTCM_LAYOUT_ALLOC(off, off_hmx_scales_qk, 256);
- VTCM_LAYOUT_ALLOC(off, off_mask_buf, m_buf_size);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_mask_buf, m_buf_size, has_mask);
VTCM_LAYOUT_ALLOC(off, off_slopes, slopes_size);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_q_scales, q_scales_size, is_w8a8);
VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_sinks, sinks_size, has_sinks);
L->q_tile_bytes = q_tile_size;
@@ -237,29 +338,44 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L,
L->k_tile_bytes = k_tile_size;
L->col_vec_bytes = col_vec_size;
L->s_tile_bytes = s_tile_size;
+ L->p_tile_bytes = p_tile_size;
// Measured from the actual offsets rather than assumed to be N * d_tile_size, so
// that inserting a region between them (or adding padding to VTCM_LAYOUT_ALLOC)
// cannot silently leave the tail of the run unzeroed.
- L->d_tile_bytes = (L->off_d_inv_l + d_tile_size) - L->off_d_tiles[0];
+ L->d_tile_bytes = is_w8a8 ? 0 : ((L->off_d_inv_l + d_tile_size) - L->off_d_tiles[0]);
+ L->o_f32_bytes = is_w8a8 ? o_f32_size : 0;
L->m_line_bytes = m_line_size;
L->m_buf_slot_bytes = m_buf_slot;
+ L->k_raw_row_padded = k_raw_row_padded;
+ L->v_raw_row_padded = v_raw_row_padded;
L->row_buf_stride = row_vec_size / 128;
L->mask_buf_row_stride = m_line_size / sizeof(__fp16);
L->sinks_bytes = has_sinks ? sinks_size : 0;
L->pipeline = pipeline;
+ L->is_w8a8 = is_w8a8;
L->total_bytes = off;
}
-// Exact VTCM usage for a given (gqa_factor, DK, DV, Br, Bc) configuration.
-static inline size_t hmx_fa_compute_vtcm_usage(size_t gqa_factor, size_t DK, size_t DV, size_t Br, size_t Bc, size_t n_hvx, bool pipeline, bool is_q_fp32, bool has_sinks, size_t n_heads) {
+// Exact VTCM usage for a given HMX layout configuration.
+static inline size_t hmx_fa_compute_vtcm_usage(const struct hmx_fa_layout_params * p) {
struct hmx_fa_vtcm_layout L;
- hmx_fa_vtcm_layout_build(&L, gqa_factor, DK, DV, Br, Bc, n_hvx, pipeline, is_q_fp32, has_sinks, n_heads);
+ hmx_fa_vtcm_layout_build(&L, p);
return L.total_bytes;
}
#define FA_HVX_BLOCK_SIZE 64
#define FA_HVX_G_MAX 8
+struct hvx_fa_layout_params {
+ int q_type;
+ size_t DK;
+ size_t DV;
+ size_t n_heads;
+ size_t n_hvx;
+ bool has_mask;
+ bool has_sinks;
+};
+
struct hvx_fa_vtcm_layout {
size_t off_q;
size_t off_k;
@@ -279,65 +395,57 @@ struct hvx_fa_vtcm_layout {
};
static inline void hvx_fa_vtcm_layout_build(struct hvx_fa_vtcm_layout * L,
- size_t DK, size_t DV,
- bool is_q_fp32, bool has_mask,
- bool has_sinks, size_t n_heads,
- size_t n_hvx) {
- const size_t size_q_row_padded = hex_round_up(DK * (is_q_fp32 ? 4 : 2), 128);
- const size_t size_k_row_padded = hex_round_up(DK * sizeof(__fp16), 128);
- const size_t size_v_row_padded = hex_round_up(DV * sizeof(__fp16), 128);
+ const struct hvx_fa_layout_params * p) {
+ const size_t size_q_row_padded = hex_round_up(htp_tensor_get_row_size(p->q_type, p->DK), 128);
+ const size_t size_k_row_padded = hex_round_up(p->DK * sizeof(__fp16), 128);
+ const size_t size_v_row_padded = hex_round_up(p->DV * sizeof(__fp16), 128);
const size_t size_q_block = size_q_row_padded * FA_HVX_G_MAX;
const size_t size_k_block = size_k_row_padded * FA_HVX_BLOCK_SIZE;
const size_t size_v_block = size_v_row_padded * FA_HVX_BLOCK_SIZE;
const size_t size_m_block = hex_round_up(FA_HVX_BLOCK_SIZE * sizeof(__fp16), 128);
- const size_t size_vkq_acc = hex_round_up(DV * sizeof(float), 128) * FA_HVX_G_MAX;
- const size_t size_sinks = hex_round_up(n_heads * sizeof(float), 128);
+ const size_t size_vkq_acc = hex_round_up(p->DV * sizeof(float), 256) * FA_HVX_G_MAX;
+ const size_t size_sinks = hex_round_up(p->n_heads * sizeof(float), 128);
size_t off = 0;
- VTCM_LAYOUT_ALLOC(off, off_q, size_q_block * n_hvx);
- VTCM_LAYOUT_ALLOC(off, off_k, size_k_block * 2 * n_hvx);
- VTCM_LAYOUT_ALLOC(off, off_v, size_v_block * 2 * n_hvx);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_m, size_m_block * HVX_FA_DMA_CACHE_SIZE * n_hvx, has_mask);
- VTCM_LAYOUT_ALLOC(off, off_a, size_vkq_acc * n_hvx);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_sinks, size_sinks, has_sinks);
+ VTCM_LAYOUT_ALLOC(off, off_q, size_q_block * p->n_hvx);
+ VTCM_LAYOUT_ALLOC(off, off_k, size_k_block * 2 * p->n_hvx);
+ VTCM_LAYOUT_ALLOC(off, off_v, size_v_block * 2 * p->n_hvx);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_m, size_m_block * HVX_FA_DMA_CACHE_SIZE * p->n_hvx, p->has_mask);
+ VTCM_LAYOUT_ALLOC(off, off_a, size_vkq_acc * p->n_hvx);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_sinks, size_sinks, p->has_sinks);
L->size_q_block = size_q_block;
L->size_k_block = size_k_block;
L->size_v_block = size_v_block;
L->size_m_block = size_m_block;
L->size_vkq_acc = size_vkq_acc;
- L->size_sinks = has_sinks ? size_sinks : 0;
+ L->size_sinks = p->has_sinks ? size_sinks : 0;
L->total_bytes = off;
}
-static inline size_t hvx_fa_compute_vtcm_usage(size_t DK, size_t DV, bool is_q_fp32, bool has_mask, bool has_sinks, size_t n_heads, size_t n_hvx) {
+static inline size_t hvx_fa_compute_vtcm_usage(const struct hvx_fa_layout_params * p) {
struct hvx_fa_vtcm_layout L;
- hvx_fa_vtcm_layout_build(&L, DK, DV, is_q_fp32, has_mask, has_sinks, n_heads, n_hvx);
+ hvx_fa_vtcm_layout_build(&L, p);
return L.total_bytes;
}
#define FA_MIN_KV_BLOCKS 3
// Cost-based (Br, Bc) search for flash attention with pipeline constraint.
-static inline int hmx_fa_find_chunk_size(size_t * Br_out,
- size_t * Bc_out,
- size_t gqa_factor,
- size_t DK,
- size_t DV,
- size_t qo_len,
- size_t kv_len,
- size_t vtcm_budget,
- size_t n_hvx,
- bool is_q_fp32,
- bool has_sinks,
- size_t n_heads,
- size_t q_split) {
- const size_t T = HMX_FP16_TILE_N_ROWS; // 32
- const size_t br_unit = hmx_ceil_div(T, gqa_factor);
- const size_t bc_unit = HMX_FP16_TILE_N_COLS * 2; // 64
- const bool can_pipeline = (kv_len >= FA_MIN_KV_BLOCKS * bc_unit && n_hvx >= 2);
+static inline int hmx_fa_find_chunk_size(struct hmx_fa_layout_params * p,
+ size_t qo_len,
+ size_t kv_len,
+ size_t vtcm_budget,
+ size_t q_split) {
+ const size_t gqa_factor = p->gqa_factor;
+ const size_t n_hvx = p->n_hvx;
+ const bool is_w8a8 = (p->kernel_type == HTP_FA_KERNEL_HMX_W8A8);
+ const size_t T = HMX_FP16_TILE_N_ROWS; // 32
+ const size_t br_unit = hmx_ceil_div(T, gqa_factor);
+ const size_t bc_unit = HMX_FP16_TILE_N_COLS * 2; // 64
+ const bool can_pipeline = (kv_len >= FA_MIN_KV_BLOCKS * bc_unit && n_hvx >= 2 && (!p->has_mask || p->mask_broadcast));
// Br_max: largest Br aligned to br_unit that does not exceed qo_len.
const size_t Br_max = qo_len >= br_unit ? hex_align_down(qo_len, br_unit) : br_unit;
@@ -350,6 +458,10 @@ static inline int hmx_fa_find_chunk_size(size_t * Br_out,
if (qo_len <= 16 && kv_len <= 2048 && Bc_limit > 256) {
Bc_limit = 256;
}
+ // Cap Bc at 2048 for W8A8 so P * V always runs in 1 superblock (<= 64 tiles of 32)
+ if (is_w8a8 && Bc_limit > 2048) {
+ Bc_limit = 2048;
+ }
// Cost coefficients calibrated from profiling
const size_t c_q_fixed = 800; // per-Q-block: q_load + epilogue o_update + o_norm + o_store
const size_t c_iter_base = 200; // per-KV-iter base (HMX dot/update + DMA)
@@ -358,10 +470,15 @@ static inline int hmx_fa_find_chunk_size(size_t * Br_out,
size_t best_cost = SIZE_MAX, best_mn = 0;
size_t best_Br = 0, best_Bc = 0;
+ struct hmx_fa_layout_params cand = *p;
+ cand.pipeline = can_pipeline;
+
for (size_t Br = Br_max; Br >= br_unit; Br -= br_unit) {
+ cand.Br = Br;
// Try all Bc candidates from Bc_limit down to bc_unit
for (size_t Bc = Bc_limit; Bc >= bc_unit; Bc -= bc_unit) {
- size_t vtcm_needed = hmx_fa_compute_vtcm_usage(gqa_factor, DK, DV, Br, Bc, n_hvx, can_pipeline, is_q_fp32, has_sinks, n_heads);
+ cand.Bc = Bc;
+ size_t vtcm_needed = hmx_fa_compute_vtcm_usage(&cand);
if (vtcm_needed <= vtcm_budget) {
// This Bc fits for this Br!
const size_t q_blocks = (qo_len + Br - 1) / Br;
@@ -398,8 +515,8 @@ static inline int hmx_fa_find_chunk_size(size_t * Br_out,
return -1;
}
- *Br_out = best_Br;
- *Bc_out = best_Bc;
+ p->Br = best_Br;
+ p->Bc = best_Bc;
return 0;
}
diff --git a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
index 68b9c1d47..c468ffdbd 100644
--- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
+++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
@@ -1,5 +1,6 @@
#include <stdint.h>
#include <stdbool.h>
+#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <HAP_farf.h>
@@ -8,6 +9,7 @@
#include "hvx-copy.h"
#include "hvx-reduce.h"
#include "hvx-exp.h"
+#include "hvx-repl.h"
#include "dma-queue.h"
#include "ggml-common.h"
#include "htp-ctx.h"
@@ -18,20 +20,47 @@
#include "hmx-queue.h"
#include "gated-delta-net-ops.h"
-#ifndef MIN
-#define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif
+struct htp_gdn_context;
+
+typedef void (*gdn_load_vec_fn_t)(HVX_Vector * restrict dst, const void * restrict src, uint32_t n);
+typedef void (*gdn_store_vec_fn_t)(void * restrict dst, const HVX_Vector * restrict src, uint32_t n);
+typedef void (*gdn_step_fn_t)(
+ const struct htp_gdn_context * gctx,
+ float * restrict s_work,
+ void * restrict attn_out,
+ const void * restrict q_t,
+ const void * restrict k_t,
+ const void * restrict v_t,
+ const float * restrict g_t,
+ const float * restrict beta_t,
+ HVX_Vector * restrict vtcm_scratch,
+ float scale,
+ uint32_t S_v,
+ const void * restrict k_next,
+ bool has_memory
+);
struct htp_gdn_context {
struct htp_ops_context * octx;
const struct htp_gdn_kernel_params * kparams;
struct htp_gdn_vtcm_layout layout;
uint8_t * vtcm_base;
+ const void * ids_data;
+ const int32_t * n_rep_data;
+ uint32_t ids_type;
+ uint32_t n_pend;
+ bool replay;
+ bool keep;
uint32_t row_start;
uint32_t nrows;
+ gdn_load_vec_fn_t load_q;
+ gdn_load_vec_fn_t load_k;
+ gdn_load_vec_fn_t load_v;
+ gdn_store_vec_fn_t store_out;
+ gdn_step_fn_t step_fn;
};
-static inline HVX_Vector gdn_mul_dot_f32(float * restrict dst, const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) {
+static __attribute__((noinline)) HVX_Vector gdn_mul_dot_f32(float * restrict dst, const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc = Q6_V_vzero();
const uint32_t epv = 128 / sizeof(float);
const uint32_t nvec = n / epv;
@@ -60,7 +89,7 @@ static inline HVX_Vector gdn_mul_dot_f32(float * restrict dst, const HVX_Vector
return hvx_vec_reduce_sum_f32(acc);
}
-static inline HVX_Vector gdn_mul_scalar_dot_f32(float * restrict dst, HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) {
+static __attribute__((noinline)) HVX_Vector gdn_mul_scalar_dot_f32(float * restrict dst, HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc = Q6_V_vzero();
const uint32_t epv = 128 / sizeof(float);
const uint32_t nvec = n / epv;
@@ -87,7 +116,7 @@ static inline HVX_Vector gdn_mul_scalar_dot_f32(float * restrict dst, HVX_Vector
return hvx_vec_reduce_sum_f32(acc);
}
-static inline HVX_Vector gdn_add_scaled_dot_f32(float * restrict dst, const HVX_Vector * restrict src,
+static __attribute__((noinline)) HVX_Vector gdn_add_scaled_dot_f32(float * restrict dst, const HVX_Vector * restrict src,
HVX_Vector vscale, const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc = Q6_V_vzero();
const uint32_t epv = 128 / sizeof(float);
@@ -117,7 +146,7 @@ static inline HVX_Vector gdn_add_scaled_dot_f32(float * restrict dst, const HVX_
return hvx_vec_reduce_sum_f32(acc);
}
-static inline HVX_Vector gdn_mul_dot4_f32(float * restrict dst0, float * restrict dst1,
+static __attribute__((noinline)) HVX_Vector gdn_mul_dot4_f32(float * restrict dst0, float * restrict dst1,
float * restrict dst2, float * restrict dst3,
const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc0 = Q6_V_vzero();
@@ -175,7 +204,7 @@ static inline HVX_Vector gdn_mul_dot4_f32(float * restrict dst0, float * restric
return hvx_vec_reduce_sum_f32x4(acc);
}
-static inline HVX_Vector gdn_mul_scalar_dot4_f32(float * restrict dst0, float * restrict dst1,
+static __attribute__((noinline)) HVX_Vector gdn_mul_scalar_dot4_f32(float * restrict dst0, float * restrict dst1,
float * restrict dst2, float * restrict dst3,
HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc0 = Q6_V_vzero();
@@ -231,18 +260,18 @@ static inline HVX_Vector gdn_mul_scalar_dot4_f32(float * restrict dst0, float *
return hvx_vec_reduce_sum_f32x4(acc);
}
-static inline HVX_Vector gdn_add_scaled_dot4_f32(float * restrict dst0, float * restrict dst1,
+static __attribute__((noinline)) HVX_Vector gdn_add_scaled_dot4_f32(float * restrict dst0, float * restrict dst1,
float * restrict dst2, float * restrict dst3,
- const HVX_Vector * restrict src, const float * restrict scale,
+ const HVX_Vector * restrict src, HVX_Vector vscale,
const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc0 = Q6_V_vzero();
HVX_Vector acc1 = Q6_V_vzero();
HVX_Vector acc2 = Q6_V_vzero();
HVX_Vector acc3 = Q6_V_vzero();
- const HVX_Vector scale0 = hvx_vec_splat_f32(scale[0]);
- const HVX_Vector scale1 = hvx_vec_splat_f32(scale[1]);
- const HVX_Vector scale2 = hvx_vec_splat_f32(scale[2]);
- const HVX_Vector scale3 = hvx_vec_splat_f32(scale[3]);
+ const HVX_Vector scale0 = hvx_vec_repl_f32(vscale);
+ const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float)));
+ const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float)));
+ const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float)));
const uint32_t epv = 128 / sizeof(float);
const uint32_t nvec = n / epv;
@@ -294,7 +323,7 @@ static inline HVX_Vector gdn_add_scaled_dot4_f32(float * restrict dst0, float *
return hvx_vec_reduce_sum_f32x4(acc);
}
-static inline HVX_Vector gdn_mul_dot8_f32(float * restrict dst0, float * restrict dst1,
+static __attribute__((noinline)) HVX_Vector gdn_mul_dot8_f32(float * restrict dst0, float * restrict dst1,
float * restrict dst2, float * restrict dst3, float * restrict dst4,
float * restrict dst5, float * restrict dst6, float * restrict dst7,
const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) {
@@ -385,7 +414,7 @@ static inline HVX_Vector gdn_mul_dot8_f32(float * restrict dst0, float * restric
return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
}
-static inline HVX_Vector gdn_mul_scalar_dot8_f32(float * restrict dst0, float * restrict dst1,
+static __attribute__((noinline)) HVX_Vector gdn_mul_scalar_dot8_f32(float * restrict dst0, float * restrict dst1,
float * restrict dst2, float * restrict dst3, float * restrict dst4,
float * restrict dst5, float * restrict dst6, float * restrict dst7,
HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) {
@@ -474,10 +503,10 @@ static inline HVX_Vector gdn_mul_scalar_dot8_f32(float * restrict dst0, float *
return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
}
-static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * restrict dst1,
+static __attribute__((noinline)) HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * restrict dst1,
float * restrict dst2, float * restrict dst3, float * restrict dst4,
float * restrict dst5, float * restrict dst6, float * restrict dst7,
- const HVX_Vector * restrict src, const float * restrict scale,
+ const HVX_Vector * restrict src, HVX_Vector vscale,
const HVX_Vector * restrict dot, uint32_t n) {
HVX_Vector acc0 = Q6_V_vzero();
HVX_Vector acc1 = Q6_V_vzero();
@@ -487,14 +516,14 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float *
HVX_Vector acc5 = Q6_V_vzero();
HVX_Vector acc6 = Q6_V_vzero();
HVX_Vector acc7 = Q6_V_vzero();
- const HVX_Vector scale0 = hvx_vec_splat_f32(scale[0]);
- const HVX_Vector scale1 = hvx_vec_splat_f32(scale[1]);
- const HVX_Vector scale2 = hvx_vec_splat_f32(scale[2]);
- const HVX_Vector scale3 = hvx_vec_splat_f32(scale[3]);
- const HVX_Vector scale4 = hvx_vec_splat_f32(scale[4]);
- const HVX_Vector scale5 = hvx_vec_splat_f32(scale[5]);
- const HVX_Vector scale6 = hvx_vec_splat_f32(scale[6]);
- const HVX_Vector scale7 = hvx_vec_splat_f32(scale[7]);
+ const HVX_Vector scale0 = hvx_vec_repl_f32(vscale);
+ const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float)));
+ const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float)));
+ const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float)));
+ const HVX_Vector scale4 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 4 * sizeof(float)));
+ const HVX_Vector scale5 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 5 * sizeof(float)));
+ const HVX_Vector scale6 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 6 * sizeof(float)));
+ const HVX_Vector scale7 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 7 * sizeof(float)));
const uint32_t epv = 128 / sizeof(float);
const uint32_t nvec = n / epv;
@@ -574,218 +603,933 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float *
return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
}
+static __attribute__((noinline)) void gdn_add_scaled_f32(float * restrict dst,
+ const HVX_Vector * restrict src, HVX_Vector vscale, uint32_t n) {
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vd = hvx_vmemu(dst + i * epv);
+ HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[i], vscale));
+ hvx_vmemu(dst + i * epv) = out;
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector out = hvx_vec_add_f32_f32(hvx_vmemu(dst + off), hvx_vec_mul_f32_f32(src[nvec], vscale));
+ hvx_vec_store_u(dst + off, nloe * sizeof(float), out);
+ }
+}
+
+static __attribute__((noinline)) void gdn_add_scaled4_f32(float * restrict dst0, float * restrict dst1,
+ float * restrict dst2, float * restrict dst3,
+ const HVX_Vector * restrict src, HVX_Vector vscale, uint32_t n) {
+ const HVX_Vector scale0 = hvx_vec_repl_f32(vscale);
+ const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float)));
+ const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float)));
+ const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float)));
+
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vs = src[i];
+ hvx_vmemu(dst0 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst0 + i * epv), hvx_vec_mul_f32_f32(vs, scale0));
+ hvx_vmemu(dst1 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst1 + i * epv), hvx_vec_mul_f32_f32(vs, scale1));
+ hvx_vmemu(dst2 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst2 + i * epv), hvx_vec_mul_f32_f32(vs, scale2));
+ hvx_vmemu(dst3 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst3 + i * epv), hvx_vec_mul_f32_f32(vs, scale3));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector vs = src[nvec];
+ hvx_vec_store_u(dst0 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst0 + off), hvx_vec_mul_f32_f32(vs, scale0)));
+ hvx_vec_store_u(dst1 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst1 + off), hvx_vec_mul_f32_f32(vs, scale1)));
+ hvx_vec_store_u(dst2 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst2 + off), hvx_vec_mul_f32_f32(vs, scale2)));
+ hvx_vec_store_u(dst3 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst3 + off), hvx_vec_mul_f32_f32(vs, scale3)));
+ }
+}
+
+static __attribute__((noinline)) void gdn_add_scaled8_f32(float * restrict dst0, float * restrict dst1,
+ float * restrict dst2, float * restrict dst3, float * restrict dst4,
+ float * restrict dst5, float * restrict dst6, float * restrict dst7,
+ const HVX_Vector * restrict src, HVX_Vector vscale, uint32_t n) {
+ const HVX_Vector scale0 = hvx_vec_repl_f32(vscale);
+ const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float)));
+ const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float)));
+ const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float)));
+ const HVX_Vector scale4 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 4 * sizeof(float)));
+ const HVX_Vector scale5 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 5 * sizeof(float)));
+ const HVX_Vector scale6 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 6 * sizeof(float)));
+ const HVX_Vector scale7 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 7 * sizeof(float)));
+
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vs = src[i];
+ hvx_vmemu(dst0 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst0 + i * epv), hvx_vec_mul_f32_f32(vs, scale0));
+ hvx_vmemu(dst1 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst1 + i * epv), hvx_vec_mul_f32_f32(vs, scale1));
+ hvx_vmemu(dst2 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst2 + i * epv), hvx_vec_mul_f32_f32(vs, scale2));
+ hvx_vmemu(dst3 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst3 + i * epv), hvx_vec_mul_f32_f32(vs, scale3));
+ hvx_vmemu(dst4 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst4 + i * epv), hvx_vec_mul_f32_f32(vs, scale4));
+ hvx_vmemu(dst5 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst5 + i * epv), hvx_vec_mul_f32_f32(vs, scale5));
+ hvx_vmemu(dst6 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst6 + i * epv), hvx_vec_mul_f32_f32(vs, scale6));
+ hvx_vmemu(dst7 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst7 + i * epv), hvx_vec_mul_f32_f32(vs, scale7));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector vs = src[nvec];
+ hvx_vec_store_u(dst0 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst0 + off), hvx_vec_mul_f32_f32(vs, scale0)));
+ hvx_vec_store_u(dst1 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst1 + off), hvx_vec_mul_f32_f32(vs, scale1)));
+ hvx_vec_store_u(dst2 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst2 + off), hvx_vec_mul_f32_f32(vs, scale2)));
+ hvx_vec_store_u(dst3 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst3 + off), hvx_vec_mul_f32_f32(vs, scale3)));
+ hvx_vec_store_u(dst4 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst4 + off), hvx_vec_mul_f32_f32(vs, scale4)));
+ hvx_vec_store_u(dst5 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst5 + off), hvx_vec_mul_f32_f32(vs, scale5)));
+ hvx_vec_store_u(dst6 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst6 + off), hvx_vec_mul_f32_f32(vs, scale6)));
+ hvx_vec_store_u(dst7 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst7 + off), hvx_vec_mul_f32_f32(vs, scale7)));
+ }
+}
+
+static __attribute__((noinline)) HVX_Vector gdn_dot_f32(const float * restrict src,
+ const HVX_Vector * restrict dot, uint32_t n) {
+ HVX_Vector acc = Q6_V_vzero();
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(hvx_vmemu(src + i * epv), dot[i]));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+ acc = hvx_vec_add_f32_f32(acc, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src + off), dot[nvec]), zero));
+ }
+ return hvx_vec_reduce_sum_f32(acc);
+}
+
+static __attribute__((noinline)) HVX_Vector gdn_dot4_f32(const float * restrict src0, const float * restrict src1,
+ const float * restrict src2, const float * restrict src3,
+ const HVX_Vector * restrict dot, uint32_t n) {
+ HVX_Vector acc0 = Q6_V_vzero();
+ HVX_Vector acc1 = Q6_V_vzero();
+ HVX_Vector acc2 = Q6_V_vzero();
+ HVX_Vector acc3 = Q6_V_vzero();
+
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vdot = dot[i];
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + i * epv), vdot));
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + i * epv), vdot));
+ acc2 = hvx_vec_add_f32_f32(acc2, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + i * epv), vdot));
+ acc3 = hvx_vec_add_f32_f32(acc3, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + i * epv), vdot));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector vdot = dot[nvec];
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+ acc0 = hvx_vec_add_f32_f32(acc0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + off), vdot), zero));
+ acc1 = hvx_vec_add_f32_f32(acc1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + off), vdot), zero));
+ acc2 = hvx_vec_add_f32_f32(acc2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + off), vdot), zero));
+ acc3 = hvx_vec_add_f32_f32(acc3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + off), vdot), zero));
+ }
+
+ HVX_Vector_x4 acc = { .v = { acc0, acc1, acc2, acc3 } };
+ return hvx_vec_reduce_sum_f32x4(acc);
+}
+
+static __attribute__((noinline)) HVX_Vector gdn_dot8_f32(const float * restrict src0, const float * restrict src1,
+ const float * restrict src2, const float * restrict src3, const float * restrict src4,
+ const float * restrict src5, const float * restrict src6, const float * restrict src7,
+ const HVX_Vector * restrict dot, uint32_t n) {
+ HVX_Vector acc0 = Q6_V_vzero();
+ HVX_Vector acc1 = Q6_V_vzero();
+ HVX_Vector acc2 = Q6_V_vzero();
+ HVX_Vector acc3 = Q6_V_vzero();
+ HVX_Vector acc4 = Q6_V_vzero();
+ HVX_Vector acc5 = Q6_V_vzero();
+ HVX_Vector acc6 = Q6_V_vzero();
+ HVX_Vector acc7 = Q6_V_vzero();
+
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vdot = dot[i];
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + i * epv), vdot));
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + i * epv), vdot));
+ acc2 = hvx_vec_add_f32_f32(acc2, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + i * epv), vdot));
+ acc3 = hvx_vec_add_f32_f32(acc3, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + i * epv), vdot));
+ acc4 = hvx_vec_add_f32_f32(acc4, hvx_vec_mul_f32_f32(hvx_vmemu(src4 + i * epv), vdot));
+ acc5 = hvx_vec_add_f32_f32(acc5, hvx_vec_mul_f32_f32(hvx_vmemu(src5 + i * epv), vdot));
+ acc6 = hvx_vec_add_f32_f32(acc6, hvx_vec_mul_f32_f32(hvx_vmemu(src6 + i * epv), vdot));
+ acc7 = hvx_vec_add_f32_f32(acc7, hvx_vec_mul_f32_f32(hvx_vmemu(src7 + i * epv), vdot));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector vdot = dot[nvec];
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+ acc0 = hvx_vec_add_f32_f32(acc0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + off), vdot), zero));
+ acc1 = hvx_vec_add_f32_f32(acc1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + off), vdot), zero));
+ acc2 = hvx_vec_add_f32_f32(acc2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + off), vdot), zero));
+ acc3 = hvx_vec_add_f32_f32(acc3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + off), vdot), zero));
+ acc4 = hvx_vec_add_f32_f32(acc4, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src4 + off), vdot), zero));
+ acc5 = hvx_vec_add_f32_f32(acc5, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src5 + off), vdot), zero));
+ acc6 = hvx_vec_add_f32_f32(acc6, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src6 + off), vdot), zero));
+ acc7 = hvx_vec_add_f32_f32(acc7, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src7 + off), vdot), zero));
+ }
+
+ HVX_Vector_x4 accA = { .v = { acc0, acc1, acc2, acc3 } };
+ HVX_Vector_x4 accB = { .v = { acc4, acc5, acc6, acc7 } };
+ HVX_Vector rA = hvx_vec_reduce_sum_f32x4(accA);
+ HVX_Vector rB = hvx_vec_reduce_sum_f32x4(accB);
+ HVX_VectorPred q16 = Q6_Q_vsetq2_R(16);
+ return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
+}
+
+static __attribute__((noinline)) HVX_Vector gdn_scale_add_dot_f32(float * restrict dst, HVX_Vector vgate,
+ const HVX_Vector * restrict src, HVX_Vector vscale,
+ const HVX_Vector * restrict dot, uint32_t n) {
+ HVX_Vector acc = Q6_V_vzero();
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + i * epv), vgate);
+ HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[i], vscale));
+ hvx_vmemu(dst + i * epv) = out;
+ acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(out, dot[i]));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+ HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + off), vgate);
+ HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[nvec], vscale));
+ hvx_vec_store_u(dst + off, nloe * sizeof(float), out);
+ acc = hvx_vec_add_f32_f32(acc, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out, dot[nvec]), zero));
+ }
+ return hvx_vec_reduce_sum_f32(acc);
+}
+
+static __attribute__((noinline)) HVX_Vector gdn_scale_add_dot4_f32(float * restrict dst0, float * restrict dst1,
+ float * restrict dst2, float * restrict dst3, HVX_Vector vgate,
+ const HVX_Vector * restrict src, HVX_Vector vscale,
+ const HVX_Vector * restrict dot, uint32_t n) {
+ HVX_Vector acc0 = Q6_V_vzero();
+ HVX_Vector acc1 = Q6_V_vzero();
+ HVX_Vector acc2 = Q6_V_vzero();
+ HVX_Vector acc3 = Q6_V_vzero();
+ const HVX_Vector scale0 = hvx_vec_repl_f32(vscale);
+ const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float)));
+ const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float)));
+ const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float)));
+
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vs = src[i];
+ HVX_Vector vdot = dot[i];
+
+ HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale0));
+ HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale1));
+ HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale2));
+ HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale3));
+
+ hvx_vmemu(dst0 + i * epv) = out0;
+ hvx_vmemu(dst1 + i * epv) = out1;
+ hvx_vmemu(dst2 + i * epv) = out2;
+ hvx_vmemu(dst3 + i * epv) = out3;
+
+ acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(out0, vdot));
+ acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(out1, vdot));
+ acc2 = hvx_vec_add_f32_f32(acc2, hvx_vec_mul_f32_f32(out2, vdot));
+ acc3 = hvx_vec_add_f32_f32(acc3, hvx_vec_mul_f32_f32(out3, vdot));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector vs = src[nvec];
+ HVX_Vector vdot = dot[nvec];
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+
+ HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + off), vgate), hvx_vec_mul_f32_f32(vs, scale0));
+ HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + off), vgate), hvx_vec_mul_f32_f32(vs, scale1));
+ HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + off), vgate), hvx_vec_mul_f32_f32(vs, scale2));
+ HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + off), vgate), hvx_vec_mul_f32_f32(vs, scale3));
+
+ hvx_vec_store_u(dst0 + off, nloe * sizeof(float), out0);
+ hvx_vec_store_u(dst1 + off, nloe * sizeof(float), out1);
+ hvx_vec_store_u(dst2 + off, nloe * sizeof(float), out2);
+ hvx_vec_store_u(dst3 + off, nloe * sizeof(float), out3);
+
+ acc0 = hvx_vec_add_f32_f32(acc0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out0, vdot), zero));
+ acc1 = hvx_vec_add_f32_f32(acc1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out1, vdot), zero));
+ acc2 = hvx_vec_add_f32_f32(acc2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out2, vdot), zero));
+ acc3 = hvx_vec_add_f32_f32(acc3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out3, vdot), zero));
+ }
+
+ HVX_Vector_x4 acc = { .v = { acc0, acc1, acc2, acc3 } };
+ return hvx_vec_reduce_sum_f32x4(acc);
+}
+
+static __attribute__((noinline)) HVX_VectorPair gdn_scale_add_dual_dot_f32(float * restrict dst, HVX_Vector vgate,
+ const HVX_Vector * restrict src, HVX_Vector vscale,
+ const HVX_Vector * restrict dot_q, const HVX_Vector * restrict dot_k, uint32_t n) {
+ HVX_Vector acc_q = Q6_V_vzero();
+ HVX_Vector acc_k = Q6_V_vzero();
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + i * epv), vgate);
+ HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[i], vscale));
+ hvx_vmemu(dst + i * epv) = out;
+ acc_q = hvx_vec_add_f32_f32(acc_q, hvx_vec_mul_f32_f32(out, dot_q[i]));
+ acc_k = hvx_vec_add_f32_f32(acc_k, hvx_vec_mul_f32_f32(out, dot_k[i]));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+ HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + off), vgate);
+ HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[nvec], vscale));
+ hvx_vec_store_u(dst + off, nloe * sizeof(float), out);
+ acc_q = hvx_vec_add_f32_f32(acc_q, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out, dot_q[nvec]), zero));
+ acc_k = hvx_vec_add_f32_f32(acc_k, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out, dot_k[nvec]), zero));
+ }
+ return Q6_W_vcombine_VV(hvx_vec_reduce_sum_f32(acc_k), hvx_vec_reduce_sum_f32(acc_q));
+}
+
+static __attribute__((noinline)) HVX_VectorPair gdn_scale_add_dual_dot4_f32(float * restrict dst0, float * restrict dst1,
+ float * restrict dst2, float * restrict dst3, HVX_Vector vgate,
+ const HVX_Vector * restrict src, HVX_Vector vscale,
+ const HVX_Vector * restrict dot_q, const HVX_Vector * restrict dot_k, uint32_t n) {
+ HVX_Vector aq0 = Q6_V_vzero();
+ HVX_Vector aq1 = Q6_V_vzero();
+ HVX_Vector aq2 = Q6_V_vzero();
+ HVX_Vector aq3 = Q6_V_vzero();
+ HVX_Vector ak0 = Q6_V_vzero();
+ HVX_Vector ak1 = Q6_V_vzero();
+ HVX_Vector ak2 = Q6_V_vzero();
+ HVX_Vector ak3 = Q6_V_vzero();
+ const HVX_Vector scale0 = hvx_vec_repl_f32(vscale);
+ const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float)));
+ const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float)));
+ const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float)));
+
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ for (uint32_t i = 0; i < nvec; ++i) {
+ HVX_Vector vs = src[i];
+ HVX_Vector vq = dot_q[i];
+ HVX_Vector vk = dot_k[i];
+
+ HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale0));
+ HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale1));
+ HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale2));
+ HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale3));
+
+ hvx_vmemu(dst0 + i * epv) = out0;
+ hvx_vmemu(dst1 + i * epv) = out1;
+ hvx_vmemu(dst2 + i * epv) = out2;
+ hvx_vmemu(dst3 + i * epv) = out3;
+
+ aq0 = hvx_vec_add_f32_f32(aq0, hvx_vec_mul_f32_f32(out0, vq));
+ aq1 = hvx_vec_add_f32_f32(aq1, hvx_vec_mul_f32_f32(out1, vq));
+ aq2 = hvx_vec_add_f32_f32(aq2, hvx_vec_mul_f32_f32(out2, vq));
+ aq3 = hvx_vec_add_f32_f32(aq3, hvx_vec_mul_f32_f32(out3, vq));
+
+ ak0 = hvx_vec_add_f32_f32(ak0, hvx_vec_mul_f32_f32(out0, vk));
+ ak1 = hvx_vec_add_f32_f32(ak1, hvx_vec_mul_f32_f32(out1, vk));
+ ak2 = hvx_vec_add_f32_f32(ak2, hvx_vec_mul_f32_f32(out2, vk));
+ ak3 = hvx_vec_add_f32_f32(ak3, hvx_vec_mul_f32_f32(out3, vk));
+ }
+ if (nloe) {
+ const uint32_t off = nvec * epv;
+ HVX_Vector vs = src[nvec];
+ HVX_Vector vq = dot_q[nvec];
+ HVX_Vector vk = dot_k[nvec];
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float));
+ HVX_Vector zero = Q6_V_vzero();
+
+ HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + off), vgate), hvx_vec_mul_f32_f32(vs, scale0));
+ HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + off), vgate), hvx_vec_mul_f32_f32(vs, scale1));
+ HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + off), vgate), hvx_vec_mul_f32_f32(vs, scale2));
+ HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + off), vgate), hvx_vec_mul_f32_f32(vs, scale3));
+
+ hvx_vec_store_u(dst0 + off, nloe * sizeof(float), out0);
+ hvx_vec_store_u(dst1 + off, nloe * sizeof(float), out1);
+ hvx_vec_store_u(dst2 + off, nloe * sizeof(float), out2);
+ hvx_vec_store_u(dst3 + off, nloe * sizeof(float), out3);
+
+ aq0 = hvx_vec_add_f32_f32(aq0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out0, vq), zero));
+ aq1 = hvx_vec_add_f32_f32(aq1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out1, vq), zero));
+ aq2 = hvx_vec_add_f32_f32(aq2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out2, vq), zero));
+ aq3 = hvx_vec_add_f32_f32(aq3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out3, vq), zero));
+
+ ak0 = hvx_vec_add_f32_f32(ak0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out0, vk), zero));
+ ak1 = hvx_vec_add_f32_f32(ak1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out1, vk), zero));
+ ak2 = hvx_vec_add_f32_f32(ak2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out2, vk), zero));
+ ak3 = hvx_vec_add_f32_f32(ak3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out3, vk), zero));
+ }
+
+ HVX_Vector_x4 acc_q = { .v = { aq0, aq1, aq2, aq3 } };
+ HVX_Vector_x4 acc_k = { .v = { ak0, ak1, ak2, ak3 } };
+ return Q6_W_vcombine_VV(hvx_vec_reduce_sum_f32x4(acc_k), hvx_vec_reduce_sum_f32x4(acc_q));
+}
+
+static inline HVX_Vector gdn_clamp_f16_range_f32(HVX_Vector v, HVX_Vector v_min, HVX_Vector v_max) {
+ HVX_VectorPred p_gt = Q6_Q_vcmp_gt_VsfVsf(v, v_max);
+ v = Q6_V_vmux_QVV(p_gt, v_max, v);
+ HVX_VectorPred p_lt = Q6_Q_vcmp_gt_VsfVsf(v_min, v);
+ return Q6_V_vmux_QVV(p_lt, v_min, v);
+}
+
+static inline HVX_Vector hvx_vec_load_u(const void * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) ((uintptr_t) src & ~(uintptr_t) 127);
+ const uint32_t left_off = (uint32_t) ((uintptr_t) src & 127);
+ const uint32_t right_off = left_off + n;
+ HVX_Vector v = (right_off > 128) ? Q6_V_valign_VVR(vsrc[1], vsrc[0], left_off) : Q6_V_vror_VR(vsrc[0], left_off);
+ return Q6_V_vand_QV(Q6_Q_vsetq2_R(n), v);
+}
+
+static __attribute__((noinline)) void gdn_load_vec_f16_to_f32(HVX_Vector * restrict dst, const void * restrict src, uint32_t n) {
+ const __fp16 * restrict s16 = (const __fp16 *) src;
+ const uint32_t n64 = n / 64;
+ const uint32_t rem = n % 64;
+ #pragma clang loop unroll(disable)
+ for (uint32_t i = 0; i < n64; ++i) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32(hvx_vmemu(s16 + i * 64));
+ dst[2 * i + 0] = Q6_V_lo_W(p);
+ dst[2 * i + 1] = Q6_V_hi_W(p);
+ }
+ if (rem) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32(hvx_vec_load_u(s16 + n64 * 64, rem * sizeof(__fp16)));
+ dst[2 * n64 + 0] = Q6_V_lo_W(p);
+ dst[2 * n64 + 1] = Q6_V_hi_W(p);
+ }
+}
+
+static __attribute__((noinline)) void gdn_load_vec_f32(HVX_Vector * restrict dst, const void * restrict src, uint32_t n) {
+ const float * restrict s32 = (const float *) src;
+ const uint32_t n32 = n / 32;
+ const uint32_t rem = n % 32;
+ #pragma clang loop unroll(disable)
+ for (uint32_t i = 0; i < n32; ++i) {
+ dst[i] = hvx_vmemu(s32 + i * 32);
+ }
+ if (rem) {
+ dst[n32] = hvx_vec_load_u(s32 + n32 * 32, rem * sizeof(float));
+ }
+}
+
+static __attribute__((noinline)) void gdn_store_vec_f16(void * restrict dst, const HVX_Vector * restrict src, uint32_t n) {
+ __fp16 * restrict d16 = (__fp16 *) dst;
+ const HVX_Vector v_min = hvx_vec_splat_f32(-65504.0f);
+ const HVX_Vector v_max = hvx_vec_splat_f32(65504.0f);
+ const uint32_t n64 = n / 64;
+ const uint32_t rem = n % 64;
+ #pragma clang loop unroll(disable)
+ for (uint32_t i = 0; i < n64; ++i) {
+ HVX_Vector v0 = gdn_clamp_f16_range_f32(src[2 * i + 0], v_min, v_max);
+ HVX_Vector v1 = gdn_clamp_f16_range_f32(src[2 * i + 1], v_min, v_max);
+ hvx_vmemu(d16 + i * 64) = hvx_vec_f32_to_f16(v0, v1);
+ }
+ if (rem) {
+ HVX_Vector v0 = gdn_clamp_f16_range_f32(src[2 * n64 + 0], v_min, v_max);
+ HVX_Vector v1 = (rem > 32) ? gdn_clamp_f16_range_f32(src[2 * n64 + 1], v_min, v_max) : Q6_V_vzero();
+ hvx_vec_store_u(d16 + n64 * 64, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1));
+ }
+}
+
+static __attribute__((noinline)) void gdn_store_vec_f32(void * restrict dst, const HVX_Vector * restrict src, uint32_t n) {
+ float * restrict d32 = (float *) dst;
+ const uint32_t n32 = n / 32;
+ const uint32_t rem = n % 32;
+ #pragma clang loop unroll(disable)
+ for (uint32_t i = 0; i < n32; ++i) {
+ hvx_vmemu(d32 + i * 32) = src[i];
+ }
+ if (rem) {
+ hvx_vec_store_u(d32 + n32 * 32, rem * sizeof(float), src[n32]);
+ }
+}
+
+static __attribute__((noinline)) HVX_Vector gdn_vec_exp_f32(HVX_Vector v) {
+ return hvx_vec_exp_f32(v);
+}
+
static __attribute__((noinline)) void gdn_step_kda_f32(
+ const struct htp_gdn_context * gctx,
float * restrict s_work,
- float * restrict attn_out,
- const float * restrict q_t,
- const float * restrict k_t,
- const float * restrict v_t,
+ void * restrict attn_out,
+ const void * restrict q_t,
+ const void * restrict k_t,
+ const void * restrict v_t,
const float * restrict g_t,
- float beta_val,
+ const float * restrict beta_t,
+ HVX_Vector * restrict vtcm_scratch,
float scale,
- uint32_t S_v
+ uint32_t S_v,
+ const void * restrict k_next,
+ bool has_memory
) {
+ (void) k_next;
+ (void) has_memory;
const uint32_t epv = 128 / sizeof(float);
const uint32_t nvec = S_v / epv;
const uint32_t nloe = S_v % epv;
- HVX_Vector vq[4];
- HVX_Vector vk[4];
- HVX_Vector vg[4];
+ HVX_Vector * restrict vq = vtcm_scratch + 0;
+ HVX_Vector * restrict vk = vtcm_scratch + 4;
+ HVX_Vector * restrict vg = vtcm_scratch + 8;
+ float * restrict v_buf = (float *) (vtcm_scratch + 12);
+ float * restrict out_buf = (float *) (vtcm_scratch + 16);
+
+ gctx->load_q(vq, q_t, S_v);
+ gctx->load_k(vk, k_t, S_v);
+ gctx->load_v((HVX_Vector *) v_buf, v_t, S_v);
for (uint32_t i = 0; i < nvec; ++i) {
- vq[i] = hvx_vmemu(q_t + i * epv);
- vk[i] = hvx_vmemu(k_t + i * epv);
- vg[i] = hvx_vec_exp_f32(hvx_vmemu(g_t + i * epv));
+ vg[i] = gdn_vec_exp_f32(hvx_vmemu(g_t + i * epv));
}
if (nloe) {
- vq[nvec] = hvx_vmemu(q_t + nvec * epv);
- vk[nvec] = hvx_vmemu(k_t + nvec * epv);
- vg[nvec] = hvx_vec_exp_f32(hvx_vmemu(g_t + nvec * epv));
+ vg[nvec] = gdn_vec_exp_f32(hvx_vec_load_u(g_t + nvec * epv, nloe * sizeof(float)));
}
- const HVX_Vector vbeta = hvx_vec_splat_f32(beta_val);
+ const HVX_Vector vbeta = hvx_vec_repl_f32(hvx_vmemu(beta_t));
const HVX_Vector vscale = hvx_vec_splat_f32(scale);
- float delta[8] __attribute__((aligned(128)));
-
uint32_t j = 0;
for (; j + 8 <= S_v; j += 8) {
- float * row0 = s_work + (uint64_t) (j + 0) * S_v;
- float * row1 = s_work + (uint64_t) (j + 1) * S_v;
- float * row2 = s_work + (uint64_t) (j + 2) * S_v;
- float * row3 = s_work + (uint64_t) (j + 3) * S_v;
- float * row4 = s_work + (uint64_t) (j + 4) * S_v;
- float * row5 = s_work + (uint64_t) (j + 5) * S_v;
- float * row6 = s_work + (uint64_t) (j + 6) * S_v;
- float * row7 = s_work + (uint64_t) (j + 7) * S_v;
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+ float * row4 = s_work + (j + 4) * S_v;
+ float * row5 = s_work + (j + 5) * S_v;
+ float * row6 = s_work + (j + 6) * S_v;
+ float * row7 = s_work + (j + 7) * S_v;
HVX_Vector vsums = gdn_mul_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7,
vg, vk, S_v);
- HVX_Vector vv_t = hvx_vmemu(v_t + j);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums);
HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta);
- hvx_vec_store_u(delta, 8 * sizeof(float), vdelta);
HVX_Vector vattn = gdn_add_scaled_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7,
- vk, delta, vq, S_v);
+ vk, vdelta, vq, S_v);
HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale);
- hvx_vec_store_u(attn_out + j, 8 * sizeof(float), res_attn);
+ hvx_vec_store_u(out_buf + j, 8 * sizeof(float), res_attn);
}
for (; j + 4 <= S_v; j += 4) {
- float * row0 = s_work + (uint64_t) (j + 0) * S_v;
- float * row1 = s_work + (uint64_t) (j + 1) * S_v;
- float * row2 = s_work + (uint64_t) (j + 2) * S_v;
- float * row3 = s_work + (uint64_t) (j + 3) * S_v;
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
HVX_Vector vsums = gdn_mul_dot4_f32(row0, row1, row2, row3, vg, vk, S_v);
- HVX_Vector vv_t = hvx_vmemu(v_t + j);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums);
HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta);
- hvx_vec_store_u(delta, 4 * sizeof(float), vdelta);
- HVX_Vector vattn = gdn_add_scaled_dot4_f32(row0, row1, row2, row3, vk, delta, vq, S_v);
+ HVX_Vector vattn = gdn_add_scaled_dot4_f32(row0, row1, row2, row3, vk, vdelta, vq, S_v);
HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale);
- hvx_vec_store_u(attn_out + j, 4 * sizeof(float), res_attn);
+ hvx_vec_store_u(out_buf + j, 4 * sizeof(float), res_attn);
}
for (; j < S_v; ++j) {
- float * row = s_work + (uint64_t) j * S_v;
+ float * row = s_work + j * S_v;
HVX_Vector vsum = gdn_mul_dot_f32(row, vg, vk, S_v);
- HVX_Vector vv_t = hvx_vec_splat_f32(v_t[j]);
+ HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j));
HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsum), vbeta);
HVX_Vector vres = gdn_add_scaled_dot_f32(row, vk, vdj, vq, S_v);
- attn_out[j] = hvx_vec_get_f32(hvx_vec_mul_f32_f32(vres, vscale));
+ hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(vres, vscale));
}
+
+ gctx->store_out(attn_out, (const HVX_Vector *) out_buf, S_v);
}
static __attribute__((noinline)) void gdn_step_scalar_f32(
+ const struct htp_gdn_context * gctx,
float * restrict s_work,
- float * restrict attn_out,
- const float * restrict q_t,
- const float * restrict k_t,
- const float * restrict v_t,
+ void * restrict attn_out,
+ const void * restrict q_t,
+ const void * restrict k_t,
+ const void * restrict v_t,
const float * restrict g_t,
- float beta_val,
+ const float * restrict beta_t,
+ HVX_Vector * restrict vtcm_scratch,
float scale,
- uint32_t S_v
+ uint32_t S_v,
+ const void * restrict k_next,
+ bool has_memory
) {
- const uint32_t epv = 128 / sizeof(float);
- const uint32_t nvec = S_v / epv;
- const uint32_t nloe = S_v % epv;
-
- HVX_Vector vq[4];
- HVX_Vector vk[4];
+ HVX_Vector * restrict vq = vtcm_scratch + 0;
+ HVX_Vector * restrict vk = vtcm_scratch + 4;
+ HVX_Vector * restrict vk_next = vtcm_scratch + 8;
+ float * restrict v_buf = (float *) (vtcm_scratch + 12);
+ float * restrict out_buf = (float *) (vtcm_scratch + 16);
+ float * restrict mem_buf = (float *) (vtcm_scratch + 20);
+
+ gctx->load_q(vq, q_t, S_v);
+ gctx->load_k(vk, k_t, S_v);
+ gctx->load_v((HVX_Vector *) v_buf, v_t, S_v);
+
+ const HVX_Vector vgate = gdn_vec_exp_f32(hvx_vec_repl_f32(hvx_vmemu(g_t)));
+ const HVX_Vector vbeta = hvx_vec_repl_f32(hvx_vmemu(beta_t));
+ const HVX_Vector vscale = hvx_vec_splat_f32(scale);
- for (uint32_t i = 0; i < nvec; ++i) {
- vq[i] = hvx_vmemu(q_t + i * epv);
- vk[i] = hvx_vmemu(k_t + i * epv);
+ if (!has_memory) {
+ if (!k_next) {
+ uint32_t j = 0;
+ for (; j + 8 <= S_v; j += 8) {
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+ float * row4 = s_work + (j + 4) * S_v;
+ float * row5 = s_work + (j + 5) * S_v;
+ float * row6 = s_work + (j + 6) * S_v;
+ float * row7 = s_work + (j + 7) * S_v;
+
+ HVX_Vector vmem = gdn_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vk, S_v);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
+ HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+
+ HVX_Vector vattn0 = gdn_scale_add_dot4_f32(row0, row1, row2, row3, vgate, vk, vdelta, vq, S_v);
+ HVX_Vector vattn1 = gdn_scale_add_dot4_f32(row4, row5, row6, row7, vgate, vk,
+ Q6_V_vror_VR(vdelta, 4 * sizeof(float)), vq, S_v);
+ hvx_vec_store_u(out_buf + j + 0, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn0, vscale));
+ hvx_vec_store_u(out_buf + j + 4, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn1, vscale));
+ }
+ for (; j + 4 <= S_v; j += 4) {
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+
+ HVX_Vector vmem = gdn_dot4_f32(row0, row1, row2, row3, vk, S_v);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
+ HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+
+ HVX_Vector vattn = gdn_scale_add_dot4_f32(row0, row1, row2, row3, vgate, vk, vdelta, vq, S_v);
+ hvx_vec_store_u(out_buf + j, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn, vscale));
+ }
+ for (; j < S_v; ++j) {
+ float * row = s_work + j * S_v;
+ HVX_Vector vmem = gdn_dot_f32(row, vk, S_v);
+ HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j));
+ HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+ HVX_Vector vres = gdn_scale_add_dot_f32(row, vgate, vk, vdj, vq, S_v);
+ hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(vres, vscale));
+ }
+ gctx->store_out(attn_out, (const HVX_Vector *) out_buf, S_v);
+ return;
+ }
+
+ // Token 0 of multi-token tile: read-only Pass 1 to seed mem_buf
+ uint32_t j = 0;
+ for (; j + 8 <= S_v; j += 8) {
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+ float * row4 = s_work + (j + 4) * S_v;
+ float * row5 = s_work + (j + 5) * S_v;
+ float * row6 = s_work + (j + 6) * S_v;
+ float * row7 = s_work + (j + 7) * S_v;
+
+ HVX_Vector vmem = gdn_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vk, S_v);
+ hvx_vec_store_u(mem_buf + j, 8 * sizeof(float), vmem);
+ }
+ for (; j + 4 <= S_v; j += 4) {
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+
+ HVX_Vector vmem = gdn_dot4_f32(row0, row1, row2, row3, vk, S_v);
+ hvx_vec_store_u(mem_buf + j, 4 * sizeof(float), vmem);
+ }
+ for (; j < S_v; ++j) {
+ HVX_Vector vmem = gdn_dot_f32(s_work + j * S_v, vk, S_v);
+ hvx_vec_store_u(mem_buf + j, sizeof(float), vmem);
+ }
}
- if (nloe) {
- vq[nvec] = hvx_vmemu(q_t + nvec * epv);
- vk[nvec] = hvx_vmemu(k_t + nvec * epv);
+
+ if (k_next) {
+ gctx->load_k(vk_next, k_next, S_v);
+
+ uint32_t j = 0;
+ for (; j + 4 <= S_v; j += 4) {
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+
+ HVX_Vector vmem = hvx_vmemu(mem_buf + j);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
+ HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+
+ HVX_VectorPair vp = gdn_scale_add_dual_dot4_f32(row0, row1, row2, row3,
+ vgate, vk, vdelta, vq, vk_next, S_v);
+ hvx_vec_store_u(out_buf + j, 4 * sizeof(float), hvx_vec_mul_f32_f32(Q6_V_lo_W(vp), vscale));
+ hvx_vec_store_u(mem_buf + j, 4 * sizeof(float), Q6_V_hi_W(vp));
+ }
+ for (; j < S_v; ++j) {
+ float * row = s_work + j * S_v;
+ HVX_Vector vmem = hvx_vec_repl_f32(hvx_vmemu(mem_buf + j));
+ HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j));
+ HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+ HVX_VectorPair vp = gdn_scale_add_dual_dot_f32(row, vgate, vk, vdj, vq, vk_next, S_v);
+ hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(Q6_V_lo_W(vp), vscale));
+ hvx_vec_store_u(mem_buf + j, sizeof(float), Q6_V_hi_W(vp));
+ }
+ } else {
+ uint32_t j = 0;
+ for (; j + 4 <= S_v; j += 4) {
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+
+ HVX_Vector vmem = hvx_vmemu(mem_buf + j);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
+ HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+
+ HVX_Vector vattn = gdn_scale_add_dot4_f32(row0, row1, row2, row3, vgate, vk, vdelta, vq, S_v);
+ hvx_vec_store_u(out_buf + j, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn, vscale));
+ }
+ for (; j < S_v; ++j) {
+ float * row = s_work + j * S_v;
+ HVX_Vector vmem = hvx_vec_repl_f32(hvx_vmemu(mem_buf + j));
+ HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j));
+ HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta);
+ HVX_Vector vres = gdn_scale_add_dot_f32(row, vgate, vk, vdj, vq, S_v);
+ hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(vres, vscale));
+ }
}
- const HVX_Vector vgate = hvx_vec_exp_f32(hvx_vec_splat_f32(g_t[0]));
- const HVX_Vector vbeta = hvx_vec_splat_f32(beta_val);
- const HVX_Vector vscale = hvx_vec_splat_f32(scale);
+ gctx->store_out(attn_out, (const HVX_Vector *) out_buf, S_v);
+}
- float delta[8] __attribute__((aligned(128)));
+static inline uint32_t gdn_read_seq_idx(const void * ids_data, uint32_t ids_type, uint32_t iv3) {
+ if (!ids_data) {
+ return iv3;
+ }
+ return (ids_type == HTP_TYPE_I64)
+ ? (uint32_t) (((const int64_t *) ids_data)[iv3])
+ : (uint32_t) (((const int32_t *) ids_data)[iv3]);
+}
+
+static inline bool gdn_has_replay(const struct htp_ops_context * octx) {
+ return octx->src[6] != NULL && octx->src[7] != NULL;
+}
+
+static inline int gdn_prepare_aux_data(
+ struct htp_ops_context * octx,
+ const struct htp_tensor * t,
+ void ** out_buf
+) {
+ if (!t) {
+ *out_buf = NULL;
+ return HTP_STATUS_OK;
+ }
+ const size_t nbytes = hex_round_up(htp_tensor_nbytes(t), 128);
+ void * buf = (nbytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, nbytes);
+ if (!buf) {
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ if (htp_tensor_read(&octx->ctx->main_th, buf, nbytes, t) == 0) {
+ if (buf != octx->ctx->ddr_spad_base) {
+ free(buf);
+ }
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ *out_buf = buf;
+ return HTP_STATUS_OK;
+}
+
+static inline void gdn_dma_push_tile_inputs(
+ dma_queue * dma_q,
+ void * vtcm_q,
+ void * vtcm_k,
+ void * vtcm_v,
+ void * vtcm_g,
+ void * vtcm_b,
+ const struct htp_tensor * q,
+ const struct htp_tensor * k,
+ const struct htp_tensor * v,
+ const struct htp_tensor * g,
+ const struct htp_tensor * beta,
+ uint32_t iq3, uint32_t iq1,
+ uint32_t ik3, uint32_t ik1,
+ uint32_t iv3, uint32_t iv1,
+ uint32_t t_base,
+ uint32_t tile_tokens,
+ uint32_t q_row_bytes,
+ uint32_t k_row_bytes,
+ uint32_t v_row_bytes,
+ uint32_t g_row_bytes
+) {
+ const dma_addr_t q_dma = q->data + ((size_t) iq3 * q->nb[3] + (size_t) t_base * q->nb[2] + (size_t) iq1 * q->nb[1]);
+ const dma_addr_t k_dma = k->data + ((size_t) ik3 * k->nb[3] + (size_t) t_base * k->nb[2] + (size_t) ik1 * k->nb[1]);
+ const dma_addr_t v_dma = v->data + ((size_t) iv3 * v->nb[3] + (size_t) t_base * v->nb[2] + (size_t) iv1 * v->nb[1]);
+ const dma_addr_t g_dma = g->data + ((size_t) iv3 * g->nb[3] + (size_t) t_base * g->nb[2] + (size_t) iv1 * g->nb[1]);
+ const dma_addr_t b_dma = beta->data + ((size_t) iv3 * beta->nb[3] + (size_t) t_base * beta->nb[2] + (size_t) iv1 * beta->nb[1]);
+
+ dma_queue_push(dma_q, dma_make_data(vtcm_q, q_dma), q_row_bytes, q->nb[2], q_row_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(vtcm_k, k_dma), k_row_bytes, k->nb[2], k_row_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(vtcm_v, v_dma), v_row_bytes, v->nb[2], v_row_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(vtcm_g, g_dma), g_row_bytes, g->nb[2], g_row_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(vtcm_b, b_dma), sizeof(float), beta->nb[2], sizeof(float), tile_tokens);
+}
+
+static __attribute__((noinline)) void gdn_replay_step_f32(
+ float * restrict s_work,
+ const float * restrict k_t,
+ const float * restrict v_t,
+ const float * restrict g_t,
+ const float * restrict beta_t,
+ HVX_Vector * restrict vtcm_scratch,
+ bool kda,
+ uint32_t S_v
+) {
+ const uint32_t epv = 128 / sizeof(float);
+ const uint32_t nvec = S_v / epv;
+ const uint32_t nloe = S_v % epv;
+
+ HVX_Vector * restrict vk = vtcm_scratch + 0;
+ HVX_Vector * restrict vg = vtcm_scratch + 4;
+ float * restrict v_buf = (float *) (vtcm_scratch + 8);
+
+ gdn_load_vec_f32(vk, k_t, S_v);
+ gdn_load_vec_f32((HVX_Vector *) v_buf, v_t, S_v);
+
+ HVX_Vector vgate = Q6_V_vzero();
+ if (kda) {
+ for (uint32_t i = 0; i < nvec; ++i) {
+ vg[i] = gdn_vec_exp_f32(hvx_vmemu(g_t + i * epv));
+ }
+ if (nloe) {
+ vg[nvec] = gdn_vec_exp_f32(hvx_vec_load_u(g_t + nvec * epv, nloe * sizeof(float)));
+ }
+ } else {
+ vgate = gdn_vec_exp_f32(hvx_vec_repl_f32(hvx_vmemu(g_t)));
+ }
+
+ const HVX_Vector vbeta = hvx_vec_repl_f32(hvx_vmemu(beta_t));
uint32_t j = 0;
for (; j + 8 <= S_v; j += 8) {
- float * row0 = s_work + (uint64_t) (j + 0) * S_v;
- float * row1 = s_work + (uint64_t) (j + 1) * S_v;
- float * row2 = s_work + (uint64_t) (j + 2) * S_v;
- float * row3 = s_work + (uint64_t) (j + 3) * S_v;
- float * row4 = s_work + (uint64_t) (j + 4) * S_v;
- float * row5 = s_work + (uint64_t) (j + 5) * S_v;
- float * row6 = s_work + (uint64_t) (j + 6) * S_v;
- float * row7 = s_work + (uint64_t) (j + 7) * S_v;
-
- HVX_Vector vsums = gdn_mul_scalar_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7,
- vgate, vk, S_v);
-
- HVX_Vector vv_t = hvx_vmemu(v_t + j);
- HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums);
- HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta);
- hvx_vec_store_u(delta, 8 * sizeof(float), vdelta);
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
+ float * row4 = s_work + (j + 4) * S_v;
+ float * row5 = s_work + (j + 5) * S_v;
+ float * row6 = s_work + (j + 6) * S_v;
+ float * row7 = s_work + (j + 7) * S_v;
- HVX_Vector vattn = gdn_add_scaled_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7,
- vk, delta, vq, S_v);
+ HVX_Vector vsums = kda
+ ? gdn_mul_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vg, vk, S_v)
+ : gdn_mul_scalar_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vgate, vk, S_v);
- HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale);
- hvx_vec_store_u(attn_out + j, 8 * sizeof(float), res_attn);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
+ HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsums), vbeta);
+
+ gdn_add_scaled8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vk, vdelta, S_v);
}
for (; j + 4 <= S_v; j += 4) {
- float * row0 = s_work + (uint64_t) (j + 0) * S_v;
- float * row1 = s_work + (uint64_t) (j + 1) * S_v;
- float * row2 = s_work + (uint64_t) (j + 2) * S_v;
- float * row3 = s_work + (uint64_t) (j + 3) * S_v;
+ float * row0 = s_work + (j + 0) * S_v;
+ float * row1 = s_work + (j + 1) * S_v;
+ float * row2 = s_work + (j + 2) * S_v;
+ float * row3 = s_work + (j + 3) * S_v;
- HVX_Vector vsums = gdn_mul_scalar_dot4_f32(row0, row1, row2, row3, vgate, vk, S_v);
+ HVX_Vector vsums = kda
+ ? gdn_mul_dot4_f32(row0, row1, row2, row3, vg, vk, S_v)
+ : gdn_mul_scalar_dot4_f32(row0, row1, row2, row3, vgate, vk, S_v);
- HVX_Vector vv_t = hvx_vmemu(v_t + j);
- HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums);
- HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta);
- hvx_vec_store_u(delta, 4 * sizeof(float), vdelta);
-
- HVX_Vector vattn = gdn_add_scaled_dot4_f32(row0, row1, row2, row3, vk, delta, vq, S_v);
+ HVX_Vector vv_t = hvx_vmemu(v_buf + j);
+ HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsums), vbeta);
- HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale);
- hvx_vec_store_u(attn_out + j, 4 * sizeof(float), res_attn);
+ gdn_add_scaled4_f32(row0, row1, row2, row3, vk, vdelta, S_v);
}
for (; j < S_v; ++j) {
- float * row = s_work + (uint64_t) j * S_v;
- HVX_Vector vsum = gdn_mul_scalar_dot_f32(row, vgate, vk, S_v);
- HVX_Vector vv_t = hvx_vec_splat_f32(v_t[j]);
+ float * row = s_work + j * S_v;
+ HVX_Vector vsum = kda
+ ? gdn_mul_dot_f32(row, vg, vk, S_v)
+ : gdn_mul_scalar_dot_f32(row, vgate, vk, S_v);
+ HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j));
HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsum), vbeta);
- HVX_Vector vres = gdn_add_scaled_dot_f32(row, vk, vdj, vq, S_v);
- attn_out[j] = hvx_vec_get_f32(hvx_vec_mul_f32_f32(vres, vscale));
+ gdn_add_scaled_f32(row, vk, vdj, S_v);
}
}
-static inline void gdn_replay_f32(
+static void gdn_replay_f32(
const struct htp_ops_context * octx,
+ dma_queue * dma_q,
float * restrict s_work,
+ float * restrict k_buf,
+ float * restrict v_buf,
+ float * restrict g_buf,
+ float * restrict b_buf,
+ HVX_Vector * restrict vtcm_scratch,
+ uint32_t tile_cap,
uint32_t ik1,
uint32_t iv1,
uint32_t iv3,
+ uint32_t n_steps,
+ uint32_t n_pend,
bool kda,
- float scale,
uint32_t S_v
) {
const struct htp_tensor * pend_k = octx->src[6];
const struct htp_tensor * pend_v = octx->src[7];
const struct htp_tensor * pend_gb = octx->src[8];
- const struct htp_tensor * n_rep = octx->src[9];
- if (!pend_k) {
- return;
- }
+ const uint32_t vec_bytes = S_v * sizeof(float);
+ const uint32_t g_elems = kda ? S_v : 1;
+ const uint32_t g_bytes = g_elems * sizeof(float);
- const uint32_t n_pend = (uint32_t) octx->op_params[1];
- const int32_t raw_n_rep = ((const int32_t *) (uintptr_t) n_rep->data)[iv3];
- const uint32_t n_steps = raw_n_rep <= 0 ? 0 : MIN((uint32_t) raw_n_rep, n_pend);
- float unused_attn[128] __attribute__((aligned(128)));
+ const dma_addr_t pk_base = pend_k->data + (size_t) iv3 * pend_k->nb[3] + (size_t) ik1 * pend_k->nb[1];
+ const dma_addr_t pv_base = pend_v->data + (size_t) iv3 * pend_v->nb[3] + (size_t) iv1 * pend_v->nb[1];
+ const dma_addr_t pgb_base = pend_gb->data + (size_t) iv3 * pend_gb->nb[3] + (size_t) iv1 * pend_gb->nb[1];
- const uint8_t * pk = (const uint8_t *) (uintptr_t) pend_k->data + (uint64_t) iv3 * pend_k->nb[3] + (uint64_t) ik1 * pend_k->nb[1];
- const uint8_t * pv = (const uint8_t *) (uintptr_t) pend_v->data + (uint64_t) iv3 * pend_v->nb[3] + (uint64_t) iv1 * pend_v->nb[1];
- const uint8_t * pgb = (const uint8_t *) (uintptr_t) pend_gb->data + (uint64_t) iv3 * pend_gb->nb[3] + (uint64_t) iv1 * pend_gb->nb[1];
+ for (uint32_t t_base = 0; t_base < n_steps; t_base += tile_cap) {
+ const uint32_t tile_tokens = hex_smin(tile_cap, n_steps - t_base);
- for (uint32_t t = 0; t < n_steps; ++t) {
- const float * k_t = (const float *) (pk + (uint64_t) t * pend_k->nb[2]);
- const float * v_t = (const float *) (pv + (uint64_t) t * pend_v->nb[2]);
- const float * g_t = (const float *) (pgb + (uint64_t) t * pend_gb->nb[2]);
- const float beta_val = *(const float *) (pgb + (uint64_t) (n_pend + t) * pend_gb->nb[2]);
+ const dma_addr_t pk_dma = pk_base + (size_t) t_base * pend_k->nb[2];
+ const dma_addr_t pv_dma = pv_base + (size_t) t_base * pend_v->nb[2];
+ const dma_addr_t pg_dma = pgb_base + (size_t) t_base * pend_gb->nb[2];
+ const dma_addr_t pb_dma = pgb_base + (size_t) (n_pend + t_base) * pend_gb->nb[2];
- if (kda) {
- gdn_step_kda_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
- } else {
- gdn_step_scalar_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
+ dma_queue_push(dma_q, dma_make_data(k_buf, pk_dma), vec_bytes, pend_k->nb[2], vec_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(v_buf, pv_dma), vec_bytes, pend_v->nb[2], vec_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(g_buf, pg_dma), g_bytes, pend_gb->nb[2], g_bytes, tile_tokens);
+ dma_queue_push(dma_q, dma_make_data(b_buf, pb_dma), sizeof(float), pend_gb->nb[2], sizeof(float), tile_tokens);
+ for (int d = 0; d < 4; ++d) {
+ dma_queue_pop(dma_q);
+ }
+
+ for (uint32_t t_local = 0; t_local < tile_tokens; ++t_local) {
+ gdn_replay_step_f32(
+ s_work,
+ k_buf + (size_t) t_local * S_v,
+ v_buf + (size_t) t_local * S_v,
+ g_buf + (size_t) t_local * g_elems,
+ b_buf + t_local,
+ vtcm_scratch, kda, S_v);
}
}
}
@@ -816,14 +1560,35 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
const struct htp_tensor * dst_cache = octx->dsts[1];
const float scale = kparams->scale;
- float * dst_base = (float *) (uintptr_t) dst->data;
- float * state_out_base = dst_cache ? (float *) (uintptr_t) dst_cache->data : (dst_base + S_v * H * n_tokens * n_seqs);
+
+ const uint32_t q_row_bytes = S_v * ((q->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t k_row_bytes = S_v * ((k->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t v_row_bytes = S_v * ((v->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t g_row_bytes = (kparams->kda ? S_v : 1) * sizeof(float);
+ const uint32_t out_row_bytes = S_v * ((dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t dst_row_stride = H * out_row_bytes;
dma_queue * dma_q = th->dma_q;
const struct htp_gdn_vtcm_layout * layout = &gctx->layout;
- float * s_work[2];
- s_work[0] = (float *) (gctx->vtcm_base + layout->bytes_per_hvx * ith);
- s_work[1] = s_work[0] + layout->state_aligned / sizeof(float);
+ uint8_t * th_vtcm = gctx->vtcm_base + layout->bytes_per_hvx * ith;
+ float * s_work_curr = (float *) th_vtcm;
+ HVX_Vector * vtcm_scratch = (HVX_Vector *) (th_vtcm + layout->off_scratch);
+
+ uint8_t * q_spad[2];
+ uint8_t * k_spad[2];
+ uint8_t * v_spad[2];
+ uint8_t * g_spad[2];
+ uint8_t * o_spad[2];
+ float * beta_spad[2];
+ for (int b = 0; b < 2; ++b) {
+ uint8_t * spad = th_vtcm + layout->off_spad + (size_t) b * layout->spad_stride;
+ q_spad[b] = spad + 0 * layout->tile_vec_bytes;
+ k_spad[b] = spad + 1 * layout->tile_vec_bytes;
+ v_spad[b] = spad + 2 * layout->tile_vec_bytes;
+ g_spad[b] = spad + 3 * layout->tile_vec_bytes;
+ o_spad[b] = spad + 4 * layout->tile_vec_bytes;
+ beta_spad[b] = (float *) (spad + 5 * layout->tile_vec_bytes);
+ }
const struct fastdiv_values * fd_H = &kparams->div_H;
const struct fastdiv_values * fd_q1 = &kparams->div_q1;
@@ -831,44 +1596,17 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
const struct fastdiv_values * fd_rq3 = &kparams->div_rq3;
const struct fastdiv_values * fd_rk3 = &kparams->div_rk3;
- const uint32_t state_seq_stride = kparams->state_seq_stride;
- const uint64_t state_size_per_snap = (uint64_t) kparams->state_size_per_snap;
- const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_tokens * n_seqs * sizeof(float));
- const bool keep = octx->src[6] && octx->op_params[2] != 0;
-
- uint32_t ir_prefetch = gctx->row_start + ith;
- int spad_idx = 0;
-
- // Prefetch preamble (up to 2 steps)
- for (int step = 0; step < 2 && ir_prefetch < row_end; step++) {
- const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H);
- const uint32_t piv3 = fastdiv(ir_prefetch, fd_H);
- dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float);
- dma_addr_t ps_out = state_out_dma_base + ((uint64_t) piv3 * H + piv1) * S_v * S_v * sizeof(float);
-
- // Push dummy write-back
- dma_queue_push(dma_q, dma_make_data(ps_out, s_work[spad_idx]),
- S_v * sizeof(float), S_v * sizeof(float),
- S_v * sizeof(float), 0);
-
- // Push fetch
- dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in),
- S_v * sizeof(float), S_v * sizeof(float),
- S_v * sizeof(float), S_v);
-
- ir_prefetch += nth;
- spad_idx ^= 1;
- }
+ const uint32_t state_seq_stride = kparams->state_seq_stride;
+ const uint32_t state_size_per_snap = kparams->state_size_per_snap;
+ const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + (size_t) S_v * H * n_tokens * n_seqs * sizeof(float));
+ const bool replay = gctx->replay;
+ const bool keep = gctx->keep;
struct htp_thread_trace * tr = th->trace;
+ const gdn_step_fn_t step_fn = gctx->step_fn;
+ const uint32_t n_tiles = (n_tokens + HTP_GDN_TOKEN_TILE - 1) / HTP_GDN_TOKEN_TILE;
- int curr_spad_idx = 0;
for (uint32_t ir = gctx->row_start + ith; ir < row_end; ir += nth) {
- dma_queue_pop(dma_q);
- dma_queue_pop(dma_q);
-
- float * s_work_curr = s_work[curr_spad_idx];
-
const uint32_t iv1 = fastmodulo(ir, H, fd_H);
const uint32_t iv3 = fastdiv(ir, fd_H);
@@ -876,64 +1614,118 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
const uint32_t ik1 = fastmodulo(iv1, k->ne[1], fd_k1);
const uint32_t iq3 = fastdiv(iv3, fd_rq3);
const uint32_t ik3 = fastdiv(iv3, fd_rk3);
+ const uint32_t is3 = gdn_read_seq_idx(gctx->ids_data, gctx->ids_type, iv3);
- dma_addr_t s_out = state_out_dma_base + ((uint64_t) iv3 * H + iv1) * S_v * S_v * sizeof(float);
- float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v;
+ const dma_addr_t s_in = state->data + ((size_t) is3 * state_seq_stride + (size_t) iv1 * S_v * S_v) * sizeof(float);
+ const dma_addr_t s_out = state_out_dma_base + ((size_t) iv3 * H + iv1) * S_v * S_v * sizeof(float);
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
- if (keep) {
- hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
+ dma_queue_push(dma_q, dma_make_data(s_work_curr, s_in),
+ S_v * sizeof(float), S_v * sizeof(float),
+ S_v * sizeof(float), S_v);
+ dma_queue_pop(dma_q);
+
+ if (replay) {
+ const int32_t raw_n_rep = gctx->n_rep_data[iv3];
+ const uint32_t n_steps = raw_n_rep <= 0 ? 0 : hex_smin((uint32_t) raw_n_rep, gctx->n_pend);
+ if (n_steps > 0) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ gdn_replay_f32(octx, dma_q, s_work_curr,
+ (float *) k_spad[0], (float *) v_spad[0], (float *) g_spad[0], beta_spad[0],
+ vtcm_scratch, HTP_GDN_TOKEN_TILE,
+ ik1, iv1, iv3, n_steps, gctx->n_pend,
+ kparams->kda != 0, S_v);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ }
+ if (keep) {
+ dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
+ S_v * sizeof(float), S_v * sizeof(float),
+ S_v * sizeof(float), S_v);
+ dma_queue_pop(dma_q);
+ }
}
- for (uint32_t t = 0; t < n_tokens; ++t) {
- const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data +
- (uint64_t) iq3 * q->nb[3] + (uint64_t) t * q->nb[2] + (uint64_t) iq1 * q->nb[1]);
- const float * k_t = (const float *) ((const uint8_t *) (uintptr_t) k->data +
- (uint64_t) ik3 * k->nb[3] + (uint64_t) t * k->nb[2] + (uint64_t) ik1 * k->nb[1]);
- const float * v_t = (const float *) ((const uint8_t *) (uintptr_t) v->data +
- (uint64_t) iv3 * v->nb[3] + (uint64_t) t * v->nb[2] + (uint64_t) iv1 * v->nb[1]);
- const float * g_t = (const float *) ((const uint8_t *) (uintptr_t) g->data +
- (uint64_t) iv3 * g->nb[3] + (uint64_t) t * g->nb[2] + (uint64_t) iv1 * g->nb[1]);
- const float beta_val = *(const float *) ((const uint8_t *) (uintptr_t) beta->data +
- (uint64_t) iv3 * beta->nb[3] + (uint64_t) t * beta->nb[2] + (uint64_t) iv1 * beta->nb[1]);
-
- if (kparams->kda) {
- gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
- } else {
- gdn_step_scalar_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
+
+ const uint32_t first_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens);
+ gdn_dma_push_tile_inputs(dma_q, q_spad[0], k_spad[0], v_spad[0], g_spad[0], beta_spad[0],
+ q, k, v, g, beta, iq3, iq1, ik3, ik1, iv3, iv1,
+ 0, first_tokens, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes);
+
+ for (uint32_t tile_idx = 0; tile_idx < n_tiles; ++tile_idx) {
+ const uint32_t curr_buf = tile_idx & 1;
+ const uint32_t next_buf = curr_buf ^ 1;
+ const uint32_t t_base = tile_idx * HTP_GDN_TOKEN_TILE;
+ const uint32_t tile_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens - t_base);
+
+ for (int d = 0; d < 5; ++d) {
+ dma_queue_pop(dma_q);
+ }
+ if (tile_idx > 0) {
+ dma_queue_pop(dma_q);
+ }
+
+ if (K <= 1 && tile_idx + 1 < n_tiles) {
+ const uint32_t next_t_base = (tile_idx + 1) * HTP_GDN_TOKEN_TILE;
+ const uint32_t next_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens - next_t_base);
+ gdn_dma_push_tile_inputs(dma_q, q_spad[next_buf], k_spad[next_buf], v_spad[next_buf], g_spad[next_buf], beta_spad[next_buf],
+ q, k, v, g, beta, iq3, iq1, ik3, ik1, iv3, iv1,
+ next_t_base, next_tokens, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes);
}
- if (K > 1) {
- const int64_t target_slot = (int64_t) n_tokens - 1 - (int64_t) t;
- if (target_slot > 0 && target_slot < (int64_t) K) {
- float * curr_state_o = state_out_base + (uint64_t) target_slot * state_size_per_snap + ((uint64_t) iv3 * H + iv1) * S_v * S_v;
- hvx_copy_f32_uu((uint8_t *) curr_state_o, (const uint8_t *) s_work_curr, S_v * S_v);
+ const uint8_t * q_curr = q_spad[curr_buf];
+ const uint8_t * k_curr = k_spad[curr_buf];
+ const uint8_t * v_curr = v_spad[curr_buf];
+ const uint8_t * g_curr = g_spad[curr_buf];
+ const float * b_curr = beta_spad[curr_buf];
+ uint8_t * o_curr = o_spad[curr_buf];
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ for (uint32_t t_local = 0; t_local < tile_tokens; ++t_local) {
+ const void * k_next = (t_local + 1 < tile_tokens) ? (k_curr + (t_local + 1) * k_row_bytes) : NULL;
+ step_fn(gctx, s_work_curr,
+ o_curr + t_local * out_row_bytes,
+ q_curr + t_local * q_row_bytes,
+ k_curr + t_local * k_row_bytes,
+ v_curr + t_local * v_row_bytes,
+ (const float *) (g_curr + t_local * g_row_bytes),
+ b_curr + t_local,
+ vtcm_scratch, scale, S_v, k_next, t_local > 0);
+
+ if (K > 1) {
+ const uint32_t t = t_base + t_local;
+ const int32_t target_slot = (int32_t) n_tokens - 1 - (int32_t) t;
+ if (target_slot > 0 && target_slot < (int32_t) K) {
+ const dma_addr_t snap_dma = state_out_dma_base +
+ ((size_t) target_slot * state_size_per_snap + ((size_t) iv3 * H + iv1) * S_v * S_v) * sizeof(float);
+ dma_queue_push(dma_q, dma_make_data(snap_dma, s_work_curr),
+ S_v * sizeof(float), S_v * sizeof(float),
+ S_v * sizeof(float), S_v);
+ dma_queue_pop(dma_q);
+ }
}
}
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+
+ if (K > 1 && tile_idx + 1 < n_tiles) {
+ const uint32_t next_t_base = (tile_idx + 1) * HTP_GDN_TOKEN_TILE;
+ const uint32_t next_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens - next_t_base);
+ gdn_dma_push_tile_inputs(dma_q, q_spad[next_buf], k_spad[next_buf], v_spad[next_buf], g_spad[next_buf], beta_spad[next_buf],
+ q, k, v, g, beta, iq3, iq1, ik3, ik1, iv3, iv1,
+ next_t_base, next_tokens, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes);
+ }
- attn_data += (uint64_t) S_v * H;
+ const dma_addr_t attn_out_dma = dst->data +
+ ((size_t) (iv3 * n_tokens + t_base) * H + iv1) * out_row_bytes;
+ dma_queue_push(dma_q, dma_make_data(attn_out_dma, o_curr),
+ dst_row_stride, out_row_bytes, out_row_bytes, tile_tokens);
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
-
- dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
- S_v * sizeof(float), S_v * sizeof(float),
- S_v * sizeof(float), keep ? 0 : S_v);
- // Prefetch next block (if any)
- if (ir_prefetch < row_end) {
- const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H);
- const uint32_t piv3 = fastdiv(ir_prefetch, fd_H);
- dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float);
+ dma_queue_pop(dma_q);
- dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in),
+ if (!keep) {
+ dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
-
- ir_prefetch += nth;
- spad_idx ^= 1;
+ dma_queue_pop(dma_q);
}
-
- curr_spad_idx ^= 1;
}
dma_queue_flush(dma_q);
}
@@ -962,13 +1754,36 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
const struct htp_tensor * dst_cache = octx->dsts[1];
const float scale = kparams->scale;
- float * dst_base = (float *) (uintptr_t) dst->data;
+
+ const uint32_t q_row_bytes = S_v * ((q->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t k_row_bytes = S_v * ((k->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t v_row_bytes = S_v * ((v->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t g_row_bytes = (kparams->kda ? S_v : 1) * sizeof(float);
+ const uint32_t out_row_bytes = S_v * ((dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
dma_queue * dma_q = th->dma_q;
const struct htp_gdn_vtcm_layout * layout = &gctx->layout;
+ uint8_t * th_vtcm = gctx->vtcm_base + layout->bytes_per_hvx * ith;
float * s_work[2];
- s_work[0] = (float *) (gctx->vtcm_base + layout->bytes_per_hvx * ith);
- s_work[1] = s_work[0] + layout->state_aligned / sizeof(float);
+ s_work[0] = (float *) th_vtcm;
+ s_work[1] = (float *) (th_vtcm + layout->state_aligned);
+ HVX_Vector * vtcm_scratch = (HVX_Vector *) (th_vtcm + layout->off_scratch);
+
+ uint8_t * q_spad[2];
+ uint8_t * k_spad[2];
+ uint8_t * v_spad[2];
+ uint8_t * g_spad[2];
+ uint8_t * o_spad[2];
+ float * beta_spad[2];
+ for (int b = 0; b < 2; ++b) {
+ uint8_t * spad = th_vtcm + layout->off_spad + (size_t) b * layout->spad_stride;
+ q_spad[b] = spad + 0 * layout->tile_vec_bytes;
+ k_spad[b] = spad + 1 * layout->tile_vec_bytes;
+ v_spad[b] = spad + 2 * layout->tile_vec_bytes;
+ g_spad[b] = spad + 3 * layout->tile_vec_bytes;
+ o_spad[b] = spad + 4 * layout->tile_vec_bytes;
+ beta_spad[b] = (float *) (spad + 5 * layout->tile_vec_bytes);
+ }
const struct fastdiv_values * fd_H = &kparams->div_H;
const struct fastdiv_values * fd_q1 = &kparams->div_q1;
@@ -977,8 +1792,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
const struct fastdiv_values * fd_rk3 = &kparams->div_rk3;
const uint32_t state_seq_stride = kparams->state_seq_stride;
- const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_seqs * sizeof(float));
- const bool keep = octx->src[6] && octx->op_params[2] != 0;
+ const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + (size_t) S_v * H * n_seqs * sizeof(float));
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -987,79 +1801,78 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
for (int step = 0; step < 2 && ir_prefetch < row_end; step++) {
const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H);
const uint32_t piv3 = fastdiv(ir_prefetch, fd_H);
- dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float);
- dma_addr_t ps_out = state_out_dma_base + ((uint64_t) piv3 * H + piv1) * S_v * S_v * sizeof(float);
+ const uint32_t piq1 = fastmodulo(piv1, q->ne[1], fd_q1);
+ const uint32_t pik1 = fastmodulo(piv1, k->ne[1], fd_k1);
+ const uint32_t piq3 = fastdiv(piv3, fd_rq3);
+ const uint32_t pik3 = fastdiv(piv3, fd_rk3);
+ const uint32_t pis3 = gdn_read_seq_idx(gctx->ids_data, gctx->ids_type, piv3);
+
+ const dma_addr_t ps_in = state->data + ((size_t) pis3 * state_seq_stride + (size_t) piv1 * S_v * S_v) * sizeof(float);
+ const dma_addr_t ps_out = state_out_dma_base + ((size_t) piv3 * H + piv1) * S_v * S_v * sizeof(float);
+ const dma_addr_t po_out = dst->data + ((size_t) piv3 * H + piv1) * out_row_bytes;
- // Push dummy write-back
dma_queue_push(dma_q, dma_make_data(ps_out, s_work[spad_idx]),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), 0);
+ dma_queue_push(dma_q, dma_make_data(po_out, o_spad[spad_idx]),
+ out_row_bytes, out_row_bytes, out_row_bytes, 0);
- // Push fetch
dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
+ gdn_dma_push_tile_inputs(dma_q, q_spad[spad_idx], k_spad[spad_idx], v_spad[spad_idx], g_spad[spad_idx], beta_spad[spad_idx],
+ q, k, v, g, beta, piq3, piq1, pik3, pik1, piv3, piv1,
+ 0, 1, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes);
ir_prefetch += nth;
spad_idx ^= 1;
}
struct htp_thread_trace * tr = th->trace;
+ const gdn_step_fn_t step_fn = gctx->step_fn;
int curr_spad_idx = 0;
for (uint32_t ir = gctx->row_start + ith; ir < row_end; ir += nth) {
- dma_queue_pop(dma_q);
- dma_queue_pop(dma_q);
-
- float * s_work_curr = s_work[curr_spad_idx];
+ for (int d = 0; d < 8; ++d) {
+ dma_queue_pop(dma_q);
+ }
const uint32_t iv1 = fastmodulo(ir, H, fd_H);
const uint32_t iv3 = fastdiv(ir, fd_H);
- const uint32_t iq1 = fastmodulo(iv1, q->ne[1], fd_q1);
- const uint32_t ik1 = fastmodulo(iv1, k->ne[1], fd_k1);
- const uint32_t iq3 = fastdiv(iv3, fd_rq3);
- const uint32_t ik3 = fastdiv(iv3, fd_rk3);
-
- dma_addr_t s_out = state_out_dma_base + ((uint64_t) iv3 * H + iv1) * S_v * S_v * sizeof(float);
- float * attn_data = dst_base + ((uint64_t) iv3 * H + iv1) * S_v;
-
- const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data +
- (uint64_t) iq3 * q->nb[3] + (uint64_t) iq1 * q->nb[1]);
- const float * k_t = (const float *) ((const uint8_t *) (uintptr_t) k->data +
- (uint64_t) ik3 * k->nb[3] + (uint64_t) ik1 * k->nb[1]);
- const float * v_t = (const float *) ((const uint8_t *) (uintptr_t) v->data +
- (uint64_t) iv3 * v->nb[3] + (uint64_t) iv1 * v->nb[1]);
- const float * g_t = (const float *) ((const uint8_t *) (uintptr_t) g->data +
- (uint64_t) iv3 * g->nb[3] + (uint64_t) iv1 * g->nb[1]);
- const float beta_val = *(const float *) ((const uint8_t *) (uintptr_t) beta->data +
- (uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]);
+ const dma_addr_t s_out = state_out_dma_base + ((size_t) iv3 * H + iv1) * S_v * S_v * sizeof(float);
+ const dma_addr_t po_out = dst->data + ((size_t) iv3 * H + iv1) * out_row_bytes;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
- if (keep) {
- hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
- }
- if (kparams->kda) {
- gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
- } else {
- gdn_step_scalar_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
- }
+ step_fn(gctx, s_work[curr_spad_idx], o_spad[curr_spad_idx],
+ q_spad[curr_spad_idx], k_spad[curr_spad_idx], v_spad[curr_spad_idx],
+ (const float *) g_spad[curr_spad_idx], beta_spad[curr_spad_idx],
+ vtcm_scratch, scale, S_v, NULL, false);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
+ dma_queue_push(dma_q, dma_make_data(s_out, s_work[curr_spad_idx]),
S_v * sizeof(float), S_v * sizeof(float),
- S_v * sizeof(float), keep ? 0 : S_v);
+ S_v * sizeof(float), S_v);
+ dma_queue_push(dma_q, dma_make_data(po_out, o_spad[curr_spad_idx]),
+ out_row_bytes, out_row_bytes, out_row_bytes, 1);
- // Prefetch next block (if any)
if (ir_prefetch < row_end) {
const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H);
const uint32_t piv3 = fastdiv(ir_prefetch, fd_H);
- dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float);
+ const uint32_t piq1 = fastmodulo(piv1, q->ne[1], fd_q1);
+ const uint32_t pik1 = fastmodulo(piv1, k->ne[1], fd_k1);
+ const uint32_t piq3 = fastdiv(piv3, fd_rq3);
+ const uint32_t pik3 = fastdiv(piv3, fd_rk3);
+ const uint32_t pis3 = gdn_read_seq_idx(gctx->ids_data, gctx->ids_type, piv3);
+
+ const dma_addr_t ps_in = state->data + ((size_t) pis3 * state_seq_stride + (size_t) piv1 * S_v * S_v) * sizeof(float);
dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in),
S_v * sizeof(float), S_v * sizeof(float),
S_v * sizeof(float), S_v);
+ gdn_dma_push_tile_inputs(dma_q, q_spad[spad_idx], k_spad[spad_idx], v_spad[spad_idx], g_spad[spad_idx], beta_spad[spad_idx],
+ q, k, v, g, beta, piq3, piq1, pik3, pik1, piv3, piv1,
+ 0, 1, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes);
ir_prefetch += nth;
spad_idx ^= 1;
@@ -1070,56 +1883,205 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
dma_queue_flush(dma_q);
}
-struct htp_gdn_hmx_gemm_task {
- const __fp16 * row_tiles;
- const __fp16 * col_tiles;
- __fp16 * out_tiles;
- uint32_t n_row_tiles;
- uint32_t n_col_tiles;
- uint32_t n_dot_tiles;
- uint32_t dot_stride;
- uint8_t * hmx_scales;
-};
+struct htp_gdn_head_ptrs {
+ float * s_state;
+ __fp16 * s_col_tiles;
+ __fp16 * s_update_tiles;
+
+ float * q_f32[2];
+ float * k_f32[2];
+ float * v_f32[2];
+ float * g_f32[2];
+ float * b_f32[2];
+ float * o_f32[2];
+
+ __fp16 * k_f16;
+
+ __fp16 * q_row_tiles;
+ __fp16 * q_prime_row_tiles;
+ __fp16 * k_row_tiles;
+ __fp16 * k_col_tiles;
+ __fp16 * k_prime_row_tiles;
+ __fp16 * k_col_tiles_64x128[2];
+ __fp16 * kk_tiles;
+ __fp16 * qk_tiles;
+ __fp16 * v_inter_tiles;
+ __fp16 * o_inter_tiles;
+ __fp16 * inv_row_tiles;
+ __fp16 * a_row_tiles;
+ __fp16 * v_prime_col_tiles;
+ __fp16 * delta_tiles;
+ __fp16 * o_intra_tiles;
+ __fp16 * d_row_tiles;
+
+ __fp16 * gamma;
+ float * lambda_init[2];
+ __fp16 * lambda_init_f16;
+ __fp16 * decay_m;
+ __fp16 * decay_a;
+
+ HVX_Vector * rows_kk;
+ HVX_Vector * rows_qk;
+ HVX_Vector * rows_inv;
+ HVX_Vector * rows_a;
-static void htp_gdn_hmx_gemm_worker(const htp_thread_t * th, void * data) {
- struct htp_gdn_hmx_gemm_task * task = (struct htp_gdn_hmx_gemm_task *) data;
- asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)task->hmx_scales));
+ HVX_Vector * vtcm_m;
+ HVX_Vector * vtcm_tmp;
+
+ uint32_t iv1;
+ uint32_t iv3;
+ uint32_t iq1;
+ uint32_t ik1;
+ uint32_t iq3;
+ uint32_t ik3;
+ dma_addr_t state_in_dma;
+ dma_addr_t state_out_dma;
+};
- const size_t dot_stride = task->dot_stride;
- for (uint32_t r = 0; r < task->n_row_tiles; ++r) {
- const __fp16 * r_tiles = task->row_tiles + r * dot_stride;
- const __fp16 * c_tiles = task->col_tiles;
- __fp16 * o_tile = task->out_tiles + r * task->n_col_tiles * HMX_FP16_TILE_N_ELMS;
+struct htp_gdn_batch_context {
+ struct htp_gdn_head_ptrs * heads;
+ float * vtcm_g_raw[2];
+ float * vtcm_b_raw[2];
+ uint8_t * hmx_scales;
+ const int32_t * n_rep_data;
+ uint32_t n_pend;
+ bool replay;
+ bool keep;
+ uint32_t head_in_seq;
+ uint32_t iv3;
+ uint32_t curr_buf;
+ uint32_t s_update_buf;
+ uint32_t c;
+ uint32_t n_batch;
+ uint32_t S_v;
+ float scale;
+ struct htp_ops_context * octx;
+ const struct htp_gdn_kernel_params * kparams;
+};
- for (uint32_t c = 0; c < task->n_col_tiles; ++c) {
- hmx_fa_qk_dot_tile(r_tiles, c_tiles, o_tile, task->n_dot_tiles);
+static inline void gdn_hmx_run_gemm(
+ const __fp16 * row_tiles,
+ const __fp16 * col_tiles,
+ __fp16 * out_tiles,
+ uint32_t n_row_tiles,
+ uint32_t n_col_tiles,
+ uint32_t n_dot_tiles
+) {
+ const size_t dot_stride = (size_t) n_dot_tiles * HMX_FP16_TILE_N_ELMS;
+ for (uint32_t r = 0; r < n_row_tiles; ++r) {
+ const __fp16 * r_tiles = row_tiles + r * dot_stride;
+ const __fp16 * c_tiles = col_tiles;
+ __fp16 * o_tile = out_tiles + r * n_col_tiles * HMX_FP16_TILE_N_ELMS;
+
+ for (uint32_t c = 0; c < n_col_tiles; ++c) {
+ hmx_fa_qk_dot_tile(r_tiles, c_tiles, o_tile, n_dot_tiles);
c_tiles += dot_stride;
o_tile += HMX_FP16_TILE_N_ELMS;
}
}
}
-static inline void htp_gdn_push_hmx_gemm_task(
- hmx_queue_t q,
- struct htp_gdn_hmx_gemm_task * task,
- const __fp16 * row_tiles,
- const __fp16 * col_tiles,
- __fp16 * out_tiles,
- uint32_t n_row_tiles,
- uint32_t n_col_tiles,
- uint32_t n_dot_tiles,
- uint8_t * scales
-) {
- task->row_tiles = row_tiles;
- task->col_tiles = col_tiles;
- task->out_tiles = out_tiles;
- task->n_row_tiles = n_row_tiles;
- task->n_col_tiles = n_col_tiles;
- task->n_dot_tiles = n_dot_tiles;
- task->dot_stride = n_dot_tiles * HMX_FP16_TILE_N_ELMS;
- task->hmx_scales = scales;
+static void gdn_hmx_kk_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ gdn_hmx_run_gemm(bctx->heads[h].k_row_tiles, bctx->heads[h].k_col_tiles, bctx->heads[h].kk_tiles, 2u, 2u, n_sv_tiles);
+ }
+}
- hmx_queue_push(q, hmx_queue_make_desc(htp_gdn_hmx_gemm_worker, task));
+static void gdn_hmx_qk_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ gdn_hmx_run_gemm(bctx->heads[h].q_row_tiles, bctx->heads[h].k_col_tiles, bctx->heads[h].qk_tiles, 2u, 2u, n_sv_tiles);
+ }
+}
+
+static void gdn_hmx_ks_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ gdn_hmx_run_gemm(bctx->heads[h].k_prime_row_tiles, bctx->heads[h].s_col_tiles, bctx->heads[h].v_inter_tiles, 2u, n_sv_tiles, n_sv_tiles);
+ }
+}
+
+static void gdn_hmx_qs_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ gdn_hmx_run_gemm(bctx->heads[h].q_prime_row_tiles, bctx->heads[h].s_col_tiles, bctx->heads[h].o_inter_tiles, 2u, n_sv_tiles, n_sv_tiles);
+ }
+}
+
+static void gdn_hmx_inv10_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ const struct htp_gdn_head_ptrs * head = &bctx->heads[h];
+ hmx_fa_qk_dot_tile(
+ (const __fp16 *) head->vtcm_m,
+ head->inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS,
+ (__fp16 *) head->vtcm_tmp,
+ 1u
+ );
+ hmx_fa_qk_dot_tile(
+ (const __fp16 *) head->vtcm_m + HMX_FP16_TILE_N_ELMS,
+ (const __fp16 *) head->vtcm_tmp,
+ head->inv_row_tiles + 2 * HMX_FP16_TILE_N_ELMS,
+ 1u
+ );
+ }
+}
+
+static void gdn_hmx_delta_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ const size_t dot_stride = 2u * HMX_FP16_TILE_N_ELMS;
+ // Write delta_tiles in col-major order [c][r] so O_INTRA reads in place
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ const struct htp_gdn_head_ptrs * head = &bctx->heads[h];
+ for (uint32_t r = 0; r < 2u; ++r) {
+ const __fp16 * r_tiles = head->inv_row_tiles + r * dot_stride;
+ const __fp16 * c_tiles = head->v_prime_col_tiles;
+ for (uint32_t c = 0; c < n_sv_tiles; ++c) {
+ __fp16 * o_tile = head->delta_tiles + (c * 2u + r) * HMX_FP16_TILE_N_ELMS;
+ hmx_fa_qk_dot_tile(r_tiles, c_tiles, o_tile, 2u);
+ c_tiles += dot_stride;
+ }
+ }
+ }
+}
+
+static void gdn_hmx_o_intra_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ gdn_hmx_run_gemm(bctx->heads[h].a_row_tiles, bctx->heads[h].delta_tiles, bctx->heads[h].o_intra_tiles, 2u, n_sv_tiles, 2u);
+ }
+}
+
+static void gdn_hmx_s_update_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data;
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales));
+ const uint32_t n_sv_tiles = bctx->S_v >> 5;
+ const uint32_t buf_idx = bctx->s_update_buf;
+ for (uint32_t h = 0; h < bctx->n_batch; ++h) {
+ gdn_hmx_run_gemm(bctx->heads[h].d_row_tiles, bctx->heads[h].k_col_tiles_64x128[buf_idx], bctx->heads[h].s_update_tiles, n_sv_tiles, n_sv_tiles, 2u);
+ }
}
static inline void gdn_unpack_64x64_tiles_to_vectors(
@@ -1162,83 +2124,19 @@ static inline void gdn_pack_64x64_vectors_to_tiles(
}
}
-static inline void gdn_unpack_64xS_tiles_to_f32(
- float * restrict dst_f32,
- const __fp16 * restrict tiles,
- uint32_t S_v
-) {
- const uint32_t n_col_tiles = S_v / 32;
- for (uint32_t r0 = 0; r0 < 2; ++r0) {
- for (uint32_t d = 0; d < S_v / 64; ++d) {
- const HVX_Vector * t0 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
- const HVX_Vector * t1 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
-
- for (uint32_t r = 0; r < 16; ++r) {
- HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2);
- HVX_VectorPair p0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp01));
- HVX_VectorPair p1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp01));
-
- float * out0 = dst_f32 + (r0 * 32 + 2 * r + 0) * S_v + d * 64;
- float * out1 = dst_f32 + (r0 * 32 + 2 * r + 1) * S_v + d * 64;
-
- hvx_vmem(out0 + 0) = Q6_V_lo_W(p0);
- hvx_vmem(out0 + 32) = Q6_V_hi_W(p0);
- hvx_vmem(out1 + 0) = Q6_V_lo_W(p1);
- hvx_vmem(out1 + 32) = Q6_V_hi_W(p1);
- }
- }
- }
+static inline float gdn_vtcm_load_f32(const float * vtcm_arr, uint32_t idx) {
+ const HVX_Vector v = hvx_vmem(&vtcm_arr[idx & ~31u]);
+ union {
+ int32_t i;
+ float f;
+ } u;
+ u.i = Q6_R_vextract_VR(v, (idx & 31u) * 4u);
+ return u.f;
}
-static inline void gdn_unpack_64xS_tiles_to_f16(
- __fp16 * restrict dst_f16,
- const __fp16 * restrict tiles,
- uint32_t S_v
-) {
- const uint32_t n_col_tiles = S_v / 32;
- for (uint32_t r0 = 0; r0 < 2; ++r0) {
- for (uint32_t d = 0; d < S_v / 64; ++d) {
- const HVX_Vector * t0 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
- const HVX_Vector * t1 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
-
- for (uint32_t r = 0; r < 16; ++r) {
- HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2);
- __fp16 * out0 = dst_f16 + (r0 * 32 + 2 * r + 0) * S_v + d * 64;
- __fp16 * out1 = dst_f16 + (r0 * 32 + 2 * r + 1) * S_v + d * 64;
-
- hvx_vmem(out0) = Q6_V_lo_W(vp01);
- hvx_vmem(out1) = Q6_V_hi_W(vp01);
- }
- }
- }
-}
-
-static inline void gdn_unpack_SxS_tiles_to_f32(
- float * restrict dst_f32,
- const __fp16 * restrict tiles,
- uint32_t S_v
-) {
- const uint32_t n_tiles = S_v / 32;
- for (uint32_t r0 = 0; r0 < n_tiles; ++r0) {
- for (uint32_t d = 0; d < S_v / 64; ++d) {
- const HVX_Vector * t0 = (const HVX_Vector *) (tiles + (r0 * n_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
- const HVX_Vector * t1 = (const HVX_Vector *) (tiles + (r0 * n_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
-
- for (uint32_t r = 0; r < 16; ++r) {
- HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2);
- HVX_VectorPair p0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp01));
- HVX_VectorPair p1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp01));
-
- float * out0 = dst_f32 + (r0 * 32 + 2 * r + 0) * S_v + d * 64;
- float * out1 = dst_f32 + (r0 * 32 + 2 * r + 1) * S_v + d * 64;
-
- hvx_vmem(out0 + 0) = Q6_V_lo_W(p0);
- hvx_vmem(out0 + 32) = Q6_V_hi_W(p0);
- hvx_vmem(out1 + 0) = Q6_V_lo_W(p1);
- hvx_vmem(out1 + 32) = Q6_V_hi_W(p1);
- }
- }
- }
+static inline uint16_t gdn_hvx_extract_u16(HVX_Vector v, uint32_t idx) {
+ const uint32_t w = (uint32_t) Q6_R_vextract_VR(v, (idx & ~1u) * 2u);
+ return (uint16_t) ((idx & 1u) ? (w >> 16) : (w & 0xFFFFu));
}
static inline void gdn_f32_to_hmx_row_tiles_and_f16(
@@ -1248,22 +2146,20 @@ static inline void gdn_f32_to_hmx_row_tiles_and_f16(
const float * restrict src,
const __fp16 * restrict scale_per_row,
uint32_t n_rows,
- uint32_t n_cols
+ uint32_t n_cols,
+ const bool write_f16
) {
- const uint32_t n_col_tiles = n_cols / 32;
- const uint32_t * scale_pairs = (const uint32_t *) scale_per_row;
+ const uint32_t n_col_tiles = n_cols >> 5;
+ const HVX_Vector v_scale_f16 = hvx_vmem(scale_per_row);
for (uint32_t r = 0; r < n_rows; r += 2) {
- uint32_t r0 = r / 32;
- uint32_t r1 = (r % 32) / 2;
+ uint32_t r0 = r >> 5;
+ uint32_t r1 = (r & 31u) >> 1;
const float * p0 = src + (r + 0) * n_cols;
const float * p1 = src + (r + 1) * n_cols;
- HVX_Vector v_scale;
- if (dst_prime_tiles) {
- uint32_t scale_pair = scale_pairs ? scale_pairs[r / 2] : 0x3c003c00;
- v_scale = Q6_V_vsplat_R(scale_pair);
- }
+ const uint32_t pair = (uint32_t) Q6_R_vextract_VR(v_scale_f16, r * 2u);
+ HVX_Vector v_scale = Q6_V_vsplat_R(pair);
for (uint32_t c = 0; c < n_col_tiles; c += 2) {
HVX_Vector v0_0 = hvx_vmem(p0 + (c + 0) * 32);
@@ -1278,16 +2174,14 @@ static inline void gdn_f32_to_hmx_row_tiles_and_f16(
((HVX_Vector *) tile0)[r1] = vh0;
((HVX_Vector *) tile1)[r1] = vh1;
- if (dst_prime_tiles) {
- HVX_Vector vh0_s = hvx_vec_mul_f16_f16(vh0, v_scale);
- HVX_Vector vh1_s = hvx_vec_mul_f16_f16(vh1, v_scale);
- __fp16 * tile0_s = dst_prime_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS;
- __fp16 * tile1_s = dst_prime_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS;
- ((HVX_Vector *) tile0_s)[r1] = vh0_s;
- ((HVX_Vector *) tile1_s)[r1] = vh1_s;
- }
+ HVX_Vector vh0_s = hvx_vec_mul_f16_f16(vh0, v_scale);
+ HVX_Vector vh1_s = hvx_vec_mul_f16_f16(vh1, v_scale);
+ __fp16 * tile0_s = dst_prime_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS;
+ __fp16 * tile1_s = dst_prime_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS;
+ ((HVX_Vector *) tile0_s)[r1] = vh0_s;
+ ((HVX_Vector *) tile1_s)[r1] = vh1_s;
- if (dst_f16) {
+ if (write_f16) {
HVX_VectorPair vp01 = Q6_W_vdeal_VVR(vh1, vh0, -2);
hvx_vmem(dst_f16 + (r + 0) * n_cols + c * 32) = Q6_V_lo_W(vp01);
hvx_vmem(dst_f16 + (r + 1) * n_cols + c * 32) = Q6_V_hi_W(vp01);
@@ -1296,74 +2190,76 @@ static inline void gdn_f32_to_hmx_row_tiles_and_f16(
}
}
-static inline void hvx_transpose_32x32_words(HVX_Vector * restrict m, HVX_Vector * restrict tmp) {
- for (int i = 0; i < 16; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(m[2*i + 1], m[2*i], -4);
- tmp[2*i + 0] = Q6_V_lo_W(p);
- tmp[2*i + 1] = Q6_V_hi_W(p);
- }
+static inline void gdn_f16_to_hmx_row_tiles(
+ __fp16 * restrict dst_tiles,
+ __fp16 * restrict dst_prime_tiles,
+ const __fp16 * restrict src,
+ const __fp16 * restrict scale_per_row,
+ uint32_t n_rows,
+ uint32_t n_cols
+) {
+ const uint32_t n_col_tiles = n_cols >> 5;
+ const HVX_Vector v_scale_f16 = hvx_vmem(scale_per_row);
- for (int b = 0; b < 32; b += 4) {
- HVX_VectorPair p0 = Q6_W_vshuff_VVR(tmp[b + 2], tmp[b + 0], -8);
- HVX_VectorPair p1 = Q6_W_vshuff_VVR(tmp[b + 3], tmp[b + 1], -8);
- m[b + 0] = Q6_V_lo_W(p0); m[b + 1] = Q6_V_hi_W(p0);
- m[b + 2] = Q6_V_lo_W(p1); m[b + 3] = Q6_V_hi_W(p1);
- }
+ for (uint32_t r = 0; r < n_rows; r += 2) {
+ uint32_t r0 = r >> 5;
+ uint32_t r1 = (r & 31u) >> 1;
+ const __fp16 * p0 = src + (r + 0) * n_cols;
+ const __fp16 * p1 = src + (r + 1) * n_cols;
- for (int b = 0; b < 32; b += 8) {
- for (int i = 0; i < 4; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(m[b + i + 4], m[b + i], -16);
- tmp[b + 2*i + 0] = Q6_V_lo_W(p);
- tmp[b + 2*i + 1] = Q6_V_hi_W(p);
- }
- }
+ const uint32_t pair = (uint32_t) Q6_R_vextract_VR(v_scale_f16, r * 2u);
+ HVX_Vector v_scale = Q6_V_vsplat_R(pair);
- for (int b = 0; b < 32; b += 16) {
- for (int i = 0; i < 8; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(tmp[b + i + 8], tmp[b + i], -32);
- m[b + 2*i + 0] = Q6_V_lo_W(p);
- m[b + 2*i + 1] = Q6_V_hi_W(p);
- }
- }
+ for (uint32_t c = 0; c < n_col_tiles; c += 2) {
+ HVX_Vector vr0 = hvx_vmem(p0 + c * 32);
+ HVX_Vector vr1 = hvx_vmem(p1 + c * 32);
+ HVX_VectorPair vp = Q6_W_vshuff_VVR(vr1, vr0, -2);
+ HVX_Vector vh0 = Q6_V_lo_W(vp);
+ HVX_Vector vh1 = Q6_V_hi_W(vp);
- for (int i = 0; i < 16; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(m[i + 16], m[i], -64);
- tmp[2 * i + 0] = Q6_V_lo_W(p);
- tmp[2 * i + 1] = Q6_V_hi_W(p);
- }
+ __fp16 * tile0 = dst_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS;
+ __fp16 * tile1 = dst_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS;
+ ((HVX_Vector *) tile0)[r1] = vh0;
+ ((HVX_Vector *) tile1)[r1] = vh1;
- for (int i = 0; i < 32; ++i) {
- m[i] = tmp[i];
+ HVX_Vector vh0_s = hvx_vec_mul_f16_f16(vh0, v_scale);
+ HVX_Vector vh1_s = hvx_vec_mul_f16_f16(vh1, v_scale);
+ __fp16 * tile0_s = dst_prime_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS;
+ __fp16 * tile1_s = dst_prime_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS;
+ ((HVX_Vector *) tile0_s)[r1] = vh0_s;
+ ((HVX_Vector *) tile1_s)[r1] = vh1_s;
+ }
}
}
-static inline void gdn_pack_d_t_row_tiles(
- __fp16 * restrict dst_tiles,
- const __fp16 * restrict src_d,
- uint32_t S_v,
- HVX_Vector * restrict m,
- HVX_Vector * restrict tmp
+// Solve (I + L) * A = I for 32x32 unit lower-triangular L in L1-cached stack, writing A rows to VTCM
+static __attribute__((noinline)) void gdn_invert_lower_32x32(
+ HVX_Vector * restrict a_rows,
+ const uint16_t * restrict l_l2
) {
- for (uint32_t col_half = 0; col_half < S_v / 64; ++col_half) {
- uint32_t r0_base = col_half * 2;
- for (uint32_t c0 = 0; c0 < 2; ++c0) {
- for (uint32_t s_local = 0; s_local < 32; ++s_local) {
- uint32_t s = c0 * 32 + s_local;
- m[s_local] = hvx_vmem(src_d + s * S_v + col_half * 64);
- }
-
- hvx_transpose_32x32_words(m, tmp);
-
- uint32_t tile0_idx = (r0_base + 0) * 2 + c0;
- uint32_t tile1_idx = (r0_base + 1) * 2 + c0;
- HVX_Vector * t0 = (HVX_Vector *)(dst_tiles + tile0_idx * HMX_FP16_TILE_N_ELMS);
- HVX_Vector * t1 = (HVX_Vector *)(dst_tiles + tile1_idx * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_VectorPred q_mask64 = Q6_Q_vsetq2_R(64);
- for (uint32_t r = 0; r < 16; ++r) {
- t0[r] = m[r];
- t1[r] = m[16 + r];
- }
+ for (uint32_t t = 0; t < 32; ++t) {
+ const uint32_t * restrict l_row_u32 = (const uint32_t *) (l_l2 + t * 32u);
+ HVX_Vector v_inv0 = Q6_V_vzero();
+ HVX_Vector v_inv1 = Q6_V_vzero();
+ uint32_t k = 0;
+ #pragma nounroll
+ for (; k + 1u < t; k += 2u) {
+ const uint32_t w = l_row_u32[k >> 1];
+ HVX_Vector v_lk0 = Q6_Vh_vsplat_R(w & 0xFFFFu);
+ HVX_Vector v_lk1 = Q6_Vh_vsplat_R(w >> 16);
+ v_inv0 = hvx_vec_sub_f16_f16(v_inv0, hvx_vec_mul_f16_f16(v_lk0, a_rows[k + 0u]));
+ v_inv1 = hvx_vec_sub_f16_f16(v_inv1, hvx_vec_mul_f16_f16(v_lk1, a_rows[k + 1u]));
}
+ HVX_Vector v_inv = hvx_vec_add_f16_f16(v_inv0, v_inv1);
+ if (k < t) {
+ HVX_Vector v_lk = Q6_Vh_vsplat_R(l_l2[t * 32u + k]);
+ v_inv = hvx_vec_sub_f16_f16(v_inv, hvx_vec_mul_f16_f16(v_lk, a_rows[k]));
+ }
+ HVX_VectorPred q_diag = (t == 0) ? Q6_Q_vsetq2_R(2) : Q6_Q_and_QQn(Q6_Q_vsetq2_R(2 * (t + 1)), Q6_Q_vsetq2_R(2 * t));
+ a_rows[t] = Q6_V_vand_QV(q_mask64, Q6_V_vmux_QVV(q_diag, v_one_f16, v_inv));
}
}
@@ -1373,22 +2269,21 @@ static __attribute__((noinline)) void gdn_build_inv_l_blocks(
const __fp16 * restrict decay_m,
const float * restrict beta,
__fp16 * restrict l10_tile,
- __fp16 * restrict neg_a11_tile
+ __fp16 * restrict neg_a11_tile,
+ HVX_Vector * restrict a_rows_vtcm
) {
- const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
- const HVX_VectorPred q_mask64 = Q6_Q_vsetq2_R(64);
-
- uint16_t beta_u16[64] __attribute__((aligned(128)));
- uint16_t l00[32][32] __attribute__((aligned(128)));
- uint16_t l11[32][32] __attribute__((aligned(128)));
+ // Keep l00, l11, and beta_u16 in L1-cached stack to avoid scalar VTCM loads in inversion
+ uint16_t l_l2_buf[2048 + 64] __attribute__((aligned(128)));
- HVX_Vector * restrict p_l00 = (HVX_Vector *) l00;
- HVX_Vector * restrict p_l11 = (HVX_Vector *) l11;
+ HVX_Vector * restrict a_rows = a_rows_vtcm;
+ HVX_Vector * restrict p_l00 = (HVX_Vector *) (l_l2_buf + 0);
+ HVX_Vector * restrict p_l11 = (HVX_Vector *) (l_l2_buf + 1024);
+ uint16_t * restrict beta_u16 = l_l2_buf + 2048;
HVX_Vector * restrict p_l10_tile = (HVX_Vector *) l10_tile;
- HVX_Vector * restrict tile00 = (HVX_Vector *) (inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS);
- HVX_Vector * restrict tile01 = (HVX_Vector *) (inv_row_tiles + 1 * HMX_FP16_TILE_N_ELMS);
- HVX_Vector * restrict tile11 = (HVX_Vector *) (inv_row_tiles + 3 * HMX_FP16_TILE_N_ELMS);
+ HVX_Vector * restrict tile00 = (HVX_Vector *) (inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS);
+ HVX_Vector * restrict tile01 = (HVX_Vector *) (inv_row_tiles + 1 * HMX_FP16_TILE_N_ELMS);
+ HVX_Vector * restrict tile11 = (HVX_Vector *) (inv_row_tiles + 3 * HMX_FP16_TILE_N_ELMS);
HVX_Vector * restrict p_neg_a11 = (HVX_Vector *) neg_a11_tile;
hvx_vmem(beta_u16) = hvx_vec_f32_to_f16(hvx_vmem(beta + 0), hvx_vmem(beta + 32));
@@ -1397,63 +2292,53 @@ static __attribute__((noinline)) void gdn_build_inv_l_blocks(
tile01[r] = Q6_V_vzero();
}
- for (uint32_t r = 0; r < 16; ++r) {
- uint32_t t0 = 2 * r;
- uint32_t t1 = t0 + 1;
+ {
+ const HVX_VectorPred q_mask64 = Q6_Q_vsetq2_R(64);
+ const uint32_t * restrict beta_u32 = (const uint32_t *) beta_u16;
- HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64);
- HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64);
- HVX_Vector v_b0 = Q6_Vh_vsplat_R(beta_u16[t0]);
- HVX_Vector v_b1 = Q6_Vh_vsplat_R(beta_u16[t1]);
+ for (uint32_t r = 0; r < 16; ++r) {
+ uint32_t t0 = 2 * r;
+ uint32_t t1 = t0 + 1;
- HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0);
- HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1);
+ HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64);
+ HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64);
+ const uint32_t bw = beta_u32[r];
+ HVX_Vector v_b0 = Q6_Vh_vsplat_R(bw & 0xFFFFu);
+ HVX_Vector v_b1 = Q6_Vh_vsplat_R(bw >> 16);
- p_l00[r] = Q6_V_vmux_QVV(q_mask64, r0, Q6_V_vror_VR(r1, 64));
- }
+ HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0);
+ HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1);
- for (uint32_t r = 0; r < 16; ++r) {
- uint32_t t0 = 32 + 2 * r;
- uint32_t t1 = t0 + 1;
+ p_l00[r] = Q6_V_vmux_QVV(q_mask64, r0, Q6_V_vror_VR(r1, 64));
+ }
- HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64);
- HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64);
- HVX_Vector v_b0 = Q6_Vh_vsplat_R(beta_u16[t0]);
- HVX_Vector v_b1 = Q6_Vh_vsplat_R(beta_u16[t1]);
+ for (uint32_t r = 0; r < 16; ++r) {
+ uint32_t t0 = 32 + 2 * r;
+ uint32_t t1 = t0 + 1;
- HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0);
- HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1);
+ HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64);
+ HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64);
+ const uint32_t bw = beta_u32[16 + r];
+ HVX_Vector v_b0 = Q6_Vh_vsplat_R(bw & 0xFFFFu);
+ HVX_Vector v_b1 = Q6_Vh_vsplat_R(bw >> 16);
- HVX_VectorPair vp_l10 = Q6_W_vshuff_VVR(r1, r0, -2);
- p_l10_tile[r] = Q6_V_lo_W(vp_l10);
- p_l11[r] = Q6_V_vmux_QVV(q_mask64, Q6_V_vror_VR(r0, 64), r1);
- }
+ HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0);
+ HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1);
- HVX_Vector a_rows[32];
- for (uint32_t t = 0; t < 32; ++t) {
- HVX_Vector v_inv = Q6_V_vzero();
- for (uint32_t k = 0; k < t; ++k) {
- HVX_Vector v_lk = Q6_Vh_vsplat_R(l00[t][k]);
- v_inv = hvx_vec_sub_f16_f16(v_inv, hvx_vec_mul_f16_f16(v_lk, a_rows[k]));
+ HVX_VectorPair vp_l10 = Q6_W_vshuff_VVR(r1, r0, -2);
+ p_l10_tile[r] = Q6_V_lo_W(vp_l10);
+ p_l11[r] = Q6_V_vmux_QVV(q_mask64, Q6_V_vror_VR(r0, 64), r1);
}
- HVX_VectorPred q_diag = (t == 0) ? Q6_Q_vsetq2_R(2) : Q6_Q_and_QQn(Q6_Q_vsetq2_R(2 * (t + 1)), Q6_Q_vsetq2_R(2 * t));
- a_rows[t] = Q6_V_vand_QV(q_mask64, Q6_V_vmux_QVV(q_diag, v_one_f16, v_inv));
}
+ gdn_invert_lower_32x32(a_rows, l_l2_buf + 0);
+
for (uint32_t r = 0; r < 16; ++r) {
HVX_VectorPair vp = Q6_W_vshuff_VVR(a_rows[2 * r + 1], a_rows[2 * r + 0], -2);
tile00[r] = Q6_V_lo_W(vp);
}
- for (uint32_t t = 0; t < 32; ++t) {
- HVX_Vector v_inv = Q6_V_vzero();
- for (uint32_t k = 0; k < t; ++k) {
- HVX_Vector v_lk = Q6_Vh_vsplat_R(l11[t][k]);
- v_inv = hvx_vec_sub_f16_f16(v_inv, hvx_vec_mul_f16_f16(v_lk, a_rows[k]));
- }
- HVX_VectorPred q_diag = (t == 0) ? Q6_Q_vsetq2_R(2) : Q6_Q_and_QQn(Q6_Q_vsetq2_R(2 * (t + 1)), Q6_Q_vsetq2_R(2 * t));
- a_rows[t] = Q6_V_vand_QV(q_mask64, Q6_V_vmux_QVV(q_diag, v_one_f16, v_inv));
- }
+ gdn_invert_lower_32x32(a_rows, l_l2_buf + 1024);
for (uint32_t r = 0; r < 16; ++r) {
HVX_VectorPair vp = Q6_W_vshuff_VVR(a_rows[2 * r + 1], a_rows[2 * r + 0], -2);
@@ -1466,7 +2351,6 @@ static __attribute__((noinline)) void gdn_build_inv_l_blocks(
}
}
-
static inline void gdn_dma_push_chunk_inputs(
dma_queue * dma_q,
float * vtcm_q,
@@ -1476,122 +2360,76 @@ static inline void gdn_dma_push_chunk_inputs(
const struct htp_tensor * k,
const struct htp_tensor * v,
uint32_t iq3, uint32_t iq1,
- uint32_t ik3, uint32_t ik1,
- uint32_t iv3, uint32_t iv1,
- uint32_t t_chunk,
- uint32_t chunk_size,
- uint32_t S_v
-) {
- const dma_addr_t q_dma = q->data + (uint64_t) iq3 * q->nb[3] + (uint64_t) t_chunk * q->nb[2] + (uint64_t) iq1 * q->nb[1];
- const dma_addr_t k_dma = k->data + (uint64_t) ik3 * k->nb[3] + (uint64_t) t_chunk * k->nb[2] + (uint64_t) ik1 * k->nb[1];
- const dma_addr_t v_dma = v->data + (uint64_t) iv3 * v->nb[3] + (uint64_t) t_chunk * v->nb[2] + (uint64_t) iv1 * v->nb[1];
-
- dma_queue_push(dma_q, dma_make_data(vtcm_q, q_dma), S_v * sizeof(float), q->nb[2], S_v * sizeof(float), chunk_size);
- dma_queue_push(dma_q, dma_make_data(vtcm_k, k_dma), S_v * sizeof(float), k->nb[2], S_v * sizeof(float), chunk_size);
- dma_queue_push(dma_q, dma_make_data(vtcm_v, v_dma), S_v * sizeof(float), v->nb[2], S_v * sizeof(float), chunk_size);
-}
-
-static inline void gdn_dma_push_chunk_gb(
- dma_queue * dma_q,
- float * vtcm_g_raw,
- float * vtcm_b_raw,
- const struct htp_tensor * g,
- const struct htp_tensor * beta,
- uint32_t iv3,
- uint32_t iv1,
- uint32_t t_chunk,
- uint32_t chunk_size,
- uint32_t n_batch
-) {
- const dma_addr_t g_dma = g->data + (uint64_t) iv3 * g->nb[3] + (uint64_t) t_chunk * g->nb[2] + (uint64_t) iv1 * g->nb[1];
- const dma_addr_t beta_dma = beta->data + (uint64_t) iv3 * beta->nb[3] + (uint64_t) t_chunk * beta->nb[2] + (uint64_t) iv1 * beta->nb[1];
- const uint32_t row_bytes = n_batch * sizeof(float);
- const uint32_t dst_stride = (n_batch > 1) ? row_bytes + sizeof(float) : row_bytes;
-
- dma_queue_push(dma_q, dma_make_data(vtcm_g_raw, g_dma), dst_stride, g->nb[2], row_bytes, chunk_size);
- dma_queue_push(dma_q, dma_make_data(vtcm_b_raw, beta_dma), dst_stride, beta->nb[2], row_bytes, chunk_size);
-}
-
-static inline void gdn_pack_s_col_tiles(
- __fp16 * restrict vtcm_s_col_tiles,
- __fp16 * restrict vtcm_s_f16,
- const float * restrict vtcm_s_state,
- uint32_t S_v
-) {
- for (uint32_t j = 0; j < S_v; ++j) {
- for (uint32_t i = 0; i < S_v; i += 64) {
- HVX_Vector v0 = hvx_vmem(vtcm_s_state + j * S_v + i + 0);
- HVX_Vector v1 = (i + 32 < S_v) ? hvx_vmem(vtcm_s_state + j * S_v + i + 32) : Q6_V_vzero();
- hvx_vmem(vtcm_s_f16 + j * S_v + i) = hvx_vec_f32_to_f16(v0, v1);
- }
- }
- hmx_interleave_rows_to_tiles(vtcm_s_col_tiles, vtcm_s_f16, S_v, S_v, S_v, 0, S_v);
-}
-
-struct htp_gdn_head_ptrs {
- float * s_state;
- __fp16 * s_f16;
- __fp16 * s_col_tiles;
- float * s_update_f32;
- __fp16 * s_update_tiles;
-
- float * q_f32[2];
- float * k_f32[2];
- float * v_f32[2];
- float * g_f32[2];
- float * b_f32[2];
- float * o_f32[2];
-
- float * v_inter_f32;
- float * o_inter_f32;
- float * o_intra_f32;
-
- __fp16 * k_f16;
- __fp16 * v_prime_f16;
- __fp16 * delta_f16;
- __fp16 * d_f16;
-
- __fp16 * q_row_tiles;
- __fp16 * q_prime_row_tiles;
- __fp16 * k_row_tiles;
- __fp16 * k_col_tiles;
- __fp16 * k_prime_row_tiles;
- __fp16 * k_col_tiles_64x128;
- __fp16 * kk_tiles;
- __fp16 * qk_tiles;
- __fp16 * v_inter_tiles;
- __fp16 * o_inter_tiles;
- __fp16 * inv_row_tiles;
- __fp16 * a_row_tiles;
- __fp16 * v_prime_col_tiles;
- __fp16 * delta_tiles;
- __fp16 * delta_col_tiles;
- __fp16 * o_intra_tiles;
- __fp16 * d_row_tiles;
+ uint32_t ik3, uint32_t ik1,
+ uint32_t iv3, uint32_t iv1,
+ uint32_t t_chunk,
+ uint32_t chunk_size,
+ uint32_t S_v
+) {
+ const dma_addr_t q_dma = q->data + (iq3 * q->nb[3] + t_chunk * q->nb[2] + iq1 * q->nb[1]);
+ const dma_addr_t k_dma = k->data + (ik3 * k->nb[3] + t_chunk * k->nb[2] + ik1 * k->nb[1]);
+ const dma_addr_t v_dma = v->data + (iv3 * v->nb[3] + t_chunk * v->nb[2] + iv1 * v->nb[1]);
- __fp16 * gamma;
- float * lambda_init;
- __fp16 * lambda_init_f16;
- __fp16 * decay_m;
- __fp16 * decay_a;
+ const uint32_t q_row_bytes = S_v * ((q->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t k_row_bytes = S_v * ((k->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const uint32_t v_row_bytes = S_v * ((v->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
- HVX_Vector * rows_kk;
- HVX_Vector * rows_qk;
- HVX_Vector * rows_inv;
- HVX_Vector * rows_a;
+ dma_queue_push(dma_q, dma_make_data(vtcm_q, q_dma), q_row_bytes, q->nb[2], q_row_bytes, chunk_size);
+ dma_queue_push(dma_q, dma_make_data(vtcm_k, k_dma), k_row_bytes, k->nb[2], k_row_bytes, chunk_size);
+ dma_queue_push(dma_q, dma_make_data(vtcm_v, v_dma), v_row_bytes, v->nb[2], v_row_bytes, chunk_size);
+}
- HVX_Vector * vtcm_m;
- HVX_Vector * vtcm_tmp;
+static inline void gdn_dma_push_chunk_gb(
+ dma_queue * dma_q,
+ float * vtcm_g_raw,
+ float * vtcm_b_raw,
+ const struct htp_tensor * g,
+ const struct htp_tensor * beta,
+ uint32_t iv3,
+ uint32_t iv1,
+ uint32_t t_chunk,
+ uint32_t chunk_size,
+ uint32_t n_batch
+) {
+ const dma_addr_t g_dma = g->data + (iv3 * g->nb[3] + t_chunk * g->nb[2] + iv1 * g->nb[1]);
+ const dma_addr_t beta_dma = beta->data + (iv3 * beta->nb[3] + t_chunk * beta->nb[2] + iv1 * beta->nb[1]);
+ const uint32_t row_bytes = n_batch * sizeof(float);
+ const uint32_t dst_stride = (n_batch > 1) ? row_bytes + sizeof(float) : row_bytes;
- uint32_t iv1;
- uint32_t iv3;
- uint32_t iq1;
- uint32_t ik1;
- uint32_t iq3;
- uint32_t ik3;
- dma_addr_t state_in_dma;
- dma_addr_t state_out_dma;
-};
+ dma_queue_push(dma_q, dma_make_data(vtcm_g_raw, g_dma), dst_stride, g->nb[2], row_bytes, chunk_size);
+ dma_queue_push(dma_q, dma_make_data(vtcm_b_raw, beta_dma), dst_stride, beta->nb[2], row_bytes, chunk_size);
+}
+
+static inline void gdn_pack_s_col_tiles(
+ __fp16 * restrict vtcm_s_col_tiles,
+ const float * restrict vtcm_s_state,
+ uint32_t S_v
+) {
+ const uint32_t n_k_tiles = S_v >> 5;
+ const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
+ const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
+ const size_t pair_region = (size_t) (2 * HMX_FP16_TILE_SIZE - 1);
+
+ for (uint32_t r = 0; r < S_v; r += 2) {
+ const uint32_t ct = r >> 5;
+ const uint32_t local_r = r & 31u;
+ const HVX_Vector v_off0 = Q6_Vw_vadd_VwVw(v_scat_base, Q6_V_vsplat_R(local_r * 4));
+ const HVX_Vector v_off1 = Q6_Vw_vadd_VwVw(v_off0, v_scat_step);
+
+ __fp16 * tile_base = vtcm_s_col_tiles + (size_t) ct * n_k_tiles * HMX_FP16_TILE_N_ELMS;
+ const float * s0 = vtcm_s_state + (r + 0) * S_v;
+ const float * s1 = vtcm_s_state + (r + 1) * S_v;
+
+ for (uint32_t d = 0; d < (S_v >> 6); ++d) {
+ const HVX_Vector v0 = hvx_vec_f32_to_f16(hvx_vmem(s0 + d * 64 + 0), hvx_vmem(s0 + d * 64 + 32));
+ const HVX_Vector v1 = hvx_vec_f32_to_f16(hvx_vmem(s1 + d * 64 + 0), hvx_vmem(s1 + d * 64 + 32));
+ Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off0, v0);
+ Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off1, v1);
+ tile_base += 2 * HMX_FP16_TILE_N_ELMS;
+ }
+ }
+ hvx_gather_sync(vtcm_s_col_tiles);
+}
static inline void gdn_init_head_ptrs(
struct htp_gdn_head_ptrs * head,
@@ -1600,6 +2438,7 @@ static inline void gdn_init_head_ptrs(
uint32_t h,
uint32_t base_iv1,
uint32_t iv3,
+ uint32_t is3,
const struct htp_tensor * q,
const struct htp_tensor * k,
const struct htp_tensor * v,
@@ -1612,61 +2451,54 @@ static inline void gdn_init_head_ptrs(
uint32_t n_tokens,
uint32_t chunk_size
) {
+ (void) v;
const size_t dma_scalar_sz = hex_round_up(chunk_size * sizeof(float), 128);
const size_t decay_sz = 64 * 64 * sizeof(__fp16);
const size_t row_vecs_sz = 64 * 128;
head->s_state = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_s_state + h * L->state_f32_bytes);
- head->s_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_s_f16 + h * L->state_f16_bytes);
head->s_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_s_col_tiles + h * L->state_tiles_bytes);
- head->s_update_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_s_update_f32 + h * L->state_f32_bytes);
head->s_update_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_s_update_tiles + h * L->state_tiles_bytes);
head->q_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_q_f32[0] + h * L->dma_chunk_bytes);
- head->q_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_q_f32[1] + h * L->dma_chunk_bytes) : head->q_f32[0];
+ head->q_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_q_f32[1] + h * L->dma_chunk_bytes);
head->k_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_k_f32[0] + h * L->dma_chunk_bytes);
- head->k_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_k_f32[1] + h * L->dma_chunk_bytes) : head->k_f32[0];
+ head->k_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_k_f32[1] + h * L->dma_chunk_bytes);
head->v_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_f32[0] + h * L->dma_chunk_bytes);
- head->v_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_f32[1] + h * L->dma_chunk_bytes) : head->v_f32[0];
+ head->v_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_f32[1] + h * L->dma_chunk_bytes);
head->g_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_g_f32[0] + h * dma_scalar_sz);
- head->g_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_g_f32[1] + h * dma_scalar_sz) : head->g_f32[0];
+ head->g_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_g_f32[1] + h * dma_scalar_sz);
head->b_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_b_f32[0] + h * dma_scalar_sz);
- head->b_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_b_f32[1] + h * dma_scalar_sz) : head->b_f32[0];
+ head->b_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_b_f32[1] + h * dma_scalar_sz);
head->o_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_f32[0] + h * L->dma_chunk_bytes);
- head->o_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_f32[1] + h * L->dma_chunk_bytes) : head->o_f32[0];
-
- head->v_inter_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_inter_f32 + h * L->dma_chunk_bytes);
- head->o_inter_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_inter_f32 + h * L->dma_chunk_bytes);
- head->o_intra_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_intra_f32 + h * L->dma_chunk_bytes);
-
- head->k_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_f16 + h * L->act_f16_bytes);
- head->v_prime_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_prime_f16 + h * L->act_f16_bytes);
- head->delta_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_f16 + h * L->act_f16_bytes);
- head->d_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_d_f16 + h * L->act_f16_bytes);
-
- head->q_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_row_tiles + h * L->tile_64xSv_bytes);
- head->q_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_prime_row_tiles + h * L->tile_64xSv_bytes);
- head->k_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_row_tiles + h * L->tile_64xSv_bytes);
- head->k_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles + h * L->tile_64xSv_bytes);
- head->k_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_prime_row_tiles + h * L->tile_64xSv_bytes);
- head->k_col_tiles_64x128 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles_64x128 + h * L->tile_64xSv_bytes);
- head->kk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_kk_tiles + h * L->tile_64x64_bytes);
- head->qk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_qk_tiles + h * L->tile_64x64_bytes);
- head->v_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_inter_tiles + h * L->tile_64xSv_bytes);
- head->o_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_inter_tiles + h * L->tile_64xSv_bytes);
- head->inv_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_inv_row_tiles + h * L->tile_64x64_bytes);
- head->a_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_a_row_tiles + h * L->tile_64x64_bytes);
- head->v_prime_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_prime_col_tiles + h * L->tile_64xSv_bytes);
- head->delta_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_tiles + h * L->tile_64xSv_bytes);
- head->delta_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_col_tiles + h * L->tile_64xSv_bytes);
- head->o_intra_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_intra_tiles + h * L->tile_64xSv_bytes);
- head->d_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_d_row_tiles + h * L->tile_64xSv_bytes);
+ head->o_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_f32[1] + h * L->dma_chunk_bytes);
+
+ head->k_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_f16 + h * L->act_f16_bytes);
+
+ head->q_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_row_tiles + h * L->tile_64xSv_bytes);
+ head->q_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_prime_row_tiles + h * L->tile_64xSv_bytes);
+ head->k_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_row_tiles + h * L->tile_64xSv_bytes);
+ head->k_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles + h * L->tile_64xSv_bytes);
+ head->k_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_prime_row_tiles + h * L->tile_64xSv_bytes);
+ head->k_col_tiles_64x128[0] = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles_64x128[0] + h * L->tile_64xSv_bytes);
+ head->k_col_tiles_64x128[1] = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles_64x128[1] + h * L->tile_64xSv_bytes);
+ head->kk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_kk_tiles + h * L->tile_64x64_bytes);
+ head->qk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_qk_tiles + h * L->tile_64x64_bytes);
+ head->v_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_inter_tiles + h * L->tile_64xSv_bytes);
+ head->o_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_inter_tiles + h * L->tile_64xSv_bytes);
+ head->inv_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_inv_row_tiles + h * L->tile_64x64_bytes);
+ head->a_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_a_row_tiles + h * L->tile_64x64_bytes);
+ head->v_prime_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_prime_col_tiles + h * L->tile_64xSv_bytes);
+ head->delta_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_tiles + h * L->tile_64xSv_bytes);
+ head->o_intra_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_intra_tiles + h * L->tile_64xSv_bytes);
+ head->d_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_d_row_tiles + h * L->tile_64xSv_bytes);
head->gamma = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_gamma + h * dma_scalar_sz);
head->lambda_init_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_gamma + h * dma_scalar_sz + 128);
- head->lambda_init = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_lambda_init + h * dma_scalar_sz);
- head->decay_m = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_m + h * decay_sz);
- head->decay_a = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_a + h * decay_sz);
+ head->lambda_init[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_lambda_init[0] + h * dma_scalar_sz);
+ head->lambda_init[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_lambda_init[1] + h * dma_scalar_sz);
+ head->decay_m = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_m + h * decay_sz);
+ head->decay_a = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_a + h * decay_sz);
head->rows_kk = VTCM_LAYOUT_PTR(HVX_Vector, vtcm_base, L->off_rows_kk + h * row_vecs_sz);
head->rows_qk = VTCM_LAYOUT_PTR(HVX_Vector, vtcm_base, L->off_rows_qk + h * row_vecs_sz);
@@ -1684,38 +2516,90 @@ static inline void gdn_init_head_ptrs(
head->ik3 = fastdiv(head->iv3, &kparams->div_rk3);
head->state_in_dma = state->data +
- ((uint64_t) head->iv3 * kparams->state_seq_stride + (uint64_t) head->iv1 * S_v * S_v) * sizeof(float);
+ ((size_t) is3 * kparams->state_seq_stride + (size_t) head->iv1 * S_v * S_v) * sizeof(float);
head->state_out_dma = dst_cache ?
- (dst_cache->data + ((uint64_t) head->iv3 * H + head->iv1) * S_v * S_v * sizeof(float)) :
- (dst->data + ((uint64_t) S_v * H * n_tokens * kparams->n_seqs + (uint64_t) (head->iv3 * H + head->iv1) * S_v * S_v) * sizeof(float));
+ (dst_cache->data + (head->iv3 * H + head->iv1) * S_v * S_v * sizeof(float)) :
+ (dst->data + (S_v * H * n_tokens * kparams->n_seqs + (head->iv3 * H + head->iv1) * S_v * S_v) * sizeof(float));
}
-struct htp_gdn_batch_context {
- struct htp_gdn_head_ptrs * heads;
- const float * vtcm_g_raw;
- const float * vtcm_b_raw;
- uint32_t curr_buf;
- uint32_t c;
- uint32_t n_batch;
- uint32_t S_v;
- float scale;
- struct htp_ops_context * octx;
- const struct htp_gdn_kernel_params * kparams;
-};
-
-static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+static void gdn_hvx_prologue_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
(void) n;
- struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+ struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
+ struct htp_ops_context * octx = bctx->octx;
+ const struct htp_gdn_kernel_params * kparams = bctx->kparams;
+ struct htp_thread_trace * tr = th->trace;
+ dma_queue * dma_q = th->dma_q;
+ struct htp_gdn_head_ptrs * head = &bctx->heads[i];
+
+ const struct htp_tensor * q = octx->src[0];
+ const struct htp_tensor * k = octx->src[1];
+ const struct htp_tensor * v = octx->src[2];
+ const struct htp_tensor * g = octx->src[3];
+ const struct htp_tensor * beta = octx->src[4];
+
+ const uint32_t S_v = bctx->S_v;
+ const uint32_t chunk_size = kparams->chunk_size;
+ const uint32_t n_tokens = kparams->n_tokens;
+ const uint32_t n_chunks = kparams->n_chunks;
- struct htp_gdn_head_ptrs * head = &bctx->heads[i];
- gdn_replay_f32(bctx->octx, head->s_state, head->ik1, head->iv1, head->iv3,
- bctx->kparams->kda, bctx->scale, bctx->S_v);
- gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, bctx->S_v);
+ dma_queue_push(dma_q, dma_make_data(head->s_state, head->state_in_dma),
+ S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
+
+ if (bctx->replay) {
+ dma_queue_pop(dma_q);
+ const int32_t raw_n_rep = bctx->n_rep_data[head->iv3];
+ const uint32_t n_steps = raw_n_rep <= 0 ? 0 : hex_smin((uint32_t) raw_n_rep, bctx->n_pend);
+ if (n_steps > 0) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+ gdn_replay_f32(octx, dma_q, head->s_state,
+ head->k_f32[0], head->v_f32[0], head->g_f32[0], head->b_f32[0],
+ head->vtcm_m, chunk_size,
+ head->ik1, head->iv1, head->iv3, n_steps, bctx->n_pend,
+ kparams->kda != 0, S_v);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+ }
+ if (bctx->keep) {
+ dma_queue_push(dma_q, dma_make_data(head->state_out_dma, head->s_state),
+ S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
+ dma_queue_pop(dma_q);
+ }
+ }
+
+ const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens);
+ gdn_dma_push_chunk_inputs(dma_q, head->q_f32[0], head->k_f32[0], head->v_f32[0],
+ q, k, v, head->iq3, head->iq1, head->ik3, head->ik1,
+ head->iv3, head->iv1, 0u, chunk0_tokens, S_v);
+ if (i == 0u) {
+ gdn_dma_push_chunk_gb(dma_q, bctx->vtcm_g_raw[0], bctx->vtcm_b_raw[0],
+ g, beta, bctx->iv3, bctx->head_in_seq, 0u, chunk0_tokens, bctx->n_batch);
+ }
+ if (!bctx->replay) {
+ dma_queue_pop(dma_q);
+ }
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+ gdn_pack_s_col_tiles(head->s_col_tiles, head->s_state, S_v);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
+
+ dma_queue_pop(dma_q);
+ dma_queue_pop(dma_q);
+ dma_queue_pop(dma_q);
+ if (i == 0u) {
+ dma_queue_pop(dma_q);
+ dma_queue_pop(dma_q);
+ }
+
+ if (n_chunks > 1u) {
+ const uint32_t c1_tokens = hex_smin(chunk_size, n_tokens - chunk_size);
+ gdn_dma_push_chunk_inputs(dma_q, head->q_f32[1], head->k_f32[1], head->v_f32[1],
+ q, k, v, head->iq3, head->iq1, head->ik3, head->ik1,
+ head->iv3, head->iv1, chunk_size, c1_tokens, S_v);
+ if (i == 0u) {
+ gdn_dma_push_chunk_gb(dma_q, bctx->vtcm_g_raw[1], bctx->vtcm_b_raw[1],
+ g, beta, bctx->iv3, bctx->head_in_seq, chunk_size, c1_tokens, bctx->n_batch);
+ }
+ }
}
static inline __attribute__((unused)) HVX_Vector hvx_clamp_neg20_0(HVX_Vector v, HVX_Vector v_zero, HVX_Vector v_neg20) {
@@ -1753,38 +2637,55 @@ static void gdn_hvx_phase1a_worker(const htp_thread_t * th, unsigned int n, unsi
const uint32_t curr_buf = bctx->curr_buf;
const uint32_t S_v = bctx->S_v;
const uint32_t n_batch = bctx->n_batch;
+ const float * vtcm_g_raw = bctx->vtcm_g_raw[curr_buf];
+ const float * vtcm_b_raw = bctx->vtcm_b_raw[curr_buf];
if (n_batch == 1) {
- hvx_vmem(head->g_f32[curr_buf] + 0) = hvx_vmem(bctx->vtcm_g_raw + 0);
- hvx_vmem(head->g_f32[curr_buf] + 32) = hvx_vmem(bctx->vtcm_g_raw + 32);
- hvx_vmem(head->b_f32[curr_buf] + 0) = hvx_vmem(bctx->vtcm_b_raw + 0);
- hvx_vmem(head->b_f32[curr_buf] + 32) = hvx_vmem(bctx->vtcm_b_raw + 32);
+ hvx_vmem(head->g_f32[curr_buf] + 0) = hvx_vmem(vtcm_g_raw + 0);
+ hvx_vmem(head->g_f32[curr_buf] + 32) = hvx_vmem(vtcm_g_raw + 32);
+ hvx_vmem(head->b_f32[curr_buf] + 0) = hvx_vmem(vtcm_b_raw + 0);
+ hvx_vmem(head->b_f32[curr_buf] + 32) = hvx_vmem(vtcm_b_raw + 32);
} else {
const uint32_t vtcm_stride = (n_batch + 1) * sizeof(float);
const HVX_Vector vv = hvx_vec_gather_offsets_w(vtcm_stride);
- const size_t rt_g = (size_t) ((const uint8_t *) bctx->vtcm_g_raw + i * sizeof(float));
- const size_t rt_b = (size_t) ((const uint8_t *) bctx->vtcm_b_raw + i * sizeof(float));
- const size_t mu = 64 * vtcm_stride;
+ const size_t rt_g = (size_t) ((const uint8_t *) vtcm_g_raw + i * sizeof(float));
+ const size_t rt_b = (size_t) ((const uint8_t *) vtcm_b_raw + i * sizeof(float));
+ const size_t mu = 32 * vtcm_stride - 1;
Q6_vgather_ARMVw((HVX_Vector *) (head->g_f32[curr_buf] + 0), rt_g, mu, vv);
Q6_vgather_ARMVw((HVX_Vector *) (head->g_f32[curr_buf] + 32), rt_g + 32 * vtcm_stride, mu, vv);
Q6_vgather_ARMVw((HVX_Vector *) (head->b_f32[curr_buf] + 0), rt_b, mu, vv);
Q6_vgather_ARMVw((HVX_Vector *) (head->b_f32[curr_buf] + 32), rt_b + 32 * vtcm_stride, mu, vv);
+ hvx_gather_sync(head->b_f32[curr_buf] + 32);
}
const uint32_t t_chunk = bctx->c * 64;
const uint32_t valid_tokens = hex_smin(64, bctx->kparams->n_tokens - t_chunk);
if (valid_tokens < 64) {
- for (uint32_t t = valid_tokens; t < 64; ++t) {
- head->g_f32[curr_buf][t] = 0.0f;
- head->b_f32[curr_buf][t] = 0.0f;
- }
const HVX_Vector vzero = Q6_V_vzero();
+ if (valid_tokens <= 32) {
+ const HVX_VectorPred mask = Q6_Q_vsetq2_R(valid_tokens * sizeof(float));
+ hvx_vmem(head->g_f32[curr_buf] + 0) = Q6_V_vand_QV(mask, hvx_vmem(head->g_f32[curr_buf] + 0));
+ hvx_vmem(head->b_f32[curr_buf] + 0) = Q6_V_vand_QV(mask, hvx_vmem(head->b_f32[curr_buf] + 0));
+ hvx_vmem(head->g_f32[curr_buf] + 32) = vzero;
+ hvx_vmem(head->b_f32[curr_buf] + 32) = vzero;
+ } else {
+ const HVX_VectorPred mask = Q6_Q_vsetq2_R((valid_tokens - 32) * sizeof(float));
+ hvx_vmem(head->g_f32[curr_buf] + 32) = Q6_V_vand_QV(mask, hvx_vmem(head->g_f32[curr_buf] + 32));
+ hvx_vmem(head->b_f32[curr_buf] + 32) = Q6_V_vand_QV(mask, hvx_vmem(head->b_f32[curr_buf] + 32));
+ }
+ const uint32_t q_words = (bctx->octx->src[0]->type == HTP_TYPE_F16) ? (S_v / 2) : S_v;
+ const uint32_t k_words = (bctx->octx->src[1]->type == HTP_TYPE_F16) ? (S_v / 2) : S_v;
+ const uint32_t v_words = (bctx->octx->src[2]->type == HTP_TYPE_F16) ? (S_v / 2) : S_v;
for (uint32_t t = valid_tokens; t < 64; ++t) {
- for (uint32_t j = 0; j < S_v; j += 32) {
- hvx_vmem(head->q_f32[curr_buf] + t * S_v + j) = vzero;
- hvx_vmem(head->k_f32[curr_buf] + t * S_v + j) = vzero;
- hvx_vmem(head->v_f32[curr_buf] + t * S_v + j) = vzero;
+ for (uint32_t j = 0; j < q_words; j += 32) {
+ hvx_vmem(head->q_f32[curr_buf] + t * q_words + j) = vzero;
+ }
+ for (uint32_t j = 0; j < k_words; j += 32) {
+ hvx_vmem(head->k_f32[curr_buf] + t * k_words + j) = vzero;
+ }
+ for (uint32_t j = 0; j < v_words; j += 32) {
+ hvx_vmem(head->v_f32[curr_buf] + t * v_words + j) = vzero;
}
}
}
@@ -1804,13 +2705,20 @@ static void gdn_hvx_phase1a_worker(const htp_thread_t * th, unsigned int n, unsi
HVX_Vector v_l0 = hvx_vec_exp_f32(hvx_clamp_neg20_0(v_gamma0, v_zero, v_neg20));
HVX_Vector v_l1 = hvx_vec_exp_f32(hvx_clamp_neg20_0(v_gamma1, v_zero, v_neg20));
- hvx_vmem(head->lambda_init + 0) = v_l0;
- hvx_vmem(head->lambda_init + 32) = v_l1;
- hvx_vmem(head->lambda_init_f16) = hvx_vec_f32_to_f16(v_l0, v_l1);
+ hvx_vmem(head->lambda_init[curr_buf] + 0) = v_l0;
+ hvx_vmem(head->lambda_init[curr_buf] + 32) = v_l1;
+ hvx_vmem(head->lambda_init_f16) = hvx_vec_f32_to_f16(v_l0, v_l1);
- gdn_f32_to_hmx_row_tiles_and_f16(head->k_row_tiles, head->k_prime_row_tiles, head->k_f16,
- head->k_f32[curr_buf], head->lambda_init_f16, 64, S_v);
- hmx_interleave_rows_to_tiles(head->k_col_tiles, head->k_f16, 64, S_v, S_v, 0, 64);
+ if (bctx->octx->src[1]->type == HTP_TYPE_F16) {
+ const __fp16 * k_f16 = (const __fp16 *) head->k_f32[curr_buf];
+ gdn_f16_to_hmx_row_tiles(head->k_row_tiles, head->k_prime_row_tiles,
+ k_f16, head->lambda_init_f16, 64, S_v);
+ hmx_interleave_rows_to_tiles(head->k_col_tiles, k_f16, 64, S_v, S_v, 0, 64);
+ } else {
+ gdn_f32_to_hmx_row_tiles_and_f16(head->k_row_tiles, head->k_prime_row_tiles, head->k_f16,
+ head->k_f32[curr_buf], head->lambda_init_f16, 64, S_v, true);
+ hmx_interleave_rows_to_tiles(head->k_col_tiles, head->k_f16, 64, S_v, S_v, 0, 64);
+ }
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_PREP, info);
}
@@ -1826,13 +2734,20 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi
const uint32_t curr_buf = bctx->curr_buf;
const uint32_t S_v = bctx->S_v;
- gdn_f32_to_hmx_row_tiles_and_f16(head->q_row_tiles, head->q_prime_row_tiles, NULL,
- head->q_f32[curr_buf], head->lambda_init_f16, 64, S_v);
+ if (bctx->octx->src[0]->type == HTP_TYPE_F16) {
+ gdn_f16_to_hmx_row_tiles(head->q_row_tiles, head->q_prime_row_tiles,
+ (const __fp16 *) head->q_f32[curr_buf], head->lambda_init_f16, 64, S_v);
+ } else {
+ gdn_f32_to_hmx_row_tiles_and_f16(head->q_row_tiles, head->q_prime_row_tiles, NULL,
+ head->q_f32[curr_buf], head->lambda_init_f16, 64, S_v, false);
+ }
- hmx_interleave_cols_to_tiles(head->k_col_tiles_64x128, head->k_f16, 64, S_v, S_v, 2, 0, 64);
+ const __fp16 * k_f16_src = (bctx->octx->src[1]->type == HTP_TYPE_F16)
+ ? (const __fp16 *) head->k_f32[curr_buf]
+ : head->k_f16;
+ hmx_interleave_cols_to_tiles(head->k_col_tiles_64x128[curr_buf], k_f16_src, 64, S_v, S_v, 2, 0, 64);
- const uint16_t * gamma_u16 = (const uint16_t *) head->gamma;
- const HVX_Vector v_gamma = hvx_vmem(head->gamma);
+ const HVX_Vector v_gamma = hvx_vmem(head->gamma);
const HVX_Vector v_zero_f16 = Q6_V_vzero();
const HVX_Vector v_neg20_f16 = hvx_vec_splat_f16(-20.0f);
@@ -1846,8 +2761,8 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi
uint32_t t0 = t;
uint32_t t1 = t + 1;
- HVX_Vector v_gamma_t0 = Q6_Vh_vsplat_R(gamma_u16[t0]);
- HVX_Vector v_gamma_t1 = Q6_Vh_vsplat_R(gamma_u16[t1]);
+ HVX_Vector v_gamma_t0 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_gamma, t0));
+ HVX_Vector v_gamma_t1 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_gamma, t1));
HVX_Vector diff0 = hvx_vec_sub_f16_f16(v_gamma_t0, v_gamma);
HVX_Vector diff1 = hvx_vec_sub_f16_f16(v_gamma_t1, v_gamma);
@@ -1864,8 +2779,8 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi
HVX_Vector diff_log2e0 = hvx_vec_mul_f16_f16(diff0, v_log2e_f16);
HVX_Vector diff_log2e1 = hvx_vec_mul_f16_f16(diff1, v_log2e_f16);
- HVX_Vector v_exp0 = hvx_vec_exp2_f16(diff_log2e0);
- HVX_Vector v_exp1 = hvx_vec_exp2_f16(diff_log2e1);
+ HVX_Vector v_exp0 = hvx_vec_exp2_neg_f16(diff_log2e0);
+ HVX_Vector v_exp1 = hvx_vec_exp2_neg_f16(diff_log2e1);
HVX_VectorPred mask_lt0 = Q6_Q_vsetq2_R(2 * t0);
HVX_VectorPred mask_lt1 = Q6_Q_vsetq2_R(2 * t1);
@@ -1889,14 +2804,14 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi
}
{
- HVX_Vector v_gamma_t = Q6_Vh_vsplat_R(gamma_u16[63]);
+ HVX_Vector v_gamma_t = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_gamma, 63));
HVX_Vector diff = hvx_vec_sub_f16_f16(v_gamma_t, v_gamma);
HVX_VectorPred p_gt = Q6_Q_vcmp_gt_VhfVhf(diff, v_zero_f16);
diff = Q6_V_vmux_QVV(p_gt, v_zero_f16, diff);
diff = Q6_Vhf_vmax_VhfVhf(v_neg20_f16, diff);
HVX_Vector diff_log2e = hvx_vec_mul_f16_f16(diff, v_log2e_f16);
- HVX_Vector v_exp = hvx_vec_exp2_f16(diff_log2e);
+ HVX_Vector v_exp = hvx_vec_exp2_neg_f16(diff_log2e);
HVX_VectorPred mask_lt_t = Q6_Q_vsetq2_R(2 * 63);
HVX_Vector v_m = Q6_V_vand_QV(mask_lt_t, v_exp);
@@ -1930,7 +2845,8 @@ static void gdn_hvx_phase2_worker(const htp_thread_t * th, unsigned int n, unsig
head->decay_m,
head->b_f32[curr_buf],
(__fp16 *) head->vtcm_m,
- (__fp16 *) head->vtcm_m + HMX_FP16_TILE_N_ELMS
+ (__fp16 *) head->vtcm_m + HMX_FP16_TILE_N_ELMS,
+ head->rows_inv
);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_SOLVE, info);
@@ -1938,38 +2854,87 @@ static void gdn_hvx_phase2_worker(const htp_thread_t * th, unsigned int n, unsig
static void gdn_hvx_phase3_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
(void) n;
- struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
- struct htp_thread_trace * tr = th->trace;
- const uint16_t info = (uint16_t) bctx->c;
+ struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
+ struct htp_ops_context * octx = bctx->octx;
+ const struct htp_gdn_kernel_params * kparams = bctx->kparams;
+ struct htp_thread_trace * tr = th->trace;
+ const uint32_t c = bctx->c;
+ const uint16_t info = (uint16_t) c;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_GDN_V_PREP, info);
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
- const uint32_t curr_buf = bctx->curr_buf;
- const uint32_t S_v = bctx->S_v;
-
- gdn_unpack_64xS_tiles_to_f32(head->v_inter_f32, head->v_inter_tiles, S_v);
-
- HVX_VectorAlias local_b[2];
- local_b[0].v = hvx_vmem(head->b_f32[curr_buf] + 0);
- local_b[1].v = hvx_vmem(head->b_f32[curr_buf] + 32);
-
- for (uint32_t t = 0; t < 64; ++t) {
- HVX_Vector vb = hvx_vec_splat_f32(local_b[t / 32].fp32[t % 32]);
- for (uint32_t j = 0; j < S_v; j += 64) {
- HVX_Vector vv0 = hvx_vmem(head->v_f32[curr_buf] + t * S_v + j + 0);
- HVX_Vector vv1 = (j + 32 < S_v) ? hvx_vmem(head->v_f32[curr_buf] + t * S_v + j + 32) : Q6_V_vzero();
- HVX_Vector vi0 = hvx_vmem(head->v_inter_f32 + t * S_v + j + 0);
- HVX_Vector vi1 = (j + 32 < S_v) ? hvx_vmem(head->v_inter_f32 + t * S_v + j + 32) : Q6_V_vzero();
-
- HVX_Vector vp0 = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv0, vi0), vb);
- HVX_Vector vp1 = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv1, vi1), vb);
-
- hvx_vmem(head->v_prime_f16 + t * S_v + j) = hvx_vec_f32_to_f16(vp0, vp1);
+ const uint32_t curr_buf = bctx->curr_buf;
+ const uint32_t S_v = bctx->S_v;
+ const uint32_t n_col_tiles = S_v >> 5;
+ const HVX_Vector v_b_lo = hvx_vmem(head->b_f32[curr_buf] + 0);
+ const HVX_Vector v_b_hi = hvx_vmem(head->b_f32[curr_buf] + 32);
+
+ if (octx->src[2]->type == HTP_TYPE_F16) {
+ const __fp16 * v_f16 = (const __fp16 *) head->v_f32[curr_buf];
+ for (uint32_t r = 0; r < 64; r += 2) {
+ const uint32_t r0 = r >> 5;
+ const uint32_t r1 = (r & 31u) >> 1;
+ const HVX_Vector v_b = r0 ? v_b_hi : v_b_lo;
+ const HVX_Vector vb0 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 0u) & 31u) * 4u));
+ const HVX_Vector vb1 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 1u) & 31u) * 4u));
+
+ for (uint32_t d = 0; d < (S_v >> 6); ++d) {
+ const uint32_t c0 = 2 * d;
+ const HVX_Vector * t_vi0 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * t_vi1 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 1) * HMX_FP16_TILE_N_ELMS);
+ const HVX_VectorPair vp_vi = Q6_W_vdeal_VVR(t_vi1[r1], t_vi0[r1], -2);
+
+ const HVX_VectorPair p_vi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_vi));
+ const HVX_VectorPair p_vv0 = hvx_vec_f16_to_f32(hvx_vmem(v_f16 + (r + 0) * S_v + d * 64));
+ const HVX_Vector vp0_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_lo_W(p_vv0), Q6_V_lo_W(p_vi0)), vb0);
+ const HVX_Vector vp0_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_hi_W(p_vv0), Q6_V_hi_W(p_vi0)), vb0);
+
+ const HVX_VectorPair p_vi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_vi));
+ const HVX_VectorPair p_vv1 = hvx_vec_f16_to_f32(hvx_vmem(v_f16 + (r + 1) * S_v + d * 64));
+ const HVX_Vector vp1_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_lo_W(p_vv1), Q6_V_lo_W(p_vi1)), vb1);
+ const HVX_Vector vp1_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_hi_W(p_vv1), Q6_V_hi_W(p_vi1)), vb1);
+
+ HVX_Vector * t_vp0 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 0) * 2 + r0) * HMX_FP16_TILE_N_ELMS);
+ HVX_Vector * t_vp1 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 1) * 2 + r0) * HMX_FP16_TILE_N_ELMS);
+ t_vp0[r1] = hvx_vec_f32_to_f16_shuff(vp0_lo, vp1_lo);
+ t_vp1[r1] = hvx_vec_f32_to_f16_shuff(vp0_hi, vp1_hi);
+ }
+ }
+ } else {
+ const float * v_f32 = head->v_f32[curr_buf];
+ for (uint32_t r = 0; r < 64; r += 2) {
+ const uint32_t r0 = r >> 5;
+ const uint32_t r1 = (r & 31u) >> 1;
+ const HVX_Vector v_b = r0 ? v_b_hi : v_b_lo;
+ const HVX_Vector vb0 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 0u) & 31u) * 4u));
+ const HVX_Vector vb1 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 1u) & 31u) * 4u));
+
+ for (uint32_t d = 0; d < (S_v >> 6); ++d) {
+ const uint32_t c0 = 2 * d;
+ const HVX_Vector * t_vi0 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * t_vi1 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 1) * HMX_FP16_TILE_N_ELMS);
+ const HVX_VectorPair vp_vi = Q6_W_vdeal_VVR(t_vi1[r1], t_vi0[r1], -2);
+
+ const HVX_VectorPair p_vi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_vi));
+ const HVX_Vector vv0_lo = hvx_vmem(v_f32 + (r + 0) * S_v + d * 64 + 0);
+ const HVX_Vector vv0_hi = hvx_vmem(v_f32 + (r + 0) * S_v + d * 64 + 32);
+ const HVX_Vector vp0_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv0_lo, Q6_V_lo_W(p_vi0)), vb0);
+ const HVX_Vector vp0_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv0_hi, Q6_V_hi_W(p_vi0)), vb0);
+
+ const HVX_VectorPair p_vi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_vi));
+ const HVX_Vector vv1_lo = hvx_vmem(v_f32 + (r + 1) * S_v + d * 64 + 0);
+ const HVX_Vector vv1_hi = hvx_vmem(v_f32 + (r + 1) * S_v + d * 64 + 32);
+ const HVX_Vector vp1_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv1_lo, Q6_V_lo_W(p_vi1)), vb1);
+ const HVX_Vector vp1_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv1_hi, Q6_V_hi_W(p_vi1)), vb1);
+
+ HVX_Vector * t_vp0 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 0) * 2 + r0) * HMX_FP16_TILE_N_ELMS);
+ HVX_Vector * t_vp1 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 1) * 2 + r0) * HMX_FP16_TILE_N_ELMS);
+ t_vp0[r1] = hvx_vec_f32_to_f16_shuff(vp0_lo, vp1_lo);
+ t_vp1[r1] = hvx_vec_f32_to_f16_shuff(vp0_hi, vp1_hi);
+ }
}
}
- hmx_interleave_cols_to_tiles(head->v_prime_col_tiles, head->v_prime_f16, 64, S_v, S_v, 2, 0, 64);
-
gdn_unpack_64x64_tiles_to_vectors(head->rows_qk, head->qk_tiles);
for (uint32_t t = 0; t < 64; ++t) {
HVX_Vector v_decay_a = hvx_vmem(head->decay_a + t * 64);
@@ -1978,6 +2943,35 @@ static void gdn_hvx_phase3_worker(const htp_thread_t * th, unsigned int n, unsig
gdn_pack_64x64_vectors_to_tiles(head->a_row_tiles, head->rows_a);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_V_PREP, info);
+
+ dma_queue * dma_q = th->dma_q;
+ const uint32_t n_chunks = kparams->n_chunks;
+ if (c + 1u < n_chunks) {
+ dma_queue_pop(dma_q);
+ dma_queue_pop(dma_q);
+ dma_queue_pop(dma_q);
+ if (i == 0u) {
+ dma_queue_pop(dma_q);
+ dma_queue_pop(dma_q);
+ }
+ }
+ if (c > 0u) {
+ dma_queue_pop(dma_q);
+ }
+ if (c + 2u < n_chunks) {
+ const uint32_t chunk_size = kparams->chunk_size;
+ const uint32_t t_c2 = (c + 2u) * chunk_size;
+ const uint32_t c2_tokens = hex_smin(chunk_size, kparams->n_tokens - t_c2);
+ gdn_dma_push_chunk_inputs(dma_q, head->q_f32[curr_buf], head->k_f32[curr_buf], head->v_f32[curr_buf],
+ octx->src[0], octx->src[1], octx->src[2],
+ head->iq3, head->iq1, head->ik3, head->ik1,
+ head->iv3, head->iv1, t_c2, c2_tokens, S_v);
+ if (i == 0u) {
+ gdn_dma_push_chunk_gb(dma_q, bctx->vtcm_g_raw[curr_buf], bctx->vtcm_b_raw[curr_buf],
+ octx->src[3], octx->src[4], bctx->iv3, bctx->head_in_seq,
+ t_c2, c2_tokens, bctx->n_batch);
+ }
+ }
}
static void gdn_hvx_phase4_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
@@ -1990,50 +2984,140 @@ static void gdn_hvx_phase4_worker(const htp_thread_t * th, unsigned int n, unsig
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
const uint32_t S_v = bctx->S_v;
- gdn_unpack_64xS_tiles_to_f16(head->delta_f16, head->delta_tiles, S_v);
- hmx_interleave_cols_to_tiles(head->delta_col_tiles, head->delta_f16, 64, S_v, S_v, 2, 0, 64);
+ const HVX_Vector v_decay_last = hvx_vmem(head->decay_a + 63 * 64);
+ const HVX_Vector vzero = Q6_V_vzero();
+ HVX_Vector * restrict m = head->vtcm_m;
+ HVX_Vector * restrict tmp = head->vtcm_tmp;
+
+ for (uint32_t col_half = 0; col_half < (S_v >> 6); ++col_half) {
+ const uint32_t r0_base = col_half * 2;
+ for (uint32_t c0 = 0; c0 < 2; ++c0) {
+ // delta_tiles is stored in col-major tile order [col_tile][row_tile]
+ const HVX_Vector * src0 = (const HVX_Vector *) (head->delta_tiles + ((2 * col_half + 0) * 2 + c0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * src1 = (const HVX_Vector *) (head->delta_tiles + ((2 * col_half + 1) * 2 + c0) * HMX_FP16_TILE_N_ELMS);
+
+ for (uint32_t r = 0; r < 16; ++r) {
+ const uint32_t s0 = c0 * 32 + 2 * r + 0;
+ const uint32_t s1 = c0 * 32 + 2 * r + 1;
+ const HVX_VectorPair vp = Q6_W_vdeal_VVR(src1[r], src0[r], -2);
+
+ const HVX_Vector vs0 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_decay_last, s0));
+ const HVX_Vector vs1 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_decay_last, s1));
+ const HVX_VectorPred p_z0 = Q6_Q_vcmp_eq_VhVh(vs0, vzero);
+ const HVX_VectorPred p_z1 = Q6_Q_vcmp_eq_VhVh(vs1, vzero);
+
+ m[2 * r + 0] = Q6_V_vmux_QVV(p_z0, vzero, hvx_vec_mul_f16_f16(Q6_V_lo_W(vp), vs0));
+ m[2 * r + 1] = Q6_V_vmux_QVV(p_z1, vzero, hvx_vec_mul_f16_f16(Q6_V_hi_W(vp), vs1));
+ }
+
+ hvx_transpose_32x32_w_shuff_inplace(m, tmp);
- const uint16_t * decay_last = (const uint16_t *) (head->decay_a + 63 * 64);
- const HVX_Vector vzero = Q6_V_vzero();
+ const uint32_t tile0_idx = (r0_base + 0) * 2 + c0;
+ const uint32_t tile1_idx = (r0_base + 1) * 2 + c0;
+ HVX_Vector * dst0 = (HVX_Vector *) (head->d_row_tiles + tile0_idx * HMX_FP16_TILE_N_ELMS);
+ HVX_Vector * dst1 = (HVX_Vector *) (head->d_row_tiles + tile1_idx * HMX_FP16_TILE_N_ELMS);
- for (uint32_t s = 0; s < 64; ++s) {
- HVX_Vector vs = Q6_Vh_vsplat_R(decay_last[s]);
- HVX_VectorPred p_zero = Q6_Q_vcmp_eq_VhVh(vs, vzero);
- for (uint32_t j = 0; j < S_v; j += 64) {
- HVX_Vector vd = hvx_vmem(head->delta_f16 + s * S_v + j);
- HVX_Vector prod = hvx_vec_mul_f16_f16(vd, vs);
- hvx_vmem(head->d_f16 + s * S_v + j) = Q6_V_vmux_QVV(p_zero, vzero, prod);
+ for (uint32_t r = 0; r < 16; ++r) {
+ dst0[r] = m[r];
+ dst1[r] = m[16 + r];
+ }
}
}
- gdn_pack_d_t_row_tiles(head->d_row_tiles, head->d_f16, S_v, head->vtcm_m, head->vtcm_tmp);
-
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_D_PREP, info);
}
static void gdn_hvx_phase5_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
(void) n;
- struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
- struct htp_thread_trace * tr = th->trace;
- const uint16_t info = (uint16_t) bctx->c;
+ struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
+ const struct htp_gdn_kernel_params * kparams = bctx->kparams;
+ const struct htp_tensor * dst = bctx->octx->dst;
+ struct htp_thread_trace * tr = th->trace;
+ const uint32_t c = bctx->c;
+ const uint16_t info = (uint16_t) c;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_GDN_OUT, info);
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
- const uint32_t curr_buf = bctx->curr_buf;
- const uint32_t S_v = bctx->S_v;
- const float scale = bctx->scale;
-
- gdn_unpack_64xS_tiles_to_f32(head->o_inter_f32, head->o_inter_tiles, S_v);
- gdn_unpack_64xS_tiles_to_f32(head->o_intra_f32, head->o_intra_tiles, S_v);
-
- HVX_Vector vscale = hvx_vec_splat_f32(scale);
- for (uint32_t j = 0; j < 64 * S_v / 32; ++j) {
- HVX_Vector vi = hvx_vmem(head->o_inter_f32 + j * 32);
- HVX_Vector va = hvx_vmem(head->o_intra_f32 + j * 32);
- hvx_vmem(head->o_f32[curr_buf] + j * 32) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(vi, va), vscale);
+ const uint32_t curr_buf = bctx->curr_buf;
+ const uint32_t S_v = bctx->S_v;
+ const uint32_t n_col_tiles = S_v >> 5;
+ const HVX_Vector vscale = hvx_vec_splat_f32(bctx->scale);
+
+ if (dst->type == HTP_TYPE_F16) {
+ __fp16 * o_f16 = (__fp16 *) head->o_f32[curr_buf];
+ const HVX_Vector v_min = hvx_vec_splat_f32(-65504.0f);
+ const HVX_Vector v_max = hvx_vec_splat_f32(65504.0f);
+
+ for (uint32_t r0 = 0; r0 < 2; ++r0) {
+ for (uint32_t d = 0; d < (S_v >> 6); ++d) {
+ const HVX_Vector * ti0 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * ti1 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * ta0 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * ta1 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
+
+ for (uint32_t r = 0; r < 16; ++r) {
+ const HVX_VectorPair vp_i = Q6_W_vdeal_VVR(ti1[r], ti0[r], -2);
+ const HVX_VectorPair vp_a = Q6_W_vdeal_VVR(ta1[r], ta0[r], -2);
+
+ const HVX_VectorPair pi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_i));
+ const HVX_VectorPair pa0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_a));
+ const HVX_Vector vo0_lo = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi0), Q6_V_lo_W(pa0)), vscale), v_min, v_max);
+ const HVX_Vector vo0_hi = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi0), Q6_V_hi_W(pa0)), vscale), v_min, v_max);
+
+ const HVX_VectorPair pi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_i));
+ const HVX_VectorPair pa1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_a));
+ const HVX_Vector vo1_lo = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi1), Q6_V_lo_W(pa1)), vscale), v_min, v_max);
+ const HVX_Vector vo1_hi = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi1), Q6_V_hi_W(pa1)), vscale), v_min, v_max);
+
+ __fp16 * out0 = o_f16 + (r0 * 32 + 2 * r + 0) * S_v + d * 64;
+ __fp16 * out1 = o_f16 + (r0 * 32 + 2 * r + 1) * S_v + d * 64;
+
+ hvx_vmem(out0) = hvx_vec_f32_to_f16(vo0_lo, vo0_hi);
+ hvx_vmem(out1) = hvx_vec_f32_to_f16(vo1_lo, vo1_hi);
+ }
+ }
+ }
+ } else {
+ float * o_f32 = head->o_f32[curr_buf];
+
+ for (uint32_t r0 = 0; r0 < 2; ++r0) {
+ for (uint32_t d = 0; d < (S_v >> 6); ++d) {
+ const HVX_Vector * ti0 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * ti1 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * ta0 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * ta1 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
+
+ for (uint32_t r = 0; r < 16; ++r) {
+ const HVX_VectorPair vp_i = Q6_W_vdeal_VVR(ti1[r], ti0[r], -2);
+ const HVX_VectorPair vp_a = Q6_W_vdeal_VVR(ta1[r], ta0[r], -2);
+
+ const HVX_VectorPair pi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_i));
+ const HVX_VectorPair pa0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_a));
+ const HVX_VectorPair pi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_i));
+ const HVX_VectorPair pa1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_a));
+
+ float * out0 = o_f32 + (r0 * 32 + 2 * r + 0) * S_v + d * 64;
+ float * out1 = o_f32 + (r0 * 32 + 2 * r + 1) * S_v + d * 64;
+
+ hvx_vmem(out0 + 0) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi0), Q6_V_lo_W(pa0)), vscale);
+ hvx_vmem(out0 + 32) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi0), Q6_V_hi_W(pa0)), vscale);
+ hvx_vmem(out1 + 0) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi1), Q6_V_lo_W(pa1)), vscale);
+ hvx_vmem(out1 + 32) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi1), Q6_V_hi_W(pa1)), vscale);
+ }
+ }
+ }
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_OUT, info);
+
+ const uint32_t chunk_size = kparams->chunk_size;
+ const uint32_t t_chunk = c * chunk_size;
+ const uint32_t valid_tokens = hex_smin(chunk_size, kparams->n_tokens - t_chunk);
+ const uint32_t row_out_bytes = S_v * ((dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float));
+ const dma_addr_t attn_chunk_dma = dst->data +
+ ((size_t) head->iv3 * kparams->n_tokens * kparams->H + (size_t) t_chunk * kparams->H + head->iv1) * row_out_bytes;
+ dma_queue_push(th->dma_q, dma_make_data(attn_chunk_dma, head->o_f32[curr_buf]),
+ dst->nb[1], row_out_bytes, row_out_bytes, valid_tokens);
}
static void gdn_hvx_phase6_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
@@ -2044,29 +3128,74 @@ static void gdn_hvx_phase6_worker(const htp_thread_t * th, unsigned int n, unsig
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_GDN_STATE, info);
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
- const uint32_t S_v = bctx->S_v;
- const uint32_t c = bctx->c;
- const uint32_t n_chunks = bctx->kparams->n_chunks;
+ const uint32_t curr_buf = bctx->curr_buf;
+ const uint32_t S_v = bctx->S_v;
+ const uint32_t c = bctx->c;
+ const uint32_t n_chunks = bctx->kparams->n_chunks;
+ const uint32_t n_tiles = S_v >> 5;
+ const HVX_Vector v_l_final = hvx_vec_splat_f32(gdn_vtcm_load_f32(head->lambda_init[curr_buf], 63));
+ const bool pack_next = (c + 1 < n_chunks);
+ const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
+ const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
+ const size_t pair_region = (size_t) (2 * HMX_FP16_TILE_SIZE - 1);
- gdn_unpack_SxS_tiles_to_f32(head->s_update_f32, head->s_update_tiles, S_v);
-
- HVX_VectorAlias last_lambda;
- last_lambda.v = hvx_vmem(head->lambda_init + 32);
- HVX_Vector v_l_final = hvx_vec_splat_f32(last_lambda.fp32[31]);
+ for (uint32_t r0 = 0; r0 < n_tiles; ++r0) {
+ for (uint32_t d = 0; d < (S_v >> 6); ++d) {
+ const HVX_Vector * t0 = (const HVX_Vector *) (head->s_update_tiles + (r0 * n_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS);
+ const HVX_Vector * t1 = (const HVX_Vector *) (head->s_update_tiles + (r0 * n_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS);
+ __fp16 * tile_base = head->s_col_tiles + (size_t) (r0 * n_tiles + 2 * d) * HMX_FP16_TILE_N_ELMS;
- for (uint32_t j = 0; j < S_v * S_v / 32; ++j) {
- HVX_Vector vs_old = hvx_vmem(head->s_state + j * 32);
- HVX_Vector vsu = hvx_vmem(head->s_update_f32 + j * 32);
- hvx_vmem(head->s_state + j * 32) = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(vs_old, v_l_final), vsu);
+ for (uint32_t r = 0; r < 16; ++r) {
+ const HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2);
+ const HVX_VectorPair p0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp01));
+ const HVX_VectorPair p1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp01));
+
+ float * s0 = head->s_state + (r0 * 32 + 2 * r + 0) * S_v + d * 64;
+ float * s1 = head->s_state + (r0 * 32 + 2 * r + 1) * S_v + d * 64;
+
+ const HVX_Vector ns0_lo = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s0 + 0), v_l_final), Q6_V_lo_W(p0));
+ const HVX_Vector ns0_hi = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s0 + 32), v_l_final), Q6_V_hi_W(p0));
+ const HVX_Vector ns1_lo = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s1 + 0), v_l_final), Q6_V_lo_W(p1));
+ const HVX_Vector ns1_hi = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s1 + 32), v_l_final), Q6_V_hi_W(p1));
+
+ hvx_vmem(s0 + 0) = ns0_lo;
+ hvx_vmem(s0 + 32) = ns0_hi;
+ hvx_vmem(s1 + 0) = ns1_lo;
+ hvx_vmem(s1 + 32) = ns1_hi;
+
+ if (pack_next) {
+ const HVX_Vector v_off0 = Q6_Vw_vadd_VwVw(v_scat_base, Q6_V_vsplat_R(2 * r * 4));
+ const HVX_Vector v_off1 = Q6_Vw_vadd_VwVw(v_off0, v_scat_step);
+ const HVX_Vector v0_f16 = hvx_vec_f32_to_f16(ns0_lo, ns0_hi);
+ const HVX_Vector v1_f16 = hvx_vec_f32_to_f16(ns1_lo, ns1_hi);
+ Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off0, v0_f16);
+ Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off1, v1_f16);
+ }
+ }
+ }
}
- if (c + 1 < n_chunks) {
- gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, S_v);
+ if (pack_next) {
+ hvx_gather_sync(head->s_col_tiles);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_STATE, info);
}
+static void gdn_hvx_epilogue_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
+ struct htp_gdn_head_ptrs * head = &bctx->heads[i];
+ dma_queue * dma_q = th->dma_q;
+ const uint32_t S_v = bctx->S_v;
+
+ dma_queue_pop(dma_q);
+ if (!bctx->keep) {
+ dma_queue_push(dma_q, dma_make_data(head->state_out_dma, head->s_state),
+ S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
+ }
+ dma_queue_flush(dma_q);
+}
static int gated_delta_net_f32_hmx_chunked(
struct htp_ops_context * octx,
@@ -2074,12 +3203,17 @@ static int gated_delta_net_f32_hmx_chunked(
uint32_t row_start,
uint32_t nrows
) {
+ if (kparams->n_chunks == 0) {
+ return HTP_STATUS_OK;
+ }
+
const struct htp_tensor * q = octx->src[0];
const struct htp_tensor * k = octx->src[1];
const struct htp_tensor * v = octx->src[2];
- const struct htp_tensor * g = octx->src[3];
- const struct htp_tensor * beta = octx->src[4];
const struct htp_tensor * state = octx->src[5];
+ const bool replay = gdn_has_replay(octx);
+ const struct htp_tensor * ids = replay ? NULL : octx->src[6];
+ const struct htp_tensor * n_rep = replay ? octx->src[9] : NULL;
const struct htp_tensor * dst = octx->dst;
const struct htp_tensor * dst_cache = octx->dsts[1];
@@ -2089,265 +3223,195 @@ static int gated_delta_net_f32_hmx_chunked(
const float scale = kparams->scale;
const uint32_t chunk_size = kparams->chunk_size;
const uint32_t n_chunks = kparams->n_chunks;
- const uint32_t n_sv_tiles = S_v / 32;
- const bool keep = octx->src[6] && octx->op_params[2] != 0;
+ const uint32_t n_pend = replay ? (uint32_t) octx->op_params[1] : 0;
+ const bool keep = replay && octx->op_params[2] != 0;
struct htp_gdn_hmx_vtcm_layout L;
- htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx, kparams->pipeline != 0);
+ htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx);
if (L.total_bytes > octx->ctx->vtcm_size) {
return HTP_STATUS_VTCM_TOO_SMALL;
}
uint8_t * const vtcm_base = (uint8_t *) octx->ctx->vtcm_base;
-
- float * vtcm_g_raw[2] = {
- VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[0]),
- L.pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[1]) : VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[0])
- };
- float * vtcm_b_raw[2] = {
- VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[0]),
- L.pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[1]) : VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[0])
- };
+ void * aux_buf = NULL;
+ const int aux_err = gdn_prepare_aux_data(octx, replay ? n_rep : ids, &aux_buf);
+ if (aux_err != HTP_STATUS_OK) {
+ return aux_err;
+ }
+ const void * ids_buf = replay ? NULL : aux_buf;
+ const int32_t * n_rep_buf = replay ? (const int32_t *) aux_buf : NULL;
+ const uint32_t ids_type = ids ? ids->type : 0;
uint8_t * vtcm_scales_1 = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L.off_scales_1);
hmx_init_column_scales(vtcm_scales_1, Q6_V_vsplat_R(0x3c00));
hmx_queue_t hmx_q = octx->ctx->hmx_queue;
- dma_queue * dma_q = octx->ctx->dma[0];
work_queue_t wp = octx->ctx->hvx_queue;
struct htp_gdn_head_ptrs heads[8];
- struct htp_gdn_hmx_gemm_task gemm_tasks[8][9];
+
+ struct htp_gdn_batch_context bctx;
+ bctx.heads = heads;
+ bctx.vtcm_g_raw[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[0]);
+ bctx.vtcm_g_raw[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[1]);
+ bctx.vtcm_b_raw[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[0]);
+ bctx.vtcm_b_raw[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[1]);
+ bctx.hmx_scales = vtcm_scales_1;
+ bctx.n_rep_data = n_rep_buf;
+ bctx.n_pend = n_pend;
+ bctx.replay = replay;
+ bctx.keep = keep;
+ bctx.S_v = S_v;
+ bctx.scale = scale;
+ bctx.octx = octx;
+ bctx.kparams = kparams;
uint32_t n_batch = 1;
for (uint32_t r = row_start; r < row_start + nrows; r += n_batch) {
const uint32_t head_in_seq = fastmodulo(r, H, &kparams->div_H);
const uint32_t iv3 = fastdiv(r, &kparams->div_H);
+ const uint32_t is3 = gdn_read_seq_idx(ids_buf, ids_type, iv3);
const uint32_t heads_left_in_seq = H - head_in_seq;
const uint32_t heads_left_in_range = (row_start + nrows) - r;
n_batch = hex_smin((uint32_t) kparams->n_heads_batch, hex_smin(heads_left_in_seq, heads_left_in_range));
for (uint32_t h = 0; h < n_batch; ++h) {
- gdn_init_head_ptrs(&heads[h], &L, vtcm_base, h, head_in_seq, iv3,
+ gdn_init_head_ptrs(&heads[h], &L, vtcm_base, h, head_in_seq, iv3, is3,
q, k, v, state, dst, dst_cache, kparams, S_v, H, n_tokens, chunk_size);
}
- struct htp_gdn_batch_context bctx;
- bctx.heads = heads;
- bctx.vtcm_g_raw = NULL;
- bctx.vtcm_b_raw = NULL;
- bctx.curr_buf = 0;
- bctx.c = 0;
- bctx.n_batch = n_batch;
- bctx.S_v = S_v;
- bctx.scale = scale;
- bctx.octx = octx;
- bctx.kparams = kparams;
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_push(dma_q, dma_make_data(heads[h].s_state, heads[h].state_in_dma),
- S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
- }
-
- if (n_chunks > 0) {
- work_queue_run(wp, gdn_hvx_replay_init_state_worker, &bctx, n_batch);
-
- if (keep) {
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
- S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
- }
- }
-
- const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens);
- for (uint32_t h = 0; h < n_batch; ++h) {
- gdn_dma_push_chunk_inputs(dma_q, heads[h].q_f32[0], heads[h].k_f32[0], heads[h].v_f32[0],
- q, k, v, heads[h].iq3, heads[h].iq1, heads[h].ik3, heads[h].ik1,
- heads[h].iv3, heads[h].iv1, 0, chunk0_tokens, S_v);
- }
- gdn_dma_push_chunk_gb(dma_q, vtcm_g_raw[0], vtcm_b_raw[0], g, beta, iv3, head_in_seq, 0, chunk0_tokens, n_batch);
- }
-
- for (uint32_t c = 0; c < n_chunks; ++c) {
- const uint32_t curr_buf = c & 1;
- const uint32_t next_buf = (c + 1) & 1;
- const uint32_t t_chunk = c * chunk_size;
-
- bctx.curr_buf = curr_buf;
- bctx.c = c;
- bctx.vtcm_g_raw = vtcm_g_raw[curr_buf];
- bctx.vtcm_b_raw = vtcm_b_raw[curr_buf];
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
- dma_queue_pop(dma_q);
- dma_queue_pop(dma_q);
- }
- dma_queue_pop(dma_q);
- dma_queue_pop(dma_q);
-
- if (c + 1 < n_chunks) {
- const uint32_t next_t_chunk = (c + 1) * chunk_size;
- const uint32_t next_tokens = hex_smin(chunk_size, n_tokens - next_t_chunk);
- for (uint32_t h = 0; h < n_batch; ++h) {
- gdn_dma_push_chunk_inputs(dma_q, heads[h].q_f32[next_buf], heads[h].k_f32[next_buf], heads[h].v_f32[next_buf],
- q, k, v, heads[h].iq3, heads[h].iq1, heads[h].ik3, heads[h].ik1,
- heads[h].iv3, heads[h].iv1, next_t_chunk, next_tokens, S_v);
- }
- gdn_dma_push_chunk_gb(dma_q, vtcm_g_raw[next_buf], vtcm_b_raw[next_buf],
- g, beta, iv3, head_in_seq, next_t_chunk, next_tokens, n_batch);
- }
-
- if (c > 0) {
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
- }
- }
-
- work_queue_run(wp, gdn_hvx_phase1a_worker, &bctx, n_batch);
+ bctx.head_in_seq = head_in_seq;
+ bctx.iv3 = iv3;
+ bctx.n_batch = n_batch;
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][0], heads[h].k_row_tiles, heads[h].k_col_tiles, heads[h].kk_tiles, 2, 2, n_sv_tiles, vtcm_scales_1);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][2], heads[h].k_prime_row_tiles, heads[h].s_col_tiles, heads[h].v_inter_tiles, 2, n_sv_tiles, n_sv_tiles, vtcm_scales_1);
- }
+ work_queue_run(wp, gdn_hvx_prologue_worker, &bctx, n_batch);
- work_queue_run(wp, gdn_hvx_phase1b_worker, &bctx, n_batch);
+ // Prologue: prepare chunk 0 (phase1a, KK, phase1b, QK + KS in-flight)
+ bctx.c = 0u;
+ bctx.curr_buf = 0u;
+ work_queue_run(wp, gdn_hvx_phase1a_worker, &bctx, n_batch);
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_kk_worker, &bctx));
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
+ work_queue_run(wp, gdn_hvx_phase1b_worker, &bctx, n_batch);
+ hmx_queue_pop(hmx_q);
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_qk_worker, &bctx));
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_ks_worker, &bctx));
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][1], heads[h].q_row_tiles, heads[h].k_col_tiles, heads[h].qk_tiles, 2, 2, n_sv_tiles, vtcm_scales_1);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][3], heads[h].q_prime_row_tiles, heads[h].s_col_tiles, heads[h].o_inter_tiles, 2, n_sv_tiles, n_sv_tiles, vtcm_scales_1);
- }
+ // Pipelined chunk loop: overlap chunk c tail with chunk c+1 prep
+ for (uint32_t c = 0u; c < n_chunks; ++c) {
+ const uint32_t curr_buf = c & 1u;
+ const uint32_t next_buf = (c + 1u) & 1u;
+ const bool has_next = (c + 1u < n_chunks);
+ // Step 1: HMX QK(c) + KS(c) || HVX phase2(c)
+ bctx.c = c;
+ bctx.curr_buf = curr_buf;
work_queue_run(wp, gdn_hvx_phase2_worker, &bctx, n_batch);
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_inv10_worker, &bctx));
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_qs_worker, &bctx));
+ hmx_queue_pop(hmx_q); // QK(c)
+ hmx_queue_pop(hmx_q); // KS(c)
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(
- hmx_q, &gemm_tasks[h][7],
- (__fp16 *) heads[h].vtcm_m,
- heads[h].inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS,
- (__fp16 *) heads[h].vtcm_tmp,
- 1, 1, 1, vtcm_scales_1
- );
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(
- hmx_q, &gemm_tasks[h][8],
- (__fp16 *) heads[h].vtcm_m + HMX_FP16_TILE_N_ELMS,
- (__fp16 *) heads[h].vtcm_tmp,
- heads[h].inv_row_tiles + 2 * HMX_FP16_TILE_N_ELMS,
- 1, 1, 1, vtcm_scales_1
- );
- }
-
+ // Step 2: HMX INV_10(c) + QS(c) || HVX phase3(c) + DMA pop(c+1)/push(c+2)
work_queue_run(wp, gdn_hvx_phase3_worker, &bctx, n_batch);
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][4], heads[h].inv_row_tiles, heads[h].v_prime_col_tiles, heads[h].delta_tiles, 2, n_sv_tiles, 2, vtcm_scales_1);
+ hmx_queue_pop(hmx_q); // INV_10(c)
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_delta_worker, &bctx));
+
+ // Step 3: HMX QS(c) tail + DELTA(c) || HVX phase1a(c+1)
+ if (has_next) {
+ bctx.c = c + 1u;
+ bctx.curr_buf = next_buf;
+ work_queue_run(wp, gdn_hvx_phase1a_worker, &bctx, n_batch);
}
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
+ hmx_queue_pop(hmx_q); // QS(c)
+ hmx_queue_pop(hmx_q); // DELTA(c)
+ if (has_next) {
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_kk_worker, &bctx));
}
+ // Step 4: HMX KK(c+1) || HVX phase4(c)
+ bctx.c = c;
+ bctx.curr_buf = curr_buf;
+ bctx.s_update_buf = curr_buf;
work_queue_run(wp, gdn_hvx_phase4_worker, &bctx, n_batch);
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][5], heads[h].a_row_tiles, heads[h].delta_col_tiles, heads[h].o_intra_tiles, 2, n_sv_tiles, 2, vtcm_scales_1);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][6], heads[h].d_row_tiles, heads[h].k_col_tiles_64x128, heads[h].s_update_tiles, n_sv_tiles, n_sv_tiles, 2, vtcm_scales_1);
- }
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_o_intra_worker, &bctx));
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_s_update_worker, &bctx));
+
+ // Step 5: HMX O_INTRA(c) + S_UPDATE(c) || HVX phase1b(c+1)
+ if (has_next) {
+ bctx.c = c + 1u;
+ bctx.curr_buf = next_buf;
+ work_queue_run(wp, gdn_hvx_phase1b_worker, &bctx, n_batch);
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_qk_worker, &bctx));
+ hmx_queue_pop(hmx_q); // KK(c+1)
}
+ hmx_queue_pop(hmx_q); // O_INTRA(c)
+ // Step 6: HMX S_UPDATE(c) tail + QK(c+1) || HVX phase5(c) + DMA store O(c)
+ bctx.c = c;
+ bctx.curr_buf = curr_buf;
work_queue_run(wp, gdn_hvx_phase5_worker, &bctx, n_batch);
+ hmx_queue_pop(hmx_q); // S_UPDATE(c)
- const uint32_t valid_tokens = hex_smin(chunk_size, n_tokens - t_chunk);
- for (uint32_t h = 0; h < n_batch; ++h) {
- const dma_addr_t attn_chunk_dma = dst->data +
- ((uint64_t) heads[h].iv3 * n_tokens * H + (uint64_t) t_chunk * H + heads[h].iv1) * S_v * sizeof(float);
- dma_queue_push(dma_q, dma_make_data(attn_chunk_dma, heads[h].o_f32[curr_buf]),
- dst->nb[1], S_v * sizeof(float), S_v * sizeof(float), valid_tokens);
- }
-
- for (uint32_t h = 0; h < n_batch; ++h) {
- hmx_queue_pop(hmx_q);
- }
-
+ // Step 7: HMX QK(c+1) tail || HVX phase6(c)
work_queue_run(wp, gdn_hvx_phase6_worker, &bctx, n_batch);
- }
-
- if (n_chunks > 0) {
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
+ if (has_next) {
+ hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_ks_worker, &bctx));
}
}
- if (!keep) {
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
- S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
- }
- }
+ work_queue_run(wp, gdn_hvx_epilogue_worker, &bctx, n_batch);
}
- dma_queue_flush(dma_q);
+ if (aux_buf && aux_buf != octx->ctx->ddr_spad_base) {
+ free(aux_buf);
+ }
return HTP_STATUS_OK;
}
int op_gated_delta_net(struct htp_ops_context * octx) {
- const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * dst_cache = octx->dsts[1];
- for (int i = 0; i < 10; i++) {
- if (htp_tensor_is_extended(octx->src[i])) {
+ for (int i = 0; i < 3; i++) {
+ if (octx->src[i]->type != HTP_TYPE_F32 && octx->src[i]->type != HTP_TYPE_F16) {
return HTP_STATUS_NO_SUPPORT;
}
}
- if (htp_tensor_is_extended(octx->dst)) {
- return HTP_STATUS_NO_SUPPORT;
+ for (int i = 3; i < 6; i++) {
+ if (octx->src[i]->type != HTP_TYPE_F32) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ }
+ const bool replay = gdn_has_replay(octx);
+ const struct htp_tensor * ids = replay ? NULL : octx->src[6];
+ const struct htp_tensor * n_rep = replay ? octx->src[9] : NULL;
+ if (replay) {
+ if (!octx->src[8] || !octx->src[9] ||
+ octx->src[6]->type != HTP_TYPE_F32 ||
+ octx->src[7]->type != HTP_TYPE_F32 ||
+ octx->src[8]->type != HTP_TYPE_F32 ||
+ octx->src[9]->type != HTP_TYPE_I32) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ } else {
+ if (octx->src[7] || octx->src[8] || octx->src[9]) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ if (ids && ids->type != HTP_TYPE_I32 && ids->type != HTP_TYPE_I64) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
}
- if (octx->dsts[1]) {
- const struct htp_tensor * dst_cache = octx->dsts[1];
- if (dst_cache->type != HTP_TYPE_F32 || htp_tensor_is_extended(dst_cache)) {
+ if (dst_cache) {
+ if (dst_cache->type != HTP_TYPE_F32) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ if (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16) {
return HTP_STATUS_NO_SUPPORT;
}
+ } else if (dst->type != HTP_TYPE_F32) {
+ return HTP_STATUS_NO_SUPPORT;
}
const struct htp_gdn_kernel_params * kparams = (const struct htp_gdn_kernel_params *) octx->kernel_params;
@@ -2362,11 +3426,9 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_mdev_data_aligned(dst) &&
- ((dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
total_rows,
- can_split ? 1 : 0,
+ 1,
octx->ctx->mdev.idx,
octx->ctx->mdev.count,
&octx->ctx->mdev.count_div
@@ -2390,6 +3452,11 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
gctx.kparams = kparams;
gctx.row_start = row_start;
gctx.nrows = nrows;
+ gctx.load_q = (octx->src[0]->type == HTP_TYPE_F16) ? gdn_load_vec_f16_to_f32 : gdn_load_vec_f32;
+ gctx.load_k = (octx->src[1]->type == HTP_TYPE_F16) ? gdn_load_vec_f16_to_f32 : gdn_load_vec_f32;
+ gctx.load_v = (octx->src[2]->type == HTP_TYPE_F16) ? gdn_load_vec_f16_to_f32 : gdn_load_vec_f32;
+ gctx.store_out = (dst->type == HTP_TYPE_F16) ? gdn_store_vec_f16 : gdn_store_vec_f32;
+ gctx.step_fn = kparams->kda ? gdn_step_kda_f32 : gdn_step_scalar_f32;
htp_gdn_vtcm_layout_build(&gctx.layout, S_v, n_hvx);
gctx.vtcm_base = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, gctx.layout.off_state);
@@ -2398,6 +3465,18 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
return HTP_STATUS_VTCM_TOO_SMALL;
}
+ void * aux_buf = NULL;
+ const int aux_err = gdn_prepare_aux_data(octx, replay ? n_rep : ids, &aux_buf);
+ if (aux_err != HTP_STATUS_OK) {
+ return aux_err;
+ }
+ gctx.ids_type = ids ? ids->type : 0;
+ gctx.ids_data = replay ? NULL : aux_buf;
+ gctx.n_rep_data = replay ? (const int32_t *) aux_buf : NULL;
+ gctx.n_pend = replay ? (uint32_t) octx->op_params[1] : 0;
+ gctx.replay = replay;
+ gctx.keep = replay && octx->op_params[2] != 0;
+
FARF(HIGH, "gated-delta-net-f32: q(%ux%ux%ux%u) k(%ux%ux%ux%u) v(%ux%ux%ux%u) state(%ux%ux%ux%u) -> (%ux%ux%ux%u) : "
"vtcm-size %zu n_hvx %u\n",
octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3],
@@ -2407,11 +3486,25 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
gctx.layout.total_bytes, n_hvx);
- if (n_tokens == 1) {
+ bool has_replay_work = gctx.keep;
+ if (replay && !has_replay_work) {
+ for (uint32_t s = 0; s < kparams->n_seqs; ++s) {
+ if (gctx.n_rep_data[s] > 0) {
+ has_replay_work = true;
+ break;
+ }
+ }
+ }
+
+ if (n_tokens == 1 && !has_replay_work) {
work_queue_run(octx->ctx->hvx_queue, gated_delta_net_f32_tg_thread, &gctx, n_hvx);
} else {
work_queue_run(octx->ctx->hvx_queue, gated_delta_net_f32_pp_thread, &gctx, n_hvx);
}
+ if (aux_buf && aux_buf != octx->ctx->ddr_spad_base) {
+ free(aux_buf);
+ }
+
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h
index aff1eb645..930881c17 100644
--- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h
+++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h
@@ -12,6 +12,7 @@
#define HTP_GDN_MAX_SV 128
#define HTP_GDN_CHUNK_SIZE 64
#define HTP_GDN_MIN_TOKENS 8
+#define HTP_GDN_TOKEN_TILE 16
#ifndef HMX_FP16_TILE_SIZE
#define HMX_FP16_TILE_SIZE 2048
@@ -24,7 +25,7 @@ enum htp_gdn_kernel_type {
struct htp_gdn_kernel_params {
uint8_t kernel_type;
- uint8_t pipeline;
+ uint8_t reserved0;
uint16_t chunk_size;
uint16_t n_chunks;
uint16_t n_heads_batch;
@@ -59,6 +60,12 @@ _Static_assert(sizeof(struct htp_gdn_kernel_params) <= 128, "htp_gdn_kernel_para
struct htp_gdn_vtcm_layout {
size_t state_aligned;
+ size_t scratch_bytes;
+ size_t tile_vec_bytes;
+ size_t tile_scalar_bytes;
+ size_t spad_stride;
+ size_t off_scratch;
+ size_t off_spad;
size_t bytes_per_hvx;
size_t off_state;
size_t total_bytes;
@@ -69,9 +76,16 @@ static inline void htp_gdn_vtcm_layout_build(
uint32_t S_v,
uint32_t n_hvx
) {
- size_t state_bytes = (size_t) S_v * S_v * sizeof(float);
- L->state_aligned = hex_round_up(state_bytes, 128);
- L->bytes_per_hvx = 2 * L->state_aligned;
+ const size_t state_bytes = (size_t) S_v * S_v * sizeof(float);
+ const size_t vec_aligned = hex_round_up((size_t) S_v * sizeof(float), 128);
+ L->state_aligned = hex_round_up(state_bytes, 128);
+ L->scratch_bytes = 24 * 128;
+ L->tile_vec_bytes = HTP_GDN_TOKEN_TILE * vec_aligned;
+ L->tile_scalar_bytes = hex_round_up(HTP_GDN_TOKEN_TILE * sizeof(float), 128);
+ L->spad_stride = 5 * L->tile_vec_bytes + L->tile_scalar_bytes;
+ L->off_scratch = 2 * L->state_aligned;
+ L->off_spad = L->off_scratch + L->scratch_bytes;
+ L->bytes_per_hvx = L->off_spad + 2 * L->spad_stride + 128;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_state, L->bytes_per_hvx * n_hvx);
L->total_bytes = off;
@@ -79,9 +93,7 @@ static inline void htp_gdn_vtcm_layout_build(
struct htp_gdn_hmx_vtcm_layout {
size_t off_s_state;
- size_t off_s_f16;
size_t off_s_col_tiles;
- size_t off_s_update_f32;
size_t off_s_update_tiles;
size_t off_q_f32[2];
@@ -93,20 +105,14 @@ struct htp_gdn_hmx_vtcm_layout {
size_t off_b_raw[2];
size_t off_o_f32[2];
- size_t off_v_inter_f32;
- size_t off_o_inter_f32;
- size_t off_o_intra_f32;
size_t off_k_f16;
- size_t off_v_prime_f16;
- size_t off_delta_f16;
- size_t off_d_f16;
size_t off_q_row_tiles;
size_t off_q_prime_row_tiles;
size_t off_k_row_tiles;
size_t off_k_col_tiles;
size_t off_k_prime_row_tiles;
- size_t off_k_col_tiles_64x128;
+ size_t off_k_col_tiles_64x128[2];
size_t off_kk_tiles;
size_t off_qk_tiles;
size_t off_v_inter_tiles;
@@ -115,12 +121,11 @@ struct htp_gdn_hmx_vtcm_layout {
size_t off_a_row_tiles;
size_t off_v_prime_col_tiles;
size_t off_delta_tiles;
- size_t off_delta_col_tiles;
size_t off_o_intra_tiles;
size_t off_d_row_tiles;
size_t off_gamma;
- size_t off_lambda_init;
+ size_t off_lambda_init[2];
size_t off_decay_m;
size_t off_decay_a;
size_t off_rows_kk;
@@ -132,7 +137,6 @@ struct htp_gdn_hmx_vtcm_layout {
size_t off_scales_1;
size_t state_f32_bytes;
- size_t state_f16_bytes;
size_t state_tiles_bytes;
size_t dma_chunk_bytes;
size_t act_f16_bytes;
@@ -141,7 +145,6 @@ struct htp_gdn_hmx_vtcm_layout {
uint32_t n_heads_batch;
uint32_t n_hvx;
- bool pipeline;
size_t total_bytes;
};
@@ -150,19 +153,16 @@ static inline void htp_gdn_hmx_vtcm_layout_build(
uint32_t S_v,
uint32_t chunk_size,
uint32_t n_heads_batch,
- uint32_t n_hvx,
- bool pipeline
+ uint32_t n_hvx
) {
memset(L, 0, sizeof(*L));
L->n_heads_batch = n_heads_batch;
L->n_hvx = n_hvx;
- L->pipeline = pipeline;
const size_t bh = (size_t) n_heads_batch;
const size_t nth = (size_t) (n_hvx > 0 ? n_hvx : 1);
const size_t state_f32_sz = hex_round_up(S_v * S_v * sizeof(float), 2048);
- const size_t state_f16_sz = hex_round_up(S_v * S_v * sizeof(__fp16), 2048);
const size_t n_sv_tiles = S_v / 32;
const size_t state_tiles_sz = n_sv_tiles * n_sv_tiles * 2048;
@@ -177,7 +177,6 @@ static inline void htp_gdn_hmx_vtcm_layout_build(
const size_t row_vecs_sz = 64 * 128;
L->state_f32_bytes = state_f32_sz;
- L->state_f16_bytes = state_f16_sz;
L->state_tiles_bytes = state_tiles_sz;
L->dma_chunk_bytes = dma_chunk_sz;
L->act_f16_bytes = act_f16_sz;
@@ -187,60 +186,52 @@ static inline void htp_gdn_hmx_vtcm_layout_build(
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_s_state, bh * state_f32_sz);
- VTCM_LAYOUT_ALLOC(off, off_s_f16, bh * state_f16_sz);
off = hex_align_up(off, HMX_FP16_TILE_SIZE);
VTCM_LAYOUT_ALLOC(off, off_s_col_tiles, bh * state_tiles_sz);
- VTCM_LAYOUT_ALLOC(off, off_s_update_f32, bh * state_f32_sz);
- off = hex_align_up(off, HMX_FP16_TILE_SIZE);
VTCM_LAYOUT_ALLOC(off, off_s_update_tiles, bh * state_tiles_sz);
VTCM_LAYOUT_ALLOC(off, off_q_f32[0], bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_q_f32[1], bh * dma_chunk_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_q_f32[1], bh * dma_chunk_sz);
VTCM_LAYOUT_ALLOC(off, off_k_f32[0], bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_k_f32[1], bh * dma_chunk_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_k_f32[1], bh * dma_chunk_sz);
VTCM_LAYOUT_ALLOC(off, off_v_f32[0], bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_v_f32[1], bh * dma_chunk_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_v_f32[1], bh * dma_chunk_sz);
VTCM_LAYOUT_ALLOC(off, off_g_f32[0], bh * dma_scalar_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_g_f32[1], bh * dma_scalar_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_g_f32[1], bh * dma_scalar_sz);
VTCM_LAYOUT_ALLOC(off, off_b_f32[0], bh * dma_scalar_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_b_f32[1], bh * dma_scalar_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_b_f32[1], bh * dma_scalar_sz);
const size_t raw_gb_sz = hex_round_up((bh + 1) * chunk_size * sizeof(float), 128);
VTCM_LAYOUT_ALLOC(off, off_g_raw[0], raw_gb_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_g_raw[1], raw_gb_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_g_raw[1], raw_gb_sz);
VTCM_LAYOUT_ALLOC(off, off_b_raw[0], raw_gb_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_b_raw[1], raw_gb_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_b_raw[1], raw_gb_sz);
VTCM_LAYOUT_ALLOC(off, off_o_f32[0], bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_f32[1], bh * dma_chunk_sz, pipeline);
+ VTCM_LAYOUT_ALLOC(off, off_o_f32[1], bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC(off, off_v_inter_f32, bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC(off, off_o_inter_f32, bh * dma_chunk_sz);
- VTCM_LAYOUT_ALLOC(off, off_o_intra_f32, bh * dma_chunk_sz);
VTCM_LAYOUT_ALLOC(off, off_k_f16, bh * act_f16_sz);
- VTCM_LAYOUT_ALLOC(off, off_v_prime_f16, bh * act_f16_sz);
- VTCM_LAYOUT_ALLOC(off, off_delta_f16, bh * act_f16_sz);
- VTCM_LAYOUT_ALLOC(off, off_d_f16, bh * act_f16_sz);
off = hex_align_up(off, HMX_FP16_TILE_SIZE);
VTCM_LAYOUT_ALLOC(off, off_q_row_tiles, bh * tile_64xSv_sz);
VTCM_LAYOUT_ALLOC(off, off_q_prime_row_tiles, bh * tile_64xSv_sz);
VTCM_LAYOUT_ALLOC(off, off_k_row_tiles, bh * tile_64xSv_sz);
VTCM_LAYOUT_ALLOC(off, off_k_col_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_k_prime_row_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_k_col_tiles_64x128, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_kk_tiles, bh * tile_64x64_sz);
- VTCM_LAYOUT_ALLOC(off, off_qk_tiles, bh * tile_64x64_sz);
- VTCM_LAYOUT_ALLOC(off, off_v_inter_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_o_inter_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_inv_row_tiles, bh * tile_64x64_sz);
- VTCM_LAYOUT_ALLOC(off, off_a_row_tiles, bh * tile_64x64_sz);
- VTCM_LAYOUT_ALLOC(off, off_v_prime_col_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_delta_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_delta_col_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_o_intra_tiles, bh * tile_64xSv_sz);
- VTCM_LAYOUT_ALLOC(off, off_d_row_tiles, bh * tile_64xSv_sz);
-
- VTCM_LAYOUT_ALLOC(off, off_gamma, bh * hex_round_up(chunk_size * sizeof(float), 128));
- VTCM_LAYOUT_ALLOC(off, off_lambda_init, bh * hex_round_up(chunk_size * sizeof(float), 128));
+ VTCM_LAYOUT_ALLOC(off, off_k_prime_row_tiles, bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_k_col_tiles_64x128[0], bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_k_col_tiles_64x128[1], bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_kk_tiles, bh * tile_64x64_sz);
+ VTCM_LAYOUT_ALLOC(off, off_qk_tiles, bh * tile_64x64_sz);
+ VTCM_LAYOUT_ALLOC(off, off_v_inter_tiles, bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_o_inter_tiles, bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_inv_row_tiles, bh * tile_64x64_sz);
+ VTCM_LAYOUT_ALLOC(off, off_a_row_tiles, bh * tile_64x64_sz);
+ VTCM_LAYOUT_ALLOC(off, off_v_prime_col_tiles, bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_delta_tiles, bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_o_intra_tiles, bh * tile_64xSv_sz);
+ VTCM_LAYOUT_ALLOC(off, off_d_row_tiles, bh * tile_64xSv_sz);
+
+ VTCM_LAYOUT_ALLOC(off, off_gamma, bh * hex_round_up(chunk_size * sizeof(float), 128));
+ VTCM_LAYOUT_ALLOC(off, off_lambda_init[0], bh * hex_round_up(chunk_size * sizeof(float), 128));
+ VTCM_LAYOUT_ALLOC(off, off_lambda_init[1], bh * hex_round_up(chunk_size * sizeof(float), 128));
VTCM_LAYOUT_ALLOC(off, off_decay_m, bh * decay_sz);
VTCM_LAYOUT_ALLOC(off, off_decay_a, bh * decay_sz);
VTCM_LAYOUT_ALLOC(off, off_rows_kk, bh * row_vecs_sz);
@@ -264,7 +255,6 @@ static inline bool htp_gdn_hmx_solve_layout(
uint32_t total_rows,
size_t vtcm_budget,
uint32_t n_hvx,
- bool pipeline,
uint32_t * n_heads_batch_out
) {
uint32_t max_batch = 8;
@@ -281,16 +271,13 @@ static inline bool htp_gdn_hmx_solve_layout(
continue;
}
struct htp_gdn_hmx_vtcm_layout L;
- htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, bh, n_hvx, pipeline);
+ htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, bh, n_hvx);
if (L.total_bytes <= vtcm_budget) {
*layout_out = L;
*n_heads_batch_out = bh;
return true;
}
}
- if (pipeline) {
- return htp_gdn_hmx_solve_layout(layout_out, S_v, chunk_size, total_rows, vtcm_budget, n_hvx, false, n_heads_batch_out);
- }
return false;
}
diff --git a/ggml/src/ggml-hexagon/htp/gather-rows.c b/ggml/src/ggml-hexagon/htp/gather-rows.c
index 02804db27..66bad4f1e 100644
--- a/ggml/src/ggml-hexagon/htp/gather-rows.c
+++ b/ggml/src/ggml-hexagon/htp/gather-rows.c
@@ -24,6 +24,7 @@ struct gather_rows_task {
uint32_t r_start;
uint32_t rows;
uint32_t rows_per_hvx;
+ uint32_t dst_es;
const struct htp_gather_rows_params * kparams;
gather_rows_compute_fn_t compute;
};
@@ -72,7 +73,10 @@ static __attribute__((noinline)) void gather_rows_init_tables_f32(
int32_t s_buf[32] __attribute__((aligned(128)));
for (uint32_t k = 0; k < kparams->vg; k++) {
for (uint32_t lane = 0; lane < 32; lane++) {
- if (col < kparams->na) {
+ if (row >= kparams->nr_max) {
+ t_buf[lane] = 0;
+ s_buf[lane] = 0;
+ } else if (col < kparams->na) {
t_buf[lane] = row * a->nb[1] + col * 4;
s_buf[lane] = s_a;
} else {
@@ -103,7 +107,10 @@ static __attribute__((noinline)) void gather_rows_init_tables_f16(
int16_t s_buf[64] __attribute__((aligned(128)));
for (uint32_t k = 0; k < kparams->vg; k++) {
for (uint32_t lane = 0; lane < 64; lane++) {
- if (col < kparams->na) {
+ if (row >= kparams->nr_max) {
+ t_buf[lane] = 0;
+ s_buf[lane] = 0;
+ } else if (col < kparams->na) {
t_buf[lane] = (int16_t) (row * a->nb[1] + col * 2);
s_buf[lane] = s_a;
} else {
@@ -120,6 +127,26 @@ static __attribute__((noinline)) void gather_rows_init_tables_f16(
}
}
+static __attribute__((noinline)) void gather_rows_widen_f16_to_f32(uint8_t * restrict buf, uint32_t nvec) {
+ HVX_Vector * restrict vbuf = (HVX_Vector *) buf;
+ for (int32_t v = (int32_t) nvec - 1; v >= 0; v--) {
+ const HVX_VectorPair vp = hvx_vec_f16_to_f32(vbuf[v]);
+ vbuf[2 * v + 0] = Q6_V_lo_W(vp);
+ vbuf[2 * v + 1] = Q6_V_hi_W(vp);
+ }
+}
+
+static __attribute__((noinline)) void gather_rows_pack_f32_to_f16(uint8_t * restrict buf, uint32_t nvec) {
+ HVX_Vector * restrict vbuf = (HVX_Vector *) buf;
+ uint32_t v = 0;
+ for (; v + 1 < nvec; v += 2) {
+ vbuf[v >> 1] = hvx_vec_f32_to_f16(vbuf[v], vbuf[v + 1]);
+ }
+ if (v < nvec) {
+ vbuf[v >> 1] = hvx_vec_f32_to_f16(vbuf[v], Q6_V_vzero());
+ }
+}
+
static void gather_rows_compute_f32_vg1(
uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec,
const struct htp_gather_rows_params * restrict kparams,
@@ -133,6 +160,7 @@ static void gather_rows_compute_f32_vg1(
Q6_vgather_ARMVw((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur);
vcur = Q6_Vw_vadd_VwVw(vcur, vinc);
}
+ hvx_gather_sync(out);
}
static void gather_rows_compute_f32_vgn(
@@ -153,6 +181,7 @@ static void gather_rows_compute_f32_vgn(
k = 0;
}
}
+ hvx_gather_sync(out);
}
static void gather_rows_compute_f16_vg1(
@@ -168,6 +197,7 @@ static void gather_rows_compute_f16_vg1(
Q6_vgather_ARMVh((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur);
vcur = Q6_Vh_vadd_VhVh(vcur, vinc);
}
+ hvx_gather_sync(out);
}
static void gather_rows_compute_f16_vgn(
@@ -188,6 +218,7 @@ static void gather_rows_compute_f16_vgn(
k = 0;
}
}
+ hvx_gather_sync(out);
}
static void gather_rows_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
@@ -207,7 +238,7 @@ static void gather_rows_thread_f32(const htp_thread_t * th, unsigned int nth, un
struct htp_thread_trace * tr = th->trace;
struct htp_gather_rows_vtcm_layout layout;
- htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 4);
+ htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 4, task->dst_es);
uint8_t * base = VTCM_LAYOUT_PTR(uint8_t, task->octx->ctx->vtcm_base, (size_t) ith * kparams->slice);
HVX_Vector * tab = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_tab);
@@ -255,10 +286,12 @@ static void gather_rows_thread_f32(const htp_thread_t * th, unsigned int nth, un
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
const uint32_t nvec = (nr * kparams->ne + 31) >> 5;
task->compute(out[buf], region[buf], nvec, kparams, tab, inc, cur);
- hvx_gather_sync(out[buf]);
+ if (task->dst_es == 2) {
+ gather_rows_pack_f32_to_f16(out[buf], nvec);
+ }
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
- gather_rows_dma_out(q, task, out[buf], r, nr, 4);
+ gather_rows_dma_out(q, task, out[buf], r, nr, task->dst_es);
const uint32_t r_prefetch = r + 2 * nr_max;
if (r_prefetch < r_end) {
@@ -288,7 +321,7 @@ static void gather_rows_thread_f16(const htp_thread_t * th, unsigned int nth, un
struct htp_thread_trace * tr = th->trace;
struct htp_gather_rows_vtcm_layout layout;
- htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 2);
+ htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 2, task->dst_es);
uint8_t * base = VTCM_LAYOUT_PTR(uint8_t, task->octx->ctx->vtcm_base, (size_t) ith * kparams->slice);
HVX_Vector * tab = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_tab);
@@ -336,10 +369,12 @@ static void gather_rows_thread_f16(const htp_thread_t * th, unsigned int nth, un
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
const uint32_t nvec = (nr * kparams->ne + 63) >> 6;
task->compute(out[buf], region[buf], nvec, kparams, tab, inc, cur);
- hvx_gather_sync(out[buf]);
+ if (task->dst_es == 4) {
+ gather_rows_widen_f16_to_f32(out[buf], nvec);
+ }
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
- gather_rows_dma_out(q, task, out[buf], r, nr, 2);
+ gather_rows_dma_out(q, task, out[buf], r, nr, task->dst_es);
const uint32_t r_prefetch = r + 2 * nr_max;
if (r_prefetch < r_end) {
@@ -379,25 +414,27 @@ int htp_gather_rows(
return HTP_STATUS_OK;
}
- const uint32_t elem_size = (a->type == HTP_TYPE_F16) ? 2 : 4;
+ const uint32_t src_es = (a->type == HTP_TYPE_F16) ? 2 : 4;
+ const uint32_t dst_es = (octx->dst->type == HTP_TYPE_F16) ? 2 : 4;
struct gather_rows_task task;
- task.octx = octx;
- task.a = a;
- task.b = b;
- task.dst = octx->dst->data;
- task.r_start = r_start;
- task.rows = r_count;
- task.kparams = kparams;
- task.rows_per_hvx = kparams->rows_per_hvx;
-
- if (elem_size == 2) {
+ task.octx = octx;
+ task.a = a;
+ task.b = b;
+ task.dst = octx->dst->data;
+ task.r_start = r_start;
+ task.rows = r_count;
+ task.rows_per_hvx = kparams->rows_per_hvx;
+ task.dst_es = dst_es;
+ task.kparams = kparams;
+
+ if (src_es == 2) {
task.compute = (kparams->vg == 1) ? gather_rows_compute_f16_vg1 : gather_rows_compute_f16_vgn;
} else {
task.compute = (kparams->vg == 1) ? gather_rows_compute_f32_vg1 : gather_rows_compute_f32_vgn;
}
- work_queue_func_t worker_func = (elem_size == 2) ? gather_rows_thread_f16 : gather_rows_thread_f32;
+ work_queue_func_t worker_func = (src_es == 2) ? gather_rows_thread_f16 : gather_rows_thread_f32;
work_queue_run(octx->ctx->hvx_queue, worker_func, &task, octx->n_hvx);
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/gather-rows.h b/ggml/src/ggml-hexagon/htp/gather-rows.h
index 9ca215ac3..4f3608652 100644
--- a/ggml/src/ggml-hexagon/htp/gather-rows.h
+++ b/ggml/src/ggml-hexagon/htp/gather-rows.h
@@ -44,11 +44,13 @@ static inline void htp_gather_rows_vtcm_layout_build(
uint32_t region_size,
uint32_t nr_max,
uint32_t ne,
- uint32_t elem_size) {
+ uint32_t src_es,
+ uint32_t dst_es) {
const size_t vec_bytes = (size_t) vg * 128;
const size_t region_aligned = hex_round_up(region_size, 128);
- const size_t out_aligned = hex_round_up(region_aligned + (size_t) nr_max * ne * elem_size, 128) - region_aligned;
+ const size_t gather_bytes = hex_round_up((size_t) nr_max * ne * src_es, 128);
+ const size_t out_aligned = (dst_es > src_es) ? (2 * gather_bytes) : gather_bytes;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_tab, vec_bytes);
@@ -65,23 +67,23 @@ static inline bool htp_gather_rows_solve_layout(
struct htp_gather_rows_params * kparams,
uint32_t na, uint32_t a_nb1,
uint32_t nb, uint32_t b_nb1, bool b_dense,
- uint32_t elem_size,
+ uint32_t src_es, uint32_t dst_es,
uint32_t total_rows,
uint32_t n_hvx,
uint32_t mdev_count,
uint32_t vtcm_size) {
- const uint32_t max_ne0 = 128 / elem_size;
+ const uint32_t max_ne0 = 128 / src_es;
const uint32_t ne = na + nb;
if (ne == 0 || ne > max_ne0) {
return false;
}
- if (elem_size != 4 && elem_size != 2) {
+ if ((src_es != 4 && src_es != 2) || (dst_es != 4 && dst_es != 2)) {
return false;
}
- const uint32_t v_lanes = 128 / elem_size;
+ const uint32_t v_lanes = 128 / src_es;
const uint32_t g = hex_gcd_u32(ne, v_lanes);
const uint32_t rg = v_lanes / g;
const uint32_t vg = ne / g;
@@ -94,34 +96,37 @@ static inline bool htp_gather_rows_solve_layout(
: total_rows;
const uint32_t rows_per_hvx = hex_round_up((max_rows_per_dev + n_hvx - 1) / n_hvx, rg);
- const uint32_t fixed = 3 * vg * 128;
- const uint32_t per_row = a_nb1 + (nb > 0 ? (b_dense ? b_nb1 : nb * b_nb1) : 0) + ne * elem_size;
- if (slice <= fixed + 2 * per_row * rg) {
+ const uint32_t max_es = MAX(src_es, dst_es);
+ const uint32_t fixed = 3 * vg * 128;
+ const uint32_t per_row = a_nb1 + (nb > 0 ? (b_dense ? b_nb1 : nb * b_nb1) : 0) + ne * max_es;
+ if (slice <= fixed + 2 * per_row) {
return false;
}
const uint32_t avail_per_buf = (slice - fixed) / 2;
uint32_t nr_max = MIN(avail_per_buf / per_row, rows_per_hvx);
- if (elem_size == 2) {
+ if (src_es == 2) {
const uint32_t per_row_region = a_nb1 + (nb > 0 ? (b_dense ? b_nb1 : nb * b_nb1) : 0);
if (per_row_region > 0) {
- nr_max = MIN(nr_max, (32768u - 256u) / per_row_region);
+ nr_max = MIN(nr_max, 1 + 32768u / per_row_region);
}
}
- nr_max = (nr_max / rg) * rg;
+ if (nr_max >= rg) {
+ nr_max = (nr_max / rg) * rg;
+ }
uint32_t v1 = 0;
uint32_t span1 = 0;
uint32_t region_size = 0;
while (nr_max > 0) {
- v1 = hex_round_up((nr_max - 1) * a_nb1 + na * elem_size, 128);
+ v1 = hex_round_up((nr_max - 1) * a_nb1 + na * src_es, 128);
if (nb > 0) {
if (b_dense) {
- span1 = elem_size;
- region_size = v1 + (nr_max - 1) * b_nb1 + nb * elem_size;
+ span1 = src_es;
+ region_size = v1 + (nr_max - 1) * b_nb1 + nb * src_es;
} else {
- span1 = (nr_max - 1) * b_nb1 + elem_size;
+ span1 = (nr_max - 1) * b_nb1 + src_es;
region_size = v1 + nb * span1;
}
} else {
@@ -130,13 +135,13 @@ static inline bool htp_gather_rows_solve_layout(
}
struct htp_gather_rows_vtcm_layout layout;
- htp_gather_rows_vtcm_layout_build(&layout, vg, region_size, nr_max, ne, elem_size);
+ htp_gather_rows_vtcm_layout_build(&layout, vg, region_size, nr_max, ne, src_es, dst_es);
- if ((elem_size != 2 || region_size <= 32768) && layout.total_per_hvx <= slice) {
+ if ((src_es != 2 || region_size <= 32768) && layout.total_per_hvx <= slice) {
break;
}
- nr_max -= rg;
+ nr_max = (nr_max > rg) ? (nr_max - rg) : (nr_max - 1);
}
if (nr_max == 0) {
diff --git a/ggml/src/ggml-hexagon/htp/get-rows-ops.c b/ggml/src/ggml-hexagon/htp/get-rows-ops.c
index 83e85f005..7ab526b18 100644
--- a/ggml/src/ggml-hexagon/htp/get-rows-ops.c
+++ b/ggml/src/ggml-hexagon/htp/get-rows-ops.c
@@ -1,17 +1,15 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <math.h>
+#include <stdlib.h>
#include <string.h>
#define GGML_COMMON_DECL_C
#include "ggml-common.h"
#include "hex-common.h"
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "htp-ctx.h"
#include "htp-ops.h"
#include "htp-tensor.h"
@@ -22,9 +20,8 @@
struct get_rows_context;
-typedef uint32_t (*get_rows_read_index_fn_t)(const void * src1, uint32_t idx, int idx_type);
typedef void (*get_rows_flat_compute_fn_t)(float * dst_spad, const void * src_spad, uint32_t cur_elems);
-typedef void (*get_rows_tiled_compute_fn_t)(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row);
+typedef void (*get_rows_tiled_compute_fn_t)(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row);
struct get_rows_context {
struct htp_ops_context * octx;
@@ -32,7 +29,6 @@ struct get_rows_context {
struct htp_get_rows_vtcm_layout vtcm_layout;
uint8_t * vtcm_base;
const void * src1_data;
- get_rows_read_index_fn_t read_index;
get_rows_flat_compute_fn_t compute_flat;
get_rows_tiled_compute_fn_t compute_tiled;
uint32_t task_start;
@@ -45,37 +41,37 @@ struct get_rows_context {
int idx_type;
};
-#define get_rows_preamble \
- const uint32_t ne00 = octx->src[0]->ne[0]; \
- const uint32_t ne01 = octx->src[0]->ne[1]; \
- const uint32_t ne02 = octx->src[0]->ne[2]; \
- const uint32_t ne03 = octx->src[0]->ne[3]; \
- \
- const uint32_t ne10 = octx->src[1]->ne[0]; \
- const uint32_t ne11 = octx->src[1]->ne[1]; \
- const uint32_t ne12 = octx->src[1]->ne[2]; \
- const uint32_t ne13 = octx->src[1]->ne[3]; \
- \
- const uint32_t ne0 = octx->dst->ne[0]; \
- const uint32_t ne1 = octx->dst->ne[1]; \
- const uint32_t ne2 = octx->dst->ne[2]; \
- const uint32_t ne3 = octx->dst->ne[3]; \
- \
- const uint32_t nb01 = octx->src[0]->nb[1]; \
- const uint32_t nb02 = octx->src[0]->nb[2]; \
- const uint32_t nb03 = octx->src[0]->nb[3]; \
- \
- const uint32_t nb10 = octx->src[1]->nb[0]; \
- const uint32_t nb11 = octx->src[1]->nb[1]; \
- const uint32_t nb12 = octx->src[1]->nb[2]; \
- \
- const uint32_t nb1 = octx->dst->nb[1]; \
- const uint32_t nb2 = octx->dst->nb[2]; \
- const uint32_t nb3 = octx->dst->nb[3]; \
- \
- const uint32_t nr = ne10 * ne11 * ne12;
-
-static uint32_t get_rows_read_index_ddr(
+#define get_rows_preamble \
+ const uint32_t __attribute__((unused)) ne00 = octx->src[0]->ne[0]; \
+ const uint32_t __attribute__((unused)) ne01 = octx->src[0]->ne[1]; \
+ const uint32_t __attribute__((unused)) ne02 = octx->src[0]->ne[2]; \
+ const uint32_t __attribute__((unused)) ne03 = octx->src[0]->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) ne10 = octx->src[1]->ne[0]; \
+ const uint32_t __attribute__((unused)) ne11 = octx->src[1]->ne[1]; \
+ const uint32_t __attribute__((unused)) ne12 = octx->src[1]->ne[2]; \
+ const uint32_t __attribute__((unused)) ne13 = octx->src[1]->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) ne0 = octx->dst->ne[0]; \
+ const uint32_t __attribute__((unused)) ne1 = octx->dst->ne[1]; \
+ const uint32_t __attribute__((unused)) ne2 = octx->dst->ne[2]; \
+ const uint32_t __attribute__((unused)) ne3 = octx->dst->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb01 = octx->src[0]->nb[1]; \
+ const uint32_t __attribute__((unused)) nb02 = octx->src[0]->nb[2]; \
+ const uint32_t __attribute__((unused)) nb03 = octx->src[0]->nb[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb10 = octx->src[1]->nb[0]; \
+ const uint32_t __attribute__((unused)) nb11 = octx->src[1]->nb[1]; \
+ const uint32_t __attribute__((unused)) nb12 = octx->src[1]->nb[2]; \
+ \
+ const uint32_t __attribute__((unused)) nb1 = octx->dst->nb[1]; \
+ const uint32_t __attribute__((unused)) nb2 = octx->dst->nb[2]; \
+ const uint32_t __attribute__((unused)) nb3 = octx->dst->nb[3]; \
+ \
+ const uint32_t __attribute__((unused)) nr = ne10 * ne11 * ne12;
+
+static inline uint32_t get_rows_read_index(
const void * src1,
uint32_t idx,
int idx_type
@@ -84,17 +80,6 @@ static uint32_t get_rows_read_index_ddr(
return *(const uint32_t *) ((const uint8_t *) src1 + off);
}
-static __attribute__((noinline)) uint32_t get_rows_read_index_vtcm(
- const void * src1,
- uint32_t idx,
- int idx_type
-) {
- const uint32_t off = idx * ((idx_type == HTP_TYPE_I64) ? sizeof(int64_t) : sizeof(int32_t));
- const HVX_Vector v = hvx_vmem((const uint8_t *) src1 + off); // off & ~127u in HW
- // vextract is normally slow, but here it avoids an HVX->L2 store and L1D miss
- return (uint32_t) Q6_R_vextract_VR(v, off);
-}
-
static void get_rows_thread_sametype(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct get_rows_context * grctx = (struct get_rows_context *) data;
struct htp_ops_context * octx = grctx->octx;
@@ -116,7 +101,7 @@ static void get_rows_thread_sametype(const htp_thread_t * th, unsigned int nth,
const uint32_t i11 = fastdiv(rem, &kparams->div_ne10);
const uint32_t i10 = rem - i11 * ne10;
- const uint32_t i01 = grctx->read_index(grctx->src1_data, i, grctx->idx_type);
+ const uint32_t i01 = get_rows_read_index(grctx->src1_data, i, grctx->idx_type);
assert(i01 < ne01);
const uint32_t q02 = fastdiv(i11, &kparams->div_ne02);
@@ -136,6 +121,102 @@ static void get_rows_thread_sametype(const htp_thread_t * th, unsigned int nth,
+static inline HVX_Vector get_rows_clamp_f16_finite(HVX_Vector v) {
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ const HVX_Vector inf = hvx_vec_splat_f32(INFINITY);
+ const HVX_VectorPred finite = Q6_Q_vcmp_gt_VsfVsf(inf, hvx_vec_abs_f32(v));
+ const HVX_VectorPred high = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(v, max_f16));
+ const HVX_VectorPred low = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(min_f16, v));
+ v = Q6_V_vmux_QVV(high, max_f16, v);
+ return Q6_V_vmux_QVV(low, min_f16, v);
+}
+
+static __attribute__((noinline)) void get_rows_flat_f32_to_f16(
+ float * restrict dst_ptr,
+ const void * restrict src_ptr,
+ uint32_t n
+) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src_ptr;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst_ptr;
+
+ const uint32_t n_vec = n / 64;
+ const uint32_t n_rem = n % 64;
+
+ for (uint32_t i = 0; i < n_vec; i++) {
+ const HVX_Vector v0 = get_rows_clamp_f16_finite(vsrc[2 * i + 0]);
+ const HVX_Vector v1 = get_rows_clamp_f16_finite(vsrc[2 * i + 1]);
+ vdst[i] = hvx_vec_f32_to_f16(v0, v1);
+ }
+
+ if (n_rem > 0) {
+ const HVX_Vector v0 = get_rows_clamp_f16_finite(vsrc[2 * n_vec + 0]);
+ const HVX_Vector v1 = (n_rem > 32) ? get_rows_clamp_f16_finite(vsrc[2 * n_vec + 1]) : Q6_V_vzero();
+ const HVX_Vector v = hvx_vec_f32_to_f16(v0, v1);
+ hvx_vec_store_a(&vdst[n_vec], n_rem * sizeof(__fp16), v);
+ }
+}
+
+static inline void get_rows_pack_f32_to_f16_inplace(
+ void * spad_ptr,
+ uint32_t n
+) {
+ HVX_Vector * vec = (HVX_Vector *) spad_ptr;
+
+ const uint32_t n_vec = n / 64;
+ const uint32_t n_rem = n % 64;
+
+ for (uint32_t i = 0; i < n_vec; i++) {
+ const HVX_Vector v0 = get_rows_clamp_f16_finite(vec[2 * i + 0]);
+ const HVX_Vector v1 = get_rows_clamp_f16_finite(vec[2 * i + 1]);
+ vec[i] = hvx_vec_f32_to_f16(v0, v1);
+ }
+
+ if (n_rem > 0) {
+ const HVX_Vector v0 = get_rows_clamp_f16_finite(vec[2 * n_vec + 0]);
+ const HVX_Vector v1 = (n_rem > 32) ? get_rows_clamp_f16_finite(vec[2 * n_vec + 1]) : Q6_V_vzero();
+ const HVX_Vector v = hvx_vec_f32_to_f16(v0, v1);
+ hvx_vec_store_a(&vec[n_vec], n_rem * sizeof(__fp16), v);
+ }
+}
+
+#define DEFINE_GET_ROWS_FLAT_F16(type) \
+ static void get_rows_flat_##type##_f16( \
+ float * dst_spad, const void * src_spad, uint32_t n) { \
+ hvx_dequantize_row_flat_##type##_f32(dst_spad, src_spad, n); \
+ get_rows_pack_f32_to_f16_inplace(dst_spad, n); \
+ }
+
+DEFINE_GET_ROWS_FLAT_F16(bf16)
+DEFINE_GET_ROWS_FLAT_F16(q1_0)
+DEFINE_GET_ROWS_FLAT_F16(q2_0)
+DEFINE_GET_ROWS_FLAT_F16(q8_0)
+DEFINE_GET_ROWS_FLAT_F16(q4_0)
+DEFINE_GET_ROWS_FLAT_F16(q4_k)
+DEFINE_GET_ROWS_FLAT_F16(q5_k)
+DEFINE_GET_ROWS_FLAT_F16(q6_k)
+
+#undef DEFINE_GET_ROWS_FLAT_F16
+
+#define DEFINE_GET_ROWS_TILED_F16(type, tile_k) \
+ static void get_rows_tiled_##type##_f16( \
+ void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, \
+ uint32_t tile_stride, uint32_t row) { \
+ hvx_dequantize_row_tiled_##type##_f32( \
+ dst_spad, src_spad, n_k_tiles, tile_stride, row); \
+ get_rows_pack_f32_to_f16_inplace(dst_spad, n_k_tiles * (tile_k)); \
+ }
+
+DEFINE_GET_ROWS_TILED_F16(q1_0, HTP_TENSOR_TILE_K_Q1_0)
+DEFINE_GET_ROWS_TILED_F16(q2_0, HTP_TENSOR_TILE_K_Q2_0)
+DEFINE_GET_ROWS_TILED_F16(q8_0, HTP_TENSOR_TILE_N_COLS)
+DEFINE_GET_ROWS_TILED_F16(q4_0, HTP_TENSOR_TILE_N_COLS)
+DEFINE_GET_ROWS_TILED_F16(q4_k, HTP_TENSOR_TILE_N_COLS)
+DEFINE_GET_ROWS_TILED_F16(q5_k, HTP_TENSOR_TILE_N_COLS)
+DEFINE_GET_ROWS_TILED_F16(q6_k, HTP_TENSOR_TILE_N_COLS)
+
+#undef DEFINE_GET_ROWS_TILED_F16
+
struct get_rows_flat_task {
dma_addr_t src0_data;
dma_addr_t dst_data;
@@ -160,7 +241,7 @@ static inline struct get_rows_flat_task get_rows_flat_calc_task(
task.dst_data = octx->dst->data + i10*nb1 + i11*nb2 + i12*nb3;
if (need_src0) {
- const uint32_t i01 = grctx->read_index(grctx->src1_data, i, grctx->idx_type);
+ const uint32_t i01 = get_rows_read_index(grctx->src1_data, i, grctx->idx_type);
assert(i01 < ne01);
const uint32_t q02 = fastdiv(i11, &kparams->div_ne02);
@@ -174,7 +255,53 @@ static inline struct get_rows_flat_task get_rows_flat_calc_task(
return task;
}
+struct get_rows_flat_pipe_state {
+ const struct htp_ops_context * octx;
+ const struct get_rows_context * grctx;
+ get_rows_flat_compute_fn_t compute;
+ uint32_t ne00;
+ uint32_t src0_bytes;
+ uint32_t dst_bytes;
+ size_t src0_spad_half;
+ size_t dst_spad_half;
+ uint32_t ir;
+ uint32_t ir_end;
+};
+
+static bool get_rows_flat_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx;
+ if (s->ir >= s->ir_end) {
+ return false;
+ }
+ task->row = s->ir++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
+
+static void get_rows_flat_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx;
+ struct get_rows_flat_task t = get_rows_flat_calc_task(s->octx, s->grctx, task->row, true);
+ dma_queue_push(dma_q, dma_make_data(in_spad, t.src0_data),
+ s->src0_spad_half, s->src0_bytes, s->src0_bytes, 1);
+}
+
+static void get_rows_flat_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ (void) task;
+ struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx;
+ s->compute((float *) out_spad, in_spad, s->ne00);
+}
+
+static void get_rows_flat_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx;
+ struct get_rows_flat_task t = get_rows_flat_calc_task(s->octx, s->grctx, task->row, false);
+ dma_queue_push(dma_q, dma_make_data(t.dst_data, out_spad),
+ s->dst_bytes, s->dst_spad_half, s->dst_bytes, 1);
+}
+
static void get_rows_thread_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct get_rows_context * grctx = (struct get_rows_context *) data;
struct htp_ops_context * octx = grctx->octx;
get_rows_preamble;
@@ -186,54 +313,27 @@ static void get_rows_thread_flat(const htp_thread_t * th, unsigned int nth, unsi
}
const uint32_t ir1 = MIN(ir0 + dr, grctx->task_start + grctx->tasks);
- dma_queue * dma_q = th->dma_q;
- struct htp_thread_trace * tr = th->trace;
const struct htp_get_rows_vtcm_layout * vtcm_layout = &grctx->vtcm_layout;
uint8_t * vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_src0) + ith * vtcm_layout->src0_bytes_per_hvx;
uint8_t * vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_dst) + ith * vtcm_layout->dst_bytes_per_hvx;
- const uint32_t src0_bytes = grctx->src0_row_size;
- const uint32_t dst_bytes = grctx->dst_row_size;
- get_rows_flat_compute_fn_t compute = grctx->compute_flat;
-
- for (uint32_t step = 0, spad_idx = 0; step < ir1 - ir0 && spad_idx < 2; ++step, spad_idx++) {
- const uint32_t i = ir0 + step;
- struct get_rows_flat_task task = get_rows_flat_calc_task(octx, grctx, i, true);
-
- dma_queue_push(dma_q,
- dma_make_data(octx->dst->data,
- vtcm_dst + spad_idx * vtcm_layout->dst_spad_half_size),
- dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 0);
- dma_queue_push(dma_q,
- dma_make_data(vtcm_src0 + spad_idx * vtcm_layout->src0_spad_half_size, task.src0_data),
- vtcm_layout->src0_spad_half_size, src0_bytes, src0_bytes, 1);
- }
-
- for (uint32_t step = 0; step < ir1 - ir0; ++step) {
- const uint32_t i = ir0 + step;
- void * dst_spad = (void *) dma_queue_pop(dma_q).src;
- void * src_spad = (void *) dma_queue_pop(dma_q).dst;
-
- struct get_rows_flat_task task = get_rows_flat_calc_task(octx, grctx, i, false);
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- compute((float *) dst_spad, src_spad, ne00);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
-
- dma_queue_push(dma_q,
- dma_make_data(task.dst_data, dst_spad),
- dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 1);
-
- const uint32_t next_step = step + 2;
- if (next_step < ir1 - ir0) {
- const uint32_t pi = ir0 + next_step;
- struct get_rows_flat_task next_task = get_rows_flat_calc_task(octx, grctx, pi, true);
- dma_queue_push(dma_q,
- dma_make_data(src_spad, next_task.src0_data),
- vtcm_layout->src0_spad_half_size, src0_bytes, src0_bytes, 1);
- }
- }
-
- dma_queue_flush(dma_q);
+ void * in_buf[2] = { vtcm_src0, vtcm_src0 + vtcm_layout->src0_spad_half_size };
+ void * out_buf[2] = { vtcm_dst, vtcm_dst + vtcm_layout->dst_spad_half_size };
+
+ struct get_rows_flat_pipe_state s = {
+ .octx = octx,
+ .grctx = grctx,
+ .compute = grctx->compute_flat,
+ .ne00 = ne00,
+ .src0_bytes = grctx->src0_row_size,
+ .dst_bytes = grctx->dst_row_size,
+ .src0_spad_half = vtcm_layout->src0_spad_half_size,
+ .dst_spad_half = vtcm_layout->dst_spad_half_size,
+ .ir = ir0,
+ .ir_end = ir1,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ get_rows_flat_next_task, get_rows_flat_push_in, get_rows_flat_compute, get_rows_flat_push_out);
}
@@ -258,7 +358,7 @@ static inline struct get_rows_tiled_task get_rows_tiled_calc_task(
const uint32_t rem = i - i12 * ne11 * ne10;
const uint32_t i11 = fastdiv(rem, &kparams->div_ne10);
const uint32_t i10 = rem - i11 * ne10;
- const uint32_t i01 = grctx->read_index(grctx->src1_data, i, grctx->idx_type);
+ const uint32_t i01 = get_rows_read_index(grctx->src1_data, i, grctx->idx_type);
assert(i01 < ne01);
const uint32_t q02 = fastdiv(i11, &kparams->div_ne02);
@@ -276,7 +376,53 @@ static inline struct get_rows_tiled_task get_rows_tiled_calc_task(
return task;
}
+struct get_rows_tiled_pipe_state {
+ const struct htp_ops_context * octx;
+ const struct get_rows_context * grctx;
+ get_rows_tiled_compute_fn_t compute_tiled;
+ uint32_t n_k_tiles;
+ uint32_t tile_size;
+ uint32_t tile_stride;
+ uint32_t dst_bytes;
+ size_t dst_spad_half;
+ uint32_t ir;
+ uint32_t ir_end;
+};
+
+static bool get_rows_tiled_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx;
+ if (s->ir >= s->ir_end) {
+ return false;
+ }
+ task->row = s->ir++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
+
+static void get_rows_tiled_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx;
+ struct get_rows_tiled_task t = get_rows_tiled_calc_task(s->octx, s->grctx, task->row, s->n_k_tiles, s->tile_size);
+ dma_queue_push(dma_q, dma_make_data(in_spad, t.tile_src_base),
+ s->tile_stride, s->tile_size, s->tile_size, s->n_k_tiles);
+}
+
+static void get_rows_tiled_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx;
+ struct get_rows_tiled_task t = get_rows_tiled_calc_task(s->octx, s->grctx, task->row, s->n_k_tiles, s->tile_size);
+ s->compute_tiled(out_spad, (const uint8_t *) in_spad, s->n_k_tiles, s->tile_stride, t.row);
+}
+
+static void get_rows_tiled_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx;
+ struct get_rows_tiled_task t = get_rows_tiled_calc_task(s->octx, s->grctx, task->row, s->n_k_tiles, s->tile_size);
+ dma_queue_push(dma_q, dma_make_data(t.dst_data, out_spad),
+ s->dst_bytes, s->dst_spad_half, s->dst_bytes, 1);
+}
+
static void get_rows_thread_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct get_rows_context * grctx = (struct get_rows_context *) data;
struct htp_ops_context * octx = grctx->octx;
get_rows_preamble;
@@ -292,84 +438,24 @@ static void get_rows_thread_tiled(const htp_thread_t * th, unsigned int nth, uns
const struct htp_get_rows_vtcm_layout * vtcm_layout = &grctx->vtcm_layout;
uint8_t * src_spad_base = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_src0) + ith * vtcm_layout->src0_bytes_per_hvx;
uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_dst) + ith * vtcm_layout->dst_bytes_per_hvx;
- dma_queue * dma_q = th->dma_q;
- struct htp_thread_trace * tr = th->trace;
-
- const uint32_t tile_size = grctx->tile_size;
- const uint32_t tile_stride = grctx->tile_stride;
- const uint32_t dst_bytes = grctx->dst_row_size;
- get_rows_tiled_compute_fn_t compute_tiled = grctx->compute_tiled;
-
- for (uint32_t step = 0, spad_idx = 0; step < ir1 - ir0 && spad_idx < 2; ++step, ++spad_idx) {
- const uint32_t i = ir0 + step;
- struct get_rows_tiled_task task = get_rows_tiled_calc_task(octx, grctx, i, n_k_tiles, tile_size);
-
- // Dummy writeback to prime the queue with dst descriptor
- dma_queue_push(dma_q,
- dma_make_data(task.dst_data, dst_spad_base + spad_idx * vtcm_layout->dst_spad_half_size),
- dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 0);
-
- // Prefetch row tiles
- dma_queue_push(dma_q,
- dma_make_data(src_spad_base + spad_idx * vtcm_layout->src0_spad_half_size, task.tile_src_base),
- tile_stride, tile_size, tile_size, n_k_tiles);
- }
-
- for (uint32_t step = 0; step < ir1 - ir0; ++step) {
- const uint32_t i = ir0 + step;
- float * dst_spad = (float *) dma_queue_pop(dma_q).src;
- uint8_t * src_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- struct get_rows_tiled_task task = get_rows_tiled_calc_task(octx, grctx, i, n_k_tiles, tile_size);
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
- compute_tiled(dst_spad, src_spad, n_k_tiles, tile_stride, task.row);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i);
-
- // Real writeback of dst_spad
- dma_queue_push(dma_q,
- dma_make_data(task.dst_data, dst_spad),
- dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 1);
-
- const uint32_t next_step = step + 2;
- if (next_step < ir1 - ir0) {
- const uint32_t ni = ir0 + next_step;
- struct get_rows_tiled_task next_task = get_rows_tiled_calc_task(octx, grctx, ni, n_k_tiles, tile_size);
- dma_queue_push(dma_q,
- dma_make_data(src_spad, next_task.tile_src_base),
- tile_stride, tile_size, tile_size, n_k_tiles);
- }
- }
-
- dma_queue_flush(dma_q);
-}
-
-static __attribute__((noinline)) void get_rows_dma_src1(
- struct htp_ops_context * octx,
- uint8_t * vtcm_src1,
- uint32_t elem_size
-) {
- const uint32_t ne10 = octx->src[1]->ne[0];
- const uint32_t ne11 = octx->src[1]->ne[1];
- const uint32_t ne12 = octx->src[1]->ne[2];
- const uint32_t ne13 = octx->src[1]->ne[3];
- const uint32_t nb11 = octx->src[1]->nb[1];
- const uint32_t nb12 = octx->src[1]->nb[2];
- const uint32_t nb13 = octx->src[1]->nb[3];
-
- dma_queue * dma_q = octx->ctx->dma[0];
- uint8_t * cur_dst = vtcm_src1;
- for (uint32_t i13 = 0; i13 < ne13; ++i13) {
- for (uint32_t i12 = 0; i12 < ne12; ++i12) {
- const dma_addr_t src_plane = octx->src[1]->data + i12 * nb12 + i13 * nb13;
- while (!dma_queue_push(dma_q, dma_make_data(cur_dst, src_plane),
- ne10 * elem_size, nb11, ne10 * elem_size, ne11)) {
- dma_queue_pop(dma_q);
- }
- cur_dst += ne10 * ne11 * elem_size;
- }
- }
- dma_queue_flush(dma_q);
+ void * in_buf[2] = { src_spad_base, src_spad_base + vtcm_layout->src0_spad_half_size };
+ void * out_buf[2] = { dst_spad_base, dst_spad_base + vtcm_layout->dst_spad_half_size };
+
+ struct get_rows_tiled_pipe_state s = {
+ .octx = octx,
+ .grctx = grctx,
+ .compute_tiled = grctx->compute_tiled,
+ .n_k_tiles = n_k_tiles,
+ .tile_size = grctx->tile_size,
+ .tile_stride = grctx->tile_stride,
+ .dst_bytes = grctx->dst_row_size,
+ .dst_spad_half = vtcm_layout->dst_spad_half_size,
+ .ir = ir0,
+ .ir_end = ir1,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ get_rows_tiled_next_task, get_rows_tiled_push_in, get_rows_tiled_compute, get_rows_tiled_push_out);
}
int op_get_rows(struct htp_ops_context * octx) {
@@ -377,7 +463,8 @@ 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);
- if (src0_row_size == 0) {
+ 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;
}
@@ -385,27 +472,22 @@ int op_get_rows(struct htp_ops_context * octx) {
if (octx->src[0]->type != octx->dst->type) {
return HTP_STATUS_NO_SUPPORT;
}
- } else {
- if (octx->dst->type != HTP_TYPE_F32) {
- 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 struct htp_tensor * dst = octx->dst;
const uint32_t total_tasks = kparams->total_tasks;
- const uint32_t dst_row_size = (kparams->kernel_type == HTP_GET_ROWS_KERNEL_SAMETYPE) ? src0_row_size : ne00 * sizeof(float);
uint32_t task_start = 0;
uint32_t tasks = total_tasks;
if (octx->ctx->mdev.count > 1) {
- uint32_t tasks_per_chunk = 1;
- htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) dst->nb[0], dst_row_size, &tasks_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, tasks_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
task_start = range.start;
tasks = range.count;
}
@@ -435,7 +517,7 @@ int op_get_rows(struct htp_ops_context * octx) {
grctx.dst_row_size = dst_row_size;
grctx.idx_type = octx->src[1]->type;
- htp_get_rows_vtcm_layout_build(&grctx.vtcm_layout, kparams->kernel_type, octx->src[0]->type, ne00, total_tasks, grctx.idx_type, n_hvx);
+ htp_get_rows_vtcm_layout_build(&grctx.vtcm_layout, kparams->kernel_type, octx->src[0]->type, octx->dst->type, ne00, n_hvx);
if (grctx.vtcm_layout.total_bytes > octx->ctx->vtcm_size) {
FARF(ERROR, "get-rows: VTCM reservation %zu is too small, needed %zu\n",
@@ -449,33 +531,62 @@ int op_get_rows(struct htp_ops_context * octx) {
q_func = get_rows_thread_sametype;
break;
case HTP_GET_ROWS_KERNEL_TILED:
- switch (octx->src[0]->type) {
- case HTP_TYPE_F16: grctx.compute_tiled = hvx_dequantize_row_tiled_f16_f32; break;
- case HTP_TYPE_Q1_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q1_0_f32; break;
- case HTP_TYPE_Q2_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q2_0_f32; break;
- case HTP_TYPE_Q8_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q8_0_f32; break;
- case HTP_TYPE_Q4_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_0_f32; break;
- case HTP_TYPE_Q4_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_k_f32; break;
- case HTP_TYPE_Q5_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q5_k_f32; break;
- case HTP_TYPE_Q6_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q6_k_f32; break;
- default: return HTP_STATUS_NO_SUPPORT;
+ if (octx->dst->type == HTP_TYPE_F16) {
+ switch (octx->src[0]->type) {
+ case HTP_TYPE_F16: grctx.compute_tiled = hvx_dequantize_row_tiled_f16_f16; break;
+ case HTP_TYPE_Q1_0: grctx.compute_tiled = get_rows_tiled_q1_0_f16; break;
+ case HTP_TYPE_Q2_0: grctx.compute_tiled = get_rows_tiled_q2_0_f16; break;
+ case HTP_TYPE_Q8_0: grctx.compute_tiled = get_rows_tiled_q8_0_f16; break;
+ case HTP_TYPE_Q4_0: grctx.compute_tiled = get_rows_tiled_q4_0_f16; break;
+ case HTP_TYPE_Q4_K: grctx.compute_tiled = get_rows_tiled_q4_k_f16; break;
+ case HTP_TYPE_Q5_K: grctx.compute_tiled = get_rows_tiled_q5_k_f16; break;
+ case HTP_TYPE_Q6_K: grctx.compute_tiled = get_rows_tiled_q6_k_f16; break;
+ default: return HTP_STATUS_NO_SUPPORT;
+ }
+ } else {
+ switch (octx->src[0]->type) {
+ case HTP_TYPE_F16: grctx.compute_tiled = hvx_dequantize_row_tiled_f16_f32; break;
+ case HTP_TYPE_Q1_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q1_0_f32; break;
+ case HTP_TYPE_Q2_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q2_0_f32; break;
+ case HTP_TYPE_Q8_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q8_0_f32; break;
+ case HTP_TYPE_Q4_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_0_f32; break;
+ case HTP_TYPE_Q4_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_k_f32; break;
+ case HTP_TYPE_Q5_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q5_k_f32; break;
+ case HTP_TYPE_Q6_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q6_k_f32; break;
+ default: return HTP_STATUS_NO_SUPPORT;
+ }
}
grctx.tile_size = htp_tensor_get_tile_size(octx->src[0]->type);
grctx.tile_stride = htp_tensor_get_tile_padded_size(octx->src[0]->type);
q_func = get_rows_thread_tiled;
break;
case HTP_GET_ROWS_KERNEL_FLAT:
- switch (octx->src[0]->type) {
- case HTP_TYPE_F16: grctx.compute_flat = hvx_dequantize_row_flat_f16_f32; break;
- case HTP_TYPE_BF16: grctx.compute_flat = hvx_dequantize_row_flat_bf16_f32; break;
- case HTP_TYPE_Q1_0: grctx.compute_flat = hvx_dequantize_row_flat_q1_0_f32; break;
- case HTP_TYPE_Q2_0: grctx.compute_flat = hvx_dequantize_row_flat_q2_0_f32; break;
- case HTP_TYPE_Q8_0: grctx.compute_flat = hvx_dequantize_row_flat_q8_0_f32; break;
- case HTP_TYPE_Q4_0: grctx.compute_flat = hvx_dequantize_row_flat_q4_0_f32; break;
- case HTP_TYPE_Q4_K: grctx.compute_flat = hvx_dequantize_row_flat_q4_k_f32; break;
- case HTP_TYPE_Q5_K: grctx.compute_flat = hvx_dequantize_row_flat_q5_k_f32; break;
- case HTP_TYPE_Q6_K: grctx.compute_flat = hvx_dequantize_row_flat_q6_k_f32; break;
- default: return HTP_STATUS_NO_SUPPORT;
+ if (octx->dst->type == HTP_TYPE_F16) {
+ switch (octx->src[0]->type) {
+ case HTP_TYPE_F32: grctx.compute_flat = get_rows_flat_f32_to_f16; break;
+ case HTP_TYPE_BF16: grctx.compute_flat = get_rows_flat_bf16_f16; break;
+ case HTP_TYPE_Q1_0: grctx.compute_flat = get_rows_flat_q1_0_f16; break;
+ case HTP_TYPE_Q2_0: grctx.compute_flat = get_rows_flat_q2_0_f16; break;
+ case HTP_TYPE_Q8_0: grctx.compute_flat = get_rows_flat_q8_0_f16; break;
+ case HTP_TYPE_Q4_0: grctx.compute_flat = get_rows_flat_q4_0_f16; break;
+ case HTP_TYPE_Q4_K: grctx.compute_flat = get_rows_flat_q4_k_f16; break;
+ case HTP_TYPE_Q5_K: grctx.compute_flat = get_rows_flat_q5_k_f16; break;
+ case HTP_TYPE_Q6_K: grctx.compute_flat = get_rows_flat_q6_k_f16; break;
+ default: return HTP_STATUS_NO_SUPPORT;
+ }
+ } else {
+ switch (octx->src[0]->type) {
+ case HTP_TYPE_F16: grctx.compute_flat = hvx_dequantize_row_flat_f16_f32; break;
+ case HTP_TYPE_BF16: grctx.compute_flat = hvx_dequantize_row_flat_bf16_f32; break;
+ case HTP_TYPE_Q1_0: grctx.compute_flat = hvx_dequantize_row_flat_q1_0_f32; break;
+ case HTP_TYPE_Q2_0: grctx.compute_flat = hvx_dequantize_row_flat_q2_0_f32; break;
+ case HTP_TYPE_Q8_0: grctx.compute_flat = hvx_dequantize_row_flat_q8_0_f32; break;
+ case HTP_TYPE_Q4_0: grctx.compute_flat = hvx_dequantize_row_flat_q4_0_f32; break;
+ case HTP_TYPE_Q4_K: grctx.compute_flat = hvx_dequantize_row_flat_q4_k_f32; break;
+ case HTP_TYPE_Q5_K: grctx.compute_flat = hvx_dequantize_row_flat_q5_k_f32; break;
+ case HTP_TYPE_Q6_K: grctx.compute_flat = hvx_dequantize_row_flat_q6_k_f32; break;
+ default: return HTP_STATUS_NO_SUPPORT;
+ }
}
q_func = get_rows_thread_flat;
break;
@@ -483,19 +594,18 @@ int op_get_rows(struct htp_ops_context * octx) {
return HTP_STATUS_NO_SUPPORT;
}
- const uint32_t elem_size = (grctx.idx_type == HTP_TYPE_I64) ? sizeof(int64_t) : sizeof(int32_t);
- const size_t src1_bytes = (size_t) total_tasks * elem_size;
-
- if (!htp_tensor_is_extended(octx->src[1]) && src1_bytes <= 128 &&
- htp_tensor_is_contiguous(octx->src[1], elem_size)) {
- grctx.src1_data = (const void *) (uintptr_t) octx->src[1]->data;
- grctx.read_index = get_rows_read_index_ddr;
- } else {
- uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, grctx.vtcm_base, grctx.vtcm_layout.off_src1);
- get_rows_dma_src1(octx, vtcm_src1, elem_size);
- grctx.src1_data = vtcm_src1;
- grctx.read_index = get_rows_read_index_vtcm;
+ const size_t src1_bytes = hex_round_up(htp_tensor_nbytes(octx->src[1]), 128);
+ void * src1_buf = (src1_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, src1_bytes);
+ if (!src1_buf) {
+ return HTP_STATUS_INTERNAL_ERR;
}
+ if (htp_tensor_read(&octx->ctx->main_th, src1_buf, src1_bytes, octx->src[1]) == 0) {
+ if (src1_buf != octx->ctx->ddr_spad_base) {
+ free(src1_buf);
+ }
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ grctx.src1_data = src1_buf;
FARF(HIGH, "get-rows: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : src0-vtcm-size %zu dst-vtcm-size %zu kernel-type %d n-hvx %d\n",
octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3],
@@ -506,5 +616,8 @@ int op_get_rows(struct htp_ops_context * octx) {
kparams->kernel_type, n_hvx);
work_queue_run(octx->ctx->hvx_queue, q_func, &grctx, n_hvx);
+ if (src1_buf != octx->ctx->ddr_spad_base) {
+ free(src1_buf);
+ }
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/get-rows-ops.h b/ggml/src/ggml-hexagon/htp/get-rows-ops.h
index 986966f11..3c724d981 100644
--- a/ggml/src/ggml-hexagon/htp/get-rows-ops.h
+++ b/ggml/src/ggml-hexagon/htp/get-rows-ops.h
@@ -29,8 +29,6 @@ struct htp_get_rows_kernel_params {
struct htp_get_rows_vtcm_layout {
size_t total_bytes;
- size_t off_src1;
- size_t src1_bytes;
size_t off_src0;
size_t off_dst;
@@ -44,39 +42,35 @@ struct htp_get_rows_vtcm_layout {
static inline void htp_get_rows_vtcm_layout_build(
struct htp_get_rows_vtcm_layout * L,
int kernel_type,
- int type,
+ int src0_type,
+ int dst_type,
uint32_t ne00,
- uint32_t total_tasks,
- int idx_type,
uint32_t n_hvx) {
memset(L, 0, sizeof(*L));
- const size_t elem_size = (idx_type == HTP_TYPE_I64) ? sizeof(int64_t) : sizeof(int32_t);
- const size_t src1_raw_bytes = total_tasks * elem_size;
- const size_t src1_bytes = ((src1_raw_bytes + 127) & ~127) + 128;
-
- L->src1_bytes = src1_bytes;
- const size_t src1_alloc_bytes = (src1_bytes + 255) & ~255;
-
if (kernel_type != HTP_GET_ROWS_KERNEL_SAMETYPE) {
size_t src0_row_size = 0;
if (kernel_type == HTP_GET_ROWS_KERNEL_TILED) {
- const size_t tile_stride = htp_tensor_get_tile_padded_size(type);
- const uint32_t n_k_tiles = ne00 / htp_tensor_get_tile_k(type);
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(src0_type);
+ const uint32_t n_k_tiles = ne00 / htp_tensor_get_tile_k(src0_type);
src0_row_size = n_k_tiles > 0 ? (n_k_tiles * tile_stride) : tile_stride;
} else {
- src0_row_size = htp_tensor_get_row_size(type, ne00);
+ src0_row_size = htp_tensor_get_row_size(src0_type, ne00);
}
+ const bool direct_f16_spad =
+ (kernel_type == HTP_GET_ROWS_KERNEL_TILED && src0_type == HTP_TYPE_F16 && dst_type == HTP_TYPE_F16) ||
+ (kernel_type == HTP_GET_ROWS_KERNEL_FLAT && src0_type == HTP_TYPE_F32 && dst_type == HTP_TYPE_F16);
+ const size_t dst_spad_row_size = htp_tensor_get_row_size(direct_f16_spad ? dst_type : HTP_TYPE_F32, ne00);
+
L->src0_spad_half_size = (src0_row_size + 255) & ~255;
- L->dst_spad_half_size = (ne00 * sizeof(float) + 255) & ~255;
+ L->dst_spad_half_size = (dst_spad_row_size + 255) & ~255;
L->src0_bytes_per_hvx = 2 * L->src0_spad_half_size;
L->dst_bytes_per_hvx = 2 * L->dst_spad_half_size;
}
size_t off = 0;
- VTCM_LAYOUT_ALLOC(off, off_src1, src1_alloc_bytes);
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx);
L->total_bytes = off;
diff --git a/ggml/src/ggml-hexagon/htp/glu-ops.c b/ggml/src/ggml-hexagon/htp/glu-ops.c
index 223c1829f..cecc0e538 100644
--- a/ggml/src/ggml-hexagon/htp/glu-ops.c
+++ b/ggml/src/ggml-hexagon/htp/glu-ops.c
@@ -1,13 +1,10 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <math.h>
#include <string.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hvx-utils.h"
#define GGML_COMMON_DECL_C
@@ -475,6 +472,7 @@ static __attribute__((noinline)) void hvx_sigglu_f32_vec(HVX_Vector * restrict v
const HVX_Vector v_max_exp = hvx_vec_splat_f32(87.0f);
const HVX_Vector v_min_exp = hvx_vec_splat_f32(-87.0f);
+ _Pragma("unroll(2)")
for (uint32_t i = 0; i < nvec; i++) {
HVX_Vector sig = hvx_vec_fast_sigmoid_f32_guard(vsrc0[i], v_one, v_max_exp, v_min_exp);
vdst[i] = hvx_vec_mul_f32_f32(sig, vsrc1[i]);
@@ -523,6 +521,11 @@ static void sigglu_f32(const float * restrict src0,
const struct htp_glu_context * gctx) {
htp_glu_op_preamble;
+ if ((size_t) nc * sizeof(float) == src0_row_size_aligned) {
+ hvx_sigglu_f32_aa((uint8_t *) dst, (const uint8_t *) src0, (const uint8_t *) src1, num_rows * (uint32_t) nc);
+ return;
+ }
+
for (uint32_t ib = 0; ib < num_rows; ib++) {
const uint8_t * restrict src0_ptr = (const uint8_t *) src0 + (ib * src0_row_size_aligned);
const uint8_t * restrict src1_ptr = (const uint8_t *) src1 + (ib * src1_row_size_aligned);
@@ -532,7 +535,58 @@ static void sigglu_f32(const float * restrict src0,
}
}
-// swiglu(x) = x1 * sigmoid(x0)
+static __attribute__((noinline)) void hvx_swiglu_f16_vec(HVX_Vector * restrict vdst,
+ const HVX_Vector * restrict vsrc0,
+ const HVX_Vector * restrict vsrc1,
+ uint32_t nvec) {
+ _Pragma("clang loop pipeline(disable) unroll(disable)")
+ for (uint32_t i = 0; i + 1 < nvec; i += 2) {
+ HVX_Vector x0 = vsrc0[i + 0];
+ HVX_Vector x1 = vsrc0[i + 1];
+ HVX_VectorPair sigp = hvx_vec_fast_sigmoid_f16_pair(x0, x1);
+ vdst[i + 0] = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x0, Q6_V_lo_W(sigp)), vsrc1[i + 0]);
+ vdst[i + 1] = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x1, Q6_V_hi_W(sigp)), vsrc1[i + 1]);
+ }
+}
+
+static __attribute__((noinline)) void hvx_swiglu_f16_tail(HVX_Vector * restrict vdst,
+ const HVX_Vector * restrict vsrc0,
+ const HVX_Vector * restrict vsrc1,
+ uint32_t nloe) {
+ HVX_Vector x = vsrc0[0];
+ HVX_Vector sig = hvx_vec_fast_sigmoid_f16(x);
+ HVX_Vector res = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x, sig), vsrc1[0]);
+ hvx_vec_store_a((void *) vdst, nloe * sizeof(_Float16), res);
+}
+
+static inline void hvx_swiglu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src0, const uint8_t * restrict src1, uint32_t n) {
+ assert((unsigned long) dst % 128 == 0);
+ assert((unsigned long) src0 % 128 == 0);
+ assert((unsigned long) src1 % 128 == 0);
+
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+ const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0;
+ const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1;
+
+ const uint32_t epv = 128 / sizeof(_Float16);
+ const uint32_t nvec = n / epv;
+ const uint32_t nloe = n % epv;
+ uint32_t i = 0;
+
+ if (nvec >= 2) {
+ const uint32_t nvec2 = nvec & ~1u;
+ hvx_swiglu_f16_vec(vdst, vsrc0, vsrc1, nvec2);
+ i = nvec2;
+ }
+ if (i < nvec) {
+ hvx_swiglu_f16_tail(vdst + i, vsrc0 + i, vsrc1 + i, epv);
+ }
+ if (nloe) {
+ hvx_swiglu_f16_tail(vdst + nvec, vsrc0 + nvec, vsrc1 + nvec, nloe);
+ }
+}
+
+// swiglu(x, g) = x * sigmoid(x) * g
static void swiglu_f16(const _Float16 * restrict src0,
const _Float16 * restrict src1,
_Float16 * restrict dst,
@@ -540,13 +594,17 @@ static void swiglu_f16(const _Float16 * restrict src0,
const struct htp_glu_context * gctx) {
htp_glu_op_preamble;
+ if ((size_t) nc * sizeof(_Float16) == src0_row_size_aligned) {
+ hvx_swiglu_f16_aa((uint8_t *) dst, (const uint8_t *) src0, (const uint8_t *) src1, num_rows * (uint32_t) nc);
+ return;
+ }
+
for (uint32_t ib = 0; ib < num_rows; ib++) {
const uint8_t * restrict src0_ptr = (const uint8_t *) src0 + (ib * src0_row_size_aligned);
const uint8_t * restrict src1_ptr = (const uint8_t *) src1 + (ib * src1_row_size_aligned);
uint8_t * restrict dst_ptr = (uint8_t *) dst + (ib * dst_row_size_aligned);
- hvx_sigmoid_f16_aa(dst_ptr, src0_ptr, nc);
- hvx_mul_mul_f16_aa(dst_ptr, src0_ptr, dst_ptr, src1_ptr, nc);
+ hvx_swiglu_f16_aa(dst_ptr, src0_ptr, src1_ptr, nc);
}
}
@@ -668,9 +726,13 @@ static __attribute__((noinline)) void hvx_sigglu_f16_vec(HVX_Vector * restrict v
const HVX_Vector * restrict vsrc0,
const HVX_Vector * restrict vsrc1,
uint32_t nvec) {
- for (uint32_t i = 0; i < nvec; i++) {
- HVX_Vector sig = hvx_vec_fast_sigmoid_f16(vsrc0[i]);
- vdst[i] = hvx_vec_mul_f16_f16(sig, vsrc1[i]);
+ for (uint32_t i = 0; i + 2 < nvec; i += 3) {
+ HVX_Vector sig0 = hvx_vec_fast_sigmoid_f16(vsrc0[i + 0]);
+ HVX_Vector sig1 = hvx_vec_fast_sigmoid_f16(vsrc0[i + 1]);
+ HVX_Vector sig2 = hvx_vec_fast_sigmoid_f16(vsrc0[i + 2]);
+ vdst[i + 0] = hvx_vec_mul_f16_f16(sig0, vsrc1[i + 0]);
+ vdst[i + 1] = hvx_vec_mul_f16_f16(sig1, vsrc1[i + 1]);
+ vdst[i + 2] = hvx_vec_mul_f16_f16(sig2, vsrc1[i + 2]);
}
}
@@ -695,9 +757,15 @@ static inline void hvx_sigglu_f16_aa(uint8_t * restrict dst, const uint8_t * res
const uint32_t epv = 128 / sizeof(_Float16);
const uint32_t nvec = n / epv;
const uint32_t nloe = n % epv;
+ uint32_t i = 0;
- if (nvec) {
- hvx_sigglu_f16_vec(vdst, vsrc0, vsrc1, nvec);
+ if (nvec >= 3) {
+ const uint32_t nvec3 = nvec - (nvec % 3);
+ hvx_sigglu_f16_vec(vdst, vsrc0, vsrc1, nvec3);
+ i = nvec3;
+ }
+ for (; i < nvec; i++) {
+ hvx_sigglu_f16_tail(vdst + i, vsrc0 + i, vsrc1 + i, epv);
}
if (nloe) {
hvx_sigglu_f16_tail(vdst + nvec, vsrc0 + nvec, vsrc1 + nvec, nloe);
@@ -712,6 +780,11 @@ static void sigglu_f16(const _Float16 * restrict src0,
const struct htp_glu_context * gctx) {
htp_glu_op_preamble;
+ if ((size_t) nc * sizeof(_Float16) == src0_row_size_aligned) {
+ hvx_sigglu_f16_aa((uint8_t *) dst, (const uint8_t *) src0, (const uint8_t *) src1, num_rows * (uint32_t) nc);
+ return;
+ }
+
for (uint32_t ib = 0; ib < num_rows; ib++) {
const uint8_t * restrict src0_ptr = (const uint8_t *) src0 + (ib * src0_row_size_aligned);
const uint8_t * restrict src1_ptr = (const uint8_t *) src1 + (ib * src1_row_size_aligned);
@@ -721,99 +794,85 @@ static void sigglu_f16(const _Float16 * restrict src0,
}
}
-#define DEFINE_GLU_PER_THREAD(TYPE, SUFFIX) \
- static void glu_##SUFFIX##_per_hvx(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { \
- struct htp_glu_context * gctx = (struct htp_glu_context *) data; \
- htp_glu_preamble; \
- \
- struct htp_thread_trace * tr = th->trace; \
- \
- size_t src0_row_size = gctx->src0_row_size; \
- size_t src1_row_size = gctx->src1_row_size; \
- size_t dst_row_size = gctx->dst_row_size; \
- \
- size_t src0_row_stride = gctx->src0_row_stride; \
- size_t src1_row_stride = gctx->src1_row_stride; \
- \
- const uint32_t src0_nrows = gctx->src0_nrows; \
- const uint32_t src0_nrows_per_hvx = gctx->src0_nrows_per_hvx; \
- \
- const uint32_t src0_start_row = gctx->row_start + src0_nrows_per_hvx * ith; \
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, gctx->row_start + src0_nrows); \
- \
- /* no work for this thread */ \
- if (src0_start_row >= src0_end_row) { \
- return; \
- } \
- \
- const dma_addr_t data_src0 = gctx->data_src0; \
- const dma_addr_t data_src1 = gctx->data_src1; \
- const dma_addr_t data_dst = gctx->data_dst; \
- \
- const size_t src0_row_size_aligned = gctx->src0_row_size_aligned; \
- const size_t src1_row_size_aligned = gctx->src1_row_size_aligned; \
- const size_t dst_row_size_aligned = gctx->dst_row_size_aligned; \
- \
- uint8_t * restrict src0_spad_data = gctx->vtcm_src0 + (ith * gctx->vtcm_src0_size_per_hvx); \
- uint8_t * restrict src1_spad_data = gctx->vtcm_src1 + (ith * gctx->vtcm_src1_size_per_hvx); \
- uint8_t * restrict dst_spad_data = gctx->vtcm_dst + (ith * gctx->vtcm_dst_size_per_hvx); \
- \
- size_t src0_spad_half_size = gctx->src0_spad_half_size; \
- size_t src1_spad_half_size = gctx->src1_spad_half_size; \
- size_t dst_spad_half_size = gctx->dst_spad_half_size; \
- \
- const int BLOCK = gctx->block; \
- \
- dma_queue * dma_q = th->dma_q; \
- glu_compute_##SUFFIX##_fn_t compute = (glu_compute_##SUFFIX##_fn_t) gctx->compute; \
- \
- for (uint32_t ir = src0_start_row, spad_idx = 0; ir < src0_end_row && spad_idx < 2; ir += BLOCK, spad_idx++) { \
- const uint32_t block_size = MIN(BLOCK, src0_end_row - ir); \
- \
- /* Dummy DMA transation for sequencing (interleaving dst,src,dst,...) */ \
- dma_queue_push(dma_q, \
- dma_make_data(data_dst, dst_spad_data + (spad_idx * dst_spad_half_size)), \
- dst_row_size, dst_row_size_aligned, dst_row_size, 0); \
- \
- dma_queue_push(dma_q, \
- dma_make_data(src0_spad_data + (spad_idx * src0_spad_half_size), data_src0 + (ir * src0_row_stride)), \
- src0_row_size_aligned, src0_row_stride, src0_row_size, block_size); \
- \
- dma_queue_push(dma_q, \
- dma_make_data(src1_spad_data + (spad_idx * src1_spad_half_size), data_src1 + (ir * src1_row_stride)), \
- src1_row_size_aligned, src1_row_stride, src1_row_size, block_size); \
- } \
- \
- for (uint32_t ir = src0_start_row; ir < src0_end_row; ir += BLOCK) { \
- const uint32_t block_size = MIN(BLOCK, src0_end_row - ir); \
- \
- TYPE * dst_spad = (TYPE *) dma_queue_pop(dma_q).src; \
- TYPE * src0_spad = (TYPE *) dma_queue_pop(dma_q).dst; \
- TYPE * src1_spad = (TYPE *) dma_queue_pop(dma_q).dst; \
- \
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir); \
- compute(src0_spad, src1_spad, dst_spad, block_size, gctx); \
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir); \
- \
- dma_queue_push(dma_q, dma_make_data(data_dst + (ir * dst_row_size), dst_spad), \
- dst_row_size, dst_row_size_aligned, dst_row_size, block_size); \
- \
- /* prefetch N+2 loop iteration if any */ \
- const uint32_t pref_block = (ir + BLOCK * 2); \
- if (pref_block < src0_end_row) { \
- const uint32_t pref_block_size = MIN(BLOCK, src0_end_row - pref_block); \
- dma_queue_push(dma_q, dma_make_data(src0_spad, data_src0 + (pref_block * src0_row_stride)), \
- src0_row_size_aligned, src0_row_stride, src0_row_size, pref_block_size); \
- dma_queue_push(dma_q, dma_make_data(src1_spad, data_src1 + (pref_block * src1_row_stride)), \
- src1_row_size_aligned, src1_row_stride, src1_row_size, pref_block_size); \
- } \
- } \
- \
- dma_queue_flush(dma_q); \
+struct glu_pipe_state {
+ const struct htp_glu_context * gctx;
+ uint32_t ir;
+ uint32_t ir_end;
+};
+
+static bool glu_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct glu_pipe_state * s = (struct glu_pipe_state *) ctx;
+ if (s->ir >= s->ir_end) {
+ return false;
}
+ const uint32_t block_size = MIN((uint32_t) s->gctx->block, s->ir_end - s->ir);
+ task->row = s->ir;
+ task->off = 0;
+ task->len = block_size;
+ task->aux = 0;
+ s->ir += block_size;
+ return true;
+}
-DEFINE_GLU_PER_THREAD(float, f32)
-DEFINE_GLU_PER_THREAD(_Float16, f16)
+static void glu_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) {
+ const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx;
+ dma_queue_push(dma_q, dma_make_data(in0_spad, gctx->data_src0 + (size_t) task->row * gctx->src0_row_stride),
+ gctx->src0_row_size_aligned, gctx->src0_row_stride, gctx->src0_row_size, task->len);
+ dma_queue_push(dma_q, dma_make_data(in1_spad, gctx->data_src1 + (size_t) task->row * gctx->src1_row_stride),
+ gctx->src1_row_size_aligned, gctx->src1_row_stride, gctx->src1_row_size, task->len);
+}
+
+static void glu_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx;
+ dma_queue_push(dma_q, dma_make_data(gctx->data_dst + (size_t) task->row * gctx->dst_row_size, out_spad),
+ gctx->dst_row_size, gctx->dst_row_size_aligned, gctx->dst_row_size, task->len);
+}
+
+static void glu_compute_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) {
+ const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx;
+ glu_compute_f32_fn_t compute = (glu_compute_f32_fn_t) gctx->compute;
+ compute((const float *) in0_spad, (const float *) in1_spad, (float *) out_spad, task->len, gctx);
+}
+
+static void glu_compute_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) {
+ const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx;
+ glu_compute_f16_fn_t compute = (glu_compute_f16_fn_t) gctx->compute;
+ compute((const _Float16 *) in0_spad, (const _Float16 *) in1_spad, (_Float16 *) out_spad, task->len, gctx);
+}
+
+static void glu_thread_run(const htp_thread_t * th, unsigned int ith, const struct htp_glu_context * gctx, dma_pipe_compute_io2_fn compute) {
+ const uint32_t src0_start_row = gctx->row_start + gctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + gctx->src0_nrows_per_hvx, gctx->row_start + gctx->src0_nrows);
+ if (src0_start_row >= src0_end_row) {
+ return;
+ }
+
+ uint8_t * src0_spad_data = gctx->vtcm_src0 + (ith * gctx->vtcm_src0_size_per_hvx);
+ uint8_t * src1_spad_data = gctx->vtcm_src1 + (ith * gctx->vtcm_src1_size_per_hvx);
+ uint8_t * dst_spad_data = gctx->vtcm_dst + (ith * gctx->vtcm_dst_size_per_hvx);
+ void * in0_buf[2] = { src0_spad_data, src0_spad_data + gctx->src0_spad_half_size };
+ void * in1_buf[2] = { src1_spad_data, src1_spad_data + gctx->src1_spad_half_size };
+ void * out_buf[2] = { dst_spad_data, dst_spad_data + gctx->dst_spad_half_size };
+
+ struct glu_pipe_state s = {
+ .gctx = gctx,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
+
+ dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf,
+ glu_next_task, glu_push_in, compute, glu_push_out);
+}
+
+static void glu_f32_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ glu_thread_run(th, ith, (const struct htp_glu_context *) data, glu_compute_f32);
+}
+
+static void glu_f16_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ glu_thread_run(th, ith, (const struct htp_glu_context *) data, glu_compute_f16);
+}
static int execute_op_glu_f32(struct htp_ops_context * octx) {
const struct htp_tensor * src0 = octx->src[0];
@@ -882,9 +941,7 @@ static int execute_op_glu_f32(struct htp_ops_context * octx) {
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -987,7 +1044,7 @@ static int execute_op_glu_f32(struct htp_ops_context * octx) {
gctx.data_src1 = data_src1;
gctx.data_dst = dst->data;
- work_queue_run(octx->ctx->hvx_queue, (work_queue_func_t)glu_f32_per_hvx, &gctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, glu_f32_thread, &gctx, n_hvx);
return HTP_STATUS_OK;
}
@@ -1048,9 +1105,7 @@ static int execute_op_glu_f16(struct htp_ops_context * octx) {
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(_Float16), (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -1153,7 +1208,7 @@ static int execute_op_glu_f16(struct htp_ops_context * octx) {
gctx.data_src1 = data_src1;
gctx.data_dst = dst->data;
- work_queue_run(octx->ctx->hvx_queue, (work_queue_func_t)glu_f16_per_hvx, &gctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, glu_f16_thread, &gctx, n_hvx);
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/hex-utils.h b/ggml/src/ggml-hexagon/htp/hex-utils.h
index cb3093dec..af3a938ac 100644
--- a/ggml/src/ggml-hexagon/htp/hex-utils.h
+++ b/ggml/src/ggml-hexagon/htp/hex-utils.h
@@ -65,11 +65,14 @@ static inline void hex_l2fetch_block(const void * addr, size_t size) {
static inline void hex_l2flush(void * addr, size_t size) {
if (size == 0) return;
- const uint32_t s = ((uint32_t) addr) & ~(HEX_L2_LINE_SIZE - 1);
- const uint32_t e = (((uint32_t) addr) + size + HEX_L2_LINE_SIZE - 1) & ~(HEX_L2_LINE_SIZE - 1);
- for (uint32_t i = s; i < e; i += HEX_L2_LINE_SIZE) {
+ // Step by 64B (L1D line size on v73+ and L2 line size on v73) so no L1D lines are skipped.
+ const uint32_t line = 64;
+ const uint32_t s = ((uint32_t) addr) & ~(line - 1);
+ const uint32_t e = (((uint32_t) addr) + size + line - 1) & ~(line - 1);
+ for (uint32_t i = s; i < e; i += line) {
Q6_dccleaninva_A((void *) i);
}
+ asm volatile(" syncht\n" : : : "memory");
}
static inline void hex_pause() {
diff --git a/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h b/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h
index d5fb48ad9..3f061c0b6 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h
@@ -623,83 +623,4 @@ static inline void hmx_fa_q_prep_fp16_pad(__fp16 * vtcm_q_t
}
}
-static inline void hmx_fa_q_prep_fallback(
- __fp16 * vtcm_q_tiles, uintptr_t q_data,
- size_t q_nb1, size_t q_nb2, size_t q_nb3,
- uint32_t q_start, uint32_t kv_head, uint32_t ib3,
- size_t start, size_t end, size_t n_rows_g,
- size_t G, size_t dk_in, size_t dk_out, bool is_q_fp32,
- const struct fastdiv_values * div_G
-) {
- for (size_t r = start; r < end; r += 2) {
- const size_t q_idx0 = fastdiv(r + 0, div_G);
- const size_t h_idx0 = fastmodulo(r + 0, G, div_G);
- const size_t q_idx1 = fastdiv(r + 1, div_G);
- const size_t h_idx1 = fastmodulo(r + 1, G, div_G);
-
- const uint8_t * q_ptr0 = (r + 0 < n_rows_g) ? ((const uint8_t *) q_data + (q_start + q_idx0) * q_nb1 +
- (kv_head * G + h_idx0) * q_nb2 + ib3 * q_nb3) :
- NULL;
- const uint8_t * q_ptr1 = (r + 1 < n_rows_g) ? ((const uint8_t *) q_data + (q_start + q_idx1) * q_nb1 +
- (kv_head * G + h_idx1) * q_nb2 + ib3 * q_nb3) :
- NULL;
-
- size_t r0 = r / HMX_FP16_TILE_N_ROWS;
- size_t r1 = r % HMX_FP16_TILE_N_ROWS;
- __fp16 * out_base = vtcm_q_tiles + r0 * HMX_FP16_TILE_N_ROWS * dk_out;
-
- if (is_q_fp32) {
- const HVX_UVector * pv_in0 = q_ptr0 ? (const HVX_UVector *) q_ptr0 : NULL;
- const HVX_UVector * pv_in1 = q_ptr1 ? (const HVX_UVector *) q_ptr1 : NULL;
-
- for (uint32_t d = 0; d < dk_out / 32; ++d) {
- HVX_Vector * out_tile = (HVX_Vector *) (out_base + d * HMX_FP16_TILE_N_ELMS);
- const size_t base_lane = (size_t) d * 32;
- const size_t real_lanes = (base_lane < dk_in) ? hex_smin(32, dk_in - base_lane) : 0;
-
- if (real_lanes == 0) {
- out_tile[r1 / 2] = Q6_V_vzero();
- continue;
- }
- HVX_Vector v0 = pv_in0 ? pv_in0[d] : Q6_V_vzero();
- HVX_Vector v1 = pv_in1 ? pv_in1[d] : Q6_V_vzero();
- if (real_lanes < 32) {
- const HVX_VectorPred keep = Q6_Q_vsetq_R((uint32_t) (real_lanes * sizeof(float)));
- v0 = Q6_V_vmux_QVV(keep, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(keep, v1, Q6_V_vzero());
- }
- out_tile[r1 / 2] = hvx_vec_f32_to_f16_shuff(v0, v1);
- }
- } else {
- const HVX_UVector * pv_in0 = q_ptr0 ? (const HVX_UVector *) q_ptr0 : NULL;
- const HVX_UVector * pv_in1 = q_ptr1 ? (const HVX_UVector *) q_ptr1 : NULL;
-
- for (uint32_t d = 0; d < dk_out / 64; ++d) {
- __fp16 * out_dtile = out_base + d * HMX_FP16_TILE_N_ELMS * 2;
- HVX_Vector * pv_out0 = ((HVX_Vector *) out_dtile) + r1 / 2;
- HVX_Vector * pv_out1 = pv_out0 + 16;
-
- const size_t base_lane = (size_t) d * 64;
- const size_t real_lanes = (base_lane < dk_in) ? hex_smin(64, dk_in - base_lane) : 0;
-
- if (real_lanes == 0) {
- *pv_out0 = Q6_V_vzero();
- *pv_out1 = Q6_V_vzero();
- continue;
- }
- HVX_Vector v0 = pv_in0 ? pv_in0[d] : Q6_V_vzero();
- HVX_Vector v1 = pv_in1 ? pv_in1[d] : Q6_V_vzero();
- if (real_lanes < 64) {
- const HVX_VectorPred keep = Q6_Q_vsetq_R((uint32_t) (real_lanes * sizeof(__fp16)));
- v0 = Q6_V_vmux_QVV(keep, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(keep, v1, Q6_V_vzero());
- }
- HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
- *pv_out0 = Q6_V_lo_W(vp);
- *pv_out1 = Q6_V_hi_W(vp);
- }
- }
- }
-}
-
#endif /* HMX_FA_KERNELS_H */
diff --git a/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h b/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h
new file mode 100644
index 000000000..06bc147cb
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h
@@ -0,0 +1,801 @@
+#ifndef HMX_FA_W8A8_KERNELS_H
+#define HMX_FA_W8A8_KERNELS_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#include "hex-fastdiv.h"
+#include "hmx-int-utils.h"
+#include "hmx-utils.h"
+#include "hvx-utils.h"
+
+// Quantize one 4-row quad of FP32 Q into W8A8 U8 SM 64x32 tiles and emit d_q (with scale folded).
+static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f32(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_q_out,
+ const float * restrict p0,
+ const float * restrict p1,
+ const float * restrict p2,
+ const float * restrict p3,
+ uint32_t rg,
+ uint32_t n_dot,
+ uint32_t valid_rows,
+ float scale_f32) {
+
+ HVX_Vector vmax0 = Q6_V_vzero();
+ HVX_Vector vmax1 = Q6_V_vzero();
+ HVX_Vector vmax2 = Q6_V_vzero();
+ HVX_Vector vmax3 = Q6_V_vzero();
+
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = *(const HVX_UVector *) (p0 + off);
+ HVX_Vector vx1 = *(const HVX_UVector *) (p1 + off);
+ HVX_Vector vx2 = *(const HVX_UVector *) (p2 + off);
+ HVX_Vector vx3 = *(const HVX_UVector *) (p3 + off);
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1));
+ vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2));
+ vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3));
+ }
+
+ vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(vmax0) : Q6_V_vzero();
+ vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(vmax1) : Q6_V_vzero();
+ vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(vmax2) : Q6_V_vzero();
+ vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(vmax3) : Q6_V_vzero();
+
+ const HVX_Vector v_sc_inv127 = hvx_vec_splat_f32(scale_f32 * (1.0f / 127.0f));
+ const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f);
+ const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f);
+
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_sc_inv127);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_sc_inv127);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_sc_inv127);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_sc_inv127);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_d = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(d_q_out, 4 * sizeof(float), v_d);
+
+ HVX_Vector v_inv0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero());
+ HVX_Vector v_inv1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero());
+ HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero());
+ HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero());
+
+#if __HVX_ARCH__ >= 81
+ const uint32_t n_pairs = n_dot >> 1;
+ for (uint32_t step = 0; step < n_pairs; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p0 + off + 32), v_inv0),
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p0 + off + 0), v_inv0))));
+ HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p1 + off + 32), v_inv1),
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p1 + off + 0), v_inv1))));
+ HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p2 + off + 32), v_inv2),
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p2 + off + 0), v_inv2))));
+ HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p3 + off + 32), v_inv3),
+ Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p3 + off + 0), v_inv3))));
+
+ pack_hf_quad_to_u8_sm_pair(tile_row_base, step * 2, rg, hf0, hf1, hf2, hf3);
+ }
+ if (n_dot & 1u) {
+ const uint32_t kt = n_dot - 1u;
+ const uint32_t off = kt * 32;
+ const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80);
+ const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1);
+ HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p0 + off), v_inv0))));
+ HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p1 + off), v_inv1))));
+ HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p2 + off), v_inv2))));
+ HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p3 + off), v_inv3))));
+
+ HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0)));
+ HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1)));
+ HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1);
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] =
+ Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b);
+ }
+#else
+ const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f
+ const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = *(const HVX_UVector *) (p0 + off);
+ HVX_Vector vx1 = *(const HVX_UVector *) (p1 + off);
+ HVX_Vector vx2 = *(const HVX_UVector *) (p2 + off);
+ HVX_Vector vx3 = *(const HVX_UVector *) (p3 + off);
+
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
+
+ HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
+ }
+#endif
+}
+
+// Quantize one 4-row quad of FP16 Q into W8A8 U8 SM 64x32 tiles and emit d_q (with scale folded).
+static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f16(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_q_out,
+ const __fp16 * restrict p0,
+ const __fp16 * restrict p1,
+ const __fp16 * restrict p2,
+ const __fp16 * restrict p3,
+ uint32_t rg,
+ uint32_t n_dot,
+ uint32_t valid_rows,
+ float scale_f32) {
+
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_abs_f16 = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector vmax_hf0 = Q6_V_vzero();
+ HVX_Vector vmax_hf1 = Q6_V_vzero();
+ HVX_Vector vmax_hf2 = Q6_V_vzero();
+ HVX_Vector vmax_hf3 = Q6_V_vzero();
+
+ const uint32_t n_pairs = n_dot >> 1;
+ for (uint32_t step = 0; step < n_pairs; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector vh0 = *(const HVX_UVector *) (p0 + off);
+ HVX_Vector vh1 = *(const HVX_UVector *) (p1 + off);
+ HVX_Vector vh2 = *(const HVX_UVector *) (p2 + off);
+ HVX_Vector vh3 = *(const HVX_UVector *) (p3 + off);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16));
+ }
+ if (n_dot & 1u) {
+ const uint32_t off = (n_dot - 1u) * 32;
+ const HVX_VectorPred q_32h = Q6_Q_vsetq2_R(32 * sizeof(__fp16));
+ HVX_Vector vh0 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p0 + off), Q6_V_vzero());
+ HVX_Vector vh1 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p1 + off), Q6_V_vzero());
+ HVX_Vector vh2 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p2 + off), Q6_V_vzero());
+ HVX_Vector vh3 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p3 + off), Q6_V_vzero());
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16));
+ }
+
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vror_VR(vmax_hf0, 64));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vror_VR(vmax_hf1, 64));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vror_VR(vmax_hf2, 64));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vror_VR(vmax_hf3, 64));
+
+ HVX_Vector vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf0), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf1), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf2), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf3), v_one_f16)))) : Q6_V_vzero();
+
+ const HVX_Vector v_sc_inv127 = hvx_vec_splat_f32(scale_f32 * (1.0f / 127.0f));
+ const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f);
+ const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f);
+
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_sc_inv127);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_sc_inv127);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_sc_inv127);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_sc_inv127);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_d = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(d_q_out, 4 * sizeof(float), v_d);
+
+ HVX_Vector v_inv0_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv1_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()));
+
+#if __HVX_ARCH__ >= 81
+ for (uint32_t step = 0; step < n_pairs; ++step) {
+ const uint32_t off = step * 64;
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p0 + off), v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p1 + off), v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p2 + off), v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p3 + off), v_one_f16);
+
+ HVX_Vector hf0 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf)));
+ HVX_Vector hf1 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf)));
+ HVX_Vector hf2 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf)));
+ HVX_Vector hf3 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf)));
+
+ pack_hf_quad_to_u8_sm_pair(tile_row_base, step * 2, rg, hf0, hf1, hf2, hf3);
+ }
+ if (n_dot & 1u) {
+ const uint32_t kt = n_dot - 1u;
+ const uint32_t off = kt * 32;
+ const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80);
+ const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1);
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p0 + off)), v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p1 + off)), v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16);
+
+ HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf))));
+ HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf))));
+ HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf))));
+ HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf))));
+
+ HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0)));
+ HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1)));
+ HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1);
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] =
+ Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b);
+ }
+#else
+ const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080);
+ const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ for (uint32_t step = 0; step < n_pairs; ++step) {
+ const uint32_t off = step * 64;
+ const uint32_t kt = step * 2;
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p0 + off)), v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p1 + off)), v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16);
+
+ {
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8));
+ HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
+ ((HVX_Vector *) (tile_row_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
+ }
+ {
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), v_bias_u8));
+ HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
+ ((HVX_Vector *) (tile_row_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
+ }
+ }
+ if (n_dot & 1u) {
+ const uint32_t kt = n_dot - 1u;
+ const uint32_t off = kt * 32;
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p0 + off)), v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p1 + off)), v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16);
+
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8));
+ HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
+ }
+#endif
+}
+
+static inline void hmx_fa_w8a8_q_prep_f32(
+ uint8_t * restrict vtcm_q_tiles,
+ float * restrict vtcm_q_scales,
+ const uint8_t * restrict temp_q_vtcm,
+ size_t start,
+ size_t end,
+ size_t g_rows_end,
+ size_t DK,
+ size_t G,
+ size_t n_rows_q,
+ const struct fastdiv_values * div_G,
+ bool q_transposed,
+ float scale_f32) {
+
+ const uint32_t n_dot = (uint32_t) (DK / 32);
+ const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80);
+
+ for (size_t r = start; r < end; r += 4) {
+ const size_t r0 = r >> 6;
+ const uint32_t rg = (uint32_t) ((r & 63) >> 2);
+ uint8_t * tile_row_base = vtcm_q_tiles + r0 * n_dot * HMX_W8A8_ACT_TILE_SIZE;
+
+ if (r >= g_rows_end) {
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = v_zp_u8;
+ }
+ hvx_vec_store_u(vtcm_q_scales + r, 4 * sizeof(float), Q6_V_vzero());
+ continue;
+ }
+
+ const uint32_t valid_rows = (uint32_t) hex_smin(4, g_rows_end - r);
+ const float * ptrs[4];
+ for (uint32_t k = 0; k < 4; ++k) {
+ if (k < valid_rows) {
+ const size_t q_idx = fastdiv(r + k, div_G);
+ const size_t h_idx = fastmodulo(r + k, G, div_G);
+ const size_t offset = q_transposed ? (h_idx * n_rows_q + q_idx) : (q_idx * G + h_idx);
+ ptrs[k] = (const float *) (temp_q_vtcm + offset * DK * sizeof(float));
+ } else {
+ ptrs[k] = ptrs[0];
+ }
+ }
+
+ hmx_fa_w8a8_q_prep_quad_f32(
+ tile_row_base, vtcm_q_scales + r,
+ ptrs[0], ptrs[1], ptrs[2], ptrs[3],
+ rg, n_dot, valid_rows, scale_f32);
+ }
+}
+
+static inline void hmx_fa_w8a8_q_prep_f16(
+ uint8_t * restrict vtcm_q_tiles,
+ float * restrict vtcm_q_scales,
+ const uint8_t * restrict temp_q_vtcm,
+ size_t start,
+ size_t end,
+ size_t g_rows_end,
+ size_t DK,
+ size_t G,
+ size_t n_rows_q,
+ const struct fastdiv_values * div_G,
+ bool q_transposed,
+ float scale_f32) {
+
+ const uint32_t n_dot = (uint32_t) (DK / 32);
+ const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80);
+
+ for (size_t r = start; r < end; r += 4) {
+ const size_t r0 = r >> 6;
+ const uint32_t rg = (uint32_t) ((r & 63) >> 2);
+ uint8_t * tile_row_base = vtcm_q_tiles + r0 * n_dot * HMX_W8A8_ACT_TILE_SIZE;
+
+ if (r >= g_rows_end) {
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = v_zp_u8;
+ }
+ hvx_vec_store_u(vtcm_q_scales + r, 4 * sizeof(float), Q6_V_vzero());
+ continue;
+ }
+
+ const uint32_t valid_rows = (uint32_t) hex_smin(4, g_rows_end - r);
+ const __fp16 * ptrs[4];
+ for (uint32_t k = 0; k < 4; ++k) {
+ if (k < valid_rows) {
+ const size_t q_idx = fastdiv(r + k, div_G);
+ const size_t h_idx = fastmodulo(r + k, G, div_G);
+ const size_t offset = q_transposed ? (h_idx * n_rows_q + q_idx) : (q_idx * G + h_idx);
+ ptrs[k] = (const __fp16 *) (temp_q_vtcm + offset * DK * sizeof(__fp16));
+ } else {
+ ptrs[k] = ptrs[0];
+ }
+ }
+
+ hmx_fa_w8a8_q_prep_quad_f16(
+ tile_row_base, vtcm_q_scales + r,
+ ptrs[0], ptrs[1], ptrs[2], ptrs[3],
+ rg, n_dot, valid_rows, scale_f32);
+ }
+}
+
+static inline HVX_Vector hmx_fa_w8a8_k_pack4(const uint8_t * p, size_t stride) {
+ HVX_Vector v0 = *(const HVX_UVector *) (p + 0 * stride);
+ HVX_Vector v1 = *(const HVX_UVector *) (p + 1 * stride);
+ HVX_Vector v2 = *(const HVX_UVector *) (p + 2 * stride);
+ HVX_Vector v3 = *(const HVX_UVector *) (p + 3 * stride);
+ HVX_Vector p01 = Q6_V_lo_W(Q6_W_vshuff_VVR(v1, v0, -4));
+ HVX_Vector p23 = Q6_V_lo_W(Q6_W_vshuff_VVR(v3, v2, -4));
+ 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.
+static inline void hmx_fa_w8a8_k_rescale_pair(
+ HVX_Vector v_q0,
+ HVX_Vector v_q1,
+ HVX_Vector v_m_b4,
+ HVX_Vector * restrict tile_dst,
+ int pair_idx,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ const HVX_Vector v_neg1_h = Q6_Vh_vsplat_R(-1);
+ HVX_VectorPair vp_p01 = Q6_Wh_vmpy_VbVb(v_q0, v_m_b4);
+ HVX_VectorPair vp_p23 = Q6_Wh_vmpy_VbVb(v_q1, v_m_b4);
+ HVX_Vector v_p23_lo = Q6_Vh_vadd_VhVh(Q6_V_lo_W(vp_p23), v_neg1_h);
+ HVX_Vector v_p23_hi = Q6_Vh_vadd_VhVh(Q6_V_hi_W(vp_p23), v_neg1_h);
+
+#if __HVX_ARCH__ >= 79
+ HVX_Vector v_W0 = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp_p01), Q6_V_lo_W(vp_p01), 7);
+ HVX_Vector v_W1 = Q6_Vb_vasr_VhVhR_rnd_sat(v_p23_hi, v_p23_lo, 7);
+#else
+ HVX_Vector v_W0 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p01), 1),
+ Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p01), 1));
+ 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);
+}
+
+// Q8_0 K -> S8 weight.b 32x32 tiles for one column tile (32 KV rows).
+static __attribute__((noinline)) void hmx_fa_w8a8_k_prep_tile(
+ const uint8_t * restrict k_raw,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t valid_rows,
+ uint32_t n_dot,
+ size_t k_raw_row_padded) {
+
+ uint16_t off_l1[64] __attribute__((aligned(128)));
+ for (uint32_t c = 0; c < 32; ++c) {
+ off_l1[c] = (c < valid_rows) ? (uint16_t) (c * k_raw_row_padded) : 0;
+ off_l1[c + 32] = 0;
+ }
+ const HVX_Vector v_off_h = *(const HVX_Vector *) off_l1;
+ const uint32_t mu = (uint32_t) (32 * k_raw_row_padded - 1);
+ const HVX_VectorPred q_valid_h = Q6_Q_vsetq2_R(valid_rows * sizeof(uint16_t));
+
+ // Step 1: gather Q8_0 block scales into tile_dst[kt * 8 + 7] and compute per-channel max
+ HVX_Vector * tile_dst_all = (HVX_Vector *) dst_wt;
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ Q6_vgather_ARMVh(&tile_dst_all[kt * 8 + 7], (size_t) (k_raw + kt * 34), mu, v_off_h);
+ }
+ hvx_gather_sync(&tile_dst_all[(n_dot - 1) * 8 + 7]);
+
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ HVX_Vector v_sc = Q6_V_vmux_QVV(q_valid_h, tile_dst_all[kt * 8 + 7], Q6_V_vzero());
+ tile_dst_all[kt * 8 + 7] = v_sc;
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(v_sc, v_abs_mask));
+ }
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_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);
+ }
+
+ // Step 2: 32x32-byte vshuffvdd transpose of int8 quants and rescale in-place to weight.b
+ // Invalid rows (r >= valid_rows) have zeroed scales so v_m_b4 == 0 zeroes their weights.
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < n_dot; ++kt) {
+ HVX_Vector * tile_dst = tile_dst_all + kt * 8;
+ const uint8_t * qs_base = k_raw + kt * 34 + 2;
+
+ HVX_Vector b0, b1, b4, b5;
+ {
+ HVX_Vector t0 = hmx_fa_w8a8_k_pack4(qs_base + 0 * k_raw_row_padded, k_raw_row_padded);
+ HVX_Vector t1 = hmx_fa_w8a8_k_pack4(qs_base + 4 * k_raw_row_padded, k_raw_row_padded);
+ HVX_VectorPair w01 = Q6_W_vshuff_VVR(t1, t0, -16);
+ HVX_Vector t2 = hmx_fa_w8a8_k_pack4(qs_base + 8 * k_raw_row_padded, k_raw_row_padded);
+ HVX_Vector t3 = hmx_fa_w8a8_k_pack4(qs_base + 12 * k_raw_row_padded, k_raw_row_padded);
+ HVX_VectorPair w23 = Q6_W_vshuff_VVR(t3, t2, -16);
+
+ HVX_VectorPair u0 = Q6_W_vshuff_VVR(Q6_V_lo_W(w23), Q6_V_lo_W(w01), -32);
+ HVX_VectorPair u2 = Q6_W_vshuff_VVR(Q6_V_hi_W(w23), Q6_V_hi_W(w01), -32);
+ b0 = Q6_V_lo_W(u0);
+ b1 = Q6_V_hi_W(u0);
+ b4 = Q6_V_lo_W(u2);
+ b5 = Q6_V_hi_W(u2);
+ }
+
+ {
+ HVX_Vector t4 = hmx_fa_w8a8_k_pack4(qs_base + 16 * k_raw_row_padded, k_raw_row_padded);
+ HVX_Vector t5 = hmx_fa_w8a8_k_pack4(qs_base + 20 * k_raw_row_padded, k_raw_row_padded);
+ HVX_VectorPair w45 = Q6_W_vshuff_VVR(t5, t4, -16);
+ HVX_Vector t6 = hmx_fa_w8a8_k_pack4(qs_base + 24 * k_raw_row_padded, k_raw_row_padded);
+ HVX_Vector t7 = hmx_fa_w8a8_k_pack4(qs_base + 28 * k_raw_row_padded, k_raw_row_padded);
+ HVX_VectorPair w67 = Q6_W_vshuff_VVR(t7, t6, -16);
+
+ const HVX_Vector v_m_b4 = tile_dst[7];
+
+ HVX_VectorPair u1 = Q6_W_vshuff_VVR(Q6_V_lo_W(w67), Q6_V_lo_W(w45), -32);
+ HVX_VectorPair q01 = Q6_W_vshuff_VVR(Q6_V_lo_W(u1), b0, -64);
+ hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q01), Q6_V_hi_W(q01), v_m_b4, tile_dst, 0, &v_sum_w, &v_l1_w);
+ HVX_VectorPair q23 = Q6_W_vshuff_VVR(Q6_V_hi_W(u1), b1, -64);
+ hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q23), Q6_V_hi_W(q23), v_m_b4, tile_dst, 1, &v_sum_w, &v_l1_w);
+
+ HVX_VectorPair u3 = Q6_W_vshuff_VVR(Q6_V_hi_W(w67), Q6_V_hi_W(w45), -32);
+ HVX_VectorPair q45 = Q6_W_vshuff_VVR(Q6_V_lo_W(u3), b4, -64);
+ hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q45), Q6_V_hi_W(q45), v_m_b4, tile_dst, 2, &v_sum_w, &v_l1_w);
+ HVX_VectorPair q67 = Q6_W_vshuff_VVR(Q6_V_hi_W(u3), b5, -64);
+ hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q67), Q6_V_hi_W(q67), v_m_b4, tile_dst, 3, &v_sum_w, &v_l1_w);
+ }
+ }
+
+ // 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);
+}
+
+// Decode one 4-row x 32-col W8A8 S tile (out_hi + out_lo) into 4 FP32 vectors.
+static inline void hmx_fa_w8a8_eval_s_tile_quad(
+ const uint8_t * restrict tile_base,
+ const float * restrict dw_base,
+ size_t c,
+ uint32_t da0,
+ uint32_t da1,
+ uint32_t da2,
+ uint32_t da3,
+ HVX_Vector sign_80,
+ HVX_Vector * v_out0,
+ HVX_Vector * v_out1,
+ HVX_Vector * v_out2,
+ HVX_Vector * v_out3) {
+
+ const size_t c0 = c >> 5;
+ const uint8_t * tp = tile_base + c0 * 2 * HMX_W8A8_ACT_TILE_SIZE;
+ const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80);
+ const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HMX_W8A8_ACT_TILE_SIZE);
+ const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) (dw_base + c));
+ HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1);
+ HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16));
+ HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16));
+
+ *v_out0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)), da0), v_dw_qf));
+ *v_out1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)), da1), v_dw_qf));
+ *v_out2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)), da2), v_dw_qf));
+ *v_out3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)), da3), v_dw_qf));
+}
+
+// Pack 4 rows x 64 FP16 values in [0, 255] (zp = 0) into 1 or 2 U8 SM 64x32 tiles.
+static inline void hmx_fa_w8a8_pack_p_quad_u8_sm(
+ uint8_t * restrict tile_base,
+ uint32_t kt,
+ uint32_t rg,
+ bool write_hi,
+ HVX_Vector hf0,
+ HVX_Vector hf1,
+ HVX_Vector hf2,
+ HVX_Vector hf3) {
+#if __HVX_ARCH__ >= 81
+ HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vub_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0)));
+ HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vub_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1)));
+ HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1);
+
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_V_lo_W(w_u8);
+ if (write_hi) {
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_V_hi_W(w_u8);
+ }
+#else
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_bias_zp0 = Q6_V_vsplat_R(0x4B400000); // 12582912.0f
+ const HVX_Vector v_zero = Q6_V_vzero();
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf0), v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf1), v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf2), v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf3), v_one_f16);
+
+ {
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp0), v_bias_zp0));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp1), v_bias_zp0));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp2), v_bias_zp0));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp3), v_bias_zp0));
+ HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_zero), v_max_u8);
+ HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_zero), v_max_u8);
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
+ }
+ if (write_hi) {
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp0), v_bias_zp0));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp1), v_bias_zp0));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp2), v_bias_zp0));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp3), v_bias_zp0));
+ HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_zero), v_max_u8);
+ HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_zero), v_max_u8);
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
+ }
+#endif
+}
+
+// Zero-gather Q8_0 V -> S8 weight.b 32x32 tiles for one DV tile (32 output cols) across kv_rows.
+static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
+ const uint8_t * restrict v_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t kv_rows,
+ uint32_t n_col_tiles,
+ size_t v_raw_row_padded) {
+
+ uint16_t off_full[64] __attribute__((aligned(128)));
+ for (uint32_t c = 0; c < 32; ++c) {
+ off_full[c] = (uint16_t) (c * v_raw_row_padded);
+ off_full[c + 32] = 0;
+ }
+ const HVX_Vector v_off_full = *(const HVX_Vector *) off_full;
+ const uint32_t mu = (uint32_t) (32 * v_raw_row_padded - 1);
+
+ // Pass 1: gather Q8_0 block scales into tile_dst[kt * 8 + 7] and reduce max across kv_rows
+ HVX_Vector * tile_dst_all = (HVX_Vector *) dst_wt;
+ for (uint32_t kt = 0; kt < n_col_tiles; ++kt) {
+ const uint32_t valid = (uint32_t) hex_smin(32, kv_rows - kt * 32);
+ HVX_Vector v_off = v_off_full;
+ if (valid < 32) {
+ uint16_t off_tail[64] __attribute__((aligned(128)));
+ for (uint32_t c = 0; c < 32; ++c) {
+ off_tail[c] = (c < valid) ? (uint16_t) (c * v_raw_row_padded) : 0;
+ off_tail[c + 32] = 0;
+ }
+ v_off = *(const HVX_Vector *) off_tail;
+ }
+ Q6_vgather_ARMVh(&tile_dst_all[kt * 8 + 7], (size_t) (v_base + (size_t) kt * 32 * v_raw_row_padded), mu, v_off);
+ }
+ hvx_gather_sync(&tile_dst_all[(n_col_tiles - 1) * 8 + 7]);
+
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < n_col_tiles; ++kt) {
+ const uint32_t valid = (uint32_t) hex_smin(32, kv_rows - kt * 32);
+ const HVX_VectorPred q_valid = Q6_Q_vsetq2_R(valid * sizeof(uint16_t));
+ HVX_Vector v_sc = Q6_V_vmux_QVV(q_valid, tile_dst_all[kt * 8 + 7], Q6_V_vzero());
+ tile_dst_all[kt * 8 + 7] = v_sc;
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(v_sc, v_abs_mask));
+ }
+ 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);
+
+ // 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);
+ const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
+ const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1);
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < n_col_tiles; ++kt) {
+ HVX_Vector * tile_dst = tile_dst_all + kt * 8;
+
+ HVX_Vector v_sc_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(tile_dst[7]), v_one_f16));
+ HVX_Vector v_m_biased = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf), v12M_sf));
+ HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased);
+ HVX_Vector v_m_b = Q6_Vb_vpacke_VhVh(v_m_h, v_m_h);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t g = 0; g < 8; ++g) {
+ const uint32_t k0 = kt * 32 + g * 4;
+ const uint8_t * p0 = v_base + (size_t) k0 * v_raw_row_padded + 2;
+ HVX_Vector r0 = (k0 + 0 < kv_rows) ? *(const HVX_UVector *) (p0 + 0 * v_raw_row_padded) : Q6_V_vzero();
+ HVX_Vector r1 = (k0 + 1 < kv_rows) ? *(const HVX_UVector *) (p0 + 1 * v_raw_row_padded) : Q6_V_vzero();
+ HVX_Vector r2 = (k0 + 2 < kv_rows) ? *(const HVX_UVector *) (p0 + 2 * v_raw_row_padded) : Q6_V_vzero();
+ HVX_Vector r3 = (k0 + 3 < kv_rows) ? *(const HVX_UVector *) (p0 + 3 * v_raw_row_padded) : Q6_V_vzero();
+
+ HVX_Vector v02 = Q6_V_lo_W(Q6_W_vshuff_VVR(r2, r0, -1));
+ HVX_Vector v13 = Q6_V_lo_W(Q6_W_vshuff_VVR(r3, r1, -1));
+ HVX_Vector v_q = Q6_V_lo_W(Q6_W_vshuff_VVR(v13, v02, -1));
+
+ HVX_Vector v_m = Q6_V_vsplat_R(Q6_R_vextract_VR(v_m_b, (int) (g * 4)));
+ HVX_VectorPair vp = Q6_Wh_vmpy_VbVb(v_q, v_m);
+#if __HVX_ARCH__ >= 79
+ HVX_Vector v_W = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp), Q6_V_lo_W(vp), 7);
+#else
+ HVX_Vector v_W = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp), 1),
+ Q6_Vh_vasl_VhR(Q6_V_lo_W(vp), 1));
+#endif
+ tile_dst[g] = v_W;
+ v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(v_l1_w, Q6_Vb_vabs_Vb(v_W), v_ones_s8);
+ }
+ }
+
+ // 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);
+}
+
+static inline void hmx_fa_w8a8_gemm_run(
+ const uint8_t * restrict act_tiles,
+ const uint8_t * restrict wt_tiles,
+ const uint8_t * restrict wt_bias,
+ uint8_t * restrict out_tiles,
+ uint32_t n_row_tiles_64,
+ uint32_t n_col_tiles,
+ uint32_t n_dot_tiles) {
+
+ __builtin_assume(n_row_tiles_64 > 0);
+ __builtin_assume(n_col_tiles > 0);
+ __builtin_assume(n_dot_tiles > 0);
+
+ const uint32_t cvt_ctrl_hi = hmx_cvt_ctrl(0, 0, 0, 1);
+#if __HVX_ARCH__ >= 79
+ const uint32_t cvt_ctrl_lo = hmx_cvt_ctrl(1, 0, 1, 0);
+#else
+ const uint32_t cvt_ctrl_lo = hmx_cvt_ctrl(0, 0, 1, 0);
+#endif
+ const uint32_t a_rng = hmx_act_sm_range(n_dot_tiles);
+ const uint32_t w_rng = hmx_wt_b_range(n_dot_tiles * HMX_W8A8_WT_TILE_SIZE);
+ const uint32_t out_cm_rng = hmx_out_cm_range();
+
+ for (uint32_t j = 0; j < n_col_tiles; ++j) {
+ const uint8_t * wt_base = wt_tiles + (size_t) j * n_dot_tiles * HMX_W8A8_WT_TILE_SIZE;
+ const uint8_t * bias_hi = wt_bias + ((size_t) j * 2 + 0) * HMX_W8A8_BIAS_BANK_SIZE;
+ const uint8_t * bias_lo = wt_bias + ((size_t) j * 2 + 1) * HMX_W8A8_BIAS_BANK_SIZE;
+#if __HVX_ARCH__ >= 79
+ hmx_load_bias_bank(bias_hi, 0);
+ hmx_load_bias_bank(bias_lo, 1);
+#endif
+
+ for (uint32_t i = 0; i < n_row_tiles_64; ++i) {
+ const uint8_t * act_base = act_tiles + (size_t) i * n_dot_tiles * HMX_W8A8_ACT_TILE_SIZE;
+ const size_t out_idx = ((size_t) i * n_col_tiles + j) * 2;
+ uint8_t * out_hi = out_tiles + (out_idx + 0) * HMX_W8A8_ACT_TILE_SIZE;
+ uint8_t * out_lo = out_tiles + (out_idx + 1) * HMX_W8A8_ACT_TILE_SIZE;
+
+ asm volatile(HMX_CLRACC_INT());
+ asm volatile(HMX_LOAD_MPY_DEEP_U8_S8_SM("%0", "%1", "%2", "%3")
+ : : "r"(act_base), "r"(a_rng), "r"(wt_base), "r"(w_rng) : "memory");
+
+#if __HVX_ARCH__ < 79
+ hmx_load_bias_bank(bias_hi, 0);
+#endif
+ asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_ctrl_hi) : "memory");
+ asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_hi), "r"(out_cm_rng) : "memory");
+
+#if __HVX_ARCH__ < 79
+ hmx_load_bias_bank(bias_lo, 0);
+#endif
+ asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_ctrl_lo) : "memory");
+ asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_lo), "r"(out_cm_rng) : "memory");
+ }
+ }
+}
+
+typedef struct {
+ const uint8_t * q_tiles;
+ const uint8_t * k_tiles;
+ const uint8_t * k_bias;
+ uint8_t * s_tiles;
+ uint32_t n_row_tiles_64;
+ uint32_t n_col_tiles;
+ uint32_t n_dot_tiles; // DK / 32
+} hmx_fa_w8a8_qk_job_t;
+
+static void hmx_fa_w8a8_qk_dot_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ hmx_fa_w8a8_qk_job_t * job = (hmx_fa_w8a8_qk_job_t *) data;
+ hmx_fa_w8a8_gemm_run(job->q_tiles, job->k_tiles, job->k_bias, job->s_tiles,
+ job->n_row_tiles_64, job->n_col_tiles, job->n_dot_tiles);
+}
+
+typedef struct {
+ const uint8_t * p_tiles;
+ const uint8_t * v_tiles;
+ const uint8_t * v_bias;
+ uint8_t * do_tiles;
+ uint32_t n_row_tiles_64;
+ uint32_t n_v_tiles; // DV / 32
+ uint32_t n_dot_tiles; // ceil(kv_rows / 32)
+} hmx_fa_w8a8_pv_job_t;
+
+static void hmx_fa_w8a8_pv_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ hmx_fa_w8a8_pv_job_t * job = (hmx_fa_w8a8_pv_job_t *) data;
+ hmx_fa_w8a8_gemm_run(job->p_tiles, job->v_tiles, job->v_bias, job->do_tiles,
+ job->n_row_tiles_64, job->n_v_tiles, job->n_dot_tiles);
+}
+
+#endif /* HMX_FA_W8A8_KERNELS_H */
diff --git a/ggml/src/ggml-hexagon/htp/hmx-int-utils.h b/ggml/src/ggml-hexagon/htp/hmx-int-utils.h
new file mode 100644
index 000000000..8011a36d1
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/hmx-int-utils.h
@@ -0,0 +1,209 @@
+#ifndef HMX_INT_UTILS_H
+#define HMX_INT_UTILS_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "hvx-utils.h"
+
+#ifndef HMX_W8A8_ACT_TILE_SIZE
+#define HMX_W8A8_ACT_TILE_SIZE 2048
+#endif
+
+static inline HVX_Vector hvx_vec_f32_to_qf32(HVX_Vector v) {
+#if __HVX_ARCH__ >= 81
+ return Q6_Vqf32_equals_Vsf(v);
+#else
+ return Q6_Vqf32_vadd_VsfVsf(v, Q6_V_vzero());
+#endif
+}
+
+static inline HVX_Vector hvx_qf32_mul_sf_scalar(HVX_Vector v_sf, uint32_t scalar_sf_bits) {
+#if __HVX_ARCH__ >= 79
+ return Q6_Vqf32_vmpy_VsfRsf(v_sf, (int32_t) scalar_sf_bits);
+#else
+ return Q6_Vqf32_vmpy_VsfVsf(v_sf, Q6_V_vsplat_R((int32_t) scalar_sf_bits));
+#endif
+}
+
+static inline void emit_int_hmx_scales_and_bias(
+ HVX_Vector v_max_sf,
+ float scale_const,
+ HVX_Vector v_sum_w,
+ HVX_Vector v_l1_w,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out) {
+
+ // |sum_k (a - zp) * w_hat| < 128 * l1_w = (l1_w << 7) <= 32768 * 2^p
+ HVX_Vector v_max_mag = Q6_Vw_vasl_VwR(v_l1_w, 7);
+ HVX_Vector v_p = Q6_Vw_vmax_VwVw(Q6_V_vzero(), Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(17), Q6_Vuw_vcl0_Vuw(v_max_mag)));
+ HVX_Vector v_ib = Q6_Vw_vsub_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), Q6_Vw_vasl_VwR(v_sum_w, 7));
+
+ HVX_Vector v_dw_base = hvx_vec_mul_f32_f32(v_max_sf, hvx_vec_splat_f32(scale_const));
+ HVX_Vector v_pow2_sf = Q6_Vsf_equals_Vw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p));
+ *(HVX_Vector *) dst_scales = hvx_vec_mul_f32_f32(v_dw_base, v_pow2_sf);
+
+ HVX_Vector v_exp_hi = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(16), v_p);
+ HVX_Vector v_exp_lo = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(24), v_p);
+ bias_out[0] = Q6_Vw_vasl_VwR(v_exp_hi, 10);
+ bias_out[1] = v_ib;
+ bias_out[2] = Q6_Vw_vasl_VwR(v_exp_lo, 10);
+ bias_out[3] = v_ib;
+}
+
+static inline void emit_int_hmx_scales_and_bias_zp0(
+ HVX_Vector v_max_sf,
+ float scale_const,
+ HVX_Vector v_l1_w,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out) {
+
+ // Unsigned a_u8 in [0, 255] (zp = 0): |sum_k a_u8 * w_hat| <= 255 * l1_w < (l1_w << 8) <= 32768 * 2^p
+ HVX_Vector v_max_mag = Q6_Vw_vasl_VwR(v_l1_w, 8);
+ HVX_Vector v_p = Q6_Vw_vmax_VwVw(Q6_V_vzero(), Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(17), Q6_Vuw_vcl0_Vuw(v_max_mag)));
+ HVX_Vector v_ib = Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p);
+
+ HVX_Vector v_dw_base = hvx_vec_mul_f32_f32(v_max_sf, hvx_vec_splat_f32(scale_const));
+ HVX_Vector v_pow2_sf = Q6_Vsf_equals_Vw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p));
+ *(HVX_Vector *) dst_scales = hvx_vec_mul_f32_f32(v_dw_base, v_pow2_sf);
+
+ HVX_Vector v_exp_hi = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(16), v_p);
+ HVX_Vector v_exp_lo = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(24), v_p);
+ bias_out[0] = Q6_Vw_vasl_VwR(v_exp_hi, 10);
+ bias_out[1] = v_ib;
+ bias_out[2] = Q6_Vw_vasl_VwR(v_exp_lo, 10);
+ bias_out[3] = v_ib;
+}
+
+static inline HVX_Vector int_hmx_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 void int_hmx_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);
+}
+
+static inline HVX_Vector int_hmx_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) {
+ const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
+ HVX_Vector v_m_biased = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf), v12M_sf));
+ 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) {
+ 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);
+}
+
+static inline void int_hmx_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);
+}
+
+static inline void int_hmx_store_and_accum_pair(
+ HVX_Vector * restrict tile_dst,
+ int pair_idx,
+ HVX_Vector v_W0,
+ HVX_Vector v_W1,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1);
+ tile_dst[2 * pair_idx + 0] = v_W0;
+ tile_dst[2 * pair_idx + 1] = v_W1;
+
+ *v_sum_w = Q6_Vw_vrmpyacc_VwVbVb(Q6_Vw_vrmpyacc_VwVbVb(*v_sum_w, v_W0, v_ones_s8), v_W1, v_ones_s8);
+ *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(
+ HVX_Vector v_q0,
+ HVX_Vector v_q1,
+ HVX_Vector v_m_b4,
+ HVX_Vector * restrict tile_dst,
+ int pair_idx,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ HVX_Vector v_neg1_h = Q6_Vh_vsplat_R(-1);
+ HVX_VectorPair vp_tie_adj = Q6_W_vcombine_VV(v_neg1_h, v_neg1_h);
+ HVX_VectorPair vp_p01 = Q6_Wh_vmpy_VbVb(v_q0, v_m_b4);
+ HVX_VectorPair vp_p23 = Q6_Wh_vmpyacc_WhVbVb(vp_tie_adj, v_q1, v_m_b4);
+
+#if __HVX_ARCH__ >= 79
+ HVX_Vector v_W0 = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp_p01), Q6_V_lo_W(vp_p01), 7);
+ HVX_Vector v_W1 = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp_p23), Q6_V_lo_W(vp_p23), 7);
+#else
+ HVX_Vector v_W0 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p01), 1),
+ Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p01), 1));
+ 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);
+}
+
+#if __HVX_ARCH__ >= 81
+static inline void pack_hf_quad_to_u8_sm_pair(
+ uint8_t * restrict tile_base,
+ uint32_t kt,
+ uint32_t rg,
+ HVX_Vector hf0,
+ HVX_Vector hf1,
+ HVX_Vector hf2,
+ HVX_Vector hf3) {
+ const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80);
+ const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1);
+
+ HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0)));
+ HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1)));
+ HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1);
+
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] =
+ Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b);
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] =
+ Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_hi_W(w_u8), v_zp_u8), v_min_u8b);
+}
+
+static inline void hmx_pack_hf_quad_to_u8_cm_pair(
+ uint8_t * restrict tile_base,
+ uint32_t kt,
+ uint32_t rg,
+ HVX_Vector hf0,
+ HVX_Vector hf1,
+ HVX_Vector hf2,
+ HVX_Vector hf3) {
+ const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80);
+ const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1);
+
+ HVX_Vector vb01 = Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf1), Q6_Vh_equals_Vhf_rnd(hf0));
+ HVX_Vector vb23 = Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf2));
+ HVX_VectorPair w_u8 = Q6_W_vdeal_VVR(vb23, vb01, -32);
+
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] =
+ Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b);
+ ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] =
+ Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_hi_W(w_u8), v_zp_u8), v_min_u8b);
+}
+#endif
+
+#endif /* HMX_INT_UTILS_H */
diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h
new file mode 100644
index 000000000..05eb3ebfc
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h
@@ -0,0 +1,2035 @@
+#include "hmx-utils.h"
+#include "hmx-queue.h"
+
+// MXFP4 dequantization LUT: maps 4-bit index to fp16 mantissa value
+// kvalues: 0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6
+static const __fp16 mxfp4_to_fp16_lut[64] __attribute__((aligned(VLEN))) = {
+ 0, 0, 0.5, 0, 1, 0, 1.5, 0, 2, 0, 3, 0, 4, 0, 6, 0, 0, 0, -0.5, 0, -1, 0, -1.5, 0, -2, 0, -3, 0, -4, 0, -6, 0,
+};
+
+static const __fp16 iq4_nl_to_fp16_lut[64] __attribute__((aligned(VLEN))) = {
+ -127, 0, -104, 0, -83, 0, -65, 0, -49, 0, -35, 0, -22, 0, -10, 0,
+ 1, 0, 13, 0, 25, 0, 38, 0, 53, 0, 69, 0, 89, 0, 113, 0,
+};
+
+// --- tiled format dequantizers ---
+
+typedef struct tiled_dequantize_state tiled_dequantize_state_t;
+typedef void (*tiled_dequant_task_fn_t)(const tiled_dequantize_state_t * state, uint32_t start_tile, uint32_t end_tile);
+
+struct tiled_dequantize_state {
+ __fp16 * dst;
+ const uint8_t * src;
+ tiled_dequant_task_fn_t task_fn;
+
+ struct fastdiv_values n_k_tiles_div;
+ uint32_t n_k_tiles;
+ uint32_t n_weight_tiles;
+ uint32_t n_tot_tiles;
+ uint32_t n_tiles_per_task;
+ uint32_t tile_size;
+ uint32_t aligned_tile_size;
+ uint32_t n_tasks;
+ uint32_t n_cols;
+ uint32_t k_block;
+ size_t row_stride;
+ uint32_t weight_type;
+};
+
+static void dequantize_tiled_weight_to_fp16_task_q1_0(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q1_0);
+ const HVX_Vector v_neg_one = Q6_Vb_vsplat_R(-1);
+ const HVX_Vector v_pos_one = Q6_Vb_vsplat_R(1);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * (4 * HTP_MM_HMX_TILE_N_ELMS);
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ const HVX_Vector v_sc = hvx_vmem(tile_src + 512);
+ const HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ for (uint32_t q = 0; q < 4; q++) {
+ const HVX_Vector v_plane = hvx_vmem(tile_src + q * 128);
+ __fp16 * quarter_dst = dst_ptr + q * HTP_MM_HMX_TILE_N_ELMS;
+
+ #pragma unroll
+ for (int g = 0; g < 8; g++) {
+ const HVX_Vector v_q = unpack_q1_0_group(v_plane, g, v_neg_one, v_pos_one);
+ const HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
+ const HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+
+ hvx_vmem(quarter_dst + (2 * g + 0) * 64) =
+ Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
+ hvx_vmem(quarter_dst + (2 * g + 1) * 64) =
+ Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
+ }
+ }
+ tile_src += tile_stride;
+ dst_ptr += 4 * HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+static inline void dequantize_q4_0_fp16_tile_step(
+ const uint8_t * restrict tile_src,
+ __fp16 * restrict dst_ptr,
+ HVX_Vector v_scale,
+ HVX_Vector mask_h4,
+ HVX_Vector i8) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = Q6_Vb_vsub_VbVb(Q6_V_vand_VV(vq, mask_h4), i8);
+ HVX_Vector v_hi = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(vq, 4), i8);
+ HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo);
+ HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4);
+ HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi);
+ HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4);
+
+ hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale));
+ }
+}
+
+// Dequantize a single tile from tiled weight data (already in VTCM) to tile-major FP16.
+static void dequantize_tiled_weight_to_fp16_task_q4_0(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_0);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector i8 = Q6_Vb_vsplat_R(8);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_sc = hvx_vmem(tile_src + 512);
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 512);
+ HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2));
+ dequantize_q4_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4, i8);
+ v_scale = v_scale_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_q4_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4, i8);
+}
+
+static inline void dequantize_q4_1_fp16_tile_step(
+ const uint8_t * restrict tile_src,
+ __fp16 * restrict dst_ptr,
+ HVX_Vector v_scale,
+ HVX_Vector v_offset,
+ HVX_Vector mask_h4) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4);
+ HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4);
+ HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo);
+ HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4);
+ HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi);
+ HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4);
+
+ hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale), v_offset));
+ }
+}
+
+static void dequantize_tiled_weight_to_fp16_task_q4_1(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_1);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_dm = hvx_vmem(tile_src + 512);
+ HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(v_dm, v_dm, -2);
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal), Q6_V_lo_W(dm_deal), -2));
+ HVX_Vector v_offset = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal), Q6_V_hi_W(dm_deal), -2));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_dm_next = hvx_vmem(tile_src + tile_stride + 512);
+ HVX_VectorPair dm_deal_next = Q6_W_vdeal_VVR(v_dm_next, v_dm_next, -2);
+ HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal_next), Q6_V_lo_W(dm_deal_next), -2));
+ HVX_Vector v_offset_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal_next), Q6_V_hi_W(dm_deal_next), -2));
+ dequantize_q4_1_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4);
+ v_scale = v_scale_next;
+ v_offset = v_offset_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_q4_1_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4);
+}
+
+static inline void dequantize_4bit_lut_fp16_tile_step(
+ const uint8_t * restrict tile_src,
+ __fp16 * restrict dst_ptr,
+ HVX_Vector v_scale,
+ HVX_Vector vlut_cvt,
+ HVX_Vector mask_h4) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4);
+ HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4);
+ HVX_VectorPair vp_d = Q6_W_vdeal_VVR(v_hi, v_lo, -2);
+ HVX_VectorPair vp_s = Q6_W_vshuff_VVR(Q6_V_hi_W(vp_d), Q6_V_lo_W(vp_d), -1);
+ HVX_VectorPair vp_lo = Q6_Wh_vlut16_VbVhR(Q6_V_lo_W(vp_s), vlut_cvt, 0);
+ HVX_VectorPair vp_hi = Q6_Wh_vlut16_VbVhR(Q6_V_hi_W(vp_s), vlut_cvt, 0);
+
+ hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi), v_scale));
+ }
+}
+
+static void dequantize_tiled_weight_to_fp16_task_iq4_nl(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ4_NL);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector vlut_cvt = hvx_vmem(iq4_nl_to_fp16_lut);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_sc = hvx_vmem(tile_src + 512);
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 512);
+ HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2));
+ dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4);
+ v_scale = v_scale_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4);
+}
+
+static inline HVX_Vector mxfp4_e8m0_to_f16_scale(HVX_Vector v_raw) {
+ HVX_Vector vh = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(v_raw));
+ vh = Q6_Vh_vsub_VhVh(vh, Q6_Vh_vsplat_R(112));
+ vh = Q6_Vh_vmax_VhVh(vh, Q6_V_vzero());
+ vh = Q6_Vh_vmin_VhVh(vh, Q6_Vh_vsplat_R(30));
+ vh = Q6_Vh_vasl_VhR(vh, 10);
+ return Q6_V_lo_W(Q6_W_vshuff_VVR(vh, vh, -2));
+}
+
+static void dequantize_tiled_weight_to_fp16_task_mxfp4(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_MXFP4);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_scale = mxfp4_e8m0_to_f16_scale(hvx_vmem(tile_src + 512));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_scale_next = mxfp4_e8m0_to_f16_scale(hvx_vmem(tile_src + tile_stride + 512));
+ dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4);
+ v_scale = v_scale_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4);
+}
+
+static inline void dequantize_q8_0_fp16_tile_step(
+ const uint8_t * restrict tile_src,
+ __fp16 * restrict dst_ptr,
+ HVX_Vector v_scale) {
+
+ #pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(hvx_vmem(tile_src + i * 128));
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+ hvx_vmem(dst_ptr + (2 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
+ hvx_vmem(dst_ptr + (2 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
+ }
+}
+
+static void dequantize_tiled_weight_to_fp16_task_q8_0(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q8_0);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_sc = hvx_vmem(tile_src + 1024);
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 1024);
+ HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2));
+ dequantize_q8_0_fp16_tile_step(tile_src, dst_ptr, v_scale);
+ v_scale = v_scale_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_q8_0_fp16_tile_step(tile_src, dst_ptr, v_scale);
+}
+
+static inline void dequantize_q5_k_fp16_tile_step(
+ const uint8_t * restrict tile_src,
+ __fp16 * restrict dst_ptr,
+ HVX_Vector v_scale,
+ HVX_Vector v_offset,
+ HVX_Vector mask_h4) {
+
+ HVX_Vector v_plane = hvx_vmem(tile_src + 640);
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = hvx_q5k_or_hibit(Q6_V_vand_VV(vq, mask_h4), v_plane, 2 * i + 0);
+ HVX_Vector v_hi = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(vq, 4), v_plane, 2 * i + 1);
+ HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo);
+ HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4);
+ HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi);
+ HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4);
+
+ hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale), v_offset));
+ }
+}
+
+static void dequantize_tiled_weight_to_fp16_task_q5_k(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_K);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_dm = hvx_vmem(tile_src + 512);
+ HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(v_dm, v_dm, -2);
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal), Q6_V_lo_W(dm_deal), -2));
+ HVX_Vector v_offset = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal), Q6_V_hi_W(dm_deal), -2));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_dm_next = hvx_vmem(tile_src + tile_stride + 512);
+ HVX_VectorPair dm_deal_next = Q6_W_vdeal_VVR(v_dm_next, v_dm_next, -2);
+ HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal_next), Q6_V_lo_W(dm_deal_next), -2));
+ HVX_Vector v_offset_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal_next), Q6_V_hi_W(dm_deal_next), -2));
+ dequantize_q5_k_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4);
+ v_scale = v_scale_next;
+ v_offset = v_offset_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_q5_k_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4);
+}
+
+static inline void dequantize_q5_0_fp16_tile_step(
+ const uint8_t * restrict tile_src,
+ __fp16 * restrict dst_ptr,
+ HVX_Vector v_scale,
+ HVX_Vector mask_h4) {
+
+ HVX_Vector v_plane = hvx_vmem(tile_src + 512);
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = hvx_q5_0_or_neg(Q6_V_vand_VV(vq, mask_h4), v_plane, 2 * i + 0);
+ HVX_Vector v_hi = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(vq, 4), v_plane, 2 * i + 1);
+ HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo);
+ HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4);
+ HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi);
+ HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4);
+
+ hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale));
+ hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale));
+ }
+}
+
+static void dequantize_tiled_weight_to_fp16_task_q5_0(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ if (start_tile >= end_tile) {
+ return;
+ }
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_0);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_sc = hvx_vmem(tile_src + 640);
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t + 1 < end_tile; t++) {
+ HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 640);
+ HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2));
+ dequantize_q5_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4);
+ v_scale = v_scale_next;
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ dequantize_q5_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4);
+}
+
+// Q6_K stores 6-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q6_K.
+// A k-group holds 4 k per row, the HMX tile holds 2, so each group is dealt into two tiles.
+static void dequantize_tiled_weight_to_fp16_task_q6_k(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q6_K);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ const HVX_Vector i32 = Q6_Vb_vsplat_R(32);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ const HVX_Vector * vptr = (const HVX_Vector *) tile_src;
+
+ HVX_Vector v_sc = vptr[6];
+ HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64);
+ HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+ HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2));
+
+ #pragma unroll
+ for (int g = 0; g < 8; g++) {
+ const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16;
+ HVX_Vector v_q = unpack_q6_k_group(vptr, g, mask_0f, mask_03, i32);
+ HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+
+ hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
+ hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
+ }
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+#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
+#define IQ2XXS_D_SCALE_F16 0x3000 // 0.125 as fp16 bits
+
+// 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));
+}
+
+// NVFP4 tiles are MXFP4 quants with one UE4M3 scale per 16 k (sub-block 0: k 0..15, sub-block 1: k 16..31)
+static void dequantize_tiled_weight_to_fp16_task_nvfp4(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_NVFP4);
+ const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ HVX_Vector v_d = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF))));
+ HVX_VectorPair vp_d = Q6_W_vshuff_VVR(v_d, v_d, -2);
+ HVX_Vector v_scale_k0 = Q6_V_lo_W(vp_d);
+ HVX_Vector v_scale_k16 = Q6_V_hi_W(vp_d);
+
+ #pragma unroll
+ for (int g = 0; g < 4; g++) {
+ const HVX_Vector v_scale = (g < 2) ? v_scale_k0 : v_scale_k16;
+
+ HVX_Vector vq = hvx_vmem(tile_src + g * 128);
+ HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4);
+ HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4);
+ HVX_VectorPair vp_d = Q6_W_vdeal_VVR(v_hi, v_lo, -2);
+ HVX_VectorPair vp_s = Q6_W_vshuff_VVR(Q6_V_hi_W(vp_d), Q6_V_lo_W(vp_d), -1);
+ HVX_VectorPair vp_lo = Q6_Wh_vlut16_VbVhR(Q6_V_lo_W(vp_s), vlut_cvt, 0);
+ HVX_VectorPair vp_hi = Q6_Wh_vlut16_VbVhR(Q6_V_hi_W(vp_s), vlut_cvt, 0);
+
+ hvx_vmem(dst_ptr + (4 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo), v_scale));
+ hvx_vmem(dst_ptr + (4 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo), v_scale));
+ hvx_vmem(dst_ptr + (4 * g + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi), v_scale));
+ hvx_vmem(dst_ptr + (4 * g + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi), v_scale));
+ }
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+// IQ2_XXS: int8 grid weights from the VTCM LUT, scaled by d / 8 * (2 * scale + 1) per row
+static void dequantize_tiled_weight_to_fp16_task_iq2_xxs(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
+ HVX_Vector v_d = Q6_V_vzero();
+ const HVX_Vector v_eighth = Q6_Vh_vsplat_R(IQ2XXS_D_SCALE_F16);
+ const uint8_t * restrict tile = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ HVX_Vector v_sgn = Q6_V_vzero();
+ if (start_tile < end_tile) {
+ v_sgn = iq2xxs_gather_issue(tile);
+ }
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block
+ if (t == start_tile || (t & (IQ2XXS_TILES_PER_SB - 1)) == 0) {
+ v_d = iq2xxs_gather_d(tile - (size_t) (t & (IQ2XXS_TILES_PER_SB - 1)) * tile_stride);
+ }
+
+ HVX_Vector v_c[2], v_w[2 * IQ2XXS_GROUPS], v_ls;
+ iq2xxs_gather_wait(tile, v_c);
+ const HVX_Vector v_sgn_cur = v_sgn;
+ if (t + 1 < end_tile) {
+ v_sgn = iq2xxs_gather_issue(tile + tile_stride);
+ }
+ iq2xxs_decode_expand(v_c, v_sgn_cur, v_w, &v_ls);
+
+ HVX_Vector v_ls_h = Q6_Vhf_equals_Vh(Q6_Vh_vpacke_VwVw(v_ls, v_ls));
+ HVX_Vector v_sc = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_d, v_ls_h));
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ #pragma unroll
+ for (int g = 0; g < 2 * IQ2XXS_GROUPS; g++) {
+ HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_w[g]);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+
+ // d / 8 is subnormal in fp16 for real weights, so apply the 1/8 after the multiply by d * ls
+ HVX_Vector v_lo = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
+ HVX_Vector v_hi = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
+ hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_lo, v_eighth));
+ hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_hi, v_eighth));
+ }
+ tile += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+// Q3_K stores 3-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q3_K.
+static void dequantize_tiled_weight_to_fp16_task_q3_k(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q3_K);
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ const HVX_Vector * vptr = (const HVX_Vector *) tile_src;
+
+ HVX_Vector v_sc = vptr[3];
+ HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64);
+ HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+ HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2));
+
+ #pragma unroll
+ for (int g = 0; g < 8; g++) {
+ const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16;
+
+ HVX_Vector v_q = unpack_q3_k_group(vptr, g, mask_03);
+ HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+
+ hvx_vmem(dst_ptr + (2 * g + 0) * 64) =
+ Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
+ hvx_vmem(dst_ptr + (2 * g + 1) * 64) =
+ Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
+ }
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+// Q2_K stores 2-bit weights, the ggml scale bytes and d / -dmin per super-block, see HTP_TENSOR_TILE_SIZE_Q2_K.
+static void dequantize_tiled_weight_to_fp16_task_q2_k(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_K);
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ HVX_Vector v_d = Q6_V_vzero();
+ HVX_Vector v_dm = Q6_V_vzero();
+ const uint8_t * restrict tile = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ const HVX_Vector * vptr = (const HVX_Vector *) tile;
+
+ // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block
+ if (t == start_tile || (t & 7) == 0) {
+ q2_k_load_dmin(tile - (size_t) (t & 7) * tile_stride, &v_d, &v_dm);
+ }
+
+ HVX_Vector v_sc, v_m;
+ q2_k_unpack_scales(tile, v_d, v_dm, &v_sc, &v_m);
+ HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64);
+ HVX_Vector v_m_k16 = Q6_V_vror_VR(v_m, 64);
+ HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+ HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2));
+ HVX_Vector v_offset_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m, v_m, -2));
+ HVX_Vector v_offset_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m_k16, v_m_k16, -2));
+
+ #pragma unroll
+ for (int g = 0; g < 8; g++) {
+ const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16;
+ const HVX_Vector v_offset = (g < 4) ? v_offset_k0 : v_offset_k16;
+
+ HVX_Vector v_q = unpack_q3_k_low2(vptr, g, mask_03);
+ HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+
+ hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(
+ Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale), v_offset));
+ hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(
+ Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale), v_offset));
+ }
+ tile += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+// Q2_0 stores codes 0..3 (value code - 1) and one fp16 scale per row, see HTP_MM_WEIGHT_TILE_SIZE_Q2_0.
+// One packed 64-k tile expands into two consecutive 32-k fp16 tiles.
+static void dequantize_tiled_weight_to_fp16_task_q2_0(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_0);
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ const HVX_Vector i1 = Q6_Vb_vsplat_R(1);
+ const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride;
+ __fp16 * restrict dst_base = state->dst + (size_t) start_tile * (2 * HTP_MM_HMX_TILE_N_ELMS);
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ const HVX_Vector * vptr = (const HVX_Vector *) tile_src;
+
+ HVX_Vector v_sc = vptr[4];
+ HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
+
+ for (int half = 0; half < 2; half++) {
+ __fp16 * dst_ptr = dst_base + half * HTP_MM_HMX_TILE_N_ELMS;
+
+ #pragma unroll
+ for (int g = 0; g < 8; g++) {
+ HVX_Vector v_q = Q6_Vb_vsub_VbVb(unpack_q3_k_low2(vptr + 2 * half, g, mask_03), i1);
+ HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
+
+ hvx_vmem(dst_ptr + (2 * g + 0) * 64) =
+ Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
+ hvx_vmem(dst_ptr + (2 * g + 1) * 64) =
+ Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
+ }
+ }
+ tile_src += tile_stride;
+ dst_base += 2 * HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+static __attribute__((noinline))
+void convert_f16_weight_to_fp16_tiles_task(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const uint32_t n_k_tiles = state->n_k_tiles;
+ const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div;
+
+ const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
+ const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
+ const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
+
+ unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div);
+ unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div);
+
+ for (unsigned t = start_tile; t < (unsigned)end_tile; ) {
+ if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; }
+
+ __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
+ {
+ uint32_t byte_off = kt * 32 * sizeof(__fp16);
+
+ HVX_Vector v_off = v_scat_base;
+ for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) {
+ uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r;
+ uint32_t row1 = row0 + 1;
+
+ const uint8_t *r0 = state->src + row0 * state->row_stride;
+ const uint8_t *r1 = state->src + row1 * state->row_stride;
+
+ HVX_Vector v0 = (row0 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r0 + byte_off)) : Q6_V_vzero();
+ HVX_Vector v1 = (row1 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r1 + byte_off)) : Q6_V_vzero();
+
+ Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v0);
+ v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
+ Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v1);
+ v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
+ }
+ }
+ ++t; ++kt;
+ }
+ hvx_gather_sync(state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS);
+}
+
+static __attribute__((noinline))
+void quantize_f32_weight_to_fp16_tiles_task(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const uint32_t n_k_tiles = state->n_k_tiles;
+ const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div;
+
+ const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
+ const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
+ const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
+
+ unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div);
+ unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div);
+
+ for (unsigned t = start_tile; t < (unsigned)end_tile; ) {
+ if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; }
+
+ __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
+ {
+ uint32_t byte_off = kt * 32 * sizeof(float);
+
+ HVX_Vector v_off = v_scat_base;
+ for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) {
+ uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r;
+ uint32_t row1 = row0 + 1;
+
+ const uint8_t *r0 = state->src + row0 * state->row_stride;
+ const uint8_t *r1 = state->src + row1 * state->row_stride;
+
+ HVX_Vector v0_f32 = (row0 < state->n_cols) ? hvx_vmem((const float *)(r0 + byte_off)) : Q6_V_vzero();
+ HVX_Vector v1_f32 = (row1 < state->n_cols) ? hvx_vmem((const float *)(r1 + byte_off)) : Q6_V_vzero();
+
+ HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32);
+
+ Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out);
+ v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
+
+ HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64);
+ Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi);
+ v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
+ }
+ }
+ ++t; ++kt;
+ }
+ hvx_gather_sync(state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS);
+}
+
+static __attribute__((noinline))
+void convert_bf16_weight_to_fp16_tiles_task(
+ const tiled_dequantize_state_t *state,
+ uint32_t start_tile, uint32_t end_tile) {
+
+ const uint32_t n_k_tiles = state->n_k_tiles;
+ const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div;
+
+ const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
+ const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
+ const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
+
+ unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div);
+ unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div);
+
+ for (unsigned t = start_tile; t < (unsigned)end_tile; ) {
+ if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; }
+
+ __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
+ {
+ uint32_t byte_off = kt * 32 * sizeof(uint16_t);
+
+ HVX_Vector v_off = v_scat_base;
+ for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) {
+ uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r;
+ uint32_t row1 = row0 + 1;
+
+ const uint8_t *r0 = state->src + row0 * state->row_stride;
+ const uint8_t *r1 = state->src + row1 * state->row_stride;
+
+ HVX_Vector v0_raw = (row0 < state->n_cols) ? hvx_vmemu((const void *)(r0 + byte_off)) : Q6_V_vzero();
+ HVX_Vector v1_raw = (row1 < state->n_cols) ? hvx_vmemu((const void *)(r1 + byte_off)) : Q6_V_vzero();
+
+ HVX_Vector v0_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v0_raw)), 16);
+ HVX_Vector v1_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v1_raw)), 16);
+
+ HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32);
+
+ Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out);
+ v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
+
+ HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64);
+ Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi);
+ v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
+ }
+ }
+ ++t; ++kt;
+ }
+ hvx_gather_sync(state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS);
+}
+
+// --- End tiled dequantizers ---
+
+// dot-chunk functions require external HMX lock
+
+static void core_dot_chunk_fp16_short(__fp16 *restrict output, const __fp16 *restrict activation,
+ const __fp16 *restrict weight, const __fp16 *restrict scales,
+ uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) {
+ __builtin_assume(n_row_tiles > 0);
+ __builtin_assume(n_col_tiles > 0);
+ __builtin_assume(n_dot_tiles > 0);
+ __builtin_assume(n_dot_tiles <= 32);
+
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales));
+
+ const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS;
+ const uint32_t range = 2048u * n_dot_tiles - 1;
+
+ for (uint32_t r = 0; r < n_row_tiles; ++r) {
+ const __fp16 *row_base = activation + r * dot_stride;
+ const __fp16 *col_base = weight;
+ __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (size_t c = 0; c < n_col_tiles; ++c) {
+ asm volatile(HMX_CLRACC_F16());
+ asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_base), "r"(col_base));
+ asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory");
+ col_base += dot_stride;
+ out_tile += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ }
+}
+
+static void core_dot_chunk_fp16(__fp16 *restrict output, const __fp16 *restrict activation,
+ const __fp16 *restrict weight, const __fp16 *restrict scales,
+ uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) {
+ if (n_dot_tiles <= 32) {
+ core_dot_chunk_fp16_short(output, activation, weight, scales, n_row_tiles, n_col_tiles, n_dot_tiles);
+ return;
+ }
+ __builtin_assume(n_row_tiles > 0);
+ __builtin_assume(n_col_tiles > 0);
+ __builtin_assume(n_dot_tiles > 32);
+
+ asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales));
+
+ const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (uint32_t r = 0; r < n_row_tiles; ++r) {
+ const __fp16 *row_base = activation + r * dot_stride;
+ const __fp16 *col_base = weight;
+ __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS;
+
+ for (size_t c = 0; c < n_col_tiles; ++c) {
+ const __fp16 *row_tiles = row_base;
+ const __fp16 *col_tiles = col_base;
+
+ asm volatile(HMX_CLRACC_F16());
+
+ const uint32_t n_loops = n_dot_tiles / 32;
+ const uint32_t rem = n_dot_tiles % 32;
+
+ for (uint32_t l = 0; l < n_loops; ++l) {
+ asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(65535), "r"(row_tiles), "r"(col_tiles));
+ row_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS;
+ col_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS;
+ }
+
+ if (rem > 0) {
+ const uint32_t range = 2048u * rem - 1;
+ asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_tiles), "r"(col_tiles));
+ }
+
+ asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory");
+
+ col_base += dot_stride;
+ out_tile += HTP_MM_HMX_TILE_N_ELMS;
+ }
+ }
+}
+
+// output : fp16 -> f32 / f16
+
+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));
+}
+
+static inline HVX_Vector hmx_pack_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);
+}
+
+static inline HVX_Vector hmx_add_bias_to_f16_vec64_f16(HVX_Vector v_f16, const void * bias_row_base, size_t c) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_VectorPair vp_bias = hmx_load_bias_f32_64_f16(bias_row_base, c);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), Q6_V_lo_W(vp_bias));
+ HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), Q6_V_hi_W(vp_bias));
+ return hmx_pack_f32_to_f16_clamped(v0, v1);
+}
+
+static inline HVX_Vector hmx_add_bias_to_f16_vec64_f32(HVX_Vector v_f16, const void * bias_row_base, size_t c) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_VectorPair vp_bias = hmx_load_bias_f32_64_f32(bias_row_base, c);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), Q6_V_lo_W(vp_bias));
+ HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), Q6_V_hi_W(vp_bias));
+ return hmx_pack_f32_to_f16_clamped(v0, v1);
+}
+
+static inline HVX_Vector hmx_add_bias_to_f16_tail_f16(HVX_Vector v_f16, const void * bias_row_base, size_t c, size_t valid_c) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_VectorPair vp_bias = hmx_load_bias_f32_64_f16(bias_row_base, c);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), Q6_V_lo_W(vp_bias));
+ HVX_Vector v1 = (valid_c > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), Q6_V_hi_W(vp_bias)) : Q6_V_vzero();
+ return hmx_pack_f32_to_f16_clamped(v0, v1);
+}
+
+static inline HVX_Vector hmx_add_bias_to_f16_tail_f32(HVX_Vector v_f16, const void * bias_row_base, size_t c, size_t valid_c) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), hmx_load_bias_f32_32_f32(bias_row_base, c));
+ HVX_Vector v1 = (valid_c > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), hmx_load_bias_f32_32_f32(bias_row_base, c + 32)) : Q6_V_vzero();
+ return hmx_pack_f32_to_f16_clamped(v0, v1);
+}
+
+#define HMX_FP16_ADD_BIAS_F32_NONE(v_out, row_ptr, c) (v_out)
+#define HMX_FP16_ADD_BIAS_F32_F16(v_out, row_ptr, c) hvx_vec_add_f32_f32((v_out), hmx_load_bias_f32_32_f16((row_ptr), (c)))
+#define HMX_FP16_ADD_BIAS_F32_F32(v_out, row_ptr, c) hvx_vec_add_f32_f32((v_out), hmx_load_bias_f32_32_f32((row_ptr), (c)))
+
+#define HMX_FP16_ADD_BIAS_F16_64_NONE(v_out, row_ptr, c) (v_out)
+#define HMX_FP16_ADD_BIAS_F16_64_F16(v_out, row_ptr, c) hmx_add_bias_to_f16_vec64_f16((v_out), (row_ptr), (c))
+#define HMX_FP16_ADD_BIAS_F16_64_F32(v_out, row_ptr, c) hmx_add_bias_to_f16_vec64_f32((v_out), (row_ptr), (c))
+
+#define HMX_FP16_ADD_BIAS_F16_TAIL_NONE(v_out, row_ptr, c, vc) (v_out)
+#define HMX_FP16_ADD_BIAS_F16_TAIL_F16(v_out, row_ptr, c, vc) hmx_add_bias_to_f16_tail_f16((v_out), (row_ptr), (c), (vc))
+#define HMX_FP16_ADD_BIAS_F16_TAIL_F32(v_out, row_ptr, c, vc) hmx_add_bias_to_f16_tail_f32((v_out), (row_ptr), (c), (vc))
+
+#define HMX_FP16_BIAS_ROW0_none(bias, off) NULL
+#define HMX_FP16_BIAS_ROW0_f16(bias, off) ((const uint8_t *) (bias) + (off))
+#define HMX_FP16_BIAS_ROW0_f32(bias, off) ((const uint8_t *) (bias) + (off))
+
+#define HMX_FP16_BIAS_ROW1_none(row0, rb) NULL
+#define HMX_FP16_BIAS_ROW1_f16(row0, rb) ((row0) + (rb))
+#define HMX_FP16_BIAS_ROW1_f32(row0, rb) ((row0) + (rb))
+
+#define HMX_FP16_BIAS_STEP_none(ptr, step) (void) 0
+#define HMX_FP16_BIAS_STEP_f16(ptr, step) ((ptr) += (step))
+#define HMX_FP16_BIAS_STEP_f32(ptr, step) ((ptr) += (step))
+
+#define HMX_STORE_VEC_nt(PTR, VEC) hvx_vmem_store_nt((PTR), (VEC))
+#define HMX_STORE_VEC_u(PTR, VEC) (hvx_vmemu((PTR)) = (VEC))
+
+#define HMX_FP16_TO_FP32_PAIR_STEP(STORE_MODE, ADD_BIAS) \
+ do { \
+ _Pragma("unroll(4)") \
+ for (size_t c = 0; c < limit_c_aligned; c += HTP_MM_HMX_TILE_N_COLS) { \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \
+ HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \
+ HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \
+ HVX_Vector v_out1 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)), bias_row1, c); \
+ HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \
+ HMX_STORE_VEC_##STORE_MODE(output_row_base + c + dst_stride, v_out1); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ size_t c = limit_c_aligned; \
+ size_t valid_c = limit_c - c; \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \
+ HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \
+ HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \
+ HVX_Vector v_out1 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)), bias_row1, c); \
+ hvx_vec_store_u(output_row_base + c, valid_c * sizeof(float), v_out0); \
+ hvx_vec_store_u(output_row_base + c + dst_stride, valid_c * sizeof(float), v_out1); \
+ } \
+ } while (0)
+
+#define HMX_FP16_TO_FP32_SINGLE_STEP(STORE_MODE, ADD_BIAS) \
+ do { \
+ _Pragma("unroll(4)") \
+ for (size_t c = 0; c < limit_c_aligned; c += HTP_MM_HMX_TILE_N_COLS) { \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \
+ HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \
+ HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \
+ HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ size_t c = limit_c_aligned; \
+ size_t valid_c = limit_c - c; \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \
+ HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \
+ HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \
+ hvx_vec_store_u(output_row_base + c, valid_c * sizeof(float), v_out0); \
+ } \
+ } while (0)
+
+#define DEFINE_FP16_TO_FP32_COL_CHUNK_MODE(SFX, ADD_BIAS, STORE_MODE) \
+static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp32_col_chunk_##SFX##_##STORE_MODE( \
+ void * restrict dst_ptr, \
+ const void * restrict bias, \
+ const __fp16 * restrict vtcm_src, \
+ uint32_t start_row, \
+ uint32_t n_rows, \
+ uint32_t c_len, \
+ uint32_t total_n_cols, \
+ uint32_t dst_stride, \
+ uint32_t bias_stride, \
+ uint32_t dst_cols, \
+ size_t bias_elem_size \
+) { \
+ float * restrict dst = (float *) dst_ptr; \
+ const size_t tile_row_stride = hmx_ceil_div(total_n_cols, \
+ HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; \
+ const HVX_Vector one = hvx_vec_splat_f16(1.0); \
+ const size_t limit_c = hex_smin(c_len, dst_cols); \
+ const size_t limit_c_aligned = (limit_c & ~31u); \
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \
+ const size_t dst_pair_stride = 2 * (size_t) dst_stride; \
+ const size_t __attribute__((unused)) bias_pair_bytes = 2 * bias_row_bytes; \
+ float * output_row_base = dst; \
+ const uint8_t * __attribute__((unused)) bias_row0 = HMX_FP16_BIAS_ROW0_##SFX(bias, 0); \
+ const uint8_t * __attribute__((unused)) bias_row1 = HMX_FP16_BIAS_ROW1_##SFX(bias_row0, \
+ bias_row_bytes); \
+ size_t r_idx0 = start_row; \
+ const __fp16 * row_base = vtcm_src + (r_idx0 >> 5) * tile_row_stride; \
+ size_t r1 = (r_idx0 & 31u) >> 1; \
+ size_t r = 0; \
+ for (; r + 1 < n_rows; r += 2) { \
+ HMX_FP16_TO_FP32_PAIR_STEP(STORE_MODE, ADD_BIAS); \
+ output_row_base += dst_pair_stride; \
+ HMX_FP16_BIAS_STEP_##SFX(bias_row0, bias_pair_bytes); \
+ HMX_FP16_BIAS_STEP_##SFX(bias_row1, bias_pair_bytes); \
+ if (++r1 == 16) { \
+ r1 = 0; \
+ row_base += tile_row_stride; \
+ } \
+ } \
+ if (r < n_rows) { \
+ HMX_FP16_TO_FP32_SINGLE_STEP(STORE_MODE, ADD_BIAS); \
+ } \
+}
+
+#define DEFINE_FP16_TO_FP32_COL_CHUNK(SFX, ADD_BIAS) \
+ DEFINE_FP16_TO_FP32_COL_CHUNK_MODE(SFX, ADD_BIAS, nt) \
+ DEFINE_FP16_TO_FP32_COL_CHUNK_MODE(SFX, ADD_BIAS, u)
+
+DEFINE_FP16_TO_FP32_COL_CHUNK(none, HMX_FP16_ADD_BIAS_F32_NONE)
+DEFINE_FP16_TO_FP32_COL_CHUNK(f16, HMX_FP16_ADD_BIAS_F32_F16)
+DEFINE_FP16_TO_FP32_COL_CHUNK(f32, HMX_FP16_ADD_BIAS_F32_F32)
+
+#define HMX_FP16_TO_FP16_PAIR_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL) \
+ do { \
+ for (size_t c = 0; c < limit_c_aligned64; c += 64) { \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \
+ const __fp16 *tile1 = row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \
+ HVX_Vector v_t1 = ((const HVX_Vector *) tile1)[r1]; \
+ HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \
+ HVX_Vector v_out0 = ADD_BIAS_64(Q6_V_lo_W(vp), bias_row0, c); \
+ HVX_Vector v_out1 = ADD_BIAS_64(Q6_V_hi_W(vp), bias_row1, c); \
+ HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \
+ HMX_STORE_VEC_##STORE_MODE(output_row_base + dst_stride + c, v_out1); \
+ } \
+ if (limit_c_aligned64 < limit_c) { \
+ const size_t c = limit_c_aligned64; \
+ const size_t valid_c = limit_c - c; \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \
+ HVX_Vector v_t1 = (valid_c > 32) \
+ ? ((const HVX_Vector *) (row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS))[r1] \
+ : Q6_V_vzero(); \
+ HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \
+ HVX_Vector v_out0 = ADD_BIAS_TAIL(Q6_V_lo_W(vp), bias_row0, c, valid_c); \
+ HVX_Vector v_out1 = ADD_BIAS_TAIL(Q6_V_hi_W(vp), bias_row1, c, valid_c); \
+ hvx_vec_store_u(output_row_base + c, valid_c * sizeof(__fp16), v_out0); \
+ hvx_vec_store_u(output_row_base + dst_stride + c, valid_c * sizeof(__fp16), v_out1); \
+ } \
+ } while (0)
+
+#define HMX_FP16_TO_FP16_SINGLE_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL) \
+ do { \
+ for (size_t c = 0; c < limit_c_aligned64; c += 64) { \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \
+ const __fp16 *tile1 = row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \
+ HVX_Vector v_t1 = ((const HVX_Vector *) tile1)[r1]; \
+ HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \
+ HVX_Vector v_out0 = ADD_BIAS_64(Q6_V_lo_W(vp), bias_row0, c); \
+ HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \
+ } \
+ if (limit_c_aligned64 < limit_c) { \
+ const size_t c = limit_c_aligned64; \
+ const size_t valid_c = limit_c - c; \
+ const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \
+ const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \
+ HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \
+ HVX_Vector v_t1 = (valid_c > 32) \
+ ? ((const HVX_Vector *) (row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS))[r1] \
+ : Q6_V_vzero(); \
+ HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \
+ HVX_Vector v_out0 = ADD_BIAS_TAIL(Q6_V_lo_W(vp), bias_row0, c, valid_c); \
+ hvx_vec_store_u(output_row_base + c, valid_c * sizeof(__fp16), v_out0); \
+ } \
+ } while (0)
+
+#define DEFINE_FP16_TO_FP16_COL_CHUNK_MODE(SFX, ADD_BIAS_64, ADD_BIAS_TAIL, STORE_MODE) \
+static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp16_col_chunk_##SFX##_##STORE_MODE( \
+ void * restrict dst_ptr, \
+ const void * restrict bias, \
+ const __fp16 * restrict vtcm_src, \
+ uint32_t start_row, \
+ uint32_t n_rows, \
+ uint32_t c_len, \
+ uint32_t total_n_cols, \
+ uint32_t dst_stride, \
+ uint32_t bias_stride, \
+ uint32_t dst_cols, \
+ size_t bias_elem_size \
+) { \
+ __fp16 * restrict dst = (__fp16 *) dst_ptr; \
+ const size_t tile_row_stride = hmx_ceil_div(total_n_cols, \
+ HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; \
+ const size_t limit_c = hex_smin(c_len, dst_cols); \
+ const size_t limit_c_aligned64 = (limit_c & ~63u); \
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \
+ const size_t dst_pair_stride = 2 * (size_t) dst_stride; \
+ const size_t __attribute__((unused)) bias_pair_bytes = 2 * bias_row_bytes; \
+ __fp16 * output_row_base = dst; \
+ const uint8_t * __attribute__((unused)) bias_row0 = HMX_FP16_BIAS_ROW0_##SFX(bias, 0); \
+ const uint8_t * __attribute__((unused)) bias_row1 = HMX_FP16_BIAS_ROW1_##SFX(bias_row0, \
+ bias_row_bytes); \
+ size_t r_idx0 = start_row; \
+ const __fp16 * row_base = vtcm_src + (r_idx0 >> 5) * tile_row_stride; \
+ size_t r1 = (r_idx0 & 31u) >> 1; \
+ size_t r = 0; \
+ for (; r + 1 < n_rows; r += 2) { \
+ HMX_FP16_TO_FP16_PAIR_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL); \
+ output_row_base += dst_pair_stride; \
+ HMX_FP16_BIAS_STEP_##SFX(bias_row0, bias_pair_bytes); \
+ HMX_FP16_BIAS_STEP_##SFX(bias_row1, bias_pair_bytes); \
+ if (++r1 == 16) { \
+ r1 = 0; \
+ row_base += tile_row_stride; \
+ } \
+ } \
+ if (r < n_rows) { \
+ HMX_FP16_TO_FP16_SINGLE_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL); \
+ } \
+}
+
+#define DEFINE_FP16_TO_FP16_COL_CHUNK(SFX, ADD_BIAS_64, ADD_BIAS_TAIL) \
+ DEFINE_FP16_TO_FP16_COL_CHUNK_MODE(SFX, ADD_BIAS_64, ADD_BIAS_TAIL, nt) \
+ DEFINE_FP16_TO_FP16_COL_CHUNK_MODE(SFX, ADD_BIAS_64, ADD_BIAS_TAIL, u)
+
+DEFINE_FP16_TO_FP16_COL_CHUNK(none, HMX_FP16_ADD_BIAS_F16_64_NONE, HMX_FP16_ADD_BIAS_F16_TAIL_NONE)
+DEFINE_FP16_TO_FP16_COL_CHUNK(f16, HMX_FP16_ADD_BIAS_F16_64_F16, HMX_FP16_ADD_BIAS_F16_TAIL_F16)
+DEFINE_FP16_TO_FP16_COL_CHUNK(f32, HMX_FP16_ADD_BIAS_F16_64_F32, HMX_FP16_ADD_BIAS_F16_TAIL_F32)
+
+typedef void (*hmx_fp16_output_col_chunk_fn_t)(
+ void * restrict dst,
+ const void * restrict bias,
+ const __fp16 * restrict vtcm_src,
+ uint32_t start_row,
+ uint32_t n_rows,
+ uint32_t c_len,
+ uint32_t total_n_cols,
+ uint32_t dst_stride,
+ uint32_t bias_stride,
+ uint32_t dst_cols,
+ size_t bias_elem_size
+);
+
+static inline hmx_fp16_output_col_chunk_fn_t resolve_fp16_output_col_chunk_fn(
+ size_t dst_elem_size,
+ const void * bias,
+ size_t bias_elem_size,
+ bool dst_aligned_nt
+) {
+ const bool dst_f16 = (dst_elem_size == sizeof(__fp16));
+ const bool bias_f16 = (bias_elem_size == sizeof(__fp16));
+ if (dst_f16) {
+ if (dst_aligned_nt) {
+ return !bias ? transfer_output_chunk_fp16_to_fp16_col_chunk_none_nt
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp16_col_chunk_f16_nt
+ : transfer_output_chunk_fp16_to_fp16_col_chunk_f32_nt);
+ }
+ return !bias ? transfer_output_chunk_fp16_to_fp16_col_chunk_none_u
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp16_col_chunk_f16_u
+ : transfer_output_chunk_fp16_to_fp16_col_chunk_f32_u);
+ }
+ if (dst_aligned_nt) {
+ return !bias ? transfer_output_chunk_fp16_to_fp32_col_chunk_none_nt
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp32_col_chunk_f16_nt
+ : transfer_output_chunk_fp16_to_fp32_col_chunk_f32_nt);
+ }
+ return !bias ? transfer_output_chunk_fp16_to_fp32_col_chunk_none_u
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp32_col_chunk_f16_u
+ : transfer_output_chunk_fp16_to_fp32_col_chunk_f32_u);
+}
+
+typedef struct {
+ hmx_fp16_output_col_chunk_fn_t col_chunk_fn;
+ const __fp16 *vtcm_src;
+ void *dst;
+ const void *bias;
+ size_t dst_elem_size;
+ size_t bias_elem_size;
+ uint32_t n_tasks;
+ uint32_t n_tot_chunks;
+ uint32_t n_chunks_per_task;
+ uint32_t n_cols;
+ uint32_t dst_stride; // DDR row stride
+ uint32_t bias_stride; // DDR row stride for residual
+ uint32_t dst_cols; // Actual output columns
+} output_transfer_task_state_t;
+
+// activations : fp32 -> fp16
+
+static void transfer_activation_row_pair_fp32_to_fp16(
+ __fp16 *restrict vtcm_dst,
+ const float *restrict row0,
+ const float *restrict row1,
+ uint32_t r,
+ uint32_t k_block,
+ uint32_t k_valid,
+ bool row0_valid,
+ bool row1_valid) {
+
+ uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index
+ uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
+
+ uint32_t c = 0;
+ for (; c + 32 <= k_valid; c += 32) {
+ HVX_Vector v0 = Q6_V_vzero();
+ HVX_Vector v1 = Q6_V_vzero();
+ if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
+ if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
+
+ HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
+
+ uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index
+ uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
+
+ HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
+ tile[r1 / 2] = v_out;
+ }
+ for (; c < k_block; c += 32) {
+ HVX_Vector v0 = Q6_V_vzero();
+ HVX_Vector v1 = Q6_V_vzero();
+ if (c < k_valid) {
+ if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
+ if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
+
+ uint32_t rem = k_valid - c;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(float));
+ v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
+ v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
+ }
+
+ HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
+
+ uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index
+ uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
+
+ HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
+ tile[r1 / 2] = v_out;
+ }
+}
+
+// F16-input variant of transfer_activation_row_pair_fp32_to_fp16, for F16 activation
+// (src1). Same shape as the F16 Q-prep in hmx-fa-kernels.h: one 128-byte load carries 64 f16
+// = two tile columns, and Q6_W_vshuff_VVR interleaves the two rows straight into the HMX tile
+// layout, so no F32 round-trip is needed. Rows are only 64-byte aligned when k_block is an odd
+// multiple of the tile width, hence the unaligned load type.
+static void transfer_activation_row_pair_f16_to_f16(__fp16 * restrict vtcm_dst,
+ const __fp16 * restrict row0,
+ const __fp16 * restrict row1,
+ uint32_t r,
+ uint32_t k_block,
+ uint32_t k_valid,
+ bool row0_valid,
+ bool row1_valid) {
+ uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index
+ uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
+
+ const uint32_t n_tile_cols = k_block / HTP_MM_HMX_TILE_N_COLS;
+ __fp16 * restrict tile_row = vtcm_dst + (size_t) r0 * n_tile_cols * HTP_MM_HMX_TILE_N_ELMS;
+
+ const HVX_UVector * pv0 = row0_valid ? (const HVX_UVector *) row0 : NULL;
+ const HVX_UVector * pv1 = row1_valid ? (const HVX_UVector *) row1 : NULL;
+
+ uint32_t c = 0;
+ for (; c + 64 <= k_valid; c += 64) {
+ HVX_Vector v0 = pv0 ? pv0[c / 64] : Q6_V_vzero();
+ HVX_Vector v1 = pv1 ? pv1[c / 64] : Q6_V_vzero();
+ HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
+
+ uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
+
+ HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS);
+ HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS);
+
+ tile0[r1 / 2] = Q6_V_lo_W(vp);
+ tile1[r1 / 2] = Q6_V_hi_W(vp);
+ }
+ // Tail: fewer than 64 valid columns left, plus the k_valid..k_block padding that HMX will
+ // still multiply, so it has to be written as zeros.
+ for (; c < k_block; c += 64) {
+ HVX_Vector v0 = Q6_V_vzero();
+ HVX_Vector v1 = Q6_V_vzero();
+
+ if (c < k_valid) {
+ uint32_t rem = k_valid - c; // 1..63 valid f16 lanes
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(__fp16));
+ if (pv0) {
+ v0 = Q6_V_vmux_QVV(mask, pv0[c / 64], Q6_V_vzero());
+ }
+ if (pv1) {
+ v1 = Q6_V_vmux_QVV(mask, pv1[c / 64], Q6_V_vzero());
+ }
+ }
+
+ HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
+
+ uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
+
+ HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS);
+ tile0[r1 / 2] = Q6_V_lo_W(vp);
+
+ if (c0 + 1 < n_tile_cols) {
+ HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS);
+ tile1[r1 / 2] = Q6_V_hi_W(vp);
+ }
+ }
+}
+
+static void transfer_activation_row_pair_fp32_to_fp16_col_chunk(
+ __fp16 *restrict vtcm_dst,
+ const float *restrict row0, // offset by c_first
+ const float *restrict row1, // offset by c_first
+ uint32_t r,
+ uint32_t k_block,
+ uint32_t c_first,
+ uint32_t c_len,
+ uint32_t k_chunk_valid,
+ bool row0_valid,
+ bool row1_valid) {
+
+ uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index
+ uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
+
+ uint32_t c = 0;
+ for (; c + 32 <= k_chunk_valid; c += 32) {
+ HVX_Vector v0 = Q6_V_vzero();
+ HVX_Vector v1 = Q6_V_vzero();
+ if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
+ if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
+
+ HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
+
+ uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index
+ uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
+
+ HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
+ tile[r1 / 2] = v_out;
+ }
+ if (c < c_len) {
+ HVX_Vector v0 = Q6_V_vzero();
+ HVX_Vector v1 = Q6_V_vzero();
+ if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
+ if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
+
+ uint32_t rem = (k_chunk_valid > c) ? (k_chunk_valid - c) : 0;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
+ v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
+ v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
+
+ HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
+
+ uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index
+ uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
+
+ HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
+ tile[r1 / 2] = v_out;
+ }
+}
+
+static void transfer_activation_row_pair_f16_to_f16_col_chunk(
+ __fp16 *restrict vtcm_dst,
+ const __fp16 *restrict row0,
+ const __fp16 *restrict row1,
+ uint32_t r,
+ uint32_t k_block,
+ uint32_t c_first,
+ uint32_t c_len,
+ uint32_t k_chunk_valid,
+ bool row0_valid,
+ bool row1_valid) {
+
+ const uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS;
+ const uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS;
+ const uint32_t n_tile_cols = k_block / HTP_MM_HMX_TILE_N_COLS;
+ __fp16 * restrict tile_row = vtcm_dst + (size_t) r0 * n_tile_cols * HTP_MM_HMX_TILE_N_ELMS;
+
+ const HVX_UVector * pv0 = row0_valid ? (const HVX_UVector *) row0 : NULL;
+ const HVX_UVector * pv1 = row1_valid ? (const HVX_UVector *) row1 : NULL;
+
+ uint32_t c = 0;
+ for (; c + 64 <= k_chunk_valid; c += 64) {
+ HVX_Vector v0 = pv0 ? pv0[c / 64] : Q6_V_vzero();
+ HVX_Vector v1 = pv1 ? pv1[c / 64] : Q6_V_vzero();
+ HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
+
+ const uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS;
+ HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS);
+ HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS);
+
+ tile0[r1 / 2] = Q6_V_lo_W(vp);
+ tile1[r1 / 2] = Q6_V_hi_W(vp);
+ }
+ for (; c < c_len; c += 64) {
+ HVX_Vector v0 = Q6_V_vzero();
+ HVX_Vector v1 = Q6_V_vzero();
+
+ if (c < k_chunk_valid) {
+ const uint32_t rem = k_chunk_valid - c;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(__fp16));
+ if (pv0) {
+ v0 = Q6_V_vmux_QVV(mask, pv0[c / 64], Q6_V_vzero());
+ }
+ if (pv1) {
+ v1 = Q6_V_vmux_QVV(mask, pv1[c / 64], Q6_V_vzero());
+ }
+ }
+
+ HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
+ const uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS;
+
+ HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS);
+ tile0[r1 / 2] = Q6_V_lo_W(vp);
+
+ if (c + 32 < c_len && c0 + 1 < n_tile_cols) {
+ HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS);
+ tile1[r1 / 2] = Q6_V_hi_W(vp);
+ }
+ }
+}
+
+static inline HVX_Vector hvx_vec_load_u(const void * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) ((uintptr_t) src & ~(uintptr_t) 127);
+ const uint32_t left_off = (uint32_t) ((uintptr_t) src & 127);
+ const uint32_t right_off = left_off + n;
+ HVX_Vector v = (right_off > 128) ? Q6_V_valign_VVR(vsrc[1], vsrc[0], left_off) : Q6_V_vror_VR(vsrc[0], left_off);
+ return Q6_V_vand_QV(Q6_Q_vsetq2_R(n), v);
+}
+
+// --- Shared HMX GLU Store Helpers & FP16-HMX GLU Epilogue ---
+
+static inline HVX_Vector hmx_glu_geglu_arg_f16(HVX_Vector x) {
+ // 0.5 * x * (1 + tanh(inner)) = x * sigmoid(2 * inner)
+ const HVX_Vector v_c0 = hvx_vec_splat_f16(2.0f * 0.7978845608028654f * 0.044715f);
+ const HVX_Vector v_c1 = hvx_vec_splat_f16(2.0f * 0.7978845608028654f);
+ const HVX_Vector x2 = hvx_vec_mul_f16_f16(x, x);
+ const HVX_Vector poly = hvx_vec_add_f16_f16(hvx_vec_mul_f16_f16(x2, v_c0), v_c1);
+ return hvx_vec_mul_f16_f16(x, poly);
+}
+
+static inline HVX_Vector hmx_glu_geglu_arg_f32(HVX_Vector x) {
+ const HVX_Vector v_c0 = hvx_vec_splat_f32(2.0f * 0.7978845608028654f * 0.044715f);
+ const HVX_Vector v_c1 = hvx_vec_splat_f32(2.0f * 0.7978845608028654f);
+ const HVX_Vector x2 = hvx_vec_mul_f32_f32(x, x);
+ const HVX_Vector poly = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x2, v_c0), v_c1);
+ return hvx_vec_mul_f32_f32(x, poly);
+}
+
+#define HMX_GLU_ARG_SWIGLU_F16(x) (x)
+#define HMX_GLU_ARG_SWIGLU_F32(x) (x)
+#define HMX_GLU_ARG_GEGLU_F16(x) hmx_glu_geglu_arg_f16(x)
+#define HMX_GLU_ARG_GEGLU_F32(x) hmx_glu_geglu_arg_f32(x)
+#define HMX_GLU_ARG_GEGLU_QUICK_F16(x) hvx_vec_mul_f16_f16((x), hvx_vec_splat_f16(1.702f))
+#define HMX_GLU_ARG_GEGLU_QUICK_F32(x) hvx_vec_mul_f32_f32((x), hvx_vec_splat_f32(1.702f))
+
+// Sigmoid-based GLU stores: out = g * sigmoid(ARG(g)) * u (vtcm_res_out is always 128B aligned).
+#define DEFINE_HMX_SIG_GLU_STORE(NAME, ARG_F16, ARG_F32) \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_tail_fp16( \
+ void * restrict dst_ptr, \
+ size_t dst_stride, \
+ const HVX_Vector * restrict g_hf, \
+ const HVX_Vector * restrict u_hf, \
+ uint32_t rows_and_bytes) { \
+ __fp16 * restrict dst = (__fp16 *) dst_ptr; \
+ const uint32_t valid_rows = rows_and_bytes >> 16; \
+ const size_t valid_bytes = rows_and_bytes & 0xffffu; \
+ _Pragma("clang loop pipeline(disable) unroll(disable)") \
+ for (uint32_t k = 0; k < valid_rows; ++k) { \
+ const HVX_Vector g = g_hf[k]; \
+ const HVX_Vector sig = hvx_vec_fast_sigmoid_f16(ARG_F16(g)); \
+ const HVX_Vector out = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g, sig), u_hf[k]); \
+ hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out); \
+ } \
+} \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_quad_fp16( \
+ void * restrict dst_ptr, \
+ size_t dst_stride, \
+ const HVX_Vector * restrict g_hf, \
+ const HVX_Vector * restrict u_hf, \
+ uint32_t valid_rows) { \
+ __fp16 * restrict dst = (__fp16 *) dst_ptr; \
+ if (valid_rows == 4u) { \
+ const HVX_Vector g0 = g_hf[0]; \
+ const HVX_Vector g1 = g_hf[1]; \
+ const HVX_VectorPair s01 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g0), ARG_F16(g1)); \
+ hvx_vmem(dst + 0 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g0, Q6_V_lo_W(s01)), u_hf[0]); \
+ hvx_vmem(dst + 1 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g1, Q6_V_hi_W(s01)), u_hf[1]); \
+ const HVX_Vector g2 = g_hf[2]; \
+ const HVX_Vector g3 = g_hf[3]; \
+ const HVX_VectorPair s23 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g2), ARG_F16(g3)); \
+ hvx_vmem(dst + 2 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g2, Q6_V_lo_W(s23)), u_hf[2]); \
+ hvx_vmem(dst + 3 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g3, Q6_V_hi_W(s23)), u_hf[3]); \
+ return; \
+ } \
+ hmx_glu_##NAME##_store_tail_fp16(dst, dst_stride, g_hf, u_hf, (valid_rows << 16) | 128u); \
+} \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_tail_fp32( \
+ void * restrict dst_ptr, \
+ size_t dst_stride, \
+ const HVX_Vector * restrict g_q, \
+ const HVX_Vector * restrict u_q, \
+ uint32_t rows_and_bytes) { \
+ float * restrict dst = (float *) dst_ptr; \
+ const uint32_t valid_rows = rows_and_bytes >> 16; \
+ const size_t valid_bytes = rows_and_bytes & 0xffffu; \
+ const HVX_Vector v_one = hvx_vec_splat_f32(1.0f); \
+ const HVX_Vector v_max_exp = hvx_vec_splat_f32(87.0f); \
+ const HVX_Vector v_min_exp = hvx_vec_splat_f32(-87.0f); \
+ _Pragma("clang loop unroll(disable)") \
+ for (uint32_t k = 0; k < valid_rows; ++k) { \
+ const HVX_Vector g = g_q[k]; \
+ const HVX_Vector sig = hvx_vec_fast_sigmoid_f32_guard(ARG_F32(g), v_one, v_max_exp, v_min_exp); \
+ const HVX_Vector out = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g, sig), u_q[k]); \
+ hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out); \
+ } \
+} \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_quad_fp32( \
+ void * restrict dst_ptr, \
+ size_t dst_stride, \
+ const HVX_Vector * restrict g_q, \
+ const HVX_Vector * restrict u_q, \
+ uint32_t valid_rows) { \
+ float * restrict dst = (float *) dst_ptr; \
+ const HVX_Vector v_one = hvx_vec_splat_f32(1.0f); \
+ const HVX_Vector v_max_exp = hvx_vec_splat_f32(87.0f); \
+ const HVX_Vector v_min_exp = hvx_vec_splat_f32(-87.0f); \
+ if (valid_rows == 4u) { \
+ const HVX_Vector g0 = g_q[0]; \
+ const HVX_Vector g1 = g_q[1]; \
+ const HVX_VectorPair s01 = hvx_vec_fast_sigmoid_f32_guard_pair(ARG_F32(g0), ARG_F32(g1), \
+ v_one, v_max_exp, v_min_exp); \
+ hvx_vmem(dst + 0 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g0, Q6_V_lo_W(s01)), u_q[0]); \
+ hvx_vmem(dst + 1 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g1, Q6_V_hi_W(s01)), u_q[1]); \
+ const HVX_Vector g2 = g_q[2]; \
+ const HVX_Vector g3 = g_q[3]; \
+ const HVX_VectorPair s23 = hvx_vec_fast_sigmoid_f32_guard_pair(ARG_F32(g2), ARG_F32(g3), \
+ v_one, v_max_exp, v_min_exp); \
+ hvx_vmem(dst + 2 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g2, Q6_V_lo_W(s23)), u_q[2]); \
+ hvx_vmem(dst + 3 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g3, Q6_V_hi_W(s23)), u_q[3]); \
+ return; \
+ } \
+ hmx_glu_##NAME##_store_tail_fp32(dst, dst_stride, g_q, u_q, (valid_rows << 16) | 128u); \
+}
+
+DEFINE_HMX_SIG_GLU_STORE(swiglu, HMX_GLU_ARG_SWIGLU_F16, HMX_GLU_ARG_SWIGLU_F32)
+DEFINE_HMX_SIG_GLU_STORE(geglu, HMX_GLU_ARG_GEGLU_F16, HMX_GLU_ARG_GEGLU_F32)
+DEFINE_HMX_SIG_GLU_STORE(geglu_quick, HMX_GLU_ARG_GEGLU_QUICK_F16, HMX_GLU_ARG_GEGLU_QUICK_F32)
+
+#define DEFINE_HMX_SIG_GLU_STRIP_FP16(NAME, ARG_F16) \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_strip_fp16( \
+ void * restrict dst_ptr, \
+ size_t dst_stride, \
+ const __fp16 * restrict u_buf, \
+ size_t u_stride, \
+ size_t n_pairs) { \
+ __fp16 * restrict dst = (__fp16 *) dst_ptr; \
+ _Pragma("clang loop unroll(disable)") \
+ for (size_t p = 0; p < n_pairs; ++p) { \
+ __fp16 * d0 = dst + (p << 6); \
+ const __fp16 * u0 = u_buf + (p << 6); \
+ const HVX_Vector g0 = hvx_vmem(d0 + 0 * dst_stride); \
+ const HVX_Vector g1 = hvx_vmem(d0 + 1 * dst_stride); \
+ const HVX_VectorPair s01 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g0), ARG_F16(g1)); \
+ hvx_vmem(d0 + 0 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g0, Q6_V_lo_W(s01)), \
+ hvx_vmem(u0 + 0 * u_stride)); \
+ hvx_vmem(d0 + 1 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g1, Q6_V_hi_W(s01)), \
+ hvx_vmem(u0 + 1 * u_stride)); \
+ const HVX_Vector g2 = hvx_vmem(d0 + 2 * dst_stride); \
+ const HVX_Vector g3 = hvx_vmem(d0 + 3 * dst_stride); \
+ const HVX_VectorPair s23 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g2), ARG_F16(g3)); \
+ hvx_vmem(d0 + 2 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g2, Q6_V_lo_W(s23)), \
+ hvx_vmem(u0 + 2 * u_stride)); \
+ hvx_vmem(d0 + 3 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g3, Q6_V_hi_W(s23)), \
+ hvx_vmem(u0 + 3 * u_stride)); \
+ } \
+}
+
+DEFINE_HMX_SIG_GLU_STRIP_FP16(swiglu, HMX_GLU_ARG_SWIGLU_F16)
+DEFINE_HMX_SIG_GLU_STRIP_FP16(geglu, HMX_GLU_ARG_GEGLU_F16)
+DEFINE_HMX_SIG_GLU_STRIP_FP16(geglu_quick, HMX_GLU_ARG_GEGLU_QUICK_F16)
+
+static __attribute__((noinline)) void hmx_glu_reglu_store_tail_fp16(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_hf,
+ const HVX_Vector * restrict u_hf,
+ uint32_t rows_and_bytes) {
+ __fp16 * restrict dst = (__fp16 *) dst_ptr;
+ const uint32_t valid_rows = rows_and_bytes >> 16;
+ const size_t valid_bytes = rows_and_bytes & 0xffffu;
+ const HVX_Vector v_zero = Q6_V_vzero();
+ for (uint32_t k = 0; k < valid_rows; ++k) {
+ const HVX_Vector out = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(g_hf[k], v_zero), u_hf[k]);
+ hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out);
+ }
+}
+
+static __attribute__((noinline)) void hmx_glu_reglu_store_quad_fp16(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_hf,
+ const HVX_Vector * restrict u_hf,
+ uint32_t valid_rows) {
+ __fp16 * restrict dst = (__fp16 *) dst_ptr;
+ const HVX_Vector v_zero = Q6_V_vzero();
+ for (uint32_t k = 0; k < valid_rows; ++k) {
+ hvx_vmem(dst + k * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(g_hf[k], v_zero), u_hf[k]);
+ }
+}
+
+static __attribute__((noinline)) void hmx_glu_reglu_store_strip_fp16(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const __fp16 * restrict u_buf,
+ size_t u_stride,
+ size_t n_pairs) {
+ __fp16 * restrict dst = (__fp16 *) dst_ptr;
+ const HVX_Vector v_zero = Q6_V_vzero();
+ _Pragma("clang loop unroll(disable)")
+ for (size_t p = 0; p < n_pairs; ++p) {
+ __fp16 * d0 = dst + (p << 6);
+ const __fp16 * u0 = u_buf + (p << 6);
+ hvx_vmem(d0 + 0 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 0 * dst_stride), v_zero), hvx_vmem(u0 + 0 * u_stride));
+ hvx_vmem(d0 + 1 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 1 * dst_stride), v_zero), hvx_vmem(u0 + 1 * u_stride));
+ hvx_vmem(d0 + 2 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 2 * dst_stride), v_zero), hvx_vmem(u0 + 2 * u_stride));
+ hvx_vmem(d0 + 3 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 3 * dst_stride), v_zero), hvx_vmem(u0 + 3 * u_stride));
+ }
+}
+
+static __attribute__((noinline)) void hmx_glu_reglu_store_tail_fp32(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_q,
+ const HVX_Vector * restrict u_q,
+ uint32_t rows_and_bytes) {
+ float * restrict dst = (float *) dst_ptr;
+ const uint32_t valid_rows = rows_and_bytes >> 16;
+ const size_t valid_bytes = rows_and_bytes & 0xffffu;
+ const HVX_Vector v_zero = Q6_V_vzero();
+ for (uint32_t k = 0; k < valid_rows; ++k) {
+ const HVX_Vector out = hvx_vec_mul_f32_f32(Q6_Vsf_vmax_VsfVsf(g_q[k], v_zero), u_q[k]);
+ hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out);
+ }
+}
+
+static __attribute__((noinline)) void hmx_glu_reglu_store_quad_fp32(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_q,
+ const HVX_Vector * restrict u_q,
+ uint32_t valid_rows) {
+ float * restrict dst = (float *) dst_ptr;
+ const HVX_Vector v_zero = Q6_V_vzero();
+ for (uint32_t k = 0; k < valid_rows; ++k) {
+ hvx_vmem(dst + k * dst_stride) = hvx_vec_mul_f32_f32(Q6_Vsf_vmax_VsfVsf(g_q[k], v_zero), u_q[k]);
+ }
+}
+
+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 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;
+
+static inline 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) {
+ if (dst_elem_size == sizeof(__fp16)) {
+ switch (glu_op) {
+ case HTP_OP_GLU_SWIGLU:
+ *store_quad_fn = hmx_glu_swiglu_store_quad_fp16;
+ *store_tail_fn = hmx_glu_swiglu_store_tail_fp16;
+ *store_strip_fn = hmx_glu_swiglu_store_strip_fp16;
+ return true;
+ case HTP_OP_GLU_GEGLU:
+ *store_quad_fn = hmx_glu_geglu_store_quad_fp16;
+ *store_tail_fn = hmx_glu_geglu_store_tail_fp16;
+ *store_strip_fn = hmx_glu_geglu_store_strip_fp16;
+ return true;
+ case HTP_OP_GLU_GEGLU_QUICK:
+ *store_quad_fn = hmx_glu_geglu_quick_store_quad_fp16;
+ *store_tail_fn = hmx_glu_geglu_quick_store_tail_fp16;
+ *store_strip_fn = hmx_glu_geglu_quick_store_strip_fp16;
+ return true;
+ case HTP_OP_GLU_REGLU:
+ *store_quad_fn = hmx_glu_reglu_store_quad_fp16;
+ *store_tail_fn = hmx_glu_reglu_store_tail_fp16;
+ *store_strip_fn = hmx_glu_reglu_store_strip_fp16;
+ return true;
+ default:
+ return false;
+ }
+ }
+ *store_strip_fn = NULL;
+ switch (glu_op) {
+ case HTP_OP_GLU_SWIGLU:
+ *store_quad_fn = hmx_glu_swiglu_store_quad_fp32;
+ *store_tail_fn = hmx_glu_swiglu_store_tail_fp32;
+ return true;
+ case HTP_OP_GLU_GEGLU:
+ *store_quad_fn = hmx_glu_geglu_store_quad_fp32;
+ *store_tail_fn = hmx_glu_geglu_store_tail_fp32;
+ return true;
+ case HTP_OP_GLU_GEGLU_QUICK:
+ *store_quad_fn = hmx_glu_geglu_quick_store_quad_fp32;
+ *store_tail_fn = hmx_glu_geglu_quick_store_tail_fp32;
+ return true;
+ case HTP_OP_GLU_REGLU:
+ *store_quad_fn = hmx_glu_reglu_store_quad_fp32;
+ *store_tail_fn = hmx_glu_reglu_store_tail_fp32;
+ return true;
+ default:
+ return false;
+ }
+}
+
+static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp16(
+ 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) {
+ const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void;
+ __fp16 * restrict dst = (__fp16 *) dst_ptr;
+ const __fp16 * vtcm_gate = (const __fp16 *) st->vtcm_gate;
+ const __fp16 * vtcm_up = (const __fp16 *) st->vtcm_up;
+ const size_t tile_row_stride = hmx_ceil_div(st->n_cols, HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS;
+ const size_t c0_first = c_first >> 5;
+ const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu);
+ const size_t limit_c_aligned = limit_c & ~63u;
+ const size_t dst_stride = st->dst_stride;
+
+ HVX_Vector g_hf[4] __attribute__((aligned(128)));
+ HVX_Vector u_hf[4] __attribute__((aligned(128)));
+
+ for (size_t r_base = 0; r_base < n_rows; ) {
+ const size_t r_idx_base = start_row + r_base;
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u)));
+ const size_t r_end = r_base + r_step;
+ const size_t tile_off = (r_idx_base >> 5) * tile_row_stride + c0_first * HTP_MM_HMX_TILE_N_ELMS;
+ const __fp16 * g_row = vtcm_gate + tile_off;
+ const __fp16 * u_row = vtcm_up + tile_off;
+
+ for (size_t r = r_base; r < r_end; r += 4) {
+ const size_t r_idx0 = start_row + r;
+ const size_t r1 = (r_idx0 & 31u) >> 1;
+ const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, r_end - r);
+ __fp16 * out_row0 = dst + r * dst_stride;
+
+ #pragma clang loop unroll(disable)
+ for (size_t c = 0; c < limit_c_aligned; c += 64) {
+ const size_t c0 = c >> 5;
+ const size_t off0 = c0 * HTP_MM_HMX_TILE_N_ELMS;
+ const size_t off1 = off0 + HTP_MM_HMX_TILE_N_ELMS;
+ const HVX_VectorPair gp0 = Q6_W_vdeal_VVR(((const HVX_Vector *) (g_row + off1))[r1],
+ ((const HVX_Vector *) (g_row + off0))[r1], -2);
+ const HVX_VectorPair up0 = Q6_W_vdeal_VVR(((const HVX_Vector *) (u_row + off1))[r1],
+ ((const HVX_Vector *) (u_row + off0))[r1], -2);
+ g_hf[0] = Q6_V_lo_W(gp0);
+ g_hf[1] = Q6_V_hi_W(gp0);
+ u_hf[0] = Q6_V_lo_W(up0);
+ u_hf[1] = Q6_V_hi_W(up0);
+ if (valid_rows > 2u) {
+ const HVX_VectorPair gp1 = Q6_W_vdeal_VVR(((const HVX_Vector *) (g_row + off1))[r1 + 1],
+ ((const HVX_Vector *) (g_row + off0))[r1 + 1], -2);
+ const HVX_VectorPair up1 = Q6_W_vdeal_VVR(((const HVX_Vector *) (u_row + off1))[r1 + 1],
+ ((const HVX_Vector *) (u_row + off0))[r1 + 1], -2);
+ g_hf[2] = Q6_V_lo_W(gp1);
+ g_hf[3] = Q6_V_hi_W(gp1);
+ u_hf[2] = Q6_V_lo_W(up1);
+ u_hf[3] = Q6_V_hi_W(up1);
+ }
+ st->store_quad_fn(out_row0 + c, dst_stride, g_hf, u_hf, valid_rows);
+ }
+ if (limit_c_aligned < limit_c) {
+ const size_t c = limit_c_aligned;
+ const size_t c0 = c >> 5;
+ const size_t off0 = c0 * HTP_MM_HMX_TILE_N_ELMS;
+ const size_t off1 = off0 + HTP_MM_HMX_TILE_N_ELMS;
+ const size_t valid_c = limit_c - c;
+ const uint32_t valid_bytes = (uint32_t) (valid_c * sizeof(__fp16));
+ const HVX_Vector g_t1_0 = (valid_c > 32) ? ((const HVX_Vector *) (g_row + off1))[r1] : Q6_V_vzero();
+ const HVX_Vector u_t1_0 = (valid_c > 32) ? ((const HVX_Vector *) (u_row + off1))[r1] : Q6_V_vzero();
+ const HVX_VectorPair gp0 = Q6_W_vdeal_VVR(g_t1_0, ((const HVX_Vector *) (g_row + off0))[r1], -2);
+ const HVX_VectorPair up0 = Q6_W_vdeal_VVR(u_t1_0, ((const HVX_Vector *) (u_row + off0))[r1], -2);
+ g_hf[0] = Q6_V_lo_W(gp0);
+ g_hf[1] = Q6_V_hi_W(gp0);
+ u_hf[0] = Q6_V_lo_W(up0);
+ u_hf[1] = Q6_V_hi_W(up0);
+ if (valid_rows > 2u) {
+ const HVX_Vector g_t1_1 = (valid_c > 32) ? ((const HVX_Vector *) (g_row + off1))[r1 + 1] : Q6_V_vzero();
+ const HVX_Vector u_t1_1 = (valid_c > 32) ? ((const HVX_Vector *) (u_row + off1))[r1 + 1] : Q6_V_vzero();
+ const HVX_VectorPair gp1 = Q6_W_vdeal_VVR(g_t1_1, ((const HVX_Vector *) (g_row + off0))[r1 + 1], -2);
+ const HVX_VectorPair up1 = Q6_W_vdeal_VVR(u_t1_1, ((const HVX_Vector *) (u_row + off0))[r1 + 1], -2);
+ g_hf[2] = Q6_V_lo_W(gp1);
+ g_hf[3] = Q6_V_hi_W(gp1);
+ u_hf[2] = Q6_V_lo_W(up1);
+ u_hf[3] = Q6_V_hi_W(up1);
+ }
+ st->store_tail_fn(out_row0 + c, dst_stride, g_hf, u_hf, (valid_rows << 16) | valid_bytes);
+ }
+ }
+ r_base = r_end;
+ }
+}
+
+static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp32(
+ 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) {
+ const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void;
+ float * restrict dst = (float *) dst_ptr;
+ const __fp16 * vtcm_gate = (const __fp16 *) st->vtcm_gate;
+ const __fp16 * vtcm_up = (const __fp16 *) st->vtcm_up;
+ const size_t tile_row_stride = hmx_ceil_div(st->n_cols, HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS;
+ const size_t c0_first = c_first >> 5;
+ const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu);
+ const size_t limit_c_aligned = limit_c & ~31u;
+ const size_t dst_stride = st->dst_stride;
+ const HVX_Vector one = hvx_vec_splat_f16(1.0f);
+
+ HVX_Vector g_q[4] __attribute__((aligned(128)));
+ HVX_Vector u_q[4] __attribute__((aligned(128)));
+
+ for (size_t r_base = 0; r_base < n_rows; ) {
+ const size_t r_idx_base = start_row + r_base;
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u)));
+ const size_t r_end = r_base + r_step;
+ const size_t tile_off = (r_idx_base >> 5) * tile_row_stride + c0_first * HTP_MM_HMX_TILE_N_ELMS;
+ const __fp16 * g_row = vtcm_gate + tile_off;
+ const __fp16 * u_row = vtcm_up + tile_off;
+
+ for (size_t r = r_base; r < r_end; r += 4) {
+ const size_t r_idx0 = start_row + r;
+ const size_t r1 = (r_idx0 & 31u) >> 1;
+ const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, r_end - r);
+ float * out_row0 = dst + r * dst_stride;
+
+ #pragma clang loop unroll(disable)
+ for (size_t c = 0; c < limit_c_aligned; c += 32) {
+ const size_t off0 = (c >> 5) * HTP_MM_HMX_TILE_N_ELMS;
+ const HVX_VectorPair gp0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1], one);
+ const HVX_VectorPair up0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1], one);
+ g_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp0));
+ g_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp0));
+ u_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up0));
+ u_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up0));
+ if (valid_rows > 2u) {
+ const HVX_VectorPair gp1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1 + 1], one);
+ const HVX_VectorPair up1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1 + 1], one);
+ g_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp1));
+ g_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp1));
+ u_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up1));
+ u_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up1));
+ }
+ st->store_quad_fn(out_row0 + c, dst_stride, g_q, u_q, valid_rows);
+ }
+ if (limit_c_aligned < limit_c) {
+ const size_t c = limit_c_aligned;
+ const size_t off0 = (c >> 5) * HTP_MM_HMX_TILE_N_ELMS;
+ const uint32_t valid_bytes = (uint32_t) ((limit_c - c) * sizeof(float));
+ const HVX_VectorPair gp0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1], one);
+ const HVX_VectorPair up0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1], one);
+ g_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp0));
+ g_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp0));
+ u_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up0));
+ u_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up0));
+ if (valid_rows > 2u) {
+ const HVX_VectorPair gp1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1 + 1], one);
+ const HVX_VectorPair up1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1 + 1], one);
+ g_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp1));
+ g_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp1));
+ u_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up1));
+ u_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up1));
+ }
+ st->store_tail_fn(out_row0 + c, dst_stride, g_q, u_q, (valid_rows << 16) | valid_bytes);
+ }
+ }
+ r_base = r_end;
+ }
+}
+
+static inline bool resolve_fp16_output_glu_fns(
+ uint8_t glu_op,
+ size_t dst_elem_size,
+ 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) {
+ if (!resolve_hmx_glu_store_fns(glu_op, dst_elem_size, store_quad_fn, store_tail_fn, store_strip_fn)) {
+ return false;
+ }
+ *col_chunk_fn = (dst_elem_size == sizeof(__fp16)) ? transfer_output_chunk_fp16_glu_fp16
+ : transfer_output_chunk_fp16_glu_fp32;
+ return true;
+}
+
diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h
new file mode 100644
index 000000000..5e06f11fb
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h
@@ -0,0 +1,3464 @@
+// --- INT HMX W8A8 SM kernels ---
+
+#include "hmx-int-utils.h"
+
+typedef void (*int_rescale_superblock_fn_t)(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride);
+
+typedef struct {
+ int_rescale_superblock_fn_t rescale_2k_fn;
+ int_rescale_superblock_fn_t rescale_tail_fn;
+ uint8_t * dst_wt_base;
+ uint8_t * dst_bias_base;
+ float * dst_scales_base;
+ const uint8_t * src_raw;
+ uint32_t n_col_tiles;
+ uint32_t n_k_tiles;
+ uint32_t n_groups;
+ uint32_t tail_tiles;
+ uint32_t aligned_tile_size;
+ uint32_t raw_shift;
+ uint32_t n_tot_units;
+ uint32_t n_units_per_task;
+ uint32_t n_tasks;
+ struct fastdiv_values n_groups_div;
+} int_weight_rescale_state_t;
+
+static const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_x8_lut[128] = {
+ 0, 0, 8, 0, 16, 0, 24, 0, 32, 0, 48, 0, 64, 0, 96, 0,
+ 0, 0, 0xf8, 0, 0xf0, 0, 0xe8, 0, 0xe0, 0, 0xd0, 0, 0xc0, 0, 0xa0, 0,
+};
+
+static inline void int_hmx_rescale_4bit_lut_step(
+ HVX_Vector vq,
+ HVX_Vector v_lut,
+ HVX_Vector v_m_b4,
+ HVX_Vector * restrict tile_dst,
+ int pair_idx,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
+ HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_0f);
+ HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4);
+ HVX_Vector v_q0 = Q6_Vb_vlut32_VbVbI(v_lo, v_lut, 0);
+ HVX_Vector v_q1 = Q6_Vb_vlut32_VbVbI(v_hi, v_lut, 0);
+ int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, pair_idx, v_sum_w, v_l1_w);
+}
+
+#define DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(NAME) \
+static __attribute__((noinline)) void rescale_##NAME##_weight_superblock_2k( \
+ const uint8_t * restrict src_base, \
+ uint8_t * restrict dst_wt, \
+ float * restrict dst_scales, \
+ HVX_Vector * restrict bias_out, \
+ uint32_t tiles_per_group, \
+ size_t dst_tile_stride) { \
+ (void) tiles_per_group; \
+ rescale_##NAME##_weight_superblock_impl( \
+ src_base, dst_wt, dst_scales, bias_out, HTP_MM_HMX_W8A8_KGROUP_TILES, dst_tile_stride); \
+} \
+static __attribute__((noinline)) void rescale_##NAME##_weight_superblock_tail( \
+ const uint8_t * restrict src_base, \
+ uint8_t * restrict dst_wt, \
+ float * restrict dst_scales, \
+ HVX_Vector * restrict bias_out, \
+ uint32_t tiles_per_group, \
+ size_t dst_tile_stride) { \
+ rescale_##NAME##_weight_superblock_impl( \
+ src_base, dst_wt, dst_scales, bias_out, tiles_per_group, dst_tile_stride); \
+}
+
+static inline HVX_Vector int_hmx_scan_max_f16_scales(
+ const uint8_t * restrict src_base,
+ size_t tile_stride,
+ size_t scale_offset,
+ uint32_t tiles_per_group) {
+
+ assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
+
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max0 = Q6_V_vzero();
+ HVX_Vector v_max1 = Q6_V_vzero();
+ const uint8_t * sc_ptr = src_base + scale_offset;
+ for (uint32_t kt = 0; kt < tiles_per_group; kt += 2) {
+ HVX_Vector v_sc0 = Q6_V_vand_VV(hvx_vmem(sc_ptr), v_abs_mask);
+ HVX_Vector v_sc1 = Q6_V_vand_VV(hvx_vmem(sc_ptr + tile_stride), v_abs_mask);
+ v_max0 = Q6_Vhf_vmax_VhfVhf(v_max0, v_sc0);
+ v_max1 = Q6_Vhf_vmax_VhfVhf(v_max1, v_sc1);
+ sc_ptr += 2 * tile_stride;
+ }
+ return Q6_Vhf_vmax_VhfVhf(v_max0, v_max1);
+}
+
+static inline void rescale_q4_0_tile_step(
+ const uint8_t * restrict tile_src,
+ HVX_Vector * restrict tile_dst,
+ HVX_Vector v_m_b4,
+ HVX_Vector mask_f0,
+ HVX_Vector sign_88,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq_s = Q6_V_vxor_VV(hvx_vmem(tile_src + i * 128), sign_88);
+ HVX_Vector v_lo = Q6_V_vand_VV(Q6_Vh_vasl_VhR(vq_s, 4), mask_f0);
+ HVX_Vector v_hi = Q6_V_vand_VV(vq_s, mask_f0);
+ int_hmx_rescale_pair_wb(v_lo, v_hi, v_m_b4, tile_dst, i, v_sum_w, v_l1_w);
+ }
+}
+
+// Rescale one (ct, g) superblock of Q4_0 tiles into int8 weight.b tiles,
+// compute sum_w and exact l1_w per output channel, and write the Bias Register bank(s) and D_w_eff.
+static __attribute__((always_inline)) inline void rescale_q4_0_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_0);
+ const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector);
+ const HVX_Vector mask_f0 = Q6_Vb_vsplat_R(0xF0);
+ const HVX_Vector sign_88 = Q6_Vb_vsplat_R(0x88);
+
+ HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 512, tiles_per_group);
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ const uint8_t * tile_src = src_base;
+ HVX_Vector * tile_dst = (HVX_Vector *) dst_wt;
+ HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 512), v_inv127_qf);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt + 1 < tiles_per_group; ++kt) {
+ HVX_Vector v_m_next = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 512), v_inv127_qf);
+ rescale_q4_0_tile_step(tile_src, tile_dst, v_m_b4, mask_f0, sign_88, &v_sum_w, &v_l1_w);
+ v_m_b4 = v_m_next;
+ tile_src += tile_stride;
+ tile_dst += dst_stride_vecs;
+ }
+ rescale_q4_0_tile_step(tile_src, tile_dst, v_m_b4, mask_f0, sign_88, &v_sum_w, &v_l1_w);
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q4_0)
+
+static inline void rescale_q8_0_tile_step(
+ const uint8_t * restrict tile_src,
+ HVX_Vector * restrict tile_dst,
+ HVX_Vector v_m_b4,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq0 = hvx_vmem(tile_src + (2 * i + 0) * 128);
+ HVX_Vector vq1 = hvx_vmem(tile_src + (2 * i + 1) * 128);
+ int_hmx_rescale_pair_wb(vq0, vq1, v_m_b4, tile_dst, i, v_sum_w, v_l1_w);
+ }
+}
+
+static __attribute__((always_inline)) inline void rescale_q8_0_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q8_0);
+ const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector);
+ HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 1024, tiles_per_group);
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ const uint8_t * tile_src = src_base;
+ HVX_Vector * tile_dst = (HVX_Vector *) dst_wt;
+ HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 1024), v_inv127_qf);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt + 1 < tiles_per_group; ++kt) {
+ HVX_Vector v_m_next = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 1024), v_inv127_qf);
+ rescale_q8_0_tile_step(tile_src, tile_dst, v_m_b4, &v_sum_w, &v_l1_w);
+ v_m_b4 = v_m_next;
+ tile_src += tile_stride;
+ tile_dst += dst_stride_vecs;
+ }
+ rescale_q8_0_tile_step(tile_src, tile_dst, v_m_b4, &v_sum_w, &v_l1_w);
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q8_0)
+
+static inline void rescale_4bit_lut_tile_step(
+ const uint8_t * restrict tile_src,
+ HVX_Vector * restrict tile_dst,
+ HVX_Vector v_lut,
+ HVX_Vector v_m_b4,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ int_hmx_rescale_4bit_lut_step(hvx_vmem(tile_src + i * 128), v_lut, v_m_b4, tile_dst, i, v_sum_w, v_l1_w);
+ }
+}
+
+static inline HVX_Vector int_hmx_mxfp4_e8m0_to_f32(HVX_Vector v_raw) {
+ HVX_Vector v_e_h = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(v_raw));
+ HVX_Vector v_e_w = Q6_V_lo_W(Q6_Wuw_vunpack_Vuh(v_e_h));
+ HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VwVw(v_e_w, Q6_V_vsplat_R(0xff));
+ return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_Vw_vasl_VwR(v_e_w, 23));
+}
+
+static __attribute__((always_inline)) inline void rescale_mxfp4_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_MXFP4);
+ const HVX_Vector v_lut = *(const HVX_Vector *) kvalues_mxfp4_x8_lut;
+ HVX_Vector v_max0 = Q6_V_vzero();
+ HVX_Vector v_max1 = Q6_V_vzero();
+ const uint8_t * sc_ptr = src_base + 512;
+ for (uint32_t kt = 0; kt < tiles_per_group; kt += 2) {
+ v_max0 = Q6_Vsf_vmax_VsfVsf(v_max0, int_hmx_mxfp4_e8m0_to_f32(hvx_vmem(sc_ptr)));
+ v_max1 = Q6_Vsf_vmax_VsfVsf(v_max1, int_hmx_mxfp4_e8m0_to_f32(hvx_vmem(sc_ptr + tile_stride)));
+ sc_ptr += 2 * tile_stride;
+ }
+ HVX_Vector v_max_sf = Q6_Vsf_vmax_VsfVsf(v_max0, v_max1);
+
+ HVX_Vector v_inv127_qf = int_hmx_inv127_from_max_f32(v_max_sf);
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_Vector v_sc_qf = hvx_vec_f32_to_qf32(int_hmx_mxfp4_e8m0_to_f32(hvx_vmem(tile_src + 512)));
+ HVX_Vector v_m_b4 = int_hmx_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf);
+ rescale_4bit_lut_tile_step(tile_src, tile_dst, v_lut, v_m_b4, &v_sum_w, &v_l1_w);
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(mxfp4)
+
+static inline void rescale_q5_0_tile_step(
+ const uint8_t * restrict tile_src,
+ HVX_Vector * restrict tile_dst,
+ HVX_Vector v_m_b4,
+ HVX_Vector mask_78,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ HVX_Vector v_plane = hvx_vmem(tile_src + 512);
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = Q6_V_vand_VV(Q6_Vh_vasl_VhR(vq, 3), mask_78);
+ HVX_Vector v_hi = Q6_V_vand_VV(Q6_Vuh_vlsr_VuhR(vq, 1), mask_78);
+ v_lo = Q6_V_vandor_VQR(v_lo, Q6_Q_vand_VR(v_plane, 0x01010101u << (2 * i)), 0x80808080);
+ v_hi = Q6_V_vandor_VQR(v_hi, Q6_Q_vand_VR(v_plane, 0x01010101u << (2 * i + 1)), 0x80808080);
+ int_hmx_rescale_pair_wb(v_lo, v_hi, v_m_b4, tile_dst, i, v_sum_w, v_l1_w);
+ }
+}
+
+static __attribute__((always_inline)) inline void rescale_q5_0_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_0);
+ const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector);
+ const HVX_Vector mask_78 = Q6_Vb_vsplat_R(0x78);
+ HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 640, tiles_per_group);
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ const uint8_t * tile_src = src_base;
+ HVX_Vector * tile_dst = (HVX_Vector *) dst_wt;
+ HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 640), v_inv127_qf);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt + 1 < tiles_per_group; ++kt) {
+ HVX_Vector v_m_next = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 640), v_inv127_qf);
+ rescale_q5_0_tile_step(tile_src, tile_dst, v_m_b4, mask_78, &v_sum_w, &v_l1_w);
+ v_m_b4 = v_m_next;
+ tile_src += tile_stride;
+ tile_dst += dst_stride_vecs;
+ }
+ rescale_q5_0_tile_step(tile_src, tile_dst, v_m_b4, mask_78, &v_sum_w, &v_l1_w);
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 16.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q5_0)
+
+static __attribute__((always_inline)) inline void rescale_iq4_nl_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ4_NL);
+ const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector);
+ const HVX_Vector v_lut = *(const HVX_Vector *) kvalues_iq4nl_lut;
+ HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 512, tiles_per_group);
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ const uint8_t * tile_src = src_base;
+ HVX_Vector * tile_dst = (HVX_Vector *) dst_wt;
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 512), v_inv127_qf);
+ rescale_4bit_lut_tile_step(tile_src, tile_dst, v_lut, v_m_b4, &v_sum_w, &v_l1_w);
+ tile_src += tile_stride;
+ tile_dst += dst_stride_vecs;
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(iq4_nl)
+
+static inline void rescale_q1_0_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q1_0);
+ const uint32_t raw_tiles = tiles_per_group >> 2;
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t rt = 0; rt < raw_tiles; ++rt) {
+ const uint8_t * tile_src = src_base + (size_t) rt * tile_stride;
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 512), v_abs_mask));
+ }
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ for (uint32_t rt = 0; rt < raw_tiles; ++rt) {
+ const uint8_t * tile_src = src_base + (size_t) rt * tile_stride;
+ HVX_Vector v_pos_m = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 512), v_inv127_qf);
+ HVX_Vector v_neg_m = Q6_Vb_vsub_VbVb(Q6_V_vzero(), v_pos_m);
+
+ for (uint32_t q = 0; q < 4; ++q) {
+ HVX_Vector v_plane = hvx_vmem(tile_src + q * 128);
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) (4 * rt + q) * dst_tile_stride);
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector v_W0 = unpack_q1_0_group(v_plane, 2 * i + 0, v_neg_m, v_pos_m);
+ HVX_Vector v_W1 = unpack_q1_0_group(v_plane, 2 * i + 1, v_neg_m, v_pos_m);
+ int_hmx_store_and_accum_pair(tile_dst, i, v_W0, v_W1, &v_sum_w, &v_l1_w);
+ }
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q1_0)
+
+static inline void rescale_q2_0_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_0);
+ const uint32_t raw_tiles = tiles_per_group >> 1;
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ const HVX_Vector i32 = Q6_Vb_vsplat_R(32);
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t rt = 0; rt < raw_tiles; ++rt) {
+ const uint8_t * tile_src = src_base + (size_t) rt * tile_stride;
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 512), v_abs_mask));
+ }
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ for (uint32_t rt = 0; rt < raw_tiles; ++rt) {
+ const HVX_Vector * vptr = (const HVX_Vector *) (src_base + (size_t) rt * tile_stride);
+ HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(vptr[4], v_inv127_qf);
+
+ for (uint32_t half = 0; half < 2; ++half) {
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) (2 * rt + half) * dst_tile_stride);
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector v_q0 = Q6_Vb_vsub_VbVb(Q6_Vh_vasl_VhR(unpack_q3_k_low2(vptr + 2 * half, 2 * i + 0, mask_03), 5), i32);
+ HVX_Vector v_q1 = Q6_Vb_vsub_VbVb(Q6_Vh_vasl_VhR(unpack_q3_k_low2(vptr + 2 * half, 2 * i + 1, mask_03), 5), i32);
+ int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 4.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q2_0)
+
+static inline void rescale_nvfp4_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_NVFP4);
+ const HVX_Vector v_lut = *(const HVX_Vector *) kvalues_mxfp4_x8_lut;
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_Vector v_sc = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF))));
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, v_sc);
+ }
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vror_VR(v_max_sc, 64));
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_Vector v_sc = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF))));
+ HVX_Vector v_m_b0, v_m_b1;
+ int_hmx_m_b4_pair_from_f16(v_sc, v_inv127_qf, &v_m_b0, &v_m_b1);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector v_m_b4 = (i < 2) ? v_m_b0 : v_m_b1;
+ int_hmx_rescale_4bit_lut_step(hvx_vmem(tile_src + i * 128), v_lut, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(nvfp4)
+
+static inline HVX_Vector unpack_q3_k_group_shl5(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
+ HVX_VectorPred q_neg = Q6_Q_vand_VR(vptr[2], 0x01010101u << g);
+ HVX_Vector v_lo2 = Q6_Vh_vasl_VhR(unpack_q3_k_low2(vptr, g, mask_03), 5);
+ return Q6_V_vandor_VQR(v_lo2, q_neg, 0x80808080);
+}
+
+static inline void rescale_q3_k_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q3_K);
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 384), v_abs_mask));
+ }
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vror_VR(v_max_sc, 64));
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const HVX_Vector * vptr = (const HVX_Vector *) (src_base + (size_t) kt * tile_stride);
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_Vector v_m_b0, v_m_b1;
+ int_hmx_m_b4_pair_from_f16(vptr[3], v_inv127_qf, &v_m_b0, &v_m_b1);
+
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector v_m_b4 = (i < 2) ? v_m_b0 : v_m_b1;
+ HVX_Vector v_q0 = unpack_q3_k_group_shl5(vptr, 2 * i + 0, mask_03);
+ HVX_Vector v_q1 = unpack_q3_k_group_shl5(vptr, 2 * i + 1, mask_03);
+ int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 4.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q3_k)
+
+static inline void rescale_q6_k_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q6_K);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80);
+ const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector v_max_sc = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 768), v_abs_mask));
+ }
+ v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vror_VR(v_max_sc, 64));
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const HVX_Vector * vptr = (const HVX_Vector *) (src_base + (size_t) kt * tile_stride);
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_Vector v_m_b0, v_m_b1;
+ int_hmx_m_b4_pair_from_f16(vptr[6], v_inv127_qf, &v_m_b0, &v_m_b1);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector v_m_b4 = (i < 2) ? v_m_b0 : v_m_b1;
+ HVX_Vector v_q0 = Q6_V_vxor_VV(Q6_Vh_vasl_VhR(unpack_q6_k_group(vptr, 2 * i + 0, mask_0f, mask_03, Q6_V_vzero()), 2), sign_80);
+ HVX_Vector v_q1 = Q6_V_vxor_VV(Q6_Vh_vasl_VhR(unpack_q6_k_group(vptr, 2 * i + 1, mask_0f, mask_03, Q6_V_vzero()), 2), sign_80);
+ int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 32.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q6_k)
+
+static inline void int_hmx_pack_q6_pair(
+ HVX_Vector v_hi0,
+ HVX_Vector v_lo0,
+ HVX_Vector v_hi1,
+ HVX_Vector v_lo1,
+ HVX_Vector * restrict v_W0_out,
+ HVX_Vector * restrict v_W1_out) {
+#if __HVX_ARCH__ >= 79
+ *v_W0_out = Q6_Vb_vasr_VhVhR_rnd_sat(v_hi0, v_lo0, 6);
+ *v_W1_out = Q6_Vb_vasr_VhVhR_rnd_sat(v_hi1, v_lo1, 6);
+#else
+ *v_W0_out = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_hi0, 2), Q6_Vh_vasl_VhR(v_lo0, 2));
+ *v_W1_out = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_hi1, 2), Q6_Vh_vasl_VhR(v_lo1, 2));
+#endif
+}
+
+static inline HVX_Vector int_hmx_asym_update_wmax_qf(
+ HVX_Vector v_wmax_sf,
+ HVX_Vector vd_qf,
+ HVX_Vector vm_qf,
+ HVX_Vector v_qmax_qf) {
+
+ const HVX_Vector v_abs_mask_sf = Q6_V_vsplat_R(0x7fffffff);
+ HVX_Vector vm_sf = Q6_Vsf_equals_Vqf32(vm_qf);
+ HVX_Vector v_end = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_qmax_qf), vm_qf));
+ HVX_Vector v_ext0 = Q6_V_vand_VV(vm_sf, v_abs_mask_sf);
+ HVX_Vector v_ext1 = Q6_V_vand_VV(v_end, v_abs_mask_sf);
+ return Q6_Vsf_vmax_VsfVsf(v_wmax_sf, Q6_Vsf_vmax_VsfVsf(v_ext0, v_ext1));
+}
+
+static inline void int_hmx_asym_alpha_beta_wb(
+ HVX_Vector vd_qf,
+ HVX_Vector vm_qf,
+ HVX_Vector v_scale_q6_qf,
+ HVX_Vector * restrict v_alpha_h_out,
+ HVX_Vector * restrict v_beta_h_out) {
+
+ const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
+ HVX_Vector v_a_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_scale_q6_qf), v12M_sf));
+ HVX_Vector v_b_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(vm_qf, v_scale_q6_qf), v12M_sf));
+ *v_alpha_h_out = Q6_Vh_vshuffe_VhVh(v_a_bias, v_a_bias);
+ *v_beta_h_out = Q6_Vh_vshuffe_VhVh(v_b_bias, v_b_bias);
+}
+
+static inline void int_hmx_rescale_asym_pair_wb(
+ HVX_Vector v_q0,
+ HVX_Vector v_q1,
+ HVX_Vector v_alpha_h,
+ HVX_Vector v_beta_h,
+ HVX_Vector * restrict tile_dst,
+ int pair_idx,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w) {
+
+ const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1);
+ HVX_VectorPair vp0 = Q6_Wh_vmpy_VbVb(v_q0, v_one_s8);
+ HVX_VectorPair vp1 = Q6_Wh_vmpy_VbVb(v_q1, v_one_s8);
+ HVX_Vector v_p0_e = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_lo_W(vp0), v_alpha_h);
+ HVX_Vector v_p0_o = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_hi_W(vp0), v_alpha_h);
+ HVX_Vector v_p1_e = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_lo_W(vp1), v_alpha_h);
+ HVX_Vector v_p1_o = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_hi_W(vp1), v_alpha_h);
+ HVX_Vector v_W0, v_W1;
+ int_hmx_pack_q6_pair(v_p0_o, v_p0_e, v_p1_o, v_p1_e, &v_W0, &v_W1);
+ int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
+}
+
+static inline void int_hmx_iq2xxs_decode_pair(
+ HVX_Vector v_c2,
+ HVX_Vector v_sgn,
+ int l,
+ HVX_Vector v_nib_lut,
+ HVX_Vector * restrict v_w0_out,
+ HVX_Vector * restrict v_w1_out) {
+
+ 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);
+
+ 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_d = (l & 1) ? Q6_Vh_vshuffo_VhVh(v_c2, v_c2) : Q6_Vh_vshuffe_VhVh(v_c2, v_c2);
+ 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_w0_out = Q6_V_vmux_QVV(q_lo, Q6_Vb_vsub_VbVb(v_zero, v_g0), v_g0);
+ *v_w1_out = Q6_V_vmux_QVV(q_hi, Q6_Vb_vsub_VbVb(v_zero, v_g1), v_g1);
+}
+
+static inline HVX_Vector int_hmx_iq2xxs_gather_d(const uint8_t * restrict sb) {
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
+ HVX_Vector v_dd = Q6_V_vzero();
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int j = 0; j < IQ2XXS_TILES_PER_SB; j++) {
+ HVX_Vector v = hvx_vmem(sb + (size_t) j * tile_stride + 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;
+}
+
+static inline void rescale_iq2_xxs_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
+ const HVX_Vector v_abs_mask_sf = Q6_V_vsplat_R(0x7fffffff);
+ const HVX_Vector v_one_w = Q6_V_vsplat_R(1);
+ const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1);
+ const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
+ const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut);
+
+ HVX_Vector v_max_sf = Q6_V_vzero();
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += IQ2XXS_TILES_PER_SB) {
+ const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride;
+ HVX_Vector v_d_sf = Q6_V_lo_W(hvx_vec_f16_to_f32(int_hmx_iq2xxs_gather_d(sb)));
+ HVX_Vector v_d_abs_sf = Q6_V_vand_VV(v_d_sf, v_abs_mask_sf);
+ HVX_Vector v_max_sc_u32 = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t j = 0; j < IQ2XXS_TILES_PER_SB; ++j) {
+ const uint8_t * tile_src = sb + (size_t) j * tile_stride;
+ HVX_Vector v_sgn = Q6_V_hi_W(Q6_W_vdeal_VVR(hvx_vmem(tile_src + VLEN), hvx_vmem(tile_src), -IQ2XXS_WORD_BYTES));
+ v_max_sc_u32 = Q6_Vw_vmax_VwVw(v_max_sc_u32, Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SCALE_SHIFT));
+ }
+
+ HVX_Vector v_max_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(v_max_sc_u32, 1), v_one_w);
+ v_max_sf = Q6_Vsf_vmax_VsfVsf(v_max_sf, hvx_vec_mul_f32_f32(v_d_abs_sf, Q6_Vsf_equals_Vw(v_max_ls)));
+ }
+
+ HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_max_sf, 8128.0f / 43.0f);
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+ HVX_Vector v_sgn = iq2xxs_gather_issue(src_base);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += IQ2XXS_TILES_PER_SB) {
+ const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride;
+ HVX_Vector v_d_qf = hvx_vec_f32_to_qf32(Q6_V_lo_W(hvx_vec_f16_to_f32(int_hmx_iq2xxs_gather_d(sb))));
+ HVX_Vector v_d_sc_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_qf, v_scale_q6_qf);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t j = 0; j < IQ2XXS_TILES_PER_SB; ++j) {
+ const uint32_t kt = sb_kt + j;
+ const uint8_t * tile_src = sb + (size_t) j * tile_stride;
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+
+ HVX_Vector v_c[2];
+ iq2xxs_gather_wait(tile_src, v_c);
+ const HVX_Vector v_sgn_cur = v_sgn;
+ if (kt + 1 < tiles_per_group) {
+ v_sgn = iq2xxs_gather_issue(tile_src + tile_stride);
+ }
+
+ HVX_Vector v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn_cur, IQ2XXS_SCALE_SHIFT), 1), v_one_w);
+ HVX_Vector v_ls_qf = hvx_vec_f32_to_qf32(Q6_Vsf_equals_Vw(v_ls));
+ HVX_Vector v_m_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_sc_qf, v_ls_qf), v12M_sf));
+ HVX_Vector v_alpha_h = Q6_Vh_vshuffe_VhVh(v_m_bias, v_m_bias);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector v_w0, v_w1;
+ int_hmx_iq2xxs_decode_pair((i < 2) ? v_c[0] : v_c[1], v_sgn_cur, i, v_nib_lut, &v_w0, &v_w1);
+ HVX_VectorPair vp0 = Q6_Wh_vmpy_VbVb(v_w0, v_one_s8);
+ HVX_VectorPair vp1 = Q6_Wh_vmpy_VbVb(v_w1, v_one_s8);
+ HVX_Vector v_p0_e = Q6_Vh_vmpyi_VhVh(Q6_V_lo_W(vp0), v_alpha_h);
+ HVX_Vector v_p0_o = Q6_Vh_vmpyi_VhVh(Q6_V_hi_W(vp0), v_alpha_h);
+ HVX_Vector v_p1_e = Q6_Vh_vmpyi_VhVh(Q6_V_lo_W(vp1), v_alpha_h);
+ HVX_Vector v_p1_o = Q6_Vh_vmpyi_VhVh(Q6_V_hi_W(vp1), v_alpha_h);
+ HVX_Vector v_W0, v_W1;
+ int_hmx_pack_q6_pair(v_p0_o, v_p0_e, v_p1_o, v_p1_e, &v_W0, &v_W1);
+ int_hmx_store_and_accum_pair(tile_dst, i, v_W0, v_W1, &v_sum_w, &v_l1_w);
+ }
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_max_sf, 0.125f * 43.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(iq2_xxs)
+
+static inline void rescale_q4_1_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_1);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_qmax_qf = hvx_vec_f32_to_qf32(hvx_vec_splat_f32(15.0f));
+
+ HVX_Vector v_wmax_sf = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16);
+ v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_qmax_qf);
+ }
+
+ HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_wmax_sf, 8128.0f);
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16);
+ HVX_Vector v_alpha_h, v_beta_h;
+ int_hmx_asym_alpha_beta_wb(Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_scale_q6_qf, &v_alpha_h, &v_beta_h);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_0f);
+ HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4);
+ int_hmx_rescale_asym_pair_wb(v_lo, v_hi, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q4_1)
+
+static inline void rescale_q5_k_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_K);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_qmax_qf = hvx_vec_f32_to_qf32(hvx_vec_splat_f32(31.0f));
+
+ HVX_Vector v_wmax_sf = Q6_V_vzero();
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16);
+ v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_qmax_qf);
+ }
+
+ HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_wmax_sf, 8128.0f);
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ const uint8_t * tile_src = src_base + (size_t) kt * tile_stride;
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_Vector v_plane = hvx_vmem(tile_src + 640);
+ HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16);
+ HVX_Vector v_alpha_h, v_beta_h;
+ int_hmx_asym_alpha_beta_wb(Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_scale_q6_qf, &v_alpha_h, &v_beta_h);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int i = 0; i < 4; ++i) {
+ HVX_Vector vq = hvx_vmem(tile_src + i * 128);
+ HVX_Vector v_lo = hvx_q5k_or_hibit(Q6_V_vand_VV(vq, mask_0f), v_plane, 2 * i + 0);
+ HVX_Vector v_hi = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(vq, 4), v_plane, 2 * i + 1);
+ int_hmx_rescale_asym_pair_wb(v_lo, v_hi, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q5_k)
+
+static inline void int_hmx_q2_k_load_dmin(
+ const uint8_t * restrict sb,
+ HVX_Vector * restrict v_d,
+ HVX_Vector * restrict v_m) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_K);
+ HVX_Vector v_dd = Q6_V_vzero();
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int j = 0; j < 8; j++) {
+ HVX_Vector v = hvx_vmem(sb + (size_t) j * tile_stride + 256);
+ 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);
+}
+
+static inline void rescale_q2_k_weight_superblock_impl(
+ const uint8_t * restrict src_base,
+ uint8_t * restrict dst_wt,
+ float * restrict dst_scales,
+ HVX_Vector * restrict bias_out,
+ uint32_t tiles_per_group,
+ size_t dst_tile_stride) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_K);
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_qmax_qf = hvx_vec_f32_to_qf32(hvx_vec_splat_f32(3.0f));
+
+ HVX_Vector v_wmax_sf = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += 8) {
+ const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride;
+ HVX_Vector v_d, v_dm;
+ int_hmx_q2_k_load_dmin(sb, &v_d, &v_dm);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t j = 0; j < 8; ++j) {
+ const uint8_t * tile_src = sb + (size_t) j * tile_stride;
+ HVX_Vector v_D, v_M;
+ q2_k_unpack_scales(tile_src, v_d, v_dm, &v_D, &v_M);
+ HVX_VectorPair vp_d_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_D), v_one_f16);
+ HVX_VectorPair vp_m_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_M), v_one_f16);
+ v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_lo_W(vp_d_qf), Q6_V_lo_W(vp_m_qf), v_qmax_qf);
+ v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_hi_W(vp_d_qf), Q6_V_hi_W(vp_m_qf), v_qmax_qf);
+ }
+ }
+
+ HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_wmax_sf, 8128.0f);
+ HVX_Vector v_sum_w = Q6_V_vzero();
+ HVX_Vector v_l1_w = Q6_V_vzero();
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += 8) {
+ const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride;
+ HVX_Vector v_d, v_dm;
+ int_hmx_q2_k_load_dmin(sb, &v_d, &v_dm);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t j = 0; j < 8; ++j) {
+ const uint32_t kt = sb_kt + j;
+ const uint8_t * tile_src = sb + (size_t) j * tile_stride;
+ const HVX_Vector * vptr = (const HVX_Vector *) tile_src;
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+
+ HVX_Vector v_D, v_M;
+ q2_k_unpack_scales(tile_src, v_d, v_dm, &v_D, &v_M);
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (int sub = 0; sub < 2; ++sub) {
+ HVX_Vector v_D_sub = (sub == 0) ? v_D : Q6_V_vror_VR(v_D, 64);
+ HVX_Vector v_M_sub = (sub == 0) ? v_M : Q6_V_vror_VR(v_M, 64);
+ HVX_Vector v_d_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_D_sub), v_one_f16));
+ HVX_Vector v_m_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_M_sub), v_one_f16));
+ HVX_Vector v_alpha_h, v_beta_h;
+ int_hmx_asym_alpha_beta_wb(v_d_qf, v_m_qf, v_scale_q6_qf, &v_alpha_h, &v_beta_h);
+
+ const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
+ for (int p = 0; p < 2; ++p) {
+ const int i = 2 * sub + p;
+ HVX_Vector v_q0 = unpack_q3_k_low2(vptr, 2 * i + 0, mask_03);
+ HVX_Vector v_q1 = unpack_q3_k_low2(vptr, 2 * i + 1, mask_03);
+ int_hmx_rescale_asym_pair_wb(v_q0, v_q1, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w);
+ }
+ }
+ }
+ }
+
+ emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q2_k)
+
+static inline void resolve_int_weight_rescale_fns(
+ int32_t weight_type,
+ int_rescale_superblock_fn_t * restrict fn_2k,
+ int_rescale_superblock_fn_t * restrict fn_tail) {
+ switch (weight_type) {
+ case HTP_TYPE_Q4_0: *fn_2k = rescale_q4_0_weight_superblock_2k; *fn_tail = rescale_q4_0_weight_superblock_tail; break;
+ case HTP_TYPE_Q8_0: *fn_2k = rescale_q8_0_weight_superblock_2k; *fn_tail = rescale_q8_0_weight_superblock_tail; break;
+ case HTP_TYPE_IQ4_NL: *fn_2k = rescale_iq4_nl_weight_superblock_2k; *fn_tail = rescale_iq4_nl_weight_superblock_tail; break;
+ case HTP_TYPE_MXFP4: *fn_2k = rescale_mxfp4_weight_superblock_2k; *fn_tail = rescale_mxfp4_weight_superblock_tail; break;
+ case HTP_TYPE_Q5_0: *fn_2k = rescale_q5_0_weight_superblock_2k; *fn_tail = rescale_q5_0_weight_superblock_tail; break;
+ case HTP_TYPE_Q1_0: *fn_2k = rescale_q1_0_weight_superblock_2k; *fn_tail = rescale_q1_0_weight_superblock_tail; break;
+ case HTP_TYPE_Q2_0: *fn_2k = rescale_q2_0_weight_superblock_2k; *fn_tail = rescale_q2_0_weight_superblock_tail; break;
+ case HTP_TYPE_NVFP4: *fn_2k = rescale_nvfp4_weight_superblock_2k; *fn_tail = rescale_nvfp4_weight_superblock_tail; break;
+ case HTP_TYPE_Q3_K: *fn_2k = rescale_q3_k_weight_superblock_2k; *fn_tail = rescale_q3_k_weight_superblock_tail; break;
+ case HTP_TYPE_Q6_K: *fn_2k = rescale_q6_k_weight_superblock_2k; *fn_tail = rescale_q6_k_weight_superblock_tail; break;
+ case HTP_TYPE_IQ2_XXS: *fn_2k = rescale_iq2_xxs_weight_superblock_2k; *fn_tail = rescale_iq2_xxs_weight_superblock_tail; break;
+ case HTP_TYPE_Q4_1:
+ case HTP_TYPE_Q4_K: *fn_2k = rescale_q4_1_weight_superblock_2k; *fn_tail = rescale_q4_1_weight_superblock_tail; break;
+ case HTP_TYPE_Q5_1:
+ case HTP_TYPE_Q5_K: *fn_2k = rescale_q5_k_weight_superblock_2k; *fn_tail = rescale_q5_k_weight_superblock_tail; break;
+ case HTP_TYPE_Q2_K: *fn_2k = rescale_q2_k_weight_superblock_2k; *fn_tail = rescale_q2_k_weight_superblock_tail; break;
+ default: *fn_2k = NULL; *fn_tail = NULL; break;
+ }
+}
+
+static void rescale_int_weight_to_int8_task(
+ const int_weight_rescale_state_t * state,
+ uint32_t start_unit,
+ uint32_t end_unit) {
+
+ const uint32_t n_k_tiles = state->n_k_tiles;
+ const uint32_t n_groups = state->n_groups;
+ const uint32_t tail_tiles = state->tail_tiles;
+ const uint32_t aligned_tile_size = state->aligned_tile_size;
+ const uint32_t raw_shift = state->raw_shift;
+ const int_rescale_superblock_fn_t rescale_2k_fn = state->rescale_2k_fn;
+ const int_rescale_superblock_fn_t tail_fn = (tail_tiles == HTP_MM_HMX_W8A8_KGROUP_TILES)
+ ? rescale_2k_fn
+ : state->rescale_tail_fn;
+
+ uint32_t ct = fastdiv(start_unit, &state->n_groups_div);
+ uint32_t g = start_unit - ct * n_groups;
+ const uint32_t n_col_paired = state->n_col_tiles & ~1u;
+
+ for (uint32_t u = start_unit; u < end_unit; ++u) {
+ const bool is_full_group = (g + 1u < n_groups);
+ const size_t kt_group_start = (size_t) g * HTP_MM_HMX_W8A8_KGROUP_TILES;
+ const size_t kt_start = (size_t) ct * n_k_tiles + kt_group_start;
+ const uint32_t tiles_in_group = is_full_group ? HTP_MM_HMX_W8A8_KGROUP_TILES : tail_tiles;
+ const int_rescale_superblock_fn_t fn = is_full_group ? rescale_2k_fn : tail_fn;
+ const uint8_t * src_base = state->src_raw + (kt_start >> raw_shift) * aligned_tile_size;
+ uint8_t * dst_wt;
+ size_t dst_tile_stride;
+ if (ct < n_col_paired) {
+ // Interleave paired column tiles (2*jp, 2*jp+1) into 2048B K-tiles for weight.b:deep.
+ dst_wt = state->dst_wt_base
+ + ((size_t) (ct & ~1u) * n_k_tiles + kt_group_start * 2 + (ct & 1u)) * HTP_MM_HMX_WEIGHT_B_TILE_SIZE;
+ dst_tile_stride = 2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE;
+ } else {
+ dst_wt = state->dst_wt_base + kt_start * HTP_MM_HMX_WEIGHT_B_TILE_SIZE;
+ dst_tile_stride = HTP_MM_HMX_WEIGHT_B_TILE_SIZE;
+ }
+ float * dst_scales = state->dst_scales_base + (size_t) u * 32;
+ HVX_Vector * bias_out = (HVX_Vector *) (state->dst_bias_base + (size_t) u * (2 * HTP_MM_HMX_BIAS_BANK_SIZE));
+
+ fn(src_base, dst_wt, dst_scales, bias_out, tiles_in_group, dst_tile_stride);
+
+ if (++g == n_groups) {
+ g = 0;
+ ++ct;
+ }
+ }
+}
+
+static inline void quantize_f16_quad_step_to_u8_sm(
+ uint8_t * restrict tile_row_base,
+ uint32_t kt,
+ uint32_t rg,
+ HVX_Vector vh0,
+ HVX_Vector vh1,
+ HVX_Vector vh2,
+ HVX_Vector vh3,
+ HVX_Vector v_inv0_qf,
+ HVX_Vector v_inv1_qf,
+ HVX_Vector v_inv2_qf,
+ HVX_Vector v_inv3_qf,
+ HVX_Vector v_one_f16,
+ HVX_Vector v_bias_u8,
+ HVX_Vector v_min_u8,
+ HVX_Vector v_max_u8) {
+
+#if __HVX_ARCH__ >= 81
+ (void) v_bias_u8;
+ (void) v_min_u8;
+ (void) v_max_u8;
+
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(vh0, v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(vh1, v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(vh2, v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(vh3, v_one_f16);
+
+ HVX_Vector hf0 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf)));
+ HVX_Vector hf1 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf)));
+ HVX_Vector hf2 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf)));
+ HVX_Vector hf3 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf),
+ Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf)));
+
+ hmx_pack_hf_quad_to_u8_cm_pair(tile_row_base, kt, rg, hf0, hf1, hf2, hf3);
+#else
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh0), v_one_f16);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh1), v_one_f16);
+ HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh2), v_one_f16);
+ HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh3), v_one_f16);
+
+ {
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8));
+ HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
+ ((HVX_Vector *) (tile_row_base + (size_t) (kt + 0) * HTP_MM_HMX_TILE_SIZE))[rg] = Q6_Vb_vpacke_VhVh(vh23, vh01);
+ }
+ {
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), v_bias_u8));
+ HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
+ ((HVX_Vector *) (tile_row_base + (size_t) (kt + 1) * HTP_MM_HMX_TILE_SIZE))[rg] = Q6_Vb_vpacke_VhVh(vh23, vh01);
+ }
+#endif
+}
+
+static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_2k(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_a_out,
+ const float * restrict p0,
+ const float * restrict p1,
+ const float * restrict p2,
+ const float * restrict p3,
+ uint32_t rg,
+ uint32_t k_start,
+ uint32_t valid_rows) {
+
+ const float * p0_base = p0 + k_start;
+ const float * p1_base = p1 + k_start;
+ const float * p2_base = p2 + k_start;
+ const float * p3_base = p3 + k_start;
+ uint8_t * tile_dst_base = tile_row_base + (size_t) (k_start >> 5) * HTP_MM_HMX_TILE_SIZE;
+
+ assert(hex_is_aligned(p0_base, 128));
+ assert(hex_is_aligned(p1_base, 128));
+ assert(hex_is_aligned(p2_base, 128));
+ assert(hex_is_aligned(p3_base, 128));
+
+ HVX_Vector vmax0 = Q6_V_vzero();
+ HVX_Vector vmax1 = Q6_V_vzero();
+ HVX_Vector vmax2 = Q6_V_vzero();
+ HVX_Vector vmax3 = Q6_V_vzero();
+
+ for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = hvx_vmem(p0_base + off);
+ HVX_Vector vx1 = hvx_vmem(p1_base + off);
+ HVX_Vector vx2 = hvx_vmem(p2_base + off);
+ HVX_Vector vx3 = hvx_vmem(p3_base + off);
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1));
+ vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2));
+ vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3));
+ }
+
+ vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(vmax0) : Q6_V_vzero();
+ vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(vmax1) : Q6_V_vzero();
+ vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(vmax2) : Q6_V_vzero();
+ vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(vmax3) : Q6_V_vzero();
+
+ const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f);
+ const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f);
+ const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f);
+
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123);
+
+ HVX_Vector v_inv0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero());
+ HVX_Vector v_inv1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero());
+ HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero());
+ HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero());
+
+#if __HVX_ARCH__ >= 81
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 32), v_inv0),
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 0), v_inv0))));
+ HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off + 32), v_inv1),
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off + 0), v_inv1))));
+ HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2_base + off + 32), v_inv2),
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2_base + off + 0), v_inv2))));
+ HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p3_base + off + 32), v_inv3),
+ Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p3_base + off + 0), v_inv3))));
+
+ hmx_pack_hf_quad_to_u8_cm_pair(tile_dst_base, step * 2, rg, hf0, hf1, hf2, hf3);
+ }
+#else
+ const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f
+ const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = hvx_vmem(p0_base + off);
+ HVX_Vector vx1 = hvx_vmem(p1_base + off);
+ HVX_Vector vx2 = hvx_vmem(p2_base + off);
+ HVX_Vector vx3 = hvx_vmem(p3_base + off);
+
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
+
+ HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
+ HVX_Vector v_u8 = Q6_Vb_vpacke_VhVh(vh23, vh01);
+
+ ((HVX_Vector *) (tile_dst_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_u8;
+ }
+#endif
+}
+
+// Quantize one superblock g (k_group columns, multiple of 32) of a 4-row FP32 group into W8A8 SM 64x32 tiles.
+static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_a_out,
+ const float * restrict p0,
+ const float * restrict p1,
+ const float * restrict p2,
+ const float * restrict p3,
+ uint32_t rg,
+ uint32_t k_start,
+ uint32_t k_group,
+ uint32_t k_valid,
+ uint32_t valid_rows) {
+
+ assert(hex_is_aligned(p0 + k_start, 128));
+ assert(hex_is_aligned(p1 + k_start, 128));
+ assert(hex_is_aligned(p2 + k_start, 128));
+ assert(hex_is_aligned(p3 + k_start, 128));
+
+ const uint32_t k_end = k_start + k_group;
+ const uint32_t c_end_full = (k_end <= k_valid) ? k_end
+ : ((k_valid > k_start) ? (k_start + ((k_valid - k_start) & ~31u)) : k_start);
+ HVX_Vector vmax0 = Q6_V_vzero();
+ HVX_Vector vmax1 = Q6_V_vzero();
+ HVX_Vector vmax2 = Q6_V_vzero();
+ HVX_Vector vmax3 = Q6_V_vzero();
+
+ for (uint32_t c = k_start; c < c_end_full; c += 32) {
+ HVX_Vector vx0 = hvx_vmem(p0 + c);
+ HVX_Vector vx1 = hvx_vmem(p1 + c);
+ HVX_Vector vx2 = hvx_vmem(p2 + c);
+ HVX_Vector vx3 = hvx_vmem(p3 + c);
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1));
+ vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2));
+ vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3));
+ }
+ if (c_end_full < k_end && c_end_full < k_valid) {
+ const uint32_t c = c_end_full;
+ const uint32_t rem = k_valid - c;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(float));
+ HVX_Vector vx0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero());
+ HVX_Vector vx1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero());
+ HVX_Vector vx2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero());
+ HVX_Vector vx3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero());
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1));
+ vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2));
+ vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3));
+ }
+
+ vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(vmax0) : Q6_V_vzero();
+ vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(vmax1) : Q6_V_vzero();
+ vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(vmax2) : Q6_V_vzero();
+ vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(vmax3) : Q6_V_vzero();
+
+ const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f);
+ const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f);
+ const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f);
+
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123);
+
+ HVX_Vector v_inv0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero());
+ HVX_Vector v_inv1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero());
+ HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero());
+ HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero());
+
+ const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f
+ const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ for (uint32_t c = k_start; c < c_end_full; c += 32) {
+ HVX_Vector vx0 = hvx_vmem(p0 + c);
+ HVX_Vector vx1 = hvx_vmem(p1 + c);
+ HVX_Vector vx2 = hvx_vmem(p2 + c);
+ HVX_Vector vx3 = hvx_vmem(p3 + c);
+
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
+
+ HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
+ HVX_Vector v_u8 = Q6_Vb_vpacke_VhVh(vh23, vh01);
+
+ uint32_t kt = c >> 5;
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_u8;
+ }
+ for (uint32_t c = c_end_full; c < k_end; c += 32) {
+ HVX_Vector vx0 = Q6_V_vzero();
+ HVX_Vector vx1 = Q6_V_vzero();
+ HVX_Vector vx2 = Q6_V_vzero();
+ HVX_Vector vx3 = Q6_V_vzero();
+ if (c < k_valid) {
+ uint32_t rem = k_valid - c;
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(float));
+ vx0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero());
+ vx1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero());
+ vx2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero());
+ vx3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero());
+ }
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
+ HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
+ HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
+
+ HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
+ HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
+ HVX_Vector v_u8 = Q6_Vb_vpacke_VhVh(vh23, vh01);
+
+ uint32_t kt = c >> 5;
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_u8;
+ }
+}
+
+static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_2k(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_a_out,
+ const __fp16 * restrict p0,
+ const __fp16 * restrict p1,
+ const __fp16 * restrict p2,
+ const __fp16 * restrict p3,
+ uint32_t rg,
+ uint32_t k_start,
+ uint32_t valid_rows) {
+
+ const __fp16 * p0_base = p0 + k_start;
+ const __fp16 * p1_base = p1 + k_start;
+ const __fp16 * p2_base = p2 + k_start;
+ const __fp16 * p3_base = p3 + k_start;
+ uint8_t * tile_dst_base = tile_row_base + (size_t) (k_start >> 5) * HTP_MM_HMX_TILE_SIZE;
+
+ assert(hex_is_aligned(p0_base, 128));
+ assert(hex_is_aligned(p1_base, 128));
+ assert(hex_is_aligned(p2_base, 128));
+ assert(hex_is_aligned(p3_base, 128));
+
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_abs_f16 = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector vmax_hf0 = Q6_V_vzero();
+ HVX_Vector vmax_hf1 = Q6_V_vzero();
+ HVX_Vector vmax_hf2 = Q6_V_vzero();
+ HVX_Vector vmax_hf3 = Q6_V_vzero();
+
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector vh0 = hvx_vmem(p0_base + off);
+ HVX_Vector vh1 = hvx_vmem(p1_base + off);
+ HVX_Vector vh2 = hvx_vmem(p2_base + off);
+ HVX_Vector vh3 = hvx_vmem(p3_base + off);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16));
+ }
+
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vror_VR(vmax_hf0, 64));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vror_VR(vmax_hf1, 64));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vror_VR(vmax_hf2, 64));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vror_VR(vmax_hf3, 64));
+
+ HVX_Vector vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf0), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf1), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf2), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf3), v_one_f16)))) : Q6_V_vzero();
+
+ const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f);
+ const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f);
+ const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f);
+
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123);
+
+ HVX_Vector v_inv0_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv1_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()));
+
+ const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080);
+ const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector vh0 = hvx_vmem(p0_base + off);
+ HVX_Vector vh1 = hvx_vmem(p1_base + off);
+ HVX_Vector vh2 = hvx_vmem(p2_base + off);
+ HVX_Vector vh3 = hvx_vmem(p3_base + off);
+ quantize_f16_quad_step_to_u8_sm(tile_dst_base, step * 2, rg, vh0, vh1, vh2, vh3,
+ v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf,
+ v_one_f16, v_bias_u8, v_min_u8, v_max_u8);
+ }
+}
+
+// Quantize one superblock g (k_group columns, multiple of 128) of a 4-row FP16 group into W8A8 SM 64x32 tiles.
+static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_a_out,
+ const __fp16 * restrict p0,
+ const __fp16 * restrict p1,
+ const __fp16 * restrict p2,
+ const __fp16 * restrict p3,
+ uint32_t rg,
+ uint32_t k_start,
+ uint32_t k_group,
+ uint32_t k_valid,
+ uint32_t valid_rows) {
+
+ assert(hex_is_aligned(p0 + k_start, 128));
+ assert(hex_is_aligned(p1 + k_start, 128));
+ assert(hex_is_aligned(p2 + k_start, 128));
+ assert(hex_is_aligned(p3 + k_start, 128));
+
+ const uint32_t k_end = k_start + k_group;
+ const uint32_t c_end_full = (k_end <= k_valid) ? k_end
+ : ((k_valid > k_start) ? (k_start + ((k_valid - k_start) & ~63u)) : k_start);
+ const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_abs_f16 = Q6_Vh_vsplat_R(0x7fff);
+ HVX_Vector vmax_hf0 = Q6_V_vzero();
+ HVX_Vector vmax_hf1 = Q6_V_vzero();
+ HVX_Vector vmax_hf2 = Q6_V_vzero();
+ HVX_Vector vmax_hf3 = Q6_V_vzero();
+
+ for (uint32_t c = k_start; c < c_end_full; c += 64) {
+ HVX_Vector vh0 = hvx_vmem(p0 + c);
+ HVX_Vector vh1 = hvx_vmem(p1 + c);
+ HVX_Vector vh2 = hvx_vmem(p2 + c);
+ HVX_Vector vh3 = hvx_vmem(p3 + c);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16));
+ }
+ if (c_end_full < k_end && c_end_full < k_valid) {
+ const uint32_t c = c_end_full;
+ const uint32_t rem_b = (k_valid - c) * sizeof(__fp16);
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem_b);
+ HVX_Vector vh0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero());
+ HVX_Vector vh1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero());
+ HVX_Vector vh2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero());
+ HVX_Vector vh3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero());
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16));
+ }
+
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vror_VR(vmax_hf0, 64));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vror_VR(vmax_hf1, 64));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vror_VR(vmax_hf2, 64));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vror_VR(vmax_hf3, 64));
+
+ HVX_Vector vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf0), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf1), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf2), v_one_f16)))) : Q6_V_vzero();
+ HVX_Vector vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf3), v_one_f16)))) : Q6_V_vzero();
+
+ const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f);
+ const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f);
+ const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f);
+
+ HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127);
+ HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4));
+ HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4));
+ HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4));
+ hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123);
+
+ HVX_Vector v_inv0_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv1_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()));
+ HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()));
+
+ const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080);
+ const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
+ const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
+
+ for (uint32_t c = k_start; c < c_end_full; c += 64) {
+ HVX_Vector vh0 = hvx_vmem(p0 + c);
+ HVX_Vector vh1 = hvx_vmem(p1 + c);
+ HVX_Vector vh2 = hvx_vmem(p2 + c);
+ HVX_Vector vh3 = hvx_vmem(p3 + c);
+ quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_bias_u8, v_min_u8, v_max_u8);
+ }
+ for (uint32_t c = c_end_full; c < k_end; c += 64) {
+ HVX_Vector vh0 = Q6_V_vzero();
+ HVX_Vector vh1 = Q6_V_vzero();
+ HVX_Vector vh2 = Q6_V_vzero();
+ HVX_Vector vh3 = Q6_V_vzero();
+ if (c < k_valid) {
+ uint32_t rem_b = (k_valid - c) * sizeof(__fp16);
+ HVX_VectorPred mask = Q6_Q_vsetq2_R(rem_b);
+ vh0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero());
+ vh1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero());
+ vh2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero());
+ vh3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero());
+ }
+ quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_bias_u8, v_min_u8, v_max_u8);
+ }
+}
+
+#define DEFINE_QUANTIZE_ACT_STEP_ROWS_W8A8(SFX, ACT_T, QUANT_SB_2K_FN, QUANT_SB_TAIL_FN) \
+static __attribute__((noinline)) void quantize_act_step_rows_##SFX( \
+ uint8_t * restrict vtcm_act_dst, \
+ float * restrict vtcm_act_scales, \
+ const uint8_t * restrict curr_buf, \
+ size_t row_bytes, \
+ uint32_t r, \
+ uint32_t valid_rows, \
+ uint32_t mc_pad, \
+ uint32_t n_k_tiles, \
+ uint32_t n_groups, \
+ uint32_t k_valid) { \
+ const uint32_t r0 = r >> 6; \
+ const uint32_t rg = (r & 63u) >> 2; \
+ uint8_t * tile_row_base = vtcm_act_dst + (size_t) r0 * n_k_tiles * HTP_MM_HMX_TILE_SIZE; \
+ if (valid_rows == 0) { \
+ const HVX_Vector v_zero = Q6_V_vzero(); \
+ const HVX_Vector v_zp = Q6_Vb_vsplat_R(0x80); \
+ for (uint32_t g = 0; g < n_groups; ++g) { \
+ hvx_vec_store_u(vtcm_act_scales + (size_t) g * mc_pad + r, 4 * sizeof(float), v_zero); \
+ } \
+ for (uint32_t kt = 0; kt < n_k_tiles; ++kt) { \
+ ((HVX_Vector *) (tile_row_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_zp; \
+ } \
+ } else { \
+ const uint32_t k_block = n_k_tiles << 5; \
+ const ACT_T * p0 = (const ACT_T *) curr_buf; \
+ const ACT_T * p1 = (valid_rows > 1) ? (const ACT_T *) (curr_buf + 1 * row_bytes) : p0; \
+ const ACT_T * p2 = (valid_rows > 2) ? (const ACT_T *) (curr_buf + 2 * row_bytes) : p0; \
+ const ACT_T * p3 = (valid_rows > 3) ? (const ACT_T *) (curr_buf + 3 * row_bytes) : p0; \
+ for (uint32_t g = 0; g < n_groups; ++g) { \
+ const uint32_t k_start = g * HTP_MM_HMX_W8A8_KGROUP; \
+ const uint32_t k_group = (g + 1u < n_groups) ? HTP_MM_HMX_W8A8_KGROUP : (k_block - k_start); \
+ float * d_a_out = vtcm_act_scales + (size_t) g * mc_pad + r; \
+ if (k_group == HTP_MM_HMX_W8A8_KGROUP && k_start + HTP_MM_HMX_W8A8_KGROUP <= k_valid) { \
+ QUANT_SB_2K_FN(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, valid_rows); \
+ } else { \
+ QUANT_SB_TAIL_FN(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, k_group, k_valid, \
+ valid_rows); \
+ } \
+ } \
+ } \
+}
+
+DEFINE_QUANTIZE_ACT_STEP_ROWS_W8A8(f16_w8a8, __fp16, quantize_act_superblock_quad_f16_to_u8_sm_2k, quantize_act_superblock_quad_f16_to_u8_sm)
+DEFINE_QUANTIZE_ACT_STEP_ROWS_W8A8(f32_w8a8, float, quantize_act_superblock_quad_f32_to_u8_sm_2k, quantize_act_superblock_quad_f32_to_u8_sm)
+
+// Core HMX W8A8 SM dot-product kernel over all superblocks g = 0..n_groups-1.
+static void core_dot_chunk_w8a8_sm(
+ uint8_t * restrict vtcm_out,
+ const uint8_t * restrict vtcm_act,
+ const uint8_t * restrict vtcm_weight_tiles,
+ const uint8_t * restrict vtcm_weight_bias,
+ uint32_t n_row_tiles_64,
+ uint32_t n_col_tiles,
+ uint32_t n_k_tiles,
+ uint32_t n_groups) {
+
+ assert(hex_is_aligned(vtcm_out, HTP_MM_HMX_TILE_SIZE));
+ assert(hex_is_aligned(vtcm_act, HTP_MM_HMX_TILE_SIZE));
+ assert(hex_is_aligned(vtcm_weight_tiles, HTP_MM_HMX_TILE_SIZE));
+
+ const uint32_t out_cm_rng = hmx_out_cm_range();
+ const uint32_t tail_tiles = n_k_tiles - (n_groups - 1u) * HTP_MM_HMX_W8A8_KGROUP_TILES;
+
+ // Clearing convert (retain_acc = 0) clears the active accumulator and implicitly swaps primary/secondary.
+#if __HVX_ARCH__ >= 79
+ const uint32_t cvt_p_hi = hmx_cvt_ctrl(0, 0, 0, 1);
+ const uint32_t cvt_p_lo = hmx_cvt_ctrl(1, 0, 1, 0);
+ const uint32_t cvt_s_hi = hmx_cvt_ctrl(2, 0, 0, 1);
+ const uint32_t cvt_s_lo = hmx_cvt_ctrl(3, 0, 1, 0);
+#else
+ const uint32_t cvt_p_hi = hmx_cvt_ctrl(0, 0, 0, 1);
+ const uint32_t cvt_p_lo = hmx_cvt_ctrl(0, 0, 1, 0);
+ const uint32_t cvt_s_hi = cvt_p_hi;
+ const uint32_t cvt_s_lo = cvt_p_lo;
+#endif
+
+ for (uint32_t g = 0; g < n_groups; ++g) {
+ const uint32_t kt_base = g * HTP_MM_HMX_W8A8_KGROUP_TILES;
+ const bool is_tail = (g + 1u == n_groups && tail_tiles < HTP_MM_HMX_W8A8_KGROUP_TILES);
+ const uint32_t tiles_in_group = is_tail ? tail_tiles : HTP_MM_HMX_W8A8_KGROUP_TILES;
+ const uint32_t a_rng = hmx_act_sm_range(tiles_in_group);
+
+ for (uint32_t j = 0; j + 1u < n_col_tiles; j += 2) {
+ const uint8_t * wt_pair_base = vtcm_weight_tiles
+ + ((size_t) (j >> 1) * n_k_tiles + kt_base) * (2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE);
+ const uint8_t * bias_p_hi = vtcm_weight_bias + (((size_t) (j + 0) * n_groups + g) * 2 + 0) * HTP_MM_HMX_BIAS_BANK_SIZE;
+ const uint8_t * bias_p_lo = vtcm_weight_bias + (((size_t) (j + 0) * n_groups + g) * 2 + 1) * HTP_MM_HMX_BIAS_BANK_SIZE;
+ const uint8_t * bias_s_hi = vtcm_weight_bias + (((size_t) (j + 1) * n_groups + g) * 2 + 0) * HTP_MM_HMX_BIAS_BANK_SIZE;
+ const uint8_t * bias_s_lo = vtcm_weight_bias + (((size_t) (j + 1) * n_groups + g) * 2 + 1) * HTP_MM_HMX_BIAS_BANK_SIZE;
+
+#if __HVX_ARCH__ >= 79
+ hmx_load_bias_bank(bias_p_hi, 0);
+ hmx_load_bias_bank(bias_p_lo, 1);
+ hmx_load_bias_bank(bias_s_hi, 2);
+ hmx_load_bias_bank(bias_s_lo, 3);
+#endif
+
+ for (uint32_t i = 0; i < n_row_tiles_64; ++i) {
+ const uint8_t * act_base = vtcm_act + ((size_t) i * n_k_tiles + kt_base) * HTP_MM_HMX_TILE_SIZE;
+
+ const size_t out_idx = (((size_t) g * n_row_tiles_64 + i) * n_col_tiles + j) * 2;
+ uint8_t * out_p_hi = vtcm_out + (out_idx + 0) * HTP_MM_HMX_TILE_SIZE;
+ uint8_t * out_p_lo = vtcm_out + (out_idx + 1) * HTP_MM_HMX_TILE_SIZE;
+ uint8_t * out_s_hi = vtcm_out + (out_idx + 2) * HTP_MM_HMX_TILE_SIZE;
+ uint8_t * out_s_lo = vtcm_out + (out_idx + 3) * HTP_MM_HMX_TILE_SIZE;
+
+ asm volatile(HMX_CLRACC_INT() : : : "memory");
+ // weight.b:deep processes 2048B/tile; cap each single-packet range to 32 tiles (64KB).
+ for (uint32_t kt = 0; kt < tiles_in_group; kt += 32u) {
+ const uint32_t n_kt = hex_smin(tiles_in_group - kt, 32u);
+ const uint32_t a_r = hmx_act_sm_range(n_kt);
+ const uint32_t w_r = hmx_wt_b_range(n_kt * (2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE));
+ const uint8_t * a_ptr = act_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE;
+ const uint8_t * w_ptr = wt_pair_base + (size_t) kt * (2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE);
+ asm volatile(HMX_LOAD_MPY_DEEP_U8_S8_CM_64C("%0", "%1", "%2", "%3")
+ : : "r"(a_ptr), "r"(a_r), "r"(w_ptr), "r"(w_r) : "memory");
+ }
+
+#if __HVX_ARCH__ >= 79
+ asm volatile(
+ HMX_CVT_UB_ACC("%0")
+ HMX_STORE_CVT_CM("%4", "%8")
+ HMX_CVT_UB_ACC("%1")
+ HMX_STORE_CVT_CM("%5", "%8")
+ HMX_CVT_UB_ACC("%2")
+ HMX_STORE_CVT_CM("%6", "%8")
+ HMX_CVT_UB_ACC("%3")
+ HMX_STORE_CVT_CM("%7", "%8")
+ :
+ : "r"(cvt_p_hi), "r"(cvt_p_lo), "r"(cvt_s_hi), "r"(cvt_s_lo),
+ "r"(out_p_hi), "r"(out_p_lo), "r"(out_s_hi), "r"(out_s_lo),
+ "r"(out_cm_rng)
+ : "memory");
+#else
+ hmx_load_bias_bank(bias_p_hi, 0);
+ asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2")
+ : : "r"(cvt_p_hi), "r"(out_p_hi), "r"(out_cm_rng) : "memory");
+ hmx_load_bias_bank(bias_p_lo, 0);
+ asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2")
+ : : "r"(cvt_p_lo), "r"(out_p_lo), "r"(out_cm_rng) : "memory");
+ hmx_load_bias_bank(bias_s_hi, 0);
+ asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2")
+ : : "r"(cvt_s_hi), "r"(out_s_hi), "r"(out_cm_rng) : "memory");
+ hmx_load_bias_bank(bias_s_lo, 0);
+ asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2")
+ : : "r"(cvt_s_lo), "r"(out_s_lo), "r"(out_cm_rng) : "memory");
+#endif
+ }
+ }
+
+ if (n_col_tiles & 1u) {
+ const uint32_t j = n_col_tiles - 1u;
+ const uint32_t w_rng = hmx_wt_b_range(tiles_in_group * HTP_MM_HMX_WEIGHT_B_TILE_SIZE);
+ const uint8_t * wt_base = vtcm_weight_tiles + ((size_t) j * n_k_tiles + kt_base) * HTP_MM_HMX_WEIGHT_B_TILE_SIZE;
+ const uint8_t * bias_hi = vtcm_weight_bias + (((size_t) j * n_groups + g) * 2 + 0) * HTP_MM_HMX_BIAS_BANK_SIZE;
+ const uint8_t * bias_lo = vtcm_weight_bias + (((size_t) j * n_groups + g) * 2 + 1) * HTP_MM_HMX_BIAS_BANK_SIZE;
+
+#if __HVX_ARCH__ >= 79
+ hmx_load_bias_bank(bias_hi, 0);
+ hmx_load_bias_bank(bias_lo, 1);
+#endif
+
+ for (uint32_t i = 0; i < n_row_tiles_64; ++i) {
+ const uint8_t * act_base = vtcm_act + ((size_t) i * n_k_tiles + kt_base) * HTP_MM_HMX_TILE_SIZE;
+
+ const size_t out_idx = (((size_t) g * n_row_tiles_64 + i) * n_col_tiles + j) * 2;
+ uint8_t * out_hi = vtcm_out + (out_idx + 0) * HTP_MM_HMX_TILE_SIZE;
+ uint8_t * out_lo = vtcm_out + (out_idx + 1) * HTP_MM_HMX_TILE_SIZE;
+
+ asm volatile(HMX_CLRACC_INT() : : : "memory");
+ asm volatile(HMX_LOAD_MPY_DEEP_U8_S8_CM("%0", "%1", "%2", "%3")
+ : : "r"(act_base), "r"(a_rng), "r"(wt_base), "r"(w_rng) : "memory");
+#if __HVX_ARCH__ < 79
+ hmx_load_bias_bank(bias_hi, 0);
+#endif
+ asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_p_hi) : "memory");
+ asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_hi), "r"(out_cm_rng) : "memory");
+#if __HVX_ARCH__ < 79
+ hmx_load_bias_bank(bias_lo, 0);
+#endif
+ asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_p_lo) : "memory");
+ asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_lo), "r"(out_cm_rng) : "memory");
+ }
+ }
+ }
+}
+
+// Stage activation scales from VTCM to 128B-aligned L1D stack memory so scalar Rsf loads avoid VTCM stalls and SROA vextract spills.
+static inline uint32_t (*stage_act_scales_to_l1d(
+ uint32_t (* restrict dst)[32],
+ const float * restrict vtcm_scales,
+ size_t group_stride,
+ uint32_t n_groups))[32] {
+ asm("" : "+r"(dst));
+ for (uint32_t g = 0; g < n_groups; ++g) {
+ *(HVX_Vector *) dst[g] = hvx_vmem(vtcm_scales + g * group_stride);
+ }
+ return dst;
+}
+
+#define HMX_INT_FIN_ROW_NONE(acc_qf, row_idx, bias_base, bias_rb, c) \
+ Q6_Vsf_equals_Vqf32(acc_qf)
+
+#define HMX_INT_FIN_ROW_F16(acc_qf, row_idx, bias_base, bias_rb, c) \
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf((acc_qf), hmx_load_bias_f32_32_f16((bias_base) + (row_idx) * (bias_rb), (c))))
+
+#define HMX_INT_FIN_ROW_F32(acc_qf, row_idx, bias_base, bias_rb, c) \
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf((acc_qf), hmx_load_bias_f32_32_f32((bias_base) + (row_idx) * (bias_rb), (c))))
+
+#define HMX_INT_BIAS_ROW_none(bias, off) NULL
+#define HMX_INT_BIAS_ROW_f16(bias, off) ((const uint8_t *) (bias) + (off))
+#define HMX_INT_BIAS_ROW_f32(bias, off) ((const uint8_t *) (bias) + (off))
+
+static inline HVX_Vector hmx_pack_f32_to_f16_bias_f16(
+ HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c) {
+ const HVX_VectorPair vp_b = hmx_load_bias_f32_64_f16(bias_row, c);
+ return hmx_pack_f32_to_f16_clamped(
+ hvx_vec_add_f32_f32(v_lo, Q6_V_lo_W(vp_b)),
+ hvx_vec_add_f32_f32(v_hi, Q6_V_hi_W(vp_b)));
+}
+
+static inline HVX_Vector hmx_pack_f32_to_f16_bias_f32(
+ HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c) {
+ return hmx_pack_f32_to_f16_clamped(
+ hvx_vec_add_f32_f32(v_lo, hmx_load_bias_f32_32_f32(bias_row, c)),
+ hvx_vec_add_f32_f32(v_hi, hmx_load_bias_f32_32_f32(bias_row, c + 32)));
+}
+
+static inline HVX_Vector hmx_pack_f32_to_f16_tail_bias_f16(
+ HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c, size_t valid_c) {
+ const HVX_VectorPair vp_b = hmx_load_bias_f32_64_f16(bias_row, c);
+ const HVX_Vector s0 = hvx_vec_add_f32_f32(v_lo, Q6_V_lo_W(vp_b));
+ const HVX_Vector s1 = (valid_c > 32) ? hvx_vec_add_f32_f32(v_hi, Q6_V_hi_W(vp_b)) : Q6_V_vzero();
+ return hmx_pack_f32_to_f16_clamped(s0, s1);
+}
+
+static inline HVX_Vector hmx_pack_f32_to_f16_tail_bias_f32(
+ HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c, size_t valid_c) {
+ const HVX_Vector s0 = hvx_vec_add_f32_f32(v_lo, hmx_load_bias_f32_32_f32(bias_row, c));
+ const HVX_Vector s1 = (valid_c > 32) ? hvx_vec_add_f32_f32(v_hi, hmx_load_bias_f32_32_f32(bias_row, c + 32)) : Q6_V_vzero();
+ return hmx_pack_f32_to_f16_clamped(s0, s1);
+}
+
+#define HMX_INT_PACK_FP16_ROW_none(v_lo, v_hi, bias_base, bias_rb, row_idx, c) \
+ hmx_pack_f32_to_f16_clamped((v_lo), (v_hi))
+#define HMX_INT_PACK_FP16_ROW_f16(v_lo, v_hi, bias_base, bias_rb, row_idx, c) \
+ hmx_pack_f32_to_f16_bias_f16((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c))
+#define HMX_INT_PACK_FP16_ROW_f32(v_lo, v_hi, bias_base, bias_rb, row_idx, c) \
+ hmx_pack_f32_to_f16_bias_f32((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c))
+
+#define HMX_INT_PACK_FP16_TAIL_none(v_lo, v_hi, bias_base, bias_rb, row_idx, c, valid_c) \
+ hmx_pack_f32_to_f16_clamped((v_lo), (v_hi))
+#define HMX_INT_PACK_FP16_TAIL_f16(v_lo, v_hi, bias_base, bias_rb, row_idx, c, valid_c) \
+ hmx_pack_f32_to_f16_tail_bias_f16((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c), (valid_c))
+#define HMX_INT_PACK_FP16_TAIL_f32(v_lo, v_hi, bias_base, bias_rb, row_idx, c, valid_c) \
+ hmx_pack_f32_to_f16_tail_bias_f32((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c), (valid_c))
+
+#define DEFINE_W8A8_EVAL_TILE_QUAD(SFX, FIN_ROW) \
+static inline void w8a8_sm_eval_tile_quad_1g_##SFX( \
+ const uint8_t * restrict tile_base, \
+ const float * restrict dw_base, \
+ size_t c, \
+ const uint32_t * restrict da, \
+ const uint8_t * restrict bias_row0, \
+ size_t bias_row_bytes, \
+ uint32_t n_rows, \
+ size_t r, \
+ bool full_quad, \
+ HVX_Vector * v_out0, \
+ HVX_Vector * v_out1, \
+ HVX_Vector * v_out2, \
+ HVX_Vector * v_out3) { \
+ (void) bias_row0; \
+ (void) bias_row_bytes; \
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \
+ const size_t c0 = c >> 5; \
+ const uint8_t * tp = tile_base + c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); \
+ const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HTP_MM_HMX_TILE_SIZE); \
+ const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) (dw_base + c)); \
+ HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); \
+ HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); \
+ HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); \
+ HVX_Vector v_f32_0 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)); \
+ HVX_Vector v_acc0_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_0, da[0]), v_dw_qf); \
+ *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row0, bias_row_bytes, c); \
+ if (full_quad || r + 1 < n_rows) { \
+ HVX_Vector v_f32_1 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)); \
+ HVX_Vector v_acc1_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_1, da[1]), v_dw_qf); \
+ *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row0, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 2 < n_rows) { \
+ HVX_Vector v_f32_2 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)); \
+ HVX_Vector v_acc2_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_2, da[2]), v_dw_qf); \
+ *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row0, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 3 < n_rows) { \
+ HVX_Vector v_f32_3 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)); \
+ HVX_Vector v_acc3_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_3, da[3]), v_dw_qf); \
+ *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row0, bias_row_bytes, c); \
+ } \
+} \
+static inline void w8a8_sm_eval_tile_quad_2g_##SFX( \
+ const uint8_t * restrict tile_base0, \
+ const uint8_t * restrict tile_base1, \
+ const float * restrict dw_base, \
+ size_t c, \
+ const uint32_t * restrict da0, \
+ const uint32_t * restrict da1, \
+ const uint8_t * restrict bias_row0, \
+ size_t bias_row_bytes, \
+ uint32_t n_rows, \
+ size_t r, \
+ bool full_quad, \
+ HVX_Vector * v_out0, \
+ HVX_Vector * v_out1, \
+ HVX_Vector * v_out2, \
+ HVX_Vector * v_out3) { \
+ (void) bias_row0; \
+ (void) bias_row_bytes; \
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \
+ const size_t c0 = c >> 5; \
+ const size_t tile_off = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const uint8_t * tp0 = tile_base0 + tile_off; \
+ const uint8_t * tp1 = tile_base1 + tile_off; \
+ const float * dwp = dw_base + c0 * 64; \
+ const HVX_Vector v_hi0_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp0, sign_80); \
+ const HVX_Vector v_lo0_u8 = *(const HVX_Vector *) (tp0 + HTP_MM_HMX_TILE_SIZE); \
+ const HVX_Vector v_dw0_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) dwp); \
+ HVX_VectorPair vp0_i16 = Q6_W_vshuff_VVR(v_hi0_s8, v_lo0_u8, -1); \
+ HVX_VectorPair vp0_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp0_i16)); \
+ HVX_VectorPair vp0_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp0_i16)); \
+ const HVX_Vector v_hi1_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp1, sign_80); \
+ const HVX_Vector v_lo1_u8 = *(const HVX_Vector *) (tp1 + HTP_MM_HMX_TILE_SIZE); \
+ const HVX_Vector v_dw1_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) (dwp + 32)); \
+ HVX_VectorPair vp1_i16 = Q6_W_vshuff_VVR(v_hi1_s8, v_lo1_u8, -1); \
+ HVX_VectorPair vp1_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp1_i16)); \
+ HVX_VectorPair vp1_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp1_i16)); \
+ HVX_Vector v_acc0_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp0_01)), da0[0]), v_dw0_qf), \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp1_01)), da1[0]), v_dw1_qf)); \
+ *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row0, bias_row_bytes, c); \
+ if (full_quad || r + 1 < n_rows) { \
+ HVX_Vector v_acc1_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp0_01)), da0[1]), v_dw0_qf), \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp1_01)), da1[1]), v_dw1_qf)); \
+ *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row0, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 2 < n_rows) { \
+ HVX_Vector v_acc2_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp0_23)), da0[2]), v_dw0_qf), \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp1_23)), da1[2]), v_dw1_qf)); \
+ *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row0, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 3 < n_rows) { \
+ HVX_Vector v_acc3_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp0_23)), da0[3]), v_dw0_qf), \
+ Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp1_23)), da1[3]), v_dw1_qf)); \
+ *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row0, bias_row_bytes, c); \
+ } \
+} \
+static inline void w8a8_sm_eval_tile_quad_ng_##SFX( \
+ const uint8_t * restrict tile_base, \
+ const float * restrict dw_base, \
+ size_t group_stride, \
+ uint32_t n_groups, \
+ const uint32_t * restrict da_quad_base, \
+ HVX_Vector sign_80, \
+ const uint8_t * restrict bias_row_base, \
+ size_t c, \
+ size_t bias_row_bytes, \
+ uint32_t n_rows, \
+ size_t r, \
+ bool full_quad, \
+ HVX_Vector * v_out0, \
+ HVX_Vector * v_out1, \
+ HVX_Vector * v_out2, \
+ HVX_Vector * v_out3) { \
+ (void) bias_row_base; \
+ (void) bias_row_bytes; \
+ const size_t c0 = c >> 5; \
+ const uint8_t * tp = tile_base + c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const float * dw = dw_base + c0 * (size_t) n_groups * 32; \
+ const uint32_t * da = da_quad_base; \
+ HVX_Vector v_acc0_qf = Q6_V_vzero(); \
+ HVX_Vector v_acc1_qf = Q6_V_vzero(); \
+ HVX_Vector v_acc2_qf = Q6_V_vzero(); \
+ HVX_Vector v_acc3_qf = Q6_V_vzero(); \
+ for (uint32_t g = 0; g < n_groups; ++g) { \
+ const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); \
+ const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HTP_MM_HMX_TILE_SIZE); \
+ const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) dw); \
+ HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); \
+ HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); \
+ HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); \
+ HVX_Vector v_f32_0 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)); \
+ HVX_Vector v_f32_1 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)); \
+ HVX_Vector v_f32_2 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)); \
+ HVX_Vector v_f32_3 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)); \
+ v_acc0_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc0_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_0, da[0]), v_dw_qf)); \
+ v_acc1_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc1_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_1, da[1]), v_dw_qf)); \
+ v_acc2_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc2_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_2, da[2]), v_dw_qf)); \
+ v_acc3_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc3_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_3, da[3]), v_dw_qf)); \
+ tp += group_stride; \
+ dw += 32; \
+ da += 32; \
+ } \
+ *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row_base, bias_row_bytes, c); \
+ if (full_quad || r + 1 < n_rows) { \
+ *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row_base, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 2 < n_rows) { \
+ *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row_base, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 3 < n_rows) { \
+ *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row_base, bias_row_bytes, c); \
+ } \
+} \
+static inline void w8a8_sm_eval_tile_quad_chunked_##SFX( \
+ const uint8_t * restrict tile_base, \
+ const float * restrict dw_base, \
+ const float * restrict act_scales_blk_base, \
+ size_t group_stride, \
+ uint32_t mc_pad, \
+ uint32_t n_groups, \
+ size_t lane, \
+ uint32_t (*da_ptr)[32], \
+ HVX_Vector sign_80, \
+ const uint8_t * restrict bias_row_base, \
+ size_t c, \
+ size_t bias_row_bytes, \
+ uint32_t n_rows, \
+ size_t r, \
+ bool full_quad, \
+ HVX_Vector * v_out0, \
+ HVX_Vector * v_out1, \
+ HVX_Vector * v_out2, \
+ HVX_Vector * v_out3) { \
+ (void) bias_row_base; \
+ (void) bias_row_bytes; \
+ const size_t c0 = c >> 5; \
+ const uint8_t * tp = tile_base + c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const float * dw = dw_base + c0 * (size_t) n_groups * 32; \
+ HVX_Vector v_acc0_qf = Q6_V_vzero(); \
+ HVX_Vector v_acc1_qf = Q6_V_vzero(); \
+ HVX_Vector v_acc2_qf = Q6_V_vzero(); \
+ HVX_Vector v_acc3_qf = Q6_V_vzero(); \
+ for (uint32_t g_base = 0; g_base < n_groups; g_base += 16u) { \
+ const uint32_t g_cnt = hex_smin(n_groups - g_base, 16u); \
+ da_ptr = stage_act_scales_to_l1d(da_ptr, act_scales_blk_base + (size_t) g_base * mc_pad, mc_pad, g_cnt); \
+ const uint32_t * da = &da_ptr[0][lane]; \
+ for (uint32_t gi = 0; gi < g_cnt; ++gi) { \
+ const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); \
+ const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HTP_MM_HMX_TILE_SIZE); \
+ const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) dw); \
+ HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); \
+ HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); \
+ HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); \
+ HVX_Vector v_f32_0 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)); \
+ HVX_Vector v_f32_1 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)); \
+ HVX_Vector v_f32_2 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)); \
+ HVX_Vector v_f32_3 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)); \
+ v_acc0_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc0_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_0, da[0]), v_dw_qf)); \
+ v_acc1_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc1_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_1, da[1]), v_dw_qf)); \
+ v_acc2_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc2_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_2, da[2]), v_dw_qf)); \
+ v_acc3_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc3_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_3, da[3]), v_dw_qf)); \
+ tp += group_stride; \
+ dw += 32; \
+ da += 32; \
+ } \
+ } \
+ *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row_base, bias_row_bytes, c); \
+ if (full_quad || r + 1 < n_rows) { \
+ *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row_base, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 2 < n_rows) { \
+ *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row_base, bias_row_bytes, c); \
+ } \
+ if (full_quad || r + 3 < n_rows) { \
+ *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row_base, bias_row_bytes, c); \
+ } \
+}
+
+DEFINE_W8A8_EVAL_TILE_QUAD(none, HMX_INT_FIN_ROW_NONE)
+DEFINE_W8A8_EVAL_TILE_QUAD(f16, HMX_INT_FIN_ROW_F16)
+DEFINE_W8A8_EVAL_TILE_QUAD(f32, HMX_INT_FIN_ROW_F32)
+
+#define HMX_INT_STORE_VEC_nt(ptr, val) hvx_vmem_store_nt((ptr), (val))
+#define HMX_INT_STORE_VEC_u(ptr, val) (hvx_vmemu((ptr)) = (val))
+
+#define W8A8_COL_FULL_QUAD_1G_FP32(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1, v2, v3; \
+ w8a8_sm_eval_tile_quad_1g_##SFX(tile_base, dw_base, c, da, \
+ bias_row0, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, v0); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, v1); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, v2); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, v3); \
+ }
+
+#define W8A8_COL_STEP_1G_FP32(SFX, STORE_MODE) \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_1G_FP32(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_##SFX(tile_base, dw_base, c, da, \
+ bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row0 + c + 0 * dst_stride) = v0; \
+ if (r + 1 < n_rows) hvx_vmemu(out_row0 + c + 1 * dst_stride) = v1; \
+ if (r + 2 < n_rows) hvx_vmemu(out_row0 + c + 2 * dst_stride) = v2; \
+ if (r + 3 < n_rows) hvx_vmemu(out_row0 + c + 3 * dst_stride) = v3; \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_##SFX(tile_base, dw_base, c, da, \
+ bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, v0); \
+ if (r + 1 < n_rows) hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, v1); \
+ if (r + 2 < n_rows) hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, v2); \
+ if (r + 3 < n_rows) hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, v3); \
+ }
+
+#define W8A8_COL_FULL_QUAD_2G_FP32(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1, v2, v3; \
+ w8a8_sm_eval_tile_quad_2g_##SFX(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ bias_row0, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, v0); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, v1); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, v2); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, v3); \
+ }
+
+#define W8A8_COL_STEP_2G_FP32(SFX, STORE_MODE) \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_2G_FP32(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_##SFX(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row0 + c + 0 * dst_stride) = v0; \
+ if (r + 1 < n_rows) hvx_vmemu(out_row0 + c + 1 * dst_stride) = v1; \
+ if (r + 2 < n_rows) hvx_vmemu(out_row0 + c + 2 * dst_stride) = v2; \
+ if (r + 3 < n_rows) hvx_vmemu(out_row0 + c + 3 * dst_stride) = v3; \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_##SFX(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, v0); \
+ if (r + 1 < n_rows) hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, v1); \
+ if (r + 2 < n_rows) hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, v2); \
+ if (r + 3 < n_rows) hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, v3); \
+ }
+
+#define W8A8_COL_FULL_QUAD_NG_FP32(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1, v2, v3; \
+ w8a8_sm_eval_tile_quad_ng_##SFX(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ bias_row_base, c, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, v0); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, v1); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, v2); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, v3); \
+ }
+
+#define W8A8_COL_STEP_NG_FP32(SFX, STORE_MODE) \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_NG_FP32(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_##SFX(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row_base + c + 0 * dst_stride) = v0; \
+ if (r + 1 < n_rows) hvx_vmemu(out_row_base + c + 1 * dst_stride) = v1; \
+ if (r + 2 < n_rows) hvx_vmemu(out_row_base + c + 2 * dst_stride) = v2; \
+ if (r + 3 < n_rows) hvx_vmemu(out_row_base + c + 3 * dst_stride) = v3; \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_##SFX(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, v0); \
+ if (r + 1 < n_rows) hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, v1); \
+ if (r + 2 < n_rows) hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, v2); \
+ if (r + 3 < n_rows) hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, v3); \
+ }
+
+#define W8A8_COL_FULL_QUAD_CHUNKED_FP32(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1, v2, v3; \
+ w8a8_sm_eval_tile_quad_chunked_##SFX(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, \
+ bias_row_base, c, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, v0); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, v1); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, v2); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, v3); \
+ }
+
+#define W8A8_COL_STEP_CHUNKED_FP32(SFX, STORE_MODE) \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_CHUNKED_FP32(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_##SFX(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, \
+ bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row_base + c + 0 * dst_stride) = v0; \
+ if (r + 1 < n_rows) hvx_vmemu(out_row_base + c + 1 * dst_stride) = v1; \
+ if (r + 2 < n_rows) hvx_vmemu(out_row_base + c + 2 * dst_stride) = v2; \
+ if (r + 3 < n_rows) hvx_vmemu(out_row_base + c + 3 * dst_stride) = v3; \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_##SFX(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, \
+ bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, v0); \
+ if (r + 1 < n_rows) hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, v1); \
+ if (r + 2 < n_rows) hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, v2); \
+ if (r + 3 < n_rows) hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, v3); \
+ }
+
+#define W8A8_COL_FULL_QUAD_1G_FP16(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \
+ HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, NULL, 0, n_rows, r, true, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, NULL, 0, n_rows, r, true, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c)); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c)); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c)); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c)); \
+ }
+
+#define W8A8_COL_STEP_1G_FP16(SFX, STORE_MODE) \
+ (void) bias_row0; \
+ (void) bias_row_bytes; \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_1G_FP16(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, NULL, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, NULL, 0, n_rows, r, false, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row0 + c + 0 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c); \
+ if (r + 1 < n_rows) { \
+ hvx_vmemu(out_row0 + c + 1 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vmemu(out_row0 + c + 2 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vmemu(out_row0 + c + 3 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c); \
+ } \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, NULL, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, NULL, 0, n_rows, r, false, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c, valid_c)); \
+ if (r + 1 < n_rows) { \
+ hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c, valid_c)); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c, valid_c)); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c, valid_c)); \
+ } \
+ }
+
+#define W8A8_COL_FULL_QUAD_2G_FP16(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \
+ HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, NULL, 0, n_rows, r, true, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, NULL, 0, n_rows, r, true,\
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c));\
+ }
+
+#define W8A8_COL_STEP_2G_FP16(SFX, STORE_MODE) \
+ (void) bias_row0; \
+ (void) bias_row_bytes; \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_2G_FP16(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, NULL, 0, n_rows, r, false,\
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, NULL, 0, n_rows, r, \
+ false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row0 + c + 0 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c); \
+ if (r + 1 < n_rows) { \
+ hvx_vmemu(out_row0 + c + 1 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vmemu(out_row0 + c + 2 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vmemu(out_row0 + c + 3 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c); \
+ } \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, NULL, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, NULL, 0, n_rows, r, \
+ false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c, valid_c)); \
+ if (r + 1 < n_rows) { \
+ hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c, valid_c)); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c, valid_c)); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c, valid_c)); \
+ } \
+ }
+
+#define W8A8_COL_FULL_QUAD_NG_FP16(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \
+ HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c, 0, n_rows, r, true, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c + 32, 0, n_rows, r, true, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c));\
+ }
+
+#define W8A8_COL_STEP_NG_FP16(SFX, STORE_MODE) \
+ (void) bias_row_base; \
+ (void) bias_row_bytes; \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_NG_FP16(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row_base + c + 0 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c); \
+ if (r + 1 < n_rows) { \
+ hvx_vmemu(out_row_base + c + 1 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vmemu(out_row_base + c + 2 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vmemu(out_row_base + c + 3 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c); \
+ } \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c, valid_c)); \
+ if (r + 1 < n_rows) { \
+ hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c, valid_c)); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c, valid_c)); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c, valid_c)); \
+ } \
+ }
+
+#define W8A8_COL_FULL_QUAD_CHUNKED_FP16(SFX, STORE_MODE) \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \
+ HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, true, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, true, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c));\
+ HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c));\
+ }
+
+#define W8A8_COL_STEP_CHUNKED_FP16(SFX, STORE_MODE) \
+ (void) bias_row_base; \
+ (void) bias_row_bytes; \
+ if (r + 3 < n_rows) { \
+ W8A8_COL_FULL_QUAD_CHUNKED_FP16(SFX, STORE_MODE) \
+ } else { \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, false, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row_base + c + 0 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c); \
+ if (r + 1 < n_rows) { \
+ hvx_vmemu(out_row_base + c + 1 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vmemu(out_row_base + c + 2 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vmemu(out_row_base + c + 3 * dst_stride) = \
+ HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c); \
+ } \
+ } \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, false, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c, valid_c)); \
+ if (r + 1 < n_rows) { \
+ hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c, valid_c)); \
+ } \
+ if (r + 2 < n_rows) { \
+ hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c, valid_c)); \
+ } \
+ if (r + 3 < n_rows) { \
+ hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, \
+ HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c, valid_c)); \
+ } \
+ }
+
+#define DEFINE_W8A8_COL_CHUNK_MODE(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX, STORE_MODE) \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_1g_##SFX##_##STORE_MODE( \
+ void * restrict dst_ptr, \
+ const void * restrict bias, \
+ const void * restrict vtcm_src_void, \
+ const float * restrict vtcm_act_scales, \
+ const float * restrict vtcm_weight_scales, \
+ uint32_t start_row, \
+ uint32_t n_rows, \
+ uint32_t mc_pad, \
+ uint32_t c_first, \
+ uint32_t c_len, \
+ uint32_t total_n_cols, \
+ uint32_t n_groups, \
+ uint32_t dst_stride, \
+ uint32_t bias_stride, \
+ uint32_t dst_cols, \
+ size_t bias_elem_size) { \
+ (void) mc_pad; \
+ (void) n_groups; \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \
+ const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t c0_first = c_first / 32; \
+ const size_t limit_c = hex_smin(c_len, dst_cols); \
+ const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \
+ uint32_t da_buf[1][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, vtcm_act_scales + (r_blk << 5), 0, 1); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint32_t * da = &da_ptr[0][lane]; \
+ const uint8_t * tile_base = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ const float * dw_base = vtcm_weight_scales + c0_first * 32; \
+ DST_T * out_row0 = dst + r * dst_stride; \
+ const uint8_t * bias_row0 = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \
+ STEP_1G(SFX, STORE_MODE) \
+ } \
+ r_base = r_end; \
+ } \
+} \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_2g_##SFX##_##STORE_MODE( \
+ void * restrict dst_ptr, \
+ const void * restrict bias, \
+ const void * restrict vtcm_src_void, \
+ const float * restrict vtcm_act_scales, \
+ const float * restrict vtcm_weight_scales, \
+ uint32_t start_row, \
+ uint32_t n_rows, \
+ uint32_t mc_pad, \
+ uint32_t c_first, \
+ uint32_t c_len, \
+ uint32_t total_n_cols, \
+ uint32_t n_groups, \
+ uint32_t dst_stride, \
+ uint32_t bias_stride, \
+ uint32_t dst_cols, \
+ size_t bias_elem_size) { \
+ (void) n_groups; \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \
+ const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \
+ const size_t n_row_tiles_64 = mc_pad / 64; \
+ const size_t group_stride = n_row_tiles_64 * total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t c0_first = c_first / 32; \
+ const size_t limit_c = hex_smin(c_len, dst_cols); \
+ const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \
+ uint32_t da_buf[2][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, vtcm_act_scales + (r_blk << 5), mc_pad, 2); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint32_t * da0 = &da_ptr[0][lane]; \
+ const uint32_t * da1 = &da_ptr[1][lane]; \
+ const uint8_t * tile_base0 = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ const uint8_t * tile_base1 = tile_base0 + group_stride; \
+ const float * dw_base = vtcm_weight_scales + c0_first * 64; \
+ DST_T * out_row0 = dst + r * dst_stride; \
+ const uint8_t * bias_row0 = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \
+ STEP_2G(SFX, STORE_MODE) \
+ } \
+ r_base = r_end; \
+ } \
+} \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_ng_##SFX##_##STORE_MODE( \
+ void * restrict dst_ptr, \
+ const void * restrict bias, \
+ const void * restrict vtcm_src_void, \
+ const float * restrict vtcm_act_scales, \
+ const float * restrict vtcm_weight_scales, \
+ uint32_t start_row, \
+ uint32_t n_rows, \
+ uint32_t mc_pad, \
+ uint32_t c_first, \
+ uint32_t c_len, \
+ uint32_t total_n_cols, \
+ uint32_t n_groups, \
+ uint32_t dst_stride, \
+ uint32_t bias_stride, \
+ uint32_t dst_cols, \
+ size_t bias_elem_size) { \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \
+ const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \
+ const size_t n_row_tiles_64 = mc_pad / 64; \
+ const size_t group_stride = n_row_tiles_64 * total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t c0_first = c_first / 32; \
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \
+ const size_t limit_c = hex_smin(c_len, dst_cols); \
+ const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \
+ const float * dw_base = vtcm_weight_scales + c0_first * (size_t) n_groups * 32; \
+ uint32_t da_buf[16][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, vtcm_act_scales + (r_blk << 5), mc_pad, n_groups); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint8_t * tile_base = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + \
+ rg * 128; \
+ const uint32_t * da_quad_base = &da_ptr[0][lane]; \
+ DST_T * out_row_base = dst + r * dst_stride; \
+ const uint8_t * bias_row_base = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \
+ STEP_NG(SFX, STORE_MODE) \
+ } \
+ r_base = r_end; \
+ } \
+} \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_chunked_##SFX##_##STORE_MODE( \
+ void * restrict dst_ptr, \
+ const void * restrict bias, \
+ const void * restrict vtcm_src_void, \
+ const float * restrict vtcm_act_scales, \
+ const float * restrict vtcm_weight_scales, \
+ uint32_t start_row, \
+ uint32_t n_rows, \
+ uint32_t mc_pad, \
+ uint32_t c_first, \
+ uint32_t c_len, \
+ uint32_t total_n_cols, \
+ uint32_t n_groups, \
+ uint32_t dst_stride, \
+ uint32_t bias_stride, \
+ uint32_t dst_cols, \
+ size_t bias_elem_size) { \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \
+ const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \
+ const size_t n_row_tiles_64 = mc_pad / 64; \
+ const size_t group_stride = n_row_tiles_64 * total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t c0_first = c_first / 32; \
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \
+ const size_t limit_c = hex_smin(c_len, dst_cols); \
+ const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \
+ const float * dw_base = vtcm_weight_scales + c0_first * (size_t) n_groups * 32; \
+ uint32_t da_buf[16][32] __attribute__((aligned(128))); \
+ uint32_t (*da_ptr)[32] = da_buf; \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ const float * act_scales_blk_base = vtcm_act_scales + (r_blk << 5); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint8_t * tile_base = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ DST_T * out_row_base = dst + r * dst_stride; \
+ const uint8_t * bias_row_base = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \
+ STEP_CHUNKED(SFX, STORE_MODE) \
+ } \
+ r_base = r_end; \
+ } \
+}
+
+#define DEFINE_W8A8_COL_CHUNK(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX) \
+ DEFINE_W8A8_COL_CHUNK_MODE(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX, nt) \
+ DEFINE_W8A8_COL_CHUNK_MODE(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX, u)
+
+DEFINE_W8A8_COL_CHUNK(fp32, float, ~31u, W8A8_COL_STEP_1G_FP32, W8A8_COL_STEP_2G_FP32, W8A8_COL_STEP_NG_FP32, W8A8_COL_STEP_CHUNKED_FP32, none)
+DEFINE_W8A8_COL_CHUNK(fp32, float, ~31u, W8A8_COL_STEP_1G_FP32, W8A8_COL_STEP_2G_FP32, W8A8_COL_STEP_NG_FP32, W8A8_COL_STEP_CHUNKED_FP32, f16)
+DEFINE_W8A8_COL_CHUNK(fp32, float, ~31u, W8A8_COL_STEP_1G_FP32, W8A8_COL_STEP_2G_FP32, W8A8_COL_STEP_NG_FP32, W8A8_COL_STEP_CHUNKED_FP32, f32)
+DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2G_FP16, W8A8_COL_STEP_NG_FP16, W8A8_COL_STEP_CHUNKED_FP16, none)
+DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2G_FP16, W8A8_COL_STEP_NG_FP16, W8A8_COL_STEP_CHUNKED_FP16, f16)
+DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2G_FP16, W8A8_COL_STEP_NG_FP16, W8A8_COL_STEP_CHUNKED_FP16, f32)
+
+#define W8A8_SCAT_STEP_1G_FP32 \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \
+ NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row0 + c) = v0; \
+ if (out_row1) hvx_vmemu(out_row1 + c) = v1; \
+ if (out_row2) hvx_vmemu(out_row2 + c) = v2; \
+ if (out_row3) hvx_vmemu(out_row3 + c) = v3; \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \
+ NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \
+ }
+
+#define W8A8_SCAT_STEP_2G_FP32 \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row0 + c) = v0; \
+ if (out_row1) hvx_vmemu(out_row1 + c) = v1; \
+ if (out_row2) hvx_vmemu(out_row2 + c) = v2; \
+ if (out_row3) hvx_vmemu(out_row3 + c) = v3; \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \
+ }
+
+#define W8A8_SCAT_STEP_NG_FP32 \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, \
+ sign_80, NULL, c, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row0 + c) = v0; \
+ if (out_row1) hvx_vmemu(out_row1 + c) = v1; \
+ if (out_row2) hvx_vmemu(out_row2 + c) = v2; \
+ if (out_row3) hvx_vmemu(out_row3 + c) = v3; \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, \
+ sign_80, NULL, c, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \
+ }
+
+#define W8A8_SCAT_STEP_CHUNKED_FP32 \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \
+ &v0, &v1, &v2, &v3); \
+ hvx_vmemu(out_row0 + c) = v0; \
+ if (out_row1) hvx_vmemu(out_row1 + c) = v1; \
+ if (out_row2) hvx_vmemu(out_row2 + c) = v2; \
+ if (out_row3) hvx_vmemu(out_row3 + c) = v3; \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_bytes = (limit_c - c) * sizeof(float); \
+ HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \
+ &v0, &v1, &v2, &v3); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \
+ }
+
+#define W8A8_SCAT_STEP_1G_FP16 \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \
+ NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, \
+ NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \
+ NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, \
+ NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \
+ }
+
+#define W8A8_SCAT_STEP_2G_FP16 \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, \
+ NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \
+ NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, \
+ NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \
+ }
+
+#define W8A8_SCAT_STEP_NG_FP16 \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \
+ NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \
+ }
+
+#define W8A8_SCAT_STEP_CHUNKED_FP16 \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, false, \
+ &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t valid_c = limit_c - c; \
+ const size_t valid_bytes = valid_c * sizeof(__fp16); \
+ HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \
+ HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \
+ &v0_lo, &v1_lo, &v2_lo, &v3_lo); \
+ if (valid_c > 32) { \
+ w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \
+ n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, \
+ false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \
+ } \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \
+ }
+
+typedef void (*int_output_col_chunk_fn_t)(
+ void * restrict dst,
+ const void * restrict bias,
+ const void * restrict vtcm_src,
+ const float * restrict vtcm_act_scales,
+ const float * restrict vtcm_weight_scales,
+ uint32_t start_row,
+ uint32_t n_rows,
+ uint32_t mc_pad,
+ uint32_t c_first,
+ uint32_t c_len,
+ uint32_t total_n_cols,
+ uint32_t n_groups,
+ uint32_t dst_stride,
+ uint32_t bias_stride,
+ uint32_t dst_cols,
+ size_t bias_elem_size);
+
+#define HMX_SELECT_INT_COL_FN(DST_SFX, GRP_SFX, bias, bias_f16, dst_aligned_nt) \
+ ((dst_aligned_nt) \
+ ? (!(bias) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_none_nt \
+ : ((bias_f16) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f16_nt \
+ : transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f32_nt)) \
+ : (!(bias) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_none_u \
+ : ((bias_f16) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f16_u \
+ : transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f32_u)))
+
+static inline int_output_col_chunk_fn_t resolve_int_output_col_chunk_fn(
+ uint32_t n_groups,
+ size_t dst_elem_size,
+ const void * bias,
+ size_t bias_elem_size,
+ bool dst_aligned_nt) {
+ const bool dst_f16 = (dst_elem_size == sizeof(__fp16));
+ const bool bias_f16 = (bias_elem_size == sizeof(__fp16));
+ if (dst_f16) {
+ if (n_groups <= 1u) {
+ return HMX_SELECT_INT_COL_FN(fp16, 1g, bias, bias_f16, dst_aligned_nt);
+ }
+ if (n_groups == 2u) {
+ return HMX_SELECT_INT_COL_FN(fp16, 2g, bias, bias_f16, dst_aligned_nt);
+ }
+ if (n_groups <= 16u) {
+ return HMX_SELECT_INT_COL_FN(fp16, ng, bias, bias_f16, dst_aligned_nt);
+ }
+ return HMX_SELECT_INT_COL_FN(fp16, chunked, bias, bias_f16, dst_aligned_nt);
+ }
+ if (n_groups <= 1u) {
+ return HMX_SELECT_INT_COL_FN(fp32, 1g, bias, bias_f16, dst_aligned_nt);
+ }
+ if (n_groups == 2u) {
+ return HMX_SELECT_INT_COL_FN(fp32, 2g, bias, bias_f16, dst_aligned_nt);
+ }
+ if (n_groups <= 16u) {
+ return HMX_SELECT_INT_COL_FN(fp32, ng, bias, bias_f16, dst_aligned_nt);
+ }
+ return HMX_SELECT_INT_COL_FN(fp32, chunked, bias, bias_f16, dst_aligned_nt);
+}
+
+// --- Fused W8A8 GLU Epilogue (paired gate/up -> f(gate) * up) ---
+
+typedef struct {
+ const float * act_scales_blk_base;
+ uint32_t (*da_ptr)[32];
+ size_t group_stride;
+ uint32_t mc_pad;
+ uint32_t n_groups;
+ uint32_t lane;
+} w8a8_sm_chunked_eval_args_t;
+
+// Thin noinline wrappers around w8a8_sm_eval_tile_quad_*_none to bound live ranges in GLU loops.
+static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_quad(
+ const uint8_t * restrict tp,
+ const float * restrict dwp,
+ const uint32_t * restrict da0,
+ HVX_Vector * restrict out) {
+ w8a8_sm_eval_tile_quad_1g_none(tp, dwp, 0, da0, NULL, 0, 4, 0, true, &out[0], &out[1], &out[2], &out[3]);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_pair_hf(
+ const uint8_t * restrict tp,
+ const float * restrict dwp,
+ const uint32_t * restrict da0,
+ HVX_Vector * restrict out_hf) {
+ HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3;
+ w8a8_sm_eval_tile_quad_1g_none(tp, dwp, 0, da0, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3);
+ w8a8_sm_eval_tile_quad_1g_none(tp, dwp, 32, da0, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3);
+ out_hf[0] = hmx_pack_f32_to_f16_clamped(lo0, hi0);
+ out_hf[1] = hmx_pack_f32_to_f16_clamped(lo1, hi1);
+ out_hf[2] = hmx_pack_f32_to_f16_clamped(lo2, hi2);
+ out_hf[3] = hmx_pack_f32_to_f16_clamped(lo3, hi3);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_strip_hf(
+ const uint8_t * restrict tp,
+ const float * restrict dwp,
+ const uint32_t * restrict da0,
+ __fp16 * restrict dst,
+ size_t dst_stride,
+ size_t n_pairs) {
+ _Pragma("clang loop unroll(disable)")
+ for (size_t p = 0; p < n_pairs; ++p) {
+ const size_t c = p << 6;
+ HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3;
+ w8a8_sm_eval_tile_quad_1g_none(tp, dwp, c, da0, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3);
+ w8a8_sm_eval_tile_quad_1g_none(tp, dwp, c + 32, da0, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3);
+ hvx_vmem(dst + c + 0 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo0, hi0);
+ hvx_vmem(dst + c + 1 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo1, hi1);
+ hvx_vmem(dst + c + 2 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo2, hi2);
+ hvx_vmem(dst + c + 3 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo3, hi3);
+ }
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_quad(
+ const uint8_t * restrict tp0,
+ const uint8_t * restrict tp1,
+ const float * restrict dwp,
+ const uint32_t * restrict da0,
+ const uint32_t * restrict da1,
+ HVX_Vector * restrict out) {
+ w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, 0, da0, da1, NULL, 0, 4, 0, true, &out[0], &out[1], &out[2], &out[3]);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_pair_hf(
+ const uint8_t * restrict tp0,
+ const uint8_t * restrict tp1,
+ const float * restrict dwp,
+ const uint32_t * restrict da0,
+ const uint32_t * restrict da1,
+ HVX_Vector * restrict out_hf) {
+ HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3;
+ w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, 0, da0, da1, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3);
+ w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, 32, da0, da1, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3);
+ out_hf[0] = hmx_pack_f32_to_f16_clamped(lo0, hi0);
+ out_hf[1] = hmx_pack_f32_to_f16_clamped(lo1, hi1);
+ out_hf[2] = hmx_pack_f32_to_f16_clamped(lo2, hi2);
+ out_hf[3] = hmx_pack_f32_to_f16_clamped(lo3, hi3);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_strip_hf(
+ const uint8_t * restrict tp0,
+ const uint8_t * restrict tp1,
+ const float * restrict dwp,
+ const uint32_t * restrict da0,
+ const uint32_t * restrict da1,
+ __fp16 * restrict dst,
+ size_t dst_stride,
+ size_t n_pairs) {
+ _Pragma("clang loop unroll(disable)")
+ for (size_t p = 0; p < n_pairs; ++p) {
+ const size_t c = p << 6;
+ HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3;
+ w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, c, da0, da1, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3);
+ w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, c + 32, da0, da1, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3);
+ hvx_vmem(dst + c + 0 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo0, hi0);
+ hvx_vmem(dst + c + 1 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo1, hi1);
+ hvx_vmem(dst + c + 2 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo2, hi2);
+ hvx_vmem(dst + c + 3 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo3, hi3);
+ }
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_ng_quad(
+ const uint8_t * restrict tp,
+ const float * restrict dw,
+ size_t group_stride,
+ uint32_t n_groups,
+ const uint32_t * restrict da,
+ HVX_Vector * restrict out) {
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80);
+ w8a8_sm_eval_tile_quad_ng_none(tp, dw, group_stride, n_groups, da, sign_80, NULL, 0, 0, 4, 0, true,
+ &out[0], &out[1], &out[2], &out[3]);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_eval_chunked_quad(
+ const uint8_t * restrict tp,
+ const float * restrict dw,
+ const w8a8_sm_chunked_eval_args_t * args,
+ HVX_Vector * restrict out) {
+ const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80);
+ w8a8_sm_eval_tile_quad_chunked_none(tp, dw, args->act_scales_blk_base, args->group_stride, args->mc_pad,
+ args->n_groups, args->lane, args->da_ptr, sign_80, NULL, 0, 0, 4, 0, true,
+ &out[0], &out[1], &out[2], &out[3]);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_pack_quad_hf(const HVX_Vector * restrict q, HVX_Vector * restrict out_hf) {
+ out_hf[0] = hmx_pack_f32_to_f16_clamped(q[0], q[4]);
+ out_hf[1] = hmx_pack_f32_to_f16_clamped(q[1], q[5]);
+ out_hf[2] = hmx_pack_f32_to_f16_clamped(q[2], q[6]);
+ out_hf[3] = hmx_pack_f32_to_f16_clamped(q[3], q[7]);
+}
+
+static __attribute__((noinline)) void w8a8_sm_glu_pack_and_store_tail_fp16(
+ const hmx_output_glu_state_t * st,
+ __fp16 * restrict dst,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_q,
+ const HVX_Vector * restrict u_q,
+ uint32_t valid_rows,
+ size_t valid_c) {
+ HVX_Vector g_hf[4] __attribute__((aligned(128)));
+ HVX_Vector u_hf[4] __attribute__((aligned(128)));
+ if (valid_c > 32) {
+ g_hf[0] = hmx_pack_f32_to_f16_clamped(g_q[0], g_q[4]);
+ g_hf[1] = hmx_pack_f32_to_f16_clamped(g_q[1], g_q[5]);
+ g_hf[2] = hmx_pack_f32_to_f16_clamped(g_q[2], g_q[6]);
+ g_hf[3] = hmx_pack_f32_to_f16_clamped(g_q[3], g_q[7]);
+ u_hf[0] = hmx_pack_f32_to_f16_clamped(u_q[0], u_q[4]);
+ u_hf[1] = hmx_pack_f32_to_f16_clamped(u_q[1], u_q[5]);
+ u_hf[2] = hmx_pack_f32_to_f16_clamped(u_q[2], u_q[6]);
+ u_hf[3] = hmx_pack_f32_to_f16_clamped(u_q[3], u_q[7]);
+ } else {
+ const HVX_Vector z = Q6_V_vzero();
+ g_hf[0] = hmx_pack_f32_to_f16_clamped(g_q[0], z);
+ g_hf[1] = hmx_pack_f32_to_f16_clamped(g_q[1], z);
+ g_hf[2] = hmx_pack_f32_to_f16_clamped(g_q[2], z);
+ g_hf[3] = hmx_pack_f32_to_f16_clamped(g_q[3], z);
+ u_hf[0] = hmx_pack_f32_to_f16_clamped(u_q[0], z);
+ u_hf[1] = hmx_pack_f32_to_f16_clamped(u_q[1], z);
+ u_hf[2] = hmx_pack_f32_to_f16_clamped(u_q[2], z);
+ u_hf[3] = hmx_pack_f32_to_f16_clamped(u_q[3], z);
+ }
+ const uint32_t valid_bytes = (uint32_t) (valid_c * sizeof(__fp16));
+ st->store_tail_fn(dst, dst_stride, g_hf, u_hf, (valid_rows << 16) | valid_bytes);
+}
+
+#define W8A8_GLU_EVAL_TILE_1G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \
+ w8a8_sm_glu_eval_1g_quad((tp_g), (dw_g), da0, (out_g)); \
+ w8a8_sm_glu_eval_1g_quad((tp_u), (dw_u), da0, (out_u));
+
+#define W8A8_GLU_EVAL_TILE_2G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \
+ w8a8_sm_glu_eval_2g_quad((tp_g), (tp_g) + group_stride, (dw_g), da0, da1, (out_g)); \
+ w8a8_sm_glu_eval_2g_quad((tp_u), (tp_u) + group_stride, (dw_u), da0, da1, (out_u));
+
+#define W8A8_GLU_EVAL_TILE_NG(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \
+ w8a8_sm_glu_eval_ng_quad((tp_g), (dw_g), group_stride, n_groups, da_quad_base, (out_g)); \
+ w8a8_sm_glu_eval_ng_quad((tp_u), (dw_u), group_stride, n_groups, da_quad_base, (out_u));
+
+#define W8A8_GLU_EVAL_TILE_CHK(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \
+ w8a8_sm_glu_eval_chunked_quad((tp_g), (dw_g), &cargs, (out_g)); \
+ w8a8_sm_glu_eval_chunked_quad((tp_u), (dw_u), &cargs, (out_u));
+
+#define W8A8_GLU_EVAL_PAIR_1G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \
+ w8a8_sm_glu_eval_1g_pair_hf((tp_g), (dw_g), da0, (out_g)); \
+ w8a8_sm_glu_eval_1g_pair_hf((tp_u), (dw_u), da0, (out_u));
+
+#define W8A8_GLU_EVAL_PAIR_2G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \
+ w8a8_sm_glu_eval_2g_pair_hf((tp_g), (tp_g) + group_stride, (dw_g), da0, da1, (out_g)); \
+ w8a8_sm_glu_eval_2g_pair_hf((tp_u), (tp_u) + group_stride, (dw_u), da0, da1, (out_u));
+
+#define W8A8_GLU_EVAL_STRIP_1G(tp_g, tp_u, dw_g, dw_u, dst_g, dst_s, dst_u, u_s, n_p) \
+ w8a8_sm_glu_eval_1g_strip_hf((tp_g), (dw_g), da0, (dst_g), (dst_s), (n_p)); \
+ w8a8_sm_glu_eval_1g_strip_hf((tp_u), (dw_u), da0, (dst_u), (u_s), (n_p));
+
+#define W8A8_GLU_EVAL_STRIP_2G(tp_g, tp_u, dw_g, dw_u, dst_g, dst_s, dst_u, u_s, n_p) \
+ w8a8_sm_glu_eval_2g_strip_hf((tp_g), (tp_g) + group_stride, (dw_g), da0, da1, (dst_g), (dst_s), (n_p)); \
+ w8a8_sm_glu_eval_2g_strip_hf((tp_u), (tp_u) + group_stride, (dw_u), da0, da1, (dst_u), (u_s), (n_p));
+
+#define W8A8_GLU_TAIL_FP16(EVAL_TILE, DW_STRIDE_ELEMS) \
+ if (limit_c_aligned < limit_c) { \
+ HVX_Vector g_q[8] __attribute__((aligned(128))); \
+ HVX_Vector u_q[8] __attribute__((aligned(128))); \
+ const size_t c = limit_c_aligned; \
+ const size_t c0 = c >> 5; \
+ const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \
+ const size_t valid_c = limit_c - c; \
+ EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \
+ if (valid_c > 32) { \
+ const size_t off1 = off0 + 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw1 = dw0 + (DW_STRIDE_ELEMS); \
+ EVAL_TILE(g_base + off1, u_base + off1, dw_g_base + dw1, dw_u_base + dw1, &g_q[4], &u_q[4]) \
+ } \
+ w8a8_sm_glu_pack_and_store_tail_fp16(st, out_row0 + c, dst_stride, g_q, u_q, valid_rows, valid_c); \
+ }
+
+#define W8A8_GLU_LOOP_FP16_PAIR(EVAL_STRIP, EVAL_PAIR, EVAL_TILE, DW_STRIDE_ELEMS) \
+ { \
+ const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, (size_t) n_rows - r); \
+ if (valid_rows == 4u) { \
+ __fp16 u_buf[4 * 256] __attribute__((aligned(128))); \
+ _Pragma("clang loop unroll(disable)") \
+ for (size_t c = 0; c < limit_c_aligned; c += 256) { \
+ const size_t n_pairs = hex_smin((limit_c_aligned - c) >> 6, (size_t) 4u); \
+ const size_t c0 = c >> 5; \
+ const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \
+ EVAL_STRIP(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, \
+ out_row0 + c, dst_stride, u_buf, 256, n_pairs) \
+ st->store_strip_fn(out_row0 + c, dst_stride, u_buf, 256, n_pairs); \
+ } \
+ } else { \
+ HVX_Vector g_hf[4] __attribute__((aligned(128))); \
+ HVX_Vector u_hf[4] __attribute__((aligned(128))); \
+ _Pragma("clang loop unroll(disable)") \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ const size_t c0 = c >> 5; \
+ const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \
+ EVAL_PAIR(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, g_hf, u_hf) \
+ st->store_quad_fn(out_row0 + c, dst_stride, g_hf, u_hf, valid_rows); \
+ } \
+ } \
+ W8A8_GLU_TAIL_FP16(EVAL_TILE, DW_STRIDE_ELEMS) \
+ }
+
+#define W8A8_GLU_LOOP_FP16_GEN(EVAL_TILE, DW_STRIDE_ELEMS) \
+ { \
+ const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, (size_t) n_rows - r); \
+ HVX_Vector g_q[8] __attribute__((aligned(128))); \
+ HVX_Vector u_q[8] __attribute__((aligned(128))); \
+ HVX_Vector g_hf[4] __attribute__((aligned(128))); \
+ HVX_Vector u_hf[4] __attribute__((aligned(128))); \
+ _Pragma("clang loop unroll(disable)") \
+ for (size_t c = 0; c < limit_c_aligned; c += 64) { \
+ const size_t c0 = c >> 5; \
+ const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t off1 = off0 + 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \
+ const size_t dw1 = dw0 + (DW_STRIDE_ELEMS); \
+ EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \
+ EVAL_TILE(g_base + off1, u_base + off1, dw_g_base + dw1, dw_u_base + dw1, &g_q[4], &u_q[4]) \
+ w8a8_sm_glu_pack_quad_hf(g_q, g_hf); \
+ w8a8_sm_glu_pack_quad_hf(u_q, u_hf); \
+ st->store_quad_fn(out_row0 + c, dst_stride, g_hf, u_hf, valid_rows); \
+ } \
+ W8A8_GLU_TAIL_FP16(EVAL_TILE, DW_STRIDE_ELEMS) \
+ }
+
+#define W8A8_GLU_LOOP_FP32(EVAL_TILE, DW_STRIDE_ELEMS) \
+ { \
+ const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, (size_t) n_rows - r); \
+ HVX_Vector g_q[4] __attribute__((aligned(128))); \
+ HVX_Vector u_q[4] __attribute__((aligned(128))); \
+ _Pragma("clang loop unroll(disable)") \
+ for (size_t c = 0; c < limit_c_aligned; c += 32) { \
+ const size_t c0 = c >> 5; \
+ const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \
+ EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \
+ st->store_quad_fn(out_row0 + c, dst_stride, g_q, u_q, valid_rows); \
+ } \
+ if (limit_c_aligned < limit_c) { \
+ const size_t c = limit_c_aligned; \
+ const size_t c0 = c >> 5; \
+ const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \
+ const uint32_t valid_bytes = (uint32_t) ((limit_c - c) * sizeof(float)); \
+ EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \
+ st->store_tail_fn(out_row0 + c, dst_stride, g_q, u_q, (valid_rows << 16) | valid_bytes); \
+ } \
+ }
+
+#define W8A8_GLU_LOOP_FP16_1G W8A8_GLU_LOOP_FP16_PAIR(W8A8_GLU_EVAL_STRIP_1G, W8A8_GLU_EVAL_PAIR_1G, W8A8_GLU_EVAL_TILE_1G, 32)
+#define W8A8_GLU_LOOP_FP16_2G W8A8_GLU_LOOP_FP16_PAIR(W8A8_GLU_EVAL_STRIP_2G, W8A8_GLU_EVAL_PAIR_2G, W8A8_GLU_EVAL_TILE_2G, 64)
+#define W8A8_GLU_LOOP_FP16_NG W8A8_GLU_LOOP_FP16_GEN(W8A8_GLU_EVAL_TILE_NG, dw_tile_elems)
+#define W8A8_GLU_LOOP_FP16_CHK W8A8_GLU_LOOP_FP16_GEN(W8A8_GLU_EVAL_TILE_CHK, dw_tile_elems)
+
+#define W8A8_GLU_LOOP_FP32_1G W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_1G, 32)
+#define W8A8_GLU_LOOP_FP32_2G W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_2G, 64)
+#define W8A8_GLU_LOOP_FP32_NG W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_NG, dw_tile_elems)
+#define W8A8_GLU_LOOP_FP32_CHK W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_CHK, dw_tile_elems)
+
+#define DEFINE_W8A8_GLU_COL_CHUNKS(DST_SFX, DST_T, ALIGN_MASK, LOOP_1G, LOOP_2G, LOOP_NG, LOOP_CHK) \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_1g( \
+ 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) { \
+ const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t c0_first = c_first >> 5; \
+ const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \
+ const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \
+ const size_t dst_stride = st->dst_stride; \
+ const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * 32; \
+ const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * 32; \
+ uint32_t da_buf[1][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, st->vtcm_act_scales + (r_blk << 5), 0, 1); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint32_t * da0 = &da_ptr[0][lane]; \
+ const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ const uint8_t * g_base = st->vtcm_gate + tile_off; \
+ const uint8_t * u_base = st->vtcm_up + tile_off; \
+ DST_T * out_row0 = dst + r * dst_stride; \
+ LOOP_1G \
+ } \
+ r_base = r_end; \
+ } \
+} \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_2g( \
+ 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) { \
+ const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \
+ const size_t n_row_tiles_64 = st->mc_pad >> 6; \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t group_stride = n_row_tiles_64 * row_tile_stride; \
+ const size_t c0_first = c_first >> 5; \
+ const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \
+ const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \
+ const size_t dst_stride = st->dst_stride; \
+ const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * 64; \
+ const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * 64; \
+ uint32_t da_buf[2][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ const float * sc_base = st->vtcm_act_scales + (r_blk << 5); \
+ uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, sc_base, st->mc_pad, 2); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint32_t * da0 = &da_ptr[0][lane]; \
+ const uint32_t * da1 = &da_ptr[1][lane]; \
+ const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ const uint8_t * g_base = st->vtcm_gate + tile_off; \
+ const uint8_t * u_base = st->vtcm_up + tile_off; \
+ DST_T * out_row0 = dst + r * dst_stride; \
+ LOOP_2G \
+ } \
+ r_base = r_end; \
+ } \
+} \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_ng( \
+ 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) { \
+ const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const uint32_t n_groups = st->n_groups; \
+ const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \
+ const size_t n_row_tiles_64 = st->mc_pad >> 6; \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t group_stride = n_row_tiles_64 * row_tile_stride; \
+ const size_t dw_tile_elems = (size_t) n_groups * 32; \
+ const size_t c0_first = c_first >> 5; \
+ const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \
+ const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \
+ const size_t dst_stride = st->dst_stride; \
+ const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * dw_tile_elems; \
+ const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * dw_tile_elems; \
+ uint32_t da_buf[16][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ const float * sc_base = st->vtcm_act_scales + (r_blk << 5); \
+ uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, sc_base, st->mc_pad, n_groups); \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ const size_t lane = r_idx0 & 31u; \
+ const uint32_t * da_quad_base = &da_ptr[0][lane]; \
+ const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ const uint8_t * g_base = st->vtcm_gate + tile_off; \
+ const uint8_t * u_base = st->vtcm_up + tile_off; \
+ DST_T * out_row0 = dst + r * dst_stride; \
+ LOOP_NG \
+ } \
+ r_base = r_end; \
+ } \
+} \
+static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_chunked( \
+ 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) { \
+ const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \
+ DST_T * restrict dst = (DST_T *) dst_ptr; \
+ const uint32_t n_groups = st->n_groups; \
+ const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \
+ const size_t n_row_tiles_64 = st->mc_pad >> 6; \
+ const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \
+ const size_t group_stride = n_row_tiles_64 * row_tile_stride; \
+ const size_t dw_tile_elems = (size_t) n_groups * 32; \
+ const size_t c0_first = c_first >> 5; \
+ const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \
+ const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \
+ const size_t dst_stride = st->dst_stride; \
+ const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * dw_tile_elems; \
+ const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * dw_tile_elems; \
+ uint32_t da_buf[16][32] __attribute__((aligned(128))); \
+ for (size_t r_base = 0; r_base < n_rows; ) { \
+ const size_t r_idx_base = start_row + r_base; \
+ const size_t r_blk = r_idx_base >> 5; \
+ const size_t r0 = r_idx_base >> 6; \
+ const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \
+ const size_t r_end = r_base + r_step; \
+ w8a8_sm_chunked_eval_args_t cargs; \
+ cargs.act_scales_blk_base = st->vtcm_act_scales + (r_blk << 5); \
+ cargs.da_ptr = da_buf; \
+ cargs.group_stride = group_stride; \
+ cargs.mc_pad = st->mc_pad; \
+ cargs.n_groups = n_groups; \
+ for (size_t r = r_base; r < r_end; r += 4) { \
+ const size_t r_idx0 = start_row + r; \
+ const size_t rg = (r_idx0 & 63u) >> 2; \
+ cargs.lane = (uint32_t) (r_idx0 & 31u); \
+ const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \
+ const uint8_t * g_base = st->vtcm_gate + tile_off; \
+ const uint8_t * u_base = st->vtcm_up + tile_off; \
+ DST_T * out_row0 = dst + r * dst_stride; \
+ LOOP_CHK \
+ } \
+ r_base = r_end; \
+ } \
+}
+
+DEFINE_W8A8_GLU_COL_CHUNKS(fp16, __fp16, ~63u, W8A8_GLU_LOOP_FP16_1G, W8A8_GLU_LOOP_FP16_2G, W8A8_GLU_LOOP_FP16_NG, W8A8_GLU_LOOP_FP16_CHK)
+DEFINE_W8A8_GLU_COL_CHUNKS(fp32, float, ~31u, W8A8_GLU_LOOP_FP32_1G, W8A8_GLU_LOOP_FP32_2G, W8A8_GLU_LOOP_FP32_NG, W8A8_GLU_LOOP_FP32_CHK)
+
+static inline bool resolve_int_output_glu_fns(
+ uint32_t n_groups,
+ uint8_t glu_op,
+ size_t dst_elem_size,
+ 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) {
+ if (!resolve_hmx_glu_store_fns(glu_op, dst_elem_size, store_quad_fn, store_tail_fn, store_strip_fn)) {
+ return false;
+ }
+ if (dst_elem_size == sizeof(__fp16)) {
+ if (n_groups <= 1u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_1g;
+ else if (n_groups == 2u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_2g;
+ else if (n_groups <= 16u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_ng;
+ else *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_chunked;
+ } else {
+ if (n_groups <= 1u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_1g;
+ else if (n_groups == 2u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_2g;
+ else if (n_groups <= 16u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_ng;
+ else *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_chunked;
+ }
+ return true;
+}
+
diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h
deleted file mode 100644
index 37c529647..000000000
--- a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h
+++ /dev/null
@@ -1,1909 +0,0 @@
-#include "hmx-utils.h"
-#include "hmx-queue.h"
-
-// MXFP4 dequantization LUT: maps 4-bit index to fp16 mantissa value
-// kvalues: 0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6
-static const __fp16 mxfp4_to_fp16_lut[64] __attribute__((aligned(VLEN))) = {
- 0, 0, 0.5, 0, 1, 0, 1.5, 0, 2, 0, 3, 0, 4, 0, 6, 0, 0, 0, -0.5, 0, -1, 0, -1.5, 0, -2, 0, -3, 0, -4, 0, -6, 0,
-};
-
-static const __fp16 iq4_nl_to_fp16_lut[64] __attribute__((aligned(VLEN))) = {
- -127, 0, -104, 0, -83, 0, -65, 0, -49, 0, -35, 0, -22, 0, -10, 0,
- 1, 0, 13, 0, 25, 0, 38, 0, 53, 0, 69, 0, 89, 0, 113, 0,
-};
-
-// --- tiled format dequantizers ---
-
-typedef struct tiled_dequantize_state tiled_dequantize_state_t;
-typedef void (*tiled_dequant_task_fn_t)(const tiled_dequantize_state_t * state, uint32_t start_tile, uint32_t end_tile);
-
-struct tiled_dequantize_state {
- __fp16 * dst;
- const uint8_t * src;
- tiled_dequant_task_fn_t task_fn;
-
- struct fastdiv_values n_k_tiles_div;
- uint32_t n_k_tiles;
- uint32_t n_weight_tiles;
- uint32_t n_tot_tiles;
- uint32_t n_tiles_per_task;
- uint32_t tile_size;
- uint32_t aligned_tile_size;
- uint32_t n_tasks;
- uint32_t n_cols;
- uint32_t k_block;
- size_t row_stride;
- uint32_t weight_type;
-};
-
-static void dequantize_tiled_weight_to_fp16_task_q1_0(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector v_neg_one = Q6_Vb_vsplat_R(-1);
- const HVX_Vector v_pos_one = Q6_Vb_vsplat_R(1);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + 4 * t * HTP_MM_HMX_TILE_N_ELMS;
-
- const HVX_Vector v_sc = hvx_vmem(tile_src + 512);
- const HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- for (uint32_t q = 0; q < 4; q++) {
- const HVX_Vector v_plane = hvx_vmem(tile_src + q * 128);
- __fp16 * quarter_dst = dst_ptr + q * HTP_MM_HMX_TILE_N_ELMS;
-
- #pragma unroll
- for (int g = 0; g < 8; g++) {
- const HVX_Vector v_q = unpack_q1_0_group(v_plane, g, v_neg_one, v_pos_one);
- const HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
- const HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
-
- hvx_vmem(quarter_dst + (2 * g + 0) * 64) =
- Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
- hvx_vmem(quarter_dst + (2 * g + 1) * 64) =
- Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
- }
- }
- }
-}
-
-// Dequantize a single tile from tiled weight data (already in VTCM) to tile-major FP16.
-static void dequantize_tiled_weight_to_fp16_task_q4_0(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
- const HVX_Vector i8 = Q6_Vb_vsplat_R(8);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = hvx_vmem(tile_src + 512);
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- // Load all 4 groups in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- // Nibble extraction
- HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4);
- HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4);
- HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4);
- HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4);
- HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4);
- HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4);
- HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4);
- HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4);
-
- // Offsetting (-8)
- v_lo0 = Q6_Vb_vsub_VbVb(v_lo0, i8);
- v_hi0 = Q6_Vb_vsub_VbVb(v_hi0, i8);
- v_lo1 = Q6_Vb_vsub_VbVb(v_lo1, i8);
- v_hi1 = Q6_Vb_vsub_VbVb(v_hi1, i8);
- v_lo2 = Q6_Vb_vsub_VbVb(v_lo2, i8);
- v_hi2 = Q6_Vb_vsub_VbVb(v_hi2, i8);
- v_lo3 = Q6_Vb_vsub_VbVb(v_lo3, i8);
- v_hi3 = Q6_Vb_vsub_VbVb(v_hi3, i8);
-
- // Shuffling
- HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1);
- HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1);
- HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1);
- HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1);
-
- // Unpack to 16-bit
- HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0));
- HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0));
- HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1));
- HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1));
- HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2));
- HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2));
- HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3));
- HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3));
-
- // Convert and scale multiplication
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated));
- HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated));
- HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated));
-
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated));
- HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated));
- HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated));
-
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated));
- HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated));
- HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated));
-
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated));
- HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated));
- HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated));
-
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3;
-
- hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3;
-
- hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3;
-
- hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3;
- }
-}
-
-static void dequantize_tiled_weight_to_fp16_task_q4_1(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector vscale_offset = hvx_vmem(tile_src + 512);
- HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(vscale_offset, vscale_offset, -2);
- HVX_Vector vd = Q6_V_lo_W(dm_deal);
- HVX_Vector vm = Q6_V_hi_W(dm_deal);
-
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vd, vd, -2));
- HVX_Vector v_offset_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vm, vm, -2));
-
- // Load all 4 groups in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- // Nibble extraction
- HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4);
- HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4);
- HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4);
- HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4);
- HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4);
- HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4);
- HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4);
- HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4);
-
- // Shuffling
- HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1);
- HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1);
- HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1);
- HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1);
-
- // Unpack to 16-bit
- HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0));
- HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0));
- HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1));
- HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1));
- HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2));
- HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2));
- HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3));
- HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3));
-
- // Convert, multiply, add offset
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated));
-
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated));
-
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated));
-
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated));
-
- // Parallel Stores
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3;
-
- hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3;
-
- hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3;
-
- hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3;
- }
-}
-
-static void dequantize_tiled_weight_to_fp16_task_iq4_nl(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
- const HVX_Vector vlut_cvt = hvx_vmem(iq4_nl_to_fp16_lut);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = hvx_vmem(tile_src + 512);
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- // Load all 4 groups in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- // Nibble extraction
- HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4);
- HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4);
- HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4);
- HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4);
- HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4);
- HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4);
- HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4);
- HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4);
-
- // Shuffling
- HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1);
- HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1);
- HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1);
- HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1);
-
- // Shuffle for LUT lookup
- HVX_Vector v_q_lo0 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf0));
- HVX_Vector v_q_hi0 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf0));
- HVX_Vector v_q_lo1 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf1));
- HVX_Vector v_q_hi1 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf1));
- HVX_Vector v_q_lo2 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf2));
- HVX_Vector v_q_hi2 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf2));
- HVX_Vector v_q_lo3 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf3));
- HVX_Vector v_q_hi3 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf3));
-
- // LUT lookup
- HVX_VectorPair vp_lo0 = Q6_Wh_vlut16_VbVhR(v_q_lo0, vlut_cvt, 0);
- HVX_VectorPair vp_hi0 = Q6_Wh_vlut16_VbVhR(v_q_hi0, vlut_cvt, 0);
- HVX_VectorPair vp_lo1 = Q6_Wh_vlut16_VbVhR(v_q_lo1, vlut_cvt, 0);
- HVX_VectorPair vp_hi1 = Q6_Wh_vlut16_VbVhR(v_q_hi1, vlut_cvt, 0);
- HVX_VectorPair vp_lo2 = Q6_Wh_vlut16_VbVhR(v_q_lo2, vlut_cvt, 0);
- HVX_VectorPair vp_hi2 = Q6_Wh_vlut16_VbVhR(v_q_hi2, vlut_cvt, 0);
- HVX_VectorPair vp_lo3 = Q6_Wh_vlut16_VbVhR(v_q_lo3, vlut_cvt, 0);
- HVX_VectorPair vp_hi3 = Q6_Wh_vlut16_VbVhR(v_q_hi3, vlut_cvt, 0);
-
- // Convert and scale multiplication
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo0), v_scale_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo0), v_scale_duplicated));
- HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi0), v_scale_duplicated));
- HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi0), v_scale_duplicated));
-
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo1), v_scale_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo1), v_scale_duplicated));
- HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi1), v_scale_duplicated));
- HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi1), v_scale_duplicated));
-
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo2), v_scale_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo2), v_scale_duplicated));
- HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi2), v_scale_duplicated));
- HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi2), v_scale_duplicated));
-
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo3), v_scale_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo3), v_scale_duplicated));
- HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi3), v_scale_duplicated));
- HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi3), v_scale_duplicated));
-
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3;
-
- hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3;
-
- hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3;
-
- hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3;
- }
-}
-
-static void dequantize_tiled_weight_to_fp16_task_mxfp4(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
- const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v = hvx_vmem(tile_src + 512);
- HVX_Vector vh = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(v));
- vh = Q6_Vh_vsub_VhVh(vh, Q6_Vh_vsplat_R(112));
- vh = Q6_Vh_vmax_VhVh(vh, Q6_V_vzero());
- vh = Q6_Vh_vmin_VhVh(vh, Q6_Vh_vsplat_R(30));
- vh = Q6_Vh_vasl_VhR(vh, 10);
-
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vh, vh, -2));
-
- // Load all 4 groups in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- // Nibble extraction
- HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4);
- HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4);
- HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4);
- HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4);
- HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4);
- HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4);
- HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4);
- HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4);
-
- // Shuffling
- HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1);
- HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1);
- HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1);
- HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1);
-
- // Shuffle for LUT lookup
- HVX_Vector v_q_lo0 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf0));
- HVX_Vector v_q_hi0 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf0));
- HVX_Vector v_q_lo1 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf1));
- HVX_Vector v_q_hi1 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf1));
- HVX_Vector v_q_lo2 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf2));
- HVX_Vector v_q_hi2 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf2));
- HVX_Vector v_q_lo3 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf3));
- HVX_Vector v_q_hi3 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf3));
-
- // LUT lookup
- HVX_VectorPair vp_lo0 = Q6_Wh_vlut16_VbVhR(v_q_lo0, vlut_cvt, 0);
- HVX_VectorPair vp_hi0 = Q6_Wh_vlut16_VbVhR(v_q_hi0, vlut_cvt, 0);
- HVX_VectorPair vp_lo1 = Q6_Wh_vlut16_VbVhR(v_q_lo1, vlut_cvt, 0);
- HVX_VectorPair vp_hi1 = Q6_Wh_vlut16_VbVhR(v_q_hi1, vlut_cvt, 0);
- HVX_VectorPair vp_lo2 = Q6_Wh_vlut16_VbVhR(v_q_lo2, vlut_cvt, 0);
- HVX_VectorPair vp_hi2 = Q6_Wh_vlut16_VbVhR(v_q_hi2, vlut_cvt, 0);
- HVX_VectorPair vp_lo3 = Q6_Wh_vlut16_VbVhR(v_q_lo3, vlut_cvt, 0);
- HVX_VectorPair vp_hi3 = Q6_Wh_vlut16_VbVhR(v_q_hi3, vlut_cvt, 0);
-
- // Convert and scale multiplication
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo0), v_scale_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo0), v_scale_duplicated));
- HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi0), v_scale_duplicated));
- HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi0), v_scale_duplicated));
-
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo1), v_scale_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo1), v_scale_duplicated));
- HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi1), v_scale_duplicated));
- HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi1), v_scale_duplicated));
-
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo2), v_scale_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo2), v_scale_duplicated));
- HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi2), v_scale_duplicated));
- HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi2), v_scale_duplicated));
-
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo3), v_scale_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo3), v_scale_duplicated));
- HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi3), v_scale_duplicated));
- HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi3), v_scale_duplicated));
-
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3;
-
- hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3;
-
- hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3;
-
- hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3;
- }
-}
-
-static void dequantize_tiled_weight_to_fp16_task_q8_0(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = hvx_vmem(tile_src + 1024);
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- // Load groups 0-3 in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- HVX_VectorPair vp_int16_0 = Q6_Wh_vunpack_Vb(vq0);
- HVX_VectorPair vp_int16_1 = Q6_Wh_vunpack_Vb(vq1);
- HVX_VectorPair vp_int16_2 = Q6_Wh_vunpack_Vb(vq2);
- HVX_VectorPair vp_int16_3 = Q6_Wh_vunpack_Vb(vq3);
-
- // Load groups 4-7 in parallel
- HVX_Vector vq4 = hvx_vmem(tile_src + 4 * 128);
- HVX_Vector vq5 = hvx_vmem(tile_src + 5 * 128);
- HVX_Vector vq6 = hvx_vmem(tile_src + 6 * 128);
- HVX_Vector vq7 = hvx_vmem(tile_src + 7 * 128);
-
- HVX_VectorPair vp_int16_4 = Q6_Wh_vunpack_Vb(vq4);
- HVX_VectorPair vp_int16_5 = Q6_Wh_vunpack_Vb(vq5);
- HVX_VectorPair vp_int16_6 = Q6_Wh_vunpack_Vb(vq6);
- HVX_VectorPair vp_int16_7 = Q6_Wh_vunpack_Vb(vq7);
-
- // Convert and scale multiply for groups 0-3
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_0)), v_scale_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_0)), v_scale_duplicated));
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_1)), v_scale_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_1)), v_scale_duplicated));
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_2)), v_scale_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_2)), v_scale_duplicated));
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_3)), v_scale_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_3)), v_scale_duplicated));
-
- // Store groups 0-3
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 4 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp3_1;
-
- // Convert and scale multiply for groups 4-7
- HVX_Vector v_grp4_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_4)), v_scale_duplicated));
- HVX_Vector v_grp4_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_4)), v_scale_duplicated));
- HVX_Vector v_grp5_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_5)), v_scale_duplicated));
- HVX_Vector v_grp5_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_5)), v_scale_duplicated));
- HVX_Vector v_grp6_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_6)), v_scale_duplicated));
- HVX_Vector v_grp6_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_6)), v_scale_duplicated));
- HVX_Vector v_grp7_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_7)), v_scale_duplicated));
- HVX_Vector v_grp7_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_7)), v_scale_duplicated));
-
- // Store groups 4-7
- hvx_vmem(dst_ptr + 8 * 64) = v_grp4_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp4_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp5_0;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp5_1;
- hvx_vmem(dst_ptr + 12 * 64) = v_grp6_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp6_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp7_0;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp7_1;
- }
-}
-
-static void dequantize_tiled_weight_to_fp16_task_q5_k(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector vscale_offset = hvx_vmem(tile_src + 512);
- HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(vscale_offset, vscale_offset, -2);
- HVX_Vector vd = Q6_V_lo_W(dm_deal);
- HVX_Vector vm = Q6_V_hi_W(dm_deal);
-
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vd, vd, -2));
- HVX_Vector v_offset_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vm, vm, -2));
-
- // Load all 4 groups in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- // Nibble extraction
- HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4);
- HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4);
- HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4);
- HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4);
- HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4);
- HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4);
- HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4);
- HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4);
-
- // Q5_K: OR in the 5th bit from the plane
- HVX_Vector v_plane = hvx_vmem(tile_src + 640);
- v_lo0 = hvx_q5k_or_hibit(v_lo0, v_plane, 0);
- v_hi0 = hvx_q5k_or_hibit(v_hi0, v_plane, 1);
- v_lo1 = hvx_q5k_or_hibit(v_lo1, v_plane, 2);
- v_hi1 = hvx_q5k_or_hibit(v_hi1, v_plane, 3);
- v_lo2 = hvx_q5k_or_hibit(v_lo2, v_plane, 4);
- v_hi2 = hvx_q5k_or_hibit(v_hi2, v_plane, 5);
- v_lo3 = hvx_q5k_or_hibit(v_lo3, v_plane, 6);
- v_hi3 = hvx_q5k_or_hibit(v_hi3, v_plane, 7);
-
- // Shuffling
- HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1);
- HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1);
- HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1);
- HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1);
-
- // Unpack to 16-bit
- HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0));
- HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0));
- HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1));
- HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1));
- HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2));
- HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2));
- HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3));
- HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3));
-
- // Convert, multiply, add offset
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated));
-
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated));
-
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated));
-
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated));
- HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated));
-
- // Parallel Stores
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3;
-
- hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3;
-
- hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3;
-
- hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3;
- }
-}
-
-static void dequantize_tiled_weight_to_fp16_task_q5_0(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = hvx_vmem(tile_src + 640);
- HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- // Load all 4 groups in parallel
- HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128);
- HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128);
- HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128);
- HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128);
-
- // Nibble extraction
- HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4);
- HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4);
- HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4);
- HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4);
- HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4);
- HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4);
- HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4);
- HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4);
-
- // Q5_0: OR 0xF0 where the plane flags a clear 5th bit (q - 16)
- HVX_Vector v_plane = hvx_vmem(tile_src + 512);
- v_lo0 = hvx_q5_0_or_neg(v_lo0, v_plane, 0);
- v_hi0 = hvx_q5_0_or_neg(v_hi0, v_plane, 1);
- v_lo1 = hvx_q5_0_or_neg(v_lo1, v_plane, 2);
- v_hi1 = hvx_q5_0_or_neg(v_hi1, v_plane, 3);
- v_lo2 = hvx_q5_0_or_neg(v_lo2, v_plane, 4);
- v_hi2 = hvx_q5_0_or_neg(v_hi2, v_plane, 5);
- v_lo3 = hvx_q5_0_or_neg(v_lo3, v_plane, 6);
- v_hi3 = hvx_q5_0_or_neg(v_hi3, v_plane, 7);
-
- // Shuffling
- HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1);
- HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1);
- HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1);
- HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1);
-
- // Unpack to 16-bit
- HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0));
- HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0));
- HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1));
- HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1));
- HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2));
- HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2));
- HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3));
- HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3));
-
- // Convert and scale multiplication
- HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated));
- HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated));
- HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated));
- HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated));
-
- HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated));
- HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated));
- HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated));
- HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated));
-
- HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated));
- HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated));
- HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated));
- HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated));
-
- HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated));
- HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated));
- HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated));
- HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated));
-
- // Parallel Stores
- hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0;
- hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1;
- hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2;
- hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3;
-
- hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0;
- hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1;
- hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2;
- hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3;
-
- hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0;
- hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1;
- hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2;
- hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3;
-
- hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0;
- hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1;
- hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2;
- hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3;
- }
-}
-
-// Q6_K stores 6-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q6_K.
-// A k-group holds 4 k per row, the HMX tile holds 2, so each group is dealt into two tiles.
-static void dequantize_tiled_weight_to_fp16_task_q6_k(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
- const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
- const HVX_Vector i32 = Q6_Vb_vsplat_R(32);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const HVX_Vector * vptr = (const HVX_Vector *) (state->src + t * state->aligned_tile_size);
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = vptr[6];
- HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64);
- HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
- HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2));
-
- #pragma unroll
- for (int g = 0; g < 8; g += 4) {
- const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16;
-
- HVX_Vector v_q0 = unpack_q6_k_group(vptr, g + 0, mask_0f, mask_03, i32);
- HVX_Vector v_q1 = unpack_q6_k_group(vptr, g + 1, mask_0f, mask_03, i32);
- HVX_Vector v_q2 = unpack_q6_k_group(vptr, g + 2, mask_0f, mask_03, i32);
- HVX_Vector v_q3 = unpack_q6_k_group(vptr, g + 3, mask_0f, mask_03, i32);
-
- HVX_VectorPair vp16_0 = Q6_Wh_vunpack_Vb(v_q0);
- HVX_VectorPair vp16_1 = Q6_Wh_vunpack_Vb(v_q1);
- HVX_VectorPair vp16_2 = Q6_Wh_vunpack_Vb(v_q2);
- HVX_VectorPair vp16_3 = Q6_Wh_vunpack_Vb(v_q3);
- HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_0), Q6_V_lo_W(vp16_0), -4);
- HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_1), Q6_V_lo_W(vp16_1), -4);
- HVX_VectorPair vp_k2 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_2), Q6_V_lo_W(vp16_2), -4);
- HVX_VectorPair vp_k3 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_3), Q6_V_lo_W(vp16_3), -4);
-
- HVX_Vector v_out00 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale));
- HVX_Vector v_out01 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale));
- HVX_Vector v_out10 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale));
- HVX_Vector v_out11 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale));
- HVX_Vector v_out20 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k2)), v_scale));
- HVX_Vector v_out21 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k2)), v_scale));
- HVX_Vector v_out30 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k3)), v_scale));
- HVX_Vector v_out31 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k3)), v_scale));
-
- hvx_vmem(dst_ptr + (2 * g + 0) * 64) = v_out00;
- hvx_vmem(dst_ptr + (2 * g + 1) * 64) = v_out01;
- hvx_vmem(dst_ptr + (2 * g + 2) * 64) = v_out10;
- hvx_vmem(dst_ptr + (2 * g + 3) * 64) = v_out11;
- hvx_vmem(dst_ptr + (2 * g + 4) * 64) = v_out20;
- hvx_vmem(dst_ptr + (2 * g + 5) * 64) = v_out21;
- hvx_vmem(dst_ptr + (2 * g + 6) * 64) = v_out30;
- hvx_vmem(dst_ptr + (2 * g + 7) * 64) = v_out31;
- }
- }
-}
-
-#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
-#define IQ2XXS_D_SCALE_F16 0x3000 // 0.125 as fp16 bits
-
-// 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));
-}
-
-// NVFP4 tiles are MXFP4 quants with one UE4M3 scale per 16 k (sub-block 0: k 0..15, sub-block 1: k 16..31)
-static void dequantize_tiled_weight_to_fp16_task_nvfp4(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F);
- const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile_src = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_d = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF))));
- HVX_VectorPair vp_d = Q6_W_vshuff_VVR(v_d, v_d, -2);
- HVX_Vector v_scale_k0 = Q6_V_lo_W(vp_d);
- HVX_Vector v_scale_k16 = Q6_V_hi_W(vp_d);
-
- #pragma unroll
- for (int g = 0; g < 4; g++) {
- const HVX_Vector v_scale = (g < 2) ? v_scale_k0 : v_scale_k16;
-
- HVX_Vector vq = hvx_vmem(tile_src + g * 128);
- HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4);
- HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4);
-
- HVX_VectorPair vp_shuf = Q6_W_vshuff_VVR(v_hi, v_lo, -1);
- HVX_VectorPair vp_lo = Q6_Wh_vlut16_VbVhR(Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf)), vlut_cvt, 0);
- HVX_VectorPair vp_hi = Q6_Wh_vlut16_VbVhR(Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf)), vlut_cvt, 0);
-
- hvx_vmem(dst_ptr + (4 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo), v_scale));
- hvx_vmem(dst_ptr + (4 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo), v_scale));
- hvx_vmem(dst_ptr + (4 * g + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi), v_scale));
- hvx_vmem(dst_ptr + (4 * g + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi), v_scale));
- }
- }
-}
-
-// IQ2_XXS: int8 grid weights from the VTCM LUT, scaled by d / 8 * (2 * scale + 1) per row
-static void dequantize_tiled_weight_to_fp16_task_iq2_xxs(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- HVX_Vector v_d = Q6_V_vzero();
- const HVX_Vector v_eighth = Q6_Vh_vsplat_R(IQ2XXS_D_SCALE_F16);
-
- HVX_Vector v_sgn = Q6_V_vzero();
- if (start_tile < end_tile) {
- v_sgn = iq2xxs_gather_issue(state->src + start_tile * state->aligned_tile_size);
- }
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile = state->src + t * state->aligned_tile_size;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block
- if (t == start_tile || (t & (IQ2XXS_TILES_PER_SB - 1)) == 0) {
- v_d = iq2xxs_gather_d(tile - (t & (IQ2XXS_TILES_PER_SB - 1)) * state->aligned_tile_size);
- }
-
- HVX_Vector v_c[2], v_w[2 * IQ2XXS_GROUPS], v_ls;
- iq2xxs_gather_wait(tile, v_c);
- const HVX_Vector v_sgn_cur = v_sgn;
- if (t + 1 < end_tile) {
- v_sgn = iq2xxs_gather_issue(tile + state->aligned_tile_size);
- }
- iq2xxs_decode_expand(v_c, v_sgn_cur, v_w, &v_ls);
-
- HVX_Vector v_ls_h = Q6_Vhf_equals_Vh(Q6_Vh_vpacke_VwVw(v_ls, v_ls));
- HVX_Vector v_sc = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_d, v_ls_h));
- HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- #pragma unroll
- for (int g = 0; g < 2 * IQ2XXS_GROUPS; g++) {
- HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_w[g]);
- HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
-
- // d / 8 is subnormal in fp16 for real weights, so apply the 1/8 after the multiply by d * ls
- HVX_Vector v_lo = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
- HVX_Vector v_hi = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
- hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_lo, v_eighth));
- hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_hi, v_eighth));
- }
- }
-}
-
-// Q3_K stores 3-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q3_K.
-static void dequantize_tiled_weight_to_fp16_task_q3_k(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const HVX_Vector * vptr = (const HVX_Vector *) (state->src + t * state->aligned_tile_size);
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = vptr[3];
- HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64);
- HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
- HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2));
-
- #pragma unroll
- for (int g = 0; g < 8; g++) {
- const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16;
-
- HVX_Vector v_q = unpack_q3_k_group(vptr, g, mask_03);
- HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
- HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
-
- hvx_vmem(dst_ptr + (2 * g + 0) * 64) =
- Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
- hvx_vmem(dst_ptr + (2 * g + 1) * 64) =
- Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
- }
- }
-}
-
-// Q2_K stores 2-bit weights, the ggml scale bytes and d / -dmin per super-block, see HTP_TENSOR_TILE_SIZE_Q2_K.
-static void dequantize_tiled_weight_to_fp16_task_q2_k(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
-
- HVX_Vector v_d = Q6_V_vzero();
- HVX_Vector v_dm = Q6_V_vzero();
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const uint8_t * tile = state->src + t * state->aligned_tile_size;
- const HVX_Vector * vptr = (const HVX_Vector *) tile;
- __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
-
- // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block
- if (t == start_tile || (t & 7) == 0) {
- q2_k_load_dmin(tile - (t & 7) * state->aligned_tile_size, &v_d, &v_dm);
- }
-
- HVX_Vector v_sc, v_m;
- q2_k_unpack_scales(tile, v_d, v_dm, &v_sc, &v_m);
- HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64);
- HVX_Vector v_m_k16 = Q6_V_vror_VR(v_m, 64);
- HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
- HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2));
- HVX_Vector v_offset_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m, v_m, -2));
- HVX_Vector v_offset_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m_k16, v_m_k16, -2));
-
- #pragma unroll
- for (int g = 0; g < 8; g++) {
- const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16;
- const HVX_Vector v_offset = (g < 4) ? v_offset_k0 : v_offset_k16;
-
- HVX_Vector v_q = unpack_q3_k_low2(vptr, g, mask_03);
- HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
- HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
-
- hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(
- Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale), v_offset));
- hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(
- Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale), v_offset));
- }
- }
-}
-
-// Q2_0 stores codes 0..3 (value code - 1) and one fp16 scale per row, see HTP_MM_WEIGHT_TILE_SIZE_Q2_0.
-// One packed 64-k tile expands into two consecutive 32-k fp16 tiles.
-static void dequantize_tiled_weight_to_fp16_task_q2_0(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
- const HVX_Vector i1 = Q6_Vb_vsplat_R(1);
-
- for (uint32_t t = start_tile; t < end_tile; t++) {
- const HVX_Vector * vptr = (const HVX_Vector *) (state->src + t * state->aligned_tile_size);
- __fp16 * dst_base = state->dst + 2 * t * HTP_MM_HMX_TILE_N_ELMS;
-
- HVX_Vector v_sc = vptr[4];
- HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2));
-
- for (int half = 0; half < 2; half++) {
- __fp16 * dst_ptr = dst_base + half * HTP_MM_HMX_TILE_N_ELMS;
-
- #pragma unroll
- for (int g = 0; g < 8; g++) {
- HVX_Vector v_q = Q6_Vb_vsub_VbVb(unpack_q3_k_low2(vptr + 2 * half, g, mask_03), i1);
- HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q);
- HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4);
-
- hvx_vmem(dst_ptr + (2 * g + 0) * 64) =
- Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale));
- hvx_vmem(dst_ptr + (2 * g + 1) * 64) =
- Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale));
- }
- }
- }
-}
-
-static __attribute__((noinline))
-void convert_f16_weight_to_fp16_tiles_task(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const uint32_t n_k_tiles = state->n_k_tiles;
- const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div;
-
- const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
- const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
- const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
-
- unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div);
- unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div);
-
- for (unsigned t = start_tile; t < (unsigned)end_tile; ) {
- if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; }
-
- __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
- {
- uint32_t byte_off = kt * 32 * sizeof(__fp16);
-
- HVX_Vector v_off = v_scat_base;
- for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) {
- uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r;
- uint32_t row1 = row0 + 1;
-
- const uint8_t *r0 = state->src + row0 * state->row_stride;
- const uint8_t *r1 = state->src + row1 * state->row_stride;
-
- HVX_Vector v0 = (row0 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r0 + byte_off)) : Q6_V_vzero();
- HVX_Vector v1 = (row1 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r1 + byte_off)) : Q6_V_vzero();
-
- Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v0);
- v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
- Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v1);
- v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
- }
- }
- ++t; ++kt;
- }
-}
-
-static __attribute__((noinline))
-void quantize_f32_weight_to_fp16_tiles_task(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const uint32_t n_k_tiles = state->n_k_tiles;
- const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div;
-
- const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
- const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
- const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
-
- unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div);
- unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div);
-
- for (unsigned t = start_tile; t < (unsigned)end_tile; ) {
- if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; }
-
- __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
- {
- uint32_t byte_off = kt * 32 * sizeof(float);
-
- HVX_Vector v_off = v_scat_base;
- for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) {
- uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r;
- uint32_t row1 = row0 + 1;
-
- const uint8_t *r0 = state->src + row0 * state->row_stride;
- const uint8_t *r1 = state->src + row1 * state->row_stride;
-
- HVX_Vector v0_f32 = (row0 < state->n_cols) ? hvx_vmem((const float *)(r0 + byte_off)) : Q6_V_vzero();
- HVX_Vector v1_f32 = (row1 < state->n_cols) ? hvx_vmem((const float *)(r1 + byte_off)) : Q6_V_vzero();
-
- HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32);
-
- Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out);
- v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
-
- HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64);
- Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi);
- v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
- }
- }
- ++t; ++kt;
- }
-}
-
-static __attribute__((noinline))
-void convert_bf16_weight_to_fp16_tiles_task(
- const tiled_dequantize_state_t *state,
- uint32_t start_tile, uint32_t end_tile) {
-
- const uint32_t n_k_tiles = state->n_k_tiles;
- const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div;
-
- const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
- const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
- const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
-
- unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div);
- unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div);
-
- for (unsigned t = start_tile; t < (unsigned)end_tile; ) {
- if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; }
-
- __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS;
- {
- uint32_t byte_off = kt * 32 * sizeof(uint16_t);
-
- HVX_Vector v_off = v_scat_base;
- for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) {
- uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r;
- uint32_t row1 = row0 + 1;
-
- const uint8_t *r0 = state->src + row0 * state->row_stride;
- const uint8_t *r1 = state->src + row1 * state->row_stride;
-
- HVX_Vector v0_raw = (row0 < state->n_cols) ? hvx_vmemu((const void *)(r0 + byte_off)) : Q6_V_vzero();
- HVX_Vector v1_raw = (row1 < state->n_cols) ? hvx_vmemu((const void *)(r1 + byte_off)) : Q6_V_vzero();
-
- HVX_Vector v0_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v0_raw)), 16);
- HVX_Vector v1_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v1_raw)), 16);
-
- HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32);
-
- Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out);
- v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
-
- HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64);
- Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi);
- v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step);
- }
- }
- ++t; ++kt;
- }
-}
-
-// --- End tiled dequantizers ---
-
-// dot-chunk functions require external HMX lock
-
-static void core_dot_chunk_fp16_short(__fp16 *restrict output, const __fp16 *restrict activation,
- const __fp16 *restrict weight, const __fp16 *restrict scales,
- uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) {
- __builtin_assume(n_row_tiles > 0);
- __builtin_assume(n_col_tiles > 0);
- __builtin_assume(n_dot_tiles > 0);
- __builtin_assume(n_dot_tiles <= 32);
-
- asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales));
-
- const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS;
- const uint32_t range = 2048u * n_dot_tiles - 1;
-
- for (uint32_t r = 0; r < n_row_tiles; ++r) {
- const __fp16 *row_base = activation + r * dot_stride;
- const __fp16 *col_base = weight;
- __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS;
-
- for (size_t c = 0; c < n_col_tiles; ++c) {
- asm volatile(HMX_CLRACC_F16());
- asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_base), "r"(col_base));
- asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory");
- col_base += dot_stride;
- out_tile += HTP_MM_HMX_TILE_N_ELMS;
- }
- }
-}
-
-static void core_dot_chunk_fp16(__fp16 *restrict output, const __fp16 *restrict activation,
- const __fp16 *restrict weight, const __fp16 *restrict scales,
- uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) {
- if (n_dot_tiles <= 32) {
- core_dot_chunk_fp16_short(output, activation, weight, scales, n_row_tiles, n_col_tiles, n_dot_tiles);
- return;
- }
- __builtin_assume(n_row_tiles > 0);
- __builtin_assume(n_col_tiles > 0);
- __builtin_assume(n_dot_tiles > 32);
-
- asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales));
-
- const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS;
-
- for (uint32_t r = 0; r < n_row_tiles; ++r) {
- const __fp16 *row_base = activation + r * dot_stride;
- const __fp16 *col_base = weight;
- __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS;
-
- for (size_t c = 0; c < n_col_tiles; ++c) {
- const __fp16 *row_tiles = row_base;
- const __fp16 *col_tiles = col_base;
-
- asm volatile(HMX_CLRACC_F16());
-
- const uint32_t n_loops = n_dot_tiles / 32;
- const uint32_t rem = n_dot_tiles % 32;
-
- for (uint32_t l = 0; l < n_loops; ++l) {
- asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(65535), "r"(row_tiles), "r"(col_tiles));
- row_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS;
- col_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS;
- }
-
- if (rem > 0) {
- const uint32_t range = 2048u * rem - 1;
- asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_tiles), "r"(col_tiles));
- }
-
- asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory");
-
- col_base += dot_stride;
- out_tile += HTP_MM_HMX_TILE_N_ELMS;
- }
- }
-}
-
-static void core_mma_chunk_fp16_short(__fp16 *restrict c, const __fp16 *restrict a, const __fp16 *restrict b,
- const __fp16 *restrict col_scales, const __fp16 *restrict eye_tile,
- uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles, bool zero_init) {
- __builtin_assume(n_row_tiles > 0);
- __builtin_assume(n_col_tiles > 0);
- __builtin_assume(n_dot_tiles > 0);
- __builtin_assume(n_dot_tiles <= 32);
-
- asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)col_scales));
-
- const size_t dot_tile_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS;
- const uint32_t range = 2048u * n_dot_tiles - 1;
-
- for (size_t i = 0; i < n_row_tiles; ++i) {
- const __fp16 *row_base = a + i * dot_tile_stride;
- __fp16 *res_base = c + i * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS;
- const __fp16 *col_base = b;
- __fp16 *accum_tile = res_base;
-
- for (size_t j = 0; j < n_col_tiles; ++j) {
- asm volatile(HMX_CLRACC_F16());
-
- if (!zero_init) {
- asm volatile(HMX_LOAD_MPY_F16("%1", "%2", "%0") : : "r"(2047), "r"(accum_tile), "r"(eye_tile));
- }
-
- asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_base), "r"(col_base));
-
- asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(accum_tile), "r"(0) : "memory");
-
- col_base += dot_tile_stride;
- accum_tile += HTP_MM_HMX_TILE_N_ELMS;
- }
- }
-}
-
-static void core_mma_chunk_fp16(__fp16 *restrict c, const __fp16 *restrict a, const __fp16 *restrict b,
- const __fp16 *restrict col_scales, const __fp16 *restrict eye_tile,
- uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles, bool zero_init) {
- if (n_dot_tiles <= 32) {
- core_mma_chunk_fp16_short(c, a, b, col_scales, eye_tile, n_row_tiles, n_col_tiles, n_dot_tiles, zero_init);
- return;
- }
- __builtin_assume(n_row_tiles > 0);
- __builtin_assume(n_col_tiles > 0);
- __builtin_assume(n_dot_tiles > 32);
-
- asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)col_scales));
-
- const size_t dot_tile_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS;
-
- for (size_t i = 0; i < n_row_tiles; ++i) {
- const __fp16 *row_base = a + i * dot_tile_stride;
- __fp16 *res_base = c + i * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS;
- const __fp16 *col_base = b;
- __fp16 *accum_tile = res_base;
-
- for (size_t j = 0; j < n_col_tiles; ++j) {
- const __fp16 *col_tiles = col_base;
- const __fp16 *row_tiles = row_base;
-
- asm volatile(HMX_CLRACC_F16());
-
- if (!zero_init) {
- asm volatile(HMX_LOAD_MPY_F16("%1", "%2", "%0") : : "r"(2047), "r"(accum_tile), "r"(eye_tile));
- }
-
- const uint32_t n_loops = n_dot_tiles / 32;
- const uint32_t rem = n_dot_tiles % 32;
-
- for (uint32_t l = 0; l < n_loops; ++l) {
- asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(65535), "r"(row_tiles), "r"(col_tiles));
- row_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS;
- col_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS;
- }
-
- if (rem > 0) {
- const uint32_t range = 2048u * rem - 1;
- asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_tiles), "r"(col_tiles));
- }
-
- asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(accum_tile), "r"(0) : "memory");
-
- col_base += dot_tile_stride;
- accum_tile += HTP_MM_HMX_TILE_N_ELMS;
- }
- }
-}
-
-// output : fp16 -> f32p
-
-static void transfer_output_chunk_fp16_to_fp32_col_chunk(
- float *restrict dst,
- const float *restrict src2,
- const __fp16 *restrict vtcm_src,
- uint32_t start_row,
- uint32_t n_rows,
- uint32_t c_len,
- uint32_t total_n_cols,
- uint32_t dst_stride,
- uint32_t src2_stride,
- uint32_t dst_cols
-) {
- const size_t tile_row_stride = hmx_ceil_div(total_n_cols, HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS;
-
- const HVX_Vector one = hvx_vec_splat_f16(1.0);
-
- const size_t limit_c = hex_smin(c_len, dst_cols);
- const size_t limit_c_aligned = (limit_c & ~31);
-
- for (size_t r = 0; r < n_rows; r += 2) {
- const size_t r_idx0 = start_row + r + 0;
- const size_t r0 = r_idx0 / HTP_MM_HMX_TILE_N_ROWS;
- const size_t r1 = (r_idx0 % HTP_MM_HMX_TILE_N_ROWS) / 2; // index of the row pair within the tile
- const __fp16 *row_base = vtcm_src + r0 * tile_row_stride;
- float *output_row_base = dst + r * dst_stride; // global memory row base for row r (and r+1)
- const float *src2_row_base = src2 ? (src2 + r * src2_stride) : NULL;
-
- #pragma unroll(4)
- for (size_t c = 0; c < limit_c_aligned; c += HTP_MM_HMX_TILE_N_COLS) {
- const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS;
- HVX_Vector v = ((const HVX_Vector *) tile)[r1];
- HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one);
-
- HVX_Vector v_out0 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp));
- if (src2_row_base) {
- HVX_Vector v_src2_0 = hvx_vmemu(src2_row_base + c + 0);
- v_out0 = hvx_vec_add_f32_f32(v_out0, v_src2_0);
- }
- hvx_vmemu(output_row_base + c + 0) = v_out0;
-
- if (r + 1 < n_rows) {
- HVX_Vector v_out1 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp));
- if (src2_row_base) {
- HVX_Vector v_src2_1 = hvx_vmemu(src2_row_base + c + src2_stride);
- v_out1 = hvx_vec_add_f32_f32(v_out1, v_src2_1);
- }
- hvx_vmemu(output_row_base + c + dst_stride) = v_out1;
- }
- }
-
- if (limit_c_aligned < limit_c) {
- size_t c = limit_c_aligned;
- size_t valid_c = limit_c - c;
- const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS;
- HVX_Vector v = ((const HVX_Vector *) tile)[r1];
- HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one);
-
- HVX_Vector v_out0 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp));
- if (src2_row_base) {
- HVX_Vector v_src2_0 = hvx_vmemu(src2_row_base + c + 0);
- v_out0 = hvx_vec_add_f32_f32(v_out0, v_src2_0);
- }
- hvx_vec_store_u(output_row_base + c, valid_c * sizeof(float), v_out0);
-
- if (r + 1 < n_rows) {
- HVX_Vector v_out1 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp));
- if (src2_row_base) {
- HVX_Vector v_src2_1 = hvx_vmemu(src2_row_base + c + src2_stride);
- v_out1 = hvx_vec_add_f32_f32(v_out1, v_src2_1);
- }
- hvx_vec_store_u(output_row_base + c + dst_stride, valid_c * sizeof(float), v_out1);
- }
- }
- }
-}
-
-static inline void transfer_output_chunk_fp16_to_fp32(
- float *restrict dst,
- const float *restrict src2,
- const __fp16 *restrict vtcm_src,
- uint32_t start_row,
- uint32_t n_rows,
- uint32_t n_cols,
- uint32_t dst_stride,
- uint32_t src2_stride,
- uint32_t dst_cols
-) {
- transfer_output_chunk_fp16_to_fp32_col_chunk(
- dst, src2, vtcm_src, start_row, n_rows, n_cols, n_cols, dst_stride, src2_stride, dst_cols
- );
-}
-
-typedef struct {
- const __fp16 *vtcm_src;
- float *dst;
- const float *src2;
- uint32_t n_tasks;
- uint32_t n_tot_chunks;
- uint32_t n_chunks_per_task;
- uint32_t n_cols;
- uint32_t dst_stride; // DDR row stride
- uint32_t src2_stride; // DDR row stride for residual
- uint32_t dst_cols; // Actual output columns
-} output_transfer_task_state_t;
-
-// activations : fp32 -> fp16
-
-static void transfer_activation_row_pair_fp32_to_fp16(
- __fp16 *restrict vtcm_dst,
- const float *restrict row0,
- const float *restrict row1,
- uint32_t r,
- uint32_t k_block,
- uint32_t k_valid,
- bool row0_valid,
- bool row1_valid) {
-
- uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- uint32_t c = 0;
- for (; c + 32 <= k_valid; c += 32) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- if (c < k_block) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
-
- uint32_t rem = k_valid - c;
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
- v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
-}
-
-// F16-input variant of transfer_activation_row_pair_fp32_to_fp16, for F16 activation
-// (src1). Same shape as the F16 Q-prep in hmx-fa-kernels.h: one 128-byte load carries 64 f16
-// = two tile columns, and Q6_W_vshuff_VVR interleaves the two rows straight into the HMX tile
-// layout, so no F32 round-trip is needed. Rows are only 64-byte aligned when k_block is an odd
-// multiple of the tile width, hence the unaligned load type.
-static void transfer_activation_row_pair_f16_to_f16(__fp16 * restrict vtcm_dst,
- const __fp16 * restrict row0,
- const __fp16 * restrict row1,
- uint32_t r,
- uint32_t k_block,
- uint32_t k_valid,
- bool row0_valid,
- bool row1_valid) {
- uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- const uint32_t n_tile_cols = k_block / HTP_MM_HMX_TILE_N_COLS;
- __fp16 * restrict tile_row = vtcm_dst + (size_t) r0 * n_tile_cols * HTP_MM_HMX_TILE_N_ELMS;
-
- const HVX_UVector * pv0 = row0_valid ? (const HVX_UVector *) row0 : NULL;
- const HVX_UVector * pv1 = row1_valid ? (const HVX_UVector *) row1 : NULL;
-
- uint32_t c = 0;
- for (; c + 64 <= k_valid; c += 64) {
- HVX_Vector v0 = pv0 ? pv0[c / 64] : Q6_V_vzero();
- HVX_Vector v1 = pv1 ? pv1[c / 64] : Q6_V_vzero();
- HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
-
- HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS);
- HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS);
-
- tile0[r1 / 2] = Q6_V_lo_W(vp);
- tile1[r1 / 2] = Q6_V_hi_W(vp);
- }
- // Tail: fewer than 64 valid columns left, plus the k_valid..k_block padding that HMX will
- // still multiply, so it has to be written as zeros.
- for (; c < k_block; c += 64) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
-
- if (c < k_valid) {
- uint32_t rem = k_valid - c; // 1..63 valid f16 lanes
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(__fp16));
- if (pv0) {
- v0 = Q6_V_vmux_QVV(mask, pv0[c / 64], Q6_V_vzero());
- }
- if (pv1) {
- v1 = Q6_V_vmux_QVV(mask, pv1[c / 64], Q6_V_vzero());
- }
- }
-
- HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
-
- HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS);
- tile0[r1 / 2] = Q6_V_lo_W(vp);
-
- if (c0 + 1 < n_tile_cols) {
- HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS);
- tile1[r1 / 2] = Q6_V_hi_W(vp);
- }
- }
-}
-
-static void transfer_activation_row_pair_fp32_to_fp16_col_chunk(
- __fp16 *restrict vtcm_dst,
- const float *restrict row0, // offset by c_first
- const float *restrict row1, // offset by c_first
- uint32_t r,
- uint32_t k_block,
- uint32_t c_first,
- uint32_t c_len,
- uint32_t k_chunk_valid,
- bool row0_valid,
- bool row1_valid) {
-
- uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- uint32_t c = 0;
- for (; c + 32 <= k_chunk_valid; c += 32) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- if (c < c_len) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c);
-
- uint32_t rem = (k_chunk_valid > c) ? (k_chunk_valid - c) : 0;
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
- v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
-}
-
-static void transfer_activation_chunk_fp32_to_fp16_gathered(
- __fp16 *restrict vtcm_dst,
- const float *restrict src,
- uint32_t start_row,
- uint32_t vtcm_start_row,
- uint32_t n_rows,
- uint32_t k_block,
- 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,
- uint32_t cne1,
- uint32_t k_valid) {
- const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS);
- const uint32_t n_rows_tiled = (n_rows / HTP_MM_HMX_TILE_N_ROWS) * HTP_MM_HMX_TILE_N_ROWS;
-
- uint32_t r = 0;
-
- #pragma unroll(2)
- for (r = 0; r < n_rows_tiled; r += 2) {
- uint32_t r_idx0 = start_row + r + 0;
- uint32_t r_idx1 = start_row + r + 1;
- uint32_t lr = vtcm_start_row + r; // vtcm-local row
- uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + r_idx0];
- struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + r_idx1];
-
- uint32_t i11_0 = fastmodulo(mapping0.i1, ne11, ne11_div);
- uint32_t i11_1 = fastmodulo(mapping1.i1, ne11, ne11_div);
-
- const float *row0_ptr = (const float *) ((const uint8_t *) src + i11_0 * nb11 + mapping0.i2 * nb12);
- const float *row1_ptr = (const float *) ((const uint8_t *) src + i11_1 * nb11 + mapping1.i2 * nb12);
-
- uint32_t c = 0;
- for (; c + 32 <= k_valid; c += 32) {
- HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c);
- HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c);
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- if (c < k_block) {
- HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c);
- HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c);
-
- uint32_t rem = k_valid - c;
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
- v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- }
-
- for (; r < n_rows_padded; r += 2) {
- uint32_t lr = vtcm_start_row + r; // vtcm-local row
- uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- const bool row0_valid = (start_row + r + 0) < cne1;
- const bool row1_valid = (start_row + r + 1) < cne1;
-
- const float *row0_ptr = NULL;
- const float *row1_ptr = NULL;
-
- if (row0_valid) {
- struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + (start_row + r + 0)];
- uint32_t i11_0 = fastmodulo(mapping0.i1, ne11, ne11_div);
- row0_ptr = (const float *) ((const uint8_t *) src + i11_0 * nb11 + mapping0.i2 * nb12);
- }
- if (row1_valid) {
- struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + (start_row + r + 1)];
- uint32_t i11_1 = fastmodulo(mapping1.i1, ne11, ne11_div);
- row1_ptr = (const float *) ((const uint8_t *) src + i11_1 * nb11 + mapping1.i2 * nb12);
- }
-
- uint32_t c = 0;
- for (; c + 32 <= k_valid; c += 32) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c);
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- if (c < k_block) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c);
-
- uint32_t rem = k_valid - c;
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
- v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- }
-}
-
-static void transfer_activation_chunk_fp32_to_fp16_gathered_flat(
- __fp16 *restrict vtcm_dst,
- const float *restrict src,
- uint32_t start_row,
- uint32_t vtcm_start_row,
- uint32_t n_rows,
- uint32_t k_block,
- const struct mmid_row_mapping *matrix_rows,
- uint32_t cur_a,
- uint32_t mapping_stride,
- size_t nb12,
- uint32_t cne1,
- uint32_t k_valid) {
- const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS);
- const uint32_t n_rows_tiled = (n_rows / HTP_MM_HMX_TILE_N_ROWS) * HTP_MM_HMX_TILE_N_ROWS;
-
- uint32_t r = 0;
-
- #pragma unroll(2)
- for (r = 0; r < n_rows_tiled; r += 2) {
- uint32_t r_idx0 = start_row + r + 0;
- uint32_t r_idx1 = start_row + r + 1;
- uint32_t lr = vtcm_start_row + r; // vtcm-local row
- uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + r_idx0];
- struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + r_idx1];
-
- const float *row0_ptr = (const float *) ((const uint8_t *) src + mapping0.i2 * nb12);
- const float *row1_ptr = (const float *) ((const uint8_t *) src + mapping1.i2 * nb12);
-
- uint32_t c = 0;
- for (; c + 32 <= k_valid; c += 32) {
- HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c);
- HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c);
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- if (c < k_block) {
- HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c);
- HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c);
-
- uint32_t rem = k_valid - c;
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
- v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- }
-
- for (; r < n_rows_padded; r += 2) {
- uint32_t lr = vtcm_start_row + r; // vtcm-local row
- uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index
- uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx
-
- const bool row0_valid = (start_row + r + 0) < cne1;
- const bool row1_valid = (start_row + r + 1) < cne1;
-
- const float *row0_ptr = NULL;
- const float *row1_ptr = NULL;
-
- if (row0_valid) {
- struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + (start_row + r + 0)];
- row0_ptr = (const float *) ((const uint8_t *) src + mapping0.i2 * nb12);
- }
- if (row1_valid) {
- struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + (start_row + r + 1)];
- row1_ptr = (const float *) ((const uint8_t *) src + mapping1.i2 * nb12);
- }
-
- uint32_t c = 0;
- for (; c + 32 <= k_valid; c += 32) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c);
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- if (c < k_block) {
- HVX_Vector v0 = Q6_V_vzero();
- HVX_Vector v1 = Q6_V_vzero();
- if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c);
- if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c);
-
- uint32_t rem = k_valid - c;
- HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0);
- v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero());
- v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero());
-
- HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1);
-
- uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0;
-
- HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS);
- tile[r1 / 2] = v_out;
- }
- }
-}
-
-static void transfer_output_chunk_fp16_to_fp32_scattered(
- float *restrict dst,
- const __fp16 *restrict vtcm_src,
- uint32_t start_row,
- uint32_t vtcm_start_row,
- uint32_t n_rows,
- uint32_t n_cols,
- const struct mmid_row_mapping *matrix_rows,
- uint32_t cur_a,
- uint32_t mapping_stride,
- size_t dst_nb1,
- size_t dst_nb2,
- uint32_t cne1) {
- assert(n_cols % HTP_MM_HMX_TILE_N_COLS == 0);
- const size_t tile_row_stride = (n_cols / HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS;
-
- const HVX_Vector one = hvx_vec_splat_f16(1.0);
-
- for (size_t r = 0; r < n_rows; r += 2) {
- uint32_t r_idx0 = start_row + r + 0;
- uint32_t r_idx1 = start_row + r + 1;
- uint32_t lr = vtcm_start_row + r; // vtcm-local row
- const size_t r0 = (lr / HTP_MM_HMX_TILE_N_ROWS);
- const size_t r1 = (lr % HTP_MM_HMX_TILE_N_ROWS) / 2; // index of the row pair within the tile
- const __fp16 *row_base = vtcm_src + r0 * tile_row_stride;
-
- if (r_idx0 >= cne1) break;
-
- struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + r_idx0];
- float *output_row0 = (float *) ((uint8_t *) dst + mapping0.i1 * dst_nb1 + mapping0.i2 * dst_nb2);
-
- float *output_row1 = NULL;
- if (r_idx1 < cne1) {
- struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + r_idx1];
- output_row1 = (float *) ((uint8_t *) dst + mapping1.i1 * dst_nb1 + mapping1.i2 * dst_nb2);
- }
-
- #pragma unroll(4)
- for (size_t c = 0; c < (size_t)n_cols; c += HTP_MM_HMX_TILE_N_COLS) {
- const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS;
- const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS;
- HVX_Vector v = ((const HVX_Vector *) tile)[r1];
- HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one);
-
- hvx_vmemu(output_row0 + c) = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp));
- if (output_row1) {
- hvx_vmemu(output_row1 + c) = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp));
- }
- }
- }
-}
diff --git a/ggml/src/ggml-hexagon/htp/hmx-queue.c b/ggml/src/ggml-hexagon/htp/hmx-queue.c
index e40a28bed..92dd3b360 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-queue.c
+++ b/ggml/src/ggml-hexagon/htp/hmx-queue.c
@@ -1,5 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-function"
-
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
@@ -14,49 +12,59 @@
#define QURT_LOWEST_PRIO (254)
-static inline void hmx_lock(hmx_queue_t q)
-{
+static inline void hmx_lock(hmx_queue_t q) {
if (!q->hmx_locked) {
- HAP_compute_res_hmx_lock(q->hap_rctx);
- q->hmx_locked = true;
+ if (HAP_compute_res_hmx_lock(q->hap_rctx) == 0) {
+ q->hmx_locked = true;
+ } else {
+ FARF(ERROR, "hmx-queue: HAP_compute_res_hmx_lock failed\n");
+ }
}
}
-static inline void hmx_unlock(hmx_queue_t q)
-{
+static inline void hmx_unlock(hmx_queue_t q) {
if (q->hmx_locked) {
HAP_compute_res_hmx_unlock(q->hap_rctx);
q->hmx_locked = false;
}
}
-static inline void hmx_queue_process(hmx_queue_t q, bool* killed) {
- unsigned int ir = atomic_load(&q->idx_read);
-
- while (ir != atomic_load(&q->idx_write)) {
- struct hmx_queue_desc *d = &q->desc[ir];
- if (!d->done) {
- FARF(HIGH, "hmx-queue-process: ir %u func %p data %p", ir, d->func, d->data);
-
- uintptr_t sig = (uintptr_t) d->func;
- switch (sig) {
- case HMX_QUEUE_NOOP: /* noop */; break;
- case HMX_QUEUE_KILL: *killed = true; break;
- case HMX_QUEUE_SUSPEND: hmx_unlock(q); break;
- case HMX_QUEUE_WAKEUP: hmx_lock(q); break;
- default:
- hmx_lock(q);
- htp_trace_event_start(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir);
- d->func(&q->th, d->data);
- htp_trace_event_stop(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir);
- break;
- }
-
- atomic_fetch_add(&d->done, 1);
+static inline void hmx_queue_process(hmx_queue_t q, bool * killed) {
+ uint32_t ir = atomic_load_explicit(&q->idx_read, memory_order_relaxed);
+
+ while (ir != atomic_load_explicit(&q->idx_write, memory_order_acquire)) {
+ struct hmx_queue_desc * d = &q->desc[ir & q->idx_mask];
+
+ FARF(HIGH, "hmx-queue-process: ir %u func %p data %p", ir, d->func, d->data);
+
+ uintptr_t sig = (uintptr_t) d->func;
+ switch (sig) {
+ case HMX_QUEUE_KILL:
+ hmx_unlock(q);
+ *killed = true;
+ break;
+ case HMX_QUEUE_SUSPEND:
+ hmx_unlock(q);
+ break;
+ case HMX_QUEUE_WAKEUP:
+ hmx_lock(q);
+ break;
+ default:
+ hmx_lock(q);
+ htp_trace_event_start(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir);
+ d->func(&q->th, d->data);
+ // drain HMX VTCM stores before signaling completion to HVX workers
+ asm volatile("syncht" ::: "memory");
+ htp_trace_event_stop(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir);
+ break;
}
- ir = (ir + 1) & q->idx_mask;
- atomic_store(&q->idx_read, ir);
+ ir++;
+ atomic_store_explicit(&q->idx_read, ir, memory_order_release);
+
+ if (*killed) {
+ break;
+ }
}
}
@@ -70,13 +78,16 @@ static void hmx_queue_thread(void * arg) {
unsigned int poll_cnt = HMX_QUEUE_POLL_COUNT;
unsigned int prev_seqn = 0;
while (!killed) {
- unsigned int seqn = atomic_load(&q->seqn);
+ unsigned int seqn = atomic_load_explicit(&q->seqn, memory_order_acquire);
if (seqn == prev_seqn) {
- // drop HVX context while spinning
- if (poll_cnt > 1 && poll_cnt == HMX_QUEUE_POLL_COUNT) {
+ // drop HVX context before spinning/sleeping
+ if (poll_cnt == HMX_QUEUE_POLL_COUNT) {
qurt_hvx_unlock();
}
- if (--poll_cnt) { hex_pause(); continue; }
+ if (--poll_cnt) {
+ hex_pause();
+ continue;
+ }
FARF(HIGH, "hmx-queue-thread: sleeping");
qurt_futex_wait(&q->seqn, prev_seqn);
poll_cnt = HMX_QUEUE_POLL_COUNT;
@@ -94,9 +105,9 @@ static void hmx_queue_thread(void * arg) {
}
size_t hmx_queue_sizeof(size_t capacity, uint32_t stack_size) {
- capacity = hex_ceil_pow2(capacity);
- size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE);
- size_t size_desc = hex_align_up(capacity * sizeof(struct hmx_queue_desc), HEX_L2_LINE_SIZE);
+ capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1);
+ size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE);
+ size_t size_desc = hex_align_up(capacity * sizeof(struct hmx_queue_desc), HEX_L2_LINE_SIZE);
size_t size_stack = stack_size;
return size_q + size_desc + size_stack;
}
@@ -106,21 +117,26 @@ size_t hmx_queue_alignof(void) {
}
hmx_queue_t hmx_queue_init(void * ptr, size_t capacity, uint32_t stack_size, uint32_t hap_rctx, dma_queue_t * dma, struct htp_thread_trace * trace) {
- capacity = hex_ceil_pow2(capacity);
- size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE);
+ capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1);
+ size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE);
size_t size_desc = hex_align_up(capacity * sizeof(struct hmx_queue_desc), HEX_L2_LINE_SIZE);
uint8_t * block = (uint8_t *) ptr;
- hmx_queue_t q = (hmx_queue_t) block; block += size_q;
+ hmx_queue_t q = (hmx_queue_t) block;
+ block += size_q;
memset(q, 0, sizeof(struct hmx_queue_s));
q->capacity = capacity;
q->idx_mask = capacity - 1;
+ q->idx_pop = 0;
q->hap_rctx = hap_rctx;
- q->external_mem = true;
+ atomic_init(&q->idx_write, 0);
+ atomic_init(&q->idx_read, 0);
+ atomic_init(&q->seqn, 0);
- q->desc = (struct hmx_queue_desc *) block; block += size_desc;
+ q->desc = (struct hmx_queue_desc *) block;
+ block += size_desc;
memset(q->desc, 0, capacity * sizeof(struct hmx_queue_desc));
q->stack = block;
@@ -128,7 +144,7 @@ hmx_queue_t hmx_queue_init(void * ptr, size_t capacity, uint32_t stack_size, uin
htp_thread_init(&q->th, dma, trace);
- // Match caller thread priority (same pattern as worker-pool.c).
+ // Match caller thread priority (same pattern as work-queue.c).
int prio = qurt_thread_get_priority(qurt_thread_get_id());
if (prio < 1) {
prio = 1;
diff --git a/ggml/src/ggml-hexagon/htp/hmx-queue.h b/ggml/src/ggml-hexagon/htp/hmx-queue.h
index efefb1455..fb9c5ab53 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-queue.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-queue.h
@@ -26,35 +26,33 @@ extern "C" {
typedef void (*hmx_queue_func)(const htp_thread_t * th, void *);
-// Dummy funcs used as signals
+// Dummy funcs used as signals (non-zero so NULL remains the empty sentinel)
enum hmx_queue_signal {
- HMX_QUEUE_NOOP = 0, // aka NULL
- HMX_QUEUE_WAKEUP,
- HMX_QUEUE_SUSPEND,
- HMX_QUEUE_KILL
+ HMX_QUEUE_WAKEUP = 1,
+ HMX_QUEUE_SUSPEND = 2,
+ HMX_QUEUE_KILL = 3,
};
struct hmx_queue_desc {
- hmx_queue_func func;
- void * data;
- atomic_uint done;
+ hmx_queue_func func;
+ void * data;
};
struct hmx_queue_s {
struct hmx_queue_desc * desc;
- atomic_uint idx_write; // updated by producer (push)
- atomic_uint idx_read; // updated by consumer (process)
- unsigned int idx_pop; // updated by producer (pop)
- uint32_t idx_mask;
- uint32_t capacity;
-
- atomic_uint seqn; // incremented for all pushes, used with futex
- qurt_thread_t thread;
- htp_thread_t th;
- void * stack;
- uint32_t hap_rctx;
- bool hmx_locked;
- bool external_mem; // memory owned externally
+ atomic_uint idx_write; // monotonic, updated by producer (push)
+ uint32_t idx_pop; // monotonic, updated by producer (pop)
+ uint32_t idx_mask;
+ uint32_t capacity;
+ atomic_uint seqn; // incremented for all pushes, used with futex
+
+ atomic_uint idx_read __attribute__((aligned(HEX_L2_LINE_SIZE))); // monotonic, updated by consumer
+ bool hmx_locked;
+
+ qurt_thread_t thread;
+ htp_thread_t th;
+ void * stack;
+ uint32_t hap_rctx;
};
typedef struct hmx_queue_s * hmx_queue_t;
@@ -70,37 +68,37 @@ static inline struct hmx_queue_desc hmx_queue_make_desc(hmx_queue_func func, voi
}
static inline bool hmx_queue_push(hmx_queue_t q, struct hmx_queue_desc d) {
- unsigned int ir = atomic_load(&q->idx_read);
- unsigned int iw = atomic_load(&q->idx_write);
+ uint32_t iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed);
- if (((iw + 1) & q->idx_mask) == ir) {
+ if ((iw - q->idx_pop) >= q->capacity) {
FARF(HIGH, "hmx-queue-push: queue is full\n");
return false;
}
- atomic_store(&d.done, 0);
-
FARF(HIGH, "hmx-queue-push: iw %u func %p data %p\n", iw, d.func, d.data);
- q->desc[iw] = d;
- atomic_store(&q->idx_write, (iw + 1) & q->idx_mask);
+ q->desc[iw & q->idx_mask] = d;
+ atomic_store_explicit(&q->idx_write, iw + 1, memory_order_release);
+
// wake up our thread
- atomic_fetch_add(&q->seqn, 1);
+ unsigned int seqn = atomic_load_explicit(&q->seqn, memory_order_relaxed) + 1;
+ atomic_store_explicit(&q->seqn, seqn, memory_order_release);
qurt_futex_wake(&q->seqn, 1);
return true;
}
static inline bool hmx_queue_signal(hmx_queue_t q, enum hmx_queue_signal sig) {
- return hmx_queue_push(q, hmx_queue_make_desc((hmx_queue_func) sig, NULL));
+ return hmx_queue_push(q, hmx_queue_make_desc((hmx_queue_func) (uintptr_t) sig, NULL));
}
static inline bool hmx_queue_empty(hmx_queue_t q) {
- return q->idx_pop == atomic_load(&q->idx_write);
+ return q->idx_pop == atomic_load_explicit(&q->idx_write, memory_order_relaxed);
}
static inline uint32_t hmx_queue_depth(hmx_queue_t q) {
- return (atomic_load(&q->idx_write) - atomic_load(&q->idx_read)) & q->idx_mask;
+ return atomic_load_explicit(&q->idx_write, memory_order_relaxed) -
+ atomic_load_explicit(&q->idx_read, memory_order_relaxed);
}
static inline uint32_t hmx_queue_capacity(hmx_queue_t q) {
@@ -108,23 +106,23 @@ static inline uint32_t hmx_queue_capacity(hmx_queue_t q) {
}
static inline struct hmx_queue_desc hmx_queue_pop_one(hmx_queue_t q) {
- unsigned int ip = q->idx_pop;
- unsigned int iw = atomic_load(&q->idx_write);
+ uint32_t ip = q->idx_pop;
+ uint32_t iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed);
struct hmx_queue_desc rd = { NULL, NULL };
if (ip == iw) {
return rd;
}
- // Wait for desc to complete
- struct hmx_queue_desc * d = &q->desc[ip];
- while (!atomic_load(&d->done)) {
+ // Wait for consumer to finish slot ip
+ while ((int32_t) (atomic_load_explicit(&q->idx_read, memory_order_relaxed) - ip) <= 0) {
FARF(HIGH, "hmx-queue-pop: waiting for HMX queue : %u\n", ip);
hex_pause();
}
+ atomic_thread_fence(memory_order_acquire);
- rd = *d;
- q->idx_pop = (ip + 1) & q->idx_mask;
+ rd = q->desc[ip & q->idx_mask];
+ q->idx_pop = ip + 1;
FARF(HIGH, "hmx-queue-pop: ip %u func %p data %p\n", ip, rd.func, rd.data);
return rd;
@@ -134,9 +132,10 @@ static inline struct hmx_queue_desc hmx_queue_pop(hmx_queue_t q) {
while (1) {
struct hmx_queue_desc d = hmx_queue_pop_one(q);
- uint32_t sig = (uint32_t) d.func;
- if (sig && sig <= HMX_QUEUE_KILL)
+ uintptr_t sig = (uintptr_t) d.func;
+ if (sig && sig <= HMX_QUEUE_KILL) {
continue;
+ }
return d;
}
diff --git a/ggml/src/ggml-hexagon/htp/hmx-utils.h b/ggml/src/ggml-hexagon/htp/hmx-utils.h
index 1952aaa2c..2a64bd442 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-utils.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-utils.h
@@ -35,6 +35,120 @@ static const int32_t hmx_transpose_scatter_offsets[32] __attribute__((aligned(VL
22 * 128, 23 * 128, 24 * 128, 25 * 128, 26 * 128, 27 * 128, 28 * 128, 29 * 128, 30 * 128, 31 * 128,
};
+// 5-stage vshuffvdd transpose of a 32x64 FP16 block into two contiguous 32x32 HMX tiles.
+// Stages 1-3 (-4, -8, -16) mix groups of 8 rows into a 4KB stack scratch; stages 4-5 (-32, -64)
+// Stage in-place in dst_tile0/dst_tile1 (each 4-vector slot holds g=0..3), then
+// combine across the 4 groups in-place with zero stack scratch.
+static inline void hmx_transpose_k_pair_tiles_vshuff(HVX_Vector * restrict dst_tile0,
+ HVX_Vector * restrict dst_tile1,
+ const uint8_t * restrict src_base,
+ size_t row_byte_stride,
+ uint32_t valid_rows) {
+ if (valid_rows >= HMX_FP16_TILE_N_ROWS) {
+ for (uint32_t g = 0; g < 4; ++g) {
+ const uint8_t * p = src_base + (size_t) (8 * g) * row_byte_stride;
+ HVX_Vector r0 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r1 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r2 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r3 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r4 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r5 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r6 = hvx_vmem(p); p += row_byte_stride;
+ HVX_Vector r7 = hvx_vmem(p);
+
+ HVX_VectorPair p01 = Q6_W_vshuff_VVR(r1, r0, -4);
+ HVX_VectorPair p23 = Q6_W_vshuff_VVR(r3, r2, -4);
+ HVX_VectorPair p45 = Q6_W_vshuff_VVR(r5, r4, -4);
+ HVX_VectorPair p67 = Q6_W_vshuff_VVR(r7, r6, -4);
+ r0 = Q6_V_lo_W(p01); r1 = Q6_V_hi_W(p01);
+ r2 = Q6_V_lo_W(p23); r3 = Q6_V_hi_W(p23);
+ r4 = Q6_V_lo_W(p45); r5 = Q6_V_hi_W(p45);
+ r6 = Q6_V_lo_W(p67); r7 = Q6_V_hi_W(p67);
+
+ HVX_VectorPair p02 = Q6_W_vshuff_VVR(r2, r0, -8);
+ HVX_VectorPair p13 = Q6_W_vshuff_VVR(r3, r1, -8);
+ HVX_VectorPair p46 = Q6_W_vshuff_VVR(r6, r4, -8);
+ HVX_VectorPair p57 = Q6_W_vshuff_VVR(r7, r5, -8);
+ r0 = Q6_V_lo_W(p02); r2 = Q6_V_hi_W(p02);
+ r1 = Q6_V_lo_W(p13); r3 = Q6_V_hi_W(p13);
+ r4 = Q6_V_lo_W(p46); r6 = Q6_V_hi_W(p46);
+ r5 = Q6_V_lo_W(p57); r7 = Q6_V_hi_W(p57);
+
+ HVX_VectorPair p04 = Q6_W_vshuff_VVR(r4, r0, -16);
+ HVX_VectorPair p15 = Q6_W_vshuff_VVR(r5, r1, -16);
+ HVX_VectorPair p26 = Q6_W_vshuff_VVR(r6, r2, -16);
+ HVX_VectorPair p37 = Q6_W_vshuff_VVR(r7, r3, -16);
+
+ dst_tile0[ 0 + g] = Q6_V_lo_W(p04); dst_tile0[ 4 + g] = Q6_V_hi_W(p04);
+ dst_tile1[ 0 + g] = Q6_V_lo_W(p15); dst_tile1[ 4 + g] = Q6_V_hi_W(p15);
+ dst_tile0[ 8 + g] = Q6_V_lo_W(p26); dst_tile0[12 + g] = Q6_V_hi_W(p26);
+ dst_tile1[ 8 + g] = Q6_V_lo_W(p37); dst_tile1[12 + g] = Q6_V_hi_W(p37);
+ }
+ } else {
+ const HVX_Vector vzero = Q6_V_vzero();
+ for (uint32_t g = 0; g < 4; ++g) {
+ const uint32_t base_r = 8 * g;
+ const uint8_t * p = src_base + (size_t) base_r * row_byte_stride;
+ HVX_Vector r0 = (base_r + 0 < valid_rows) ? hvx_vmem(p + 0 * row_byte_stride) : vzero;
+ HVX_Vector r1 = (base_r + 1 < valid_rows) ? hvx_vmem(p + 1 * row_byte_stride) : vzero;
+ HVX_Vector r2 = (base_r + 2 < valid_rows) ? hvx_vmem(p + 2 * row_byte_stride) : vzero;
+ HVX_Vector r3 = (base_r + 3 < valid_rows) ? hvx_vmem(p + 3 * row_byte_stride) : vzero;
+ HVX_Vector r4 = (base_r + 4 < valid_rows) ? hvx_vmem(p + 4 * row_byte_stride) : vzero;
+ HVX_Vector r5 = (base_r + 5 < valid_rows) ? hvx_vmem(p + 5 * row_byte_stride) : vzero;
+ HVX_Vector r6 = (base_r + 6 < valid_rows) ? hvx_vmem(p + 6 * row_byte_stride) : vzero;
+ HVX_Vector r7 = (base_r + 7 < valid_rows) ? hvx_vmem(p + 7 * row_byte_stride) : vzero;
+
+ HVX_VectorPair p01 = Q6_W_vshuff_VVR(r1, r0, -4);
+ HVX_VectorPair p23 = Q6_W_vshuff_VVR(r3, r2, -4);
+ HVX_VectorPair p45 = Q6_W_vshuff_VVR(r5, r4, -4);
+ HVX_VectorPair p67 = Q6_W_vshuff_VVR(r7, r6, -4);
+ r0 = Q6_V_lo_W(p01); r1 = Q6_V_hi_W(p01);
+ r2 = Q6_V_lo_W(p23); r3 = Q6_V_hi_W(p23);
+ r4 = Q6_V_lo_W(p45); r5 = Q6_V_hi_W(p45);
+ r6 = Q6_V_lo_W(p67); r7 = Q6_V_hi_W(p67);
+
+ HVX_VectorPair p02 = Q6_W_vshuff_VVR(r2, r0, -8);
+ HVX_VectorPair p13 = Q6_W_vshuff_VVR(r3, r1, -8);
+ HVX_VectorPair p46 = Q6_W_vshuff_VVR(r6, r4, -8);
+ HVX_VectorPair p57 = Q6_W_vshuff_VVR(r7, r5, -8);
+ r0 = Q6_V_lo_W(p02); r2 = Q6_V_hi_W(p02);
+ r1 = Q6_V_lo_W(p13); r3 = Q6_V_hi_W(p13);
+ r4 = Q6_V_lo_W(p46); r6 = Q6_V_hi_W(p46);
+ r5 = Q6_V_lo_W(p57); r7 = Q6_V_hi_W(p57);
+
+ HVX_VectorPair p04 = Q6_W_vshuff_VVR(r4, r0, -16);
+ HVX_VectorPair p15 = Q6_W_vshuff_VVR(r5, r1, -16);
+ HVX_VectorPair p26 = Q6_W_vshuff_VVR(r6, r2, -16);
+ HVX_VectorPair p37 = Q6_W_vshuff_VVR(r7, r3, -16);
+
+ dst_tile0[ 0 + g] = Q6_V_lo_W(p04); dst_tile0[ 4 + g] = Q6_V_hi_W(p04);
+ dst_tile1[ 0 + g] = Q6_V_lo_W(p15); dst_tile1[ 4 + g] = Q6_V_hi_W(p15);
+ dst_tile0[ 8 + g] = Q6_V_lo_W(p26); dst_tile0[12 + g] = Q6_V_hi_W(p26);
+ dst_tile1[ 8 + g] = Q6_V_lo_W(p37); dst_tile1[12 + g] = Q6_V_hi_W(p37);
+ }
+ }
+
+ for (uint32_t t = 0; t < 2; ++t) {
+ HVX_Vector * dst = t ? dst_tile1 : dst_tile0;
+ for (uint32_t p0 = 0; p0 < 16; p0 += 4) {
+ HVX_Vector a = dst[p0 + 0];
+ HVX_Vector b = dst[p0 + 1];
+ HVX_Vector c = dst[p0 + 2];
+ HVX_Vector d = dst[p0 + 3];
+
+ HVX_VectorPair pab = Q6_W_vshuff_VVR(b, a, -32);
+ HVX_VectorPair pcd = Q6_W_vshuff_VVR(d, c, -32);
+ HVX_VectorPair out0 = Q6_W_vshuff_VVR(Q6_V_lo_W(pcd), Q6_V_lo_W(pab), -64);
+ HVX_VectorPair out1 = Q6_W_vshuff_VVR(Q6_V_hi_W(pcd), Q6_V_hi_W(pab), -64);
+
+ dst[p0 + 0] = Q6_V_lo_W(out0);
+ dst[p0 + 1] = Q6_V_hi_W(out0);
+ dst[p0 + 2] = Q6_V_lo_W(out1);
+ dst[p0 + 3] = Q6_V_hi_W(out1);
+ }
+ }
+}
+
// Scatter row-major FP16 data (in VTCM scratch) into transposed [K][N] tiles.
// vtcm_src: [n_cols][src_stride] row-major fp16 (only first k elements per row are used)
// vtcm_dst: [n_col_tiles][n_k_tiles][HMX_FP16_TILE_N_ELMS] tile-major interleaved fp16
@@ -50,18 +164,36 @@ static inline void hmx_interleave_rows_to_tiles(__fp16 * restrict vtcm_dst,
assert(k % HMX_FP16_TILE_N_COLS == 0);
const uint32_t n_k_tiles = k / HMX_FP16_TILE_N_COLS;
+ const bool pair_scatter = (n_k_tiles & 1) == 0;
+ __builtin_assume(k > 0);
+ __builtin_assume(end_row > start_row);
+
+ if (pair_scatter && ((start_row & 31) == 0) && ((end_row & 31) == 0) &&
+ hex_is_aligned(vtcm_src, 128) && ((src_stride & 63) == 0)) {
+ const uint32_t n_c_iters = n_k_tiles >> 1;
+ const size_t row_byte_stride = src_stride * sizeof(__fp16);
+ const size_t tile_pair_vecs = 2 * (HMX_FP16_TILE_SIZE / sizeof(HVX_Vector));
+
+ for (uint32_t r_base = start_row; r_base < end_row; r_base += HMX_FP16_TILE_N_ROWS) {
+ const uint32_t ct = r_base / HMX_FP16_TILE_N_ROWS;
+ const uint32_t valid_rows = (r_base < n_cols) ? (n_cols - r_base) : 0;
+ HVX_Vector * tile_base = (HVX_Vector *) (vtcm_dst + (size_t) ct * n_k_tiles * HMX_FP16_TILE_N_ELMS);
+ const uint8_t * row_src = (const uint8_t *) (vtcm_src + (size_t) r_base * src_stride);
+
+ for (uint32_t i = 0; i < n_c_iters; ++i) {
+ hmx_transpose_k_pair_tiles_vshuff(tile_base, tile_base + 16, row_src + (size_t) i * 128,
+ row_byte_stride, valid_rows);
+ tile_base += tile_pair_vecs;
+ }
+ }
+ return;
+ }
+
const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets);
const HVX_Vector v_scat_step = Q6_V_vsplat_R(4);
const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64);
- // Each hvx_vmemu load brings 64 fp16 = 128 bytes covering 2 adjacent K-tiles.
- // When n_k_tiles is even, scatter into 2 K-tiles per call (region 4095, no mask)
- // using the upper half of hmx_transpose_scatter_offsets. Tail one K-tile (when
- // n_k_tiles is odd) falls back to single-tile masked scatter.
- const bool pair_scatter = (n_k_tiles & 1) == 0;
const size_t pair_region = (size_t) (2 * HMX_FP16_TILE_SIZE - 1);
const size_t single_region = (size_t) (HMX_FP16_TILE_SIZE - 1);
- __builtin_assume(k > 0);
- __builtin_assume(end_row > start_row);
if (pair_scatter) {
// Step c by 64 fp16 (two K-tiles per scatter), advance dst by 2 tiles per iter.
@@ -148,6 +280,7 @@ static inline void hmx_interleave_rows_to_tiles(__fp16 * restrict vtcm_dst,
}
}
}
+ hvx_gather_sync(vtcm_dst);
}
// Interleave row-major FP16 data into column-major tile format.
@@ -227,4 +360,69 @@ static inline void hmx_interleave_cols_to_tiles(__fp16 * restrict tiles_out,
#define HMX_CLRACC_F16() \
"mxclracc.hf\n"
+// --- Fixed-point INT HMX inline asm macros and helpers (v73+) ---
+
+#define HMX_CLRACC_INT() \
+ "mxclracc\n"
+
+#define HMX_SWAPACC() \
+ "mxswapacc\n"
+
+#define HMX_LOAD_MPY_DEEP_U8_S8_SM(act, act_rt, wt, wt_rt) \
+ "{\n" \
+ " activation.ub = mxmem(" act ", " act_rt "):deep\n" \
+ " weight.b = mxmem(" wt ", " wt_rt ")\n" \
+ "}\n"
+
+#define HMX_LOAD_MPY_DEEP_U8_S8_SM_64C(act, act_rt, wt, wt_rt) \
+ "{\n" \
+ " activation.ub = mxmem(" act ", " act_rt "):deep\n" \
+ " weight.b = mxmem(" wt ", " wt_rt "):deep\n" \
+ "}\n"
+
+#define HMX_LOAD_MPY_DEEP_U8_S8_CM(act, act_rt, wt, wt_rt) \
+ "{\n" \
+ " activation.ub = mxmem(" act ", " act_rt "):deep:cm\n" \
+ " weight.b = mxmem(" wt ", " wt_rt ")\n" \
+ "}\n"
+
+#define HMX_LOAD_MPY_DEEP_U8_S8_CM_64C(act, act_rt, wt, wt_rt) \
+ "{\n" \
+ " activation.ub = mxmem(" act ", " act_rt "):deep:cm\n" \
+ " weight.b = mxmem(" wt ", " wt_rt "):deep\n" \
+ "}\n"
+
+#define HMX_CVT_UB_ACC(ctrl) \
+ "cvt.ub = acc(" ctrl ")\n"
+
+#define HMX_CVT_UH_ACC_2X1(ctrl) \
+ "cvt.uh = acc(" ctrl "):2x1\n"
+
+#define HMX_STORE_CVT_SM(out, range) \
+ "mxmem(" out ", " range ") = cvt\n"
+
+#define HMX_STORE_CVT_CM(out, range) \
+ "mxmem(" out ", " range "):cm = cvt\n"
+
+static inline uint32_t hmx_act_sm_range(uint32_t n_tiles) {
+ return 2048u * n_tiles - 1u;
+}
+
+static inline uint32_t hmx_out_cm_range(void) {
+ return 0x3Fu << 5;
+}
+
+static inline uint32_t hmx_wt_b_range(uint32_t n_bytes) {
+ return ((n_bytes - 128u) & ~127u) | 0x7Fu;
+}
+
+static inline uint32_t hmx_cvt_ctrl(uint32_t bank, uint32_t frac_only, uint32_t sat_mode, uint32_t retain_acc) {
+ return (1u << 15) | ((frac_only & 1u) << 14) | ((bank & 3u) << 12) | ((sat_mode & 1u) << 1) | (retain_acc & 1u);
+}
+
+static inline void hmx_load_bias_bank(const void * addr, uint32_t bank) {
+ uint32_t rs = ((uint32_t) (uintptr_t) addr & ~255u) | (bank & 3u);
+ asm volatile("bias = mxmem2(%0)\n" :: "r"(rs) : "memory");
+}
+
#endif // HMX_UTILS_H
diff --git a/ggml/src/ggml-hexagon/htp/htp-ctx.h b/ggml/src/ggml-hexagon/htp/htp-ctx.h
index 27b56ff0b..b514f633e 100644
--- a/ggml/src/ggml-hexagon/htp/htp-ctx.h
+++ b/ggml/src/ggml-hexagon/htp/htp-ctx.h
@@ -1,10 +1,11 @@
#ifndef HTP_CTX_H
#define HTP_CTX_H
+#include "dma-proxy.h"
#include "dma-queue.h"
#include "hmx-queue.h"
-#include "htp-dcache.h"
#include "htp-ops.h"
+#include "htp-thread.h"
#include "htp-trace.h"
#include "work-queue.h"
#include "hex-fastdiv.h"
@@ -27,15 +28,6 @@ struct htp_mmap {
uint32_t flags;
};
-// Scratchpad state
-struct htp_spad {
- const struct htp_tensor * src; // original src of the data (for reuse)
- uint8_t * data; // pointer to an area in vtcm
- uint32_t stride; // stride used inside this spad
- uint32_t size; // total size
- uint32_t size_per_hvx; // size per hvx
-};
-
struct htp_mdev_group {
uint16_t idx;
uint16_t count;
@@ -61,11 +53,6 @@ struct htp_ops_context {
const struct htp_tensor * dsts[HTP_OP_MAX_OUTPUTS];
};
- // TODO convert these to an array
- struct htp_spad src0_spad;
- struct htp_spad src1_spad;
- struct htp_spad dst_spad;
-
uint32_t flags;
uint32_t n_hvx;
struct fastdiv_values n_hvx_div;
@@ -86,8 +73,10 @@ struct htp_context {
struct htp_mmap mmap[HTP_MAX_MMAPS];
dma_queue_t dma[HTP_MAX_NTHREADS];
struct htp_thread_trace trace[HTP_MAX_NTHREADS];
+ htp_thread_t main_th;
work_queue_t hvx_queue;
hmx_queue_t hmx_queue;
+ dma_proxy_t dma_proxy;
uint32_t n_threads;
uint32_t n_hvx;
@@ -107,7 +96,6 @@ struct htp_context {
atomic_bool vtcm_needs_release;
uint64_t max_vmem;
- struct htp_dirty_range dirty_ranges[HTP_MAX_DIRTY_RANGES];
// Persistent DDR scratchpad for MUL_MAT_ID mappings
void * ddr_spad_base;
diff --git a/ggml/src/ggml-hexagon/htp/htp-dcache.c b/ggml/src/ggml-hexagon/htp/htp-dcache.c
deleted file mode 100644
index 52fc8e403..000000000
--- a/ggml/src/ggml-hexagon/htp/htp-dcache.c
+++ /dev/null
@@ -1,357 +0,0 @@
-#include "htp-dcache.h"
-
-#include <qurt.h>
-#include <qurt_memory.h>
-#include <HAP_farf.h>
-
-#include "hex-common.h"
-#include "hex-utils.h"
-#include "hex-fastdiv.h"
-#include "htp-trace.h"
-#include "htp-ctx.h"
-#include "work-queue.h"
-
-struct l2flush_range {
- uint32_t start; // line-aligned start address
- uint32_t end; // line-aligned end address
- uint32_t block_first; // global block index of this range's first block
- uint32_t n_blocks; // number of HTP_DCACHE_BLOCK_SIZE chunks (last may be partial)
-};
-
-struct l2flush_multi_task {
- struct l2flush_range ranges[HTP_MAX_DIRTY_RANGES];
- uint32_t n_ranges;
- uint32_t total_blocks;
- uint32_t blocks_per_hvx;
-};
-
-static void flush_all_dcache(struct htp_context * ctx) {
- struct htp_thread_trace * tr = &ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, 0);
- qurt_mem_cache_clean((qurt_addr_t) 0, 0, QURT_MEM_CACHE_FLUSH_INVALIDATE_ALL, QURT_MEM_DCACHE);
- hex_l2fetch_block(ctx, ctx->footprint);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, 0);
- memset(ctx->dirty_ranges, 0, sizeof(ctx->dirty_ranges));
-}
-
-static void l2flush_multi_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
- struct l2flush_multi_task * task = (struct l2flush_multi_task *) data;
- (void) n;
-
- const uint32_t gb_first = i * task->blocks_per_hvx;
- uint32_t gb_last = gb_first + task->blocks_per_hvx;
- if (gb_last > task->total_blocks) {
- gb_last = task->total_blocks;
- }
- if (gb_first >= gb_last) {
- return;
- }
-
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, gb_first);
-
- for (uint32_t r = 0; r < task->n_ranges; r++) {
- const struct l2flush_range * rg = &task->ranges[r];
- const uint32_t rb_first = rg->block_first;
- const uint32_t rb_last = rg->block_first + rg->n_blocks;
-
- const uint32_t lo = gb_first > rb_first ? gb_first : rb_first;
- const uint32_t hi = gb_last < rb_last ? gb_last : rb_last;
- if (lo >= hi) {
- continue;
- }
-
- const uint32_t s = rg->start + (lo - rb_first) * HTP_DCACHE_BLOCK_SIZE;
- uint32_t e = rg->start + (hi - rb_first) * HTP_DCACHE_BLOCK_SIZE;
- if (e > rg->end) {
- e = rg->end;
- }
- hex_l2flush((void *) (uintptr_t) s, e - s);
- }
-
- htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, gb_first);
-}
-
-static void merge_dirty_ranges(struct htp_context * ctx) {
- for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) {
- struct htp_dirty_range * r = &ctx->dirty_ranges[i];
- if (!r->start) continue;
-
- for (uint32_t j = 0; j < HTP_MAX_DIRTY_RANGES;) {
- struct htp_dirty_range * s = &ctx->dirty_ranges[j];
- if (i == j || !s->start || r->end < s->start || s->end < r->start) {
- j++;
- continue;
- }
-
- r->start = MIN(r->start, s->start);
- r->end = MAX(r->end, s->end);
- s->start = 0;
- s->end = 0;
- j = 0;
- }
- }
-}
-
-void htp_dcache_mark_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n) {
- const struct htp_tensor * pending[HTP_OP_MAX_OUTPUTS];
- uint32_t n_pending = 0;
-
- for (uint32_t i = 0; i < n; i++) {
- const struct htp_tensor * t = tensors[i];
- if (!t || (t->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) {
- continue;
- }
-
- uint32_t t_start = t->data;
- uint32_t t_end = t_start + t->size;
-
- bool merged = false;
- for (uint32_t j = 0; j < HTP_MAX_DIRTY_RANGES; j++) {
- struct htp_dirty_range * r = &ctx->dirty_ranges[j];
- if (!r->start) continue;
-
- if (r->start <= t_end && t_start <= r->end) {
- uint32_t new_start = (t_start < r->start) ? t_start : r->start;
- uint32_t new_end = (t_end > r->end) ? t_end : r->end;
- r->start = new_start;
- r->end = new_end;
- merged = true;
- }
- }
-
- if (!merged) {
- pending[n_pending++] = t;
- }
- }
-
- merge_dirty_ranges(ctx);
-
- if (n_pending == 0) {
- return;
- }
-
- uint32_t empty_indices[HTP_MAX_DIRTY_RANGES];
- uint32_t active_indices[HTP_MAX_DIRTY_RANGES];
- uint32_t n_active = 0;
- uint32_t n_empty = 0;
- for (uint32_t j = 0; j < HTP_MAX_DIRTY_RANGES; j++) {
- if (ctx->dirty_ranges[j].start) {
- active_indices[n_active++] = j;
- } else {
- empty_indices[n_empty++] = j;
- }
- }
-
- if (n_pending <= n_empty) {
- for (uint32_t i = 0; i < n_pending; i++) {
- uint32_t idx = empty_indices[i];
- struct htp_dirty_range * r = &ctx->dirty_ranges[idx];
- r->start = pending[i]->data;
- r->end = pending[i]->data + pending[i]->size;
- }
- merge_dirty_ranges(ctx);
- return;
- }
-
- uint32_t n_evict = n_pending - n_empty;
- uint32_t total_evict_size = 0;
- for (uint32_t i = 0; i < n_evict; i++) {
- uint32_t idx = active_indices[i];
- struct htp_dirty_range * r = &ctx->dirty_ranges[idx];
- total_evict_size += r->end - r->start;
- }
-
- if (total_evict_size > HTP_DCACHE_FLUSH_ALL_THRESHOLD) {
- flush_all_dcache(ctx);
- for (uint32_t i = 0; i < n_pending; i++) {
- struct htp_dirty_range * r = &ctx->dirty_ranges[i];
- r->start = pending[i]->data;
- r->end = pending[i]->data + pending[i]->size;
- }
- merge_dirty_ranges(ctx);
- return;
- }
-
- if (total_evict_size > HTP_DCACHE_FLUSH_WQ_THRESHOLD && ctx->n_hvx > 1 && n_evict <= HTP_MAX_DIRTY_RANGES) {
- struct l2flush_multi_task task;
- task.n_ranges = n_evict;
-
- uint32_t block_acc = 0;
- for (uint32_t i = 0; i < n_evict; i++) {
- uint32_t idx = active_indices[i];
- struct htp_dirty_range * r = &ctx->dirty_ranges[idx];
-
- struct l2flush_range * rg = &task.ranges[i];
- rg->start = hex_align_down((size_t) r->start, HEX_L2_LINE_SIZE);
- rg->end = hex_align_up((size_t) r->end, HEX_L2_LINE_SIZE);
- rg->block_first = block_acc;
- rg->n_blocks = (rg->end - rg->start + HTP_DCACHE_BLOCK_SIZE - 1) / HTP_DCACHE_BLOCK_SIZE;
- block_acc += rg->n_blocks;
- }
-
- task.total_blocks = block_acc;
- task.blocks_per_hvx = fastdiv(block_acc + ctx->n_hvx - 1, &ctx->n_hvx_div);
-
- work_queue_run(ctx->hvx_queue, l2flush_multi_worker, &task, ctx->n_hvx);
- } else {
- struct htp_thread_trace * tr = &ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, 0);
- for (uint32_t i = 0; i < n_evict; i++) {
- uint32_t idx = active_indices[i];
- struct htp_dirty_range * r = &ctx->dirty_ranges[idx];
- uint32_t size = r->end - r->start;
- hex_l2flush((void *) (uintptr_t) r->start, size);
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, 0);
- }
-
- for (uint32_t i = 0; i < n_evict; i++) {
- uint32_t idx = active_indices[i];
- struct htp_dirty_range * r = &ctx->dirty_ranges[idx];
- r->start = pending[i]->data;
- r->end = pending[i]->data + pending[i]->size;
- }
-
- for (uint32_t i = 0; i < n_empty; i++) {
- uint32_t idx = empty_indices[i];
- struct htp_dirty_range * r = &ctx->dirty_ranges[idx];
- r->start = pending[n_evict + i]->data;
- r->end = pending[n_evict + i]->data + pending[n_evict + i]->size;
- }
-
- merge_dirty_ranges(ctx);
-}
-
-static void make_tensor_clean(struct htp_context * ctx, const struct htp_tensor * t) {
- if (!t || (t->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) {
- return;
- }
-
- uint32_t t_start = t->data;
- uint32_t t_end = t_start + t->size;
-
- for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) {
- struct htp_dirty_range * r = &ctx->dirty_ranges[i];
- if (!r->start) continue;
-
- if (r->start < t_end && t_start < r->end) {
- if (t_start <= r->start && r->end <= t_end) {
- r->start = 0;
- r->end = 0;
- } else if (t_start <= r->start) {
- r->start = t_end;
- } else if (r->end <= t_end) {
- r->end = t_start;
- }
- }
- }
-}
-
-static inline bool is_tensor_dirty(struct htp_context * ctx, const struct htp_tensor * t) {
- if (!t || (t->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) {
- return false;
- }
-
- uint32_t t_start = t->data;
- uint32_t t_end = t_start + t->size;
-
- for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) {
- struct htp_dirty_range * r = &ctx->dirty_ranges[i];
- if (!r->start) continue;
-
- if (r->start < t_end && t_start < r->end) {
- return true;
- }
- }
- return false;
-}
-
-static void flush_dirty_ranges(struct htp_context * ctx, const struct htp_dirty_range * ranges, uint32_t n_ranges, uint64_t total_dirty) {
- if (total_dirty >= HTP_DCACHE_FLUSH_WQ_THRESHOLD && ctx->n_hvx > 1) {
- struct l2flush_multi_task task;
- task.n_ranges = n_ranges;
-
- uint32_t block_acc = 0;
- for (uint32_t i = 0; i < n_ranges; i++) {
- const struct htp_dirty_range * r = &ranges[i];
- struct l2flush_range * rg = &task.ranges[i];
- rg->start = hex_align_down((size_t) r->start, HEX_L2_LINE_SIZE);
- rg->end = hex_align_up((size_t) r->end, HEX_L2_LINE_SIZE);
- rg->block_first = block_acc;
- rg->n_blocks = (rg->end - rg->start + HTP_DCACHE_BLOCK_SIZE - 1) / HTP_DCACHE_BLOCK_SIZE;
- block_acc += rg->n_blocks;
- }
-
- task.total_blocks = block_acc;
- task.blocks_per_hvx = fastdiv(block_acc + ctx->n_hvx - 1, &ctx->n_hvx_div);
-
- work_queue_run(ctx->hvx_queue, l2flush_multi_worker, &task, ctx->n_hvx);
- } else {
- struct htp_thread_trace * tr = &ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, 0);
- for (uint32_t i = 0; i < n_ranges; i++) {
- const struct htp_dirty_range * r = &ranges[i];
- hex_l2flush((void *) (uintptr_t) r->start, r->end - r->start);
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, 0);
- }
-}
-
-void htp_dcache_flush_dirty_ranges(struct htp_context * ctx) {
- struct htp_dirty_range ranges[HTP_MAX_DIRTY_RANGES];
- uint32_t n_ranges = 0;
- uint64_t total_dirty = 0;
-
- for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) {
- const struct htp_dirty_range * r = &ctx->dirty_ranges[i];
- if (!r->start) {
- continue;
- }
- ranges[n_ranges++] = *r;
- total_dirty += r->end - r->start;
- }
-
- if (total_dirty == 0) {
- return;
- }
-
- if (total_dirty > HTP_DCACHE_FLUSH_ALL_THRESHOLD) {
- flush_all_dcache(ctx);
- return;
- }
-
- flush_dirty_ranges(ctx, ranges, n_ranges, total_dirty);
- memset(ctx->dirty_ranges, 0, sizeof(ctx->dirty_ranges));
-}
-
-void htp_dcache_flush_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n) {
- const struct htp_tensor * dirty_tensors[HTP_OP_MAX_INPUTS];
- struct htp_dirty_range ranges[HTP_OP_MAX_INPUTS];
- uint32_t n_dirty = 0;
- uint64_t total_dirty = 0;
-
- for (uint32_t i = 0; i < n; i++) {
- const struct htp_tensor * t = tensors[i];
- if (is_tensor_dirty(ctx, t)) {
- dirty_tensors[n_dirty++] = t;
- ranges[n_dirty - 1].start = t->data;
- ranges[n_dirty - 1].end = t->data + t->size;
- total_dirty += t->size;
- }
- }
-
- if (total_dirty == 0) {
- return;
- }
-
- if (total_dirty > HTP_DCACHE_FLUSH_ALL_THRESHOLD) {
- flush_all_dcache(ctx);
- return;
- }
-
- flush_dirty_ranges(ctx, ranges, n_dirty, total_dirty);
- for (uint32_t i = 0; i < n_dirty; i++) {
- make_tensor_clean(ctx, dirty_tensors[i]);
- }
-}
diff --git a/ggml/src/ggml-hexagon/htp/htp-dcache.h b/ggml/src/ggml-hexagon/htp/htp-dcache.h
deleted file mode 100644
index c1c37573c..000000000
--- a/ggml/src/ggml-hexagon/htp/htp-dcache.h
+++ /dev/null
@@ -1,24 +0,0 @@
-#ifndef HTP_DCACHE_H
-#define HTP_DCACHE_H
-
-#include <stdint.h>
-#include "hex-common.h"
-#include "htp-ops.h"
-
-#define HTP_MAX_DIRTY_RANGES 64
-#define HTP_DCACHE_BLOCK_SIZE (HEX_L2_LINE_SIZE * 4) // flush granularity (chunks per thread)
-#define HTP_DCACHE_FLUSH_WQ_THRESHOLD (4 * 1024)
-#define HTP_DCACHE_FLUSH_ALL_THRESHOLD (4 * 1024 * 1024)
-
-struct htp_dirty_range {
- uint32_t start;
- uint32_t end;
-};
-
-struct htp_context;
-
-void htp_dcache_flush_dirty_ranges(struct htp_context * ctx);
-void htp_dcache_flush_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n);
-void htp_dcache_mark_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n);
-
-#endif // HTP_DCACHE_H
diff --git a/ggml/src/ggml-hexagon/htp/htp-ops.h b/ggml/src/ggml-hexagon/htp/htp-ops.h
index 2cb49c0a8..25a2b6459 100644
--- a/ggml/src/ggml-hexagon/htp/htp-ops.h
+++ b/ggml/src/ggml-hexagon/htp/htp-ops.h
@@ -129,6 +129,7 @@ enum htp_op_code {
HTP_OP_LIGHTNING_INDEXER,
HTP_OP_SSM_SCAN,
HTP_OP_TIMESTEP_EMBEDDING,
+ HTP_OP_MUL_MAT_NX_GLU,
HTP_OP_INVALID
};
@@ -154,10 +155,11 @@ enum htp_op_code {
#define HTP_DDR_SPAD_SIZE (512 * 1024)
enum htp_tensor_flags {
- HTP_TENSOR_WEIGHT = (1U << 0), // Tensor buffer model weight data (not compute)
- HTP_TENSOR_TILED = (1U << 1), // Tensor is in tiled format
- HTP_TENSOR_FENCE = (1U << 2), // Tensor is synchronization fence (explicitly managed)
- HTP_TENSOR_FUSEABLE = (1U << 3), // Tensor can be fused (host-only)
+ HTP_TENSOR_WEIGHT = (1U << 0), // Tensor buffer model weight data (not compute)
+ HTP_TENSOR_TILED = (1U << 1), // Tensor is in tiled format
+ HTP_TENSOR_FENCE = (1U << 2), // Tensor is synchronization fence (explicitly managed)
+ HTP_TENSOR_FUSEABLE = (1U << 3), // Tensor can be fused (host-only)
+ HTP_TENSOR_LOWERED_F16 = (1U << 4), // F32 tensor lowered in-place to F16 (host-only)
};
enum htp_buf_flags {
diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.c b/ggml/src/ggml-hexagon/htp/htp-tensor.c
new file mode 100644
index 000000000..eceaa270a
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/htp-tensor.c
@@ -0,0 +1,86 @@
+#include "htp-tensor.h"
+
+#include <string.h>
+
+#include "dma-copy.h"
+#include "hex-utils.h"
+
+#define HTP_TENSOR_READ_SMALL_BYTES 256
+
+static inline void htp_tensor_read_l2flush(const htp_thread_t * th, uintptr_t start, size_t len) {
+ const uintptr_t s = hex_align_down(start, HEX_L2_LINE_SIZE);
+ const uintptr_t e = hex_align_up(start + len, HEX_L2_LINE_SIZE);
+ if (e <= s) {
+ return;
+ }
+ htp_trace_event_start(th->trace, HTP_TRACE_EVT_L2FLUSH, 0);
+ hex_l2flush((void *) s, e - s);
+ htp_trace_event_stop(th->trace, HTP_TRACE_EVT_L2FLUSH, 0);
+}
+
+size_t htp_tensor_read(const htp_thread_t * th, void * dst, size_t dst_size, const struct htp_tensor * src) {
+ if (!th || !dst || !src) {
+ return 0;
+ }
+
+ const uint32_t ne0 = src->ne[0];
+ const uint32_t ne1 = src->ne[1];
+ const uint32_t ne2 = src->ne[2];
+ const uint32_t ne3 = src->ne[3];
+ if (ne0 == 0 || ne1 == 0 || ne2 == 0 || ne3 == 0) {
+ return 0;
+ }
+
+ const uint32_t row_bytes = htp_tensor_get_row_size(src->type, ne0);
+ if (row_bytes == 0 || (row_bytes % ne0) != 0) {
+ return 0;
+ }
+
+ const uint32_t elem_size = row_bytes / ne0;
+ const size_t nrows = (size_t) ne1 * ne2 * ne3;
+ const size_t total_bytes = (size_t) row_bytes * nrows;
+ if (total_bytes > dst_size) {
+ return 0;
+ }
+
+ const uintptr_t dst_addr = (uintptr_t) dst;
+ const bool is_contig = htp_tensor_is_contiguous(src, elem_size);
+
+ if (!htp_tensor_is_extended(src) && is_contig && total_bytes <= HTP_TENSOR_READ_SMALL_BYTES) {
+ if (!(src->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) {
+ htp_tensor_read_l2flush(th, (uintptr_t) src->data, total_bytes);
+ }
+ memcpy(dst, (const void *) (uintptr_t) src->data, total_bytes);
+ return total_bytes;
+ }
+
+ htp_tensor_read_l2flush(th, dst_addr, total_bytes);
+
+ dma_queue * dma_q = th->dma_q;
+ if (ne0 > 1 && src->nb[0] != elem_size) {
+ dma_addr_t cur_dst = (dma_addr_t) dst_addr;
+ for (uint32_t i3 = 0; i3 < ne3; ++i3) {
+ for (uint32_t i2 = 0; i2 < ne2; ++i2) {
+ for (uint32_t i1 = 0; i1 < ne1; ++i1) {
+ const dma_addr_t cur_src = src->data +
+ (dma_addr_t) i1 * src->nb[1] +
+ (dma_addr_t) i2 * src->nb[2] +
+ (dma_addr_t) i3 * src->nb[3];
+ dma_cpy_push_2d_chunked(dma_q, cur_dst, cur_src, elem_size, src->nb[0], elem_size, ne0);
+ cur_dst += row_bytes;
+ }
+ }
+ }
+ } else {
+ struct htp_tensor dst_t = *src;
+ dst_t.data = (dma_addr_t) dst_addr;
+ dst_t.nb[0] = elem_size;
+ dst_t.nb[1] = row_bytes;
+ dst_t.nb[2] = row_bytes * ne1;
+ dst_t.nb[3] = dst_t.nb[2] * ne2;
+ dma_cpy_sametype_sameshape(dma_q, &dst_t, src, elem_size);
+ }
+ dma_queue_flush(dma_q);
+
+ return total_bytes;
+}
diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.h b/ggml/src/ggml-hexagon/htp/htp-tensor.h
index 2f9a4b129..23122959d 100644
--- a/ggml/src/ggml-hexagon/htp/htp-tensor.h
+++ b/ggml/src/ggml-hexagon/htp/htp-tensor.h
@@ -8,8 +8,6 @@
#include "hex-common.h"
#include "hex-fastdiv.h"
-#define HTP_TENSOR_MDEV_LINE_SIZE 128
-
// Currently HMX requires 32x32 tile formats (do not change)
#define HTP_TENSOR_TILE_N_COLS 32
#define HTP_TENSOR_TILE_N_ROWS 32
@@ -69,53 +67,6 @@ static inline bool htp_tensor_is_permuted(const struct htp_tensor * t) {
return t->nb[0] > t->nb[1] || t->nb[1] > t->nb[2] || t->nb[2] > t->nb[3];
}
-static inline bool htp_tensor_mdev_data_aligned(const struct htp_tensor * t) {
- return ((uintptr_t) t->data & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0;
-}
-
-static inline bool htp_tensor_can_row_partition(const struct htp_tensor * t, uint32_t elem_size) {
- if (!htp_tensor_mdev_data_aligned(t)) {
- return false;
- }
- if (t->ne[0] != 1 && t->nb[0] != elem_size) {
- return false;
- }
- if (htp_tensor_is_permuted(t)) {
- return false;
- }
- if (t->ne[1] > 1 && (t->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) != 0) return false;
- if (t->ne[2] > 1 && (t->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) != 0) return false;
- if (t->ne[3] > 1 && (t->nb[3] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) != 0) return false;
- return true;
-}
-
-static inline bool htp_tensor_mdev_rows_per_chunk(const struct htp_tensor * t, uint32_t elem_size, uint32_t row_size, uint32_t * rows_per_chunk) {
- *rows_per_chunk = 0;
-
- if (!htp_tensor_mdev_data_aligned(t)) {
- return false;
- }
- if (t->ne[0] != 1 && t->nb[0] != elem_size) {
- return false;
- }
- if (htp_tensor_is_permuted(t)) {
- return false;
- }
- if (t->ne[1] > 1 && (t->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0 &&
- (t->ne[2] <= 1 || (t->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0) &&
- (t->ne[3] <= 1 || (t->nb[3] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0)) {
- *rows_per_chunk = 1;
- return true;
- }
- if (t->nb[1] == row_size &&
- (t->ne[2] <= 1 || t->nb[2] == t->nb[1] * t->ne[1]) &&
- (t->ne[3] <= 1 || t->nb[3] == t->nb[2] * t->ne[2])) {
- *rows_per_chunk = (row_size > 0) ? (HTP_TENSOR_MDEV_LINE_SIZE / hex_gcd_u32(row_size, HTP_TENSOR_MDEV_LINE_SIZE)) : 1;
- return true;
- }
- return false;
-}
-
static inline struct htp_tensor_mdev_range htp_tensor_mdev_partition(uint32_t total_units, uint32_t units_per_chunk, uint32_t mdev_idx, uint32_t mdev_count, const struct fastdiv_values * mdev_count_div) {
struct htp_tensor_mdev_range range = { 0, total_units };
@@ -214,4 +165,16 @@ static inline uint32_t htp_tensor_get_row_size(int type, uint32_t ne00) {
}
}
+static inline size_t htp_tensor_nbytes(const struct htp_tensor * t) {
+ return (size_t) htp_tensor_get_row_size(t->type, t->ne[0]) * t->ne[1] * t->ne[2] * t->ne[3];
+}
+
+#ifdef __HVX_ARCH__
+#include "htp-thread.h"
+
+// Read tensor data contiguously into a 128-byte aligned cached DDR buffer.
+// [dst, hex_align_up(dst + bytes, 128)) must be exclusively owned by the caller.
+size_t htp_tensor_read(const htp_thread_t * th, void * dst, size_t dst_size, const struct htp_tensor * src);
+#endif
+
#endif // HTP_TENSOR_H
diff --git a/ggml/src/ggml-hexagon/htp/htp-vtcm.h b/ggml/src/ggml-hexagon/htp/htp-vtcm.h
index a1e90575f..f17fde80d 100644
--- a/ggml/src/ggml-hexagon/htp/htp-vtcm.h
+++ b/ggml/src/ggml-hexagon/htp/htp-vtcm.h
@@ -4,6 +4,13 @@
#include <stddef.h>
#include <stdint.h>
+// Reserve one HVX vector at the end of physical VTCM so tail hvx_vmemu loads cannot fault past the page end
+#define HTP_VTCM_GUARD_SIZE 128
+
+static inline size_t htp_vtcm_usable_size(size_t raw_size) {
+ return (raw_size - HTP_VTCM_GUARD_SIZE) & ~(size_t) 127;
+}
+
static inline uint8_t *vtcm_seq_alloc(uint8_t **vtcm_ptr, size_t size) {
uint8_t *p = *vtcm_ptr;
*vtcm_ptr += size;
diff --git a/ggml/src/ggml-hexagon/htp/hvx-base.h b/ggml/src/ggml-hexagon/htp/hvx-base.h
index e87a30d14..c80ce5bb6 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-base.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-base.h
@@ -12,6 +12,10 @@
#define hvx_vmem(A) *((HVX_Vector *)(A))
#define hvx_vmemu(A) *((HVX_UVector *)(A))
+static inline void hvx_vmem_store_nt(void * restrict dst, HVX_Vector v) {
+ asm("vmem(%1+#0):nt = %2" : "=m"(*(HVX_Vector *) dst) : "r"(dst), "v"(v));
+}
+
static inline void hvx_vec_store_u(void * restrict dst, uint32_t n, HVX_Vector v) {
// Rotate as needed.
v = Q6_V_vlalign_VVR(v, v, (size_t) dst);
@@ -187,6 +191,9 @@ static inline HVX_VectorPair hvx_vec_f16_to_f32(HVX_Vector v) {
#endif
static inline HVX_Vector hvx_vec_i16_from_hf_rnd_sat(HVX_Vector vin) {
+#if __HVX_ARCH__ >= 81
+ return Q6_Vh_equals_Vhf_rnd(vin);
+#else
// This looks complicated.
// Ideally should just be Q6_Vh_equals_Vhf(vin)
// but that instruction does not do proper rounding.
@@ -208,10 +215,17 @@ static inline HVX_Vector hvx_vec_i16_from_hf_rnd_sat(HVX_Vector vin) {
// now round down to 16
return Q6_Vh_vround_VwVw_sat(vsf_1, vsf_0);
+#endif
}
#if __HVX_ARCH__ < 79
+static inline HVX_VectorPair hvx_vec_mpy_f32_f16(HVX_Vector x, HVX_Vector y)
+{
+ HVX_VectorPair m = Q6_Wqf32_vmpy_VhfVhf(x, y);
+ return Q6_W_vcombine_VV(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(m)), Q6_Vsf_equals_Vqf32(Q6_V_lo_W(m)));
+}
+
static inline HVX_VectorPair hvx_vec_mpyacc_f32_f16(HVX_VectorPair acc, HVX_Vector x, HVX_Vector y)
{
HVX_VectorPair m = Q6_Wqf32_vmpy_VhfVhf(x, y);
@@ -222,6 +236,11 @@ static inline HVX_VectorPair hvx_vec_mpyacc_f32_f16(HVX_VectorPair acc, HVX_Vect
#else
+static inline HVX_VectorPair hvx_vec_mpy_f32_f16(HVX_Vector x, HVX_Vector y)
+{
+ return Q6_Wsf_vmpy_VhfVhf(x, y);
+}
+
static inline HVX_VectorPair hvx_vec_mpyacc_f32_f16(HVX_VectorPair acc, HVX_Vector x, HVX_Vector y)
{
return Q6_Wsf_vmpyacc_WsfVhfVhf(acc, x, y);
@@ -400,7 +419,7 @@ static inline void hvx_transpose_32x32_w_shuff(uint8_t * restrict dst, uint32_t
}
}
-// Specialized store that will follow outstanding scatters or gathers to make sure they complete
+// Drain outstanding vscatter/vgather before DMA, HMX, or scalar access to the VTCM region.
static inline void hvx_gather_sync(void * vtcm_addr) {
asm volatile("vmem(%0+#0):scatter_release\n"
"v0 = vmem(%0+#0)\n" :: "r"(vtcm_addr) : "v0", "memory");
@@ -424,7 +443,7 @@ static inline HVX_Vector hvx_vec_gather_offsets_h(uint32_t stride) {
}
// Rows [0, nrows) of the transpose of ncols src vectors (src_stride apart) to dst.
-// src, dst in VTCM. Async: hvx_gather_sync() before use.
+// src, dst in VTCM. Async: call hvx_gather_sync() before DMA, HMX, or scalar access.
// Use for partial tiles (small ncols). Fewest packets.
static inline void hvx_transpose_32x32_w_gather(uint8_t * restrict dst, uint32_t dst_stride, const uint8_t * restrict src,
uint32_t src_stride, HVX_Vector offsets, uint32_t nrows, uint32_t ncols) {
diff --git a/ggml/src/ggml-hexagon/htp/hvx-dump.h b/ggml/src/ggml-hexagon/htp/hvx-dump.h
index 85201fc34..684387d98 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-dump.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-dump.h
@@ -9,7 +9,7 @@
#include "hex-utils.h"
#include "hvx-types.h"
-static void hvx_vec_dump_f16_n(char * pref, HVX_Vector v, uint32_t n) {
+static inline void hvx_vec_dump_f16_n(char * pref, HVX_Vector v, uint32_t n) {
HVX_VectorAlias u = { .v = v };
const uint32_t n0 = n / 16;
@@ -23,11 +23,11 @@ static void hvx_vec_dump_f16_n(char * pref, HVX_Vector v, uint32_t n) {
}
}
-static void hvx_vec_dump_f16(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_f16(char * pref, HVX_Vector v) {
hvx_vec_dump_f16_n(pref, v, 64);
}
-static void hvx_vec_dump_f32_n(char * pref, HVX_Vector v, uint32_t n) {
+static inline void hvx_vec_dump_f32_n(char * pref, HVX_Vector v, uint32_t n) {
HVX_VectorAlias u = { .v = v };
const uint32_t n0 = n / 16;
@@ -41,21 +41,22 @@ static void hvx_vec_dump_f32_n(char * pref, HVX_Vector v, uint32_t n) {
}
}
-static void hvx_vec_dump_f32_hmt(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_f32_hmt(char * pref, HVX_Vector v) {
union {
HVX_Vector v;
float d[32];
} u = { .v = v };
+ (void) u;
FARF(HIGH, "%s: %.6f %.6f %.6f %.6f ... %.6f %.6f %.6f %.6f ... %.6f %.6f %.6f %.6f\n", pref, u.d[0], u.d[1],
u.d[2], u.d[3], u.d[12], u.d[13], u.d[14], u.d[15], u.d[28], u.d[29], u.d[30], u.d[31]);
}
-static void hvx_vec_dump_f32(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_f32(char * pref, HVX_Vector v) {
hvx_vec_dump_f32_n(pref, v, 32);
}
-static void hvx_vec_dump_int32(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_int32(char * pref, HVX_Vector v) {
union {
HVX_Vector v;
int32_t d[32];
@@ -66,27 +67,29 @@ static void hvx_vec_dump_int32(char * pref, HVX_Vector v) {
}
}
-static void hvx_vec_dump_int32_hmt(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_int32_hmt(char * pref, HVX_Vector v) {
union {
HVX_Vector v;
int32_t d[32];
} u = { .v = v };
+ (void) u;
FARF(HIGH, "%s: %d %d %d %d ... %d %d %d %d ... %d %d %d %d\n", pref, u.d[0], u.d[1], u.d[2], u.d[3], u.d[12],
u.d[13], u.d[14], u.d[15], u.d[28], u.d[29], u.d[30], u.d[31]);
}
-static void hvx_vec_dump_int8_hmt(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_int8_hmt(char * pref, HVX_Vector v) {
union {
HVX_Vector v;
int8_t d[128];
} u = { .v = v };
+ (void) u;
FARF(HIGH, "%s: %d %d %d %d ... %d %d %d %d ... %d %d %d %d\n", pref, u.d[0], u.d[1], u.d[2], u.d[3], u.d[60],
u.d[61], u.d[62], u.d[63], u.d[124], u.d[125], u.d[126], u.d[127]);
}
-static void hvx_vec_dump_int8(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_int8(char * pref, HVX_Vector v) {
union {
HVX_Vector v;
int8_t d[128];
@@ -97,7 +100,7 @@ static void hvx_vec_dump_int8(char * pref, HVX_Vector v) {
}
}
-static void hvx_vec_dump_uint8(char * pref, HVX_Vector v) {
+static inline void hvx_vec_dump_uint8(char * pref, HVX_Vector v) {
union {
HVX_Vector v;
uint8_t d[128];
@@ -108,7 +111,7 @@ static void hvx_vec_dump_uint8(char * pref, HVX_Vector v) {
}
}
-static bool hvx_vec_eq(HVX_Vector v0, HVX_Vector v1, size_t n) {
+static inline bool hvx_vec_eq(HVX_Vector v0, HVX_Vector v1, size_t n) {
typedef union {
HVX_Vector v;
int8_t d[128];
diff --git a/ggml/src/ggml-hexagon/htp/hvx-exp.h b/ggml/src/ggml-hexagon/htp/hvx-exp.h
index 93ca8cf51..b69534a74 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-exp.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-exp.h
@@ -214,7 +214,25 @@ static inline void hvx_exp_f32(uint8_t * restrict dst, const uint8_t * restrict
}
}
-static inline HVX_Vector hvx_vec_exp2_f16(HVX_Vector x_v) {
+// 2^x on 64 fp16 lanes, requires x <= 0
+#if __HVX_ARCH__ >= 81
+#define HVX_EXP2_FIXED_G0 (-12573)
+#define HVX_EXP2_FIXED_G1 (15210)
+#define HVX_EXP2_FIXED_G2 (-2645)
+#define HVX_EXP2_FIXED_G2_PAIR ((int32_t) ((uint32_t) (uint16_t) HVX_EXP2_FIXED_G2 * 0x00010001u))
+
+static inline HVX_Vector hvx_vec_exp2_neg_f16(HVX_Vector x_v) {
+ const HVX_Vector z = Q6_Vuh_vmin_VuhVuh(Q6_V_vand_VV(x_v, Q6_Vh_vsplat_R(0x7FFF)), Q6_Vh_vsplat_R(0x4E40));
+ const HVX_Vector t = Q6_Vh_equals_Vhf_rnd(Q6_Vh_vadd_VhVh(z, Q6_Vh_vsplat_R(0x2800)));
+ const HVX_Vector rho = Q6_V_vand_VV(t, Q6_Vh_vsplat_R(0x03FF));
+ const HVX_Vector r15 = Q6_Vh_vasl_VhR(rho, 5);
+ HVX_Vector r = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15, HVX_EXP2_FIXED_G2_PAIR), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G1));
+ r = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(r, r15), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G0));
+ const HVX_Vector b = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(0x6400), t), Q6_Vh_vmpy_VhVh_s1_rnd_sat(r, rho));
+ return Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(b, Q6_Vh_vsplat_R(0x1400)));
+}
+#else
+static inline HVX_Vector hvx_vec_exp2_neg_f16(HVX_Vector x_v) {
const HVX_Vector zero_v = Q6_V_vzero();
const HVX_Vector half_hf_v = Q6_Vh_vsplat_R(0x3800); // fp16 0.5
@@ -230,7 +248,7 @@ static inline HVX_Vector hvx_vec_exp2_f16(HVX_Vector x_v) {
HVX_Vector x_qf16 = Q6_Vqf16_vsub_VhfVhf(x_v, f_v); // fractional part in qf16
// Horner: y = ((((E5*x + E4)*x + E3)*x + E2)*x + E1)*x + E0
- HVX_Vector y = Q6_Vqf16_vmpy_Vqf16Vqf16(Q6_Vh_vsplat_R(0x5082), x_qf16); // E5*x
+ HVX_Vector y = Q6_Vqf16_vmpy_Vqf16Vqf16(Q6_Vqf16_vadd_VhfVhf(Q6_Vh_vsplat_R(0x090c), zero_v), x_qf16); // E5*x
y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x157d)); // + E4
y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16);
y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x20ed)); // + E3
@@ -251,5 +269,6 @@ static inline HVX_Vector hvx_vec_exp2_f16(HVX_Vector x_v) {
y = Q6_Vh_vaslacc_VhVhR(y, k_v, 10);
return Q6_V_vmux_QVV(q_underflow, zero_v, y);
}
+#endif
#endif /* HVX_EXP_H */
diff --git a/ggml/src/ggml-hexagon/htp/hvx-inverse.h b/ggml/src/ggml-hexagon/htp/hvx-inverse.h
index 256a8843b..312881b3d 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-inverse.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-inverse.h
@@ -70,12 +70,9 @@ static inline HVX_Vector hvx_vec_inverse_f16(HVX_Vector vals) {
// Get mantissa for 16-bit representation
HVX_Vector mant_recip = Q6_V_vand_VV(Q6_Vh_vasr_VhR(Q6_Vh_vasl_VhVh(rm, vcl0), 5), Q6_Vh_vsplat_R(0x03FF));
- //Compute Reciprocal Exponent
- HVX_Vector exp_recip =
- Q6_Vh_vsub_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(254), exp_u16), Q6_Vh_vsub_VhVh(vcl0, Q6_Vh_vsplat_R(1)));
- //Convert it for 16-bit representation
- exp_recip = Q6_Vh_vadd_VhVh_sat(Q6_Vh_vsub_VhVh(exp_recip, Q6_Vh_vsplat_R(127)), Q6_Vh_vsplat_R(15));
- exp_recip = Q6_Vh_vasl_VhR(exp_recip, 10);
+ // Compute reciprocal exponent for 16-bit representation: (254 - exp_u16) - (vcl0 - 1) - 127 + 15
+ HVX_Vector exp_recip = Q6_Vh_vsub_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(143), exp_u16), vcl0);
+ exp_recip = Q6_Vh_vasl_VhR(exp_recip, 10);
//Merge exponent and mantissa for reciprocal
HVX_Vector recip = Q6_V_vor_VV(exp_recip, mant_recip);
@@ -86,6 +83,21 @@ static inline HVX_Vector hvx_vec_inverse_f16(HVX_Vector vals) {
return recip;
}
+// Reciprocal of positive normal fp16 in [1.0f, 16384.0f] (e.g. 1 + exp(-|x|) in sigmoid).
+static inline HVX_Vector hvx_vec_inverse_pos_f16(HVX_Vector avals) {
+ HVX_Vector mant_u16 = Q6_Vh_vasl_VhR(avals, 6);
+ HVX_Vector exp_u16 = Q6_Vuh_vlsr_VuhR(avals, 10);
+
+ HVX_Vector rm = hvx_vec_recip_xp1_O3_unsigned(mant_u16);
+ HVX_Vector vcl0 = Q6_Vuh_vcl0_Vuh(rm);
+
+ HVX_Vector mant_recip = Q6_V_vand_VV(Q6_Vh_vasr_VhR(Q6_Vh_vasl_VhVh(rm, vcl0), 5), Q6_Vh_vsplat_R(0x03FF));
+ HVX_Vector exp_recip = Q6_Vh_vsub_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(31), exp_u16), vcl0);
+ exp_recip = Q6_Vh_vasl_VhR(exp_recip, 10);
+
+ return Q6_V_vor_VV(exp_recip, mant_recip);
+}
+
static inline HVX_Vector hvx_vec_inverse_f32(HVX_Vector v_sf) {
HVX_Vector inv_aprox_sf = Q6_V_vsplat_R(0x7EEEEBB3);
HVX_Vector two_sf = hvx_vec_splat_f32(2.0);
diff --git a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h
index d7488976b..53799b30a 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h
@@ -4,7 +4,7 @@
#include "hvx-utils.h"
#include "htp-tensor.h"
-// Float activation copy/quantization kernels (DDR -> VTCM)
+// Float activation copy/quantization kernels (VTCM -> VTCM)
static inline void quantize_f32_f32_kernel(
const uint8_t * restrict src_data,
@@ -16,9 +16,7 @@ static inline void quantize_f32_f32_kernel(
size_t dst_stride
) {
(void) tmp_data;
- const size_t src_row_size = ne0 * sizeof(float);
for (uint32_t i = 0; i < nrows; ++i) {
- hex_l2fetch(src_data, src_row_size, src_stride, 2);
hvx_copy_f32_au(dst_data, src_data, ne0);
dst_data += dst_stride;
@@ -36,9 +34,7 @@ static inline void quantize_f32_f16_kernel(
size_t dst_stride
) {
(void) tmp_data;
- const size_t src_row_size = ne0 * sizeof(float);
for (uint32_t i = 0; i < nrows; ++i) {
- hex_l2fetch(src_data, src_row_size, src_stride, 2);
hvx_copy_f16_f32_au(dst_data, src_data, ne0);
dst_data += dst_stride;
@@ -56,9 +52,7 @@ static inline void quantize_f16_f16_kernel(
size_t dst_stride
) {
(void) tmp_data;
- const size_t src_row_size = ne0 * sizeof(float);
for (uint32_t i = 0; i < nrows; ++i) {
- hex_l2fetch(src_data, src_row_size, src_stride, 2);
hvx_copy_f16_au(dst_data, src_data, ne0);
dst_data += dst_stride;
@@ -66,8 +60,65 @@ static inline void quantize_f16_f16_kernel(
}
}
+static inline void quantize_f16_f32_kernel(
+ const uint8_t * restrict src_data,
+ uint8_t * restrict dst_data,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t nrows,
+ size_t src_stride,
+ size_t dst_stride
+) {
+ (void) tmp_data;
+ const size_t dst_valid_bytes = ne0 * sizeof(float);
+ for (uint32_t i = 0; i < nrows; ++i) {
+ hvx_copy_f32_f16_au(dst_data, src_data, ne0);
+ if (dst_stride > dst_valid_bytes) {
+ hvx_splat_f32_u(dst_data + dst_valid_bytes, 0.0f, (dst_stride - dst_valid_bytes) / sizeof(float));
+ }
+
+ dst_data += dst_stride;
+ src_data += src_stride;
+ }
+}
+
// Float dot product kernels (HVX)
+typedef void (*hvx_flat_store_1x1_fn_t)(void * restrict s, HVX_Vector rsum);
+typedef void (*hvx_flat_store_2x1_fn_t)(void * restrict s, HVX_Vector rsum0, HVX_Vector rsum1);
+
+static __attribute__((noinline)) void hvx_flat_store_1x1_f32(void * restrict s, HVX_Vector rsum) {
+ hvx_vec_store_u(s, 4, hvx_vec_reduce_sum_f32(rsum));
+}
+
+static __attribute__((noinline)) void hvx_flat_store_1x1_f16(void * restrict s, HVX_Vector rsum) {
+ HVX_Vector v_sum = hvx_vec_reduce_sum_f32(rsum);
+ 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, 2, hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
+}
+
+static __attribute__((noinline)) void hvx_flat_store_2x1_f32(void * restrict s, HVX_Vector rsum0, HVX_Vector rsum1) {
+ hvx_vec_store_u(s, 8, hvx_vec_reduce_sum_f32x2(rsum0, rsum1));
+}
+
+static __attribute__((noinline)) void hvx_flat_store_2x1_f16(void * restrict s, HVX_Vector rsum0, HVX_Vector rsum1) {
+ HVX_Vector v_sum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1);
+ 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, 4, hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
+}
+
+static inline hvx_flat_store_1x1_fn_t resolve_hvx_flat_store_1x1_fn(uint32_t dst_elem_size) {
+ return (dst_elem_size == sizeof(__fp16)) ? hvx_flat_store_1x1_f16 : hvx_flat_store_1x1_f32;
+}
+
+static inline hvx_flat_store_2x1_fn_t resolve_hvx_flat_store_2x1_fn(uint32_t dst_elem_size) {
+ return (dst_elem_size == sizeof(__fp16)) ? hvx_flat_store_2x1_f16 : hvx_flat_store_2x1_f32;
+}
+
#if __HVX_ARCH__ < 79
#define HVX_OP_ADD_F32(a, b) Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(a, b))
#define HVX_OP_MUL_F32(a, b) Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(a, b))
@@ -76,7 +127,7 @@ static inline void quantize_f16_f16_kernel(
#define HVX_OP_MUL_F32(a, b) Q6_Vsf_vmpy_VsfVsf(a, b)
#endif
-static inline void flat_vec_dot_f32_f32_aa_1x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy) {
+static inline void flat_vec_dot_f32_f32_aa_1x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, hvx_flat_store_1x1_fn_t store_1x1) {
const HVX_Vector * restrict x = (const HVX_Vector *) vx;
const HVX_Vector * restrict y = (const HVX_Vector *) vy;
@@ -101,12 +152,12 @@ static inline void flat_vec_dot_f32_f32_aa_1x1(const uint32_t n, float * restric
rsum = HVX_OP_ADD_F32(rsum, prod);
}
- *s = hvx_vec_get_f32(hvx_vec_reduce_sum_f32(rsum));
+ store_1x1(s, rsum);
}
-static inline void flat_vec_dot_f32_f32_aa_2x1(const uint32_t n, float * restrict s0,
+static inline void flat_vec_dot_f32_f32_aa_2x1(const uint32_t n, void * restrict s0,
const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0) {
+ const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1) {
const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0;
const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1;
const HVX_Vector * restrict y = (const HVX_Vector *) vy0;
@@ -139,13 +190,12 @@ static inline void flat_vec_dot_f32_f32_aa_2x1(const uint32_t n, float * restric
rsum1 = HVX_OP_ADD_F32(rsum1, prod1);
}
- HVX_Vector rsum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1);
- hvx_vec_store_u(s0, 8, rsum);
+ store_2x1(s0, rsum0, rsum1);
}
-static inline void flat_vec_dot_f32_f32_aa_2x2(const uint32_t n, float * restrict s0, float * restrict s1,
+static inline void flat_vec_dot_f32_f32_aa_2x2(const uint32_t n, void * restrict s0, void * restrict s1,
const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0, const void * restrict vy1) {
+ const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1) {
const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0;
const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1;
const HVX_Vector * restrict y0 = (const HVX_Vector *) vy0;
@@ -188,15 +238,11 @@ static inline void flat_vec_dot_f32_f32_aa_2x2(const uint32_t n, float * restric
r1_c1_sum = HVX_OP_ADD_F32(r1_c1_sum, HVX_OP_MUL_F32(r1_sf, c1_sf));
}
- // Reduce and store results
- HVX_Vector r0_r1_c0_sum = hvx_vec_reduce_sum_f32x2(r0_c0_sum, r1_c0_sum);
- HVX_Vector r0_r1_c1_sum = hvx_vec_reduce_sum_f32x2(r0_c1_sum, r1_c1_sum);
-
- hvx_vec_store_u(s0, 8, r0_r1_c0_sum);
- hvx_vec_store_u(s1, 8, r0_r1_c1_sum);
+ store_2x1(s0, r0_c0_sum, r1_c0_sum);
+ store_2x1(s1, r0_c1_sum, r1_c1_sum);
}
-static inline void flat_vec_dot_bf16_f32_aa_1x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy) {
+static inline void flat_vec_dot_bf16_f32_aa_1x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, hvx_flat_store_1x1_fn_t store_1x1) {
const HVX_Vector * restrict x = (const HVX_Vector *) vx;
const HVX_Vector * restrict y = (const HVX_Vector *) vy;
@@ -240,12 +286,12 @@ static inline void flat_vec_dot_bf16_f32_aa_1x1(const uint32_t n, float * restri
}
HVX_Vector rsum = HVX_OP_ADD_F32(rsum0, rsum1);
- *s = hvx_vec_get_f32(hvx_vec_reduce_sum_f32(rsum));
+ store_1x1(s, rsum);
}
-static inline void flat_vec_dot_bf16_f32_aa_2x1(const uint32_t n, float * restrict s0,
+static inline void flat_vec_dot_bf16_f32_aa_2x1(const uint32_t n, void * restrict s0,
const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0) {
+ const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1) {
const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0;
const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1;
const HVX_Vector * restrict y = (const HVX_Vector *) vy0;
@@ -301,13 +347,12 @@ static inline void flat_vec_dot_bf16_f32_aa_2x1(const uint32_t n, float * restri
}
}
- HVX_Vector rsum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1);
- hvx_vec_store_u(s0, 8, rsum);
+ store_2x1(s0, rsum0, rsum1);
}
-static inline void flat_vec_dot_bf16_f32_aa_2x2(const uint32_t n, float * restrict s0, float * restrict s1,
+static inline void flat_vec_dot_bf16_f32_aa_2x2(const uint32_t n, void * restrict s0, void * restrict s1,
const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0, const void * restrict vy1) {
+ const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1) {
const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0;
const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1;
const HVX_Vector * restrict y0 = (const HVX_Vector *) vy0;
@@ -382,17 +427,14 @@ static inline void flat_vec_dot_bf16_f32_aa_2x2(const uint32_t n, float * restri
}
}
- HVX_Vector r0_r1_c0_sum = hvx_vec_reduce_sum_f32x2(r0_c0_sum, r1_c0_sum);
- HVX_Vector r0_r1_c1_sum = hvx_vec_reduce_sum_f32x2(r0_c1_sum, r1_c1_sum);
-
- hvx_vec_store_u(s0, 8, r0_r1_c0_sum);
- hvx_vec_store_u(s1, 8, r0_r1_c1_sum);
+ store_2x1(s0, r0_c0_sum, r1_c0_sum);
+ store_2x1(s1, r0_c1_sum, r1_c1_sum);
}
#undef HVX_OP_ADD_F32
#undef HVX_OP_MUL_F32
-static inline void flat_vec_dot_f16_f16_aa_1x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy) {
+static inline void flat_vec_dot_f16_f16_aa_1x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, hvx_flat_store_1x1_fn_t store_1x1) {
const HVX_Vector * restrict x = (const HVX_Vector *) vx;
const HVX_Vector * restrict y = (const HVX_Vector *) vy;
@@ -416,12 +458,12 @@ static inline void flat_vec_dot_f16_f16_aa_1x1(const uint32_t n, float * restric
}
HVX_Vector rsum = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(rsum_p), Q6_V_hi_W(rsum_p)));
- hvx_vec_store_u(s, 4, hvx_vec_reduce_sum_f32(rsum));
+ store_1x1(s, rsum);
}
-static inline void flat_vec_dot_f16_f16_aa_2x1(const uint32_t n, float * restrict s0,
+static inline void flat_vec_dot_f16_f16_aa_2x1(const uint32_t n, void * restrict s0,
const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0) {
+ const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1) {
const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0;
const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1;
const HVX_Vector * restrict y = (const HVX_Vector *) vy0;
@@ -452,13 +494,12 @@ static inline void flat_vec_dot_f16_f16_aa_2x1(const uint32_t n, float * restric
HVX_Vector rsum0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(rsum0_p), Q6_V_hi_W(rsum0_p)));
HVX_Vector rsum1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(rsum1_p), Q6_V_hi_W(rsum1_p)));
- HVX_Vector rsum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1);
- hvx_vec_store_u(s0, 8, rsum);
+ store_2x1(s0, rsum0, rsum1);
}
-static inline void flat_vec_dot_f16_f16_aa_2x2(const uint32_t n, float * restrict s0, float * restrict s1,
+static inline void flat_vec_dot_f16_f16_aa_2x2(const uint32_t n, void * restrict s0, void * restrict s1,
const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0, const void * restrict vy1) {
+ const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1) {
const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0;
const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1;
const HVX_Vector * restrict y0 = (const HVX_Vector *) vy0;
@@ -508,19 +549,110 @@ static inline void flat_vec_dot_f16_f16_aa_2x2(const uint32_t n, float * restric
HVX_Vector r1_c0_sum = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(r1_c0_sum_p), Q6_V_hi_W(r1_c0_sum_p)));
HVX_Vector r1_c1_sum = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(r1_c1_sum_p), Q6_V_hi_W(r1_c1_sum_p)));
- // Reduce and store results
- HVX_Vector r0_r1_c0_sum = hvx_vec_reduce_sum_f32x2(r0_c0_sum, r1_c0_sum);
- HVX_Vector r0_r1_c1_sum = hvx_vec_reduce_sum_f32x2(r0_c1_sum, r1_c1_sum);
+ store_2x1(s0, r0_c0_sum, r1_c0_sum);
+ store_2x1(s1, r0_c1_sum, r1_c1_sum);
+}
+
+typedef void (*hvx_tensor_add_row_fn_t)(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n);
+
+static __attribute__((noinline)) void hvx_tensor_add_row_f32_f32(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) {
+ float * restrict d = (float *) dst_ptr;
+ const float * restrict b = (const float *) bias_ptr;
+ uint32_t c = 0;
+ for (; c + 32 <= n; c += 32) {
+ hvx_vmemu(d + c) = hvx_vec_add_f32_f32(hvx_vmemu(d + c), hvx_vmemu(b + c));
+ }
+ if (c < n) {
+ const uint32_t rem = n - c;
+ HVX_Vector v_sum = hvx_vec_add_f32_f32(hvx_vmemu(d + c), hvx_vmemu(b + c));
+ hvx_vec_store_u(d + c, rem * sizeof(float), v_sum);
+ }
+}
+
+static __attribute__((noinline)) void hvx_tensor_add_row_f32_f16(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) {
+ float * restrict d = (float *) dst_ptr;
+ const __fp16 * restrict b = (const __fp16 *) bias_ptr;
+ uint32_t c = 0;
+ for (; c + 64 <= n; c += 64) {
+ HVX_VectorPair vp_b = hvx_vec_f16_to_f32(hvx_vmemu(b + c));
+ hvx_vmemu(d + c + 0) = hvx_vec_add_f32_f32(hvx_vmemu(d + c + 0), Q6_V_lo_W(vp_b));
+ hvx_vmemu(d + c + 32) = hvx_vec_add_f32_f32(hvx_vmemu(d + c + 32), Q6_V_hi_W(vp_b));
+ }
+ if (c + 32 <= n) {
+ HVX_Vector v_b = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(b + c)));
+ hvx_vmemu(d + c) = hvx_vec_add_f32_f32(hvx_vmemu(d + c), v_b);
+ c += 32;
+ }
+ if (c < n) {
+ const uint32_t rem = n - c;
+ HVX_Vector v_b = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(b + c)));
+ HVX_Vector v_sum = hvx_vec_add_f32_f32(hvx_vmemu(d + c), v_b);
+ hvx_vec_store_u(d + c, rem * sizeof(float), v_sum);
+ }
+}
- hvx_vec_store_u(&s0[0], 8, r0_r1_c0_sum); // row0,col0 row1,col0
- hvx_vec_store_u(&s1[0], 8, r0_r1_c1_sum); // row0,col1 row1,col1
+static __attribute__((noinline)) void hvx_tensor_add_row_f16_f32(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) {
+ __fp16 * restrict d = (__fp16 *) dst_ptr;
+ const float * restrict b = (const float *) bias_ptr;
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ uint32_t c = 0;
+ for (; c + 64 <= n; c += 64) {
+ HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c));
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), hvx_vmemu(b + c + 0));
+ HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), hvx_vmemu(b + c + 32));
+ 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));
+ hvx_vmemu(d + c) = hvx_vec_f32_to_f16(v0, v1);
+ }
+ if (c < n) {
+ const uint32_t rem = n - c;
+ HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c));
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), hvx_vmemu(b + c));
+ HVX_Vector v1 = (rem > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), hvx_vmemu(b + c + 32)) : Q6_V_vzero();
+ 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));
+ hvx_vec_store_u(d + c, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1));
+ }
}
+static __attribute__((noinline)) void hvx_tensor_add_row_f16_f16(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) {
+ __fp16 * restrict d = (__fp16 *) dst_ptr;
+ const __fp16 * restrict b = (const __fp16 *) bias_ptr;
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ uint32_t c = 0;
+ for (; c + 64 <= n; c += 64) {
+ HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c));
+ HVX_VectorPair vp_b = hvx_vec_f16_to_f32(hvx_vmemu(b + c));
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), Q6_V_lo_W(vp_b));
+ HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), Q6_V_hi_W(vp_b));
+ 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));
+ hvx_vmemu(d + c) = hvx_vec_f32_to_f16(v0, v1);
+ }
+ if (c < n) {
+ const uint32_t rem = n - c;
+ HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c));
+ HVX_VectorPair vp_b = hvx_vec_f16_to_f32(hvx_vmemu(b + c));
+ HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), Q6_V_lo_W(vp_b));
+ HVX_Vector v1 = (rem > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), Q6_V_hi_W(vp_b)) : Q6_V_vzero();
+ 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));
+ hvx_vec_store_u(d + c, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1));
+ }
+}
+static inline hvx_tensor_add_row_fn_t resolve_hvx_tensor_add_row_fn(uint32_t dst_elem_size, uint32_t bias_elem_size) {
+ if (dst_elem_size == sizeof(__fp16)) {
+ return (bias_elem_size == sizeof(__fp16)) ? hvx_tensor_add_row_f16_f16 : hvx_tensor_add_row_f16_f32;
+ }
+ return (bias_elem_size == sizeof(__fp16)) ? hvx_tensor_add_row_f32_f16 : hvx_tensor_add_row_f32_f32;
+}
static inline void hvx_tensor_add_f32_grid(
const struct htp_tensor * restrict dst,
- const struct htp_tensor * restrict src2,
+ const struct htp_tensor * restrict bias,
uint32_t start_row,
uint32_t end_row,
uint32_t start_col,
@@ -529,46 +661,33 @@ static inline void hvx_tensor_add_f32_grid(
const struct fastdiv_values * div_ne11
) {
if (start_row >= end_row || start_col >= end_col) return;
- const uint32_t nb1 = dst->nb[1]; // row stride in bytes
+ const uint32_t nb1 = dst->nb[1];
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const uint32_t bias_elem_size = (bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const hvx_tensor_add_row_fn_t add_row_fn = resolve_hvx_tensor_add_row_fn(dst_elem_size, bias_elem_size);
+ const uint32_t n_cols = end_col - start_col;
+ const size_t dst_col_off = (size_t) start_col * dst_elem_size;
+ const size_t bias_col_off = (size_t) start_col * bias_elem_size;
const uint32_t ne11 = dst->ne[1];
const uint32_t ne12 = dst->ne[2];
const uint32_t ne11_12 = ne11 * ne12;
- const bool is_broadcast1 = (src2->ne[1] == 1);
- const bool is_broadcast2 = (src2->ne[2] == 1);
- const bool is_broadcast3 = (src2->ne[3] == 1);
+ const size_t bias_nb1 = (bias->ne[1] == 1) ? 0 : bias->nb[1];
+ const size_t bias_nb2 = (bias->ne[2] == 1) ? 0 : bias->nb[2];
+ const size_t bias_nb3 = (bias->ne[3] == 1) ? 0 : bias->nb[3];
for (uint32_t r = start_row; r < end_row; r++) {
- float * dst_row = (float *) ((uint8_t *) dst->data + (size_t) r * nb1);
-
uint32_t i13 = fastdiv(r, div_ne11_12);
uint32_t i12 = fastdiv(r - i13 * ne11_12, div_ne11);
uint32_t i11 = r - i13 * ne11_12 - i12 * ne11;
- uint32_t i23 = is_broadcast3 ? 0 : i13;
- uint32_t i22 = is_broadcast2 ? 0 : i12;
- uint32_t i21 = is_broadcast1 ? 0 : i11;
-
- const float * src2_row = (const float *) ((const uint8_t *) src2->data +
- (size_t) i21 * src2->nb[1] + (size_t) i22 * src2->nb[2] + (size_t) i23 * src2->nb[3]);
-
- float * dst_ptr = &dst_row[start_col];
- const float * src2_ptr = &src2_row[start_col];
- int remaining = end_col - start_col;
- while (remaining >= 32) {
- HVX_Vector v_out = hvx_vmemu(dst_ptr);
- HVX_Vector v_z = hvx_vmemu(src2_ptr);
- hvx_vmemu(dst_ptr) = hvx_vec_add_f32_f32(v_out, v_z);
- dst_ptr += 32;
- src2_ptr += 32;
- remaining -= 32;
- }
- if (remaining > 0) {
- HVX_Vector v_out = hvx_vmemu(dst_ptr);
- HVX_Vector v_z = hvx_vmemu(src2_ptr);
- hvx_vec_store_u(dst_ptr, remaining * sizeof(float), hvx_vec_add_f32_f32(v_out, v_z));
- }
+ uint8_t * dst_ptr = (uint8_t *) dst->data +
+ (size_t) i11 * nb1 + (size_t) i12 * dst->nb[2] + (size_t) i13 * dst->nb[3] + dst_col_off;
+ const uint8_t * bias_ptr = (const uint8_t *) bias->data +
+ (size_t) i11 * bias_nb1 + (size_t) i12 * bias_nb2 + (size_t) i13 * bias_nb3 + bias_col_off;
+
+ add_row_fn(dst_ptr, bias_ptr, n_cols);
}
}
diff --git a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h
index e39ca336b..1b4784665 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h
@@ -64,25 +64,26 @@ static inline void quantize_block_f32_q8_1_tiled_impl(float * restrict x, uint8_
}
// word 8b: sum of block b (sums16: k 0..15, and word 8b + 4: k 16..31)
- const HVX_Vector v_inv127 = hvx_vec_splat_f32(1.0f / 127.0f);
- HVX_Vector vd0_sf = hvx_vec_mul_f32_f32(vmax0_sf, v_inv127);
- HVX_Vector vd1_sf = hvx_vec_mul_f32_f32(vmax1_sf, v_inv127);
- HVX_Vector vd2_sf = hvx_vec_mul_f32_f32(vmax2_sf, v_inv127);
- HVX_Vector vd3_sf = hvx_vec_mul_f32_f32(vmax3_sf, v_inv127);
-
- HVX_Vector v_sums_sf = Q6_Vsf_equals_Vw(v_sums);
- HVX_Vector voff0_sf = hvx_vec_mul_f32_f32(vd0_sf, v_sums_sf);
- HVX_Vector voff1_sf = hvx_vec_mul_f32_f32(vd1_sf, Q6_V_vror_VR(v_sums_sf, 32));
- HVX_Vector voff2_sf = hvx_vec_mul_f32_f32(vd2_sf, Q6_V_vror_VR(v_sums_sf, 64));
- HVX_Vector voff3_sf = hvx_vec_mul_f32_f32(vd3_sf, Q6_V_vror_VR(v_sums_sf, 96));
-
- HVX_Vector voff01_hf = hvx_vec_f32_to_f16(voff0_sf, voff1_sf);
- HVX_Vector voff23_hf = hvx_vec_f32_to_f16(voff2_sf, voff3_sf);
-
- int32_t __attribute__((aligned(128))) ws[32];
+ HVX_Vector voff01_hf = Q6_V_vzero();
+ HVX_Vector voff23_hf = Q6_V_vzero();
+ HVX_Vector v_s16 = Q6_V_vzero();
if (sums16) {
- // |sum of 16 int8| <= 2032 fits a halfword
- *(HVX_Vector *) ws = v_sums;
+ v_s16 = Q6_Vh_vshuffe_VhVh(Q6_V_vror_VR(v_sums, 16), v_sums);
+ } else {
+ const HVX_Vector v_inv127 = hvx_vec_splat_f32(1.0f / 127.0f);
+ HVX_Vector vd0_sf = hvx_vec_mul_f32_f32(vmax0_sf, v_inv127);
+ HVX_Vector vd1_sf = hvx_vec_mul_f32_f32(vmax1_sf, v_inv127);
+ HVX_Vector vd2_sf = hvx_vec_mul_f32_f32(vmax2_sf, v_inv127);
+ HVX_Vector vd3_sf = hvx_vec_mul_f32_f32(vmax3_sf, v_inv127);
+
+ HVX_Vector v_sums_sf = Q6_Vsf_equals_Vw(v_sums);
+ HVX_Vector voff0_sf = hvx_vec_mul_f32_f32(vd0_sf, v_sums_sf);
+ HVX_Vector voff1_sf = hvx_vec_mul_f32_f32(vd1_sf, Q6_V_vror_VR(v_sums_sf, 32));
+ HVX_Vector voff2_sf = hvx_vec_mul_f32_f32(vd2_sf, Q6_V_vror_VR(v_sums_sf, 64));
+ HVX_Vector voff3_sf = hvx_vec_mul_f32_f32(vd3_sf, Q6_V_vror_VR(v_sums_sf, 96));
+
+ voff01_hf = hvx_vec_f32_to_f16(voff0_sf, voff1_sf);
+ voff23_hf = hvx_vec_f32_to_f16(voff2_sf, voff3_sf);
}
static const uint8_t __attribute__((aligned(128))) repl[128] = {
@@ -104,7 +105,7 @@ static inline void quantize_block_f32_q8_1_tiled_impl(float * restrict x, uint8_
HVX_Vector voff_b = (b < 2) ? voff01_hf : voff23_hf;
HVX_Vector r_scale = hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(vd_b, 64) : vd_b);
HVX_Vector r_offset = sums16
- ? Q6_V_vsplat_R(((uint32_t) ws[8 * b + 4] << 16) | ((uint32_t) ws[8 * b] & 0xFFFF))
+ ? Q6_V_vdelta_VV(Q6_V_vror_VR(v_s16, b * 32), v_repl_ctrl)
: hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(voff_b, 64) : voff_b);
HVX_Vector r0 = Q6_V_vdelta_VV(v_act, v_repl_ctrl);
@@ -264,6 +265,254 @@ 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) {
+ assert((unsigned long) x % 128 == 0);
+ assert((unsigned long) y_block % 128 == 0);
+
+ const HVX_Vector * vx = (const HVX_Vector *) x;
+
+ HVX_Vector vx01_hf = vx[0];
+ HVX_Vector vx23_hf = vx[1];
+ HVX_Vector vmax01_hf, vmax23_hf;
+ HVX_Vector vmax0_sf = Q6_V_vzero(), vmax1_sf = Q6_V_vzero(), vmax2_sf = Q6_V_vzero(), vmax3_sf = Q6_V_vzero();
+ if (sums16) {
+ const HVX_Vector * vsb = (const HVX_Vector *) x_sb;
+ HVX_Vector vm = hvx_vec_abs_f16(vsb[0]);
+ for (int i = 1; i < 4; i++) {
+ vm = Q6_Vhf_vmax_VhfVhf(vm, hvx_vec_abs_f16(vsb[i]));
+ }
+ vmax01_hf = vmax23_hf = hvx_vec_reduce_max_f16(vm);
+ } else {
+ vmax01_hf = hvx_vec_reduce_abs_max_half_f16(vx01_hf);
+ vmax23_hf = hvx_vec_reduce_abs_max_half_f16(vx23_hf);
+ HVX_VectorPair p01 = hvx_vec_f16_to_f32(vmax01_hf);
+ HVX_VectorPair p23 = hvx_vec_f16_to_f32(vmax23_hf);
+ vmax0_sf = Q6_V_lo_W(p01);
+ vmax1_sf = Q6_V_hi_W(p01);
+ vmax2_sf = Q6_V_lo_W(p23);
+ vmax3_sf = Q6_V_hi_W(p23);
+ }
+
+ HVX_Vector vd01_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax01_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0
+ HVX_Vector vd01_hf = Q6_Vhf_equals_Vqf16(vd01_qf16);
+ HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf);
+ vx01_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx01_hf, vd01_inv_hf));
+
+ HVX_Vector vd23_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax23_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0
+ HVX_Vector vd23_hf = Q6_Vhf_equals_Vqf16(vd23_qf16);
+ HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf);
+ vx23_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx23_hf, vd23_inv_hf));
+
+ HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf);
+ HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf);
+ HVX_Vector vx_i8 = Q6_Vb_vpack_VhVh_sat(vx23_i16, vx01_i16);
+
+ const HVX_Vector ones = Q6_Vb_vsplat_R(1);
+ HVX_Vector v_sums = Q6_Vw_vrmpy_VbVb(vx_i8, ones);
+ v_sums = Q6_Vw_vadd_VwVw(v_sums, Q6_V_vror_VR(v_sums, 4));
+ v_sums = Q6_Vw_vadd_VwVw(v_sums, Q6_V_vror_VR(v_sums, 8));
+ if (!sums16) {
+ v_sums = Q6_Vw_vadd_VwVw(v_sums, Q6_V_vror_VR(v_sums, 16));
+ }
+
+ HVX_Vector voff01_hf = Q6_V_vzero();
+ HVX_Vector voff23_hf = Q6_V_vzero();
+ HVX_Vector v_s16 = Q6_V_vzero();
+ if (sums16) {
+ v_s16 = Q6_Vh_vshuffe_VhVh(Q6_V_vror_VR(v_sums, 16), v_sums);
+ } else {
+ const HVX_Vector v_inv127 = hvx_vec_splat_f32(1.0f / 127.0f);
+ HVX_Vector vd0_sf = hvx_vec_mul_f32_f32(vmax0_sf, v_inv127);
+ HVX_Vector vd1_sf = hvx_vec_mul_f32_f32(vmax1_sf, v_inv127);
+ HVX_Vector vd2_sf = hvx_vec_mul_f32_f32(vmax2_sf, v_inv127);
+ HVX_Vector vd3_sf = hvx_vec_mul_f32_f32(vmax3_sf, v_inv127);
+
+ HVX_Vector v_sums_sf = Q6_Vsf_equals_Vw(v_sums);
+ HVX_Vector voff0_sf = hvx_vec_mul_f32_f32(vd0_sf, v_sums_sf);
+ HVX_Vector voff1_sf = hvx_vec_mul_f32_f32(vd1_sf, Q6_V_vror_VR(v_sums_sf, 32));
+ HVX_Vector voff2_sf = hvx_vec_mul_f32_f32(vd2_sf, Q6_V_vror_VR(v_sums_sf, 64));
+ HVX_Vector voff3_sf = hvx_vec_mul_f32_f32(vd3_sf, Q6_V_vror_VR(v_sums_sf, 96));
+
+ voff01_hf = hvx_vec_f32_to_f16(voff0_sf, voff1_sf);
+ voff23_hf = hvx_vec_f32_to_f16(voff2_sf, voff3_sf);
+ }
+
+ static const uint8_t __attribute__((aligned(128))) repl[128] = {
+ 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x40, 0x40, 0x40, 0x40, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ };
+ HVX_Vector v_repl_ctrl = * (const HVX_Vector *) repl;
+
+ #pragma unroll
+ for (int b = 0; b < 4; b++) {
+ HVX_Vector v_act = Q6_V_vror_VR(vx_i8, b * 32);
+ HVX_Vector vd_b = (b < 2) ? vd01_hf : vd23_hf;
+ HVX_Vector voff_b = (b < 2) ? voff01_hf : voff23_hf;
+ HVX_Vector r_scale = hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(vd_b, 64) : vd_b);
+ HVX_Vector r_offset = sums16
+ ? Q6_V_vdelta_VV(Q6_V_vror_VR(v_s16, b * 32), v_repl_ctrl)
+ : hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(voff_b, 64) : voff_b);
+
+ HVX_Vector r0 = Q6_V_vdelta_VV(v_act, v_repl_ctrl);
+ HVX_Vector r1 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 4), v_repl_ctrl);
+ HVX_Vector r2 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 8), v_repl_ctrl);
+ HVX_Vector r3 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 12), v_repl_ctrl);
+ HVX_Vector r4 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 16), v_repl_ctrl);
+ HVX_Vector r5 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 20), v_repl_ctrl);
+ HVX_Vector r6 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 24), v_repl_ctrl);
+ HVX_Vector r7 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 28), v_repl_ctrl);
+
+ HVX_Vector * restrict dst = (HVX_Vector *) (y_block + b * 1280);
+ dst[0] = r0;
+ dst[1] = r1;
+ dst[2] = r2;
+ dst[3] = r3;
+ dst[4] = r4;
+ dst[5] = r5;
+ dst[6] = r6;
+ dst[7] = r7;
+ dst[8] = r_scale;
+ dst[9] = r_offset;
+ }
+}
+
+static inline void quantize_block_f16_q8_1_tiled(const __fp16 * restrict x, uint8_t * restrict y_block) {
+ quantize_block_f16_q8_1_tiled_impl(x, y_block, false, NULL);
+}
+
+static inline void quantize_block_f16_q8_1_s16_tiled(const __fp16 * restrict x, uint8_t * restrict y_block, const __fp16 * restrict x_sb) {
+ quantize_block_f16_q8_1_tiled_impl(x, y_block, true, x_sb);
+}
+
+static inline void quantize_block_f16_q8_0_tiled(const __fp16 * restrict x, uint8_t * restrict y_block) {
+ assert((unsigned long) x % 128 == 0);
+ assert((unsigned long) y_block % 128 == 0);
+
+ const HVX_Vector * vx = (const HVX_Vector *) x;
+
+ HVX_Vector vx01_hf = vx[0];
+ HVX_Vector vx23_hf = vx[1];
+ HVX_Vector vmax01_hf = hvx_vec_reduce_abs_max_half_f16(vx01_hf);
+ HVX_Vector vmax23_hf = hvx_vec_reduce_abs_max_half_f16(vx23_hf);
+
+ HVX_Vector vd01_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax01_hf, Q6_Vh_vsplat_R(0x2008));
+ HVX_Vector vd23_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax23_hf, Q6_Vh_vsplat_R(0x2008));
+ HVX_Vector vd01_hf = Q6_Vhf_equals_Vqf16(vd01_qf16);
+ HVX_Vector vd23_hf = Q6_Vhf_equals_Vqf16(vd23_qf16);
+
+ HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf);
+ HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf);
+ vx01_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx01_hf, vd01_inv_hf));
+ vx23_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx23_hf, vd23_inv_hf));
+
+ HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf);
+ HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf);
+ HVX_Vector vx_i8 = Q6_Vb_vpack_VhVh_sat(vx23_i16, vx01_i16);
+
+ HVX_VectorPair vp01 = Q6_W_vshuff_VVR(vd01_hf, vd01_hf, -64);
+ HVX_VectorPair vp23 = Q6_W_vshuff_VVR(vd23_hf, vd23_hf, -64);
+
+ static const uint8_t __attribute__((aligned(128))) repl[128] = {
+ 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x40, 0x40, 0x40, 0x40, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
+ };
+ HVX_Vector v_repl_ctrl = * (const HVX_Vector *) repl;
+
+ #pragma unroll
+ for (int b = 0; b < 4; b++) {
+ HVX_Vector v_act = Q6_V_vror_VR(vx_i8, b * 32);
+ HVX_Vector r_scale;
+ if (b == 0) {
+ r_scale = Q6_V_lo_W(vp01);
+ } else if (b == 1) {
+ r_scale = Q6_V_hi_W(vp01);
+ } else if (b == 2) {
+ r_scale = Q6_V_lo_W(vp23);
+ } else {
+ r_scale = Q6_V_hi_W(vp23);
+ }
+
+ HVX_Vector r0 = Q6_V_vdelta_VV(v_act, v_repl_ctrl);
+ HVX_Vector r1 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 4), v_repl_ctrl);
+ HVX_Vector r2 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 8), v_repl_ctrl);
+ HVX_Vector r3 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 12), v_repl_ctrl);
+ HVX_Vector r4 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 16), v_repl_ctrl);
+ HVX_Vector r5 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 20), v_repl_ctrl);
+ HVX_Vector r6 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 24), v_repl_ctrl);
+ HVX_Vector r7 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 28), v_repl_ctrl);
+
+ HVX_Vector * restrict dst = (HVX_Vector *) (y_block + b * 1152);
+ dst[0] = r0;
+ dst[1] = r1;
+ dst[2] = r2;
+ dst[3] = r3;
+ dst[4] = r4;
+ dst[5] = r5;
+ dst[6] = r6;
+ dst[7] = r7;
+ dst[8] = r_scale;
+ }
+}
+
+static void quantize_row_f16_q8_0_tiled(const __fp16 * restrict x, uint8_t * restrict y, uint32_t k) {
+ assert(k % 32 == 0);
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (k + qk - 1) / qk;
+
+ for (uint32_t i = 0; i < nb; i++) {
+ uint8_t * restrict y_block = y + i * 4 * 1152;
+ quantize_block_f16_q8_0_tiled(x + i * qk, y_block);
+ }
+}
+
+static void quantize_row_f16_q8_1_tiled(const __fp16 * restrict x, uint8_t * restrict y, uint32_t k) {
+ assert(k % 32 == 0);
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (k + qk - 1) / qk;
+
+ for (uint32_t i = 0; i < nb; i++) {
+ uint8_t * restrict y_block = y + i * 4 * 1280;
+ quantize_block_f16_q8_1_tiled(x + i * qk, y_block);
+ }
+}
+
+static void quantize_row_f16_q8_1_s16_tiled(const __fp16 * restrict x, uint8_t * restrict y, uint32_t k) {
+ assert(k % 32 == 0);
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (k + qk - 1) / qk;
+
+ for (uint32_t i = 0; i < nb; i++) {
+ uint8_t * restrict y_block = y + i * 4 * 1280;
+ quantize_block_f16_q8_1_s16_tiled(x + i * qk, y_block, x + (i & ~1u) * qk); // k % 256 == 0 for Q2_K
+ }
+}
+
static inline void quantize_half_f16_tiled_splat(HVX_Vector v_src, HVX_Vector * restrict dst) {
static const uint8_t __attribute__((aligned(128))) repl[128] = {
0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04,
@@ -357,34 +606,6 @@ static inline HVX_VectorPair hvx_vec_mul_f16_f16_to_f32_pair(HVX_Vector v1, HVX_
#endif
}
-static inline HVX_Vector unpack_and_interleave_4bit(HVX_Vector v_a, HVX_Vector v_b, HVX_Vector mask_h4) {
- HVX_Vector v_W0 = Q6_V_vand_VV(v_a, mask_h4);
- HVX_Vector v_W1 = Q6_Vub_vlsr_VubR(v_a, 4);
- HVX_Vector v_W2 = Q6_V_vand_VV(v_b, mask_h4);
- HVX_Vector v_W3 = Q6_Vub_vlsr_VubR(v_b, 4);
-
- HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_W1, v_W0, -1);
- HVX_VectorPair v23_pair = Q6_W_vshuff_VVR(v_W3, v_W2, -1);
- HVX_VectorPair v0123_pair = Q6_W_vshuff_VVR(Q6_V_lo_W(v23_pair), Q6_V_lo_W(v01_pair), -2);
- return Q6_V_lo_W(v0123_pair);
-}
-
-static inline HVX_VectorPair unpack_and_interleave_4bit_x2(HVX_Vector v_src, HVX_Vector mask_h4) {
- HVX_Vector v_lo = Q6_V_vand_VV(v_src, mask_h4);
- HVX_Vector v_hi = Q6_Vub_vlsr_VubR(v_src, 4);
- HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1);
- HVX_Vector v01_lo = Q6_V_lo_W(v01_pair);
- HVX_Vector v01_hi = Q6_V_hi_W(v01_pair);
-
- HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64);
- HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2));
-
- HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64);
- HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2));
-
- return Q6_W_vcombine_VV(v_W1, v_W0);
-}
-
static inline HVX_Vector unpack_q1_0_group(
HVX_Vector v_plane,
int g,
@@ -426,9 +647,9 @@ static inline HVX_Vector accum_4bit_32x1(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8);
- HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_vand_VV(v_src, mask_h4), i8);
+ HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(v_src, 4), i8);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]);
v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]);
}
@@ -447,9 +668,9 @@ static inline HVX_Vector accum_4bit_32x1_lut(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0);
- HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0);
+ HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]);
v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]);
}
@@ -496,9 +717,9 @@ static inline HVX_VectorPair accum_4bit_32x2(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8);
- HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_vand_VV(v_src, mask_h4), i8);
+ HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(v_src, 4), i8);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]);
@@ -522,9 +743,9 @@ static inline HVX_VectorPair accum_4bit_32x2_lut(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0);
- HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0);
+ HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]);
@@ -543,9 +764,7 @@ static inline HVX_Vector accum_q8_0_32x1(
HVX_Vector v_sum = Q6_V_vzero();
#pragma unroll
for (int g = 0; g < 8; g++) {
- HVX_Vector v_rot = Q6_V_vror_VR(vptr[g], 64);
- HVX_Vector v_W = Q6_V_lo_W(Q6_W_vshuff_VVR(v_rot, vptr[g], -2));
- v_sum = Q6_Vw_vrmpyacc_VwVbVb(v_sum, v_W, v_act[g]);
+ v_sum = Q6_Vw_vrmpyacc_VwVbVb(v_sum, vptr[g], v_act[g]);
}
return v_sum;
}
@@ -559,8 +778,7 @@ static inline HVX_VectorPair accum_q8_0_32x2(
HVX_Vector v_sum1 = Q6_V_vzero();
#pragma unroll
for (int g = 0; g < 8; g++) {
- HVX_Vector v_rot = Q6_V_vror_VR(vptr[g], 64);
- HVX_Vector v_W = Q6_V_lo_W(Q6_W_vshuff_VVR(v_rot, vptr[g], -2));
+ HVX_Vector v_W = vptr[g];
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W, v_act0[g]);
v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W, v_act1[g]);
}
@@ -573,27 +791,9 @@ static inline HVX_Vector hvx_q5k_or_hibit(HVX_Vector v, HVX_Vector v_plane, int
return Q6_V_vandor_VQR(v, q, 0x10101010);
}
-// 5-bit variant: the high bit comes from the plane, see hvx_q5k_or_hibit
-static inline HVX_VectorPair unpack_and_interleave_5bit_x2(HVX_Vector v_src, HVX_Vector v_plane, int i, HVX_Vector mask_h4) {
- HVX_Vector v_lo = hvx_q5k_or_hibit(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i);
- HVX_Vector v_hi = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1);
- HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1);
- HVX_Vector v01_lo = Q6_V_lo_W(v01_pair);
- HVX_Vector v01_hi = Q6_V_hi_W(v01_pair);
-
- HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64);
- HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2));
-
- HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64);
- HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2));
-
- return Q6_W_vcombine_VV(v_W1, v_W0);
-}
-
static inline HVX_Vector accum_5bit_32x1(
const HVX_Vector * restrict vptr,
- const HVX_Vector * restrict v_act,
- HVX_Vector i8
+ const HVX_Vector * restrict v_act
) {
HVX_Vector v_sum0 = Q6_V_vzero();
HVX_Vector v_sum1 = Q6_V_vzero();
@@ -602,9 +802,9 @@ static inline HVX_Vector accum_5bit_32x1(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_5bit_x2(vptr[i], v_plane, i, mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8);
- HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = hvx_q5k_or_hibit(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0);
+ HVX_Vector v_W1 = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]);
v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]);
}
@@ -615,8 +815,7 @@ static inline HVX_Vector accum_5bit_32x1(
static inline HVX_VectorPair accum_5bit_32x2(
const HVX_Vector * restrict vptr,
const HVX_Vector * restrict v_act0,
- const HVX_Vector * restrict v_act1,
- HVX_Vector i8
+ const HVX_Vector * restrict v_act1
) {
HVX_Vector v_sum0 = Q6_V_vzero();
HVX_Vector v_sum1 = Q6_V_vzero();
@@ -625,9 +824,9 @@ static inline HVX_VectorPair accum_5bit_32x2(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_5bit_x2(vptr[i], v_plane, i, mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8);
- HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = hvx_q5k_or_hibit(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0);
+ HVX_Vector v_W1 = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]);
@@ -645,23 +844,6 @@ static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j
return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0);
}
-// Q5_0: signed bytes (q - 16) straight from the nibbles and the plane
-static inline HVX_VectorPair unpack_and_interleave_q5_0_x2(HVX_Vector v_src, HVX_Vector v_plane, int i, HVX_Vector mask_h4) {
- HVX_Vector v_lo = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i);
- HVX_Vector v_hi = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1);
- HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1);
- HVX_Vector v01_lo = Q6_V_lo_W(v01_pair);
- HVX_Vector v01_hi = Q6_V_hi_W(v01_pair);
-
- HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64);
- HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2));
-
- HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64);
- HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2));
-
- return Q6_W_vcombine_VV(v_W1, v_W0);
-}
-
static inline HVX_Vector accum_q5_0_32x1(
const HVX_Vector * restrict vptr,
const HVX_Vector * restrict v_act
@@ -673,9 +855,11 @@ static inline HVX_Vector accum_q5_0_32x1(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_q5_0_x2(vptr[i], v_plane, i, mask_h4);
- v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, Q6_V_lo_W(v_W_pair), v_act[i * 2 + 0]);
- v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, Q6_V_hi_W(v_W_pair), v_act[i * 2 + 1]);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0);
+ HVX_Vector v_W1 = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1);
+ v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]);
+ v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]);
}
return Q6_Vw_vadd_VwVw(v_sum0, v_sum1);
@@ -693,9 +877,9 @@ static inline HVX_VectorPair accum_q5_0_32x2(
#pragma unroll
for (int i = 0; i < 4; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_q5_0_x2(vptr[i], v_plane, i, mask_h4);
- HVX_Vector v_W0 = Q6_V_lo_W(v_W_pair);
- HVX_Vector v_W1 = Q6_V_hi_W(v_W_pair);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0);
+ HVX_Vector v_W1 = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]);
@@ -986,7 +1170,63 @@ static inline HVX_Vector q2_k_int_scale(HVX_Vector v_isum, HVX_Vector v_msum, HV
return hvx_vec_mul_f32_f32(v_t, v_da32);
}
-static void tiled_vec_dot_q1_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+typedef void (*hvx_tiled_store_row_fn_t)(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz);
+
+static __attribute__((noinline)) void hvx_tiled_store_row_f32_none(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ (void) sz;
+ hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
+}
+
+static __attribute__((noinline)) void hvx_tiled_store_row_f32_f32(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ v_sum = hvx_vec_add_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_f32_f16(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ HVX_Vector v_sz = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(sz)));
+ v_sum = hvx_vec_add_f32_f32(v_sum, v_sz);
+ hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
+}
+
+static __attribute__((noinline)) void hvx_tiled_store_row_f16_none(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ (void) 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_f16_f32(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ v_sum = hvx_vec_add_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_f16_f16(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ HVX_Vector v_sz = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(sz)));
+ v_sum = hvx_vec_add_f32_f32(v_sum, v_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_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));
+ if (dst_f16) {
+ return !has_bias ? hvx_tiled_store_row_f16_none
+ : (bias_f16 ? hvx_tiled_store_row_f16_f16
+ : hvx_tiled_store_row_f16_f32);
+ }
+ return !has_bias ? hvx_tiled_store_row_f32_none
+ : (bias_f16 ? hvx_tiled_store_row_f32_f16
+ : hvx_tiled_store_row_f32_f32);
+}
+
+static void tiled_vec_dot_q1_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1013,14 +1253,10 @@ static void tiled_vec_dot_q1_0_32x1(const uint32_t n, float * restrict s, const
}
HVX_Vector v_sum_float = Q6_Vsf_equals_Vqf32(v_sum_qf);
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q1_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q1_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1057,19 +1293,11 @@ static void tiled_vec_dot_q1_0_32x2(const uint32_t n, float * restrict s0, float
HVX_Vector v_sum_float_c0 = Q6_Vsf_equals_Vqf32(v_sum_qf_c0);
HVX_Vector v_sum_float_c1 = Q6_Vsf_equals_Vqf32(v_sum_qf_c1);
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q4_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q4_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1092,14 +1320,10 @@ static void tiled_vec_dot_q4_0_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled);
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q4_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q4_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1135,19 +1359,11 @@ static void tiled_vec_dot_q4_0_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1);
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q4_1_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q4_1_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1178,14 +1394,10 @@ static void tiled_vec_dot_q4_1_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled);
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q4_1_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q4_1_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1231,19 +1443,11 @@ static void tiled_vec_dot_q4_1_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1);
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q8_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q8_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1265,14 +1469,10 @@ static void tiled_vec_dot_q8_0_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled);
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q8_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q8_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1307,19 +1507,11 @@ static void tiled_vec_dot_q8_0_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1);
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q5_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q5_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1341,14 +1533,10 @@ static void tiled_vec_dot_q5_0_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled);
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q5_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q5_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1383,19 +1571,11 @@ static void tiled_vec_dot_q5_0_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1);
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q5_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1406,7 +1586,7 @@ static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const
const HVX_Vector * restrict vptr = (const HVX_Vector *) (tile_ptr + kt * 768);
const HVX_Vector * restrict v_act = (const HVX_Vector *) (y_q + kt * 1280);
- HVX_Vector v_sum = accum_5bit_32x1(vptr, v_act, Q6_V_vzero());
+ HVX_Vector v_sum = accum_5bit_32x1(vptr, v_act);
HVX_Vector v_sum_sf = Q6_Vsf_equals_Vw(v_sum);
HVX_Vector v_scale_offset = vptr[4];
@@ -1426,14 +1606,10 @@ static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled);
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q5_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q5_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1447,7 +1623,7 @@ static void tiled_vec_dot_q5_k_32x2(const uint32_t n, float * restrict s0, float
const HVX_Vector * restrict v_act0 = (const HVX_Vector *) (y0_q + kt * 1280);
const HVX_Vector * restrict v_act1 = (const HVX_Vector *) (y1_q + kt * 1280);
- HVX_VectorPair v_sums = accum_5bit_32x2(vptr, v_act0, v_act1, Q6_V_vzero());
+ HVX_VectorPair v_sums = accum_5bit_32x2(vptr, v_act0, v_act1);
HVX_Vector v_sum_c0 = Q6_V_lo_W(v_sums);
HVX_Vector v_sum_c1 = Q6_V_hi_W(v_sums);
@@ -1479,19 +1655,11 @@ static void tiled_vec_dot_q5_k_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1);
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q6_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q6_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1507,14 +1675,10 @@ static void tiled_vec_dot_q6_k_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, scale_q6_k_32x1(v_sums, vptr[6], v_act[8]));
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q6_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q6_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1536,19 +1700,11 @@ static void tiled_vec_dot_q6_k_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, scale_q6_k_32x1(v_sums1, vptr[6], v_act1[8]));
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q3_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q3_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1563,14 +1719,10 @@ static void tiled_vec_dot_q3_k_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, scale_q6_k_32x1(v_sums, vptr[3], v_act[8]));
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q3_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q3_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1591,19 +1743,11 @@ static void tiled_vec_dot_q3_k_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, scale_q6_k_32x1(v_sums1, vptr[3], v_act1[8]));
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_q2_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q2_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1628,14 +1772,10 @@ static void tiled_vec_dot_q2_k_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, q2_k_int_scale(v_isum, v_msum, v_d, v_m, v_act_sb[8]));
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q2_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q2_k_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1671,20 +1811,12 @@ static void tiled_vec_dot_q2_k_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, q2_k_int_scale(v_isum1, v_msum1, v_d, v_m, v_act1_sb[8]));
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
// One Q2_0 weight tile covers 64 k: act tiles 2 * kt and 2 * kt + 1, each 32 k wide (Q8_1)
-static void tiled_vec_dot_q2_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_q2_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1711,14 +1843,10 @@ static void tiled_vec_dot_q2_0_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(v_tile_qf), v_dw_sf));
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_q2_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_q2_0_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1758,19 +1886,11 @@ static void tiled_vec_dot_q2_0_32x2(const uint32_t n, float * restrict s0, float
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(v_tile_qf_c1), v_dw_sf));
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_iq4nl_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_iq4nl_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -1794,14 +1914,10 @@ static void tiled_vec_dot_iq4nl_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled);
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_iq4nl_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -1838,16 +1954,8 @@ static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, float * restrict s0, floa
v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1);
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
#define IQ2XXS_GROUPS 4 // 8-element grid entries per tile row
@@ -1958,7 +2066,7 @@ static inline HVX_Vector iq2xxs_load_d(const uint8_t * restrict sb) {
return hvx_vec_mul_f32_f32(Q6_V_lo_W(hvx_vec_f16_to_f32(iq2xxs_gather_d(sb))), hvx_vec_splat_f32(IQ2XXS_D_SCALE));
}
-static void tiled_vec_dot_iq2xxs_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_iq2xxs_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
@@ -1993,14 +2101,10 @@ static void tiled_vec_dot_iq2xxs_32x1(const uint32_t n, float * restrict s, cons
}
}
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_iq2xxs_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_iq2xxs_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -2044,19 +2148,11 @@ static void tiled_vec_dot_iq2xxs_32x2(const uint32_t n, float * restrict s0, flo
}
}
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_mxfp4_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_mxfp4_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
@@ -2091,14 +2187,10 @@ static void tiled_vec_dot_mxfp4_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_mul_f32_f32(v_sum_float, hvx_vec_splat_f32(0.5f));
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_mxfp4_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -2150,16 +2242,8 @@ static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, float * restrict s0, floa
v_sum_float_c0 = hvx_vec_mul_f32_f32(v_sum_float_c0, hvx_vec_splat_f32(0.5f));
v_sum_float_c1 = hvx_vec_mul_f32_f32(v_sum_float_c1, hvx_vec_splat_f32(0.5f));
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ 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
@@ -2200,9 +2284,9 @@ static inline HVX_Vector accum_nvfp4_group_32x1(const HVX_Vector * restrict vptr
#pragma unroll
for (int i = 0; i < NVFP4_VECS_PER_GROUP; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0);
- HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0);
+ HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]);
v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]);
}
@@ -2216,9 +2300,9 @@ static inline HVX_VectorPair accum_nvfp4_group_32x2(const HVX_Vector * restrict
#pragma unroll
for (int i = 0; i < NVFP4_VECS_PER_GROUP; i++) {
- HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4);
- HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0);
- HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0);
+ HVX_Vector v_src = vptr[i];
+ HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0);
+ HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]);
v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]);
@@ -2230,7 +2314,7 @@ static inline HVX_VectorPair accum_nvfp4_group_32x2(const HVX_Vector * restrict
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
-static void tiled_vec_dot_nvfp4_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+static void tiled_vec_dot_nvfp4_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y_q = vy;
const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_NVFP4);
@@ -2261,14 +2345,10 @@ static void tiled_vec_dot_nvfp4_32x1(const uint32_t n, float * restrict s, const
v_sum_float = hvx_vec_mul_f32_f32(v_sum_float, hvx_vec_splat_f32(0.5f));
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float);
- }
+ store_row(s, valid_rows, v_sum_float, sz);
}
-static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_nvfp4_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 uint8_t * restrict tile_ptr = vx;
const uint8_t * restrict y0_q = vy0;
const uint8_t * restrict y1_q = vy1;
@@ -2307,19 +2387,11 @@ static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, float * restrict s0, floa
v_sum_float_c0 = hvx_vec_mul_f32_f32(v_sum_float_c0, hvx_vec_splat_f32(0.5f));
v_sum_float_c1 = hvx_vec_mul_f32_f32(v_sum_float_c1, hvx_vec_splat_f32(0.5f));
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1);
- }
+ store_row(s0, valid_rows, v_sum_float_c0, sz0);
+ store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-static void tiled_vec_dot_f16_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) {
+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;
const uint32_t n_vecs = ((n + 31) / 32) * 16;
@@ -2333,14 +2405,10 @@ static void tiled_vec_dot_f16_32x1(const uint32_t n, float * restrict s, const v
HVX_Vector v_sum = hvx_vec_add_f32_f32(Q6_V_lo_W(acc), Q6_V_hi_W(acc));
- if (sz) {
- hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum, hvx_vmemu(sz)));
- } else {
- hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
- }
+ store_row(s, valid_rows, v_sum, sz);
}
-static void tiled_vec_dot_f16_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) {
+static void tiled_vec_dot_f16_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;
@@ -2359,16 +2427,8 @@ static void tiled_vec_dot_f16_32x2(const uint32_t n, float * restrict s0, float
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));
- if (sz0) {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum0, hvx_vmemu(sz0)));
- } else {
- hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum0);
- }
- if (sz1) {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum1, hvx_vmemu(sz1)));
- } else {
- hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum1);
- }
+ store_row(s0, valid_rows, v_sum0, sz0);
+ store_row(s1, valid_rows, v_sum1, sz1);
}
@@ -2389,6 +2449,23 @@ static inline void quantize_f32_q8_0_tiled_kernel(
}
}
+static inline void quantize_f16_q8_0_tiled_kernel(
+ const uint8_t * restrict src_data,
+ uint8_t * restrict dst_data,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t nrows,
+ size_t src_row_size,
+ size_t dst_row_size
+) {
+ (void) tmp_data;
+ for (uint32_t i = 0; i < nrows; ++i) {
+ quantize_row_f16_q8_0_tiled((const __fp16 *) src_data, dst_data, ne0);
+ dst_data += dst_row_size;
+ src_data += src_row_size;
+ }
+}
+
static inline void quantize_f32_q8_1_tiled_kernel(
const uint8_t * restrict src_data,
uint8_t * restrict dst_data,
@@ -2406,6 +2483,23 @@ static inline void quantize_f32_q8_1_tiled_kernel(
}
}
+static inline void quantize_f16_q8_1_tiled_kernel(
+ const uint8_t * restrict src_data,
+ uint8_t * restrict dst_data,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t nrows,
+ size_t src_row_size,
+ size_t dst_row_size
+) {
+ (void) tmp_data;
+ for (uint32_t i = 0; i < nrows; ++i) {
+ quantize_row_f16_q8_1_tiled((const __fp16 *) src_data, dst_data, ne0);
+ dst_data += dst_row_size;
+ src_data += src_row_size;
+ }
+}
+
static inline void quantize_f32_q8_1_s16_tiled_kernel(
const uint8_t * restrict src_data,
uint8_t * restrict dst_data,
@@ -2423,6 +2517,23 @@ static inline void quantize_f32_q8_1_s16_tiled_kernel(
}
}
+static inline void quantize_f16_q8_1_s16_tiled_kernel(
+ const uint8_t * restrict src_data,
+ uint8_t * restrict dst_data,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t nrows,
+ size_t src_row_size,
+ size_t dst_row_size
+) {
+ (void) tmp_data;
+ for (uint32_t i = 0; i < nrows; ++i) {
+ quantize_row_f16_q8_1_s16_tiled((const __fp16 *) src_data, dst_data, ne0);
+ dst_data += dst_row_size;
+ src_data += src_row_size;
+ }
+}
+
static inline void quantize_f32_f16_tiled_kernel(
const uint8_t * restrict src_data,
uint8_t * restrict dst_data,
@@ -2487,6 +2598,36 @@ static inline void quantize_f32_q8_0_tiled_block_kernel(
}
}
+static inline void quantize_f16_q8_0_tiled_block_kernel(
+ const __fp16 * restrict src,
+ uint8_t * restrict dst,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t ib_first,
+ uint32_t ib_last,
+ size_t src_row_size,
+ size_t dst_row_size,
+ uint32_t r,
+ uint32_t c
+) {
+ (void) tmp_data;
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (ne0 + qk - 1) / qk;
+
+ for (uint32_t ib = ib_first; ib < ib_last; ++ib) {
+ const __fp16 * restrict src_ptr = (const __fp16 *) ((const uint8_t *) src + r * src_row_size + c * qk * sizeof(__fp16));
+ uint8_t * restrict dst_ptr = dst + r * dst_row_size + c * 4 * 1152;
+
+ quantize_block_f16_q8_0_tiled(src_ptr, dst_ptr);
+
+ c++;
+ if (c == nb) {
+ c = 0;
+ r++;
+ }
+ }
+}
+
static inline void quantize_f32_q8_1_tiled_block_kernel(
const float * restrict src,
uint8_t * restrict dst,
@@ -2517,6 +2658,36 @@ static inline void quantize_f32_q8_1_tiled_block_kernel(
}
}
+static inline void quantize_f16_q8_1_tiled_block_kernel(
+ const __fp16 * restrict src,
+ uint8_t * restrict dst,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t ib_first,
+ uint32_t ib_last,
+ size_t src_row_size,
+ size_t dst_row_size,
+ uint32_t r,
+ uint32_t c
+) {
+ (void) tmp_data;
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (ne0 + qk - 1) / qk;
+
+ for (uint32_t ib = ib_first; ib < ib_last; ++ib) {
+ const __fp16 * restrict src_ptr = (const __fp16 *) ((const uint8_t *) src + r * src_row_size + c * qk * sizeof(__fp16));
+ uint8_t * restrict dst_ptr = dst + r * dst_row_size + c * 4 * 1280;
+
+ quantize_block_f16_q8_1_tiled(src_ptr, dst_ptr);
+
+ c++;
+ if (c == nb) {
+ c = 0;
+ r++;
+ }
+ }
+}
+
static inline void quantize_f32_q8_1_s16_tiled_block_kernel(
const float * restrict src,
uint8_t * restrict dst,
@@ -2547,6 +2718,36 @@ static inline void quantize_f32_q8_1_s16_tiled_block_kernel(
}
}
+static inline void quantize_f16_q8_1_s16_tiled_block_kernel(
+ const __fp16 * restrict src,
+ uint8_t * restrict dst,
+ uint8_t * restrict tmp_data,
+ uint32_t ne0,
+ uint32_t ib_first,
+ uint32_t ib_last,
+ size_t src_row_size,
+ size_t dst_row_size,
+ uint32_t r,
+ uint32_t c
+) {
+ (void) tmp_data;
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (ne0 + qk - 1) / qk;
+
+ for (uint32_t ib = ib_first; ib < ib_last; ++ib) {
+ const __fp16 * restrict src_ptr = (const __fp16 *) ((const uint8_t *) src + r * src_row_size + c * qk * sizeof(__fp16));
+ uint8_t * restrict dst_ptr = dst + r * dst_row_size + c * 4 * 1280;
+
+ quantize_block_f16_q8_1_s16_tiled(src_ptr, dst_ptr, src_ptr - (c & 1) * qk); // super-block of 256 k
+
+ c++;
+ if (c == nb) {
+ c = 0;
+ r++;
+ }
+ }
+}
+
static inline void quantize_f32_f16_tiled_block_kernel(
const float * restrict src,
uint8_t * restrict dst,
diff --git a/ggml/src/ggml-hexagon/htp/hvx-norm.h b/ggml/src/ggml-hexagon/htp/hvx-norm.h
index 5d13acc87..4f6011cc1 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-norm.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-norm.h
@@ -341,29 +341,48 @@ static inline void hvx_fast_rms_norm_f16(const uint8_t * restrict src,
const int nvec = num_elems / VLEN_FP16; // number of full f16 vectors
const int nloe = num_elems % VLEN_FP16; // leftover elements
- HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000);
HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon);
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p = Q6_W_vzero();
+
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
- HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
- HVX_Vector p0 = Q6_V_lo_W(p);
- HVX_Vector p1 = Q6_V_hi_W(p);
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0));
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1));
+ HVX_Vector v = v_src[i];
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v);
}
if (nloe > 0) {
HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
- HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
- HVX_VectorPair p = hvx_vec_f16_to_f32(v1);
- HVX_Vector p0 = Q6_V_lo_W(p);
- HVX_Vector p1 = Q6_V_hi_W(p);
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0));
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1));
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v);
}
- sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
+ HVX_Vector sum_v = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p));
+#else
+ HVX_Vector sum0 = Q6_V_vzero();
+ HVX_Vector sum1 = Q6_V_vzero();
+
+ #pragma unroll(4)
+ for (int i = 0; i < nvec; i++) {
+ HVX_Vector v = v_src[i];
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq));
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq));
+ }
+
+ HVX_Vector sum_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum0, sum1));
+#endif
+
+ sum_v = hvx_vec_reduce_sum_f32(sum_v);
HVX_Vector t_v = hvx_vec_splat_f32((float) num_elems);
HVX_Vector denom_v = hvx_vec_inverse_f32(t_v);
@@ -374,19 +393,19 @@ static inline void hvx_fast_rms_norm_f16(const uint8_t * restrict src,
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
- HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_src[i]);
HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v));
HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v));
- v_dst[i] = hvx_vec_f32_to_f16(r0, r1);
+ v_dst[i] = hvx_vec_f32_to_f16_shuff(r0, r1);
}
if (nloe > 0) {
HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
- HVX_VectorPair p = hvx_vec_f16_to_f32(v1);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1);
HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v));
HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v));
- HVX_Vector result = hvx_vec_f32_to_f16(r0, r1);
+ HVX_Vector result = hvx_vec_f32_to_f16_shuff(r0, r1);
hvx_vec_store_a(&v_dst[nvec], nloe * SIZEOF_FP16, result);
}
}
@@ -402,35 +421,63 @@ static inline void hvx_fast_norm_f16(const uint8_t * restrict src,
const int nvec = num_elems / VLEN_FP16;
const int nloe = num_elems % VLEN_FP16;
- HVX_Vector sum_sq_v = Q6_V_vsplat_R(0x00000000);
- HVX_Vector sum_x_v = Q6_V_vsplat_R(0x00000000);
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0);
HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon);
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_sq_p = Q6_W_vzero();
+ HVX_VectorPair sum_x_p = Q6_W_vzero();
+
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
- HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
- HVX_Vector p0 = Q6_V_lo_W(p);
- HVX_Vector p1 = Q6_V_hi_W(p);
- sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0));
- sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1));
- sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p0, Q6_V_vzero()));
- sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p1, Q6_V_vzero()));
+ HVX_Vector v = v_src[i];
+ sum_sq_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_sq_p, v, v);
+ sum_x_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_x_p, v, one_hf);
}
if (nloe > 0) {
HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
- HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
- HVX_VectorPair p = hvx_vec_f16_to_f32(v1);
- HVX_Vector p0 = Q6_V_lo_W(p);
- HVX_Vector p1 = Q6_V_hi_W(p);
- sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0));
- sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1));
- sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p0, Q6_V_vzero()));
- sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p1, Q6_V_vzero()));
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ sum_sq_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_sq_p, v, v);
+ sum_x_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_x_p, v, one_hf);
}
- sum_sq_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_sq_v));
- sum_x_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_x_v));
+ HVX_Vector sum_sq_v = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_sq_p), Q6_V_hi_W(sum_sq_p));
+ HVX_Vector sum_x_v = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_x_p), Q6_V_hi_W(sum_x_p));
+#else
+ HVX_Vector sum_sq0 = Q6_V_vzero();
+ HVX_Vector sum_sq1 = Q6_V_vzero();
+ HVX_Vector sum_x0 = Q6_V_vzero();
+ HVX_Vector sum_x1 = Q6_V_vzero();
+
+ #pragma unroll(4)
+ for (int i = 0; i < nvec; i++) {
+ HVX_Vector v = v_src[i];
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ HVX_VectorPair xp = Q6_Wqf32_vmpy_VhfVhf(v, one_hf);
+ sum_sq0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq0, Q6_V_lo_W(sq));
+ sum_sq1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq1, Q6_V_hi_W(sq));
+ sum_x0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x0, Q6_V_lo_W(xp));
+ sum_x1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x1, Q6_V_hi_W(xp));
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ HVX_VectorPair xp = Q6_Wqf32_vmpy_VhfVhf(v, one_hf);
+ sum_sq0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq0, Q6_V_lo_W(sq));
+ sum_sq1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq1, Q6_V_hi_W(sq));
+ sum_x0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x0, Q6_V_lo_W(xp));
+ sum_x1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x1, Q6_V_hi_W(xp));
+ }
+
+ HVX_Vector sum_sq_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq0, sum_sq1));
+ HVX_Vector sum_x_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum_x0, sum_x1));
+#endif
+
+ sum_sq_v = hvx_vec_reduce_sum_f32(sum_sq_v);
+ sum_x_v = hvx_vec_reduce_sum_f32(sum_x_v);
HVX_Vector t_v = hvx_vec_splat_f32((float) num_elems);
HVX_Vector denom_v = hvx_vec_inverse_f32(t_v);
@@ -445,23 +492,23 @@ static inline void hvx_fast_norm_f16(const uint8_t * restrict src,
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
- HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_src[i]);
HVX_Vector d0 = Q6_Vqf32_vsub_VsfVsf(Q6_V_lo_W(p), mean_x_b);
HVX_Vector d1 = Q6_Vqf32_vsub_VsfVsf(Q6_V_hi_W(p), mean_x_b);
HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d0), scale_v));
HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d1), scale_v));
- v_dst[i] = hvx_vec_f32_to_f16(r0, r1);
+ v_dst[i] = hvx_vec_f32_to_f16_shuff(r0, r1);
}
if (nloe > 0) {
HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
- HVX_VectorPair p = hvx_vec_f16_to_f32(v1);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1);
HVX_Vector d0 = Q6_Vqf32_vsub_VsfVsf(Q6_V_lo_W(p), mean_x_b);
HVX_Vector d1 = Q6_Vqf32_vsub_VsfVsf(Q6_V_hi_W(p), mean_x_b);
HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d0), scale_v));
HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d1), scale_v));
- HVX_Vector result = hvx_vec_f32_to_f16(r0, r1);
+ HVX_Vector result = hvx_vec_f32_to_f16_shuff(r0, r1);
hvx_vec_store_a(&v_dst[nvec], nloe * SIZEOF_FP16, result);
}
}
@@ -477,51 +524,224 @@ static inline void hvx_fast_l2_norm_f16(const uint8_t * restrict src,
const int nvec = num_elems / VLEN_FP16;
const int nloe = num_elems % VLEN_FP16;
- HVX_Vector sum_v = hvx_vec_splat_f32(0.0f);
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p = Q6_W_vzero();
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
- HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
- HVX_Vector p0 = Q6_V_lo_W(p);
- HVX_Vector p1 = Q6_V_hi_W(p);
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0));
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1));
+ HVX_Vector v = v_src[i];
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v);
}
if (nloe > 0) {
HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
- HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
- HVX_VectorPair p = hvx_vec_f16_to_f32(v1);
- HVX_Vector p0 = Q6_V_lo_W(p);
- HVX_Vector p1 = Q6_V_hi_W(p);
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0));
- sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1));
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v);
}
- HVX_Vector sum_sf = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
- HVX_Vector rsqrt_v = hvx_vec_rsqrt_f32(sum_sf);
- HVX_Vector sqrt_v = hvx_vec_inverse_f32(rsqrt_v);
- HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon);
- HVX_Vector denom_v = Q6_Vsf_vmax_VsfVsf(sqrt_v, epsilon_v);
- HVX_Vector scale_v = hvx_vec_inverse_f32(denom_v);
+ HVX_Vector sum_sf = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p));
+#else
+ HVX_Vector sum0 = Q6_V_vzero();
+ HVX_Vector sum1 = Q6_V_vzero();
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
- HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
+ HVX_Vector v = v_src[i];
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq));
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq));
+ }
+
+ HVX_Vector sum_sf = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum0, sum1));
+#endif
+
+ sum_sf = hvx_vec_reduce_sum_f32(sum_sf);
+ HVX_Vector eps2_v = hvx_vec_splat_f32(epsilon * epsilon);
+ HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_vmax_VsfVsf(sum_sf, eps2_v));
+
+ #pragma unroll(4)
+ for (int i = 0; i < nvec; i++) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_src[i]);
HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v));
HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v));
- v_dst[i] = hvx_vec_f32_to_f16(r0, r1);
+ v_dst[i] = hvx_vec_f32_to_f16_shuff(r0, r1);
}
if (nloe > 0) {
HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16);
HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
- HVX_VectorPair p = hvx_vec_f16_to_f32(v1);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1);
HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v));
HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v));
- HVX_Vector result = hvx_vec_f32_to_f16(r0, r1);
+ HVX_Vector result = hvx_vec_f32_to_f16_shuff(r0, r1);
hvx_vec_store_a(&v_dst[nvec], nloe * SIZEOF_FP16, result);
}
}
+static __attribute__((noinline, unused)) void hvx_rms_norm_mul_f16_w32_ne128_bcast_rows(
+ const uint8_t * restrict src,
+ const uint8_t * restrict weight,
+ uint8_t * restrict dst,
+ uint32_t num_rows,
+ size_t src_stride,
+ size_t dst_stride,
+ float epsilon,
+ float scale) {
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) weight;
+ const HVX_VectorPair wp0 = Q6_W_vdeal_VVR(v_w[1], v_w[0], -4);
+ const HVX_VectorPair wp1 = Q6_W_vdeal_VVR(v_w[3], v_w[2], -4);
+ const HVX_Vector w0 = Q6_V_lo_W(wp0);
+ const HVX_Vector w1 = Q6_V_hi_W(wp0);
+ const HVX_Vector w2 = Q6_V_lo_W(wp1);
+ const HVX_Vector w3 = Q6_V_hi_W(wp1);
+
+ const HVX_Vector v_one_f16 = Q6_Vh_vsplat_R(0x3c00);
+ const HVX_Vector denom_v = hvx_vec_splat_f32(1.0f / 128.0f);
+ const HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon);
+ const HVX_Vector scale_opt = hvx_vec_splat_f32(scale);
+ const bool has_scale = (scale != 0.0f);
+
+ #pragma nounroll
+ for (uint32_t ir = 0; ir < num_rows; ++ir) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) (src + ir * src_stride);
+ HVX_Vector * restrict v_dst = (HVX_Vector *) (dst + ir * dst_stride);
+
+ const HVX_Vector s0_hf = v_src[0];
+ const HVX_Vector s1_hf = v_src[1];
+ const HVX_VectorPair p0 = hvx_vec_mpy_f32_f16(s0_hf, v_one_f16);
+ const HVX_VectorPair p1 = hvx_vec_mpy_f32_f16(s1_hf, v_one_f16);
+ const HVX_Vector x0 = Q6_V_lo_W(p0);
+ const HVX_Vector x1 = Q6_V_hi_W(p0);
+ const HVX_Vector x2 = Q6_V_lo_W(p1);
+ const HVX_Vector x3 = Q6_V_hi_W(p1);
+
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p = Q6_Wsf_vmpy_VhfVhf(s0_hf, s0_hf);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s1_hf, s1_hf);
+ HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p)));
+#else
+ HVX_Vector sum01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, x0), Q6_Vqf32_vmpy_VsfVsf(x1, x1));
+ HVX_Vector sum23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, x2), Q6_Vqf32_vmpy_VsfVsf(x3, x3));
+ HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum01, sum23)));
+#endif
+
+ HVX_Vector mean_eps = Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(sum_v, denom_v), epsilon_v);
+ HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_equals_Vqf32(mean_eps));
+ if (has_scale) {
+ scale_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(scale_v, scale_opt));
+ }
+
+ HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, scale_v));
+ HVX_Vector s1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x1, scale_v));
+ HVX_Vector s2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, scale_v));
+ HVX_Vector s3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x3, scale_v));
+
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, w0));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, w1));
+ HVX_Vector r2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s2, w2));
+ HVX_Vector r3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s3, w3));
+
+ v_dst[0] = hvx_vec_f32_to_f16_shuff(r0, r1);
+ v_dst[1] = hvx_vec_f32_to_f16_shuff(r2, r3);
+ }
+}
+
+static __attribute__((noinline, unused)) void hvx_rms_norm_mul_f16_w32_ne256_bcast_rows(
+ const uint8_t * restrict src,
+ const uint8_t * restrict weight,
+ uint8_t * restrict dst,
+ uint32_t num_rows,
+ size_t src_stride,
+ size_t dst_stride,
+ float epsilon,
+ float scale) {
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) weight;
+ const HVX_VectorPair wp0 = Q6_W_vdeal_VVR(v_w[1], v_w[0], -4);
+ const HVX_VectorPair wp1 = Q6_W_vdeal_VVR(v_w[3], v_w[2], -4);
+ const HVX_VectorPair wp2 = Q6_W_vdeal_VVR(v_w[5], v_w[4], -4);
+ const HVX_VectorPair wp3 = Q6_W_vdeal_VVR(v_w[7], v_w[6], -4);
+ const HVX_Vector w0 = Q6_V_lo_W(wp0);
+ const HVX_Vector w1 = Q6_V_hi_W(wp0);
+ const HVX_Vector w2 = Q6_V_lo_W(wp1);
+ const HVX_Vector w3 = Q6_V_hi_W(wp1);
+ const HVX_Vector w4 = Q6_V_lo_W(wp2);
+ const HVX_Vector w5 = Q6_V_hi_W(wp2);
+ const HVX_Vector w6 = Q6_V_lo_W(wp3);
+ const HVX_Vector w7 = Q6_V_hi_W(wp3);
+
+ const HVX_Vector v_one_f16 = Q6_Vh_vsplat_R(0x3c00);
+ const HVX_Vector denom_v = hvx_vec_splat_f32(1.0f / 256.0f);
+ const HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon);
+ const HVX_Vector scale_opt = hvx_vec_splat_f32(scale);
+ const bool has_scale = (scale != 0.0f);
+
+ #pragma nounroll
+ for (uint32_t ir = 0; ir < num_rows; ++ir) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) (src + ir * src_stride);
+ HVX_Vector * restrict v_dst = (HVX_Vector *) (dst + ir * dst_stride);
+
+ const HVX_Vector s0_hf = v_src[0];
+ const HVX_Vector s1_hf = v_src[1];
+ const HVX_Vector s2_hf = v_src[2];
+ const HVX_Vector s3_hf = v_src[3];
+ const HVX_VectorPair p0 = hvx_vec_mpy_f32_f16(s0_hf, v_one_f16);
+ const HVX_VectorPair p1 = hvx_vec_mpy_f32_f16(s1_hf, v_one_f16);
+ const HVX_VectorPair p2 = hvx_vec_mpy_f32_f16(s2_hf, v_one_f16);
+ const HVX_VectorPair p3 = hvx_vec_mpy_f32_f16(s3_hf, v_one_f16);
+
+ const HVX_Vector x0 = Q6_V_lo_W(p0);
+ const HVX_Vector x1 = Q6_V_hi_W(p0);
+ const HVX_Vector x2 = Q6_V_lo_W(p1);
+ const HVX_Vector x3 = Q6_V_hi_W(p1);
+ const HVX_Vector x4 = Q6_V_lo_W(p2);
+ const HVX_Vector x5 = Q6_V_hi_W(p2);
+ const HVX_Vector x6 = Q6_V_lo_W(p3);
+ const HVX_Vector x7 = Q6_V_hi_W(p3);
+
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p = Q6_Wsf_vmpy_VhfVhf(s0_hf, s0_hf);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s1_hf, s1_hf);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s2_hf, s2_hf);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s3_hf, s3_hf);
+ HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p)));
+#else
+ HVX_Vector s01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, x0), Q6_Vqf32_vmpy_VsfVsf(x1, x1));
+ HVX_Vector s23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, x2), Q6_Vqf32_vmpy_VsfVsf(x3, x3));
+ HVX_Vector s45 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x4, x4), Q6_Vqf32_vmpy_VsfVsf(x5, x5));
+ HVX_Vector s67 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x6, x6), Q6_Vqf32_vmpy_VsfVsf(x7, x7));
+ HVX_Vector sum_qf = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(s01, s23),
+ Q6_Vqf32_vadd_Vqf32Vqf32(s45, s67));
+ HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_qf));
+#endif
+
+ HVX_Vector mean_eps = Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(sum_v, denom_v), epsilon_v);
+ HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_equals_Vqf32(mean_eps));
+ if (has_scale) {
+ scale_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(scale_v, scale_opt));
+ }
+
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, scale_v)), w0));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x1, scale_v)), w1));
+ HVX_Vector r2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, scale_v)), w2));
+ HVX_Vector r3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x3, scale_v)), w3));
+ HVX_Vector r4 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x4, scale_v)), w4));
+ HVX_Vector r5 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x5, scale_v)), w5));
+ HVX_Vector r6 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x6, scale_v)), w6));
+ HVX_Vector r7 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x7, scale_v)), w7));
+
+ v_dst[0] = hvx_vec_f32_to_f16_shuff(r0, r1);
+ v_dst[1] = hvx_vec_f32_to_f16_shuff(r2, r3);
+ v_dst[2] = hvx_vec_f32_to_f16_shuff(r4, r5);
+ v_dst[3] = hvx_vec_f32_to_f16_shuff(r6, r7);
+ }
+}
+
#endif // HVX_NORM_H
diff --git a/ggml/src/ggml-hexagon/htp/hvx-quant.h b/ggml/src/ggml-hexagon/htp/hvx-quant.h
index b0ca6ecf6..358ece4e8 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-quant.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-quant.h
@@ -16,12 +16,28 @@
#define GGML_COMMON_DECL_C
#endif
#include "ggml-common.h"
-#include "ggml-impl.h"
+
+static inline float hvx_fp16_to_fp32(uint16_t h) {
+ __fp16 f;
+ memcpy(&f, &h, sizeof(f));
+ return (float) f;
+}
+
+static inline HVX_Vector hvx_vec_reduce_max_32_f16(HVX_Vector v) {
+ v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 32));
+ v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 16));
+ v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 8));
+ v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 4));
+ v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 2));
+ HVX_Vector pair = Q6_V_vmux_QVV(Q6_Q_vsetq_R(2), v, Q6_V_vror_VR(v, 62));
+ return hvx_vec_repl_2x_f16(pair);
+}
static inline void hvx_quantize_row_q8_0_f32(void * restrict dst_ptr, const float * restrict src_ptr, int n) {
const int nb = n / QK8_0;
block_q8_0 * dst = (block_q8_0 *) dst_ptr;
- HVX_Vector zero = Q6_V_vzero();
+ const HVX_Vector inv127_hf = Q6_Vh_vsplat_R(0x2008); // 1.0 / 127.0
+ const HVX_Vector zero = Q6_V_vzero();
int i = 0;
for (; i + 3 < nb; i += 4) {
@@ -32,31 +48,78 @@ static inline void hvx_quantize_row_q8_0_f32(void * restrict dst_ptr, const floa
HVX_Vector vmax2_sf = hvx_vec_reduce_max_f32(hvx_vec_abs_f32(vx[2]));
HVX_Vector vmax3_sf = hvx_vec_reduce_max_f32(hvx_vec_abs_f32(vx[3]));
- HVX_Vector vx0_qf = Q6_Vqf32_vsub_VsfVsf(vx[0], zero);
- HVX_Vector vx1_qf = Q6_Vqf32_vsub_VsfVsf(vx[1], zero);
- HVX_Vector vx2_qf = Q6_Vqf32_vsub_VsfVsf(vx[2], zero);
- HVX_Vector vx3_qf = Q6_Vqf32_vsub_VsfVsf(vx[3], zero);
+ HVX_Vector vmax01_hf = hvx_vec_f32_to_f16(vmax0_sf, vmax1_sf);
+ HVX_Vector vmax23_hf = hvx_vec_f32_to_f16(vmax2_sf, vmax3_sf);
+
+ HVX_Vector vx01_hf = hvx_vec_f32_to_f16(vx[0], vx[1]);
+ HVX_Vector vx23_hf = hvx_vec_f32_to_f16(vx[2], vx[3]);
+
+ HVX_Vector vd01_hf = hvx_vec_mul_f16_f16(vmax01_hf, inv127_hf);
+ HVX_Vector vd23_hf = hvx_vec_mul_f16_f16(vmax23_hf, inv127_hf);
+
+ HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf);
+ HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf);
+ vx01_hf = hvx_vec_mul_f16_f16(vx01_hf, vd01_inv_hf);
+ vx23_hf = hvx_vec_mul_f16_f16(vx23_hf, vd23_inv_hf);
+
+ HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf);
+ HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf);
+ HVX_Vector vx_i8 = Q6_Vb_vpack_VhVh_sat(vx23_i16, vx01_i16);
+
+ hvx_vec_store_u(&dst[i + 0].d, 2, vd01_hf);
+ hvx_vec_store_u(dst[i + 0].qs, 32, vx_i8);
+
+ hvx_vec_store_u(&dst[i + 1].d, 2, Q6_V_vror_VR(vd01_hf, 64));
+ hvx_vec_store_u(dst[i + 1].qs, 32, Q6_V_vror_VR(vx_i8, 32));
+
+ hvx_vec_store_u(&dst[i + 2].d, 2, vd23_hf);
+ hvx_vec_store_u(dst[i + 2].qs, 32, Q6_V_vror_VR(vx_i8, 64));
+
+ hvx_vec_store_u(&dst[i + 3].d, 2, Q6_V_vror_VR(vd23_hf, 64));
+ hvx_vec_store_u(dst[i + 3].qs, 32, Q6_V_vror_VR(vx_i8, 96));
+ }
+
+ for (; i < nb; i++) {
+ const float * block_src = src_ptr + i * QK8_0;
+ HVX_Vector vx = *(const HVX_UVector *) block_src;
+ HVX_Vector vmax_sf = hvx_vec_reduce_max_f32(hvx_vec_abs_f32(vx));
+
+ HVX_Vector vmax_hf = hvx_vec_f32_to_f16(vmax_sf, zero);
+ HVX_Vector vx_hf = hvx_vec_f32_to_f16(vx, zero);
+
+ HVX_Vector vd_hf = hvx_vec_mul_f16_f16(vmax_hf, inv127_hf);
+ HVX_Vector vd_inv_hf = hvx_vec_inverse_f16(vd_hf);
+ vx_hf = hvx_vec_mul_f16_f16(vx_hf, vd_inv_hf);
+
+ HVX_Vector v_i16 = hvx_vec_i16_from_hf_rnd_sat(vx_hf);
+ HVX_Vector v_i8 = Q6_Vb_vpack_VhVh_sat(zero, v_i16);
+
+ hvx_vec_store_u(&dst[i].d, 2, vd_hf);
+ hvx_vec_store_u(dst[i].qs, 32, v_i8);
+ }
+}
- HVX_Vector vmax0_qf = Q6_Vqf32_vsub_VsfVsf(vmax0_sf, zero);
- HVX_Vector vmax1_qf = Q6_Vqf32_vsub_VsfVsf(vmax1_sf, zero);
- HVX_Vector vmax2_qf = Q6_Vqf32_vsub_VsfVsf(vmax2_sf, zero);
- HVX_Vector vmax3_qf = Q6_Vqf32_vsub_VsfVsf(vmax3_sf, zero);
+static inline void hvx_quantize_row_q8_0_f16(void * restrict dst_ptr, const __fp16 * restrict src_ptr, int n) {
+ const int nb = n / QK8_0;
+ block_q8_0 * dst = (block_q8_0 *) dst_ptr;
+ const HVX_Vector inv127_hf = Q6_Vh_vsplat_R(0x2008); // 1.0 / 127.0
- HVX_Vector vmax01_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vmax1_qf, vmax0_qf)));
- HVX_Vector vmax23_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vmax3_qf, vmax2_qf)));
+ int i = 0;
+ for (; i + 3 < nb; i += 4) {
+ const HVX_UVector * vsrc = (const HVX_UVector *) (src_ptr + i * QK8_0);
+ HVX_Vector vx01_hf = vsrc[0];
+ HVX_Vector vx23_hf = vsrc[1];
- HVX_Vector vx01_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vx1_qf, vx0_qf)));
- HVX_Vector vx23_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vx3_qf, vx2_qf)));
+ HVX_Vector vmax01_hf = hvx_vec_reduce_max_32_f16(hvx_vec_abs_f16(vx01_hf));
+ HVX_Vector vmax23_hf = hvx_vec_reduce_max_32_f16(hvx_vec_abs_f16(vx23_hf));
- HVX_Vector vd01_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax01_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0
- HVX_Vector vd23_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax23_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0
- HVX_Vector vd01_hf = Q6_Vhf_equals_Vqf16(vd01_qf16);
- HVX_Vector vd23_hf = Q6_Vhf_equals_Vqf16(vd23_qf16);
+ HVX_Vector vd01_hf = hvx_vec_mul_f16_f16(vmax01_hf, inv127_hf);
+ HVX_Vector vd23_hf = hvx_vec_mul_f16_f16(vmax23_hf, inv127_hf);
HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf);
HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf);
- vx01_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx01_hf, vd01_inv_hf));
- vx23_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx23_hf, vd23_inv_hf));
+ vx01_hf = hvx_vec_mul_f16_f16(vx01_hf, vd01_inv_hf);
+ vx23_hf = hvx_vec_mul_f16_f16(vx23_hf, vd23_inv_hf);
HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf);
HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf);
@@ -75,24 +138,20 @@ static inline void hvx_quantize_row_q8_0_f32(void * restrict dst_ptr, const floa
hvx_vec_store_u(dst[i + 3].qs, 32, Q6_V_vror_VR(vx_i8, 96));
}
+ const HVX_Vector zero = Q6_V_vzero();
for (; i < nb; i++) {
- const float * block_src = src_ptr + i * QK8_0;
- HVX_Vector vx = *(const HVX_UVector *) block_src;
- HVX_Vector v_abs = hvx_vec_abs_f32(vx);
- HVX_Vector v_max = hvx_vec_reduce_max_f32(v_abs);
- float amax = hvx_vec_get_f32(v_max);
-
- const float d = amax / 127.0f;
- const float id = d ? (1.0f / d) : 0.0f;
- dst[i].d = GGML_FP32_TO_FP16(d);
-
- HVX_Vector vid = hvx_vec_splat_f32(id);
- HVX_Vector v_scaled = hvx_vec_mul_f32_f32(vx, vid);
- HVX_Vector v_scaled_qf = Q6_Vqf32_vsub_VsfVsf(v_scaled, zero);
- HVX_Vector v_scaled_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(zero, v_scaled_qf)));
- HVX_Vector v_i16 = hvx_vec_i16_from_hf_rnd_sat(v_scaled_hf);
+ const __fp16 * block_src = src_ptr + i * QK8_0;
+ HVX_Vector vx_hf = *(const HVX_UVector *) block_src;
+ HVX_Vector vmax_hf = hvx_vec_reduce_max_32_f16(hvx_vec_abs_f16(vx_hf));
+
+ HVX_Vector vd_hf = hvx_vec_mul_f16_f16(vmax_hf, inv127_hf);
+ HVX_Vector vd_inv_hf = hvx_vec_inverse_f16(vd_hf);
+ vx_hf = hvx_vec_mul_f16_f16(vx_hf, vd_inv_hf);
+
+ HVX_Vector v_i16 = hvx_vec_i16_from_hf_rnd_sat(vx_hf);
HVX_Vector v_i8 = Q6_Vb_vpack_VhVh_sat(zero, v_i16);
+ hvx_vec_store_u(&dst[i].d, 2, vd_hf);
hvx_vec_store_u(dst[i].qs, 32, v_i8);
}
}
@@ -121,29 +180,99 @@ static inline void hvx_dequantize_row_flat_q8_0_f32(float * restrict dst_ptr, co
}
}
-static inline void hvx_dequantize_row_flat_q8_0_f16(__fp16 * restrict dst_ptr, const void * restrict src_ptr, uint32_t n) {
- const int nb = n / QK8_0;
- const block_q8_0 * src = (const block_q8_0 *) src_ptr;
+static inline HVX_VectorPair hvx_dequant_q8_0_x4_f16(HVX_Vector v0, HVX_Vector v1,
+ HVX_VectorPred q32, HVX_VectorPred q64, HVX_VectorPred q96) {
+ HVX_Vector qs = Q6_V_vmux_QVV(q96, Q6_V_valign_VVR(v1, v0, 6), Q6_V_valign_VVR(v1, v0, 8));
+ qs = Q6_V_vmux_QVV(q64, Q6_V_valign_VVR(v1, v0, 4), qs);
+ qs = Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(v1, v0, 2), qs);
- for (int i = nb - 1; i >= 0; i--) {
- HVX_Vector vd_f16 = Q6_Vh_vsplat_R(*(const int16_t *) &src[i].d);
- HVX_VectorPair vp_f32 = hvx_vec_f16_to_f32(vd_f16);
- HVX_Vector vd = Q6_V_lo_W(vp_f32);
+ const HVX_Vector s01 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(v0), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 34)));
+ const HVX_Vector s23 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 68)), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 102)));
- HVX_Vector vq_i8 = *(const HVX_UVector *) src[i].qs;
+ const HVX_VectorPair qh = Q6_Wh_vunpack_Vb(qs);
+ const HVX_Vector res01 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vh(Q6_V_lo_W(qh)), s01);
+ const HVX_Vector res23 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vh(Q6_V_hi_W(qh)), s23);
+ return Q6_W_vcombine_VV(res23, res01);
+}
- HVX_VectorPair p16 = Q6_Wh_vunpack_Vb(vq_i8);
- HVX_Vector v_i16 = Q6_V_lo_W(p16);
- HVX_VectorPair p32 = Q6_Ww_vunpack_Vh(v_i16);
- HVX_Vector v_i32 = Q6_V_lo_W(p32);
+static __attribute__((noinline)) void hvx_dequantize_row_flat_q8_0_f16_u(__fp16 * dst_ptr, const void * src_ptr, int32_t nb) {
+ const uint8_t * src_base = (const uint8_t *) src_ptr;
+ const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
+ const HVX_VectorPred q64 = Q6_Q_vsetq_R(64);
+ const HVX_VectorPred q96 = Q6_Q_vsetq_R(96);
+
+ const int32_t n_full = nb / 4;
+ const int32_t rem = nb & 3;
+
+ if (rem > 0) {
+ const uint8_t * s = src_base + n_full * 4 * sizeof(block_q8_0);
+ __fp16 * d = dst_ptr + n_full * 4 * QK8_0;
+ const HVX_Vector v0 = *(const HVX_UVector *) s;
+ const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, Q6_V_vzero(), q32, q64, q96);
+ if (rem == 3) {
+ hvx_vec_store_u(d + 64, 64, Q6_V_hi_W(res));
+ hvx_vmemu(d + 0) = Q6_V_lo_W(res);
+ } else if (rem == 2) {
+ hvx_vmemu(d + 0) = Q6_V_lo_W(res);
+ } else {
+ hvx_vec_store_u(d + 0, 64, Q6_V_lo_W(res));
+ }
+ }
- HVX_Vector v_f32 = Q6_Vsf_equals_Vw(v_i32);
- HVX_Vector res_f32 = hvx_vec_mul_f32_f32(v_f32, vd);
+ for (int32_t g = n_full - 1; g >= 0; --g) {
+ const uint8_t * s = src_base + g * 4 * sizeof(block_q8_0);
+ __fp16 * d = dst_ptr + g * 4 * QK8_0;
+ const HVX_Vector v0 = *(const HVX_UVector *) s;
+ const HVX_Vector v1 = *(const HVX_UVector *) (s + VLEN);
+ const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, v1, q32, q64, q96);
+ hvx_vmemu(d + 64) = Q6_V_hi_W(res);
+ hvx_vmemu(d + 0) = Q6_V_lo_W(res);
+ }
+}
- HVX_Vector res_f16 = hvx_vec_f32_to_f16(res_f32, Q6_V_vzero());
+// Q8_0 row to f16 (supports in-place dst_ptr == src_ptr), 4 blocks (128 values) per step backwards.
+static inline void hvx_dequantize_row_flat_q8_0_f16(__fp16 * dst_ptr, const void * src_ptr, uint32_t n) {
+ const int32_t nb = (int32_t) (n / QK8_0);
+ if (nb <= 0) {
+ return;
+ }
+
+ if (!hex_is_aligned(dst_ptr, 128)) {
+ hvx_dequantize_row_flat_q8_0_f16_u(dst_ptr, src_ptr, nb);
+ return;
+ }
- __fp16 * block_dst = dst_ptr + i * QK8_0;
- hvx_vec_store_u(block_dst, QK8_0 * sizeof(__fp16), res_f16);
+ const uint8_t * src_base = (const uint8_t *) src_ptr;
+ const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
+ const HVX_VectorPred q64 = Q6_Q_vsetq_R(64);
+ const HVX_VectorPred q96 = Q6_Q_vsetq_R(96);
+
+ const int32_t n_full = nb / 4;
+ const int32_t rem = nb & 3;
+
+ if (rem > 0) {
+ const uint8_t * s = src_base + n_full * 4 * sizeof(block_q8_0);
+ __fp16 * d = dst_ptr + n_full * 4 * QK8_0;
+ const HVX_Vector v0 = *(const HVX_UVector *) s;
+ const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, Q6_V_vzero(), q32, q64, q96);
+ if (rem == 3) {
+ Q6_vmem_QRIV(q64, (HVX_Vector *) (d + 64), Q6_V_hi_W(res));
+ hvx_vmem(d + 0) = Q6_V_lo_W(res);
+ } else if (rem == 2) {
+ hvx_vmem(d + 0) = Q6_V_lo_W(res);
+ } else {
+ Q6_vmem_QRIV(q64, (HVX_Vector *) (d + 0), Q6_V_lo_W(res));
+ }
+ }
+
+ for (int32_t g = n_full - 1; g >= 0; --g) {
+ const uint8_t * s = src_base + g * 4 * sizeof(block_q8_0);
+ __fp16 * d = dst_ptr + g * 4 * QK8_0;
+ const HVX_Vector v0 = *(const HVX_UVector *) s;
+ const HVX_Vector v1 = *(const HVX_UVector *) (s + VLEN);
+ const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, v1, q32, q64, q96);
+ hvx_vmem(d + 64) = Q6_V_hi_W(res);
+ hvx_vmem(d + 0) = Q6_V_lo_W(res);
}
}
@@ -288,8 +417,8 @@ static inline void hvx_dequantize_row_flat_q4_k_f32(float * restrict dst_ptr, co
const block_q4_K * src = (const block_q4_K *) src_ptr;
for (int i = 0; i < nb; i++) {
- const float d = GGML_FP16_TO_FP32(src[i].d);
- const float min = GGML_FP16_TO_FP32(src[i].dmin);
+ const float d = hvx_fp16_to_fp32(src[i].d);
+ const float min = hvx_fp16_to_fp32(src[i].dmin);
const uint8_t * sc = src[i].scales;
float * y = dst_ptr + i * QK_K;
@@ -343,8 +472,8 @@ static inline void hvx_dequantize_row_flat_q5_k_f32(float * restrict dst_ptr, co
const block_q5_K * src = (const block_q5_K *) src_ptr;
for (int i = 0; i < nb; i++) {
- const float d = GGML_FP16_TO_FP32(src[i].d);
- const float min = GGML_FP16_TO_FP32(src[i].dmin);
+ const float d = hvx_fp16_to_fp32(src[i].d);
+ const float min = hvx_fp16_to_fp32(src[i].dmin);
const uint8_t * sc = src[i].scales;
HVX_Vector v_qh = *(const HVX_UVector *) src[i].qh;
@@ -410,7 +539,7 @@ static inline void hvx_dequantize_row_flat_q6_k_f32(float * restrict dst_ptr, co
const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
for (int i = 0; i < nb; i++) {
- const float d = GGML_FP16_TO_FP32(src[i].d);
+ const float d = hvx_fp16_to_fp32(src[i].d);
const uint8_t * restrict ql = src[i].ql;
const uint8_t * restrict qh = src[i].qh;
@@ -478,26 +607,17 @@ static inline void hvx_dequantize_row_flat_q6_k_f32(float * restrict dst_ptr, co
}
// bytes row, row + 32, row + 64 and row + 96 of v, to bytes 0..3
-static inline HVX_Vector hvx_dequantize_gather4(HVX_Vector v, uint32_t row) {
- v = Q6_V_vror_VR(v, row);
- HVX_Vector packed = Q6_V_vmux_QVV(Q6_Q_vsetq_R(1), v, Q6_V_vror_VR(v, 31));
- packed = Q6_V_vmux_QVV(Q6_Q_vsetq_R(2), packed, Q6_V_vror_VR(v, 62));
- return Q6_V_vmux_QVV(Q6_Q_vsetq_R(3), packed, Q6_V_vror_VR(v, 93));
-}
-
-static inline void hvx_dequantize_row_tiled_q8_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
- const HVX_VectorPred first2 = Q6_Q_vsetq_R(2);
+static inline void hvx_dequantize_row_tiled_q8_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
HVX_Vector vq = Q6_V_vzero();
for (int group = 7; group >= 0; --group) {
- const HVX_Vector v = Q6_V_vror_VR(hvx_vmem(tile + group * VLEN), 2 * row);
- const HVX_Vector packed = Q6_V_vmux_QVV(first2, v, Q6_V_vror_VR(v, 62));
- vq = Q6_V_vmux_QVV(first4, packed, Q6_V_vror_VR(vq, VLEN - 4));
+ const HVX_Vector v = Q6_V_vror_VR(hvx_vmem(tile + group * VLEN), 4 * row);
+ vq = Q6_V_vmux_QVV(first4, v, Q6_V_vror_VR(vq, VLEN - 4));
}
const HVX_Vector scales = hvx_vmem(tile + 1024);
@@ -510,22 +630,24 @@ static inline void hvx_dequantize_row_tiled_q8_0_f32(float * dst_spad, const uin
}
}
-static inline void hvx_dequantize_row_tiled_q4_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
- const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
+static inline void hvx_dequantize_row_tiled_q4_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+ const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector i8 = Q6_Vb_vsplat_R(8);
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
HVX_Vector vq = Q6_V_vzero();
- for (int group = 3; group >= 0; --group) {
- vq = Q6_V_vmux_QVV(first4, hvx_dequantize_gather4(hvx_vmem(tile + group * VLEN), row), Q6_V_vror_VR(vq, VLEN - 4));
+ for (int i = 3; i >= 0; --i) {
+ const HVX_Vector plane = Q6_V_vror_VR(hvx_vmem(tile + i * VLEN), 4 * row);
+ const HVX_Vector hi = Q6_Vub_vlsr_VubR(plane, 4);
+ const HVX_Vector lo = Q6_V_vand_VV(plane, mask_0f);
+ vq = Q6_V_vmux_QVV(first4, hi, Q6_V_vror_VR(vq, VLEN - 4));
+ vq = Q6_V_vmux_QVV(first4, lo, Q6_V_vror_VR(vq, VLEN - 4));
}
-
- const HVX_Vector lo = Q6_V_vand_VV(vq, Q6_Vb_vsplat_R(0x0F));
- const HVX_Vector hi = Q6_Vub_vlsr_VubR(vq, 4);
- vq = Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -1));
- vq = Q6_Vb_vsub_VbVb(vq, Q6_Vb_vsplat_R(8));
+ vq = Q6_Vb_vsub_VbVb(vq, i8);
const HVX_Vector scales = hvx_vmem(tile + 512);
const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 2 * row));
@@ -537,22 +659,23 @@ static inline void hvx_dequantize_row_tiled_q4_0_f32(float * dst_spad, const uin
}
}
-static inline void hvx_dequantize_row_tiled_q4_k_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
- const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
+static inline void hvx_dequantize_row_tiled_q4_k_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+ const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
HVX_Vector vq = Q6_V_vzero();
- for (int group = 3; group >= 0; --group) {
- vq = Q6_V_vmux_QVV(first4, hvx_dequantize_gather4(hvx_vmem(tile + group * VLEN), row), Q6_V_vror_VR(vq, VLEN - 4));
+ for (int i = 3; i >= 0; --i) {
+ const HVX_Vector plane = Q6_V_vror_VR(hvx_vmem(tile + i * VLEN), 4 * row);
+ const HVX_Vector hi = Q6_Vub_vlsr_VubR(plane, 4);
+ const HVX_Vector lo = Q6_V_vand_VV(plane, mask_0f);
+ vq = Q6_V_vmux_QVV(first4, hi, Q6_V_vror_VR(vq, VLEN - 4));
+ vq = Q6_V_vmux_QVV(first4, lo, Q6_V_vror_VR(vq, VLEN - 4));
}
- const HVX_Vector lo = Q6_V_vand_VV(vq, Q6_Vb_vsplat_R(0x0F));
- const HVX_Vector hi = Q6_Vub_vlsr_VubR(vq, 4);
- vq = Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -1));
-
const HVX_Vector scales = hvx_vmem(tile + 512);
const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 4 * row));
const HVX_Vector scale = Q6_V_lo_W(hvx_vec_f16_to_f32(scale_hf));
@@ -566,26 +689,24 @@ static inline void hvx_dequantize_row_tiled_q4_k_f32(float * dst_spad, const uin
}
}
-static inline void hvx_dequantize_row_tiled_q5_k_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
- const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
- const HVX_Vector one = Q6_Vb_vsplat_R(1);
+static inline void hvx_dequantize_row_tiled_q5_k_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+ const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
+ const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
- const HVX_Vector p5 = hvx_dequantize_gather4(hvx_vmem(tile + 640), row);
+ const HVX_Vector p5 = Q6_V_vror_VR(hvx_vmem(tile + 640), 4 * row);
HVX_Vector vq = Q6_V_vzero();
- HVX_Vector vh = Q6_V_vzero();
- for (int group = 3; group >= 0; --group) {
- vq = Q6_V_vmux_QVV(first4, hvx_dequantize_gather4(hvx_vmem(tile + group * VLEN), row), Q6_V_vror_VR(vq, VLEN - 4));
- vh = Q6_V_vmux_QVV(first4, Q6_Vub_vlsr_VubR(p5, 2 * group), Q6_V_vror_VR(vh, VLEN - 4));
+ for (int i = 3; i >= 0; --i) {
+ const HVX_Vector plane = Q6_V_vror_VR(hvx_vmem(tile + i * VLEN), 4 * row);
+ const HVX_Vector hi = Q6_V_vandor_VQR(Q6_Vub_vlsr_VubR(plane, 4), Q6_Q_vand_VR(p5, 0x01010101u << (2 * i + 1)), 0x10101010);
+ const HVX_Vector lo = Q6_V_vandor_VQR(Q6_V_vand_VV(plane, mask_0f), Q6_Q_vand_VR(p5, 0x01010101u << (2 * i + 0)), 0x10101010);
+ vq = Q6_V_vmux_QVV(first4, hi, Q6_V_vror_VR(vq, VLEN - 4));
+ vq = Q6_V_vmux_QVV(first4, lo, Q6_V_vror_VR(vq, VLEN - 4));
}
- const HVX_Vector lo = Q6_V_vor_VV(Q6_V_vand_VV(vq, Q6_Vb_vsplat_R(0x0F)), Q6_Vw_vasl_VwR(Q6_V_vand_VV(vh, one), 4));
- const HVX_Vector hi = Q6_V_vor_VV(Q6_Vub_vlsr_VubR(vq, 4), Q6_Vw_vasl_VwR(Q6_V_vand_VV(Q6_Vub_vlsr_VubR(vh, 1), one), 4));
- vq = Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -1));
-
const HVX_Vector scales = hvx_vmem(tile + 512);
const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 4 * row));
const HVX_Vector scale = Q6_V_lo_W(hvx_vec_f16_to_f32(scale_hf));
@@ -599,7 +720,7 @@ static inline void hvx_dequantize_row_tiled_q5_k_f32(float * dst_spad, const uin
}
}
-static inline void hvx_dequantize_row_tiled_q6_k_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+static inline void hvx_dequantize_row_tiled_q6_k_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
const HVX_VectorPred first4 = Q6_Q_vsetq_R(4);
const HVX_VectorPred first16 = Q6_Q_vsetq_R(16 * sizeof(float));
const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F);
@@ -607,7 +728,7 @@ static inline void hvx_dequantize_row_tiled_q6_k_f32(float * dst_spad, const uin
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
HVX_Vector vq = Q6_V_vzero();
for (int group = 7; group >= 0; --group) {
@@ -641,27 +762,53 @@ static inline HVX_Vector hvx_dequantize_tiled_f16_gather4(const uint8_t * p, uin
return Q6_V_lo_W(Q6_W_vshuff_VVR(w23, w01, 8));
}
-static inline void hvx_dequantize_row_tiled_f16_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+static inline HVX_Vector hvx_gather_tiled_f16_row_k(const uint8_t * tile, uint32_t r_byte) {
+ HVX_Vector g0 = hvx_dequantize_tiled_f16_gather4(tile + 0 * VLEN, r_byte);
+ HVX_Vector g1 = hvx_dequantize_tiled_f16_gather4(tile + 4 * VLEN, r_byte);
+ HVX_Vector g01 = Q6_V_lo_W(Q6_W_vshuff_VVR(g1, g0, 16));
+ asm volatile("" : "+v"(g01));
+
+ HVX_Vector g2 = hvx_dequantize_tiled_f16_gather4(tile + 8 * VLEN, r_byte);
+ HVX_Vector g3 = hvx_dequantize_tiled_f16_gather4(tile + 12 * VLEN, r_byte);
+ HVX_Vector g23 = Q6_V_lo_W(Q6_W_vshuff_VVR(g3, g2, 16));
+
+ return Q6_V_lo_W(Q6_W_vshuff_VVR(g23, g01, 32));
+}
+
+static inline void hvx_dequantize_row_tiled_f16_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
const uint32_t r_byte = 4 * row;
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS;
- HVX_Vector g0 = hvx_dequantize_tiled_f16_gather4(tile + 0 * VLEN, r_byte);
- HVX_Vector g1 = hvx_dequantize_tiled_f16_gather4(tile + 4 * VLEN, r_byte);
- HVX_Vector g01 = Q6_V_lo_W(Q6_W_vshuff_VVR(g1, g0, 16));
+ HVX_Vector g = hvx_gather_tiled_f16_row_k(tile, r_byte);
+ *(HVX_Vector *) dst = Q6_V_lo_W(hvx_vec_f16_to_f32(g));
+ }
+}
- HVX_Vector g2 = hvx_dequantize_tiled_f16_gather4(tile + 8 * VLEN, r_byte);
- HVX_Vector g3 = hvx_dequantize_tiled_f16_gather4(tile + 12 * VLEN, r_byte);
- HVX_Vector g23 = Q6_V_lo_W(Q6_W_vshuff_VVR(g3, g2, 16));
+static inline void hvx_dequantize_row_tiled_f16_f16(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+ HVX_Vector * vdst = (HVX_Vector *) dst_spad;
+ const uint32_t r_byte = 4 * row;
+ const uint32_t n_pairs = n_k_tiles / 2;
+
+ for (uint32_t pair = 0; pair < n_pairs; ++pair) {
+ const uint8_t * tile0 = src_spad + (2 * pair + 0) * tile_stride;
+ const uint8_t * tile1 = src_spad + (2 * pair + 1) * tile_stride;
+ HVX_Vector g0 = hvx_gather_tiled_f16_row_k(tile0, r_byte);
+ asm volatile("" : "+v"(g0));
+ HVX_Vector g1 = hvx_gather_tiled_f16_row_k(tile1, r_byte);
+ vdst[pair] = Q6_V_lo_W(Q6_W_vshuff_VVR(g1, g0, 64));
+ }
- HVX_Vector g = Q6_V_lo_W(Q6_W_vshuff_VVR(g23, g01, 32));
- *(HVX_Vector *) dst = Q6_V_lo_W(hvx_vec_f16_to_f32(g));
+ if (n_k_tiles & 1) {
+ const uint8_t * tile = src_spad + (2 * n_pairs) * tile_stride;
+ HVX_Vector g = hvx_gather_tiled_f16_row_k(tile, r_byte);
+ hvx_vec_store_a(&vdst[n_pairs], HTP_TENSOR_TILE_N_COLS * sizeof(__fp16), g);
}
}
-static inline void hvx_dequantize_row_tiled_q1_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+static inline void hvx_dequantize_row_tiled_q1_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
static const uint32_t __attribute__((aligned(128))) bit_mask[32] = {
1u << 0, 1u << 8, 1u << 16, 1u << 24,
1u << 1, 1u << 9, 1u << 17, 1u << 25,
@@ -678,7 +825,7 @@ static inline void hvx_dequantize_row_tiled_q1_0_f32(float * dst_spad, const uin
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_K_Q1_0;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_K_Q1_0;
const HVX_Vector scales = hvx_vmem(tile + 512);
const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 2 * row));
@@ -694,13 +841,13 @@ static inline void hvx_dequantize_row_tiled_q1_0_f32(float * dst_spad, const uin
}
}
-static inline void hvx_dequantize_row_tiled_q2_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
+static inline void hvx_dequantize_row_tiled_q2_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) {
const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03);
const HVX_Vector v_one = Q6_Vb_vsplat_R(1);
for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) {
const uint8_t * tile = src_spad + k_tile * tile_stride;
- float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_K_Q2_0;
+ float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_K_Q2_0;
const HVX_Vector v_packed = hvx_dequantize_tiled_f16_gather4(tile, 4 * row);
const HVX_Vector p0 = Q6_V_vand_VV(v_packed, mask_03);
diff --git a/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h b/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h
index 3f253a0b0..c34583d7c 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h
@@ -52,6 +52,85 @@ static inline HVX_Vector hvx_vec_fast_sigmoid_f32_guard(HVX_Vector v,
return Q6_V_vmux_QVV(pred_min, out, Q6_V_vzero());
}
+static inline HVX_VectorPair hvx_vec_fast_sigmoid_f32_guard_pair(HVX_Vector x0,
+ HVX_Vector x1,
+ HVX_Vector one,
+ HVX_Vector max_exp,
+ HVX_Vector min_exp) {
+ const HVX_Vector c_log2f = Q6_V_vsplat_R(FAST_SIGMOID_LOG2F);
+ const HVX_Vector c1 = Q6_V_vsplat_R(FAST_SIGMOID_C1);
+ const HVX_Vector c2 = Q6_V_vsplat_R(FAST_SIGMOID_C2);
+ const HVX_Vector c3 = Q6_V_vsplat_R(FAST_SIGMOID_C3);
+ const HVX_Vector inv_aprox = Q6_V_vsplat_R(0x7EEEEBB3);
+ const HVX_Vector two_sf = hvx_vec_splat_f32(2.0f);
+ const HVX_Vector zero = Q6_V_vzero();
+
+ HVX_Vector v0 = Q6_Vqf32_vmpy_VsfVsf(x0, c_log2f);
+ HVX_Vector v1 = Q6_Vqf32_vmpy_VsfVsf(x1, c_log2f);
+ v0 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(v0), c3);
+ v1 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(v1), c3);
+
+ HVX_Vector in_int0 = hvx_vec_truncate_f32(Q6_Vsf_equals_Vqf32(v0));
+ HVX_Vector in_int1 = hvx_vec_truncate_f32(Q6_Vsf_equals_Vqf32(v1));
+ HVX_Vector f0 = Q6_Vqf32_vsub_Vqf32Vsf(v0, Q6_Vsf_equals_Vw(in_int0));
+ HVX_Vector f1 = Q6_Vqf32_vsub_Vqf32Vsf(v1, Q6_Vsf_equals_Vw(in_int1));
+ HVX_Vector ff0 = Q6_Vqf32_vmpy_Vqf32Vqf32(f0, f0);
+ HVX_Vector ff1 = Q6_Vqf32_vmpy_Vqf32Vqf32(f1, f1);
+
+ HVX_Vector p1_0 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(ff0), c2);
+ HVX_Vector p1_1 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(ff1), c2);
+ p1_0 = Q6_Vqf32_vadd_Vqf32Vsf(p1_0, c_log2f);
+ p1_1 = Q6_Vqf32_vadd_Vqf32Vsf(p1_1, c_log2f);
+
+ HVX_Vector p2_0 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(f0), c1);
+ HVX_Vector p2_1 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(f1), c1);
+ p2_0 = Q6_Vqf32_vmpy_Vqf32Vqf32(p2_0, ff0);
+ p2_1 = Q6_Vqf32_vmpy_Vqf32Vqf32(p2_1, ff1);
+ p2_0 = Q6_Vqf32_vadd_Vqf32Vqf32(p2_0, f0);
+ p2_1 = Q6_Vqf32_vadd_Vqf32Vqf32(p2_1, f1);
+
+ HVX_Vector v3_0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(p2_0, p1_0));
+ HVX_Vector v3_1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(p2_1, p1_1));
+ v3_0 = Q6_Vw_vaslacc_VwVwR(v3_0, in_int0, 24);
+ v3_1 = Q6_Vw_vaslacc_VwVwR(v3_1, in_int1, 24);
+
+ HVX_Vector v4_0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_Vqf32Vqf32(p2_0, p1_0));
+ HVX_Vector v4_1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_Vqf32Vqf32(p2_1, p1_1));
+ HVX_Vector v5_0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(v3_0, v4_0));
+ HVX_Vector v5_1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(v3_1, v4_1));
+
+ HVX_Vector i0 = Q6_Vw_vsub_VwVw(inv_aprox, v5_0);
+ HVX_Vector i1 = Q6_Vw_vsub_VwVw(inv_aprox, v5_1);
+
+ HVX_Vector r0 = Q6_Vqf32_vmpy_VsfVsf(
+ i0, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(i0, v5_0)))));
+ HVX_Vector r1 = Q6_Vqf32_vmpy_VsfVsf(
+ i1, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(i1, v5_1)))));
+
+ r0 = Q6_Vqf32_vmpy_Vqf32Vqf32(
+ r0, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r0), v5_0))));
+ r1 = Q6_Vqf32_vmpy_Vqf32Vqf32(
+ r1, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r1), v5_1))));
+
+ r0 = Q6_Vqf32_vmpy_Vqf32Vqf32(
+ r0, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r0), v5_0))));
+ r1 = Q6_Vqf32_vmpy_Vqf32Vqf32(
+ r1, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r1), v5_1))));
+
+ HVX_Vector out0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v3_0, Q6_Vsf_equals_Vqf32(r0)));
+ HVX_Vector out1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v3_1, Q6_Vsf_equals_Vqf32(r1)));
+
+ const HVX_VectorPred pmax0 = Q6_Q_vcmp_gt_VsfVsf(max_exp, x0);
+ const HVX_VectorPred pmin0 = Q6_Q_vcmp_gt_VsfVsf(x0, min_exp);
+ const HVX_VectorPred pmax1 = Q6_Q_vcmp_gt_VsfVsf(max_exp, x1);
+ const HVX_VectorPred pmin1 = Q6_Q_vcmp_gt_VsfVsf(x1, min_exp);
+
+ out0 = Q6_V_vmux_QVV(pmin0, Q6_V_vmux_QVV(pmax0, out0, one), zero);
+ out1 = Q6_V_vmux_QVV(pmin1, Q6_V_vmux_QVV(pmax1, out1, one), zero);
+
+ return Q6_W_vcombine_VV(out1, out0);
+}
+
static inline HVX_Vector hvx_vec_fast_sigmoid_f32_2it(HVX_Vector v) {
v = Q6_Vqf32_vmpy_VsfVsf(v, Q6_V_vsplat_R(FAST_SIGMOID_LOG2F));
v = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(v), Q6_V_vsplat_R(FAST_SIGMOID_C3));
@@ -115,11 +194,15 @@ static inline HVX_Vector hvx_vec_tanh_f32(HVX_Vector x) {
return Q6_Vsf_equals_Vqf32(res);
}
-static inline HVX_Vector hvx_vec_silu_f32(HVX_Vector x) {
+static inline HVX_Vector hvx_vec_sigmoid_f32(HVX_Vector x) {
HVX_Vector one = hvx_vec_splat_f32(1.0f);
HVX_Vector max_exp = hvx_vec_splat_f32(87.f);
HVX_Vector min_exp = hvx_vec_splat_f32(-87.f);
- HVX_Vector sig = hvx_vec_fast_sigmoid_f32_guard(x, one, max_exp, min_exp);
+ return hvx_vec_fast_sigmoid_f32_guard(x, one, max_exp, min_exp);
+}
+
+static inline HVX_Vector hvx_vec_silu_f32(HVX_Vector x) {
+ HVX_Vector sig = hvx_vec_sigmoid_f32(x);
return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x, sig));
}
@@ -195,33 +278,185 @@ static inline void hvx_tanh_f32_aa(uint8_t * restrict dst, const uint8_t * restr
hvx_tanh_loop_body(HVX_Vector, HVX_Vector, hvx_vec_store_a);
}
+#if __HVX_ARCH__ >= 81
+// Centered degree-4 minimax polynomial for 1 / (1 + e) in t = e - 0.5 on [-0.5, 0.5]
+#define HVX_SIGMOID_RECIP_C0 (0x3956)
+#define HVX_SIGMOID_RECIP_C1 (0xB711)
+#define HVX_SIGMOID_RECIP_C2 (0x34AF)
+#define HVX_SIGMOID_RECIP_C3 (0xB365)
+#define HVX_SIGMOID_RECIP_C4 (0x3113)
+
+static inline HVX_Vector hvx_vec_fast_sigmoid_f16(HVX_Vector x_v) {
+ const HVX_Vector a = Q6_V_vand_VV(x_v, Q6_Vh_vsplat_R(0x7FFF));
+ const HVX_Vector z = Q6_Vuh_vmin_VuhVuh(a, Q6_Vh_vsplat_R(0x4C50)); // min(|x|, 17.25) so e underflows to exact 0 in fp16
+ const HVX_Vector y = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(z, Q6_Vh_vsplat_R(0x65C5)));
+ const HVX_Vector t = Q6_Vh_equals_Vhf_rnd(y);
+ const HVX_Vector rho = Q6_V_vand_VV(t, Q6_Vh_vsplat_R(0x03FF));
+ const HVX_Vector r15 = Q6_Vh_vasl_VhR(rho, 5);
+ HVX_Vector rp = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15, HVX_EXP2_FIXED_G2_PAIR), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G1));
+ rp = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp, r15), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G0));
+ const HVX_Vector b = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(0x6400), t), Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp, rho));
+ const HVX_Vector e = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(b, Q6_Vh_vsplat_R(0x1400)));
+ const HVX_Vector tc = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_VhfVhf(e, Q6_Vh_vsplat_R(0xB800)));
+
+ HVX_Vector p = Q6_Vqf16_vmpy_VhfVhf(tc, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C4));
+ p = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C3));
+ p = Q6_Vqf16_vmpy_Vqf16Vhf(p, tc);
+ p = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C2));
+ p = Q6_Vqf16_vmpy_Vqf16Vhf(p, tc);
+ p = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C1));
+ p = Q6_Vqf16_vmpy_Vqf16Vhf(p, tc);
+ const HVX_Vector r_q = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C0));
+
+ const HVX_Vector r = Q6_Vhf_equals_Vqf16(r_q);
+ const HVX_Vector er = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_Vqf16Vhf(r_q, e));
+ const HVX_VectorPred is_neg = Q6_Q_vcmp_gt_VhVh(Q6_V_vzero(), x_v);
+ return Q6_V_vmux_QVV(is_neg, er, r);
+}
+
+static inline HVX_VectorPair hvx_vec_fast_sigmoid_f16_pair(HVX_Vector x0, HVX_Vector x1) {
+ const HVX_Vector em_mask = Q6_Vh_vsplat_R(0x7FFF);
+ const HVX_Vector v_clamp = Q6_Vh_vsplat_R(0x4C50); // min(|x|, 17.25) so e underflows to exact 0 in fp16
+ const HVX_Vector v_scale = Q6_Vh_vsplat_R(0x65C5);
+ const HVX_Vector v_frac = Q6_Vh_vsplat_R(0x03FF);
+ const HVX_Vector v_g1 = Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G1);
+ const HVX_Vector v_g0 = Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G0);
+ const HVX_Vector v_base = Q6_Vh_vsplat_R(0x6400);
+ const HVX_Vector v_last = Q6_Vh_vsplat_R(0x1400);
+ const HVX_Vector v_nhalf = Q6_Vh_vsplat_R(0xB800);
+
+ const HVX_Vector z0 = Q6_Vuh_vmin_VuhVuh(Q6_V_vand_VV(x0, em_mask), v_clamp);
+ const HVX_Vector z1 = Q6_Vuh_vmin_VuhVuh(Q6_V_vand_VV(x1, em_mask), v_clamp);
+ const HVX_Vector y0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(z0, v_scale));
+ const HVX_Vector y1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(z1, v_scale));
+ const HVX_Vector t0 = Q6_Vh_equals_Vhf_rnd(y0);
+ const HVX_Vector t1 = Q6_Vh_equals_Vhf_rnd(y1);
+ const HVX_Vector rho0 = Q6_V_vand_VV(t0, v_frac);
+ const HVX_Vector rho1 = Q6_V_vand_VV(t1, v_frac);
+ const HVX_Vector r15_0 = Q6_Vh_vasl_VhR(rho0, 5);
+ const HVX_Vector r15_1 = Q6_Vh_vasl_VhR(rho1, 5);
+
+ HVX_Vector rp0 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15_0, HVX_EXP2_FIXED_G2_PAIR), v_g1);
+ HVX_Vector rp1 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15_1, HVX_EXP2_FIXED_G2_PAIR), v_g1);
+ rp0 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp0, r15_0), v_g0);
+ rp1 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp1, r15_1), v_g0);
+
+ const HVX_Vector b0 = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(v_base, t0), Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp0, rho0));
+ const HVX_Vector b1 = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(v_base, t1), Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp1, rho1));
+ const HVX_Vector e0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(b0, v_last));
+ const HVX_Vector e1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(b1, v_last));
+ const HVX_Vector tc0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_VhfVhf(e0, v_nhalf));
+ const HVX_Vector tc1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_VhfVhf(e1, v_nhalf));
+
+ const HVX_Vector c4 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C4);
+ const HVX_Vector c3 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C3);
+ const HVX_Vector c2 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C2);
+ const HVX_Vector c1 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C1);
+ const HVX_Vector c0 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C0);
+
+ HVX_Vector p0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(tc0, c4), c3);
+ HVX_Vector p1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(tc1, c4), c3);
+ p0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p0, tc0), c2);
+ p1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p1, tc1), c2);
+ p0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p0, tc0), c1);
+ p1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p1, tc1), c1);
+ const HVX_Vector rq0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p0, tc0), c0);
+ const HVX_Vector rq1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p1, tc1), c0);
+
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_Vector r0 = Q6_Vhf_equals_Vqf16(rq0);
+ const HVX_Vector r1 = Q6_Vhf_equals_Vqf16(rq1);
+ const HVX_Vector er0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_Vqf16Vhf(rq0, e0));
+ const HVX_Vector er1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_Vqf16Vhf(rq1, e1));
+ const HVX_Vector out0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VhVh(zero, x0), er0, r0);
+ const HVX_Vector out1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VhVh(zero, x1), er1, r1);
+ return Q6_W_vcombine_VV(out1, out0);
+}
+#else
+// Clamping u >= -14.0f keeps 2^u in normal fp16 range while 1.0f + 2^-14 == 1.0f in fp16
static inline HVX_Vector hvx_vec_fast_sigmoid_f16(HVX_Vector x_v) {
const HVX_Vector v_one = hvx_vec_splat_f16(1.0f);
const HVX_Vector v_neg_log2e = hvx_vec_splat_f16(-EXP_LOG2E_F);
const HVX_Vector em_mask = Q6_Vh_vsplat_R(0x7FFF);
+ const HVX_Vector half_hf_v = Q6_Vh_vsplat_R(0x3800);
+ const HVX_Vector v_clamp_min = hvx_vec_splat_f16(-14.0f);
- // Compute absolute value of x_v
- HVX_Vector abs_x = Q6_V_vand_VV(x_v, em_mask);
-
- // Compute u = -abs_x * log2(e) <= 0.
- HVX_Vector u = hvx_vec_mul_f16_f16(abs_x, v_neg_log2e);
-
- // Clamp input to prevent underflow in exp2
- const HVX_Vector v_clamp_min = hvx_vec_splat_f16(-24.0f);
- u = Q6_Vhf_vmax_VhfVhf(v_clamp_min, u);
-
- HVX_Vector exp_val = hvx_vec_exp2_f16(u);
- HVX_Vector denom = hvx_vec_add_f16_f16(v_one, exp_val);
- HVX_Vector sig_abs = hvx_vec_inverse_f16(denom);
-
- // check if x_v < 0 (using integer comparison on absolute value)
+ HVX_Vector abs_x = Q6_V_vand_VV(x_v, em_mask);
HVX_VectorPred is_neg = Q6_Q_vcmp_gt_VhVh(abs_x, x_v);
-
- // If x_v < 0, return 1.0f - sig_abs
+ HVX_Vector u = hvx_vec_mul_f16_f16(abs_x, v_neg_log2e);
+ u = Q6_Vhf_vmax_VhfVhf(v_clamp_min, u);
+
+ HVX_Vector x_minus_half = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(u, half_hf_v));
+ HVX_Vector k_v = Q6_Vh_equals_Vhf(x_minus_half);
+ HVX_Vector f_v = Q6_Vhf_equals_Vh(k_v);
+ HVX_Vector x_qf16 = Q6_Vqf16_vsub_VhfVhf(u, f_v);
+
+ // Degree-4 polynomial for 2^f on [-0.5, 0.5] (max error < 4.2e-5, well below fp16 0.5 ULP)
+ HVX_Vector y = Q6_Vqf16_vmpy_Vqf16Vqf16(Q6_Vqf16_vadd_VhfVhf(Q6_Vh_vsplat_R(0x20ed), Q6_V_vzero()), x_qf16);
+ y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x2b1b));
+ y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16);
+ y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x33b0));
+ y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16);
+ y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x398c));
+ y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16);
+ y = Q6_Vqf16_vadd_Vqf16Vhf(y, v_one);
+
+ HVX_Vector exp_val = Q6_Vh_vaslacc_VhVhR(Q6_Vhf_equals_Vqf16(y), k_v, 10);
+ HVX_Vector denom = hvx_vec_add_f16_f16(v_one, exp_val);
+ HVX_Vector sig_abs = hvx_vec_inverse_pos_f16(denom);
HVX_Vector sig_neg = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_one, sig_abs));
return Q6_V_vmux_QVV(is_neg, sig_neg, sig_abs);
}
+static inline HVX_VectorPair hvx_vec_fast_sigmoid_f16_pair(HVX_Vector x0, HVX_Vector x1) {
+ const HVX_Vector v_one = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector v_neg_log2e = hvx_vec_splat_f16(-EXP_LOG2E_F);
+ const HVX_Vector em_mask = Q6_Vh_vsplat_R(0x7FFF);
+ const HVX_Vector half_hf_v = Q6_Vh_vsplat_R(0x3800);
+ const HVX_Vector v_clamp_min = hvx_vec_splat_f16(-14.0f);
+
+ const HVX_Vector abs0 = Q6_V_vand_VV(x0, em_mask);
+ const HVX_Vector abs1 = Q6_V_vand_VV(x1, em_mask);
+ const HVX_VectorPred is_neg0 = Q6_Q_vcmp_gt_VhVh(abs0, x0);
+ const HVX_VectorPred is_neg1 = Q6_Q_vcmp_gt_VhVh(abs1, x1);
+
+ HVX_Vector u0 = Q6_Vhf_vmax_VhfVhf(v_clamp_min, hvx_vec_mul_f16_f16(abs0, v_neg_log2e));
+ HVX_Vector u1 = Q6_Vhf_vmax_VhfVhf(v_clamp_min, hvx_vec_mul_f16_f16(abs1, v_neg_log2e));
+
+ HVX_Vector k0 = Q6_Vh_equals_Vhf(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(u0, half_hf_v)));
+ HVX_Vector k1 = Q6_Vh_equals_Vhf(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(u1, half_hf_v)));
+ HVX_Vector q0 = Q6_Vqf16_vsub_VhfVhf(u0, Q6_Vhf_equals_Vh(k0));
+ HVX_Vector q1 = Q6_Vqf16_vsub_VhfVhf(u1, Q6_Vhf_equals_Vh(k1));
+
+ // Degree-4 polynomial for 2^f on [-0.5, 0.5] (max error < 4.2e-5, well below fp16 0.5 ULP)
+ const HVX_Vector c3 = Q6_Vqf16_vadd_VhfVhf(Q6_Vh_vsplat_R(0x20ed), Q6_V_vzero());
+ const HVX_Vector c2 = Q6_Vh_vsplat_R(0x2b1b);
+ const HVX_Vector c1 = Q6_Vh_vsplat_R(0x33b0);
+ const HVX_Vector c0 = Q6_Vh_vsplat_R(0x398c);
+
+ HVX_Vector y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(c3, q0), c2);
+ HVX_Vector y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(c3, q1), c2);
+ y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y0, q0), c1);
+ y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y1, q1), c1);
+ y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y0, q0), c0);
+ y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y1, q1), c0);
+ y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y0, q0), v_one);
+ y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y1, q1), v_one);
+
+ HVX_Vector e0 = Q6_Vh_vaslacc_VhVhR(Q6_Vhf_equals_Vqf16(y0), k0, 10);
+ HVX_Vector e1 = Q6_Vh_vaslacc_VhVhR(Q6_Vhf_equals_Vqf16(y1), k1, 10);
+ HVX_Vector d0 = hvx_vec_add_f16_f16(v_one, e0);
+ HVX_Vector d1 = hvx_vec_add_f16_f16(v_one, e1);
+ HVX_Vector sa0 = hvx_vec_inverse_pos_f16(d0);
+ HVX_Vector sa1 = hvx_vec_inverse_pos_f16(d1);
+ HVX_Vector sn0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_one, sa0));
+ HVX_Vector sn1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_one, sa1));
+ HVX_Vector out0 = Q6_V_vmux_QVV(is_neg0, sn0, sa0);
+ HVX_Vector out1 = Q6_V_vmux_QVV(is_neg1, sn1, sa1);
+ return Q6_W_vcombine_VV(out1, out0);
+}
+#endif
+
static inline HVX_Vector hvx_vec_tanh_f16(HVX_Vector x) {
// tanh(x) = 2 * sigmoid(2x) - 1
const HVX_Vector v_two = hvx_vec_splat_f16(2.0f);
diff --git a/ggml/src/ggml-hexagon/htp/im2col-ops.c b/ggml/src/ggml-hexagon/htp/im2col-ops.c
index 602ee1598..8bba8dede 100644
--- a/ggml/src/ggml-hexagon/htp/im2col-ops.c
+++ b/ggml/src/ggml-hexagon/htp/im2col-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <hexagon_protos.h>
#include <hexagon_types.h>
@@ -935,7 +931,7 @@ int op_im2col(struct htp_ops_context * octx) {
uint32_t nrows = kparams->total_rows;
if (octx->ctx->mdev.count > 1) {
const struct htp_tensor_mdev_range range =
- htp_tensor_mdev_partition(kparams->total_rows, htp_tensor_mdev_data_aligned(dst) ? kparams->rows_per_chunk : 0,
+ htp_tensor_mdev_partition(kparams->total_rows, 1,
octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_base = range.start;
nrows = range.count;
@@ -1039,7 +1035,7 @@ int op_im2col_3d(struct htp_ops_context * octx) {
uint32_t nrows = kparams->total_rows;
if (octx->ctx->mdev.count > 1) {
const struct htp_tensor_mdev_range range =
- htp_tensor_mdev_partition(kparams->total_rows, htp_tensor_mdev_data_aligned(dst) ? kparams->rows_per_chunk : 0,
+ htp_tensor_mdev_partition(kparams->total_rows, 1,
octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_base = range.start;
nrows = range.count;
diff --git a/ggml/src/ggml-hexagon/htp/im2col-ops.h b/ggml/src/ggml-hexagon/htp/im2col-ops.h
index 23497d01d..d845f6cf1 100644
--- a/ggml/src/ggml-hexagon/htp/im2col-ops.h
+++ b/ggml/src/ggml-hexagon/htp/im2col-ops.h
@@ -65,7 +65,6 @@ struct htp_im2col_kernel_params {
uint32_t OD, OH, OW;
uint32_t patch_stride;
uint32_t total_rows;
- uint32_t rows_per_chunk;
struct fastdiv_values div_OH;
struct fastdiv_values div_OD;
diff --git a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c
index 5d60c506e..1d3f85e61 100644
--- a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c
+++ b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <string.h>
@@ -25,12 +21,26 @@
#include "lightning-indexer-ops.h"
+struct htp_lid_context;
+
+typedef void (*lid_prep_q_fn_t)(HVX_Vector * restrict q_sp, const uint8_t * restrict qs, uint8_t * restrict qh,
+ size_t qs_row_size, uint32_t D, uint32_t n_rows);
+typedef void (*lid_prep_w_fn_t)(HVX_Vector * restrict w_dst, const uint8_t * restrict ws, uint32_t ha, uint32_t hb);
+typedef void (*lid_prep_k_fn_t)(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf,
+ HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr);
+
struct htp_lid_context {
const struct htp_ops_context * octx;
const struct htp_lid_kernel_params * kp;
uint32_t n_blocks;
uint32_t blocks_per_hvx;
+ uint32_t q_row_bytes;
+ uint32_t w_row_bytes;
+
+ lid_prep_q_fn_t prep_q;
+ lid_prep_w_fn_t prep_w;
+ lid_prep_k_fn_t prep_k;
// current stream and token tile
uint32_t is;
@@ -62,12 +72,53 @@ static inline void lid_prep_step_info(uint32_t k, uint32_t K, uint32_t t_first,
static inline void lid_prep_push_step(dma_queue * dma_q, const struct htp_lid_context * lctx,
const struct htp_tensor * q, const struct htp_tensor * w,
uint8_t * qs, uint8_t * ws, uint32_t qs_row_size, uint32_t w_row_size,
- uint32_t D, uint32_t n_head, uint32_t t, uint32_t ha, uint32_t hb) {
+ uint32_t t, uint32_t ha, uint32_t hb) {
const uint32_t it = lctx->t0 + t;
dma_queue_push(dma_q, dma_make_data(qs, q->data + it * q->nb[2] + lctx->is * q->nb[3] + ha * q->nb[1]),
- qs_row_size, q->nb[1], D * sizeof(float), hb - ha);
+ qs_row_size, q->nb[1], lctx->q_row_bytes, hb - ha);
dma_queue_push(dma_q, dma_make_data(ws, w->data + it * w->nb[1] + lctx->is * w->nb[3]),
- w_row_size, w_row_size, n_head * sizeof(float), 1);
+ w_row_size, w_row_size, lctx->w_row_bytes, 1);
+}
+
+static inline void lid_splat_q_row(HVX_Vector * restrict q_sp, const HVX_Vector * restrict qv, uint32_t D) {
+ for (uint32_t d0 = 0; d0 < D; d0 += VLEN_FP16) {
+ const HVX_Vector v = qv[d0 / VLEN_FP16];
+ const uint32_t nd = MIN(VLEN_FP16, D - d0);
+ for (uint32_t j = 0; j < nd; ++j) {
+ *q_sp++ = hvx_vec_repl_f16(Q6_V_vror_VR(v, j * SIZEOF_FP16));
+ }
+ }
+}
+
+static void lid_prep_q_f32(HVX_Vector * restrict q_sp, const uint8_t * restrict qs, uint8_t * restrict qh,
+ size_t qs_row_size, uint32_t D, uint32_t n_rows) {
+ for (uint32_t r = 0; r < n_rows; ++r, q_sp += D) {
+ hvx_copy_f16_f32_aa(qh, qs + r * qs_row_size, D);
+ lid_splat_q_row(q_sp, (const HVX_Vector *) qh, D);
+ }
+}
+
+static void lid_prep_q_f16(HVX_Vector * restrict q_sp, const uint8_t * restrict qs, uint8_t * restrict qh,
+ size_t qs_row_size, uint32_t D, uint32_t n_rows) {
+ (void) qh;
+ for (uint32_t r = 0; r < n_rows; ++r, q_sp += D) {
+ lid_splat_q_row(q_sp, (const HVX_Vector *) (qs + r * qs_row_size), D);
+ }
+}
+
+static void lid_prep_w_f32(HVX_Vector * restrict w_dst, const uint8_t * restrict ws, uint32_t ha, uint32_t hb) {
+ const HVX_Vector * restrict wv = (const HVX_Vector *) ws;
+ for (uint32_t h = ha; h < hb; ++h) {
+ w_dst[h] = hvx_vec_repl4(Q6_V_vror_VR(wv[h / VLEN_FP32], (h % VLEN_FP32) * SIZEOF_FP32));
+ }
+}
+
+static void lid_prep_w_f16(HVX_Vector * restrict w_dst, const uint8_t * restrict ws, uint32_t ha, uint32_t hb) {
+ const HVX_Vector * restrict wv = (const HVX_Vector *) ws;
+ for (uint32_t h = ha; h < hb; ++h) {
+ const HVX_Vector vh = hvx_vec_repl_f16(Q6_V_vror_VR(wv[h / VLEN_FP16], (h % VLEN_FP16) * SIZEOF_FP16));
+ w_dst[h] = Q6_V_lo_W(hvx_vec_f16_to_f32_shuff(vh));
+ }
}
// Splat every Q element (f16) and every head weight (f32) into a full vector.
@@ -115,11 +166,11 @@ static void lid_prep_thread(const htp_thread_t * th, unsigned int nth, unsigned
// Prologue: prime both slots
uint32_t t, ha, hb;
lid_prep_step_info(0, n_steps, t_first, i0, i1, n_head, &t, &ha, &hb);
- lid_prep_push_step(dma_q, lctx, q, w, qs[0], ws[0], L->size_qs_row, w_row_size, D, n_head, t, ha, hb);
+ lid_prep_push_step(dma_q, lctx, q, w, qs[0], ws[0], L->size_qs_row, w_row_size, t, ha, hb);
if (n_steps > 1) {
lid_prep_step_info(1, n_steps, t_first, i0, i1, n_head, &t, &ha, &hb);
- lid_prep_push_step(dma_q, lctx, q, w, qs[1], ws[1], L->size_qs_row, w_row_size, D, n_head, t, ha, hb);
+ lid_prep_push_step(dma_q, lctx, q, w, qs[1], ws[1], L->size_qs_row, w_row_size, t, ha, hb);
}
// Loop: pop(slot) -> compute(slot) -> push(slot, k + 2)
@@ -134,32 +185,15 @@ static void lid_prep_thread(const htp_thread_t * th, unsigned int nth, unsigned
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) it);
- HVX_Vector * restrict q_sp = (HVX_Vector *) lctx->spad_q + (t * n_head + ha) * D;
- for (uint32_t h = ha; h < hb; ++h) {
- hvx_copy_f16_f32_aa(qh, qs[slot] + (h - ha) * L->size_qs_row, D);
-
- const HVX_Vector * restrict qv = (const HVX_Vector *) qh;
- for (uint32_t d0 = 0; d0 < D; d0 += VLEN_FP16) {
- const HVX_Vector v = qv[d0 / VLEN_FP16];
- const uint32_t nd = MIN(VLEN_FP16, D - d0);
- for (uint32_t j = 0; j < nd; ++j) {
- *q_sp++ = hvx_vec_repl_f16(Q6_V_vror_VR(v, j * SIZEOF_FP16));
- }
- }
- }
-
- const HVX_Vector * restrict wv = (const HVX_Vector *) ws[slot];
- HVX_Vector * restrict w_dst = (HVX_Vector *) (lctx->spad_w + t * n_head * VLEN);
- for (uint32_t h = ha; h < hb; ++h) {
- w_dst[h] = hvx_vec_repl4(Q6_V_vror_VR(wv[h / VLEN_FP32], (h % VLEN_FP32) * SIZEOF_FP32));
- }
+ lctx->prep_q((HVX_Vector *) lctx->spad_q + (t * n_head + ha) * D, qs[slot], qh, L->size_qs_row, D, hb - ha);
+ lctx->prep_w((HVX_Vector *) (lctx->spad_w + t * n_head * VLEN), ws[slot], ha, hb);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) it);
if (k + 2 < n_steps) {
uint32_t next_t, next_ha, next_hb;
lid_prep_step_info(k + 2, n_steps, t_first, i0, i1, n_head, &next_t, &next_ha, &next_hb);
- lid_prep_push_step(dma_q, lctx, q, w, qs[slot], ws[slot], L->size_qs_row, w_row_size, D, n_head, next_t, next_ha, next_hb);
+ lid_prep_push_step(dma_q, lctx, q, w, qs[slot], ws[slot], L->size_qs_row, w_row_size, next_t, next_ha, next_hb);
}
}
}
@@ -170,37 +204,6 @@ static void lid_prep_thread(const htp_thread_t * th, unsigned int nth, unsigned
#define LID_MUL_F16(a, b) Q6_Vhf_vmpy_VhfVhf(a, b)
#endif
-// Q8_0 row to f16 in place, 4 blocks (128 values) per step.
-// Go backwards: the f16 output of a group is wider than its input and covers the input of the next group.
-static inline void lid_dequant_row_q8_0(uint8_t * restrict row, uint32_t D) {
- const int32_t nb = D / QK8_0;
-
- const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
- const HVX_VectorPred q64 = Q6_Q_vsetq_R(64);
- const HVX_VectorPred q96 = Q6_Q_vsetq_R(96);
-
- for (int32_t g = (nb - 1) / 4; g >= 0; --g) {
- const uint8_t * src = row + g * 4 * sizeof(block_q8_0);
- const HVX_Vector v0 = *(const HVX_UVector *) src;
- const HVX_Vector v1 = *(const HVX_UVector *) (src + VLEN);
-
- HVX_Vector qs = Q6_V_vmux_QVV(q96, Q6_V_valign_VVR(v1, v0, 6), Q6_V_valign_VVR(v1, v0, 8));
- qs = Q6_V_vmux_QVV(q64, Q6_V_valign_VVR(v1, v0, 4), qs);
- qs = Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(v1, v0, 2), qs);
-
- const HVX_Vector s01 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(v0), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 34)));
- const HVX_Vector s23 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 68)), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 102)));
-
- const HVX_VectorPair qh = Q6_Wh_vunpack_Vb(qs);
-
- HVX_Vector * dst = (HVX_Vector *) (row + g * 2 * VLEN);
- dst[0] = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(qh)), s01));
- if (g * 4 + 2 < nb) {
- dst[1] = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(qh)), s23));
- }
- }
-}
-
// Q4_0 blocks i, i + 1 (v loaded at block i) to signed quants: block i in bytes 0..31, block i + 1 in bytes 32..63.
// qs[j] holds value j (low nibble) and j + 16 (high nibble). lo16 selects bytes 0..15 and 32..47.
static inline HVX_Vector lid_q4_0_pair_quants(HVX_Vector v, HVX_VectorPred q32, HVX_VectorPred lo16) {
@@ -237,7 +240,8 @@ static __attribute__((noinline)) void lid_dequant_block(uint8_t * restrict k_buf
}
} else {
for (uint32_t r = 0; r < nkv; ++r) {
- lid_dequant_row_q8_0(k_buf + r * row_stride, D);
+ __fp16 * row = (__fp16 *) (k_buf + r * row_stride);
+ hvx_dequantize_row_flat_q8_0_f16(row, row, D);
}
}
}
@@ -446,46 +450,30 @@ static inline void lid_compute_row2(float * restrict o0,
HVX_VectorPair out1 = Q6_W_vzero();
uint32_t h = 0;
- for (; h + 4 <= n_head; h += 4) {
+ for (; h + 2 <= n_head; h += 2) {
const HVX_Vector * restrict q0 = q_t + h * D;
const HVX_Vector * restrict q1 = q0 + D;
- const HVX_Vector * restrict q2 = q1 + D;
- const HVX_Vector * restrict q3 = q2 + D;
HVX_VectorPair a0 = Q6_W_vzero();
HVX_VectorPair a1 = Q6_W_vzero();
- HVX_VectorPair a2 = Q6_W_vzero();
- HVX_VectorPair a3 = Q6_W_vzero();
HVX_VectorPair b0 = Q6_W_vzero();
HVX_VectorPair b1 = Q6_W_vzero();
- HVX_VectorPair b2 = Q6_W_vzero();
- HVX_VectorPair b3 = Q6_W_vzero();
for (uint32_t d = 0; d < D; ++d) {
const HVX_Vector k0 = kt0[d];
const HVX_Vector k1 = kt1[d];
const HVX_Vector v0 = q0[d];
const HVX_Vector v1 = q1[d];
- const HVX_Vector v2 = q2[d];
- const HVX_Vector v3 = q3[d];
a0 = lid_mpyacc(a0, k0, v0);
b0 = lid_mpyacc(b0, k1, v0);
a1 = lid_mpyacc(a1, k0, v1);
b1 = lid_mpyacc(b1, k1, v1);
- a2 = lid_mpyacc(a2, k0, v2);
- b2 = lid_mpyacc(b2, k1, v2);
- a3 = lid_mpyacc(a3, k0, v3);
- b3 = lid_mpyacc(b3, k1, v3);
}
out0 = lid_head_acc(out0, a0, w_t[h + 0]);
out0 = lid_head_acc(out0, a1, w_t[h + 1]);
- out0 = lid_head_acc(out0, a2, w_t[h + 2]);
- out0 = lid_head_acc(out0, a3, w_t[h + 3]);
out1 = lid_head_acc(out1, b0, w_t[h + 0]);
out1 = lid_head_acc(out1, b1, w_t[h + 1]);
- out1 = lid_head_acc(out1, b2, w_t[h + 2]);
- out1 = lid_head_acc(out1, b3, w_t[h + 3]);
}
for (; h < n_head; ++h) {
const HVX_Vector * restrict q0 = q_t + h * D;
@@ -505,6 +493,105 @@ static inline void lid_compute_row2(float * restrict o0,
lid_store_row(o1, out1, m1);
}
+static __attribute__((noinline)) void lid_prep_k_block_f16(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf,
+ HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) {
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const size_t stride = lctx->L.size_k_raw_row;
+ HVX_Vector * const kt_t1 = kt_t0 + HTP_LID_KV_BLOCK;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b);
+ for (uint32_t d0 = 0; d0 < D; d0 += HTP_LID_KV_BLOCK) {
+ lid_transpose_64x64_f16(kt + d0, k_buf + d0 * sizeof(__fp16), stride, nkv, kt_t0, kt_t1);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b);
+}
+
+static __attribute__((noinline)) void lid_prep_k_block_f32(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf,
+ HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) {
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const size_t stride = lctx->L.size_k_raw_row;
+ HVX_Vector * const kt_t1 = kt_t0 + HTP_LID_KV_BLOCK;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b);
+ for (uint32_t r = 0; r < nkv; ++r) {
+ lid_convert_row_f32_to_f16(k_buf + r * stride, D);
+ }
+ for (uint32_t d0 = 0; d0 < D; d0 += HTP_LID_KV_BLOCK) {
+ lid_transpose_64x64_f16(kt + d0, k_buf + d0 * sizeof(__fp16), stride, nkv, kt_t0, kt_t1);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b);
+}
+
+static __attribute__((noinline)) void lid_prep_k_block_q8_0_gather(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf,
+ HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) {
+ (void) nkv;
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const size_t stride = lctx->L.size_k_raw_row;
+ HVX_Vector * const sc = kt_t0 + 2 * HTP_LID_KV_BLOCK;
+ const HVX_Vector g_offs = hvx_vec_gather_offsets_h(stride);
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b);
+ lid_transpose_q8_0_gather(kt, kt_t0, sc, k_buf, stride, g_offs, D);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b);
+}
+
+static __attribute__((noinline)) void lid_prep_k_block_q8_0(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf,
+ HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) {
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const size_t stride = lctx->L.size_k_raw_row;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b);
+ lid_dequant_block(k_buf, stride, nkv, D, false);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b);
+
+ lid_prep_k_block_f16(lctx, kt, k_buf, kt_t0, nkv, b, tr);
+}
+
+static __attribute__((noinline)) void lid_prep_k_block_q4_0(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf,
+ HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) {
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const size_t stride = lctx->L.size_k_raw_row;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b);
+ lid_dequant_block(k_buf, stride, nkv, D, true);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b);
+
+ lid_prep_k_block_f16(lctx, kt, k_buf, kt_t0, nkv, b, tr);
+}
+
+static __attribute__((noinline)) void lid_compute_rows1(const struct htp_lid_context * lctx, uint8_t * restrict o0,
+ const HVX_Vector * restrict kt0, const uint8_t * restrict m0) {
+ const struct htp_lid_vtcm_layout * L = &lctx->L;
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const uint32_t n_head = lctx->octx->src[0]->ne[1];
+ const uint32_t nt = lctx->nt;
+
+ for (uint32_t t = 0; t < nt; ++t) {
+ const HVX_Vector * q_t = (const HVX_Vector *) lctx->spad_q + t * n_head * D;
+ const HVX_Vector * w_t = (const HVX_Vector *) (lctx->spad_w + t * n_head * VLEN);
+ lid_compute_row((float *) (o0 + t * L->size_o_row), q_t, w_t, kt0,
+ (const __fp16 *) (m0 + t * L->size_m_row), D, n_head);
+ }
+}
+
+static __attribute__((noinline)) void lid_compute_rows2(const struct htp_lid_context * lctx, uint8_t * restrict o0, uint8_t * restrict o1,
+ const HVX_Vector * restrict kt0, const HVX_Vector * restrict kt1,
+ const uint8_t * restrict m0, const uint8_t * restrict m1) {
+ const struct htp_lid_vtcm_layout * L = &lctx->L;
+ const uint32_t D = lctx->octx->src[0]->ne[0];
+ const uint32_t n_head = lctx->octx->src[0]->ne[1];
+ const uint32_t nt = lctx->nt;
+
+ for (uint32_t t = 0; t < nt; ++t) {
+ const HVX_Vector * q_t = (const HVX_Vector *) lctx->spad_q + t * n_head * D;
+ const HVX_Vector * w_t = (const HVX_Vector *) (lctx->spad_w + t * n_head * VLEN);
+ lid_compute_row2((float *) (o0 + t * L->size_o_row), (float *) (o1 + t * L->size_o_row),
+ q_t, w_t, kt0, kt1,
+ (const __fp16 *) (m0 + t * L->size_m_row), (const __fp16 *) (m1 + t * L->size_m_row),
+ D, n_head);
+ }
+}
+
// Each thread owns a range of kv blocks and streams K / mask in, output out (HTP_LID_N_BUF buffers)
static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_lid_context * lctx = (struct htp_lid_context *) data;
@@ -523,14 +610,9 @@ static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsign
const struct htp_lid_vtcm_layout * L = &lctx->L;
- const uint32_t D = q->ne[0];
- const uint32_t n_head = q->ne[1];
- const uint32_t n_kv = k->ne[2];
- const uint32_t nt = lctx->nt;
-
- const bool is_f32 = (k->type == HTP_TYPE_F32);
- const bool is_q8_0 = (k->type == HTP_TYPE_Q8_0);
- const bool is_q4_0 = (k->type == HTP_TYPE_Q4_0);
+ const uint32_t D = q->ne[0];
+ const uint32_t n_kv = k->ne[2];
+ const uint32_t nt = lctx->nt;
const uint32_t k_row_size = lctx->kp->k_row_size;
const uint32_t nbk2 = k->nb[2];
@@ -549,12 +631,6 @@ static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsign
kt[0] = (HVX_Vector *) (lctx->spad_kt + ith * L->size_kt);
kt[1] = kt[0] + hex_round_up(D, HTP_LID_KV_BLOCK);
HVX_Vector * kt_t0 = kt[1] + hex_round_up(D, HTP_LID_KV_BLOCK);
- HVX_Vector * kt_t1 = kt_t0 + HTP_LID_KV_BLOCK;
-
- // Q8_0: transpose by gather from the raw rows (sc: one vector of block scales per 32 d)
- const bool q8_g = is_q8_0 && lid_q8_0_gather_ok(L->size_k_raw_row, D);
- HVX_Vector * sc = kt_t1 + HTP_LID_KV_BLOCK;
- const HVX_Vector g_offs = hvx_vec_gather_offsets_h(L->size_k_raw_row);
struct htp_thread_trace * tr = th->trace;
dma_queue * dma_q = th->dma_q;
@@ -586,41 +662,14 @@ static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsign
k_buf[j] = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst;
m_buf[j] = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst;
- if ((is_q8_0 && !q8_g) || is_q4_0) {
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) (b + j));
- lid_dequant_block(k_buf[j], L->size_k_raw_row, nkv, D, is_q4_0);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) (b + j));
- }
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) (b + j));
- if (is_f32) {
- for (uint32_t r = 0; r < nkv; ++r) {
- lid_convert_row_f32_to_f16(k_buf[j] + r * L->size_k_raw_row, D);
- }
- }
- if (q8_g) {
- lid_transpose_q8_0_gather(kt[j], kt_t0, sc, k_buf[j], L->size_k_raw_row, g_offs, D);
- } else {
- for (uint32_t d0 = 0; d0 < D; d0 += HTP_LID_KV_BLOCK) {
- lid_transpose_64x64_f16(kt[j] + d0, k_buf[j] + d0 * sizeof(__fp16), L->size_k_raw_row, nkv, kt_t0, kt_t1);
- }
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) (b + j));
+ lctx->prep_k(lctx, kt[j], k_buf[j], kt_t0, nkv, b + j, tr);
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) b);
- for (uint32_t t = 0; t < nt; ++t) {
- const HVX_Vector * q_t = (const HVX_Vector *) lctx->spad_q + t * n_head * D;
- const HVX_Vector * w_t = (const HVX_Vector *) (lctx->spad_w + t * n_head * VLEN);
- if (nb == 2) {
- lid_compute_row2((float *) (o_buf[0] + t * L->size_o_row), (float *) (o_buf[1] + t * L->size_o_row),
- q_t, w_t, kt[0], kt[1],
- (const __fp16 *) (m_buf[0] + t * L->size_m_row), (const __fp16 *) (m_buf[1] + t * L->size_m_row),
- D, n_head);
- } else {
- lid_compute_row((float *) (o_buf[0] + t * L->size_o_row), q_t, w_t, kt[0],
- (const __fp16 *) (m_buf[0] + t * L->size_m_row), D, n_head);
- }
+ if (nb == 2) {
+ lid_compute_rows2(lctx, o_buf[0], o_buf[1], kt[0], kt[1], m_buf[0], m_buf[1]);
+ } else {
+ lid_compute_rows1(lctx, o_buf[0], kt[0], m_buf[0]);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) b);
@@ -670,6 +719,20 @@ struct lid_hmx_set {
uint32_t n_u;
};
+struct lid_hmx_w_slice {
+ const uint8_t * ptr;
+ size_t base_off;
+};
+
+struct htp_lid_hmx_context;
+
+typedef void (*lid_hmx_q_scg_fn_t)(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
+ struct lid_hmx_w_slice ws);
+typedef void (*lid_hmx_q_tiles_fn_t)(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
+ const uint8_t * qs, uint8_t * qh);
+typedef void (*lid_hmx_prep_k_fn_t)(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw,
+ uint32_t r0, uint32_t r1, uint32_t nv);
+
struct htp_lid_hmx_context {
const struct htp_ops_context * octx;
const struct htp_lid_kernel_params * kp;
@@ -680,6 +743,12 @@ struct htp_lid_hmx_context {
uint32_t n_blocks; // per run
uint32_t n_tile; // tokens per token tile
uint32_t n_tt; // token tiles per stream
+ uint32_t q_row_bytes;
+ uint32_t w_row_bytes;
+
+ lid_hmx_q_scg_fn_t q_scg;
+ lid_hmx_q_tiles_fn_t q_tiles;
+ lid_hmx_prep_k_fn_t prep_k;
uint32_t n_qsets; // Q sets per buffer
uint32_t qbuf; // Q buffer of the run (two buffers: the next run's Q is prepped during this run)
@@ -687,6 +756,7 @@ struct htp_lid_hmx_context {
uint32_t tile0; // first (stream, token tile) of the run
uint32_t n_run; // sets in the run
uint32_t n_qthr; // threads with Q work in the run
+ uint32_t per_k0; // K rows per non-Q thread for block 0
uint32_t nt_run; // tokens of each set in the run
uint32_t n_u_run; // token tiles of 32 of each set in the run
int32_t g; // current stage
@@ -704,7 +774,7 @@ struct htp_lid_hmx_context {
uint8_t * sc;
uint8_t * sc_id;
__fp16 * s;
- float * w;
+ uint8_t * w;
uint8_t * qs;
uint8_t * k_raw[2];
__fp16 * k_t[2];
@@ -841,17 +911,16 @@ static void lid_hmx_worker(const htp_thread_t * th, void * data) {
static inline void lid_hmx_rows(const struct htp_lid_hmx_context * hctx, uint32_t ith, uint32_t nth, uint32_t g, uint32_t n_rows,
uint32_t * r0, uint32_t * r1) {
uint32_t per;
- if (g == 0 && hctx->n_qthr < nth) {
+ if (g == 0 && hctx->per_k0 > 0) {
if (ith < hctx->n_qthr) {
*r0 = *r1 = 0;
return;
}
ith -= hctx->n_qthr;
- per = (n_rows + nth - hctx->n_qthr - 1) / (nth - hctx->n_qthr);
+ per = hctx->per_k0;
} else {
- per = fastdiv(n_rows + hctx->octx->n_hvx - 1, &hctx->octx->n_hvx_div);
+ per = hex_round_up(fastdiv(n_rows + hctx->octx->n_hvx - 1, &hctx->octx->n_hvx_div), 2);
}
- per = hex_round_up(per, 2);
*r0 = MIN(ith * per, n_rows);
*r1 = MIN(*r0 + per, n_rows);
}
@@ -920,12 +989,48 @@ static inline void lid_q8_0_pair_store(HVX_Vector * restrict dst, HVX_Vector a,
}
}
+// Raw Q8_0 rows [r0, r1) (D = 128, n_dot = 4) to activation tiles, dequant fused with the row pair interleave.
+static void lid_hmx_prep_k_q8_0_d128(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw,
+ uint32_t r0, uint32_t r1, uint32_t nv) {
+ const size_t row_stride = hctx->L.size_k_raw_row;
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
+
+ for (uint32_t r = r0; r < r1; r += 2) {
+ const uint8_t * p0 = k_raw + r * row_stride;
+ const uint8_t * p1 = p0 + row_stride;
+ const bool v0 = r < nv;
+ const bool v1 = r + 1 < nv;
+
+ HVX_Vector * dst = (HVX_Vector *) (k_t + (r / 32) * 4 * HMX_FP16_TILE_N_ELMS) + (r % 32) / 2;
+
+ // D = 128: the row is 136 bytes, two aligned loads; scales at halfwords 0, 17, 34, 51
+ const HVX_Vector a0 = v0 ? ((const HVX_Vector *) p0)[0] : zero;
+ const HVX_Vector a1 = v0 ? ((const HVX_Vector *) p0)[1] : zero;
+ const HVX_Vector b0 = v1 ? ((const HVX_Vector *) p1)[0] : zero;
+ const HVX_Vector b1 = v1 ? ((const HVX_Vector *) p1)[1] : zero;
+
+ const HVX_VectorPair ds = Q6_W_vshuff_VVR(b0, a0, -SIZEOF_FP16);
+
+ lid_q8_0_pair_store(dst,
+ Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a0, a0, 2), Q6_V_valign_VVR(a0, a0, 4)),
+ Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b0, b0, 2), Q6_V_valign_VVR(b0, b0, 4)),
+ hvx_vec_repl4(Q6_V_lo_W(ds)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_lo_W(ds), 17 * 4)), true);
+ lid_q8_0_pair_store(dst + 32,
+ Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a1, a0, 70), Q6_V_valign_VVR(a1, a0, 72)),
+ Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b1, b0, 70), Q6_V_valign_VVR(b1, b0, 72)),
+ hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 2 * 4)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 19 * 4)), true);
+ }
+}
+
// Raw Q8_0 rows [r0, r1) to activation tiles, dequant fused with the row pair interleave. Rows >= nv are zero.
// Per row pair and two blocks: interleave the quants of both rows as bytes, widen, then scale by the (d_r, d_r+1) word.
-static inline void lid_hmx_prep_k_q8_0(__fp16 * restrict k_t, const uint8_t * restrict k_raw, size_t row_stride,
- uint32_t r0, uint32_t r1, uint32_t nv, uint32_t n_dot) {
- const HVX_Vector zero = Q6_V_vzero();
- const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
+static void lid_hmx_prep_k_q8_0(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw,
+ uint32_t r0, uint32_t r1, uint32_t nv) {
+ const size_t row_stride = hctx->L.size_k_raw_row;
+ const uint32_t n_dot = hctx->L.n_dot;
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
for (uint32_t r = r0; r < r1; r += 2) {
const uint8_t * p0 = k_raw + r * row_stride;
@@ -935,26 +1040,6 @@ static inline void lid_hmx_prep_k_q8_0(__fp16 * restrict k_t, const uint8_t * re
HVX_Vector * dst = (HVX_Vector *) (k_t + (r / 32) * n_dot * HMX_FP16_TILE_N_ELMS) + (r % 32) / 2;
- if (n_dot == 4) {
- // D = 128: the row is 136 bytes, two aligned loads; scales at halfwords 0, 17, 34, 51
- const HVX_Vector a0 = v0 ? ((const HVX_Vector *) p0)[0] : zero;
- const HVX_Vector a1 = v0 ? ((const HVX_Vector *) p0)[1] : zero;
- const HVX_Vector b0 = v1 ? ((const HVX_Vector *) p1)[0] : zero;
- const HVX_Vector b1 = v1 ? ((const HVX_Vector *) p1)[1] : zero;
-
- const HVX_VectorPair ds = Q6_W_vshuff_VVR(b0, a0, -SIZEOF_FP16);
-
- lid_q8_0_pair_store(dst,
- Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a0, a0, 2), Q6_V_valign_VVR(a0, a0, 4)),
- Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b0, b0, 2), Q6_V_valign_VVR(b0, b0, 4)),
- hvx_vec_repl4(Q6_V_lo_W(ds)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_lo_W(ds), 17 * 4)), true);
- lid_q8_0_pair_store(dst + 32,
- Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a1, a0, 70), Q6_V_valign_VVR(a1, a0, 72)),
- Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b1, b0, 70), Q6_V_valign_VVR(b1, b0, 72)),
- hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 2 * 4)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 19 * 4)), true);
- continue;
- }
-
for (uint32_t i = 0; i < n_dot; i += 2) {
const uint8_t * pa = p0 + i * sizeof(block_q8_0);
const uint8_t * pb = p1 + i * sizeof(block_q8_0);
@@ -973,11 +1058,13 @@ static inline void lid_hmx_prep_k_q8_0(__fp16 * restrict k_t, const uint8_t * re
// Raw Q4_0 rows [r0, r1) to activation tiles, same as Q8_0: per row pair and two blocks, one load per row.
// Rows >= nv are zero.
-static inline void lid_hmx_prep_k_q4_0(__fp16 * restrict k_t, const uint8_t * restrict k_raw, size_t row_stride,
- uint32_t r0, uint32_t r1, uint32_t nv, uint32_t n_dot) {
- const HVX_Vector zero = Q6_V_vzero();
- const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
- const HVX_VectorPred lo16 = Q6_Q_or_QQ(Q6_Q_vsetq_R(16), Q6_Q_and_QQn(Q6_Q_vsetq_R(48), q32));
+static void lid_hmx_prep_k_q4_0(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw,
+ uint32_t r0, uint32_t r1, uint32_t nv) {
+ const size_t row_stride = hctx->L.size_k_raw_row;
+ const uint32_t n_dot = hctx->L.n_dot;
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_VectorPred q32 = Q6_Q_vsetq_R(32);
+ const HVX_VectorPred lo16 = Q6_Q_or_QQ(Q6_Q_vsetq_R(16), Q6_Q_and_QQn(Q6_Q_vsetq_R(48), q32));
for (uint32_t r = r0; r < r1; r += 2) {
const uint8_t * p0 = k_raw + r * row_stride;
@@ -1000,9 +1087,11 @@ static inline void lid_hmx_prep_k_q4_0(__fp16 * restrict k_t, const uint8_t * re
}
// F16 rows [r0, r1) to activation tiles: row pairs interleaved. Rows >= nv are zero.
-static inline void lid_hmx_prep_k_f16(__fp16 * restrict k_t, const uint8_t * restrict k_raw, size_t row_stride,
- uint32_t r0, uint32_t r1, uint32_t nv, uint32_t n_dot) {
- const HVX_Vector zero = Q6_V_vzero();
+static void lid_hmx_prep_k_f16(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw,
+ uint32_t r0, uint32_t r1, uint32_t nv) {
+ const size_t row_stride = hctx->L.size_k_raw_row;
+ const uint32_t n_dot = hctx->L.n_dot;
+ const HVX_Vector zero = Q6_V_vzero();
for (uint32_t r = r0; r < r1; r += 2) {
const HVX_Vector * p0 = (const HVX_Vector *) (k_raw + r * row_stride);
@@ -1022,10 +1111,30 @@ static inline void lid_hmx_prep_k_f16(__fp16 * restrict k_t, const uint8_t * res
}
}
+// F32 rows [r0, r1) to activation tiles: f32 -> f16 fused with row-pair interleave. Rows >= nv are zero.
+static void lid_hmx_prep_k_f32(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw,
+ uint32_t r0, uint32_t r1, uint32_t nv) {
+ const size_t row_stride = hctx->L.size_k_raw_row;
+ const uint32_t n_dot = hctx->L.n_dot;
+ const HVX_Vector zero = Q6_V_vzero();
+
+ for (uint32_t r = r0; r < r1; r += 2) {
+ const HVX_Vector * p0 = (const HVX_Vector *) (k_raw + r * row_stride);
+ const HVX_Vector * p1 = (const HVX_Vector *) (k_raw + (r + 1) * row_stride);
+ const bool v0 = r < nv;
+ const bool v1 = r + 1 < nv;
+
+ HVX_Vector * dst = (HVX_Vector *) (k_t + (r / 32) * n_dot * HMX_FP16_TILE_N_ELMS) + (r % 32) / 2;
+
+ for (uint32_t i = 0; i < n_dot; ++i) {
+ dst[i * 16] = hvx_vec_f32_to_f16_shuff(v0 ? p0[i] : zero, v1 ? p1[i] : zero);
+ }
+ }
+}
+
// K rows of block g (this thread's rows) to activation tiles, one piece per set; set padding rows are zero.
// Not inlined: keeps the stage's registers out of the prep loops.
static __attribute__((noinline)) void lid_hmx_prep_k(const struct htp_lid_hmx_context * hctx, uint32_t ith, uint32_t nth, uint32_t g) {
- const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
const struct htp_tensor * k = hctx->octx->src[1];
const uint32_t n_kv = k->ne[2];
@@ -1036,11 +1145,8 @@ static __attribute__((noinline)) void lid_hmx_prep_k(const struct htp_lid_hmx_co
uint32_t r0, r1;
lid_hmx_rows(hctx, ith, nth, g, n_rows, &r0, &r1);
- uint8_t * k_raw = hctx->k_raw[g % 2];
+ const uint8_t * k_raw = hctx->k_raw[g % 2];
__fp16 * k_t = hctx->k_t[g % 2];
- const bool f32 = k->type == HTP_TYPE_F32;
- const bool q8 = k->type == HTP_TYPE_Q8_0;
- const bool q4 = k->type == HTP_TYPE_Q4_0;
for (uint32_t r = r0; r < r1;) {
const uint32_t x = xa + r;
@@ -1049,24 +1155,71 @@ static __attribute__((noinline)) void lid_hmx_prep_k(const struct htp_lid_hmx_co
const uint32_t end = MIN(r1, (set + 1) * ks - xa);
const uint32_t nv = r + (kv < n_kv ? n_kv - kv : 0);
- if (q8) {
- lid_hmx_prep_k_q8_0(k_t, k_raw, L->size_k_raw_row, r, end, nv, L->n_dot);
- } else if (q4) {
- lid_hmx_prep_k_q4_0(k_t, k_raw, L->size_k_raw_row, r, end, nv, L->n_dot);
- } else {
- if (f32) {
- for (uint32_t i = r; i < end; ++i) {
- lid_convert_row_f32_to_f16(k_raw + i * L->size_k_raw_row, k->ne[0]);
- }
- }
- lid_hmx_prep_k_f16(k_t, k_raw, L->size_k_raw_row, r, end, nv, L->n_dot);
- }
+ hctx->prep_k(hctx, k_t, k_raw, r, end, nv);
r = end;
}
}
+static __attribute__((noinline)) void lid_hmx_extract_seg(const struct htp_lid_hmx_context * hctx, uint32_t ith, uint32_t g,
+ uint32_t ta, uint32_t tb, uint32_t q0, uint32_t q1) {
+ const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
+
+ const uint32_t n_u = hctx->n_u_run;
+ const uint32_t mu = (n_u + 1) * HMX_FP16_TILE_SIZE - 1;
+
+ static const int32_t base_offs[32] __attribute__((aligned(128))) = {
+ 0 * 128, 1 * 128, 2 * 128, 3 * 128, 4 * 128, 5 * 128, 6 * 128, 7 * 128,
+ 8 * 128, 9 * 128, 10 * 128, 11 * 128, 12 * 128, 13 * 128, 14 * 128, 15 * 128,
+ 0 * 128, 1 * 128, 2 * 128, 3 * 128, 4 * 128, 5 * 128, 6 * 128, 7 * 128,
+ 8 * 128, 9 * 128, 10 * 128, 11 * 128, 12 * 128, 13 * 128, 14 * 128, 15 * 128,
+ };
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_Vector hi_off = Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), zero, Q6_V_vsplat_R(n_u * HMX_FP16_TILE_SIZE));
+ const HVX_Vector v_offs = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) base_offs, hi_off);
+
+ HVX_Vector * gbuf = (HVX_Vector *) (hctx->qs + ith * L->size_qs + 2 * 32 * L->size_qs_row + 32 * L->size_qh_row);
+
+ const HVX_Vector ninf = Q6_V_vsplat_R(0xFF800000);
+ const HVX_Vector one = Q6_Vh_vsplat_R(0x3C00);
+ const HVX_Vector hinf = Q6_Vh_vsplat_R(0xFC00);
+
+ const __fp16 * o_base = hctx->o[g % 2];
+ const uint8_t * m_buf = hctx->m[g % 4];
+ uint8_t * o_buf = hctx->out[g % 2];
+
+ for (uint32_t t = ta; t < tb; ++t) {
+ const uint32_t u = t / 32;
+ const HVX_Vector off = Q6_Vw_vadd_VwVw(v_offs, Q6_V_vsplat_R((t % 32) * 4));
+
+ for (uint32_t q = q0; q < q1; ++q) {
+ const __fp16 * base = o_base + (2 * q * n_u + u) * HMX_FP16_TILE_N_ELMS;
+ Q6_vgather_ARMVw(gbuf + q - q0, (size_t) base, mu, off);
+ }
+ hvx_gather_sync(gbuf + q1 - q0 - 1);
+
+ const HVX_Vector * mv = (const HVX_Vector *) (m_buf + t * L->size_m_row);
+ HVX_Vector * ov = (HVX_Vector *) (o_buf + t * L->size_o_row);
+
+ for (uint32_t q = q0; q < q1; ++q) {
+ const HVX_VectorPair s = hvx_vec_f16_to_f32(gbuf[q - q0]);
+
+ // qf32 math does not keep inf: add a finite mask, then put -inf back
+ const HVX_Vector m_f16 = mv[q];
+ const HVX_VectorPred m_inf = Q6_Q_vcmp_eq_VhVh(m_f16, hinf);
+ const HVX_VectorPair m_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, zero, m_f16));
+ const HVX_VectorPair f_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, one, zero));
+
+ const HVX_Vector acc0 = HVX_OP_ADD_F32(Q6_V_lo_W(s), Q6_V_lo_W(m_f32));
+ const HVX_Vector acc1 = HVX_OP_ADD_F32(Q6_V_hi_W(s), Q6_V_hi_W(m_f32));
+ ov[2 * q + 0] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_lo_W(f_f32), zero), ninf, acc0);
+ ov[2 * q + 1] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_hi_W(f_f32), zero), ninf, acc1);
+ }
+ }
+}
+
// O column of each token (64 kv per gather) + mask -> f32 rows, then one DMA out per segment
static __attribute__((noinline)) void lid_hmx_extract(const struct htp_lid_hmx_context * hctx, const htp_thread_t * th, uint32_t ith, uint32_t nth, uint32_t g) {
+ (void) nth;
const struct htp_ops_context * octx = hctx->octx;
const struct htp_tensor * dst = octx->dst;
const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
@@ -1084,58 +1237,13 @@ static __attribute__((noinline)) void lid_hmx_extract(const struct htp_lid_hmx_c
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) g);
- const uint32_t n_u = hctx->n_u_run;
- const uint32_t mu = (n_u + 1) * HMX_FP16_TILE_SIZE - 1;
-
- int32_t offs[32] __attribute__((aligned(128)));
- for (int l = 0; l < 32; l++) {
- offs[l] = (l / 16) * n_u * HMX_FP16_TILE_SIZE + (l % 16) * 128;
- }
- const HVX_Vector v_offs = *(const HVX_Vector *) offs;
-
- HVX_Vector * gbuf = (HVX_Vector *) (hctx->qs + ith * L->size_qs + 2 * 32 * L->size_qs_row + 32 * L->size_qh_row);
-
- const HVX_Vector zero = Q6_V_vzero();
- const HVX_Vector ninf = Q6_V_vsplat_R(0xFF800000);
- const HVX_Vector one = Q6_Vh_vsplat_R(0x3C00);
- const HVX_Vector hinf = Q6_Vh_vsplat_R(0xFC00);
-
- const __fp16 * o_base = hctx->o[g % 2];
- const uint8_t * m_buf = hctx->m[g % 4];
- uint8_t * o_buf = hctx->out[g % 2];
+ uint8_t * o_buf = hctx->out[g % 2];
for (uint32_t i = 0; i < n_seg; ++i) {
const uint32_t q0 = seg[i].x0 / 64;
const uint32_t q1 = (seg[i].x0 + seg[i].nv + 63) / 64;
- for (uint32_t t = ta; t < tb; ++t) {
- const uint32_t u = t / 32;
- const HVX_Vector off = Q6_Vw_vadd_VwVw(v_offs, Q6_V_vsplat_R((t % 32) * 4));
-
- for (uint32_t q = q0; q < q1; ++q) {
- const __fp16 * base = o_base + (2 * q * n_u + u) * HMX_FP16_TILE_N_ELMS;
- Q6_vgather_ARMVw(gbuf + q - q0, (size_t) base, mu, off);
- }
- hvx_gather_sync(gbuf + q1 - q0 - 1);
-
- const HVX_Vector * mv = (const HVX_Vector *) (m_buf + t * L->size_m_row);
- HVX_Vector * ov = (HVX_Vector *) (o_buf + t * L->size_o_row);
-
- for (uint32_t q = q0; q < q1; ++q) {
- const HVX_VectorPair s = hvx_vec_f16_to_f32(gbuf[q - q0]);
-
- // qf32 math does not keep inf: add a finite mask, then put -inf back
- const HVX_Vector m_f16 = mv[q];
- const HVX_VectorPred m_inf = Q6_Q_vcmp_eq_VhVh(m_f16, hinf);
- const HVX_VectorPair m_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, zero, m_f16));
- const HVX_VectorPair f_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, one, zero));
-
- const HVX_Vector acc0 = HVX_OP_ADD_F32(Q6_V_lo_W(s), Q6_V_lo_W(m_f32));
- const HVX_Vector acc1 = HVX_OP_ADD_F32(Q6_V_hi_W(s), Q6_V_hi_W(m_f32));
- ov[2 * q + 0] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_lo_W(f_f32), zero), ninf, acc0);
- ov[2 * q + 1] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_hi_W(f_f32), zero), ninf, acc1);
- }
- }
+ lid_hmx_extract_seg(hctx, ith, g, ta, tb, q0, q1);
const struct lid_hmx_set S = hctx->sets[seg[i].set];
dma_queue_push(th->dma_q,
@@ -1234,39 +1342,16 @@ static uint32_t lid_hmx_push_q(const struct htp_lid_hmx_context * hctx, dma_queu
const uint32_t cnt = MIN(nh - h, nr - r);
dma_queue_push(dma_q, dma_make_data(qs + r * hctx->L.size_qs_row,
q->data + S->is * q->nb[3] + (S->t0 + t) * q->nb[2] + h * q->nb[1]),
- hctx->L.size_qs_row, q->nb[1], q->ne[0] * sizeof(float), cnt);
+ hctx->L.size_qs_row, q->nb[1], hctx->q_row_bytes, cnt);
r += cnt;
n++;
}
return n;
}
-// Scales (|w| per channel, f16 in the low half of each word) and G tile (sign(w) at row c, column token(c) % 32)
-// of one channel tile. w points at the tile's 32 channels, the first one is (token t, head h).
-static inline void lid_hmx_build_sc_g(uint8_t * restrict sc, __fp16 * restrict gt, const float * restrict w,
- uint32_t t, uint32_t h, uint32_t nr, uint32_t nh) {
+// G tile (sign(w) at row c, column token(c) % 32) of one channel tile. First channel is (token t, head h).
+static inline void lid_hmx_build_g(__fp16 * restrict gt, HVX_Vector sv, uint32_t t, uint32_t h, uint32_t nr, uint32_t nh) {
const HVX_Vector zero = Q6_V_vzero();
- const HVX_Vector wv = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(nr * sizeof(float)), *(const HVX_Vector *) w, zero);
-
- HVX_Vector * scv = (HVX_Vector *) sc;
- scv[0] = hvx_vec_f32_to_f16_shuff(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x7FFFFFFF)), zero);
- scv[1] = zero;
-
- // sign(w) as f16 bits in the low half of each word, then packed: row r in halfword r
- const HVX_VectorPred nz = Q6_Q_vcmp_gt_VuwVuw(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x7FFFFFFF)), zero);
- const HVX_Vector sgn = Q6_V_vor_VV(Q6_V_vsplat_R(0x3C00), Q6_Vw_vasr_VwR(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x80000000)), 16));
- const HVX_Vector sv = Q6_Vh_vpacke_VwVw(zero, Q6_V_vmux_QVV(nz, sgn, zero));
-
- // token column of each row; -1 for missing rows (only rows 0..31 are used)
- int16_t tcol[64] __attribute__((aligned(128))) = { 0 };
- for (uint32_t r = 0; r < 32; ++r) {
- tcol[r] = r < nr ? (int16_t) (t % 32) : -1;
- if (++h == nh) {
- h = 0;
- t++;
- }
- }
- const HVX_Vector tv = *(const HVX_Vector *) tcol;
// halfword 2n and 2n + 1 of a G vector are column n
static const int16_t col[64] __attribute__((aligned(128))) = {
@@ -1276,11 +1361,23 @@ static inline void lid_hmx_build_sc_g(uint8_t * restrict sc, __fp16 * restrict g
};
const HVX_Vector cv = *(const HVX_Vector *) col;
- // vector p holds rows 2p, 2p + 1
+ // vector p holds rows 2p, 2p + 1; token column is t % 32 (-1 for missing rows)
HVX_Vector * gv = (HVX_Vector *) gt;
for (uint32_t p = 0; p < 16; ++p) {
- const HVX_Vector tp = hvx_vec_repl4(Q6_V_vror_VR(tv, p * 4));
- const HVX_Vector sp = hvx_vec_repl4(Q6_V_vror_VR(sv, p * 4));
+ const uint32_t r0 = 2 * p;
+ const int32_t c0 = r0 < nr ? (int32_t) (t & 31) : -1;
+ if (++h == nh) {
+ h = 0;
+ t++;
+ }
+ const int32_t c1 = (r0 + 1) < nr ? (int32_t) (t & 31) : -1;
+ if (++h == nh) {
+ h = 0;
+ t++;
+ }
+ const uint32_t t_pair = ((uint32_t) c1 << 16) | ((uint32_t) c0 & 0xFFFFu);
+ const HVX_Vector tp = Q6_V_vsplat_R(t_pair);
+ const HVX_Vector sp = hvx_vec_repl4(Q6_V_vror_VR(sv, p * 4));
gv[p] = Q6_V_vmux_QVV(Q6_Q_vcmp_eq_VhVh(cv, tp), sp, zero);
}
}
@@ -1290,28 +1387,61 @@ static inline uint32_t lid_hmx_slot(const struct htp_lid_hmx_context * hctx, uin
return qbuf * hctx->n_qsets + set;
}
-// Scales and G of channel tile c of a Q slot (needs the slot's w)
-static __attribute__((noinline)) void lid_hmx_q_scg(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c) {
+// Scales (|w| per channel, f16 in the low half of each word) and G of channel tile c of a Q slot (f32 w)
+static __attribute__((noinline)) void lid_hmx_q_scg_f32(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
+ struct lid_hmx_w_slice ws) {
const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
const uint32_t nh = hctx->octx->src[0]->ne[1];
const uint32_t ch = c * 32;
+ const uint32_t nr = MIN(32, S->nt * nh - ch);
const uint32_t t = fastdiv(ch, &hctx->kp->div_n_head);
- lid_hmx_build_sc_g(hctx->sc + (slot * L->n_ch + c) * 256, hctx->gw + (slot * L->n_ch + c) * HMX_FP16_TILE_N_ELMS,
- hctx->w + slot * (L->size_w / sizeof(float)) + ch, t, ch - t * nh, MIN(32, S->nt * nh - ch), nh);
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_Vector raw = *(const HVX_Vector *) (ws.ptr + ((size_t) c * 128 - ws.base_off));
+ const HVX_Vector wv = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(nr * sizeof(float)), raw, zero);
+ const HVX_Vector abs_wv = Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x7FFFFFFF));
+
+ HVX_Vector * scv = (HVX_Vector *) (hctx->sc + (slot * L->n_ch + c) * 256);
+ scv[0] = hvx_vec_f32_to_f16_shuff(abs_wv, zero);
+ scv[1] = zero;
+
+ // sign(w) as f16 bits in the low half of each word, then packed: row r in halfword r
+ const HVX_VectorPred nz = Q6_Q_vcmp_gt_VuwVuw(abs_wv, zero);
+ const HVX_Vector sgn = Q6_V_vor_VV(Q6_V_vsplat_R(0x3C00), Q6_Vw_vasr_VwR(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x80000000)), 16));
+ const HVX_Vector sv = Q6_Vh_vpacke_VwVw(zero, Q6_V_vmux_QVV(nz, sgn, zero));
+
+ lid_hmx_build_g(hctx->gw + (slot * L->n_ch + c) * HMX_FP16_TILE_N_ELMS, sv, t, ch - t * nh, nr, nh);
}
-// Staged f32 Q rows of channel tile c to f16, then to the weight tiles of a Q slot
-static __attribute__((noinline)) void lid_hmx_q_tiles(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
- const uint8_t * qs, uint8_t * qh) {
+// Scales and G of channel tile c of a Q slot (f16 w)
+static __attribute__((noinline)) void lid_hmx_q_scg_f16(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
+ struct lid_hmx_w_slice ws) {
const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
- const uint32_t D = hctx->octx->src[0]->ne[0];
const uint32_t nh = hctx->octx->src[0]->ne[1];
- const uint32_t nr = MIN(32, S->nt * nh - c * 32);
+ const uint32_t ch = c * 32;
+ const uint32_t nr = MIN(32, S->nt * nh - ch);
+ const uint32_t t = fastdiv(ch, &hctx->kp->div_n_head);
- for (uint32_t r = 0; r < nr; ++r) {
- hvx_copy_f16_f32_aa(qh + r * L->size_qh_row, qs + r * L->size_qs_row, D);
- }
+ const HVX_Vector zero = Q6_V_vzero();
+ const HVX_Vector raw = Q6_V_vror_VR(*(const HVX_Vector *) (ws.ptr + ((size_t) (c / 2) * 128 - ws.base_off)), (c & 1) * 64);
+ const HVX_Vector wh = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(nr * sizeof(__fp16)), raw, zero);
+ const HVX_Vector abs_wh = Q6_V_vand_VV(wh, Q6_Vh_vsplat_R(0x7FFF));
+
+ HVX_Vector * scv = (HVX_Vector *) (hctx->sc + (slot * L->n_ch + c) * 256);
+ scv[0] = Q6_V_lo_W(Q6_W_vshuff_VVR(zero, abs_wh, -SIZEOF_FP16));
+ scv[1] = zero;
+
+ const HVX_VectorPred nz = Q6_Q_vcmp_gt_VuhVuh(abs_wh, zero);
+ const HVX_Vector sgn = Q6_V_vor_VV(Q6_Vh_vsplat_R(0x3C00), Q6_V_vand_VV(wh, Q6_Vh_vsplat_R(0x8000)));
+ const HVX_Vector sv = Q6_V_vmux_QVV(nz, sgn, zero);
+
+ lid_hmx_build_g(hctx->gw + (slot * L->n_ch + c) * HMX_FP16_TILE_N_ELMS, sv, t, ch - t * nh, nr, nh);
+}
+
+static inline void lid_hmx_scatter_q_tiles(const struct htp_lid_hmx_context * hctx, uint32_t slot, uint32_t c, uint32_t nr,
+ const __fp16 * src, size_t src_stride) {
+ const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
+ const uint32_t D = hctx->octx->src[0]->ne[0];
// missing channels must be zero (finite): zero the tiles, then scatter only the valid rows
__fp16 * qw = hctx->qw + (slot * L->n_ch + c) * L->n_dot * HMX_FP16_TILE_N_ELMS;
@@ -1320,17 +1450,40 @@ static __attribute__((noinline)) void lid_hmx_q_tiles(const struct htp_lid_hmx_c
((HVX_Vector *) qw)[i] = Q6_V_vzero();
}
}
- hmx_interleave_rows_to_tiles(qw, (const __fp16 *) qh, nr, D, L->size_qh_row / sizeof(__fp16), 0, hex_round_up(nr, 2));
- hvx_gather_sync(qw);
+ hmx_interleave_rows_to_tiles(qw, src, nr, D, src_stride, 0, hex_round_up(nr, 2));
}
-static inline uint32_t lid_hmx_find_valid_gc(const struct htp_lid_hmx_context * hctx, uint32_t gc, uint32_t gc1) {
+// Staged f32 Q rows of channel tile c to f16, then to the weight tiles of a Q slot
+static __attribute__((noinline)) void lid_hmx_q_tiles_f32(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
+ const uint8_t * qs, uint8_t * qh) {
+ const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
+ const uint32_t D = hctx->octx->src[0]->ne[0];
+ const uint32_t nh = hctx->octx->src[0]->ne[1];
+ const uint32_t nr = MIN(32, S->nt * nh - c * 32);
+
+ for (uint32_t r = 0; r < nr; ++r) {
+ hvx_copy_f16_f32_aa(qh + r * L->size_qh_row, qs + r * L->size_qs_row, D);
+ }
+ lid_hmx_scatter_q_tiles(hctx, slot, c, nr, (const __fp16 *) qh, L->size_qh_row / sizeof(__fp16));
+}
+
+// Staged f16 Q rows of channel tile c directly to the weight tiles of a Q slot
+static __attribute__((noinline)) void lid_hmx_q_tiles_f16(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c,
+ const uint8_t * qs, uint8_t * qh) {
+ (void) qh;
+ const uint32_t nh = hctx->octx->src[0]->ne[1];
+ const uint32_t nr = MIN(32, S->nt * nh - c * 32);
+ lid_hmx_scatter_q_tiles(hctx, slot, c, nr, (const __fp16 *) qs, hctx->L.size_qs_row / sizeof(__fp16));
+}
+
+static inline uint32_t lid_hmx_find_valid_gc(const struct htp_lid_hmx_context * hctx, const struct lid_hmx_set * sets,
+ uint32_t gc, uint32_t gc1) {
const struct fastdiv_values * div_n_ch = &hctx->kp->div_n_ch;
const uint32_t n_ch = hctx->L.n_ch;
while (gc < gc1) {
const uint32_t set = fastdiv(gc, div_n_ch);
const uint32_t c = gc - set * n_ch;
- if (c < hctx->nx_sets[set].n_ch) {
+ if (c < sets[set].n_ch) {
return gc;
}
gc++;
@@ -1338,30 +1491,54 @@ static inline uint32_t lid_hmx_find_valid_gc(const struct htp_lid_hmx_context *
return gc1;
}
-static inline uint32_t lid_hmx_q_chunk_push(const struct htp_lid_hmx_context * hctx, dma_queue * dma_q,
- uint8_t * qs, uint32_t qb, uint32_t gc) {
- const struct htp_ops_context * octx = hctx->octx;
- const struct htp_tensor * w = octx->src[2];
- const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
- const uint32_t nh = octx->src[0]->ne[1];
+// Push w rows of [gc0, gc1) into per-HVX wd, one 2D DMA per overlapped set
+static uint32_t lid_hmx_push_w(const struct htp_lid_hmx_context * hctx, dma_queue * dma_q, uint8_t * wd,
+ const struct lid_hmx_set * sets, uint32_t gc0, uint32_t gc1,
+ struct lid_hmx_w_slice w_set[HTP_LID_HMX_MAX_QSETS]) {
+ if (gc0 >= gc1) {
+ return 0;
+ }
+ const struct htp_tensor * w = hctx->octx->src[2];
+ const struct fastdiv_values * div_n_ch = &hctx->kp->div_n_ch;
+ const uint32_t n_ch = hctx->L.n_ch;
+ const uint32_t nh = hctx->octx->src[0]->ne[1];
+ const size_t row_b = hctx->w_row_bytes;
- const uint32_t set = fastdiv(gc, &hctx->kp->div_n_ch);
- const uint32_t c = gc - set * L->n_ch;
- const struct lid_hmx_set * S = &hctx->nx_sets[set];
+ uint32_t n_dma = 0;
+ size_t off = 0;
+ for (uint32_t set = fastdiv(gc0, div_n_ch), set_end = fastdiv(gc1 - 1, div_n_ch); set <= set_end; ++set) {
+ const struct lid_hmx_set S = sets[set];
+ const uint32_t c0 = MAX(gc0, set * n_ch) - set * n_ch;
+ const uint32_t c1 = MIN(MIN(gc1, (set + 1) * n_ch) - set * n_ch, S.n_ch);
+ if (c0 >= c1) {
+ continue;
+ }
- const uint32_t slot = lid_hmx_slot(hctx, qb, set);
- const uint32_t ch = c * 32;
- const uint32_t ta = fastdiv(ch, &hctx->kp->div_n_head);
- const uint32_t tb = fastdiv(MIN(ch + 32, S->nt * nh) - 1, &hctx->kp->div_n_head) + 1;
+ const uint32_t ta = fastdiv(c0 * 32, &hctx->kp->div_n_head);
+ const uint32_t tb = fastdiv(MIN(c1 * 32, S.nt * nh) - 1, &hctx->kp->div_n_head) + 1;
+ const size_t ta_b = (size_t) ta * row_b;
+ const size_t base_off = ta_b & ~(size_t) 127;
+ uint8_t * dst = wd + off;
+
+ w_set[set].ptr = dst;
+ w_set[set].base_off = base_off;
+ dma_queue_push(dma_q, dma_make_data(dst + (ta_b & 127), w->data + S.is * w->nb[3] + (S.t0 + ta) * w->nb[1]),
+ row_b, w->nb[1], row_b, tb - ta);
+ off += hex_round_up((size_t) tb * row_b - base_off, 128);
+ n_dma++;
+ }
+ return n_dma;
+}
- float * wd = hctx->w + slot * (L->size_w / sizeof(float));
- dma_queue_push(dma_q, dma_make_data(wd + ta * nh, w->data + S->is * w->nb[3] + (S->t0 + ta) * w->nb[1]),
- nh * sizeof(float), w->nb[1], nh * sizeof(float), tb - ta);
- return 1 + lid_hmx_push_q(hctx, dma_q, qs, S, c);
+static inline uint32_t lid_hmx_q_chunk_push(const struct htp_lid_hmx_context * hctx, dma_queue * dma_q,
+ uint8_t * qs, uint32_t gc) {
+ const uint32_t set = fastdiv(gc, &hctx->kp->div_n_ch);
+ return lid_hmx_push_q(hctx, dma_q, qs, &hctx->nx_sets[set], gc - set * hctx->L.n_ch);
}
// Stage g share of the next run's Q prep (the DMA queue of the thread is empty here)
static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_context * hctx, const htp_thread_t * th, uint32_t ith, uint32_t nth) {
+ (void) nth;
const struct htp_ops_context * octx = hctx->octx;
const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
@@ -1373,25 +1550,28 @@ static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_c
const uint32_t gc1 = MIN(gc0 + per, b);
const uint32_t qb = hctx->qbuf ^ 1;
+ uint32_t gc_cur = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc0, gc1);
+ if (gc_cur >= gc1) {
+ return;
+ }
+
dma_queue * dma_q = th->dma_q;
+ uint8_t * wd = hctx->w + ith * L->size_w;
uint8_t * qs[2];
qs[0] = hctx->qs + ith * L->size_qs;
qs[1] = qs[0] + 32 * L->size_qs_row;
uint8_t * qh = qs[0] + 2 * 32 * L->size_qs_row;
- uint32_t gc_cur = lid_hmx_find_valid_gc(hctx, gc0, gc1);
- if (gc_cur >= gc1) {
- return;
- }
+ struct lid_hmx_w_slice w_set[HTP_LID_HMX_MAX_QSETS];
+ uint32_t n_dma[2] = {0, 0};
+ n_dma[0] = lid_hmx_push_w(hctx, dma_q, wd, hctx->nx_sets, gc_cur, gc1, w_set) +
+ lid_hmx_q_chunk_push(hctx, dma_q, qs[0], gc_cur);
- const uint32_t gc_next = lid_hmx_find_valid_gc(hctx, gc_cur + 1, gc1);
+ const uint32_t gc_next = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_cur + 1, gc1);
uint32_t gc_prefetch = gc1;
-
- uint32_t n_dma[2] = {0, 0};
- n_dma[0] = lid_hmx_q_chunk_push(hctx, dma_q, qs[0], qb, gc_cur);
if (gc_next < gc1) {
- n_dma[1] = lid_hmx_q_chunk_push(hctx, dma_q, qs[1], qb, gc_next);
- gc_prefetch = lid_hmx_find_valid_gc(hctx, gc_next + 1, gc1);
+ n_dma[1] = lid_hmx_q_chunk_push(hctx, dma_q, qs[1], gc_next);
+ gc_prefetch = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_next + 1, gc1);
}
uint32_t slot = 0;
@@ -1405,17 +1585,17 @@ static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_c
const struct lid_hmx_set * S = &hctx->nx_sets[set];
const uint32_t qslot = lid_hmx_slot(hctx, qb, set);
- lid_hmx_q_scg(hctx, qslot, S, c);
- lid_hmx_q_tiles(hctx, qslot, S, c, qs[slot], qh);
+ hctx->q_scg(hctx, qslot, S, c, w_set[set]);
+ hctx->q_tiles(hctx, qslot, S, c, qs[slot], qh);
if (gc_prefetch < gc1) {
- n_dma[slot] = lid_hmx_q_chunk_push(hctx, dma_q, qs[slot], qb, gc_prefetch);
- gc_prefetch = lid_hmx_find_valid_gc(hctx, gc_prefetch + 1, gc1);
+ n_dma[slot] = lid_hmx_q_chunk_push(hctx, dma_q, qs[slot], gc_prefetch);
+ gc_prefetch = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_prefetch + 1, gc1);
} else {
n_dma[slot] = 0;
}
- gc_cur = lid_hmx_find_valid_gc(hctx, gc_cur + 1, gc1);
+ gc_cur = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_cur + 1, gc1);
slot ^= 1;
}
}
@@ -1425,12 +1605,8 @@ static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_c
static void lid_hmx_qprep_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_lid_hmx_context * hctx = (struct htp_lid_hmx_context *) data;
const struct htp_ops_context * octx = hctx->octx;
- const struct htp_tensor * q = octx->src[0];
- const struct htp_tensor * w = octx->src[2];
const struct htp_lid_hmx_vtcm_layout * L = &hctx->L;
- const uint32_t nh = q->ne[1];
-
struct htp_thread_trace * tr = th->trace;
dma_queue * dma_q = th->dma_q;
@@ -1438,32 +1614,16 @@ static void lid_hmx_qprep_thread(const htp_thread_t * th, unsigned int nth, unsi
const uint32_t per = fastdiv(n_tot + octx->n_hvx - 1, &octx->n_hvx_div);
const uint32_t gc0 = MIN(ith * per, n_tot);
const uint32_t gc1 = MIN(gc0 + per, n_tot);
+ const uint32_t first = lid_hmx_find_valid_gc(hctx, hctx->sets, gc0, gc1);
+ uint8_t * wd = hctx->w + ith * L->size_w;
uint8_t * qs = hctx->qs + ith * L->size_qs;
uint8_t * qh = qs + 2 * 32 * L->size_qs_row;
// all input DMAs in flight at once: w of the sets, Q of the first channel tile, then K and mask of block 0
- uint32_t n_dma = 0;
- uint32_t first = gc1;
+ struct lid_hmx_w_slice w_set[HTP_LID_HMX_MAX_QSETS];
const struct fastdiv_values * div_n_ch = &hctx->kp->div_n_ch;
- for (uint32_t set = fastdiv(gc0, div_n_ch); gc0 < gc1 && set <= fastdiv(gc1 - 1, div_n_ch); ++set) {
- const struct lid_hmx_set S = hctx->sets[set];
-
- const uint32_t c0 = MAX(gc0, set * L->n_ch) - set * L->n_ch;
- const uint32_t c1 = MIN(MIN(gc1, (set + 1) * L->n_ch) - set * L->n_ch, S.n_ch);
- if (c0 >= c1) {
- continue;
- }
- first = MIN(first, set * L->n_ch + c0);
-
- const uint32_t ta = fastdiv(c0 * 32, &hctx->kp->div_n_head);
- const uint32_t tb = fastdiv(MIN(c1 * 32, S.nt * nh) - 1, &hctx->kp->div_n_head) + 1;
- float * wd = hctx->w + lid_hmx_slot(hctx, hctx->qbuf, set) * (L->size_w / sizeof(float));
- dma_queue_push(dma_q, dma_make_data(wd + ta * nh, w->data + S.is * w->nb[3] + (S.t0 + ta) * w->nb[1]),
- nh * sizeof(float), w->nb[1], nh * sizeof(float), tb - ta);
- n_dma++;
- }
-
+ uint32_t n_dma = lid_hmx_push_w(hctx, dma_q, wd, hctx->sets, first, gc1, w_set);
if (first < gc1) {
const uint32_t set = fastdiv(first, div_n_ch);
const struct lid_hmx_set S = hctx->sets[set];
@@ -1494,13 +1654,13 @@ static void lid_hmx_qprep_thread(const htp_thread_t * th, unsigned int nth, unsi
// scales and G while the Q rows land
const uint32_t slot = lid_hmx_slot(hctx, hctx->qbuf, set);
- lid_hmx_q_scg(hctx, slot, &S, c);
+ hctx->q_scg(hctx, slot, &S, c, w_set[set]);
for (uint32_t i = 0; i < n_q; ++i) {
dma_queue_pop(dma_q);
}
- lid_hmx_q_tiles(hctx, slot, &S, c, qs, qh);
+ hctx->q_tiles(hctx, slot, &S, c, qs, qh);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) gc0);
@@ -1525,24 +1685,35 @@ static void lid_hmx_first_thread(const htp_thread_t * th, unsigned int nth, unsi
static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kernel_params * kparams) {
const struct htp_tensor * q = octx->src[0];
+ const struct htp_tensor * k = octx->src[1];
+ const struct htp_tensor * w = octx->src[2];
const uint32_t D = q->ne[0];
const uint32_t n_head = q->ne[1];
const uint32_t n_stream = q->ne[3];
const uint32_t n_hvx = kparams->n_hvx;
const uint32_t n_qsets = kparams->n_qsets;
+ const bool q_f16 = (q->type == HTP_TYPE_F16);
+ const bool w_f16 = (w->type == HTP_TYPE_F16);
struct htp_lid_hmx_context hctx;
memset(&hctx, 0, sizeof(hctx));
- hctx.octx = octx;
- hctx.kp = kparams;
- hctx.Bc = kparams->kv_block;
- hctx.kv_seg = kparams->kv_seg;
- hctx.n_tile = kparams->n_tokens_tile;
- hctx.n_tt = kparams->n_tt;
- hctx.n_qsets = n_qsets;
+ hctx.octx = octx;
+ hctx.kp = kparams;
+ hctx.Bc = kparams->kv_block;
+ hctx.kv_seg = kparams->kv_seg;
+ hctx.n_tile = kparams->n_tokens_tile;
+ hctx.n_tt = kparams->n_tt;
+ hctx.q_row_bytes = D * (q_f16 ? sizeof(__fp16) : sizeof(float));
+ hctx.w_row_bytes = n_head * (w_f16 ? sizeof(__fp16) : sizeof(float));
+ hctx.q_scg = w_f16 ? lid_hmx_q_scg_f16 : lid_hmx_q_scg_f32;
+ hctx.q_tiles = q_f16 ? lid_hmx_q_tiles_f16 : lid_hmx_q_tiles_f32;
+ hctx.n_qsets = n_qsets;
htp_lid_hmx_vtcm_layout_build(&hctx.L, D, n_head, hctx.n_tile, hctx.Bc, n_qsets * kparams->n_qbuf, n_hvx,
kparams->k_row_size);
+ hctx.prep_k = k->type == HTP_TYPE_Q8_0 ? (hctx.L.n_dot == 4 ? lid_hmx_prep_k_q8_0_d128 : lid_hmx_prep_k_q8_0) :
+ k->type == HTP_TYPE_Q4_0 ? lid_hmx_prep_k_q4_0 :
+ k->type == HTP_TYPE_F32 ? lid_hmx_prep_k_f32 : lid_hmx_prep_k_f16;
uint8_t * const base = octx->ctx->vtcm_base;
const struct htp_lid_hmx_vtcm_layout * L = &hctx.L;
@@ -1552,7 +1723,7 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne
hctx.sc = VTCM_LAYOUT_PTR(uint8_t, base, L->off_sc);
hctx.sc_id = VTCM_LAYOUT_PTR(uint8_t, base, L->off_sc_id);
hctx.s = VTCM_LAYOUT_PTR(__fp16, base, L->off_s);
- hctx.w = VTCM_LAYOUT_PTR(float, base, L->off_w);
+ hctx.w = VTCM_LAYOUT_PTR(uint8_t, base, L->off_w);
hctx.qs = VTCM_LAYOUT_PTR(uint8_t, base, L->off_qs);
for (int i = 0; i < 2; i++) {
hctx.k_raw[i] = VTCM_LAYOUT_PTR(uint8_t, base, L->off_k_raw[i]);
@@ -1591,6 +1762,7 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne
const uint32_t per = fastdiv(n_tot + n_hvx - 1, &octx->n_hvx_div);
hctx.n_qthr = (n_tot + per - 1) / per;
+ hctx.per_k0 = 0;
hctx.g = -1;
const bool q_ready = hctx.nx_on;
@@ -1599,6 +1771,10 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne
hctx.nx_on = false;
work_queue_run(octx->ctx->hvx_queue, lid_hmx_first_thread, &hctx, n_hvx);
} else {
+ if (hctx.n_qthr < n_hvx) {
+ const uint32_t n_rows0 = MIN(hctx.Bc, hctx.n_run * hctx.kv_seg);
+ hctx.per_k0 = hex_round_up((n_rows0 + n_hvx - hctx.n_qthr - 1) / (n_hvx - hctx.n_qthr), 2);
+ }
work_queue_run(octx->ctx->hvx_queue, lid_hmx_qprep_thread, &hctx, n_hvx);
}
@@ -1661,6 +1837,8 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne
int op_lightning_indexer(struct htp_ops_context * octx) {
const struct htp_tensor * q = octx->src[0];
+ const struct htp_tensor * k = octx->src[1];
+ const struct htp_tensor * w = octx->src[2];
const struct htp_tensor * m = octx->src[3];
// no multi-device split yet, device 0 does all the work
@@ -1682,14 +1860,25 @@ int op_lightning_indexer(struct htp_ops_context * octx) {
return lid_hmx_run(octx, kparams);
}
+ const bool q_f16 = (q->type == HTP_TYPE_F16);
+ const bool w_f16 = (w->type == HTP_TYPE_F16);
+
struct htp_lid_context lctx;
- lctx.octx = octx;
- lctx.kp = kparams;
- lctx.n_blocks = kparams->n_kv_blocks;
- lctx.blocks_per_hvx = kparams->blocks_per_hvx;
+ lctx.octx = octx;
+ lctx.kp = kparams;
+ lctx.n_blocks = kparams->n_kv_blocks;
+ lctx.blocks_per_hvx = kparams->blocks_per_hvx;
+ lctx.q_row_bytes = q->ne[0] * (q_f16 ? sizeof(__fp16) : sizeof(float));
+ lctx.w_row_bytes = q->ne[1] * (w_f16 ? sizeof(__fp16) : sizeof(float));
+ lctx.prep_q = q_f16 ? lid_prep_q_f16 : lid_prep_q_f32;
+ lctx.prep_w = w_f16 ? lid_prep_w_f16 : lid_prep_w_f32;
htp_lid_vtcm_layout_build(&lctx.L, q->ne[0], q->ne[1], kparams->n_tokens_tile, kparams->n_hvx, kparams->k_row_size);
+ lctx.prep_k = k->type == HTP_TYPE_Q8_0 ? (lid_q8_0_gather_ok(lctx.L.size_k_raw_row, q->ne[0]) ? lid_prep_k_block_q8_0_gather : lid_prep_k_block_q8_0) :
+ k->type == HTP_TYPE_Q4_0 ? lid_prep_k_block_q4_0 :
+ k->type == HTP_TYPE_F32 ? lid_prep_k_block_f32 : lid_prep_k_block_f16;
+
uint8_t * const base = octx->ctx->vtcm_base;
lctx.spad_q = VTCM_LAYOUT_PTR(uint8_t, base, lctx.L.off_q);
diff --git a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h
index 14b3503f6..4ed5bb5c7 100644
--- a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h
+++ b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h
@@ -18,7 +18,7 @@ extern "C" {
#define HTP_LID_HMX_TOKENS_MAX 512 // HMX can keep more tokens; VTCM decides
#define HTP_LID_HMX_KV_BLOCK_MAX 2048
#define HTP_LID_HMX_MAX_QSETS 8 // streams in one HMX pipeline run
-#define HTP_LID_N_BUF 4 // K / mask / output buffers per thread (two blocks computed, two in flight)
+#define HTP_LID_N_BUF 4 // K / mask / output buffers per HVX (two blocks computed, two in flight)
#ifndef HMX_FP16_TILE_N_COLS
#define HMX_FP16_TILE_N_COLS 32
@@ -72,15 +72,15 @@ struct htp_lid_vtcm_layout {
size_t off_o;
size_t size_q_row; // f16 Q row, padded
- size_t size_qs_row; // f32 Q staging row, padded
+ size_t size_qs_row; // f32/f16 Q staging row, padded
size_t size_k_row; // f16 K row, padded
size_t size_k_raw_row;
size_t size_m_row; // f16 mask row of one kv block, padded
size_t size_o_row; // f32 output row of one kv block, padded
- size_t size_qs; // per thread
+ size_t size_qs; // per HVX
size_t size_k_buf; // one K buffer
- size_t size_kt; // per thread: two transposed K blocks, two 64x64 scratch tiles, Q8_0 block scales
+ size_t size_kt; // per HVX: two transposed K blocks, two 64x64 scratch tiles, Q8_0 block scales
size_t size_m_buf; // one mask buffer
size_t size_o_buf; // one output buffer
@@ -122,29 +122,29 @@ static inline size_t htp_lid_compute_vtcm_usage(size_t D, size_t n_head, size_t
// HMX path. K is the activation (kv rows), Q the weights (one output channel per (token, head)).
// mm1: S = relu(K Q^T) * |w| per channel (HMX convert scale + pos clamp)
// mm2: O = S G, G[(t,h), t] = sign(w[t,h]). O is [kv, token], f16.
-// Q weights, G, scales and w are per Q set (one per stream when all tokens fit one tile).
+// Q weights, G and scales are per Q set (one per stream when all tokens fit one tile).
struct htp_lid_hmx_vtcm_layout {
size_t off_qw; // Q weight tiles [n_qsets][n_ch][n_dot]
size_t off_g; // G weight tiles [n_qsets][n_ch]
size_t off_sc; // per channel scales, 256 bytes per channel tile, [n_qsets][n_ch]
size_t off_sc_id; // identity scales
size_t off_s; // S tiles of one block and token tile, [n_rt][n_sg]
- size_t off_w; // w of the token tile, [n_qsets][n_tok][n_head] f32
- size_t off_qs; // per thread: f32 and f16 staging for 32 Q rows, gather scratch
+ size_t off_w; // per HVX: w staging for its channel tiles
+ size_t off_qs; // per HVX: f32/f16 and f16 staging for 32 Q rows, gather scratch
size_t off_k_raw[2]; // K rows, [Bc][size_k_row]
size_t off_k_t[2]; // K tiles [n_rt][n_dot]
size_t off_o[2]; // O tiles [n_rt][n_u]
size_t off_m[4]; // mask rows [n_tok][size_m_row]
size_t off_out[2]; // f32 output rows [n_tok][size_o_row]
- size_t size_qs_row; // f32 Q row, padded
+ size_t size_qs_row; // f32/f16 Q row, padded
size_t size_qh_row; // f16 Q row, padded
size_t size_k_row; // f16 K row, padded
size_t size_k_raw_row;
size_t size_m_row;
size_t size_o_row;
- size_t size_qs; // per thread
- size_t size_w; // per Q set
+ size_t size_qs; // per HVX
+ size_t size_w; // per HVX
uint32_t n_ch; // channel tiles: ceil(n_tok * n_head / 32)
uint32_t n_u; // token tiles: ceil(n_tok / 32)
@@ -169,8 +169,9 @@ static inline void htp_lid_hmx_vtcm_layout_build(struct htp_lid_hmx_vtcm_layout
L->size_k_raw_row = L->size_k_row > hex_round_up(k_row_size, 128) ? L->size_k_row : hex_round_up(k_row_size, 128);
L->size_m_row = hex_round_up(Bc * sizeof(uint16_t), 128);
L->size_o_row = hex_round_up(Bc * sizeof(float), 128);
+ const size_t w_tiles = (n_qsets * L->n_ch + n_hvx - 1) / n_hvx;
L->size_qs = 2 * 32 * L->size_qs_row + 32 * L->size_qh_row + hex_round_up(Bc / 64 * 128, 128);
- L->size_w = hex_round_up(n_tok * n_head * sizeof(float), 128);
+ L->size_w = w_tiles * 128 + 2 * hex_round_up(n_head * sizeof(float), 128) + 256;
const size_t tile = HMX_FP16_TILE_SIZE;
@@ -185,7 +186,7 @@ static inline void htp_lid_hmx_vtcm_layout_build(struct htp_lid_hmx_vtcm_layout
VTCM_LAYOUT_ALLOC(off, off_o[1], (size_t) L->n_rt * L->n_u * tile);
VTCM_LAYOUT_ALLOC(off, off_sc, n_qsets * L->n_ch * 256);
VTCM_LAYOUT_ALLOC(off, off_sc_id, 256);
- VTCM_LAYOUT_ALLOC(off, off_w, n_qsets * L->size_w);
+ VTCM_LAYOUT_ALLOC(off, off_w, n_hvx * L->size_w);
VTCM_LAYOUT_ALLOC(off, off_qs, n_hvx * L->size_qs);
for (int i = 0; i < 2; i++) {
VTCM_LAYOUT_ALLOC(off, off_k_raw[i], Bc * L->size_k_raw_row);
diff --git a/ggml/src/ggml-hexagon/htp/main.c b/ggml/src/ggml-hexagon/htp/main.c
index 712e898d2..a944d7c51 100644
--- a/ggml/src/ggml-hexagon/htp/main.c
+++ b/ggml/src/ggml-hexagon/htp/main.c
@@ -1,8 +1,3 @@
-#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <AEEStdErr.h>
@@ -22,6 +17,7 @@
#include "htp-thread.h"
#include "hex-utils.h"
+#include "dma-proxy.h"
#include "dma-queue.h"
#include "hmx-queue.h"
@@ -29,8 +25,8 @@
#include "ggml-common.h"
#include "hex-bitmap.h"
#include "htp-ctx.h"
-#include "htp-dcache.h"
#include "htp-ops.h"
+#include "htp-vtcm.h"
#include "htp_iface.h"
#include "work-queue.h"
#include "htp-trace.h"
@@ -38,9 +34,10 @@
#include "dsv4-hc-ops.h"
#include "htp-fence.h"
+#define DMA_PROXY_CAPACITY 64
+#define DMA_PROXY_STACK_SIZE 16384
#define HMX_QUEUE_CAPACITY 128
#define HMX_QUEUE_STACK_SIZE 16384
-#define WORK_QUEUE_CAPACITY 16
#define WORK_QUEUE_STACK_SIZE 16384
#define MAIN_THREAD_STACK_SIZE 32768
@@ -348,14 +345,14 @@ static int vtcm_alloc(struct htp_context * ctx, uint64_t size_override) {
}
void * vtcm_ptr;
- if (HAP_compute_res_attr_get_vtcm_ptr_v2(&attr, &vtcm_ptr, &vtcm_size) != 0) {
+ if (HAP_compute_res_attr_get_vtcm_ptr_v2(&attr, &vtcm_ptr, &vtcm_size) != 0 || vtcm_size < 2 * HTP_VTCM_GUARD_SIZE) {
HAP_compute_res_release(rctx);
FARF(ERROR, "failed to allocate %zu bytes VTCM (new)\n", ctx->vtcm_size);
return AEE_ENOMEMORY;
}
ctx->vtcm_base = (uint8_t *) vtcm_ptr;
- ctx->vtcm_size = vtcm_size;
+ ctx->vtcm_size = htp_vtcm_usable_size(vtcm_size);
ctx->vtcm_rctx = rctx;
atomic_store(&ctx->vtcm_valid, false);
atomic_store(&ctx->vtcm_needs_release, false);
@@ -502,8 +499,8 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp
if (n_hvx > HTP_MAX_NHVX) {
n_hvx = HTP_MAX_NHVX;
}
- if (n_hvx > hw_nth - 1) {
- n_hvx = hw_nth - 1;
+ if (n_hvx > hw_nth - 2) {
+ n_hvx = hw_nth - 2;
}
uint32_t n_threads = hw_nth;
@@ -525,7 +522,7 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp
// 3. work_queue
size_t wq_align = work_queue_alignof();
size_t offset_wq = hex_align_up(offset, wq_align);
- size_t size_wq = work_queue_sizeof(n_hvx, WORK_QUEUE_CAPACITY, WORK_QUEUE_STACK_SIZE);
+ size_t size_wq = work_queue_sizeof(n_hvx, WORK_QUEUE_STACK_SIZE);
offset = offset_wq + size_wq;
// 4. dma_queue
@@ -548,6 +545,12 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp
offset = offset_hmx + size_hmx;
}
+ // 6. dma_proxy
+ size_t dp_align = dma_proxy_alignof();
+ size_t offset_dma_proxy = hex_align_up(offset, dp_align);
+ size_t size_dma_proxy = dma_proxy_sizeof(DMA_PROXY_CAPACITY, DMA_PROXY_STACK_SIZE);
+ offset = offset_dma_proxy + size_dma_proxy;
+
size_t footprint = hex_align_up(offset, 128);
void * block = memalign(4096, footprint);
@@ -610,6 +613,9 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp
#if (__HEXAGON_ARCH__ >= 79)
HAP_set_dcvs_v3_protected_bus_corners(&request, 1);
+ if (power_mode >= HTP_POWER_MODE_HIGH_PERFORMANCE) {
+ HAP_set_ddr_perf_mode(&request, 1);
+ }
#endif
if ((err = HAP_power_set((void *) ctx, &request)) != 0) {
htp_iface_stop(handle);
@@ -677,13 +683,15 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp
dma_ptr_curr += size_dma_q;
}
+ ctx->main_th = (htp_thread_t) { 0, ctx->dma[0], &ctx->trace[0] };
+
ctx->ddr_spad_size = HTP_DDR_SPAD_SIZE;
ctx->ddr_spad_base = memalign(128, ctx->ddr_spad_size);
htp_thread_reset();
void * wq_ptr = (void *) ((uintptr_t) block + offset_wq);
- ctx->hvx_queue = work_queue_init(wq_ptr, n_hvx, WORK_QUEUE_CAPACITY, WORK_QUEUE_STACK_SIZE, ctx->dma, ctx->trace);
+ ctx->hvx_queue = work_queue_init(wq_ptr, n_hvx, WORK_QUEUE_STACK_SIZE, ctx->dma, ctx->trace);
ctx->hmx_enabled = n_hmx;
ctx->hmx_queue = NULL;
@@ -693,6 +701,9 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp
}
FARF(HIGH, "HMX %s (n_hmx=%d)", ctx->hmx_enabled ? "enabled" : "disabled", n_hmx);
+ void * dp_ptr = (void *) ((uintptr_t) block + offset_dma_proxy);
+ ctx->dma_proxy = dma_proxy_init(dp_ptr, DMA_PROXY_CAPACITY, DMA_PROXY_STACK_SIZE, ctx->dma, ctx->trace);
+
ctx->main_stack = NULL;
ctx->main_thread = 0;
atomic_store(&ctx->killed, false);
@@ -744,16 +755,21 @@ AEEResult htp_iface_stop(remote_handle64 handle) {
work_queue_free(ctx->hvx_queue);
- for (int i = 0; i < ctx->n_threads; i++) {
- dma_queue_free(ctx->dma[i]);
- }
-
if (ctx->hmx_queue) {
hmx_queue_free(ctx->hmx_queue);
ctx->hmx_queue = NULL;
}
ctx->hmx_enabled = false;
+ if (ctx->dma_proxy) {
+ dma_proxy_free(ctx->dma_proxy);
+ ctx->dma_proxy = NULL;
+ }
+
+ for (int i = 0; i < ctx->n_threads; i++) {
+ dma_queue_free(ctx->dma[i]);
+ }
+
vtcm_free(ctx);
if (ctx->ddr_spad_base) {
@@ -762,6 +778,18 @@ AEEResult htp_iface_stop(remote_handle64 handle) {
ctx->ddr_spad_size = 0;
}
+#if (__HEXAGON_ARCH__ >= 79)
+ {
+ HAP_power_request_t request;
+ memset(&request, 0, sizeof(request));
+ request.type = HAP_power_set_DCVS_v3;
+ request.dcvs_v3.set_dcvs_enable = TRUE;
+ request.dcvs_v3.dcvs_enable = TRUE;
+ HAP_set_ddr_perf_mode(&request, 0);
+ HAP_power_set((void *) ctx, &request);
+ }
+#endif
+
free(ctx);
h->ctx = NULL;
@@ -787,8 +815,8 @@ AEEResult htp_iface_hwinfo(remote_handle64 handle, uint32_t * n_threads, uint32_
if (n_hvx_val > HTP_MAX_NHVX) {
n_hvx_val = HTP_MAX_NHVX;
}
- if (n_hvx_val > n_threads_val - 1) {
- n_hvx_val = n_threads_val - 1;
+ if (n_hvx_val > n_threads_val - 2) {
+ n_hvx_val = n_threads_val - 2;
}
*n_threads = n_threads_val;
@@ -858,8 +886,6 @@ static int op_fence(struct htp_ops_context * octx) {
atomic_uint * sync_fence = (atomic_uint *) (uintptr_t) sync->data;
if (mode == 1) {
- htp_dcache_flush_dirty_ranges(ctx);
-
htp_mdev_group_barrier(octx);
if (ctx->mdev.idx == 0) {
@@ -932,6 +958,7 @@ static int execute_op(struct htp_ops_context * octx) {
return op_matmul_id_nx(octx);
case HTP_OP_MUL_MAT_NX:
+ case HTP_OP_MUL_MAT_NX_GLU:
return op_matmul_nx(octx);
case HTP_OP_MUL:
@@ -1273,8 +1300,6 @@ static int proc_op_req(struct htp_ops_context * octx, struct htp_buf_desc * bufs
src->ne[0], src->ne[1], src->ne[2], src->ne[3]);
}
- htp_dcache_flush_dirty_tensors(octx->ctx, octx->src, HTP_OP_MAX_INPUTS);
-
// Prep output tensors
for (uint32_t i = 0; i < HTP_OP_MAX_OUTPUTS; i++) {
uint16_t dst_idx = op->dst[i];
@@ -1289,17 +1314,12 @@ static int proc_op_req(struct htp_ops_context * octx, struct htp_buf_desc * bufs
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]);
}
- htp_dcache_mark_dirty_tensors(octx->ctx, octx->dsts, HTP_OP_MAX_OUTPUTS);
-
htp_mdev_group_barrier(octx);
int status = execute_op(octx);
htp_ops_context_set_status(octx, status);
- octx->src0_spad.src = NULL;
- octx->src1_spad.src = NULL;
- octx->dst_spad.src = NULL;
return octx->status;
}
@@ -1352,7 +1372,6 @@ static void process_opbatch(struct htp_context * ctx, const struct htp_opbatch_r
htp_trace_event_start(&ctx->trace[0], HTP_TRACE_EVT_L2FLUSH, 0);
qurt_mem_cache_clean((qurt_addr_t) 0, 0, QURT_MEM_CACHE_FLUSH_INVALIDATE_ALL, QURT_MEM_DCACHE);
hex_l2fetch_block(ctx, ctx->footprint);
- memset(ctx->dirty_ranges, 0, sizeof(ctx->dirty_ranges));
htp_trace_event_stop(&ctx->trace[0], HTP_TRACE_EVT_L2FLUSH, 0);
htp_trace_event_start(&ctx->trace[0], HTP_TRACE_EVT_BUFF, 0);
@@ -1395,6 +1414,7 @@ static void process_opbatch(struct htp_context * ctx, const struct htp_opbatch_r
}
}
+ dma_proxy_flush(ctx->dma_proxy);
if (ctx->hmx_queue) {
hmx_queue_suspend(ctx->hmx_queue);
hmx_queue_flush(ctx->hmx_queue);
diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.c b/ggml/src/ggml-hexagon/htp/matmul-ops.c
index ea05937a5..1dc0a9332 100644
--- a/ggml/src/ggml-hexagon/htp/matmul-ops.c
+++ b/ggml/src/ggml-hexagon/htp/matmul-ops.c
@@ -1,8 +1,3 @@
-#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <HAP_compute_res.h>
@@ -27,7 +22,7 @@
#include "htp-vtcm.h"
typedef struct {
- float *dst;
+ dma_addr_t dst_dma_addr;
dma_addr_t bias_addr;
size_t bias_bytes;
dma_addr_t act_dma_addr;
@@ -37,7 +32,9 @@ typedef struct {
int k;
int n;
int act_stride;
- uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
+ 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;
@@ -61,90 +58,12 @@ typedef struct {
int r3;
struct fastdiv_values div_r2;
struct fastdiv_values div_r3;
+ int32_t kernel_type;
+ int hmx_n_groups;
+ struct fastdiv_values div_hmx_n_groups;
+ struct fastdiv_values div_n_k_tiles;
} hmx_mm_batched_params_t;
-static bool htp_matmul_has_extended_weight(const struct htp_ops_context * octx, uint32_t n_weights) {
- for (uint32_t i = 0; i < n_weights; ++i) {
- if (htp_tensor_is_extended(octx->src[i])) {
- return true;
- }
- }
- return false;
-}
-
-struct htp_mm_context {
- const char * type;
- struct htp_ops_context * octx;
- const struct htp_tensor * act;
-
- void (*vec_dot_1x1)(const uint32_t n, float * restrict s0,
- const void * restrict vx0,
- const void * restrict vy0);
-
- void (*vec_dot_2x1)(const uint32_t n, float * restrict s0,
- const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0);
-
- void (*vec_dot_2x2)(const uint32_t n, float * restrict s0, float * restrict s1,
- const void * restrict vx0, const void * restrict vx1,
- const void * restrict vy0, const void * restrict vy1);
-
- void (*vec_dot_32x1)(const uint32_t n, float * restrict s,
- const void * restrict vx,
- const void * restrict vy, uint32_t valid_rows,
- const float * restrict sz);
-
- void (*vec_dot_32x2)(const uint32_t n, float * restrict s0, float * restrict s1,
- const void * restrict vx,
- const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows,
- const float * restrict sz0, const float * restrict sz1);
-
- // Precomputed values
- uint32_t src0_nrows_per_hvx;
- uint32_t src0_row_start;
- uint32_t src0_row_end;
- uint32_t src0_row_size_padded;
- uint32_t act_nrows;
- uint32_t cur_m_start;
- uint32_t cur_m_rows;
-
- struct fastdiv_values mm_div_ne12_ne1;
- struct fastdiv_values mm_div_ne1;
- struct fastdiv_values mm_div_r2;
- struct fastdiv_values mm_div_r3;
- struct fastdiv_values mm_div_ne11;
-
- // Precomputed block-parallel quantization values
- uint32_t quant_ib_first[HTP_MAX_NHVX];
- uint32_t quant_ib_last[HTP_MAX_NHVX];
- uint32_t quant_r[HTP_MAX_NHVX];
- uint32_t quant_c[HTP_MAX_NHVX];
- uint32_t n_quant_tasks;
- uint32_t n_quant_rows_per_hvx;
-
- // Fields for scattered mapping & HMX support in MUL_MAT_ID
- const uint32_t * matrix_row_counts;
- const struct mmid_row_mapping * matrix_rows;
- uint32_t mapping_stride;
-
- // Dynamic VTCM pointers allocated sequentially
- uint8_t * vtcm_src0;
- uint8_t * vtcm_act;
- uint8_t * vtcm_bias;
- uint8_t * vtcm_dst;
- uint8_t * vtcm_act_raw;
-
- // Cached strides
- uint32_t vtcm_src0_stride;
- uint32_t vtcm_act_stride;
- uint32_t vtcm_act_raw_stride;
-
- // Cached thread offsets/sizes
- uint32_t vtcm_src0_size_per_hvx;
- uint32_t vtcm_act_size_per_hvx;
- uint32_t vtcm_dst_size_per_hvx;
-};
-
static int htp_mm_init_context(
struct htp_ops_context * octx,
const struct htp_mm_kernel_params * kparams
@@ -210,53 +129,48 @@ static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct
iq2xxs_lut_copy(base + L->off_lut);
}
-#define htp_matmul_tensors_preamble \
- const struct htp_tensor * restrict src0 = octx->src[0]; \
- const struct htp_tensor * restrict src1 = octx->src[1]; \
- const struct htp_tensor * restrict src2 = octx->src[2]; \
- const struct htp_tensor * restrict dst = octx->dst; \
- const struct htp_tensor * restrict act = src1; \
- \
- const uint32_t ne00 = src0->ne[0]; \
- const uint32_t ne01 = src0->ne[1]; \
- const uint32_t ne02 = src0->ne[2]; \
- const uint32_t ne03 = src0->ne[3]; \
- \
- const uint32_t ne10 = src1->ne[0]; \
- const uint32_t ne11 = src1->ne[1]; \
- const uint32_t ne12 = src1->ne[2]; \
- const uint32_t ne13 = src1->ne[3]; \
- \
- const uint32_t ne20 = src2 ? src2->ne[0] : 0; \
- const uint32_t ne21 = src2 ? src2->ne[1] : 0; \
- const uint32_t ne22 = src2 ? src2->ne[2] : 0; \
- const uint32_t ne23 = src2 ? src2->ne[3] : 0; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb00 = src0->nb[0]; \
- const uint32_t nb01 = src0->nb[1]; \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t nb10 = src1->nb[0]; \
- const uint32_t nb11 = src1->nb[1]; \
- const uint32_t nb12 = src1->nb[2]; \
- const uint32_t nb13 = src1->nb[3]; \
- \
- const uint32_t nb0 = dst->nb[0]; \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
-
-#define htp_matmul_preamble \
- struct htp_mm_context * mmctx = data; \
- struct htp_ops_context * octx = mmctx->octx; \
- dma_queue * dma_q = th->dma_q; \
- uint32_t src0_nrows_per_hvx = mmctx->src0_nrows_per_hvx; \
+#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->src[2]; \
+ 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];
+
+#define htp_matmul_preamble \
+ struct htp_mm_context * mmctx = data; \
+ struct htp_ops_context * octx = mmctx->octx; \
+ dma_queue * __attribute__((unused)) dma_q = th->dma_q; \
+ uint32_t __attribute__((unused)) src0_nrows_per_hvx = mmctx->src0_nrows_per_hvx; \
htp_matmul_tensors_preamble;
@@ -265,12 +179,90 @@ static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct
// hvx kernels first: the HMX Q6_K dequantizer reuses unpack_q6_k_group from there
#include "hvx-mm-kernels-tiled.h"
#include "hvx-mm-kernels-float.h"
-#include "hmx-mm-kernels-tiled.h"
+#include "hmx-mm-kernels-tiled-fp.h"
+#include "hmx-mm-kernels-tiled-int.h"
+
+struct htp_mm_context {
+ const char * type;
+ struct htp_ops_context * octx;
+ const struct htp_tensor * act;
+ const int32_t * ids_data;
+
+ void (*vec_dot_1x1)(const uint32_t n, void * restrict s0,
+ const void * restrict vx0,
+ const void * restrict vy0, hvx_flat_store_1x1_fn_t store_1x1);
+
+ void (*vec_dot_2x1)(const uint32_t n, void * restrict s0,
+ const void * restrict vx0, const void * restrict vx1,
+ const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1);
+
+ void (*vec_dot_2x2)(const uint32_t n, void * restrict s0, void * restrict s1,
+ const void * restrict vx0, const void * restrict vx1,
+ const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1);
+
+ void (*vec_dot_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);
+
+ void (*vec_dot_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);
+
+ hvx_tiled_store_row_fn_t store_row;
+ hvx_flat_store_1x1_fn_t flat_store_1x1;
+ hvx_flat_store_2x1_fn_t flat_store_2x1;
+
+ // Precomputed values
+ uint32_t src0_nrows_per_hvx;
+ uint32_t src0_row_start;
+ uint32_t src0_row_end;
+ uint32_t src0_row_size_padded;
+ uint32_t act_nrows;
+ uint32_t cur_m_start;
+ uint32_t cur_m_rows;
+
+ struct fastdiv_values mm_div_ne12_ne1;
+ struct fastdiv_values mm_div_ne1;
+ struct fastdiv_values mm_div_r2;
+ struct fastdiv_values mm_div_r3;
+ struct fastdiv_values mm_div_ne11;
+
+ // Precomputed block-parallel quantization values
+ uint32_t quant_ib_first[HTP_MAX_NHVX];
+ uint32_t quant_ib_last[HTP_MAX_NHVX];
+ uint32_t quant_r[HTP_MAX_NHVX];
+ uint32_t quant_c[HTP_MAX_NHVX];
+ uint32_t n_quant_tasks;
+ uint32_t n_quant_rows_per_hvx;
+
+ // Fields for scattered mapping & HMX support in MUL_MAT_ID
+ const uint32_t * matrix_row_counts;
+ const struct mmid_row_mapping * matrix_rows;
+ uint32_t mapping_stride;
+
+ // Dynamic VTCM pointers allocated sequentially
+ uint8_t * vtcm_src0;
+ uint8_t * vtcm_act;
+ uint8_t * vtcm_bias;
+ uint8_t * vtcm_dst;
+ uint8_t * vtcm_act_raw;
+
+ // Cached strides
+ uint32_t vtcm_src0_stride;
+ uint32_t vtcm_act_stride;
+ uint32_t vtcm_act_raw_stride;
+
+ // Cached per-HVX VTCM sizes
+ uint32_t vtcm_src0_size_per_hvx;
+ uint32_t vtcm_act_size_per_hvx;
+ uint32_t vtcm_dst_size_per_hvx;
+};
static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
htp_matmul_preamble;
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start;
const uint32_t act_nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13);
const uint32_t cur_m_start = mmctx->cur_m_start;
@@ -282,11 +274,11 @@ static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
const uint32_t n_prefetch = kparams->n_prefetch;
assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
+ (void) n_prefetch;
const size_t dst_row_size = nb1;
- const size_t act_row_size = nb11;
const size_t act_stride = mmctx->vtcm_act_stride;
- const size_t src2_stride = src2 ? ((src2->ne[1] == 1) ? 0 : src2->nb[1]) : 0;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
@@ -294,74 +286,55 @@ static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const dma_addr_t src0_row = src0->data;
- const uint32_t tile_size = htp_tensor_get_tile_size(src0->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type);
uint32_t tile_row_stride = n_k_tiles_w * tile_size;
- uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size;
uint32_t ct_start = src0_start_row / 32;
uint32_t ct_end = (src0_end_row + 31) / 32;
- uint32_t push_ct = ct_start;
- if (src0_start_row < src0_end_row) {
- for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned,
- src0_row + push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- }
- }
-
if (src0_start_row >= src0_end_row) {
return;
}
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ct_start * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
+
for (uint32_t ct = ct_start; ct < ct_end; ct++) {
const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
int valid_rows = (int)ne0 - (int)(ct * 32);
valid_rows = MIN(32, MAX(0, valid_rows));
+ const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size;
+ const size_t row_bytes = (size_t) valid_rows * dst_elem_size;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- uint32_t ir1 = 0;
- for (; ir1 + 1 < act_nrows; ir1 += 2) {
- const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (ir1+0) * act_stride);
- const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (ir1+1) * act_stride);
- float * restrict dst_row0 = (float *) (dst->data + ((cur_m_start + ir1+0) * dst_row_size));
- float * restrict dst_row1 = (float *) (dst->data + ((cur_m_start + ir1+1) * dst_row_size));
-
- float * dst_ptr0 = &dst_row0[ct * 32];
- float * dst_ptr1 = &dst_row1[ct * 32];
-
- const float * src2_ptr0 = NULL;
- const float * src2_ptr1 = NULL;
- if (src2) {
- const float * restrict src2_row0 = (const float *) ((const uint8_t *) src2->data + ((cur_m_start + ir1+0) * src2_stride));
- const float * restrict src2_row1 = (const float *) ((const uint8_t *) src2->data + ((cur_m_start + ir1+1) * src2_stride));
- src2_ptr0 = &src2_row0[ct * 32];
- src2_ptr1 = &src2_row1[ct * 32];
+ for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, act_nrows - m0);
+ uint32_t r = 0;
+ for (; r + 1 < m_cnt; r += 2) {
+ const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (m0 + r + 0) * act_stride);
+ const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (m0 + r + 1) * act_stride);
+ void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 128;
+ void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 128;
+ mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL, mmctx->store_row);
}
- mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, src2_ptr0, src2_ptr1);
- }
-
- for (; ir1 < act_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride);
- float * restrict dst_row = (float *) (dst->data + ((cur_m_start + ir1) * dst_row_size));
- float * dst_ptr = &dst_row[ct * 32];
-
- const float * src2_ptr = NULL;
- if (src2) {
- const float * restrict src2_row = (const float *) ((const uint8_t *) src2->data + ((cur_m_start + ir1) * src2_stride));
- src2_ptr = &src2_row[ct * 32];
+ for (; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 128;
+ mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, mmctx->store_row);
}
- mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, src2_ptr);
+ const dma_addr_t dst_addr = dst->data + (dma_addr_t) (cur_m_start + m0) * dst_row_size + ct_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 128, row_bytes, m_cnt);
+ dma_queue_pop(dma_q);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride),
+ if (ct + 1 < ct_end) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ct + 1) * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- push_ct++;
}
}
}
@@ -369,8 +342,6 @@ static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
htp_matmul_preamble;
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start;
-
const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith;
const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end);
@@ -380,9 +351,8 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const uint32_t n_prefetch = kparams->n_prefetch;
assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
- const size_t dst_row_size = nb1;
- const size_t act_row_size = nb11;
- const size_t act_stride = mmctx->vtcm_act_stride;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const uint32_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
uint8_t * vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
@@ -393,10 +363,9 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const dma_addr_t src0_row = src0->data;
const uint8_t * restrict act_col = (const uint8_t *) act_data;
- float * restrict dst_col = (float *) dst->data;
- const uint32_t tile_size = htp_tensor_get_tile_size(src0->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type);
uint32_t tile_row_stride = n_k_tiles_w * tile_size;
@@ -407,14 +376,15 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
uint32_t push_ct = ct_start;
if (src0_start_row < src0_end_row) {
- if (src2) {
- float * vtcm_bias_ptr = (float *) mmctx->vtcm_bias + src0_start_row;
- const dma_addr_t src2_addr = src2->data + src0_start_row * sizeof(float);
+ if (bias) {
+ uint8_t * vtcm_bias_ptr = mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size;
+ const dma_addr_t bias_addr = bias->data + (size_t) src0_start_row * bias_elem_size;
int slice_size = (int)MIN(src0_end_row, ne0) - (int)src0_start_row;
if (slice_size > 0) {
- dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, src2_addr),
- slice_size * sizeof(float), slice_size * sizeof(float), slice_size * sizeof(float), 1);
- dma_queue_pop_nowait(dma_q);
+ const size_t slice_bytes = (size_t) slice_size * bias_elem_size;
+ dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, bias_addr),
+ slice_bytes, slice_bytes, slice_bytes, 1);
+ dma_queue_pop(dma_q);
}
}
for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
@@ -435,7 +405,7 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
valid_rows = MIN(32, MAX(0, valid_rows));
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL);
+ mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, hvx_tiled_store_row_f32_none);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
if (push_ct < ct_end) {
@@ -448,15 +418,24 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
int copy_cnt = (int)MIN(src0_end_row, ne0) - (int)src0_start_row;
if (copy_cnt > 0) {
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct_end);
- if (src2) {
- hvx_add_f32_uuu((uint8_t *) &dst_col[src0_start_row],
- (const uint8_t *) tmp,
- (const uint8_t *) ((const float *) mmctx->vtcm_bias + src0_start_row),
- copy_cnt);
- } else {
- hvx_copy_f32_ua((uint8_t *) &dst_col[src0_start_row], (uint8_t *) tmp, copy_cnt);
+ const hvx_tiled_store_row_fn_t store_row = mmctx->store_row;
+ const uint8_t * bias_in = bias ? (mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size) : NULL;
+ if (bias_in) {
+ for (int c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c);
+ HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c);
+ store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, bias_in + (size_t) c * bias_elem_size);
+ }
+ } else if (dst_elem_size != sizeof(float)) {
+ for (int c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c);
+ HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c);
+ store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, NULL);
+ }
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct_end);
+ dma_sync_write(dma_q, dst->data + (size_t) src0_start_row * dst_elem_size,
+ vtcm_dst_ptr, (size_t) copy_cnt * dst_elem_size);
}
}
@@ -472,6 +451,7 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign
const size_t act_stride = mmctx->vtcm_act_stride;
uint8_t * restrict vtcm_weight_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
struct htp_thread_trace * tr = th->trace;
@@ -484,11 +464,13 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign
if (!src_w || !dst) continue;
dma_queue * dma_q = th->dma_q;
- const uint32_t tile_size = htp_tensor_get_tile_size(src_w->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src_w->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
const uint32_t ne00 = src_w->ne[0];
const uint32_t ne01 = src_w->ne[1];
const size_t dst_row_size = dst->nb[1];
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const hvx_tiled_store_row_fn_t store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float));
const dma_addr_t src_w_row = src_w->data;
const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src_w->type);
@@ -498,8 +480,7 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign
uint32_t src0_start_row = 0;
uint32_t src0_end_row = ne01;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float));
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, can_split ? 32 : 0,
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, 32,
octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
src0_start_row = range.start;
src0_end_row = range.start + range.count;
@@ -516,43 +497,68 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign
uint32_t ct_start = start_row / 32;
uint32_t ct_end = (end_row + 31) / 32;
- uint32_t push_ct = ct_start;
- for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr + d * tile_row_transfer_size_aligned,
- src_w_row + push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- }
-
- for (uint32_t ct = ct_start; ct < ct_end; ct++) {
- const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
- int valid_rows = (int)dst->ne[0] - (int)(ct * 32);
- valid_rows = MIN(32, MAX(0, valid_rows));
+ if (act_nrows == 1) {
+ uint32_t push_ct = ct_start;
+ for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr + d * tile_row_transfer_size_aligned,
+ src_w_row + (dma_addr_t) push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
+ }
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- uint32_t ir1 = 0;
- for (; ir1 + 1 < act_nrows; ir1 += 2) {
- const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (ir1+0) * act_stride);
- const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (ir1+1) * act_stride);
+ for (uint32_t ct = ct_start; ct < ct_end; ct++) {
+ const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
+ int valid_rows = (int)dst->ne[0] - (int)(ct * 32);
+ valid_rows = MIN(32, MAX(0, valid_rows));
- float * restrict dst_row0 = (float *) (dst->data + ((ir1+0) * dst_row_size));
- float * restrict dst_row1 = (float *) (dst->data + ((ir1+1) * dst_row_size));
- float * dst_ptr0 = &dst_row0[ct * 32];
- float * dst_ptr1 = &dst_row1[ct * 32];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size;
+ mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_data, valid_rows, NULL, store_row);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL);
+ if (push_ct < ct_end) {
+ dma_queue_push(dma_q, dma_make_data(w_tile, src_w_row + (dma_addr_t) push_ct * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
+ push_ct++;
+ }
}
+ const size_t copy_bytes = (size_t) (MIN(end_row, dst->ne[0]) - start_row) * dst_elem_size;
+ dma_sync_write(dma_q, dst->data + (size_t) start_row * dst_elem_size, vtcm_dst_ptr, copy_bytes);
+ } else {
+ dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr, src_w_row + (dma_addr_t) ct_start * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- for (; ir1 < act_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride);
- float * restrict dst_row = (float *) (dst->data + (ir1 * dst_row_size));
- float * dst_ptr = &dst_row[ct * 32];
- mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL);
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
+ for (uint32_t ct = ct_start; ct < ct_end; ct++) {
+ const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
+ int valid_rows = (int)dst->ne[0] - (int)(ct * 32);
+ valid_rows = MIN(32, MAX(0, valid_rows));
+ const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size;
+ const size_t row_bytes = (size_t) valid_rows * dst_elem_size;
- if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src_w_row + push_ct * tile_row_stride),
- aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- push_ct++;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
+ for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, act_nrows - m0);
+ uint32_t r = 0;
+ for (; r + 1 < m_cnt; r += 2) {
+ const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (m0 + r + 0) * act_stride);
+ const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (m0 + r + 1) * act_stride);
+ void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 128;
+ void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 128;
+ mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL, store_row);
+ }
+ for (; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 128;
+ mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, store_row);
+ }
+ const dma_addr_t dst_addr = dst->data + (dma_addr_t) m0 * dst_row_size + ct_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 128, row_bytes, m_cnt);
+ dma_queue_pop(dma_q);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
+
+ if (ct + 1 < ct_end) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr, src_w_row + (dma_addr_t) (ct + 1) * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
+ }
}
}
}
@@ -588,21 +594,12 @@ static void hvx_mm_transfer_act_dma(
dma_queue_pop(dma_q);
} else {
const uint32_t ne12_ne1 = act->ne[2] * act->ne[1];
- const bool use_fastdiv = kparams->div_ne12_ne1.mp != 0;
for (uint32_t ir = 0; ir < m_rows; ++ir) {
const uint32_t ir1 = m_start + ir;
- uint32_t i11, i12, i13;
- if (use_fastdiv) {
- i13 = fastdiv(ir1, &kparams->div_ne12_ne1);
- const uint32_t rem = ir1 - i13 * ne12_ne1;
- i12 = fastdiv(rem, &kparams->div_ne1);
- i11 = rem - i12 * act->ne[1];
- } else {
- i13 = ne12_ne1 ? ir1 / ne12_ne1 : 0;
- const uint32_t rem = ir1 - i13 * ne12_ne1;
- i12 = act->ne[1] ? rem / act->ne[1] : 0;
- i11 = rem - i12 * act->ne[1];
- }
+ const uint32_t i13 = fastdiv(ir1, &kparams->div_ne12_ne1);
+ const uint32_t rem = ir1 - i13 * ne12_ne1;
+ const uint32_t i12 = fastdiv(rem, &kparams->div_ne1);
+ const uint32_t i11 = rem - i12 * act->ne[1];
const dma_addr_t row_src = act_base + (i11 * act->nb[1] +
i12 * act->nb[2] +
i13 * act->nb[3]);
@@ -634,7 +631,6 @@ static void hvx_mm_transfer_act_dma(
static void name(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { \
(void) nth; \
struct htp_mm_context * mmctx = data; \
- struct htp_ops_context * octx = mmctx->octx; \
const struct htp_tensor * src = mmctx->act; \
const uint32_t ne0 = src->ne[0]; \
const uint32_t nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : mmctx->act_nrows; \
@@ -663,9 +659,12 @@ static void name(const htp_thread_t * th, unsigned int nth, unsigned int ith, vo
QUANTIZE_IMPL(quantize_f32_q8_0_tiled, "quantize-f32-q8_0_tiled", quantize_f32_q8_0_tiled_kernel, htp_mm_q8_0_tiled_row_size(ne0))
QUANTIZE_IMPL(quantize_f32_q8_1_tiled, "quantize-f32-q8_1_tiled", quantize_f32_q8_1_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0))
QUANTIZE_IMPL(quantize_f32_q8_1_s16_tiled, "quantize-f32-q8_1_s16_tiled", quantize_f32_q8_1_s16_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0))
+QUANTIZE_IMPL(quantize_f16_q8_0_tiled, "quantize-f16-q8_0_tiled", quantize_f16_q8_0_tiled_kernel, htp_mm_q8_0_tiled_row_size(ne0))
+QUANTIZE_IMPL(quantize_f16_q8_1_tiled, "quantize-f16-q8_1_tiled", quantize_f16_q8_1_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0))
+QUANTIZE_IMPL(quantize_f16_q8_1_s16_tiled, "quantize-f16-q8_1_s16_tiled", quantize_f16_q8_1_s16_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0))
QUANTIZE_IMPL(quantize_f32_f16_tiled, "quantize-f32-f16_tiled", quantize_f32_f16_tiled_kernel, htp_mm_f16_tiled_row_size(ne0))
QUANTIZE_IMPL(quantize_f16_f16_tiled, "quantize-f16-f16_tiled", quantize_f16_f16_tiled_kernel, htp_mm_f16_tiled_row_size(ne0))
-QUANTIZE_IMPL(quantize_f32_f32, "quantize-f32-f32", quantize_f32_f32_kernel, mmctx->vtcm_act_stride)
+QUANTIZE_IMPL(quantize_f16_f32, "quantize-f16-f32", quantize_f16_f32_kernel, mmctx->vtcm_act_stride)
QUANTIZE_IMPL(quantize_f32_f16, "quantize-f32-f16", quantize_f32_f16_kernel, mmctx->vtcm_act_stride)
QUANTIZE_IMPL(quantize_f16_f16, "quantize-f16-f16", quantize_f16_f16_kernel, mmctx->vtcm_act_stride)
@@ -675,7 +674,6 @@ static void quantize_f32_q8_0_tiled_block(const htp_thread_t * th, unsigned int
if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
return;
}
- struct htp_ops_context * octx = mmctx->octx;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
@@ -703,7 +701,6 @@ static void quantize_f32_q8_1_tiled_block(const htp_thread_t * th, unsigned int
if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
return;
}
- struct htp_ops_context * octx = mmctx->octx;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
@@ -731,7 +728,6 @@ static void quantize_f32_q8_1_s16_tiled_block(const htp_thread_t * th, unsigned
if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
return;
}
- struct htp_ops_context * octx = mmctx->octx;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
@@ -759,7 +755,6 @@ static void quantize_f32_f16_tiled_block(const htp_thread_t * th, unsigned int n
if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
return;
}
- struct htp_ops_context * octx = mmctx->octx;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
@@ -787,7 +782,6 @@ static void quantize_f16_f16_tiled_block(const htp_thread_t * th, unsigned int n
if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
return;
}
- struct htp_ops_context * octx = mmctx->octx;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
@@ -809,55 +803,144 @@ static void quantize_f16_f16_tiled_block(const htp_thread_t * th, unsigned int n
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
}
-// q8_1 for weight types with offsets (q8_1_s16 for Q2_K), f16_tiled for F16, otherwise q8_0
-static inline work_queue_func_t htp_mm_act_quant_row_func(int weight_type, int act_type) {
- if (weight_type == HTP_TYPE_F16) {
- return (act_type == HTP_TYPE_F16) ? quantize_f16_f16_tiled : quantize_f32_f16_tiled;
- }
- if (weight_type == HTP_TYPE_Q2_K) {
- return quantize_f32_q8_1_s16_tiled;
- }
- return htp_mm_weight_has_offset(weight_type) ? quantize_f32_q8_1_tiled : quantize_f32_q8_0_tiled;
-}
-
-static inline work_queue_func_t htp_mm_act_quant_block_func(int weight_type, int act_type) {
- if (weight_type == HTP_TYPE_F16) {
- return (act_type == HTP_TYPE_F16) ? quantize_f16_f16_tiled_block : quantize_f32_f16_tiled_block;
- }
- if (weight_type == HTP_TYPE_Q2_K) {
- return quantize_f32_q8_1_s16_tiled_block;
+static void quantize_f16_q8_0_tiled_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ struct htp_mm_context * mmctx = data;
+ if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
+ return;
}
- return htp_mm_weight_has_offset(weight_type) ? quantize_f32_q8_1_tiled_block : quantize_f32_q8_0_tiled_block;
-}
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
-static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_matmul_preamble;
+ const struct htp_tensor * src = mmctx->act;
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start;
- const uint32_t cur_m_rows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13);
- const uint32_t cur_m_start = mmctx->cur_m_start;
+ quantize_f16_q8_0_tiled_block_kernel(
+ (const __fp16 *) mmctx->vtcm_act_raw,
+ mmctx->vtcm_act,
+ NULL,
+ src->ne[0],
+ mmctx->quant_ib_first[ith],
+ mmctx->quant_ib_last[ith],
+ mmctx->vtcm_act_raw_stride,
+ htp_mm_q8_0_tiled_row_size(src->ne[0]),
+ mmctx->quant_r[ith],
+ mmctx->quant_c[ith]
+ );
- const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
+}
+static void quantize_f16_q8_1_tiled_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ struct htp_mm_context * mmctx = data;
+ if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
+ return;
+ }
struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
- const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- const uint32_t n_prefetch = kparams->n_prefetch;
- assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
-
- const size_t dst_row_size = nb1;
- const size_t act_stride = mmctx->vtcm_act_stride;
-
- uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
- uint8_t * restrict act_data = mmctx->vtcm_act;
-
- const uint32_t tile_size = htp_tensor_get_tile_size(src0->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type);
+ const struct htp_tensor * src = mmctx->act;
- const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type);
- const uint32_t tile_row_stride = n_k_tiles_w * tile_size;
- const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size;
+ quantize_f16_q8_1_tiled_block_kernel(
+ (const __fp16 *) mmctx->vtcm_act_raw,
+ mmctx->vtcm_act,
+ NULL,
+ src->ne[0],
+ mmctx->quant_ib_first[ith],
+ mmctx->quant_ib_last[ith],
+ mmctx->vtcm_act_raw_stride,
+ htp_mm_q8_1_tiled_row_size(src->ne[0]),
+ mmctx->quant_r[ith],
+ mmctx->quant_c[ith]
+ );
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
+}
+
+static void quantize_f16_q8_1_s16_tiled_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ struct htp_mm_context * mmctx = data;
+ if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) {
+ return;
+ }
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
+
+ const struct htp_tensor * src = mmctx->act;
+
+ quantize_f16_q8_1_s16_tiled_block_kernel(
+ (const __fp16 *) mmctx->vtcm_act_raw,
+ mmctx->vtcm_act,
+ NULL,
+ src->ne[0],
+ mmctx->quant_ib_first[ith],
+ mmctx->quant_ib_last[ith],
+ mmctx->vtcm_act_raw_stride,
+ htp_mm_q8_1_tiled_row_size(src->ne[0]),
+ mmctx->quant_r[ith],
+ mmctx->quant_c[ith]
+ );
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
+}
+
+// q8_1 for weight types with offsets (q8_1_s16 for Q2_K), f16_tiled for F16, otherwise q8_0
+static inline work_queue_func_t htp_mm_act_quant_row_func(int weight_type, int act_type) {
+ const bool act_f16 = (act_type == HTP_TYPE_F16);
+ if (weight_type == HTP_TYPE_F16) {
+ return act_f16 ? quantize_f16_f16_tiled : quantize_f32_f16_tiled;
+ }
+ if (weight_type == HTP_TYPE_Q2_K) {
+ return act_f16 ? quantize_f16_q8_1_s16_tiled : quantize_f32_q8_1_s16_tiled;
+ }
+ if (htp_mm_weight_has_offset(weight_type)) {
+ return act_f16 ? quantize_f16_q8_1_tiled : quantize_f32_q8_1_tiled;
+ }
+ return act_f16 ? quantize_f16_q8_0_tiled : quantize_f32_q8_0_tiled;
+}
+
+static inline work_queue_func_t htp_mm_act_quant_block_func(int weight_type, int act_type) {
+ const bool act_f16 = (act_type == HTP_TYPE_F16);
+ if (weight_type == HTP_TYPE_F16) {
+ return act_f16 ? quantize_f16_f16_tiled_block : quantize_f32_f16_tiled_block;
+ }
+ if (weight_type == HTP_TYPE_Q2_K) {
+ return act_f16 ? quantize_f16_q8_1_s16_tiled_block : quantize_f32_q8_1_s16_tiled_block;
+ }
+ if (htp_mm_weight_has_offset(weight_type)) {
+ return act_f16 ? quantize_f16_q8_1_tiled_block : quantize_f32_q8_1_tiled_block;
+ }
+ return act_f16 ? quantize_f16_q8_0_tiled_block : quantize_f32_q8_0_tiled_block;
+}
+
+static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ htp_matmul_preamble;
+
+ const uint32_t cur_m_rows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13);
+ const uint32_t cur_m_start = mmctx->cur_m_start;
+
+ const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end);
+
+ struct htp_thread_trace * tr = th->trace;
+
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ const uint32_t n_prefetch = kparams->n_prefetch;
+ assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
+ (void) n_prefetch;
+
+ const size_t dst_row_size = nb1;
+ const size_t act_stride = mmctx->vtcm_act_stride;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+
+ uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
+ uint8_t * restrict act_data = mmctx->vtcm_act;
+
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
+
+ const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type);
+ const uint32_t tile_row_stride = n_k_tiles_w * tile_size;
const uint32_t src0_slice_stride = ((ne01 + 31) / 32) * tile_row_stride;
const uint32_t ct_start = src0_start_row / 32;
@@ -892,20 +975,20 @@ static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
}
const uint32_t slice_idx = i03 * ne02 + i02;
- const dma_addr_t src0_slice = src0->data + (size_t) slice_idx * src0_slice_stride;
+ const dma_addr_t src0_slice = src0->data + (dma_addr_t) slice_idx * src0_slice_stride;
- uint32_t push_ct = ct_start;
- for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned,
- src0_slice + (size_t) push_ct * tile_row_stride),
- aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- }
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
+
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_slice + (dma_addr_t) ct_start * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
for (uint32_t ct = ct_start; ct < ct_end; ct++) {
const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
int valid_rows = (int)ne0 - (int)(ct * 32);
valid_rows = MIN(32, MAX(0, valid_rows));
+ const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size;
+ const size_t row_bytes = (size_t) valid_rows * dst_elem_size;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
for (uint32_t b = b_grp_start; b < b_grp_end; b++) {
@@ -916,42 +999,41 @@ static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
const uint32_t cur_b2 = b - cur_b3 * ne12;
- uint8_t * dst_batch_base = (uint8_t *) dst->data + (size_t) cur_b2 * nb2 + (size_t) cur_b3 * nb3;
+ const dma_addr_t dst_batch_base = dst->data + (dma_addr_t) cur_b2 * nb2 + (dma_addr_t) cur_b3 * nb3;
const uint32_t chunk_m_offset = m_first - cur_m_start;
const uint32_t dst_m_offset = m_first - b_m_start;
const uint32_t batch_nrows = m_last - m_first;
- uint32_t ir1 = 0;
- for (; ir1 + 1 < batch_nrows; ir1 += 2) {
- const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 0) * act_stride);
- const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 1) * act_stride);
- float * restrict dst_row0 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 0) * dst_row_size);
- float * restrict dst_row1 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 1) * dst_row_size);
- float * dst_ptr0 = &dst_row0[ct * 32];
- float * dst_ptr1 = &dst_row1[ct * 32];
- mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL);
- }
- for (; ir1 < batch_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + ir1) * act_stride);
- float * restrict dst_row = (float *) (dst_batch_base + (dst_m_offset + ir1) * dst_row_size);
- float * dst_ptr = &dst_row[ct * 32];
- mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL);
+ for (uint32_t m0 = 0; m0 < batch_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, batch_nrows - m0);
+ uint32_t r = 0;
+ for (; r + 1 < m_cnt; r += 2) {
+ const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 0) * act_stride);
+ const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 1) * act_stride);
+ void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 128;
+ void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 128;
+ mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL, mmctx->store_row);
+ }
+ for (; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 128;
+ mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, mmctx->store_row);
+ }
+ const dma_addr_t dst_addr = dst_batch_base + (dma_addr_t) (dst_m_offset + m0) * dst_row_size + ct_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 128, row_bytes, m_cnt);
+ dma_queue_pop(dma_q);
}
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src0_slice + (size_t) push_ct * tile_row_stride),
+ if (ct + 1 < ct_end) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_slice + (dma_addr_t) (ct + 1) * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- push_ct++;
}
}
b_grp_start = b_grp_end;
}
- if (src2) {
- hvx_tensor_add_f32_grid(dst, src2, cur_m_start, cur_m_start + cur_m_rows, src0_start_row, src0_end_row, &kparams->div_ne12_ne1, &kparams->div_ne1);
- }
}
static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
@@ -960,9 +1042,8 @@ static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
const uint32_t n_prefetch = kparams->n_prefetch;
assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
- const uint32_t prefetch_mask = n_prefetch - 1;
+ (void) n_prefetch;
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; // src0 rows
const uint32_t act_nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : mmctx->act_nrows;
const uint32_t cur_m_start = mmctx->cur_m_start;
@@ -974,12 +1055,12 @@ static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const size_t dst_row_size = nb1;
const size_t src0_row_size = nb01;
- const size_t act_row_size = nb11;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
const size_t src0_stride = mmctx->vtcm_src0_stride;
const size_t act_stride = mmctx->vtcm_act_stride;
- // Per-thread VTCMs for all tensors
+ // Per-HVX VTCMs for all tensors
uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
@@ -987,94 +1068,87 @@ static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const dma_addr_t src0_row = src0->data;
- // Prefill vtcm with src0 rows
- if (src0_start_row < src0_end_row) {
- for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) {
- const int is0 = (ir0 - src0_start_row);
- if (is0 >= (int)n_prefetch) {
- break;
- }
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + ir0 * src0_row_size),
- src0_stride, src0_row_size, src0_row_size, 2);
- }
- }
-
if (src0_start_row >= src0_end_row) {
return;
}
+ if (src0_start_row < src0_end_row_x2) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) src0_start_row * src0_row_size),
+ src0_stride, src0_row_size, src0_row_size, 2);
+ }
+
// Process src0 rows
for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) {
const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst;
+ const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
- // Process act columns in pairs (2x2 tiling)
- uint32_t ir1 = 0;
- for (; ir1 + 1 < act_nrows; ir1 += 2) {
- const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (ir1+0) * act_stride);
- const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (ir1+1) * act_stride);
- float * restrict dst_row0 = (float *) (dst->data + ((cur_m_start + ir1+0) * dst_row_size));
- float * restrict dst_row1 = (float *) (dst->data + ((cur_m_start + ir1+1) * dst_row_size));
- mmctx->vec_dot_2x2(ne00, &dst_row0[ir0], &dst_row1[ir0], ss0, ss0 + src0_stride, act_col0, act_col1);
- }
-
- // Handle remaining act rows (fallback to 2x1)
- for (; ir1 < act_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride);
- float * restrict dst_row = (float *) (dst->data + ((cur_m_start + ir1) * dst_row_size));
- mmctx->vec_dot_2x1(ne00, &dst_row[ir0], ss0, ss0 + src0_stride, act_col);
+ for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, act_nrows - m0);
+ uint32_t r = 0;
+ for (; r + 1 < m_cnt; r += 2) {
+ const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (m0 + r + 0) * act_stride);
+ const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (m0 + r + 1) * act_stride);
+ void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 16;
+ void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 16;
+ mmctx->vec_dot_2x2(ne00, dst_ptr0, dst_ptr1, ss0, ss0 + src0_stride, act_col0, act_col1, mmctx->flat_store_2x1);
+ }
+ for (; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16;
+ mmctx->vec_dot_2x1(ne00, dst_ptr, ss0, ss0 + src0_stride, act_col, mmctx->flat_store_2x1);
+ }
+ const dma_addr_t dst_addr = dst->data + (dma_addr_t) (cur_m_start + m0) * dst_row_size + ir0_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, 2u * dst_elem_size, m_cnt);
+ dma_queue_pop(dma_q);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
- // Prefetch next (n + vtcm_nrows) row
- const int pr0 = (ir0 + n_prefetch);
- const int is0 = (pr0 - src0_start_row) & prefetch_mask;
- if (pr0 < src0_end_row_x2) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + pr0 * src0_row_size),
+ if (ir0 + 2 < src0_end_row_x2) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ir0 + 2) * src0_row_size),
src0_stride, src0_row_size, src0_row_size, 2);
}
}
// Process the last row (if any)
if (src0_end_row != src0_end_row_x2) {
- uint32_t ir0 = src0_end_row_x2;
- const int is0 = (ir0 - src0_start_row) & prefetch_mask;
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + ir0 * src0_row_size),
+ const uint32_t ir0 = src0_end_row_x2;
+ const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size;
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ir0 * src0_row_size),
src0_stride, src0_row_size, src0_row_size, 1);
const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
- #pragma unroll(2)
- for (uint32_t ir1 = 0; ir1 < act_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride);
- float * restrict dst_row = (float *) (dst->data + ((cur_m_start + ir1) * dst_row_size));
- mmctx->vec_dot_1x1(ne00, &dst_row[ir0], ss0, act_col);
+ for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, act_nrows - m0);
+ for (uint32_t r = 0; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16;
+ mmctx->vec_dot_1x1(ne00, dst_ptr, ss0, act_col, mmctx->flat_store_1x1);
+ }
+ const dma_addr_t dst_addr = dst->data + (dma_addr_t) (cur_m_start + m0) * dst_row_size + ir0_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, dst_elem_size, m_cnt);
+ dma_queue_pop(dma_q);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
}
- if (src2) {
- hvx_tensor_add_f32_grid(dst, src2, cur_m_start, cur_m_start + act_nrows, src0_start_row, src0_end_row, &kparams->div_ne12_ne1, &kparams->div_ne1);
- }
}
static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
htp_matmul_preamble;
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start;
-
const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith;
const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end);
struct htp_thread_trace * tr = th->trace;
- const size_t dst_row_size = nb1;
const size_t src0_row_size = nb01;
- const size_t act_row_size = nb11;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const uint32_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
const size_t src0_stride = mmctx->vtcm_src0_stride;
- const size_t act_stride = mmctx->vtcm_act_stride;
- // Per-thread VTCMs for all tensors
+ // Per-HVX VTCMs for all tensors
uint8_t * vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
uint8_t * act_data = mmctx->vtcm_act;
@@ -1083,7 +1157,6 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const dma_addr_t src0_row = src0->data;
const uint8_t * restrict act_col = (const uint8_t *) act_data;
- float * restrict dst_col = (float *) dst->data;
const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
@@ -1094,14 +1167,15 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
// Prefill vtcm with 2x src0 rows
if (src0_start_row < src0_end_row) {
- if (src2) {
- float * vtcm_bias_ptr = (float *) mmctx->vtcm_bias + src0_start_row;
- const dma_addr_t src2_addr = src2->data + src0_start_row * sizeof(float);
+ if (bias) {
+ uint8_t * vtcm_bias_ptr = mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size;
+ const dma_addr_t bias_addr = bias->data + (size_t) src0_start_row * bias_elem_size;
int slice_size = (int)src0_end_row - (int)src0_start_row;
if (slice_size > 0) {
- dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, src2_addr),
- slice_size * sizeof(float), slice_size * sizeof(float), slice_size * sizeof(float), 1);
- dma_queue_pop_nowait(dma_q);
+ const size_t slice_bytes = (size_t) slice_size * bias_elem_size;
+ dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, bias_addr),
+ slice_bytes, slice_bytes, slice_bytes, 1);
+ dma_queue_pop(dma_q);
}
}
for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) {
@@ -1123,7 +1197,7 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) {
const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
- mmctx->vec_dot_2x1(ne00, &tmp[ir0 - src0_start_row], ss0, ss0 + src0_stride, act_col);
+ mmctx->vec_dot_2x1(ne00, &tmp[ir0 - src0_start_row], ss0, ss0 + src0_stride, act_col, hvx_flat_store_2x1_f32);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
// Prefetch next (n + vtcm_nrows) row
@@ -1143,22 +1217,31 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
src0_stride, src0_row_size, src0_row_size, 1);
const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
- mmctx->vec_dot_1x1(ne00, &tmp[ir0 - src0_start_row], ss0, act_col);
+ mmctx->vec_dot_1x1(ne00, &tmp[ir0 - src0_start_row], ss0, act_col, hvx_flat_store_1x1_f32);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
}
int copy_cnt = src0_end_row - src0_start_row;
if (copy_cnt > 0) {
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, src0_end_row);
- if (src2) {
- hvx_add_f32_uuu((uint8_t *) &dst_col[src0_start_row],
- (const uint8_t *) tmp,
- (const uint8_t *) ((const float *) mmctx->vtcm_bias + src0_start_row),
- copy_cnt);
- } else {
- hvx_copy_f32_ua((uint8_t *) &dst_col[src0_start_row], (uint8_t *) tmp, copy_cnt);
+ const hvx_tiled_store_row_fn_t store_row = mmctx->store_row;
+ const uint8_t * bias_in = bias ? (mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size) : NULL;
+ if (bias_in) {
+ for (int c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c);
+ HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c);
+ store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, bias_in + (size_t) c * bias_elem_size);
+ }
+ } else if (dst_elem_size != sizeof(float)) {
+ for (int c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c);
+ HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c);
+ store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, NULL);
+ }
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, src0_end_row);
+ dma_sync_write(dma_q, dst->data + (size_t) src0_start_row * dst_elem_size,
+ vtcm_dst_ptr, (size_t) copy_cnt * dst_elem_size);
}
}
@@ -1168,9 +1251,8 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
const uint32_t n_prefetch = kparams->n_prefetch;
assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
- const uint32_t prefetch_mask = n_prefetch - 1;
+ (void) n_prefetch;
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start;
const uint32_t cur_m_rows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13);
const uint32_t cur_m_start = mmctx->cur_m_start;
@@ -1184,6 +1266,7 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const size_t src0_row_size = nb01;
const size_t src0_stride = mmctx->vtcm_src0_stride;
const size_t act_stride = mmctx->vtcm_act_stride;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
@@ -1217,19 +1300,17 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
b_grp_end++;
}
- const dma_addr_t src0_row = src0->data + ((size_t) i02 * nb02 + (size_t) i03 * nb03);
+ const dma_addr_t src0_row = src0->data + ((dma_addr_t) i02 * nb02 + (dma_addr_t) i03 * nb03);
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
- for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) {
- const int is0 = (ir0 - src0_start_row);
- if (is0 >= (int)n_prefetch) {
- break;
- }
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + (size_t) ir0 * src0_row_size),
+ if (src0_start_row < src0_end_row_x2) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) src0_start_row * src0_row_size),
src0_stride, src0_row_size, src0_row_size, 2);
}
for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) {
const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst;
+ const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
for (uint32_t b = b_grp_start; b < b_grp_end; b++) {
@@ -1240,40 +1321,44 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
const uint32_t cur_b2 = b - cur_b3 * ne12;
- uint8_t * dst_batch_base = (uint8_t *) dst->data + (size_t) cur_b2 * nb2 + (size_t) cur_b3 * nb3;
+ const dma_addr_t dst_batch_base = dst->data + (dma_addr_t) cur_b2 * nb2 + (dma_addr_t) cur_b3 * nb3;
const uint32_t chunk_m_offset = m_first - cur_m_start;
const uint32_t dst_m_offset = m_first - b_m_start;
const uint32_t batch_nrows = m_last - m_first;
- uint32_t ir1 = 0;
- for (; ir1 + 1 < batch_nrows; ir1 += 2) {
- const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 0) * act_stride);
- const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 1) * act_stride);
- float * restrict dst_row0 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 0) * dst_row_size);
- float * restrict dst_row1 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 1) * dst_row_size);
- mmctx->vec_dot_2x2(ne00, &dst_row0[ir0], &dst_row1[ir0], ss0, ss0 + src0_stride, act_col0, act_col1);
- }
- for (; ir1 < batch_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + ir1) * act_stride);
- float * restrict dst_row = (float *) (dst_batch_base + (dst_m_offset + ir1) * dst_row_size);
- mmctx->vec_dot_2x1(ne00, &dst_row[ir0], ss0, ss0 + src0_stride, act_col);
+ for (uint32_t m0 = 0; m0 < batch_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, batch_nrows - m0);
+ uint32_t r = 0;
+ for (; r + 1 < m_cnt; r += 2) {
+ const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 0) * act_stride);
+ const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 1) * act_stride);
+ void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 16;
+ void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 16;
+ mmctx->vec_dot_2x2(ne00, dst_ptr0, dst_ptr1, ss0, ss0 + src0_stride, act_col0, act_col1, mmctx->flat_store_2x1);
+ }
+ for (; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16;
+ mmctx->vec_dot_2x1(ne00, dst_ptr, ss0, ss0 + src0_stride, act_col, mmctx->flat_store_2x1);
+ }
+ const dma_addr_t dst_addr = dst_batch_base + (dma_addr_t) (dst_m_offset + m0) * dst_row_size + ir0_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, 2u * dst_elem_size, m_cnt);
+ dma_queue_pop(dma_q);
}
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
- const int pr0 = (ir0 + n_prefetch);
- const int is0 = (pr0 - src0_start_row) & prefetch_mask;
- if (pr0 < src0_end_row_x2) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + (size_t) pr0 * src0_row_size),
+ if (ir0 + 2 < src0_end_row_x2) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ir0 + 2) * src0_row_size),
src0_stride, src0_row_size, src0_row_size, 2);
}
}
if (src0_end_row != src0_end_row_x2) {
- uint32_t ir0 = src0_end_row_x2;
- const int is0 = (ir0 - src0_start_row) & prefetch_mask;
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + (size_t) ir0 * src0_row_size),
+ const uint32_t ir0 = src0_end_row_x2;
+ const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size;
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ir0 * src0_row_size),
src0_stride, src0_row_size, src0_row_size, 1);
const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst;
@@ -1286,16 +1371,22 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
const uint32_t cur_b2 = b - cur_b3 * ne12;
- uint8_t * dst_batch_base = (uint8_t *) dst->data + (size_t) cur_b2 * nb2 + (size_t) cur_b3 * nb3;
+ const dma_addr_t dst_batch_base = dst->data + (dma_addr_t) cur_b2 * nb2 + (dma_addr_t) cur_b3 * nb3;
const uint32_t chunk_m_offset = m_first - cur_m_start;
const uint32_t dst_m_offset = m_first - b_m_start;
const uint32_t batch_nrows = m_last - m_first;
- for (uint32_t ir1 = 0; ir1 < batch_nrows; ++ir1) {
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + ir1) * act_stride);
- float * restrict dst_row = (float *) (dst_batch_base + (dst_m_offset + ir1) * dst_row_size);
- mmctx->vec_dot_1x1(ne00, &dst_row[ir0], ss0, act_col);
+ for (uint32_t m0 = 0; m0 < batch_nrows; m0 += 32) {
+ const uint32_t m_cnt = MIN(32u, batch_nrows - m0);
+ for (uint32_t r = 0; r < m_cnt; ++r) {
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r) * act_stride);
+ void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16;
+ mmctx->vec_dot_1x1(ne00, dst_ptr, ss0, act_col, mmctx->flat_store_1x1);
+ }
+ const dma_addr_t dst_addr = dst_batch_base + (dma_addr_t) (dst_m_offset + m0) * dst_row_size + ir0_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, dst_elem_size, m_cnt);
+ dma_queue_pop(dma_q);
}
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
@@ -1303,10 +1394,6 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
b_grp_start = b_grp_end;
}
-
- if (src2) {
- hvx_tensor_add_f32_grid(dst, src2, cur_m_start, cur_m_start + cur_m_rows, src0_start_row, src0_end_row, &kparams->div_ne12_ne1, &kparams->div_ne1);
- }
}
#define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id) * mmctx->mapping_stride + (i1)]
@@ -1314,10 +1401,6 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i
static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
htp_matmul_preamble;
- const struct htp_tensor * restrict ids = octx->src[2];
-
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; // src0 rows per expert
- const uint32_t act_nrows = ne11;
const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith;
const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end);
@@ -1331,20 +1414,20 @@ static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
const uint32_t n_prefetch = kparams->n_prefetch;
assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
+ (void) n_prefetch;
- const uint32_t n_ids = ids->ne[0]; // n_expert_used
const uint32_t n_as = ne02; // n_expert
const uint32_t * matrix_row_counts = mmctx->matrix_row_counts;
const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows;
- const size_t dst_row_size = nb1;
- const size_t act_row_size = htp_mm_q8_0_tiled_row_size(ne10);
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
const size_t act_stride = mmctx->vtcm_act_stride;
- // Per-thread VTCMs for all tensors
+ // Per-HVX VTCMs for all tensors
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
for (uint32_t cur_a = 0; cur_a < n_as; ++cur_a) {
@@ -1353,47 +1436,50 @@ static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned
continue;
}
- const dma_addr_t src0_row = src0->data + cur_a * nb02;
+ const dma_addr_t src0_row = src0->data + (dma_addr_t) cur_a * nb02;
- const uint32_t tile_size = htp_tensor_get_tile_size(src0->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type);
const uint32_t tile_row_stride = n_k_tiles_w * tile_size;
- const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size;
const uint32_t ct_start = src0_start_row / 32;
const uint32_t ct_end = (src0_end_row + 31) / 32;
- uint32_t push_ct = ct_start;
- for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride),
- aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- }
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ct_start * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
for (uint32_t ct = ct_start; ct < ct_end; ct++) {
const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
int valid_rows = (int)ne0 - (int)(ct * 32);
valid_rows = MIN(32, MAX(0, valid_rows));
+ const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size;
+ const size_t row_bytes = (size_t) valid_rows * dst_elem_size;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- for (uint32_t cid = 0; cid < cne1; ++cid) {
- struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid);
- const int rm1 = row_mapping.i1; // expert idx
- const int rm2 = row_mapping.i2; // token idx
-
- const uint32_t ir1 = fastmodulo(rm1, ne11, &mmctx->mm_div_ne11); // act row idx
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * ne11 + 0) * act_stride);
- float * restrict dst_row = (float *) (dst->data + (rm1 * nb1 + rm2 * nb2 + 0));
-
- mmctx->vec_dot_32x1(ne10, &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL);
+ for (uint32_t cid0 = 0; cid0 < (uint32_t) cne1; cid0 += 32) {
+ const uint32_t cnt = MIN(32u, (uint32_t) cne1 - cid0);
+ for (uint32_t r = 0; r < cnt; ++r) {
+ struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r);
+ const int rm1 = row_mapping.i1;
+ const int rm2 = row_mapping.i2;
+ const uint32_t ir1 = fastmodulo(rm1, ne11, &mmctx->mm_div_ne11);
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * ne11) * act_stride);
+ mmctx->vec_dot_32x1(ne10, vtcm_dst_ptr + (size_t) r * 128, w_tile, act_col, valid_rows, NULL, mmctx->store_row);
+ }
+ for (uint32_t r = 0; r < cnt; ++r) {
+ struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r);
+ const dma_addr_t dst_addr = dst->data + (dma_addr_t) row_mapping.i1 * nb1 + (dma_addr_t) row_mapping.i2 * nb2 + ct_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr + (size_t) r * 128), row_bytes, row_bytes, row_bytes, 1);
+ }
+ dma_queue_flush(dma_q);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride),
+ if (ct + 1 < ct_end) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ct + 1) * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- push_ct++;
}
}
}
@@ -1404,7 +1490,6 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned
const struct htp_tensor * restrict ids = octx->src[2];
- const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; // src0 rows per expert
const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith;
const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end);
@@ -1421,29 +1506,32 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned
assert(ne13 % ne03 == 0);
- const size_t dst_row_size = nb1;
- const size_t act_row_size = htp_mm_q8_0_tiled_row_size(ne10);
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
- const uint32_t n_aids = src2->ne[0]; // num activated experts
+ const uint32_t n_aids = ids->ne[0]; // num activated experts
const uint32_t n_ids = ne02; // num experts
+ (void) n_ids;
- // Per-thread VTCMs for all tensors
+ // Per-HVX VTCMs for all tensors
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
+ const uint32_t copy_cnt = MIN(src0_end_row, ne0) - src0_start_row;
+
for (uint32_t ie1 = 0; ie1 < n_aids; ++ie1) { // for each expert
- const int32_t eid = *(const int32_t *) ((const uint8_t *) src2->data + ie1 * src2->nb[0]);
+ const int32_t eid = mmctx->ids_data[ie1];
if (eid < 0) {
continue;
}
assert(eid >= 0 && eid < (int32_t) n_ids);
- const dma_addr_t src0_row = src0->data + eid * nb02;
+ const dma_addr_t src0_row = src0->data + (dma_addr_t) eid * nb02;
const uint8_t * restrict act_col = (const uint8_t *) act_data;
- float * restrict dst_row = (float *) (dst->data + ie1 * nb1);
+ const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * nb1;
- const uint32_t tile_size = htp_tensor_get_tile_size(src0->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type);
const uint32_t tile_row_stride = n_k_tiles_w * tile_size;
const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size;
@@ -1453,7 +1541,7 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned
uint32_t push_ct = ct_start;
for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride),
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + (dma_addr_t) push_ct * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
}
@@ -1464,15 +1552,17 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned
valid_rows = MIN(32, MAX(0, valid_rows));
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- mmctx->vec_dot_32x1(ne10, &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL);
+ mmctx->vec_dot_32x1(ne10, vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size, w_tile, act_col, valid_rows, NULL, mmctx->store_row);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride),
+ dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + (dma_addr_t) push_ct * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
push_ct++;
}
}
+ dma_sync_write(dma_q, dst_row + (size_t) src0_start_row * dst_elem_size,
+ vtcm_dst_ptr, (size_t) copy_cnt * dst_elem_size);
}
}
@@ -1493,12 +1583,14 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
const uint32_t n_aids = ids->ne[0];
const uint32_t n_ids = src0->ne[2];
+ (void) n_ids;
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
for (uint32_t ie1 = 0; ie1 < n_aids; ++ie1) {
- const int32_t eid = *(const int32_t *) ((const uint8_t *) ids->data + ie1 * ids->nb[0]);
+ const int32_t eid = mmctx->ids_data[ie1];
if (eid < 0) continue;
assert(eid < (int32_t) n_ids);
@@ -1508,12 +1600,13 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
if (!src_w || !dst) continue;
dma_queue * dma_q = th->dma_q;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const hvx_tiled_store_row_fn_t store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float));
const uint32_t ne01 = src_w->ne[1];
uint32_t start_row = 0;
uint32_t end_row = ne01;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float));
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
start_row = range.start;
end_row = range.start + range.count;
}
@@ -1526,12 +1619,12 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, end_row);
if (src0_start_row >= src0_end_row) continue;
- const dma_addr_t src0_row = src_w->data + eid * src_w->nb[2];
+ const dma_addr_t src0_row = src_w->data + (dma_addr_t) eid * src_w->nb[2];
const uint8_t * restrict act_col = (const uint8_t *) act_data;
- float * restrict dst_row = (float *) (dst->data + ie1 * dst->nb[1]);
+ const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * dst->nb[1];
- const uint32_t tile_size = htp_tensor_get_tile_size(src_w->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src_w->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
const uint32_t n_k_tiles_w = src_w->ne[0] / htp_tensor_get_tile_k(src_w->type);
const uint32_t tile_row_stride = n_k_tiles_w * tile_size;
const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size;
@@ -1541,7 +1634,7 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
uint32_t push_ct = ct_start;
for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride),
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + (dma_addr_t) push_ct * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
}
@@ -1552,15 +1645,17 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
valid_rows = MIN(32, MAX(0, valid_rows));
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- mmctx->vec_dot_32x1(act->ne[0], &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL);
+ mmctx->vec_dot_32x1(act->ne[0], vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size, w_tile, act_col, valid_rows, NULL, store_row);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride),
+ dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + (dma_addr_t) push_ct * tile_row_stride),
aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
push_ct++;
}
}
+ const size_t copy_bytes = (size_t) (MIN(src0_end_row, dst->ne[0]) - src0_start_row) * dst_elem_size;
+ dma_sync_write(dma_q, dst_row + (size_t) src0_start_row * dst_elem_size, vtcm_dst_ptr, copy_bytes);
}
}
}
@@ -1572,13 +1667,13 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
const uint32_t n_weights = kparams->n_weights;
const struct htp_tensor * restrict src0 = octx->src[0];
const struct htp_tensor * restrict act = octx->src[n_weights];
- const struct htp_tensor * restrict ids = octx->src[n_weights + 1];
struct htp_thread_trace * tr = th->trace;
const uint32_t n_prefetch = kparams->n_prefetch;
assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
+ (void) n_prefetch;
const uint32_t n_as = src0->ne[2];
@@ -1588,6 +1683,7 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
const size_t act_stride = mmctx->vtcm_act_stride;
uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith;
+ uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith;
uint8_t * restrict act_data = mmctx->vtcm_act;
for (uint32_t cur_a = 0; cur_a < n_as; ++cur_a) {
@@ -1600,12 +1696,13 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
if (!src_w || !dst) continue;
dma_queue * dma_q = th->dma_q;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const hvx_tiled_store_row_fn_t store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float));
const uint32_t ne01 = src_w->ne[1];
uint32_t start_row = 0;
uint32_t end_row = ne01;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float));
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
start_row = range.start;
end_row = range.start + range.count;
}
@@ -1618,47 +1715,50 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign
const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, end_row);
if (src0_start_row >= src0_end_row) continue;
- const dma_addr_t src0_row = src_w->data + cur_a * src_w->nb[2];
+ const dma_addr_t src0_row = src_w->data + (dma_addr_t) cur_a * src_w->nb[2];
- const uint32_t tile_size = htp_tensor_get_tile_size(src_w->type);
- const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src_w->type);
+ const uint32_t tile_size = kparams->tile_size;
+ const uint32_t aligned_tile_size = kparams->aligned_tile_size;
const uint32_t n_k_tiles_w = src_w->ne[0] / htp_tensor_get_tile_k(src_w->type);
const uint32_t tile_row_stride = n_k_tiles_w * tile_size;
- const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size;
const uint32_t ct_start = src0_start_row / 32;
const uint32_t ct_end = (src0_end_row + 31) / 32;
- uint32_t push_ct = ct_start;
- for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) {
- dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride),
- aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- }
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ct_start * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
for (uint32_t ct = ct_start; ct < ct_end; ct++) {
const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
int valid_rows = (int)dst->ne[0] - (int)(ct * 32);
valid_rows = MIN(32, MAX(0, valid_rows));
+ const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size;
+ const size_t row_bytes = (size_t) valid_rows * dst_elem_size;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- for (uint32_t cid = 0; cid < (uint32_t) cne1; ++cid) {
- struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid);
- const int rm1 = row_mapping.i1;
- const int rm2 = row_mapping.i2;
-
- const uint32_t ir1 = fastmodulo(rm1, act->ne[1], &mmctx->mm_div_ne11);
- const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * act->ne[1]) * act_stride);
- float * restrict dst_row = (float *) (dst->data + (rm1 * dst->nb[1] + rm2 * dst->nb[2]));
-
- mmctx->vec_dot_32x1(act->ne[0], &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL);
+ for (uint32_t cid0 = 0; cid0 < (uint32_t) cne1; cid0 += 32) {
+ const uint32_t cnt = MIN(32u, (uint32_t) cne1 - cid0);
+ for (uint32_t r = 0; r < cnt; ++r) {
+ struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r);
+ const int rm1 = row_mapping.i1;
+ const int rm2 = row_mapping.i2;
+ const uint32_t ir1 = fastmodulo(rm1, act->ne[1], &mmctx->mm_div_ne11);
+ const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * act->ne[1]) * act_stride);
+ mmctx->vec_dot_32x1(act->ne[0], vtcm_dst_ptr + (size_t) r * 128, w_tile, act_col, valid_rows, NULL, store_row);
+ }
+ for (uint32_t r = 0; r < cnt; ++r) {
+ struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r);
+ const dma_addr_t dst_addr = dst->data + (dma_addr_t) row_mapping.i1 * dst->nb[1] + (dma_addr_t) row_mapping.i2 * dst->nb[2] + ct_dst_off;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr + (size_t) r * 128), row_bytes, row_bytes, row_bytes, 1);
+ }
+ dma_queue_flush(dma_q);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- if (push_ct < ct_end) {
- dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride),
- aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
- push_ct++;
+ if (ct + 1 < ct_end) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ct + 1) * tile_row_stride),
+ aligned_tile_size, tile_size, tile_size, n_k_tiles_w);
}
}
}
@@ -1769,9 +1869,12 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
uint32_t src0_row_start = 0;
uint32_t src0_row_end = src0_nrows;
+ const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float));
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
src0_row_start = range.start;
src0_row_end = range.start + range.count;
}
@@ -1795,23 +1898,30 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
}
const size_t src0_row_size = nb01;
- const size_t dst_row_size = nb1;
- size_t act_row_size = nb11;
+ const size_t dst_row_size = (size_t) ne0 * sizeof(float);
+ const size_t act_row_size = kparams->act_row_size;
const size_t src0_row_size_padded = hex_round_up(src0_row_size, 128);
work_queue_func_t quant_task_func;
- work_queue_func_t matmul_job_func;
+ work_queue_func_t matmul_task_func;
uint32_t n_quant_tasks = 1;
const bool is_batched = (ne12 > 1 || ne13 > 1 || ne02 > 1 || ne03 > 1);
+ if (bias && (is_batched || act_nrows > 1)) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
if (is_batched) {
- matmul_job_func = is_tiled ? hvx_mm_4d_tiled : hvx_mm_4d_flat;
+ matmul_task_func = is_tiled ? hvx_mm_4d_tiled : hvx_mm_4d_flat;
} else if (act_nrows > 1) {
- matmul_job_func = is_tiled ? hvx_mm_2d_tiled : hvx_mm_2d_flat;
+ matmul_task_func = is_tiled ? hvx_mm_2d_tiled : hvx_mm_2d_flat;
} else {
- matmul_job_func = is_tiled ? hvx_mv_2d_tiled : hvx_mv_2d_flat;
+ matmul_task_func = is_tiled ? hvx_mv_2d_tiled : hvx_mv_2d_flat;
}
+ mmctx->store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, bias != NULL && !is_batched, bias_elem_size);
+ mmctx->flat_store_1x1 = resolve_hvx_flat_store_1x1_fn(dst_elem_size);
+ mmctx->flat_store_2x1 = resolve_hvx_flat_store_2x1_fn(dst_elem_size);
+
bool need_quant = true;
switch (kparams->kernel_type) {
@@ -1822,27 +1932,26 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
mmctx->vec_dot_1x1 = flat_vec_dot_f16_f16_aa_1x1;
mmctx->vec_dot_2x1 = flat_vec_dot_f16_f16_aa_2x1;
mmctx->vec_dot_2x2 = flat_vec_dot_f16_f16_aa_2x2;
- act_row_size = kparams->act_row_size;
break;
case HTP_MM_KERNEL_HVX_F32_F32_VTCM:
- quant_task_func = NULL;
- need_quant = false;
+ quant_task_func = (act->type == HTP_TYPE_F16) ? quantize_f16_f32 : NULL;
+ need_quant = (act->type == HTP_TYPE_F16);
+ n_quant_tasks = need_quant ? MIN(act_nrows, octx->n_hvx) : 1;
mmctx->type = "f32-f32";
mmctx->vec_dot_1x1 = flat_vec_dot_f32_f32_aa_1x1;
mmctx->vec_dot_2x1 = flat_vec_dot_f32_f32_aa_2x1;
mmctx->vec_dot_2x2 = flat_vec_dot_f32_f32_aa_2x2;
- act_row_size = kparams->act_row_size;
break;
case HTP_MM_KERNEL_HVX_BF16_F32_VTCM:
- quant_task_func = NULL;
- need_quant = false;
+ quant_task_func = (act->type == HTP_TYPE_F16) ? quantize_f16_f32 : NULL;
+ need_quant = (act->type == HTP_TYPE_F16);
+ n_quant_tasks = need_quant ? MIN(act_nrows, octx->n_hvx) : 1;
mmctx->type = "bf16-f32";
mmctx->vec_dot_1x1 = flat_vec_dot_bf16_f32_aa_1x1;
mmctx->vec_dot_2x1 = flat_vec_dot_bf16_f32_aa_2x1;
mmctx->vec_dot_2x2 = flat_vec_dot_bf16_f32_aa_2x2;
- act_row_size = kparams->act_row_size;
break;
case HTP_MM_KERNEL_HVX_QUANT_BLOCK:
@@ -1871,7 +1980,6 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
n_quant_tasks = MIN(act_nrows, octx->n_hvx);
quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
}
- act_row_size = kparams->act_row_size;
break;
}
}
@@ -1882,7 +1990,7 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, ne10, m_layout_rows, octx->n_hvx,
- dst_row_size, src0_row_size, act_row_size, src2 ? src2->nb[1] : 0, kparams->n_prefetch, false, false);
+ dst_row_size, src0_row_size, act_elem_size, bias ? bias->nb[1] : 0, kparams->n_prefetch, false, false);
if (kparams->kernel_type == HTP_MM_KERNEL_HVX_F16_F16_VTCM ||
kparams->kernel_type == HTP_MM_KERNEL_HVX_F32_F32_VTCM ||
@@ -1923,9 +2031,12 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
mmctx->vtcm_src0_stride = src0_row_size_padded;
mmctx->vtcm_act_stride = act_row_size;
if (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW) {
- mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10);
- } else if (kparams->kernel_type == HTP_MM_KERNEL_HVX_F16_F16_VTCM) {
- mmctx->vtcm_act_raw_stride = hex_round_up(ne10 * sizeof(float), 128);
+ mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10, act_elem_size);
+ } else if (kparams->kernel_type == HTP_MM_KERNEL_HVX_F16_F16_VTCM ||
+ ((kparams->kernel_type == HTP_MM_KERNEL_HVX_F32_F32_VTCM ||
+ kparams->kernel_type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM) &&
+ act_elem_size == sizeof(__fp16))) {
+ mmctx->vtcm_act_raw_stride = hex_round_up(ne10 * act_elem_size, 128);
} else {
mmctx->vtcm_act_raw_stride = 0;
}
@@ -1968,7 +2079,7 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, m_start, cur_m_rows);
}
- work_queue_run(octx->ctx->hvx_queue, matmul_job_func, mmctx, octx->n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, matmul_task_func, mmctx, octx->n_hvx);
}
} else {
mmctx->cur_m_start = 0;
@@ -1983,7 +2094,7 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) {
hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, 0, act_nrows);
}
- work_queue_run(octx->ctx->hvx_queue, matmul_job_func, mmctx, octx->n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, matmul_task_func, mmctx, octx->n_hvx);
}
return HTP_STATUS_OK;
@@ -1994,8 +2105,11 @@ static void dequantize_tiled_worker_loop(const htp_thread_t * th, unsigned int n
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i);
for (unsigned int task_id = i; task_id < (unsigned int) state->n_tasks; task_id += n) {
- int start = task_id * state->n_tiles_per_task;
- int end = hex_smin(start + state->n_tiles_per_task, state->n_tot_tiles);
+ const uint32_t start = task_id * state->n_tiles_per_task;
+ if (start >= state->n_tot_tiles) {
+ break;
+ }
+ const uint32_t end = hex_smin(start + state->n_tiles_per_task, state->n_tot_tiles);
state->task_fn(state, start, end);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i);
@@ -2010,12 +2124,16 @@ static void transfer_output_chunk_worker_fn(const htp_thread_t * th, unsigned in
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, start_chunk_idx);
for (unsigned int task_id = i; task_id < (unsigned int)st->n_tasks; task_id += n) {
- int chunk_idx = task_id * st->n_chunks_per_task;
- size_t chunk_size = hex_smin(st->n_tot_chunks - chunk_idx, st->n_chunks_per_task);
+ const uint32_t chunk_idx = task_id * st->n_chunks_per_task;
+ if (chunk_idx >= st->n_tot_chunks) {
+ continue;
+ }
+ const uint32_t chunk_size = hex_smin(st->n_tot_chunks - chunk_idx, st->n_chunks_per_task);
- float *dst = st->dst + chunk_idx * st->dst_stride;
- const float *src2 = st->src2 ? (st->src2 + chunk_idx * st->src2_stride) : NULL;
- transfer_output_chunk_fp16_to_fp32(dst, src2, st->vtcm_src, chunk_idx, chunk_size, st->n_cols, st->dst_stride, st->src2_stride, st->dst_cols);
+ void * dst = (uint8_t *) st->dst + (size_t) chunk_idx * st->dst_stride * st->dst_elem_size;
+ const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) chunk_idx * st->bias_stride * st->bias_elem_size) : NULL;
+ st->col_chunk_fn(dst, bias, st->vtcm_src, chunk_idx, chunk_size,
+ st->n_cols, st->n_cols, st->dst_stride, st->bias_stride, st->dst_cols, st->bias_elem_size);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, start_chunk_idx);
@@ -2050,9 +2168,10 @@ typedef struct {
size_t vtcm_f32_act_bytes;
uint32_t dma_step_rows;
uint32_t dma_step_rows_shift;
+ uint32_t act_elem_size;
} activation_transfer_col_chunk_state_t;
-static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk(
+static void transfer_activation_chunk_to_fp16_dma_pipelined_col_chunk(
dma_queue *dma_q,
__fp16 *restrict vtcm_dst,
dma_addr_t act_dma_addr,
@@ -2062,7 +2181,8 @@ static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk(
uint32_t k_chunk_valid,
uint32_t c_first,
uint32_t c_len,
- float *thread_f32_act,
+ uint8_t *act_spad,
+ uint32_t act_elem_size,
struct htp_thread_trace *tr,
uint32_t dma_step_rows,
uint32_t dma_step_rows_shift) {
@@ -2072,40 +2192,59 @@ static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk(
const uint32_t n_steps = n_rows_padded >> dma_step_rows_shift;
+ const bool act_is_f16 = (act_elem_size == sizeof(__fp16));
+ const size_t row_bytes = (size_t) c_len * act_elem_size;
+ const size_t src_row_bytes = (size_t) k_stride * act_elem_size;
+ const size_t width_bytes = (size_t) k_chunk_valid * act_elem_size;
+ const size_t src_col_offset = (size_t) c_first * act_elem_size;
+
// Push step 0
if (n_steps > 0 && n_rows > 0) {
uint32_t nrows_to_fetch = hex_smin(n_rows, R);
- dma_queue_push(dma_q, dma_make_data(thread_f32_act, act_dma_addr + (size_t) c_first * sizeof(float)),
- c_len * sizeof(float), k_stride * sizeof(float), k_chunk_valid * sizeof(float), nrows_to_fetch);
+ dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr + src_col_offset),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
}
// Push step 1
if (n_steps > 1) {
uint32_t next_r = R * 1;
if (next_r < n_rows) {
uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, R);
- float *next_buf = thread_f32_act + 1 * R * c_len;
- dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + ((size_t) next_r * k_stride + c_first) * sizeof(float)),
- c_len * sizeof(float), k_stride * sizeof(float), k_chunk_valid * sizeof(float), nrows_to_fetch);
+ uint8_t *next_buf = act_spad + 1 * R * row_bytes;
+ dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + (size_t) next_r * src_row_bytes + src_col_offset),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
}
}
for (uint32_t s = 0; s < n_steps; ++s) {
uint32_t r = s << dma_step_rows_shift;
- float *curr_buf = thread_f32_act;
+ uint8_t *curr_buf = act_spad;
if (r < n_rows) {
- curr_buf = (float *) dma_queue_pop(dma_q).dst;
+ curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst;
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
- for (uint32_t p = 0; p < (R >> 1); ++p) {
- uint32_t row_idx = r + (p << 1);
- float *pair_buf = curr_buf + (p << 1) * c_len;
- bool r0_valid = ((row_idx + 0) < n_rows);
- bool r1_valid = ((row_idx + 1) < n_rows);
-
- transfer_activation_row_pair_fp32_to_fp16_col_chunk(
- vtcm_dst, pair_buf, pair_buf + c_len, row_idx, k_block, c_first, c_len, k_chunk_valid, r0_valid, r1_valid
- );
+ if (act_is_f16) {
+ for (uint32_t p = 0; p < (R >> 1); ++p) {
+ uint32_t row_idx = r + (p << 1);
+ const __fp16 *pair_buf = (const __fp16 *) (curr_buf + (p << 1) * row_bytes);
+ bool r0_valid = ((row_idx + 0) < n_rows);
+ bool r1_valid = ((row_idx + 1) < n_rows);
+
+ transfer_activation_row_pair_f16_to_f16_col_chunk(
+ vtcm_dst, pair_buf, pair_buf + c_len, row_idx, k_block, c_first, c_len, k_chunk_valid, r0_valid, r1_valid
+ );
+ }
+ } else {
+ for (uint32_t p = 0; p < (R >> 1); ++p) {
+ uint32_t row_idx = r + (p << 1);
+ const float *pair_buf = (const float *) (curr_buf + (p << 1) * row_bytes);
+ bool r0_valid = ((row_idx + 0) < n_rows);
+ bool r1_valid = ((row_idx + 1) < n_rows);
+
+ transfer_activation_row_pair_fp32_to_fp16_col_chunk(
+ vtcm_dst, pair_buf, pair_buf + c_len, row_idx, k_block, c_first, c_len, k_chunk_valid, r0_valid, r1_valid
+ );
+ }
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
@@ -2114,8 +2253,8 @@ static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk(
uint32_t next_r = next_s << dma_step_rows_shift;
if (next_r < n_rows) {
uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, R);
- dma_queue_push(dma_q, dma_make_data(curr_buf, act_dma_addr + ((size_t) next_r * k_stride + c_first) * sizeof(float)),
- c_len * sizeof(float), k_stride * sizeof(float), k_chunk_valid * sizeof(float), nrows_to_fetch);
+ dma_queue_push(dma_q, dma_make_data(curr_buf, act_dma_addr + (size_t) next_r * src_row_bytes + src_col_offset),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
}
}
}
@@ -2125,11 +2264,19 @@ static void transfer_activation_chunk_col_chunk_worker_fn(const htp_thread_t * t
struct htp_thread_trace * tr = th->trace;
uint32_t n_blocks = st->k_block / 32;
- uint32_t b_first = fastdiv(n_blocks * i, &st->n_hvx_div);
- uint32_t b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div);
+ uint32_t b_first;
+ uint32_t b_last;
+ if (st->act_elem_size == sizeof(__fp16)) {
+ uint32_t n_pairs = n_blocks / 2;
+ b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2;
+ b_last = fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2;
+ } else {
+ b_first = fastdiv(n_blocks * i, &st->n_hvx_div);
+ b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div);
+ }
uint32_t c_first = b_first * 32;
- uint32_t c_last = b_last * 32;
- uint32_t c_len = c_last - c_first;
+ uint32_t c_last = b_last * 32;
+ uint32_t c_len = c_last - c_first;
if (c_len == 0) {
return;
@@ -2142,12 +2289,12 @@ static void transfer_activation_chunk_col_chunk_worker_fn(const htp_thread_t * t
__fp16 *dst = st->dst;
- size_t thread_scratch_bytes = hex_align_down(fastdiv(st->vtcm_f32_act_bytes, &st->n_hvx_div), 128);
- float *thread_f32_act = (float *)((char *)st->vtcm_f32_act + i * thread_scratch_bytes);
+ size_t scratch_bytes_per_hvx = hex_align_down(fastdiv(st->vtcm_f32_act_bytes, &st->n_hvx_div), 128);
+ uint8_t *act_spad = (uint8_t *)st->vtcm_f32_act + i * scratch_bytes_per_hvx;
- transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk(
+ transfer_activation_chunk_to_fp16_dma_pipelined_col_chunk(
th->dma_q, dst, st->act_dma_addr, st->n_rows, st->k_block, st->k_stride, k_chunk_valid,
- c_first, c_len, thread_f32_act, tr, st->dma_step_rows, st->dma_step_rows_shift
+ c_first, c_len, act_spad, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift
);
}
@@ -2159,7 +2306,7 @@ static void transfer_activation_chunk_to_fp16_dma_pipelined(
uint32_t k_block,
uint32_t k_stride,
uint32_t k_valid,
- uint8_t *thread_act,
+ uint8_t *act_spad,
uint32_t act_elem_size,
struct htp_thread_trace *tr,
uint32_t dma_step_rows,
@@ -2178,7 +2325,7 @@ static void transfer_activation_chunk_to_fp16_dma_pipelined(
// Push step 0
if (n_steps > 0 && n_rows > 0) {
uint32_t nrows_to_fetch = hex_smin(n_rows, R);
- dma_queue_push(dma_q, dma_make_data(thread_act, act_dma_addr),
+ dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr),
row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
}
// Push step 1 (if valid)
@@ -2186,14 +2333,14 @@ static void transfer_activation_chunk_to_fp16_dma_pipelined(
uint32_t next_r = R * 1;
if (next_r < n_rows) {
uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, R);
- uint8_t *next_buf = thread_act + 1 * R * row_bytes;
+ uint8_t *next_buf = act_spad + 1 * R * row_bytes;
dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + (size_t) next_r * src_row_bytes),
row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
}
}
for (uint32_t s = 0; s < n_steps; ++s) {
uint32_t r = s << dma_step_rows_shift;
- uint8_t *curr_buf = thread_act;
+ uint8_t *curr_buf = act_spad;
if (r < n_rows) {
curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst;
@@ -2246,19 +2393,103 @@ static void transfer_activation_chunk_worker_fn(const htp_thread_t * th, unsigne
__fp16 *dst = st->dst + chunk_idx * st->k_block;
const dma_addr_t act_dma_addr = st->act_dma_addr + (size_t) chunk_idx * st->k_stride * st->act_elem_size;
- uint8_t *thread_act = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx;
+ uint8_t *act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx;
transfer_activation_chunk_to_fp16_dma_pipelined(
- th->dma_q, dst, act_dma_addr, chunk_size, st->k_block, st->k_stride, st->k_valid, thread_act, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift
+ th->dma_q, dst, act_dma_addr, chunk_size, st->k_block, st->k_stride, st->k_valid, act_spad, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift
);
}
}
+static inline void push_gathered_act_rows_dma(
+ 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(
+ 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(
+ 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(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);
+ }
+ }
+}
+
typedef struct {
const struct mmid_row_mapping * matrix_rows;
__fp16 * dst;
- const float * src;
- uint32_t n_tasks;
- uint32_t n_tot_chunks;
+ dma_addr_t act_dma_addr;
+ float * vtcm_f32_act;
+ size_t vtcm_f32_act_bytes_per_hvx;
+ size_t act_elem_size;
+ uint32_t n_rows;
+ uint32_t mc_pad;
uint32_t n_chunks_per_task;
uint32_t k_block;
uint32_t cur_a;
@@ -2268,90 +2499,95 @@ typedef struct {
size_t nb11;
size_t nb12;
uint32_t start_row;
- uint32_t cne1;
uint32_t k_valid;
} activation_transfer_gathered_task_state_t;
-typedef struct {
- const struct mmid_row_mapping * matrix_rows;
- const __fp16 * vtcm_src;
- float * dst;
- uint32_t n_tasks;
- uint32_t n_tot_chunks;
- uint32_t n_chunks_per_task;
- uint32_t n_cols;
- uint32_t cur_a;
- uint32_t mapping_stride;
- size_t dst_nb1;
- size_t dst_nb2;
- uint32_t start_row;
- uint32_t cne1;
-} output_transfer_scattered_task_state_t;
-
static void transfer_activation_chunk_gathered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- activation_transfer_gathered_task_state_t *st = data;
+ (void) n;
+ activation_transfer_gathered_task_state_t * st = (activation_transfer_gathered_task_state_t *) data;
struct htp_thread_trace * tr = th->trace;
- int chunk_idx = i;
- int chunk_size = st->n_chunks_per_task;
- int vtcm_start_row = chunk_idx * chunk_size;
- int start_row = st->start_row + vtcm_start_row;
- int n_rows = hex_smin(st->cne1 - start_row, chunk_size);
- if (n_rows > 0) {
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx);
- transfer_activation_chunk_fp32_to_fp16_gathered(
- st->dst, st->src, start_row, vtcm_start_row, n_rows, st->k_block,
- st->matrix_rows, st->cur_a, st->mapping_stride,
- st->ne11, &st->ne11_div, st->nb11, st->nb12, st->cne1, st->k_valid);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx);
- }
-}
+ dma_queue * dma_q = th->dma_q;
-static void transfer_activation_chunk_gathered_worker_flat_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- activation_transfer_gathered_task_state_t *st = data;
- struct htp_thread_trace * tr = th->trace;
- int chunk_idx = i;
- int chunk_size = st->n_chunks_per_task;
- int vtcm_start_row = chunk_idx * chunk_size;
- int start_row = st->start_row + vtcm_start_row;
- int n_rows = hex_smin(st->cne1 - start_row, chunk_size);
- if (n_rows > 0) {
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx);
- transfer_activation_chunk_fp32_to_fp16_gathered_flat(
- st->dst, st->src, start_row, vtcm_start_row, n_rows, st->k_block,
- st->matrix_rows, st->cur_a, st->mapping_stride,
- st->nb12, st->cne1, st->k_valid);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx);
+ const uint32_t vtcm_start_row = i * st->n_chunks_per_task;
+ if (vtcm_start_row >= st->mc_pad) {
+ return;
}
-}
-
-static void transfer_output_chunk_scattered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- output_transfer_scattered_task_state_t *st = data;
- struct htp_thread_trace * tr = th->trace;
- int chunk_idx = i;
- int chunk_size = st->n_chunks_per_task;
- int vtcm_start_row = chunk_idx * chunk_size;
- int start_row = st->start_row + vtcm_start_row;
- int n_rows = hex_smin(st->cne1 - start_row, chunk_size);
- if (n_rows > 0) {
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, chunk_idx);
- transfer_output_chunk_fp16_to_fp32_scattered(
- st->dst, st->vtcm_src, start_row, vtcm_start_row, n_rows, st->n_cols,
- st->matrix_rows, st->cur_a, st->mapping_stride,
- st->dst_nb1, st->dst_nb2, st->cne1);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, chunk_idx);
+ const uint32_t vtcm_end_row = hex_smin(vtcm_start_row + st->n_chunks_per_task, st->mc_pad);
+ const bool act_is_f16 = (st->act_elem_size == sizeof(__fp16));
+ const size_t row_bytes = (size_t) st->k_block * st->act_elem_size;
+ const size_t valid_bytes = (size_t) st->k_valid * st->act_elem_size;
+ const size_t slot_bytes = 2u * row_bytes;
+ const bool double_buf = (st->vtcm_f32_act_bytes_per_hvx >= 2u * slot_bytes);
+ uint8_t * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx;
+
+ if (double_buf) {
+ if (vtcm_start_row < st->n_rows) {
+ const uint32_t nrows = hex_smin(st->n_rows - vtcm_start_row, 2u);
+ push_gathered_act_rows_dma(dma_q, act_spad, st->act_dma_addr, nrows, st->start_row, vtcm_start_row,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ const uint32_t r1 = vtcm_start_row + 2u;
+ if (r1 < vtcm_end_row && r1 < st->n_rows) {
+ const uint32_t nrows = hex_smin(st->n_rows - r1, 2u);
+ push_gathered_act_rows_dma(dma_q, act_spad + slot_bytes, st->act_dma_addr, nrows, st->start_row, r1,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
}
-}
-// --- HMX Dispatchers & Entry Points ---
+ uint32_t step = 0;
+ for (uint32_t r = vtcm_start_row; r < vtcm_end_row; r += 2u, ++step) {
+ uint8_t * curr_buf = act_spad + (double_buf ? (step & 1u) * slot_bytes : 0u);
+ const uint32_t valid_rows = (r < st->n_rows) ? hex_smin(st->n_rows - r, 2u) : 0u;
-static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type, bool is_tiled) {
- switch (weight_type) {
- case HTP_TYPE_Q4_0: return dequantize_tiled_weight_to_fp16_task_q4_0;
- case HTP_TYPE_IQ4_NL: return dequantize_tiled_weight_to_fp16_task_iq4_nl;
- case HTP_TYPE_Q4_1:
- case HTP_TYPE_Q4_K: return dequantize_tiled_weight_to_fp16_task_q4_1;
- case HTP_TYPE_MXFP4: return dequantize_tiled_weight_to_fp16_task_mxfp4;
- case HTP_TYPE_NVFP4: return dequantize_tiled_weight_to_fp16_task_nvfp4;
+ if (valid_rows > 0) {
+ if (!double_buf) {
+ push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, valid_rows, st->start_row, r,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ for (uint32_t s = 0; s < valid_rows; ++s) {
+ dma_queue_pop(dma_q);
+ }
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
+ if (act_is_f16) {
+ const __fp16 * pair_buf = (const __fp16 *) curr_buf;
+ transfer_activation_row_pair_f16_to_f16(
+ st->dst, pair_buf, pair_buf + st->k_block, r, st->k_block, st->k_valid,
+ valid_rows >= 1u, valid_rows >= 2u);
+ } else {
+ const float * pair_buf = (const float *) curr_buf;
+ transfer_activation_row_pair_fp32_to_fp16(
+ st->dst, pair_buf, pair_buf + st->k_block, r, st->k_block, st->k_valid,
+ valid_rows >= 1u, valid_rows >= 2u);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
+
+ if (double_buf) {
+ const uint32_t next_r = r + 4u;
+ if (next_r < vtcm_end_row && next_r < st->n_rows) {
+ const uint32_t nrows = hex_smin(st->n_rows - next_r, 2u);
+ push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, nrows, st->start_row, next_r,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ }
+ }
+}
+
+// --- HMX Dispatchers & Entry Points ---
+
+static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type, bool is_tiled) {
+ switch (weight_type) {
+ case HTP_TYPE_Q4_0: return dequantize_tiled_weight_to_fp16_task_q4_0;
+ case HTP_TYPE_IQ4_NL: return dequantize_tiled_weight_to_fp16_task_iq4_nl;
+ case HTP_TYPE_Q4_1:
+ case HTP_TYPE_Q4_K: return dequantize_tiled_weight_to_fp16_task_q4_1;
+ case HTP_TYPE_MXFP4: return dequantize_tiled_weight_to_fp16_task_mxfp4;
+ case HTP_TYPE_NVFP4: return dequantize_tiled_weight_to_fp16_task_nvfp4;
case HTP_TYPE_IQ2_XXS: return dequantize_tiled_weight_to_fp16_task_iq2_xxs;
case HTP_TYPE_Q8_0: return dequantize_tiled_weight_to_fp16_task_q8_0;
case HTP_TYPE_Q5_0: return dequantize_tiled_weight_to_fp16_task_q5_0;
@@ -2370,12 +2606,12 @@ static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type,
}
static void dequantize_tiled_weight_chunk_to_fp16_tiles(
- struct htp_context *ctx, __fp16 *vtcm_dst,
+ struct htp_ops_context *octx, __fp16 *vtcm_dst,
const void *weight_src_ddr,
int n_cols, int k_block,
size_t row_stride, int weight_type,
int n_k_tiles, struct fastdiv_values n_k_tiles_div,
- tiled_dequant_task_fn_t dequant_worker_fn, int n_hvx) {
+ tiled_dequant_task_fn_t dequant_worker_fn) {
if (!dequant_worker_fn) {
return;
@@ -2383,14 +2619,19 @@ static void dequantize_tiled_weight_chunk_to_fp16_tiles(
assert(k_block % HTP_MM_HMX_TILE_N_COLS == 0);
- const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+ const int n_hvx = (int) octx->n_hvx;
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
const uint32_t n_weight_tiles = k_block / htp_tensor_get_tile_k(weight_type);
- const size_t n_tot_tiles = n_col_tiles * n_weight_tiles;
+ const size_t n_tot_tiles = n_col_tiles * n_weight_tiles;
+ if (n_tot_tiles == 0) {
+ return;
+ }
- size_t n_tiles_per_task = (n_hvx == 1) ? n_tot_tiles : hmx_ceil_div(n_tot_tiles, n_hvx);
+ const size_t n_tiles_per_task = (n_hvx <= 1) ? n_tot_tiles
+ : fastdiv(n_tot_tiles + (uint32_t) n_hvx - 1, &octx->n_hvx_div);
tiled_dequantize_state_t state;
- state.n_tasks = (n_tot_tiles + n_tiles_per_task - 1) / n_tiles_per_task;
+ state.n_tasks = hex_smin((int) n_tot_tiles, n_hvx);
state.n_tot_tiles = n_tot_tiles;
state.n_tiles_per_task = n_tiles_per_task;
state.dst = vtcm_dst;
@@ -2404,23 +2645,26 @@ static void dequantize_tiled_weight_chunk_to_fp16_tiles(
state.n_weight_tiles = n_weight_tiles;
state.n_k_tiles_div = n_k_tiles_div;
- state.tile_size = htp_tensor_get_tile_size(weight_type);
- state.aligned_tile_size = htp_tensor_get_tile_padded_size(weight_type);
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ state.tile_size = kparams->tile_size;
+ state.aligned_tile_size = kparams->aligned_tile_size;
- int n_tasks = hex_smin((int) state.n_tasks, n_hvx);
- work_queue_run(ctx->hvx_queue, dequantize_tiled_worker_loop, &state, n_tasks);
+ work_queue_run(octx->ctx->hvx_queue, dequantize_tiled_worker_loop, &state, (int) state.n_tasks);
}
typedef struct {
- float * dst;
- const __fp16 * vtcm_src;
- const float * src2;
- uint32_t n_rows;
- uint32_t n_cols;
- uint32_t dst_stride;
- uint32_t src2_stride;
- uint32_t dst_cols;
- struct fastdiv_values n_hvx_div;
+ hmx_fp16_output_col_chunk_fn_t col_chunk_fn;
+ void * dst;
+ const __fp16 * vtcm_src;
+ const void * bias;
+ uint32_t n_rows;
+ uint32_t n_cols;
+ uint32_t dst_stride;
+ uint32_t bias_stride;
+ uint32_t dst_cols;
+ size_t dst_elem_size;
+ size_t bias_elem_size;
+ struct fastdiv_values n_hvx_div;
} output_transfer_col_chunk_state_t;
static void transfer_output_chunk_col_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
@@ -2431,72 +2675,97 @@ static void transfer_output_chunk_col_chunk_worker_fn(const htp_thread_t * th, u
// Round up: the last block is partial when N is not 32-aligned. Its pad
// columns are dropped by the dst_cols clamp inside the store.
uint32_t n_blocks = hmx_ceil_div(st->n_cols, 32);
- uint32_t b_first = fastdiv(n_blocks * i, &st->n_hvx_div);
- uint32_t b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div);
- uint32_t c_first = b_first * 32;
- uint32_t c_last = b_last * 32;
- uint32_t c_len = c_last - c_first;
-
- if (c_len == 0) return;
+ uint32_t b_first;
+ uint32_t b_last;
+ if (st->dst_elem_size == sizeof(__fp16)) {
+ uint32_t n_pairs = hmx_ceil_div(n_blocks, 2);
+ b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2;
+ b_last = MIN(n_blocks, fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2);
+ } else {
+ b_first = fastdiv(n_blocks * i, &st->n_hvx_div);
+ b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div);
+ }
+ if (b_first >= b_last) return;
+ uint32_t c_first = b_first * 32;
+ uint32_t c_last = b_last * 32;
+ uint32_t c_len = c_last - c_first;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
- const __fp16 *vtcm_src = st->vtcm_src + b_first * HTP_MM_HMX_TILE_N_ELMS;
- const float *src2 = st->src2 ? (st->src2 + c_first) : NULL;
- float *dst = st->dst + c_first;
+ const __fp16 * vtcm_src = st->vtcm_src + b_first * HTP_MM_HMX_TILE_N_ELMS;
+ const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) c_first * st->bias_elem_size) : NULL;
+ void * dst = (uint8_t *) st->dst + (size_t) c_first * st->dst_elem_size;
int chunk_dst_cols = (int)st->dst_cols - (int)c_first;
if (chunk_dst_cols > 0) {
- transfer_output_chunk_fp16_to_fp32_col_chunk(
- dst, src2, vtcm_src, 0, st->n_rows, c_len, st->n_cols,
- st->dst_stride, st->src2_stride, (uint32_t)chunk_dst_cols
- );
+ st->col_chunk_fn(dst, bias, vtcm_src, 0, st->n_rows, c_len, st->n_cols,
+ st->dst_stride, st->bias_stride, (uint32_t)chunk_dst_cols, st->bias_elem_size);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
}
-static void transfer_output_chunk_threaded(struct htp_context *ctx, float *dst, const float *src2, const __fp16 *vtcm_src,
- int n_rows, int n_cols, int dst_stride, uint32_t src2_stride, int dst_cols, int n_hvx) {
- if (n_rows <= 0) return;
-
- uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32);
- if (n_hvx > 1 && n_blocks >= (uint32_t)n_hvx) {
- struct fastdiv_values n_hvx_div = (n_hvx == (int)ctx->n_hvx) ? ctx->n_hvx_div : init_fastdiv_values(n_hvx);
- output_transfer_col_chunk_state_t col_state;
- col_state.dst = dst;
- col_state.src2 = src2;
- col_state.vtcm_src = vtcm_src;
- col_state.n_rows = (uint32_t)n_rows;
- col_state.n_cols = (uint32_t)n_cols;
- col_state.dst_stride = (uint32_t)dst_stride;
- col_state.src2_stride = src2_stride;
- col_state.dst_cols = (uint32_t)dst_cols;
- col_state.n_hvx_div = n_hvx_div;
-
- work_queue_run(ctx->hvx_queue, transfer_output_chunk_col_chunk_worker_fn, &col_state, n_hvx);
+static void transfer_output_chunk_threaded(struct htp_ops_context *octx, void *dst, const void *bias, const __fp16 *vtcm_src,
+ int n_rows, int n_cols, int dst_stride, uint32_t bias_stride, int dst_cols,
+ size_t dst_elem_size, size_t bias_elem_size) {
+ if (n_rows <= 0 || dst_cols <= 0) {
return;
}
- size_t n_tot_chunks = n_rows;
- size_t n_chunks_per_task = (n_hvx == 1) ? n_tot_chunks : hmx_ceil_div(n_rows, n_hvx);
- n_chunks_per_task = hex_align_up(n_chunks_per_task, 2);
+ const bool dst_aligned_nt = ((((uintptr_t) dst | ((size_t) dst_stride * dst_elem_size)) & 127u) == 0);
+ const hmx_fp16_output_col_chunk_fn_t col_chunk_fn =
+ resolve_fp16_output_col_chunk_fn(dst_elem_size, bias, bias_elem_size, dst_aligned_nt);
+
+ const int n_hvx = (int) octx->n_hvx;
+ const uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32);
+ const uint32_t n_units = (dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks;
+ const bool prefer_row_chunk = ((uint32_t) n_rows >= (uint32_t) n_hvx * 32u);
+ if (n_hvx > 1 && !prefer_row_chunk && n_units >= (uint32_t) n_hvx) {
+ const uint32_t n_row_pairs = ((uint32_t) n_rows + 1u) >> 1;
+ const uint32_t row_max = fastdiv(n_row_pairs + (uint32_t) n_hvx - 1u, &octx->n_hvx_div);
+ const uint32_t col_max = fastdiv(n_units + (uint32_t) n_hvx - 1u, &octx->n_hvx_div);
+ if ((uint64_t) n_units * row_max > (uint64_t) n_row_pairs * col_max) {
+ output_transfer_col_chunk_state_t col_state;
+ col_state.col_chunk_fn = col_chunk_fn;
+ col_state.dst = dst;
+ col_state.bias = bias;
+ col_state.vtcm_src = vtcm_src;
+ col_state.n_rows = (uint32_t) n_rows;
+ col_state.n_cols = (uint32_t) n_cols;
+ col_state.dst_stride = (uint32_t) dst_stride;
+ col_state.bias_stride = bias_stride;
+ col_state.dst_cols = (uint32_t) dst_cols;
+ col_state.dst_elem_size = dst_elem_size;
+ col_state.bias_elem_size = bias_elem_size;
+ col_state.n_hvx_div = octx->n_hvx_div;
+
+ work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_col_chunk_worker_fn, &col_state, n_hvx);
+ return;
+ }
+ }
- int actual_hvx = hmx_ceil_div(n_rows, n_chunks_per_task);
+ const uint32_t chunk_align = prefer_row_chunk ? 32u : 2u;
+ uint32_t n_chunks_per_task = (n_hvx <= 1) ? (uint32_t) n_rows
+ : fastdiv((uint32_t) n_rows + (uint32_t) n_hvx - 1u, &octx->n_hvx_div);
+ n_chunks_per_task = hex_align_up(n_chunks_per_task, chunk_align);
+ const int actual_hvx = hex_smin(n_hvx, ((int) n_rows + 1) >> 1);
output_transfer_task_state_t state;
- state.n_tasks = actual_hvx;
- state.n_tot_chunks = n_tot_chunks;
+ state.col_chunk_fn = col_chunk_fn;
+ state.n_tasks = (uint32_t) actual_hvx;
+ state.n_tot_chunks = (uint32_t) n_rows;
state.n_chunks_per_task = n_chunks_per_task;
state.dst = dst;
- state.src2 = src2;
+ state.bias = bias;
state.vtcm_src = vtcm_src;
- state.n_cols = n_cols;
- state.dst_stride = dst_stride;
- state.src2_stride = src2_stride;
- state.dst_cols = dst_cols;
-
- work_queue_run(ctx->hvx_queue, transfer_output_chunk_worker_fn, &state, actual_hvx);
+ state.n_cols = (uint32_t) n_cols;
+ state.dst_stride = (uint32_t) dst_stride;
+ state.bias_stride = bias_stride;
+ state.dst_cols = (uint32_t) dst_cols;
+ state.dst_elem_size = dst_elem_size;
+ state.bias_elem_size = bias_elem_size;
+
+ work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_worker_fn, &state, actual_hvx);
}
struct activation_transfer_params {
@@ -2536,14 +2805,17 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_
}
const size_t n_tasks = (n_rows + 31) >> 5;
- if (act_elem_size == sizeof(float) && n_hvx > 1 && k_block > 32 && n_tasks < (size_t) n_hvx) {
+ const bool col_chunk_ok = (act_elem_size == sizeof(float))
+ ? (k_block >= 32 * n_hvx)
+ : ((k_block & 63) == 0 && (k_block >> 6) >= n_hvx);
+ if (n_hvx > 1 && col_chunk_ok && n_tasks < (size_t) n_hvx) {
// Calculate step rows parameters for column-chunked dma pipelining
uint32_t dma_step_rows = 2;
uint32_t dma_step_rows_shift = 1;
if (vtcm_f32_act_bytes > 0) {
- size_t thread_scratch_bytes = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128);
- size_t thread_scratch_elements = thread_scratch_bytes / sizeof(float);
- size_t dma_step_rows_max = fastdiv(thread_scratch_elements / 2, k_div);
+ size_t scratch_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128);
+ size_t scratch_elems_per_hvx = scratch_bytes_per_hvx / act_elem_size;
+ size_t dma_step_rows_max = fastdiv(scratch_elems_per_hvx / 2, k_div);
if (dma_step_rows_max >= 4) {
dma_step_rows = 4;
dma_step_rows_shift = 2;
@@ -2563,6 +2835,7 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_
col_state.vtcm_f32_act_bytes = vtcm_f32_act_bytes;
col_state.dma_step_rows = dma_step_rows;
col_state.dma_step_rows_shift = dma_step_rows_shift;
+ col_state.act_elem_size = act_elem_size;
work_queue_run(ctx->hvx_queue, transfer_activation_chunk_col_chunk_worker_fn, &col_state, n_hvx);
return;
@@ -2590,8 +2863,8 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_
uint32_t dma_step_rows = 2;
uint32_t dma_step_rows_shift = 1;
if (state.vtcm_f32_act_bytes_per_hvx > 0) {
- size_t thread_scratch_elements = state.vtcm_f32_act_bytes_per_hvx / sizeof(float);
- size_t dma_step_rows_max = fastdiv(thread_scratch_elements / 2, k_div);
+ size_t scratch_elems_per_hvx = state.vtcm_f32_act_bytes_per_hvx / act_elem_size;
+ size_t dma_step_rows_max = fastdiv(scratch_elems_per_hvx / 2, k_div);
if (dma_step_rows_max >= 4) {
dma_step_rows = 4;
dma_step_rows_shift = 2;
@@ -2603,25 +2876,686 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_
int active_hvx = hex_smin(n_hvx, (int)state.n_tasks);
work_queue_run(ctx->hvx_queue, transfer_activation_chunk_worker_fn, &state, active_hvx);
}
-// --- Async HMX matmul job (for pipeline overlap) ---
+
+// --- INT HMX W8A8 SM Threaded Helpers ---
+
+static void rescale_int_weight_worker_loop(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ int_weight_rescale_state_t * state = (int_weight_rescale_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i);
+ for (unsigned int task_id = i; task_id < state->n_tasks; task_id += n) {
+ uint32_t start = task_id * state->n_units_per_task;
+ if (start >= state->n_tot_units) {
+ break;
+ }
+ uint32_t end = hex_smin(start + state->n_units_per_task, state->n_tot_units);
+ rescale_int_weight_to_int8_task(state, start, end);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i);
+}
+
+static void rescale_int_weight_chunk_to_int8_tiles_scales(
+ struct htp_ops_context * octx,
+ void * vtcm_weight_buf,
+ size_t weight_bias_offset,
+ float * dst_scales,
+ const void * weight_src_raw,
+ int n_cols,
+ int k_block,
+ int n_groups,
+ const struct fastdiv_values * n_groups_div,
+ int aligned_tile_size,
+ int32_t weight_type) {
+
+ const int n_hvx = (int) octx->n_hvx;
+ const uint32_t n_col_tiles = (uint32_t) hmx_ceil_div(n_cols, 32);
+ const uint32_t n_k_tiles = (uint32_t) (k_block >> 5);
+ const uint32_t tail_tiles = n_k_tiles - ((uint32_t) n_groups - 1u) * HTP_MM_HMX_W8A8_KGROUP_TILES;
+ const uint32_t n_tot_units = n_col_tiles * (uint32_t) n_groups;
+ if (n_tot_units == 0) {
+ return;
+ }
+
+ const uint32_t n_units_per_task = (n_hvx <= 1) ? n_tot_units
+ : fastdiv(n_tot_units + (uint32_t) n_hvx - 1, &octx->n_hvx_div);
+
+ int_weight_rescale_state_t state;
+ resolve_int_weight_rescale_fns(weight_type, &state.rescale_2k_fn, &state.rescale_tail_fn);
+ state.dst_wt_base = (uint8_t *) vtcm_weight_buf;
+ state.dst_bias_base = (uint8_t *) vtcm_weight_buf + weight_bias_offset;
+ state.dst_scales_base = dst_scales;
+ state.src_raw = (const uint8_t *) weight_src_raw;
+ state.n_col_tiles = n_col_tiles;
+ state.n_k_tiles = n_k_tiles;
+ state.n_groups = (uint32_t) n_groups;
+ state.tail_tiles = tail_tiles;
+ state.aligned_tile_size = (uint32_t) aligned_tile_size;
+ state.raw_shift = (weight_type == HTP_TYPE_Q1_0) ? 2u
+ : ((weight_type == HTP_TYPE_Q2_0) ? 1u : 0u);
+ state.n_tot_units = n_tot_units;
+ state.n_units_per_task = n_units_per_task;
+ state.n_tasks = hex_smin(n_tot_units, (uint32_t) n_hvx);
+ state.n_groups_div = *n_groups_div;
+
+ work_queue_run(octx->ctx->hvx_queue, rescale_int_weight_worker_loop, &state, (int) state.n_tasks);
+}
+
+static void rescale_int_weight_chunk_to_int8_tiles(
+ struct htp_ops_context * octx,
+ void * vtcm_weight_buf,
+ size_t weight_bias_offset,
+ size_t weight_scales_offset,
+ const void * weight_src_raw,
+ int n_cols,
+ int k_block,
+ int n_groups,
+ const struct fastdiv_values * n_groups_div,
+ int aligned_tile_size,
+ int32_t weight_type) {
+ float * dst_scales = (float *) ((uint8_t *) vtcm_weight_buf + weight_scales_offset);
+ rescale_int_weight_chunk_to_int8_tiles_scales(
+ octx, vtcm_weight_buf, weight_bias_offset, dst_scales,
+ weight_src_raw, n_cols, k_block, n_groups, n_groups_div, aligned_tile_size, weight_type);
+}
+
+typedef void (*int_act_dma_pipelined_fn_t)(
+ dma_queue * dma_q,
+ uint8_t * restrict vtcm_act_dst,
+ float * restrict vtcm_act_scales,
+ dma_addr_t act_dma_addr,
+ uint32_t row_start,
+ uint32_t row_end,
+ uint32_t n_rows,
+ uint32_t mc_pad,
+ uint32_t k_block,
+ uint32_t k_stride,
+ uint32_t k_valid,
+ uint32_t n_groups,
+ uint8_t * act_spad,
+ size_t scratch_bytes_per_hvx,
+ struct htp_thread_trace * tr);
+
+typedef struct {
+ int_act_dma_pipelined_fn_t dma_pipelined_fn;
+ uint8_t * vtcm_act_dst;
+ float * vtcm_act_scales;
+ dma_addr_t act_dma_addr;
+ float * vtcm_f32_act;
+ uint32_t n_tasks;
+ uint32_t n_rows;
+ uint32_t mc_pad;
+ uint32_t n_rows_per_task;
+ uint32_t k_block;
+ uint32_t k_stride;
+ uint32_t k_valid;
+ uint32_t n_groups;
+ size_t vtcm_f32_act_bytes_per_hvx;
+} int_activation_transfer_task_state_t;
+
+#define DEFINE_TRANSFER_ACT_CHUNK_DMA_PIPELINED(SFX, ACT_T) \
+static void transfer_activation_chunk_##SFX##_dma_pipelined( \
+ dma_queue * dma_q, \
+ uint8_t * restrict vtcm_act_dst, \
+ float * restrict vtcm_act_scales, \
+ dma_addr_t act_dma_addr, \
+ uint32_t row_start, \
+ uint32_t row_end, \
+ uint32_t n_rows, \
+ uint32_t mc_pad, \
+ uint32_t k_block, \
+ uint32_t k_stride, \
+ uint32_t k_valid, \
+ uint32_t n_groups, \
+ uint8_t * act_spad, \
+ size_t scratch_bytes_per_hvx, \
+ struct htp_thread_trace * tr) { \
+ const uint32_t step_rows = 4u; \
+ const size_t row_bytes = (size_t) k_block * sizeof(ACT_T); \
+ const size_t src_row_bytes = (size_t) k_stride * sizeof(ACT_T); \
+ const size_t width_bytes = (size_t) k_valid * sizeof(ACT_T); \
+ const bool double_buf = (scratch_bytes_per_hvx >= 2 * step_rows * row_bytes); \
+ const uint32_t n_k_tiles = k_block >> 5; \
+ if (double_buf) { \
+ if (row_start < row_end && row_start < n_rows) { \
+ uint32_t nrows_to_fetch = hex_smin(n_rows - row_start, step_rows); \
+ dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr + (size_t) row_start * src_row_bytes), \
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \
+ } \
+ if (row_start + step_rows < row_end && row_start + step_rows < n_rows) { \
+ uint32_t next_r = row_start + step_rows; \
+ uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, step_rows); \
+ uint8_t * next_buf = act_spad + step_rows * row_bytes; \
+ dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + (size_t) next_r * src_row_bytes), \
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \
+ } \
+ } \
+ for (uint32_t r = row_start; r < row_end; r += step_rows) { \
+ uint8_t * curr_buf = act_spad; \
+ if (r < n_rows) { \
+ if (double_buf) { \
+ curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst; \
+ } else { \
+ uint32_t nrows_to_fetch = hex_smin(n_rows - r, step_rows); \
+ dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr + (size_t) r * src_row_bytes), \
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \
+ curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst; \
+ } \
+ } \
+ const uint32_t valid_rows = (r < n_rows) ? hex_smin(n_rows - r, step_rows) : 0u; \
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, r); \
+ quantize_act_step_rows_##SFX( \
+ vtcm_act_dst, vtcm_act_scales, curr_buf, row_bytes, \
+ r, valid_rows, mc_pad, n_k_tiles, n_groups, k_valid); \
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, r); \
+ if (double_buf) { \
+ uint32_t next_r = r + 2 * step_rows; \
+ if (next_r < row_end && next_r < n_rows) { \
+ uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, step_rows); \
+ dma_queue_push(dma_q, dma_make_data(curr_buf, act_dma_addr + (size_t) next_r * src_row_bytes), \
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \
+ } \
+ } \
+ } \
+}
+
+DEFINE_TRANSFER_ACT_CHUNK_DMA_PIPELINED(f16_w8a8, __fp16)
+DEFINE_TRANSFER_ACT_CHUNK_DMA_PIPELINED(f32_w8a8, float)
+
+static inline int_act_dma_pipelined_fn_t resolve_int_act_dma_pipelined_fn(uint32_t act_elem_size) {
+ return (act_elem_size == sizeof(__fp16)) ? transfer_activation_chunk_f16_w8a8_dma_pipelined
+ : transfer_activation_chunk_f32_w8a8_dma_pipelined;
+}
+
+static void transfer_activation_chunk_int_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ int_activation_transfer_task_state_t * st = (int_activation_transfer_task_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ for (unsigned int task_id = i; task_id < st->n_tasks; task_id += n) {
+ uint32_t row_start = task_id * st->n_rows_per_task;
+ if (row_start >= st->mc_pad) {
+ break;
+ }
+ uint32_t row_end = hex_smin(row_start + st->n_rows_per_task, st->mc_pad);
+ uint8_t * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx;
+ st->dma_pipelined_fn(
+ th->dma_q, st->vtcm_act_dst, st->vtcm_act_scales, st->act_dma_addr,
+ row_start, row_end, st->n_rows, st->mc_pad,
+ st->k_block, st->k_stride, st->k_valid, st->n_groups,
+ act_spad, st->vtcm_f32_act_bytes_per_hvx, tr);
+ }
+}
+
+static void transfer_activation_chunk_int_threaded(
+ struct htp_context * ctx,
+ uint8_t * vtcm_act_dst,
+ float * vtcm_act_scales,
+ dma_addr_t act_dma_addr,
+ int n_rows,
+ int k_block,
+ int k_stride,
+ int k_valid,
+ int n_groups,
+ int n_hvx,
+ const struct fastdiv_values * act_hvx_div,
+ float * vtcm_f32_act,
+ size_t vtcm_f32_act_bytes,
+ uint32_t act_elem_size) {
+
+ if (n_rows <= 0) {
+ return;
+ }
+
+ const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, 64u);
+ const uint32_t resolved_esize = act_elem_size ? act_elem_size : (uint32_t) sizeof(float);
+ uint32_t rows_per_task = (n_hvx <= 1) ? mc_pad : fastdiv(mc_pad + (uint32_t) n_hvx - 1, act_hvx_div);
+ rows_per_task = hex_align_up(rows_per_task, 4u);
+
+ int_activation_transfer_task_state_t state;
+ state.dma_pipelined_fn = resolve_int_act_dma_pipelined_fn(resolved_esize);
+ state.vtcm_act_dst = vtcm_act_dst;
+ state.vtcm_act_scales = vtcm_act_scales;
+ state.act_dma_addr = act_dma_addr;
+ state.vtcm_f32_act = vtcm_f32_act;
+ state.n_rows = (uint32_t) n_rows;
+ state.mc_pad = mc_pad;
+ state.n_rows_per_task = rows_per_task;
+ state.n_tasks = (uint32_t) hex_smin(n_hvx, (int) (mc_pad >> 2));
+ state.k_block = (uint32_t) k_block;
+ state.k_stride = (uint32_t) k_stride;
+ state.k_valid = (uint32_t) k_valid;
+ state.n_groups = (uint32_t) n_groups;
+ state.vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128);
+
+ work_queue_run(ctx->hvx_queue, transfer_activation_chunk_int_worker_fn, &state, (int) state.n_tasks);
+}
+
+typedef struct {
+ int_output_col_chunk_fn_t col_chunk_fn;
+ void * dst;
+ const void * bias;
+ const uint8_t * vtcm_src;
+ const float * vtcm_act_scales;
+ const float * vtcm_weight_scales;
+ uint32_t n_rows;
+ uint32_t mc_pad;
+ uint32_t n_cols;
+ uint32_t n_groups;
+ uint32_t dst_stride;
+ uint32_t bias_stride;
+ uint32_t dst_cols;
+ uint32_t n_tasks;
+ uint32_t n_chunks_per_task;
+ size_t dst_elem_size;
+ size_t bias_elem_size;
+ struct fastdiv_values n_hvx_div;
+} int_output_transfer_state_t;
+
+static void transfer_output_chunk_int_col_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ int_output_transfer_state_t * st = (int_output_transfer_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint32_t n_blocks = hmx_ceil_div(st->n_cols, 32);
+ uint32_t b_first;
+ uint32_t b_last;
+ if (st->dst_elem_size == sizeof(__fp16)) {
+ const uint32_t n_pairs = hmx_ceil_div(n_blocks, 2);
+ b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2;
+ b_last = MIN(n_blocks, fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2);
+ } else {
+ b_first = fastdiv(n_blocks * i, &st->n_hvx_div);
+ b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div);
+ }
+ if (b_first >= b_last) {
+ return;
+ }
+ const uint32_t c_first = b_first * 32;
+ const uint32_t c_last = b_last * 32;
+ const uint32_t c_len = c_last - c_first;
+
+ const int chunk_dst_cols = (int) st->dst_cols - (int) c_first;
+ if (chunk_dst_cols <= 0) {
+ return;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
+ const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) c_first * st->bias_elem_size) : NULL;
+ void * dst = (uint8_t *) st->dst + (size_t) c_first * st->dst_elem_size;
+
+ st->col_chunk_fn(
+ dst, bias, st->vtcm_src, st->vtcm_act_scales, st->vtcm_weight_scales,
+ 0, st->n_rows, st->mc_pad, c_first, c_len, st->n_cols, st->n_groups,
+ st->dst_stride, st->bias_stride, (uint32_t) chunk_dst_cols, st->bias_elem_size);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
+}
+
+static void transfer_output_chunk_int_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ int_output_transfer_state_t * st = (int_output_transfer_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint32_t n_quads = (st->n_rows + 3u) >> 2;
+ const uint32_t q_first = (n_quads <= n) ? i : fastdiv(n_quads * i, &st->n_hvx_div);
+ const uint32_t q_last = (n_quads <= n) ? (i + 1u) : fastdiv(n_quads * (i + 1u), &st->n_hvx_div);
+ const uint32_t row_start = q_first << 2;
+ const uint32_t row_end = hex_smin(st->n_rows, q_last << 2);
+ if (row_start >= row_end) {
+ return;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start);
+ const uint32_t chunk_size = row_end - row_start;
+ void * dst = (uint8_t *) st->dst + (size_t) row_start * st->dst_stride * st->dst_elem_size;
+ const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) row_start * st->bias_stride * st->bias_elem_size) : NULL;
+
+ st->col_chunk_fn(
+ dst, bias, st->vtcm_src, st->vtcm_act_scales, st->vtcm_weight_scales,
+ row_start, chunk_size, st->mc_pad, 0, st->n_cols, st->n_cols, st->n_groups,
+ st->dst_stride, st->bias_stride, st->dst_cols, st->bias_elem_size);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start);
+}
+
+static void transfer_output_chunk_int_threaded(
+ struct htp_ops_context * octx,
+ void * dst,
+ const void * bias,
+ const void * vtcm_src,
+ const float * vtcm_act_scales,
+ const float * vtcm_weight_scales,
+ int n_rows,
+ int n_cols,
+ int n_groups,
+ int dst_stride,
+ uint32_t bias_stride,
+ int dst_cols,
+ size_t dst_elem_size,
+ size_t bias_elem_size) {
+
+ if (n_rows <= 0 || dst_cols <= 0) {
+ return;
+ }
+
+ const int n_hvx = (int) octx->n_hvx;
+ const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, 64u);
+ const bool dst_aligned_nt = ((((uintptr_t) dst | ((size_t) dst_stride * dst_elem_size)) & 127u) == 0);
+
+ int_output_transfer_state_t state;
+ state.col_chunk_fn = resolve_int_output_col_chunk_fn((uint32_t) n_groups, dst_elem_size, bias, bias_elem_size, dst_aligned_nt);
+ state.dst = dst;
+ state.bias = bias;
+ state.vtcm_src = (const uint8_t *) vtcm_src;
+ state.vtcm_act_scales = vtcm_act_scales;
+ state.vtcm_weight_scales = vtcm_weight_scales;
+ state.n_rows = (uint32_t) n_rows;
+ state.mc_pad = mc_pad;
+ state.n_cols = (uint32_t) n_cols;
+ state.n_groups = (uint32_t) n_groups;
+ state.dst_stride = (uint32_t) dst_stride;
+ state.bias_stride = bias_stride;
+ state.dst_cols = (uint32_t) dst_cols;
+ state.dst_elem_size = dst_elem_size;
+ state.bias_elem_size = bias_elem_size;
+ state.n_hvx_div = octx->n_hvx_div;
+
+ const uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32);
+ const uint32_t n_units = (dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks;
+ const bool prefer_row_chunk = ((uint32_t) n_rows >= (uint32_t) n_hvx * 64u);
+ if (n_hvx > 1 && !prefer_row_chunk && n_units >= (uint32_t) n_hvx) {
+ work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_col_chunk_worker_fn, &state, n_hvx);
+ return;
+ }
+
+ const int actual_hvx = hex_smin(n_hvx, (n_rows + 3) >> 2);
+ work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_worker_fn, &state, actual_hvx);
+}
+
+static void transfer_output_chunk_int_glu_col_chunk_task(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ hmx_output_glu_state_t * st = (hmx_output_glu_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint32_t n_blocks = hmx_ceil_div(st->n_cols, 32);
+ uint32_t b_first;
+ uint32_t b_last;
+ if (st->dst_elem_size == sizeof(__fp16)) {
+ const uint32_t n_pairs = hmx_ceil_div(n_blocks, 2);
+ b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2;
+ b_last = MIN(n_blocks, fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2);
+ } else {
+ b_first = fastdiv(n_blocks * i, &st->n_hvx_div);
+ b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div);
+ }
+ if (b_first >= b_last) {
+ return;
+ }
+ const uint32_t c_first = b_first * 32;
+ const uint32_t c_len = (b_last - b_first) * 32;
+ const int chunk_dst_cols = (int) st->dst_cols - (int) c_first;
+ if (chunk_dst_cols <= 0) {
+ return;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
+ void * dst = (uint8_t *) st->dst + (size_t) c_first * st->dst_elem_size;
+ const uint32_t eff_dst_cols = (uint32_t) hex_smin((size_t) c_len, (size_t) chunk_dst_cols);
+ st->col_chunk_fn(st, dst, 0, st->n_rows, c_first, (c_len << 16) | eff_dst_cols);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
+}
+
+static void transfer_output_chunk_int_glu_row_task(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ hmx_output_glu_state_t * st = (hmx_output_glu_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint32_t n_quads = (st->n_rows + 3u) >> 2;
+ const uint32_t q_first = (n_quads <= n) ? i : fastdiv(n_quads * i, &st->n_hvx_div);
+ const uint32_t q_last = (n_quads <= n) ? (i + 1u) : fastdiv(n_quads * (i + 1u), &st->n_hvx_div);
+ const uint32_t row_start = q_first << 2;
+ const uint32_t row_end = hex_smin(st->n_rows, q_last << 2);
+ if (row_start >= row_end) {
+ return;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start);
+ const uint32_t eff_dst_cols = (uint32_t) hex_smin((size_t) st->n_cols, (size_t) st->dst_cols);
+ const uint32_t c_packed = (st->n_cols << 16) | eff_dst_cols;
+ const uint32_t chunk_size = row_end - row_start;
+ void * dst = (uint8_t *) st->dst + (size_t) row_start * st->dst_stride * st->dst_elem_size;
+ st->col_chunk_fn(st, dst, row_start, chunk_size, 0, c_packed);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start);
+}
+
+static void transfer_output_chunk_int_glu_threaded(
+ 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) {
+
+ if (n_rows <= 0 || dst_cols <= 0) {
+ return;
+ }
+
+ const int n_hvx = (int) octx->n_hvx;
+ state->dst = dst;
+ state->vtcm_gate = (const uint8_t *) vtcm_gate;
+ state->vtcm_up = (const uint8_t *) vtcm_up;
+ state->vtcm_wt_scales_gate = vtcm_wt_scales_gate;
+ state->vtcm_wt_scales_up = vtcm_wt_scales_up;
+ state->n_rows = (uint32_t) n_rows;
+ state->mc_pad = hex_align_up((uint32_t) n_rows, 64u);
+ state->n_cols = (uint32_t) n_cols;
+ state->dst_cols = (uint32_t) dst_cols;
+ state->n_hvx_div = octx->n_hvx_div;
+
+ const uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32);
+ const uint32_t n_units = (state->dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks;
+ const bool prefer_row_chunk = ((uint32_t) n_rows >= (uint32_t) n_hvx * 64u);
+ if (n_hvx > 1 && !prefer_row_chunk && n_units >= (uint32_t) n_hvx) {
+ work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_glu_col_chunk_task, state, n_hvx);
+ return;
+ }
+
+ const int actual_hvx = hex_smin(n_hvx, (n_rows + 3) >> 2);
+ work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_glu_row_task, state, actual_hvx);
+}
+
+typedef struct {
+ const struct mmid_row_mapping * matrix_rows;
+ uint8_t * vtcm_act_dst;
+ float * vtcm_act_scales;
+ dma_addr_t act_dma_addr;
+ float * vtcm_f32_act;
+ uint32_t act_elem_size;
+ uint32_t n_tasks;
+ uint32_t n_rows;
+ uint32_t mc_pad;
+ uint32_t k_block;
+ uint32_t k_valid;
+ uint32_t n_groups;
+ size_t vtcm_f32_act_bytes_per_hvx;
+ uint32_t start_row;
+ uint32_t cur_a;
+ uint32_t mapping_stride;
+ uint32_t ne11;
+ struct fastdiv_values ne11_div;
+ size_t nb11;
+ size_t nb12;
+} int_activation_transfer_gathered_state_t;
+
+static void transfer_activation_chunk_int_gathered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ int_activation_transfer_gathered_state_t * st = (int_activation_transfer_gathered_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+ dma_queue * dma_q = th->dma_q;
+
+ const uint32_t row_start = i * 4u;
+ const uint32_t row_stride = n * 4u;
+ if (row_start >= st->mc_pad) {
+ return;
+ }
+
+ const bool act_is_f16 = (st->act_elem_size == sizeof(__fp16));
+ const size_t row_bytes = hex_align_up((size_t) st->k_block * st->act_elem_size, 128);
+ const size_t valid_bytes = (size_t) st->k_valid * st->act_elem_size;
+ const size_t slot_bytes = 4u * row_bytes;
+ const bool double_buf = (st->vtcm_f32_act_bytes_per_hvx >= 2u * slot_bytes);
+ const uint32_t n_k_tiles = st->k_block >> 5;
+ uint8_t * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx;
+
+ if (double_buf) {
+ if (row_start < st->n_rows) {
+ const uint32_t nrows = hex_smin(st->n_rows - row_start, 4u);
+ push_gathered_act_rows_dma(dma_q, act_spad, st->act_dma_addr, nrows, st->start_row, row_start,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ const uint32_t r1 = row_start + row_stride;
+ if (r1 < st->mc_pad && r1 < st->n_rows) {
+ const uint32_t nrows = hex_smin(st->n_rows - r1, 4u);
+ push_gathered_act_rows_dma(dma_q, act_spad + slot_bytes, st->act_dma_addr, nrows, st->start_row, r1,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ }
+
+ uint32_t step = 0;
+ for (uint32_t r = row_start; r < st->mc_pad; r += row_stride, ++step) {
+ uint8_t * curr_buf = act_spad + (double_buf ? (step & 1u) * slot_bytes : 0u);
+ const uint32_t valid_rows = (r < st->n_rows) ? hex_smin(st->n_rows - r, 4u) : 0u;
+
+ if (valid_rows > 0) {
+ if (!double_buf) {
+ push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, valid_rows, st->start_row, r,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ for (uint32_t s = 0; s < valid_rows; ++s) {
+ dma_queue_pop(dma_q);
+ }
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, r);
+ if (act_is_f16) {
+ quantize_act_step_rows_f16_w8a8(
+ st->vtcm_act_dst, st->vtcm_act_scales, curr_buf, row_bytes,
+ r, valid_rows, st->mc_pad, n_k_tiles, st->n_groups, st->k_valid);
+ } else {
+ quantize_act_step_rows_f32_w8a8(
+ st->vtcm_act_dst, st->vtcm_act_scales, curr_buf, row_bytes,
+ r, valid_rows, st->mc_pad, n_k_tiles, st->n_groups, st->k_valid);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, r);
+
+ if (double_buf) {
+ const uint32_t next_r = r + 2u * row_stride;
+ if (next_r < st->mc_pad && next_r < st->n_rows) {
+ const uint32_t nrows = hex_smin(st->n_rows - next_r, 4u);
+ push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, nrows, st->start_row, next_r,
+ row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride,
+ st->ne11, &st->ne11_div, st->nb11, st->nb12);
+ }
+ }
+ }
+}
+
+static void transfer_activation_chunk_int_gathered_threaded(
+ struct htp_context * ctx,
+ uint8_t * vtcm_act_dst,
+ float * vtcm_act_scales,
+ dma_addr_t act_dma_addr,
+ uint32_t act_elem_size,
+ int start_row,
+ int n_rows,
+ int k_block,
+ int k_valid,
+ int n_groups,
+ const struct mmid_row_mapping * matrix_rows,
+ int cur_a,
+ int mapping_stride,
+ int ne11,
+ size_t nb11,
+ size_t nb12,
+ int n_hvx,
+ const struct fastdiv_values * act_hvx_div,
+ float * vtcm_f32_act,
+ size_t vtcm_f32_act_bytes) {
+ if (n_rows <= 0) {
+ return;
+ }
+
+ const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, 64u);
+ const uint32_t resolved_esize = act_elem_size ? act_elem_size : (uint32_t) sizeof(float);
+
+ int_activation_transfer_gathered_state_t state = {
+ .matrix_rows = matrix_rows,
+ .vtcm_act_dst = vtcm_act_dst,
+ .vtcm_act_scales = vtcm_act_scales,
+ .act_dma_addr = act_dma_addr,
+ .vtcm_f32_act = vtcm_f32_act,
+ .act_elem_size = resolved_esize,
+ .n_tasks = (uint32_t) hex_smin(n_hvx, (int) (mc_pad >> 2)),
+ .n_rows = (uint32_t) n_rows,
+ .mc_pad = mc_pad,
+ .k_block = (uint32_t) k_block,
+ .k_valid = (uint32_t) k_valid,
+ .n_groups = (uint32_t) n_groups,
+ .vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128),
+ .start_row = (uint32_t) start_row,
+ .cur_a = (uint32_t) cur_a,
+ .mapping_stride = (uint32_t) mapping_stride,
+ .ne11 = (uint32_t) ne11,
+ .ne11_div = ne11 > 1 ? init_fastdiv_values(ne11) : (struct fastdiv_values){0, 0},
+ .nb11 = nb11,
+ .nb12 = nb12,
+ };
+
+ work_queue_run(ctx->hvx_queue, transfer_activation_chunk_int_gathered_worker_fn, &state, (int) state.n_tasks);
+}
+
+// --- Async HMX matmul task (for pipeline overlap) ---
typedef struct {
- __fp16 * output;
- const __fp16 * activation;
- const __fp16 * weight;
- const __fp16 * scales;
- uint32_t n_row_tiles;
- uint32_t n_col_tiles;
- uint32_t n_dot_tiles;
-} hmx_matmul_job_t;
-
-static void hmx_matmul_worker_fn(const htp_thread_t * th, void * data) {
- hmx_matmul_job_t * job = (hmx_matmul_job_t *) data;
- FARF(HIGH, "hmx-mm-job: n_row_tiles %u n_col_tiles %u n_dot_tiles %u", job->n_row_tiles, job->n_col_tiles, job->n_dot_tiles);
- core_dot_chunk_fp16(job->output, job->activation, job->weight, job->scales, job->n_row_tiles, job->n_col_tiles, job->n_dot_tiles);
+ __fp16 * output;
+ const __fp16 * activation;
+ const __fp16 * weight;
+ const __fp16 * scales;
+ const uint8_t * weight_bias;
+ uint32_t n_row_tiles;
+ uint32_t n_col_tiles;
+ uint32_t n_dot_tiles;
+ uint32_t n_groups;
+} hmx_matmul_task_t;
+
+static void hmx_matmul_fp16_worker_fn(const htp_thread_t * th, void * data) {
+ (void) th;
+ hmx_matmul_task_t * task = (hmx_matmul_task_t *) data;
+ FARF(HIGH, "hmx-mm-fp16-task: n_row_tiles %u n_col_tiles %u n_dot_tiles %u",
+ task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles);
+ core_dot_chunk_fp16(task->output, task->activation, task->weight, task->scales,
+ task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles);
}
-static inline void hmx_matmul_job_init(hmx_matmul_job_t * job,
+static void hmx_matmul_w8a8_worker_fn(const htp_thread_t * th, void * data) {
+ (void) th;
+ hmx_matmul_task_t * task = (hmx_matmul_task_t *) data;
+ FARF(HIGH, "hmx-mm-w8a8-task: n_row_tiles %u n_col_tiles %u n_dot_tiles %u n_groups %u",
+ task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles, task->n_groups);
+ core_dot_chunk_w8a8_sm((uint8_t *) task->output, (const uint8_t *) task->activation,
+ (const uint8_t *) task->weight, task->weight_bias,
+ task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles, task->n_groups);
+}
+
+static inline hmx_queue_func hmx_get_matmul_worker_fn(int32_t kernel_type) {
+ if (htp_mm_kernel_is_hmx_w8a8(kernel_type)) {
+ return hmx_matmul_w8a8_worker_fn;
+ }
+ return hmx_matmul_fp16_worker_fn;
+}
+
+static inline void hmx_matmul_task_init(hmx_matmul_task_t * task,
__fp16 * output,
const __fp16 * activation,
const __fp16 * weight,
@@ -2629,20 +3563,42 @@ static inline void hmx_matmul_job_init(hmx_matmul_job_t * job,
uint32_t n_row_tiles,
uint32_t n_col_tiles,
uint32_t n_dot_tiles) {
- job->output = output;
- job->activation = activation;
- job->weight = weight;
- job->scales = scales;
- job->n_row_tiles = n_row_tiles;
- job->n_col_tiles = n_col_tiles;
- job->n_dot_tiles = n_dot_tiles;
+ task->output = output;
+ task->activation = activation;
+ task->weight = weight;
+ task->scales = scales;
+ task->weight_bias = NULL;
+ task->n_row_tiles = n_row_tiles;
+ task->n_col_tiles = n_col_tiles;
+ task->n_dot_tiles = n_dot_tiles;
+ task->n_groups = 1;
+}
+
+static inline void hmx_matmul_task_init_int(hmx_matmul_task_t * task,
+ void * output,
+ const void * activation,
+ const void * weight_buf,
+ size_t weight_bias_offset,
+ uint32_t n_row_tiles,
+ uint32_t n_col_tiles,
+ uint32_t n_dot_tiles,
+ uint32_t n_groups) {
+ task->output = (__fp16 *) output;
+ task->activation = (const __fp16 *) activation;
+ task->weight = (const __fp16 *) weight_buf;
+ task->scales = NULL;
+ task->weight_bias = (const uint8_t *) weight_buf + weight_bias_offset;
+ task->n_row_tiles = n_row_tiles;
+ task->n_col_tiles = n_col_tiles;
+ task->n_dot_tiles = n_dot_tiles;
+ task->n_groups = n_groups;
}
-static int hmx_mm_2d_f32(struct htp_context *ctx,
+static int hmx_mm_2d_f32(struct htp_ops_context *octx,
dma_queue *weight_dma,
- float *restrict dst,
- dma_addr_t src2_addr,
- size_t src2_bytes,
+ dma_addr_t dst_dma_addr,
+ dma_addr_t bias_addr,
+ size_t bias_bytes,
dma_addr_t act_dma_addr,
dma_addr_t weight,
int m, int k, int n,
@@ -2652,27 +3608,38 @@ static int hmx_mm_2d_f32(struct htp_context *ctx,
int weight_type,
int k_valid,
int dst_stride,
- uint32_t src2_stride,
+ uint32_t bias_stride,
int dst_cols,
+ uint32_t dst_elem_size,
+ uint32_t bias_elem_size,
int m_chunk,
int n_chunk,
int pipeline,
- int n_hvx,
int act_hvx,
const struct fastdiv_values * act_hvx_div,
const struct fastdiv_values * k_div,
int tile_size,
int aligned_tile_size,
- int vtcm_size) {
+ int vtcm_size,
+ int32_t kernel_type,
+ int hmx_n_groups,
+ const struct fastdiv_values * div_hmx_n_groups,
+ const struct fastdiv_values * div_n_k_tiles) {
+ struct htp_context * ctx = octx->ctx;
struct htp_thread_trace * tr = &ctx->trace[0];
htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
- const bool is_tiled = (tile_size > 0);
+ const bool is_tiled = (tile_size > 0);
+ const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type);
+ const int n_groups = is_int_hmx ? hmx_n_groups : 1;
- if (k % 32 != 0) {
+ if ((k & 31) != 0) {
return -1;
}
- if (!hex_is_aligned(dst, sizeof(float))) { return -1; }
+ if ((dst_dma_addr & (dst_elem_size - 1)) != 0) { return -1; }
+
+ const struct fastdiv_values n_groups_div = *div_hmx_n_groups;
+ const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type);
size_t row_stride = htp_tensor_get_row_size(weight_type, k);
if (row_stride == 0) {
@@ -2681,11 +3648,10 @@ static int hmx_mm_2d_f32(struct htp_context *ctx,
tiled_dequant_task_fn_t dequant_worker_fn = hmx_get_dequant_worker_fn(weight_type, is_tiled);
- const int n_k_tiles = k / HTP_MM_HMX_TILE_N_COLS;
- const int n_weight_tiles = k / htp_tensor_get_tile_k(weight_type);
- const struct fastdiv_values n_k_tiles_div = init_fastdiv_values(n_k_tiles);
+ const int n_k_tiles = k >> 5;
+ const int n_weight_tiles = (weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / htp_tensor_get_tile_k(weight_type));
+ const struct fastdiv_values n_k_tiles_div = *div_n_k_tiles;
- const size_t vec_dot_size = k * sizeof(__fp16);
const size_t vtcm_budget = ctx->vtcm_size;
const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride;
@@ -2696,8 +3662,15 @@ static int hmx_mm_2d_f32(struct htp_context *ctx,
size_t n_chunk_n_cols = n_chunk;
size_t vtcm_used = vtcm_size;
+ const bool has_bias = (bias_bytes > 0 && bias_addr != 0);
+ const bool has_2d_bias = (pipeline && !has_bias && bias_addr != 0);
+ const size_t res_in_elem_size = has_2d_bias ? bias_elem_size : 0;
+ const size_t res_out_elem_size = dst_elem_size;
+
struct htp_mm_hmx_vtcm_layout L;
- htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_2D, weight_type, k, m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, src2_bytes);
+ htp_mm_hmx_vtcm_layout_build_ex(&L, is_int_hmx ? kernel_type : HTP_MM_KERNEL_HMX_2D, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, bias_bytes,
+ res_in_elem_size, res_out_elem_size);
vtcm_used = L.total_bytes;
if (vtcm_used > vtcm_budget) {
@@ -2713,34 +3686,45 @@ static int hmx_mm_2d_f32(struct htp_context *ctx,
};
__fp16 *vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act);
float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
+ float *vtcm_act_scales = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_act_scales, is_int_hmx);
__fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]);
void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]);
void *vtcm_scratch1 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline);
void *vtcm_scratch2 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[1], pipeline);
- __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales);
+ void *vtcm_res_in[2] = {
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_in[0], has_2d_bias),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_in[1], has_2d_bias),
+ };
+ void *vtcm_res_out[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline),
+ };
+ __fp16 *vtcm_scales = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_scales, !is_int_hmx);
- hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16
+ if (!is_int_hmx) {
+ hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16
+ }
if (L.lut_bytes > 0) {
iq2xxs_lut_copy(base + L.off_lut);
}
- const bool has_bias = (src2_bytes > 0 && src2_addr != 0);
- float *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_bias, has_bias);
+ void *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_bias, has_bias);
if (has_bias) {
- dma_queue_push(weight_dma, dma_make_data(vtcm_bias, src2_addr), hex_align_up(src2_bytes, 128), 0, src2_bytes, 1);
+ dma_queue_push(weight_dma, dma_make_data(vtcm_bias, bias_addr), hex_align_up(bias_bytes, 128), 0, bias_bytes, 1);
dma_queue_pop(weight_dma);
}
- FARF(HIGH, "hmx-mm-2d: m %d k %d n %d wtype %d mc %zu nc %zu vtcm %zu/%zu",
- m, k, n, weight_type, m_chunk_n_rows, n_chunk_n_cols, vtcm_used, vtcm_budget);
+ FARF(HIGH, "hmx-mm-2d: ktype %d m %d k %d n %d wtype %d mc %zu nc %zu vtcm %zu/%zu",
+ (int) kernel_type, m, k, n, weight_type, m_chunk_n_rows, n_chunk_n_cols, vtcm_used, vtcm_budget);
int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ const uint32_t m_tile_rows = is_int_hmx ? 64u : HTP_MM_HMX_TILE_N_ROWS;
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
if (pipeline) {
- // --- Asynchronous Pipelined Loop ---
- hmx_matmul_job_t job_slots[2]; // persistent double-buffered job descriptors
+ // --- Asynchronous Pipelined Loop (strict lockstep FIFO on weight_dma) ---
+ hmx_matmul_task_t task_slots[2];
void *vtcm_raw_bufs[4] = {
vtcm_weight_raw[0],
vtcm_weight_raw[1],
@@ -2755,163 +3739,363 @@ static int hmx_mm_2d_f32(struct htp_context *ctx,
};
void *vtcm_output_bufs[2] = { vtcm_output, vtcm_scratch2 };
- for (size_t mr = 0; mr < m; mr += m_chunk_n_rows) {
- const size_t n_rows = hex_smin(m - mr, m_chunk_n_rows);
+ const size_t dst_row_bytes = (size_t) dst_stride * dst_elem_size;
+ const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size;
+ const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
+ const size_t res_in_stride_bytes = has_2d_bias ? hex_align_up(n_chunk_n_cols * bias_elem_size, 128) : 0;
+ const uint32_t res_in_stride_elems = has_2d_bias ? (uint32_t) (res_in_stride_bytes / bias_elem_size) : 0;
- struct activation_transfer_params act_params = {
- .ctx = ctx,
- .dst = vtcm_f16_act,
- .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, // byte offset (F16/F32)
- .n_rows = (int) n_rows,
- .k_block = k,
- .k_stride = act_stride,
- .n_hvx = act_hvx,
- .act_hvx_div = act_hvx_div,
- .k_div = k_div,
- .k_valid = k_valid,
- .vtcm_f32_act = vtcm_f32_act,
- .vtcm_f32_act_bytes = L.act_f32_bytes,
- .act_elem_size = act_elem_size,
- };
- transfer_activation_chunk_threaded(&act_params);
+ const bool preissue_w0 = is_int_hmx && L.can_preissue_weight && n > 0;
- // Prologue: push A0 and optionally A1 (if n_chunk_cnt > 1)
- const size_t n_cols_A0 = hex_smin(n - 0 * n_chunk_n_cols, n_chunk_n_cols);
- const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0;
- dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
- dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0);
+ for (size_t mr = 0; mr < (size_t) m; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin((size_t) m - mr, m_chunk_n_rows);
+
+ if (preissue_w0) {
+ const size_t n_cols_A0 = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_raw_bufs[0], weight),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0);
+ }
+
+ if (is_int_hmx) {
+ transfer_activation_chunk_int_threaded(
+ ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales,
+ act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ (int) n_rows, k, act_stride, k_valid, n_groups,
+ act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size);
+ } else {
+ struct activation_transfer_params act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ .n_rows = (int) n_rows,
+ .k_block = k,
+ .k_stride = act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = k_valid,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ };
+ transfer_activation_chunk_threaded(&act_params);
+ }
+ if (!preissue_w0) {
+ const size_t n_cols_A0 = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0);
+ }
if (1 < n_chunk_cnt) {
- const size_t n_cols_A1 = hex_smin(n - 1 * n_chunk_n_cols, n_chunk_n_cols);
+ const size_t n_cols_A1 = hex_smin((size_t) n - n_chunk_n_cols, n_chunk_n_cols);
const uint32_t height_A1 = is_tiled ? hmx_ceil_div(n_cols_A1, 32) * n_weight_tiles : n_cols_A1;
dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[1], weight + n_chunk_n_cols * weight_stride),
dma_dst_stride, dma_src_stride, dma_width_bytes, height_A1);
}
+ if (has_2d_bias) {
+ const int vcols0 = hex_smin((int) hex_smin((size_t) n, n_chunk_n_cols), dst_cols);
+ const size_t cbytes = (vcols0 > 0) ? (size_t) vcols0 * bias_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(vtcm_res_in[0], bias_addr + (mr * bias_stride) * bias_elem_size),
+ res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0);
+ }
- // Main loop: pop A_i -> dequantize A_i -> push A_{i+2} -> submit C_i -> wait C_{i-1} and store D_{i-1}
for (int i = 0; i < n_chunk_cnt; ++i) {
- const size_t nc = i * n_chunk_n_cols;
- const size_t nc_p2 = nc + 2 * n_chunk_n_cols;
-
- const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols);
- const size_t n_cols_p2 = hex_smin(n - nc_p2, n_chunk_n_cols);
-
- // 1. pop A_i
- void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
-
- // 2. dequantize A_i
- dequantize_tiled_weight_chunk_to_fp16_tiles(
- ctx, vtcm_weight_bufs[i % 4], curr_raw,
- n_cols, k, row_stride, weight_type,
- n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx);
-
- // 3. push A_{i+2} (if i+2 < n_chunk_cnt)
- if (i + 2 < n_chunk_cnt) {
- const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2;
- dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride),
- dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2);
- }
+ const size_t nc = (size_t) i * n_chunk_n_cols;
+ const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols);
- // 4. submit C_i
- hmx_matmul_job_init(&job_slots[i % 2], (__fp16 *) vtcm_output_bufs[i % 2],
- (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4],
- vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS),
- hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), k / HTP_MM_HMX_TILE_N_ROWS);
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job_slots[i % 2]));
+ // 1. Pop w_i and dequantize / rescale into vtcm_weight_bufs[i % 4]
+ void * curr_raw;
+ if (i == 0 && preissue_w0) {
+ curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst;
+ } else {
+ curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ }
+ if (is_int_hmx) {
+ rescale_int_weight_chunk_to_int8_tiles(
+ octx, vtcm_weight_bufs[i % 4], L.weight_bias_offset, L.weight_scales_offset,
+ curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+ } else {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, vtcm_weight_bufs[i % 4], curr_raw,
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
- // 5. wait C_{i-1} and store D_{i-1} (multi-thread HVX, parallel with C_i)
- if (i > 0) {
- hmx_queue_pop(ctx->hmx_queue);
- const size_t nc_prev = (i - 1) * n_chunk_n_cols;
- const size_t n_cols_prev = hex_smin(n - nc_prev, n_chunk_n_cols);
- float *output_chunk = dst + (mr * dst_stride + nc_prev);
- const float *bias_chunk = has_bias ? (vtcm_bias + mr * src2_stride + nc_prev) : NULL;
- int chunk_dst_cols = dst_cols - (int)nc_prev;
- if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output_chunk, bias_chunk, vtcm_output_bufs[(i - 1) % 2], n_rows, n_cols_prev, dst_stride, src2_stride, chunk_dst_cols, n_hvx);
+ if (i == 0) {
+ if (is_int_hmx) {
+ hmx_matmul_task_init_int(&task_slots[0], vtcm_output_bufs[0],
+ vtcm_f16_act, vtcm_weight_bufs[0], L.weight_bias_offset,
+ hmx_ceil_div(n_rows, m_tile_rows),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ } else {
+ hmx_matmul_task_init(&task_slots[0], (__fp16 *) vtcm_output_bufs[0],
+ (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[0],
+ vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles);
}
- }
- }
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[0]));
- // Epilogue: wait C_{last} and store D_{last}
- hmx_queue_pop(ctx->hmx_queue);
- const size_t nc_last = (n_chunk_cnt - 1) * n_chunk_n_cols;
- const size_t n_cols_last = hex_smin(n - nc_last, n_chunk_n_cols);
- float *output_chunk = dst + (mr * dst_stride + nc_last);
- const float *bias_chunk = has_bias ? (vtcm_bias + mr * src2_stride + nc_last) : NULL;
- int chunk_dst_cols = dst_cols - (int)nc_last;
- if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output_chunk, bias_chunk, vtcm_output_bufs[(n_chunk_cnt - 1) % 2], n_rows, n_cols_last, dst_stride, src2_stride, chunk_dst_cols, n_hvx);
+ if (2 < n_chunk_cnt) {
+ const size_t nc2 = 2u * n_chunk_n_cols;
+ const size_t n_cols_p2 = hex_smin((size_t) n - nc2, n_chunk_n_cols);
+ const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[2], weight + nc2 * weight_stride),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2);
+ }
+ if (has_2d_bias && 1 < n_chunk_cnt) {
+ const size_t nc1 = n_chunk_n_cols;
+ const int vcols1 = hex_smin((int) hex_smin((size_t) n - nc1, n_chunk_n_cols), dst_cols - (int) nc1);
+ const size_t cbytes = (vcols1 > 0) ? (size_t) vcols1 * bias_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(vtcm_res_in[1], bias_addr + (mr * bias_stride + nc1) * bias_elem_size),
+ res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ } else {
+ const int prev = (i - 1) & 1;
+ const size_t nc_prev = (size_t) (i - 1) * n_chunk_n_cols;
+ const size_t n_cols_p = hex_smin((size_t) n - nc_prev, n_chunk_n_cols);
+
+ // 2. Wait C_{i-1} and submit C_i
+ hmx_queue_pop(ctx->hmx_queue);
+ if (is_int_hmx) {
+ hmx_matmul_task_init_int(&task_slots[i & 1], vtcm_output_bufs[i & 1],
+ vtcm_f16_act, vtcm_weight_bufs[i % 4], L.weight_bias_offset,
+ hmx_ceil_div(n_rows, m_tile_rows),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ } else {
+ hmx_matmul_task_init(&task_slots[i & 1], (__fp16 *) vtcm_output_bufs[i & 1],
+ (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4],
+ vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles);
+ }
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[i & 1]));
+
+ // 3. Pop r_{i-1} (if 2D residual); out_{i-2} uses vtcm_res_out[cur], popped after D_{i-1}
+ if (has_2d_bias) {
+ dma_queue_pop(weight_dma);
+ }
+
+ // 4. HVX epilogue D_{i-1} (VTCM -> vtcm_res_out[prev], parallel with C_i and out_{i-2} DMA)
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ const void * bias_chunk = has_2d_bias ? vtcm_res_in[prev]
+ : (has_bias ? ((const uint8_t *) vtcm_bias + (mr * bias_stride + nc_prev) * bias_elem_size) : NULL);
+ const uint32_t ep_bias_stride = has_2d_bias ? res_in_stride_elems : bias_stride;
+ if (is_int_hmx) {
+ const float * wt_scales_prev = (const float *) ((const uint8_t *) vtcm_weight_bufs[(i - 1) % 4] + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out[prev], bias_chunk, vtcm_output_bufs[prev],
+ vtcm_act_scales, wt_scales_prev, (int) n_rows, (int) n_cols_p,
+ n_groups, res_out_stride_elems, ep_bias_stride, chunk_dst_cols,
+ dst_elem_size, bias_elem_size);
+ } else {
+ transfer_output_chunk_threaded(octx, vtcm_res_out[prev], bias_chunk, vtcm_output_bufs[prev],
+ n_rows, n_cols_p, res_out_stride_elems, ep_bias_stride, chunk_dst_cols,
+ dst_elem_size, bias_elem_size);
+ }
+ }
+
+ // 5. Drain out_{i-2}, then push out_{i-1}, w_{i+2}, and r_{i+1}
+ if (i >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+ {
+ const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ if (i + 2 < n_chunk_cnt) {
+ const size_t nc_p2 = (size_t) (i + 2) * n_chunk_n_cols;
+ const size_t n_cols_p2 = hex_smin((size_t) n - nc_p2, n_chunk_n_cols);
+ const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2);
+ }
+ if (has_2d_bias && i + 1 < n_chunk_cnt) {
+ const size_t nc_p1 = (size_t) (i + 1) * n_chunk_n_cols;
+ const int vcols_r = hex_smin((int) hex_smin((size_t) n - nc_p1, n_chunk_n_cols), dst_cols - (int) nc_p1);
+ const size_t cbytes = (vcols_r > 0) ? (size_t) vcols_r * bias_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(vtcm_res_in[prev], bias_addr + (mr * bias_stride + nc_p1) * bias_elem_size),
+ res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ }
+ }
+
+ // Epilogue: wait C_{last}, pop r_{last} and out_{last-1}, run D_{last}, push+pop out_{last}
+ {
+ const int last = (n_chunk_cnt - 1) & 1;
+ const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols;
+ const size_t n_cols_last = hex_smin((size_t) n - nc_last, n_chunk_n_cols);
+
+ hmx_queue_pop(ctx->hmx_queue);
+ if (has_2d_bias) {
+ dma_queue_pop(weight_dma);
+ }
+ if (n_chunk_cnt >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+
+ const int chunk_dst_cols = dst_cols - (int) nc_last;
+ if (chunk_dst_cols > 0) {
+ const void * bias_chunk = has_2d_bias ? vtcm_res_in[last]
+ : (has_bias ? ((const uint8_t *) vtcm_bias + (mr * bias_stride + nc_last) * bias_elem_size) : NULL);
+ const uint32_t ep_bias_stride = has_2d_bias ? res_in_stride_elems : bias_stride;
+ if (is_int_hmx) {
+ const float * wt_scales_last = (const float *) ((const uint8_t *) vtcm_weight_bufs[(n_chunk_cnt - 1) % 4] + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out[last], bias_chunk, vtcm_output_bufs[last],
+ vtcm_act_scales, wt_scales_last, (int) n_rows, (int) n_cols_last,
+ n_groups, res_out_stride_elems, ep_bias_stride, chunk_dst_cols,
+ dst_elem_size, bias_elem_size);
+ } else {
+ transfer_output_chunk_threaded(octx, vtcm_res_out[last], bias_chunk, vtcm_output_bufs[last],
+ n_rows, n_cols_last, res_out_stride_elems, ep_bias_stride, chunk_dst_cols,
+ dst_elem_size, bias_elem_size);
+ }
+ }
+
+ const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
}
}
} else {
- // --- Synchronous loop (m <= 32 or fallback) ---
- hmx_matmul_job_t job;
+ // --- Synchronous loop (m <= 32 or fallback) with lockstep DMA writeback ---
+ hmx_matmul_task_t task;
void *vtcm_raw_bufs[2] = { vtcm_weight_raw[0], dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch0 };
void *vtcm_weight_bufs[2] = { dequant_worker_fn ? vtcm_scratch0 : vtcm_weight_raw[0], vtcm_scratch0 };
- for (size_t mr = 0; mr < m; mr += m_chunk_n_rows) {
- const size_t n_rows = hex_smin(m - mr, m_chunk_n_rows);
+ const size_t dst_row_bytes = (size_t) dst_stride * dst_elem_size;
+ const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
- struct activation_transfer_params act_params = {
- .ctx = ctx,
- .dst = vtcm_f16_act,
- .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, // byte offset (F16/F32)
- .n_rows = (int) n_rows,
- .k_block = k,
- .k_stride = act_stride,
- .n_hvx = act_hvx,
- .act_hvx_div = act_hvx_div,
- .k_div = k_div,
- .k_valid = k_valid,
- .vtcm_f32_act = vtcm_f32_act,
- .vtcm_f32_act_bytes = L.act_f32_bytes,
- .act_elem_size = act_elem_size,
- };
- transfer_activation_chunk_threaded(&act_params);
+ const bool preissue_w0 = is_int_hmx && L.can_preissue_weight && n > 0;
+
+ for (size_t mr = 0; mr < (size_t) m; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin((size_t) m - mr, m_chunk_n_rows);
+
+ if (preissue_w0) {
+ const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_raw_bufs[0], weight),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height);
+ }
+
+ if (is_int_hmx) {
+ transfer_activation_chunk_int_threaded(
+ ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales,
+ act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ (int) n_rows, k, act_stride, k_valid, n_groups,
+ act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size);
+ } else {
+ struct activation_transfer_params act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ .n_rows = (int) n_rows,
+ .k_block = k,
+ .k_stride = act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = k_valid,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ };
+ transfer_activation_chunk_threaded(&act_params);
+ }
- // A0: Pre-fetch the first weight chunk (nc = 0)
- if (n > 0) {
- const size_t n_cols = hex_smin(n, n_chunk_n_cols);
+ if (!preissue_w0 && n > 0) {
+ const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols);
const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols;
dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), dma_dst_stride, dma_src_stride, dma_width_bytes, height);
}
for (int i = 0; i < n_chunk_cnt; ++i) {
const size_t nc = (size_t) i * n_chunk_n_cols;
- const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols);
- const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, m_tile_rows);
const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
- // A: Wait for weight DMA
- void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ // A: Wait for weight DMA (and previous output writeback)
+ void * curr_raw;
+ if (i == 0 && preissue_w0) {
+ curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst;
+ } else {
+ curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ }
+ if (i > 0) {
+ dma_queue_pop(weight_dma);
+ }
- // B: Weight Dequantize (Threaded)
- dequantize_tiled_weight_chunk_to_fp16_tiles(
- ctx, vtcm_weight_bufs[i % 2], curr_raw,
- n_cols, k, row_stride, weight_type,
- n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx);
+ // B: Weight Dequantize / Rescale (Threaded)
+ if (is_int_hmx) {
+ rescale_int_weight_chunk_to_int8_tiles(
+ octx, vtcm_weight_bufs[i % 2], L.weight_bias_offset, L.weight_scales_offset,
+ curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+ } else {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, vtcm_weight_bufs[i % 2], curr_raw,
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
// Start weight DMA for the next chunk early
const size_t nc_next = nc + n_chunk_n_cols;
- if (nc_next < n) {
- const size_t n_cols_next = hex_smin(n - nc_next, n_chunk_n_cols);
+ if (nc_next < (size_t) n) {
+ const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols);
const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next;
dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_next);
}
// C: HMX Compute (Queue-based)
- hmx_matmul_job_init(&job, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS);
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job));
+ if (is_int_hmx) {
+ hmx_matmul_task_init_int(&task, vtcm_output, vtcm_f16_act, vtcm_weight_bufs[i % 2], L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ } else {
+ hmx_matmul_task_init(&task, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ }
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task));
hmx_queue_pop(ctx->hmx_queue);
- // D: Output Store
- float *output_chunk = dst + (mr * dst_stride + nc);
- const float *bias_chunk = has_bias ? (vtcm_bias + mr * src2_stride + nc) : NULL;
- int chunk_dst_cols = dst_cols - (int)nc;
+ // D: Output Store into vtcm_res_out[0] + 2D bypass DMA
+ const void *bias_chunk = has_bias ? ((const uint8_t *) vtcm_bias + (mr * bias_stride + nc) * bias_elem_size) : NULL;
+ int chunk_dst_cols = dst_cols - (int) nc;
if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output_chunk, bias_chunk, vtcm_output, n_rows, n_cols, dst_stride, src2_stride, chunk_dst_cols, n_hvx);
+ if (is_int_hmx) {
+ const float * wt_scales = (const float *) ((const uint8_t *) vtcm_weight_bufs[i % 2] + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out[0], bias_chunk, vtcm_output,
+ vtcm_act_scales, wt_scales, (int) n_rows, (int) n_cols,
+ n_groups, res_out_stride_elems, bias_stride, chunk_dst_cols,
+ dst_elem_size, bias_elem_size);
+ } else {
+ transfer_output_chunk_threaded(octx, vtcm_res_out[0], bias_chunk, vtcm_output,
+ n_rows, n_cols, res_out_stride_elems, bias_stride, chunk_dst_cols,
+ dst_elem_size, bias_elem_size);
+ }
}
+ const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ if (n_chunk_cnt > 0) {
+ dma_queue_pop(weight_dma);
}
}
}
@@ -2919,6 +4103,711 @@ static int hmx_mm_2d_f32(struct htp_context *ctx,
return 0;
}
+static int hmx_mm_nx_glu_int_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const struct htp_tensor * restrict src_gate = octx->src[0];
+ const struct htp_tensor * restrict src_up = octx->src[1];
+ const struct htp_tensor * restrict act = octx->src[2];
+ const struct htp_tensor * restrict dst = octx->dst;
+
+ const int weight_type = (int) src_gate->type;
+ const int k = (int) act->ne[0];
+ const int k_valid = (int) act->ne[0];
+ const size_t n = (size_t) src_gate->ne[1];
+ const int m = (int) (act->ne[1] * act->ne[2] * act->ne[3]);
+ const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const int act_stride = (int) (act->nb[1] / act_elem_size);
+ const dma_addr_t act_dma_addr = act->data;
+
+ const int32_t kernel_type = kparams->kernel_type;
+ const int n_groups = kparams->hmx_n_groups;
+ const int tile_k = htp_tensor_get_tile_k(weight_type);
+
+ if (tile_k <= 0 || (k % tile_k) != 0 || (k & 31) != 0 || !htp_mm_kernel_is_hmx_int(kernel_type)) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ if (n == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ hmx_output_glu_state_t glu_state;
+ if (!resolve_int_output_glu_fns((uint32_t) n_groups, kparams->glu_op, dst_elem_size,
+ &glu_state.col_chunk_fn, &glu_state.store_quad_fn,
+ &glu_state.store_tail_fn, &glu_state.store_strip_fn)) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
+ const struct fastdiv_values n_groups_div = kparams->div_hmx_n_groups;
+ const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type);
+
+ const int n_k_tiles = k >> 5;
+ const int n_weight_tiles = (weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / tile_k);
+ const int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+ if (tile_size <= 0) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
+ const size_t vtcm_budget = ctx->vtcm_size;
+ const int m_chunk_n_rows = kparams->m_chunk;
+ const int n_chunk_n_cols = kparams->n_chunk;
+ const int pipeline = kparams->pipeline;
+ const int act_hvx = kparams->n_act_hvx;
+ const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx;
+
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_glu(&L, kernel_type, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, pipeline, act_hvx, aligned_tile_size,
+ dst_elem_size);
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-mm-nx-glu: VTCM overflow: used %zu budget %zu, m %d k %d n %zu mc %d nc %d",
+ L.total_bytes, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * const base = (uint8_t *) ctx->vtcm_base;
+ void * vtcm_weight_raw[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_weight[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_weight[1], pipeline)
+ };
+ uint8_t * vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
+ float * vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
+ float * vtcm_act_scales = VTCM_LAYOUT_PTR(float, base, L.off_act_scales);
+ void * vtcm_gate[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_dst[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[1], pipeline)
+ };
+ void * vtcm_up[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_dst_up[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst_up[1], pipeline)
+ };
+ void * vtcm_scratch[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline)
+ };
+ float * vtcm_wt_scales_gate[2] = {
+ VTCM_LAYOUT_PTR(float, base, L.off_wt_scales_gate[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_wt_scales_gate[1], pipeline)
+ };
+ float * vtcm_wt_scales_up[2] = {
+ VTCM_LAYOUT_PTR(float, base, L.off_wt_scales_up[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_wt_scales_up[1], pipeline)
+ };
+ void * vtcm_res_out[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline)
+ };
+
+ if (L.lut_bytes > 0) {
+ iq2xxs_lut_copy(base + L.off_lut);
+ }
+
+ int m_start = 0;
+ int m_rows = m;
+ if (octx->ctx->mdev.count > 1) {
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ m_start = (int) range.start;
+ m_rows = (int) range.count;
+ }
+ if (m_rows == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ FARF(HIGH, "hmx-mm-nx-glu: glu %u ktype %d m %d (%d..%d) k %d n %zu wtype %d mc %d nc %d vtcm %zu/%zu",
+ (unsigned) kparams->glu_op, (int) kernel_type, m, m_start, m_start + m_rows, k, n, weight_type,
+ m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const size_t mr_end = (size_t) (m_start + m_rows);
+ const dma_addr_t w_gate = src_gate->data;
+ const dma_addr_t w_up = src_up->data;
+ const size_t w_gate_stride = src_gate->nb[1];
+ const size_t w_up_stride = src_up->nb[1];
+ const dma_addr_t dst_dma_addr = dst->data;
+ const size_t dst_stride = dst->nb[1] / dst_elem_size;
+ const size_t dst_row_bytes = dst->nb[1];
+ const int dst_cols = (int) dst->ne[0];
+ const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
+ const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ dma_queue * weight_dma = octx->ctx->dma[0];
+
+ glu_state.vtcm_act_scales = vtcm_act_scales;
+ glu_state.n_groups = (uint32_t) n_groups;
+ glu_state.dst_stride = (uint32_t) res_out_stride_elems;
+ glu_state.dst_elem_size = dst_elem_size;
+
+ if (pipeline) {
+ // 4-buffer HMX output pipeline: vtcm_gate[2] + vtcm_up[2] (GLU(s-1) overlaps both HMX(gate_s) and HMX(up_s))
+ hmx_matmul_task_t task_gate[2];
+ hmx_matmul_task_t task_up[2];
+ const bool preissue_gate0 = L.can_preissue_weight && n > 0;
+
+ for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u);
+
+ if (preissue_gate0) {
+ const size_t n_cols0 = hex_smin(n, (size_t) n_chunk_n_cols);
+ const uint32_t height0 = hmx_ceil_div(n_cols0, 32) * n_weight_tiles;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_weight_raw[0], w_gate),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+
+ transfer_activation_chunk_int_threaded(
+ ctx, vtcm_act, vtcm_act_scales,
+ act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ (int) n_rows, k, act_stride, k_valid, n_groups,
+ act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size);
+
+ // Prologue: push gate_0 (if not preissued) and up_0
+ {
+ const size_t n_cols0 = hex_smin(n, (size_t) n_chunk_n_cols);
+ const uint32_t height0 = hmx_ceil_div(n_cols0, 32) * n_weight_tiles;
+ if (!preissue_gate0) {
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[1], w_up),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+
+ for (int s = 0; s < n_chunk_cnt; ++s) {
+ const int cur = s & 1;
+ const int prev = (s - 1) & 1;
+ const size_t nc = (size_t) s * n_chunk_n_cols;
+ const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols);
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+
+ // 1. Pop gate_s, wait HMX(gate_{s-1}) so vtcm_scratch[0] is free, rescale and submit HMX(gate_s)
+ if (s == 0 && preissue_gate0) {
+ dma_proxy_pop(ctx->dma_proxy);
+ } else {
+ dma_queue_pop(weight_dma);
+ }
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ rescale_int_weight_chunk_to_int8_tiles_scales(
+ octx, vtcm_scratch[0], L.weight_bias_offset, vtcm_wt_scales_gate[cur],
+ vtcm_weight_raw[0], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+
+ hmx_matmul_task_init_int(&task_gate[cur], vtcm_gate[cur],
+ vtcm_act, vtcm_scratch[0], L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_gate[cur]));
+
+ if (s + 1 < n_chunk_cnt) {
+ const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols;
+ const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols);
+ const uint32_t height_n = hmx_ceil_div(n_cols_n, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate + nc_n * w_gate_stride),
+ aligned_tile_size, tile_size, tile_size, height_n);
+ }
+
+ // 2. Pop up_s, wait HMX(up_{s-1}) so vtcm_scratch[1] and GLU(s-1) inputs are ready, rescale and submit HMX(up_s)
+ dma_queue_pop(weight_dma);
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ rescale_int_weight_chunk_to_int8_tiles_scales(
+ octx, vtcm_scratch[1], L.weight_bias_offset, vtcm_wt_scales_up[cur],
+ vtcm_weight_raw[1], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+
+ hmx_matmul_task_init_int(&task_up[cur], vtcm_up[cur],
+ vtcm_act, vtcm_scratch[1], L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_up[cur]));
+
+ if (s + 1 < n_chunk_cnt) {
+ const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols;
+ const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols);
+ const uint32_t height_n = hmx_ceil_div(n_cols_n, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[1], w_up + nc_n * w_up_stride),
+ aligned_tile_size, tile_size, tile_size, height_n);
+ }
+
+ // 3. Run HVX GLU(s-1) in parallel with HMX(gate_s) + HMX(up_s) + out_{s-2} DMA, then drain out_{s-2} and push out_{s-1}
+ if (s > 0) {
+ const size_t nc_prev = (size_t) (s - 1) * n_chunk_n_cols;
+ const size_t n_cols_p = hex_smin(n - nc_prev, (size_t) n_chunk_n_cols);
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_int_glu_threaded(
+ octx, &glu_state, vtcm_res_out[prev], vtcm_gate[prev], vtcm_up[prev],
+ vtcm_wt_scales_gate[prev], vtcm_wt_scales_up[prev],
+ (int) n_rows, (int) n_cols_p, chunk_dst_cols);
+ }
+ if (s >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+ const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ }
+
+ // Epilogue: wait HMX(gate_{last}) + HMX(up_{last}), drain out_{last-1}, run GLU(last), push+pop out_{last}
+ {
+ const int last = (n_chunk_cnt - 1) & 1;
+ const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols;
+ const size_t n_cols_last = hex_smin(n - nc_last, (size_t) n_chunk_n_cols);
+ const int chunk_dst_cols = dst_cols - (int) nc_last;
+
+ hmx_queue_pop(ctx->hmx_queue);
+ hmx_queue_pop(ctx->hmx_queue);
+ if (n_chunk_cnt >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_int_glu_threaded(
+ octx, &glu_state, vtcm_res_out[last], vtcm_gate[last], vtcm_up[last],
+ vtcm_wt_scales_gate[last], vtcm_wt_scales_up[last],
+ (int) n_rows, (int) n_cols_last, chunk_dst_cols);
+ }
+
+ const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+ } else {
+ // Non-pipelined 2-buffer path (m <= 32)
+ hmx_matmul_task_t task;
+
+ for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u);
+
+ transfer_activation_chunk_int_threaded(
+ ctx, vtcm_act, vtcm_act_scales,
+ act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ (int) n_rows, k, act_stride, k_valid, n_groups,
+ act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size);
+
+ for (int s = 0; s < n_chunk_cnt; ++s) {
+ const size_t nc = (size_t) s * n_chunk_n_cols;
+ const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols);
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+ const uint32_t height = hmx_ceil_div(n_cols, 32) * n_weight_tiles;
+
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate + nc * w_gate_stride),
+ aligned_tile_size, tile_size, tile_size, height);
+ dma_queue_pop(weight_dma);
+ rescale_int_weight_chunk_to_int8_tiles_scales(
+ octx, vtcm_scratch[0], L.weight_bias_offset, vtcm_wt_scales_gate[0],
+ vtcm_weight_raw[0], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+ hmx_matmul_task_init_int(&task, vtcm_gate[0], vtcm_act, vtcm_scratch[0], L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_up + nc * w_up_stride),
+ aligned_tile_size, tile_size, tile_size, height);
+ dma_queue_pop(weight_dma);
+ rescale_int_weight_chunk_to_int8_tiles_scales(
+ octx, vtcm_scratch[0], L.weight_bias_offset, vtcm_wt_scales_up[0],
+ vtcm_weight_raw[0], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+ hmx_matmul_task_init_int(&task, vtcm_up[0], vtcm_act, vtcm_scratch[0], L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_int_glu_threaded(
+ octx, &glu_state, vtcm_res_out[0], vtcm_gate[0], vtcm_up[0],
+ vtcm_wt_scales_gate[0], vtcm_wt_scales_up[0],
+ (int) n_rows, (int) n_cols, chunk_dst_cols);
+ }
+ const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+ }
+
+ return HTP_STATUS_OK;
+}
+
+static int hmx_mm_nx_glu_fp16_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const struct htp_tensor * restrict src_gate = octx->src[0];
+ const struct htp_tensor * restrict src_up = octx->src[1];
+ const struct htp_tensor * restrict act = octx->src[2];
+ const struct htp_tensor * restrict dst = octx->dst;
+
+ const int weight_type = (int) src_gate->type;
+ const int k = (int) act->ne[0];
+ const int k_valid = (int) act->ne[0];
+ const size_t n = (size_t) src_gate->ne[1];
+ const int m = (int) (act->ne[1] * act->ne[2] * act->ne[3]);
+ const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const int act_stride = (int) (act->nb[1] / act_elem_size);
+ const dma_addr_t act_dma_addr = act->data;
+
+ const int32_t kernel_type = kparams->kernel_type;
+ const int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+ const bool is_tiled = (tile_size > 0);
+ const int tile_k = htp_tensor_get_tile_k(weight_type);
+
+ if ((k & 31) != 0 || (is_tiled && (tile_k <= 0 || (k % tile_k) != 0)) || kernel_type != HTP_MM_KERNEL_HMX_2D) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ if (n == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ const size_t row_stride = htp_tensor_get_row_size(weight_type, k);
+ if (row_stride == 0) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
+ hmx_output_glu_state_t glu_state;
+ if (!resolve_fp16_output_glu_fns(kparams->glu_op, dst_elem_size,
+ &glu_state.col_chunk_fn, &glu_state.store_quad_fn,
+ &glu_state.store_tail_fn, &glu_state.store_strip_fn)) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
+ const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type);
+ const int n_k_tiles = k >> 5;
+ const int n_weight_tiles = is_tiled ? ((weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / tile_k)) : 0;
+ const struct fastdiv_values n_k_tiles_div = kparams->div_n_k_tiles;
+ tiled_dequant_task_fn_t dequant_worker_fn = hmx_get_dequant_worker_fn(weight_type, is_tiled);
+
+ const size_t vtcm_budget = ctx->vtcm_size;
+ const int m_chunk_n_rows = kparams->m_chunk;
+ const int n_chunk_n_cols = kparams->n_chunk;
+ const int pipeline = kparams->pipeline;
+ const int act_hvx = kparams->n_act_hvx;
+ const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx;
+ const struct fastdiv_values * k_div = &kparams->div_ne00_padded;
+
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_glu(&L, kernel_type, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, pipeline, act_hvx, aligned_tile_size,
+ dst_elem_size);
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-mm-nx-glu-fp16: VTCM overflow: used %zu budget %zu, m %d k %d n %zu mc %d nc %d",
+ L.total_bytes, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * const base = (uint8_t *) ctx->vtcm_base;
+ void * vtcm_weight_raw[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_weight[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_weight[1], pipeline)
+ };
+ __fp16 * vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act);
+ float * vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
+ __fp16 * vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales);
+ __fp16 * vtcm_gate[2] = {
+ VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_dst[1], pipeline)
+ };
+ __fp16 * vtcm_up[2] = {
+ VTCM_LAYOUT_PTR(__fp16, base, L.off_dst_up[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_dst_up[1], pipeline)
+ };
+ void * vtcm_scratch[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline)
+ };
+ void * vtcm_res_out[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline)
+ };
+
+ hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16
+ if (L.lut_bytes > 0) {
+ iq2xxs_lut_copy(base + L.off_lut);
+ }
+
+ int m_start = 0;
+ int m_rows = m;
+ if (octx->ctx->mdev.count > 1) {
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ m_start = (int) range.start;
+ m_rows = (int) range.count;
+ }
+ if (m_rows == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ FARF(HIGH, "hmx-mm-nx-glu-fp16: glu %u m %d (%d..%d) k %d n %zu wtype %d mc %d nc %d vtcm %zu/%zu",
+ (unsigned) kparams->glu_op, m, m_start, m_start + m_rows, k, n, weight_type,
+ m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const size_t mr_end = (size_t) (m_start + m_rows);
+ const dma_addr_t w_gate = src_gate->data;
+ const dma_addr_t w_up = src_up->data;
+ const size_t w_gate_stride = src_gate->nb[1];
+ const size_t w_up_stride = src_up->nb[1];
+ const dma_addr_t dst_dma_addr = dst->data;
+ const size_t dst_stride = dst->nb[1] / dst_elem_size;
+ const size_t dst_row_bytes = dst->nb[1];
+ const int dst_cols = (int) dst->ne[0];
+ const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
+ const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ const uint32_t dma_dst_stride = is_tiled ? (uint32_t) aligned_tile_size : (uint32_t) row_stride;
+ const uint32_t dma_width_bytes = is_tiled ? (uint32_t) tile_size : (uint32_t) row_stride;
+ const uint32_t dma_src_stride_g = is_tiled ? (uint32_t) tile_size : (uint32_t) w_gate_stride;
+ const uint32_t dma_src_stride_u = is_tiled ? (uint32_t) tile_size : (uint32_t) w_up_stride;
+ dma_queue * weight_dma = octx->ctx->dma[0];
+
+ glu_state.vtcm_act_scales = NULL;
+ glu_state.vtcm_wt_scales_up = NULL;
+ glu_state.n_groups = 1u;
+ glu_state.dst_stride = (uint32_t) res_out_stride_elems;
+ glu_state.dst_elem_size = dst_elem_size;
+
+ if (pipeline) {
+ // When dequant_worker_fn is NULL (pre-tiled F16), ping-pong raw/HMX across {weight_raw, scratch}.
+ void * gate_raw_buf[2] = { vtcm_weight_raw[0], dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch[0] };
+ void * up_raw_buf[2] = { vtcm_weight_raw[1], dequant_worker_fn ? vtcm_weight_raw[1] : vtcm_scratch[1] };
+ void * gate_hmx_buf[2] = { dequant_worker_fn ? vtcm_scratch[0] : vtcm_weight_raw[0], vtcm_scratch[0] };
+ void * up_hmx_buf[2] = { dequant_worker_fn ? vtcm_scratch[1] : vtcm_weight_raw[1], vtcm_scratch[1] };
+
+ hmx_matmul_task_t task_gate[2];
+ hmx_matmul_task_t task_up[2];
+
+ for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+
+ struct activation_transfer_params act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ .n_rows = (int) n_rows,
+ .k_block = k,
+ .k_stride = act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = k_valid,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ };
+ transfer_activation_chunk_threaded(&act_params);
+
+ // Prologue: push gate_0 and up_0
+ {
+ const size_t n_cols0 = hex_smin(n, (size_t) n_chunk_n_cols);
+ const uint32_t height0 = is_tiled ? (hmx_ceil_div(n_cols0, 32) * n_weight_tiles) : (uint32_t) n_cols0;
+ dma_queue_push(weight_dma, dma_make_data(gate_raw_buf[0], w_gate),
+ dma_dst_stride, dma_src_stride_g, dma_width_bytes, height0);
+ dma_queue_push(weight_dma, dma_make_data(up_raw_buf[0], w_up),
+ dma_dst_stride, dma_src_stride_u, dma_width_bytes, height0);
+ }
+
+ for (int s = 0; s < n_chunk_cnt; ++s) {
+ const int cur = s & 1;
+ const int next = (s + 1) & 1;
+ const int prev = (s - 1) & 1;
+ const size_t nc = (size_t) s * n_chunk_n_cols;
+ const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols);
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+
+ // 1. Pop gate_s, wait HMX(gate_{s-1}) so gate_hmx_buf[cur] is free, dequant and submit HMX(gate_s)
+ dma_queue_pop(weight_dma);
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ if (dequant_worker_fn) {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, gate_hmx_buf[cur], gate_raw_buf[cur],
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
+
+ hmx_matmul_task_init(&task_gate[cur], vtcm_gate[cur], vtcm_f16_act, (__fp16 *) gate_hmx_buf[cur],
+ vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_gate[cur]));
+
+ if (s + 1 < n_chunk_cnt) {
+ const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols;
+ const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols);
+ const uint32_t height_n = is_tiled ? (hmx_ceil_div(n_cols_n, 32) * n_weight_tiles) : (uint32_t) n_cols_n;
+ dma_queue_push(weight_dma, dma_make_data(gate_raw_buf[next], w_gate + nc_n * w_gate_stride),
+ dma_dst_stride, dma_src_stride_g, dma_width_bytes, height_n);
+ }
+
+ // 2. Pop up_s, wait HMX(up_{s-1}) so up_hmx_buf[cur] and GLU(s-1) inputs are ready, dequant and submit HMX(up_s)
+ dma_queue_pop(weight_dma);
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ if (dequant_worker_fn) {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, up_hmx_buf[cur], up_raw_buf[cur],
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
+
+ hmx_matmul_task_init(&task_up[cur], vtcm_up[cur], vtcm_f16_act, (__fp16 *) up_hmx_buf[cur],
+ vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_up[cur]));
+
+ if (s + 1 < n_chunk_cnt) {
+ const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols;
+ const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols);
+ const uint32_t height_n = is_tiled ? (hmx_ceil_div(n_cols_n, 32) * n_weight_tiles) : (uint32_t) n_cols_n;
+ dma_queue_push(weight_dma, dma_make_data(up_raw_buf[next], w_up + nc_n * w_up_stride),
+ dma_dst_stride, dma_src_stride_u, dma_width_bytes, height_n);
+ }
+
+ // 3. Run HVX GLU(s-1) in parallel with HMX(gate_s) + HMX(up_s) + out_{s-2} DMA, then drain out_{s-2} and push out_{s-1}
+ if (s > 0) {
+ const size_t nc_prev = (size_t) (s - 1) * n_chunk_n_cols;
+ const size_t n_cols_p = hex_smin(n - nc_prev, (size_t) n_chunk_n_cols);
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_int_glu_threaded(
+ octx, &glu_state, vtcm_res_out[prev], vtcm_gate[prev], vtcm_up[prev],
+ NULL, NULL, (int) n_rows, (int) n_cols_p, chunk_dst_cols);
+ }
+ if (s >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+ const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ }
+
+ // Epilogue: wait HMX(gate_{last}) + HMX(up_{last}), drain out_{last-1}, run GLU(last), push+pop out_{last}
+ {
+ const int last = (n_chunk_cnt - 1) & 1;
+ const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols;
+ const size_t n_cols_last = hex_smin(n - nc_last, (size_t) n_chunk_n_cols);
+ const int chunk_dst_cols = dst_cols - (int) nc_last;
+
+ hmx_queue_pop(ctx->hmx_queue);
+ hmx_queue_pop(ctx->hmx_queue);
+ if (n_chunk_cnt >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_int_glu_threaded(
+ octx, &glu_state, vtcm_res_out[last], vtcm_gate[last], vtcm_up[last],
+ NULL, NULL, (int) n_rows, (int) n_cols_last, chunk_dst_cols);
+ }
+
+ const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+ } else {
+ // Non-pipelined 2-buffer path (m <= 32)
+ void * w_hmx = dequant_worker_fn ? vtcm_scratch[0] : vtcm_weight_raw[0];
+ hmx_matmul_task_t task;
+
+ for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+
+ struct activation_transfer_params act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ .n_rows = (int) n_rows,
+ .k_block = k,
+ .k_stride = act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = k_valid,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ };
+ transfer_activation_chunk_threaded(&act_params);
+
+ for (int s = 0; s < n_chunk_cnt; ++s) {
+ const size_t nc = (size_t) s * n_chunk_n_cols;
+ const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols);
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+ const uint32_t height = is_tiled ? (hmx_ceil_div(n_cols, 32) * n_weight_tiles) : (uint32_t) n_cols;
+
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate + nc * w_gate_stride),
+ dma_dst_stride, dma_src_stride_g, dma_width_bytes, height);
+ dma_queue_pop(weight_dma);
+ if (dequant_worker_fn) {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, w_hmx, vtcm_weight_raw[0],
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
+ hmx_matmul_task_init(&task, vtcm_gate[0], vtcm_f16_act, (__fp16 *) w_hmx,
+ vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_up + nc * w_up_stride),
+ dma_dst_stride, dma_src_stride_u, dma_width_bytes, height);
+ dma_queue_pop(weight_dma);
+ if (dequant_worker_fn) {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, w_hmx, vtcm_weight_raw[0],
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
+ hmx_matmul_task_init(&task, vtcm_up[0], vtcm_f16_act, (__fp16 *) w_hmx,
+ vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_int_glu_threaded(
+ octx, &glu_state, vtcm_res_out[0], vtcm_gate[0], vtcm_up[0],
+ NULL, NULL, (int) n_rows, (int) n_cols, chunk_dst_cols);
+ }
+ const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+ }
+
+ return HTP_STATUS_OK;
+}
+
static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) {
struct htp_context * ctx = octx->ctx;
struct htp_thread_trace * tr = &ctx->trace[0];
@@ -2940,16 +4829,23 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
const int act_stride = (int) (act->nb[1] / act_elem_size);
const dma_addr_t act_dma_addr = act->data;
- if (k % 32 != 0) { return HTP_STATUS_NO_SUPPORT; }
+ const int32_t kernel_type = kparams->kernel_type;
+ const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type);
+ const int n_groups = is_int_hmx ? kparams->hmx_n_groups : 1;
+
+ if ((k & 31) != 0) { return HTP_STATUS_NO_SUPPORT; }
+
+ const struct fastdiv_values n_groups_div = kparams->div_hmx_n_groups;
+ const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type);
size_t row_stride = htp_tensor_get_row_size(weight_type, k);
if (row_stride == 0) {
return HTP_STATUS_NO_SUPPORT;
}
- const int n_k_tiles = k / HTP_MM_HMX_TILE_N_COLS;
- const int n_weight_tiles = k / htp_tensor_get_tile_k(weight_type);
- const struct fastdiv_values n_k_tiles_div = init_fastdiv_values(n_k_tiles);
+ const int n_k_tiles = k >> 5;
+ const int n_weight_tiles = (weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / htp_tensor_get_tile_k(weight_type));
+ const struct fastdiv_values n_k_tiles_div = kparams->div_n_k_tiles;
const int tile_size = kparams->tile_size;
const int aligned_tile_size = kparams->aligned_tile_size;
@@ -2961,7 +4857,6 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
const int m_chunk_n_rows = kparams->m_chunk;
const int n_chunk_n_cols = kparams->n_chunk;
const int pipeline = kparams->pipeline;
- const int n_hvx = octx->n_hvx;
const int act_hvx = kparams->n_act_hvx;
const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx;
const struct fastdiv_values * k_div = &kparams->div_ne00_padded;
@@ -2969,8 +4864,18 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride;
const uint32_t dma_width_bytes = is_tiled ? tile_size : row_stride;
+ size_t max_dst_elem_size = sizeof(__fp16);
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ if (octx->dsts[p]) {
+ const size_t es = (octx->dsts[p]->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ if (es > max_dst_elem_size) max_dst_elem_size = es;
+ }
+ }
+
struct htp_mm_hmx_vtcm_layout L;
- htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_2D, weight_type, k, m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, 0);
+ htp_mm_hmx_vtcm_layout_build_ex(&L, kernel_type, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, 0,
+ 0, max_dst_elem_size);
if (L.total_bytes > vtcm_budget) {
FARF(ERROR, "hmx-mm-nx-2d: VTCM overflow: used %zu budget %zu, m %d k %d mc %d nc %d",
@@ -2985,13 +4890,20 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
};
__fp16 *vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act);
float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
+ float *vtcm_act_scales = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_act_scales, is_int_hmx);
__fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]);
void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]);
void *vtcm_scratch1 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline);
void *vtcm_scratch2 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[1], pipeline);
- __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales);
+ void *vtcm_res_out[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline),
+ };
+ __fp16 *vtcm_scales = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_scales, !is_int_hmx);
- hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16
+ if (!is_int_hmx) {
+ hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16
+ }
if (L.lut_bytes > 0) {
iq2xxs_lut_copy(base + L.off_lut);
}
@@ -2999,17 +4911,7 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
int m_start = 0;
int m_rows = m;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 1;
- for (uint32_t p = 0; p < n_weights; ++p) {
- const struct htp_tensor * restrict dst = octx->dsts[p];
- uint32_t dst_rpc = 0;
- if (!htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), dst->ne[0] * sizeof(float), &dst_rpc)) {
- rows_per_chunk = 0;
- break;
- }
- rows_per_chunk = MAX(rows_per_chunk, dst_rpc);
- }
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
m_start = (int) range.start;
m_rows = (int) range.count;
}
@@ -3018,15 +4920,16 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
return HTP_STATUS_OK;
}
- FARF(HIGH, "hmx-mm-nx-2d: n_weights %u m %d (%d..%d) k %d wtype %d mc %d nc %d vtcm %zu/%zu",
- n_weights, m, m_start, m_start + m_rows, k, weight_type, m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget);
+ FARF(HIGH, "hmx-mm-nx-2d: ktype %d n_weights %u m %d (%d..%d) k %d wtype %d mc %d nc %d vtcm %zu/%zu",
+ (int) kernel_type, n_weights, m, m_start, m_start + m_rows, k, weight_type, m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget);
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
const size_t mr_end = (size_t)(m_start + m_rows);
+ const uint32_t m_tile_rows = is_int_hmx ? 64u : HTP_MM_HMX_TILE_N_ROWS;
if (pipeline) {
- hmx_matmul_job_t job_slots[2];
+ hmx_matmul_task_t task_slots[2];
void *vtcm_raw_bufs[4] = {
vtcm_weight_raw[0],
vtcm_weight_raw[1],
@@ -3041,25 +4944,46 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
};
void *vtcm_output_bufs[2] = { vtcm_output, vtcm_scratch2 };
+ const bool preissue_p0 = is_int_hmx && L.can_preissue_weight && n_weights > 0
+ && octx->src[0] && octx->dsts[0] && octx->src[0]->ne[1] > 0;
+
for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) {
const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
- struct activation_transfer_params act_params = {
- .ctx = ctx,
- .dst = vtcm_f16_act,
- .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
- .n_rows = (int) n_rows,
- .k_block = k,
- .k_stride = act_stride,
- .n_hvx = act_hvx,
- .act_hvx_div = act_hvx_div,
- .k_div = k_div,
- .k_valid = k_valid,
- .vtcm_f32_act = vtcm_f32_act,
- .vtcm_f32_act_bytes = L.act_f32_bytes,
- .act_elem_size = act_elem_size,
- };
- transfer_activation_chunk_threaded(&act_params);
+ if (preissue_p0) {
+ const struct htp_tensor * src_w0 = octx->src[0];
+ const size_t n0 = src_w0->ne[1];
+ const size_t n_cols_A0 = hex_smin(n0, (size_t) n_chunk_n_cols);
+ const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0;
+ const uint32_t src_str0 = is_tiled ? tile_size : src_w0->nb[1];
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_raw_bufs[0], src_w0->data),
+ dma_dst_stride, src_str0, dma_width_bytes, height_A0);
+ }
+
+ if (is_int_hmx) {
+ transfer_activation_chunk_int_threaded(
+ ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales,
+ act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ (int) n_rows, k, act_stride, k_valid, n_groups,
+ act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size);
+ } else {
+ struct activation_transfer_params act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ .n_rows = (int) n_rows,
+ .k_block = k,
+ .k_stride = act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = k_valid,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ };
+ transfer_activation_chunk_threaded(&act_params);
+ }
for (uint32_t p = 0; p < n_weights; p++) {
const struct htp_tensor * restrict src_w = octx->src[p];
@@ -3067,101 +4991,203 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
if (!src_w || !dst) continue;
const dma_addr_t weight = src_w->data;
- dma_queue * weight_dma = octx->ctx->dma[0];
- float * dst_ptr = (float *) dst->data;
- const size_t n = src_w->ne[1];
+ dma_queue * weight_dma = octx->ctx->dma[0];
+ const dma_addr_t dst_dma_addr = dst->data;
+ const size_t n = src_w->ne[1];
if (n == 0) continue;
- const size_t weight_stride = src_w->nb[1];
- const size_t dst_stride = dst->nb[1] / sizeof(float);
- const int dst_cols = (int) dst->ne[0];
- const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ const size_t weight_stride = src_w->nb[1];
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_stride = dst->nb[1] / dst_elem_size;
+ const size_t dst_row_bytes = dst->nb[1];
+ const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
+ const int dst_cols = (int) dst->ne[0];
+ const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
+ const bool p_preissued = (p == 0 && preissue_p0);
- const size_t n_cols_A0 = hex_smin(n - 0 * n_chunk_n_cols, n_chunk_n_cols);
- const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0;
- dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
- dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0);
+ if (!p_preissued) {
+ const size_t n_cols_A0 = hex_smin(n, (size_t) n_chunk_n_cols);
+ const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0);
+ }
if (1 < n_chunk_cnt) {
- const size_t n_cols_A1 = hex_smin(n - 1 * n_chunk_n_cols, n_chunk_n_cols);
+ const size_t n_cols_A1 = hex_smin(n - (size_t) n_chunk_n_cols, (size_t) n_chunk_n_cols);
const uint32_t height_A1 = is_tiled ? hmx_ceil_div(n_cols_A1, 32) * n_weight_tiles : n_cols_A1;
- dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[1], weight + n_chunk_n_cols * weight_stride),
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[1], weight + (size_t) n_chunk_n_cols * weight_stride),
dma_dst_stride, dma_src_stride, dma_width_bytes, height_A1);
}
for (int i = 0; i < n_chunk_cnt; ++i) {
- const size_t nc = i * n_chunk_n_cols;
- const size_t nc_p2 = nc + 2 * n_chunk_n_cols;
-
- const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols);
- const size_t n_cols_p2 = hex_smin(n - nc_p2, n_chunk_n_cols);
-
- void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
-
- dequantize_tiled_weight_chunk_to_fp16_tiles(
- ctx, vtcm_weight_bufs[i % 4], curr_raw,
- n_cols, k, row_stride, weight_type,
- n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx);
+ const size_t nc = (size_t) i * n_chunk_n_cols;
+ const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols);
+
+ void * curr_raw;
+ if (i == 0 && p_preissued) {
+ curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst;
+ } else {
+ curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ }
- if (i + 2 < n_chunk_cnt) {
- const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2;
- dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride),
- dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2);
+ if (is_int_hmx) {
+ rescale_int_weight_chunk_to_int8_tiles(
+ octx, vtcm_weight_bufs[i % 4], L.weight_bias_offset, L.weight_scales_offset,
+ curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+ } else {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, vtcm_weight_bufs[i % 4], curr_raw,
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
}
- hmx_matmul_job_init(&job_slots[i % 2], (__fp16 *) vtcm_output_bufs[i % 2],
- (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4],
- vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS),
- hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), k / HTP_MM_HMX_TILE_N_ROWS);
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job_slots[i % 2]));
+ if (i == 0) {
+ if (is_int_hmx) {
+ hmx_matmul_task_init_int(&task_slots[0], vtcm_output_bufs[0],
+ vtcm_f16_act, vtcm_weight_bufs[0], L.weight_bias_offset,
+ hmx_ceil_div(n_rows, m_tile_rows),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ } else {
+ hmx_matmul_task_init(&task_slots[0], (__fp16 *) vtcm_output_bufs[0],
+ (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[0],
+ vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles);
+ }
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[0]));
+
+ if (2 < n_chunk_cnt) {
+ const size_t nc2 = 2u * (size_t) n_chunk_n_cols;
+ const size_t n_cols_p2 = hex_smin(n - nc2, (size_t) n_chunk_n_cols);
+ const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[2], weight + nc2 * weight_stride),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2);
+ }
+ } else {
+ const int prev = (i - 1) & 1;
+ const size_t nc_prev = (size_t) (i - 1) * n_chunk_n_cols;
+ const size_t n_cols_p = hex_smin(n - nc_prev, (size_t) n_chunk_n_cols);
- if (i > 0) {
hmx_queue_pop(ctx->hmx_queue);
- const size_t nc_prev = (i - 1) * n_chunk_n_cols;
- const size_t n_cols_prev = hex_smin(n - nc_prev, n_chunk_n_cols);
- float *output_chunk = dst_ptr + (mr * dst_stride + nc_prev);
- int chunk_dst_cols = dst_cols - (int)nc_prev;
+ if (is_int_hmx) {
+ hmx_matmul_task_init_int(&task_slots[i & 1], vtcm_output_bufs[i & 1],
+ vtcm_f16_act, vtcm_weight_bufs[i % 4], L.weight_bias_offset,
+ hmx_ceil_div(n_rows, m_tile_rows),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ } else {
+ hmx_matmul_task_init(&task_slots[i & 1], (__fp16 *) vtcm_output_bufs[i & 1],
+ (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4],
+ vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles);
+ }
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[i & 1]));
+
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output_chunk, NULL, vtcm_output_bufs[(i - 1) % 2], n_rows, n_cols_prev, dst_stride, 0, chunk_dst_cols, n_hvx);
+ if (is_int_hmx) {
+ const float * wt_scales_prev = (const float *) ((const uint8_t *) vtcm_weight_bufs[(i - 1) % 4] + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out[prev], NULL, vtcm_output_bufs[prev],
+ vtcm_act_scales, wt_scales_prev, (int) n_rows, (int) n_cols_p,
+ n_groups, res_out_stride_elems, 0, chunk_dst_cols,
+ dst_elem_size, sizeof(float));
+ } else {
+ transfer_output_chunk_threaded(octx, vtcm_res_out[prev], NULL, vtcm_output_bufs[prev],
+ n_rows, n_cols_p, res_out_stride_elems, 0, chunk_dst_cols,
+ dst_elem_size, sizeof(float));
+ }
+ }
+
+ if (i >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+
+ const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+
+ if (i + 2 < n_chunk_cnt) {
+ const size_t nc_p2 = (size_t) (i + 2) * n_chunk_n_cols;
+ const size_t n_cols_p2 = hex_smin(n - nc_p2, (size_t) n_chunk_n_cols);
+ const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2);
}
}
}
- hmx_queue_pop(ctx->hmx_queue);
- const size_t nc_last = (n_chunk_cnt - 1) * n_chunk_n_cols;
- const size_t n_cols_last = hex_smin(n - nc_last, n_chunk_n_cols);
- float *output_chunk = dst_ptr + (mr * dst_stride + nc_last);
- int chunk_dst_cols = dst_cols - (int)nc_last;
- if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output_chunk, NULL, vtcm_output_bufs[(n_chunk_cnt - 1) % 2], n_rows, n_cols_last, dst_stride, 0, chunk_dst_cols, n_hvx);
+ {
+ const int last = (n_chunk_cnt - 1) & 1;
+ const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols;
+ const size_t n_cols_last = hex_smin(n - nc_last, (size_t) n_chunk_n_cols);
+
+ hmx_queue_pop(ctx->hmx_queue);
+ if (n_chunk_cnt >= 2) {
+ dma_queue_pop(weight_dma);
+ }
+
+ const int chunk_dst_cols = dst_cols - (int) nc_last;
+ if (chunk_dst_cols > 0) {
+ if (is_int_hmx) {
+ const float * wt_scales_last = (const float *) ((const uint8_t *) vtcm_weight_bufs[(n_chunk_cnt - 1) % 4] + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out[last], NULL, vtcm_output_bufs[last],
+ vtcm_act_scales, wt_scales_last, (int) n_rows, (int) n_cols_last,
+ n_groups, res_out_stride_elems, 0, chunk_dst_cols,
+ dst_elem_size, sizeof(float));
+ } else {
+ transfer_output_chunk_threaded(octx, vtcm_res_out[last], NULL, vtcm_output_bufs[last],
+ n_rows, n_cols_last, res_out_stride_elems, 0, chunk_dst_cols,
+ dst_elem_size, sizeof(float));
+ }
+ }
+
+ const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
}
}
}
} else {
- hmx_matmul_job_t job;
+ hmx_matmul_task_t task;
void *vtcm_raw_bufs[2] = { vtcm_weight_raw[0], dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch0 };
void *vtcm_weight_bufs[2] = { dequant_worker_fn ? vtcm_scratch0 : vtcm_weight_raw[0], vtcm_scratch0 };
for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) {
const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
- struct activation_transfer_params act_params = {
- .ctx = ctx,
- .dst = vtcm_f16_act,
- .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
- .n_rows = (int) n_rows,
- .k_block = k,
- .k_stride = act_stride,
- .n_hvx = act_hvx,
- .act_hvx_div = act_hvx_div,
- .k_div = k_div,
- .k_valid = k_valid,
- .vtcm_f32_act = vtcm_f32_act,
- .vtcm_f32_act_bytes = L.act_f32_bytes,
- .act_elem_size = act_elem_size,
- };
- transfer_activation_chunk_threaded(&act_params);
+ if (is_int_hmx) {
+ transfer_activation_chunk_int_threaded(
+ ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales,
+ act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ (int) n_rows, k, act_stride, k_valid, n_groups,
+ act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size);
+ } else {
+ struct activation_transfer_params act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size,
+ .n_rows = (int) n_rows,
+ .k_block = k,
+ .k_stride = act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = k_valid,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ };
+ transfer_activation_chunk_threaded(&act_params);
+ }
for (uint32_t p = 0; p < n_weights; p++) {
const struct htp_tensor * restrict src_w = octx->src[p];
@@ -3169,52 +5195,88 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k
if (!src_w || !dst) continue;
const dma_addr_t weight = src_w->data;
- dma_queue * weight_dma = octx->ctx->dma[0];
- float * dst_ptr = (float *) dst->data;
- const size_t n = src_w->ne[1];
+ dma_queue * weight_dma = octx->ctx->dma[0];
+ const dma_addr_t dst_dma_addr = dst->data;
+ const size_t n = src_w->ne[1];
if (n == 0) continue;
- const size_t weight_stride = src_w->nb[1];
- const size_t dst_stride = dst->nb[1] / sizeof(float);
- const int dst_cols = (int) dst->ne[0];
- const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ const size_t weight_stride = src_w->nb[1];
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_stride = dst->nb[1] / dst_elem_size;
+ const size_t dst_row_bytes = dst->nb[1];
+ const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
+ const int dst_cols = (int) dst->ne[0];
+ const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
if (n > 0) {
- const size_t n_cols = hex_smin(n, n_chunk_n_cols);
+ const size_t n_cols = hex_smin(n, (size_t) n_chunk_n_cols);
const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols;
dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), dma_dst_stride, dma_src_stride, dma_width_bytes, height);
}
for (int i = 0; i < n_chunk_cnt; ++i) {
const size_t nc = (size_t) i * n_chunk_n_cols;
- const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols);
- const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, m_tile_rows);
const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ if (i > 0) {
+ dma_queue_pop(weight_dma);
+ }
- dequantize_tiled_weight_chunk_to_fp16_tiles(
- ctx, vtcm_weight_bufs[i % 2], curr_raw,
- n_cols, k, row_stride, weight_type,
- n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx);
+ if (is_int_hmx) {
+ rescale_int_weight_chunk_to_int8_tiles(
+ octx, vtcm_weight_bufs[i % 2], L.weight_bias_offset, L.weight_scales_offset,
+ curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type);
+ } else {
+ dequantize_tiled_weight_chunk_to_fp16_tiles(
+ octx, vtcm_weight_bufs[i % 2], curr_raw,
+ n_cols, k, row_stride, weight_type,
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn);
+ }
- const size_t nc_next = nc + n_chunk_n_cols;
+ const size_t nc_next = nc + (size_t) n_chunk_n_cols;
if (nc_next < n) {
- const size_t n_cols_next = hex_smin(n - nc_next, n_chunk_n_cols);
+ const size_t n_cols_next = hex_smin(n - nc_next, (size_t) n_chunk_n_cols);
const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next;
dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_next);
}
- hmx_matmul_job_init(&job, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS);
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job));
+ if (is_int_hmx) {
+ hmx_matmul_task_init_int(&task, vtcm_output, vtcm_f16_act, vtcm_weight_bufs[i % 2], L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ } else {
+ hmx_matmul_task_init(&task, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ }
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task));
hmx_queue_pop(ctx->hmx_queue);
- float *output_chunk = dst_ptr + (mr * dst_stride + nc);
- int chunk_dst_cols = dst_cols - (int)nc;
+ int chunk_dst_cols = dst_cols - (int) nc;
if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output_chunk, NULL, vtcm_output, n_rows, n_cols, dst_stride, 0, chunk_dst_cols, n_hvx);
+ if (is_int_hmx) {
+ const float * wt_scales = (const float *) ((const uint8_t *) vtcm_weight_bufs[i % 2] + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out[0], NULL, vtcm_output,
+ vtcm_act_scales, wt_scales, (int) n_rows, (int) n_cols,
+ n_groups, res_out_stride_elems, 0, chunk_dst_cols,
+ dst_elem_size, sizeof(float));
+ } else {
+ transfer_output_chunk_threaded(octx, vtcm_res_out[0], NULL, vtcm_output,
+ n_rows, n_cols, res_out_stride_elems, 0, chunk_dst_cols,
+ dst_elem_size, sizeof(float));
+ }
}
+ const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0;
+ dma_queue_push(weight_dma,
+ dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ if (n_chunk_cnt > 0) {
+ dma_queue_pop(weight_dma);
}
}
}
@@ -3236,16 +5298,16 @@ static inline dma_addr_t hmx_mm_act_batch_addr(const hmx_mm_batched_params_t *pa
dst_b3 * params->act_nb3;
}
-static inline float *hmx_mm_dst_batch_ptr(const hmx_mm_batched_params_t *params,
- int dst_b2, int dst_b3) {
- return (float *) ((uint8_t *) params->dst +
- (size_t) dst_b2 * params->dst_nb2 +
- (size_t) dst_b3 * params->dst_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 int hmx_mm_batched_simple(struct htp_context *ctx,
+static int hmx_mm_batched_simple(struct htp_ops_context *octx,
const hmx_mm_batched_params_t *params,
- int m_chunk, int n_chunk, int pipeline, int n_hvx, int act_hvx, int vtcm_size,
+ int m_chunk, int n_chunk, int pipeline, int act_hvx, int vtcm_size,
const struct fastdiv_values * act_hvx_div, const struct fastdiv_values * k_div) {
int ret = 0;
for (int b3 = 0; b3 < params->ne13 && ret == 0; ++b3) {
@@ -3253,25 +5315,29 @@ static int hmx_mm_batched_simple(struct htp_context *ctx,
dma_addr_t cur_bias_addr = params->bias_addr ? (params->bias_addr +
b2 * params->bias_nb2 +
b3 * params->bias_nb3) : 0;
- ret = hmx_mm_2d_f32(ctx, params->weight_dma, hmx_mm_dst_batch_ptr(params, b2, b3),
+ ret = hmx_mm_2d_f32(octx, params->weight_dma, hmx_mm_dst_batch_addr(params, b2, b3),
cur_bias_addr, params->bias_bytes,
hmx_mm_act_batch_addr(params, b2, b3),
hmx_mm_weight_batch_data(params, b2, b3),
params->m, params->k, params->n,
params->act_stride, params->act_elem_size, params->weight_stride,
params->weight_type, params->k, params->dst_stride, params->bias_stride, params->dst_cols,
- m_chunk, n_chunk, pipeline, n_hvx, act_hvx,
- act_hvx_div, k_div, params->tile_size, params->aligned_tile_size, vtcm_size);
+ params->dst_elem_size, params->bias_elem_size,
+ m_chunk, n_chunk, pipeline, act_hvx,
+ act_hvx_div, k_div, params->tile_size, params->aligned_tile_size, vtcm_size,
+ params->kernel_type, params->hmx_n_groups,
+ ¶ms->div_hmx_n_groups, ¶ms->div_n_k_tiles);
}
}
return ret;
}
-static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t *params,
- int m_chunk, int n_chunk, int pipeline, int n_hvx, int act_hvx,
+static int hmx_mm_batched(struct htp_ops_context *octx, const hmx_mm_batched_params_t *params,
+ int m_chunk, int n_chunk, int pipeline, int act_hvx,
const struct fastdiv_values * act_hvx_div,
const struct fastdiv_values * k_div,
int vtcm_size) {
+ struct htp_context * ctx = octx->ctx;
const size_t row_stride = htp_tensor_get_row_size(params->weight_type, params->k);
if (row_stride == 0) { return -1; }
if (params->act_stride < params->k || (params->tile_size == 0 && (size_t) params->weight_stride < row_stride) || params->dst_stride < params->dst_cols) { return -1; }
@@ -3279,7 +5345,7 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
if (params->ne12 % params->ne02 != 0 || params->ne13 % params->ne03 != 0) { return -1; }
// N (the weight row count) does not have to be 32-aligned:
if (params->k % 32 != 0) { return -1; }
- if (!hex_is_aligned(params->dst, sizeof(float))) { return -1; }
+ if ((params->dst_dma_addr & (params->dst_elem_size - 1)) != 0) { return -1; }
const int group_size = params->r2;
const size_t vtcm_budget = ctx->vtcm_size;
@@ -3287,9 +5353,10 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
// Check if the precomputed parameters are grouped or simple.
// If simple, or if group_size <= 1, we use simple fallback loop.
// Grouped path is only valid for flat F16 if group_size > 1 and it fits within VTCM budget.
- bool run_grouped = (params->weight_type == HTP_TYPE_F16 && params->tile_size == 0 && group_size > 1 && (size_t)vtcm_size <= vtcm_budget);
+ bool run_grouped = (params->weight_type == HTP_TYPE_F16 && params->tile_size == 0 && group_size > 1 &&
+ params->bias_nb2 == 0 && params->bias_nb3 == 0 && (size_t)vtcm_size <= vtcm_budget);
if (!run_grouped) {
- return hmx_mm_batched_simple(ctx, params, m_chunk, n_chunk, pipeline, n_hvx, act_hvx, vtcm_size, act_hvx_div, k_div);
+ return hmx_mm_batched_simple(octx, params, m_chunk, n_chunk, pipeline, act_hvx, vtcm_size, act_hvx_div, k_div);
}
struct htp_thread_trace * tr = &ctx->trace[0];
@@ -3299,12 +5366,12 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
size_t n_chunk_n_cols = n_chunk;
struct htp_mm_hmx_vtcm_layout L;
- htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_BATCHED, HTP_TYPE_F16, params->k, m_chunk_n_rows, n_chunk_n_cols, group_size, false, act_hvx, 0, params->bias_bytes);
+ htp_mm_hmx_vtcm_layout_build_ex(&L, HTP_MM_KERNEL_HMX_BATCHED, HTP_TYPE_F16, params->k, m_chunk_n_rows, n_chunk_n_cols, group_size, false, act_hvx, 0, params->bias_bytes, 0, params->dst_elem_size);
if (L.total_bytes > vtcm_budget) {
FARF(HIGH, "%s: grouped layout overflowed VTCM, falling back to simple batched loop", __func__);
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
- return hmx_mm_batched_simple(ctx, params, m_chunk, n_chunk, pipeline, n_hvx, act_hvx, vtcm_size, act_hvx_div, k_div);
+ return hmx_mm_batched_simple(octx, params, m_chunk, n_chunk, pipeline, act_hvx, vtcm_size, act_hvx_div, k_div);
}
uint8_t * const base = (uint8_t *) ctx->vtcm_base;
@@ -3313,11 +5380,12 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
__fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]);
void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]);
void *vtcm_scratch1 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[1]);
+ void *vtcm_res_out = VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]);
__fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales);
float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
const bool has_bias = (params->bias_bytes > 0 && params->bias_addr != 0);
- float *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_bias, has_bias);
+ void *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_bias, has_bias);
if (has_bias) {
dma_queue_push(params->weight_dma, dma_make_data(vtcm_bias, params->bias_addr), hex_align_up(params->bias_bytes, 128), 0, params->bias_bytes, 1);
dma_queue_pop(params->weight_dma);
@@ -3335,7 +5403,7 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
- hmx_matmul_job_t job;
+ hmx_matmul_task_t task;
for (int b3 = 0; b3 < params->ne13; ++b3) {
for (int b2_base = 0; b2_base < params->ne12; b2_base += group_size) {
@@ -3373,60 +5441,66 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
transfer_activation_chunk_threaded(&act_params);
}
- // Prologue: Push A0 and A1 (if exists)
- {
+ const size_t dst_row_bytes = (size_t) params->dst_stride * params->dst_elem_size;
+ const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * params->dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / params->dst_elem_size);
+
+ // Prologue: push first weight chunk
+ if (params->n > 0) {
const size_t n_cols_first = hex_smin((size_t) params->n, n_chunk_n_cols);
dma_queue_push(weight_dma, dma_make_data(vtcm_scratch0, weight_group),
- fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_first);
- }
- if (n_chunk_n_cols < (size_t) params->n) {
- const size_t n_cols_second = hex_smin((size_t) params->n - n_chunk_n_cols, n_chunk_n_cols);
- const dma_addr_t second_weight_chunk = weight_group + n_chunk_n_cols * weight_row_bytes;
- dma_queue_push(weight_dma, dma_make_data(vtcm_scratch1, second_weight_chunk),
- fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_second);
+ fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_first);
}
for (size_t nc = 0; nc < (size_t) params->n; nc += n_chunk_n_cols) {
const size_t n_cols = hex_smin((size_t) params->n - nc, n_chunk_n_cols);
const size_t n_col_tiles = hmx_ceil_div((int) n_cols, HTP_MM_HMX_TILE_N_COLS);
- {
- void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
-
- const size_t n_cols_tiled = hex_align_up(n_cols, HTP_MM_HMX_TILE_N_COLS);
+ void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ if (nc > 0) {
+ dma_queue_pop(weight_dma);
+ }
- hmx_interleave_rows_to_tiles(vtcm_weight, (const __fp16 *) curr_raw, (uint32_t) n_cols, params->k, params->k, 0, (uint32_t) n_cols_tiled);
+ const size_t n_cols_tiled = hex_align_up(n_cols, HTP_MM_HMX_TILE_N_COLS);
+ hmx_interleave_rows_to_tiles(vtcm_weight, (const __fp16 *) curr_raw, (uint32_t) n_cols, params->k, params->k, 0, (uint32_t) n_cols_tiled);
- const size_t nc_next = nc + n_chunk_n_cols * 2;
- if (nc_next < (size_t) params->n) {
+ // Reuse the interleaved weight for every q_head in this GQA group.
+ // Push next weight chunk right before the last head so earlier heads can
+ // sync-DMA their outputs on an empty queue, and the last head overlaps with next weight.
+ const size_t nc_next = nc + n_chunk_n_cols;
+ for (int g = 0; g < group_size; ++g) {
+ if (g == group_size - 1 && nc_next < (size_t) params->n) {
const size_t n_cols_next = hex_smin((size_t) params->n - nc_next, n_chunk_n_cols);
- const dma_addr_t next_weight_chunk = weight_group + nc_next * weight_row_bytes;
-
- dma_queue_push(weight_dma, dma_make_data(curr_raw, next_weight_chunk),
- fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_next);
+ void * next_raw = (curr_raw == vtcm_scratch0) ? vtcm_scratch1 : vtcm_scratch0;
+ dma_queue_push(weight_dma, dma_make_data(next_raw, weight_group + nc_next * weight_row_bytes),
+ fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_next);
}
- }
- // Reuse the interleaved weight for every q_head in this GQA group
- for (int g = 0; g < group_size; ++g) {
- {
- const __fp16 * vtcm_act_g = vtcm_f16_act + (size_t) g * L.act_head_stride;
- hmx_matmul_job_init(&job, vtcm_output, vtcm_act_g, vtcm_weight, vtcm_scales, n_row_tiles, n_col_tiles, params->k / 32);
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job));
- hmx_queue_pop(ctx->hmx_queue);
- }
+ const __fp16 * vtcm_act_g = vtcm_f16_act + (size_t) g * L.act_head_stride;
+ hmx_matmul_task_init(&task, vtcm_output, vtcm_act_g, vtcm_weight, vtcm_scales, n_row_tiles, n_col_tiles, params->k / 32);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_fp16_worker_fn, &task));
+ hmx_queue_pop(ctx->hmx_queue);
- {
- float *output = hmx_mm_dst_batch_ptr(params, b2_base + g, b3) + mr * params->dst_stride + nc;
- const float *bias_chunk = has_bias ? (vtcm_bias + mr * params->bias_stride + nc) : NULL;
- int chunk_dst_cols = params->dst_cols - (int)nc;
- if (chunk_dst_cols > 0) {
- transfer_output_chunk_threaded(ctx, output, bias_chunk, vtcm_output, (int) n_rows, (int) n_cols,
- params->dst_stride, params->bias_stride, chunk_dst_cols, n_hvx);
- }
+ const void * bias_chunk = has_bias ? ((const uint8_t *) vtcm_bias + (mr * params->bias_stride + nc) * params->bias_elem_size) : NULL;
+ const int chunk_dst_cols = params->dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ transfer_output_chunk_threaded(octx, vtcm_res_out, bias_chunk, vtcm_output, (int) n_rows, (int) n_cols,
+ res_out_stride_elems, params->bias_stride, chunk_dst_cols,
+ params->dst_elem_size, params->bias_elem_size);
+ }
+ const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols);
+ const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * params->dst_elem_size : 0;
+ const dma_addr_t out_addr = hmx_mm_dst_batch_addr(params, b2_base + g, b3) + (mr * params->dst_stride + nc) * params->dst_elem_size;
+ dma_queue_push(weight_dma, dma_make_data(out_addr, vtcm_res_out),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ if (g < group_size - 1) {
+ dma_queue_pop(weight_dma);
}
}
}
+ if (params->n > 0) {
+ dma_queue_pop(weight_dma);
+ }
}
}
}
@@ -3435,9 +5509,10 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t
}
static void transfer_activation_chunk_gathered_threaded(
- struct htp_context *ctx,
+ struct htp_ops_context *octx,
__fp16 *dst,
- const float *src,
+ dma_addr_t act_dma_addr,
+ size_t act_elem_size,
int start_row,
int n_rows,
int k_block,
@@ -3447,83 +5522,250 @@ static void transfer_activation_chunk_gathered_threaded(
int ne11,
size_t nb11,
size_t nb12,
- int cne1,
+ int k_valid,
int n_hvx,
- int k_valid) {
- if (n_rows <= 0) return;
- int chunks_per_hvx = hmx_ceil_div(n_rows, n_hvx);
- chunks_per_hvx = hex_align_up(chunks_per_hvx, 2);
+ const struct fastdiv_values * act_hvx_div,
+ float * vtcm_f32_act,
+ size_t vtcm_f32_act_bytes) {
+ if (n_rows <= 0) {
+ return;
+ }
+ const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ uint32_t chunks_per_hvx = (n_hvx <= 1) ? mc_pad
+ : fastdiv(mc_pad + (uint32_t) n_hvx - 1u, act_hvx_div);
+ chunks_per_hvx = hex_align_up(chunks_per_hvx, 2u);
- int actual_hvx = hmx_ceil_div(n_rows, chunks_per_hvx);
+ const int actual_hvx = (int) hmx_ceil_div(mc_pad, chunks_per_hvx);
activation_transfer_gathered_task_state_t state = {
- .dst = dst,
- .src = src,
- .n_tasks = actual_hvx,
- .n_tot_chunks = n_rows,
- .n_chunks_per_task = chunks_per_hvx,
- .k_block = k_block,
- .matrix_rows = matrix_rows,
- .cur_a = cur_a,
- .mapping_stride = mapping_stride,
- .ne11 = ne11,
- .ne11_div = ne11 > 1 ? init_fastdiv_values(ne11) : (struct fastdiv_values){0, 0},
- .nb11 = nb11,
- .nb12 = nb12,
- .start_row = start_row,
- .cne1 = cne1,
- .k_valid = k_valid,
+ .dst = dst,
+ .act_dma_addr = act_dma_addr,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128),
+ .act_elem_size = act_elem_size,
+ .n_rows = (uint32_t) n_rows,
+ .mc_pad = mc_pad,
+ .n_chunks_per_task = chunks_per_hvx,
+ .k_block = (uint32_t) k_block,
+ .matrix_rows = matrix_rows,
+ .cur_a = (uint32_t) cur_a,
+ .mapping_stride = (uint32_t) mapping_stride,
+ .ne11 = (uint32_t) ne11,
+ .ne11_div = ne11 > 1 ? init_fastdiv_values(ne11) : (struct fastdiv_values){0, 0},
+ .nb11 = nb11,
+ .nb12 = nb12,
+ .start_row = (uint32_t) start_row,
+ .k_valid = (uint32_t) k_valid,
};
- work_queue_func_t worker_fn = ne11 == 1 ? transfer_activation_chunk_gathered_worker_flat_fn :
- transfer_activation_chunk_gathered_worker_fn;
-
- work_queue_run(ctx->hvx_queue, worker_fn, &state, actual_hvx);
+ work_queue_run(octx->ctx->hvx_queue, transfer_activation_chunk_gathered_worker_fn, &state, actual_hvx);
}
-static void transfer_output_chunk_scattered_threaded(
- struct htp_context *ctx,
- float *dst,
- const __fp16 *vtcm_src,
- int start_row,
- int n_rows,
- int n_cols,
- const struct mmid_row_mapping *matrix_rows,
- int cur_a,
- int mapping_stride,
- size_t dst_nb1,
- size_t dst_nb2,
- int cne1,
- int n_hvx) {
- if (n_rows <= 0) return;
- int chunks_per_hvx = hmx_ceil_div(n_rows, n_hvx);
- chunks_per_hvx = hex_align_up(chunks_per_hvx, 2);
-
- int actual_hvx = hmx_ceil_div(n_rows, chunks_per_hvx);
-
- output_transfer_scattered_task_state_t state = {
- .vtcm_src = vtcm_src,
- .dst = dst,
- .n_tasks = actual_hvx,
- .n_tot_chunks = n_rows,
- .n_chunks_per_task = chunks_per_hvx,
- .n_cols = n_cols,
- .matrix_rows = matrix_rows,
- .cur_a = cur_a,
- .mapping_stride = mapping_stride,
- .dst_nb1 = dst_nb1,
- .dst_nb2 = dst_nb2,
- .start_row = start_row,
- .cne1 = cne1,
- };
+static __attribute__((noinline)) int hmx_mm_id_2d_int(
+ struct htp_ops_context * octx,
+ 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,
+ int tile_size,
+ int aligned_tile_size,
+ const struct mmid_row_mapping * matrix_rows,
+ int cur_a,
+ int mapping_stride,
+ int m_start,
+ int m_end,
+ int32_t kernel_type) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const int mr_limit = hex_smin(m, m_end);
+ const int m_valid_core = mr_limit - m_start;
+ if (m_valid_core <= 0 || n_weights == 0) {
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+ return 0;
+ }
+
+ const int m_core_padded = hex_align_up(m_valid_core, 64);
+
+ if (k % 32 != 0 || n % 32 != 0 || tile_size <= 0) { return -1; }
+ if ((activation & (act_elem_size - 1)) != 0) { return -1; }
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ if ((dsts[p] & (dst_elem_size - 1)) != 0) { return -1; }
+ }
+
+ size_t row_stride = htp_tensor_get_row_size(weight_type, k);
+ if (row_stride == 0) {
+ return -1;
+ }
+
+ const uint32_t n_groups = ((uint32_t) k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP;
+ const uint32_t n_k_tiles = (uint32_t) k / HTP_MM_HMX_TILE_N_COLS;
+ const uint32_t n_weight_tiles = (uint32_t) k / htp_tensor_get_tile_k(weight_type);
+ const struct fastdiv_values n_groups_div = init_fastdiv_values(n_groups);
+
+ const size_t vtcm_budget = ctx->vtcm_size;
+ size_t m_chunk_n_rows = 0, n_chunk_n_cols = 0, vtcm_used = 0;
+ int act_hvx = 0;
+ if (!htp_mm_int_hmx_solve_2d_params(
+ kernel_type, weight_type, (uint32_t) k, (uint32_t) m_core_padded,
+ (uint32_t) n, (uint32_t) m_core_padded, (uint32_t) m_core_padded,
+ (int) octx->n_hvx, /*pipeline=*/false, /*is_matmul_id=*/true,
+ (uint32_t) aligned_tile_size, /*bias_size=*/0, dst_elem_size, vtcm_budget,
+ &m_chunk_n_rows, &n_chunk_n_cols, &act_hvx, &vtcm_used)) {
+ FARF(ERROR, "hmx-mm-id-2d-int: VTCM too small: m %d k %d n %d budget %zu", m_core_padded, k, n, vtcm_budget);
+ return -1;
+ }
+
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_ex(
+ &L, kernel_type, weight_type, (uint32_t) k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, /*pipeline=*/false,
+ (uint32_t) act_hvx, (uint32_t) aligned_tile_size, 0, 0, dst_elem_size);
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-mm-id-2d-int: VTCM overflow: used %zu budget %zu", L.total_bytes, vtcm_budget);
+ return -1;
+ }
+
+ uint8_t * const base = (uint8_t *) ctx->vtcm_base;
+ void * vtcm_weight = VTCM_LAYOUT_PTR(void, base, L.off_weight[0]);
+ uint8_t * vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
+ float * vtcm_act_scales = VTCM_LAYOUT_PTR(float, base, L.off_act_scales);
+ float * vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
+ void * vtcm_output = VTCM_LAYOUT_PTR(void, base, L.off_dst[0]);
+ void * vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]);
+ uint8_t * vtcm_res_out = VTCM_LAYOUT_PTR(uint8_t, base, L.off_res_out[0]);
+ if (L.lut_bytes > 0) {
+ iq2xxs_lut_copy(base + L.off_lut);
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const struct fastdiv_values act_hvx_div = init_fastdiv_values((uint32_t) act_hvx);
+ const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
+ hmx_matmul_task_t task;
+
+ const bool preissue_p0 = L.can_preissue_weight && n > 0 && n_weights > 0;
+
+ for (size_t mr = (size_t) m_start; mr < (size_t) mr_limit; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin((size_t) mr_limit - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u);
+ const bool overlap_w_next = (n_rows <= 200u);
+
+ if (preissue_p0) {
+ const size_t n_cols0 = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height0 = hmx_ceil_div(n_cols0, 32) * n_weight_tiles;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_weight, weights[0]),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+
+ transfer_activation_chunk_int_gathered_threaded(
+ ctx, vtcm_act, vtcm_act_scales, activation, (uint32_t) act_elem_size,
+ (int) mr, (int) n_rows, k, k_valid, (int) n_groups,
+ matrix_rows, cur_a, mapping_stride, ne11, act_nb1, act_nb2,
+ act_hvx, &act_hvx_div, vtcm_f32_act, L.act_f32_bytes);
- work_queue_run(ctx->hvx_queue, transfer_output_chunk_scattered_worker_fn, &state, actual_hvx);
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ const dma_addr_t weight_p = weights[p];
+ const dma_addr_t dst_p = dsts[p];
+ const bool p_preissued = (p == 0 && preissue_p0);
+
+ if (n > 0 && !p_preissued) {
+ const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height = hmx_ceil_div(n_cols, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight, weight_p),
+ aligned_tile_size, tile_size, tile_size, height);
+ }
+
+ for (int i = 0; i < n_chunk_cnt; ++i) {
+ const size_t nc = (size_t) i * n_chunk_n_cols;
+ const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols);
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+
+ void * curr_raw;
+ if (i == 0 && p_preissued) {
+ curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst;
+ } else {
+ curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ }
+ if (overlap_w_next && i > 0) {
+ for (size_t s = 0; s < n_rows; ++s) {
+ dma_queue_pop(weight_dma);
+ }
+ }
+
+ rescale_int_weight_chunk_to_int8_tiles(
+ octx, vtcm_scratch0, L.weight_bias_offset, L.weight_scales_offset,
+ curr_raw, (int) n_cols, k, (int) n_groups, &n_groups_div,
+ aligned_tile_size, weight_type);
+
+ const size_t nc_next = nc + n_chunk_n_cols;
+ if (overlap_w_next && nc_next < (size_t) n) {
+ const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols);
+ const uint32_t height_next = hmx_ceil_div(n_cols_next, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight, weight_p + nc_next * weight_stride),
+ aligned_tile_size, tile_size, tile_size, height_next);
+ }
+
+ hmx_matmul_task_init_int(&task, vtcm_output, vtcm_act, vtcm_scratch0, L.weight_bias_offset,
+ n_row_tiles, n_col_tiles, n_k_tiles, n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_w8a8_worker_fn, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const float * wt_scales = (const float *) ((const uint8_t *) vtcm_scratch0 + L.weight_scales_offset);
+ transfer_output_chunk_int_threaded(
+ octx, vtcm_res_out, NULL, vtcm_output,
+ vtcm_act_scales, wt_scales, (int) n_rows, (int) n_cols,
+ (int) n_groups, res_out_stride_elems, 0, (int) n_cols,
+ dst_elem_size, sizeof(float));
+
+ if (overlap_w_next) {
+ push_scattered_dst_rows_dma(
+ weight_dma, dst_p + nc * dst_elem_size, vtcm_res_out,
+ (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size,
+ matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2);
+ } else {
+ sync_scattered_dst_rows_dma(
+ weight_dma, dst_p + nc * dst_elem_size, vtcm_res_out,
+ (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size,
+ matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2);
+ if (nc_next < (size_t) n) {
+ const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols);
+ const uint32_t height_next = hmx_ceil_div(n_cols_next, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_weight, weight_p + nc_next * weight_stride),
+ aligned_tile_size, tile_size, tile_size, height_next);
+ }
+ }
+ }
+ if (overlap_w_next && n_chunk_cnt > 0) {
+ for (size_t s = 0; s < n_rows; ++s) {
+ dma_queue_pop(weight_dma);
+ }
+ }
+ }
+ }
+
+ return 0;
}
-static int hmx_mm_id_2d_f32(struct htp_context *ctx,
+static int hmx_mm_id_2d_f32(struct htp_ops_context *octx,
dma_queue *weight_dma,
- float *restrict dst,
- const float *activation,
+ dma_addr_t dst,
+ dma_addr_t activation,
+ size_t act_elem_size,
+ size_t dst_elem_size,
dma_addr_t weight,
int m, int k, int n,
int k_valid,
@@ -3539,16 +5781,32 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx,
int mapping_stride,
int m_start,
int m_end,
- int n_hvx) {
+ int32_t kernel_type) {
+ if (htp_mm_kernel_is_hmx_int(kernel_type)) {
+ const dma_addr_t dsts[1] = { dst };
+ const dma_addr_t weights[1] = { weight };
+ return hmx_mm_id_2d_int(
+ octx, weight_dma, dsts, activation, act_elem_size, dst_elem_size,
+ weights, 1, m, k, n, k_valid, ne11, act_nb1, act_nb2, dst_nb1, dst_nb2,
+ weight_stride, weight_type, tile_size, aligned_tile_size,
+ matrix_rows, cur_a, mapping_stride, m_start, m_end,
+ kernel_type);
+ }
+ struct htp_context * ctx = octx->ctx;
struct htp_thread_trace * tr = &ctx->trace[0];
htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
- const int cne1 = m;
- const int m_core = m_end - m_start;
- const int m_core_padded = hex_align_up(m_core > 0 ? m_core : 1, 32);
+ const int mr_limit = hex_smin(m, m_end);
+ const int m_valid_core = mr_limit - m_start;
+ if (m_valid_core <= 0) {
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+ return 0;
+ }
+
+ const int m_core_padded = hex_align_up(m_valid_core, HTP_MM_HMX_TILE_N_ROWS);
if (k % 32 != 0 || n % 32 != 0) { return -1; }
- if (!hex_is_aligned(dst, VLEN) || !hex_is_aligned(activation, VLEN)) { return -1; }
+ if ((dst & (dst_elem_size - 1)) != 0 || (activation & (act_elem_size - 1)) != 0) { return -1; }
size_t row_stride = htp_tensor_get_row_size(weight_type, k);
if (row_stride == 0) {
@@ -3559,7 +5817,6 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx,
const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(weight_type);
const struct fastdiv_values n_k_tiles_div = init_fastdiv_values(n_k_tiles);
- const size_t vec_dot_size = k * sizeof(__fp16);
const size_t vtcm_budget = ctx->vtcm_size;
size_t vtcm_used = 0;
@@ -3570,65 +5827,63 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx,
const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
const uint32_t dma_width_bytes = is_tiled ? tile_size : row_stride;
- const size_t qweight_row_stride = is_tiled ? (size_t)(n_weight_tiles * aligned_tile_size) / 32 : 0;
- const size_t weight_row_stride = is_tiled ? qweight_row_stride : row_stride;
-
- size_t size_per_n = 0, size_per_m = 0, size_per_mn = 0;
- htp_mm_hmx_get_2d_chunk_costs(weight_type, k, /*pipeline=*/false, aligned_tile_size,
- &size_per_n, &size_per_m, &size_per_mn);
-
- const size_t overhead = htp_mm_hmx_get_2d_overhead(weight_type, /*pipeline=*/false, /*is_matmul_id=*/true);
size_t m_chunk_n_rows = 0, n_chunk_n_cols = 0;
- if (htp_mm_hmx_compute_chunks(vtcm_budget, overhead, size_per_n, size_per_m, size_per_mn,
- m_core_padded, n,
- /*m_block_cost=*/(size_t) n * HTP_MM_HMX_COST_W_DEQUANT,
- /*n_block_cost=*/(size_t) m_core_padded * HTP_MM_HMX_COST_A_CONVERT, &m_chunk_n_rows, &n_chunk_n_cols, &vtcm_used)) {
+ int act_hvx = 0;
+ if (!htp_mm_hmx_solve_2d_params(
+ weight_type, (uint32_t) k, (uint32_t) m_core_padded,
+ (uint32_t) n, (uint32_t) m_core_padded, (uint32_t) m_core_padded,
+ (int) octx->n_hvx, /*pipeline=*/false, /*is_matmul_id=*/true,
+ (uint32_t) aligned_tile_size, /*bias_size=*/0, dst_elem_size, vtcm_budget,
+ &m_chunk_n_rows, &n_chunk_n_cols, &act_hvx, &vtcm_used)) {
FARF(ERROR, "hmx-mm-id-2d: VTCM too small : m %d k %d n %d budget %zu", m_core_padded, k, n, vtcm_budget);
return -1;
}
- const size_t weight_area_size = hex_align_up(n_chunk_n_cols * weight_row_stride, HTP_MM_HMX_TILE_SIZE);
- const size_t act_area_size = hex_align_up(m_chunk_n_rows * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
- const size_t output_area_size = hex_align_up(m_chunk_n_rows * n_chunk_n_cols * sizeof(__fp16), HTP_MM_HMX_TILE_SIZE);
-
- size_t scratch0_size = hex_align_up(n_chunk_n_cols * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
-
- uint8_t *vtcm_ptr = (uint8_t *) ctx->vtcm_base;
- __fp16 *vtcm_weight = weight_area_size ? (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, weight_area_size) : NULL;
- __fp16 *vtcm_f16_act = (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, act_area_size);
- __fp16 *vtcm_output = (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, output_area_size);
- void *vtcm_scratch0 = vtcm_seq_alloc(&vtcm_ptr, scratch0_size);
- __fp16 *vtcm_scales = (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, 256);
- const size_t lut_size = htp_mm_hmx_lut_bytes(weight_type);
- uint8_t *vtcm_lut = lut_size ? (uint8_t *) vtcm_seq_alloc(&vtcm_ptr, lut_size) : NULL;
-
- vtcm_used = vtcm_ptr - (uint8_t *) ctx->vtcm_base;
- if (vtcm_used > vtcm_budget) {
- FARF(ERROR, "hmx-mm-id-2d: VTCM overflow: used %zu budget %zu", vtcm_used, vtcm_budget);
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_ex(
+ &L, HTP_MM_KERNEL_HMX_2D, weight_type, (uint32_t) k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, /*pipeline=*/false,
+ (uint32_t) act_hvx, (uint32_t) aligned_tile_size, 0, 0, dst_elem_size);
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-mm-id-2d: VTCM overflow: used %zu budget %zu", L.total_bytes, vtcm_budget);
return -1;
}
+ uint8_t * const base = (uint8_t *) ctx->vtcm_base;
+ __fp16 *vtcm_weight = VTCM_LAYOUT_PTR(__fp16, base, L.off_weight[0]);
+ __fp16 *vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act);
+ float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32);
+ __fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]);
+ void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]);
+ uint8_t *vtcm_res_out = VTCM_LAYOUT_PTR(uint8_t, base, L.off_res_out[0]);
+ __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales);
+ uint8_t *vtcm_lut = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_lut, L.lut_bytes > 0);
+
hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00));
- if (lut_size) {
+ if (L.lut_bytes > 0) {
iq2xxs_lut_copy(vtcm_lut);
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
- hmx_matmul_job_t job;
+ const struct fastdiv_values act_hvx_div = init_fastdiv_values((uint32_t) act_hvx);
+ hmx_matmul_task_t task;
void *vtcm_raw_bufs[2] = { vtcm_weight, dequant_worker_fn ? vtcm_weight : vtcm_scratch0 };
void *vtcm_weight_bufs[2] = { dequant_worker_fn ? vtcm_scratch0 : vtcm_weight, vtcm_scratch0 };
const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols);
+ const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128);
+ const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size);
- for (size_t mr = (size_t) m_start; mr < (size_t) m_end; mr += m_chunk_n_rows) {
- const size_t n_rows = hex_smin((size_t) m_end - mr, m_chunk_n_rows);
- const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ for (size_t mr = (size_t) m_start; mr < (size_t) mr_limit; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin((size_t) mr_limit - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ const bool overlap_w_next = (n_rows <= 200u);
transfer_activation_chunk_gathered_threaded(
- ctx, vtcm_f16_act, activation, (int) mr, (int) n_rows, k,
- matrix_rows, cur_a, mapping_stride, ne11, act_nb1, act_nb2, cne1, n_hvx, k_valid);
+ octx, vtcm_f16_act, activation, act_elem_size, (int) mr, (int) n_rows, k,
+ matrix_rows, cur_a, mapping_stride, ne11, act_nb1, act_nb2, k_valid,
+ act_hvx, &act_hvx_div, vtcm_f32_act, L.act_f32_bytes);
- // A0: Pre-fetch the first weight chunk (nc = 0)
if (n > 0) {
const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols);
const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols;
@@ -3641,34 +5896,58 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx,
const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols);
const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
- // A: Wait for weight DMA
void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ if (overlap_w_next && i > 0) {
+ for (size_t s = 0; s < n_rows; ++s) {
+ dma_queue_pop(weight_dma);
+ }
+ }
- // B: Weight Dequantize (Threaded)
dequantize_tiled_weight_chunk_to_fp16_tiles(
- ctx, vtcm_weight_bufs[i % 2], curr_raw,
+ octx, vtcm_weight_bufs[i % 2], curr_raw,
n_cols, k, row_stride, weight_type,
- n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx
+ n_k_tiles, n_k_tiles_div, dequant_worker_fn
);
- // Start weight DMA for the next chunk early
const size_t nc_next = nc + n_chunk_n_cols;
- if (nc_next < (size_t) n) {
+ if (overlap_w_next && nc_next < (size_t) n) {
const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols);
const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next;
dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride),
dma_dst_stride, dma_src_stride, dma_width_bytes, height_next);
}
- // C: HMX Compute (Queue-based)
- hmx_matmul_job_init(&job, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS);
- hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job));
+ hmx_matmul_task_init(&task, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_fp16_worker_fn, &task));
hmx_queue_pop(ctx->hmx_queue);
- // D: Output Store
- transfer_output_chunk_scattered_threaded(
- ctx, dst + nc, vtcm_output, (int) mr, (int) n_rows, (int) n_cols,
- matrix_rows, cur_a, mapping_stride, dst_nb1, dst_nb2, cne1, n_hvx);
+ transfer_output_chunk_threaded(
+ octx, vtcm_res_out, NULL, vtcm_output,
+ n_rows, n_cols, res_out_stride_elems, 0, (int) n_cols,
+ dst_elem_size, sizeof(float));
+
+ if (overlap_w_next) {
+ push_scattered_dst_rows_dma(
+ weight_dma, dst + nc * dst_elem_size, vtcm_res_out,
+ (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size,
+ matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2);
+ } else {
+ sync_scattered_dst_rows_dma(
+ weight_dma, dst + nc * dst_elem_size, vtcm_res_out,
+ (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size,
+ matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2);
+ if (nc_next < (size_t) n) {
+ const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols);
+ const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_next);
+ }
+ }
+ }
+ if (overlap_w_next && n_chunk_cnt > 0) {
+ for (size_t s = 0; s < n_rows; ++s) {
+ dma_queue_pop(weight_dma);
+ }
}
}
@@ -3683,18 +5962,15 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
int k = (int) src0->ne[0];
int n = (int) src0->ne[1];
const int m_total = (int) act->ne[1];
- const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const uint32_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
const int act_stride = (int) (act->nb[1] / act_elem_size);
int m_start = 0;
int m_rows = m_total;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- if ((dst->ne[2] <= 1 || (dst->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0) &&
- (dst->ne[3] <= 1 || (dst->nb[3] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0)) {
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), dst->ne[0] * sizeof(float), &rows_per_chunk);
- }
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m_total, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m_total, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
m_start = (int) range.start;
m_rows = (int) range.count;
}
@@ -3703,32 +5979,31 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
return HTP_STATUS_OK;
}
- dma_addr_t src2_addr = 0;
- size_t src2_bytes = 0;
- uint32_t src2_stride = 0;
- size_t src2_nb2 = 0;
- size_t src2_nb3 = 0;
- if (src2) {
- src2_stride = (src2->ne[1] == 1) ? 0 : (uint32_t) (src2->nb[1] / sizeof(float));
- src2_addr = src2->data + (size_t) m_start * src2_stride * sizeof(float);
- const size_t slice_bytes = (src2->ne[1] == 1) ? src2->nb[1] : (size_t) m_rows * src2->nb[1];
- src2_bytes = MIN((size_t) kparams->vtcm_bias_size, slice_bytes);
- src2_nb2 = (src2->ne[2] == 1) ? 0 : src2->nb[2];
- src2_nb3 = (src2->ne[3] == 1) ? 0 : src2->nb[3];
+ dma_addr_t bias_addr = 0;
+ size_t bias_bytes = 0;
+ uint32_t bias_stride = 0;
+ size_t bias_nb2 = 0;
+ size_t bias_nb3 = 0;
+ if (bias) {
+ bias_stride = (bias->ne[1] == 1) ? 0 : (uint32_t) (bias->nb[1] / bias_elem_size);
+ bias_addr = bias->data + (size_t) m_start * bias_stride * bias_elem_size;
+ const size_t slice_bytes = (bias->ne[1] == 1) ? bias->nb[1] : (size_t) m_rows * bias->nb[1];
+ bias_bytes = MIN((size_t) kparams->vtcm_bias_size, slice_bytes);
+ bias_nb2 = (bias->ne[2] == 1) ? 0 : bias->nb[2];
+ bias_nb3 = (bias->ne[3] == 1) ? 0 : bias->nb[3];
}
- const int dst_stride = (int)(dst->nb[1] / sizeof(float));
- float * dst_ptr = (float *) dst->data + m_start * dst_stride;
+ const int dst_stride = (int) (dst->nb[1] / dst_elem_size);
+ const dma_addr_t dst_addr = dst->data + (size_t) m_start * dst_stride * dst_elem_size;
// byte offset, act_stride is in activation elements (F16 or F32)
const dma_addr_t act_addr = act->data + (size_t) m_start * act_stride * act_elem_size;
int ret = -1;
- const int n_hvx = kparams->n_hvx;
- if (kparams->kernel_type == HTP_MM_KERNEL_HMX_BATCHED) {
+ if (htp_mm_kernel_is_hmx_batched(kparams->kernel_type)) {
hmx_mm_batched_params_t batch_params = {
- .dst = dst_ptr,
- .bias_addr = src2_addr,
- .bias_bytes = src2_bytes,
+ .dst_dma_addr = dst_addr,
+ .bias_addr = bias_addr,
+ .bias_bytes = bias_bytes,
.act_dma_addr = act_addr,
.weight = src0->data,
.weight_dma = octx->ctx->dma[0],
@@ -3737,11 +6012,13 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
.n = n,
.act_stride = act_stride,
.act_elem_size = act_elem_size,
+ .dst_elem_size = dst_elem_size,
+ .bias_elem_size = bias_elem_size,
.weight_stride = (int) src0->nb[1],
.weight_type = (int) src0->type,
.dst_stride = dst_stride,
.dst_cols = (int) dst->ne[0],
- .bias_stride = src2_stride,
+ .bias_stride = bias_stride,
.tile_size = kparams->tile_size,
.aligned_tile_size = kparams->aligned_tile_size,
.ne02 = ne02,
@@ -3754,31 +6031,37 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
.act_nb3 = act->nb[3],
.dst_nb2 = dst->nb[2],
.dst_nb3 = dst->nb[3],
- .bias_nb2 = src2_nb2,
- .bias_nb3 = src2_nb3,
+ .bias_nb2 = bias_nb2,
+ .bias_nb3 = bias_nb3,
.r2 = (ne02 > 0) ? (ne12 / ne02) : 1,
.r3 = (ne03 > 0) ? (ne13 / ne03) : 1,
.div_r2 = kparams->div_r2,
.div_r3 = kparams->div_r3,
+ .kernel_type = kparams->kernel_type,
+ .hmx_n_groups = kparams->hmx_n_groups,
+ .div_hmx_n_groups = kparams->div_hmx_n_groups,
+ .div_n_k_tiles = kparams->div_n_k_tiles,
};
- ret = hmx_mm_batched(octx->ctx, &batch_params,
+ ret = hmx_mm_batched(octx, &batch_params,
kparams->m_chunk, kparams->n_chunk,
- kparams->pipeline, n_hvx,
+ kparams->pipeline,
kparams->n_act_hvx,
&kparams->div_n_act_hvx,
&kparams->div_ne00_padded,
kparams->vtcm_size);
} else {
ret = hmx_mm_2d_f32(
- octx->ctx, octx->ctx->dma[0], dst_ptr, src2_addr, src2_bytes,
+ octx, octx->ctx->dma[0], dst_addr, bias_addr, bias_bytes,
act_addr, src0->data,
m_rows, k, n, act_stride, act_elem_size, (int) src0->nb[1], (int) src0->type, (int) act->ne[0],
- dst_stride, src2_stride, (int)dst->ne[0],
- kparams->m_chunk, kparams->n_chunk, kparams->pipeline, n_hvx,
+ dst_stride, bias_stride, (int)dst->ne[0], dst_elem_size, bias_elem_size,
+ kparams->m_chunk, kparams->n_chunk, kparams->pipeline,
kparams->n_act_hvx,
&kparams->div_n_act_hvx,
&kparams->div_ne00_padded,
- kparams->tile_size, kparams->aligned_tile_size, kparams->vtcm_size
+ kparams->tile_size, kparams->aligned_tile_size, kparams->vtcm_size,
+ kparams->kernel_type, kparams->hmx_n_groups,
+ &kparams->div_hmx_n_groups, &kparams->div_n_k_tiles
);
}
@@ -3816,13 +6099,12 @@ static int hmx_mm_op_matmul_id(
const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows;
htp_matmul_tensors_preamble;
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- const int n_ids = octx->src[2]->ne[0];
const int n_as = ne02;
- const bool mdev_split = (octx->ctx->mdev.count > 1) && htp_tensor_can_row_partition(dst, sizeof(float));
- if (octx->ctx->mdev.count > 1 && !mdev_split && octx->ctx->mdev.idx > 0) {
- return HTP_STATUS_OK;
- }
+ const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+
+ const bool mdev_split = (octx->ctx->mdev.count > 1);
uint32_t n_active = 0;
if (mdev_split) {
for (uint32_t a = 0; a < (uint32_t) n_as; ++a) {
@@ -3850,10 +6132,11 @@ static int hmx_mm_op_matmul_id(
m_start = (int) range.start;
m_end = (int) (range.start + range.count);
}
- if (m_start >= m_end) continue;
+ if (m_start >= m_end || m_start >= cne1) continue;
- int ret = hmx_mm_id_2d_f32(octx->ctx, octx->ctx->dma[0], (float*) dst->data, (float*) act->data,
- src0->data + cur_a * nb02,
+ int ret = hmx_mm_id_2d_f32(octx, octx->ctx->dma[0], dst->data, act->data,
+ act_elem_size, dst_elem_size,
+ src0->data + (dma_addr_t) cur_a * nb02,
cne1, ne00, ne01,
ne10,
ne11,
@@ -3862,7 +6145,8 @@ static int hmx_mm_op_matmul_id(
(int) src0->nb[1], (int) src0->type,
kparams->tile_size, kparams->aligned_tile_size,
matrix_rows, cur_a, mmctx->mapping_stride,
- m_start, m_end, (int) octx->n_hvx);
+ m_start, m_end,
+ kparams->kernel_type);
if (ret != 0) {
FARF(ERROR, "HMX matmul failed for expert %u, error %d\n", cur_a, ret);
return HTP_STATUS_NO_SUPPORT;
@@ -3885,7 +6169,6 @@ static int hvx_mm_matmul_id(
htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- const struct htp_tensor * restrict ids = octx->src[2];
const size_t src0_row_size = nb01;
const uint32_t qk = HTP_MM_ACT_BLOCK_K;
@@ -3909,11 +6192,13 @@ static int hvx_mm_matmul_id(
n_quant_tasks = MIN(act_nrows, octx->n_hvx);
quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
}
- size_t act_row_size = htp_mm_tiled_act_row_size(src0->type, ne10);
+ const size_t act_row_size = kparams->act_row_size;
+ size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_row_size = (size_t) ne0 * sizeof(float);
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, ne10, act_nrows, octx->n_hvx,
- 0, src0_row_size, act_row_size, 0, kparams->n_prefetch, true, false);
+ dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, true, false);
const size_t vtcm_size = L.total_bytes;
@@ -3941,7 +6226,7 @@ static int hvx_mm_matmul_id(
mmctx->vtcm_src0_stride = src0_row_size_padded;
mmctx->vtcm_act_stride = act_row_size;
- mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10);
+ mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10, act_elem_size);
mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div);
mmctx->vtcm_act_size_per_hvx = L.act_bytes;
@@ -3975,14 +6260,9 @@ static int hmx_mm_op_matmul_id_nx(
const struct htp_tensor * restrict act = octx->src[n_weights];
const int n_as = src0->ne[2];
- bool mdev_split = (octx->ctx->mdev.count > 1);
- for (uint32_t p = 0; p < n_weights && mdev_split; ++p) {
- const struct htp_tensor * restrict dst = octx->dsts[p];
- mdev_split = htp_tensor_can_row_partition(dst, sizeof(float));
- }
- if (octx->ctx->mdev.count > 1 && !mdev_split && octx->ctx->mdev.idx > 0) {
- return HTP_STATUS_OK;
- }
+ const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+
+ const bool mdev_split = (octx->ctx->mdev.count > 1);
uint32_t n_active = 0;
if (mdev_split) {
for (uint32_t a = 0; a < (uint32_t) n_as; ++a) {
@@ -4010,15 +6290,53 @@ static int hmx_mm_op_matmul_id_nx(
m_start = (int) range.start;
m_end = (int) (range.start + range.count);
}
- if (m_start >= m_end) continue;
+ if (m_start >= m_end || m_start >= cne1) continue;
+
+ if (htp_mm_kernel_is_hmx_int(kparams->kernel_type)) {
+ const struct htp_tensor * restrict dst0 = octx->dsts[0];
+ bool same_shape = true;
+ dma_addr_t dst_addrs[HTP_OP_MAX_OUTPUTS];
+ dma_addr_t weight_addrs[HTP_OP_MAX_OUTPUTS];
+ for (uint32_t p = 0; p < n_weights && same_shape; ++p) {
+ const struct htp_tensor * restrict sw = octx->src[p];
+ const struct htp_tensor * restrict d = octx->dsts[p];
+ if (sw->ne[0] != src0->ne[0] || sw->ne[1] != src0->ne[1] ||
+ sw->nb[1] != src0->nb[1] || sw->type != src0->type ||
+ d->type != dst0->type || d->nb[1] != dst0->nb[1] || d->nb[2] != dst0->nb[2]) {
+ same_shape = false;
+ break;
+ }
+ dst_addrs[p] = d->data;
+ weight_addrs[p] = sw->data + (dma_addr_t) cur_a * sw->nb[2];
+ }
+ if (same_shape) {
+ const size_t dst0_elem_size = (dst0->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ int ret = hmx_mm_id_2d_int(
+ octx, octx->ctx->dma[0], dst_addrs, act->data,
+ act_elem_size, dst0_elem_size, weight_addrs, n_weights,
+ cne1, src0->ne[0], src0->ne[1], act->ne[0], act->ne[1],
+ act->nb[1], act->nb[2], dst0->nb[1], dst0->nb[2],
+ (int) src0->nb[1], (int) src0->type,
+ kparams->tile_size, kparams->aligned_tile_size,
+ matrix_rows, cur_a, mmctx->mapping_stride,
+ m_start, m_end, kparams->kernel_type);
+ if (ret != 0) {
+ FARF(ERROR, "HMX matmul ID NX failed for expert %u, error %d\n", cur_a, ret);
+ return HTP_STATUS_NO_SUPPORT;
+ }
+ continue;
+ }
+ }
for (uint32_t p = 0; p < n_weights; ++p) {
const struct htp_tensor * restrict src_w = octx->src[p];
const struct htp_tensor * restrict dst = octx->dsts[p];
if (!src_w || !dst) continue;
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
- int ret = hmx_mm_id_2d_f32(octx->ctx, octx->ctx->dma[0], (float*) dst->data, (float*) act->data,
- src_w->data + cur_a * src_w->nb[2],
+ int ret = hmx_mm_id_2d_f32(octx, octx->ctx->dma[0], dst->data, act->data,
+ act_elem_size, dst_elem_size,
+ src_w->data + (dma_addr_t) cur_a * src_w->nb[2],
cne1, src_w->ne[0], src_w->ne[1],
act->ne[0],
act->ne[1],
@@ -4027,7 +6345,8 @@ static int hmx_mm_op_matmul_id_nx(
(int) src_w->nb[1], (int) src_w->type,
kparams->tile_size, kparams->aligned_tile_size,
matrix_rows, cur_a, mmctx->mapping_stride,
- m_start, m_end, (int) octx->n_hvx);
+ m_start, m_end,
+ kparams->kernel_type);
if (ret != 0) {
FARF(ERROR, "HMX matmul ID NX failed for expert %u weight %u, error %d\n", cur_a, p, ret);
return HTP_STATUS_NO_SUPPORT;
@@ -4043,7 +6362,6 @@ static int hvx_mm_matmul_id_nx(
struct htp_mm_context * mmctx,
work_queue_func_t hvx_mmid_task_func
) {
- const uint32_t src0_row_size_padded = mmctx->src0_row_size_padded;
const uint32_t act_nrows = mmctx->act_nrows;
struct htp_thread_trace * tr = &octx->ctx->trace[0];
@@ -4053,7 +6371,6 @@ static int hvx_mm_matmul_id_nx(
const uint32_t n_weights = kparams->n_weights;
const struct htp_tensor * restrict src0 = octx->src[0];
const struct htp_tensor * restrict act = octx->src[n_weights];
- const struct htp_tensor * restrict ids = octx->src[n_weights + 1];
const size_t src0_row_size = src0->nb[1];
const uint32_t qk = HTP_MM_ACT_BLOCK_K;
@@ -4077,11 +6394,19 @@ static int hvx_mm_matmul_id_nx(
n_quant_tasks = MIN(act_nrows, octx->n_hvx);
quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
}
- size_t act_row_size = htp_mm_tiled_act_row_size(src0->type, act->ne[0]);
+ const size_t act_row_size = kparams->act_row_size;
+ size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ size_t max_dst_row_size = 0;
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ if (octx->dsts[p]) {
+ const size_t sz = (size_t) octx->dsts[p]->ne[0] * sizeof(float);
+ if (sz > max_dst_row_size) max_dst_row_size = sz;
+ }
+ }
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, act->ne[0], act_nrows, octx->n_hvx,
- 0, src0_row_size, act_row_size, 0, kparams->n_prefetch, true, false);
+ max_dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, true, false);
const size_t vtcm_size = L.total_bytes;
@@ -4100,7 +6425,7 @@ static int hvx_mm_matmul_id_nx(
mmctx->vtcm_src0_stride = 0;
mmctx->vtcm_act_stride = act_row_size;
- mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0]);
+ mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0], act_elem_size);
mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div);
mmctx->vtcm_act_size_per_hvx = L.act_bytes;
@@ -4128,19 +6453,18 @@ static int hvx_mm_matmul_id_nx(
}
static __attribute__((noinline)) uint32_t scan_expert_ids_n(
- const struct htp_tensor * ids,
+ const int32_t * ids_data,
+ uint32_t ids_ne1,
const uint32_t n_ids,
uint32_t n_as,
uint32_t * counts,
struct mmid_row_mapping * matrix_rows,
uint32_t mapping_stride
) {
- const size_t ids_nb1 = ids->nb[1];
- const uint8_t * ids_data = (const uint8_t *) ids->data;
uint32_t n_skipped = 0;
- for (uint32_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) {
- const int32_t * row_ptr = (const int32_t *) (ids_data + iid1 * ids_nb1);
+ for (uint32_t iid1 = 0; iid1 < ids_ne1; ++iid1) {
+ const int32_t * row_ptr = ids_data + (size_t) iid1 * n_ids;
for (uint32_t id = 0; id < n_ids; ++id) {
const int32_t i02 = row_ptr[id];
if (i02 < 0) {
@@ -4159,54 +6483,26 @@ static __attribute__((noinline)) uint32_t scan_expert_ids_n(
}
static __attribute__((noinline)) uint32_t scan_expert_ids(
- const struct htp_tensor * ids,
+ const int32_t * ids_data,
+ uint32_t ids_ne1,
uint32_t n_ids,
uint32_t n_as,
uint32_t * counts,
struct mmid_row_mapping * matrix_rows,
uint32_t mapping_stride
) {
- const size_t ids_nb0 = ids->nb[0];
-
- if (ids_nb0 == 4) {
- switch (n_ids) {
- case 8: return scan_expert_ids_n(ids, 8, n_as, counts, matrix_rows, mapping_stride);
- case 4: return scan_expert_ids_n(ids, 4, n_as, counts, matrix_rows, mapping_stride);
- case 2: return scan_expert_ids_n(ids, 2, n_as, counts, matrix_rows, mapping_stride);
- default: return scan_expert_ids_n(ids, n_ids, n_as, counts, matrix_rows, mapping_stride);
- }
- } else {
- // Strided fallback
- const size_t ids_nb1 = ids->nb[1];
- const uint8_t * ids_data = (const uint8_t *) ids->data;
- uint32_t n_skipped = 0;
- for (uint32_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) {
- const int32_t * row_ptr = (const int32_t *) (ids_data + iid1 * ids_nb1);
- for (uint32_t id = 0; id < n_ids; ++id) {
- const int32_t i02 = *(const int32_t *) ((const uint8_t *) row_ptr + id * ids_nb0);
- if (i02 < 0) {
- n_skipped++;
- continue;
- }
- assert(i02 >= 0 && i02 < (int32_t) n_as);
-
- if (matrix_rows) {
- matrix_rows[i02 * mapping_stride + counts[i02]] = (struct mmid_row_mapping) { id, iid1 };
- }
- counts[i02] += 1;
- }
- }
- return n_skipped;
+ switch (n_ids) {
+ case 8: return scan_expert_ids_n(ids_data, ids_ne1, 8, n_as, counts, matrix_rows, mapping_stride);
+ case 4: return scan_expert_ids_n(ids_data, ids_ne1, 4, n_as, counts, matrix_rows, mapping_stride);
+ case 2: return scan_expert_ids_n(ids_data, ids_ne1, 2, n_as, counts, matrix_rows, mapping_stride);
+ default: return scan_expert_ids_n(ids_data, ids_ne1, n_ids, n_as, counts, matrix_rows, mapping_stride);
}
}
-static __attribute__((noinline)) uint32_t count_skipped_ids_single(const struct htp_tensor * ids, uint32_t n_ids) {
- const uint8_t * ids_data = (const uint8_t *) ids->data;
- const size_t ids_nb0 = ids->nb[0];
+static __attribute__((noinline)) uint32_t count_skipped_ids_single(const int32_t * ids_data, uint32_t n_ids) {
uint32_t n_skipped = 0;
for (uint32_t id = 0; id < n_ids; ++id) {
- const int32_t i02 = *(const int32_t *) (ids_data + id * ids_nb0);
- if (i02 < 0) {
+ if (ids_data[id] < 0) {
n_skipped++;
}
}
@@ -4216,7 +6512,8 @@ static __attribute__((noinline)) uint32_t count_skipped_ids_single(const struct
// Zero rows for skipped slots (ids < 0). Matmuls only write rows that an expert owns.
static void zero_skipped_dst_rows(
struct htp_ops_context * octx,
- const struct htp_tensor * ids,
+ const int32_t * ids_data,
+ uint32_t ids_ne1,
uint32_t n_ids,
const struct htp_tensor * dst
) {
@@ -4225,10 +6522,8 @@ static void zero_skipped_dst_rows(
uint32_t col_count = dst->ne[0];
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_can_row_partition(dst, elem_size);
- const uint32_t chunk_elems = (dst->type == HTP_TYPE_F16) ? 64 : 32;
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- dst->ne[0], can_split ? chunk_elems : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ dst->ne[0], 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
col_start = range.start;
col_count = range.count;
}
@@ -4237,51 +6532,104 @@ static void zero_skipped_dst_rows(
return;
}
- const uint8_t * ids_data = (const uint8_t *) ids->data;
- const size_t ids_nb0 = ids->nb[0];
- const size_t ids_nb1 = ids->nb[1];
const size_t dst_nb1 = dst->nb[1];
const size_t dst_nb2 = dst->nb[2];
- const uint32_t col_offset_bytes = col_start * elem_size;
-
- for (uint32_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) {
- const uint8_t * ids_row = ids_data + iid1 * ids_nb1;
- uint8_t * dst_row_group = (uint8_t *) dst->data + iid1 * dst_nb2 + col_offset_bytes;
+ const size_t col_offset_bytes = (size_t) col_start * elem_size;
+ const size_t row_bytes = (size_t) col_count * elem_size;
+
+ // Zero one row in VTCM and copy to skipped dst rows via bypass DMA.
+ dma_queue * const dma_q = octx->ctx->dma[0];
+ uint8_t * const vtcm_zero = octx->ctx->vtcm_base;
+ const size_t chunk_bytes = MIN(row_bytes, octx->ctx->vtcm_size);
+ hvx_splat_u8_a(vtcm_zero, 0, (uint32_t) hex_round_up(chunk_bytes, 128));
+
+ uint32_t pending = 0;
+ for (uint32_t iid1 = 0; iid1 < ids_ne1; ++iid1) {
+ const int32_t * ids_row = ids_data + (size_t) iid1 * n_ids;
+ const dma_addr_t dst_row_group = dst->data + (dma_addr_t) iid1 * dst_nb2 + col_offset_bytes;
for (uint32_t id = 0; id < n_ids; ++id) {
- const int32_t i02 = *(const int32_t *) (ids_row + id * ids_nb0);
- if (i02 < 0) {
- hvx_splat_u(dst_row_group + id * dst_nb1, Q6_V_vzero(), col_count, elem_size);
+ if (ids_row[id] < 0) {
+ const dma_addr_t row_base = dst_row_group + (dma_addr_t) id * dst_nb1;
+ for (size_t off = 0; off < row_bytes; off += chunk_bytes) {
+ const size_t n = MIN(chunk_bytes, row_bytes - off);
+ dma_queue_push(dma_q, dma_make_data(row_base + off, vtcm_zero), n, n, n, 1);
+ if (++pending >= 128) {
+ dma_queue_flush(dma_q);
+ pending = 0;
+ }
+ }
}
}
}
+ if (pending > 0) {
+ dma_queue_flush(dma_q);
+ }
}
static int htp_mmid_prepare_mapping(
struct htp_ops_context * octx,
const struct htp_tensor * ids,
+ uint8_t * ids_stack,
+ size_t ids_stack_size,
uint32_t n_ids,
uint32_t n_as,
uint32_t act_nrows,
- uint8_t ** out_mapping_buf,
+ const int32_t ** out_ids_data,
+ void ** out_ids_alloc,
+ void ** out_map_alloc,
uint32_t ** out_matrix_row_counts,
struct mmid_row_mapping ** out_matrix_rows,
uint32_t * out_mapping_stride,
uint32_t * out_n_skipped
) {
- uint8_t * mapping_buf = octx->ctx->ddr_spad_base;
+ const size_t ids_bytes = hex_round_up(htp_tensor_nbytes(ids), 128);
+ uint8_t * ids_buf = NULL;
+ void * ids_alloc = NULL;
+ uint8_t * spad_base = (uint8_t *) octx->ctx->ddr_spad_base;
+ size_t spad_avail = octx->ctx->ddr_spad_size;
+
+ if (ids_bytes <= ids_stack_size) {
+ ids_buf = ids_stack;
+ } else if (ids_bytes <= spad_avail) {
+ ids_buf = spad_base;
+ spad_base += ids_bytes;
+ spad_avail -= ids_bytes;
+ } else {
+ ids_alloc = memalign(128, ids_bytes);
+ if (!ids_alloc) {
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ ids_buf = (uint8_t *) ids_alloc;
+ }
+
+ if (htp_tensor_read(&octx->ctx->main_th, ids_buf, ids_bytes, ids) == 0) {
+ free(ids_alloc);
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+
+ const int32_t * ids_data = (const int32_t *) ids_buf;
+
+ void * map_alloc = NULL;
+ uint8_t * mapping_buf = spad_base;
uint32_t mapping_stride = 1;
- uint32_t * matrix_row_counts = (uint32_t *) mapping_buf;
+ uint32_t * matrix_row_counts = NULL;
struct mmid_row_mapping * matrix_rows = NULL;
uint32_t n_skipped = 0;
if (act_nrows > 1) {
const size_t matrix_row_counts_size = n_as * sizeof(uint32_t);
- assert(octx->ctx->ddr_spad_size >= matrix_row_counts_size);
-
- hex_l2fetch_block((const void *) ids->data, ids->ne[1] * ids->nb[1]);
+ if (matrix_row_counts_size > spad_avail) {
+ map_alloc = memalign(128, matrix_row_counts_size);
+ if (!map_alloc) {
+ free(ids_alloc);
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ mapping_buf = (uint8_t *) map_alloc;
+ }
+ matrix_row_counts = (uint32_t *) mapping_buf;
hvx_splat_u(matrix_row_counts, Q6_V_vzero(), n_as, sizeof(uint32_t));
- n_skipped = scan_expert_ids(ids, n_ids, n_as, matrix_row_counts, NULL, 0);
+ n_skipped = scan_expert_ids(ids_data, ids->ne[1], n_ids, n_as, matrix_row_counts, NULL, 0);
uint32_t max_count = hvx_reduce_max_i32((const uint8_t *) matrix_row_counts, n_as);
mapping_stride = max_count > 0 ? max_count : 1;
@@ -4289,23 +6637,28 @@ static int htp_mmid_prepare_mapping(
size_t matrix_row_map_size = n_as * mapping_stride * sizeof(struct mmid_row_mapping);
const size_t total_map_size = matrix_row_counts_size + matrix_row_map_size;
- if (total_map_size > octx->ctx->ddr_spad_size) {
- mapping_buf = memalign(128, total_map_size);
- if (!mapping_buf) {
+ if (total_map_size > spad_avail) {
+ free(map_alloc);
+ map_alloc = memalign(128, total_map_size);
+ if (!map_alloc) {
+ free(ids_alloc);
return HTP_STATUS_INTERNAL_ERR;
}
+ mapping_buf = (uint8_t *) map_alloc;
}
matrix_row_counts = (uint32_t *) mapping_buf;
matrix_rows = (struct mmid_row_mapping *) (mapping_buf + matrix_row_counts_size);
hvx_splat_u(matrix_row_counts, Q6_V_vzero(), n_as, sizeof(uint32_t));
- scan_expert_ids(ids, n_ids, n_as, matrix_row_counts, matrix_rows, mapping_stride);
+ scan_expert_ids(ids_data, ids->ne[1], n_ids, n_as, matrix_row_counts, matrix_rows, mapping_stride);
} else {
- n_skipped = count_skipped_ids_single(ids, n_ids);
+ n_skipped = count_skipped_ids_single(ids_data, n_ids);
}
- *out_mapping_buf = mapping_buf;
+ *out_ids_data = ids_data;
+ *out_ids_alloc = ids_alloc;
+ *out_map_alloc = map_alloc;
*out_matrix_row_counts = matrix_row_counts;
*out_matrix_rows = matrix_rows;
*out_mapping_stride = mapping_stride;
@@ -4333,12 +6686,8 @@ int op_matmul_id(struct htp_ops_context * octx) {
mmctx->act = act;
const struct htp_tensor * restrict ids = octx->src[2];
- if (htp_tensor_is_extended(ids) || htp_tensor_is_extended(act) || htp_tensor_is_extended(dst)) {
- return HTP_STATUS_NO_SUPPORT;
- }
const size_t src0_row_size = nb01;
- const size_t dst_row_size = nb1;
const size_t src0_row_size_padded = hex_round_up(src0_row_size, 128);
@@ -4349,23 +6698,28 @@ int op_matmul_id(struct htp_ops_context * octx) {
const int n_ids = ids->ne[0]; // n_expert_used
const int n_as = ne02; // n_expert
- uint8_t * mapping_buf = NULL;
- uint32_t * matrix_row_counts = NULL;
+ uint8_t __attribute__((aligned(128))) ids_stack[256];
+ const int32_t * ids_data = NULL;
+ void * ids_alloc = NULL;
+ void * map_alloc = NULL;
+ uint32_t * matrix_row_counts = NULL;
struct mmid_row_mapping * matrix_rows = NULL;
- uint32_t mapping_stride = 1;
- uint32_t n_skipped = 0;
+ uint32_t mapping_stride = 1;
+ uint32_t n_skipped = 0;
- int map_status = htp_mmid_prepare_mapping(octx, ids, n_ids, n_as, act_nrows,
- &mapping_buf, &matrix_row_counts, &matrix_rows,
+ int map_status = htp_mmid_prepare_mapping(octx, ids, ids_stack, sizeof(ids_stack), n_ids, n_as, act_nrows,
+ &ids_data, &ids_alloc, &map_alloc,
+ &matrix_row_counts, &matrix_rows,
&mapping_stride, &n_skipped);
if (map_status != HTP_STATUS_OK) {
return map_status;
}
if (n_skipped > 0) {
- zero_skipped_dst_rows(octx, ids, n_ids, dst);
+ zero_skipped_dst_rows(octx, ids_data, ids->ne[1], n_ids, dst);
}
+ mmctx->ids_data = ids_data;
mmctx->matrix_row_counts = matrix_row_counts;
mmctx->matrix_rows = matrix_rows;
mmctx->mapping_stride = mapping_stride;
@@ -4383,17 +6737,16 @@ int op_matmul_id(struct htp_ops_context * octx) {
} else {
uint32_t src0_row_start = 0;
uint32_t src0_row_end = src0_nrows;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float));
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
src0_row_start = range.start;
src0_row_end = range.start + range.count;
}
if (src0_row_start >= src0_row_end) {
- if (mapping_buf != octx->ctx->ddr_spad_base) {
- free(mapping_buf);
- }
+ free(map_alloc);
+ free(ids_alloc);
return HTP_STATUS_OK;
}
@@ -4404,6 +6757,8 @@ int op_matmul_id(struct htp_ops_context * octx) {
mmctx->src0_nrows_per_hvx = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div);
mmctx->src0_nrows_per_hvx = hex_round_up(mmctx->src0_nrows_per_hvx, 32);
+ mmctx->store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float));
+
if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) == 0) {
s = hvx_mm_matmul_id(octx, mmctx, act_nrows > 1 ? hvx_mm_id_tiled : hvx_mv_id_tiled);
} else {
@@ -4411,9 +6766,8 @@ int op_matmul_id(struct htp_ops_context * octx) {
}
}
- if (mapping_buf != octx->ctx->ddr_spad_base) {
- free(mapping_buf);
- }
+ free(map_alloc);
+ free(ids_alloc);
return s;
}
@@ -4436,14 +6790,6 @@ int op_matmul_id_nx(struct htp_ops_context * octx) {
const struct htp_tensor * restrict src0 = octx->src[0];
const struct htp_tensor * restrict act = octx->src[n_weights];
const struct htp_tensor * restrict ids = octx->src[n_weights + 1];
- if (htp_tensor_is_extended(ids) || htp_tensor_is_extended(act)) {
- return HTP_STATUS_NO_SUPPORT;
- }
- for (uint32_t p = 0; p < n_weights; p++) {
- if (htp_tensor_is_extended(octx->dsts[p])) {
- return HTP_STATUS_NO_SUPPORT;
- }
- }
mmctx->act = act;
@@ -4455,14 +6801,18 @@ int op_matmul_id_nx(struct htp_ops_context * octx) {
const int n_ids = ids->ne[0];
const int n_as = src0->ne[2];
- uint8_t * mapping_buf = NULL;
- uint32_t * matrix_row_counts = NULL;
+ uint8_t __attribute__((aligned(128))) ids_stack[256];
+ const int32_t * ids_data = NULL;
+ void * ids_alloc = NULL;
+ void * map_alloc = NULL;
+ uint32_t * matrix_row_counts = NULL;
struct mmid_row_mapping * matrix_rows = NULL;
- uint32_t mapping_stride = 1;
- uint32_t n_skipped = 0;
+ uint32_t mapping_stride = 1;
+ uint32_t n_skipped = 0;
- int map_status = htp_mmid_prepare_mapping(octx, ids, n_ids, n_as, act_nrows,
- &mapping_buf, &matrix_row_counts, &matrix_rows,
+ int map_status = htp_mmid_prepare_mapping(octx, ids, ids_stack, sizeof(ids_stack), n_ids, n_as, act_nrows,
+ &ids_data, &ids_alloc, &map_alloc,
+ &matrix_row_counts, &matrix_rows,
&mapping_stride, &n_skipped);
if (map_status != HTP_STATUS_OK) {
return map_status;
@@ -4472,11 +6822,12 @@ int op_matmul_id_nx(struct htp_ops_context * octx) {
for (uint32_t p = 0; p < n_weights; ++p) {
const struct htp_tensor * restrict d = octx->dsts[p];
if (d) {
- zero_skipped_dst_rows(octx, ids, n_ids, d);
+ zero_skipped_dst_rows(octx, ids_data, ids->ne[1], n_ids, d);
}
}
}
+ mmctx->ids_data = ids_data;
mmctx->matrix_row_counts = matrix_row_counts;
mmctx->matrix_rows = matrix_rows;
mmctx->mapping_stride = mapping_stride;
@@ -4499,9 +6850,8 @@ int op_matmul_id_nx(struct htp_ops_context * octx) {
}
}
- if (mapping_buf != octx->ctx->ddr_spad_base) {
- free(mapping_buf);
- }
+ free(map_alloc);
+ free(ids_alloc);
return s;
}
@@ -4513,6 +6863,12 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) {
return status;
}
+ if (octx->op == HTP_OP_MUL_MAT_NX_GLU) {
+ return htp_mm_kernel_is_hmx_int(kparams->kernel_type)
+ ? hmx_mm_nx_glu_int_2d(octx, kparams)
+ : hmx_mm_nx_glu_fp16_2d(octx, kparams);
+ }
+
if (kparams->n_hmx) {
return hmx_mm_nx_2d_f32(octx, kparams);
}
@@ -4563,11 +6919,19 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) {
quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
}
- const size_t act_row_size = htp_mm_tiled_act_row_size(src0->type, act->ne[0]);
+ const size_t act_row_size = kparams->act_row_size;
+ const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ size_t max_dst_row_size = 0;
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ if (octx->dsts[p]) {
+ const size_t sz = (size_t) octx->dsts[p]->ne[0] * sizeof(float);
+ if (sz > max_dst_row_size) max_dst_row_size = sz;
+ }
+ }
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, act->ne[0], act_nrows, octx->n_hvx,
- 0, src0_row_size, act_row_size, 0, kparams->n_prefetch, false, true);
+ max_dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, false, true);
const size_t vtcm_size = L.total_bytes;
@@ -4581,12 +6945,12 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) {
mmctx->vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0);
mmctx->vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
mmctx->vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, base, L.off_dst);
- mmctx->vtcm_act_raw = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act_raw);
+ mmctx->vtcm_act_raw = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_act_raw, quant_task_func != NULL);
hvx_mm_iq2xxs_lut_init(base, &L);
mmctx->vtcm_src0_stride = 0;
mmctx->vtcm_act_stride = act_row_size;
- mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0]);
+ mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0], act_elem_size);
mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div);
mmctx->vtcm_act_size_per_hvx = L.act_bytes;
@@ -4594,11 +6958,14 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) {
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
- hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act_raw, mmctx->vtcm_act_raw_stride, 0, act_nrows);
-
- mmctx->n_quant_rows_per_hvx = (act_nrows + n_quant_tasks - 1) / n_quant_tasks;
- mmctx->n_quant_tasks = n_quant_tasks;
- work_queue_run(octx->ctx->hvx_queue, quant_task_func, mmctx, n_quant_tasks);
+ if (quant_task_func) {
+ hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act_raw, mmctx->vtcm_act_raw_stride, 0, act_nrows);
+ mmctx->n_quant_rows_per_hvx = (act_nrows + n_quant_tasks - 1) / n_quant_tasks;
+ mmctx->n_quant_tasks = n_quant_tasks;
+ work_queue_run(octx->ctx->hvx_queue, quant_task_func, mmctx, n_quant_tasks);
+ } else {
+ hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, 0, act_nrows);
+ }
work_queue_run(octx->ctx->hvx_queue, hvx_mm_nx_2d_tiled, mmctx, octx->n_hvx);
diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.h b/ggml/src/ggml-hexagon/htp/matmul-ops.h
index 94441cf8c..e3c9569ca 100644
--- a/ggml/src/ggml-hexagon/htp/matmul-ops.h
+++ b/ggml/src/ggml-hexagon/htp/matmul-ops.h
@@ -14,11 +14,15 @@ extern "C" {
#endif
// --- HMX Tile Constraints ---
-#define HTP_MM_HMX_TILE_N_COLS 32
-#define HTP_MM_HMX_TILE_N_ROWS 32
-#define HTP_MM_HMX_TILE_SIZE (32 * 32 * sizeof(__fp16)) // 2048 bytes
-#define HTP_MM_HMX_TILE_N_ELMS 1024
-#define HTP_MM_HMX_MIN_NROWS 4
+#define HTP_MM_HMX_TILE_N_COLS 32
+#define HTP_MM_HMX_TILE_N_ROWS 32
+#define HTP_MM_HMX_TILE_SIZE (32 * 32 * sizeof(__fp16)) // 2048 bytes
+#define HTP_MM_HMX_TILE_N_ELMS 1024
+#define HTP_MM_HMX_MIN_NROWS 4
+#define HTP_MM_HMX_WEIGHT_B_TILE_SIZE 1024
+#define HTP_MM_HMX_BIAS_BANK_SIZE 256
+#define HTP_MM_HMX_W8A8_KGROUP 2048u
+#define HTP_MM_HMX_W8A8_KGROUP_TILES 64u
#define HTP_MM_WEIGHT_TILE_K_Q2_0 64
#define HTP_MM_WEIGHT_TILE_SIZE_Q2_0 HTP_TENSOR_TILE_SIZE_Q2_0
@@ -46,6 +50,8 @@ enum htp_mm_kernel_type {
// HMX paths
HTP_MM_KERNEL_HMX_2D,
HTP_MM_KERNEL_HMX_BATCHED,
+ HTP_MM_KERNEL_HMX_W8A8_2D,
+ HTP_MM_KERNEL_HMX_W8A8_BATCHED,
// HVX floating-point paths
HTP_MM_KERNEL_HVX_F16_F16_VTCM,
@@ -57,17 +63,60 @@ enum htp_mm_kernel_type {
HTP_MM_KERNEL_HVX_QUANT_BLOCK, // parallel block-wise quantization
};
+static inline bool htp_mm_kernel_is_hmx_w8a8(int32_t kt) {
+ return kt == HTP_MM_KERNEL_HMX_W8A8_2D || kt == HTP_MM_KERNEL_HMX_W8A8_BATCHED;
+}
+
+static inline bool htp_mm_kernel_is_hmx_int(int32_t kt) {
+ return htp_mm_kernel_is_hmx_w8a8(kt);
+}
+
+static inline bool htp_mm_kernel_is_hmx_2d(int32_t kt) {
+ return kt == HTP_MM_KERNEL_HMX_2D || kt == HTP_MM_KERNEL_HMX_W8A8_2D;
+}
+
+static inline bool htp_mm_kernel_is_hmx_batched(int32_t kt) {
+ return kt == HTP_MM_KERNEL_HMX_BATCHED || kt == HTP_MM_KERNEL_HMX_W8A8_BATCHED;
+}
+
+static inline bool htp_is_int_hmx_weight_type(int wtype) {
+ return wtype == HTP_TYPE_Q4_0 || wtype == HTP_TYPE_Q8_0 ||
+ wtype == HTP_TYPE_IQ4_NL || wtype == HTP_TYPE_MXFP4 ||
+ wtype == HTP_TYPE_Q5_0 || wtype == HTP_TYPE_Q1_0 ||
+ wtype == HTP_TYPE_Q2_0 || wtype == HTP_TYPE_NVFP4 ||
+ wtype == HTP_TYPE_Q3_K || wtype == HTP_TYPE_Q6_K ||
+ wtype == HTP_TYPE_IQ2_XXS || wtype == HTP_TYPE_Q4_1 ||
+ wtype == HTP_TYPE_Q4_K || wtype == HTP_TYPE_Q5_1 ||
+ wtype == HTP_TYPE_Q5_K || wtype == HTP_TYPE_Q2_K;
+}
+
+static inline uint32_t htp_int_hmx_min_k(int wtype) {
+ switch (wtype) {
+ case HTP_TYPE_IQ2_XXS:
+ case HTP_TYPE_Q2_K:
+ case HTP_TYPE_Q3_K:
+ case HTP_TYPE_Q4_K:
+ case HTP_TYPE_Q5_K:
+ case HTP_TYPE_Q6_K:
+ return 256u;
+ case HTP_TYPE_Q1_0:
+ return 128u;
+ default:
+ return 64u;
+ }
+}
+
// Op-specific struct for precomputed matmul params
struct htp_mm_kernel_params {
uint8_t kernel_type; // enum htp_mm_kernel_type
uint8_t pipeline; // 1 = pipelined execution, 0 = standard
- uint8_t unused; // reserved
uint8_t n_hmx; // 1 = use HMX, 0 = use HVX
+ uint8_t n_hvx; // Number of HVX threads
- uint8_t n_hvx; // Number of threads to spawn
- uint8_t n_act_hvx; // Number of threads for activation preparation
+ uint8_t n_act_hvx; // Number of HVX for activation preparation
uint8_t n_prefetch; // Prefetch lookahead buffers/rows in VTCM
uint8_t n_weights; // Number of weights for fused NX
+ uint8_t glu_op; // HTP_OP_GLU_* for fused MUL_MAT_NX_GLU (0 if none)
int32_t m_chunk; // Row chunk size (M chunk)
int32_t n_chunk; // Col chunk size (N chunk)
@@ -76,6 +125,7 @@ struct htp_mm_kernel_params {
int32_t act_row_size; // Row size for activation scratchpad
int32_t vtcm_size; // Total required scratchpad size in VTCM
int32_t vtcm_bias_size; // bias scratchpad size in VTCM (fused only)
+ int32_t hmx_n_groups; // Number of K superblocks for INT HMX kernels (1 for FP16)
// Precomputed division values
struct fastdiv_values div_ne12_ne1;
@@ -85,6 +135,8 @@ struct htp_mm_kernel_params {
struct fastdiv_values div_ne12;
struct fastdiv_values div_n_act_hvx;
struct fastdiv_values div_ne00_padded;
+ struct fastdiv_values div_hmx_n_groups;
+ struct fastdiv_values div_n_k_tiles;
};
#if defined(__cplusplus)
@@ -106,12 +158,13 @@ static inline int htp_mm_hmx_compute_chunks(size_t vtcm_total,
size_t per_mn_cost,
size_t m,
size_t n,
+ size_t m_align,
size_t m_block_cost,
size_t n_block_cost,
size_t * m_chunk_out,
size_t * n_chunk_out,
size_t * total_out) {
- if (m == 0 || n == 0) return -1;
+ if (m == 0 || n == 0 || m_align == 0) return -1;
if (vtcm_total <= overhead) return -1;
if (per_n_cost == 0 || per_m_cost == 0 || per_mn_cost == 0) return -1;
@@ -135,7 +188,7 @@ static inline int htp_mm_hmx_compute_chunks(size_t vtcm_total,
{
size_t remain = usable - n_fixed;
size_t mc = remain / mc_denom;
- mc = hex_align_down(mc, HTP_MM_HMX_TILE_N_ROWS);
+ mc = hex_align_down(mc, m_align);
mc = hex_smin(mc, m);
if (mc == 0) {
@@ -214,8 +267,8 @@ static inline size_t htp_mm_tiled_act_row_size(int weight_type, uint32_t ne) {
return htp_mm_weight_has_offset(weight_type) ? htp_mm_q8_1_tiled_row_size(ne) : htp_mm_q8_0_tiled_row_size(ne);
}
-static inline size_t htp_mm_act_raw_row_size(uint32_t ne) {
- return hex_round_up(ne, HTP_MM_ACT_BLOCK_K) * sizeof(float);
+static inline size_t htp_mm_act_raw_row_size(uint32_t ne, size_t act_elem_size) {
+ return hex_round_up(ne, HTP_MM_ACT_BLOCK_K) * act_elem_size;
}
static inline size_t htp_mm_round_up(size_t n, size_t m) {
@@ -226,22 +279,40 @@ static inline bool htp_mm_hmx_pipeline(uint32_t m) {
return m > 32;
}
-static inline void htp_mm_hmx_get_2d_chunk_costs(
- int wtype, uint32_t k, bool pipeline, uint32_t aligned_tile_size,
+static inline void htp_mm_hmx_get_2d_chunk_costs_ex(
+ int kernel_type, int wtype, uint32_t k, bool pipeline, uint32_t aligned_tile_size,
size_t * size_per_n_out, size_t * size_per_m_out, size_t * size_per_mn_out
) {
const bool is_quant = (wtype != HTP_TYPE_F16 && wtype != HTP_TYPE_F32 && wtype != HTP_TYPE_BF16);
const size_t row_stride = htp_tensor_get_row_size(wtype, k);
- const size_t vec_dot_size = k * sizeof(uint16_t);
const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(wtype);
const size_t qweight_row_stride = is_quant ? (size_t)(n_weight_tiles * aligned_tile_size) / 32 : 0;
+ if (htp_mm_kernel_is_hmx_int(kernel_type)) {
+ const size_t n_groups = (k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP;
+ const size_t w_unpacked_per_n = (size_t) k * sizeof(uint8_t) + n_groups * 20;
+
+ *size_per_n_out = (pipeline ? 2 : 1) * ((is_quant ? qweight_row_stride : row_stride) + w_unpacked_per_n);
+ *size_per_m_out = (size_t) k * sizeof(uint8_t) + n_groups * sizeof(float);
+ *size_per_mn_out = (pipeline ? 2 : 1) * n_groups * sizeof(uint16_t);
+ return;
+ }
+
+ const size_t vec_dot_size = k * sizeof(uint16_t);
*size_per_n_out = (pipeline ? 2 : 1) * (is_quant ? qweight_row_stride : row_stride) +
(pipeline ? 2 * vec_dot_size : vec_dot_size);
*size_per_m_out = vec_dot_size;
*size_per_mn_out = (pipeline ? 2 : 1) * sizeof(uint16_t);
}
+static inline void htp_mm_hmx_get_2d_chunk_costs(
+ int wtype, uint32_t k, bool pipeline, uint32_t aligned_tile_size,
+ size_t * size_per_n_out, size_t * size_per_m_out, size_t * size_per_mn_out
+) {
+ htp_mm_hmx_get_2d_chunk_costs_ex(HTP_MM_KERNEL_HMX_2D, wtype, k, pipeline, aligned_tile_size,
+ size_per_n_out, size_per_m_out, size_per_mn_out);
+}
+
static inline void htp_mm_hmx_get_batched_chunk_costs(
uint32_t k, uint32_t group_size,
size_t * size_per_n_out, size_t * size_per_m_out, size_t * size_per_mn_out
@@ -257,7 +328,7 @@ static inline size_t htp_mm_hmx_lut_bytes(int wtype) {
}
static inline size_t htp_mm_hmx_get_2d_overhead(int wtype, bool pipeline, bool is_matmul_id) {
- size_t num_regions = pipeline ? 7 : (is_matmul_id ? 4 : 5);
+ size_t num_regions = pipeline ? 8 : (is_matmul_id ? 4 : 6);
return num_regions * HTP_MM_HMX_TILE_SIZE + 256 + htp_mm_hmx_lut_bytes(wtype);
}
@@ -269,8 +340,14 @@ struct htp_mm_hmx_vtcm_layout {
// Byte offsets from vtcm_base for each region
size_t off_weight[2]; // [1] is only used when pipelined
size_t off_act;
+ size_t off_act_scales; // INT HMX activation group scales d_a
size_t off_act_f32; // fp32 activation conversion scratch
size_t off_dst[2]; // [1] is only used when pipelined
+ size_t off_dst_up[2]; // double-buffered up HMX output for fused GLU ([1] when pipelined)
+ size_t off_wt_scales_gate[2]; // per-chunk gate weight scales for fused GLU
+ size_t off_wt_scales_up[2]; // per-chunk up weight scales for fused GLU ([1] when pipelined)
+ size_t off_res_in[2]; // double-buffered 2D residual/bias input slice (pipelined 2D MUL_MAT_ADD)
+ size_t off_res_out[2]; // double-buffered output DMA writeback slice (pipelined HMX 2D)
size_t off_scratch[2]; // dequantization scratch pads
size_t off_scales; // HMX scales (256 bytes)
size_t off_bias; // bias in VTCM
@@ -279,14 +356,22 @@ struct htp_mm_hmx_vtcm_layout {
// Cached sizes of regions for HMX kernel use
size_t weight_area_bytes;
size_t act_area_bytes;
+ size_t act_scales_bytes;
size_t act_f32_bytes;
size_t output_area_bytes;
+ size_t wt_scales_bytes;
+ size_t res_in_bytes;
+ size_t res_out_bytes;
size_t scratch_bytes[2];
+ size_t weight_tiles_bytes;
+ size_t weight_bias_offset;
+ size_t weight_scales_offset;
size_t act_head_stride;
size_t bias_bytes;
size_t lut_bytes;
size_t total_bytes;
+ bool can_preissue_weight;
};
struct htp_mm_hvx_vtcm_layout {
@@ -309,7 +394,7 @@ struct htp_mm_hvx_vtcm_layout {
size_t total_bytes;
};
-static inline void htp_mm_hmx_vtcm_layout_build(
+static inline void htp_mm_hmx_vtcm_layout_build_core(
struct htp_mm_hmx_vtcm_layout * L,
int kernel_type,
int wtype,
@@ -320,11 +405,33 @@ static inline void htp_mm_hmx_vtcm_layout_build(
bool pipeline,
uint32_t act_hvx,
uint32_t aligned_tile_size,
- size_t bias_size
+ size_t bias_size,
+ size_t res_in_elem_size,
+ size_t res_out_elem_size,
+ bool is_glu
) {
size_t off = 0;
- L->lut_bytes = 0;
- L->off_lut = 0;
+ L->lut_bytes = 0;
+ L->off_lut = 0;
+ L->off_act_scales = 0;
+ L->can_preissue_weight = false;
+ L->act_scales_bytes = 0;
+ L->off_dst_up[0] = 0;
+ L->off_dst_up[1] = 0;
+ L->off_wt_scales_gate[0] = 0;
+ L->off_wt_scales_gate[1] = 0;
+ L->off_wt_scales_up[0] = 0;
+ L->off_wt_scales_up[1] = 0;
+ L->wt_scales_bytes = 0;
+ L->off_res_in[0] = 0;
+ L->off_res_in[1] = 0;
+ L->off_res_out[0] = 0;
+ L->off_res_out[1] = 0;
+ L->res_in_bytes = 0;
+ L->res_out_bytes = 0;
+ L->weight_tiles_bytes = 0;
+ L->weight_bias_offset = 0;
+ L->weight_scales_offset = 0;
if (kernel_type == HTP_MM_KERNEL_HMX_BATCHED) {
const size_t vec_dot_size = k * sizeof(uint16_t);
@@ -333,6 +440,8 @@ static inline void htp_mm_hmx_vtcm_layout_build(
const size_t activation_area_size = hex_align_up(group_size * act_head_stride * sizeof(uint16_t), HTP_MM_HMX_TILE_SIZE);
const size_t output_area_size = hex_align_up(group_size * mc * nc * sizeof(uint16_t), HTP_MM_HMX_TILE_SIZE);
const size_t scratch_area_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
+ const size_t res_out_size = (res_out_elem_size > 0)
+ ? hex_align_up(mc * hex_align_up(nc * res_out_elem_size, 128), HTP_MM_HMX_TILE_SIZE) : 0;
const size_t min_f32_size = hex_align_up(act_hvx * HTP_MM_DMA_ACT_MULTIPLIER * k * sizeof(float), 128);
// Group A: Permanent activation tiles and scales
@@ -349,6 +458,7 @@ static inline void htp_mm_hmx_vtcm_layout_build(
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst[1], output_area_size, false);
VTCM_LAYOUT_ALLOC(off_group_b, off_scratch[0], scratch_area_size);
VTCM_LAYOUT_ALLOC(off_group_b, off_scratch[1], scratch_area_size);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_out[0], res_out_size, res_out_size > 0);
const size_t group_b_size = off_group_b - off_group_a;
@@ -364,6 +474,7 @@ static inline void htp_mm_hmx_vtcm_layout_build(
L->act_area_bytes = activation_area_size;
L->act_f32_bytes = act_f32_size;
L->output_area_bytes = output_area_size;
+ L->res_out_bytes = res_out_size;
L->scratch_bytes[0] = scratch_area_size;
L->scratch_bytes[1] = scratch_area_size;
L->act_head_stride = act_head_stride;
@@ -371,51 +482,108 @@ static inline void htp_mm_hmx_vtcm_layout_build(
off = off_group_a + hex_smax(group_b_size, group_c_size);
} else {
- // HTP_MM_KERNEL_HMX_2D
+ // HTP_MM_KERNEL_HMX_2D / W8A8
+ const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type);
const bool is_quant = (wtype != HTP_TYPE_F16 && wtype != HTP_TYPE_F32 && wtype != HTP_TYPE_BF16);
const size_t row_stride = htp_tensor_get_row_size(wtype, k);
- const size_t vec_dot_size = k * sizeof(uint16_t);
const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(wtype);
- const size_t min_f32_size = hex_align_up(act_hvx * HTP_MM_DMA_ACT_MULTIPLIER * k * sizeof(float), 128);
+ const uint32_t dma_act_mult = is_int_hmx ? 8u : HTP_MM_DMA_ACT_MULTIPLIER;
+ const size_t min_f32_size = hex_align_up((size_t) act_hvx * dma_act_mult * k * sizeof(float), 128);
const size_t weight_area_size = is_quant
? hex_align_up((nc / 32) * n_weight_tiles * aligned_tile_size, HTP_MM_HMX_TILE_SIZE)
: hex_align_up(nc * row_stride, HTP_MM_HMX_TILE_SIZE);
- const size_t act_area_size = hex_align_up(mc * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
- const size_t output_area_size = hex_align_up(mc * nc * sizeof(__fp16), HTP_MM_HMX_TILE_SIZE);
- const size_t scratch0_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
+ size_t act_area_size = 0;
+ size_t act_scales_size = 0;
+ size_t output_area_size = 0;
+ size_t scratch0_size = 0;
+
+ if (is_int_hmx) {
+ const size_t n_groups = (k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP;
+ const size_t mc_pad = hex_align_up(mc, 64);
+ const size_t nc_pad = hex_align_up(nc, 32);
+
+ act_area_size = hex_align_up(mc_pad * k * sizeof(uint8_t), HTP_MM_HMX_TILE_SIZE);
+ act_scales_size = hex_align_up(n_groups * mc_pad * sizeof(float), HTP_MM_HMX_TILE_SIZE);
+ output_area_size = hex_align_up(n_groups * mc_pad * nc_pad * sizeof(uint16_t), HTP_MM_HMX_TILE_SIZE);
+
+ const size_t w_tiles_bytes = hex_align_up(nc_pad * k * sizeof(uint8_t), 256);
+ const size_t w_bias_bytes = hex_align_up((nc_pad / 32) * n_groups * 512, 256);
+ const size_t w_scales_bytes = hex_align_up(nc_pad * n_groups * sizeof(float), 256);
+
+ L->weight_tiles_bytes = w_tiles_bytes;
+ L->weight_bias_offset = w_tiles_bytes;
+ L->weight_scales_offset = w_tiles_bytes + w_bias_bytes;
+ L->wt_scales_bytes = is_glu ? hex_align_up(w_scales_bytes, HTP_MM_HMX_TILE_SIZE) : 0;
+ scratch0_size = hex_align_up(w_tiles_bytes + w_bias_bytes + (is_glu ? 0 : w_scales_bytes), HTP_MM_HMX_TILE_SIZE);
+ } else {
+ const size_t vec_dot_size = k * sizeof(uint16_t);
+ act_area_size = hex_align_up(mc * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
+ output_area_size = hex_align_up(mc * nc * sizeof(__fp16), HTP_MM_HMX_TILE_SIZE);
+ scratch0_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
+ }
+
const size_t scratch1_size = pipeline ? scratch0_size : 0;
+ const size_t res_in_size = (pipeline && res_in_elem_size > 0)
+ ? hex_align_up(mc * hex_align_up(nc * res_in_elem_size, 128), HTP_MM_HMX_TILE_SIZE) : 0;
+ const size_t res_out_size = (res_out_elem_size > 0)
+ ? hex_align_up(mc * hex_align_up(nc * res_out_elem_size, 128), HTP_MM_HMX_TILE_SIZE) : 0;
- // Group A: Scales and activation tiles (must not overlap with Group B or C)
+ // Group A: Scales and activation tiles (must not overlap with Group B or C)
size_t off_group_a = 0;
- VTCM_LAYOUT_ALLOC(off_group_a, off_scales, HTP_MM_HMX_TILE_SIZE); // Padded to 2K for alignment and future persistent data
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_scales, HTP_MM_HMX_TILE_SIZE, !is_int_hmx);
VTCM_LAYOUT_ALLOC(off_group_a, off_act, act_area_size);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_act_scales, act_scales_size, act_scales_size > 0);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_bias, hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE), bias_size > 0);
// Group B: Compute-only buffers (starts at off_group_a)
size_t off_group_b = off_group_a;
VTCM_LAYOUT_ALLOC(off_group_b, off_weight[0], weight_area_size);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_weight[1], weight_area_size, pipeline);
+ const size_t off_after_weights = off_group_b;
VTCM_LAYOUT_ALLOC(off_group_b, off_dst[0], output_area_size);
VTCM_LAYOUT_ALLOC(off_group_b, off_scratch[0], scratch0_size);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_scratch[1], scratch0_size, pipeline);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst[1], output_area_size, pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst_up[0], output_area_size, is_glu);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst_up[1], output_area_size, is_glu && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_gate[0], L->wt_scales_bytes, is_glu);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_gate[1], L->wt_scales_bytes, is_glu && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_up[0], L->wt_scales_bytes, is_glu);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_up[1], L->wt_scales_bytes, is_glu && pipeline);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_in[0], res_in_size, res_in_size > 0);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_in[1], res_in_size, res_in_size > 0);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_out[0], res_out_size, res_out_size > 0);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_out[1], res_out_size, pipeline && res_out_size > 0);
const size_t group_b_size = off_group_b - off_group_a;
- // Group C: Activation prep temporary buffer (overlaps Group B, starting at off_group_a)
- const size_t max_f32_size = act_hvx * 64 * k * sizeof(float);
- const size_t act_f32_size = hex_align_up(hex_smin(max_f32_size, hex_smax(min_f32_size, group_b_size)), 128);
- size_t off_group_c = off_group_a;
- VTCM_LAYOUT_ALLOC(off_group_c, off_act_f32, act_f32_size);
-
- const size_t group_c_size = off_group_c - off_group_a;
+ // Group C: Activation prep temporary buffer (overlaps Group B).
+ // Place after weight staging when space permits so chunk-0 weight DMA overlaps activation quant.
+ const size_t max_f32_size = act_hvx * 64 * k * sizeof(float);
+ const size_t avail_after_w = off_group_b - off_after_weights;
+ size_t act_f32_size;
+ size_t group_c_size;
+ if (is_int_hmx && avail_after_w >= min_f32_size) {
+ act_f32_size = hex_align_down(hex_smin(max_f32_size, avail_after_w), 128);
+ L->off_act_f32 = off_after_weights;
+ group_c_size = group_b_size;
+ L->can_preissue_weight = true;
+ } else {
+ act_f32_size = hex_align_up(hex_smin(max_f32_size, hex_smax(min_f32_size, group_b_size)), 128);
+ size_t off_group_c = off_group_a;
+ VTCM_LAYOUT_ALLOC(off_group_c, off_act_f32, act_f32_size);
+ group_c_size = off_group_c - off_group_a;
+ }
L->weight_area_bytes = weight_area_size;
L->act_area_bytes = act_area_size;
+ L->act_scales_bytes = act_scales_size;
L->act_f32_bytes = act_f32_size;
L->output_area_bytes = output_area_size;
+ L->res_in_bytes = res_in_size;
+ L->res_out_bytes = res_out_size;
L->scratch_bytes[0] = scratch0_size;
L->scratch_bytes[1] = scratch1_size;
L->act_head_stride = 0;
@@ -430,6 +598,55 @@ static inline void htp_mm_hmx_vtcm_layout_build(
L->total_bytes = off;
}
+static inline void htp_mm_hmx_vtcm_layout_build_ex(
+ struct htp_mm_hmx_vtcm_layout * L,
+ int kernel_type,
+ int wtype,
+ uint32_t k,
+ size_t mc,
+ size_t nc,
+ uint32_t group_size,
+ bool pipeline,
+ uint32_t act_hvx,
+ uint32_t aligned_tile_size,
+ size_t bias_size,
+ size_t res_in_elem_size,
+ size_t res_out_elem_size
+) {
+ htp_mm_hmx_vtcm_layout_build_core(L, kernel_type, wtype, k, mc, nc, group_size, pipeline, act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, false);
+}
+
+static inline void htp_mm_hmx_vtcm_layout_build_glu(
+ struct htp_mm_hmx_vtcm_layout * L,
+ int kernel_type,
+ int wtype,
+ uint32_t k,
+ size_t mc,
+ size_t nc,
+ bool pipeline,
+ uint32_t act_hvx,
+ uint32_t aligned_tile_size,
+ size_t res_out_elem_size
+) {
+ htp_mm_hmx_vtcm_layout_build_core(L, kernel_type, wtype, k, mc, nc, 1, pipeline, act_hvx, aligned_tile_size, 0, 0, res_out_elem_size, true);
+}
+
+static inline void htp_mm_hmx_vtcm_layout_build(
+ struct htp_mm_hmx_vtcm_layout * L,
+ int kernel_type,
+ int wtype,
+ uint32_t k,
+ size_t mc,
+ size_t nc,
+ uint32_t group_size,
+ bool pipeline,
+ uint32_t act_hvx,
+ uint32_t aligned_tile_size,
+ size_t bias_size
+) {
+ htp_mm_hmx_vtcm_layout_build_ex(L, kernel_type, wtype, k, mc, nc, group_size, pipeline, act_hvx, aligned_tile_size, bias_size, 0, 0);
+}
+
static inline void htp_mm_hvx_vtcm_layout_build(
struct htp_mm_hvx_vtcm_layout * L,
int kernel_type,
@@ -439,13 +656,14 @@ static inline void htp_mm_hvx_vtcm_layout_build(
uint32_t n_hvx,
size_t dst_row_size,
size_t src0_row_size,
- size_t act_row_size,
+ size_t act_elem_size,
size_t bias_row_size,
uint32_t n_prefetch,
bool is_matmul_id,
bool is_fused_nx
) {
- (void)act_row_size;
+ const size_t raw_elem_size = (act_elem_size == sizeof(__fp16)) ? sizeof(__fp16) : sizeof(float);
+ const size_t hvx_dst_stage_bytes = 32u * 128u; // 4KB per HVX for DMA output staging
size_t src0_sz = 0;
size_t act_sz = 0;
size_t bias_sz = bias_row_size > 0 ? htp_mm_round_up(bias_row_size, 128) : 0;
@@ -461,12 +679,16 @@ static inline void htp_mm_hvx_vtcm_layout_build(
size_t tiled_act_row_size = htp_mm_tiled_act_row_size(wtype, ne10);
size_t q_act_sz = hex_round_up(tiled_act_row_size * act_nrows, 128);
- size_t raw_row_size = htp_mm_act_raw_row_size(ne10);
+ size_t raw_row_size = htp_mm_act_raw_row_size(ne10, raw_elem_size);
+
+ size_t dst_per_hvx = (act_nrows == 1)
+ ? hex_smax(htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128), hvx_dst_stage_bytes)
+ : hvx_dst_stage_bytes;
src0_sz = weight_sz_per_hvx * n_hvx; // shared single-weight prefetch buffer
act_sz = q_act_sz; // quantized activation buffer
bias_sz = 0;
- dst_sz = 0;
+ dst_sz = dst_per_hvx * n_hvx;
act_raw_sz = hex_round_up(raw_row_size * act_nrows, 128);
} else if (is_matmul_id) {
const size_t act_row_size_tiled = htp_mm_tiled_act_row_size(wtype, ne10);
@@ -477,23 +699,25 @@ static inline void htp_mm_hvx_vtcm_layout_build(
act_sz = htp_mm_round_up(act_row_size_tiled * act_nrows, 256);
- size_t raw_row_size = htp_mm_act_raw_row_size(ne10);
+ size_t raw_row_size = htp_mm_act_raw_row_size(ne10, raw_elem_size);
+ size_t dst_per_hvx = (act_nrows == 1)
+ ? hex_smax(htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128), hvx_dst_stage_bytes)
+ : hvx_dst_stage_bytes;
src0_sz = src0_sz_per_hvx * n_hvx;
- dst_sz = 0;
+ dst_sz = dst_per_hvx * n_hvx;
bias_sz = 0;
act_raw_sz = hex_round_up(raw_row_size * act_nrows, 128);
} else {
const size_t src0_row_size_padded = htp_mm_round_up(src0_row_size, 128);
- const size_t dst_nrows = (act_nrows > 1) ? 0 : 1;
switch (kernel_type) {
case HTP_MM_KERNEL_HVX_F16_F16_VTCM: {
size_t f16_act_row_size = htp_mm_round_up(ne10 * 2, 128);
act_sz = htp_mm_round_up(f16_act_row_size * act_nrows, 256);
src0_sz = htp_mm_round_up(n_prefetch * src0_row_size_padded, 256) * n_hvx;
- dst_sz = dst_nrows > 0 ? htp_mm_round_up(dst_row_size, 128) * n_hvx : 0;
- act_raw_sz = hex_round_up(hex_round_up(ne10 * sizeof(float), 128) * act_nrows, 128);
+ dst_sz = ((act_nrows == 1) ? hex_smax(htp_mm_round_up(dst_row_size, 128), hvx_dst_stage_bytes) : hvx_dst_stage_bytes) * n_hvx;
+ act_raw_sz = hex_round_up(hex_round_up(ne10 * raw_elem_size, 128) * act_nrows, 128);
break;
}
case HTP_MM_KERNEL_HVX_F32_F32_VTCM:
@@ -501,8 +725,10 @@ static inline void htp_mm_hvx_vtcm_layout_build(
size_t f32_act_row_size = htp_mm_round_up(ne10 * 4, 128);
act_sz = htp_mm_round_up(f32_act_row_size * act_nrows, 256);
src0_sz = htp_mm_round_up(n_prefetch * src0_row_size_padded, 256) * n_hvx;
- dst_sz = dst_nrows > 0 ? htp_mm_round_up(dst_row_size, 128) * n_hvx : 0;
- act_raw_sz = 0;
+ dst_sz = ((act_nrows == 1) ? hex_smax(htp_mm_round_up(dst_row_size, 128), hvx_dst_stage_bytes) : hvx_dst_stage_bytes) * n_hvx;
+ act_raw_sz = (raw_elem_size == sizeof(__fp16))
+ ? hex_round_up(hex_round_up(ne10 * sizeof(__fp16), 128) * act_nrows, 128)
+ : 0;
break;
}
case HTP_MM_KERNEL_HVX_QUANT_BLOCK:
@@ -516,9 +742,11 @@ static inline void htp_mm_hvx_vtcm_layout_build(
src0_sz = tiled_vtcm_size * n_hvx;
act_sz = htp_mm_round_up(q_act_row_size * act_nrows, 256);
- size_t dst_slice_per_hvx = (dst_nrows > 0 && act_nrows == 1) ? htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128) : 0;
- dst_sz = dst_slice_per_hvx * n_hvx;
- size_t raw_row_size = htp_mm_act_raw_row_size(ne10);
+ size_t dst_per_hvx = (act_nrows == 1)
+ ? hex_smax(htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128), hvx_dst_stage_bytes)
+ : hvx_dst_stage_bytes;
+ dst_sz = dst_per_hvx * n_hvx;
+ size_t raw_row_size = htp_mm_act_raw_row_size(ne10, raw_elem_size);
act_raw_sz = hex_round_up(raw_row_size * act_nrows, 128);
break;
}
@@ -561,17 +789,18 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
uint32_t n_hvx,
size_t dst_row_size,
size_t src0_row_size,
- size_t act_row_size,
+ size_t act_elem_size,
size_t bias_row_size,
uint32_t n_prefetch,
size_t vtcm_budget,
struct htp_mm_hvx_vtcm_layout * L_out,
uint32_t * m_chunk_out
) {
+ const size_t raw_elem_size = (act_elem_size == sizeof(__fp16)) ? sizeof(__fp16) : sizeof(float);
struct htp_mm_hvx_vtcm_layout L;
htp_mm_hvx_vtcm_layout_build(
&L, kernel_type, wtype, ne10, act_nrows, n_hvx,
- dst_row_size, src0_row_size, act_row_size, bias_row_size, n_prefetch, false, false
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false
);
if (L.total_bytes <= vtcm_budget) {
@@ -600,7 +829,7 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
size_t eff_row_size = row_size;
if (kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) {
- eff_row_size += htp_mm_act_raw_row_size(ne10);
+ eff_row_size += htp_mm_act_raw_row_size(ne10, raw_elem_size);
}
uint32_t m_chunk = (uint32_t) (avail_act / eff_row_size);
@@ -616,14 +845,22 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
htp_mm_hvx_vtcm_layout_build(
&L, kernel_type, wtype, ne10, m_chunk, n_hvx,
- dst_row_size, src0_row_size, act_row_size, bias_row_size, n_prefetch, false, false
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false
);
while (m_chunk > 2 && L.total_bytes > vtcm_budget) {
m_chunk -= 2;
htp_mm_hvx_vtcm_layout_build(
&L, kernel_type, wtype, ne10, m_chunk, n_hvx,
- dst_row_size, src0_row_size, act_row_size, bias_row_size, n_prefetch, false, false
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false
+ );
+ }
+
+ if (m_chunk > 1 && L.total_bytes > vtcm_budget) {
+ m_chunk = 1;
+ htp_mm_hvx_vtcm_layout_build(
+ &L, kernel_type, wtype, ne10, m_chunk, n_hvx,
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false
);
}
@@ -636,19 +873,33 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
return false;
}
-static inline size_t htp_mm_hmx_get_2d_vtcm_size(
- int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size
+static inline size_t htp_mm_hmx_get_2d_vtcm_size_core(
+ int kernel_type, int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size,
+ size_t res_in_elem_size, size_t res_out_elem_size, bool is_glu
) {
struct htp_mm_hmx_vtcm_layout L;
- htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_2D, wtype, k, mc, nc, 1, pipeline, act_hvx, aligned_tile_size, bias_size);
+ htp_mm_hmx_vtcm_layout_build_core(&L, kernel_type, wtype, k, mc, nc, 1, pipeline, act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, is_glu);
return L.total_bytes;
}
+static inline size_t htp_mm_hmx_get_2d_vtcm_size_ex(
+ int kernel_type, int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size,
+ size_t res_in_elem_size, size_t res_out_elem_size
+) {
+ return htp_mm_hmx_get_2d_vtcm_size_core(kernel_type, wtype, k, mc, nc, pipeline, act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, false);
+}
+
+static inline size_t htp_mm_hmx_get_2d_vtcm_size(
+ int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size
+) {
+ return htp_mm_hmx_get_2d_vtcm_size_ex(HTP_MM_KERNEL_HMX_2D, wtype, k, mc, nc, pipeline, act_hvx, aligned_tile_size, bias_size, 0, 0);
+}
+
static inline size_t htp_mm_hmx_get_batched_vtcm_size(
- int wtype, uint32_t k, size_t mc, size_t nc, uint32_t group_size, bool pipeline, uint32_t act_hvx, size_t bias_size) {
+ int wtype, uint32_t k, size_t mc, size_t nc, uint32_t group_size, bool pipeline, uint32_t act_hvx, size_t bias_size, size_t res_out_elem_size) {
(void)pipeline;
struct htp_mm_hmx_vtcm_layout L;
- htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_BATCHED, wtype, k, mc, nc, group_size, false, act_hvx, 0, bias_size);
+ htp_mm_hmx_vtcm_layout_build_ex(&L, HTP_MM_KERNEL_HMX_BATCHED, wtype, k, mc, nc, group_size, false, act_hvx, 0, bias_size, 0, res_out_elem_size);
return L.total_bytes;
}
@@ -661,6 +912,7 @@ static inline bool htp_mm_hmx_solve_batched_params(
int n_hvx,
bool pipeline,
size_t bias_size,
+ size_t res_out_elem_size,
size_t vtcm_budget,
size_t * m_chunk_out,
size_t * n_chunk_out,
@@ -678,15 +930,16 @@ static inline bool htp_mm_hmx_solve_batched_params(
size_t group_overhead = htp_mm_hmx_get_batched_overhead() + (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0);
size_t group_size_per_n, group_size_per_m, group_size_per_mn;
htp_mm_hmx_get_batched_chunk_costs(k, group_size, &group_size_per_n, &group_size_per_m, &group_size_per_mn);
+ group_size_per_mn += res_out_elem_size;
size_t m_chunk_candidate = 0;
size_t n_chunk_candidate = 0;
size_t vtcm_size_candidate = 0;
- if (htp_mm_hmx_compute_chunks(vtcm_budget, group_overhead, group_size_per_n, group_size_per_m, group_size_per_mn, hex_align_up(ne11, 32), ne01_padded,
+ if (htp_mm_hmx_compute_chunks(vtcm_budget, group_overhead, group_size_per_n, group_size_per_m, group_size_per_mn, hex_align_up(ne11, 32), ne01_padded, HTP_MM_HMX_TILE_N_ROWS,
(size_t) ne01_padded * HTP_MM_HMX_COST_W_DEQUANT, (size_t) ne11 * HTP_MM_HMX_COST_A_CONVERT,
&m_chunk_candidate, &n_chunk_candidate, &vtcm_size_candidate) == 0) {
- size_t exact_size = htp_mm_hmx_get_batched_vtcm_size(wtype, k, m_chunk_candidate, n_chunk_candidate, group_size, pipeline, act_hvx, bias_size);
+ size_t exact_size = htp_mm_hmx_get_batched_vtcm_size(wtype, k, m_chunk_candidate, n_chunk_candidate, group_size, pipeline, act_hvx, bias_size, res_out_elem_size);
if (exact_size <= vtcm_budget) {
size_t mblocks = ((size_t) ne11 + m_chunk_candidate - 1) / m_chunk_candidate;
if (mblocks < best_mblocks || (mblocks == best_mblocks && act_hvx > best_act_hvx)) {
@@ -715,7 +968,8 @@ static inline bool htp_mm_hmx_solve_batched_params(
return false;
}
-static inline bool htp_mm_hmx_solve_2d_params(
+static inline bool htp_mm_hmx_solve_2d_params_core(
+ int kernel_type,
int wtype,
uint32_t k,
uint32_t m_id_rows,
@@ -727,62 +981,247 @@ static inline bool htp_mm_hmx_solve_2d_params(
bool is_matmul_id,
uint32_t aligned_tile_size,
size_t bias_size,
+ size_t res_in_elem_size,
+ size_t res_out_elem_size,
+ bool is_glu,
size_t vtcm_budget,
size_t * m_chunk_out,
size_t * n_chunk_out,
int * act_hvx_out,
size_t * vtcm_size_out
) {
- size_t best_mblocks = SIZE_MAX;
- int best_act_hvx = 0;
- size_t best_m_chunk = 0;
- size_t best_n_chunk = 0;
- size_t best_vtcm_size = 0;
+ const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type);
+ const size_t m_align = is_int_hmx ? 64u : HTP_MM_HMX_TILE_N_ROWS;
+ const size_t n_total = hex_align_up((size_t) ne01_padded, HTP_MM_HMX_TILE_N_COLS);
+ const size_t m_target = is_matmul_id ? hex_align_up((size_t) m_id_rows, m_align)
+ : hex_align_up((size_t) ne11_padded, m_align);
+ const size_t m_rows = (m_for_cost > 0) ? (size_t) m_for_cost : m_target;
+ if (m_target == 0 || n_total == 0) {
+ return false;
+ }
- const int m_for_chunks = is_matmul_id ? hex_align_up(m_id_rows, 32) : ne11_padded;
+ size_t per_n_approx = 0, per_m_approx = 0, per_mn_approx = 0;
+ htp_mm_hmx_get_2d_chunk_costs_ex(kernel_type, wtype, k, pipeline, aligned_tile_size,
+ &per_n_approx, &per_m_approx, &per_mn_approx);
+ if (is_glu) {
+ const size_t n_groups = (k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP;
+ per_mn_approx += (pipeline ? 2u : 1u) * (is_int_hmx ? (n_groups * sizeof(uint16_t)) : sizeof(__fp16));
+ }
+ per_mn_approx += (pipeline ? 2u : 1u) * res_out_elem_size + (pipeline ? 2u * res_in_elem_size : 0u);
+ const size_t base_overhead = htp_mm_hmx_get_2d_overhead(wtype, pipeline, is_matmul_id) +
+ (is_int_hmx ? (HTP_MM_HMX_TILE_SIZE + (pipeline ? 2u : 1u) * 768u) : 0u) +
+ ((is_glu && is_int_hmx) ? ((pipeline ? 4u : 2u) * HTP_MM_HMX_TILE_SIZE) : 0u) +
+ (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0u);
+ if (vtcm_budget <= base_overhead || per_n_approx == 0 || per_m_approx == 0 || per_mn_approx == 0) {
+ return false;
+ }
+ const size_t usable = vtcm_budget - base_overhead;
+
+ const size_t min_par_nc = (size_t) (n_hvx > 0 ? n_hvx : 1) * HTP_MM_HMX_TILE_N_COLS;
+ size_t nc_cap = n_total;
+ if (pipeline) {
+ if (n_total >= 4u * min_par_nc) {
+ nc_cap = hex_align_down(n_total / 4u, HTP_MM_HMX_TILE_N_COLS);
+ } else if (n_total >= 2u * min_par_nc) {
+ nc_cap = hex_align_down(n_total / 2u, HTP_MM_HMX_TILE_N_COLS);
+ }
+ if (nc_cap > 512u && min_par_nc <= 512u) {
+ nc_cap = 512u;
+ }
+ }
+ const size_t nc_hi = hex_align_down(hex_smin(nc_cap, usable / per_n_approx), HTP_MM_HMX_TILE_N_COLS);
+ if (nc_hi < HTP_MM_HMX_TILE_N_COLS) {
+ return false;
+ }
+ // Avoid 1-tile (64B fp16) column chunks when >=2 tiles fit, preventing partial-cacheline RFO stores in O-PROC
+ const size_t min_nc_pref = (n_total >= 2u * HTP_MM_HMX_TILE_N_COLS && nc_hi >= 2u * HTP_MM_HMX_TILE_N_COLS)
+ ? (2u * HTP_MM_HMX_TILE_N_COLS)
+ : HTP_MM_HMX_TILE_N_COLS;
+
+ size_t best_mblocks = SIZE_MAX;
+ size_t best_ncost = SIZE_MAX;
+ int best_act_hvx = 0;
+ size_t best_mc = 0;
+ size_t best_nc = 0;
+ size_t best_vtcm_size = 0;
- int act_hvx = n_hvx;
- while (act_hvx >= 1) {
- size_t simple_2d_overhead = htp_mm_hmx_get_2d_overhead(wtype, pipeline, is_matmul_id) + (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0);
- size_t simple_2d_size_per_n, simple_2d_size_per_m, simple_2d_size_per_mn;
- htp_mm_hmx_get_2d_chunk_costs(wtype, k, pipeline, aligned_tile_size, &simple_2d_size_per_n, &simple_2d_size_per_m, &simple_2d_size_per_mn);
+ for (int act_hvx = n_hvx; act_hvx >= 1; act_hvx = (act_hvx == 1) ? 0 : (act_hvx / 2)) {
+ const uint32_t layout_act_hvx = (uint32_t) act_hvx;
- size_t m_chunk_candidate = 0;
- size_t n_chunk_candidate = 0;
- size_t vtcm_size_candidate = 0;
+ for (size_t nc = nc_hi; nc >= HTP_MM_HMX_TILE_N_COLS; nc -= HTP_MM_HMX_TILE_N_COLS) {
+ if (nc < min_nc_pref && best_act_hvx > 0) {
+ break;
+ }
+ size_t n_fixed = 0, ncmn = 0, mc_denom = 0;
+ if (hex_mul_overflow(nc, per_n_approx, &n_fixed) || n_fixed >= usable) {
+ if (nc == HTP_MM_HMX_TILE_N_COLS) break;
+ continue;
+ }
+ if (hex_mul_overflow(nc, per_mn_approx, &ncmn) ||
+ hex_add_overflow(per_m_approx, ncmn, &mc_denom) || mc_denom == 0) {
+ if (nc == HTP_MM_HMX_TILE_N_COLS) break;
+ continue;
+ }
- if (htp_mm_hmx_compute_chunks(vtcm_budget, simple_2d_overhead, simple_2d_size_per_n, simple_2d_size_per_m, simple_2d_size_per_mn, m_for_chunks, ne01_padded,
- (size_t) ne01_padded * HTP_MM_HMX_COST_W_DEQUANT, (size_t) m_for_cost * HTP_MM_HMX_COST_A_CONVERT,
- &m_chunk_candidate, &n_chunk_candidate, &vtcm_size_candidate) == 0) {
- size_t exact_size = htp_mm_hmx_get_2d_vtcm_size(wtype, k, m_chunk_candidate, n_chunk_candidate, pipeline, is_matmul_id ? 0 : act_hvx, aligned_tile_size, bias_size);
- if (exact_size <= vtcm_budget) {
- size_t mblocks = ((size_t) m_for_cost + m_chunk_candidate - 1) / m_chunk_candidate;
- if (mblocks < best_mblocks || (mblocks == best_mblocks && act_hvx > best_act_hvx)) {
- best_mblocks = mblocks;
- best_act_hvx = act_hvx;
- best_m_chunk = m_chunk_candidate;
- best_n_chunk = n_chunk_candidate;
- best_vtcm_size = exact_size;
+ size_t mc = hex_align_down((usable - n_fixed) / mc_denom, m_align);
+ mc = hex_smin(mc, m_target);
+ while (mc >= m_align) {
+ size_t exact = htp_mm_hmx_get_2d_vtcm_size_core(
+ kernel_type, wtype, k, mc, nc, pipeline, layout_act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, is_glu);
+ if (exact <= vtcm_budget) {
+ const size_t mblocks = (m_rows + mc - 1u) / mc;
+ size_t mc_tight = (mblocks > 1u)
+ ? hex_smin(mc, hex_align_up((m_rows + mblocks - 1u) / mblocks, m_align))
+ : mc;
+ if (mc_tight != mc) {
+ size_t exact_tight = htp_mm_hmx_get_2d_vtcm_size_core(
+ kernel_type, wtype, k, mc_tight, nc, pipeline, layout_act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, is_glu);
+ if (exact_tight <= vtcm_budget) {
+ mc = mc_tight;
+ exact = exact_tight;
+ }
+ }
+
+ const size_t nblocks = (n_total + nc - 1u) / nc;
+ const size_t col_tiles = nc / HTP_MM_HMX_TILE_N_COLS;
+ const size_t hvx_cnt = (n_hvx > 0) ? (size_t) n_hvx : 1u;
+ const size_t eff_nc = (col_tiles >= hvx_cnt)
+ ? (((col_tiles + hvx_cnt - 1u) / hvx_cnt) * hvx_cnt * HTP_MM_HMX_TILE_N_COLS)
+ : nc;
+ const size_t pipe_tail = pipeline ? ((nblocks == 1u) ? (2u * eff_nc) : eff_nc) : 0u;
+ const size_t ncost = nblocks * eff_nc + pipe_tail + nblocks * HTP_MM_HMX_TILE_N_COLS;
+
+ const bool better =
+ (mblocks < best_mblocks) ||
+ (mblocks == best_mblocks && ncost < best_ncost) ||
+ (mblocks == best_mblocks && ncost == best_ncost && act_hvx > best_act_hvx) ||
+ (mblocks == best_mblocks && ncost == best_ncost && act_hvx == best_act_hvx && nc < best_nc);
+
+ if (better) {
+ best_mblocks = mblocks;
+ best_ncost = ncost;
+ best_act_hvx = act_hvx;
+ best_mc = mc;
+ best_nc = nc;
+ best_vtcm_size = exact;
+ }
+ break;
}
+ mc -= m_align;
}
+
+ if ((best_mblocks == 1u && best_nc >= n_total) || nc == HTP_MM_HMX_TILE_N_COLS) break;
}
- if (act_hvx == 1) {
- act_hvx = 0;
- } else {
- act_hvx /= 2;
- }
+ if (best_mblocks == 1u && (best_nc >= n_total || best_nc >= 128u)) break;
}
if (best_act_hvx > 0) {
- *m_chunk_out = best_m_chunk;
- *n_chunk_out = best_n_chunk;
+ *m_chunk_out = best_mc;
+ *n_chunk_out = best_nc;
+ *act_hvx_out = best_act_hvx;
*vtcm_size_out = best_vtcm_size;
- *act_hvx_out = best_act_hvx;
return true;
}
return false;
}
+static inline bool htp_mm_hmx_solve_2d_params_ex(
+ int kernel_type,
+ int wtype,
+ uint32_t k,
+ uint32_t m_id_rows,
+ uint32_t ne01_padded,
+ uint32_t ne11_padded,
+ uint32_t m_for_cost,
+ int n_hvx,
+ bool pipeline,
+ bool is_matmul_id,
+ uint32_t aligned_tile_size,
+ size_t bias_size,
+ size_t res_in_elem_size,
+ size_t res_out_elem_size,
+ size_t vtcm_budget,
+ size_t * m_chunk_out,
+ size_t * n_chunk_out,
+ int * act_hvx_out,
+ size_t * vtcm_size_out
+) {
+ return htp_mm_hmx_solve_2d_params_core(kernel_type, wtype, k, m_id_rows, ne01_padded, ne11_padded, m_for_cost,
+ n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, res_in_elem_size,
+ res_out_elem_size, false, vtcm_budget, m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out);
+}
+
+static inline bool htp_mm_hmx_solve_2d_params_glu(
+ int kernel_type,
+ int wtype,
+ uint32_t k,
+ uint32_t ne01_padded,
+ uint32_t ne11_padded,
+ uint32_t m_for_cost,
+ int n_hvx,
+ bool pipeline,
+ uint32_t aligned_tile_size,
+ size_t res_out_elem_size,
+ size_t vtcm_budget,
+ size_t * m_chunk_out,
+ size_t * n_chunk_out,
+ int * act_hvx_out,
+ size_t * vtcm_size_out
+) {
+ return htp_mm_hmx_solve_2d_params_core(kernel_type, wtype, k, 0, ne01_padded, ne11_padded, m_for_cost,
+ n_hvx, pipeline, false, aligned_tile_size, 0, 0,
+ res_out_elem_size, true, vtcm_budget, m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out);
+}
+
+static inline bool htp_mm_int_hmx_solve_2d_params(
+ int kernel_type,
+ int wtype,
+ uint32_t k,
+ uint32_t m_id_rows,
+ uint32_t ne01_padded,
+ uint32_t ne11_padded,
+ uint32_t m_for_cost,
+ int n_hvx,
+ bool pipeline,
+ bool is_matmul_id,
+ uint32_t aligned_tile_size,
+ size_t bias_size,
+ size_t res_out_elem_size,
+ size_t vtcm_budget,
+ size_t * m_chunk_out,
+ size_t * n_chunk_out,
+ int * act_hvx_out,
+ size_t * vtcm_size_out
+) {
+ return htp_mm_hmx_solve_2d_params_ex(kernel_type, wtype, k, m_id_rows, ne01_padded, ne11_padded, m_for_cost,
+ n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, 0, res_out_elem_size, vtcm_budget,
+ m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out);
+}
+
+static inline bool htp_mm_hmx_solve_2d_params(
+ int wtype,
+ uint32_t k,
+ uint32_t m_id_rows,
+ uint32_t ne01_padded,
+ uint32_t ne11_padded,
+ uint32_t m_for_cost,
+ int n_hvx,
+ bool pipeline,
+ bool is_matmul_id,
+ uint32_t aligned_tile_size,
+ size_t bias_size,
+ size_t res_out_elem_size,
+ size_t vtcm_budget,
+ size_t * m_chunk_out,
+ size_t * n_chunk_out,
+ int * act_hvx_out,
+ size_t * vtcm_size_out
+) {
+ return htp_mm_hmx_solve_2d_params_ex(HTP_MM_KERNEL_HMX_2D, wtype, k, m_id_rows, ne01_padded, ne11_padded, m_for_cost,
+ n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, 0, res_out_elem_size, vtcm_budget,
+ m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out);
+}
+
#ifdef __cplusplus
}
#endif
diff --git a/ggml/src/ggml-hexagon/htp/pad-ops.c b/ggml/src/ggml-hexagon/htp/pad-ops.c
index b77e95a90..61db555a9 100644
--- a/ggml/src/ggml-hexagon/htp/pad-ops.c
+++ b/ggml/src/ggml-hexagon/htp/pad-ops.c
@@ -1,13 +1,8 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
-#include <string.h>
-
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hvx-utils.h"
#define GGML_COMMON_DECL_C
@@ -20,7 +15,7 @@
#include "htp-vtcm.h"
#include "pad-ops.h"
-/* Circular wrap: maps any integer x into [0, n) */
+// Circular wrap: maps any integer x into [0, n)
static inline uint32_t wrap_around(int32_t x, uint32_t n, const struct fastdiv_values * div_n) {
if (x >= 0) {
const uint32_t ux = (uint32_t) x;
@@ -31,54 +26,33 @@ static inline uint32_t wrap_around(int32_t x, uint32_t n, const struct fastdiv_v
return rem ? (n - rem) : 0;
}
-/* Decompose a flat dst row index into (i1, i2, i3) */
+// Decompose a flat dst row index into (i1, i2, i3)
static inline void pad_decompose_row(uint32_t ir, uint32_t ne1, uint32_t ne2,
const struct htp_pad_kernel_params * kparams,
- uint32_t *i1, uint32_t *i2, uint32_t *i3) {
+ uint32_t * i1, uint32_t * i2, uint32_t * i3) {
*i3 = fastdiv(ir, &kparams->div_ne1_ne2);
const uint32_t rem = ir - (*i3) * (ne1 * ne2);
*i2 = fastdiv(rem, &kparams->div_ne1);
*i1 = rem - (*i2) * ne1;
}
-/* Return non-zero if row (i1,i2,i3) falls in the non-padded interior */
+// Return non-zero if row (i1,i2,i3) falls in the non-padded interior
static inline int pad_is_interior(uint32_t i1, uint32_t i2, uint32_t i3,
- int32_t lp1, int32_t rp1, uint32_t ne1,
- int32_t lp2, int32_t rp2, uint32_t ne2,
- int32_t lp3, int32_t rp3, uint32_t ne3) {
- return ((int32_t)i1 >= lp1 && (int32_t)i1 < (int32_t)ne1 - rp1) &&
- ((int32_t)i2 >= lp2 && (int32_t)i2 < (int32_t)ne2 - rp2) &&
- ((int32_t)i3 >= lp3 && (int32_t)i3 < (int32_t)ne3 - rp3);
-}
-
-/* Compute the DDR src row pointer for a zero-pad interior row */
-static inline const uint8_t * pad_src_row_ptr(const struct htp_tensor * src,
- uint32_t i1, uint32_t i2, uint32_t i3,
- int32_t lp1, int32_t lp2, int32_t lp3) {
- return (const uint8_t *) src->data
- + (i1 - (uint32_t)lp1) * src->nb[1]
- + (i2 - (uint32_t)lp2) * src->nb[2]
- + (i3 - (uint32_t)lp3) * src->nb[3];
+ int32_t lp1, int32_t rp1, uint32_t ne1,
+ int32_t lp2, int32_t rp2, uint32_t ne2,
+ int32_t lp3, int32_t rp3, uint32_t ne3) {
+ return ((int32_t) i1 >= lp1 && (int32_t) i1 < (int32_t) ne1 - rp1) &&
+ ((int32_t) i2 >= lp2 && (int32_t) i2 < (int32_t) ne2 - rp2) &&
+ ((int32_t) i3 >= lp3 && (int32_t) i3 < (int32_t) ne3 - rp3);
}
static inline dma_addr_t pad_src_row_data(const struct htp_tensor * src,
uint32_t i1, uint32_t i2, uint32_t i3,
int32_t lp1, int32_t lp2, int32_t lp3) {
return src->data
- + (i1 - (uint32_t)lp1) * src->nb[1]
- + (i2 - (uint32_t)lp2) * src->nb[2]
- + (i3 - (uint32_t)lp3) * src->nb[3];
-}
-
-/* Compute the DDR src row pointer for a circular row (wrap-around indexing) */
-static inline const uint8_t * pad_circ_src_row_ptr(const struct htp_tensor * src,
- const struct htp_pad_kernel_params * kparams,
- uint32_t i1, uint32_t i2, uint32_t i3,
- int32_t lp1, int32_t lp2, int32_t lp3) {
- return (const uint8_t *) src->data
- + wrap_around((int32_t)i1 - lp1, src->ne[1], &kparams->div_ne01) * src->nb[1]
- + wrap_around((int32_t)i2 - lp2, src->ne[2], &kparams->div_ne02) * src->nb[2]
- + wrap_around((int32_t)i3 - lp3, src->ne[3], &kparams->div_ne03) * src->nb[3];
+ + (size_t) (i1 - (uint32_t) lp1) * src->nb[1]
+ + (size_t) (i2 - (uint32_t) lp2) * src->nb[2]
+ + (size_t) (i3 - (uint32_t) lp3) * src->nb[3];
}
static inline dma_addr_t pad_circ_src_row_data(const struct htp_tensor * src,
@@ -86,14 +60,18 @@ static inline dma_addr_t pad_circ_src_row_data(const struct htp_tensor * src,
uint32_t i1, uint32_t i2, uint32_t i3,
int32_t lp1, int32_t lp2, int32_t lp3) {
return src->data
- + wrap_around((int32_t)i1 - lp1, src->ne[1], &kparams->div_ne01) * src->nb[1]
- + wrap_around((int32_t)i2 - lp2, src->ne[2], &kparams->div_ne02) * src->nb[2]
- + wrap_around((int32_t)i3 - lp3, src->ne[3], &kparams->div_ne03) * src->nb[3];
+ + (size_t) wrap_around((int32_t) i1 - lp1, src->ne[1], &kparams->div_ne01) * src->nb[1]
+ + (size_t) wrap_around((int32_t) i2 - lp2, src->ne[2], &kparams->div_ne02) * src->nb[2]
+ + (size_t) wrap_around((int32_t) i3 - lp3, src->ne[3], &kparams->div_ne03) * src->nb[3];
}
struct htp_pad_context {
- struct htp_ops_context * octx;
+ struct htp_ops_context * octx;
const struct htp_pad_kernel_params * kparams;
+ uint8_t * vtcm_src0;
+ uint8_t * vtcm_dst;
+ size_t src0_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
int32_t lp0, rp0;
int32_t lp1, rp1;
@@ -103,385 +81,299 @@ struct htp_pad_context {
uint32_t nrows_per_hvx;
uint32_t total_dst_rows;
uint32_t row_start;
+ uint32_t chunk_elems;
size_t type_size;
+ size_t chunk_bytes_aligned;
+};
- // Row sizes for DMA kernel (populated when VTCM is available)
- size_t src_row_size;
- size_t src_row_size_aligned;
- size_t dst_row_size;
- size_t dst_row_size_aligned;
+struct pad_pipe_state {
+ const struct htp_tensor * src;
+ const struct htp_tensor * dst;
+ const struct htp_pad_kernel_params * kparams;
+ size_t type_size;
+ size_t chunk_bytes_aligned;
+ int32_t lp0, rp0;
+ int32_t lp1, rp1;
+ int32_t lp2, rp2;
+ int32_t lp3, rp3;
+ uint32_t ne00;
+ uint32_t ne0;
+ uint32_t ne1;
+ uint32_t ne2;
+ uint32_t ne3;
+ uint32_t nb1;
+ uint32_t nb2;
+ uint32_t nb3;
+ uint32_t chunk_elems;
+ uint32_t row;
+ uint32_t row_end;
+ uint32_t off;
};
-#define htp_pad_preamble \
- const struct htp_tensor * src = octx->src[0]; \
- const struct htp_tensor * dst = octx->dst; \
- \
- const uint32_t ne00 = src->ne[0]; \
- const uint32_t nb00 = src->nb[0]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3]; \
- \
- const int32_t lp0 = pctx->lp0, rp0 = pctx->rp0; \
- const int32_t lp1 = pctx->lp1, rp1 = pctx->rp1; \
- const int32_t lp2 = pctx->lp2, rp2 = pctx->rp2; \
- const int32_t lp3 = pctx->lp3, rp3 = pctx->rp3; \
- \
- const size_t type_size = pctx->type_size; \
- \
- const uint32_t row_start = pctx->row_start + pctx->nrows_per_hvx * ith; \
- const uint32_t row_end = MIN(row_start + pctx->nrows_per_hvx, pctx->row_start + pctx->total_dst_rows);
+// ---------------------------------------------------------------------------
+// Shared task iteration and output writeback
+// ---------------------------------------------------------------------------
+static bool pad_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+ if (s->row >= s->row_end) {
+ return false;
+ }
-#define htp_pad_dma_preamble \
- const size_t src_row_size = pctx->src_row_size; \
- const size_t src_row_size_aligned = pctx->src_row_size_aligned; \
- const size_t dst_row_size = pctx->dst_row_size; \
- const size_t dst_row_size_aligned = pctx->dst_row_size_aligned; \
- \
- uint8_t * src_spad_base = octx->src0_spad.data + ith * octx->src0_spad.size_per_hvx; \
- uint8_t * dst_spad_base = octx->dst_spad.data + ith * octx->dst_spad.size_per_hvx; \
- \
- dma_queue * dma_q = th->dma_q;
+ const uint32_t rem = s->ne0 - s->off;
+ const uint32_t len = MIN(s->chunk_elems, rem);
-// ---------------------------------------------------------------------------
-// HVX vectorized PAD kernel
-// ---------------------------------------------------------------------------
+ task->row = s->row;
+ task->off = s->off;
+ task->len = len;
+ task->aux = 0;
-static void pad_job_per_hvx_hvx(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- const struct htp_pad_context * pctx = (const struct htp_pad_context *) data;
- struct htp_ops_context * octx = pctx->octx;
- htp_pad_preamble;
-
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
-
- for (uint32_t dst_row = row_start; dst_row < row_end; dst_row++) {
- uint32_t i1, i2, i3;
- pad_decompose_row(dst_row, ne1, ne2, pctx->kparams, &i1, &i2, &i3);
-
- uint8_t * dst_ptr = (uint8_t *) dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3;
-
- const int interior = pad_is_interior(i1, i2, i3,
- lp1, rp1, ne1,
- lp2, rp2, ne2,
- lp3, rp3, ne3);
-
- if (!interior) {
- hvx_splat_f32_u(dst_ptr, 0.0f, ne0);
- } else {
- const uint8_t * src_ptr = pad_src_row_ptr(src, i1, i2, i3, lp1, lp2, lp3);
-
- if (lp0 > 0) {
- hvx_splat_f32_u(dst_ptr, 0.0f, (uint32_t)lp0);
- }
-
- uint8_t * dst_row_start = dst_ptr + (size_t)lp0 * type_size;
- if (nb00 == type_size) {
- hvx_copy_f32_uu(dst_row_start, src_ptr, ne00);
- } else {
- for (uint32_t i = 0; i < ne00; i++) {
- memcpy(dst_row_start + i * type_size,
- src_ptr + (size_t)i * nb00,
- type_size);
- }
- }
-
- if (rp0 > 0) {
- hvx_splat_f32_u(dst_ptr + ((size_t)lp0 + ne00) * type_size, 0.0f, (uint32_t)rp0);
- }
- }
+ s->off += len;
+ if (s->off >= s->ne0) {
+ s->off = 0;
+ s->row++;
}
+ return true;
+}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
+static bool pad_const_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+ if (!pad_next_task(ctx, task)) {
+ return false;
+ }
- FARF(HIGH, "pad-hvx %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
- ith, nth,
- src->ne[0], src->ne[1], src->ne[2], src->ne[3],
- dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
- row_start, row_end);
+ uint32_t i1, i2, i3;
+ pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3);
+ task->aux = (uint32_t) pad_is_interior(i1, i2, i3,
+ s->lp1, s->rp1, s->ne1,
+ s->lp2, s->rp2, s->ne2,
+ s->lp3, s->rp3, s->ne3);
+ return true;
+}
+
+static bool pad_circ_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+ if (s->row >= s->row_end) {
+ return false;
+ }
+
+ const uint32_t lp0 = (uint32_t) s->lp0;
+ const uint32_t ne00 = s->ne00;
+ uint32_t sx;
+ if (s->off < lp0) {
+ sx = ne00 - lp0 + s->off;
+ } else if (s->off < lp0 + ne00) {
+ sx = s->off - lp0;
+ } else {
+ sx = s->off - lp0 - ne00;
+ }
+
+ // Split at ne00 wrap boundary so each task is one contiguous DMA read
+ const uint32_t rem = s->ne0 - s->off;
+ const uint32_t len = MIN(MIN(s->chunk_elems, rem), ne00 - sx);
+
+ task->row = s->row;
+ task->off = s->off;
+ task->len = len;
+ task->aux = sx;
+
+ s->off += len;
+ if (s->off >= s->ne0) {
+ s->off = 0;
+ s->row++;
+ }
+ return true;
+}
+
+static void pad_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+
+ uint32_t i1, i2, i3;
+ pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3);
+
+ const size_t bytes = (size_t) task->len * s->type_size;
+ const dma_addr_t dst = s->dst->data
+ + (size_t) i1 * s->nb1 + (size_t) i2 * s->nb2 + (size_t) i3 * s->nb3
+ + (size_t) task->off * s->type_size;
+
+ dma_queue_push(dma_q, dma_make_data(dst, out_spad), bytes, s->chunk_bytes_aligned, bytes, 1);
}
// ---------------------------------------------------------------------------
-// HVX + DMA PAD kernel - aligned, double-buffered
+// Constant (zero) PAD pipeline callbacks
// ---------------------------------------------------------------------------
-static void pad_job_per_hvx_hvx_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- const struct htp_pad_context * pctx = (const struct htp_pad_context *) data;
- struct htp_ops_context * octx = pctx->octx;
- htp_pad_preamble;
- htp_pad_dma_preamble;
-
- // -----------------------------------------------------------------------
- // Priming phase: push 2 pairs of (dummy_dst_DMA, src_DMA) to seed the
- // double-buffer pipeline before the main loop begins.
- // -----------------------------------------------------------------------
- for (uint32_t ir = row_start, spad_idx = 0; ir < row_end && spad_idx < 2; ir++, spad_idx++) {
- uint8_t * src_spad_cur = src_spad_base + spad_idx * src_row_size_aligned;
- uint8_t * dst_spad_cur = dst_spad_base + spad_idx * dst_row_size_aligned;
-
- dma_queue_push(dma_q,
- dma_make_data(dst->data, dst_spad_cur),
- dst_row_size, dst_row_size_aligned, dst_row_size, 0);
-
- uint32_t i1, i2, i3;
- pad_decompose_row(ir, ne1, ne2, pctx->kparams, &i1, &i2, &i3);
- const int interior = pad_is_interior(i1, i2, i3,
- lp1, rp1, ne1,
- lp2, rp2, ne2,
- lp3, rp3, ne3);
-
- const dma_addr_t src_data = interior
- ? pad_src_row_data(src, i1, i2, i3, lp1, lp2, lp3) : src->data;
-
- // Interior row: real DMA (1 row) from DDR to VTCM.
- // Border row: null DMA (nrows=0)
- dma_queue_push(dma_q,
- dma_make_data(src_spad_cur, src_data),
- src_row_size_aligned, src_row_size, src_row_size, interior ? 1 : 0);
+static void pad_const_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+
+ if (!task->aux) {
+ dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0);
+ return;
}
- // -----------------------------------------------------------------------
- // Main loop: pop completed DMAs, compute in VTCM with aligned HVX ops,
- // push dst DMA and prefetch src for the next+1 row.
- // -----------------------------------------------------------------------
- struct htp_thread_trace * tr = th->trace;
-
- for (uint32_t ir = row_start; ir < row_end; ir++) {
- uint8_t * dst_spad_cur = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * src_spad_cur = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- uint32_t i1, i2, i3;
- pad_decompose_row(ir, ne1, ne2, pctx->kparams, &i1, &i2, &i3);
-
- const dma_addr_t dst_data = dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3;
-
- const int interior = pad_is_interior(i1, i2, i3,
- lp1, rp1, ne1,
- lp2, rp2, ne2,
- lp3, rp3, ne3);
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- if (!interior) {
- hvx_splat_f32_a(dst_spad_cur, 0.0f, ne0);
- } else {
- hvx_splat_f32_a(dst_spad_cur, 0.0f, ne0);
-
- uint8_t * dst_interior = dst_spad_cur + (size_t)lp0 * type_size;
-
- if ((uintptr_t)dst_interior % VLEN == 0) {
- hvx_copy_f32_aa(dst_interior, src_spad_cur, ne00);
- } else {
- hvx_copy_f32_ua(dst_interior, src_spad_cur, ne00);
- }
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
-
- dma_queue_push(dma_q,
- dma_make_data(dst_data, dst_spad_cur),
- dst_row_size, dst_row_size_aligned, dst_row_size, 1);
-
- const uint32_t next_row = ir + 2;
- if (next_row < row_end) {
- uint32_t ni1, ni2, ni3;
- pad_decompose_row(next_row, ne1, ne2, pctx->kparams, &ni1, &ni2, &ni3);
- const int next_interior = pad_is_interior(ni1, ni2, ni3,
- lp1, rp1, ne1,
- lp2, rp2, ne2,
- lp3, rp3, ne3);
- const dma_addr_t next_src_data = next_interior
- ? pad_src_row_data(src, ni1, ni2, ni3, lp1, lp2, lp3) : src->data;
-
- dma_queue_push(dma_q,
- dma_make_data(src_spad_cur, next_src_data),
- src_row_size_aligned, src_row_size, src_row_size, next_interior ? 1 : 0);
- }
+ const uint32_t ov_start = MAX(task->off, (uint32_t) s->lp0);
+ const uint32_t ov_end = MIN(task->off + task->len, (uint32_t) s->lp0 + s->ne00);
+ if (ov_start >= ov_end) {
+ dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0);
+ return;
}
- dma_queue_flush(dma_q);
+ uint32_t i1, i2, i3;
+ pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3);
- FARF(HIGH, "pad-hvx-dma %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
- ith, nth,
- src->ne[0], src->ne[1], src->ne[2], src->ne[3],
- dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
- row_start, row_end);
+ const uint32_t copy_len = ov_end - ov_start;
+ const uint32_t src_off = ov_start - (uint32_t) s->lp0;
+ const size_t bytes = (size_t) copy_len * s->type_size;
+ const dma_addr_t src_addr = pad_src_row_data(s->src, i1, i2, i3, s->lp1, s->lp2, s->lp3)
+ + (size_t) src_off * s->type_size;
+
+ dma_queue_push(dma_q, dma_make_data(in_spad, src_addr), s->chunk_bytes_aligned, bytes, bytes, 1);
+}
+
+static void __attribute__((noinline)) pad_const_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+
+ const uint8_t * src_spad = (const uint8_t *) in_spad;
+ uint8_t * dst_spad = (uint8_t *) out_spad;
+ const uint32_t total_bytes = task->len * (uint32_t) s->type_size;
+
+ if (!task->aux) {
+ hvx_splat_u8_a(dst_spad, 0, total_bytes);
+ return;
+ }
+
+ const uint32_t ov_start = MAX(task->off, (uint32_t) s->lp0);
+ const uint32_t ov_end = MIN(task->off + task->len, (uint32_t) s->lp0 + s->ne00);
+ if (ov_start >= ov_end) {
+ hvx_splat_u8_a(dst_spad, 0, total_bytes);
+ return;
+ }
+
+ const uint32_t copy_len = ov_end - ov_start;
+ const uint32_t copy_bytes = copy_len * (uint32_t) s->type_size;
+ const uint32_t dst_off = ov_start - task->off;
+
+ if (copy_len < task->len) {
+ hvx_splat_u8_a(dst_spad, 0, total_bytes);
+ }
+
+ uint8_t * dst_interior = dst_spad + (size_t) dst_off * s->type_size;
+ if (((uintptr_t) dst_interior & (VLEN - 1)) == 0) {
+ hvx_copy_aa(dst_interior, src_spad, copy_bytes, 1);
+ } else {
+ hvx_copy_ua(dst_interior, src_spad, copy_bytes, 1);
+ }
}
// ---------------------------------------------------------------------------
-// HVX circular PAD kernel
+// Circular PAD pipeline callbacks
// ---------------------------------------------------------------------------
-static void pad_job_per_hvx_hvx_circular(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- const struct htp_pad_context * pctx = (const struct htp_pad_context *) data;
- struct htp_ops_context * octx = pctx->octx;
- htp_pad_preamble;
-
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
-
- for (uint32_t dst_row = row_start; dst_row < row_end; dst_row++) {
- uint32_t i1, i2, i3;
- pad_decompose_row(dst_row, ne1, ne2, pctx->kparams, &i1, &i2, &i3);
-
- uint8_t * dst_ptr = (uint8_t *) dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3;
- const uint8_t * src_row = pad_circ_src_row_ptr(src, pctx->kparams, i1, i2, i3, lp1, lp2, lp3);
-
- if (nb00 == type_size) {
-
- if (lp0 > 0) {
- if ((uint32_t)lp0 < 32) {
- memcpy(dst_ptr,
- src_row + (size_t)(ne00 - (uint32_t)lp0) * type_size,
- (size_t)lp0 * type_size);
- } else {
- hvx_copy_f32_uu(dst_ptr,
- src_row + (size_t)(ne00 - (uint32_t)lp0) * type_size,
- (uint32_t)lp0);
- }
- }
- hvx_copy_f32_uu(dst_ptr + (size_t)lp0 * type_size, src_row, ne00);
- if (rp0 > 0) {
- if ((uint32_t)rp0 < 32) {
- memcpy(dst_ptr + ((size_t)lp0 + ne00) * type_size,
- src_row,
- (size_t)rp0 * type_size);
- } else {
- hvx_copy_f32_uu(dst_ptr + ((size_t)lp0 + ne00) * type_size,
- src_row,
- (uint32_t)rp0);
- }
- }
- } else {
- for (uint32_t i = 0; i < (uint32_t)lp0; i++) {
- *(float *)(dst_ptr + i * type_size) =
- *(const float *)(src_row + (size_t)(ne00 - (uint32_t)lp0 + i) * nb00);
- }
- for (uint32_t i = 0; i < ne00; i++) {
- *(float *)(dst_ptr + ((size_t)lp0 + i) * type_size) =
- *(const float *)(src_row + (size_t)i * nb00);
- }
- for (uint32_t i = 0; i < (uint32_t)rp0; i++) {
- *(float *)(dst_ptr + ((size_t)lp0 + ne00 + i) * type_size) =
- *(const float *)(src_row + (size_t)i * nb00);
- }
- }
- }
+static void pad_circ_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
+ uint32_t i1, i2, i3;
+ pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3);
- FARF(HIGH, "pad-hvx-circ %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
- ith, nth,
- src->ne[0], src->ne[1], src->ne[2], src->ne[3],
- dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
- row_start, row_end);
+ const dma_addr_t src_row = pad_circ_src_row_data(s->src, s->kparams, i1, i2, i3, s->lp1, s->lp2, s->lp3);
+ const size_t bytes = (size_t) task->len * s->type_size;
+
+ dma_queue_push(dma_q,
+ dma_make_data(in_spad, src_row + (size_t) task->aux * s->type_size),
+ s->chunk_bytes_aligned, bytes, bytes, 1);
+}
+
+static void __attribute__((noinline)) pad_circ_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct pad_pipe_state * s = (struct pad_pipe_state *) ctx;
+
+ hvx_copy_aa((uint8_t *) out_spad, (const uint8_t *) in_spad, task->len * (uint32_t) s->type_size, 1);
}
// ---------------------------------------------------------------------------
-// HVX + DMA circular PAD kernel - aligned, double-buffered
+// Per thread workers
// ---------------------------------------------------------------------------
-static void pad_job_per_hvx_hvx_circular_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void pad_state_init(struct pad_pipe_state * s, const struct htp_pad_context * pctx,
+ uint32_t row_start, uint32_t row_end) {
+ struct htp_ops_context * octx = pctx->octx;
+ const struct htp_tensor * src = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
+
+ s->src = src;
+ s->dst = dst;
+ s->kparams = pctx->kparams;
+ s->type_size = pctx->type_size;
+ s->chunk_bytes_aligned = pctx->chunk_bytes_aligned;
+ s->lp0 = pctx->lp0; s->rp0 = pctx->rp0;
+ s->lp1 = pctx->lp1; s->rp1 = pctx->rp1;
+ s->lp2 = pctx->lp2; s->rp2 = pctx->rp2;
+ s->lp3 = pctx->lp3; s->rp3 = pctx->rp3;
+ s->ne00 = src->ne[0];
+ s->ne0 = dst->ne[0];
+ s->ne1 = dst->ne[1];
+ s->ne2 = dst->ne[2];
+ s->ne3 = dst->ne[3];
+ s->nb1 = dst->nb[1];
+ s->nb2 = dst->nb[2];
+ s->nb3 = dst->nb[3];
+ s->chunk_elems = pctx->chunk_elems;
+ s->row = row_start;
+ s->row_end = row_end;
+ s->off = 0;
+}
+
+static void pad_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
const struct htp_pad_context * pctx = (const struct htp_pad_context *) data;
- struct htp_ops_context * octx = pctx->octx;
- htp_pad_preamble;
- htp_pad_dma_preamble;
-
- // -----------------------------------------------------------------------
- // Priming phase: push 2 pairs of (dummy_dst_DMA, src_DMA) to seed the
- // double-buffer pipeline. Every row is a real src DMA (no null DMAs).
- // -----------------------------------------------------------------------
- for (uint32_t ir = row_start, spad_idx = 0; ir < row_end && spad_idx < 2; ir++, spad_idx++) {
- uint8_t * src_spad_cur = src_spad_base + spad_idx * src_row_size_aligned;
- uint8_t * dst_spad_cur = dst_spad_base + spad_idx * dst_row_size_aligned;
-
- dma_queue_push(dma_q,
- dma_make_data(dst->data, dst_spad_cur),
- dst_row_size, dst_row_size_aligned, dst_row_size, 0);
-
- uint32_t pi1, pi2, pi3;
- pad_decompose_row(ir, ne1, ne2, pctx->kparams, &pi1, &pi2, &pi3);
- const dma_addr_t src_data = pad_circ_src_row_data(src, pctx->kparams, pi1, pi2, pi3, lp1, lp2, lp3);
- dma_queue_push(dma_q,
- dma_make_data(src_spad_cur, src_data),
- src_row_size_aligned, src_row_size, src_row_size, 1);
+
+ const uint32_t row_start = pctx->row_start + pctx->nrows_per_hvx * ith;
+ const uint32_t row_end = MIN(row_start + pctx->nrows_per_hvx, pctx->row_start + pctx->total_dst_rows);
+
+ if (row_start >= row_end) {
+ return;
}
- // -----------------------------------------------------------------------
- // Main loop: pop completed DMAs, assemble circular row in VTCM with
- // aligned HVX ops, push dst DMA and prefetch src for the next+1 row.
- // -----------------------------------------------------------------------
- struct htp_thread_trace * tr = th->trace;
-
- for (uint32_t ir = row_start; ir < row_end; ir++) {
- uint8_t * dst_spad_cur = (uint8_t *) dma_queue_pop(dma_q).src;
- uint8_t * src_spad_cur = (uint8_t *) dma_queue_pop(dma_q).dst;
-
- uint32_t i1, i2, i3;
- pad_decompose_row(ir, ne1, ne2, pctx->kparams, &i1, &i2, &i3);
- const dma_addr_t dst_data = dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3;
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- if (lp0 > 0) {
- uint8_t * dst_left = dst_spad_cur;
- const uint8_t * src_left = src_spad_cur + (size_t)(ne00 - (uint32_t)lp0) * type_size;
- if ((uint32_t)lp0 < 32) {
- memcpy(dst_left, src_left, (size_t)lp0 * type_size);
- } else {
- hvx_copy_f32_uu(dst_left, src_left, (uint32_t)lp0);
- }
- }
-
- {
- uint8_t * dst_mid = dst_spad_cur + (size_t)lp0 * type_size;
- if ((uintptr_t)dst_mid % VLEN == 0) {
- hvx_copy_f32_aa(dst_mid, src_spad_cur, ne00);
- } else {
- hvx_copy_f32_ua(dst_mid, src_spad_cur, ne00);
- }
- }
-
- if (rp0 > 0) {
- uint8_t * dst_right = dst_spad_cur + ((size_t)lp0 + ne00) * type_size;
- if ((uint32_t)rp0 < 32) {
- memcpy(dst_right, src_spad_cur, (size_t)rp0 * type_size);
- } else {
- if ((uintptr_t)dst_right % VLEN == 0) {
- hvx_copy_f32_aa(dst_right, src_spad_cur, (uint32_t)rp0);
- } else {
- hvx_copy_f32_ua(dst_right, src_spad_cur, (uint32_t)rp0);
- }
- }
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
-
- dma_queue_push(dma_q,
- dma_make_data(dst_data, dst_spad_cur),
- dst_row_size, dst_row_size_aligned, dst_row_size, 1);
-
- const uint32_t next_row = ir + 2;
- if (next_row < row_end) {
- uint32_t nri1, nri2, nri3;
- pad_decompose_row(next_row, ne1, ne2, pctx->kparams, &nri1, &nri2, &nri3);
- const dma_addr_t next_src_data = pad_circ_src_row_data(src, pctx->kparams, nri1, nri2, nri3, lp1, lp2, lp3);
- dma_queue_push(dma_q,
- dma_make_data(src_spad_cur, next_src_data),
- src_row_size_aligned, src_row_size, src_row_size, 1);
- }
+ uint8_t * src_spad = pctx->vtcm_src0 + ith * pctx->src0_bytes_per_hvx;
+ uint8_t * dst_spad = pctx->vtcm_dst + ith * pctx->dst_bytes_per_hvx;
+ void * in_buf[2] = { src_spad, src_spad + pctx->chunk_bytes_aligned };
+ void * out_buf[2] = { dst_spad, dst_spad + pctx->chunk_bytes_aligned };
+
+ struct pad_pipe_state s;
+ pad_state_init(&s, pctx, row_start, row_end);
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, pad_const_next_task, pad_const_push_in, pad_const_compute, pad_push_out);
+
+ FARF(HIGH, "pad-hvx %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
+ ith, nth,
+ s.src->ne[0], s.src->ne[1], s.src->ne[2], s.src->ne[3],
+ s.dst->ne[0], s.dst->ne[1], s.dst->ne[2], s.dst->ne[3],
+ row_start, row_end);
+}
+
+static void pad_thread_circular(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ const struct htp_pad_context * pctx = (const struct htp_pad_context *) data;
+
+ const uint32_t row_start = pctx->row_start + pctx->nrows_per_hvx * ith;
+ const uint32_t row_end = MIN(row_start + pctx->nrows_per_hvx, pctx->row_start + pctx->total_dst_rows);
+
+ if (row_start >= row_end) {
+ return;
}
- dma_queue_flush(dma_q);
+ uint8_t * src_spad = pctx->vtcm_src0 + ith * pctx->src0_bytes_per_hvx;
+ uint8_t * dst_spad = pctx->vtcm_dst + ith * pctx->dst_bytes_per_hvx;
+ void * in_buf[2] = { src_spad, src_spad + pctx->chunk_bytes_aligned };
+ void * out_buf[2] = { dst_spad, dst_spad + pctx->chunk_bytes_aligned };
+
+ struct pad_pipe_state s;
+ pad_state_init(&s, pctx, row_start, row_end);
- FARF(HIGH, "pad-hvx-circ-dma %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, pad_circ_next_task, pad_circ_push_in, pad_circ_compute, pad_push_out);
+
+ FARF(HIGH, "pad-hvx-circ %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
ith, nth,
- src->ne[0], src->ne[1], src->ne[2], src->ne[3],
- dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
+ s.src->ne[0], s.src->ne[1], s.src->ne[2], s.src->ne[3],
+ s.dst->ne[0], s.dst->ne[1], s.dst->ne[2], s.dst->ne[3],
row_start, row_end);
}
@@ -491,6 +383,10 @@ int op_pad(struct htp_ops_context * octx) {
const struct htp_pad_kernel_params * kparams =
(const struct htp_pad_kernel_params *) octx->kernel_params;
+ if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || dst->type != src0->type) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
const int32_t lp0 = octx->op_params[0];
const int32_t rp0 = octx->op_params[1];
const int32_t lp1 = octx->op_params[2];
@@ -499,20 +395,15 @@ int op_pad(struct htp_ops_context * octx) {
const int32_t rp2 = octx->op_params[5];
const int32_t lp3 = octx->op_params[6];
const int32_t rp3 = octx->op_params[7];
- const int32_t circular = octx->op_params[8];
const uint32_t total_dst_rows = kparams->total_rows;
const size_t type_size = kparams->elem_size;
- const size_t src_row_size = src0->ne[0] * type_size;
- const size_t dst_row_size = dst->ne[0] * type_size;
uint32_t row_start = 0;
uint32_t nrows = total_dst_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, type_size, (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_dst_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_dst_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -527,60 +418,40 @@ int op_pad(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
- if (!kparams->use_dma && (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst))) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
struct htp_pad_vtcm_layout layout = { 0 };
- if (kparams->use_dma) {
- htp_pad_vtcm_layout_build(&layout, src_row_size, dst_row_size, n_hvx);
-
- octx->src0_spad.size_per_hvx = layout.src0_bytes_per_hvx;
- octx->dst_spad.size_per_hvx = layout.dst_bytes_per_hvx;
- octx->src0_spad.size = n_hvx * layout.src0_bytes_per_hvx;
- octx->dst_spad.size = n_hvx * layout.dst_bytes_per_hvx;
- octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0);
- octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst);
- octx->src0_spad.src = NULL;
- octx->dst_spad.src = NULL;
- }
+ htp_pad_vtcm_layout_build(&layout, (size_t) kparams->chunk_elems * type_size, n_hvx);
struct htp_pad_context pctx = {
- .octx = octx,
- .kparams = kparams,
+ .octx = octx,
+ .kparams = kparams,
+ .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0),
+ .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst),
+ .src0_bytes_per_hvx = layout.src0_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
.lp0 = lp0, .rp0 = rp0,
.lp1 = lp1, .rp1 = rp1,
.lp2 = lp2, .rp2 = rp2,
.lp3 = lp3, .rp3 = rp3,
- .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
- .total_dst_rows = nrows,
- .row_start = row_start,
- .type_size = type_size,
- .src_row_size = src_row_size,
- .src_row_size_aligned = layout.src_row_size_aligned,
- .dst_row_size = dst_row_size,
- .dst_row_size_aligned = layout.dst_row_size_aligned,
+ .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
+ .total_dst_rows = nrows,
+ .row_start = row_start,
+ .chunk_elems = kparams->chunk_elems,
+ .type_size = type_size,
+ .chunk_bytes_aligned = layout.chunk_bytes_aligned,
};
- FARF(HIGH, "pad-hvx%s%s: (%ux%ux%ux%u) -> (%ux%ux%ux%u) pads=(%d,%d,%d,%d,%d,%d,%d,%d)\n",
- circular ? "-circ" : "",
- kparams->use_dma ? "-dma" : "",
+ FARF(HIGH, "pad-hvx%s: (%ux%ux%ux%u) -> (%ux%ux%ux%u) pads=(%d,%d,%d,%d,%d,%d,%d,%d)\n",
+ circular ? "-circ" : "",
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
lp0, rp0, lp1, rp1, lp2, rp2, lp3, rp3);
switch (kparams->kernel_type) {
- case HTP_PAD_KERNEL_HVX_CIRCULAR_DMA:
- work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx_circular_dma, &pctx, n_hvx);
- break;
case HTP_PAD_KERNEL_HVX_CIRCULAR:
- work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx_circular, &pctx, n_hvx);
- break;
- case HTP_PAD_KERNEL_HVX_DMA:
- work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx_dma, &pctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, pad_thread_circular, &pctx, n_hvx);
break;
default:
- work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx, &pctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, pad_thread, &pctx, n_hvx);
break;
}
diff --git a/ggml/src/ggml-hexagon/htp/pad-ops.h b/ggml/src/ggml-hexagon/htp/pad-ops.h
index 15357e5f6..da0404f96 100644
--- a/ggml/src/ggml-hexagon/htp/pad-ops.h
+++ b/ggml/src/ggml-hexagon/htp/pad-ops.h
@@ -7,32 +7,27 @@
#include <stdint.h>
enum htp_pad_kernel_type {
- HTP_PAD_KERNEL_HVX = 0,
- HTP_PAD_KERNEL_HVX_DMA = 1,
- HTP_PAD_KERNEL_HVX_CIRCULAR = 2,
- HTP_PAD_KERNEL_HVX_CIRCULAR_DMA = 3,
+ HTP_PAD_KERNEL_HVX = 0,
+ HTP_PAD_KERNEL_HVX_CIRCULAR = 1,
};
struct htp_pad_vtcm_layout {
size_t total_bytes;
size_t off_src0;
size_t off_dst;
- size_t src_row_size_aligned;
- size_t dst_row_size_aligned;
+ size_t chunk_bytes_aligned;
size_t src0_bytes_per_hvx;
size_t dst_bytes_per_hvx;
};
static inline void htp_pad_vtcm_layout_build(
struct htp_pad_vtcm_layout * L,
- size_t src_row_size,
- size_t dst_row_size,
+ size_t chunk_bytes,
uint32_t n_hvx
) {
- L->src_row_size_aligned = hex_round_up(src_row_size, 128);
- L->dst_row_size_aligned = hex_round_up(dst_row_size, 128);
- L->src0_bytes_per_hvx = 2 * L->src_row_size_aligned;
- L->dst_bytes_per_hvx = 2 * L->dst_row_size_aligned;
+ L->chunk_bytes_aligned = hex_round_up(chunk_bytes, 128);
+ L->src0_bytes_per_hvx = 2 * L->chunk_bytes_aligned;
+ L->dst_bytes_per_hvx = 2 * L->chunk_bytes_aligned;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
@@ -45,7 +40,7 @@ struct htp_pad_kernel_params {
uint8_t kernel_type;
uint32_t n_hvx;
uint32_t total_rows;
- uint32_t use_dma;
+ uint32_t chunk_elems;
uint32_t elem_size;
uint32_t vtcm_size;
diff --git a/ggml/src/ggml-hexagon/htp/pool-ops.c b/ggml/src/ggml-hexagon/htp/pool-ops.c
index 12cd8ea90..55bf27416 100644
--- a/ggml/src/ggml-hexagon/htp/pool-ops.c
+++ b/ggml/src/ggml-hexagon/htp/pool-ops.c
@@ -1,10 +1,9 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-
#include <float.h>
#include <HAP_farf.h>
#include "hex-common.h"
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "htp-trace.h"
#include "htp-ctx.h"
#include "htp-ops.h"
@@ -147,9 +146,13 @@ static inline void pool_pixel_boundary_vec(
HVX_Vector acc = mask_identity;
for (uint32_t ky = ky_lo; ky < ky_hi; ++ky) {
const float * row = src + (uint32_t) (iy0 + (int32_t) ky) * p->src_x;
- for (uint32_t k = 0; k < valid_kx; k += VLEN_FP32) {
- const uint32_t k_rem = valid_kx - k;
- const uint32_t n = (k_rem < VLEN_FP32) ? k_rem : VLEN_FP32;
+ uint32_t k = 0;
+ for (; k + VLEN_FP32 <= valid_kx; k += VLEN_FP32) {
+ const HVX_Vector v = *(const HVX_UVector *) (row + ix0 + kx_lo + k);
+ acc = is_max ? Q6_Vsf_vmax_VsfVsf(acc, v) : hvx_vec_add_f32_f32(acc, v);
+ }
+ if (k < valid_kx) {
+ const uint32_t n = valid_kx - k;
const HVX_VectorPred q = Q6_Q_vsetq_R(n * sizeof(float));
const HVX_Vector raw = *(const HVX_UVector *) (row + ix0 + kx_lo + k);
const HVX_Vector v = Q6_V_vmux_QVV(q, raw, mask_identity);
@@ -255,13 +258,57 @@ struct pool_2d_context {
uint32_t planes_per_hvx;
};
+struct pool_pipe_state {
+ dma_addr_t src_data;
+ dma_addr_t dst_data;
+ const struct htp_pool_2d_kernel_params * kparams;
+ pool_plane_fn_t pool_plane;
+ uint32_t src_plane_bytes;
+ uint32_t dst_plane_bytes;
+ uint32_t src_spad_half;
+ uint32_t dst_spad_half;
+ uint32_t plane;
+ uint32_t plane_end;
+};
+
+static bool pool_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct pool_pipe_state * s = (struct pool_pipe_state *) ctx;
+ if (s->plane >= s->plane_end) {
+ return false;
+ }
+ task->row = s->plane++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
+
+static void pool_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct pool_pipe_state * s = (struct pool_pipe_state *) ctx;
+ const dma_addr_t src_addr = s->src_data + (size_t) task->row * s->src_plane_bytes;
+ dma_queue_push(dma_q, dma_make_data(in_spad, src_addr),
+ s->src_spad_half, s->src_plane_bytes, s->src_plane_bytes, 1);
+}
+
+static void pool_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ (void) task;
+ struct pool_pipe_state * s = (struct pool_pipe_state *) ctx;
+ s->pool_plane((const float *) in_spad, (float *) out_spad, s->kparams);
+}
+
+static void pool_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct pool_pipe_state * s = (struct pool_pipe_state *) ctx;
+ const dma_addr_t dst_addr = s->dst_data + (size_t) task->row * s->dst_plane_bytes;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->dst_plane_bytes, s->dst_spad_half, s->dst_plane_bytes, 1);
+}
+
static void pool_2d_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct pool_2d_context * ctx = (struct pool_2d_context *) data;
const struct htp_pool_2d_kernel_params * p = ctx->kparams;
const struct htp_pool_vtcm_layout * L = &ctx->layout;
const struct htp_tensor * src0 = ctx->octx->src[0];
const struct htp_tensor * dst = ctx->octx->dst;
- pool_plane_fn_t pool_plane = ctx->pool_plane;
const uint32_t planes_per_hvx = ctx->planes_per_hvx;
const uint32_t first = ctx->plane_start + ith * planes_per_hvx;
const uint32_t last = MIN(first + planes_per_hvx, ctx->plane_start + ctx->plane_count);
@@ -270,75 +317,38 @@ static void pool_2d_thread(const htp_thread_t * th, unsigned int nth, unsigned i
return;
}
- struct htp_thread_trace * tr = th->trace;
- dma_queue * dma_queue = th->dma_q;
-
- const uint32_t src_plane_bytes = L->src_plane_bytes;
- const uint32_t dst_plane_bytes = L->dst_plane_bytes;
- const uint32_t src_spad_half = (uint32_t) L->src_spad_half_size;
- const uint32_t dst_spad_half = (uint32_t) L->dst_spad_half_size;
+ const uint32_t src_spad_half = (uint32_t) L->src_spad_half_size;
+ const uint32_t dst_spad_half = (uint32_t) L->dst_spad_half_size;
uint8_t * vtcm_base = (uint8_t *) ctx->octx->ctx->vtcm_base;
uint8_t * src_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_src) + ith * L->src_bytes_per_hvx;
uint8_t * dst_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_dst) + ith * L->dst_bytes_per_hvx;
- float * srcb2[2] = { (float *) src_spad, (float *) (src_spad + src_spad_half) };
- float * dstb2[2] = { (float *) dst_spad, (float *) (dst_spad + dst_spad_half) };
-
- const uint32_t total = last - first;
-
- // Warm up the pipeline: push up to 2 initial (dummy dst, src) transfer pairs.
- for (uint32_t i = 0; i < total && i < 2; ++i) {
- dma_queue_push(dma_queue,
- dma_make_data(dst->data, dstb2[i]),
- dst_plane_bytes, dst_spad_half,
- dst_plane_bytes, 0);
-
- const dma_addr_t src_addr = src0->data + (first + i) * src_plane_bytes;
- dma_queue_push(dma_queue,
- dma_make_data(srcb2[i], src_addr),
- src_spad_half, src_plane_bytes,
- src_plane_bytes, 1);
- }
-
- for (uint32_t i = 0; i < total; ++i) {
- const uint32_t plane = first + i;
- const uint32_t buf = i & 1u;
- float * srcb = srcb2[buf];
- float * dstb = dstb2[buf];
-
- dma_queue_pop(dma_queue); // dst writeback from plane i - 2 (or dummy on iter 0, 1)
- dma_queue_pop(dma_queue); // input for plane i
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) plane);
- pool_plane(srcb, dstb, p);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) plane);
-
- const dma_addr_t dst_addr = dst->data + plane * dst_plane_bytes;
- dma_queue_push(dma_queue,
- dma_make_data(dst_addr, dstb),
- dst_plane_bytes, dst_spad_half,
- dst_plane_bytes, 1);
-
- if (i + 2 < total) {
- const dma_addr_t next_src_addr = src0->data + (plane + 2) * src_plane_bytes;
- dma_queue_push(dma_queue,
- dma_make_data(srcb, next_src_addr),
- src_spad_half, src_plane_bytes,
- src_plane_bytes, 1);
- }
- }
+ void * in_buf[2] = { src_spad, src_spad + src_spad_half };
+ void * out_buf[2] = { dst_spad, dst_spad + dst_spad_half };
+
+ struct pool_pipe_state s = {
+ .src_data = src0->data,
+ .dst_data = dst->data,
+ .kparams = p,
+ .pool_plane = ctx->pool_plane,
+ .src_plane_bytes = L->src_plane_bytes,
+ .dst_plane_bytes = L->dst_plane_bytes,
+ .src_spad_half = src_spad_half,
+ .dst_spad_half = dst_spad_half,
+ .plane = first,
+ .plane_end = last,
+ };
- dma_queue_flush(dma_queue);
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, pool_next_task, pool_push_in, pool_compute, pool_push_out);
- FARF(HIGH, "pool2d-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n",
+ FARF(HIGH, "pool2d-f32 %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n",
ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], first, last);
(void) nth;
}
int op_pool_2d(struct htp_ops_context * octx) {
- const struct htp_tensor * dst = octx->dst;
const struct htp_pool_2d_kernel_params * p =
(const struct htp_pool_2d_kernel_params *) octx->kernel_params;
@@ -346,7 +356,7 @@ int op_pool_2d(struct htp_ops_context * octx) {
uint32_t plane_count = p->planes;
if (octx->ctx->mdev.count > 1) {
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- plane_count, htp_tensor_mdev_data_aligned(dst) ? p->planes_per_chunk : 0,
+ plane_count, 1,
octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
plane_start = range.start;
plane_count = range.count;
diff --git a/ggml/src/ggml-hexagon/htp/pool-ops.h b/ggml/src/ggml-hexagon/htp/pool-ops.h
index e113bb9dd..1e379bef5 100644
--- a/ggml/src/ggml-hexagon/htp/pool-ops.h
+++ b/ggml/src/ggml-hexagon/htp/pool-ops.h
@@ -31,7 +31,6 @@ struct htp_pool_2d_kernel_params {
int32_t pad_y;
uint32_t n_hvx;
uint32_t planes;
- uint32_t planes_per_chunk;
uint32_t pool_op;
uint32_t avg_divide_count;
uint32_t ox_lo;
diff --git a/ggml/src/ggml-hexagon/htp/repeat-ops.c b/ggml/src/ggml-hexagon/htp/repeat-ops.c
index a9e4d5c86..43326232b 100644
--- a/ggml/src/ggml-hexagon/htp/repeat-ops.c
+++ b/ggml/src/ggml-hexagon/htp/repeat-ops.c
@@ -1,12 +1,11 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
+#include <math.h>
#include <string.h>
+#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hvx-utils.h"
#define GGML_COMMON_DECL_C
@@ -16,49 +15,241 @@
#include "htp-trace.h"
#include "htp-ops.h"
#include "htp-tensor.h"
+#include "htp-vtcm.h"
#include "repeat-ops.h"
+typedef void (*repeat_fill_vtcm_fn_t)(
+ uint8_t * restrict dst_vtcm,
+ const uint8_t * restrict src_vtcm,
+ uint32_t n_elems,
+ uint32_t reps,
+ uint32_t dst_elem_size
+);
+
struct htp_repeat_context {
- struct htp_ops_context * octx;
+ struct htp_ops_context * octx;
const struct htp_repeat_kernel_params * kparams;
+ repeat_fill_vtcm_fn_t fill_vtcm;
+
+ dma_addr_t data_src;
+ dma_addr_t data_dst;
+ uint8_t * vtcm_src;
+ uint8_t * vtcm_dst;
+ size_t src_buf_bytes;
+ size_t dst_buf_bytes;
+ size_t src_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
uint32_t nrows_per_hvx;
- uint32_t total_dst_rows; // ne1 * ne2 * ne3
+ uint32_t total_dst_rows;
uint32_t row_start;
-
- size_t type_size;
+ uint32_t src_elem_size;
+ uint32_t dst_elem_size;
+ uint32_t tile_elems;
+ uint32_t dst_reps;
};
-static void repeat_job_per_hvx(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- const struct htp_repeat_context * rctx = (const struct htp_repeat_context *) data;
- struct htp_ops_context * octx = rctx->octx;
+static inline void repeat_row_addrs(
+ const struct htp_repeat_context * rctx,
+ const struct htp_tensor * src,
+ const struct htp_tensor * dst,
+ uint32_t dst_row,
+ dma_addr_t * src_addr,
+ dma_addr_t * dst_addr
+) {
const struct htp_repeat_kernel_params * kparams = rctx->kparams;
- const struct htp_tensor * src = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
+ const uint32_t dst_row_div_ne1 = fastdiv(dst_row, &kparams->div_ne1);
+ const uint32_t i1 = dst_row - dst_row_div_ne1 * dst->ne[1];
+ const uint32_t i3 = fastdiv(dst_row, &kparams->div_ne12);
+ const uint32_t i2 = dst_row_div_ne1 - i3 * dst->ne[2];
+
+ const uint32_t k1 = fastmodulo(i1, src->ne[1], &kparams->div_ne01);
+ const uint32_t k2 = fastmodulo(i2, src->ne[2], &kparams->div_ne02);
+ const uint32_t k3 = fastmodulo(i3, src->ne[3], &kparams->div_ne03);
+
+ *src_addr = rctx->data_src + (size_t) k1 * src->nb[1] + (size_t) k2 * src->nb[2] + (size_t) k3 * src->nb[3];
+ *dst_addr = rctx->data_dst + (size_t) i1 * dst->nb[1] + (size_t) i2 * dst->nb[2] + (size_t) i3 * dst->nb[3];
+}
+
+static inline HVX_Vector repeat_clamp_f16_finite(HVX_Vector v) {
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ const HVX_Vector inf = hvx_vec_splat_f32(INFINITY);
+ const HVX_VectorPred finite = Q6_Q_vcmp_gt_VsfVsf(inf, hvx_vec_abs_f32(v));
+ const HVX_VectorPred high = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(v, max_f16));
+ const HVX_VectorPred low = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(min_f16, v));
+ v = Q6_V_vmux_QVV(high, max_f16, v);
+ return Q6_V_vmux_QVV(low, min_f16, v);
+}
+
+static inline void repeat_row_f32_to_f16_a(uint8_t * restrict dst_ptr, const uint8_t * restrict src_ptr, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src_ptr;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst_ptr;
+
+ const uint32_t n_vec = n / 64;
+ const uint32_t n_rem = n % 64;
+
+ for (uint32_t i = 0; i < n_vec; i++) {
+ const HVX_Vector v0 = repeat_clamp_f16_finite(vsrc[2 * i + 0]);
+ const HVX_Vector v1 = repeat_clamp_f16_finite(vsrc[2 * i + 1]);
+ vdst[i] = hvx_vec_f32_to_f16(v0, v1);
+ }
+
+ if (n_rem > 0) {
+ const HVX_Vector v0 = repeat_clamp_f16_finite(vsrc[2 * n_vec + 0]);
+ const HVX_Vector v1 = (n_rem > 32) ? repeat_clamp_f16_finite(vsrc[2 * n_vec + 1]) : Q6_V_vzero();
+ const HVX_Vector v = hvx_vec_f32_to_f16(v0, v1);
+ hvx_vec_store_a(&vdst[n_vec], n_rem * sizeof(__fp16), v);
+ }
+}
+
+static void __attribute__((noinline)) repeat_fill_vtcm_same(
+ uint8_t * restrict dst_vtcm,
+ const uint8_t * restrict src_vtcm,
+ uint32_t n_elems,
+ uint32_t reps,
+ uint32_t dst_elem_size
+) {
+ const uint32_t unit_bytes = n_elems * dst_elem_size;
+ if (reps == 1) {
+ hvx_copy_aa(dst_vtcm, src_vtcm, unit_bytes, 1);
+ return;
+ }
+
+ if (n_elems == 1) {
+ const int32_t bits = Q6_R_vextract_VR(hvx_vmem(src_vtcm), 0);
+ const HVX_Vector sv = (dst_elem_size == 2) ? Q6_Vh_vsplat_R(bits) : Q6_V_vsplat_R(bits);
+ hvx_splat_a(dst_vtcm, sv, reps * dst_elem_size, 1);
+ return;
+ }
+
+ hvx_copy_aa(dst_vtcm, src_vtcm, unit_bytes, 1);
+ for (uint32_t r = 1; r < reps; r++) {
+ hvx_copy_ua(dst_vtcm + (size_t) r * unit_bytes, src_vtcm, unit_bytes, 1);
+ }
+}
+
+static void __attribute__((noinline)) repeat_fill_vtcm_f32_to_f16(
+ uint8_t * restrict dst_vtcm,
+ const uint8_t * restrict src_vtcm,
+ uint32_t n_elems,
+ uint32_t reps,
+ uint32_t dst_elem_size
+) {
+ (void) dst_elem_size;
+ repeat_row_f32_to_f16_a(dst_vtcm, src_vtcm, n_elems);
+ if (reps == 1) {
+ return;
+ }
+
+ if (n_elems == 1) {
+ const int32_t bits = Q6_R_vextract_VR(hvx_vmem(dst_vtcm), 0);
+ hvx_splat_a(dst_vtcm, Q6_Vh_vsplat_R(bits), reps, sizeof(__fp16));
+ return;
+ }
+
+ const size_t unit_bytes = (size_t) n_elems * sizeof(__fp16);
+ for (uint32_t r = 1; r < reps; r++) {
+ hvx_copy_f16_ua(dst_vtcm + (size_t) r * unit_bytes, dst_vtcm, n_elems);
+ }
+}
+
+struct repeat_pipe_state {
+ const struct htp_repeat_context * rctx;
+ const struct htp_tensor * src;
+ const struct htp_tensor * dst;
+ repeat_fill_vtcm_fn_t fill_vtcm;
+ size_t src_row_bytes;
+ size_t dst_row_bytes;
+ size_t src_buf_bytes;
+ size_t dst_buf_bytes;
+ uint32_t ne00;
+ uint32_t nr0;
+ uint32_t dst_elem_size;
+ uint32_t row;
+ uint32_t row_end;
+};
+
+static bool repeat_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx;
+ if (s->row >= s->row_end) {
+ return false;
+ }
+ task->row = s->row++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
+
+static void repeat_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx;
+ dma_addr_t src_addr, dst_addr;
+ repeat_row_addrs(s->rctx, s->src, s->dst, task->row, &src_addr, &dst_addr);
+ dma_queue_push(dma_q, dma_make_data(in_spad, src_addr),
+ s->src_buf_bytes, s->src_row_bytes, s->src_row_bytes, 1);
+}
+
+static void repeat_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ (void) task;
+ struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx;
+ s->fill_vtcm((uint8_t *) out_spad, (const uint8_t *) in_spad, s->ne00, s->nr0, s->dst_elem_size);
+}
- const uint32_t ne00 = src->ne[0];
- const uint32_t ne01 = src->ne[1];
- const uint32_t ne02 = src->ne[2];
- const uint32_t ne03 = src->ne[3];
+static void repeat_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx;
+ dma_addr_t src_addr, dst_addr;
+ repeat_row_addrs(s->rctx, s->src, s->dst, task->row, &src_addr, &dst_addr);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->dst_row_bytes, s->dst_buf_bytes, s->dst_row_bytes, 1);
+}
+
+static void repeat_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ const struct htp_repeat_context * rctx = (const struct htp_repeat_context *) data;
+ struct htp_ops_context * octx = rctx->octx;
+ const struct htp_tensor * src = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
- const uint32_t nb00 = src->nb[0];
- const uint32_t nb01 = src->nb[1];
- const uint32_t nb02 = src->nb[2];
- const uint32_t nb03 = src->nb[3];
+ const uint32_t row_start = rctx->row_start + rctx->nrows_per_hvx * ith;
+ const uint32_t row_end = MIN(row_start + rctx->nrows_per_hvx, rctx->row_start + rctx->total_dst_rows);
+ if (row_start >= row_end) {
+ return;
+ }
- const uint32_t ne0 = dst->ne[0];
- const uint32_t ne1 = dst->ne[1];
- const uint32_t ne2 = dst->ne[2];
- const uint32_t ne3 = dst->ne[3];
+ uint8_t * src_vtcm_base = rctx->vtcm_src + ith * rctx->src_bytes_per_hvx;
+ uint8_t * dst_vtcm_base = rctx->vtcm_dst + ith * rctx->dst_bytes_per_hvx;
+ void * in_buf[2] = { src_vtcm_base, src_vtcm_base + rctx->src_buf_bytes };
+ void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + rctx->dst_buf_bytes };
+
+ struct repeat_pipe_state s = {
+ .rctx = rctx,
+ .src = src,
+ .dst = dst,
+ .fill_vtcm = rctx->fill_vtcm,
+ .src_row_bytes = (size_t) src->ne[0] * rctx->src_elem_size,
+ .dst_row_bytes = (size_t) dst->ne[0] * rctx->dst_elem_size,
+ .src_buf_bytes = rctx->src_buf_bytes,
+ .dst_buf_bytes = rctx->dst_buf_bytes,
+ .ne00 = src->ne[0],
+ .nr0 = rctx->kparams->nr0,
+ .dst_elem_size = rctx->dst_elem_size,
+ .row = row_start,
+ .row_end = row_end,
+ };
- const uint32_t nb0 = dst->nb[0];
- const uint32_t nb1 = dst->nb[1];
- const uint32_t nb2 = dst->nb[2];
- const uint32_t nb3 = dst->nb[3];
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, repeat_next_task, repeat_push_in, repeat_compute, repeat_push_out);
- const uint32_t nr0 = kparams->nr0;
+ FARF(HIGH, "repeat %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
+ ith, nth, src->ne[0], src->ne[1], src->ne[2], src->ne[3],
+ dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
+ row_start, row_end);
+}
- const size_t row_bytes = ne00 * rctx->type_size;
+static void repeat_thread_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ const struct htp_repeat_context * rctx = (const struct htp_repeat_context *) data;
+ struct htp_ops_context * octx = rctx->octx;
+ const struct htp_tensor * src = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
const uint32_t row_start = rctx->row_start + rctx->nrows_per_hvx * ith;
const uint32_t row_end = MIN(row_start + rctx->nrows_per_hvx, rctx->row_start + rctx->total_dst_rows);
@@ -66,34 +257,61 @@ static void repeat_job_per_hvx(const htp_thread_t * th, unsigned int nth, unsign
return;
}
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
+ const uint32_t ne00 = src->ne[0];
+ const uint32_t nr0 = rctx->kparams->nr0;
+ const uint32_t src_elem_size = rctx->src_elem_size;
+ const uint32_t dst_elem_size = rctx->dst_elem_size;
+ const uint32_t tile_elems = rctx->tile_elems;
+ const uint32_t dst_reps = rctx->dst_reps;
- for (uint32_t dst_row = row_start; dst_row < row_end; dst_row++) {
- // Decompose flat dst row index into (i1, i2, i3)
- const uint32_t dst_row_div_ne1 = fastdiv(dst_row, &kparams->div_ne1);
- const uint32_t i1 = dst_row - dst_row_div_ne1 * ne1;
- const uint32_t i3 = fastdiv(dst_row, &kparams->div_ne12);
- const uint32_t i2 = dst_row_div_ne1 - i3 * ne2;
+ uint8_t * src_vtcm = rctx->vtcm_src + ith * rctx->src_bytes_per_hvx;
+ uint8_t * dst_vtcm = rctx->vtcm_dst + ith * rctx->dst_bytes_per_hvx;
- // Map to source indices (tiling)
- const uint32_t k1 = fastmodulo(i1, ne01, &kparams->div_ne01);
- const uint32_t k2 = fastmodulo(i2, ne02, &kparams->div_ne02);
- const uint32_t k3 = fastmodulo(i3, ne03, &kparams->div_ne03);
+ dma_queue * dma_q = th->dma_q;
+ struct htp_thread_trace * tr = th->trace;
+ const repeat_fill_vtcm_fn_t fill_vtcm = rctx->fill_vtcm;
- const uint8_t * src_row = (const uint8_t *) src->data + k1 * nb01 + k2 * nb02 + k3 * nb03;
- uint8_t * dst_base = (uint8_t *) dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3;
+ if (tile_elems == ne00) {
+ const size_t src_row_bytes = (size_t) ne00 * src_elem_size;
+ const size_t dst_unit_bytes = (size_t) ne00 * dst_elem_size;
- // Tile along dimension 0
- for (uint32_t i0 = 0; i0 < nr0; i0++) {
- uint8_t * dst_ptr = dst_base + i0 * ne00 * nb0;
- memcpy(dst_ptr, src_row, row_bytes);
+ for (uint32_t ir = row_start; ir < row_end; ir++) {
+ dma_addr_t src_addr, dst_addr;
+ repeat_row_addrs(rctx, src, dst, ir, &src_addr, &dst_addr);
+
+ dma_sync_read(dma_q, src_vtcm, src_addr, src_row_bytes);
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ fill_vtcm(dst_vtcm, src_vtcm, ne00, dst_reps, dst_elem_size);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+
+ for (uint32_t r = 0; r < nr0; r += dst_reps) {
+ const uint32_t cnt = MIN(dst_reps, nr0 - r);
+ dma_sync_write(dma_q, dst_addr + (size_t) r * dst_unit_bytes, dst_vtcm, (size_t) cnt * dst_unit_bytes);
+ }
+ }
+ } else {
+ for (uint32_t ir = row_start; ir < row_end; ir++) {
+ dma_addr_t src_addr, dst_addr;
+ repeat_row_addrs(rctx, src, dst, ir, &src_addr, &dst_addr);
+
+ for (uint32_t col0 = 0; col0 < ne00; col0 += tile_elems) {
+ const uint32_t cnt = MIN(tile_elems, ne00 - col0);
+ dma_sync_read(dma_q, src_vtcm, src_addr + (size_t) col0 * src_elem_size, (size_t) cnt * src_elem_size);
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ fill_vtcm(dst_vtcm, src_vtcm, cnt, 1, dst_elem_size);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+
+ for (uint32_t i0 = 0; i0 < nr0; i0++) {
+ const dma_addr_t d = dst_addr + ((size_t) i0 * ne00 + col0) * dst_elem_size;
+ dma_sync_write(dma_q, d, dst_vtcm, (size_t) cnt * dst_elem_size);
+ }
+ }
}
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
-
- FARF(HIGH, "repeat %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
+ FARF(HIGH, "repeat-tiled %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n",
ith, nth, src->ne[0], src->ne[1], src->ne[2], src->ne[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
row_start, row_end);
@@ -103,36 +321,26 @@ int op_repeat(struct htp_ops_context * octx) {
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- size_t type_size;
- switch (src0->type) {
- case HTP_TYPE_F32: type_size = 4; break;
- case HTP_TYPE_F16: type_size = 2; break;
- default:
- FARF(ERROR, "repeat: unsupported type %u\n", src0->type);
- return HTP_STATUS_NO_SUPPORT;
- }
-
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) {
+ if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) ||
+ (dst->type != src0->type && !(src0->type == HTP_TYPE_F32 && dst->type == HTP_TYPE_F16))) {
+ FARF(ERROR, "repeat: unsupported types %u -> %u\n", src0->type, dst->type);
return HTP_STATUS_NO_SUPPORT;
}
+ const uint32_t src_elem_size = (src0->type == HTP_TYPE_F16) ? 2 : 4;
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? 2 : 4;
+
const struct htp_repeat_kernel_params * kparams =
(const struct htp_repeat_kernel_params *) octx->kernel_params;
- if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
- const uint32_t total_dst_rows = dst->ne[1] * dst->ne[2] * dst->ne[3];
- const size_t dst_row_size = dst->ne[0] * type_size;
+ const uint32_t total_dst_rows = dst->ne[1] * dst->ne[2] * dst->ne[3];
uint32_t row_start = 0;
uint32_t nrows = total_dst_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, type_size, (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_dst_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ total_dst_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -141,23 +349,54 @@ int op_repeat(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
- const uint32_t n_hvx = octx->n_hvx;
+ if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, nrows))) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
+
+ const uint32_t n_hvx = octx->n_hvx;
+ const uint32_t n_bufs = kparams->pipelined ? 2 : 1;
+
+ struct htp_repeat_vtcm_layout layout;
+ htp_repeat_vtcm_layout_build(&layout,
+ (size_t) kparams->tile_elems * src_elem_size,
+ (size_t) kparams->tile_elems * kparams->dst_reps * dst_elem_size,
+ n_bufs, n_hvx);
+
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "repeat: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
struct htp_repeat_context rctx = {
- .octx = octx,
- .kparams = kparams,
- .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
- .total_dst_rows = nrows,
- .row_start = row_start,
- .type_size = type_size,
+ .octx = octx,
+ .kparams = kparams,
+ .fill_vtcm = (src0->type == dst->type) ? repeat_fill_vtcm_same : repeat_fill_vtcm_f32_to_f16,
+ .data_src = (dma_addr_t) src0->data,
+ .data_dst = (dma_addr_t) dst->data,
+ .vtcm_src = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_src),
+ .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_dst),
+ .src_buf_bytes = layout.src_buf_bytes,
+ .dst_buf_bytes = layout.dst_buf_bytes,
+ .src_bytes_per_hvx = layout.src_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
+ .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
+ .total_dst_rows = nrows,
+ .row_start = row_start,
+ .src_elem_size = src_elem_size,
+ .dst_elem_size = dst_elem_size,
+ .tile_elems = kparams->tile_elems,
+ .dst_reps = kparams->dst_reps,
};
- FARF(HIGH, "repeat: (%ux%ux%ux%u) -> (%ux%ux%ux%u) nr=(%u,%u,%u,%u)\n",
+ FARF(HIGH, "repeat: (%ux%ux%ux%u) -> (%ux%ux%ux%u) nr=(%u,%u,%u,%u) pipe=%u\n",
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
- kparams->nr0, kparams->nr1, kparams->nr2, kparams->nr3);
+ kparams->nr0, kparams->nr1, kparams->nr2, kparams->nr3, kparams->pipelined);
- work_queue_run(octx->ctx->hvx_queue, repeat_job_per_hvx, &rctx, n_hvx);
+ work_queue_func_t worker = kparams->pipelined ? repeat_thread : repeat_thread_tiled;
+ work_queue_run(octx->ctx->hvx_queue, worker, &rctx, n_hvx);
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/repeat-ops.h b/ggml/src/ggml-hexagon/htp/repeat-ops.h
index 1561994d4..7fcb49470 100644
--- a/ggml/src/ggml-hexagon/htp/repeat-ops.h
+++ b/ggml/src/ggml-hexagon/htp/repeat-ops.h
@@ -1,15 +1,51 @@
#ifndef HTP_REPEAT_OPS_H
#define HTP_REPEAT_OPS_H
+#include "hex-common.h"
#include "hex-fastdiv.h"
+#include "htp-vtcm.h"
+#include <stddef.h>
#include <stdint.h>
+struct htp_repeat_vtcm_layout {
+ size_t src_buf_bytes;
+ size_t dst_buf_bytes;
+ size_t src_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
+ size_t off_src;
+ size_t off_dst;
+ size_t total_bytes;
+};
+
+static inline void htp_repeat_vtcm_layout_build(
+ struct htp_repeat_vtcm_layout * L,
+ size_t src_tile_bytes,
+ size_t dst_tile_bytes,
+ uint32_t n_bufs,
+ uint32_t n_hvx
+) {
+ size_t off = 0;
+
+ L->src_buf_bytes = hex_round_up(src_tile_bytes, 128);
+ L->dst_buf_bytes = hex_round_up(dst_tile_bytes, 128);
+ L->src_bytes_per_hvx = (size_t) n_bufs * L->src_buf_bytes;
+ L->dst_bytes_per_hvx = (size_t) n_bufs * L->dst_buf_bytes;
+
+ VTCM_LAYOUT_ALLOC(off, off_src, (size_t) n_hvx * L->src_bytes_per_hvx);
+ VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) n_hvx * L->dst_bytes_per_hvx);
+ L->total_bytes = off;
+}
+
struct htp_repeat_kernel_params {
uint32_t n_hvx;
uint32_t nr0;
uint32_t nr1;
uint32_t nr2;
uint32_t nr3;
+ uint32_t tile_elems;
+ uint32_t dst_reps;
+ uint32_t pipelined;
+ uint32_t vtcm_size;
struct fastdiv_values div_ne1;
struct fastdiv_values div_ne12;
diff --git a/ggml/src/ggml-hexagon/htp/roll-ops.c b/ggml/src/ggml-hexagon/htp/roll-ops.c
index aa7a0ad4b..6279985ba 100644
--- a/ggml/src/ggml-hexagon/htp/roll-ops.c
+++ b/ggml/src/ggml-hexagon/htp/roll-ops.c
@@ -1,13 +1,10 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <string.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hvx-utils.h"
#define GGML_COMMON_DECL_C
@@ -17,15 +14,22 @@
#include "htp-trace.h"
#include "htp-ops.h"
#include "htp-tensor.h"
+#include "htp-vtcm.h"
#include "roll-ops.h"
struct htp_roll_context {
- struct htp_ops_context * octx;
+ struct htp_ops_context * octx;
const struct htp_roll_kernel_params * kparams;
+ uint8_t * vtcm_src;
+ uint8_t * vtcm_dst;
+ size_t row_size_aligned;
+ size_t src_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
uint32_t row_start;
uint32_t nrows;
uint32_t nrows_per_hvx;
+ uint32_t use_vtcm;
};
static inline uint32_t htp_roll_wrap(int32_t i, uint32_t ne) {
@@ -38,32 +42,32 @@ static inline uint32_t htp_roll_wrap(int32_t i, uint32_t ne) {
return (uint32_t) i;
}
-#define htp_roll_preamble \
- const struct htp_tensor * src0 = octx->src[0]; \
- const struct htp_tensor * dst = octx->dst; \
- const struct htp_roll_kernel_params * kparams = \
- (const struct htp_roll_kernel_params *) octx->kernel_params; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb01 = src0->nb[1]; \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3]; \
- \
- const int32_t s0 = octx->op_params[0]; \
- const int32_t s1 = octx->op_params[1]; \
- const int32_t s2 = octx->op_params[2]; \
- const int32_t s3 = octx->op_params[3]; \
- \
- const uint32_t i0_src0 = kparams->i0_src0; \
- const uint32_t n0 = kparams->n0;
+#define htp_roll_preamble \
+ const struct htp_tensor * src0 = octx->src[0]; \
+ const struct htp_tensor * dst = octx->dst; \
+ const struct htp_roll_kernel_params * kparams = \
+ (const struct htp_roll_kernel_params *) octx->kernel_params; \
+ \
+ 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)) 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)) nb1 = dst->nb[1]; \
+ const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \
+ const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; \
+ \
+ const int32_t __attribute__((unused)) s0 = octx->op_params[0]; \
+ const int32_t __attribute__((unused)) s1 = octx->op_params[1]; \
+ const int32_t __attribute__((unused)) s2 = octx->op_params[2]; \
+ const int32_t __attribute__((unused)) s3 = octx->op_params[3]; \
+ \
+ const uint32_t __attribute__((unused)) i0_src0 = kparams->i0_src0; \
+ const uint32_t __attribute__((unused)) n0 = kparams->n0;
#define htp_roll_dma_preamble dma_queue * q = octx->ctx->dma[0];
@@ -93,14 +97,15 @@ static inline void roll_dma_push_rows(dma_queue * q,
uint32_t nrows,
uint32_t row_size,
uint32_t i0_src0,
- uint32_t n0) {
+ uint32_t n0,
+ uint32_t elem_size) {
const dma_addr_t dst_base = dst->data + (size_t) dst_row * row_size;
const dma_addr_t src_base = src0->data + (size_t) src_row * row_size;
- roll_dma_push(q, dst_base, src_base + (size_t) i0_src0 * sizeof(float),
- row_size, row_size, n0 * sizeof(float), nrows);
- roll_dma_push(q, dst_base + (size_t) n0 * sizeof(float), src_base,
- row_size, row_size, i0_src0 * sizeof(float), nrows);
+ roll_dma_push(q, dst_base, src_base + (size_t) i0_src0 * elem_size,
+ row_size, row_size, n0 * elem_size, nrows);
+ roll_dma_push(q, dst_base + (size_t) n0 * elem_size, src_base,
+ row_size, row_size, i0_src0 * elem_size, nrows);
}
// Same row-wrap split as roll_dma_push_rows, but addressed with explicit byte strides so it
@@ -112,21 +117,23 @@ static inline void roll_dma_push_range(dma_queue * q,
uint32_t src_stride,
uint32_t nrows,
uint32_t i0_src0,
- uint32_t n0) {
- roll_dma_push(q, dst_row, src_row + (size_t) i0_src0 * sizeof(float),
- dst_stride, src_stride, n0 * sizeof(float), nrows);
- roll_dma_push(q, dst_row + (size_t) n0 * sizeof(float), src_row,
- dst_stride, src_stride, i0_src0 * sizeof(float), nrows);
+ uint32_t n0,
+ uint32_t elem_size) {
+ roll_dma_push(q, dst_row, src_row + (size_t) i0_src0 * elem_size,
+ dst_stride, src_stride, n0 * elem_size, nrows);
+ roll_dma_push(q, dst_row + (size_t) n0 * elem_size, src_row,
+ dst_stride, src_stride, i0_src0 * elem_size, nrows);
}
-static int roll_dma_f32_contiguous(struct htp_ops_context * octx) {
+static int roll_dma_contiguous(struct htp_ops_context * octx) {
htp_roll_preamble;
htp_roll_dma_preamble;
- const uint32_t row_size = ne0 * sizeof(float);
+ const uint32_t elem_size = kparams->elem_size;
+ const uint32_t row_size = ne0 * elem_size;
if (s1 == 0 && s2 == 0 && s3 == 0) {
- roll_dma_push_rows(q, dst, src0, 0, 0, ne1 * ne2 * ne3, row_size, i0_src0, n0);
+ roll_dma_push_rows(q, dst, src0, 0, 0, ne1 * ne2 * ne3, row_size, i0_src0, n0, elem_size);
dma_queue_flush(q);
return HTP_STATUS_OK;
}
@@ -140,9 +147,9 @@ static int roll_dma_f32_contiguous(struct htp_ops_context * octx) {
const uint32_t n2_first = ne2 - i2_src0;
roll_dma_push_rows(q, dst, src0, dst_row0, src_row0, n2_first * ne1,
- row_size, i0_src0, n0);
+ row_size, i0_src0, n0, elem_size);
roll_dma_push_rows(q, dst, src0, dst_row0 + n2_first * ne1, i03 * ne2 * ne1,
- i2_src0 * ne1, row_size, i0_src0, n0);
+ i2_src0 * ne1, row_size, i0_src0, n0, elem_size);
}
dma_queue_flush(q);
@@ -160,9 +167,9 @@ static int roll_dma_f32_contiguous(struct htp_ops_context * octx) {
const uint32_t src_row0 = (i03 * ne2 + i02) * ne1;
roll_dma_push_rows(q, dst, src0, dst_row0, src_row0 + i1_src0,
- n1_first, row_size, i0_src0, n0);
+ n1_first, row_size, i0_src0, n0, elem_size);
roll_dma_push_rows(q, dst, src0, dst_row0 + n1_first, src_row0,
- i1_src0, row_size, i0_src0, n0);
+ i1_src0, row_size, i0_src0, n0, elem_size);
}
}
@@ -173,12 +180,13 @@ static int roll_dma_f32_contiguous(struct htp_ops_context * octx) {
// DMA path for a row-contiguous but otherwise arbitrarily strided src0 (e.g. a permuted view).
// Same row-wrap split as above, one DMA push per (i2,i3), addressed via the real nb01/nb02/nb03
// instead of assuming a packed layout.
-static int roll_dma_f32_strided(struct htp_ops_context * octx) {
+static int roll_dma_strided(struct htp_ops_context * octx) {
htp_roll_preamble;
htp_roll_dma_preamble;
- const uint32_t i1_src0 = htp_roll_wrap(-s1, ne1);
- const uint32_t n1_first = ne1 - i1_src0;
+ const uint32_t elem_size = kparams->elem_size;
+ const uint32_t i1_src0 = htp_roll_wrap(-s1, ne1);
+ const uint32_t n1_first = ne1 - i1_src0;
for (uint32_t i3 = 0; i3 < ne3; i3++) {
const uint32_t i03 = htp_roll_wrap((int32_t) i3 - s3, ne3);
@@ -189,9 +197,9 @@ static int roll_dma_f32_strided(struct htp_ops_context * octx) {
const dma_addr_t src_row0 = src0->data + (size_t) i02 * nb02 + (size_t) i03 * nb03;
roll_dma_push_range(q, dst_row0, src_row0 + (size_t) i1_src0 * nb01,
- nb1, nb01, n1_first, i0_src0, n0);
+ nb1, nb01, n1_first, i0_src0, n0, elem_size);
roll_dma_push_range(q, dst_row0 + (size_t) n1_first * nb1, src_row0,
- nb1, nb01, i1_src0, i0_src0, n0);
+ nb1, nb01, i1_src0, i0_src0, n0, elem_size);
}
}
@@ -199,9 +207,104 @@ static int roll_dma_f32_strided(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
-static void roll_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static inline void roll_row_addrs(
+ const struct htp_tensor * src0,
+ const struct htp_tensor * dst,
+ const struct htp_roll_kernel_params * kparams,
+ uint32_t row,
+ int32_t s1,
+ int32_t s2,
+ int32_t s3,
+ dma_addr_t * src_addr,
+ dma_addr_t * dst_addr
+) {
+ const uint32_t ne1 = dst->ne[1];
+ const uint32_t ne2 = dst->ne[2];
+ const uint32_t ne3 = dst->ne[3];
+
+ const uint32_t i3 = fastdiv(row, &kparams->div_ne2_ne1);
+ const uint32_t rem = row - i3 * ne2 * ne1;
+ const uint32_t i2 = fastdiv(rem, &kparams->div_ne1);
+ const uint32_t i1 = rem - i2 * ne1;
+
+ const uint32_t i01 = htp_roll_wrap((int32_t) i1 - s1, ne1);
+ const uint32_t i02 = htp_roll_wrap((int32_t) i2 - s2, ne2);
+ const uint32_t i03 = htp_roll_wrap((int32_t) i3 - s3, ne3);
+
+ *src_addr = src0->data + (size_t) i01 * src0->nb[1] + (size_t) i02 * src0->nb[2] + (size_t) i03 * src0->nb[3];
+ *dst_addr = dst->data + (size_t) i1 * dst->nb[1] + (size_t) i2 * dst->nb[2] + (size_t) i3 * dst->nb[3];
+}
+
+static void __attribute__((noinline)) roll_copy_row_vtcm(
+ uint8_t * restrict dst_vtcm,
+ const uint8_t * restrict src_vtcm,
+ uint32_t ne0,
+ uint32_t i0_src0,
+ uint32_t n0,
+ uint32_t elem_size
+) {
+ if (i0_src0 == 0) {
+ hvx_copy_aa(dst_vtcm, src_vtcm, ne0 * elem_size, 1);
+ } else {
+ const uint32_t n0_bytes = n0 * elem_size;
+ const uint32_t i0_src0_bytes = i0_src0 * elem_size;
+ hvx_copy_au(dst_vtcm, src_vtcm + i0_src0_bytes, n0_bytes, 1);
+ hvx_copy_ua(dst_vtcm + n0_bytes, src_vtcm, i0_src0_bytes, 1);
+ }
+}
+
+struct roll_pipe_state {
+ const struct htp_tensor * src0;
+ const struct htp_tensor * dst;
+ const struct htp_roll_kernel_params * kparams;
+ size_t row_size;
+ size_t row_size_aligned;
+ uint32_t ne0;
+ uint32_t i0_src0;
+ uint32_t n0;
+ uint32_t elem_size;
+ int32_t s1, s2, s3;
+ uint32_t row;
+ uint32_t row_end;
+};
+
+static bool roll_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct roll_pipe_state * s = (struct roll_pipe_state *) ctx;
+ if (s->row >= s->row_end) {
+ return false;
+ }
+ task->row = s->row++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
+
+static void roll_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct roll_pipe_state * s = (struct roll_pipe_state *) ctx;
+ dma_addr_t src_addr, dst_addr;
+ roll_row_addrs(s->src0, s->dst, s->kparams, task->row, s->s1, s->s2, s->s3, &src_addr, &dst_addr);
+ dma_queue_push(dma_q, dma_make_data(in_spad, src_addr),
+ s->row_size_aligned, s->row_size, s->row_size, 1);
+}
+
+static void roll_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ (void) task;
+ struct roll_pipe_state * s = (struct roll_pipe_state *) ctx;
+ roll_copy_row_vtcm((uint8_t *) out_spad, (const uint8_t *) in_spad, s->ne0, s->i0_src0, s->n0, s->elem_size);
+}
+
+static void roll_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct roll_pipe_state * s = (struct roll_pipe_state *) ctx;
+ dma_addr_t src_addr, dst_addr;
+ roll_row_addrs(s->src0, s->dst, s->kparams, task->row, s->s1, s->s2, s->s3, &src_addr, &dst_addr);
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->row_size, s->row_size_aligned, s->row_size, 1);
+}
+
+static void roll_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_roll_context * rctx = (struct htp_roll_context *) data;
- struct htp_ops_context * octx = rctx->octx;
+ struct htp_ops_context * octx = rctx->octx;
htp_roll_preamble;
@@ -211,58 +314,68 @@ static void roll_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned
return;
}
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
-
- for (uint32_t row = row_start; row < row_end; row++) {
- const uint32_t i3 = fastdiv(row, &kparams->div_ne2_ne1);
- const uint32_t rem = row - i3 * ne2 * ne1;
- const uint32_t i2 = fastdiv(rem, &kparams->div_ne1);
- const uint32_t i1 = rem - i2 * ne1;
+ dma_queue * dma_q = th->dma_q;
+ const uint32_t elem_size = kparams->elem_size;
+ const size_t row_size = (size_t) ne0 * elem_size;
- const uint32_t i01 = htp_roll_wrap((int32_t) i1 - s1, ne1);
- const uint32_t i02 = htp_roll_wrap((int32_t) i2 - s2, ne2);
- const uint32_t i03 = htp_roll_wrap((int32_t) i3 - s3, ne3);
-
- const uint8_t * src_row = (const uint8_t *) (uintptr_t) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
- uint8_t * dst_row = (uint8_t *) (uintptr_t) dst->data + i1*nb1 + i2*nb2 + i3*nb3;
-
- hex_l2fetch(src_row + i0_src0 * sizeof(float), n0 * sizeof(float), ne0 * sizeof(float), 1);
- hvx_copy_uu(dst_row, src_row + i0_src0 * sizeof(float), n0, sizeof(float));
-
- if (i0_src0 != 0) {
- hex_l2fetch(src_row, i0_src0 * sizeof(float), ne0 * sizeof(float), 1);
- hvx_copy_uu(dst_row + n0 * sizeof(float), src_row, i0_src0, sizeof(float));
+ if (!rctx->use_vtcm) {
+ for (uint32_t row = row_start; row < row_end; row++) {
+ dma_addr_t src_addr, dst_addr;
+ roll_row_addrs(src0, dst, kparams, row, s1, s2, s3, &src_addr, &dst_addr);
+ roll_dma_push_range(dma_q, dst_addr, src_addr, nb1, nb01, 1, i0_src0, n0, elem_size);
}
+ dma_queue_flush(dma_q);
+ return;
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start);
+ const size_t row_size_aligned = rctx->row_size_aligned;
+ uint8_t * src_vtcm_base = rctx->vtcm_src + ith * rctx->src_bytes_per_hvx;
+ uint8_t * dst_vtcm_base = rctx->vtcm_dst + ith * rctx->dst_bytes_per_hvx;
+ void * in_buf[2] = { src_vtcm_base, src_vtcm_base + row_size_aligned };
+ void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + row_size_aligned };
+
+ struct roll_pipe_state s = {
+ .src0 = src0,
+ .dst = dst,
+ .kparams = kparams,
+ .row_size = row_size,
+ .row_size_aligned = row_size_aligned,
+ .ne0 = ne0,
+ .i0_src0 = i0_src0,
+ .n0 = n0,
+ .elem_size = elem_size,
+ .s1 = s1, .s2 = s2, .s3 = s3,
+ .row = row_start,
+ .row_end = row_end,
+ };
+
+ dma_pipe_io_run(dma_q, th->trace, &s, in_buf, out_buf, roll_next_task, roll_push_in, roll_compute, roll_push_out);
FARF(HIGH, "roll %d/%d: (%ux%ux%ux%u) rows %u:%u shift=(%d,%d,%d,%d)\n",
ith, nth, ne0, ne1, ne2, ne3,
row_start, row_end, s0, s1, s2, s3);
}
-int execute_op_roll_f32(struct htp_ops_context * octx) {
+static int execute_op_roll(struct htp_ops_context * octx) {
htp_roll_preamble;
if (kparams->kernel_type == HTP_ROLL_KERNEL_DMA_CONTIGUOUS) {
- return roll_dma_f32_contiguous(octx);
+ return roll_dma_contiguous(octx);
}
if (kparams->kernel_type == HTP_ROLL_KERNEL_DMA_STRIDED) {
- return roll_dma_f32_strided(octx);
+ return roll_dma_strided(octx);
}
- const uint32_t total_rows = kparams->total_rows;
- const size_t dst_row_size = ne0 * sizeof(float);
+ const uint32_t total_rows = kparams->total_rows;
+ const uint32_t elem_size = kparams->elem_size;
+ const size_t dst_row_size = (size_t) ne0 * elem_size;
uint32_t row_start = 0;
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -271,32 +384,51 @@ int execute_op_roll_f32(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, nrows))) {
return HTP_STATUS_INVAL_PARAMS;
}
- const uint32_t n_hvx = octx->n_hvx;
+ const uint32_t n_hvx = octx->n_hvx;
+ const uint32_t use_vtcm = (kparams->vtcm_size > 0) ? 1 : 0;
+
+ struct htp_roll_vtcm_layout layout = { 0 };
+ if (use_vtcm) {
+ htp_roll_vtcm_layout_build(&layout, dst_row_size, n_hvx);
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "roll: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+ }
+
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
+
struct htp_roll_context rctx = {
- .octx = octx,
- .kparams = kparams,
- .row_start = row_start,
- .nrows = nrows,
- .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
+ .octx = octx,
+ .kparams = kparams,
+ .vtcm_src = use_vtcm ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_src) : NULL,
+ .vtcm_dst = use_vtcm ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_dst) : NULL,
+ .row_size_aligned = layout.row_size_aligned,
+ .src_bytes_per_hvx = layout.src_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
+ .row_start = row_start,
+ .nrows = nrows,
+ .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div),
+ .use_vtcm = use_vtcm,
};
- work_queue_run(octx->ctx->hvx_queue, roll_thread_f32, &rctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, roll_thread, &rctx, n_hvx);
return HTP_STATUS_OK;
}
int op_roll(struct htp_ops_context * octx) {
+ if (octx->src[0]->type != octx->dst->type) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
switch (octx->src[0]->type) {
case HTP_TYPE_F32:
- return execute_op_roll_f32(octx);
+ case HTP_TYPE_F16:
+ return execute_op_roll(octx);
default:
return HTP_STATUS_NO_SUPPORT;
diff --git a/ggml/src/ggml-hexagon/htp/roll-ops.h b/ggml/src/ggml-hexagon/htp/roll-ops.h
index f98fb8ea9..8774aee97 100644
--- a/ggml/src/ggml-hexagon/htp/roll-ops.h
+++ b/ggml/src/ggml-hexagon/htp/roll-ops.h
@@ -1,7 +1,10 @@
#ifndef HTP_ROLL_OPS_H
#define HTP_ROLL_OPS_H
+#include "hex-common.h"
#include "hex-fastdiv.h"
+#include "htp-vtcm.h"
+#include <stddef.h>
#include <stdint.h>
enum htp_roll_kernel_type {
@@ -10,12 +13,39 @@ enum htp_roll_kernel_type {
HTP_ROLL_KERNEL_HVX = 3,
};
+struct htp_roll_vtcm_layout {
+ size_t row_size_aligned;
+ size_t src_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
+ size_t off_src;
+ size_t off_dst;
+ size_t total_bytes;
+};
+
+static inline void htp_roll_vtcm_layout_build(
+ struct htp_roll_vtcm_layout * L,
+ size_t row_size,
+ uint32_t n_hvx
+) {
+ size_t off = 0;
+
+ L->row_size_aligned = hex_round_up(row_size, 128);
+ L->src_bytes_per_hvx = 2 * L->row_size_aligned;
+ L->dst_bytes_per_hvx = 2 * L->row_size_aligned;
+
+ VTCM_LAYOUT_ALLOC(off, off_src, (size_t) n_hvx * L->src_bytes_per_hvx);
+ VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) n_hvx * L->dst_bytes_per_hvx);
+ L->total_bytes = off;
+}
+
struct htp_roll_kernel_params {
uint8_t kernel_type;
uint32_t n_hvx;
uint32_t total_rows;
uint32_t i0_src0;
uint32_t n0;
+ uint32_t elem_size;
+ uint32_t vtcm_size;
struct fastdiv_values div_ne1;
struct fastdiv_values div_ne2_ne1;
diff --git a/ggml/src/ggml-hexagon/htp/rope-ops.c b/ggml/src/ggml-hexagon/htp/rope-ops.c
index 1c73de10b..b6924ee6e 100644
--- a/ggml/src/ggml-hexagon/htp/rope-ops.c
+++ b/ggml/src/ggml-hexagon/htp/rope-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -28,39 +24,34 @@
#define HTP_ROPE_TYPE_IMROPE 40
#define htp_rope_preamble \
- const uint32_t ne00 = src0->ne[0]; \
- const uint32_t ne01 = src0->ne[1]; \
- const uint32_t ne02 = src0->ne[2]; \
- const uint32_t ne03 = src0->ne[3]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
const uint32_t ne1 = dst->ne[1]; \
const uint32_t ne2 = dst->ne[2]; \
const uint32_t ne3 = dst->ne[3]; \
\
- const uint32_t nb00 = src0->nb[0]; \
const uint32_t nb01 = src0->nb[1]; \
const uint32_t nb02 = src0->nb[2]; \
const uint32_t nb03 = src0->nb[3]; \
\
- const uint32_t nb0 = dst->nb[0]; \
const uint32_t nb1 = dst->nb[1]; \
const uint32_t nb2 = dst->nb[2]; \
const uint32_t nb3 = dst->nb[3];
+struct htp_rope_context;
+
+typedef void (*rope_compute_fn_t)(const struct htp_rope_context * rctx, uint8_t * src, uint32_t nr, const float * restrict theta_cache);
+
struct htp_rope_context {
- int32_t n_dims;
- int32_t n_offs;
- int32_t mode;
- int32_t n_ctx_orig;
- int32_t sections[4];
+ int32_t n_dims;
+ int32_t n_offs;
+ int32_t mode;
+ int32_t sections[4];
+ uint32_t ne_rot;
+
+ rope_compute_fn_t compute_block;
- float freq_base;
float freq_scale;
float ext_factor;
float attn_factor;
- float beta_fast;
- float beta_slow;
float theta_scale;
float theta_scale_32;
float theta_powers[32];
@@ -74,19 +65,24 @@ struct htp_rope_context {
size_t spad_per_hvx;
size_t theta_cache_offset;
- size_t src0_row_size;
- size_t src0_row_stride;
- size_t dst_row_size;
- size_t dst_row_stride;
- size_t src0_row_size_aligned;
- uint32_t src0_nrows;
+ uint8_t * cs_table;
+ size_t cs_stride;
+ uint32_t cs_i2_base;
+ uint32_t cs_i2_count;
+
+ size_t src0_row_size;
+ size_t src0_row_stride;
+ size_t dst_row_size;
+ size_t dst_row_stride;
+ size_t src0_row_size_aligned;
uint32_t row_start;
uint32_t nrows;
struct fastdiv_values div_ne2_ne1;
struct fastdiv_values div_ne1;
- const float * freq_factors;
+ const float * freq_factors;
+ const int32_t * pos_data;
};
static float rope_yarn_ramp(const float low, const float high, const int i0) {
@@ -121,7 +117,7 @@ static inline void rope_yarn_one(float theta, float freq_scale, float * corr_dim
}
// 32 thetas -> 32 deinterleaved pairs [cos[32] | sin[32]] at cache[i0].
-static inline void rope_cache_hvx_32(float * cache, uint32_t i0,
+static __attribute__((noinline)) void rope_cache_hvx_32(float * cache, uint32_t i0,
HVX_Vector v_theta,
const float * freq_factors,
HVX_Vector v_freq_scale,
@@ -138,13 +134,9 @@ static inline void rope_cache_hvx_32(float * cache, uint32_t i0,
vcos = hvx_vec_mul_f32_f32(vcos, v_mscale);
vsin = hvx_vec_mul_f32_f32(vsin, v_mscale);
- if (((uintptr_t) (cache + i0)) % 128 == 0) {
- hvx_vmem(cache + i0 + 0) = vcos;
- hvx_vmem(cache + i0 + 32) = vsin;
- } else {
- hvx_vec_store_u(cache + i0 + 0, 32 * sizeof(float), vcos);
- hvx_vec_store_u(cache + i0 + 32, 32 * sizeof(float), vsin);
- }
+ assert(((uintptr_t) (cache + i0)) % 128 == 0);
+ hvx_vmem(cache + i0 + 0) = vcos;
+ hvx_vmem(cache + i0 + 32) = vsin;
}
static __attribute__((noinline)) void rope_cache_init(const float theta_base,
@@ -280,6 +272,11 @@ static __attribute__((noinline)) void mrope_cache_init(const float pos_t,
const float theta_scale,
const float * theta_powers,
const float theta_scale_32) {
+ if (!indep_sects && pos_t == pos_h && pos_t == pos_w && pos_t == pos_e) {
+ rope_cache_init(pos_t, freq_scale, freq_factors, corr_dims, n_cache, ext_factor, mscale, cache, theta_scale, theta_powers, theta_scale_32);
+ return;
+ }
+
const int sect_dims = sections[0] + sections[1] + sections[2] + sections[3];
const int sec_w = sections[0] + sections[1];
const int sec_e = sec_w + sections[2];
@@ -289,8 +286,8 @@ static __attribute__((noinline)) void mrope_cache_init(const float pos_t,
const bool imrope_mod3 = is_imrope && !indep_sects && no_wrap
&& sections[0] > 0 && sections[1] > 0 && sections[2] > 0
&& n_pairs <= (uint32_t) (3 * sections[0])
- && n_pairs <= (uint32_t) (3 * sections[1])
- && n_pairs <= (uint32_t) (3 * sections[2]);
+ && n_pairs <= (uint32_t) (3 * sections[1] + 1)
+ && n_pairs <= (uint32_t) (3 * sections[2] + 2);
const bool contig = !is_imrope && !indep_sects && no_wrap;
if (ext_factor == 0.0f && (imrope_mod3 || contig)) {
@@ -379,18 +376,6 @@ static __attribute__((noinline)) void mrope_cache_init(const float pos_t,
#define M_PI 3.1415926535897932384626433
-static void rope_corr_dims(int n_dims,
- int n_ctx_orig,
- float freq_base,
- float beta_fast,
- float beta_slow,
- float * dims) {
- float start = floorf(n_dims * logf(n_ctx_orig / (beta_fast * 2 * (float) M_PI)) / (2 * logf(freq_base)));
- float end = ceilf(n_dims * logf(n_ctx_orig / (beta_slow * 2 * (float) M_PI)) / (2 * logf(freq_base)));
- dims[0] = MAX(0, start);
- dims[1] = MIN(n_dims - 1, end);
-}
-
static inline void hvx_rope_neox_mul(HVX_Vector v0, HVX_Vector v1, HVX_Vector vcos, HVX_Vector vsin,
HVX_Vector * o0, HVX_Vector * o1) {
HVX_Vector vx0_c = Q6_Vqf32_vmpy_VsfVsf(v0, vcos);
@@ -401,6 +386,18 @@ static inline void hvx_rope_neox_mul(HVX_Vector v0, HVX_Vector v1, HVX_Vector vc
*o1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(vx0_s, vx1_c));
}
+#if __HVX_ARCH__ < 79
+static inline void hvx_rope_neox_mul_qf32(HVX_Vector v0_qf, HVX_Vector v1_qf, HVX_Vector vcos_qf, HVX_Vector vsin_qf,
+ HVX_Vector * o0, HVX_Vector * o1) {
+ HVX_Vector vx0_c = Q6_Vqf32_vmpy_Vqf32Vqf32(v0_qf, vcos_qf);
+ HVX_Vector vx0_s = Q6_Vqf32_vmpy_Vqf32Vqf32(v0_qf, vsin_qf);
+ HVX_Vector vx1_c = Q6_Vqf32_vmpy_Vqf32Vqf32(v1_qf, vcos_qf);
+ HVX_Vector vx1_s = Q6_Vqf32_vmpy_Vqf32Vqf32(v1_qf, vsin_qf);
+ *o0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_Vqf32Vqf32(vx0_c, vx1_s));
+ *o1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(vx0_s, vx1_c));
+}
+#endif
+
// theta_cache full 32-pair blocks are deinterleaved [cos | sin].
static inline void hvx_rope_neox_f32_aa(float * restrict dst, const float * restrict src0, uint32_t ne, const float * restrict theta_cache) {
const uint32_t he = ne / 2;
@@ -512,7 +509,7 @@ static inline void hvx_rope_f32_aa(float * restrict dst, const float * restrict
}
}
-static void inline rope_basic_f32_inplace(struct htp_rope_context * rctx, uint8_t * src,
+static __attribute__((noinline)) void rope_basic_f32_inplace(const struct htp_rope_context * rctx, uint8_t * src,
uint32_t nr, const float * restrict theta_cache) {
const uint32_t n_offs = rctx->n_offs;
#pragma unroll(4)
@@ -522,9 +519,10 @@ static void inline rope_basic_f32_inplace(struct htp_rope_context * rctx, uint8_
}
}
-static void inline rope_neox_f32_inplace(struct htp_rope_context * rctx, uint8_t * src,
- uint32_t nr, uint32_t ne, const float * restrict theta_cache) {
+static __attribute__((noinline)) void rope_neox_f32_inplace(const struct htp_rope_context * rctx, uint8_t * src,
+ uint32_t nr, const float * restrict theta_cache) {
const uint32_t n_offs = rctx->n_offs;
+ const uint32_t ne = rctx->ne_rot;
#pragma unroll(4)
for (uint32_t i = 0; i < nr; i++) {
float * s = (float *) (src + i * rctx->src0_row_size_aligned);
@@ -532,13 +530,494 @@ static void inline rope_neox_f32_inplace(struct htp_rope_context * rctx, uint8_t
}
}
-static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static inline HVX_Vector hvx_vec_clamp_f16_f32_vec(HVX_Vector x, HVX_Vector f16_min, HVX_Vector f16_max) {
+ return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max);
+}
+
+static __attribute__((noinline)) void hvx_rope_neox_f16_aa(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) {
+ const uint32_t he = ne / 2;
+ const uint32_t nvec = he / 64;
+ const uint32_t nloe = he % 64;
+
+ const HVX_Vector * vt = (const HVX_Vector *) theta_cache;
+
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector zero = Q6_V_vzero();
+#endif
+
+ if (nloe == 0) {
+ const HVX_Vector * vs = (const HVX_Vector *) src0;
+ HVX_Vector * vd = (HVX_Vector *) dst;
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_Vector v0 = vs[i];
+ HVX_Vector v1 = vs[nvec + i];
+#if __HVX_ARCH__ < 79
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v0), one_hf);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v1), one_hf);
+
+ HVX_Vector vcos0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 0], zero);
+ HVX_Vector vsin0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 1], zero);
+ HVX_Vector vcos1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 2], zero);
+ HVX_Vector vsin1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 3], zero);
+
+ HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi;
+ hvx_rope_neox_mul_qf32(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vcos0_qf, vsin0_qf, &o0_lo, &o1_lo);
+ hvx_rope_neox_mul_qf32(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vcos1_qf, vsin1_qf, &o0_hi, &o1_hi);
+#else
+ HVX_VectorPair vp0 = hvx_vec_f16_to_f32(v0);
+ HVX_VectorPair vp1 = hvx_vec_f16_to_f32(v1);
+
+ HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi;
+ hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[i * 4 + 0], vt[i * 4 + 1], &o0_lo, &o1_lo);
+ hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[i * 4 + 2], vt[i * 4 + 3], &o0_hi, &o1_hi);
+#endif
+ HVX_Vector vout0 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max));
+ HVX_Vector vout1 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max));
+
+ vd[i] = vout0;
+ vd[nvec + i] = vout1;
+ }
+ return;
+ }
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_Vector v0 = ((const HVX_Vector *) src0)[i];
+ HVX_Vector v1 = hvx_vmemu(src0 + he + i * 64);
+#if __HVX_ARCH__ < 79
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v0), one_hf);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v1), one_hf);
+
+ HVX_Vector vcos0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 0], zero);
+ HVX_Vector vsin0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 1], zero);
+ HVX_Vector vcos1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 2], zero);
+ HVX_Vector vsin1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 3], zero);
+
+ HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi;
+ hvx_rope_neox_mul_qf32(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vcos0_qf, vsin0_qf, &o0_lo, &o1_lo);
+ hvx_rope_neox_mul_qf32(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vcos1_qf, vsin1_qf, &o0_hi, &o1_hi);
+#else
+ HVX_VectorPair vp0 = hvx_vec_f16_to_f32(v0);
+ HVX_VectorPair vp1 = hvx_vec_f16_to_f32(v1);
+
+ HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi;
+ hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[i * 4 + 0], vt[i * 4 + 1], &o0_lo, &o1_lo);
+ hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[i * 4 + 2], vt[i * 4 + 3], &o0_hi, &o1_hi);
+#endif
+ HVX_Vector vout0 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max));
+ HVX_Vector vout1 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max));
+
+ ((HVX_Vector *) dst)[i] = vout0;
+ hvx_vmemu(dst + he + i * 64) = vout1;
+ }
+
+ if (nloe > 0) {
+ HVX_Vector v0 = ((const HVX_Vector *) src0)[nvec];
+ HVX_Vector v1 = hvx_vmemu(src0 + he + nvec * 64);
+#if __HVX_ARCH__ < 79
+ HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v0), one_hf);
+ HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v1), one_hf);
+
+ HVX_Vector vcos0_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 0], zero);
+ HVX_Vector vsin0_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 1], zero);
+
+ HVX_Vector o0_lo, o1_lo;
+ hvx_rope_neox_mul_qf32(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vcos0_qf, vsin0_qf, &o0_lo, &o1_lo);
+ o0_lo = hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max);
+ o1_lo = hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max);
+
+ HVX_Vector o0_hi = o0_lo;
+ HVX_Vector o1_hi = o1_lo;
+ if (nloe > 32) {
+ HVX_Vector vcos1_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 2], zero);
+ HVX_Vector vsin1_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 3], zero);
+ hvx_rope_neox_mul_qf32(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vcos1_qf, vsin1_qf, &o0_hi, &o1_hi);
+ o0_hi = hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max);
+ o1_hi = hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max);
+ }
+#else
+ HVX_VectorPair vp0 = hvx_vec_f16_to_f32(v0);
+ HVX_VectorPair vp1 = hvx_vec_f16_to_f32(v1);
+
+ HVX_Vector o0_lo, o1_lo;
+ hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[nvec * 4 + 0], vt[nvec * 4 + 1], &o0_lo, &o1_lo);
+ o0_lo = hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max);
+ o1_lo = hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max);
+
+ HVX_Vector o0_hi = o0_lo;
+ HVX_Vector o1_hi = o1_lo;
+ if (nloe > 32) {
+ hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[nvec * 4 + 2], vt[nvec * 4 + 3], &o0_hi, &o1_hi);
+ o0_hi = hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max);
+ o1_hi = hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max);
+ }
+#endif
+ HVX_Vector vout0 = hvx_vec_f32_to_f16(o0_lo, o0_hi);
+ HVX_Vector vout1 = hvx_vec_f32_to_f16(o1_lo, o1_hi);
+
+ hvx_vec_store_a(dst + nvec * 64, nloe * sizeof(_Float16), vout0);
+ hvx_vec_store_u(dst + he + nvec * 64, nloe * sizeof(_Float16), vout1);
+ }
+}
+
+static __attribute__((noinline)) void hvx_rope_f16_aa(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) {
+ const uint32_t nvec = ne / 64;
+ const uint32_t nloe = ne % 64;
+
+ const HVX_Vector * vs = (const HVX_Vector *) src0;
+ HVX_Vector * vd = (HVX_Vector *) dst;
+ const HVX_Vector * vt = (const HVX_Vector *) theta_cache;
+
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector zero = Q6_V_vzero();
+#endif
+
+ for (uint32_t i = 0; i < nvec; i++) {
+#if __HVX_ARCH__ < 79
+ HVX_VectorPair vx0_x1 = Q6_Wqf32_vmpy_VhfVhf(vs[i], one_hf);
+
+ HVX_Vector vcos_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 2 + 0], zero);
+ HVX_Vector vsin_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 2 + 1], zero);
+
+ HVX_Vector o0, o1;
+ hvx_rope_neox_mul_qf32(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vcos_qf, vsin_qf, &o0, &o1);
+#else
+ HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(vs[i]);
+
+ HVX_Vector o0, o1;
+ hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[i * 2 + 0], vt[i * 2 + 1], &o0, &o1);
+#endif
+ HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max));
+
+ vd[i] = vout;
+ }
+
+ if (nloe > 0) {
+#if __HVX_ARCH__ < 79
+ HVX_VectorPair vx0_x1 = Q6_Wqf32_vmpy_VhfVhf(vs[nvec], one_hf);
+
+ HVX_Vector vcos_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 2 + 0], zero);
+ HVX_Vector vsin_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 2 + 1], zero);
+
+ HVX_Vector o0, o1;
+ hvx_rope_neox_mul_qf32(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vcos_qf, vsin_qf, &o0, &o1);
+#else
+ HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(vs[nvec]);
+
+ HVX_Vector o0, o1;
+ hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[nvec * 2 + 0], vt[nvec * 2 + 1], &o0, &o1);
+#endif
+ HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max));
+
+ hvx_vec_store_a(dst + nvec * 64, nloe * sizeof(_Float16), vout);
+ }
+}
+
+static __attribute__((noinline)) void hvx_rope_neox_f16(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) {
+ const uint32_t he = ne / 2;
+ const uint32_t nvec = he / 64;
+ const uint32_t nloe = he % 64;
+
+ const HVX_Vector * vt = (const HVX_Vector *) theta_cache;
+
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_VectorPair vp0 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + i * 64));
+ HVX_VectorPair vp1 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + he + i * 64));
+
+ HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi;
+ hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[i * 4 + 0], vt[i * 4 + 1], &o0_lo, &o1_lo);
+ hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[i * 4 + 2], vt[i * 4 + 3], &o0_hi, &o1_hi);
+
+ HVX_Vector vout0 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max));
+ HVX_Vector vout1 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max));
+
+ hvx_vmemu(dst + i * 64) = vout0;
+ hvx_vmemu(dst + he + i * 64) = vout1;
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPair vp0 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + nvec * 64));
+ HVX_VectorPair vp1 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + he + nvec * 64));
+
+ HVX_Vector o0_lo, o1_lo;
+ hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[nvec * 4 + 0], vt[nvec * 4 + 1], &o0_lo, &o1_lo);
+ o0_lo = hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max);
+ o1_lo = hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max);
+
+ HVX_Vector o0_hi = o0_lo;
+ HVX_Vector o1_hi = o1_lo;
+ if (nloe > 32) {
+ hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[nvec * 4 + 2], vt[nvec * 4 + 3], &o0_hi, &o1_hi);
+ o0_hi = hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max);
+ o1_hi = hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max);
+ }
+
+ HVX_Vector vout0 = hvx_vec_f32_to_f16(o0_lo, o0_hi);
+ HVX_Vector vout1 = hvx_vec_f32_to_f16(o1_lo, o1_hi);
+
+ hvx_vec_store_u(dst + nvec * 64, nloe * sizeof(_Float16), vout0);
+ hvx_vec_store_u(dst + he + nvec * 64, nloe * sizeof(_Float16), vout1);
+ }
+}
+
+static __attribute__((noinline)) void hvx_rope_f16(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) {
+ const uint32_t nvec = ne / 64;
+ const uint32_t nloe = ne % 64;
+
+ const HVX_Vector * vt = (const HVX_Vector *) theta_cache;
+
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + i * 64));
+
+ HVX_Vector o0, o1;
+ hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[i * 2 + 0], vt[i * 2 + 1], &o0, &o1);
+
+ HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max));
+
+ hvx_vmemu(dst + i * 64) = vout;
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + nvec * 64));
+
+ HVX_Vector o0, o1;
+ hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[nvec * 2 + 0], vt[nvec * 2 + 1], &o0, &o1);
+
+ HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max),
+ hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max));
+
+ hvx_vec_store_u(dst + nvec * 64, nloe * sizeof(_Float16), vout);
+ }
+}
+
+static __attribute__((noinline)) void rope_basic_f16_aa_inplace(const struct htp_rope_context * rctx, uint8_t * src,
+ uint32_t nr, const float * restrict theta_cache) {
+ const uint32_t n_offs = rctx->n_offs;
+ #pragma unroll(4)
+ for (uint32_t i = 0; i < nr; i++) {
+ _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned);
+ hvx_rope_f16_aa(s + n_offs, s + n_offs, rctx->n_dims, theta_cache);
+ }
+}
+
+static __attribute__((noinline)) void rope_basic_f16_ua_inplace(const struct htp_rope_context * rctx, uint8_t * src,
+ uint32_t nr, const float * restrict theta_cache) {
+ const uint32_t n_offs = rctx->n_offs;
+ for (uint32_t i = 0; i < nr; i++) {
+ _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned);
+ hvx_rope_f16(s + n_offs, s + n_offs, rctx->n_dims, theta_cache);
+ }
+}
+
+static __attribute__((noinline)) void rope_neox_f16_aa_inplace(const struct htp_rope_context * rctx, uint8_t * src,
+ uint32_t nr, const float * restrict theta_cache) {
+ const uint32_t n_offs = rctx->n_offs;
+ const uint32_t ne = rctx->ne_rot;
+ #pragma unroll(4)
+ for (uint32_t i = 0; i < nr; i++) {
+ _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned);
+ hvx_rope_neox_f16_aa(s + n_offs, s + n_offs, ne, theta_cache);
+ }
+}
+
+static __attribute__((noinline)) void rope_neox_f16_ua_inplace(const struct htp_rope_context * rctx, uint8_t * src,
+ uint32_t nr, const float * restrict theta_cache) {
+ const uint32_t n_offs = rctx->n_offs;
+ const uint32_t ne = rctx->ne_rot;
+ for (uint32_t i = 0; i < nr; i++) {
+ _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned);
+ hvx_rope_neox_f16(s + n_offs, s + n_offs, ne, theta_cache);
+ }
+}
+
+static inline void rope_init_token_cache(const struct htp_rope_context * rctx, uint32_t i2, float * cache) {
+ const struct htp_tensor * dst = rctx->octx->dst;
+ const uint32_t ne2 = dst->ne[2];
+ const int32_t * pos = rctx->pos_data;
+ const bool is_mrope = (rctx->mode & HTP_ROPE_TYPE_MROPE) != 0;
+ const bool is_vision = (rctx->mode == HTP_ROPE_TYPE_VISION);
+
+ if (is_mrope) {
+ // src1 holds four position arrays stacked along ne0: pos[i2 + k*ne2]
+ const bool is_imrope = (rctx->mode == HTP_ROPE_TYPE_IMROPE);
+ mrope_cache_init(
+ (float) pos[i2],
+ (float) pos[i2 + ne2],
+ (float) pos[i2 + ne2 * 2],
+ (float) pos[i2 + ne2 * 3],
+ rctx->sections, is_imrope, is_vision,
+ rctx->freq_scale, rctx->freq_factors, (float *) rctx->corr_dims,
+ rctx->ne_rot, rctx->ext_factor, rctx->attn_factor,
+ cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32);
+ } else {
+ rope_cache_init(
+ (float) pos[i2], rctx->freq_scale, rctx->freq_factors, (float *) rctx->corr_dims,
+ rctx->ne_rot, rctx->ext_factor, rctx->attn_factor,
+ cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32);
+ }
+}
+
+static void rope_cs_precomp_task(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ const struct htp_rope_context * rctx = (const struct htp_rope_context *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint32_t count = rctx->cs_i2_count;
+ const uint32_t per_hvx = (count + nth - 1) / nth;
+ const uint32_t t0 = per_hvx * ith;
+ const uint32_t t1 = MIN(t0 + per_hvx, count);
+
+ if (t0 >= t1) {
+ return;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, rctx->cs_i2_base + t0);
+ for (uint32_t t = t0; t < t1; t++) {
+ float * cache = (float *) (rctx->cs_table + (size_t) t * rctx->cs_stride);
+ rope_init_token_cache(rctx, rctx->cs_i2_base + t, cache);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, rctx->cs_i2_base + t0);
+}
+
+static void rope_task_precomp(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ const struct htp_rope_context * rctx = (const struct htp_rope_context *) data;
+ struct htp_ops_context * octx = rctx->octx;
+
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
+
+ const uint32_t ne1 = dst->ne[1];
+ const uint32_t ne2 = dst->ne[2];
+ const uint32_t ne3 = dst->ne[3];
+ const uint32_t nb01 = src0->nb[1];
+ const uint32_t nb03 = src0->nb[3];
+ const uint32_t nb1 = dst->nb[1];
+ const uint32_t nb3 = dst->nb[3];
+
+ const uint32_t src0_nrows = rctx->nrows;
+ const uint32_t src0_nrows_per_hvx = rctx->src0_nrows_per_hvx;
+
+ const uint32_t src0_start_row = rctx->row_start + src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, rctx->row_start + src0_nrows);
+
+ if (src0_start_row >= src0_end_row) {
+ return;
+ }
+
+ uint8_t * src0_spad_base = rctx->vtcm_base + (ith * rctx->spad_per_hvx) + rctx->theta_cache_offset;
+ dma_queue * dma_q = th->dma_q;
+ struct htp_thread_trace * tr = th->trace;
+
+ const uint8_t * cs_table = rctx->cs_table;
+ const size_t cs_stride = rctx->cs_stride;
+ const uint32_t cs_i2_base = rctx->cs_i2_base;
+
+ const uint32_t ne2_ne1 = ne2 * ne1;
+ const uint32_t i3_start = fastdiv(src0_start_row, &rctx->div_ne2_ne1);
+ const uint32_t rem = fastmodulo(src0_start_row, ne2_ne1, &rctx->div_ne2_ne1);
+ const uint32_t i2_start = fastdiv(rem, &rctx->div_ne1);
+ const uint32_t i1_start = fastmodulo(rem, ne1, &rctx->div_ne1);
+
+ uint32_t ir = src0_start_row;
+ uint32_t cur_slot = 0;
+
+ for (uint32_t i3 = i3_start; i3 < ne3 && ir < src0_end_row; i3++) {
+ uint32_t cur_i2 = (i3 == i3_start) ? i2_start : 0;
+ uint32_t cur_i1 = (i3 == i3_start) ? i1_start : 0;
+ const uint32_t b_row0 = cur_i2 * ne1 + cur_i1;
+ const uint32_t nrows = MIN(src0_end_row - ir, ne2_ne1 - b_row0);
+
+ const dma_addr_t src0_b_base = src0->data + (size_t) i3 * nb03;
+ const dma_addr_t dst_b_base = dst->data + (size_t) i3 * nb3;
+ const uint32_t dma_depth = dma_queue_depth(dma_q);
+
+ const uint32_t p_nrows = MIN(nrows, 2 * HTP_ROPE_SPAD_BLOCK);
+ for (uint32_t pr = 0; pr < p_nrows; pr += HTP_ROPE_SPAD_BLOCK) {
+ const uint32_t pnr = MIN(nrows - pr, HTP_ROPE_SPAD_BLOCK);
+ const uint32_t slot = (cur_slot + pr / HTP_ROPE_SPAD_BLOCK) % HTP_ROPE_SPAD_NSLOTS;
+ uint8_t * spad_slot = rope_spad_slot(src0_spad_base, slot, rctx->src0_row_size_aligned);
+ const dma_addr_t src0_data = src0_b_base + (size_t) (b_row0 + pr) * nb01;
+
+ dma_queue_push(dma_q, dma_make_data(dst->data, spad_slot), 0, 0, 0, 0);
+ dma_queue_push(dma_q, dma_make_data(spad_slot, src0_data),
+ rctx->src0_row_size_aligned, rctx->src0_row_stride, rctx->src0_row_size, pnr);
+ }
+
+ for (uint32_t d = 0; d < dma_depth; d++) { dma_queue_pop_nowait(dma_q); }
+
+ for (uint32_t cnr = 0, cr = 0; cr < nrows; cr += cnr) {
+ cnr = MIN(nrows - cr, HTP_ROPE_SPAD_BLOCK);
+
+ dma_queue_pop(dma_q);
+ uint8_t * cur_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir + cr);
+ uint32_t rem_c = cnr;
+ uint8_t * p = cur_spad;
+ while (rem_c > 0) {
+ const uint32_t run = MIN(rem_c, ne1 - cur_i1);
+ const float * cs = (const float *) (cs_table + (size_t) (cur_i2 - cs_i2_base) * cs_stride);
+ rctx->compute_block(rctx, p, run, cs);
+ p += run * rctx->src0_row_size_aligned;
+ rem_c -= run;
+ cur_i1 += run;
+ if (cur_i1 == ne1) {
+ cur_i1 = 0;
+ cur_i2++;
+ }
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir + cr);
+
+ const dma_addr_t dst_data = dst_b_base + (size_t) (b_row0 + cr) * nb1;
+ dma_queue_push(dma_q, dma_make_data(dst_data, cur_spad),
+ rctx->dst_row_stride, rctx->src0_row_size_aligned, rctx->dst_row_size, cnr);
+
+ if ((cr + 2 * HTP_ROPE_SPAD_BLOCK) < nrows) {
+ const uint32_t p_cr = cr + 2 * HTP_ROPE_SPAD_BLOCK;
+ const uint32_t pnr = MIN(nrows - p_cr, HTP_ROPE_SPAD_BLOCK);
+ const uint32_t p_slot = (cur_slot + p_cr / HTP_ROPE_SPAD_BLOCK) % HTP_ROPE_SPAD_NSLOTS;
+ uint8_t * p_spad = rope_spad_slot(src0_spad_base, p_slot, rctx->src0_row_size_aligned);
+ const dma_addr_t p_src0_data = src0_b_base + (size_t) (b_row0 + p_cr) * nb01;
+
+ dma_queue_push(dma_q, dma_make_data(p_spad, p_src0_data),
+ rctx->src0_row_size_aligned, rctx->src0_row_stride, rctx->src0_row_size, pnr);
+ }
+ }
+
+ const uint32_t n_chunks = (nrows + HTP_ROPE_SPAD_BLOCK - 1) / HTP_ROPE_SPAD_BLOCK;
+ cur_slot = (cur_slot + n_chunks) % HTP_ROPE_SPAD_NSLOTS;
+ ir += nrows;
+ }
+
+ dma_queue_flush(dma_q);
+
+ FARF(HIGH, "rope-precomp: %d/%d: (%u:%u)\n", ith, nth, src0_start_row, src0_end_row);
+}
+
+static void rope_task(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_rope_context * rctx = (struct htp_rope_context *) data;
struct htp_ops_context * octx = rctx->octx;
const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * src1 = octx->src[1];
- const struct htp_tensor * src2 = octx->src[2];
const struct htp_tensor * dst = octx->dst;
htp_rope_preamble;
@@ -554,11 +1033,6 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int
return;
}
- const int32_t mode = rctx->mode;
- // MROPE, IMROPE and VISION use NEOX-style pairing for the rotation
- const bool is_neox = (mode & HTP_ROPE_TYPE_NEOX) || (mode & HTP_ROPE_TYPE_MROPE);
- const bool is_vision = (mode == HTP_ROPE_TYPE_VISION);
-
// VTCM setup
uint8_t * src0_spad_base = rctx->vtcm_base + (ith * rctx->spad_per_hvx);
float * theta_cache = (float *) (src0_spad_base);
@@ -566,8 +1040,6 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int
dma_queue * dma_q = th->dma_q;
struct htp_thread_trace * tr = th->trace;
- const int32_t * pos = (const int32_t *) (uintptr_t) src1->data;
- const float * freq_factors = rctx->freq_factors;
const uint32_t i3_start = fastdiv(src0_start_row, &rctx->div_ne2_ne1);
const uint32_t rem = fastmodulo(src0_start_row, ne2 * ne1, &rctx->div_ne2_ne1);
@@ -606,32 +1078,10 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int
rctx->src0_row_size_aligned, rctx->src0_row_stride, rctx->src0_row_size, pnr);
}
- // Update theta cache
if (i2 != prev_i2) {
prev_i2 = i2;
-
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, i2);
- // VISION rotates the full row; other modes only rotate n_dims.
- const uint32_t n_cache = is_vision ? ne0 : (uint32_t) rctx->n_dims;
- const bool is_mrope = (rctx->mode & HTP_ROPE_TYPE_MROPE) != 0;
- if (is_mrope) {
- // src1 holds four position arrays stacked along ne0:
- // pos[i2], pos[i2+ne2], pos[i2+ne2*2], pos[i2+ne2*3]
- const bool is_imrope = (rctx->mode == HTP_ROPE_TYPE_IMROPE);
- mrope_cache_init(
- (float) pos[i2],
- (float) pos[i2 + ne2],
- (float) pos[i2 + ne2 * 2],
- (float) pos[i2 + ne2 * 3],
- rctx->sections, is_imrope, is_vision,
- rctx->freq_scale, freq_factors, rctx->corr_dims,
- n_cache, rctx->ext_factor, rctx->attn_factor,
- theta_cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32);
- } else {
- rope_cache_init(pos[i2], rctx->freq_scale, freq_factors, rctx->corr_dims,
- n_cache, rctx->ext_factor, rctx->attn_factor,
- theta_cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32);
- }
+ rope_init_token_cache(rctx, i2, theta_cache);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, i2);
}
@@ -639,13 +1089,11 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int
for (uint32_t d = 0; d < dma_depth; d++) { dma_queue_pop_nowait(dma_q); }
// Compute loop
- const uint32_t ne = is_vision ? ne0 : rctx->n_dims;
const uint32_t base_i1 = i1;
const uint32_t base_ir = ir;
for (uint32_t cnr = 0, cr = 0; cr < nrows; cr += cnr) {
cnr = MIN(nrows - cr, HTP_ROPE_SPAD_BLOCK);
- const uint32_t slot = (cur_slot + cr / HTP_ROPE_SPAD_BLOCK) % HTP_ROPE_SPAD_NSLOTS;
const uint32_t cur_ir = base_ir + cr;
const uint32_t cur_i1 = base_i1 + cr;
@@ -653,11 +1101,7 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int
uint8_t * cur_spad = (uint8_t *) dma_queue_pop(dma_q).dst;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, cur_ir);
- if (is_neox || is_vision) {
- rope_neox_f32_inplace(rctx, cur_spad, cnr, ne, theta_cache);
- } else {
- rope_basic_f32_inplace(rctx, cur_spad, cnr, theta_cache);
- }
+ rctx->compute_block(rctx, cur_spad, cnr, theta_cache);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, cur_ir);
const dma_addr_t dst_data = dst->data + i3 * nb3 + i2 * nb2 + cur_i1 * nb1;
@@ -689,10 +1133,32 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int
done:
dma_queue_flush(dma_q);
- FARF(HIGH, "rope-f32: %d/%d: (%u:%u)\n", ith, nth, src0_start_row, src0_end_row);
+ FARF(HIGH, "rope: %d/%d: (%u:%u)\n", ith, nth, src0_start_row, src0_end_row);
}
-static int execute_op_rope_f32(struct htp_ops_context * octx) {
+static inline void hvx_rope_init_theta_powers(float * dst, float theta_scale) {
+ static const int32_t lane_idx[32] __attribute__((aligned(128))) = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+ };
+ const HVX_Vector v_idx = *(const HVX_Vector *) lane_idx;
+ HVX_Vector v = Q6_Vqf32_vadd_VsfVsf(hvx_vec_splat_f32(1.0f), Q6_V_vzero());
+ HVX_Vector p = Q6_Vqf32_vadd_VsfVsf(hvx_vec_splat_f32(theta_scale), Q6_V_vzero());
+
+ #pragma clang loop unroll(full)
+ for (int bit = 0; bit < 5; ++bit) {
+ const HVX_Vector mask = Q6_V_vsplat_R(1 << bit);
+ const HVX_VectorPred q = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(v_idx, mask), mask);
+ v = Q6_V_vmux_QVV(q, Q6_Vqf32_vmpy_Vqf32Vqf32(v, p), v);
+ if (bit < 4) {
+ p = Q6_Vqf32_vmpy_Vqf32Vqf32(p, p);
+ }
+ }
+
+ hvx_vmemu(dst) = Q6_Vsf_equals_Vqf32(v);
+}
+
+static int execute_op_rope(struct htp_ops_context * octx) {
int err = HTP_STATUS_OK;
const struct htp_tensor * src0 = octx->src[0];
@@ -706,21 +1172,17 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) {
}
assert(octx->ctx->vtcm_size >= kparams->vtcm_size);
- if (htp_tensor_is_extended(src1)) {
- return HTP_STATUS_NO_SUPPORT;
- }
+ const bool is_f16 = (src0->type == HTP_TYPE_F16);
+ const size_t elem_size = is_f16 ? sizeof(_Float16) : sizeof(float);
const uint32_t total_rows = src0->ne[1] * src0->ne[2] * src0->ne[3];
- const size_t dst_data_row_size = dst->ne[0] * sizeof(float);
uint32_t row_start = 0;
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_data_row_size, &rows_per_chunk);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -732,21 +1194,34 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
const uint32_t ne0 = dst->ne[0];
- const size_t src0_row_size = src0->ne[0] * sizeof(float);
+ const size_t src0_row_size = src0->ne[0] * elem_size;
const size_t src0_row_stride = src0->nb[1];
- const size_t dst_row_size = dst->ne[0] * sizeof(float);
+ const size_t dst_row_size = dst->ne[0] * elem_size;
const size_t dst_row_stride = dst->nb[1];
struct htp_rope_vtcm_layout layout;
- htp_rope_vtcm_layout_build(&layout, src0->ne[0], kparams->n_hvx, src2 ? src2->ne[0] : 0);
+ htp_rope_vtcm_layout_build(&layout, src0->ne[0], elem_size, kparams->n_hvx, src2 ? src2->ne[0] : 0);
struct htp_rope_context rctx;
memset(&rctx, 0, sizeof(struct htp_rope_context));
+ const size_t pos_bytes = hex_round_up(htp_tensor_nbytes(src1), 128);
+ void * pos_buf = (pos_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, pos_bytes);
+ if (!pos_buf) {
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ if (htp_tensor_read(&octx->ctx->main_th, pos_buf, pos_bytes, src1) == 0) {
+ if (pos_buf != octx->ctx->ddr_spad_base) {
+ free(pos_buf);
+ }
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+
rctx.octx = octx;
rctx.vtcm_base = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_spad);
rctx.spad_per_hvx = layout.bytes_per_hvx;
rctx.theta_cache_offset = layout.theta_cache_size_aligned;
+ rctx.pos_data = (const int32_t *) pos_buf;
if (src2) {
dma_queue * dma_q = octx->ctx->dma[0];
@@ -759,27 +1234,20 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) {
}
const int32_t * op_params = &octx->op_params[0];
- rctx.n_dims = ((const int32_t *) op_params)[1];
- rctx.mode = ((const int32_t *) op_params)[2];
- rctx.n_ctx_orig = ((const int32_t *) op_params)[4];
- rctx.n_offs = ((const int32_t *) op_params)[15];
+ rctx.n_dims = ((const int32_t *) op_params)[1];
+ rctx.mode = ((const int32_t *) op_params)[2];
+ rctx.n_offs = ((const int32_t *) op_params)[15];
- memcpy(&rctx.freq_base, (int32_t *) op_params + 5, sizeof(float));
memcpy(&rctx.freq_scale, (int32_t *) op_params + 6, sizeof(float));
memcpy(&rctx.ext_factor, (int32_t *) op_params + 7, sizeof(float));
memcpy(&rctx.attn_factor, (int32_t *) op_params + 8, sizeof(float));
- memcpy(&rctx.beta_fast, (int32_t *) op_params + 9, sizeof(float));
- memcpy(&rctx.beta_slow, (int32_t *) op_params + 10, sizeof(float));
memcpy(&rctx.sections, (int32_t *) op_params + 11, sizeof(int) * 4);
- rctx.theta_scale = powf(rctx.freq_base, -2.0f / rctx.n_dims);
- rctx.theta_powers[0] = 1.0f;
- for (int j = 1; j < 32; j++) {
- rctx.theta_powers[j] = rctx.theta_powers[j - 1] * rctx.theta_scale;
- }
- rctx.theta_scale_32 = rctx.theta_powers[31] * rctx.theta_scale;
-
- rope_corr_dims(rctx.n_dims, rctx.n_ctx_orig, rctx.freq_base, rctx.beta_fast, rctx.beta_slow, rctx.corr_dims);
+ rctx.theta_scale = kparams->theta_scale;
+ rctx.theta_scale_32 = kparams->theta_scale_32;
+ hvx_rope_init_theta_powers(rctx.theta_powers, rctx.theta_scale);
+ rctx.corr_dims[0] = kparams->corr_dims[0];
+ rctx.corr_dims[1] = kparams->corr_dims[1];
rctx.src0_row_size = src0_row_size;
rctx.src0_row_stride = src0_row_stride;
@@ -787,25 +1255,83 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) {
rctx.dst_row_stride = dst_row_stride;
rctx.src0_row_size_aligned = layout.src0_row_size_aligned;
- rctx.src0_nrows = nrows;
rctx.nrows = nrows;
rctx.row_start = row_start;
rctx.src0_nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
rctx.div_ne2_ne1 = kparams->div_ne2_ne1;
rctx.div_ne1 = kparams->div_ne1;
- FARF(HIGH, "rope-f32 n-rows %u n-dims %d ne0 %u ext-factor %.6f theta-scale %.6f attn-factor %.6f\n", rctx.src0_nrows, rctx.n_dims, ne0,
+ // MROPE, IMROPE and VISION use NEOX-style pairing for the rotation; VISION rotates full ne0
+ const bool is_neox = (rctx.mode & HTP_ROPE_TYPE_NEOX) || (rctx.mode & HTP_ROPE_TYPE_MROPE);
+ const bool is_vision = (rctx.mode == HTP_ROPE_TYPE_VISION);
+ const bool f16_aa = (rctx.n_offs & 63) == 0;
+
+ rctx.ne_rot = is_vision ? ne0 : (uint32_t) rctx.n_dims;
+ if (is_f16) {
+ if (is_neox || is_vision) {
+ rctx.compute_block = f16_aa ? rope_neox_f16_aa_inplace : rope_neox_f16_ua_inplace;
+ } else {
+ rctx.compute_block = f16_aa ? rope_basic_f16_aa_inplace : rope_basic_f16_ua_inplace;
+ }
+ } else {
+ rctx.compute_block = (is_neox || is_vision) ? rope_neox_f32_inplace : rope_basic_f32_inplace;
+ }
+
+ const uint32_t ne1 = dst->ne[1];
+ const uint32_t ne2 = dst->ne[2];
+ const uint32_t ne3 = dst->ne[3];
+
+ uint32_t cs_i2_base = 0;
+ uint32_t cs_i2_count = ne2;
+ if (ne3 == 1) {
+ const uint32_t i2_first = fastdiv(row_start, &rctx.div_ne1);
+ const uint32_t i2_last = fastdiv(row_start + nrows - 1, &rctx.div_ne1);
+ cs_i2_base = i2_first;
+ cs_i2_count = i2_last - i2_first + 1;
+ }
+
+ // Precompute cos/sin and batch DMAs across tokens only when ne1 < HTP_ROPE_SPAD_BLOCK;
+ // for larger ne1, rope_task already issues full DMA blocks and overlaps cos/sin with DMA.
+ const bool want_precomp = (ne1 < HTP_ROPE_SPAD_BLOCK) && (cs_i2_count > 1) &&
+ (src0->nb[2] == ne1 * src0->nb[1]) &&
+ (dst->nb[2] == ne1 * dst->nb[1]);
+
+ if (want_precomp && rctx.ne_rot > 0) {
+ const size_t cs_stride = hex_round_up((uint32_t) (rctx.ne_rot * sizeof(float)), 256);
+ const size_t cs_off = hex_round_up(layout.total_bytes, 256);
+ const size_t cs_bytes = (size_t) cs_i2_count * cs_stride;
+ if (cs_off + cs_bytes <= octx->ctx->vtcm_size) {
+ rctx.cs_table = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, cs_off);
+ rctx.cs_stride = cs_stride;
+ rctx.cs_i2_base = cs_i2_base;
+ rctx.cs_i2_count = cs_i2_count;
+
+ work_queue_run(octx->ctx->hvx_queue, rope_cs_precomp_task, &rctx, MIN(n_hvx, cs_i2_count));
+ }
+ }
+
+ FARF(HIGH, "rope-%s n-rows %u n-dims %d ne0 %u ext-factor %.6f theta-scale %.6f attn-factor %.6f\n",
+ is_f16 ? "f16" : "f32", rctx.nrows, rctx.n_dims, ne0,
rctx.ext_factor, rctx.theta_scale, rctx.attn_factor);
- work_queue_run(octx->ctx->hvx_queue, rope_job_f32, &rctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, rctx.cs_table ? rope_task_precomp : rope_task, &rctx, n_hvx);
+
+ if (pos_buf != octx->ctx->ddr_spad_base) {
+ free(pos_buf);
+ }
return err;
}
int op_rope(struct htp_ops_context * octx) {
+ if (octx->src[0]->type != octx->dst->type) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
switch (octx->src[0]->type) {
case HTP_TYPE_F32:
- return execute_op_rope_f32(octx);
+ case HTP_TYPE_F16:
+ return execute_op_rope(octx);
default:
return HTP_STATUS_NO_SUPPORT;
diff --git a/ggml/src/ggml-hexagon/htp/rope-ops.h b/ggml/src/ggml-hexagon/htp/rope-ops.h
index a21b85c06..d5418d214 100644
--- a/ggml/src/ggml-hexagon/htp/rope-ops.h
+++ b/ggml/src/ggml-hexagon/htp/rope-ops.h
@@ -13,6 +13,10 @@ struct htp_rope_kernel_params {
uint32_t n_hvx;
uint32_t vtcm_size;
+ float theta_scale;
+ float theta_scale_32;
+ float corr_dims[2];
+
struct fastdiv_values div_ne2_ne1;
struct fastdiv_values div_ne1;
};
@@ -36,12 +40,13 @@ struct htp_rope_vtcm_layout {
static inline void htp_rope_vtcm_layout_build(
struct htp_rope_vtcm_layout * L,
uint32_t ne00,
+ size_t elem_size,
uint32_t n_hvx,
uint32_t n_freq_factors
) {
- const size_t src0_row_size = ne00 * sizeof(float);
+ const size_t src0_row_size = ne00 * elem_size;
const size_t src0_row_size_aligned = hex_round_up((uint32_t) src0_row_size, 128);
- const size_t theta_cache_size_aligned = hex_round_up((uint32_t) src0_row_size, 256);
+ const size_t theta_cache_size_aligned = hex_round_up((uint32_t) (ne00 * sizeof(float)), 256);
const size_t freq_factors_size_aligned = hex_round_up(n_freq_factors * sizeof(float), 256);
L->src0_row_size_aligned = src0_row_size_aligned;
diff --git a/ggml/src/ggml-hexagon/htp/set-rows-ops.c b/ggml/src/ggml-hexagon/htp/set-rows-ops.c
index add91408f..ec6db870b 100644
--- a/ggml/src/ggml-hexagon/htp/set-rows-ops.c
+++ b/ggml/src/ggml-hexagon/htp/set-rows-ops.c
@@ -1,14 +1,12 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <math.h>
+#include <stdlib.h>
#include <string.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "work-queue.h"
#include "hvx-utils.h"
#include "hex-utils.h"
@@ -24,186 +22,235 @@
#include "htp-tensor.h"
#include "htp/set-rows-ops.h"
-#define set_rows_preamble \
- const uint32_t ne00 = octx->src[0]->ne[0]; \
- const uint32_t ne01 = octx->src[0]->ne[1]; \
- const uint32_t ne02 = octx->src[0]->ne[2]; \
- const uint32_t ne03 = octx->src[0]->ne[3]; \
- \
- const uint32_t ne10 = octx->src[1]->ne[0]; \
- const uint32_t ne11 = octx->src[1]->ne[1]; \
- const uint32_t ne12 = octx->src[1]->ne[2]; \
- const uint32_t ne13 = octx->src[1]->ne[3]; \
- \
- const uint32_t nb01 = octx->src[0]->nb[1]; \
- const uint32_t nb02 = octx->src[0]->nb[2]; \
- const uint32_t nb03 = octx->src[0]->nb[3]; \
- \
- const uint32_t nb10 = octx->src[1]->nb[0]; \
- const uint32_t nb11 = octx->src[1]->nb[1]; \
- const uint32_t nb12 = octx->src[1]->nb[2]; \
- \
- const uint32_t nb1 = octx->dst->nb[1]; \
- const uint32_t nb2 = octx->dst->nb[2]; \
- const uint32_t nb3 = octx->dst->nb[3]; \
- \
- const uint32_t ne0 = octx->dst->ne[0]; \
- const uint32_t ne1 = octx->dst->ne[1]; \
- const uint32_t ne2 = octx->dst->ne[2]; \
- const uint32_t ne3 = octx->dst->ne[3]; \
- \
- const uint32_t nr = ne01;
+#define set_rows_preamble \
+ const uint32_t __attribute__((unused)) ne00 = octx->src[0]->ne[0]; \
+ const uint32_t __attribute__((unused)) ne01 = octx->src[0]->ne[1]; \
+ const uint32_t __attribute__((unused)) ne02 = octx->src[0]->ne[2]; \
+ const uint32_t __attribute__((unused)) ne03 = octx->src[0]->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) ne10 = octx->src[1]->ne[0]; \
+ const uint32_t __attribute__((unused)) ne11 = octx->src[1]->ne[1]; \
+ const uint32_t __attribute__((unused)) ne12 = octx->src[1]->ne[2]; \
+ const uint32_t __attribute__((unused)) ne13 = octx->src[1]->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb01 = octx->src[0]->nb[1]; \
+ const uint32_t __attribute__((unused)) nb02 = octx->src[0]->nb[2]; \
+ const uint32_t __attribute__((unused)) nb03 = octx->src[0]->nb[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb10 = octx->src[1]->nb[0]; \
+ const uint32_t __attribute__((unused)) nb11 = octx->src[1]->nb[1]; \
+ const uint32_t __attribute__((unused)) nb12 = octx->src[1]->nb[2]; \
+ \
+ const uint32_t __attribute__((unused)) nb1 = octx->dst->nb[1]; \
+ const uint32_t __attribute__((unused)) nb2 = octx->dst->nb[2]; \
+ const uint32_t __attribute__((unused)) nb3 = octx->dst->nb[3]; \
+ \
+ const uint32_t __attribute__((unused)) ne0 = octx->dst->ne[0]; \
+ const uint32_t __attribute__((unused)) ne1 = octx->dst->ne[1]; \
+ const uint32_t __attribute__((unused)) ne2 = octx->dst->ne[2]; \
+ const uint32_t __attribute__((unused)) ne3 = octx->dst->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) nr = ne01;
+
+typedef void (*set_rows_compute_fn_t)(void * restrict dst, const void * restrict src, uint32_t n);
struct set_rows_context {
struct htp_ops_context * octx;
const struct htp_set_rows_kernel_params * kparams;
struct htp_set_rows_vtcm_layout vtcm_layout;
+ set_rows_compute_fn_t compute;
uint8_t * vtcm_base;
+ const void * src1_data;
uint32_t task_start;
uint32_t tasks;
uint32_t tasks_per_hvx;
+ bool is_i32;
};
-#define SET_ROWS_THREAD_DMA_FN(TYPE_NAME, IDX_TYPE, COMPUTE_EXPR) \
-static void set_rows_thread_dma_##TYPE_NAME##_##IDX_TYPE(const htp_thread_t * th, unsigned int nth, \
- unsigned int ith, void *data) { \
- struct set_rows_context * srctx = (struct set_rows_context *)data; \
- struct htp_ops_context * octx = srctx->octx; \
- const struct htp_set_rows_kernel_params * kparams = srctx->kparams; \
- set_rows_preamble; \
- struct htp_thread_trace * tr = th->trace; \
- const uint32_t dr = srctx->tasks_per_hvx; \
- const uint32_t ir0 = srctx->task_start + dr * ith; \
- if (ir0 >= srctx->task_start + srctx->tasks) { \
- return; \
- } \
- const uint32_t ir1 = MIN(ir0 + dr, srctx->task_start + srctx->tasks); \
- dma_queue * dma_q = th->dma_q; \
- const struct htp_set_rows_vtcm_layout * vtcm_layout = &srctx->vtcm_layout; \
- uint8_t * vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_src0) + \
- ith * vtcm_layout->src0_bytes_per_hvx; \
- uint8_t * vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_dst) + \
- ith * vtcm_layout->dst_bytes_per_hvx; \
- const uint32_t src0_row_size = ne00 * sizeof(float); \
- const uint32_t dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00); \
- const uint32_t nrows_per_hvx = ir1 - ir0; \
- const uint32_t total_steps = ne03 * ne02 * nrows_per_hvx; \
- uint32_t pi_step = 0; \
- uint32_t pi02 = 0; \
- uint32_t pi03 = 0; \
- for (uint32_t step = 0, spad_idx = 0; step < total_steps && spad_idx < 2; ++step, spad_idx++) { \
- uint32_t i = ir0 + pi_step; \
- const dma_addr_t src0_data = octx->src[0]->data + i*nb01 + pi02*nb02 + pi03*nb03; \
- dma_queue_push(dma_q, \
- dma_make_data(octx->dst->data, \
- vtcm_dst + spad_idx * vtcm_layout->dst_spad_half_size), \
- dst_row_size, vtcm_layout->dst_spad_half_size, dst_row_size, 0); \
- dma_queue_push(dma_q, \
- dma_make_data(vtcm_src0 + spad_idx * vtcm_layout->src0_spad_half_size, \
- src0_data), \
- vtcm_layout->src0_spad_half_size, src0_row_size, src0_row_size, 1); \
- pi_step++; \
- if (pi_step == nrows_per_hvx) { \
- pi_step = 0; \
- pi02++; \
- if (pi02 == ne02) { \
- pi02 = 0; \
- pi03++; \
- } \
- } \
- } \
- uint32_t ci_step = 0; \
- uint32_t ci02 = 0; \
- uint32_t ci03 = 0; \
- uint32_t ci11_base = 0; \
- uint32_t ci12_base = 0; \
- for (uint32_t step = 0; step < total_steps; ++step) { \
- void * dst_spad = (void *) dma_queue_pop(dma_q).src; \
- void * src_spad = (void *) dma_queue_pop(dma_q).dst; \
- uint32_t i = ir0 + ci_step; \
- const uintptr_t src1_addr = octx->src[1]->data + i*nb10 + ci11_base*nb11 + ci12_base*nb12; \
- const IDX_TYPE i1 = *(const IDX_TYPE *)src1_addr; \
- const bool valid_i1 = ((uint64_t)i1 < (uint64_t)ne1); \
- const uint32_t target_i1 = (uint32_t)i1; \
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, step); \
- if (valid_i1) { \
- COMPUTE_EXPR; \
- } \
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, step); \
- if (valid_i1) { \
- const dma_addr_t dst_data = octx->dst->data + target_i1*nb1 + ci02*nb2 + ci03*nb3; \
- dma_queue_push(dma_q, \
- dma_make_data(dst_data, dst_spad), \
- dst_row_size, vtcm_layout->dst_spad_half_size, dst_row_size, 1); \
- } else { \
- dma_queue_push(dma_q, \
- dma_make_data(octx->dst->data, dst_spad), \
- dst_row_size, vtcm_layout->dst_spad_half_size, dst_row_size, 0); \
- } \
- const uint32_t next_step = step + 2; \
- if (next_step < total_steps) { \
- uint32_t ni = ir0 + pi_step; \
- const dma_addr_t psrc0_data = octx->src[0]->data + ni*nb01 + pi02*nb02 + pi03*nb03; \
- dma_queue_push(dma_q, \
- dma_make_data(src_spad, psrc0_data), \
- vtcm_layout->src0_spad_half_size, src0_row_size, src0_row_size, 1); \
- pi_step++; \
- if (pi_step == nrows_per_hvx) { \
- pi_step = 0; \
- pi02++; \
- if (pi02 == ne02) { \
- pi02 = 0; \
- pi03++; \
- } \
- } \
- } \
- ci_step++; \
- if (ci_step == nrows_per_hvx) { \
- ci_step = 0; \
- ci02++; \
- ci11_base++; \
- if (ci11_base == ne11) { \
- ci11_base = 0; \
- } \
- if (ci02 == ne02) { \
- ci02 = 0; \
- ci03++; \
- ci12_base++; \
- if (ci12_base == ne12) { \
- ci12_base = 0; \
- } \
- } \
- } \
- } \
- dma_queue_flush(dma_q); \
+static __attribute__((noinline)) void set_rows_row_f32_f32(void * restrict dst, const void * restrict src, uint32_t n) {
+ hvx_copy_f32_uu((uint8_t *) dst, (const uint8_t *) src, n);
}
-SET_ROWS_THREAD_DMA_FN(f32, int32_t, { hvx_copy_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); })
-SET_ROWS_THREAD_DMA_FN(f32, int64_t, { hvx_copy_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); })
+static __attribute__((noinline)) void set_rows_row_f16_f32(void * restrict dst, const void * restrict src, uint32_t n) {
+ hvx_copy_f16_f32_uu((uint8_t *) dst, (const uint8_t *) src, n);
+}
-SET_ROWS_THREAD_DMA_FN(f16, int32_t, { hvx_copy_f16_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); })
-SET_ROWS_THREAD_DMA_FN(f16, int64_t, { hvx_copy_f16_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); })
+static __attribute__((noinline)) void set_rows_row_q8_0_f32(void * restrict dst, const void * restrict src, uint32_t n) {
+ hvx_quantize_row_q8_0_f32(dst, (const float *) src, n);
+}
-SET_ROWS_THREAD_DMA_FN(q8_0, int32_t, { hvx_quantize_row_q8_0_f32(dst_spad, (const float *)src_spad, ne00); })
-SET_ROWS_THREAD_DMA_FN(q8_0, int64_t, { hvx_quantize_row_q8_0_f32(dst_spad, (const float *)src_spad, ne00); })
+static __attribute__((noinline)) void set_rows_row_f32_f16(void * restrict dst, const void * restrict src, uint32_t n) {
+ hvx_copy_f32_f16_uu((uint8_t *) dst, (const uint8_t *) src, n);
+}
-int op_set_rows(struct htp_ops_context * octx) {
- const struct htp_set_rows_kernel_params * kparams = (const struct htp_set_rows_kernel_params *)octx->kernel_params;
+static __attribute__((noinline)) void set_rows_row_f16_f16(void * restrict dst, const void * restrict src, uint32_t n) {
+ hvx_copy_f16_uu((uint8_t *) dst, (const uint8_t *) src, n);
+}
+
+static __attribute__((noinline)) void set_rows_row_q8_0_f16(void * restrict dst, const void * restrict src, uint32_t n) {
+ hvx_quantize_row_q8_0_f16(dst, (const __fp16 *) src, n);
+}
+
+struct set_rows_pipe_state {
+ dma_addr_t src0_data;
+ uintptr_t src1_data;
+ dma_addr_t dst_data;
+ set_rows_compute_fn_t compute;
+ uint32_t ne00;
+ uint32_t ne02;
+ uint32_t ne1;
+ uint32_t ne11;
+ uint32_t ne12;
+ uint32_t nb01, nb02, nb03;
+ uint32_t nb10, nb11, nb12;
+ uint32_t nb1, nb2, nb3;
+ uint32_t src0_row_size;
+ uint32_t dst_row_size;
+ size_t src0_spad_half;
+ size_t dst_spad_half;
+ uint32_t ir0;
+ uint32_t nrows_per_hvx;
+ uint32_t step;
+ uint32_t total_steps;
+ uint32_t ci_step;
+ uint32_t ci02;
+ uint32_t ci03;
+ uint32_t ci11_base;
+ uint32_t ci12_base;
+ bool is_i32;
+};
+
+static bool set_rows_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx;
+ if (s->step >= s->total_steps) {
+ return false;
+ }
+
+ const uint32_t i = s->ir0 + s->ci_step;
+ const uintptr_t src1_addr = s->src1_data + (size_t) i * s->nb10 + (size_t) s->ci11_base * s->nb11 + (size_t) s->ci12_base * s->nb12;
+ const uint64_t idx = s->is_i32 ? (uint64_t) *(const int32_t *) src1_addr : (uint64_t) *(const int64_t *) src1_addr;
+
+ task->row = i;
+ task->off = s->ci02;
+ task->len = s->ci03;
+ task->aux = (idx < (uint64_t) s->ne1) ? (uint32_t) idx : UINT32_MAX;
+
+ s->step++;
+ s->ci_step++;
+ if (s->ci_step == s->nrows_per_hvx) {
+ s->ci_step = 0;
+ s->ci02++;
+ s->ci11_base++;
+ if (s->ci11_base == s->ne11) {
+ s->ci11_base = 0;
+ }
+ if (s->ci02 == s->ne02) {
+ s->ci02 = 0;
+ s->ci03++;
+ s->ci12_base++;
+ if (s->ci12_base == s->ne12) {
+ s->ci12_base = 0;
+ }
+ }
+ }
+ return true;
+}
+
+static void set_rows_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx;
+ if (task->aux >= s->ne1) {
+ dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0);
+ return;
+ }
+ const dma_addr_t src0_addr = s->src0_data + (size_t) task->row * s->nb01 + (size_t) task->off * s->nb02 + (size_t) task->len * s->nb03;
+ dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr),
+ s->src0_spad_half, s->src0_row_size, s->src0_row_size, 1);
+}
+
+static void set_rows_pipe_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx;
+ if (task->aux < s->ne1) {
+ s->compute(out_spad, in_spad, s->ne00);
+ }
+}
+
+static void set_rows_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx;
+ if (task->aux >= s->ne1) {
+ dma_queue_push(dma_q, dma_make_data(0, out_spad), 0, 0, 0, 0);
+ return;
+ }
+ const dma_addr_t dst_addr = s->dst_data + (size_t) task->aux * s->nb1 + (size_t) task->off * s->nb2 + (size_t) task->len * s->nb3;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->dst_row_size, s->dst_spad_half, s->dst_row_size, 1);
+}
+
+static void set_rows_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ struct set_rows_context * srctx = (struct set_rows_context *) data;
+ struct htp_ops_context * octx = srctx->octx;
set_rows_preamble;
- if (htp_tensor_is_extended(octx->src[1])) {
- return HTP_STATUS_NO_SUPPORT;
+ const uint32_t dr = srctx->tasks_per_hvx;
+ const uint32_t ir0 = srctx->task_start + dr * ith;
+ if (ir0 >= srctx->task_start + srctx->tasks) {
+ return;
}
+ const uint32_t ir1 = MIN(ir0 + dr, srctx->task_start + srctx->tasks);
+
+ const struct htp_set_rows_vtcm_layout * vtcm_layout = &srctx->vtcm_layout;
+ uint8_t * vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_src0) + ith * vtcm_layout->src0_bytes_per_hvx;
+ uint8_t * vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_dst) + ith * vtcm_layout->dst_bytes_per_hvx;
+ void * in_buf[2] = { vtcm_src0, vtcm_src0 + vtcm_layout->src0_spad_half_size };
+ void * out_buf[2] = { vtcm_dst, vtcm_dst + vtcm_layout->dst_spad_half_size };
+
+ const uint32_t nrows_per_hvx = ir1 - ir0;
+ const uint32_t idx_elem_size = srctx->is_i32 ? sizeof(int32_t) : sizeof(int64_t);
+
+ struct set_rows_pipe_state s = {
+ .src0_data = octx->src[0]->data,
+ .src1_data = (uintptr_t) srctx->src1_data,
+ .dst_data = octx->dst->data,
+ .compute = srctx->compute,
+ .ne00 = ne00,
+ .ne02 = ne02,
+ .ne1 = ne1,
+ .ne11 = ne11,
+ .ne12 = ne12,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb10 = idx_elem_size, .nb11 = ne10 * idx_elem_size, .nb12 = ne10 * ne11 * idx_elem_size,
+ .nb1 = nb1, .nb2 = nb2, .nb3 = nb3,
+ .src0_row_size = htp_tensor_get_row_size(octx->src[0]->type, ne00),
+ .dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00),
+ .src0_spad_half = vtcm_layout->src0_spad_half_size,
+ .dst_spad_half = vtcm_layout->dst_spad_half_size,
+ .ir0 = ir0,
+ .nrows_per_hvx = nrows_per_hvx,
+ .step = 0,
+ .total_steps = ne03 * ne02 * nrows_per_hvx,
+ .ci_step = 0,
+ .ci02 = 0,
+ .ci03 = 0,
+ .ci11_base = 0,
+ .ci12_base = 0,
+ .is_i32 = srctx->is_i32,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ set_rows_next_task, set_rows_push_in, set_rows_pipe_compute, set_rows_push_out);
+}
+
+int op_set_rows(struct htp_ops_context * octx) {
+ const struct htp_set_rows_kernel_params * kparams = (const struct htp_set_rows_kernel_params *)octx->kernel_params;
+ set_rows_preamble;
- const struct htp_tensor * dst = octx->dst;
const uint32_t total_tasks = kparams->total_tasks;
uint32_t task_start = 0;
uint32_t tasks = total_tasks;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_mdev_data_aligned(dst) && (dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0 && !htp_tensor_is_permuted(dst);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
task_start = range.start;
tasks = range.count;
}
@@ -218,9 +265,6 @@ int op_set_rows(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
- // l2fetch the src1 (indices) tensor in the main thread
- hex_l2fetch_block((const void *)octx->src[1]->data, octx->src[1]->ne[3] * octx->src[1]->nb[3]);
-
struct set_rows_context srctx;
srctx.octx = octx;
srctx.kparams = kparams;
@@ -228,19 +272,43 @@ int op_set_rows(struct htp_ops_context * octx) {
srctx.tasks = tasks;
srctx.tasks_per_hvx = fastdiv(tasks + n_hvx - 1, &octx->n_hvx_div);
- htp_set_rows_vtcm_layout_build(&srctx.vtcm_layout, octx->dst->type, ne00, n_hvx);
+ htp_set_rows_vtcm_layout_build(&srctx.vtcm_layout, octx->src[0]->type, octx->dst->type, ne00, n_hvx);
srctx.vtcm_base = (uint8_t *)octx->ctx->vtcm_base;
- work_queue_func_t q_func = NULL;
- const bool is_i32 = (octx->src[1]->type == HTP_TYPE_I32);
+ srctx.is_i32 = (octx->src[1]->type == HTP_TYPE_I32);
+ srctx.compute = NULL;
- switch (octx->dst->type) {
- case HTP_TYPE_F32: q_func = is_i32 ? set_rows_thread_dma_f32_int32_t : set_rows_thread_dma_f32_int64_t; break;
- case HTP_TYPE_F16: q_func = is_i32 ? set_rows_thread_dma_f16_int32_t : set_rows_thread_dma_f16_int64_t; break;
- case HTP_TYPE_Q8_0: q_func = is_i32 ? set_rows_thread_dma_q8_0_int32_t : set_rows_thread_dma_q8_0_int64_t; break;
- default: return HTP_STATUS_NO_SUPPORT;
+ if (octx->src[0]->type == HTP_TYPE_F32) {
+ switch (octx->dst->type) {
+ case HTP_TYPE_F32: srctx.compute = set_rows_row_f32_f32; break;
+ case HTP_TYPE_F16: srctx.compute = set_rows_row_f16_f32; break;
+ case HTP_TYPE_Q8_0: srctx.compute = set_rows_row_q8_0_f32; break;
+ default: return HTP_STATUS_NO_SUPPORT;
+ }
+ } else if (octx->src[0]->type == HTP_TYPE_F16) {
+ switch (octx->dst->type) {
+ case HTP_TYPE_F32: srctx.compute = set_rows_row_f32_f16; break;
+ case HTP_TYPE_F16: srctx.compute = set_rows_row_f16_f16; break;
+ case HTP_TYPE_Q8_0: srctx.compute = set_rows_row_q8_0_f16; break;
+ default: return HTP_STATUS_NO_SUPPORT;
+ }
+ } else {
+ return HTP_STATUS_NO_SUPPORT;
}
+ const size_t src1_bytes = hex_round_up(htp_tensor_nbytes(octx->src[1]), 128);
+ void * src1_buf = (src1_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, src1_bytes);
+ if (!src1_buf) {
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ if (htp_tensor_read(&octx->ctx->main_th, src1_buf, src1_bytes, octx->src[1]) == 0) {
+ if (src1_buf != octx->ctx->ddr_spad_base) {
+ free(src1_buf);
+ }
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ srctx.src1_data = src1_buf;
+
FARF(HIGH, "set-rows: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : src0-vtcm-size %zu dst-vtcm-size %zu n-hvx %d\n",
octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3],
octx->src[1]->ne[0], octx->src[1]->ne[1], octx->src[1]->ne[2], octx->src[1]->ne[3],
@@ -249,7 +317,11 @@ int op_set_rows(struct htp_ops_context * octx) {
srctx.vtcm_layout.dst_bytes_per_hvx * n_hvx,
n_hvx);
- work_queue_run(octx->ctx->hvx_queue, q_func, &srctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, set_rows_thread, &srctx, n_hvx);
+
+ if (src1_buf != octx->ctx->ddr_spad_base) {
+ free(src1_buf);
+ }
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/set-rows-ops.h b/ggml/src/ggml-hexagon/htp/set-rows-ops.h
index 85086b08e..b693606d4 100644
--- a/ggml/src/ggml-hexagon/htp/set-rows-ops.h
+++ b/ggml/src/ggml-hexagon/htp/set-rows-ops.h
@@ -25,11 +25,12 @@ struct htp_set_rows_vtcm_layout {
static inline void htp_set_rows_vtcm_layout_build(
struct htp_set_rows_vtcm_layout * L,
+ int src0_type,
int dst_type,
uint32_t ne00,
uint32_t n_hvx) {
- size_t src0_row_size = ne00 * sizeof(float);
+ size_t src0_row_size = htp_tensor_get_row_size(src0_type, ne00);
size_t dst_row_size = htp_tensor_get_row_size(dst_type, ne00);
size_t src0_row_size_aligned = (src0_row_size + 255) & ~255;
diff --git a/ggml/src/ggml-hexagon/htp/softmax-ops.c b/ggml/src/ggml-hexagon/htp/softmax-ops.c
index 22aebcd5e..44293de06 100644
--- a/ggml/src/ggml-hexagon/htp/softmax-ops.c
+++ b/ggml/src/ggml-hexagon/htp/softmax-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -9,6 +5,7 @@
#include <string.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "work-queue.h"
#include "hvx-utils.h"
#include "hex-fastdiv.h"
@@ -28,7 +25,8 @@ struct htp_softmax_context {
struct htp_ops_context * octx;
const struct htp_softmax_kernel_params * kparams;
- void * compute;
+ void * prep;
+ void * softmax;
dma_addr_t data_src0;
dma_addr_t data_src1;
@@ -37,10 +35,13 @@ struct htp_softmax_context {
uint8_t * vtcm_src0;
uint8_t * vtcm_src1;
uint8_t * vtcm_dst;
+ uint8_t * vtcm_work;
+ float * vtcm_src2;
uint32_t vtcm_src0_size_per_hvx;
uint32_t vtcm_src1_size_per_hvx;
uint32_t vtcm_dst_size_per_hvx;
+ uint32_t vtcm_work_size_per_hvx;
uint32_t src0_spad_half_size;
uint32_t src1_spad_half_size;
@@ -50,7 +51,10 @@ struct htp_softmax_context {
uint32_t src1_row_size_aligned;
uint32_t dst_row_size_aligned;
+ bool src0_f16;
+ bool dst_f16;
bool use_f16;
+ bool use_src2;
uint32_t n_head;
uint32_t n_head_log2;
@@ -72,7 +76,7 @@ struct htp_softmax_context {
float slopes[512] __attribute__((aligned(128)));
};
-typedef void (*softmax_compute_fn_t)(
+typedef void (*softmax_prep_fn_t)(
void * restrict dst,
const void * restrict src0,
const void * restrict mask,
@@ -81,21 +85,82 @@ typedef void (*softmax_compute_fn_t)(
float slope
);
-static void hvx_fast_softmax_prep_f16(const uint8_t * restrict src,
- uint8_t * restrict dst,
- const int num_elems,
- float scale,
- const uint8_t * restrict mask,
- float slope) {
- const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+static __attribute__((noinline)) void hvx_fast_softmax_prep_nomask(
+ void * restrict dst,
+ const void * restrict src0,
+ const void * restrict mask,
+ uint32_t ne00,
+ float scale,
+ float slope
+) {
+ (void) mask;
+ (void) slope;
+ hvx_scale_f32((uint8_t *) dst, (const uint8_t *) src0, ne00, scale);
+}
+
+static __attribute__((noinline)) void hvx_fast_softmax_prep_src16_nomask(
+ void * restrict dst,
+ const void * restrict src0,
+ const void * restrict mask,
+ uint32_t ne00,
+ float scale,
+ float slope
+) {
+ (void) mask;
+ (void) slope;
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src0;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ HVX_Vector scale_vec = hvx_vec_splat_f32(scale);
+
+ const int nvec_64 = (int) ne00 / VLEN_FP16;
+ const int nloe_64 = (int) ne00 % VLEN_FP16;
+
+ #pragma unroll(2)
+ for (int i = 0; i < nvec_64; i++) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]);
+ HVX_Vector s0 = Q6_V_lo_W(p);
+ HVX_Vector s1 = Q6_V_hi_W(p);
+
+ v_dst[2 * i] = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec));
+ v_dst[2 * i + 1] = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec));
+ }
+
+ if (nloe_64 > 0) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[nvec_64]);
+ HVX_Vector s0 = Q6_V_lo_W(p);
+ HVX_Vector v0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec));
+
+ if (nloe_64 <= VLEN_FP32) {
+ hvx_vec_store_a(&v_dst[2 * nvec_64], nloe_64 * sizeof(float), v0);
+ } else {
+ v_dst[2 * nvec_64] = v0;
+
+ HVX_Vector s1 = Q6_V_hi_W(p);
+ HVX_Vector v1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec));
+
+ hvx_vec_store_a(&v_dst[2 * nvec_64 + 1], (nloe_64 - VLEN_FP32) * sizeof(float), v1);
+ }
+ }
+}
+
+static __attribute__((noinline)) void hvx_fast_softmax_prep_f16(
+ void * restrict dst,
+ const void * restrict src0,
+ const void * restrict mask,
+ uint32_t ne00,
+ float scale,
+ float slope
+) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src0;
HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask;
HVX_Vector scale_vec = hvx_vec_splat_f32(scale);
HVX_Vector slope_vec = hvx_vec_splat_f32(slope);
- const int nvec_64 = num_elems / VLEN_FP16;
- const int nloe_64 = num_elems % VLEN_FP16;
+ const int nvec_64 = (int) ne00 / VLEN_FP16;
+ const int nloe_64 = (int) ne00 % VLEN_FP16;
#pragma unroll(2)
for (int i = 0; i < nvec_64; i++) {
@@ -134,21 +199,23 @@ static void hvx_fast_softmax_prep_f16(const uint8_t * restrict src,
}
}
-static void hvx_fast_softmax_prep_f32(const uint8_t * restrict src,
- uint8_t * restrict dst,
- const int num_elems,
- float scale,
- const uint8_t * restrict mask,
- float slope) {
- const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+static __attribute__((noinline)) void hvx_fast_softmax_prep_f32(
+ void * restrict dst,
+ const void * restrict src0,
+ const void * restrict mask,
+ uint32_t ne00,
+ float scale,
+ float slope
+) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src0;
HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask;
HVX_Vector scale_vec = hvx_vec_splat_f32(scale);
HVX_Vector slope_vec = hvx_vec_splat_f32(slope);
- const int nvec = num_elems / VLEN_FP32;
- const int nloe = num_elems % VLEN_FP32;
+ const int nvec = (int) ne00 / VLEN_FP32;
+ const int nloe = (int) ne00 % VLEN_FP32;
#pragma unroll(4)
for (int i = 0; i < nvec; i++) {
@@ -174,76 +241,65 @@ static void hvx_fast_softmax_prep_f32(const uint8_t * restrict src,
}
}
-static void hvx_fast_softmax_f32(const uint8_t * restrict src, uint8_t * restrict dst, const int num_elems) {
- const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
- HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
-
- const int nvec = num_elems / VLEN_FP32;
- const int nloe = num_elems % VLEN_FP32;
-
- HVX_Vector max_vec = hvx_vec_splat_f32(((const float *) src)[0]);
-
- #pragma unroll(2)
- for (int i = 0; i < nvec; i++) {
- HVX_Vector v1 = v_src[i];
- max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v1);
- }
-
- if (nloe > 0) {
- HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float));
- HVX_Vector neg_inf = hvx_vec_splat_f32(-INFINITY);
- HVX_Vector v_tail = Q6_V_vmux_QVV(q_mask, v_src[nvec], neg_inf);
- max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v_tail);
- }
+static __attribute__((noinline)) void hvx_fast_softmax_prep_src16_mask_f16(
+ void * restrict dst,
+ const void * restrict src0,
+ const void * restrict mask,
+ uint32_t ne00,
+ float scale,
+ float slope
+) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src0;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask;
- max_vec = hvx_vec_reduce_max_f32(max_vec);
+ HVX_Vector scale_vec = hvx_vec_splat_f32(scale);
+ HVX_Vector slope_vec = hvx_vec_splat_f32(slope);
- HVX_Vector sum_vec = Q6_V_vsplat_R(0x00000000);
+ const int nvec_64 = (int) ne00 / VLEN_FP16;
+ const int nloe_64 = (int) ne00 % VLEN_FP16;
#pragma unroll(2)
- for (int i = 0; i < nvec; i++) {
- HVX_Vector v1 = v_src[i];
- HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec);
+ for (int i = 0; i < nvec_64; i++) {
+ HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[i]);
+ HVX_Vector s0 = Q6_V_lo_W(ps);
+ HVX_Vector s1 = Q6_V_hi_W(ps);
- HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2));
+ HVX_VectorPair pm = hvx_vec_f16_to_f32(v_mask[i]);
+ HVX_Vector m0 = Q6_V_lo_W(pm);
+ HVX_Vector m1 = Q6_V_hi_W(pm);
- sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3);
+ HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec));
+ HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec));
- v_dst[i] = v3;
+ v_dst[2 * i] = Q6_Vsf_equals_Vqf32(v0);
+ v_dst[2 * i + 1] = Q6_Vsf_equals_Vqf32(v1);
}
- if (nloe > 0) {
- HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float));
- HVX_Vector v1 = v_src[nvec];
- HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec);
- HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2));
- HVX_Vector v3_pad = Q6_V_vmux_QVV(q_mask, v3, Q6_V_vzero());
-
- sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3_pad);
- v_dst[nvec] = v3_pad;
- }
+ if (nloe_64 > 0) {
+ HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[nvec_64]);
+ HVX_Vector s0 = Q6_V_lo_W(ps);
- sum_vec = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_vec));
+ HVX_VectorPair pm = hvx_vec_f16_to_f32(v_mask[nvec_64]);
+ HVX_Vector m0 = Q6_V_lo_W(pm);
- HVX_VectorPred pos_sum = Q6_Q_vcmp_gt_VwVw(sum_vec, Q6_V_vzero());
- HVX_Vector v4 = hvx_vec_inverse_f32(sum_vec);
- HVX_Vector scale_vec = Q6_V_vmux_QVV(pos_sum, v4, hvx_vec_splat_f32(1.0f));
+ HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec));
- #pragma unroll(2)
- for (int i = 0; i < nvec; i++) {
- HVX_Vector v1 = v_dst[i];
- HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec);
- v_dst[i] = Q6_Vsf_equals_Vqf32(v2);
- }
+ if (nloe_64 <= VLEN_FP32) {
+ hvx_vec_store_a(&v_dst[2 * nvec_64], nloe_64 * sizeof(float), Q6_Vsf_equals_Vqf32(v0));
+ } else {
+ v_dst[2 * nvec_64] = Q6_Vsf_equals_Vqf32(v0);
- if (nloe > 0) {
- HVX_Vector v1 = v_dst[nvec];
- HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec);
- hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(float), Q6_Vsf_equals_Vqf32(v2));
+ HVX_Vector s1 = Q6_V_hi_W(ps);
+ HVX_Vector m1 = Q6_V_hi_W(pm);
+ HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec));
+
+ hvx_vec_store_a(&v_dst[2 * nvec_64 + 1], (nloe_64 - VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(v1));
+ }
}
}
-static void compute_fast_softmax_f32_nomask(
+static __attribute__((noinline)) void hvx_fast_softmax_prep_src16_mask_f32(
void * restrict dst,
const void * restrict src0,
const void * restrict mask,
@@ -251,236 +307,413 @@ static void compute_fast_softmax_f32_nomask(
float scale,
float slope
) {
- (void) mask;
- (void) slope;
- hvx_scale_f32((uint8_t *) dst, (const uint8_t *) src0, ne00, scale);
- hvx_fast_softmax_f32((const uint8_t *) dst, (uint8_t *) dst, ne00);
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src0;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask;
+
+ HVX_Vector scale_vec = hvx_vec_splat_f32(scale);
+ HVX_Vector slope_vec = hvx_vec_splat_f32(slope);
+
+ const int nvec_64 = (int) ne00 / VLEN_FP16;
+ const int nloe_64 = (int) ne00 % VLEN_FP16;
+
+ #pragma unroll(2)
+ for (int i = 0; i < nvec_64; i++) {
+ HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[i]);
+ HVX_Vector s0 = Q6_V_lo_W(ps);
+ HVX_Vector s1 = Q6_V_hi_W(ps);
+
+ HVX_Vector m0 = v_mask[2 * i];
+ HVX_Vector m1 = v_mask[2 * i + 1];
+
+ HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec));
+ HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec));
+
+ v_dst[2 * i] = Q6_Vsf_equals_Vqf32(v0);
+ v_dst[2 * i + 1] = Q6_Vsf_equals_Vqf32(v1);
+ }
+
+ if (nloe_64 > 0) {
+ HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[nvec_64]);
+ HVX_Vector s0 = Q6_V_lo_W(ps);
+ HVX_Vector m0 = v_mask[2 * nvec_64];
+ HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec));
+
+ if (nloe_64 <= VLEN_FP32) {
+ hvx_vec_store_a(&v_dst[2 * nvec_64], nloe_64 * sizeof(float), Q6_Vsf_equals_Vqf32(v0));
+ } else {
+ v_dst[2 * nvec_64] = Q6_Vsf_equals_Vqf32(v0);
+
+ HVX_Vector s1 = Q6_V_hi_W(ps);
+ HVX_Vector m1 = v_mask[2 * nvec_64 + 1];
+ HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec));
+
+ hvx_vec_store_a(&v_dst[2 * nvec_64 + 1], (nloe_64 - VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(v1));
+ }
+ }
}
-static void compute_fast_softmax_f32_mask_f32(
- void * restrict dst,
- const void * restrict src0,
- const void * restrict mask,
- uint32_t ne00,
- float scale,
- float slope
-) {
- hvx_fast_softmax_prep_f32((const uint8_t *) src0, (uint8_t *) dst, ne00, scale, (const uint8_t *) mask, slope);
- hvx_fast_softmax_f32((const uint8_t *) dst, (uint8_t *) dst, ne00);
+typedef void (*softmax_fn_t)(
+ uint8_t * restrict work,
+ uint8_t * restrict dst,
+ const int num_elems,
+ const float * restrict sink_ptr
+);
+
+#define DEFINE_HVX_FAST_SOFTMAX(SFX, HAS_SINK, DST_F16) \
+static __attribute__((noinline)) void hvx_fast_softmax_##SFX( \
+ uint8_t * restrict work, \
+ uint8_t * restrict dst, \
+ const int num_elems, \
+ const float * restrict sink_ptr \
+) { \
+ HVX_Vector * restrict v_work = (HVX_Vector *) work; \
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst; \
+ (void) sink_ptr; \
+ (void) v_dst; \
+ \
+ const int nvec = num_elems / VLEN_FP32; \
+ const int nloe = num_elems % VLEN_FP32; \
+ \
+ HVX_Vector max_vec = hvx_vec_repl4(v_work[0]); \
+ \
+ _Pragma("unroll(2)") \
+ for (int i = 0; i < nvec; i++) { \
+ HVX_Vector v1 = v_work[i]; \
+ max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v1); \
+ } \
+ \
+ if (nloe > 0) { \
+ HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float)); \
+ HVX_Vector neg_inf = hvx_vec_splat_f32(-INFINITY); \
+ HVX_Vector v_tail = Q6_V_vmux_QVV(q_mask, v_work[nvec], neg_inf); \
+ max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v_tail); \
+ } \
+ \
+ max_vec = hvx_vec_reduce_max_f32(max_vec); \
+ HVX_Vector sink_vec; \
+ if (HAS_SINK) { \
+ sink_vec = hvx_vec_repl4(hvx_vmemu(sink_ptr)); \
+ max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, sink_vec); \
+ } \
+ \
+ HVX_Vector sum_vec = Q6_V_vsplat_R(0x00000000); \
+ \
+ _Pragma("nounroll") \
+ _Pragma("clang loop pipeline(disable)") \
+ for (int i = 0; i < nvec; i++) { \
+ HVX_Vector v1 = v_work[i]; \
+ HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec); \
+ HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2)); \
+ \
+ sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3); \
+ v_work[i] = v3; \
+ } \
+ \
+ if (nloe > 0) { \
+ HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float)); \
+ HVX_Vector v1 = v_work[nvec]; \
+ HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec); \
+ HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2)); \
+ HVX_Vector v3_pad = Q6_V_vmux_QVV(q_mask, v3, Q6_V_vzero()); \
+ \
+ sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3_pad); \
+ v_work[nvec] = v3_pad; \
+ } \
+ \
+ sum_vec = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_vec)); \
+ if (HAS_SINK) { \
+ HVX_Vector sink_sub = Q6_Vqf32_vsub_VsfVsf(sink_vec, max_vec); \
+ HVX_Vector sink_exp = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(sink_sub)); \
+ sum_vec = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(sum_vec, sink_exp)); \
+ } \
+ \
+ HVX_VectorPred pos_sum = Q6_Q_vcmp_gt_VwVw(sum_vec, Q6_V_vzero()); \
+ HVX_Vector v4 = hvx_vec_inverse_f32(sum_vec); \
+ HVX_Vector scale_vec = Q6_V_vmux_QVV(pos_sum, v4, hvx_vec_splat_f32(1.0f)); \
+ \
+ if (DST_F16) { \
+ const int nvec_64 = num_elems / VLEN_FP16; \
+ const int nloe_64 = num_elems % VLEN_FP16; \
+ \
+ _Pragma("unroll(2)") \
+ for (int i = 0; i < nvec_64; i++) { \
+ HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * i], scale_vec)); \
+ HVX_Vector s1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * i + 1], scale_vec)); \
+ v_dst[i] = hvx_vec_f32_to_f16(s0, s1); \
+ } \
+ \
+ if (nloe_64 > 0) { \
+ HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * nvec_64], scale_vec)); \
+ HVX_Vector s1 = (nloe_64 > VLEN_FP32) \
+ ? Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * nvec_64 + 1], scale_vec)) \
+ : Q6_V_vzero(); \
+ HVX_Vector d = hvx_vec_f32_to_f16(s0, s1); \
+ hvx_vec_store_a(&v_dst[nvec_64], nloe_64 * sizeof(__fp16), d); \
+ } \
+ } else { \
+ _Pragma("unroll(2)") \
+ for (int i = 0; i < nvec; i++) { \
+ HVX_Vector v1 = v_work[i]; \
+ HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec); \
+ v_work[i] = Q6_Vsf_equals_Vqf32(v2); \
+ } \
+ \
+ if (nloe > 0) { \
+ HVX_Vector v1 = v_work[nvec]; \
+ HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec); \
+ hvx_vec_store_a(&v_work[nvec], nloe * sizeof(float), Q6_Vsf_equals_Vqf32(v2)); \
+ } \
+ } \
}
-static void compute_fast_softmax_f32_mask_f16(
- void * restrict dst,
- const void * restrict src0,
- const void * restrict mask,
- uint32_t ne00,
- float scale,
- float slope
+DEFINE_HVX_FAST_SOFTMAX(f32_nosink, 0, 0)
+DEFINE_HVX_FAST_SOFTMAX(f32_sink, 1, 0)
+DEFINE_HVX_FAST_SOFTMAX(f16_nosink, 0, 1)
+DEFINE_HVX_FAST_SOFTMAX(f16_sink, 1, 1)
+
+#undef DEFINE_HVX_FAST_SOFTMAX
+
+static __attribute__((noinline)) void softmax_init_alibi_slopes(
+ float * restrict slopes,
+ uint32_t n_head,
+ uint32_t n_head_log2,
+ float m0,
+ float m1
) {
- hvx_fast_softmax_prep_f16((const uint8_t *) src0, (uint8_t *) dst, ne00, scale, (const uint8_t *) mask, slope);
- hvx_fast_softmax_f32((const uint8_t *) dst, (uint8_t *) dst, ne00);
+ for (uint32_t h = 0; h < n_head; h += 32) {
+ HVX_Vector v_slopes = hvx_alibi_slopes(h, 1, n_head_log2, m0, m1);
+ hvx_vmem(&slopes[h]) = v_slopes;
+ }
}
-static const softmax_compute_fn_t softmax_kernels[HTP_SOFTMAX_KERNEL_COUNT] = {
- [HTP_SOFTMAX_KERNEL_NOMASK] = compute_fast_softmax_f32_nomask,
- [HTP_SOFTMAX_KERNEL_MASK_F32] = compute_fast_softmax_f32_mask_f32,
- [HTP_SOFTMAX_KERNEL_MASK_F16] = compute_fast_softmax_f32_mask_f16,
+static const softmax_prep_fn_t softmax_prep_kernels[HTP_SOFTMAX_KERNEL_COUNT] = {
+ [HTP_SOFTMAX_KERNEL_NOMASK] = hvx_fast_softmax_prep_nomask,
+ [HTP_SOFTMAX_KERNEL_MASK_F32] = hvx_fast_softmax_prep_f32,
+ [HTP_SOFTMAX_KERNEL_MASK_F16] = hvx_fast_softmax_prep_f16,
+ [HTP_SOFTMAX_KERNEL_SRC16_NOMASK] = hvx_fast_softmax_prep_src16_nomask,
+ [HTP_SOFTMAX_KERNEL_SRC16_MASK_F32] = hvx_fast_softmax_prep_src16_mask_f32,
+ [HTP_SOFTMAX_KERNEL_SRC16_MASK_F16] = hvx_fast_softmax_prep_src16_mask_f16,
};
-static void softmax_thread_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- (void) nth;
- const struct htp_softmax_context * smctx = (const struct htp_softmax_context *) data;
- struct htp_ops_context * octx = smctx->octx;
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
- const uint32_t src0_nrows = smctx->nrows;
- const uint32_t src0_nrows_per_hvx = smctx->src0_nrows_per_hvx;
+static const softmax_fn_t softmax_kernels[2][2] = {
+ { hvx_fast_softmax_f32_nosink, hvx_fast_softmax_f32_sink },
+ { hvx_fast_softmax_f16_nosink, hvx_fast_softmax_f16_sink },
+};
- const uint32_t src0_start_row = smctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, smctx->row_start + src0_nrows);
+struct softmax_pipe_state {
+ const struct htp_softmax_context * smctx;
+ dma_addr_t data_src0;
+ dma_addr_t data_src1;
+ dma_addr_t data_dst;
+ uint8_t * work_vtcm;
+ size_t src0_row_size;
+ size_t dst_row_size;
+ size_t mask_row_size;
+ size_t src0_row_size_aligned;
+ size_t src1_row_size_aligned;
+ size_t dst_row_size_aligned;
+ uint32_t ne00, ne01, ne02, ne03;
+ uint32_t ne12, ne13;
+ uint32_t nb11, nb12, nb13;
+ softmax_prep_fn_t prep;
+ softmax_fn_t softmax_fn;
+ float scale;
+ float slope;
+ const float * sink_ptr;
+ uint32_t prev_i2;
+ uint32_t r;
+ uint32_t r_end;
+ bool has_bias;
+ bool has_sinks;
+ bool dst_f16;
+};
- if (src0_start_row >= src0_end_row) {
- return;
+static bool softmax_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx;
+ if (s->r >= s->r_end) {
+ return false;
}
+ task->row = s->r++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
- const dma_addr_t data_src0 = smctx->data_src0;
- const dma_addr_t data_dst = smctx->data_dst;
+static void softmax_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx;
+ const dma_addr_t src0_addr = s->data_src0 + (size_t) task->row * s->src0_row_size;
+ dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr),
+ s->src0_row_size_aligned, s->src0_row_size, s->src0_row_size, 1);
+}
- const size_t src0_row_size = src0->ne[0] * sizeof(float);
- const size_t dst_row_size = src0->ne[0] * sizeof(float);
+static void softmax_push_in_mask(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) {
+ struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx;
+ const struct htp_softmax_context * smctx = s->smctx;
+ const uint32_t r = task->row;
+
+ const dma_addr_t src0_addr = s->data_src0 + (size_t) r * s->src0_row_size;
+
+ const uint32_t i1 = fastmodulo(r, s->ne01, &smctx->div_ne01);
+ const uint32_t r_div_ne01 = fastdiv(r, &smctx->div_ne01);
+ const uint32_t i2 = fastmodulo(r_div_ne01, s->ne02, &smctx->div_ne02);
+ const uint32_t i3 = fastdiv(r_div_ne01, &smctx->div_ne02);
+ const uint32_t i12 = (s->ne12 == s->ne02) ? i2 : fastmodulo(i2, s->ne12, &smctx->div_ne12);
+ const uint32_t i13 = (s->ne13 == s->ne03) ? i3 : fastmodulo(i3, s->ne13, &smctx->div_ne13);
+ const dma_addr_t src1_addr = s->data_src1 + (size_t) i1 * s->nb11 + (size_t) i12 * s->nb12 + (size_t) i13 * s->nb13;
+
+ dma_queue_push(dma_q, dma_make_data(in0_spad, src0_addr),
+ s->src0_row_size_aligned, s->src0_row_size, s->src0_row_size, 1);
+ dma_queue_push(dma_q, dma_make_data(in1_spad, src1_addr),
+ s->src1_row_size_aligned, s->mask_row_size, s->mask_row_size, 1);
+}
- uint8_t * src0_vtcm_base = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx);
- uint8_t * dst_vtcm_base = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx);
+static void softmax_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx;
+ void * w_spad = s->dst_f16 ? (void *) s->work_vtcm : out_spad;
- const size_t src0_vtcm_half = smctx->src0_spad_half_size;
- const size_t dst_vtcm_half = smctx->dst_spad_half_size;
+ if (s->has_sinks) {
+ const uint32_t r_div_ne01 = fastdiv(task->row, &s->smctx->div_ne01);
+ const uint32_t i2 = fastmodulo(r_div_ne01, s->ne02, &s->smctx->div_ne02);
+ if (i2 != s->prev_i2) {
+ s->sink_ptr = s->smctx->vtcm_src2 + i2;
+ s->prev_i2 = i2;
+ }
+ }
- dma_queue * dma_q = th->dma_q;
+ s->prep(w_spad, in_spad, NULL, s->ne00, s->scale, 1.0f);
+ s->softmax_fn((uint8_t *) w_spad, (uint8_t *) out_spad, s->ne00, s->sink_ptr);
+}
- for (uint32_t r = src0_start_row, idx = 0; r < src0_end_row && idx < 2; r++, idx++) {
- dma_addr_t cur_dst = data_dst + r * dst_row_size;
- dma_addr_t cur_src0 = data_src0 + r * src0_row_size;
- void * d_spad = dst_vtcm_base + idx * dst_vtcm_half;
- void * s_spad = src0_vtcm_base + idx * src0_vtcm_half;
+static void softmax_compute_mask(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) {
+ struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx;
+ void * w_spad = s->dst_f16 ? (void *) s->work_vtcm : out_spad;
- dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad),
- dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 0);
- dma_queue_push(dma_q, dma_make_data(s_spad, cur_src0),
- smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1);
+ if (s->has_bias || s->has_sinks) {
+ const uint32_t r_div_ne01 = fastdiv(task->row, &s->smctx->div_ne01);
+ const uint32_t i2 = fastmodulo(r_div_ne01, s->ne02, &s->smctx->div_ne02);
+ if (i2 != s->prev_i2) {
+ if (s->has_bias) {
+ s->slope = s->smctx->slopes[i2];
+ }
+ if (s->has_sinks) {
+ s->sink_ptr = s->smctx->vtcm_src2 + i2;
+ }
+ s->prev_i2 = i2;
+ }
}
- softmax_compute_fn_t compute = (softmax_compute_fn_t) smctx->compute;
- const uint32_t ne00 = src0->ne[0];
+ s->prep(w_spad, in0_spad, in1_spad, s->ne00, s->scale, s->slope);
+ s->softmax_fn((uint8_t *) w_spad, (uint8_t *) out_spad, s->ne00, s->sink_ptr);
+}
- for (uint32_t r = src0_start_row; r < src0_end_row; ++r) {
- void * d_spad = (void *) dma_queue_pop(dma_q).src;
- void * s_spad = (void *) dma_queue_pop(dma_q).dst;
+static void softmax_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx;
+ const dma_addr_t dst_addr = s->data_dst + (size_t) task->row * s->dst_row_size;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad),
+ s->dst_row_size, s->dst_row_size_aligned, s->dst_row_size, 1);
+}
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, r);
- compute(d_spad, s_spad, NULL, ne00, smctx->scale, 1.0f);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, r);
+static void softmax_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct htp_softmax_context * smctx = (const struct htp_softmax_context *) data;
+ struct htp_ops_context * octx = smctx->octx;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
- dma_addr_t cur_dst = data_dst + r * dst_row_size;
- dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad),
- dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 1);
+ const uint32_t src0_start_row = smctx->row_start + smctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + smctx->src0_nrows_per_hvx, smctx->row_start + smctx->nrows);
- const uint32_t next_r = r + 2;
- if (next_r < src0_end_row) {
- dma_addr_t next_src0 = data_src0 + next_r * src0_row_size;
- dma_queue_push(dma_q, dma_make_data(s_spad, next_src0),
- smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1);
- }
+ if (src0_start_row >= src0_end_row) {
+ return;
}
- dma_queue_flush(dma_q);
+ uint8_t * src0_vtcm_base = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx);
+ uint8_t * dst_vtcm_base = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_base, src0_vtcm_base + smctx->src0_spad_half_size };
+ void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + smctx->dst_spad_half_size };
+
+ struct softmax_pipe_state s = {
+ .smctx = smctx,
+ .data_src0 = smctx->data_src0,
+ .data_dst = smctx->data_dst,
+ .work_vtcm = smctx->dst_f16 ? (smctx->vtcm_work + ith * smctx->vtcm_work_size_per_hvx) : NULL,
+ .src0_row_size = src0->ne[0] * (smctx->src0_f16 ? sizeof(__fp16) : sizeof(float)),
+ .dst_row_size = dst->ne[0] * (smctx->dst_f16 ? sizeof(__fp16) : sizeof(float)),
+ .src0_row_size_aligned = smctx->src0_row_size_aligned,
+ .dst_row_size_aligned = smctx->dst_row_size_aligned,
+ .ne00 = src0->ne[0],
+ .ne02 = src0->ne[2],
+ .prep = (softmax_prep_fn_t) smctx->prep,
+ .softmax_fn = (softmax_fn_t) smctx->softmax,
+ .scale = smctx->scale,
+ .slope = 1.0f,
+ .sink_ptr = NULL,
+ .prev_i2 = (uint32_t) -1,
+ .r = src0_start_row,
+ .r_end = src0_end_row,
+ .has_bias = false,
+ .has_sinks = smctx->use_src2,
+ .dst_f16 = smctx->dst_f16,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ softmax_next_task, softmax_push_in, softmax_compute, softmax_push_out);
}
-static void softmax_thread_mask_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+static void softmax_thread_mask(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
(void) nth;
const struct htp_softmax_context * smctx = (const struct htp_softmax_context *) data;
struct htp_ops_context * octx = smctx->octx;
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * src1 = octx->src[1];
const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
- const uint32_t src0_nrows = smctx->nrows;
- const uint32_t src0_nrows_per_hvx = smctx->src0_nrows_per_hvx;
- const uint32_t src0_start_row = smctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, smctx->row_start + src0_nrows);
+ const uint32_t src0_start_row = smctx->row_start + smctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + smctx->src0_nrows_per_hvx, smctx->row_start + smctx->nrows);
if (src0_start_row >= src0_end_row) {
return;
}
- const dma_addr_t data_src0 = smctx->data_src0;
- const dma_addr_t data_src1 = smctx->data_src1;
- const dma_addr_t data_dst = smctx->data_dst;
-
- const size_t src0_row_size = src0->ne[0] * sizeof(float);
- const size_t dst_row_size = src0->ne[0] * sizeof(float);
- const size_t mask_row_size = smctx->use_f16 ? (src1->ne[0] * sizeof(__fp16)) : (src1->ne[0] * sizeof(float));
-
uint8_t * src0_vtcm_base = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx);
uint8_t * src1_vtcm_base = smctx->vtcm_src1 + (ith * smctx->vtcm_src1_size_per_hvx);
uint8_t * dst_vtcm_base = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx);
+ void * in0_buf[2] = { src0_vtcm_base, src0_vtcm_base + smctx->src0_spad_half_size };
+ void * in1_buf[2] = { src1_vtcm_base, src1_vtcm_base + smctx->src1_spad_half_size };
+ void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + smctx->dst_spad_half_size };
+
+ struct softmax_pipe_state s = {
+ .smctx = smctx,
+ .data_src0 = smctx->data_src0,
+ .data_src1 = smctx->data_src1,
+ .data_dst = smctx->data_dst,
+ .work_vtcm = smctx->dst_f16 ? (smctx->vtcm_work + ith * smctx->vtcm_work_size_per_hvx) : NULL,
+ .src0_row_size = src0->ne[0] * (smctx->src0_f16 ? sizeof(__fp16) : sizeof(float)),
+ .dst_row_size = dst->ne[0] * (smctx->dst_f16 ? sizeof(__fp16) : sizeof(float)),
+ .mask_row_size = smctx->use_f16 ? (src1->ne[0] * sizeof(__fp16)) : (src1->ne[0] * sizeof(float)),
+ .src0_row_size_aligned = smctx->src0_row_size_aligned,
+ .src1_row_size_aligned = smctx->src1_row_size_aligned,
+ .dst_row_size_aligned = smctx->dst_row_size_aligned,
+ .ne00 = src0->ne[0], .ne01 = src0->ne[1], .ne02 = src0->ne[2], .ne03 = src0->ne[3],
+ .ne12 = src1->ne[2], .ne13 = src1->ne[3],
+ .nb11 = src1->nb[1], .nb12 = src1->nb[2], .nb13 = src1->nb[3],
+ .prep = (softmax_prep_fn_t) smctx->prep,
+ .softmax_fn = (softmax_fn_t) smctx->softmax,
+ .scale = smctx->scale,
+ .slope = 1.0f,
+ .sink_ptr = NULL,
+ .prev_i2 = (uint32_t) -1,
+ .r = src0_start_row,
+ .r_end = src0_end_row,
+ .has_bias = smctx->max_bias > 0.0f,
+ .has_sinks = smctx->use_src2,
+ .dst_f16 = smctx->dst_f16,
+ };
- const size_t src0_vtcm_half = smctx->src0_spad_half_size;
- const size_t src1_vtcm_half = smctx->src1_spad_half_size;
- const size_t dst_vtcm_half = smctx->dst_spad_half_size;
-
- const uint32_t nb11 = src1->nb[1];
- const uint32_t nb12 = src1->nb[2];
- const uint32_t nb13 = src1->nb[3];
-
- const uint32_t ne00 = src0->ne[0];
- const uint32_t ne01 = src0->ne[1];
- const uint32_t ne02 = src0->ne[2];
- const uint32_t ne03 = src0->ne[3];
- const uint32_t ne12 = src1->ne[2];
- const uint32_t ne13 = src1->ne[3];
-
- const struct fastdiv_values * div_ne01 = &smctx->div_ne01;
- const struct fastdiv_values * div_ne02 = &smctx->div_ne02;
- const struct fastdiv_values * div_ne12 = &smctx->div_ne12;
- const struct fastdiv_values * div_ne13 = &smctx->div_ne13;
-
- dma_queue * dma_q = th->dma_q;
-
- for (uint32_t r = src0_start_row, idx = 0; r < src0_end_row && idx < 2; r++, idx++) {
- dma_addr_t cur_dst = data_dst + r * dst_row_size;
- dma_addr_t cur_src0 = data_src0 + r * src0_row_size;
-
- uint32_t i1 = fastmodulo(r, ne01, div_ne01);
- uint32_t r_div_ne01 = fastdiv(r, div_ne01);
- uint32_t i2 = fastmodulo(r_div_ne01, ne02, div_ne02);
- uint32_t i3 = fastdiv(r_div_ne01, div_ne02);
- uint32_t i12 = (ne12 == ne02) ? i2 : fastmodulo(i2, ne12, div_ne12);
- uint32_t i13 = (ne13 == ne03) ? i3 : fastmodulo(i3, ne13, div_ne13);
- dma_addr_t cur_src1 = data_src1 + i1 * nb11 + i12 * nb12 + i13 * nb13;
-
- void * d_spad = dst_vtcm_base + idx * dst_vtcm_half;
- void * s_spad = src0_vtcm_base + idx * src0_vtcm_half;
- void * m_spad = src1_vtcm_base + idx * src1_vtcm_half;
-
- dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad),
- dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 0);
- dma_queue_push(dma_q, dma_make_data(s_spad, cur_src0),
- smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1);
- dma_queue_push(dma_q, dma_make_data(m_spad, cur_src1),
- smctx->src1_row_size_aligned, mask_row_size, mask_row_size, 1);
- }
-
- softmax_compute_fn_t compute = (softmax_compute_fn_t) smctx->compute;
- const bool has_bias = smctx->max_bias > 0.0f;
- uint32_t prev_i2 = (uint32_t)-1;
- float slope = 1.0f;
-
- for (uint32_t r = src0_start_row; r < src0_end_row; ++r) {
- void * d_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * s_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
- void * m_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
-
- if (has_bias) {
- uint32_t r_div_ne01 = fastdiv(r, div_ne01);
- uint32_t i2 = fastmodulo(r_div_ne01, ne02, div_ne02);
- if (i2 != prev_i2) {
- slope = smctx->slopes[i2];
- prev_i2 = i2;
- }
- }
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, r);
- compute(d_spad, s_spad, m_spad, ne00, smctx->scale, slope);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, r);
-
- dma_addr_t cur_dst = data_dst + r * dst_row_size;
- dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad),
- dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 1);
-
- const uint32_t next_r = r + 2;
- if (next_r < src0_end_row) {
- dma_addr_t next_src0 = data_src0 + next_r * src0_row_size;
-
- uint32_t ni1 = fastmodulo(next_r, ne01, div_ne01);
- uint32_t nr_div_ne01 = fastdiv(next_r, div_ne01);
- uint32_t ni2 = fastmodulo(nr_div_ne01, ne02, div_ne02);
- uint32_t ni3 = fastdiv(nr_div_ne01, div_ne02);
- uint32_t ni12 = (ne12 == ne02) ? ni2 : fastmodulo(ni2, ne12, div_ne12);
- uint32_t ni13 = (ne13 == ne03) ? ni3 : fastmodulo(ni3, ne13, div_ne13);
- dma_addr_t next_src1 = data_src1 + ni1 * nb11 + ni12 * nb12 + ni13 * nb13;
-
- dma_queue_push(dma_q, dma_make_data(s_spad, next_src0),
- smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1);
- dma_queue_push(dma_q, dma_make_data(m_spad, next_src1),
- smctx->src1_row_size_aligned, mask_row_size, mask_row_size, 1);
- }
- }
-
- dma_queue_flush(dma_q);
+ dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf,
+ softmax_next_task, softmax_push_in_mask, softmax_compute_mask, softmax_push_out);
}
static int execute_op_softmax_f32(struct htp_ops_context * octx) {
@@ -507,17 +740,13 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
}
const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
- const size_t elem_size = sizeof(float);
- const size_t dst_row_size = dst->nb[1];
uint32_t row_start = 0;
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) elem_size, (uint32_t) dst_row_size, &rows_per_chunk);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
if (nrows < octx->n_hvx) {
@@ -536,14 +765,19 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
htp_softmax_vtcm_layout_build(&layout,
src0->ne[0],
kparams->use_src1 ? octx->src[1]->ne[0] : 0,
+ kparams->n_head,
+ kparams->src0_f16 != 0,
+ kparams->dst_f16 != 0,
kparams->use_src1 != 0,
kparams->use_f16 != 0,
+ kparams->use_src2 != 0,
kparams->n_hvx);
struct htp_softmax_context smctx = {
.octx = octx,
.kparams = kparams,
- .compute = (void *) softmax_kernels[kparams->kernel_type],
+ .prep = (void *) softmax_prep_kernels[kparams->kernel_type],
+ .softmax = (void *) softmax_kernels[kparams->dst_f16 != 0][kparams->use_src2 != 0],
.data_src0 = src0->data,
.data_src1 = kparams->use_src1 ? octx->src[1]->data : 0,
@@ -552,10 +786,13 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
.vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_src0),
.vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_dst),
.vtcm_src1 = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, vtcm_base, layout.off_src1, kparams->use_src1),
+ .vtcm_work = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, vtcm_base, layout.off_work, kparams->dst_f16),
+ .vtcm_src2 = VTCM_LAYOUT_PTR_OPTIONAL(float, vtcm_base, layout.off_src2, kparams->use_src2),
.vtcm_src0_size_per_hvx = (uint32_t) layout.src0_bytes_per_hvx,
.vtcm_src1_size_per_hvx = (uint32_t) layout.src1_bytes_per_hvx,
.vtcm_dst_size_per_hvx = (uint32_t) layout.dst_bytes_per_hvx,
+ .vtcm_work_size_per_hvx = (uint32_t) layout.work_bytes_per_hvx,
.src0_spad_half_size = (uint32_t) layout.src0_spad_half_size,
.src1_spad_half_size = (uint32_t) layout.src1_spad_half_size,
@@ -565,7 +802,10 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
.src1_row_size_aligned = (uint32_t) layout.src1_spad_half_size,
.dst_row_size_aligned = (uint32_t) layout.dst_spad_half_size,
+ .src0_f16 = kparams->src0_f16 != 0,
+ .dst_f16 = kparams->dst_f16 != 0,
.use_f16 = kparams->use_f16 != 0,
+ .use_src2 = kparams->use_src2 != 0,
.n_head = kparams->n_head,
.n_head_log2 = kparams->n_head_log2,
@@ -589,30 +829,33 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
if (kparams->n_head > 512) {
return HTP_STATUS_INVAL_PARAMS;
}
- for (uint32_t h = 0; h < kparams->n_head; h += 32) {
- HVX_Vector v_slopes = hvx_alibi_slopes(h, 1, kparams->n_head_log2, kparams->m0, kparams->m1);
- hvx_vmem(&smctx.slopes[h]) = v_slopes;
- }
+ softmax_init_alibi_slopes(smctx.slopes, kparams->n_head, kparams->n_head_log2, kparams->m0, kparams->m1);
+ }
+
+ if (kparams->use_src2) {
+ const struct htp_tensor * src2 = octx->src[2];
+ dma_queue * dma_q = octx->ctx->dma[0];
+ dma_queue_push(dma_q, dma_make_data(smctx.vtcm_src2, src2->data), layout.src2_bytes, 0, src2->size, 1);
+ dma_queue_pop(dma_q);
}
- work_queue_func_t task_func = kparams->use_src1 ? softmax_thread_mask_dma : softmax_thread_dma;
+ work_queue_func_t task_func = kparams->use_src1 ? softmax_thread_mask : softmax_thread;
work_queue_run(octx->ctx->hvx_queue, task_func, &smctx, n_hvx);
return HTP_STATUS_OK;
}
int op_softmax(struct htp_ops_context * octx) {
- int err = HTP_STATUS_OK;
+ if (octx->dst->type != HTP_TYPE_F32 && octx->dst->type != HTP_TYPE_F16) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
switch (octx->src[0]->type) {
case HTP_TYPE_F32:
- err = execute_op_softmax_f32(octx);
- break;
+ case HTP_TYPE_F16:
+ return execute_op_softmax_f32(octx);
default:
- err = HTP_STATUS_NO_SUPPORT;
- break;
+ return HTP_STATUS_NO_SUPPORT;
}
-
- return err;
}
diff --git a/ggml/src/ggml-hexagon/htp/softmax-ops.h b/ggml/src/ggml-hexagon/htp/softmax-ops.h
index 9e5f9c759..3ca9ff315 100644
--- a/ggml/src/ggml-hexagon/htp/softmax-ops.h
+++ b/ggml/src/ggml-hexagon/htp/softmax-ops.h
@@ -13,11 +13,17 @@ enum htp_softmax_kernel_type {
HTP_SOFTMAX_KERNEL_NOMASK = 0,
HTP_SOFTMAX_KERNEL_MASK_F32,
HTP_SOFTMAX_KERNEL_MASK_F16,
+ HTP_SOFTMAX_KERNEL_SRC16_NOMASK,
+ HTP_SOFTMAX_KERNEL_SRC16_MASK_F32,
+ HTP_SOFTMAX_KERNEL_SRC16_MASK_F16,
HTP_SOFTMAX_KERNEL_COUNT,
};
struct htp_softmax_kernel_params {
uint8_t kernel_type;
+ uint8_t src0_f16;
+ uint8_t dst_f16;
+ uint8_t use_src2;
uint32_t n_hvx;
uint32_t vtcm_size;
@@ -48,10 +54,14 @@ struct htp_softmax_vtcm_layout {
size_t off_src0;
size_t off_dst;
size_t off_src1;
+ size_t off_work;
+ size_t off_src2;
size_t src0_bytes_per_hvx;
size_t dst_bytes_per_hvx;
size_t src1_bytes_per_hvx;
+ size_t work_bytes_per_hvx;
+ size_t src2_bytes;
size_t src0_spad_half_size;
size_t dst_spad_half_size;
@@ -62,17 +72,23 @@ static inline void htp_softmax_vtcm_layout_build(
struct htp_softmax_vtcm_layout * L,
uint32_t ne00,
uint32_t ne10,
+ uint32_t n_head,
+ bool src0_f16,
+ bool dst_f16,
bool use_src1,
bool use_f16,
+ bool use_src2,
uint32_t n_hvx
) {
- size_t src0_row_size = ne00 * sizeof(float);
- size_t dst_row_size = ne00 * sizeof(float);
+ size_t src0_row_size = ne00 * (src0_f16 ? 2 : 4);
+ size_t dst_row_size = ne00 * (dst_f16 ? 2 : 4);
size_t src1_row_size = use_src1 ? (ne10 * (use_f16 ? 2 : 4)) : 0;
+ size_t work_row_size = dst_f16 ? (ne00 * sizeof(float)) : 0;
size_t src0_row_size_aligned = hex_round_up(src0_row_size, 128);
size_t dst_row_size_aligned = hex_round_up(dst_row_size, 128);
size_t src1_row_size_aligned = use_src1 ? hex_round_up(src1_row_size, 128) : 0;
+ size_t work_row_size_aligned = dst_f16 ? hex_round_up(work_row_size, 128) : 0;
L->src0_spad_half_size = src0_row_size_aligned;
L->dst_spad_half_size = dst_row_size_aligned;
@@ -82,11 +98,15 @@ static inline void htp_softmax_vtcm_layout_build(
L->src0_bytes_per_hvx = src0_row_size_aligned * 2;
L->dst_bytes_per_hvx = dst_row_size_aligned * 2;
L->src1_bytes_per_hvx = src1_row_size_aligned * 2;
+ L->work_bytes_per_hvx = work_row_size_aligned;
+ L->src2_bytes = use_src2 ? hex_round_up(n_head * sizeof(float), 128) : 0;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx);
VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_src1, L->src1_bytes_per_hvx * n_hvx, use_src1);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_work, L->work_bytes_per_hvx * n_hvx, dst_f16);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_src2, L->src2_bytes, use_src2);
L->total_bytes = off;
}
diff --git a/ggml/src/ggml-hexagon/htp/solve-tri-ops.c b/ggml/src/ggml-hexagon/htp/solve-tri-ops.c
index 73eff927e..082db4043 100644
--- a/ggml/src/ggml-hexagon/htp/solve-tri-ops.c
+++ b/ggml/src/ggml-hexagon/htp/solve-tri-ops.c
@@ -1,8 +1,7 @@
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <string.h>
+#include "dma-queue.h"
#include "hex-common.h"
#include "htp-trace.h"
@@ -11,155 +10,309 @@
#include "htp-ctx.h"
#include "htp-ops.h"
#include "htp-tensor.h"
+#include "htp-vtcm.h"
#include "hvx-types.h"
#include "hvx-utils.h"
#include "solve-tri-ops.h"
struct htp_solve_tri_context {
- struct htp_ops_context * octx;
+ struct htp_ops_context * octx;
const struct htp_solve_tri_kernel_params * kparams;
- uint32_t jobs_per_hvx;
- uint32_t total_jobs;
- uint32_t job_start;
- uint32_t k_chunks;
- uint32_t col_block;
+ uint8_t * vtcm_a;
+ uint8_t * vtcm_bx;
+ size_t a_row_aligned;
+ size_t a_bytes_per_hvx;
+ size_t bx_bytes_per_hvx;
+ uint32_t jobs_per_hvx;
+ uint32_t total_jobs;
+ uint32_t job_start;
+ uint32_t k_chunks;
+ uint32_t col_block;
+ uint32_t a_full;
+ uint8_t a_f16;
+ uint8_t b_f16;
+ uint8_t x_f16;
};
-static inline void solve_tri_row_scalar(const float * A_row,
- const float * B_row,
- float * X,
- uint32_t row,
- uint32_t k,
- uint32_t col0,
- uint32_t coln,
- float inv_diag) {
- for (uint32_t col = col0; col < col0 + coln; ++col) {
- float sum = 0.0f;
- for (uint32_t t = 0; t < row; ++t) {
- sum += A_row[t] * X[t * k + col];
- }
- X[row * k + col] = (B_row[col] - sum) * inv_diag;
+static inline HVX_Vector hvx_solve_tri_clamp_f16(HVX_Vector v) {
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ return Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v));
+}
+
+static void __attribute__((noinline)) solve_tri_widen_bx_f16(HVX_Vector * restrict bx, uint32_t n) {
+ for (uint32_t row = 0; row < n; ++row) {
+ bx[row] = Q6_V_lo_W(hvx_vec_f16_to_f32(bx[row]));
}
}
-static inline HVX_Vector hvx_load_partial_f32(const float * src, uint32_t n) {
- HVX_Vector v = *((const HVX_UVector *) src);
- HVX_VectorPred mask = Q6_Q_vsetq2_R(n * sizeof(float));
- return Q6_V_vmux_QVV(mask, v, Q6_V_vzero());
+static void __attribute__((noinline)) solve_tri_pack_bx_f16(HVX_Vector * restrict bx, uint32_t n) {
+ const HVX_Vector zero = Q6_V_vzero();
+ for (uint32_t row = 0; row < n; ++row) {
+ bx[row] = hvx_vec_f32_to_f16(hvx_solve_tri_clamp_f16(bx[row]), zero);
+ }
}
-static inline void solve_tri_row_hvx(const float * A_row,
- const float * B_row,
- float * X,
- uint32_t row,
- uint32_t k,
- uint32_t col0,
- uint32_t coln,
- float inv_diag) {
- const bool full = (coln == VLEN_FP32);
+static void __attribute__((noinline)) solve_tri_widen_a_row_f16(uint8_t * restrict row_buf, uint32_t len) {
+ HVX_Vector * restrict vecs = (HVX_Vector *) row_buf;
+ const uint32_t nvec_f32 = (len + VLEN_FP32 - 1) >> 5;
+ const uint32_t nvec_f16 = (len + VLEN_FP16 - 1) >> 6;
+ for (int32_t vi = (int32_t) nvec_f16 - 1; vi >= 0; --vi) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vecs[vi]);
+ if ((uint32_t) (2 * vi + 1) < nvec_f32) {
+ vecs[2 * vi + 1] = Q6_V_hi_W(p);
+ }
+ vecs[2 * vi] = Q6_V_lo_W(p);
+ }
+}
+static void __attribute__((noinline)) solve_tri_widen_a_full_f16(uint8_t * restrict vtcm_a, size_t a_row_aligned, uint32_t n) {
+ for (uint32_t row = 0; row < n; ++row) {
+ solve_tri_widen_a_row_f16(vtcm_a + (size_t) row * a_row_aligned, row + 1);
+ }
+}
+
+static inline void solve_tri_row_vtcm_hvx(
+ const HVX_Vector * restrict a_row_vecs,
+ HVX_Vector * restrict bx,
+ uint32_t row
+) {
HVX_Vector sum_v = Q6_V_vzero();
- for (uint32_t t = 0; t < row; ++t) {
- const float a = A_row[t];
- const float * x_row_col = X + t * k + col0;
+ uint32_t t = 0;
+
+ for (; t + VLEN_FP32 <= row; t += VLEN_FP32) {
+ const HVX_Vector a_vec = a_row_vecs[t >> 5];
+ for (uint32_t j = 0; j < VLEN_FP32; ++j) {
+ const HVX_Vector a_v = Q6_V_vsplat_R(Q6_R_vextract_VR(a_vec, j * 4));
+ sum_v = hvx_vec_add_f32_f32(sum_v, hvx_vec_mul_f32_f32(bx[t + j], a_v));
+ }
+ }
+
+ if (t < row) {
+ const HVX_Vector a_vec = a_row_vecs[t >> 5];
+ const uint32_t rem = row - t;
+ for (uint32_t j = 0; j < rem; ++j) {
+ const HVX_Vector a_v = Q6_V_vsplat_R(Q6_R_vextract_VR(a_vec, j * 4));
+ sum_v = hvx_vec_add_f32_f32(sum_v, hvx_vec_mul_f32_f32(bx[t + j], a_v));
+ }
+ }
- HVX_Vector x_v = full ? *((const HVX_UVector *) x_row_col) : hvx_load_partial_f32(x_row_col, coln);
- HVX_Vector a_v = hvx_vec_splat_f32(a);
- sum_v = hvx_vec_add_f32_f32(sum_v, hvx_vec_mul_f32_f32(x_v, a_v));
+ const int32_t diag_bits = Q6_R_vextract_VR(a_row_vecs[row >> 5], (row & 31u) * 4);
+ float diag;
+ memcpy(&diag, &diag_bits, sizeof(float));
+
+ const HVX_Vector inv_diag_v = hvx_vec_splat_f32(1.0f / diag);
+ bx[row] = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(bx[row], sum_v), inv_diag_v);
+}
+
+static void __attribute__((noinline)) solve_tri_solve_full_f32(
+ const uint8_t * restrict vtcm_a,
+ HVX_Vector * restrict vtcm_bx,
+ size_t a_row_aligned,
+ uint32_t n
+) {
+ for (uint32_t row = 0; row < n; ++row) {
+ const HVX_Vector * a_row_vecs = (const HVX_Vector *) (vtcm_a + (size_t) row * a_row_aligned);
+ solve_tri_row_vtcm_hvx(a_row_vecs, vtcm_bx, row);
}
+}
- const float * b_row_col = B_row + col0;
- float * x_out_col = X + row * k + col0;
+static void __attribute__((noinline)) solve_tri_solve_row_f32(
+ const HVX_Vector * restrict a_row_vecs,
+ HVX_Vector * restrict vtcm_bx,
+ uint32_t row
+) {
+ solve_tri_row_vtcm_hvx(a_row_vecs, vtcm_bx, row);
+}
- HVX_Vector b_v = full ? *((const HVX_UVector *) b_row_col) : hvx_load_partial_f32(b_row_col, coln);
- HVX_Vector inv_diag_v = hvx_vec_splat_f32(inv_diag);
+static void solve_tri_col_chunk_a_full(
+ dma_queue * dma_q,
+ struct htp_thread_trace * tr,
+ const uint8_t * vtcm_a,
+ HVX_Vector * vtcm_bx,
+ dma_addr_t B_batch,
+ dma_addr_t X_batch,
+ uint32_t nb11,
+ uint32_t dst_nb1,
+ size_t a_row_aligned,
+ uint32_t n,
+ uint32_t col0,
+ uint32_t coln,
+ uint8_t b_f16,
+ uint8_t x_f16,
+ uint16_t trace_id
+) {
+ const size_t b_elem_size = b_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t x_elem_size = x_f16 ? sizeof(__fp16) : sizeof(float);
+
+ dma_queue_push(dma_q, dma_make_data(vtcm_bx, B_batch + (size_t) col0 * b_elem_size), VLEN, nb11, (size_t) coln * b_elem_size, n);
+ dma_queue_pop(dma_q);
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ if (b_f16) {
+ solve_tri_widen_bx_f16(vtcm_bx, n);
+ }
+ solve_tri_solve_full_f32(vtcm_a, vtcm_bx, a_row_aligned, n);
+ if (x_f16) {
+ solve_tri_pack_bx_f16(vtcm_bx, n);
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+
+ dma_queue_push(dma_q, dma_make_data(X_batch + (size_t) col0 * x_elem_size, vtcm_bx), dst_nb1, VLEN, (size_t) coln * x_elem_size, n);
+ dma_queue_pop(dma_q);
+}
+
+static void solve_tri_col_chunk_a_stream(
+ dma_queue * dma_q,
+ struct htp_thread_trace * tr,
+ uint8_t * vtcm_a_row,
+ HVX_Vector * vtcm_bx,
+ dma_addr_t A_batch,
+ dma_addr_t B_batch,
+ dma_addr_t X_batch,
+ uint32_t nb01,
+ uint32_t nb11,
+ uint32_t dst_nb1,
+ uint32_t n,
+ uint32_t col0,
+ uint32_t coln,
+ uint8_t a_f16,
+ uint8_t b_f16,
+ uint8_t x_f16,
+ uint16_t trace_id
+) {
+ const size_t a_elem_size = a_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t b_elem_size = b_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t x_elem_size = x_f16 ? sizeof(__fp16) : sizeof(float);
+
+ dma_queue_push(dma_q, dma_make_data(vtcm_bx, B_batch + (size_t) col0 * b_elem_size), VLEN, nb11, (size_t) coln * b_elem_size, n);
+ dma_queue_pop(dma_q);
+
+ if (b_f16) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ solve_tri_widen_bx_f16(vtcm_bx, n);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ }
+
+ for (uint32_t row = 0; row < n; ++row) {
+ const size_t a_bytes = (size_t) (row + 1) * a_elem_size;
+ dma_sync_read(dma_q, vtcm_a_row, A_batch + (size_t) row * nb01, a_bytes);
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ if (a_f16) {
+ solve_tri_widen_a_row_f16(vtcm_a_row, row + 1);
+ }
+ solve_tri_solve_row_f32((const HVX_Vector *) vtcm_a_row, vtcm_bx, row);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ }
+
+ if (x_f16) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ solve_tri_pack_bx_f16(vtcm_bx, n);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id);
+ }
- HVX_Vector out_v = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(b_v, sum_v), inv_diag_v);
- hvx_vec_store_u((void *) x_out_col, coln * sizeof(float), out_v);
+ dma_queue_push(dma_q, dma_make_data(X_batch + (size_t) col0 * x_elem_size, vtcm_bx), dst_nb1, VLEN, (size_t) coln * x_elem_size, n);
+ dma_queue_pop(dma_q);
}
// Batch-level thread: each job is one full batch.
-static void solve_tri_batch_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data;
- struct htp_ops_context * octx = sctx->octx;
+static void solve_tri_batch_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data;
+ struct htp_ops_context * octx = sctx->octx;
const struct htp_solve_tri_kernel_params * kparams = sctx->kparams;
- const struct htp_tensor * src0 = octx->src[0]; // A
- const struct htp_tensor * src1 = octx->src[1]; // B
- const struct htp_tensor * dst = octx->dst; // X
-
- const uint32_t n = src0->ne[0];
- const uint32_t k = src1->ne[0];
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * src1 = octx->src[1];
+ const struct htp_tensor * dst = octx->dst;
+ const uint32_t n = src0->ne[0];
+ const uint32_t k = src1->ne[0];
const uint32_t ne02 = src0->ne[2];
- const uint32_t col_block = VLEN_FP32;
- const uint32_t k_full = k & ~(col_block - 1);
-
const uint32_t start_batch = sctx->job_start + sctx->jobs_per_hvx * ith;
const uint32_t end_batch = MIN(start_batch + sctx->jobs_per_hvx, sctx->job_start + sctx->total_jobs);
+ if (start_batch >= end_batch) {
+ return;
+ }
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_batch);
+ uint8_t * vtcm_a = sctx->vtcm_a + ith * sctx->a_bytes_per_hvx;
+ HVX_Vector * vtcm_bx = (HVX_Vector *) (sctx->vtcm_bx + ith * sctx->bx_bytes_per_hvx);
+ const size_t a_row_aligned = sctx->a_row_aligned;
+ const uint8_t a_f16 = sctx->a_f16;
+ const uint8_t b_f16 = sctx->b_f16;
+ const uint8_t x_f16 = sctx->x_f16;
+ const size_t a_row_bytes = (size_t) n * (a_f16 ? sizeof(__fp16) : sizeof(float));
+
+ dma_queue * dma_q = th->dma_q;
+ struct htp_thread_trace * tr = th->trace;
for (uint32_t batch = start_batch; batch < end_batch; ++batch) {
const uint32_t i03 = fastdiv(batch, &kparams->div_ne02);
const uint32_t i02 = batch - i03 * ne02;
- const float * A_batch =
- (const float *) ((const uint8_t *) (uintptr_t) src0->data + i02 * src0->nb[2] + i03 * src0->nb[3]);
- const float * B_batch =
- (const float *) ((const uint8_t *) (uintptr_t) src1->data + i02 * src1->nb[2] + i03 * src1->nb[3]);
- float * X_batch = (float *) ((uint8_t *) (uintptr_t) dst->data + i02 * dst->nb[2] + i03 * dst->nb[3]);
-
- for (uint32_t row = 0; row < n; ++row) {
- const float diag = A_batch[row * n + row];
- const float inv_diag = 1.0f / diag;
- const float * A_row = A_batch + row * n;
- const float * B_row = B_batch + row * k;
-
- uint32_t col0 = 0;
- for (; col0 < k_full; col0 += col_block) {
- solve_tri_row_hvx(A_row, B_row, X_batch, row, k, col0, col_block, inv_diag);
+ const dma_addr_t A_batch = src0->data + (size_t) i02 * src0->nb[2] + (size_t) i03 * src0->nb[3];
+ const dma_addr_t B_batch = src1->data + (size_t) i02 * src1->nb[2] + (size_t) i03 * src1->nb[3];
+ const dma_addr_t X_batch = dst->data + (size_t) i02 * dst->nb[2] + (size_t) i03 * dst->nb[3];
+
+ if (sctx->a_full) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_a, A_batch), a_row_aligned, src0->nb[1], a_row_bytes, n);
+ dma_queue_pop(dma_q);
+ if (a_f16) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) batch);
+ solve_tri_widen_a_full_f16(vtcm_a, a_row_aligned, n);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) batch);
}
- if (col0 < k) {
- const uint32_t coln = k - col0;
- if (coln >= 8) {
- solve_tri_row_hvx(A_row, B_row, X_batch, row, k, col0, coln, inv_diag);
- } else {
- solve_tri_row_scalar(A_row, B_row, X_batch, row, k, col0, coln, inv_diag);
- }
+ for (uint32_t col0 = 0; col0 < k; col0 += VLEN_FP32) {
+ const uint32_t coln = MIN(VLEN_FP32, k - col0);
+ solve_tri_col_chunk_a_full(dma_q, tr, vtcm_a, vtcm_bx, B_batch, X_batch,
+ src1->nb[1], dst->nb[1], a_row_aligned, n, col0, coln, b_f16, x_f16, (uint16_t) batch);
+ }
+ } else {
+ for (uint32_t col0 = 0; col0 < k; col0 += VLEN_FP32) {
+ const uint32_t coln = MIN(VLEN_FP32, k - col0);
+ solve_tri_col_chunk_a_stream(dma_q, tr, vtcm_a, vtcm_bx, A_batch, B_batch, X_batch,
+ src0->nb[1], src1->nb[1], dst->nb[1], n, col0, coln, a_f16, b_f16, x_f16, (uint16_t) batch);
}
}
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) end_batch);
-
FARF(HIGH, "solve-tri-batch %d/%d: A=(%ux%u) B=(%ux%u) batch %u:%u\n",
ith, nth, n, n, k, n, start_batch, end_batch);
}
// Chunk-level thread: each job is one (batch, col_chunk) pair.
-static void solve_tri_chunk_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data;
- struct htp_ops_context * octx = sctx->octx;
+static void solve_tri_chunk_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data;
+ struct htp_ops_context * octx = sctx->octx;
const struct htp_solve_tri_kernel_params * kparams = sctx->kparams;
- const struct htp_tensor * src0 = octx->src[0]; // A
- const struct htp_tensor * src1 = octx->src[1]; // B
- const struct htp_tensor * dst = octx->dst; // X
-
- const uint32_t n = src0->ne[0];
- const uint32_t k = src1->ne[0];
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * src1 = octx->src[1];
+ const struct htp_tensor * dst = octx->dst;
+ const uint32_t n = src0->ne[0];
+ const uint32_t k = src1->ne[0];
const uint32_t ne02 = src0->ne[2];
const uint32_t start_job = sctx->job_start + sctx->jobs_per_hvx * ith;
const uint32_t end_job = MIN(start_job + sctx->jobs_per_hvx, sctx->job_start + sctx->total_jobs);
+ if (start_job >= end_job) {
+ return;
+ }
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_job);
+ uint8_t * vtcm_a = sctx->vtcm_a + ith * sctx->a_bytes_per_hvx;
+ HVX_Vector * vtcm_bx = (HVX_Vector *) (sctx->vtcm_bx + ith * sctx->bx_bytes_per_hvx);
+ const size_t a_row_aligned = sctx->a_row_aligned;
+ const uint8_t a_f16 = sctx->a_f16;
+ const uint8_t b_f16 = sctx->b_f16;
+ const uint8_t x_f16 = sctx->x_f16;
+ const size_t a_row_bytes = (size_t) n * (a_f16 ? sizeof(__fp16) : sizeof(float));
+
+ dma_queue * dma_q = th->dma_q;
+ struct htp_thread_trace * tr = th->trace;
+ uint32_t last_batch = UINT32_MAX;
for (uint32_t job = start_job; job < end_job; ++job) {
const uint32_t batch = fastdiv(job, &kparams->div_k_chunks);
@@ -168,123 +321,114 @@ static void solve_tri_chunk_thread_f32(const htp_thread_t * th, unsigned int nth
const uint32_t i03 = fastdiv(batch, &kparams->div_ne02);
const uint32_t i02 = batch - i03 * ne02;
- const float * A_batch =
- (const float *) ((const uint8_t *) (uintptr_t) src0->data + i02 * src0->nb[2] + i03 * src0->nb[3]);
- const float * B_batch =
- (const float *) ((const uint8_t *) (uintptr_t) src1->data + i02 * src1->nb[2] + i03 * src1->nb[3]);
- float * X_batch = (float *) ((uint8_t *) (uintptr_t) dst->data + i02 * dst->nb[2] + i03 * dst->nb[3]);
+ const dma_addr_t A_batch = src0->data + (size_t) i02 * src0->nb[2] + (size_t) i03 * src0->nb[3];
+ const dma_addr_t B_batch = src1->data + (size_t) i02 * src1->nb[2] + (size_t) i03 * src1->nb[3];
+ const dma_addr_t X_batch = dst->data + (size_t) i02 * dst->nb[2] + (size_t) i03 * dst->nb[3];
const uint32_t col0 = chunk * sctx->col_block;
const uint32_t coln = MIN(sctx->col_block, k - col0);
- for (uint32_t row = 0; row < n; ++row) {
- const float diag = A_batch[row * n + row];
- const float inv_diag = 1.0f / diag;
-
- const float * A_row = A_batch + row * n;
- const float * B_row = B_batch + row * k;
-
- if (coln >= 8) {
- solve_tri_row_hvx(A_row, B_row, X_batch, row, k, col0, coln, inv_diag);
- } else {
- solve_tri_row_scalar(A_row, B_row, X_batch, row, k, col0, coln, inv_diag);
+ if (sctx->a_full) {
+ if (batch != last_batch) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_a, A_batch), a_row_aligned, src0->nb[1], a_row_bytes, n);
+ dma_queue_pop(dma_q);
+ if (a_f16) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) job);
+ solve_tri_widen_a_full_f16(vtcm_a, a_row_aligned, n);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) job);
+ }
+ last_batch = batch;
}
+ solve_tri_col_chunk_a_full(dma_q, tr, vtcm_a, vtcm_bx, B_batch, X_batch,
+ src1->nb[1], dst->nb[1], a_row_aligned, n, col0, coln, b_f16, x_f16, (uint16_t) job);
+ } else {
+ solve_tri_col_chunk_a_stream(dma_q, tr, vtcm_a, vtcm_bx, A_batch, B_batch, X_batch,
+ src0->nb[1], src1->nb[1], dst->nb[1], n, col0, coln, a_f16, b_f16, x_f16, (uint16_t) job);
}
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) end_job);
-
FARF(HIGH, "solve-tri-chunk %d/%d: A=(%ux%u) B=(%ux%u) jobs %u:%u\n",
ith, nth, n, n, k, n, start_job, end_job);
}
int op_solve_tri(struct htp_ops_context * octx) {
- const struct htp_tensor * src0 = octx->src[0]; // A
- const struct htp_tensor * src1 = octx->src[1]; // B
- const struct htp_tensor * dst = octx->dst; // X
- const struct htp_solve_tri_kernel_params * kparams =
- (const struct htp_solve_tri_kernel_params *) octx->kernel_params;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * src1 = octx->src[1];
+ const struct htp_tensor * dst = octx->dst;
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(src1) || htp_tensor_is_extended(dst)) {
+ if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) ||
+ (src1->type != HTP_TYPE_F32 && src1->type != HTP_TYPE_F16) ||
+ (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) {
return HTP_STATUS_NO_SUPPORT;
}
+ const struct htp_solve_tri_kernel_params * kparams =
+ (const struct htp_solve_tri_kernel_params *) octx->kernel_params;
+
const uint32_t col_block = kparams->col_block;
const uint32_t k_chunks = kparams->k_chunks;
const uint32_t total_batches = kparams->total_batches;
const bool batched = (kparams->batched != 0);
+ const uint8_t a_f16 = (src0->type == HTP_TYPE_F16) ? 1 : 0;
+ const uint8_t b_f16 = (src1->type == HTP_TYPE_F16) ? 1 : 0;
+ const uint8_t x_f16 = (dst->type == HTP_TYPE_F16) ? 1 : 0;
FARF(HIGH, "solve-tri: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : batched %d\n",
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3],
src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], batched);
- if (batched) {
- uint32_t job_start = 0;
- uint32_t njobs = total_batches;
-
- if (octx->ctx->mdev.count > 1) {
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_batches, htp_tensor_mdev_data_aligned(dst) ? kparams->batches_per_chunk : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
- job_start = range.start;
- njobs = range.count;
- }
-
- if (njobs == 0) {
- return HTP_STATUS_OK;
- }
-
- if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, njobs))) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
- const uint32_t n_hvx = octx->n_hvx;
-
- struct htp_solve_tri_context sctx = {
- .octx = octx,
- .kparams = kparams,
- .jobs_per_hvx = fastdiv(njobs + n_hvx - 1, &octx->n_hvx_div),
- .total_jobs = njobs,
- .job_start = job_start,
- .k_chunks = k_chunks,
- .col_block = col_block,
- };
-
- work_queue_run(octx->ctx->hvx_queue, solve_tri_batch_thread_f32, &sctx, n_hvx);
- } else {
- const uint32_t total_jobs = kparams->total_jobs;
-
- uint32_t job_start = 0;
- uint32_t njobs = total_jobs;
-
- if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_mdev_data_aligned(dst) && ((dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_jobs, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
- job_start = range.start;
- njobs = range.count;
- }
+ uint32_t job_start = 0;
+ uint32_t njobs = batched ? total_batches : kparams->total_jobs;
- if (njobs == 0) {
- return HTP_STATUS_OK;
- }
+ if (octx->ctx->mdev.count > 1) {
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ njobs, 1,
+ octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ job_start = range.start;
+ njobs = range.count;
+ }
- if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, njobs))) {
- return HTP_STATUS_INVAL_PARAMS;
- }
+ if (njobs == 0) {
+ return HTP_STATUS_OK;
+ }
- const uint32_t n_hvx = octx->n_hvx;
+ if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, njobs))) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
- struct htp_solve_tri_context sctx = {
- .octx = octx,
- .kparams = kparams,
- .jobs_per_hvx = fastdiv(njobs + n_hvx - 1, &octx->n_hvx_div),
- .total_jobs = njobs,
- .job_start = job_start,
- .k_chunks = k_chunks,
- .col_block = col_block,
- };
+ const uint32_t n_hvx = octx->n_hvx;
- work_queue_run(octx->ctx->hvx_queue, solve_tri_chunk_thread_f32, &sctx, n_hvx);
+ struct htp_solve_tri_vtcm_layout layout;
+ htp_solve_tri_vtcm_layout_build(&layout, src0->ne[0], kparams->a_full, n_hvx);
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "solve-tri: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
}
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
+
+ struct htp_solve_tri_context sctx = {
+ .octx = octx,
+ .kparams = kparams,
+ .vtcm_a = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_a),
+ .vtcm_bx = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_bx),
+ .a_row_aligned = layout.a_row_aligned,
+ .a_bytes_per_hvx = layout.a_bytes_per_hvx,
+ .bx_bytes_per_hvx = layout.bx_bytes_per_hvx,
+ .jobs_per_hvx = fastdiv(njobs + n_hvx - 1, &octx->n_hvx_div),
+ .total_jobs = njobs,
+ .job_start = job_start,
+ .k_chunks = k_chunks,
+ .col_block = col_block,
+ .a_full = kparams->a_full,
+ .a_f16 = a_f16,
+ .b_f16 = b_f16,
+ .x_f16 = x_f16,
+ };
+
+ work_queue_func_t worker = batched ? solve_tri_batch_thread : solve_tri_chunk_thread;
+ work_queue_run(octx->ctx->hvx_queue, worker, &sctx, n_hvx);
+
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/solve-tri-ops.h b/ggml/src/ggml-hexagon/htp/solve-tri-ops.h
index 6a46cfdc4..965545ad6 100644
--- a/ggml/src/ggml-hexagon/htp/solve-tri-ops.h
+++ b/ggml/src/ggml-hexagon/htp/solve-tri-ops.h
@@ -1,9 +1,38 @@
#ifndef HTP_SOLVE_TRI_OPS_H
#define HTP_SOLVE_TRI_OPS_H
+#include "hex-common.h"
#include "hex-fastdiv.h"
+#include "htp-vtcm.h"
+#include <stddef.h>
#include <stdint.h>
+struct htp_solve_tri_vtcm_layout {
+ size_t a_row_aligned;
+ size_t a_bytes_per_hvx;
+ size_t bx_bytes_per_hvx;
+ size_t off_a;
+ size_t off_bx;
+ size_t total_bytes;
+};
+
+static inline void htp_solve_tri_vtcm_layout_build(
+ struct htp_solve_tri_vtcm_layout * L,
+ uint32_t n,
+ uint32_t a_full,
+ uint32_t n_hvx
+) {
+ size_t off = 0;
+
+ L->a_row_aligned = hex_round_up((size_t) n * sizeof(float), 128);
+ L->a_bytes_per_hvx = a_full ? ((size_t) n * L->a_row_aligned) : L->a_row_aligned;
+ L->bx_bytes_per_hvx = (size_t) n * 128;
+
+ VTCM_LAYOUT_ALLOC(off, off_a, (size_t) n_hvx * L->a_bytes_per_hvx);
+ VTCM_LAYOUT_ALLOC(off, off_bx, (size_t) n_hvx * L->bx_bytes_per_hvx);
+ L->total_bytes = off;
+}
+
struct htp_solve_tri_kernel_params {
uint32_t n_hvx;
uint32_t total_batches;
@@ -11,7 +40,8 @@ struct htp_solve_tri_kernel_params {
uint32_t k_chunks;
uint32_t col_block;
uint32_t batched;
- uint32_t batches_per_chunk;
+ uint32_t a_full;
+ uint32_t vtcm_size;
struct fastdiv_values div_ne02;
struct fastdiv_values div_k_chunks;
diff --git a/ggml/src/ggml-hexagon/htp/ssm-conv.c b/ggml/src/ggml-hexagon/htp/ssm-conv.c
index d75304fef..a7a511ba7 100644
--- a/ggml/src/ggml-hexagon/htp/ssm-conv.c
+++ b/ggml/src/ggml-hexagon/htp/ssm-conv.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_mem.h>
#include <HAP_ps.h>
@@ -21,66 +17,157 @@
#include "hvx-utils.h"
#include "ssm-conv.h"
+typedef void (*htp_ssm_conv_decode_dot_fn_t)(
+ const void * restrict raw_in,
+ float * restrict src0_T,
+ const float * restrict src1_raw,
+ const float * restrict src1_T,
+ float * restrict out,
+ uint32_t tile_n,
+ uint32_t d_inner_stride,
+ uint32_t tile_off,
+ uint32_t d_conv);
+
+typedef void (*htp_ssm_conv_transpose_block_fn_t)(
+ const void * restrict raw_block,
+ float * restrict T,
+ uint32_t raw_stride_bytes,
+ uint32_t ncs,
+ uint32_t cb_n);
+
+typedef void (*htp_ssm_conv_prefill_dot_fn_t)(
+ const float * restrict src0_T,
+ const float * restrict wp,
+ float * restrict op,
+ uint32_t n_t,
+ uint32_t d_conv,
+ uint32_t d_inner_stride,
+ uint32_t dst_tile_stride);
+
+typedef size_t (*htp_ssm_conv_epilogue_fn_t)(
+ float * restrict out,
+ uint32_t n_t,
+ uint32_t tile_n);
+
+typedef void (*htp_ssm_conv_token_step_fn_t)(
+ float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride);
+
+typedef void (*htp_ssm_conv_state_unpack_fn_t)(
+ float * restrict state_raw,
+ float * restrict hist,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps);
+
+typedef void (*htp_ssm_conv_state_pack_fn_t)(
+ float * restrict hist,
+ float * restrict state_raw,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps);
+
struct htp_ssm_conv_context {
struct htp_ops_context * octx;
const struct htp_ssm_conv_kernel_params * kparams;
+ struct htp_ssm_conv_vtcm_layout layout;
+ uint8_t * vtcm_base;
uint32_t nrows_per_hvx;
uint32_t d_inner_tile;
uint32_t row_start;
uint32_t nrows;
+ bool raw_dot;
+ htp_ssm_conv_decode_dot_fn_t decode_dot_fn;
+ htp_ssm_conv_transpose_block_fn_t transpose_block_fn;
+ htp_ssm_conv_prefill_dot_fn_t prefill_dot_fn;
+ htp_ssm_conv_epilogue_fn_t epilogue_fn;
+ htp_ssm_conv_token_step_fn_t token_step_fn;
+ htp_ssm_conv_state_unpack_fn_t state_unpack_fn;
+ htp_ssm_conv_state_pack_fn_t state_pack_fn;
};
-// In-register 32x32 fp32 transpose using std 5-stage HVX vshuff butterfly.
-static inline void hvx_transpose_32x32_f32(HVX_Vector m[32]) {
- HVX_Vector tmp[32];
-
- // Stage 0 (R = -4): pair (2i, 2i+1) for i = 0..15. m -> tmp.
- for (int i = 0; i < 16; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(m[2*i + 1], m[2*i], -4);
- tmp[2*i + 0] = Q6_V_lo_W(p);
- tmp[2*i + 1] = Q6_V_hi_W(p);
+static __attribute__((noinline)) void hvx_ssm_conv_widen_f16_vtcm(const __fp16 * restrict src,
+ float * restrict dst,
+ uint32_t n_elems) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+ const uint32_t n_v = (n_elems + VLEN_FP16 - 1) / VLEN_FP16;
+ for (uint32_t i = 0; i < n_v; ++i) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[i]);
+ vdst[2 * i + 0] = Q6_V_lo_W(p);
+ vdst[2 * i + 1] = Q6_V_hi_W(p);
}
+}
- // Stage 1 (R = -8): per block of 4, pair (b+0, b+2) and (b+1, b+3). tmp -> m.
- for (int b = 0; b < 32; b += 4) {
- HVX_VectorPair p0 = Q6_W_vshuff_VVR(tmp[b + 2], tmp[b + 0], -8);
- HVX_VectorPair p1 = Q6_W_vshuff_VVR(tmp[b + 3], tmp[b + 1], -8);
- m[b + 0] = Q6_V_lo_W(p0); m[b + 1] = Q6_V_hi_W(p0);
- m[b + 2] = Q6_V_lo_W(p1); m[b + 3] = Q6_V_hi_W(p1);
- }
+static inline HVX_Vector hvx_ssm_conv_clamp_f16_f32(HVX_Vector x) {
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+ return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max);
+}
- // Stage 2 (R = -16): per block of 8, pair (b+i, b+i+4) for i = 0..3. m -> tmp.
- for (int b = 0; b < 32; b += 8) {
- for (int i = 0; i < 4; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(m[b + i + 4], m[b + i], -16);
- tmp[b + 2*i + 0] = Q6_V_lo_W(p);
- tmp[b + 2*i + 1] = Q6_V_hi_W(p);
- }
- }
+static inline HVX_Vector hvx_ssm_conv_silu_pack_f16(HVX_Vector u0, HVX_Vector u1) {
+ HVX_Vector x = hvx_vec_f32_to_f16(hvx_ssm_conv_clamp_f16_f32(u0),
+ hvx_ssm_conv_clamp_f16_f32(u1));
+ return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(x));
+}
- // Stage 3 (R = -32): per block of 16, pair (b+i, b+i+8) for i = 0..7. tmp -> m.
- for (int b = 0; b < 32; b += 16) {
- for (int i = 0; i < 8; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(tmp[b + i + 8], tmp[b + i], -32);
- m[b + 2*i + 0] = Q6_V_lo_W(p);
- m[b + 2*i + 1] = Q6_V_hi_W(p);
- }
- }
+static __attribute__((noinline)) void hvx_ssm_conv_pack_f16_rows_vtcm(float * restrict buf,
+ uint32_t n_rows,
+ uint32_t n_elems_per_row) {
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector zero = Q6_V_vzero();
+ const uint32_t n_v32 = (n_elems_per_row + VLEN_FP32 - 1) / VLEN_FP32;
+ const uint32_t n_v16 = (n_v32 + 1) / 2;
+ HVX_Vector * restrict vbuf = (HVX_Vector *) buf;
- // Stage 4 (R = -64): pair (i, i+16) for i = 0..15. m -> tmp -> m.
- for (int i = 0; i < 16; ++i) {
- HVX_VectorPair p = Q6_W_vshuff_VVR(m[i + 16], m[i], -64);
- tmp[2 * i + 0] = Q6_V_lo_W(p);
- tmp[2 * i + 1] = Q6_V_hi_W(p);
+ for (uint32_t r = 0; r < n_rows; ++r) {
+ HVX_Vector * sr = vbuf + (size_t) r * n_v32;
+ HVX_Vector * dr = vbuf + (size_t) r * n_v16;
+ for (uint32_t i = 0; i < n_v32; i += 2) {
+ HVX_Vector v0 = sr[i];
+ HVX_Vector v1 = (i + 1 < n_v32) ? sr[i + 1] : zero;
+ v0 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v0, f16_max), f16_min);
+ v1 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v1, f16_max), f16_min);
+ dr[i / 2] = hvx_vec_f32_to_f16(v0, v1);
+ }
}
+}
- for (int i = 0; i < 32; ++i) {
- m[i] = tmp[i];
+static __attribute__((noinline)) void hvx_ssm_conv_silu_pack_f16_rows_vtcm(float * restrict buf,
+ uint32_t n_rows,
+ uint32_t n_elems_per_row) {
+ const HVX_Vector zero = Q6_V_vzero();
+ const uint32_t n_v32 = (n_elems_per_row + VLEN_FP32 - 1) / VLEN_FP32;
+ const uint32_t n_v16 = (n_v32 + 1) / 2;
+ HVX_Vector * restrict vbuf = (HVX_Vector *) buf;
+
+ for (uint32_t r = 0; r < n_rows; ++r) {
+ HVX_Vector * sr = vbuf + (size_t) r * n_v32;
+ HVX_Vector * dr = vbuf + (size_t) r * n_v16;
+ for (uint32_t i = 0; i < n_v32; i += 2) {
+ HVX_Vector v0 = sr[i];
+ HVX_Vector v1 = (i + 1 < n_v32) ? sr[i + 1] : zero;
+ dr[i / 2] = hvx_ssm_conv_silu_pack_f16(v0, v1);
+ }
}
}
// HVX deinterleave for d_conv == 4: channel-major raw VTCM -> tap-major T VTCM
-static inline void hvx_ssm_conv_unpack_to_T_4(const float * raw, float * T, uint32_t d_inner_per_hvx, uint32_t d_inner_stride) {
+static __attribute__((noinline)) void hvx_ssm_conv_unpack_to_T_4(const float * restrict raw,
+ float * restrict T,
+ uint32_t d_inner_per_hvx,
+ uint32_t d_inner_stride) {
for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) {
HVX_Vector v0 = *(const HVX_Vector *)(raw + (cb + 0) * 4);
HVX_Vector v1 = *(const HVX_Vector *)(raw + (cb + 8) * 4);
@@ -100,31 +187,27 @@ static inline void hvx_ssm_conv_unpack_to_T_4(const float * raw, float * T, uint
}
}
-// HVX transpose for general d_conv <= 32: channel-major raw VTCM -> tap-major T VTCM
-static inline void hvx_ssm_conv_unpack_to_T_gen(const float * raw, float * T, uint32_t d_inner_per_hvx, uint32_t d_inner_stride, uint32_t d_conv) {
- uint32_t __attribute__((aligned(VLEN))) mask_buf[VLEN_FP32] = { 0 };
- for (uint32_t j = 0; j < d_conv; ++j) {
- mask_buf[j] = 0xFFFFFFFF;
- }
- const HVX_Vector mask = *(const HVX_Vector *) mask_buf;
+// HVX gather transpose for general d_conv <= 32: channel-major raw VTCM -> tap-major T VTCM
+static __attribute__((noinline)) void hvx_ssm_conv_unpack_to_T_gen(const float * restrict raw,
+ float * restrict T,
+ uint32_t d_inner_per_hvx,
+ uint32_t d_inner_stride,
+ uint32_t d_conv) {
+ const uint32_t raw_stride_bytes = d_conv * sizeof(float);
+ const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes);
for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) {
const uint32_t cb_n = MIN(VLEN_FP32, d_inner_per_hvx - cb);
- HVX_Vector sub[32];
- for (uint32_t r = 0; r < cb_n; ++r) {
- const float * ch_ptr = raw + (cb + r) * d_conv;
- sub[r] = Q6_V_vand_VV(*(const HVX_UVector *) ch_ptr, mask);
- }
- for (uint32_t r = cb_n; r < 32; ++r) {
- sub[r] = hvx_vec_splat_f32(0.0f);
- }
-
- hvx_transpose_32x32_f32(sub);
+ const size_t base = (size_t) (raw + (size_t) cb * d_conv);
+ const uint32_t mu = cb_n * raw_stride_bytes - 1;
for (uint32_t j = 0; j < d_conv; ++j) {
- *(HVX_Vector *)(T + j * d_inner_stride + cb) = sub[j];
+ Q6_vgather_ARMVw((HVX_Vector *) (T + (size_t) j * d_inner_stride + cb),
+ base + j * sizeof(float), mu, vv);
}
}
+
+ hvx_gather_sync(T);
}
static inline void hvx_ssm_conv_unpack_to_T(const float * raw, float * T, uint32_t d_inner_per_hvx, uint32_t d_inner_stride, uint32_t d_conv) {
@@ -135,6 +218,40 @@ static inline void hvx_ssm_conv_unpack_to_T(const float * raw, float * T, uint32
}
}
+// HVX gather transpose + F16->F32 widen for decode when d_conv != 4
+static __attribute__((noinline)) void hvx_ssm_conv_unpack_to_T_f16(const __fp16 * restrict raw,
+ float * restrict T,
+ uint32_t d_inner_per_hvx,
+ uint32_t d_inner_stride,
+ uint32_t d_conv) {
+ const uint32_t raw_stride_bytes = hex_round_up(d_conv, 2) * sizeof(__fp16);
+ const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes);
+
+ for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) {
+ const uint32_t cb_n = MIN(VLEN_FP32, d_inner_per_hvx - cb);
+ const size_t base = (size_t) ((const uint8_t *) raw + (size_t) cb * raw_stride_bytes);
+ const uint32_t mu = cb_n * raw_stride_bytes - 1;
+
+ for (uint32_t j = 0; j < d_conv; j += 2) {
+ Q6_vgather_ARMVw((HVX_Vector *) (T + (size_t) j * d_inner_stride + cb),
+ base + j * sizeof(__fp16), mu, vv);
+ }
+ }
+
+ hvx_gather_sync(T);
+
+ for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) {
+ for (uint32_t j = 0; j < d_conv; j += 2) {
+ HVX_Vector v_pair = *(const HVX_Vector *) (T + (size_t) j * d_inner_stride + cb);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_pair);
+ *(HVX_Vector *) (T + (size_t) j * d_inner_stride + cb) = Q6_V_lo_W(p);
+ if (j + 1 < d_conv) {
+ *(HVX_Vector *) (T + (size_t) (j + 1) * d_inner_stride + cb) = Q6_V_hi_W(p);
+ }
+ }
+ }
+}
+
static __attribute__((noinline)) void hvx_ssm_conv_silu_vtcm(float * restrict buf, uint32_t n_vecs) {
HVX_Vector * restrict vbuf = (HVX_Vector *) buf;
for (uint32_t i = 0; i < n_vecs; ++i) {
@@ -145,7 +262,10 @@ static __attribute__((noinline)) void hvx_ssm_conv_silu_vtcm(float * restrict bu
// Decode dot product specialization for d_conv == 4: multiply in the raw channel-major layout,
// then deinterleave the products so each vector holds one tap of 32 channels, and sum.
// Keeps both operands in DMA layout - no transpose, no scratch.
-static inline void hvx_ssm_conv_decode_4(const float * x, const float * w, float * out, uint32_t n_ch) {
+static __attribute__((noinline)) void hvx_ssm_conv_decode_4(const float * restrict x,
+ const float * restrict w,
+ float * restrict out,
+ uint32_t n_ch) {
for (uint32_t cb = 0; cb < n_ch; cb += VLEN_FP32) {
const float * xp = x + cb * 4;
const float * wp = w + cb * 4;
@@ -168,23 +288,730 @@ static inline void hvx_ssm_conv_decode_4(const float * x, const float * w, float
}
}
+static __attribute__((noinline)) void hvx_ssm_conv_decode_4_f16(const __fp16 * restrict x,
+ const float * restrict w,
+ float * restrict out,
+ uint32_t n_ch) {
+ for (uint32_t cb = 0; cb < n_ch; cb += VLEN_FP32) {
+ const __fp16 * xp = x + cb * 4;
+ const float * wp = w + cb * 4;
+
+ HVX_VectorPair x01 = hvx_vec_f16_to_f32(*(const HVX_Vector *)(xp + 0));
+ HVX_VectorPair x23 = hvx_vec_f16_to_f32(*(const HVX_Vector *)(xp + 64));
+
+ HVX_Vector p0 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(x01), *(const HVX_Vector *)(wp + 0));
+ HVX_Vector p1 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(x01), *(const HVX_Vector *)(wp + 32));
+ HVX_Vector p2 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(x23), *(const HVX_Vector *)(wp + 64));
+ HVX_Vector p3 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(x23), *(const HVX_Vector *)(wp + 96));
+
+ HVX_VectorPair p01 = Q6_W_vdeal_VVR(p1, p0, -4);
+ HVX_VectorPair p23 = Q6_W_vdeal_VVR(p3, p2, -4);
+
+ HVX_VectorPair q02 = Q6_W_vdeal_VVR(Q6_V_lo_W(p23), Q6_V_lo_W(p01), -4);
+ HVX_VectorPair q13 = Q6_W_vdeal_VVR(Q6_V_hi_W(p23), Q6_V_hi_W(p01), -4);
+
+ HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_lo_W(q02), Q6_V_lo_W(q13));
+ HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_hi_W(q02), Q6_V_hi_W(q13));
+
+ *(HVX_Vector *)(out + cb) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b));
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_decode_dot_gen(const float * restrict src0_T,
+ const float * restrict src1_T,
+ float * restrict out,
+ uint32_t tile_n,
+ uint32_t tile_stride,
+ uint32_t d_inner_stride,
+ uint32_t tile_off,
+ uint32_t d_conv) {
+ for (uint32_t cb = 0; cb < tile_n; cb += VLEN_FP32) {
+ HVX_Vector acc = hvx_vec_splat_f32(0.0f);
+ for (uint32_t j = 0; j < d_conv; ++j) {
+ HVX_Vector x = *(const HVX_Vector *)(src0_T + j * tile_stride + cb);
+ HVX_Vector w = *(const HVX_Vector *)(src1_T + j * d_inner_stride + tile_off + cb);
+ acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w));
+ }
+ *(HVX_Vector *)(out + cb) = Q6_Vsf_equals_Vqf32(acc);
+ }
+}
+
+static size_t ssm_conv_epilogue_f32(float * restrict out, uint32_t n_t, uint32_t tile_n) {
+ (void) out;
+ (void) n_t;
+ return (size_t) hex_round_up(tile_n, VLEN_FP32) * sizeof(float);
+}
+
+static size_t ssm_conv_epilogue_silu_f32(float * restrict out, uint32_t n_t, uint32_t tile_n) {
+ const uint32_t dst_tile_stride = hex_round_up(tile_n, VLEN_FP32);
+ hvx_ssm_conv_silu_vtcm(out, n_t * (dst_tile_stride / VLEN_FP32));
+ return (size_t) dst_tile_stride * sizeof(float);
+}
+
+static size_t ssm_conv_epilogue_f16(float * restrict out, uint32_t n_t, uint32_t tile_n) {
+ hvx_ssm_conv_pack_f16_rows_vtcm(out, n_t, tile_n);
+ return (size_t) hex_round_up(tile_n, VLEN_FP16) * sizeof(__fp16);
+}
+
+static size_t ssm_conv_epilogue_silu_f16(float * restrict out, uint32_t n_t, uint32_t tile_n) {
+ hvx_ssm_conv_silu_pack_f16_rows_vtcm(out, n_t, tile_n);
+ return (size_t) hex_round_up(tile_n, VLEN_FP16) * sizeof(__fp16);
+}
+
+static void ssm_conv_decode_dot_4_f32(const void * restrict raw_in,
+ float * restrict src0_T,
+ const float * restrict src1_raw,
+ const float * restrict src1_T,
+ float * restrict out,
+ uint32_t tile_n,
+ uint32_t d_inner_stride,
+ uint32_t tile_off,
+ uint32_t d_conv) {
+ (void) src0_T;
+ (void) src1_T;
+ (void) d_inner_stride;
+ (void) d_conv;
+ hvx_ssm_conv_decode_4((const float *) raw_in, src1_raw + tile_off * 4, out, tile_n);
+}
+
+static void ssm_conv_decode_dot_4_f16(const void * restrict raw_in,
+ float * restrict src0_T,
+ const float * restrict src1_raw,
+ const float * restrict src1_T,
+ float * restrict out,
+ uint32_t tile_n,
+ uint32_t d_inner_stride,
+ uint32_t tile_off,
+ uint32_t d_conv) {
+ (void) src0_T;
+ (void) src1_T;
+ (void) d_inner_stride;
+ (void) d_conv;
+ hvx_ssm_conv_decode_4_f16((const __fp16 *) raw_in, src1_raw + tile_off * 4, out, tile_n);
+}
+
+static void ssm_conv_decode_dot_gen_f32(const void * restrict raw_in,
+ float * restrict src0_T,
+ const float * restrict src1_raw,
+ const float * restrict src1_T,
+ float * restrict out,
+ uint32_t tile_n,
+ uint32_t d_inner_stride,
+ uint32_t tile_off,
+ uint32_t d_conv) {
+ (void) src1_raw;
+ const uint32_t tile_stride = hex_round_up(tile_n, VLEN_FP32);
+ hvx_ssm_conv_unpack_to_T((const float *) raw_in, src0_T, tile_n, tile_stride, d_conv);
+ hvx_ssm_conv_decode_dot_gen(src0_T, src1_T, out, tile_n, tile_stride, d_inner_stride, tile_off, d_conv);
+}
+
+static void ssm_conv_decode_dot_gen_f16(const void * restrict raw_in,
+ float * restrict src0_T,
+ const float * restrict src1_raw,
+ const float * restrict src1_T,
+ float * restrict out,
+ uint32_t tile_n,
+ uint32_t d_inner_stride,
+ uint32_t tile_off,
+ uint32_t d_conv) {
+ (void) src1_raw;
+ const uint32_t tile_stride = hex_round_up(tile_n, VLEN_FP32);
+ hvx_ssm_conv_unpack_to_T_f16((const __fp16 *) raw_in, src0_T, tile_n, tile_stride, d_conv);
+ hvx_ssm_conv_decode_dot_gen(src0_T, src1_T, out, tile_n, tile_stride, d_inner_stride, tile_off, d_conv);
+}
+
// Transpose src0 for prefill: one 32-channel block {32, ncs} (VTCM) -> T {ncs, 32} (VTCM).
// One VTCM gather per output row: lane r picks channel cb+r, the region bound drops
// the lanes past the channel tail.
-static inline void hvx_ssm_conv_transpose_block(const float * raw_block,
- float * T,
- uint32_t raw_stride_bytes,
- uint32_t ncs,
- uint32_t cb_n,
- HVX_Vector vv) {
- const size_t base = (size_t) raw_block;
- const uint32_t mu = cb_n * raw_stride_bytes - 1;
+static __attribute__((noinline)) void hvx_ssm_conv_transpose_block(const void * restrict raw_block,
+ float * restrict T,
+ uint32_t raw_stride_bytes,
+ uint32_t ncs,
+ uint32_t cb_n) {
+ const size_t base = (size_t) raw_block;
+ const uint32_t mu = cb_n * raw_stride_bytes - 1;
+ const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes);
for (uint32_t t = 0; t < ncs; ++t) {
Q6_vgather_ARMVw((HVX_Vector *) (T + (size_t) t * VLEN_FP32), base + t * sizeof(float), mu, vv);
}
+
+ hvx_gather_sync(T);
+}
+
+// Transpose + widen F16 src0 for prefill: each 32-bit word gather fetches 2 consecutive F16 time steps
+// across 32 channels into even rows of T, then hvx_vec_f16_to_f32_shuff widens them into rows t and t+1.
+static __attribute__((noinline)) void hvx_ssm_conv_transpose_block_f16(const void * restrict raw_block,
+ float * restrict T,
+ uint32_t raw_stride_bytes,
+ uint32_t ncs,
+ uint32_t cb_n) {
+ const size_t base = (size_t) raw_block;
+ const uint32_t mu = cb_n * raw_stride_bytes - 1;
+ const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes);
+ HVX_Vector * T_vec = (HVX_Vector *) T;
+
+ for (uint32_t t = 0; t < ncs; t += 2) {
+ Q6_vgather_ARMVw(&T_vec[t], base + t * sizeof(__fp16), mu, vv);
+ }
+
+ hvx_gather_sync(T);
+
+ for (uint32_t t = 0; t < ncs; t += 2) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(T_vec[t]);
+ T_vec[t] = Q6_V_lo_W(p);
+ if (t + 1 < ncs) {
+ T_vec[t + 1] = Q6_V_hi_W(p);
+ }
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_prefill_dot_block_4(const float * restrict src0_T,
+ const float * restrict wp,
+ float * restrict op,
+ uint32_t n_t,
+ uint32_t d_conv,
+ uint32_t d_inner_stride,
+ uint32_t dst_tile_stride) {
+ (void) d_conv;
+ const uint32_t C_TILE = VLEN_FP32;
+ const HVX_Vector w0 = *(const HVX_Vector *) (wp);
+ const HVX_Vector w1 = *(const HVX_Vector *) (wp + d_inner_stride);
+ const HVX_Vector w2 = *(const HVX_Vector *) (wp + 2 * d_inner_stride);
+ const HVX_Vector w3 = *(const HVX_Vector *) (wp + 3 * d_inner_stride);
+
+ HVX_Vector x0 = *(const HVX_Vector *) (src0_T);
+ HVX_Vector x1 = *(const HVX_Vector *) (src0_T + C_TILE);
+ HVX_Vector x2 = *(const HVX_Vector *) (src0_T + 2 * C_TILE);
+
+ for (uint32_t t = 0; t < n_t; ++t) {
+ const HVX_Vector x3 = *(const HVX_Vector *) (src0_T + (t + 3) * C_TILE);
+
+ HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0),
+ Q6_Vqf32_vmpy_VsfVsf(x1, w1));
+ HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, w2),
+ Q6_Vqf32_vmpy_VsfVsf(x3, w3));
+
+ *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b));
+
+ x0 = x1;
+ x1 = x2;
+ x2 = x3;
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_prefill_dot_block_gen(const float * restrict src0_T,
+ const float * restrict wp,
+ float * restrict op,
+ uint32_t n_t,
+ uint32_t d_conv,
+ uint32_t d_inner_stride,
+ uint32_t dst_tile_stride) {
+ const uint32_t C_TILE = VLEN_FP32;
+ for (uint32_t t = 0; t < n_t; ++t) {
+ HVX_Vector acc = hvx_vec_splat_f32(0.0f);
+ for (uint32_t j = 0; j < d_conv; ++j) {
+ HVX_Vector x = *(const HVX_Vector *) (src0_T + (t + j) * C_TILE);
+ HVX_Vector w = *(const HVX_Vector *) (wp + j * d_inner_stride);
+ acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w));
+ }
+ *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(acc);
+ }
+}
+
+// HVX scatter transpose for tap-major hist [s_taps, c_stride] -> channel-major raw [cur_c, s_taps]
+static __attribute__((noinline)) void hvx_ssm_conv_pack_from_T_gen(const float * restrict hist,
+ float * restrict raw,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps) {
+ const uint32_t raw_stride_bytes = s_taps * sizeof(float);
+ const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes);
+
+ for (uint32_t cb = 0; cb < cur_c; cb += VLEN_FP32) {
+ const uint32_t cb_n = MIN(VLEN_FP32, cur_c - cb);
+ const size_t base = (size_t) (raw + (size_t) cb * s_taps);
+ const uint32_t mu = cb_n * raw_stride_bytes - 1;
+
+ for (uint32_t j = 0; j < s_taps; ++j) {
+ const HVX_Vector vj = *(const HVX_Vector *) (hist + (size_t) j * c_stride + cb);
+ Q6_vscatter_RMVwV(base + j * sizeof(float), mu, vv, vj);
+ }
+ }
+
+ hvx_gather_sync(raw);
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_pack_f16_flat_vtcm(const float * restrict src,
+ __fp16 * restrict dst,
+ uint32_t n_elems) {
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector zero = Q6_V_vzero();
+ const uint32_t n_v32 = (n_elems + VLEN_FP32 - 1) / VLEN_FP32;
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ for (uint32_t i = 0; i < n_v32; i += 2) {
+ HVX_Vector v0 = vsrc[i];
+ HVX_Vector v1 = (i + 1 < n_v32) ? vsrc[i + 1] : zero;
+ v0 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v0, f16_max), f16_min);
+ v1 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v1, f16_max), f16_min);
+ vdst[i / 2] = hvx_vec_f32_to_f16(v0, v1);
+ }
+}
+
+static void ssm_conv_state_unpack_f32_nat(float * restrict state_raw,
+ float * restrict hist,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps) {
+ hvx_ssm_conv_unpack_to_T_gen(state_raw, hist, cur_c, c_stride, s_taps);
+}
+
+static void ssm_conv_state_unpack_f16_nat(float * restrict state_raw,
+ float * restrict hist,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps) {
+ hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) hist, state_raw, cur_c * s_taps);
+ hvx_ssm_conv_unpack_to_T_gen(state_raw, hist, cur_c, c_stride, s_taps);
+}
+
+static void ssm_conv_state_pack_f32_nat(float * restrict hist,
+ float * restrict state_raw,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps) {
+ hvx_ssm_conv_pack_from_T_gen(hist, state_raw, cur_c, c_stride, s_taps);
+}
+
+static void ssm_conv_state_pack_f16_nat(float * restrict hist,
+ float * restrict state_raw,
+ uint32_t cur_c,
+ uint32_t c_stride,
+ uint32_t s_taps) {
+ hvx_ssm_conv_pack_from_T_gen(hist, state_raw, cur_c, c_stride, s_taps);
+ hvx_ssm_conv_pack_f16_flat_vtcm(state_raw, (__fp16 *) hist, cur_c * s_taps);
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_pack_f16_strip_1d(const float * restrict strip_f32,
+ uint8_t * restrict dp,
+ uint32_t cur_t,
+ size_t d_row_stride,
+ bool has_hi) {
+ const HVX_Vector * restrict sp = (const HVX_Vector *) strip_f32;
+ const uint32_t hi_off = has_hi ? 1 : 0;
+ _Pragma("clang loop unroll(disable)")
+ for (uint32_t t = 0; t < cur_t; ++t) {
+ HVX_Vector u0 = sp[0];
+ HVX_Vector u1 = sp[hi_off];
+ *(HVX_Vector *) dp = hvx_vec_f32_to_f16(hvx_ssm_conv_clamp_f16_f32(u0),
+ hvx_ssm_conv_clamp_f16_f32(u1));
+ sp += 2;
+ dp += d_row_stride;
+ }
}
+static __attribute__((noinline)) void hvx_ssm_conv_silu_pack_f16_strip_1d(const float * restrict strip_f32,
+ uint8_t * restrict dp,
+ uint32_t cur_t,
+ size_t d_row_stride,
+ bool has_hi) {
+ const HVX_Vector * restrict sp = (const HVX_Vector *) strip_f32;
+ const uint32_t hi_off = has_hi ? 1 : 0;
+
+#if __HVX_ARCH__ >= 81
+ _Pragma("clang loop unroll(disable)")
+#else
+ _Pragma("clang loop unroll(disable) pipeline(disable)")
+#endif
+ for (uint32_t t = 0; t < cur_t; ++t) {
+ *(HVX_Vector *) dp = hvx_ssm_conv_silu_pack_f16(sp[0], sp[hi_off]);
+ sp += 2;
+ dp += d_row_stride;
+ }
+}
+
+#define DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP(NAME, X_F16) \
+ static __attribute__((noinline)) void NAME(float * restrict hist, \
+ const void * restrict x_tile, \
+ const float * restrict wp, \
+ void * restrict out_ptr, \
+ uint32_t cb, \
+ uint32_t cur_t, \
+ uint32_t c_stride, \
+ uint32_t w_stride, \
+ size_t x_row_stride, \
+ size_t out_row_stride) { \
+ const HVX_Vector w0_0 = *(const HVX_Vector *) (wp + 0 * w_stride + cb + 0); \
+ const HVX_Vector w0_1 = *(const HVX_Vector *) (wp + 0 * w_stride + cb + 32); \
+ const HVX_Vector w1_0 = *(const HVX_Vector *) (wp + 1 * w_stride + cb + 0); \
+ const HVX_Vector w1_1 = *(const HVX_Vector *) (wp + 1 * w_stride + cb + 32); \
+ const HVX_Vector w2_0 = *(const HVX_Vector *) (wp + 2 * w_stride + cb + 0); \
+ const HVX_Vector w2_1 = *(const HVX_Vector *) (wp + 2 * w_stride + cb + 32); \
+ const HVX_Vector w3_0 = *(const HVX_Vector *) (wp + 3 * w_stride + cb + 0); \
+ const HVX_Vector w3_1 = *(const HVX_Vector *) (wp + 3 * w_stride + cb + 32); \
+ \
+ HVX_Vector xm3_0 = *(const HVX_Vector *) (hist + 0 * c_stride + cb + 0); \
+ HVX_Vector xm3_1 = *(const HVX_Vector *) (hist + 0 * c_stride + cb + 32); \
+ HVX_Vector xm2_0 = *(const HVX_Vector *) (hist + 1 * c_stride + cb + 0); \
+ HVX_Vector xm2_1 = *(const HVX_Vector *) (hist + 1 * c_stride + cb + 32); \
+ HVX_Vector xm1_0 = *(const HVX_Vector *) (hist + 2 * c_stride + cb + 0); \
+ HVX_Vector xm1_1 = *(const HVX_Vector *) (hist + 2 * c_stride + cb + 32); \
+ \
+ const uint8_t * restrict xp = (const uint8_t *) x_tile + cb * (X_F16 ? 2 : 4); \
+ uint8_t * restrict dp = (uint8_t *) out_ptr; \
+ \
+ _Pragma("clang loop unroll(disable)") \
+ for (uint32_t t = 0; t < cur_t; ++t) { \
+ HVX_Vector x0_0; \
+ HVX_Vector x0_1; \
+ if (X_F16) { \
+ HVX_VectorPair x0_p = hvx_vec_f16_to_f32(*(const HVX_Vector *) xp); \
+ x0_0 = Q6_V_lo_W(x0_p); \
+ x0_1 = Q6_V_hi_W(x0_p); \
+ } else { \
+ x0_0 = *((const HVX_Vector *) xp + 0); \
+ x0_1 = *((const HVX_Vector *) xp + 1); \
+ } \
+ \
+ HVX_Vector a0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm3_0, w0_0), \
+ Q6_Vqf32_vmpy_VsfVsf(xm2_0, w1_0)); \
+ HVX_Vector b0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm1_0, w2_0), \
+ Q6_Vqf32_vmpy_VsfVsf(x0_0, w3_0)); \
+ HVX_Vector a1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm3_1, w0_1), \
+ Q6_Vqf32_vmpy_VsfVsf(xm2_1, w1_1)); \
+ HVX_Vector b1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm1_1, w2_1), \
+ Q6_Vqf32_vmpy_VsfVsf(x0_1, w3_1)); \
+ *((HVX_Vector *) dp + 0) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a0, b0)); \
+ *((HVX_Vector *) dp + 1) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a1, b1)); \
+ \
+ xm3_0 = xm2_0; \
+ xm3_1 = xm2_1; \
+ xm2_0 = xm1_0; \
+ xm2_1 = xm1_1; \
+ xm1_0 = x0_0; \
+ xm1_1 = x0_1; \
+ \
+ xp += x_row_stride; \
+ dp += out_row_stride; \
+ } \
+ \
+ *(HVX_Vector *) (hist + 0 * c_stride + cb + 0) = xm3_0; \
+ *(HVX_Vector *) (hist + 0 * c_stride + cb + 32) = xm3_1; \
+ *(HVX_Vector *) (hist + 1 * c_stride + cb + 0) = xm2_0; \
+ *(HVX_Vector *) (hist + 1 * c_stride + cb + 32) = xm2_1; \
+ *(HVX_Vector *) (hist + 2 * c_stride + cb + 0) = xm1_0; \
+ *(HVX_Vector *) (hist + 2 * c_stride + cb + 32) = xm1_1; \
+ }
+
+DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP(hvx_ssm_conv_token_4_dot_f32_strip, false)
+DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP(hvx_ssm_conv_token_4_dot_f16_strip, true)
+
+#undef DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP
+
+#define DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32(NAME, X_F16) \
+ static __attribute__((noinline)) void NAME(float * restrict hist, \
+ const void * restrict x_tile, \
+ const float * restrict wp, \
+ void * restrict dst_tile, \
+ uint32_t cur_c, \
+ uint32_t cur_t, \
+ uint32_t c_stride, \
+ uint32_t w_stride, \
+ size_t x_row_stride, \
+ size_t f32_row_stride) { \
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) { \
+ for (uint32_t sub = 0; sub < 64 && cb + sub < cur_c; sub += 32) { \
+ const uint32_t ch = cb + sub; \
+ const HVX_Vector w0 = *(const HVX_Vector *) (wp + 0 * w_stride + ch); \
+ const HVX_Vector w1 = *(const HVX_Vector *) (wp + 1 * w_stride + ch); \
+ const HVX_Vector w2 = *(const HVX_Vector *) (wp + 2 * w_stride + ch); \
+ const HVX_Vector w3 = *(const HVX_Vector *) (wp + 3 * w_stride + ch); \
+ \
+ HVX_Vector xm3 = *(const HVX_Vector *) (hist + 0 * c_stride + ch); \
+ HVX_Vector xm2 = *(const HVX_Vector *) (hist + 1 * c_stride + ch); \
+ HVX_Vector xm1 = *(const HVX_Vector *) (hist + 2 * c_stride + ch); \
+ \
+ const uint8_t * restrict xp = (const uint8_t *) x_tile + \
+ (X_F16 ? (cb * 2) : (ch * 4)); \
+ uint8_t * restrict dp = (uint8_t *) dst_tile + ch * sizeof(float); \
+ \
+ _Pragma("clang loop unroll(disable) pipeline(disable)") \
+ for (uint32_t t = 0; t < cur_t; ++t) { \
+ HVX_Vector x0; \
+ if (X_F16) { \
+ HVX_VectorPair x0_p = hvx_vec_f16_to_f32(*(const HVX_Vector *) xp); \
+ x0 = (sub == 0) ? Q6_V_lo_W(x0_p) : Q6_V_hi_W(x0_p); \
+ } else { \
+ x0 = *(const HVX_Vector *) xp; \
+ } \
+ \
+ HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm3, w0), \
+ Q6_Vqf32_vmpy_VsfVsf(xm2, w1)); \
+ HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm1, w2), \
+ Q6_Vqf32_vmpy_VsfVsf(x0, w3)); \
+ HVX_Vector u = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b)); \
+ *(HVX_Vector *) dp = hvx_vec_silu_f32(u); \
+ \
+ xm3 = xm2; \
+ xm2 = xm1; \
+ xm1 = x0; \
+ \
+ xp += x_row_stride; \
+ dp += f32_row_stride; \
+ } \
+ \
+ *(HVX_Vector *) (hist + 0 * c_stride + ch) = xm3; \
+ *(HVX_Vector *) (hist + 1 * c_stride + ch) = xm2; \
+ *(HVX_Vector *) (hist + 2 * c_stride + ch) = xm1; \
+ } \
+ } \
+ }
+
+DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32(hvx_ssm_conv_token_4_dot_f32_silu, false)
+DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32(hvx_ssm_conv_token_4_dot_f16_silu, true)
+
+#undef DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f16(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) {
+ hvx_ssm_conv_token_4_dot_f16_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256);
+ hvx_ssm_conv_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c);
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f16_silu(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) {
+ hvx_ssm_conv_token_4_dot_f16_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256);
+ hvx_ssm_conv_silu_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c);
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f32(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ (void) strip_f32;
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) {
+ hvx_ssm_conv_token_4_dot_f32_strip(hist, x_tile, wp, (uint8_t *) dst_tile + cb * sizeof(float), cb, cur_t, c_stride, w_stride, x_row_stride, d_row_stride);
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f32_silu(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ (void) strip_f32;
+ hvx_ssm_conv_token_4_dot_f32_silu(hist, x_tile, wp, dst_tile, cur_c, cur_t, c_stride, w_stride, x_row_stride, d_row_stride);
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f16(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) {
+ hvx_ssm_conv_token_4_dot_f32_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256);
+ hvx_ssm_conv_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c);
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f16_silu(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) {
+ hvx_ssm_conv_token_4_dot_f32_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256);
+ hvx_ssm_conv_silu_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c);
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f32(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ (void) strip_f32;
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) {
+ hvx_ssm_conv_token_4_dot_f16_strip(hist, x_tile, wp, (uint8_t *) dst_tile + cb * sizeof(float), cb, cur_t, c_stride, w_stride, x_row_stride, d_row_stride);
+ }
+}
+
+static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f32_silu(float * restrict hist,
+ const void * restrict x_tile,
+ const float * restrict wp,
+ void * restrict dst_tile,
+ float * restrict strip_f32,
+ uint32_t cur_c,
+ uint32_t cur_t,
+ uint32_t d_conv,
+ uint32_t c_stride,
+ uint32_t w_stride,
+ size_t x_row_stride,
+ size_t d_row_stride) {
+ (void) d_conv;
+ (void) strip_f32;
+ hvx_ssm_conv_token_4_dot_f16_silu(hist, x_tile, wp, dst_tile, cur_c, cur_t, c_stride, w_stride, x_row_stride, d_row_stride);
+}
+
+#define DEFINE_SSM_CONV_TOKEN_GEN(NAME, X_F16, DST_F16, APPLY_SILU) \
+ static __attribute__((noinline)) void NAME(float * restrict hist, \
+ const void * restrict x_tile, \
+ const float * restrict wp, \
+ void * restrict dst_tile, \
+ float * restrict strip_f32, \
+ uint32_t cur_c, \
+ uint32_t cur_t, \
+ uint32_t d_conv, \
+ uint32_t c_stride, \
+ uint32_t w_stride, \
+ size_t x_row_stride, \
+ size_t d_row_stride) { \
+ (void) strip_f32; \
+ const uint32_t s_taps = d_conv - 1; \
+ for (uint32_t cb = 0; cb < cur_c; cb += 64) { \
+ const uint8_t * restrict xp = (const uint8_t *) x_tile + cb * (X_F16 ? 2 : 4); \
+ uint8_t * restrict dp = (uint8_t *) dst_tile + cb * (DST_F16 ? 2 : 4); \
+ \
+ _Pragma("clang loop unroll(disable) pipeline(disable)") \
+ for (uint32_t t = 0; t < cur_t; ++t) { \
+ HVX_Vector x0_0; \
+ HVX_Vector x0_1; \
+ if (X_F16) { \
+ HVX_VectorPair x0_p = hvx_vec_f16_to_f32(*(const HVX_Vector *) xp); \
+ x0_0 = Q6_V_lo_W(x0_p); \
+ x0_1 = Q6_V_hi_W(x0_p); \
+ } else { \
+ x0_0 = *((const HVX_Vector *) xp + 0); \
+ x0_1 = *((const HVX_Vector *) xp + 1); \
+ } \
+ \
+ HVX_Vector acc0 = Q6_Vqf32_vmpy_VsfVsf( \
+ x0_0, *(const HVX_Vector *) (wp + (size_t) s_taps * w_stride + cb + 0)); \
+ HVX_Vector acc1 = Q6_Vqf32_vmpy_VsfVsf( \
+ x0_1, *(const HVX_Vector *) (wp + (size_t) s_taps * w_stride + cb + 32)); \
+ \
+ _Pragma("clang loop unroll(disable)") \
+ for (uint32_t j = 0; j < s_taps; ++j) { \
+ HVX_Vector hj_0 = *(const HVX_Vector *) (hist + (size_t) j * c_stride + cb + 0); \
+ HVX_Vector hj_1 = *(const HVX_Vector *) (hist + (size_t) j * c_stride + cb + 32); \
+ HVX_Vector wj_0 = *(const HVX_Vector *) (wp + (size_t) j * w_stride + cb + 0); \
+ HVX_Vector wj_1 = *(const HVX_Vector *) (wp + (size_t) j * w_stride + cb + 32); \
+ acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, Q6_Vqf32_vmpy_VsfVsf(hj_0, wj_0)); \
+ acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, Q6_Vqf32_vmpy_VsfVsf(hj_1, wj_1)); \
+ if (j > 0) { \
+ *(HVX_Vector *) (hist + (size_t) (j - 1) * c_stride + cb + 0) = hj_0; \
+ *(HVX_Vector *) (hist + (size_t) (j - 1) * c_stride + cb + 32) = hj_1; \
+ } \
+ } \
+ *(HVX_Vector *) (hist + (size_t) (s_taps - 1) * c_stride + cb + 0) = x0_0; \
+ *(HVX_Vector *) (hist + (size_t) (s_taps - 1) * c_stride + cb + 32) = x0_1; \
+ \
+ HVX_Vector u0 = Q6_Vsf_equals_Vqf32(acc0); \
+ HVX_Vector u1 = Q6_Vsf_equals_Vqf32(acc1); \
+ \
+ if (DST_F16) { \
+ if (APPLY_SILU) { \
+ *(HVX_Vector *) dp = hvx_ssm_conv_silu_pack_f16(u0, u1); \
+ } else { \
+ *(HVX_Vector *) dp = hvx_vec_f32_to_f16(hvx_ssm_conv_clamp_f16_f32(u0), \
+ hvx_ssm_conv_clamp_f16_f32(u1)); \
+ } \
+ } else { \
+ if (APPLY_SILU) { \
+ u0 = hvx_vec_silu_f32(u0); \
+ u1 = hvx_vec_silu_f32(u1); \
+ } \
+ *((HVX_Vector *) dp + 0) = u0; \
+ *((HVX_Vector *) dp + 1) = u1; \
+ } \
+ \
+ xp += x_row_stride; \
+ dp += d_row_stride; \
+ } \
+ } \
+ }
+
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f32, false, false, false)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f32_silu, false, false, true)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f16, false, true, false)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f16_silu, false, true, true)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f32, true, false, false)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f32_silu, true, false, true)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f16, true, true, false)
+DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f16_silu, true, true, true)
+
+#undef DEFINE_SSM_CONV_TOKEN_GEN
+
// Single-token decode worker (n_t == 1)
static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_ssm_conv_context * scctx = (struct htp_ssm_conv_context *) data;
@@ -197,10 +1024,19 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
dma_queue * dma_q = th->dma_q;
- const uint32_t d_conv = kparams->d_conv;
- const uint32_t d_inner = kparams->d_inner;
- const uint32_t n_s = kparams->n_s;
- const bool apply_silu = kparams->silu != 0;
+ const uint32_t d_conv = kparams->d_conv;
+ const uint32_t n_s = kparams->n_s;
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const bool src1_f16 = (src1->type == HTP_TYPE_F16);
+ const bool dst_f16 = (dst->type == HTP_TYPE_F16);
+ const bool raw_dot = scctx->raw_dot;
+
+ const htp_ssm_conv_decode_dot_fn_t decode_dot_fn = scctx->decode_dot_fn;
+ const htp_ssm_conv_epilogue_fn_t epilogue_fn = scctx->epilogue_fn;
+
+ const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t src1_elem_size = src1_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float);
const uint32_t dr = scctx->nrows_per_hvx;
const uint32_t ir0 = scctx->row_start + dr * ith;
@@ -210,26 +1046,28 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
return;
}
- const uint32_t d_inner_per_hvx = ir1 - ir0;
- const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32);
- const uint32_t d_inner_tile = scctx->d_inner_tile;
+ const uint32_t d_inner_per_hvx = ir1 - ir0;
+ const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32);
+ const uint32_t d_inner_tile = scctx->d_inner_tile;
const size_t src0_stride_inner_bytes = src0->nb[1];
const size_t src0_stride_seq_bytes = src0->nb[2];
const size_t dst_stride_seq_bytes = dst->nb[2];
- uint8_t * src1_spad_base = octx->src1_spad.data + ith * octx->src1_spad.size_per_hvx;
- uint8_t * src0_spad_base = octx->src0_spad.data + ith * octx->src0_spad.size_per_hvx;
- uint8_t * dst_spad_base = octx->dst_spad.data + ith * octx->dst_spad.size_per_hvx;
+ uint8_t * src1_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src1) + ith * scctx->layout.src1_bytes_per_hvx;
+ uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src0) + ith * scctx->layout.src0_bytes_per_hvx;
+ uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_dst) + ith * scctx->layout.dst_bytes_per_hvx;
- const size_t weight_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float);
- const size_t weight_raw_size = hex_round_up(weight_bytes, 128);
+ const size_t weight_f32_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float);
+ const size_t weight_dma_bytes = (size_t) d_inner_per_hvx * d_conv * src1_elem_size;
+ const size_t weight_raw_size = hex_round_up(weight_f32_bytes, 128) + 128;
float * src1_raw = (float *) src1_spad_base;
float * src1_T = (float *) (src1_spad_base + weight_raw_size);
- const size_t src0_tile_raw_bytes = hex_round_up(d_inner_tile * d_conv * sizeof(float), 128);
- const size_t dst_tile_bytes = hex_round_up(d_inner_tile * sizeof(float), 128);
+ const size_t raw_stride_bytes = src0_f16 ? ((size_t) hex_round_up(d_conv, 2) * sizeof(__fp16)) : ((size_t) d_conv * sizeof(float));
+ const size_t src0_tile_raw_bytes = hex_round_up((size_t) d_inner_tile * raw_stride_bytes, 128);
+ const size_t dst_tile_bytes = hex_round_up((size_t) d_inner_tile * sizeof(float), 128);
float * src0_tile_raw[2] = { (float *) src0_spad_base, (float *) (src0_spad_base + src0_tile_raw_bytes) };
float * src0_T = (float *) (src0_spad_base + 2 * src0_tile_raw_bytes);
@@ -238,12 +1076,9 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
struct htp_thread_trace * tr = th->trace;
- // raw_dot keeps both operands in the DMA layout, so src1 needs no prep pass
- const bool raw_dot = (d_conv == 4) && (d_inner_per_hvx % VLEN_FP32 == 0);
-
const uint32_t n_tiles = fastdiv(d_inner_per_hvx + d_inner_tile - 1, &kparams->div_d_inner_tile);
const uint32_t n_chunks = n_s * n_tiles;
- const size_t row_bytes = d_conv * sizeof(float);
+ const size_t row_bytes = (size_t) d_conv * src0_elem_size;
uint32_t s_fetch = 0;
uint32_t tile_off_fetch = 0;
@@ -251,11 +1086,11 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
#define SSM_CONV_DECODE_PUSH_FETCH(c) \
do { \
const uint32_t cur_tile_n = MIN(d_inner_tile, d_inner_per_hvx - tile_off_fetch); \
- const dma_addr_t fetch_ddr = src0->data + s_fetch * src0_stride_seq_bytes + \
- (ir0 + tile_off_fetch) * src0_stride_inner_bytes; \
+ const dma_addr_t fetch_ddr = src0->data + (s_fetch * src0_stride_seq_bytes + \
+ (ir0 + tile_off_fetch) * src0_stride_inner_bytes); \
dma_queue_push(dma_q, \
dma_make_data((uint8_t *) src0_tile_raw[(c) & 1], fetch_ddr), \
- row_bytes, src0_stride_inner_bytes, row_bytes, cur_tile_n); \
+ raw_stride_bytes, src0_stride_inner_bytes, row_bytes, cur_tile_n); \
tile_off_fetch += d_inner_tile; \
if (tile_off_fetch >= d_inner_per_hvx) { \
tile_off_fetch = 0; \
@@ -264,20 +1099,27 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
} while (0)
// Queue weights and initial input tiles together so DDR reads overlap
- const dma_addr_t src1_ddr = src1->data + ir0 * d_conv * sizeof(float);
- dma_queue_push(dma_q, dma_make_data((uint8_t *) src1_raw, src1_ddr), weight_bytes, weight_bytes, weight_bytes, 1);
+ const dma_addr_t src1_ddr = src1->data + (size_t) ir0 * d_conv * src1_elem_size;
+ uint8_t * src1_dma_dest = src1_f16 ? (uint8_t *) src1_T : (uint8_t *) src1_raw;
+ dma_queue_push(dma_q, dma_make_data(src1_dma_dest, src1_ddr), weight_dma_bytes, weight_dma_bytes, weight_dma_bytes, 1);
+ dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[0]), 0, 0, 0, 0);
SSM_CONV_DECODE_PUSH_FETCH(0);
if (n_chunks > 1) {
+ dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[1]), 0, 0, 0, 0);
SSM_CONV_DECODE_PUSH_FETCH(1);
}
dma_queue_pop(dma_q); // weights
- if (!raw_dot) {
- // Unpack/transpose src1_raw into src1_T {d_conv, d_inner_stride}
+ if (src1_f16 || !raw_dot) {
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0);
- hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, d_inner_stride, d_conv);
+ if (src1_f16) {
+ hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) src1_T, src1_raw, d_inner_per_hvx * d_conv);
+ }
+ if (!raw_dot) {
+ hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, d_inner_stride, d_conv);
+ }
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0);
}
@@ -287,39 +1129,18 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
for (uint32_t c = 0; c < n_chunks; ++c) {
const uint32_t tile_n = MIN(d_inner_tile, d_inner_per_hvx - tile_off);
- if (c >= 2) {
- dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1]
- }
+ dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1]
dma_queue_pop(dma_q); // fetch chunk c
float * restrict out = dst_tile[c & 1];
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i3);
- if (raw_dot) {
- const float * xp = src0_tile_raw[c & 1];
- const float * wp = src1_raw + tile_off * 4;
- hvx_ssm_conv_decode_4(xp, wp, out, tile_n);
- } else {
- const uint32_t tile_stride = hex_round_up(tile_n, VLEN_FP32);
- hvx_ssm_conv_unpack_to_T(src0_tile_raw[c & 1], src0_T, tile_n, tile_stride, d_conv);
-
- for (uint32_t cb = 0; cb < tile_n; cb += VLEN_FP32) {
- HVX_Vector acc = hvx_vec_splat_f32(0.0f);
- for (uint32_t j = 0; j < d_conv; ++j) {
- HVX_Vector x = *(const HVX_Vector *)(src0_T + j * tile_stride + cb);
- HVX_Vector w = *(const HVX_Vector *)(src1_T + j * d_inner_stride + tile_off + cb);
- acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w));
- }
- *(HVX_Vector *)(out + cb) = Q6_Vsf_equals_Vqf32(acc);
- }
- }
- if (apply_silu) {
- hvx_ssm_conv_silu_vtcm(out, hex_round_up(tile_n, VLEN_FP32) / VLEN_FP32);
- }
+ decode_dot_fn(src0_tile_raw[c & 1], src0_T, src1_raw, src1_T, out, tile_n, d_inner_stride, tile_off, d_conv);
+ epilogue_fn(out, 1, tile_n);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i3);
- const dma_addr_t dst_ddr = dst->data + i3 * dst_stride_seq_bytes + (ir0 + tile_off) * sizeof(float);
- const size_t tile_out_bytes = (size_t) tile_n * sizeof(float);
+ const dma_addr_t dst_ddr = dst->data + (i3 * dst_stride_seq_bytes + (size_t) (ir0 + tile_off) * dst_elem_size);
+ const size_t tile_out_bytes = (size_t) tile_n * dst_elem_size;
dma_queue_push(dma_q, dma_make_data(dst_ddr, (uint8_t *) out),
tile_out_bytes, tile_out_bytes, tile_out_bytes, 1);
@@ -334,9 +1155,7 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth
}
}
- for (uint32_t k = MIN(n_chunks, 2); k > 0; --k) {
- dma_queue_pop(dma_q); // drain the last writebacks
- }
+ dma_queue_flush(dma_q);
#undef SSM_CONV_DECODE_PUSH_FETCH
@@ -358,12 +1177,21 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
dma_queue * dma_q = th->dma_q;
- const uint32_t d_conv = kparams->d_conv;
- const uint32_t d_inner = kparams->d_inner;
- const uint32_t n_t = kparams->n_t;
- const uint32_t n_s = kparams->n_s;
- const uint32_t ncs = src0->ne[0];
- const bool apply_silu = kparams->silu != 0;
+ const uint32_t d_conv = kparams->d_conv;
+ const uint32_t n_t = kparams->n_t;
+ const uint32_t n_s = kparams->n_s;
+ const uint32_t ncs = src0->ne[0];
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const bool src1_f16 = (src1->type == HTP_TYPE_F16);
+ const bool dst_f16 = (dst->type == HTP_TYPE_F16);
+
+ const htp_ssm_conv_transpose_block_fn_t transpose_block_fn = scctx->transpose_block_fn;
+ const htp_ssm_conv_prefill_dot_fn_t prefill_dot_fn = scctx->prefill_dot_fn;
+ const htp_ssm_conv_epilogue_fn_t epilogue_fn = scctx->epilogue_fn;
+
+ const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t src1_elem_size = src1_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float);
const uint32_t dr = scctx->nrows_per_hvx;
const uint32_t ir0 = scctx->row_start + dr * ith;
@@ -373,28 +1201,29 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
return;
}
- const uint32_t d_inner_per_hvx = ir1 - ir0;
- const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32);
- const uint32_t d_inner_tile = scctx->d_inner_tile;
+ const uint32_t d_inner_per_hvx = ir1 - ir0;
+ const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32);
+ const uint32_t d_inner_tile = scctx->d_inner_tile;
const size_t src0_stride_inner_bytes = src0->nb[1];
const size_t src0_stride_seq_bytes = src0->nb[2];
const size_t dst_stride_token_bytes = dst->nb[1];
const size_t dst_stride_seq_bytes = dst->nb[2];
- uint8_t * src1_spad_base = octx->src1_spad.data + ith * octx->src1_spad.size_per_hvx;
- uint8_t * src0_spad_base = octx->src0_spad.data + ith * octx->src0_spad.size_per_hvx;
- uint8_t * dst_spad_base = octx->dst_spad.data + ith * octx->dst_spad.size_per_hvx;
+ uint8_t * src1_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src1) + ith * scctx->layout.src1_bytes_per_hvx;
+ uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src0) + ith * scctx->layout.src0_bytes_per_hvx;
+ uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_dst) + ith * scctx->layout.dst_bytes_per_hvx;
- const size_t weight_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float);
- const size_t weight_raw_size = hex_round_up(weight_bytes, 128);
+ const size_t weight_f32_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float);
+ const size_t weight_dma_bytes = (size_t) d_inner_per_hvx * d_conv * src1_elem_size;
+ const size_t weight_raw_size = hex_round_up(weight_f32_bytes, 128) + 128;
float * src1_raw = (float *) src1_spad_base;
float * src1_T = (float *) (src1_spad_base + weight_raw_size);
// src0 spad holds two raw tiles (fetch of tile n+1 overlaps compute of tile n) plus
// the transposed block. dst spad holds two tiles so a writeback can stay in flight.
- const size_t raw_stride_bytes = ncs * sizeof(float) + sizeof(float);
+ const size_t raw_stride_bytes = htp_ssm_conv_raw_stride_bytes(ncs, src0_elem_size);
const size_t src0_tile_raw_bytes = hex_round_up(d_inner_tile * raw_stride_bytes, 128);
const size_t dst_tile_bytes = hex_round_up(d_inner_tile * n_t * sizeof(float), 128);
@@ -407,18 +1236,18 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
const uint32_t n_tiles = fastdiv(d_inner_per_hvx + d_inner_tile - 1, &kparams->div_d_inner_tile);
const uint32_t n_chunks = n_s * n_tiles;
- const size_t row_bytes = ncs * sizeof(float);
+ const size_t row_bytes = (size_t) ncs * src0_elem_size;
uint32_t s_fetch = 0;
uint32_t tile_off_fetch = 0;
// Chunk c fetches into src0_tile_raw[c & 1] and writes back from dst_tile[c & 1].
- // Two fetches run ahead, so the queue order is F0 F1 W0 F2 W1 ... and pops follow it.
+ // Two fetches run ahead with dummy writeback pushes in prologue: W-2 F0 W-1 F1 W0 F2 ...
#define SSM_CONV_PUSH_FETCH(c) \
do { \
const uint32_t cur_tile_n = MIN(d_inner_tile, d_inner_per_hvx - tile_off_fetch); \
- const dma_addr_t fetch_ddr = src0->data + s_fetch * src0_stride_seq_bytes + \
- (ir0 + tile_off_fetch) * src0_stride_inner_bytes; \
+ const dma_addr_t fetch_ddr = src0->data + (s_fetch * src0_stride_seq_bytes + \
+ (ir0 + tile_off_fetch) * src0_stride_inner_bytes); \
dma_queue_push(dma_q, \
dma_make_data((uint8_t *) src0_tile_raw[(c) & 1], fetch_ddr), \
raw_stride_bytes, src0_stride_inner_bytes, row_bytes, cur_tile_n); \
@@ -430,11 +1259,14 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
} while (0)
// Queue weights and initial input tiles together so DDR reads overlap
- const dma_addr_t src1_ddr = src1->data + ir0 * d_conv * sizeof(float);
- dma_queue_push(dma_q, dma_make_data((uint8_t *) src1_raw, src1_ddr), weight_bytes, weight_bytes, weight_bytes, 1);
+ const dma_addr_t src1_ddr = src1->data + (size_t) ir0 * d_conv * src1_elem_size;
+ uint8_t * src1_dma_dest = src1_f16 ? (uint8_t *) src1_T : (uint8_t *) src1_raw;
+ dma_queue_push(dma_q, dma_make_data(src1_dma_dest, src1_ddr), weight_dma_bytes, weight_dma_bytes, weight_dma_bytes, 1);
+ dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[0]), 0, 0, 0, 0);
SSM_CONV_PUSH_FETCH(0);
if (n_chunks > 1) {
+ dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[1]), 0, 0, 0, 0);
SSM_CONV_PUSH_FETCH(1);
}
@@ -442,14 +1274,14 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
// Unpack/transpose src1_raw into src1_T {d_conv, d_inner_stride}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0);
+ if (src1_f16) {
+ hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) src1_T, src1_raw, d_inner_per_hvx * d_conv);
+ }
hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, d_inner_stride, d_conv);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0);
const uint32_t C_TILE = VLEN_FP32;
- // gather offsets: lane r reads channel r of the raw tile block
- const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes);
-
uint32_t i3 = 0;
uint32_t tile_off = 0;
@@ -459,9 +1291,7 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
const float * restrict raw = src0_tile_raw[c & 1];
float * restrict out = dst_tile[c & 1];
- if (c >= 2) {
- dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1]
- }
+ dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1]
dma_queue_pop(dma_q); // fetch chunk c
// Channel block outer, token inner: the taps and the sliding window stay in
@@ -472,61 +1302,25 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
const uint32_t cb_n = MIN(C_TILE, tile_n - cb);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off);
- const float * raw_ch = (const float *) ((const uint8_t *) raw + (size_t) cb * raw_stride_bytes);
- hvx_ssm_conv_transpose_block(raw_ch, src0_T, raw_stride_bytes, ncs, cb_n, vv);
+ const uint8_t * raw_ch = (const uint8_t *) raw + (size_t) cb * raw_stride_bytes;
+ transpose_block_fn(raw_ch, src0_T, raw_stride_bytes, ncs, cb_n);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off);
const float * restrict wp = src1_T + tile_off + cb;
float * restrict op = out + cb;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off);
- if (d_conv == 4) {
- const HVX_Vector w0 = *(const HVX_Vector *) (wp);
- const HVX_Vector w1 = *(const HVX_Vector *) (wp + d_inner_stride);
- const HVX_Vector w2 = *(const HVX_Vector *) (wp + 2 * d_inner_stride);
- const HVX_Vector w3 = *(const HVX_Vector *) (wp + 3 * d_inner_stride);
-
- HVX_Vector x0 = *(const HVX_Vector *) (src0_T);
- HVX_Vector x1 = *(const HVX_Vector *) (src0_T + C_TILE);
- HVX_Vector x2 = *(const HVX_Vector *) (src0_T + 2 * C_TILE);
-
- for (uint32_t t = 0; t < n_t; ++t) {
- const HVX_Vector x3 = *(const HVX_Vector *) (src0_T + (t + 3) * C_TILE);
-
- HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0),
- Q6_Vqf32_vmpy_VsfVsf(x1, w1));
- HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, w2),
- Q6_Vqf32_vmpy_VsfVsf(x3, w3));
-
- *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b));
-
- x0 = x1;
- x1 = x2;
- x2 = x3;
- }
- } else {
- for (uint32_t t = 0; t < n_t; ++t) {
- HVX_Vector acc = hvx_vec_splat_f32(0.0f);
- for (uint32_t j = 0; j < d_conv; ++j) {
- HVX_Vector x = *(const HVX_Vector *) (src0_T + (t + j) * C_TILE);
- HVX_Vector w = *(const HVX_Vector *) (wp + j * d_inner_stride);
- acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w));
- }
- *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(acc);
- }
- }
+ prefill_dot_fn(src0_T, wp, op, n_t, d_conv, d_inner_stride, dst_tile_stride);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off);
}
- if (apply_silu) {
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off);
- hvx_ssm_conv_silu_vtcm(out, n_t * (dst_tile_stride / C_TILE));
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off);
- }
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off);
+ const size_t dst_vtcm_stride_bytes = epilogue_fn(out, n_t, tile_n);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off);
// Writeback dst_tile VTCM -> DDR via 2D DMA
- dma_queue_push(dma_q, dma_make_data(dst->data + i3 * dst_stride_seq_bytes + (ir0 + tile_off) * sizeof(float), (uint8_t *) out),
- dst_stride_token_bytes, dst_tile_stride * sizeof(float), tile_n * sizeof(float), n_t);
+ dma_queue_push(dma_q, dma_make_data(dst->data + (i3 * dst_stride_seq_bytes + (size_t) (ir0 + tile_off) * dst_elem_size), (uint8_t *) out),
+ dst_stride_token_bytes, dst_vtcm_stride_bytes, (size_t) tile_n * dst_elem_size, n_t);
if (c + 2 < n_chunks) {
SSM_CONV_PUSH_FETCH(c + 2);
@@ -539,9 +1333,7 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
}
}
- for (uint32_t k = MIN(n_chunks, 2); k > 0; --k) {
- dma_queue_pop(dma_q); // drain the last writebacks
- }
+ dma_queue_flush(dma_q);
#undef SSM_CONV_PUSH_FETCH
@@ -551,10 +1343,176 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt
dst->ne[2], dst->ne[3]);
}
+// Fused token-major worker (n_t == 1 decode and n_t > 1 prefill)
+static void ssm_conv_thread_token_major(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_ssm_conv_context * scctx = (struct htp_ssm_conv_context *) data;
+ struct htp_ops_context * octx = scctx->octx;
+ const struct htp_ssm_conv_kernel_params * kparams = scctx->kparams;
+
+ const struct htp_tensor * restrict state = octx->src[0];
+ const struct htp_tensor * restrict weight = octx->src[1];
+ const struct htp_tensor * restrict x = octx->src[2];
+ const struct htp_tensor * restrict dst = octx->dsts[0];
+ const struct htp_tensor * restrict dst_state = octx->dsts[1];
+
+ dma_queue * dma_q = th->dma_q;
+
+ const uint32_t d_conv = kparams->d_conv;
+ const uint32_t s_taps = d_conv - 1;
+ const uint32_t n_t = kparams->n_t;
+ const uint32_t n_s = kparams->n_s;
+ const uint32_t n_t_tile = kparams->n_t_tile;
+ const bool state_f16 = (state->type == HTP_TYPE_F16);
+ const bool weight_f16 = (weight->type == HTP_TYPE_F16);
+ const bool x_f16 = (x->type == HTP_TYPE_F16);
+ const bool dst_f16 = (dst->type == HTP_TYPE_F16);
+ const bool dst_state_f16 = (dst_state && dst_state->type == HTP_TYPE_F16);
+
+ const htp_ssm_conv_token_step_fn_t token_step_fn = scctx->token_step_fn;
+ const htp_ssm_conv_state_unpack_fn_t state_unpack_fn = scctx->state_unpack_fn;
+ const htp_ssm_conv_state_pack_fn_t state_pack_fn = scctx->state_pack_fn;
+
+ const size_t state_elem_size = state_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t weight_elem_size = weight_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t x_elem_size = x_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_state_elem_size = dst_state_f16 ? sizeof(__fp16) : sizeof(float);
+
+ const uint32_t dr = scctx->nrows_per_hvx;
+ const uint32_t ir0 = scctx->row_start + dr * ith;
+ const uint32_t ir1 = MIN(ir0 + dr, scctx->row_start + scctx->nrows);
+
+ if (ir0 >= ir1) {
+ return;
+ }
+
+ const uint32_t d_inner_per_hvx = ir1 - ir0;
+ const uint32_t w_stride = hex_round_up(d_inner_per_hvx, 64);
+ const uint32_t d_inner_tile = scctx->d_inner_tile;
+ const uint32_t c_stride = hex_round_up(d_inner_tile, 64);
+
+ const size_t state_stride_seq_bytes = state->nb[2];
+ const size_t x_stride_token_bytes = x->nb[1];
+ const size_t x_stride_seq_bytes = x->nb[2];
+ const size_t dst_stride_token_bytes = dst->nb[1];
+ const size_t dst_stride_seq_bytes = dst->nb[2];
+ const size_t dst_state_stride_seq_bytes = dst_state ? dst_state->nb[1] : 0;
+
+ uint8_t * src1_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src1) + ith * scctx->layout.src1_bytes_per_hvx;
+ uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src0) + ith * scctx->layout.src0_bytes_per_hvx;
+ uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_dst) + ith * scctx->layout.dst_bytes_per_hvx;
+
+ const size_t weight_dma_bytes = (size_t) d_inner_per_hvx * d_conv * weight_elem_size;
+ const size_t weight_raw_size = hex_round_up((size_t) w_stride * d_conv * sizeof(float), 128) + 128;
+
+ float * src1_raw = (float *) src1_spad_base;
+ float * src1_T = (float *) (src1_spad_base + weight_raw_size);
+
+ const size_t x_row_stride = hex_round_up((size_t) c_stride * x_elem_size, 128);
+ const size_t x_tile_bytes = hex_round_up((size_t) n_t_tile * x_row_stride, 128);
+ const size_t state_raw_sz = hex_round_up((size_t) c_stride * s_taps * sizeof(float), 128) + 128;
+ const size_t d_row_stride = hex_round_up((size_t) c_stride * dst_elem_size, 128);
+ const size_t d_tile_bytes = hex_round_up((size_t) n_t_tile * d_row_stride, 128);
+
+ uint8_t * x_tile[2] = { src0_spad_base, src0_spad_base + x_tile_bytes };
+ float * state_raw = (float *) (src0_spad_base + 2 * x_tile_bytes);
+ float * hist = (float *) ((uint8_t *) state_raw + state_raw_sz);
+ uint8_t * d_tile[2] = { dst_spad_base, dst_spad_base + d_tile_bytes };
+ float * strip_f32 = (float *) (dst_spad_base + 2 * d_tile_bytes);
+
+ struct htp_thread_trace * tr = th->trace;
+
+ const dma_addr_t src1_ddr = weight->data + (size_t) ir0 * d_conv * weight_elem_size;
+ uint8_t * src1_dma_dest = weight_f16 ? (uint8_t *) src1_T : (uint8_t *) src1_raw;
+ dma_queue_push(dma_q, dma_make_data(src1_dma_dest, src1_ddr), weight_dma_bytes, weight_dma_bytes, weight_dma_bytes, 1);
+ dma_queue_pop(dma_q);
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0);
+ if (weight_f16) {
+ hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) src1_T, src1_raw, d_inner_per_hvx * d_conv);
+ }
+ hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, w_stride, d_conv);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0);
+
+ const uint32_t n_t_blocks = kparams->n_t_blocks;
+
+ for (uint32_t seq = 0; seq < n_s; ++seq) {
+ for (uint32_t tile_off = 0; tile_off < d_inner_per_hvx; tile_off += d_inner_tile) {
+ const uint32_t cur_c = MIN(d_inner_tile, d_inner_per_hvx - tile_off);
+ const size_t st_in_sz = (size_t) cur_c * s_taps * state_elem_size;
+ const dma_addr_t st_in_ddr = state->data + seq * state_stride_seq_bytes + (size_t) (ir0 + tile_off) * s_taps * state_elem_size;
+ const size_t x_width = (size_t) cur_c * x_elem_size;
+ const size_t d_width = (size_t) cur_c * dst_elem_size;
+ const dma_addr_t x_base = x->data + seq * x_stride_seq_bytes + (size_t) (ir0 + tile_off) * x_elem_size;
+ const dma_addr_t d_base = dst->data + seq * dst_stride_seq_bytes + (size_t) (ir0 + tile_off) * dst_elem_size;
+
+ uint8_t * st_in_vtcm = state_f16 ? (uint8_t *) hist : (uint8_t *) state_raw;
+ dma_queue_push(dma_q, dma_make_data(st_in_vtcm, st_in_ddr), st_in_sz, st_in_sz, st_in_sz, 1);
+
+ const uint32_t cur_t0 = MIN(n_t_tile, n_t);
+ dma_queue_push(dma_q, dma_make_data(dst->data, d_tile[0]), 0, 0, 0, 0);
+ dma_queue_push(dma_q, dma_make_data(x_tile[0], x_base), x_row_stride, x_stride_token_bytes, x_width, cur_t0);
+ if (n_t_blocks > 1) {
+ const uint32_t cur_t1 = MIN(n_t_tile, n_t - n_t_tile);
+ dma_queue_push(dma_q, dma_make_data(dst->data, d_tile[1]), 0, 0, 0, 0);
+ dma_queue_push(dma_q, dma_make_data(x_tile[1], x_base + (size_t) n_t_tile * x_stride_token_bytes),
+ x_row_stride, x_stride_token_bytes, x_width, cur_t1);
+ }
+
+ dma_queue_pop(dma_q); // state
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off);
+ state_unpack_fn(state_raw, hist, cur_c, c_stride, s_taps);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off);
+
+ const float * restrict wp = src1_T + tile_off;
+
+ for (uint32_t tb = 0; tb < n_t_blocks; ++tb) {
+ const uint32_t t0 = tb * n_t_tile;
+ const uint32_t cur_t = MIN(n_t_tile, n_t - t0);
+
+ dma_queue_pop(dma_q); // writeback of block tb-2
+ dma_queue_pop(dma_q); // fetch of block tb
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) t0);
+ token_step_fn(hist, x_tile[tb & 1], wp, d_tile[tb & 1], strip_f32,
+ cur_c, cur_t, d_conv, c_stride, w_stride, x_row_stride, d_row_stride);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) t0);
+
+ dma_queue_push(dma_q, dma_make_data(d_base + (size_t) t0 * dst_stride_token_bytes, d_tile[tb & 1]),
+ dst_stride_token_bytes, d_row_stride, d_width, cur_t);
+
+ if (tb + 2 < n_t_blocks) {
+ const uint32_t next_t0 = (tb + 2) * n_t_tile;
+ const uint32_t next_t = MIN(n_t_tile, n_t - next_t0);
+ dma_queue_push(dma_q, dma_make_data(x_tile[tb & 1], x_base + (size_t) next_t0 * x_stride_token_bytes),
+ x_row_stride, x_stride_token_bytes, x_width, next_t);
+ }
+ }
+
+ if (dst_state) {
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off);
+ state_pack_fn(hist, state_raw, cur_c, c_stride, s_taps);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off);
+
+ const size_t st_out_sz = (size_t) cur_c * s_taps * dst_state_elem_size;
+ const dma_addr_t st_out_ddr = dst_state->data + seq * dst_state_stride_seq_bytes + (size_t) (ir0 + tile_off) * s_taps * dst_state_elem_size;
+ uint8_t * st_out_vtcm = dst_state_f16 ? (uint8_t *) hist : (uint8_t *) state_raw;
+ dma_queue_push(dma_q, dma_make_data(st_out_ddr, st_out_vtcm), st_out_sz, st_out_sz, st_out_sz, 1);
+ }
+
+ dma_queue_flush(dma_q);
+ }
+ }
+
+ FARF(HIGH, "ssm-conv-token-major %d/%d: (%u:%u) d_conv=%u n_t=%u n_s=%u\n",
+ ith, nth, ir0, ir1, d_conv, n_t, n_s);
+}
+
int op_ssm_conv_f32(struct htp_ops_context * octx) {
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * src1 = octx->src[1];
- const struct htp_tensor * dst = octx->dst;
+ const struct htp_tensor * src0 = octx->src[0];
+ const struct htp_tensor * src2 = octx->src[2];
+ const struct htp_tensor * dst = octx->dsts[0];
+ const struct htp_tensor * dst_state = octx->dsts[1];
const struct htp_ssm_conv_kernel_params * kparams = (const struct htp_ssm_conv_kernel_params *) octx->kernel_params;
@@ -566,10 +1524,10 @@ int op_ssm_conv_f32(struct htp_ops_context * octx) {
uint32_t nrows = kparams->d_inner;
if (octx->ctx->mdev.count > 1) {
- const uint32_t elems_per_chunk = VLEN_FP32;
+ const uint32_t elems_per_chunk = (dst->type == HTP_TYPE_F16) ? VLEN_FP16 : VLEN_FP32;
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
kparams->d_inner,
- htp_tensor_mdev_data_aligned(dst) ? elems_per_chunk : 0,
+ elems_per_chunk,
octx->ctx->mdev.idx,
octx->ctx->mdev.count,
&octx->ctx->mdev.count_div
@@ -589,34 +1547,107 @@ int op_ssm_conv_f32(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
const uint32_t raw_rpt = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
const uint32_t d_inner_per_hvx = hex_round_up(raw_rpt, VLEN_FP32);
+ const size_t src0_elem_size = (src0->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
struct htp_ssm_conv_vtcm_layout L;
- htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, kparams->d_conv, kparams->n_t, kparams->d_inner_tile, n_hvx);
+ if (kparams->token_major) {
+ const size_t x_elem_size = (src2->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ htp_ssm_conv_token_vtcm_layout_build(&L, d_inner_per_hvx, kparams->d_conv, kparams->n_t_tile,
+ kparams->d_inner_tile, n_hvx, x_elem_size, dst_elem_size);
+ } else {
+ htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, kparams->d_conv, kparams->n_t,
+ kparams->d_inner_tile, n_hvx, src0_elem_size);
+ }
uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
- octx->src0_spad.size_per_hvx = L.src0_bytes_per_hvx;
- octx->src1_spad.size_per_hvx = L.src1_bytes_per_hvx;
- octx->dst_spad.size_per_hvx = L.dst_bytes_per_hvx;
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const bool dst_f16 = (dst->type == HTP_TYPE_F16);
+ const bool apply_silu = kparams->silu != 0;
+
+ if (kparams->token_major) {
+ const bool x_f16 = (src2->type == HTP_TYPE_F16);
+ const bool dst_st_f16 = (dst_state && dst_state->type == HTP_TYPE_F16);
+ const bool is_d4 = (kparams->d_conv == 4);
+
+ htp_ssm_conv_token_step_fn_t token_step_fn;
+ if (is_d4) {
+ if (x_f16 && dst_f16) {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f16_f16_silu : hvx_ssm_conv_token_4_f16_f16;
+ } else if (x_f16 && !dst_f16) {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f16_f32_silu : hvx_ssm_conv_token_4_f16_f32;
+ } else if (!x_f16 && dst_f16) {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f32_f16_silu : hvx_ssm_conv_token_4_f32_f16;
+ } else {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f32_f32_silu : hvx_ssm_conv_token_4_f32_f32;
+ }
+ } else {
+ if (x_f16 && dst_f16) {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f16_f16_silu : hvx_ssm_conv_token_gen_f16_f16;
+ } else if (x_f16 && !dst_f16) {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f16_f32_silu : hvx_ssm_conv_token_gen_f16_f32;
+ } else if (!x_f16 && dst_f16) {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f32_f16_silu : hvx_ssm_conv_token_gen_f32_f16;
+ } else {
+ token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f32_f32_silu : hvx_ssm_conv_token_gen_f32_f32;
+ }
+ }
- octx->src0_spad.size = L.src0_bytes;
- octx->src1_spad.size = L.src1_bytes;
- octx->dst_spad.size = L.dst_bytes;
+ const htp_ssm_conv_state_unpack_fn_t state_unpack_fn =
+ src0_f16 ? ssm_conv_state_unpack_f16_nat : ssm_conv_state_unpack_f32_nat;
+
+ const htp_ssm_conv_state_pack_fn_t state_pack_fn =
+ dst_st_f16 ? ssm_conv_state_pack_f16_nat : ssm_conv_state_pack_f32_nat;
+
+ struct htp_ssm_conv_context scctx = {
+ .octx = octx,
+ .kparams = kparams,
+ .layout = L,
+ .vtcm_base = base,
+ .nrows_per_hvx = d_inner_per_hvx,
+ .d_inner_tile = kparams->d_inner_tile,
+ .row_start = row_start,
+ .nrows = nrows,
+ .token_step_fn = token_step_fn,
+ .state_unpack_fn = state_unpack_fn,
+ .state_pack_fn = state_pack_fn,
+ };
+
+ work_queue_run(octx->ctx->hvx_queue, ssm_conv_thread_token_major, &scctx, n_hvx);
+ return HTP_STATUS_OK;
+ }
+
+ const bool raw_dot = (kparams->d_conv == 4) && (nrows % VLEN_FP32 == 0);
- octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0);
- octx->src1_spad.data = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src1);
- octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, base, L.off_dst);
- octx->src0_spad.src = NULL;
- octx->src1_spad.src = NULL;
- octx->dst_spad.src = NULL;
+ htp_ssm_conv_decode_dot_fn_t decode_dot_fn;
+ if (raw_dot) {
+ decode_dot_fn = src0_f16 ? ssm_conv_decode_dot_4_f16 : ssm_conv_decode_dot_4_f32;
+ } else {
+ decode_dot_fn = src0_f16 ? ssm_conv_decode_dot_gen_f16 : ssm_conv_decode_dot_gen_f32;
+ }
+
+ htp_ssm_conv_epilogue_fn_t epilogue_fn;
+ if (apply_silu) {
+ epilogue_fn = dst_f16 ? ssm_conv_epilogue_silu_f16 : ssm_conv_epilogue_silu_f32;
+ } else {
+ epilogue_fn = dst_f16 ? ssm_conv_epilogue_f16 : ssm_conv_epilogue_f32;
+ }
struct htp_ssm_conv_context scctx = {
- .octx = octx,
- .kparams = kparams,
- .nrows_per_hvx = d_inner_per_hvx,
- .d_inner_tile = kparams->d_inner_tile,
- .row_start = row_start,
- .nrows = nrows,
+ .octx = octx,
+ .kparams = kparams,
+ .layout = L,
+ .vtcm_base = base,
+ .nrows_per_hvx = d_inner_per_hvx,
+ .d_inner_tile = kparams->d_inner_tile,
+ .row_start = row_start,
+ .nrows = nrows,
+ .raw_dot = raw_dot,
+ .decode_dot_fn = decode_dot_fn,
+ .transpose_block_fn = src0_f16 ? hvx_ssm_conv_transpose_block_f16 : hvx_ssm_conv_transpose_block,
+ .prefill_dot_fn = (kparams->d_conv == 4) ? hvx_ssm_conv_prefill_dot_block_4 : hvx_ssm_conv_prefill_dot_block_gen,
+ .epilogue_fn = epilogue_fn,
};
FARF(HIGH, "ssm-conv-f32: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : mode %s\n",
@@ -639,6 +1670,7 @@ int op_ssm_conv(struct htp_ops_context * octx) {
switch (dst->type) {
case HTP_TYPE_F32:
+ case HTP_TYPE_F16:
return op_ssm_conv_f32(octx);
default:
return HTP_STATUS_NO_SUPPORT;
diff --git a/ggml/src/ggml-hexagon/htp/ssm-conv.h b/ggml/src/ggml-hexagon/htp/ssm-conv.h
index 7c3f3041f..97a49c59f 100644
--- a/ggml/src/ggml-hexagon/htp/ssm-conv.h
+++ b/ggml/src/ggml-hexagon/htp/ssm-conv.h
@@ -18,6 +18,9 @@ struct htp_ssm_conv_kernel_params {
uint32_t vtcm_size;
uint32_t silu;
+ uint32_t token_major;
+ uint32_t n_t_tile;
+ uint32_t n_t_blocks;
struct fastdiv_values div_d_inner_tile;
};
@@ -35,13 +38,21 @@ struct htp_ssm_conv_vtcm_layout {
size_t dst_bytes;
};
+static inline size_t htp_ssm_conv_raw_stride_bytes(uint32_t ncs, size_t src0_elem_size) {
+ if (src0_elem_size == 2) {
+ return (size_t) hex_round_up(ncs, 2) * 2 + sizeof(float);
+ }
+ return (size_t) ncs * sizeof(float) + sizeof(float);
+}
+
static inline void htp_ssm_conv_vtcm_layout_build(
struct htp_ssm_conv_vtcm_layout * L,
uint32_t d_inner_per_hvx,
uint32_t d_conv,
uint32_t n_t,
uint32_t d_inner_tile,
- uint32_t n_hvx
+ uint32_t n_hvx,
+ size_t src0_elem_size
) {
const size_t src1_raw_bytes = hex_round_up((size_t) d_inner_per_hvx * d_conv * sizeof(float), 128) + 128;
const size_t src1_T_bytes = hex_round_up((size_t) d_conv * d_inner_per_hvx * sizeof(float), 128);
@@ -49,13 +60,14 @@ static inline void htp_ssm_conv_vtcm_layout_build(
L->src1_bytes_per_hvx = src1_raw_bytes + src1_T_bytes;
if (n_t == 1) {
- const size_t src0_tile_raw_bytes = hex_round_up((size_t) d_inner_tile * d_conv * sizeof(float), 128);
+ const size_t raw_stride_bytes = (src0_elem_size == 2) ? ((size_t) hex_round_up(d_conv, 2) * 2) : ((size_t) d_conv * sizeof(float));
+ const size_t src0_tile_raw_bytes = hex_round_up((size_t) d_inner_tile * raw_stride_bytes, 128);
const size_t src0_T_bytes = hex_round_up((size_t) d_conv * d_inner_tile * sizeof(float), 128);
L->src0_bytes_per_hvx = 2 * src0_tile_raw_bytes + src0_T_bytes;
L->dst_bytes_per_hvx = 2 * hex_round_up((size_t) d_inner_tile * sizeof(float), 128);
} else {
const uint32_t ncs = d_conv - 1 + n_t;
- const size_t raw_stride_bytes = ncs * sizeof(float) + sizeof(float);
+ const size_t raw_stride_bytes = htp_ssm_conv_raw_stride_bytes(ncs, src0_elem_size);
const size_t src0_block_T = hex_round_up((size_t) ncs * 32 * sizeof(float), 128);
const size_t src0_tile_raw = hex_round_up((size_t) d_inner_tile * raw_stride_bytes, 128);
L->src0_bytes_per_hvx = 2 * src0_tile_raw + src0_block_T;
@@ -73,6 +85,43 @@ static inline void htp_ssm_conv_vtcm_layout_build(
L->total_bytes = off;
}
+static inline void htp_ssm_conv_token_vtcm_layout_build(
+ struct htp_ssm_conv_vtcm_layout * L,
+ uint32_t d_inner_per_hvx,
+ uint32_t d_conv,
+ uint32_t n_t_tile,
+ uint32_t d_inner_tile,
+ uint32_t n_hvx,
+ size_t x_elem_size,
+ size_t dst_elem_size
+) {
+ const uint32_t w_stride = hex_round_up(d_inner_per_hvx, 64);
+ const uint32_t c_stride = hex_round_up(d_inner_tile, 64);
+ const size_t src1_raw = hex_round_up((size_t) w_stride * d_conv * sizeof(float), 128) + 128;
+ const size_t src1_T = hex_round_up((size_t) d_conv * w_stride * sizeof(float), 128);
+ const size_t x_row_stride = hex_round_up((size_t) c_stride * x_elem_size, 128);
+ const size_t x_tile_bytes = hex_round_up((size_t) n_t_tile * x_row_stride, 128);
+ const size_t state_raw = hex_round_up((size_t) c_stride * (d_conv - 1) * sizeof(float), 128) + 128;
+ const size_t hist_bytes = hex_round_up((size_t) (d_conv - 1) * c_stride * sizeof(float), 128);
+ const size_t d_row_stride = hex_round_up((size_t) c_stride * dst_elem_size, 128);
+ const size_t d_tile_bytes = hex_round_up((size_t) n_t_tile * d_row_stride, 128);
+ const size_t strip_bytes = hex_round_up((size_t) n_t_tile * 64 * sizeof(float), 128);
+
+ L->src1_bytes_per_hvx = (src1_raw + src1_T) | 128;
+ L->src0_bytes_per_hvx = (2 * x_tile_bytes + state_raw + hist_bytes) | 128;
+ L->dst_bytes_per_hvx = (2 * d_tile_bytes + strip_bytes) | 128;
+
+ L->src0_bytes = L->src0_bytes_per_hvx * n_hvx;
+ L->src1_bytes = L->src1_bytes_per_hvx * n_hvx;
+ L->dst_bytes = L->dst_bytes_per_hvx * n_hvx;
+
+ size_t off = 0;
+ VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes);
+ VTCM_LAYOUT_ALLOC(off, off_src1, L->src1_bytes);
+ VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes);
+ L->total_bytes = off;
+}
+
#if defined(__cplusplus)
static_assert(sizeof(struct htp_ssm_conv_kernel_params) <= 128, "htp_ssm_conv_kernel_params is too large for kernel_params blob");
#else
diff --git a/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c b/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c
index 6ba2d4112..65892572c 100644
--- a/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c
+++ b/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c
@@ -1,4 +1,5 @@
#include <math.h>
+#include <stdlib.h>
#include <string.h>
#include "hvx-exp.h"
@@ -44,6 +45,7 @@ struct htp_ssm_scan_context {
struct htp_ops_context * octx;
const struct htp_ssm_scan_kernel_params * kparams;
struct htp_ssm_scan_vtcm_layout layout;
+ const int32_t * ids_data;
uint32_t unit_start;
uint32_t nunits;
uint32_t units_per_hvx;
@@ -355,8 +357,7 @@ static inline void ssm_scan_decode_push_inputs(
const struct htp_tensor * A = octx->src[3];
const struct htp_tensor * B = octx->src[4];
const struct htp_tensor * C = octx->src[5];
- const struct htp_tensor * ids = octx->src[6];
- const int32_t id = ((const int32_t *) (uintptr_t) ids->data)[unit->q];
+ const int32_t id = scctx->ids_data[unit->q];
const size_t state_row_bytes = (size_t) kparams->d_state * sizeof(float);
const size_t state_row_stride = layout->state_row_stride;
const size_t x_bytes = (size_t) unit->nrows * sizeof(float);
@@ -498,7 +499,6 @@ static inline void ssm_scan_prefill_push_fetch(
const struct htp_tensor * A = octx->src[3];
const struct htp_tensor * B = octx->src[4];
const struct htp_tensor * C = octx->src[5];
- const struct htp_tensor * ids = octx->src[6];
const struct htp_ssm_scan_unit unit = ssm_scan_decode_unit(kparams, unit_index);
const uint32_t t0 = c * kparams->token_tile;
const uint32_t nt = MIN(kparams->token_tile, kparams->n_tokens - t0);
@@ -508,7 +508,7 @@ static inline void ssm_scan_prefill_push_fetch(
const size_t row_bytes = (size_t) unit.nrows * sizeof(float);
if (c == 0) {
- const int32_t id = ((const int32_t *) (uintptr_t) ids->data)[unit.q];
+ const int32_t id = scctx->ids_data[unit.q];
const size_t a_bytes = (size_t) kparams->n_a * sizeof(float);
const dma_addr_t state_in = s->data + (size_t) id * s->nb[3] + (size_t) unit.head * s->nb[2] + (size_t) unit.row0 * s->nb[1];
const dma_addr_t A_in = A->data + (size_t) unit.head * A->nb[1];
@@ -1484,17 +1484,31 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) {
const struct htp_ssm_scan_kernel_params * kparams =
(const struct htp_ssm_scan_kernel_params *) octx->kernel_params;
- if (htp_tensor_is_extended(ids)) {
- return HTP_STATUS_NO_SUPPORT;
+ const size_t ids_bytes = hex_round_up(htp_tensor_nbytes(ids), 128);
+ void * ids_buf = (ids_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, ids_bytes);
+ if (!ids_buf) {
+ return HTP_STATUS_INTERNAL_ERR;
+ }
+ if (htp_tensor_read(&octx->ctx->main_th, ids_buf, ids_bytes, ids) == 0) {
+ if (ids_buf != octx->ctx->ddr_spad_base) {
+ free(ids_buf);
+ }
+ return HTP_STATUS_INTERNAL_ERR;
}
- const int32_t * ids_data = (const int32_t *) ids->data;
+ const int32_t * ids_data = (const int32_t *) ids_buf;
for (uint32_t q = 0; q < kparams->n_seqs; ++q) {
if (ids_data[q] < 0 || (uint32_t) ids_data[q] >= s->ne[3]) {
+ if (ids_buf != octx->ctx->ddr_spad_base) {
+ free(ids_buf);
+ }
return HTP_STATUS_INVAL_PARAMS;
}
}
if (octx->flags & HTP_OPFLAGS_STUB) {
+ if (ids_buf != octx->ctx->ddr_spad_base) {
+ free(ids_buf);
+ }
return HTP_STATUS_OK;
}
@@ -1509,6 +1523,9 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) {
}
if (nunits == 0) {
+ if (ids_buf != octx->ctx->ddr_spad_base) {
+ free(ids_buf);
+ }
return HTP_STATUS_OK;
}
@@ -1520,6 +1537,7 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) {
struct htp_ssm_scan_context scctx = {
.octx = octx,
.kparams = kparams,
+ .ids_data = ids_data,
.unit_start = unit_start,
.nunits = nunits,
.units_per_hvx = units_per_hvx,
@@ -1530,29 +1548,35 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) {
kparams->kernel_type == HTP_SSM_SCAN_KERNEL_HMX
);
- octx->n_hvx = n_hvx;
- octx->src0_spad.data = octx->ctx->vtcm_base;
- octx->src0_spad.size_per_hvx = kparams->vtcm_per_hvx;
- octx->src0_spad.size = kparams->vtcm_size;
+ octx->n_hvx = n_hvx;
+ int status = HTP_STATUS_OK;
switch (kparams->kernel_type) {
case HTP_SSM_SCAN_KERNEL_HVX_DECODE:
work_queue_run(octx->ctx->hvx_queue, ssm_scan_thread_f32_decode, &scctx, n_hvx);
+ status = octx->status;
break;
case HTP_SSM_SCAN_KERNEL_HVX_PREFILL:
work_queue_run(octx->ctx->hvx_queue, ssm_scan_thread_f32_prefill, &scctx, n_hvx);
+ status = octx->status;
break;
case HTP_SSM_SCAN_KERNEL_HMX:
ssm_scan_run_hmx_chunked(&scctx);
+ status = octx->status;
break;
default:
- return HTP_STATUS_NO_SUPPORT;
+ status = HTP_STATUS_NO_SUPPORT;
+ break;
+ }
+
+ if (ids_buf != octx->ctx->ddr_spad_base) {
+ free(ids_buf);
}
- return octx->status;
+ return status;
}
int op_ssm_scan(struct htp_ops_context * octx) {
diff --git a/ggml/src/ggml-hexagon/htp/sum-rows-ops.c b/ggml/src/ggml-hexagon/htp/sum-rows-ops.c
index b3f8a7090..c226c1cea 100644
--- a/ggml/src/ggml-hexagon/htp/sum-rows-ops.c
+++ b/ggml/src/ggml-hexagon/htp/sum-rows-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -9,6 +5,7 @@
#include <math.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hvx-utils.h"
#define GGML_COMMON_DECL_C
@@ -20,89 +17,329 @@
#include "htp-tensor.h"
#include "sum-rows-ops.h"
-#define sum_rows_preamble \
- const struct htp_tensor *src0 = octx->src[0]; \
- const struct htp_tensor *dst = octx->dst; \
- \
- const uint32_t ne00 = src0->ne[0]; \
- const uint32_t ne01 = src0->ne[1]; \
- const uint32_t ne02 = src0->ne[2]; \
- const uint32_t ne03 = src0->ne[3]; \
- \
- const uint32_t nb00 = src0->nb[0]; \
- const uint32_t nb01 = src0->nb[1]; \
- const uint32_t nb02 = src0->nb[2]; \
- const uint32_t nb03 = src0->nb[3]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb0 = dst->nb[0]; \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3]; \
+#define sum_rows_preamble \
+ const struct htp_tensor *src0 = octx->src[0]; \
+ const struct htp_tensor *dst = octx->dst; \
+ \
+ 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)) 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)) 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)) 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]; \
+
+typedef void (*sum_rows_compute_fn_t)(
+ const uint8_t * restrict src,
+ uint8_t * restrict dst,
+ uint32_t ne00,
+ uint32_t nrows,
+ size_t src_row_stride
+);
struct sum_rows_context {
- struct htp_ops_context * octx;
- const uint8_t * src_data;
- uint8_t * dst_data;
- uint32_t ne00;
- size_t src_stride;
- size_t dst_stride;
- uint32_t rows_per_hvx;
- uint32_t total_rows;
+ struct htp_ops_context * octx;
+ const struct htp_sum_rows_kernel_params * kparams;
+ sum_rows_compute_fn_t compute;
+ dma_addr_t data_src0;
+ dma_addr_t data_dst;
+ uint8_t * vtcm_src0;
+ uint8_t * vtcm_dst;
+ size_t src0_data_row_size;
+ size_t src0_row_size_aligned;
+ size_t src0_vtcm_half_size;
+ size_t dst_vtcm_half_size;
+ size_t vtcm_src0_size_per_hvx;
+ size_t vtcm_dst_size_per_hvx;
+ size_t dst_elem_size;
+ uint32_t row_start;
+ uint32_t src0_nrows;
+ uint32_t src0_nrows_per_hvx;
+ uint32_t block;
};
-static void sum_rows_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void *data) {
- const struct sum_rows_context * smctx = (const struct sum_rows_context *) data;
+static inline size_t sum_rows_row_offset(
+ uint32_t ir,
+ uint32_t ne1,
+ uint32_t ne2,
+ const struct fastdiv_values * div_ne1,
+ const struct fastdiv_values * div_ne2,
+ const struct fastdiv_values * div_ne12,
+ size_t nb1,
+ size_t nb2,
+ size_t nb3
+) {
+ const uint32_t i1 = fastmodulo(ir, ne1, div_ne1);
+ const uint32_t ir_div_ne1 = fastdiv(ir, div_ne1);
+ const uint32_t i2 = fastmodulo(ir_div_ne1, ne2, div_ne2);
+ const uint32_t i3 = fastdiv(ir, div_ne12);
+ return (size_t) i1 * nb1 + (size_t) i2 * nb2 + (size_t) i3 * nb3;
+}
- const uint32_t rows_per_hvx = smctx->rows_per_hvx;
- const uint32_t total_rows = smctx->total_rows;
+static inline uint32_t sum_rows_block_size(
+ uint32_t ir,
+ uint32_t end_row,
+ uint32_t block,
+ bool contig,
+ uint32_t ne1,
+ const struct fastdiv_values * div_ne1
+) {
+ uint32_t limit = MIN(block, end_row - ir);
+ if (!contig) {
+ const uint32_t slice_end = (fastdiv(ir, div_ne1) + 1) * ne1;
+ limit = MIN(limit, slice_end - ir);
+ }
+ return limit;
+}
- const uint32_t start_row = rows_per_hvx * ith;
- const uint32_t end_row = MIN(start_row + rows_per_hvx, total_rows);
+static inline HVX_Vector hvx_vec_clamp_f16_f32(HVX_Vector v_sf) {
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ return Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sf));
+}
- if (start_row >= end_row) {
- return;
+static inline HVX_Vector hvx_row_reduce_sum_f32(const uint8_t * restrict src, uint32_t num_elems) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+
+ const uint32_t nvec = num_elems / VLEN_FP32;
+ const uint32_t nloe = num_elems % VLEN_FP32;
+
+ HVX_Vector acc = Q6_V_vzero();
+ uint32_t i = 0;
+
+ #pragma unroll(4)
+ for (; i < nvec; i++) {
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, vsrc[i]);
+ }
+ if (nloe) {
+ const HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(float));
+ const HVX_Vector v = Q6_V_vand_QV(bmask, vsrc[i]);
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, v);
}
- const size_t src_stride = smctx->src_stride;
- const size_t dst_stride = smctx->dst_stride;
- const uint32_t ne00 = smctx->ne00;
+ return Q6_Vsf_equals_Vqf32(hvx_vec_reduce_sum_qf32(acc));
+}
+
+static inline HVX_Vector hvx_row_reduce_sum_f16(const uint8_t * restrict src, uint32_t num_elems) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
- const float * restrict src_th = (const float *) (smctx->src_data + (start_row * src_stride));
- float * restrict dst_th = (float *) (smctx->dst_data + (start_row * dst_stride));
+ const uint32_t nvec = num_elems / VLEN_FP16;
+ const uint32_t nloe = num_elems % VLEN_FP16;
- // Calculate actual number of rows for this thread
- const uint32_t n_rows = end_row - start_row;
+ HVX_Vector acc = Q6_V_vzero();
+ uint32_t i = 0;
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_row);
+ #pragma unroll(2)
+ for (; i < nvec; i++) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(vsrc[i]);
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_lo_W(p));
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_hi_W(p));
+ }
+ if (nloe) {
+ const HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(__fp16));
+ const HVX_Vector v = Q6_V_vand_QV(bmask, vsrc[i]);
+ const HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v);
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_lo_W(p));
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_hi_W(p));
+ }
- for (uint32_t ir = 0; ir < n_rows; ir++) {
- const float * restrict src_local = (const float *) ((const uint8_t *) src_th + ir * src_stride);
- float * restrict dst_local = (float *) ((uint8_t *) dst_th + ir * dst_stride);
+ return Q6_Vsf_equals_Vqf32(hvx_vec_reduce_sum_qf32(acc));
+}
- if (ir + 1 < n_rows) {
- hex_l2fetch((const uint8_t *) src_local + src_stride, src_stride, src_stride, 1);
- }
+static void __attribute__((noinline)) sum_rows_block_f32_f32(
+ const uint8_t * restrict src,
+ uint8_t * restrict dst,
+ const uint32_t ne00,
+ const uint32_t nrows,
+ const size_t src_row_stride
+) {
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ for (uint32_t b = 0; b < nrows; ++b) {
+ const HVX_Vector sum_sf = hvx_row_reduce_sum_f32(src + b * src_row_stride, ne00);
+ const uint32_t b_off = (b & 31u) * sizeof(float);
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(float));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 5], sum_sf);
+ }
+}
- *dst_local = hvx_reduce_sum_f32((const uint8_t *) src_local, ne00);
+static void __attribute__((noinline)) sum_rows_block_f32_f16(
+ const uint8_t * restrict src,
+ uint8_t * restrict dst,
+ const uint32_t ne00,
+ const uint32_t nrows,
+ const size_t src_row_stride
+) {
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ for (uint32_t b = 0; b < nrows; ++b) {
+ const HVX_Vector sum_sf = hvx_vec_clamp_f16_f32(hvx_row_reduce_sum_f32(src + b * src_row_stride, ne00));
+ const HVX_Vector sum_hf = hvx_vec_f32_to_f16_shuff(sum_sf, sum_sf);
+ const uint32_t b_off = (b & 63u) * sizeof(__fp16);
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(__fp16));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 6], sum_hf);
}
+}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_row);
+static void __attribute__((noinline)) sum_rows_block_f16_f32(
+ const uint8_t * restrict src,
+ uint8_t * restrict dst,
+ const uint32_t ne00,
+ const uint32_t nrows,
+ const size_t src_row_stride
+) {
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ for (uint32_t b = 0; b < nrows; ++b) {
+ const HVX_Vector sum_sf = hvx_row_reduce_sum_f16(src + b * src_row_stride, ne00);
+ const uint32_t b_off = (b & 31u) * sizeof(float);
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(float));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 5], sum_sf);
+ }
}
-int op_sum_rows(struct htp_ops_context * octx) {
+static void __attribute__((noinline)) sum_rows_block_f16_f16(
+ const uint8_t * restrict src,
+ uint8_t * restrict dst,
+ const uint32_t ne00,
+ const uint32_t nrows,
+ const size_t src_row_stride
+) {
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ for (uint32_t b = 0; b < nrows; ++b) {
+ const HVX_Vector sum_sf = hvx_vec_clamp_f16_f32(hvx_row_reduce_sum_f16(src + b * src_row_stride, ne00));
+ const HVX_Vector sum_hf = hvx_vec_f32_to_f16_shuff(sum_sf, sum_sf);
+ const uint32_t b_off = (b & 63u) * sizeof(__fp16);
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(__fp16));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 6], sum_hf);
+ }
+}
+
+struct sum_rows_pipe_state {
+ dma_addr_t data_src;
+ dma_addr_t data_dst;
+ sum_rows_compute_fn_t compute;
+ size_t src0_data_row_size;
+ size_t src0_row_size_aligned;
+ size_t dst_elem_size;
+ uint32_t ne00;
+ uint32_t ne01;
+ uint32_t ne02;
+ uint32_t nb01;
+ uint32_t nb02;
+ uint32_t nb03;
+ uint32_t block;
+ bool src0_contig;
+ const struct fastdiv_values * div_ne01;
+ const struct fastdiv_values * div_ne02;
+ const struct fastdiv_values * div_ne012;
+ uint32_t ir;
+ uint32_t ir_end;
+};
+
+static bool sum_rows_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx;
+ if (s->ir >= s->ir_end) {
+ return false;
+ }
+ const uint32_t block_size = sum_rows_block_size(s->ir, s->ir_end, s->block, s->src0_contig, s->ne01, s->div_ne01);
+ task->row = s->ir;
+ task->off = 0;
+ task->len = block_size;
+ task->aux = 0;
+ s->ir += block_size;
+ return true;
+}
+
+static void sum_rows_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx;
+ const size_t src0_off = s->src0_contig ? ((size_t) task->row * s->nb01) :
+ sum_rows_row_offset(task->row, s->ne01, s->ne02, s->div_ne01, s->div_ne02, s->div_ne012, s->nb01, s->nb02, s->nb03);
+ dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src + src0_off),
+ s->src0_row_size_aligned, s->nb01, s->src0_data_row_size, task->len);
+}
+
+static void sum_rows_pipe_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx;
+ s->compute((const uint8_t *) in_spad, (uint8_t *) out_spad, s->ne00, task->len, s->src0_row_size_aligned);
+}
+
+static void sum_rows_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx;
+ const size_t dst_off = (size_t) task->row * s->dst_elem_size;
+ const size_t dst_bytes = (size_t) task->len * s->dst_elem_size;
+ dma_queue_push(dma_q, dma_make_data(s->data_dst + dst_off, out_spad),
+ dst_bytes, dst_bytes, dst_bytes, 1);
+}
+
+static void sum_rows_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct sum_rows_context * smctx = (const struct sum_rows_context *) data;
+ struct htp_ops_context * octx = smctx->octx;
+
sum_rows_preamble;
- if (octx->src[0]->type != HTP_TYPE_F32) {
- return HTP_STATUS_NO_SUPPORT;
+ const uint32_t src0_nrows_per_hvx = smctx->src0_nrows_per_hvx;
+ const uint32_t src0_nrows = smctx->src0_nrows;
+ const uint32_t src0_start_row = smctx->row_start + src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, smctx->row_start + src0_nrows);
+
+ if (src0_start_row >= src0_end_row) {
+ return;
}
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) {
+ uint8_t * src0_vtcm_data = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx);
+ uint8_t * dst_vtcm_data = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + smctx->src0_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + smctx->dst_vtcm_half_size };
+
+ struct sum_rows_pipe_state s = {
+ .data_src = smctx->data_src0,
+ .data_dst = smctx->data_dst,
+ .compute = smctx->compute,
+ .src0_data_row_size = smctx->src0_data_row_size,
+ .src0_row_size_aligned = smctx->src0_row_size_aligned,
+ .dst_elem_size = smctx->dst_elem_size,
+ .ne00 = ne00,
+ .ne01 = ne01,
+ .ne02 = ne02,
+ .nb01 = nb01,
+ .nb02 = nb02,
+ .nb03 = nb03,
+ .block = smctx->block,
+ .src0_contig = smctx->kparams->src0_contig,
+ .div_ne01 = &smctx->kparams->div_ne01,
+ .div_ne02 = &smctx->kparams->div_ne02,
+ .div_ne012 = &smctx->kparams->div_ne012,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ sum_rows_next_task, sum_rows_push_in, sum_rows_pipe_compute, sum_rows_push_out);
+}
+
+int op_sum_rows(struct htp_ops_context * octx) {
+ sum_rows_preamble;
+
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const bool dst_f16 = (dst->type == HTP_TYPE_F16);
+
+ if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) ||
+ (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) {
return HTP_STATUS_NO_SUPPORT;
}
@@ -113,16 +350,17 @@ int op_sum_rows(struct htp_ops_context * octx) {
return HTP_STATUS_INVAL_PARAMS;
}
- const uint32_t src0_nrows = ne01 * ne02 * ne03;
- const size_t dst_data_row_size = dst->ne[0] * sizeof(float);
+ const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t src0_data_row_size = (size_t) ne00 * src0_elem_size;
+ const uint32_t src0_nrows = ne01 * ne02 * ne03;
uint32_t row_start = 0;
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_data_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -134,31 +372,133 @@ int op_sum_rows(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
const uint32_t rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
+ struct htp_sum_rows_vtcm_layout layout;
+ htp_sum_rows_vtcm_layout_build(&layout, src0_data_row_size, dst_elem_size, kparams->block, n_hvx);
+
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "sum_rows: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ sum_rows_compute_fn_t compute = NULL;
+ if (!src0_f16 && !dst_f16) {
+ compute = sum_rows_block_f32_f32;
+ } else if (!src0_f16 && dst_f16) {
+ compute = sum_rows_block_f32_f16;
+ } else if (src0_f16 && !dst_f16) {
+ compute = sum_rows_block_f16_f32;
+ } else {
+ compute = sum_rows_block_f16_f16;
+ }
+
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
+
struct sum_rows_context smctx = {
- .octx = octx,
- .src_data = (const uint8_t *) src0->data + row_start * nb01,
- .dst_data = (uint8_t *) dst->data + row_start * nb1,
- .ne00 = ne00,
- .src_stride = nb01,
- .dst_stride = nb1,
- .rows_per_hvx = rows_per_hvx,
- .total_rows = nrows,
+ .octx = octx,
+ .kparams = kparams,
+ .compute = compute,
+ .data_src0 = (dma_addr_t) src0->data,
+ .data_dst = (dma_addr_t) dst->data,
+ .vtcm_src0 = vtcm_base + layout.src0_off,
+ .vtcm_dst = vtcm_base + layout.dst_off,
+ .src0_data_row_size = src0_data_row_size,
+ .src0_row_size_aligned = layout.src0_row_size_aligned,
+ .src0_vtcm_half_size = layout.src0_half_bytes,
+ .dst_vtcm_half_size = layout.dst_half_bytes,
+ .vtcm_src0_size_per_hvx = layout.src0_bytes_per_hvx,
+ .vtcm_dst_size_per_hvx = layout.dst_bytes_per_hvx,
+ .dst_elem_size = dst_elem_size,
+ .row_start = row_start,
+ .src0_nrows = nrows,
+ .src0_nrows_per_hvx = rows_per_hvx,
+ .block = kparams->block,
};
- work_queue_run(octx->ctx->hvx_queue, sum_rows_thread_f32, &smctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, sum_rows_thread, &smctx, n_hvx);
return HTP_STATUS_OK;
}
+static float __attribute__((noinline)) hvx_sum_chunk_f32(const uint8_t * restrict src, uint32_t num_elems) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+
+ const uint32_t nvec = num_elems / VLEN_FP32;
+ const uint32_t nloe = num_elems % VLEN_FP32;
+
+ HVX_Vector acc = Q6_V_vzero();
+ uint32_t i = 0;
+ #pragma unroll(4)
+ for (; i < nvec; i++) {
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, vsrc[i]);
+ }
+ if (nloe) {
+ const HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(float));
+ const HVX_Vector v = Q6_V_vand_QV(bmask, vsrc[i]);
+ acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, v);
+ }
+
+ return hvx_vec_get_f32(Q6_Vsf_equals_Vqf32(hvx_vec_reduce_sum_qf32(acc)));
+}
+
+static float __attribute__((noinline)) hvx_sum_chunk_f16(const uint8_t * restrict src, uint32_t num_elems) {
+ return hvx_vec_get_f32(hvx_row_reduce_sum_f16(src, num_elems));
+}
+
+typedef float (*sum_chunk_fn_t)(const uint8_t * restrict src, uint32_t num_elems);
+
struct sum_context {
struct htp_ops_context * octx;
- const float * src_data;
+ sum_chunk_fn_t sum_chunk;
+ dma_addr_t data_src0;
+ uint8_t * vtcm_src0;
+ size_t src0_elem_size;
+ size_t chunk_bytes;
+ size_t src0_bytes_per_hvx;
float partial_sums[HTP_MAX_NHVX];
uint32_t total_elems;
uint32_t elems_per_hvx;
+ uint32_t chunk_elems;
};
-static void sum_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+struct sum_pipe_state {
+ dma_addr_t data_src;
+ sum_chunk_fn_t sum_chunk;
+ size_t src0_elem_size;
+ size_t chunk_bytes;
+ uint32_t chunk_elems;
+ uint32_t pos;
+ uint32_t end;
+ float sum;
+};
+
+static bool sum_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct sum_pipe_state * s = (struct sum_pipe_state *) ctx;
+ if (s->pos >= s->end) {
+ return false;
+ }
+ const uint32_t cnt = MIN(s->chunk_elems, s->end - s->pos);
+ task->row = s->pos;
+ task->off = 0;
+ task->len = cnt;
+ task->aux = 0;
+ s->pos += cnt;
+ return true;
+}
+
+static void sum_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct sum_pipe_state * s = (struct sum_pipe_state *) ctx;
+ const size_t nb = (size_t) task->len * s->src0_elem_size;
+ dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src + (size_t) task->row * s->src0_elem_size),
+ s->chunk_bytes, nb, nb, 1);
+}
+
+static void sum_pipe_compute(void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct sum_pipe_state * s = (struct sum_pipe_state *) ctx;
+ s->sum += s->sum_chunk((const uint8_t *) in_spad, task->len);
+}
+
+static void sum_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct sum_context * sctx = (struct sum_context *) data;
const uint32_t start = sctx->elems_per_hvx * ith;
const uint32_t end = MIN(start + sctx->elems_per_hvx, sctx->total_elems);
@@ -168,28 +508,31 @@ static void sum_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned i
return;
}
- const uint32_t n = end - start;
- const float * src = sctx->src_data + start;
-
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start);
-
- hex_l2fetch_block((const void *) src, n * sizeof(float));
+ uint8_t * vtcm_src = sctx->vtcm_src0 + ith * sctx->src0_bytes_per_hvx;
+ void * in_buf[2] = { vtcm_src, vtcm_src + sctx->chunk_bytes };
+
+ struct sum_pipe_state s = {
+ .data_src = sctx->data_src0,
+ .sum_chunk = sctx->sum_chunk,
+ .src0_elem_size = sctx->src0_elem_size,
+ .chunk_bytes = sctx->chunk_bytes,
+ .chunk_elems = sctx->chunk_elems,
+ .pos = start,
+ .end = end,
+ .sum = 0.0f,
+ };
- sctx->partial_sums[ith] = hvx_reduce_sum_f32((const uint8_t *) src, n);
+ dma_pipe_in_run(th->dma_q, th->trace, &s, in_buf, sum_next_task, sum_push_in, sum_pipe_compute);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start);
+ sctx->partial_sums[ith] = s.sum;
}
int op_sum(struct htp_ops_context * octx) {
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- if (src0->type != HTP_TYPE_F32) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) {
+ if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) ||
+ (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) {
return HTP_STATUS_NO_SUPPORT;
}
@@ -204,47 +547,228 @@ int op_sum(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const bool dst_f16 = (dst->type == HTP_TYPE_F16);
+ const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float);
+ const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float);
+ const uint32_t n_hvx = octx->n_hvx;
+
+ struct htp_sum_vtcm_layout layout;
+ htp_sum_vtcm_layout_build(&layout, kparams->chunk_elems, src0_elem_size, n_hvx);
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "sum: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
+ uint8_t * vtcm_dst = vtcm_base + layout.dst_off;
+
const uint32_t total_elems = (uint32_t) (src0->ne[0] * src0->ne[1] * src0->ne[2] * src0->ne[3]);
if (total_elems == 0) {
- ((float *) dst->data)[0] = 0.0f;
+ hvx_vmem(vtcm_dst) = Q6_V_vzero();
+ dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, dst_elem_size);
return HTP_STATUS_OK;
}
- const uint32_t n_hvx = octx->n_hvx;
- const uint32_t elems_per_hvx = kparams->elems_per_hvx;
-
struct sum_context sctx = {
- .octx = octx,
- .src_data = (const float *) src0->data,
- .total_elems = total_elems,
- .elems_per_hvx = elems_per_hvx,
+ .octx = octx,
+ .sum_chunk = src0_f16 ? hvx_sum_chunk_f16 : hvx_sum_chunk_f32,
+ .data_src0 = (dma_addr_t) src0->data,
+ .vtcm_src0 = vtcm_base + layout.src0_off,
+ .src0_elem_size = src0_elem_size,
+ .chunk_bytes = layout.chunk_bytes,
+ .src0_bytes_per_hvx = layout.src0_bytes_per_hvx,
+ .total_elems = total_elems,
+ .elems_per_hvx = kparams->elems_per_hvx,
+ .chunk_elems = kparams->chunk_elems,
};
- work_queue_run(octx->ctx->hvx_queue, sum_thread_f32, &sctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, sum_thread, &sctx, n_hvx);
float sum = 0.0f;
for (uint32_t i = 0; i < n_hvx; i++) {
sum += sctx.partial_sums[i];
}
- ((float *) dst->data)[0] = sum;
+
+ if (dst_f16) {
+ const HVX_Vector sum_sf = hvx_vec_clamp_f16_f32(hvx_vec_splat_f32(sum));
+ hvx_vmem(vtcm_dst) = hvx_vec_f32_to_f16_shuff(sum_sf, sum_sf);
+ } else {
+ hvx_vmem(vtcm_dst) = hvx_vec_splat_f32(sum);
+ }
+ dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, dst_elem_size);
return HTP_STATUS_OK;
}
-static inline void argmax_slice_f32(
- const float * restrict src,
- uint32_t n,
- uint32_t offset,
- float * out_val,
- int32_t * out_idx
+static void __attribute__((noinline)) hvx_argmax_chunk_f32(
+ const uint8_t * restrict src,
+ uint32_t cnt,
+ uint32_t base_idx,
+ float * best_val,
+ int32_t * best_idx
) {
- hvx_argmax_f32(src, n, offset, out_val, out_idx);
+ static const int32_t c_lane_idx[32] __attribute__((aligned(128))) = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
+ };
+
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ const HVX_Vector v_step = Q6_V_vsplat_R(32);
+ HVX_Vector v_cur_idx = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) c_lane_idx, Q6_V_vsplat_R((int32_t) base_idx));
+ HVX_Vector vmax = hvx_vec_splat_f32(-INFINITY);
+ HVX_Vector vidx = Q6_V_vsplat_R((int32_t) base_idx);
+
+ const uint32_t nvec = cnt / VLEN_FP32;
+ const uint32_t nloe = cnt % VLEN_FP32;
+
+ for (uint32_t vi = 0; vi < nvec; vi++) {
+ const HVX_Vector v = vsrc[vi];
+ const HVX_VectorPred pred = Q6_Q_vcmp_gt_VsfVsf(v, vmax);
+ vmax = Q6_V_vmux_QVV(pred, v, vmax);
+ vidx = Q6_V_vmux_QVV(pred, v_cur_idx, vidx);
+ v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step);
+ }
+
+ if (nloe) {
+ const HVX_Vector v = vsrc[nvec];
+ const HVX_VectorPred valid = Q6_Q_vsetq_R(nloe * sizeof(float));
+ const HVX_VectorPred pred = Q6_Q_and_QQ(valid, Q6_Q_vcmp_gt_VsfVsf(v, vmax));
+ vmax = Q6_V_vmux_QVV(pred, v, vmax);
+ vidx = Q6_V_vmux_QVV(pred, v_cur_idx, vidx);
+ }
+
+ for (uint32_t shift = 64; shift >= 4; shift >>= 1) {
+ const HVX_Vector v_val_r = Q6_V_vror_VR(vmax, shift);
+ const HVX_Vector v_idx_r = Q6_V_vror_VR(vidx, shift);
+ const HVX_VectorPred gt = Q6_Q_vcmp_gt_VsfVsf(v_val_r, vmax);
+ const HVX_VectorPred eq = Q6_Q_vcmp_eq_VwVw(v_val_r, vmax);
+ const HVX_VectorPred lt_idx = Q6_Q_vcmp_gt_VwVw(vidx, v_idx_r);
+ const HVX_VectorPred take = Q6_Q_or_QQ(gt, Q6_Q_and_QQ(eq, lt_idx));
+ vmax = Q6_V_vmux_QVV(take, v_val_r, vmax);
+ vidx = Q6_V_vmux_QVV(take, v_idx_r, vidx);
+ }
+
+ const int32_t val_bits = Q6_R_vextract_VR(vmax, 0);
+ float c_val;
+ memcpy(&c_val, &val_bits, sizeof(float));
+ const int32_t c_idx = Q6_R_vextract_VR(vidx, 0);
+
+ if (c_val > *best_val) {
+ *best_val = c_val;
+ *best_idx = c_idx;
+ }
+}
+
+static void __attribute__((noinline)) hvx_argmax_chunk_f16(
+ const uint8_t * restrict src,
+ uint32_t cnt,
+ uint32_t base_idx,
+ float * best_val,
+ int32_t * best_idx
+) {
+ static const int32_t c_lane_idx[32] __attribute__((aligned(128))) = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
+ };
+
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ const HVX_Vector v_step = Q6_V_vsplat_R(32);
+ HVX_Vector v_cur_idx = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) c_lane_idx, Q6_V_vsplat_R((int32_t) base_idx));
+ HVX_Vector vmax = hvx_vec_splat_f32(-INFINITY);
+ HVX_Vector vidx = Q6_V_vsplat_R((int32_t) base_idx);
+
+ const uint32_t nvec = cnt / VLEN_FP16;
+ const uint32_t nloe = cnt % VLEN_FP16;
+
+ for (uint32_t vi = 0; vi < nvec; vi++) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[vi]);
+ const HVX_Vector v0 = Q6_V_lo_W(p);
+ const HVX_VectorPred p0 = Q6_Q_vcmp_gt_VsfVsf(v0, vmax);
+ vmax = Q6_V_vmux_QVV(p0, v0, vmax);
+ vidx = Q6_V_vmux_QVV(p0, v_cur_idx, vidx);
+ v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step);
+
+ const HVX_Vector v1 = Q6_V_hi_W(p);
+ const HVX_VectorPred p1 = Q6_Q_vcmp_gt_VsfVsf(v1, vmax);
+ vmax = Q6_V_vmux_QVV(p1, v1, vmax);
+ vidx = Q6_V_vmux_QVV(p1, v_cur_idx, vidx);
+ v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step);
+ }
+
+ if (nloe) {
+ const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[nvec]);
+ const HVX_Vector v0 = Q6_V_lo_W(p);
+ if (nloe >= VLEN_FP32) {
+ const HVX_VectorPred p0 = Q6_Q_vcmp_gt_VsfVsf(v0, vmax);
+ vmax = Q6_V_vmux_QVV(p0, v0, vmax);
+ vidx = Q6_V_vmux_QVV(p0, v_cur_idx, vidx);
+ v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step);
+
+ const uint32_t rem = nloe - VLEN_FP32;
+ if (rem) {
+ const HVX_Vector v1 = Q6_V_hi_W(p);
+ const HVX_VectorPred valid = Q6_Q_vsetq_R(rem * sizeof(float));
+ const HVX_VectorPred p1 = Q6_Q_and_QQ(valid, Q6_Q_vcmp_gt_VsfVsf(v1, vmax));
+ vmax = Q6_V_vmux_QVV(p1, v1, vmax);
+ vidx = Q6_V_vmux_QVV(p1, v_cur_idx, vidx);
+ }
+ } else {
+ const HVX_VectorPred valid = Q6_Q_vsetq_R(nloe * sizeof(float));
+ const HVX_VectorPred p0 = Q6_Q_and_QQ(valid, Q6_Q_vcmp_gt_VsfVsf(v0, vmax));
+ vmax = Q6_V_vmux_QVV(p0, v0, vmax);
+ vidx = Q6_V_vmux_QVV(p0, v_cur_idx, vidx);
+ }
+ }
+
+ for (uint32_t shift = 64; shift >= 4; shift >>= 1) {
+ const HVX_Vector v_val_r = Q6_V_vror_VR(vmax, shift);
+ const HVX_Vector v_idx_r = Q6_V_vror_VR(vidx, shift);
+ const HVX_VectorPred gt = Q6_Q_vcmp_gt_VsfVsf(v_val_r, vmax);
+ const HVX_VectorPred eq = Q6_Q_vcmp_eq_VwVw(v_val_r, vmax);
+ const HVX_VectorPred lt_idx = Q6_Q_vcmp_gt_VwVw(vidx, v_idx_r);
+ const HVX_VectorPred take = Q6_Q_or_QQ(gt, Q6_Q_and_QQ(eq, lt_idx));
+ vmax = Q6_V_vmux_QVV(take, v_val_r, vmax);
+ vidx = Q6_V_vmux_QVV(take, v_idx_r, vidx);
+ }
+
+ const int32_t val_bits = Q6_R_vextract_VR(vmax, 0);
+ float c_val;
+ memcpy(&c_val, &val_bits, sizeof(float));
+ const int32_t c_idx = Q6_R_vextract_VR(vidx, 0);
+
+ if (c_val > *best_val) {
+ *best_val = c_val;
+ *best_idx = c_idx;
+ }
+}
+
+typedef void (*argmax_chunk_fn_t)(
+ const uint8_t * restrict src,
+ uint32_t cnt,
+ uint32_t base_idx,
+ float * best_val,
+ int32_t * best_idx
+);
+
+static void __attribute__((noinline)) hvx_vtcm_store_lane_i32(uint8_t * vtcm_dst, uint32_t lane, int32_t val) {
+ const uint32_t b_off = lane * sizeof(int32_t);
+ const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off);
+ const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(int32_t));
+ Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), (HVX_Vector *) vtcm_dst, Q6_V_vsplat_R(val));
}
struct argmax_context {
struct htp_ops_context * octx;
- const float * src_data;
- int32_t * dst_data;
+ argmax_chunk_fn_t argmax_chunk;
+ dma_addr_t data_src0;
+ dma_addr_t data_dst;
+ uint8_t * vtcm_src0;
+ uint8_t * vtcm_dst;
+ size_t src0_elem_size;
+ size_t chunk_bytes;
+ size_t src0_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
uint32_t ne00;
uint32_t src_stride;
uint32_t dst_stride;
@@ -252,12 +776,52 @@ struct argmax_context {
uint32_t nrows;
uint32_t rows_per_hvx;
uint32_t elems_per_hvx;
+ uint32_t chunk_elems;
float partial_max[HTP_MAX_NHVX];
int32_t partial_idx[HTP_MAX_NHVX];
};
+struct argmax_single_pipe_state {
+ dma_addr_t data_src;
+ argmax_chunk_fn_t argmax_chunk;
+ size_t src0_elem_size;
+ size_t chunk_bytes;
+ uint32_t chunk_elems;
+ uint32_t pos;
+ uint32_t end;
+ float best_val;
+ int32_t best_idx;
+};
+
+static bool argmax_single_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct argmax_single_pipe_state * s = (struct argmax_single_pipe_state *) ctx;
+ if (s->pos >= s->end) {
+ return false;
+ }
+ const uint32_t cnt = MIN(s->chunk_elems, s->end - s->pos);
+ task->row = s->pos;
+ task->off = 0;
+ task->len = cnt;
+ task->aux = 0;
+ s->pos += cnt;
+ return true;
+}
+
+static void argmax_single_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct argmax_single_pipe_state * s = (struct argmax_single_pipe_state *) ctx;
+ const size_t nb = (size_t) task->len * s->src0_elem_size;
+ dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src + (size_t) task->row * s->src0_elem_size),
+ s->chunk_bytes, nb, nb, 1);
+}
+
+static void argmax_single_compute(void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct argmax_single_pipe_state * s = (struct argmax_single_pipe_state *) ctx;
+ s->argmax_chunk((const uint8_t *) in_spad, task->len, task->row, &s->best_val, &s->best_idx);
+}
+
static void argmax_thread_single_row(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct argmax_context * actx = (struct argmax_context *) data;
const uint32_t start = actx->elems_per_hvx * ith;
const uint32_t end = MIN(start + actx->elems_per_hvx, actx->ne00);
@@ -268,25 +832,30 @@ static void argmax_thread_single_row(const htp_thread_t * th, unsigned int nth,
return;
}
- const uint32_t n = end - start;
- const float * src = actx->src_data + start;
-
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start);
-
- hex_l2fetch_block((const void *) src, n * sizeof(float));
-
- float max_val;
- int32_t max_idx;
- argmax_slice_f32(src, n, start, &max_val, &max_idx);
+ uint8_t * vtcm_src = actx->vtcm_src0 + ith * actx->src0_bytes_per_hvx;
+ void * in_buf[2] = { vtcm_src, vtcm_src + actx->chunk_bytes };
+
+ struct argmax_single_pipe_state s = {
+ .data_src = actx->data_src0,
+ .argmax_chunk = actx->argmax_chunk,
+ .src0_elem_size = actx->src0_elem_size,
+ .chunk_bytes = actx->chunk_bytes,
+ .chunk_elems = actx->chunk_elems,
+ .pos = start,
+ .end = end,
+ .best_val = -INFINITY,
+ .best_idx = (int32_t) start,
+ };
- actx->partial_max[ith] = max_val;
- actx->partial_idx[ith] = max_idx;
+ dma_pipe_in_run(th->dma_q, th->trace, &s, in_buf,
+ argmax_single_next_task, argmax_single_push_in, argmax_single_compute);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start);
+ actx->partial_max[ith] = s.best_val;
+ actx->partial_idx[ith] = s.best_idx;
}
static void argmax_thread_multi_row(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct argmax_context * actx = (struct argmax_context *) data;
const uint32_t r0 = actx->row_start + actx->rows_per_hvx * ith;
const uint32_t r1 = MIN(r0 + actx->rows_per_hvx, actx->row_start + actx->nrows);
@@ -295,46 +864,86 @@ static void argmax_thread_multi_row(const htp_thread_t * th, unsigned int nth, u
return;
}
- struct htp_thread_trace * tr = th->trace;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r0);
+ const dma_addr_t data_src = actx->data_src0;
+ const dma_addr_t data_dst = actx->data_dst;
+ uint8_t * vtcm_src = actx->vtcm_src0 + ith * actx->src0_bytes_per_hvx;
+ uint8_t * vtcm_dst = actx->vtcm_dst + ith * actx->dst_bytes_per_hvx;
+ const size_t src0_elem_size = actx->src0_elem_size;
+ const uint32_t ne00 = actx->ne00;
+ const uint32_t chunk_elems = actx->chunk_elems;
+ const size_t chunk_bytes = actx->chunk_bytes;
+ const uint32_t src_stride = actx->src_stride;
+ const uint32_t dst_stride = actx->dst_stride;
+ const argmax_chunk_fn_t argmax_chunk = actx->argmax_chunk;
+
+ dma_queue * dma_q = th->dma_q;
+ struct htp_thread_trace * tr = th->trace;
+
+ uint32_t dst_row0 = r0;
+ uint32_t dst_cnt = 0;
for (uint32_t r = r0; r < r1; r++) {
- const float * src_row = (const float *) ((const uint8_t *) actx->src_data + r * actx->src_stride);
- int32_t * dst_val = (int32_t *) ((uint8_t *) actx->dst_data + r * actx->dst_stride);
+ const dma_addr_t src_row = data_src + (size_t) r * src_stride;
+
+ uint32_t push_pos = 0;
+ for (uint32_t bi = 0; bi < 2 && push_pos < ne00; bi++) {
+ const uint32_t cnt = MIN(chunk_elems, ne00 - push_pos);
+ const size_t nb = (size_t) cnt * src0_elem_size;
+ dma_queue_push(dma_q,
+ dma_make_data(vtcm_src + bi * chunk_bytes, src_row + (size_t) push_pos * src0_elem_size),
+ chunk_bytes, nb, nb, 1);
+ push_pos += cnt;
+ }
- hex_l2fetch_block((const void *) src_row, actx->ne00 * sizeof(float));
+ float max_val = -INFINITY;
+ int32_t max_idx = 0;
- float max_val;
- int32_t max_idx;
- argmax_slice_f32(src_row, actx->ne00, 0, &max_val, &max_idx);
+ for (uint32_t pos = 0; pos < ne00; ) {
+ const uint32_t cnt = MIN(chunk_elems, ne00 - pos);
+ uint8_t * buf = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst;
- *dst_val = max_idx;
- }
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
+ argmax_chunk(buf, cnt, pos, &max_val, &max_idx);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r);
+
+ if (push_pos < ne00) {
+ const uint32_t pcnt = MIN(chunk_elems, ne00 - push_pos);
+ const size_t pnb = (size_t) pcnt * src0_elem_size;
+ dma_queue_push(dma_q,
+ dma_make_data(buf, src_row + (size_t) push_pos * src0_elem_size),
+ chunk_bytes, pnb, pnb, 1);
+ push_pos += pcnt;
+ }
+ pos += cnt;
+ }
+
+ hvx_vtcm_store_lane_i32(vtcm_dst, dst_cnt, max_idx);
+ dst_cnt++;
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r0);
+ if (dst_cnt == VLEN_FP32 || r + 1 == r1) {
+ dma_sync_write(dma_q, data_dst + (size_t) dst_row0 * dst_stride, vtcm_dst, (size_t) dst_cnt * sizeof(int32_t));
+ dst_row0 = r + 1;
+ dst_cnt = 0;
+ }
+ }
}
int op_argmax(struct htp_ops_context * octx) {
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- if (src0->type != HTP_TYPE_F32 || dst->type != HTP_TYPE_I32) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) {
+ if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || dst->type != HTP_TYPE_I32) {
return HTP_STATUS_NO_SUPPORT;
}
const struct htp_sum_rows_kernel_params * kparams =
(const struct htp_sum_rows_kernel_params *) octx->kernel_params;
- if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
- const uint32_t ne00 = src0->ne[0];
- const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
+ const bool src0_f16 = (src0->type == HTP_TYPE_F16);
+ const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float);
+ const argmax_chunk_fn_t argmax_chunk = src0_f16 ? hvx_argmax_chunk_f16 : hvx_argmax_chunk_f32;
+ const uint32_t ne00 = src0->ne[0];
+ const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
if (ne00 == 0 || src0_nrows == 0) {
return HTP_STATUS_OK;
@@ -345,30 +954,52 @@ int op_argmax(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
+ if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
+
+ const uint32_t n_hvx = octx->n_hvx;
+
+ struct htp_sum_vtcm_layout layout;
+ htp_sum_vtcm_layout_build(&layout, kparams->chunk_elems, src0_elem_size, n_hvx);
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "argmax: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
+ uint8_t * vtcm_dst = vtcm_base + layout.dst_off;
+
if (ne00 == 1) {
- ((int32_t *) dst->data)[0] = 0;
+ hvx_vmem(vtcm_dst) = Q6_V_vzero();
+ dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, sizeof(int32_t));
return HTP_STATUS_OK;
}
- const uint32_t n_hvx = octx->n_hvx;
- const uint32_t elems_per_hvx = kparams->elems_per_hvx;
-
struct argmax_context actx = {
- .octx = octx,
- .src_data = (const float *) src0->data,
- .dst_data = (int32_t *) dst->data,
- .ne00 = ne00,
- .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * sizeof(float)),
- .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t),
- .row_start = 0,
- .nrows = 1,
- .rows_per_hvx = 1,
- .elems_per_hvx = elems_per_hvx,
+ .octx = octx,
+ .argmax_chunk = argmax_chunk,
+ .data_src0 = (dma_addr_t) src0->data,
+ .data_dst = (dma_addr_t) dst->data,
+ .vtcm_src0 = vtcm_base + layout.src0_off,
+ .vtcm_dst = vtcm_dst,
+ .src0_elem_size = src0_elem_size,
+ .chunk_bytes = layout.chunk_bytes,
+ .src0_bytes_per_hvx = layout.src0_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
+ .ne00 = ne00,
+ .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * src0_elem_size),
+ .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t),
+ .row_start = 0,
+ .nrows = 1,
+ .rows_per_hvx = 1,
+ .elems_per_hvx = kparams->elems_per_hvx,
+ .chunk_elems = kparams->chunk_elems,
};
work_queue_run(octx->ctx->hvx_queue, argmax_thread_single_row, &actx, n_hvx);
- float best_val = actx.partial_max[0];
+ float best_val = actx.partial_max[0];
int32_t best_idx = actx.partial_idx[0];
for (uint32_t i = 1; i < n_hvx; i++) {
if (actx.partial_max[i] > best_val) {
@@ -376,7 +1007,9 @@ int op_argmax(struct htp_ops_context * octx) {
best_idx = actx.partial_idx[i];
}
}
- ((int32_t *) dst->data)[0] = best_idx;
+
+ hvx_vmem(vtcm_dst) = Q6_V_vsplat_R(best_idx);
+ dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, sizeof(int32_t));
return HTP_STATUS_OK;
}
@@ -384,11 +1017,8 @@ int op_argmax(struct htp_ops_context * octx) {
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- const bool can_split = htp_tensor_mdev_data_aligned(dst) &&
- htp_tensor_is_contiguous(dst, sizeof(int32_t));
- const uint32_t elems_per_chunk = can_split ? 32 : 0;
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- src0_nrows, elems_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -397,20 +1027,41 @@ int op_argmax(struct htp_ops_context * octx) {
return HTP_STATUS_OK;
}
+ if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, nrows))) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
+
const uint32_t n_hvx = octx->n_hvx;
const uint32_t rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div);
+ struct htp_sum_vtcm_layout layout;
+ htp_sum_vtcm_layout_build(&layout, kparams->chunk_elems, src0_elem_size, n_hvx);
+ if (octx->ctx->vtcm_size < layout.total_bytes) {
+ FARF(ERROR, "argmax: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * vtcm_base = octx->ctx->vtcm_base;
+
struct argmax_context actx = {
- .octx = octx,
- .src_data = (const float *) src0->data,
- .dst_data = (int32_t *) dst->data,
- .ne00 = ne00,
- .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * sizeof(float)),
- .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t),
- .row_start = row_start,
- .nrows = nrows,
- .rows_per_hvx = rows_per_hvx,
- .elems_per_hvx = 0,
+ .octx = octx,
+ .argmax_chunk = argmax_chunk,
+ .data_src0 = (dma_addr_t) src0->data,
+ .data_dst = (dma_addr_t) dst->data,
+ .vtcm_src0 = vtcm_base + layout.src0_off,
+ .vtcm_dst = vtcm_base + layout.dst_off,
+ .src0_elem_size = src0_elem_size,
+ .chunk_bytes = layout.chunk_bytes,
+ .src0_bytes_per_hvx = layout.src0_bytes_per_hvx,
+ .dst_bytes_per_hvx = layout.dst_bytes_per_hvx,
+ .ne00 = ne00,
+ .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * src0_elem_size),
+ .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t),
+ .row_start = row_start,
+ .nrows = nrows,
+ .rows_per_hvx = rows_per_hvx,
+ .elems_per_hvx = 0,
+ .chunk_elems = kparams->chunk_elems,
};
work_queue_run(octx->ctx->hvx_queue, argmax_thread_multi_row, &actx, n_hvx);
diff --git a/ggml/src/ggml-hexagon/htp/sum-rows-ops.h b/ggml/src/ggml-hexagon/htp/sum-rows-ops.h
index 0b8acf030..c8c3bfdf0 100644
--- a/ggml/src/ggml-hexagon/htp/sum-rows-ops.h
+++ b/ggml/src/ggml-hexagon/htp/sum-rows-ops.h
@@ -1,13 +1,82 @@
#ifndef HTP_SUM_ROWS_OPS_H
#define HTP_SUM_ROWS_OPS_H
+#include <stddef.h>
#include <stdint.h>
+#include "hex-common.h"
+#include "hex-fastdiv.h"
+#include "htp-vtcm.h"
+
struct htp_sum_rows_kernel_params {
- uint32_t n_hvx;
- uint32_t elems_per_hvx;
+ uint32_t n_hvx;
+ uint32_t elems_per_hvx;
+ uint32_t block;
+ uint32_t chunk_elems;
+ uint32_t src0_contig;
+ uint32_t vtcm_size;
+ struct fastdiv_values div_ne01;
+ struct fastdiv_values div_ne02;
+ struct fastdiv_values div_ne012;
+};
+
+struct htp_sum_vtcm_layout {
+ size_t chunk_bytes;
+ size_t src0_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
+ size_t src0_off;
+ size_t dst_off;
+ size_t total_bytes;
};
+static inline void htp_sum_vtcm_layout_build(
+ struct htp_sum_vtcm_layout * L,
+ uint32_t chunk_elems,
+ size_t src0_elem_size,
+ uint32_t n_hvx
+) {
+ size_t off = 0;
+
+ L->chunk_bytes = hex_round_up((size_t) chunk_elems * src0_elem_size, 128);
+ L->src0_bytes_per_hvx = 2 * L->chunk_bytes;
+ L->dst_bytes_per_hvx = 128;
+
+ VTCM_LAYOUT_ALLOC(off, src0_off, (size_t) n_hvx * L->src0_bytes_per_hvx);
+ VTCM_LAYOUT_ALLOC(off, dst_off, (size_t) n_hvx * L->dst_bytes_per_hvx);
+ L->total_bytes = off;
+}
+
+struct htp_sum_rows_vtcm_layout {
+ size_t src0_row_size_aligned;
+ size_t src0_half_bytes;
+ size_t dst_half_bytes;
+ size_t src0_bytes_per_hvx;
+ size_t dst_bytes_per_hvx;
+ size_t src0_off;
+ size_t dst_off;
+ size_t total_bytes;
+};
+
+static inline void htp_sum_rows_vtcm_layout_build(
+ struct htp_sum_rows_vtcm_layout * L,
+ size_t src0_row_size,
+ size_t dst_elem_size,
+ uint32_t block,
+ uint32_t n_hvx
+) {
+ size_t off = 0;
+
+ L->src0_row_size_aligned = hex_round_up(src0_row_size, 128);
+ L->src0_half_bytes = L->src0_row_size_aligned * block;
+ L->dst_half_bytes = hex_round_up((size_t) block * dst_elem_size, 128);
+ L->src0_bytes_per_hvx = 2 * L->src0_half_bytes;
+ L->dst_bytes_per_hvx = 2 * L->dst_half_bytes;
+
+ VTCM_LAYOUT_ALLOC(off, src0_off, (size_t) n_hvx * L->src0_bytes_per_hvx);
+ VTCM_LAYOUT_ALLOC(off, dst_off, (size_t) n_hvx * L->dst_bytes_per_hvx);
+ L->total_bytes = off;
+}
+
#if defined(__cplusplus)
static_assert(sizeof(struct htp_sum_rows_kernel_params) <= 128, "htp_sum_rows_kernel_params is too large for kernel_params blob");
#else
diff --git a/ggml/src/ggml-hexagon/htp/timestep-ops.c b/ggml/src/ggml-hexagon/htp/timestep-ops.c
index 28451e38b..4835df3bb 100644
--- a/ggml/src/ggml-hexagon/htp/timestep-ops.c
+++ b/ggml/src/ggml-hexagon/htp/timestep-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <stdint.h>
@@ -186,8 +182,6 @@ int op_timestep_embedding(struct htp_ops_context * octx) {
const struct htp_timestep_kernel_params * kparams =
(const struct htp_timestep_kernel_params *) octx->kernel_params;
- const int32_t max_period = (int32_t) octx->op_params[1];
-
// Only device 0 writes the output when running multi-device
if (octx->ctx->mdev.count > 1 && octx->ctx->mdev.idx != 0) {
return HTP_STATUS_OK;
diff --git a/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c b/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c
index 9c4dc583c..6fefd2231 100644
--- a/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c
+++ b/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
#include <stdatomic.h>
diff --git a/ggml/src/ggml-hexagon/htp/unary-ops.c b/ggml/src/ggml-hexagon/htp/unary-ops.c
index 19ade22f3..258cafaff 100644
--- a/ggml/src/ggml-hexagon/htp/unary-ops.c
+++ b/ggml/src/ggml-hexagon/htp/unary-ops.c
@@ -1,7 +1,3 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-#pragma clang diagnostic ignored "-Wunused-function"
-#pragma clang diagnostic ignored "-Wunused-but-set-variable"
-
#include <HAP_farf.h>
#include <HAP_perf.h>
@@ -9,6 +5,7 @@
#include <string.h>
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "hex-fastdiv.h"
#include "hvx-exp.h"
#include "hvx-sigmoid.h"
@@ -28,19 +25,22 @@ struct htp_unary_context;
typedef void (*unary_compute_fn_t)(const void * restrict src,
void * restrict dst,
uint32_t num_rows,
+ uint32_t ne0,
const struct htp_unary_context * uctx);
typedef void (*unary_rms_norm_mul_compute_fn_t)(const void * restrict src,
- const void * restrict weight,
+ const void * restrict mul,
void * restrict dst,
uint32_t num_rows,
+ uint32_t src1_row_start,
const struct htp_unary_context * uctx);
typedef void (*unary_rms_norm_mul_add_compute_fn_t)(const void * restrict src,
- const void * restrict weight,
+ const void * restrict mul,
const void * restrict add,
void * restrict dst,
uint32_t num_rows,
+ uint32_t src1_row_start,
const struct htp_unary_context * uctx);
typedef void (*unary_tri_compute_fn_t)(const void * restrict src,
@@ -49,11 +49,6 @@ typedef void (*unary_tri_compute_fn_t)(const void * restrict src,
uint32_t ir,
const struct htp_unary_context * uctx);
-typedef void (*unary_tile_compute_fn_t)(void * restrict dst,
- const void * restrict src,
- uint32_t tw,
- const struct htp_unary_context * uctx);
-
typedef void (*unary_tiled_tri_compute_fn_t)(const void * restrict src,
void * restrict dst,
uint32_t tile_elems,
@@ -62,27 +57,43 @@ typedef void (*unary_tiled_tri_compute_fn_t)(const void * restrict src,
uint32_t ne0,
int32_t ttype);
+typedef float (*rms_tile_sum_sq_fn_t)(const uint8_t * restrict src,
+ uint32_t num_elems);
+
+typedef void (*rms_apply_row_fn_t)(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v);
+
struct htp_unary_context {
struct htp_ops_context * octx;
const struct htp_unary_kernel_params * kparams;
void * compute;
+ rms_tile_sum_sq_fn_t rms_tile_sum_sq_fn;
+ rms_apply_row_fn_t rms_apply_row_fn;
dma_addr_t data_src0;
- dma_addr_t data_src1; // weight/scale tensor for RMS_NORM_MUL
+ dma_addr_t data_src1; // mul/scale tensor for RMS_NORM_MUL
dma_addr_t data_src2; // residual tensor for RMS_NORM_MUL_ADD
dma_addr_t data_dst;
size_t src0_data_row_size; // actual data bytes per row
size_t src1_data_row_size;
+ size_t src2_data_row_size;
size_t dst_data_row_size; // actual data bytes per row
size_t src0_row_size_aligned;
size_t src1_row_size_aligned;
+ size_t src1_block_stride;
+ size_t src2_row_size_aligned;
size_t dst_row_size_aligned;
size_t src0_vtcm_half_size;
size_t src1_vtcm_half_size;
+ size_t src2_vtcm_half_size;
size_t dst_vtcm_half_size;
uint32_t block;
@@ -91,7 +102,12 @@ struct htp_unary_context {
uint32_t row_start;
uint32_t nc;
uint32_t col_tile; // tiled mode
- bool broadcast_weight;
+ uint32_t src1_nrows;
+ bool broadcast_src1;
+ bool src0_f16;
+ bool src1_f16;
+ bool src2_f16;
+ bool dst_f16;
uint8_t * vtcm_src0;
uint8_t * vtcm_src1;
@@ -125,48 +141,100 @@ static inline uint32_t unary_block_size(uint32_t ir,
uint32_t end_row,
uint32_t block,
bool contig,
+ bool slice_dma,
uint32_t ne1,
const struct fastdiv_values * div_ne1) {
uint32_t limit = MIN(block, end_row - ir);
if (!contig) {
- const uint32_t slice_end = (fastdiv(ir, div_ne1) + 1) * ne1;
+ const uint32_t slice_idx = fastdiv(ir, div_ne1);
+ const uint32_t slice_start = slice_idx * ne1;
+ if (slice_dma && ir == slice_start && limit >= ne1) {
+ return fastdiv(limit, div_ne1) * ne1;
+ }
+ const uint32_t slice_end = slice_start + ne1;
limit = MIN(limit, slice_end - ir);
}
return limit;
}
-#define htp_unary_preamble \
- const uint32_t ne00 = src->ne[0]; \
- const uint32_t ne01 = src->ne[1]; \
- const uint32_t ne02 = src->ne[2]; \
- const uint32_t ne03 = src->ne[3]; \
- \
- const uint32_t ne0 = dst->ne[0]; \
- const uint32_t ne1 = dst->ne[1]; \
- const uint32_t ne2 = dst->ne[2]; \
- const uint32_t ne3 = dst->ne[3]; \
- \
- const uint32_t nb00 = src->nb[0]; \
- const uint32_t nb01 = src->nb[1]; \
- const uint32_t nb02 = src->nb[2]; \
- const uint32_t nb03 = src->nb[3]; \
- \
- const uint32_t nb0 = dst->nb[0]; \
- const uint32_t nb1 = dst->nb[1]; \
- const uint32_t nb2 = dst->nb[2]; \
- const uint32_t nb3 = dst->nb[3];
-
-#define htp_unary_op_preamble \
- int32_t * op_params = uctx->octx->op_params; \
- const uint32_t ne0 = uctx->nc; \
- const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \
+static inline void unary_push_src0_dma(dma_queue * dma_q,
+ void * dst_vtcm,
+ dma_addr_t data_src,
+ uint32_t ir,
+ uint32_t block_size,
+ bool src0_contig,
+ bool src0_slice_dma,
+ uint32_t ne01,
+ uint32_t ne02,
+ const struct fastdiv_values * div_ne01,
+ const struct fastdiv_values * div_ne02,
+ const struct fastdiv_values * div_ne012,
+ size_t nb01,
+ size_t nb02,
+ size_t nb03,
+ size_t src0_row_size_aligned,
+ size_t src0_data_row_size) {
+ if (src0_contig) {
+ dma_queue_push(dma_q,
+ dma_make_data(dst_vtcm, data_src + (size_t) ir * nb01),
+ src0_row_size_aligned, nb01, src0_data_row_size, block_size);
+ return;
+ }
+ if (src0_slice_dma) {
+ const uint32_t slice_idx = fastdiv(ir, div_ne01);
+ if (ir == slice_idx * ne01 && block_size >= ne01) {
+ const size_t slice_bytes = (size_t) ne01 * src0_data_row_size;
+ const uint32_t n_slices = fastdiv(block_size, div_ne01);
+ dma_queue_push(dma_q,
+ dma_make_data(dst_vtcm, data_src + (size_t) slice_idx * nb02),
+ slice_bytes, nb02, slice_bytes, n_slices);
+ return;
+ }
+ }
+ const size_t src0_off = unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
+ dma_queue_push(dma_q,
+ dma_make_data(dst_vtcm, data_src + src0_off),
+ src0_row_size_aligned, nb01, src0_data_row_size, block_size);
+}
+
+#define htp_unary_preamble \
+ const uint32_t __attribute__((unused)) ne00 = src->ne[0]; \
+ const uint32_t __attribute__((unused)) ne01 = src->ne[1]; \
+ const uint32_t __attribute__((unused)) ne02 = src->ne[2]; \
+ const uint32_t __attribute__((unused)) ne03 = src->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 = src->nb[0]; \
+ const uint32_t __attribute__((unused)) nb01 = src->nb[1]; \
+ const uint32_t __attribute__((unused)) nb02 = src->nb[2]; \
+ const uint32_t __attribute__((unused)) nb03 = src->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];
+
+#define htp_unary_op_preamble \
+ int32_t * __attribute__((unused)) op_params = uctx->octx->op_params; \
+ const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \
const size_t dst_row_size_aligned = uctx->dst_row_size_aligned;
+static inline HVX_Vector hvx_vec_clamp_f16_f32(HVX_Vector x) {
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_neg_f32(f16_max);
+ return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max);
+}
+
static void scale_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float scale = 0.f;
@@ -185,6 +253,7 @@ static void scale_f32(const void * restrict src,
static void clamp_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float min = 0.f;
@@ -196,13 +265,38 @@ static void clamp_f32(const void * restrict src,
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_clamp_scalar_f32(dst_local, src_local, min, max, ne0);
+ hvx_clamp_scalar_f32_aa(dst_local, src_local, min, max, ne0);
+ }
+}
+
+static inline HVX_Vector hvx_vec_leaky_relu_f32(HVX_Vector x, HVX_Vector slope, HVX_Vector zero) {
+ HVX_VectorPred pred = Q6_Q_vcmp_gt_VsfVsf(x, zero);
+ HVX_Vector neg = hvx_vec_mul_f32_f32(x, slope);
+ return Q6_V_vmux_QVV(pred, x, neg);
+}
+
+static inline void unary_leaky_relu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, float slope, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const HVX_Vector vslope = hvx_vec_splat_f32(slope);
+ const HVX_Vector vzero = Q6_V_vzero();
+
+ const uint32_t nvec = n / VLEN_FP32;
+ const uint32_t nloe = n % VLEN_FP32;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = hvx_vec_leaky_relu_f32(vsrc[i], vslope, vzero);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), hvx_vec_leaky_relu_f32(vsrc[nvec], vslope, vzero));
}
}
static void leaky_relu_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float negative_slope = 0.f;
@@ -212,74 +306,1316 @@ static void leaky_relu_f32(const void * restrict src,
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_leaky_relu_scalar_f32(dst_local, src_local, negative_slope, ne0);
+ unary_leaky_relu_f32_aa(dst_local, src_local, negative_slope, ne0);
}
}
-static void rms_norm_f32(const void * restrict src,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
- htp_unary_op_preamble;
- float epsilon = 0.f;
- float scale = 0.f;
- memcpy(&epsilon, &op_params[0], sizeof(float));
- memcpy(&scale, &op_params[1], sizeof(float));
+static inline HVX_Vector rms_norm_sum_sq_f32(const uint8_t * restrict src, uint32_t num_elems, HVX_Vector sum_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ const uint32_t nvec = num_elems / VLEN_FP32;
+ const uint32_t nloe = num_elems % VLEN_FP32;
- for (uint32_t ir = 0; ir < num_rows; ir++) {
- const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
- uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+ #pragma unroll(4)
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_Vector v1 = v_src[i];
+ sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(v1, v1));
+ }
- hvx_fast_rms_norm_f32((const uint8_t *) src_local, (uint8_t *) dst_local, ne0, epsilon, scale);
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(float));
+ HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]);
+ sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(v1, v1));
}
+
+ return sum_v;
}
-static void rms_norm_mul_f32(const void * restrict src,
- const void * restrict weight,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
- htp_unary_op_preamble;
- float epsilon = 0.f;
- float scale = 0.f;
- memcpy(&epsilon, &op_params[0], sizeof(float));
- memcpy(&scale, &op_params[1], sizeof(float));
+static inline HVX_Vector rms_norm_sum_sq_f16(const uint8_t * restrict src, uint32_t num_elems, HVX_Vector sum_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ const uint32_t nvec = num_elems / VLEN_FP16;
+ const uint32_t nloe = num_elems % VLEN_FP16;
- for (uint32_t ir = 0; ir < num_rows; ir++) {
- const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
- const uint8_t * restrict w_local = (const uint8_t *)weight + (uctx->broadcast_weight ? 0 : ir * uctx->src1_row_size_aligned);
- uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p = Q6_W_vzero();
+
+ #pragma unroll(4)
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_Vector v = v_src[i];
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v);
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(_Float16));
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v);
+ }
+
+ sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p)));
+#else
+ HVX_Vector sum0 = Q6_V_vzero();
+ HVX_Vector sum1 = Q6_V_vzero();
+
+ #pragma unroll(4)
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_Vector v = v_src[i];
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq));
+ }
+
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(_Float16));
+ HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]);
+ HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v);
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq));
+ }
+
+ sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vadd_Vqf32Vqf32(sum0, sum1));
+#endif
+
+ return sum_v;
+}
+
+static inline HVX_Vector rms_norm_scale_from_sum_precomp(HVX_Vector sum_v,
+ HVX_Vector inv_ne0_v,
+ HVX_Vector eps_v,
+ HVX_Vector scale_param_v) {
+ HVX_Vector mean_v = Q6_Vqf32_vmpy_VsfVsf(sum_v, inv_ne0_v);
+ HVX_Vector mean_epsilon_v = Q6_Vqf32_vadd_Vqf32Vsf(mean_v, eps_v);
+ HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_equals_Vqf32(mean_epsilon_v));
+ return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(scale_v, scale_param_v));
+}
+
+static inline HVX_Vector rms_norm_scale_from_sum_f32(HVX_Vector sum_v, uint32_t num_elems, float epsilon, float scale) {
+ const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) num_elems));
+ const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon);
+ const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f);
+ return rms_norm_scale_from_sum_precomp(sum_v, inv_ne0_v, eps_v, scale_param_v);
+}
+
+static inline HVX_Vector rms_norm_row_scale_precomp_f32(const uint8_t * restrict src,
+ uint32_t num_elems,
+ HVX_Vector inv_ne0_v,
+ HVX_Vector eps_v,
+ HVX_Vector scale_param_v) {
+ HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000);
+ sum_v = rms_norm_sum_sq_f32(src, num_elems, sum_v);
+ sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
+ return rms_norm_scale_from_sum_precomp(sum_v, inv_ne0_v, eps_v, scale_param_v);
+}
+
+static inline HVX_Vector rms_norm_row_scale_precomp_f16(const uint8_t * restrict src,
+ uint32_t num_elems,
+ HVX_Vector inv_ne0_v,
+ HVX_Vector eps_v,
+ HVX_Vector scale_param_v) {
+ HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000);
+ sum_v = rms_norm_sum_sq_f16(src, num_elems, sum_v);
+ sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
+ return rms_norm_scale_from_sum_precomp(sum_v, inv_ne0_v, eps_v, scale_param_v);
+}
+
+static inline void rms_norm_scale_4rows_from_sums(HVX_Vector_x4 sums,
+ HVX_Vector inv_ne0_v,
+ HVX_Vector eps_v,
+ HVX_Vector scale_param_v,
+ HVX_Vector * restrict scale_v0,
+ HVX_Vector * restrict scale_v1,
+ HVX_Vector * restrict scale_v2,
+ HVX_Vector * restrict scale_v3) {
+ HVX_Vector sum_x4 = hvx_vec_reduce_sum_f32x4(sums);
+ HVX_Vector scale_x4 = rms_norm_scale_from_sum_precomp(sum_x4, inv_ne0_v, eps_v, scale_param_v);
+
+ HVX_VectorPair p01 = Q6_W_vshuff_VVR(scale_x4, scale_x4, 4);
+ HVX_VectorPair p02 = Q6_W_vshuff_VVR(Q6_V_lo_W(p01), Q6_V_lo_W(p01), 8);
+ HVX_VectorPair p13 = Q6_W_vshuff_VVR(Q6_V_hi_W(p01), Q6_V_hi_W(p01), 8);
+
+ *scale_v0 = Q6_V_lo_W(p02);
+ *scale_v1 = Q6_V_lo_W(p13);
+ *scale_v2 = Q6_V_hi_W(p02);
+ *scale_v3 = Q6_V_hi_W(p13);
+}
+
+static inline void rms_norm_4rows_scale_precomp_f32(const uint8_t * restrict src,
+ size_t stride,
+ uint32_t num_elems,
+ HVX_Vector inv_ne0_v,
+ HVX_Vector eps_v,
+ HVX_Vector scale_param_v,
+ HVX_Vector * restrict scale_v0,
+ HVX_Vector * restrict scale_v1,
+ HVX_Vector * restrict scale_v2,
+ HVX_Vector * restrict scale_v3) {
+ const uint32_t nvec = num_elems / VLEN_FP32;
+
+ HVX_Vector sum0 = Q6_V_vzero();
+ HVX_Vector sum1 = Q6_V_vzero();
+ HVX_Vector sum2 = Q6_V_vzero();
+ HVX_Vector sum3 = Q6_V_vzero();
+
+ const uint8_t * restrict s0 = src;
+ #pragma clang loop unroll(disable)
+ for (uint32_t i = 0; i < nvec; i++) {
+ const uint8_t * restrict s1 = s0 + stride;
+ const uint8_t * restrict s2 = s1 + stride;
+ const uint8_t * restrict s3 = s2 + stride;
+ HVX_Vector v0 = *(const HVX_Vector *) s0;
+ HVX_Vector v1 = *(const HVX_Vector *) s1;
+ HVX_Vector v2 = *(const HVX_Vector *) s2;
+ HVX_Vector v3 = *(const HVX_Vector *) s3;
+ s0 += VLEN;
+ sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_Vqf32_vmpy_VsfVsf(v0, v0));
+ sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_Vqf32_vmpy_VsfVsf(v1, v1));
+ sum2 = Q6_Vqf32_vadd_Vqf32Vqf32(sum2, Q6_Vqf32_vmpy_VsfVsf(v2, v2));
+ sum3 = Q6_Vqf32_vadd_Vqf32Vqf32(sum3, Q6_Vqf32_vmpy_VsfVsf(v3, v3));
+ }
+
+ HVX_Vector_x4 sums = { .v = {
+ Q6_Vsf_equals_Vqf32(sum0),
+ Q6_Vsf_equals_Vqf32(sum1),
+ Q6_Vsf_equals_Vqf32(sum2),
+ Q6_Vsf_equals_Vqf32(sum3),
+ } };
+ rms_norm_scale_4rows_from_sums(sums, inv_ne0_v, eps_v, scale_param_v, scale_v0, scale_v1, scale_v2, scale_v3);
+}
+
+static inline void rms_norm_4rows_scale_precomp_f16(const uint8_t * restrict src,
+ size_t stride,
+ uint32_t num_elems,
+ HVX_Vector inv_ne0_v,
+ HVX_Vector eps_v,
+ HVX_Vector scale_param_v,
+ HVX_Vector * restrict scale_v0,
+ HVX_Vector * restrict scale_v1,
+ HVX_Vector * restrict scale_v2,
+ HVX_Vector * restrict scale_v3) {
+ const uint32_t nvec = num_elems / VLEN_FP16;
+ const uint8_t * restrict s0 = src;
+
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p0 = Q6_W_vzero();
+ HVX_VectorPair sum_p1 = Q6_W_vzero();
+ HVX_VectorPair sum_p2 = Q6_W_vzero();
+ HVX_VectorPair sum_p3 = Q6_W_vzero();
+
+ #pragma clang loop unroll(disable)
+ for (uint32_t i = 0; i < nvec; i++) {
+ const uint8_t * restrict s1 = s0 + stride;
+ const uint8_t * restrict s2 = s1 + stride;
+ const uint8_t * restrict s3 = s2 + stride;
+ HVX_Vector v0 = *(const HVX_Vector *) s0;
+ HVX_Vector v1 = *(const HVX_Vector *) s1;
+ HVX_Vector v2 = *(const HVX_Vector *) s2;
+ HVX_Vector v3 = *(const HVX_Vector *) s3;
+ s0 += VLEN;
+ sum_p0 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p0, v0, v0);
+ sum_p1 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p1, v1, v1);
+ sum_p2 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p2, v2, v2);
+ sum_p3 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p3, v3, v3);
+ }
+
+ HVX_Vector_x4 sums = { .v = {
+ Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p0), Q6_V_hi_W(sum_p0)),
+ Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p1), Q6_V_hi_W(sum_p1)),
+ Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p2), Q6_V_hi_W(sum_p2)),
+ Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p3), Q6_V_hi_W(sum_p3)),
+ } };
+#else
+ HVX_Vector sum0_lo = Q6_V_vzero(), sum0_hi = Q6_V_vzero();
+ HVX_Vector sum1_lo = Q6_V_vzero(), sum1_hi = Q6_V_vzero();
+ HVX_Vector sum2_lo = Q6_V_vzero(), sum2_hi = Q6_V_vzero();
+ HVX_Vector sum3_lo = Q6_V_vzero(), sum3_hi = Q6_V_vzero();
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ const uint8_t * restrict s1 = s0 + stride;
+ const uint8_t * restrict s2 = s1 + stride;
+ const uint8_t * restrict s3 = s2 + stride;
+ HVX_Vector v0 = *(const HVX_Vector *) s0;
+ HVX_Vector v1 = *(const HVX_Vector *) s1;
+ HVX_Vector v2 = *(const HVX_Vector *) s2;
+ HVX_Vector v3 = *(const HVX_Vector *) s3;
+ s0 += VLEN;
+ HVX_VectorPair sq0 = Q6_Wqf32_vmpy_VhfVhf(v0, v0);
+ HVX_VectorPair sq1 = Q6_Wqf32_vmpy_VhfVhf(v1, v1);
+ HVX_VectorPair sq2 = Q6_Wqf32_vmpy_VhfVhf(v2, v2);
+ HVX_VectorPair sq3 = Q6_Wqf32_vmpy_VhfVhf(v3, v3);
+ sum0_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum0_lo, Q6_V_lo_W(sq0));
+ sum0_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum0_hi, Q6_V_hi_W(sq0));
+ sum1_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum1_lo, Q6_V_lo_W(sq1));
+ sum1_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum1_hi, Q6_V_hi_W(sq1));
+ sum2_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum2_lo, Q6_V_lo_W(sq2));
+ sum2_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum2_hi, Q6_V_hi_W(sq2));
+ sum3_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum3_lo, Q6_V_lo_W(sq3));
+ sum3_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum3_hi, Q6_V_hi_W(sq3));
+ }
+
+ HVX_Vector_x4 sums = { .v = {
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum0_lo, sum0_hi)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum1_lo, sum1_hi)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum2_lo, sum2_hi)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum3_lo, sum3_hi)),
+ } };
+#endif
+ rms_norm_scale_4rows_from_sums(sums, inv_ne0_v, eps_v, scale_param_v, scale_v0, scale_v1, scale_v2, scale_v3);
+}
+
+static __attribute__((noinline)) float rms_norm_tile_sum_sq_f32(const uint8_t * restrict src,
+ uint32_t num_elems) {
+ HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000);
+ sum_v = rms_norm_sum_sq_f32(src, num_elems, sum_v);
+ sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
+ return hvx_vec_get_f32(sum_v);
+}
+
+static __attribute__((noinline)) float rms_norm_tile_sum_sq_f16(const uint8_t * restrict src,
+ uint32_t num_elems) {
+ HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000);
+ sum_v = rms_norm_sum_sq_f16(src, num_elems, sum_v);
+ sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
+ return hvx_vec_get_f32(sum_v);
+}
+
+static inline HVX_VectorPair rms_load_pair_f32(const uint8_t * restrict ptr, uint32_t i, bool is_f16) {
+ const HVX_Vector * restrict v_ptr = (const HVX_Vector *) ptr;
+ if (is_f16) {
+ return hvx_vec_f16_to_f32(v_ptr[i >> 6]);
+ }
+ return Q6_W_vcombine_VV(v_ptr[(i >> 5) + 1], v_ptr[i >> 5]);
+}
+
+static inline HVX_Vector rms_load_vec_f32(const uint8_t * restrict ptr, uint32_t i, bool is_f16) {
+ const HVX_Vector * restrict v_ptr = (const HVX_Vector *) ptr;
+ if (!is_f16) {
+ return v_ptr[i >> 5];
+ }
+ HVX_VectorPair p = hvx_vec_f16_to_f32(v_ptr[i >> 6]);
+ return (i & 32u) ? Q6_V_hi_W(p) : Q6_V_lo_W(p);
+}
+
+static inline void rms_store_pair_f32(uint8_t * restrict dst, uint32_t i, HVX_Vector r0, HVX_Vector r1, bool is_f16) {
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ if (is_f16) {
+ r0 = hvx_vec_clamp_f16_f32(r0);
+ r1 = hvx_vec_clamp_f16_f32(r1);
+ v_dst[i >> 6] = hvx_vec_f32_to_f16(r0, r1);
+ } else {
+ v_dst[(i >> 5) + 0] = r0;
+ v_dst[(i >> 5) + 1] = r1;
+ }
+}
- hvx_fast_rms_norm_mul_f32(src_local, w_local, dst_local, ne0, epsilon, scale);
+static inline void rms_store_tail_f32(uint8_t * restrict dst, uint32_t i, uint32_t rem, HVX_Vector r0, HVX_Vector r1, bool is_f16) {
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+ if (is_f16) {
+ r0 = hvx_vec_clamp_f16_f32(r0);
+ r1 = hvx_vec_clamp_f16_f32(r1);
+ HVX_Vector packed = hvx_vec_f32_to_f16(r0, r1);
+ hvx_vec_store_a(&v_dst[i >> 6], rem * sizeof(_Float16), packed);
+ } else if (rem <= 32) {
+ hvx_vec_store_a(&v_dst[i >> 5], rem * sizeof(float), r0);
+ } else {
+ v_dst[(i >> 5) + 0] = r0;
+ hvx_vec_store_a(&v_dst[(i >> 5) + 1], (rem - 32) * sizeof(float), r1);
}
}
-static void rms_norm_mul_add_f32(const void * restrict src,
- const void * restrict weight,
- const void * restrict add,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
- htp_unary_op_preamble;
+static inline HVX_Vector rms_clamp_pack_f16_shuff(HVX_Vector r0, HVX_Vector r1, HVX_Vector f16_min, HVX_Vector f16_max) {
+ r0 = Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(r0, f16_min), f16_max);
+ r1 = Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(r1, f16_min), f16_max);
+ return hvx_vec_f32_to_f16_shuff(r0, r1);
+}
+
+static inline HVX_Vector rms_clamp_pack_f16(HVX_Vector r0, HVX_Vector r1, HVX_Vector f16_min, HVX_Vector f16_max) {
+ return Q6_Vh_vdeal_Vh(rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max));
+}
+
+static inline void rms_norm_apply_row_f16(const uint8_t * restrict src,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector scale_qf = Q6_Vqf32_vadd_VsfVsf(scale_v, Q6_V_vzero());
+#endif
+
+ #pragma unroll(2)
+ for (uint32_t k = 0; k < nvec; k++) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(v_src[k], one_hf);
+ HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), scale_v);
+ HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), scale_v);
+#else
+ HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(v_src[k], one_hf);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), scale_qf));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), scale_qf));
+#endif
+ v_dst[k] = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max);
+ }
+
+ if (nloe > 0) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(v_src[nvec], one_hf);
+ HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), scale_v);
+ HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), scale_v);
+#else
+ HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(v_src[nvec], one_hf);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), scale_qf));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), scale_qf));
+#endif
+ HVX_Vector packed = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max);
+ hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed);
+ }
+}
+
+static inline void rms_norm_apply_row_mul_f16_f32(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) mul;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+
+ #pragma unroll(2)
+ for (uint32_t k = 0; k < nvec; k++) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf);
+ HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 0], scale_v);
+ HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 1], scale_v);
+ HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0);
+ HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1);
+#else
+ HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf);
+ HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 0], scale_v);
+ HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 1], scale_v);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1));
+#endif
+ v_dst[k] = rms_clamp_pack_f16(r0, r1, f16_min, f16_max);
+ }
+
+ if (nloe > 0) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf);
+ HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v);
+ HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0);
+ HVX_Vector r1 = Q6_V_vzero();
+ if (nloe > 32) {
+ HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v);
+ r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1);
+ }
+#else
+ HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf);
+ HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0));
+ HVX_Vector r1 = Q6_V_vzero();
+ if (nloe > 32) {
+ HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v);
+ r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1));
+ }
+#endif
+ HVX_Vector packed = rms_clamp_pack_f16(r0, r1, f16_min, f16_max);
+ hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed);
+ }
+}
+
+static inline void rms_norm_apply_row_mul_f16_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) mul;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector scale_qf = Q6_Vqf32_vadd_VsfVsf(scale_v, Q6_V_vzero());
+#endif
+
+ #pragma unroll(2)
+ for (uint32_t k = 0; k < nvec; k++) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[k], v_w[k]);
+ HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v);
+ HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v);
+#else
+ HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[k], v_w[k]);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf));
+#endif
+ v_dst[k] = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max);
+ }
+
+ if (nloe > 0) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[nvec], v_w[nvec]);
+ HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v);
+ HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v);
+#else
+ HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[nvec], v_w[nvec]);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf));
+#endif
+ HVX_Vector packed = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max);
+ hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed);
+ }
+}
+
+static inline void rms_norm_apply_row_mul_add_f16_f32_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) mul;
+ const HVX_Vector * restrict v_add = (const HVX_Vector *) add;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+
+ #pragma unroll(2)
+ for (uint32_t k = 0; k < nvec; k++) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf);
+ HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[k]), one_hf);
+ HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 0], scale_v);
+ HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 1], scale_v);
+ HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0), Q6_V_lo_W(ap));
+ HVX_Vector r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1), Q6_V_hi_W(ap));
+#else
+ HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf);
+ HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[k]), one_hf);
+ HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 0], scale_v);
+ HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 1], scale_v);
+ HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0);
+ HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap)));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap)));
+#endif
+ v_dst[k] = rms_clamp_pack_f16(r0, r1, f16_min, f16_max);
+ }
+
+ if (nloe > 0) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf);
+ HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[nvec]), one_hf);
+ HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v);
+ HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0), Q6_V_lo_W(ap));
+ HVX_Vector r1 = Q6_V_vzero();
+ if (nloe > 32) {
+ HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v);
+ r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1), Q6_V_hi_W(ap));
+ }
+#else
+ HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf);
+ HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[nvec]), one_hf);
+ HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v);
+ HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap)));
+ HVX_Vector r1 = Q6_V_vzero();
+ if (nloe > 32) {
+ HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v);
+ HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1);
+ r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap)));
+ }
+#endif
+ HVX_Vector packed = rms_clamp_pack_f16(r0, r1, f16_min, f16_max);
+ hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed);
+ }
+}
+
+static inline void rms_norm_apply_row_mul_add_f16_f16_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) mul;
+ const HVX_Vector * restrict v_add = (const HVX_Vector *) add;
+ HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector scale_qf = Q6_Vqf32_vadd_VsfVsf(scale_v, Q6_V_vzero());
+#endif
+
+ #pragma unroll(2)
+ for (uint32_t k = 0; k < nvec; k++) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[k], v_w[k]);
+ HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(v_add[k], one_hf);
+ HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v), Q6_V_lo_W(ap));
+ HVX_Vector r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v), Q6_V_hi_W(ap));
+#else
+ HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[k], v_w[k]);
+ HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(v_add[k], one_hf);
+ HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf);
+ HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap)));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap)));
+#endif
+ v_dst[k] = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max);
+ }
+
+ if (nloe > 0) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[nvec], v_w[nvec]);
+ HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(v_add[nvec], one_hf);
+ HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v), Q6_V_lo_W(ap));
+ HVX_Vector r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v), Q6_V_hi_W(ap));
+#else
+ HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[nvec], v_w[nvec]);
+ HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(v_add[nvec], one_hf);
+ HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf);
+ HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf);
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap)));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap)));
+#endif
+ HVX_Vector packed = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max);
+ hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed);
+ }
+}
+
+static inline void rms_norm_apply_row_inl_f16_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ (void) mul;
+ (void) add;
+ rms_norm_apply_row_f16(src, dst, n, scale_v);
+}
+
+static inline void rms_norm_apply_row_inl_mul_f16_f32_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ (void) add;
+ rms_norm_apply_row_mul_f16_f32(src, mul, dst, n, scale_v);
+}
+
+static inline void rms_norm_apply_row_inl_mul_f16_f16_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ (void) add;
+ rms_norm_apply_row_mul_f16_f16(src, mul, dst, n, scale_v);
+}
+
+static inline void rms_norm_apply_row_inl_mul_add_f16_f32_f16_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ rms_norm_apply_row_mul_add_f16_f32_f16(src, mul, add, dst, n, scale_v);
+}
+
+static inline void rms_norm_apply_row_inl_mul_add_f16_f16_f16_f16(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ HVX_Vector scale_v) {
+ rms_norm_apply_row_mul_add_f16_f16_f16(src, mul, add, dst, n, scale_v);
+}
+
+static inline void rms_norm_apply_4rows_inl_f16_f16(const uint8_t * restrict src,
+ size_t src_stride,
+ const uint8_t * restrict mul,
+ uint8_t * restrict dst,
+ size_t dst_stride,
+ uint32_t n,
+ HVX_Vector scale_v0,
+ HVX_Vector scale_v1,
+ HVX_Vector scale_v2,
+ HVX_Vector scale_v3) {
+ (void) mul;
+ const uint32_t nvec = n / VLEN_FP16;
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector scale_qf0 = Q6_Vqf32_vadd_VsfVsf(scale_v0, Q6_V_vzero());
+ const HVX_Vector scale_qf1 = Q6_Vqf32_vadd_VsfVsf(scale_v1, Q6_V_vzero());
+ const HVX_Vector scale_qf2 = Q6_Vqf32_vadd_VsfVsf(scale_v2, Q6_V_vzero());
+ const HVX_Vector scale_qf3 = Q6_Vqf32_vadd_VsfVsf(scale_v3, Q6_V_vzero());
+#endif
+
+ const uint8_t * restrict s0 = src;
+ uint8_t * restrict d0 = dst;
+ #pragma clang loop unroll(disable) pipeline(disable)
+ for (uint32_t k = 0; k < nvec; k++) {
+ const uint8_t * restrict s1 = s0 + src_stride;
+ const uint8_t * restrict s2 = s1 + src_stride;
+ const uint8_t * restrict s3 = s2 + src_stride;
+ uint8_t * restrict d1 = d0 + dst_stride;
+ uint8_t * restrict d2 = d1 + dst_stride;
+ uint8_t * restrict d3 = d2 + dst_stride;
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp0 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf);
+ *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp0), scale_v0),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp0), scale_v0), f16_min, f16_max);
+ HVX_VectorPair sp1 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf);
+ *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp1), scale_v1),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp1), scale_v1), f16_min, f16_max);
+ HVX_VectorPair sp2 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf);
+ *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp2), scale_v2),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp2), scale_v2), f16_min, f16_max);
+ HVX_VectorPair sp3 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf);
+ *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp3), scale_v3),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp3), scale_v3), f16_min, f16_max);
+#else
+ HVX_VectorPair sp0 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf);
+ *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp0), scale_qf0)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp0), scale_qf0)), f16_min, f16_max);
+ HVX_VectorPair sp1 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf);
+ *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp1), scale_qf1)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp1), scale_qf1)), f16_min, f16_max);
+ HVX_VectorPair sp2 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf);
+ *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp2), scale_qf2)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp2), scale_qf2)), f16_min, f16_max);
+ HVX_VectorPair sp3 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf);
+ *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp3), scale_qf3)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp3), scale_qf3)), f16_min, f16_max);
+#endif
+ s0 += VLEN;
+ d0 += VLEN;
+ }
+}
+
+static inline void rms_norm_apply_4rows_inl_mul_f16_f32_f16(const uint8_t * restrict src,
+ size_t src_stride,
+ const uint8_t * restrict mul,
+ uint8_t * restrict dst,
+ size_t dst_stride,
+ uint32_t n,
+ HVX_Vector scale_v0,
+ HVX_Vector scale_v1,
+ HVX_Vector scale_v2,
+ HVX_Vector scale_v3) {
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) mul;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f);
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+
+ const uint8_t * restrict s0 = src;
+ uint8_t * restrict d0 = dst;
+ #pragma clang loop unroll(disable) pipeline(disable)
+ for (uint32_t k = 0; k < nvec; k++) {
+ HVX_VectorPair wp = Q6_W_vdeal_VVR(v_w[2 * k + 1], v_w[2 * k + 0], -4);
+ HVX_Vector we = Q6_V_lo_W(wp);
+ HVX_Vector wo = Q6_V_hi_W(wp);
+ const uint8_t * restrict s1 = s0 + src_stride;
+ const uint8_t * restrict s2 = s1 + src_stride;
+ const uint8_t * restrict s3 = s2 + src_stride;
+ uint8_t * restrict d1 = d0 + dst_stride;
+ uint8_t * restrict d2 = d1 + dst_stride;
+ uint8_t * restrict d3 = d2 + dst_stride;
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sp0 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf);
+ *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp0), Q6_Vsf_vmpy_VsfVsf(we, scale_v0)),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp0), Q6_Vsf_vmpy_VsfVsf(wo, scale_v0)), f16_min, f16_max);
+ HVX_VectorPair sp1 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf);
+ *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp1), Q6_Vsf_vmpy_VsfVsf(we, scale_v1)),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp1), Q6_Vsf_vmpy_VsfVsf(wo, scale_v1)), f16_min, f16_max);
+ HVX_VectorPair sp2 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf);
+ *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp2), Q6_Vsf_vmpy_VsfVsf(we, scale_v2)),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp2), Q6_Vsf_vmpy_VsfVsf(wo, scale_v2)), f16_min, f16_max);
+ HVX_VectorPair sp3 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf);
+ *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp3), Q6_Vsf_vmpy_VsfVsf(we, scale_v3)),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp3), Q6_Vsf_vmpy_VsfVsf(wo, scale_v3)), f16_min, f16_max);
+#else
+ HVX_VectorPair sp0 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf);
+ *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp0), Q6_Vqf32_vmpy_VsfVsf(we, scale_v0))),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp0), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v0))), f16_min, f16_max);
+ HVX_VectorPair sp1 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf);
+ *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp1), Q6_Vqf32_vmpy_VsfVsf(we, scale_v1))),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp1), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v1))), f16_min, f16_max);
+ HVX_VectorPair sp2 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf);
+ *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp2), Q6_Vqf32_vmpy_VsfVsf(we, scale_v2))),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp2), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v2))), f16_min, f16_max);
+ HVX_VectorPair sp3 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf);
+ *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp3), Q6_Vqf32_vmpy_VsfVsf(we, scale_v3))),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp3), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v3))), f16_min, f16_max);
+#endif
+ s0 += VLEN;
+ d0 += VLEN;
+ }
+}
+
+static inline void rms_norm_apply_4rows_inl_mul_f16_f16_f16(const uint8_t * restrict src,
+ size_t src_stride,
+ const uint8_t * restrict mul,
+ uint8_t * restrict dst,
+ size_t dst_stride,
+ uint32_t n,
+ HVX_Vector scale_v0,
+ HVX_Vector scale_v1,
+ HVX_Vector scale_v2,
+ HVX_Vector scale_v3) {
+ const HVX_Vector * restrict v_src0 = (const HVX_Vector *) (src + 0 * src_stride);
+ const HVX_Vector * restrict v_src1 = (const HVX_Vector *) (src + 1 * src_stride);
+ const HVX_Vector * restrict v_src2 = (const HVX_Vector *) (src + 2 * src_stride);
+ const HVX_Vector * restrict v_src3 = (const HVX_Vector *) (src + 3 * src_stride);
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) mul;
+ HVX_Vector * restrict v_dst0 = (HVX_Vector *) (dst + 0 * dst_stride);
+ HVX_Vector * restrict v_dst1 = (HVX_Vector *) (dst + 1 * dst_stride);
+ HVX_Vector * restrict v_dst2 = (HVX_Vector *) (dst + 2 * dst_stride);
+ HVX_Vector * restrict v_dst3 = (HVX_Vector *) (dst + 3 * dst_stride);
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f);
+#if __HVX_ARCH__ < 79
+ const HVX_Vector scale_qf0 = Q6_Vqf32_vadd_VsfVsf(scale_v0, Q6_V_vzero());
+ const HVX_Vector scale_qf1 = Q6_Vqf32_vadd_VsfVsf(scale_v1, Q6_V_vzero());
+ const HVX_Vector scale_qf2 = Q6_Vqf32_vadd_VsfVsf(scale_v2, Q6_V_vzero());
+ const HVX_Vector scale_qf3 = Q6_Vqf32_vadd_VsfVsf(scale_v3, Q6_V_vzero());
+#endif
+
+ #pragma clang loop unroll(disable)
+ for (uint32_t k = 0; k < nvec; k++) {
+ HVX_Vector wk = v_w[k];
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sw0 = Q6_Wsf_vmpy_VhfVhf(v_src0[k], wk);
+ HVX_VectorPair sw1 = Q6_Wsf_vmpy_VhfVhf(v_src1[k], wk);
+ v_dst0[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw0), scale_v0),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw0), scale_v0), f16_min, f16_max);
+ v_dst1[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw1), scale_v1),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw1), scale_v1), f16_min, f16_max);
+
+ HVX_VectorPair sw2 = Q6_Wsf_vmpy_VhfVhf(v_src2[k], wk);
+ HVX_VectorPair sw3 = Q6_Wsf_vmpy_VhfVhf(v_src3[k], wk);
+ v_dst2[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw2), scale_v2),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw2), scale_v2), f16_min, f16_max);
+ v_dst3[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw3), scale_v3),
+ Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw3), scale_v3), f16_min, f16_max);
+#else
+ HVX_VectorPair sw0 = Q6_Wqf32_vmpy_VhfVhf(v_src0[k], wk);
+ HVX_VectorPair sw1 = Q6_Wqf32_vmpy_VhfVhf(v_src1[k], wk);
+ v_dst0[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw0), scale_qf0)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw0), scale_qf0)), f16_min, f16_max);
+ v_dst1[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw1), scale_qf1)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw1), scale_qf1)), f16_min, f16_max);
+
+ HVX_VectorPair sw2 = Q6_Wqf32_vmpy_VhfVhf(v_src2[k], wk);
+ HVX_VectorPair sw3 = Q6_Wqf32_vmpy_VhfVhf(v_src3[k], wk);
+ v_dst2[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw2), scale_qf2)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw2), scale_qf2)), f16_min, f16_max);
+ v_dst3[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw3), scale_qf3)),
+ Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw3), scale_qf3)), f16_min, f16_max);
+#endif
+ }
+}
+
+#define DEFINE_RMS_NORM_APPLY_ROW(SFX, HAS_MUL, HAS_ADD, S0_F16, S1_F16, S2_F16, D_F16) \
+ static inline void rms_norm_apply_row_inl_##SFX(const uint8_t * restrict src, \
+ const uint8_t * restrict mul, \
+ const uint8_t * restrict add, \
+ uint8_t * restrict dst, \
+ uint32_t n, \
+ HVX_Vector scale_v) { \
+ (void) mul; \
+ (void) add; \
+ uint32_t i = 0; \
+ for (; i + 64 <= n; i += 64) { \
+ HVX_VectorPair sp = rms_load_pair_f32(src, i, S0_F16); \
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp), scale_v)); \
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp), scale_v)); \
+ if (HAS_MUL) { \
+ HVX_VectorPair wp = rms_load_pair_f32(mul, i, S1_F16); \
+ r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r0, Q6_V_lo_W(wp))); \
+ r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r1, Q6_V_hi_W(wp))); \
+ } \
+ if (HAS_ADD) { \
+ HVX_VectorPair ap = rms_load_pair_f32(add, i, S2_F16); \
+ r0 = hvx_vec_add_f32_f32(r0, Q6_V_lo_W(ap)); \
+ r1 = hvx_vec_add_f32_f32(r1, Q6_V_hi_W(ap)); \
+ } \
+ rms_store_pair_f32(dst, i, r0, r1, D_F16); \
+ } \
+ if (i < n) { \
+ const uint32_t rem = n - i; \
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(rms_load_vec_f32(src, i, S0_F16), scale_v)); \
+ HVX_Vector r1 = Q6_V_vzero(); \
+ if (rem > 32) { \
+ r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(rms_load_vec_f32(src, i + 32, S0_F16), scale_v)); \
+ } \
+ if (HAS_MUL) { \
+ r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r0, rms_load_vec_f32(mul, i, S1_F16))); \
+ if (rem > 32) { \
+ r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r1, rms_load_vec_f32(mul, i + 32, S1_F16))); \
+ } \
+ } \
+ if (HAS_ADD) { \
+ r0 = hvx_vec_add_f32_f32(r0, rms_load_vec_f32(add, i, S2_F16)); \
+ if (rem > 32) { \
+ r1 = hvx_vec_add_f32_f32(r1, rms_load_vec_f32(add, i + 32, S2_F16)); \
+ } \
+ } \
+ rms_store_tail_f32(dst, i, rem, r0, r1, D_F16); \
+ } \
+ }
+
+#define DEFINE_RMS_NORM_APPLY_4ROWS(SFX, HAS_MUL, S0_F16, S1_F16, D_F16) \
+ static inline void rms_norm_apply_4rows_inl_##SFX(const uint8_t * restrict src, \
+ size_t src_stride, \
+ const uint8_t * restrict mul, \
+ uint8_t * restrict dst, \
+ size_t dst_stride, \
+ uint32_t n, \
+ HVX_Vector scale_v0, \
+ HVX_Vector scale_v1, \
+ HVX_Vector scale_v2, \
+ HVX_Vector scale_v3) { \
+ (void) mul; \
+ _Pragma("clang loop unroll(disable) pipeline(disable)") \
+ for (uint32_t i = 0; i < n; i += 64) { \
+ HVX_VectorPair wp = Q6_W_vzero(); \
+ if (HAS_MUL) { \
+ wp = rms_load_pair_f32(mul, i, S1_F16); \
+ } \
+ const uint8_t * restrict s = src; \
+ uint8_t * restrict d = dst; \
+ HVX_VectorPair sp0 = rms_load_pair_f32(s, i, S0_F16); \
+ HVX_Vector r00 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp0), scale_v0)); \
+ HVX_Vector r01 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp0), scale_v0)); \
+ if (HAS_MUL) { \
+ r00 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r00, Q6_V_lo_W(wp))); \
+ r01 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r01, Q6_V_hi_W(wp))); \
+ } \
+ rms_store_pair_f32(d, i, r00, r01, D_F16); \
+ s += src_stride; \
+ d += dst_stride; \
+ HVX_VectorPair sp1 = rms_load_pair_f32(s, i, S0_F16); \
+ HVX_Vector r10 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp1), scale_v1)); \
+ HVX_Vector r11 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp1), scale_v1)); \
+ if (HAS_MUL) { \
+ r10 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r10, Q6_V_lo_W(wp))); \
+ r11 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r11, Q6_V_hi_W(wp))); \
+ } \
+ rms_store_pair_f32(d, i, r10, r11, D_F16); \
+ s += src_stride; \
+ d += dst_stride; \
+ HVX_VectorPair sp2 = rms_load_pair_f32(s, i, S0_F16); \
+ HVX_Vector r20 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp2), scale_v2)); \
+ HVX_Vector r21 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp2), scale_v2)); \
+ if (HAS_MUL) { \
+ r20 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r20, Q6_V_lo_W(wp))); \
+ r21 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r21, Q6_V_hi_W(wp))); \
+ } \
+ rms_store_pair_f32(d, i, r20, r21, D_F16); \
+ s += src_stride; \
+ d += dst_stride; \
+ HVX_VectorPair sp3 = rms_load_pair_f32(s, i, S0_F16); \
+ HVX_Vector r30 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp3), scale_v3)); \
+ HVX_Vector r31 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp3), scale_v3)); \
+ if (HAS_MUL) { \
+ r30 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r30, Q6_V_lo_W(wp))); \
+ r31 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r31, Q6_V_hi_W(wp))); \
+ } \
+ rms_store_pair_f32(d, i, r30, r31, D_F16); \
+ } \
+ }
+
+DEFINE_RMS_NORM_APPLY_ROW(f32_f32, false, false, false, false, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(f32_f16, false, false, false, false, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(f16_f32, false, false, true, false, false, false)
+
+DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f32_f32, true, false, false, false, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f16_f32, true, false, false, true, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f32_f16, true, false, false, false, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f16_f16, true, false, false, true, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_f16_f32_f32, true, false, true, false, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_f16_f16_f32, true, false, true, true, false, false)
+
+DEFINE_RMS_NORM_APPLY_4ROWS(f32_f32, false, false, false, false)
+DEFINE_RMS_NORM_APPLY_4ROWS(f32_f16, false, false, false, true)
+DEFINE_RMS_NORM_APPLY_4ROWS(f16_f32, false, true, false, false)
+
+DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f32_f32, true, false, false, false)
+DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f16_f32, true, false, true, false)
+DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f32_f16, true, false, false, true)
+DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f16_f16, true, false, true, true)
+DEFINE_RMS_NORM_APPLY_4ROWS(mul_f16_f32_f32, true, true, false, false)
+DEFINE_RMS_NORM_APPLY_4ROWS(mul_f16_f16_f32, true, true, true, false)
+
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f32_f32, true, true, false, false, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f32_f16, true, true, false, false, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f16_f32, true, true, false, false, true, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f16_f16, true, true, false, false, true, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f32_f32, true, true, false, true, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f32_f16, true, true, false, true, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f16_f32, true, true, false, true, true, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f16_f16, true, true, false, true, true, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f32_f32_f32, true, true, true, false, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f32_f32_f16, true, true, true, false, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f32_f16_f32, true, true, true, false, true, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f16_f32_f32, true, true, true, true, false, false)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f16_f32_f16, true, true, true, true, false, true)
+DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f16_f16_f32, true, true, true, true, true, false)
+
+#undef DEFINE_RMS_NORM_APPLY_ROW
+#undef DEFINE_RMS_NORM_APPLY_4ROWS
+
+#define DEFINE_RMS_NORM_BLOCK_FNS(SFX, S0_TY) \
+ static __attribute__((noinline)) void rms_norm_apply_tile_row_##SFX(const uint8_t * restrict src, \
+ const uint8_t * restrict mul, \
+ const uint8_t * restrict add, \
+ uint8_t * restrict dst, \
+ uint32_t n, \
+ HVX_Vector scale_v) { \
+ rms_norm_apply_row_inl_##SFX(src, mul, add, dst, n, scale_v); \
+ } \
+ static __attribute__((noinline)) void rms_norm_rows_##SFX(const void * restrict src, \
+ void * restrict dst, \
+ const uint32_t num_rows, \
+ const uint32_t ne0, \
+ const struct htp_unary_context * uctx) { \
+ htp_unary_op_preamble; \
+ float epsilon = 0.f; \
+ float scale = 0.f; \
+ memcpy(&epsilon, &op_params[0], sizeof(float)); \
+ memcpy(&scale, &op_params[1], sizeof(float)); \
+ const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) ne0)); \
+ const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); \
+ const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); \
+ const uint8_t * restrict src_local = (const uint8_t *) src; \
+ uint8_t * restrict dst_local = (uint8_t *) dst; \
+ uint32_t ir = 0; \
+ if ((ne0 & 63u) == 0) { \
+ for (; ir + 4 <= num_rows; ir += 4) { \
+ HVX_Vector scale_v0, scale_v1, scale_v2, scale_v3; \
+ rms_norm_4rows_scale_precomp_##S0_TY(src_local, src0_row_size_aligned, ne0, \
+ inv_ne0_v, eps_v, scale_param_v, \
+ &scale_v0, &scale_v1, &scale_v2, &scale_v3); \
+ rms_norm_apply_4rows_inl_##SFX(src_local, src0_row_size_aligned, NULL, \
+ dst_local, dst_row_size_aligned, ne0, \
+ scale_v0, scale_v1, scale_v2, scale_v3); \
+ src_local += 4 * src0_row_size_aligned; \
+ dst_local += 4 * dst_row_size_aligned; \
+ } \
+ } \
+ for (; ir < num_rows; ir++) { \
+ HVX_Vector scale_v = rms_norm_row_scale_precomp_##S0_TY(src_local, ne0, inv_ne0_v, eps_v, scale_param_v); \
+ rms_norm_apply_row_inl_##SFX(src_local, NULL, NULL, dst_local, ne0, scale_v); \
+ src_local += src0_row_size_aligned; \
+ dst_local += dst_row_size_aligned; \
+ } \
+ }
+
+#define DEFINE_RMS_NORM_MUL_BLOCK_FNS(SFX, S0_TY) \
+ static __attribute__((noinline)) void rms_norm_apply_tile_row_mul_##SFX(const uint8_t * restrict src, \
+ const uint8_t * restrict mul, \
+ const uint8_t * restrict add, \
+ uint8_t * restrict dst, \
+ uint32_t n, \
+ HVX_Vector scale_v) { \
+ rms_norm_apply_row_inl_mul_##SFX(src, mul, add, dst, n, scale_v); \
+ } \
+ static __attribute__((noinline)) void rms_norm_mul_rows_##SFX(const void * restrict src, \
+ const void * restrict mul, \
+ void * restrict dst, \
+ const uint32_t num_rows, \
+ const uint32_t src1_row_start, \
+ const struct htp_unary_context * uctx) { \
+ htp_unary_op_preamble; \
+ const uint32_t ne0 = uctx->nc; \
+ float epsilon = 0.f; \
+ float scale = 0.f; \
+ memcpy(&epsilon, &op_params[0], sizeof(float)); \
+ memcpy(&scale, &op_params[1], sizeof(float)); \
+ const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) ne0)); \
+ const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); \
+ const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); \
+ const size_t mul_stride = uctx->src1_block_stride; \
+ const uint8_t * mul_base = (const uint8_t *) mul; \
+ const uint8_t * mul_end = (uctx->broadcast_src1 && uctx->src1_nrows > 1) \
+ ? (mul_base + (size_t) uctx->src1_nrows * mul_stride) \
+ : NULL; \
+ const uint8_t * restrict src_local = (const uint8_t *) src; \
+ const uint8_t * restrict mul_local = mul_base + (size_t) src1_row_start * mul_stride; \
+ uint8_t * restrict dst_local = (uint8_t *) dst; \
+ uint32_t ir = 0; \
+ if ((ne0 & 63u) == 0 && mul_stride == 0) { \
+ for (; ir + 4 <= num_rows; ir += 4) { \
+ HVX_Vector scale_v0, scale_v1, scale_v2, scale_v3; \
+ rms_norm_4rows_scale_precomp_##S0_TY(src_local, src0_row_size_aligned, ne0, \
+ inv_ne0_v, eps_v, scale_param_v, \
+ &scale_v0, &scale_v1, &scale_v2, &scale_v3); \
+ rms_norm_apply_4rows_inl_mul_##SFX(src_local, src0_row_size_aligned, mul_base, \
+ dst_local, dst_row_size_aligned, ne0, \
+ scale_v0, scale_v1, scale_v2, scale_v3); \
+ src_local += 4 * src0_row_size_aligned; \
+ dst_local += 4 * dst_row_size_aligned; \
+ } \
+ } \
+ for (; ir < num_rows; ir++) { \
+ HVX_Vector scale_v = rms_norm_row_scale_precomp_##S0_TY(src_local, ne0, inv_ne0_v, eps_v, scale_param_v); \
+ rms_norm_apply_row_inl_mul_##SFX(src_local, mul_local, NULL, dst_local, ne0, scale_v); \
+ src_local += src0_row_size_aligned; \
+ dst_local += dst_row_size_aligned; \
+ mul_local += mul_stride; \
+ if (mul_local == mul_end) { \
+ mul_local = mul_base; \
+ } \
+ } \
+ }
+
+#define DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(SFX, S0_TY) \
+ static __attribute__((noinline)) void rms_norm_apply_tile_row_mul_add_##SFX(const uint8_t * restrict src, \
+ const uint8_t * restrict mul, \
+ const uint8_t * restrict add, \
+ uint8_t * restrict dst, \
+ uint32_t n, \
+ HVX_Vector scale_v) { \
+ rms_norm_apply_row_inl_mul_add_##SFX(src, mul, add, dst, n, scale_v); \
+ } \
+ static __attribute__((noinline)) void rms_norm_mul_add_rows_##SFX(const void * restrict src, \
+ const void * restrict mul, \
+ const void * restrict add, \
+ void * restrict dst, \
+ const uint32_t num_rows, \
+ const uint32_t src1_row_start, \
+ const struct htp_unary_context * uctx) { \
+ htp_unary_op_preamble; \
+ const uint32_t ne0 = uctx->nc; \
+ const size_t src2_row_size_aligned = uctx->src2_row_size_aligned; \
+ float epsilon = 0.f; \
+ float scale = 0.f; \
+ memcpy(&epsilon, &op_params[0], sizeof(float)); \
+ memcpy(&scale, &op_params[1], sizeof(float)); \
+ const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) ne0)); \
+ const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); \
+ const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); \
+ const size_t mul_stride = uctx->src1_block_stride; \
+ const uint8_t * mul_base = (const uint8_t *) mul; \
+ const uint8_t * mul_end = (uctx->broadcast_src1 && uctx->src1_nrows > 1) \
+ ? (mul_base + (size_t) uctx->src1_nrows * mul_stride) \
+ : NULL; \
+ const uint8_t * restrict src_local = (const uint8_t *) src; \
+ const uint8_t * restrict mul_local = mul_base + (size_t) src1_row_start * mul_stride; \
+ const uint8_t * restrict add_local = (const uint8_t *) add; \
+ uint8_t * restrict dst_local = (uint8_t *) dst; \
+ for (uint32_t ir = 0; ir < num_rows; ir++) { \
+ HVX_Vector scale_v = rms_norm_row_scale_precomp_##S0_TY(src_local, ne0, inv_ne0_v, eps_v, scale_param_v); \
+ rms_norm_apply_row_inl_mul_add_##SFX(src_local, mul_local, add_local, dst_local, ne0, scale_v); \
+ src_local += src0_row_size_aligned; \
+ add_local += src2_row_size_aligned; \
+ dst_local += dst_row_size_aligned; \
+ mul_local += mul_stride; \
+ if (mul_local == mul_end) { \
+ mul_local = mul_base; \
+ } \
+ } \
+ }
+
+DEFINE_RMS_NORM_BLOCK_FNS(f32_f32, f32)
+DEFINE_RMS_NORM_BLOCK_FNS(f32_f16, f32)
+DEFINE_RMS_NORM_BLOCK_FNS(f16_f32, f16)
+DEFINE_RMS_NORM_BLOCK_FNS(f16_f16, f16)
+
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f32_f32, f32)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f32_f16, f32)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f16_f32, f32)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f16_f16, f32)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f32_f32, f16)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f32_f16, f16)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f16_f32, f16)
+DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f16_f16, f16)
+
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f32_f32, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f32_f16, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f16_f32, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f16_f16, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f32_f32, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f32_f16, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f16_f32, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f16_f16, f32)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f32_f32, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f32_f16, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f16_f32, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f16_f16, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f32_f32, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f32_f16, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f16_f32, f16)
+DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f16_f16, f16)
+
+#undef DEFINE_RMS_NORM_BLOCK_FNS
+#undef DEFINE_RMS_NORM_MUL_BLOCK_FNS
+#undef DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS
+
+static const rms_apply_row_fn_t rms_norm_apply_row_table[2][2] = {
+ { rms_norm_apply_tile_row_f32_f32, rms_norm_apply_tile_row_f32_f16 },
+ { rms_norm_apply_tile_row_f16_f32, rms_norm_apply_tile_row_f16_f16 },
+};
+
+static const rms_apply_row_fn_t rms_norm_mul_apply_row_table[2][2][2] = {
+ {
+ { rms_norm_apply_tile_row_mul_f32_f32_f32, rms_norm_apply_tile_row_mul_f32_f32_f16 },
+ { rms_norm_apply_tile_row_mul_f32_f16_f32, rms_norm_apply_tile_row_mul_f32_f16_f16 },
+ },
+ {
+ { rms_norm_apply_tile_row_mul_f16_f32_f32, rms_norm_apply_tile_row_mul_f16_f32_f16 },
+ { rms_norm_apply_tile_row_mul_f16_f16_f32, rms_norm_apply_tile_row_mul_f16_f16_f16 },
+ },
+};
+
+static const rms_apply_row_fn_t rms_norm_mul_add_apply_row_table[2][2][2][2] = {
+ {
+ {
+ { rms_norm_apply_tile_row_mul_add_f32_f32_f32_f32, rms_norm_apply_tile_row_mul_add_f32_f32_f32_f16 },
+ { rms_norm_apply_tile_row_mul_add_f32_f32_f16_f32, rms_norm_apply_tile_row_mul_add_f32_f32_f16_f16 },
+ },
+ {
+ { rms_norm_apply_tile_row_mul_add_f32_f16_f32_f32, rms_norm_apply_tile_row_mul_add_f32_f16_f32_f16 },
+ { rms_norm_apply_tile_row_mul_add_f32_f16_f16_f32, rms_norm_apply_tile_row_mul_add_f32_f16_f16_f16 },
+ },
+ },
+ {
+ {
+ { rms_norm_apply_tile_row_mul_add_f16_f32_f32_f32, rms_norm_apply_tile_row_mul_add_f16_f32_f32_f16 },
+ { rms_norm_apply_tile_row_mul_add_f16_f32_f16_f32, rms_norm_apply_tile_row_mul_add_f16_f32_f16_f16 },
+ },
+ {
+ { rms_norm_apply_tile_row_mul_add_f16_f16_f32_f32, rms_norm_apply_tile_row_mul_add_f16_f16_f32_f16 },
+ { rms_norm_apply_tile_row_mul_add_f16_f16_f16_f32, rms_norm_apply_tile_row_mul_add_f16_f16_f16_f16 },
+ },
+ },
+};
+
+static const unary_compute_fn_t rms_norm_rows_table[2][2] = {
+ { rms_norm_rows_f32_f32, rms_norm_rows_f32_f16 },
+ { rms_norm_rows_f16_f32, rms_norm_rows_f16_f16 },
+};
+
+static void rms_norm_mul_rows_f16_f32_f16_ne128_bc(const void * restrict src,
+ const void * restrict mul,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t src1_row_start,
+ const struct htp_unary_context * uctx) {
+ (void) src1_row_start;
+ const int32_t * op_params = uctx->octx->op_params;
float epsilon = 0.f;
float scale = 0.f;
memcpy(&epsilon, &op_params[0], sizeof(float));
memcpy(&scale, &op_params[1], sizeof(float));
+ hvx_rms_norm_mul_f16_w32_ne128_bcast_rows((const uint8_t *) src, (const uint8_t *) mul, (uint8_t *) dst,
+ num_rows, uctx->src0_row_size_aligned, uctx->dst_row_size_aligned,
+ epsilon, scale);
+}
+
+static void rms_norm_mul_rows_f16_f32_f16_ne256_bc(const void * restrict src,
+ const void * restrict mul,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t src1_row_start,
+ const struct htp_unary_context * uctx) {
+ (void) src1_row_start;
+ const int32_t * op_params = uctx->octx->op_params;
+ float epsilon = 0.f;
+ float scale = 0.f;
+ memcpy(&epsilon, &op_params[0], sizeof(float));
+ memcpy(&scale, &op_params[1], sizeof(float));
+ hvx_rms_norm_mul_f16_w32_ne256_bcast_rows((const uint8_t *) src, (const uint8_t *) mul, (uint8_t *) dst,
+ num_rows, uctx->src0_row_size_aligned, uctx->dst_row_size_aligned,
+ epsilon, scale);
+}
+
+static const unary_rms_norm_mul_compute_fn_t rms_norm_mul_rows_table[2][2][2] = {
+ {
+ { rms_norm_mul_rows_f32_f32_f32, rms_norm_mul_rows_f32_f32_f16 },
+ { rms_norm_mul_rows_f32_f16_f32, rms_norm_mul_rows_f32_f16_f16 },
+ },
+ {
+ { rms_norm_mul_rows_f16_f32_f32, rms_norm_mul_rows_f16_f32_f16 },
+ { rms_norm_mul_rows_f16_f16_f32, rms_norm_mul_rows_f16_f16_f16 },
+ },
+};
- const uint8_t * restrict w_local = (const uint8_t *) weight;
-
- for (uint32_t ir = 0; ir < num_rows; ir++) {
- const uint8_t * restrict src_local = (const uint8_t *) src + (ir * src0_row_size_aligned);
- const uint8_t * restrict add_local = (const uint8_t *) add + (ir * src0_row_size_aligned);
- uint8_t * restrict dst_local = (uint8_t *) dst + (ir * dst_row_size_aligned);
+static const unary_rms_norm_mul_add_compute_fn_t rms_norm_mul_add_rows_table[2][2][2][2] = {
+ {
+ {
+ { rms_norm_mul_add_rows_f32_f32_f32_f32, rms_norm_mul_add_rows_f32_f32_f32_f16 },
+ { rms_norm_mul_add_rows_f32_f32_f16_f32, rms_norm_mul_add_rows_f32_f32_f16_f16 },
+ },
+ {
+ { rms_norm_mul_add_rows_f32_f16_f32_f32, rms_norm_mul_add_rows_f32_f16_f32_f16 },
+ { rms_norm_mul_add_rows_f32_f16_f16_f32, rms_norm_mul_add_rows_f32_f16_f16_f16 },
+ },
+ },
+ {
+ {
+ { rms_norm_mul_add_rows_f16_f32_f32_f32, rms_norm_mul_add_rows_f16_f32_f32_f16 },
+ { rms_norm_mul_add_rows_f16_f32_f16_f32, rms_norm_mul_add_rows_f16_f32_f16_f16 },
+ },
+ {
+ { rms_norm_mul_add_rows_f16_f16_f32_f32, rms_norm_mul_add_rows_f16_f16_f32_f16 },
+ { rms_norm_mul_add_rows_f16_f16_f16_f32, rms_norm_mul_add_rows_f16_f16_f16_f16 },
+ },
+ },
+};
- hvx_fast_rms_norm_mul_add_f32(src_local, w_local, add_local, dst_local, ne0, epsilon, scale);
- }
+static __attribute__((noinline)) void rms_norm_apply_tile(const uint8_t * restrict src,
+ const uint8_t * restrict mul,
+ const uint8_t * restrict add,
+ uint8_t * restrict dst,
+ uint32_t n,
+ uint32_t ne0,
+ float sum_sq,
+ float epsilon,
+ float scale,
+ const struct htp_unary_context * uctx) {
+ const HVX_Vector scale_v = rms_norm_scale_from_sum_f32(hvx_vec_splat_f32(sum_sq), ne0, epsilon, scale);
+ uctx->rms_apply_row_fn(src, mul, add, dst, n, scale_v);
}
static void norm_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float epsilon = 0.f;
@@ -296,6 +1632,7 @@ static void norm_f32(const void * restrict src,
static void sqr_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -310,6 +1647,7 @@ static void sqr_f32(const void * restrict src,
static void sqrt_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -324,6 +1662,7 @@ static void sqrt_f32(const void * restrict src,
static void scale_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float scale = 0.f;
@@ -342,6 +1681,7 @@ static void scale_f16(const void * restrict src,
static void clamp_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float min = 0.f;
@@ -353,29 +1693,55 @@ static void clamp_f16(const void * restrict src,
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_clamp_scalar_f16(dst_local, src_local, (_Float16) min, (_Float16) max, ne0);
+ hvx_clamp_scalar_f16_aa(dst_local, src_local, (_Float16) min, (_Float16) max, ne0);
}
}
-static void rms_norm_f16(const void * restrict src,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
+static inline void hvx_leaky_relu_scalar_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, float slope, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const HVX_Vector vslope = hvx_vec_splat_f32(slope);
+ const HVX_Vector vzero = Q6_V_vzero();
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[i]);
+ HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_lo_W(f32p), vslope, vzero));
+ HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_hi_W(f32p), vslope, vzero));
+ vdst[i] = hvx_vec_f32_to_f16(lo, hi);
+ }
+ if (nloe) {
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[nvec]);
+ HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_lo_W(f32p), vslope, vzero));
+ HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_hi_W(f32p), vslope, vzero));
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_f32_to_f16(lo, hi));
+ }
+}
+
+static void leaky_relu_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
- float epsilon = 0.f;
- memcpy(&epsilon, op_params, sizeof(float));
+ float negative_slope = 0.f;
+ memcpy(&negative_slope, &op_params[0], sizeof(float));
for (uint32_t ir = 0; ir < num_rows; ir++) {
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_fast_rms_norm_f16((const uint8_t *) src_local, (uint8_t *) dst_local, ne0, epsilon);
+ hvx_leaky_relu_scalar_f16_aa(dst_local, src_local, negative_slope, ne0);
}
}
static void norm_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float epsilon = 0.f;
@@ -392,6 +1758,7 @@ static void norm_f16(const void * restrict src,
static void sqr_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -406,6 +1773,7 @@ static void sqr_f16(const void * restrict src,
static void sqrt_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -420,6 +1788,7 @@ static void sqrt_f16(const void * restrict src,
static void abs_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -434,6 +1803,7 @@ static void abs_f16(const void * restrict src,
static void log_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -448,6 +1818,7 @@ static void log_f16(const void * restrict src,
static void step_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -462,6 +1833,7 @@ static void step_f16(const void * restrict src,
static void ceil_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -476,6 +1848,7 @@ static void ceil_f16(const void * restrict src,
static void sgn_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -490,6 +1863,7 @@ static void sgn_f16(const void * restrict src,
static void l2_norm_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float epsilon = 0.f;
@@ -506,6 +1880,7 @@ static void l2_norm_f16(const void * restrict src,
static void neg_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -517,9 +1892,31 @@ static void neg_f32(const void * restrict src,
}
}
-static void exp_f32(const void * restrict src,
+static inline void unary_neg_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[i]);
+ HVX_Vector lo = hvx_vec_neg_f32(Q6_V_lo_W(f32p));
+ HVX_Vector hi = hvx_vec_neg_f32(Q6_V_hi_W(f32p));
+ vdst[i] = hvx_vec_f32_to_f16(lo, hi);
+ }
+ if (nloe) {
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[nvec]);
+ HVX_Vector lo = hvx_vec_neg_f32(Q6_V_lo_W(f32p));
+ HVX_Vector hi = hvx_vec_neg_f32(Q6_V_hi_W(f32p));
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_f32_to_f16(lo, hi));
+ }
+}
+
+static void neg_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -527,123 +1924,375 @@ static void exp_f32(const void * restrict src,
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_exp_f32(dst_local, src_local, ne0, false);
+ unary_neg_f16_aa(dst_local, src_local, ne0);
}
}
-static void sigmoid_f32(const void * restrict src,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
- htp_unary_op_preamble;
+static __attribute__((noinline)) HVX_Vector unary_vec_exp_f32(HVX_Vector x) {
+ return hvx_vec_exp_f32_guard(x, hvx_vec_splat_f32(88.7228f), hvx_vec_splat_f32(INFINITY));
+}
- for (uint32_t ir = 0; ir < num_rows; ir++) {
- const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
- uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+static inline void unary_exp_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP32;
+ const uint32_t nloe = n % VLEN_FP32;
- hvx_sigmoid_f32_aa(dst_local, src_local, ne0);
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_exp_f32(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_exp_f32(vsrc[nvec]));
}
}
-// silu(x) = x * sigmoid(x)
-static void silu_f32(const void * restrict src,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
+static void exp_f32(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
for (uint32_t ir = 0; ir < num_rows; ir++) {
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_sigmoid_f32_aa(dst_local, src_local, ne0);
- hvx_mul_f32_aaa(dst_local, src_local, dst_local, ne0);
+ unary_exp_f32_aa(dst_local, src_local, ne0);
}
}
-// GELU uses the tanh approximation.
-static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_f32(HVX_Vector x) {
- const HVX_Vector half = hvx_vec_splat_f32(0.5f);
- const HVX_Vector one = hvx_vec_splat_f32(1.0f);
-
- HVX_Vector inner = hvx_vec_mul_f32_f32(x, x);
- inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.044715f));
- inner = hvx_vec_add_f32_f32(inner, one);
- inner = hvx_vec_mul_f32_f32(inner, x);
- inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.7978845608028654f));
-
- return hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(half, x),
- hvx_vec_add_f32_f32(one, hvx_vec_tanh_f32(inner)));
+static __attribute__((noinline)) HVX_Vector unary_vec_exp_f16(HVX_Vector v) {
+ const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f);
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(v);
+ HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_exp_f32(Q6_Vsf_vmin_VsfVsf(Q6_V_lo_W(f32p), max_exp)));
+ HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_exp_f32(Q6_Vsf_vmin_VsfVsf(Q6_V_hi_W(f32p), max_exp)));
+ return hvx_vec_f32_to_f16(lo, hi);
}
-static inline void hvx_gelu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
- assert((unsigned long) dst % 128 == 0);
- assert((unsigned long) src % 128 == 0);
-
- HVX_Vector * restrict vdst = (HVX_Vector *) dst;
- HVX_Vector * restrict vsrc = (HVX_Vector *) src;
+static inline void hvx_exp_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
- const uint32_t nvec = n / VLEN_FP32;
- const uint32_t nloe = n % VLEN_FP32;
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
- uint32_t i = 0;
- _Pragma("unroll(4)")
- for (; i < nvec; i++) {
- vdst[i] = hvx_vec_gelu_f32(vsrc[i]);
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_exp_f16(vsrc[i]);
}
if (nloe) {
- hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_f32(vsrc[i]));
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), unary_vec_exp_f16(vsrc[nvec]));
}
}
-// GELU_QUICK uses x * sigmoid(1.702 * x).
-static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_quick_f32(HVX_Vector x) {
- const HVX_Vector one = hvx_vec_splat_f32(1.0f);
- const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f);
- const HVX_Vector min_exp = hvx_vec_splat_f32(-87.0f);
- const HVX_Vector scaled = hvx_vec_mul_f32_f32(x, hvx_vec_splat_f32(1.702f));
- const HVX_Vector sigmoid = hvx_vec_fast_sigmoid_f32_guard(scaled, one, max_exp, min_exp);
+static void exp_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
- return hvx_vec_mul_f32_f32(x, sigmoid);
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_exp_f16_aa(dst_local, src_local, ne0);
+ }
}
-static inline void hvx_gelu_quick_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
- assert((unsigned long) dst % 128 == 0);
- assert((unsigned long) src % 128 == 0);
+static __attribute__((noinline)) HVX_Vector unary_vec_sigmoid_f32(HVX_Vector x) {
+ return hvx_vec_sigmoid_f32(x);
+}
- HVX_Vector * restrict vdst = (HVX_Vector *) dst;
- HVX_Vector * restrict vsrc = (HVX_Vector *) src;
+static inline void unary_sigmoid_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
const uint32_t nvec = n / VLEN_FP32;
const uint32_t nloe = n % VLEN_FP32;
- uint32_t i = 0;
- _Pragma("unroll(4)")
- for (; i < nvec; i++) {
- vdst[i] = hvx_vec_gelu_quick_f32(vsrc[i]);
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_sigmoid_f32(vsrc[i]);
}
if (nloe) {
- hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_quick_f32(vsrc[i]));
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_sigmoid_f32(vsrc[nvec]));
}
}
-static void gelu_f32(const void * restrict src,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
+static void sigmoid_f32(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
for (uint32_t ir = 0; ir < num_rows; ir++) {
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_gelu_f32_aa(dst_local, src_local, ne0);
+ unary_sigmoid_f32_aa(dst_local, src_local, ne0);
}
}
-static void gelu_quick_f32(const void * restrict src,
+static void sigmoid_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_sigmoid_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
+static __attribute__((noinline)) HVX_Vector unary_vec_silu_f32(HVX_Vector x) {
+ return hvx_vec_silu_f32(x);
+}
+
+static inline void unary_silu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP32;
+ const uint32_t nloe = n % VLEN_FP32;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_silu_f32(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_silu_f32(vsrc[nvec]));
+ }
+}
+
+// silu(x) = x * sigmoid(x)
+static void silu_f32(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ unary_silu_f32_aa(dst_local, src_local, ne0);
+ }
+}
+
+static inline HVX_Vector hvx_vec_silu_f16(HVX_Vector x) {
+ return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(x));
+}
+
+static inline void hvx_silu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ _Pragma("clang loop unroll(disable)")
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = hvx_vec_silu_f16(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_silu_f16(vsrc[nvec]));
+ }
+}
+
+static void silu_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_silu_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
+// GELU uses the tanh approximation.
+static inline HVX_Vector hvx_vec_gelu_f32_inline(HVX_Vector x) {
+ const HVX_Vector half = hvx_vec_splat_f32(0.5f);
+ const HVX_Vector one = hvx_vec_splat_f32(1.0f);
+
+ HVX_Vector inner = hvx_vec_mul_f32_f32(x, x);
+ inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.044715f));
+ inner = hvx_vec_add_f32_f32(inner, one);
+ inner = hvx_vec_mul_f32_f32(inner, x);
+ inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.7978845608028654f));
+
+ return hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(half, x),
+ hvx_vec_add_f32_f32(one, hvx_vec_tanh_f32(inner)));
+}
+
+static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_f32(HVX_Vector x) {
+ return hvx_vec_gelu_f32_inline(x);
+}
+
+static inline void hvx_gelu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ assert((unsigned long) dst % 128 == 0);
+ assert((unsigned long) src % 128 == 0);
+
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+ HVX_Vector * restrict vsrc = (HVX_Vector *) src;
+
+ const uint32_t nvec = n / VLEN_FP32;
+ const uint32_t nloe = n % VLEN_FP32;
+
+ uint32_t i = 0;
+ for (; i < nvec; i++) {
+ vdst[i] = hvx_vec_gelu_f32(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_f32(vsrc[i]));
+ }
+}
+
+static inline HVX_Vector hvx_vec_gelu_f16(HVX_Vector x) {
+ const HVX_Vector v_coef_a = hvx_vec_splat_f16(0.044715f);
+ const HVX_Vector v_two_sqrt_2_pi = hvx_vec_splat_f16(1.5957691216057308f);
+ const HVX_Vector v_one = hvx_vec_splat_f16(1.0f);
+
+ HVX_Vector x2 = hvx_vec_mul_f16_f16(x, x);
+ HVX_Vector coef = hvx_vec_add_f16_f16(hvx_vec_mul_f16_f16(x2, v_coef_a), v_one);
+ HVX_Vector y2 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x, coef), v_two_sqrt_2_pi);
+ return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(y2));
+}
+
+static inline void hvx_gelu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ _Pragma("unroll(2)")
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = hvx_vec_gelu_f16(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_gelu_f16(vsrc[nvec]));
+ }
+}
+
+// GELU_QUICK uses x * sigmoid(1.702 * x).
+static inline HVX_Vector hvx_vec_gelu_quick_f32_inline(HVX_Vector x) {
+ const HVX_Vector scaled = hvx_vec_mul_f32_f32(x, hvx_vec_splat_f32(1.702f));
+ const HVX_Vector sigmoid = hvx_vec_sigmoid_f32(scaled);
+
+ return hvx_vec_mul_f32_f32(x, sigmoid);
+}
+
+static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_quick_f32(HVX_Vector x) {
+ return hvx_vec_gelu_quick_f32_inline(x);
+}
+
+static inline void hvx_gelu_quick_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ assert((unsigned long) dst % 128 == 0);
+ assert((unsigned long) src % 128 == 0);
+
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+ HVX_Vector * restrict vsrc = (HVX_Vector *) src;
+
+ const uint32_t nvec = n / VLEN_FP32;
+ const uint32_t nloe = n % VLEN_FP32;
+
+ uint32_t i = 0;
+ for (; i < nvec; i++) {
+ vdst[i] = hvx_vec_gelu_quick_f32(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_quick_f32(vsrc[i]));
+ }
+}
+
+static inline HVX_Vector hvx_vec_gelu_quick_f16(HVX_Vector x) {
+ const HVX_Vector v_scale = hvx_vec_splat_f16(1.702f);
+ HVX_Vector scaled = hvx_vec_mul_f16_f16(x, v_scale);
+ return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(scaled));
+}
+
+static inline void hvx_gelu_quick_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ _Pragma("clang loop pipeline(disable) unroll(disable)")
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = hvx_vec_gelu_quick_f16(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_gelu_quick_f16(vsrc[nvec]));
+ }
+}
+
+static __attribute__((noinline)) HVX_Vector unary_vec_gelu_erf_f16(HVX_Vector v) {
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(v);
+ HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_gelu_erf_f32(Q6_V_lo_W(f32p)));
+ HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_gelu_erf_f32(Q6_V_hi_W(f32p)));
+ return hvx_vec_f32_to_f16(lo, hi);
+}
+
+static inline void hvx_gelu_erf_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_gelu_erf_f16(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), unary_vec_gelu_erf_f16(vsrc[nvec]));
+ }
+}
+
+static void gelu_f32(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_gelu_f32_aa(dst_local, src_local, ne0);
+ }
+}
+
+static void gelu_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_gelu_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
+static void gelu_quick_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -655,9 +2304,25 @@ static void gelu_quick_f32(const void * restrict src,
}
}
+static void gelu_quick_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_gelu_quick_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
static void gelu_erf_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -669,12 +2334,28 @@ static void gelu_erf_f32(const void * restrict src,
}
}
+static void gelu_erf_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *) src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *) dst + (ir * dst_row_size_aligned);
+
+ hvx_gelu_erf_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
static void tri_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
const uint32_t ir,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
+ const uint32_t ne0 = uctx->nc;
const int32_t ttype = op_params[0];
const HVX_Vector zero = hvx_vec_splat_f32(0.0f);
const uint32_t nvec = ne0 / VLEN_FP32;
@@ -757,38 +2438,62 @@ static void tri_f32(const void * restrict src,
// softplus(x) = log(1 + exp(x))
// Match CPU reference: return x for x > 20 to avoid overflow.
+static inline HVX_Vector hvx_vec_softplus_f32_inline(HVX_Vector x) {
+ const HVX_Vector twenty = hvx_vec_splat_f32(20.0f);
+ const HVX_Vector one = hvx_vec_splat_f32(1.0f);
+
+ HVX_VectorPred pred_gt20 = Q6_Q_vcmp_gt_VsfVsf(x, twenty);
+ HVX_Vector expx = hvx_vec_exp_f32(x);
+ HVX_Vector logv = hvx_vec_log_f32(hvx_vec_add_f32_f32(one, expx));
+ return Q6_V_vmux_QVV(pred_gt20, x, logv);
+}
+
+static __attribute__((noinline)) HVX_Vector hvx_vec_softplus_f32(HVX_Vector x) {
+ return hvx_vec_softplus_f32_inline(x);
+}
+
static inline void hvx_softplus_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
const HVX_Vector * restrict v_src = (const HVX_Vector *) src;
HVX_Vector * restrict v_dst = (HVX_Vector *) dst;
- const HVX_Vector twenty = hvx_vec_splat_f32(20.0f);
- const HVX_Vector one = hvx_vec_splat_f32(1.0f);
-
const uint32_t nvec = n / VLEN_FP32;
const uint32_t nloe = n % VLEN_FP32;
- #pragma unroll(4)
for (uint32_t i = 0; i < nvec; i++) {
- HVX_Vector x = v_src[i];
- HVX_VectorPred pred_gt20 = Q6_Q_vcmp_gt_VsfVsf(x, twenty);
- HVX_Vector expx = hvx_vec_exp_f32(x);
- HVX_Vector logv = hvx_vec_log_f32(hvx_vec_add_f32_f32(one, expx));
- v_dst[i] = Q6_V_vmux_QVV(pred_gt20, x, logv);
+ v_dst[i] = hvx_vec_softplus_f32(v_src[i]);
}
if (nloe > 0) {
- HVX_Vector x = v_src[nvec];
- HVX_VectorPred pred_gt20 = Q6_Q_vcmp_gt_VsfVsf(x, twenty);
- HVX_Vector expx = hvx_vec_exp_f32(x);
- HVX_Vector logv = hvx_vec_log_f32(hvx_vec_add_f32_f32(one, expx));
- HVX_Vector sp = Q6_V_vmux_QVV(pred_gt20, x, logv);
- hvx_vec_store_a((void *) &v_dst[nvec], nloe * sizeof(float), sp);
+ hvx_vec_store_a((void *) &v_dst[nvec], nloe * sizeof(float), hvx_vec_softplus_f32(v_src[nvec]));
+ }
+}
+
+static __attribute__((noinline)) HVX_Vector unary_vec_softplus_f16(HVX_Vector v) {
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32(v);
+ HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_softplus_f32_inline(Q6_V_lo_W(f32p)));
+ HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_softplus_f32_inline(Q6_V_hi_W(f32p)));
+ return hvx_vec_f32_to_f16(lo, hi);
+}
+
+static inline void hvx_softplus_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_softplus_f16(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), unary_vec_softplus_f16(vsrc[nvec]));
}
}
static void softplus_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -800,9 +2505,25 @@ static void softplus_f32(const void * restrict src,
}
}
+static void softplus_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_softplus_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
static void l2_norm_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
float epsilon = 0.f;
@@ -926,6 +2647,7 @@ static inline void hvx_fwht_row_f16(const uint8_t * restrict src, uint8_t * rest
static void hadamard_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
const HVX_Vector v_scale = hvx_vec_splat_f32(1.0f / sqrtf((float) ne0));
@@ -941,6 +2663,7 @@ static void hadamard_f32(const void * restrict src,
static void hadamard_f16(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
const HVX_Vector v_scale = hvx_vec_splat_f32(1.0f / sqrtf((float) ne0));
@@ -953,9 +2676,29 @@ static void hadamard_f16(const void * restrict src,
}
}
+static __attribute__((noinline)) HVX_Vector unary_vec_tanh_f32(HVX_Vector x) {
+ return hvx_vec_tanh_f32(x);
+}
+
+static inline void unary_tanh_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP32;
+ const uint32_t nloe = n % VLEN_FP32;
+
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = unary_vec_tanh_f32(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_tanh_f32(vsrc[nvec]));
+ }
+}
+
static void tanh_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -963,15 +2706,216 @@ static void tanh_f32(const void * restrict src,
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_tanh_f32_aa(dst_local, src_local, ne0);
+ unary_tanh_f32_aa(dst_local, src_local, ne0);
}
}
-static void abs_f32(const void * restrict src,
- void * restrict dst,
- const uint32_t num_rows,
- const struct htp_unary_context * uctx) {
- htp_unary_op_preamble;
+static inline void unary_tanh_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ _Pragma("clang loop unroll(disable)")
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = hvx_vec_tanh_f16(vsrc[i]);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_tanh_f16(vsrc[nvec]));
+ }
+}
+
+static void tanh_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ unary_tanh_f16_aa(dst_local, src_local, ne0);
+ }
+}
+
+static inline HVX_Vector hvx_vec_exp_clamped_f32(HVX_Vector x) {
+ return hvx_vec_exp_f32(Q6_Vsf_vmin_VsfVsf(x, hvx_vec_splat_f32(88.0f)));
+}
+
+static inline HVX_Vector hvx_vec_clamp_sig_f16_f32(HVX_Vector x) {
+ const HVX_Vector vmax = hvx_vec_splat_f32(24.0f);
+ const HVX_Vector vmin = hvx_vec_splat_f32(-24.0f);
+ return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, vmin), vmax);
+}
+
+static inline void hvx_vec_sigmoid_pair_f16_f32(HVX_Vector u_lo,
+ HVX_Vector u_hi,
+ HVX_Vector * restrict y_lo,
+ HVX_Vector * restrict y_hi) {
+ HVX_Vector u_f16 = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_sig_f16_f32(u_lo), hvx_vec_clamp_sig_f16_f32(u_hi));
+ HVX_Vector s_f16 = hvx_vec_fast_sigmoid_f16(u_f16);
+ HVX_VectorPair sp = hvx_vec_f16_to_f32_shuff(s_f16);
+ *y_lo = Q6_V_lo_W(sp);
+ *y_hi = Q6_V_hi_W(sp);
+}
+
+static inline void hvx_vec_silu_pair_f16_f32(HVX_Vector u_lo,
+ HVX_Vector u_hi,
+ HVX_Vector * restrict y_lo,
+ HVX_Vector * restrict y_hi) {
+ HVX_Vector u_f16 = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_sig_f16_f32(u_lo), hvx_vec_clamp_sig_f16_f32(u_hi));
+ HVX_Vector s_f16 = hvx_vec_fast_sigmoid_f16(u_f16);
+ HVX_VectorPair sp = hvx_vec_f16_to_f32_shuff(s_f16);
+ *y_lo = hvx_vec_mul_f32_f32(u_lo, Q6_V_lo_W(sp));
+ *y_hi = hvx_vec_mul_f32_f32(u_hi, Q6_V_hi_W(sp));
+}
+
+static inline void hvx_vec_gelu_quick_pair_f16_f32(HVX_Vector u_lo,
+ HVX_Vector u_hi,
+ HVX_Vector * restrict y_lo,
+ HVX_Vector * restrict y_hi) {
+ const HVX_Vector c_1702 = hvx_vec_splat_f32(1.702f);
+ HVX_Vector in_lo = hvx_vec_clamp_sig_f16_f32(hvx_vec_mul_f32_f32(u_lo, c_1702));
+ HVX_Vector in_hi = hvx_vec_clamp_sig_f16_f32(hvx_vec_mul_f32_f32(u_hi, c_1702));
+ HVX_Vector s_f16 = hvx_vec_fast_sigmoid_f16(hvx_vec_f32_to_f16_shuff(in_lo, in_hi));
+ HVX_VectorPair sp = hvx_vec_f16_to_f32_shuff(s_f16);
+ *y_lo = hvx_vec_mul_f32_f32(u_lo, Q6_V_lo_W(sp));
+ *y_hi = hvx_vec_mul_f32_f32(u_hi, Q6_V_hi_W(sp));
+}
+
+#define DEFINE_UNARY_SCALE_BIAS_FNS_EX(NAME, VEC_ATTR, VEC_FN, PAIR_F16_FN) \
+ static VEC_ATTR HVX_Vector unary_vec_##NAME##_scale_bias_f32( \
+ HVX_Vector x, \
+ HVX_Vector v_in_s, \
+ HVX_Vector v_in_b, \
+ HVX_Vector v_out_s, \
+ HVX_Vector v_out_b \
+ ) { \
+ HVX_Vector u = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x, v_in_s), v_in_b); \
+ HVX_Vector y = VEC_FN(u); \
+ return hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(y, v_out_s), v_out_b); \
+ } \
+ static inline HVX_Vector unary_vec_##NAME##_scale_bias_f16( \
+ HVX_Vector v, \
+ HVX_Vector v_in_s, \
+ HVX_Vector v_in_b, \
+ HVX_Vector v_out_s, \
+ HVX_Vector v_out_b \
+ ) { \
+ HVX_VectorPair f32p = hvx_vec_f16_to_f32_shuff(v); \
+ HVX_Vector u_lo = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_lo_W(f32p), v_in_s), v_in_b); \
+ HVX_Vector u_hi = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_hi_W(f32p), v_in_s), v_in_b); \
+ HVX_Vector y_lo; \
+ HVX_Vector y_hi; \
+ PAIR_F16_FN(u_lo, u_hi, &y_lo, &y_hi); \
+ HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(y_lo, v_out_s), v_out_b)); \
+ HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(y_hi, v_out_s), v_out_b)); \
+ return hvx_vec_f32_to_f16_shuff(lo, hi); \
+ } \
+ static void NAME##_scale_bias_f32(const void * restrict src, \
+ void * restrict dst, \
+ const uint32_t num_rows, \
+ const uint32_t ne0, \
+ const struct htp_unary_context * uctx) { \
+ const struct htp_unary_kernel_params * kp = uctx->kparams; \
+ const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \
+ const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; \
+ const HVX_Vector v_in_s = hvx_vec_splat_f32(kp->in_scale); \
+ const HVX_Vector v_in_b = hvx_vec_splat_f32(kp->in_bias); \
+ const HVX_Vector v_out_s = hvx_vec_splat_f32(kp->out_scale); \
+ const HVX_Vector v_out_b = hvx_vec_splat_f32(kp->out_bias); \
+ const uint32_t nvec = ne0 / VLEN_FP32; \
+ const uint32_t nloe = ne0 % VLEN_FP32; \
+ if (nloe == 0) { \
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ const uint32_t total_vec = num_rows * nvec; \
+ _Pragma("clang loop pipeline(disable) unroll(disable)") \
+ for (uint32_t i = 0; i < total_vec; i++) { \
+ vdst[i] = unary_vec_##NAME##_scale_bias_f32(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \
+ } \
+ return; \
+ } \
+ for (uint32_t ir = 0; ir < num_rows; ir++) { \
+ const HVX_Vector * restrict vsrc = \
+ (const HVX_Vector *) ((const uint8_t *) src + ir * src0_row_size_aligned); \
+ HVX_Vector * restrict vdst = (HVX_Vector *) ((uint8_t *) dst + ir * dst_row_size_aligned); \
+ _Pragma("clang loop pipeline(disable) unroll(disable)") \
+ for (uint32_t i = 0; i < nvec; i++) { \
+ vdst[i] = unary_vec_##NAME##_scale_bias_f32(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \
+ } \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), \
+ unary_vec_##NAME##_scale_bias_f32(vsrc[nvec], v_in_s, v_in_b, v_out_s, v_out_b)); \
+ } \
+ } \
+ static void NAME##_scale_bias_f16(const void * restrict src, \
+ void * restrict dst, \
+ const uint32_t num_rows, \
+ const uint32_t ne0, \
+ const struct htp_unary_context * uctx) { \
+ const struct htp_unary_kernel_params * kp = uctx->kparams; \
+ const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \
+ const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; \
+ const HVX_Vector v_in_s = hvx_vec_splat_f32(kp->in_scale); \
+ const HVX_Vector v_in_b = hvx_vec_splat_f32(kp->in_bias); \
+ const HVX_Vector v_out_s = hvx_vec_splat_f32(kp->out_scale); \
+ const HVX_Vector v_out_b = hvx_vec_splat_f32(kp->out_bias); \
+ const uint32_t nvec = ne0 / VLEN_FP16; \
+ const uint32_t nloe = ne0 % VLEN_FP16; \
+ if (nloe == 0) { \
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; \
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst; \
+ const uint32_t total_vec = num_rows * nvec; \
+ _Pragma("clang loop pipeline(disable) unroll(disable)") \
+ for (uint32_t i = 0; i < total_vec; i++) { \
+ vdst[i] = unary_vec_##NAME##_scale_bias_f16(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \
+ } \
+ return; \
+ } \
+ for (uint32_t ir = 0; ir < num_rows; ir++) { \
+ const HVX_Vector * restrict vsrc = \
+ (const HVX_Vector *) ((const uint8_t *) src + ir * src0_row_size_aligned); \
+ HVX_Vector * restrict vdst = (HVX_Vector *) ((uint8_t *) dst + ir * dst_row_size_aligned); \
+ _Pragma("clang loop pipeline(disable) unroll(disable)") \
+ for (uint32_t i = 0; i < nvec; i++) { \
+ vdst[i] = unary_vec_##NAME##_scale_bias_f16(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \
+ } \
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), \
+ unary_vec_##NAME##_scale_bias_f16(vsrc[nvec], v_in_s, v_in_b, v_out_s, v_out_b)); \
+ } \
+ }
+
+#define DEFINE_UNARY_SCALE_BIAS_FNS(NAME, F32_ATTR, F16_HELPER_ATTR, VEC_FN) \
+ static F16_HELPER_ATTR HVX_Vector hvx_vec_##NAME##_f32_helper(HVX_Vector u) { \
+ return VEC_FN(u); \
+ } \
+ static inline void hvx_vec_##NAME##_pair_f32(HVX_Vector u_lo, \
+ HVX_Vector u_hi, \
+ HVX_Vector * restrict y_lo, \
+ HVX_Vector * restrict y_hi) { \
+ *y_lo = hvx_vec_##NAME##_f32_helper(u_lo); \
+ *y_hi = hvx_vec_##NAME##_f32_helper(u_hi); \
+ } \
+ DEFINE_UNARY_SCALE_BIAS_FNS_EX(NAME, F32_ATTR, VEC_FN, hvx_vec_##NAME##_pair_f32)
+
+DEFINE_UNARY_SCALE_BIAS_FNS(exp, __attribute__((noinline)), __attribute__((noinline)), hvx_vec_exp_clamped_f32)
+DEFINE_UNARY_SCALE_BIAS_FNS_EX(sigmoid, inline, hvx_vec_sigmoid_f32, hvx_vec_sigmoid_pair_f16_f32)
+DEFINE_UNARY_SCALE_BIAS_FNS_EX(silu, inline, hvx_vec_silu_f32, hvx_vec_silu_pair_f16_f32)
+DEFINE_UNARY_SCALE_BIAS_FNS(gelu, inline, __attribute__((noinline)), hvx_vec_gelu_f32_inline)
+DEFINE_UNARY_SCALE_BIAS_FNS_EX(gelu_quick, inline, hvx_vec_gelu_quick_f32_inline, hvx_vec_gelu_quick_pair_f16_f32)
+DEFINE_UNARY_SCALE_BIAS_FNS(gelu_erf, __attribute__((noinline)), __attribute__((noinline)), hvx_vec_gelu_erf_f32)
+DEFINE_UNARY_SCALE_BIAS_FNS(softplus, __attribute__((noinline)), __attribute__((noinline)), hvx_vec_softplus_f32_inline)
+DEFINE_UNARY_SCALE_BIAS_FNS(tanh, inline, __attribute__((noinline)), hvx_vec_tanh_f32)
+
+static void abs_f32(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
for (uint32_t ir = 0; ir < num_rows; ir++) {
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
@@ -984,6 +2928,40 @@ static void abs_f32(const void * restrict src,
static void relu_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
+ const struct htp_unary_context * uctx) {
+ htp_unary_op_preamble;
+
+ for (uint32_t ir = 0; ir < num_rows; ir++) {
+ const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
+ uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
+
+ hvx_max_scalar_f32_aa(dst_local, src_local, 0.0f, ne0);
+ }
+}
+
+static inline void hvx_relu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) {
+ const HVX_Vector * restrict vsrc = (const HVX_Vector *) src;
+ HVX_Vector * restrict vdst = (HVX_Vector *) dst;
+
+ const HVX_Vector zero = Q6_V_vzero();
+
+ const uint32_t nvec = n / VLEN_FP16;
+ const uint32_t nloe = n % VLEN_FP16;
+
+ _Pragma("unroll(4)")
+ for (uint32_t i = 0; i < nvec; i++) {
+ vdst[i] = Q6_Vhf_vmax_VhfVhf(vsrc[i], zero);
+ }
+ if (nloe) {
+ hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), Q6_Vhf_vmax_VhfVhf(vsrc[nvec], zero));
+ }
+}
+
+static void relu_f16(const void * restrict src,
+ void * restrict dst,
+ const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -991,13 +2969,14 @@ static void relu_f32(const void * restrict src,
const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned);
uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned);
- hvx_max_scalar_f32(dst_local, src_local, 0.0f, ne0);
+ hvx_relu_f16_aa(dst_local, src_local, ne0);
}
}
static void step_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -1012,6 +2991,7 @@ static void step_f32(const void * restrict src,
static void ceil_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -1026,6 +3006,7 @@ static void ceil_f32(const void * restrict src,
static void sgn_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -1040,6 +3021,7 @@ static void sgn_f32(const void * restrict src,
static void log_f32(const void * restrict src,
void * restrict dst,
const uint32_t num_rows,
+ const uint32_t ne0,
const struct htp_unary_context * uctx) {
htp_unary_op_preamble;
@@ -1051,115 +3033,6 @@ static void log_f32(const void * restrict src,
}
}
-#// Pointwise unary ops on one column tile in VTCM.
-static void tile_scale_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- float scale = 0.f;
- float bias = 0.f;
- memcpy(&scale, &uctx->octx->op_params[0], sizeof(float));
- memcpy(&bias, &uctx->octx->op_params[1], sizeof(float));
- hvx_scale_offset_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw, scale, bias);
-}
-
-static void tile_clamp_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- float min = 0.f;
- float max = 0.f;
- memcpy(&min, &uctx->octx->op_params[0], sizeof(float));
- memcpy(&max, &uctx->octx->op_params[1], sizeof(float));
- hvx_clamp_scalar_f32((uint8_t *) dst, (const uint8_t *) src, min, max, tw);
-}
-
-static void tile_leaky_relu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- float negative_slope = 0.f;
- memcpy(&negative_slope, &uctx->octx->op_params[0], sizeof(float));
- hvx_leaky_relu_scalar_f32((uint8_t *) dst, (const uint8_t *) src, negative_slope, tw);
-}
-
-static void tile_sqr_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_sqr_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_sqrt_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_sqrt_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_neg_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_scale_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw, -1.0f);
-}
-
-static void tile_exp_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_exp_f32((uint8_t *) dst, (const uint8_t *) src, tw, false);
-}
-
-static void tile_sigmoid_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_sigmoid_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_silu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_sigmoid_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
- hvx_mul_f32_aaa((uint8_t *) dst, (const uint8_t *) src, (uint8_t *) dst, tw);
-}
-
-static void tile_gelu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_gelu_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_gelu_quick_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_gelu_quick_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_gelu_erf_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_gelu_erf_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_softplus_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_softplus_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_tanh_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_tanh_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_abs_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_abs_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_log_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_log_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_relu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_max_scalar_f32((uint8_t *) dst, (const uint8_t *) src, 0.0f, tw);
-}
-
-static void tile_step_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_step_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_ceil_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_ceil_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
-static void tile_sgn_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) {
- (void) uctx;
- hvx_sgn_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw);
-}
-
static void tri_apply_tile_f32(const void * restrict src, void * restrict dst,
uint32_t tile_elems, uint32_t col_start, uint32_t i01,
uint32_t ne0, int32_t ttype) {
@@ -1232,239 +3105,308 @@ static void tri_apply_tile_f32(const void * restrict src, void * restrict dst,
}
}
-// 1. Standard row-block unary task (F32 and F16).
-static void unary_thread_row_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- (void) nth;
- const struct htp_unary_context * uctx = (const struct htp_unary_context *) data;
- struct htp_ops_context * octx = uctx->octx;
- const struct htp_tensor * src = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
- htp_unary_preamble;
-
- const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx;
- const size_t src0_data_row_size = uctx->src0_data_row_size;
- const size_t dst_data_row_size = uctx->dst_data_row_size;
- const size_t src0_row_size_aligned = uctx->src0_row_size_aligned;
- const size_t dst_row_size_aligned = uctx->dst_row_size_aligned;
-
- const uint32_t src0_nrows = uctx->src0_nrows;
- const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows);
+struct unary_row_pipe_state {
+ const struct htp_unary_context * uctx;
+ dma_addr_t data_src0;
+ dma_addr_t data_src1;
+ dma_addr_t data_src2;
+ dma_addr_t data_dst;
+ uint8_t * src1_vtcm_bc;
+ uint32_t ne0, ne01, ne02;
+ uint32_t nb01, nb02, nb03;
+ uint32_t nb11, nb12, nb13;
+ uint32_t nb21, nb22, nb23;
+ uint32_t nb1;
+ uint32_t block;
+ bool src0_contig;
+ bool src1_contig;
+ bool block_contig;
+ bool src0_slice_dma;
+ uint32_t ir;
+ uint32_t ir_end;
+};
- if (src0_start_row >= src0_end_row) {
- return;
+static bool unary_row_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ if (s->ir >= s->ir_end) {
+ return false;
}
+ const uint32_t block_size = unary_block_size(s->ir, s->ir_end, s->block, s->block_contig, s->src0_slice_dma,
+ s->ne01, &s->uctx->kparams->div_ne01);
+ task->row = s->ir;
+ task->off = 0;
+ task->len = block_size;
+ task->aux = 0;
+ s->ir += block_size;
+ return true;
+}
- const dma_addr_t data_src = uctx->data_src0;
- const dma_addr_t data_dst = uctx->data_dst;
+static void unary_row_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
+ unary_push_src0_dma(dma_q, (uint8_t *) in_spad, s->data_src0,
+ task->row, task->len, s->src0_contig, s->src0_slice_dma, s->ne01, s->ne02,
+ &uctx->kparams->div_ne01, &uctx->kparams->div_ne02, &uctx->kparams->div_ne012,
+ s->nb01, s->nb02, s->nb03, uctx->src0_row_size_aligned, uctx->src0_data_row_size);
+}
- uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
- uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+static void unary_row_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
+ const size_t dst_off = (size_t) task->row * s->nb1;
+ dma_queue_push(dma_q, dma_make_data(s->data_dst + dst_off, out_spad),
+ s->nb1, uctx->dst_row_size_aligned, uctx->dst_data_row_size, task->len);
+}
- const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size;
- const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size;
+static void unary_row_block_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ unary_compute_fn_t compute = (unary_compute_fn_t) s->uctx->compute;
+ compute(in_spad, out_spad, task->len, s->ne0, s->uctx);
+}
- const bool src0_contig = uctx->kparams->src0_contig;
- const uint32_t BLOCK = uctx->block;
+static void unary_rms_norm_mul_bc_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
+ const uint32_t src1_row_start = (uctx->src1_nrows <= 1) ? 0 : fastmodulo(task->row, uctx->src1_nrows, &uctx->kparams->div_ne01);
+ unary_rms_norm_mul_compute_fn_t compute = (unary_rms_norm_mul_compute_fn_t) uctx->compute;
+ compute(in_spad, s->src1_vtcm_bc, out_spad, task->len, src1_row_start, uctx);
+}
+static void unary_rms_norm_mul_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01;
const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02;
const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012;
- dma_queue * dma_q = th->dma_q;
-
- for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) {
- const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01);
+ const size_t src0_off = s->src0_contig ? ((size_t) task->row * s->nb01) :
+ unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb01, s->nb02, s->nb03);
+ const size_t src1_off = s->src1_contig ? ((size_t) task->row * s->nb11) :
+ unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb11, s->nb12, s->nb13);
- dma_queue_push(dma_q,
- dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)),
- nb1, dst_row_size_aligned, dst_data_row_size, 0);
+ dma_queue_push(dma_q, dma_make_data(in0_spad, s->data_src0 + src0_off),
+ uctx->src0_row_size_aligned, s->nb01, uctx->src0_data_row_size, task->len);
+ dma_queue_push(dma_q, dma_make_data(in1_spad, s->data_src1 + src1_off),
+ uctx->src1_row_size_aligned, s->nb11, uctx->src1_data_row_size, task->len);
+}
- const size_t src0_off = src0_contig ? ((size_t) ir * nb01) :
- unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off),
- src0_row_size_aligned, nb01, src0_data_row_size, block_size);
+static void unary_rms_norm_mul_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ unary_rms_norm_mul_compute_fn_t compute = (unary_rms_norm_mul_compute_fn_t) s->uctx->compute;
+ compute(in0_spad, in1_spad, out_spad, task->len, 0, s->uctx);
+}
- ir += block_size;
- }
+static void unary_rms_norm_mul_add_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in2_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
+ const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01;
+ const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02;
+ const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012;
- unary_compute_fn_t compute = (unary_compute_fn_t) uctx->compute;
+ const size_t src0_off = s->src0_contig ? ((size_t) task->row * s->nb01) :
+ unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb01, s->nb02, s->nb03);
+ const size_t src2_off = s->src0_contig ? ((size_t) task->row * s->nb21) :
+ unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb21, s->nb22, s->nb23);
- for (uint32_t ir = src0_start_row; ir < src0_end_row; ) {
- const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01);
+ dma_queue_push(dma_q, dma_make_data(in0_spad, s->data_src0 + src0_off),
+ uctx->src0_row_size_aligned, s->nb01, uctx->src0_data_row_size, task->len);
+ dma_queue_push(dma_q, dma_make_data(in2_spad, s->data_src2 + src2_off),
+ uctx->src2_row_size_aligned, s->nb21, uctx->src2_data_row_size, task->len);
+}
- void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+static void unary_rms_norm_mul_add_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in2_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
+ const uint32_t src1_row_start = (uctx->src1_nrows <= 1) ? 0 : fastmodulo(task->row, uctx->src1_nrows, &uctx->kparams->div_ne01);
+ unary_rms_norm_mul_add_compute_fn_t compute = (unary_rms_norm_mul_add_compute_fn_t) uctx->compute;
+ compute(in0_spad, s->src1_vtcm_bc, in2_spad, out_spad, task->len, src1_row_start, uctx);
+}
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir);
- compute(src0_vtcm, dst_vtcm, block_size, uctx);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir);
+// 1. Standard row-block unary task (F32 and F16).
+static void unary_thread_row_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct htp_unary_context * uctx = (const struct htp_unary_context *) data;
+ struct htp_ops_context * octx = uctx->octx;
+ const struct htp_tensor * src = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
+ htp_unary_preamble;
- const size_t dst_off = (size_t) ir * nb1;
- dma_queue_push(dma_q,
- dma_make_data(data_dst + dst_off, dst_vtcm),
- nb1, dst_row_size_aligned, dst_data_row_size, block_size);
-
- const uint32_t next_ir = ir + block_size;
- if (next_ir < src0_end_row) {
- const uint32_t next_block_size = unary_block_size(next_ir, src0_end_row, BLOCK, src0_contig,
- ne01, div_ne01);
- const uint32_t pref_ir = next_ir + next_block_size;
- if (pref_ir < src0_end_row) {
- const uint32_t pref_block_size = unary_block_size(pref_ir, src0_end_row, BLOCK, src0_contig,
- ne01, div_ne01);
- const size_t src0_pref_off = src0_contig ? ((size_t) pref_ir * nb01) :
- unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm, data_src + src0_pref_off),
- src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size);
- }
- }
- ir += block_size;
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
+ if (src0_start_row >= src0_end_row) {
+ return;
}
- dma_queue_flush(dma_q);
+ uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
+
+ struct unary_row_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_dst = uctx->data_dst,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1,
+ .block = uctx->block,
+ .src0_contig = uctx->kparams->src0_contig,
+ .block_contig = uctx->kparams->src0_contig,
+ .src0_slice_dma = uctx->kparams->src0_slice_dma,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
+
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ unary_row_next_task, unary_row_push_in, unary_row_block_compute, unary_row_push_out);
}
-// 2. RMS_NORM_MUL row-block task with weight buffer.
-static void unary_thread_rms_norm_mul_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+// 2a. RMS_NORM_MUL row-block task with broadcast src1 buffer.
+static void unary_thread_rms_norm_mul_bc(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
(void) nth;
const struct htp_unary_context * uctx = (const struct htp_unary_context *) data;
struct htp_ops_context * octx = uctx->octx;
const struct htp_tensor * src = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
htp_unary_preamble;
- const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx;
- const size_t src0_data_row_size = uctx->src0_data_row_size;
- const size_t dst_data_row_size = uctx->dst_data_row_size;
- const size_t src0_row_size_aligned = uctx->src0_row_size_aligned;
- const size_t dst_row_size_aligned = uctx->dst_row_size_aligned;
-
- const uint32_t src0_nrows = uctx->src0_nrows;
- const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows);
-
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
if (src0_start_row >= src0_end_row) {
return;
}
- const dma_addr_t data_src = uctx->data_src0;
- const dma_addr_t data_src1 = uctx->data_src1;
- const dma_addr_t data_dst = uctx->data_dst;
-
const struct htp_tensor * src1 = octx->src[1];
- const uint32_t nb11 = src1->nb[1];
- const uint32_t nb12 = src1->nb[2];
- const uint32_t nb13 = src1->nb[3];
-
uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
- uint8_t * src1_vtcm_data = uctx->vtcm_src1 ? (uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx)) : NULL;
- uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx);
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
- const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size;
- const size_t src1_vtcm_half_size = uctx->src1_vtcm_half_size;
- const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size;
+ dma_queue * dma_q = th->dma_q;
+ dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, uctx->data_src1),
+ uctx->src1_row_size_aligned, src1->nb[1], uctx->src1_data_row_size, uctx->src1_nrows);
+ dma_queue_flush(dma_q);
- const bool src0_contig = uctx->kparams->src0_contig;
- const bool src1_contig = uctx->kparams->src1_contig;
- const bool block_contig = src0_contig && src1_contig;
- const uint32_t BLOCK = uctx->block;
+ struct unary_row_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_dst = uctx->data_dst,
+ .src1_vtcm_bc = src1_vtcm_data,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1,
+ .block = uctx->block,
+ .src0_contig = uctx->kparams->src0_contig,
+ .block_contig = uctx->kparams->src0_contig,
+ .src0_slice_dma = uctx->kparams->src0_slice_dma,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
- const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01;
- const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02;
- const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012;
+ dma_pipe_io_run(dma_q, th->trace, &s, in_buf, out_buf,
+ unary_row_next_task, unary_row_push_in, unary_rms_norm_mul_bc_compute, unary_row_push_out);
+}
- dma_queue * dma_q = th->dma_q;
+// 2b. RMS_NORM_MUL row-block task with dynamic non-broadcast src1 buffer.
+static void unary_thread_rms_norm_mul(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct htp_unary_context * uctx = (const struct htp_unary_context *) data;
+ struct htp_ops_context * octx = uctx->octx;
+ const struct htp_tensor * src = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
+ htp_unary_preamble;
- if (uctx->broadcast_weight) {
- dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, data_src1),
- uctx->src1_row_size_aligned, 0, uctx->src1_data_row_size, 1);
- dma_queue_flush(dma_q);
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
+ if (src0_start_row >= src0_end_row) {
+ return;
}
- for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) {
- const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, block_contig, ne01, div_ne01);
-
- dma_queue_push(dma_q,
- dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)),
- nb1, dst_row_size_aligned, dst_data_row_size, 0);
+ const struct htp_tensor * src1 = octx->src[1];
+ uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
+ uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx);
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in0_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * in1_buf[2] = { src1_vtcm_data, src1_vtcm_data + uctx->src1_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
+
+ struct unary_row_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_src1 = uctx->data_src1,
+ .data_dst = uctx->data_dst,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb11 = src1->nb[1], .nb12 = src1->nb[2], .nb13 = src1->nb[3],
+ .nb1 = nb1,
+ .block = uctx->block,
+ .src0_contig = uctx->kparams->src0_contig,
+ .src1_contig = uctx->kparams->src1_contig,
+ .block_contig = uctx->kparams->src0_contig && uctx->kparams->src1_contig,
+ .src0_slice_dma = false,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
- const size_t src0_off = src0_contig ? ((size_t) ir * nb01) :
- unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off),
- src0_row_size_aligned, nb01, src0_data_row_size, block_size);
+ dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf,
+ unary_row_next_task, unary_rms_norm_mul_push_in, unary_rms_norm_mul_compute, unary_row_push_out);
+}
- if (!uctx->broadcast_weight) {
- const size_t src1_off = src1_contig ? ((size_t) ir * nb11) :
- unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb11, nb12, nb13);
- dma_queue_push(dma_q,
- dma_make_data(src1_vtcm_data + (vtcm_idx * src1_vtcm_half_size), data_src1 + src1_off),
- uctx->src1_row_size_aligned, nb11, uctx->src1_data_row_size, block_size);
- }
+// 2b. RMS_NORM_MUL_ADD row-block task with broadcast src1 and residual add.
+static void unary_thread_rms_norm_mul_add(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
+ const struct htp_unary_context * uctx = (const struct htp_unary_context *) data;
+ struct htp_ops_context * octx = uctx->octx;
+ const struct htp_tensor * src = octx->src[0];
+ const struct htp_tensor * dst = octx->dst;
+ htp_unary_preamble;
- ir += block_size;
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
+ if (src0_start_row >= src0_end_row) {
+ return;
}
- unary_rms_norm_mul_compute_fn_t compute = (unary_rms_norm_mul_compute_fn_t) uctx->compute;
-
- for (uint32_t ir = src0_start_row; ir < src0_end_row; ) {
- const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, block_contig, ne01, div_ne01);
-
- void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
- void * src1_vtcm = NULL;
- if (!uctx->broadcast_weight) {
- src1_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
- }
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir);
- const void * w = uctx->broadcast_weight ? (const void *) src1_vtcm_data : src1_vtcm;
- compute(src0_vtcm, w, dst_vtcm, block_size, uctx);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir);
+ const struct htp_tensor * src1 = octx->src[1];
+ const struct htp_tensor * src2 = octx->src[2];
+ uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
+ uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx);
+ uint8_t * src2_vtcm_data = uctx->vtcm_src2 + (ith * uctx->vtcm_src2_size_per_hvx);
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in0_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * in2_buf[2] = { src2_vtcm_data, src2_vtcm_data + uctx->src2_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
- const size_t dst_off = (size_t) ir * nb1;
- dma_queue_push(dma_q,
- dma_make_data(data_dst + dst_off, dst_vtcm),
- nb1, dst_row_size_aligned, dst_data_row_size, block_size);
-
- const uint32_t next_ir = ir + block_size;
- if (next_ir < src0_end_row) {
- const uint32_t next_block_size = unary_block_size(next_ir, src0_end_row, BLOCK, block_contig,
- ne01, div_ne01);
- const uint32_t pref_ir = next_ir + next_block_size;
- if (pref_ir < src0_end_row) {
- const uint32_t pref_block_size = unary_block_size(pref_ir, src0_end_row, BLOCK, block_contig,
- ne01, div_ne01);
- const size_t src0_pref_off = src0_contig ? ((size_t) pref_ir * nb01) :
- unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm, data_src + src0_pref_off),
- src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size);
+ dma_queue * dma_q = th->dma_q;
+ dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, uctx->data_src1),
+ uctx->src1_row_size_aligned, src1->nb[1], uctx->src1_data_row_size, uctx->src1_nrows);
+ dma_queue_flush(dma_q);
- if (!uctx->broadcast_weight) {
- const size_t src1_pref_off = src1_contig ? ((size_t) pref_ir * nb11) :
- unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb11, nb12, nb13);
- dma_queue_push(dma_q,
- dma_make_data(src1_vtcm, data_src1 + src1_pref_off),
- uctx->src1_row_size_aligned, nb11, uctx->src1_data_row_size, pref_block_size);
- }
- }
- }
- ir += block_size;
- }
+ struct unary_row_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_src2 = uctx->data_src2,
+ .data_dst = uctx->data_dst,
+ .src1_vtcm_bc = src1_vtcm_data,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb21 = src2->nb[1], .nb22 = src2->nb[2], .nb23 = src2->nb[3],
+ .nb1 = nb1,
+ .block = uctx->block,
+ .src0_contig = uctx->kparams->src0_contig,
+ .block_contig = uctx->kparams->src0_contig,
+ .src0_slice_dma = false,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
- dma_queue_flush(dma_q);
+ dma_pipe_io2_run(dma_q, th->trace, &s, in0_buf, in2_buf, out_buf,
+ unary_row_next_task, unary_rms_norm_mul_add_push_in, unary_rms_norm_mul_add_compute, unary_row_push_out);
}
-// 2b. RMS_NORM_MUL_ADD row-block task with broadcast weight and residual add.
-static void unary_thread_rms_norm_mul_add_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+// 2c. 2-pass column-tiled task for wide-row RMS_NORM / RMS_NORM_MUL / RMS_NORM_MUL_ADD.
+static void unary_thread_tiled_rms_norm(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
(void) nth;
const struct htp_unary_context * uctx = (const struct htp_unary_context *) data;
struct htp_ops_context * octx = uctx->octx;
@@ -1475,10 +3417,7 @@ static void unary_thread_rms_norm_mul_add_f32(const htp_thread_t * th, unsigned
htp_unary_preamble;
const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx;
- const size_t src0_data_row_size = uctx->src0_data_row_size;
- const size_t dst_data_row_size = uctx->dst_data_row_size;
- const size_t src0_row_size_aligned = uctx->src0_row_size_aligned;
- const size_t dst_row_size_aligned = uctx->dst_row_size_aligned;
+ const uint32_t col_tile = uctx->col_tile;
const uint32_t src0_nrows = uctx->src0_nrows;
const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith;
@@ -1488,91 +3427,169 @@ static void unary_thread_rms_norm_mul_add_f32(const htp_thread_t * th, unsigned
return;
}
+ const bool has_src1_mul = (octx->op == HTP_OP_RMS_NORM_MUL || octx->op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src2_add = (octx->op == HTP_OP_RMS_NORM_MUL_ADD);
+
+ const struct htp_tensor * src1 = has_src1_mul ? octx->src[1] : NULL;
+ const struct htp_tensor * src2 = has_src2_add ? octx->src[2] : NULL;
+
+ const uint32_t nb10 = has_src1_mul ? src1->nb[0] : 0;
+ const uint32_t nb11 = has_src1_mul ? src1->nb[1] : 0;
+ const uint32_t nb12 = has_src1_mul ? src1->nb[2] : 0;
+ const uint32_t nb13 = has_src1_mul ? src1->nb[3] : 0;
+
+ const uint32_t nb20 = has_src2_add ? src2->nb[0] : 0;
+ const uint32_t nb21 = has_src2_add ? src2->nb[1] : 0;
+ const uint32_t nb22 = has_src2_add ? src2->nb[2] : 0;
+ const uint32_t nb23 = has_src2_add ? src2->nb[3] : 0;
+
const dma_addr_t data_src = uctx->data_src0;
const dma_addr_t data_src1 = uctx->data_src1;
const dma_addr_t data_src2 = uctx->data_src2;
const dma_addr_t data_dst = uctx->data_dst;
uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
- uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx);
- uint8_t * src2_vtcm_data = uctx->vtcm_src2 + (ith * uctx->vtcm_src2_size_per_hvx);
+ uint8_t * src1_vtcm_data = uctx->vtcm_src1 ? (uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx)) : NULL;
+ uint8_t * src2_vtcm_data = uctx->vtcm_src2 ? (uctx->vtcm_src2 + (ith * uctx->vtcm_src2_size_per_hvx)) : NULL;
uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
- const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size;
- const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size;
-
- const bool src0_contig = uctx->kparams->src0_contig;
- const uint32_t BLOCK = uctx->block;
+ const size_t src0_half = uctx->src0_vtcm_half_size;
+ const size_t src1_half = uctx->src1_vtcm_half_size;
+ const size_t src2_half = uctx->src2_vtcm_half_size;
+ const size_t dst_half = uctx->dst_vtcm_half_size;
const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01;
const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02;
const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012;
- dma_queue * dma_q = th->dma_q;
-
- dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, data_src1),
- uctx->src1_row_size_aligned, 0, uctx->src1_data_row_size, 1);
- dma_queue_flush(dma_q);
+ const uint32_t tiles_per_row = uctx->kparams->tiles_per_row;
+ const bool src0_contig = uctx->kparams->src0_contig;
+ const bool src1_contig = uctx->kparams->src1_contig;
- for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) {
- const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01);
+ float epsilon = 0.f;
+ float scale = 0.f;
+ memcpy(&epsilon, &octx->op_params[0], sizeof(float));
+ memcpy(&scale, &octx->op_params[1], sizeof(float));
- dma_queue_push(dma_q,
- dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)),
- nb1, dst_row_size_aligned, dst_data_row_size, 0);
+ dma_queue * dma_q = th->dma_q;
+ const rms_tile_sum_sq_fn_t tile_sum_sq_fn = uctx->rms_tile_sum_sq_fn;
+
+ for (uint32_t row = src0_start_row; row < src0_end_row; row++) {
+ const uint32_t src1_row = (!has_src1_mul || !uctx->broadcast_src1) ? row :
+ ((uctx->src1_nrows <= 1) ? 0 : fastmodulo(row, uctx->src1_nrows, div_ne01));
+ const size_t src0_row_off = src0_contig ? ((size_t) row * nb01) :
+ unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
+ const size_t src1_row_off = !has_src1_mul ? 0 :
+ (uctx->broadcast_src1 ? ((size_t) src1_row * nb11) :
+ (src1_contig ? ((size_t) row * nb11) :
+ unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb11, nb12, nb13)));
+ const size_t src2_row_off = !has_src2_add ? 0 :
+ (src0_contig ? ((size_t) row * nb21) :
+ unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb21, nb22, nb23));
+ const size_t dst_row_off = (size_t) row * nb1;
+
+ for (uint32_t t = 0; t < tiles_per_row && t < 2; t++) {
+ const uint32_t col = t * col_tile;
+ const uint32_t tw = MIN(col_tile, ne0 - col);
+ const size_t tb0 = (size_t) tw * nb00;
+ dma_queue_push(dma_q,
+ dma_make_data(src0_vtcm_data + (t * src0_half), data_src + src0_row_off + (size_t) col * nb00),
+ tb0, tb0, tb0, 1);
+ }
- const size_t src0_off = src0_contig ? ((size_t) ir * nb01) :
- unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off),
- src0_row_size_aligned, nb01, src0_data_row_size, block_size);
- dma_queue_push(dma_q,
- dma_make_data(src2_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src2 + src0_off),
- src0_row_size_aligned, nb01, src0_data_row_size, block_size);
+ float sum_sq = 0.0f;
+ for (uint32_t t = 0; t < tiles_per_row; t++) {
+ const uint32_t col = t * col_tile;
+ const uint32_t tw = MIN(col_tile, ne0 - col);
+ const uint8_t * s0 = (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst;
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row);
+ sum_sq += tile_sum_sq_fn(s0, tw);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row);
+
+ const uint32_t pt = t + 2;
+ if (pt < tiles_per_row) {
+ const uint32_t pcol = pt * col_tile;
+ const uint32_t ptw = MIN(col_tile, ne0 - pcol);
+ const size_t ptb0 = (size_t) ptw * nb00;
+ dma_queue_push(dma_q,
+ dma_make_data((void *) s0, data_src + src0_row_off + (size_t) pcol * nb00),
+ ptb0, ptb0, ptb0, 1);
+ }
+ }
- ir += block_size;
- }
+ for (uint32_t t = 0; t < tiles_per_row && t < 2; t++) {
+ const uint32_t col = t * col_tile;
+ const uint32_t tw = MIN(col_tile, ne0 - col);
+ const size_t tb0 = (size_t) tw * nb00;
- unary_rms_norm_mul_add_compute_fn_t compute = (unary_rms_norm_mul_add_compute_fn_t) uctx->compute;
+ dma_queue_push(dma_q, dma_make_data(data_dst, dst_vtcm_data + (t * dst_half)), 0, 0, 0, 0);
+ dma_queue_push(dma_q,
+ dma_make_data(src0_vtcm_data + (t * src0_half), data_src + src0_row_off + (size_t) col * nb00),
+ tb0, tb0, tb0, 1);
+ if (has_src1_mul) {
+ const size_t tb1 = (size_t) tw * nb10;
+ dma_queue_push(dma_q,
+ dma_make_data(src1_vtcm_data + (t * src1_half), data_src1 + src1_row_off + (size_t) col * nb10),
+ tb1, tb1, tb1, 1);
+ }
+ if (has_src2_add) {
+ const size_t tb2 = (size_t) tw * nb20;
+ dma_queue_push(dma_q,
+ dma_make_data(src2_vtcm_data + (t * src2_half), data_src2 + src2_row_off + (size_t) col * nb20),
+ tb2, tb2, tb2, 1);
+ }
+ }
- for (uint32_t ir = src0_start_row; ir < src0_end_row; ) {
- const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01);
+ for (uint32_t t = 0; t < tiles_per_row; t++) {
+ const uint32_t col = t * col_tile;
+ const uint32_t tw = MIN(col_tile, ne0 - col);
- void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
- void * src2_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+ uint8_t * d_vtcm = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).src;
+ const uint8_t * s0_vtcm = (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst;
+ const uint8_t * s1_vtcm = has_src1_mul ? (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst : NULL;
+ const uint8_t * s2_vtcm = has_src2_add ? (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst : NULL;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir);
- compute(src0_vtcm, src1_vtcm_data, src2_vtcm, dst_vtcm, block_size, uctx);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir);
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row);
+ rms_norm_apply_tile(s0_vtcm, s1_vtcm, s2_vtcm, d_vtcm, tw, ne0, sum_sq, epsilon, scale, uctx);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row);
- const size_t dst_off = (size_t) ir * nb1;
- dma_queue_push(dma_q,
- dma_make_data(data_dst + dst_off, dst_vtcm),
- nb1, dst_row_size_aligned, dst_data_row_size, block_size);
-
- const uint32_t next_ir = ir + block_size;
- if (next_ir < src0_end_row) {
- const uint32_t next_block_size = unary_block_size(next_ir, src0_end_row, BLOCK, src0_contig,
- ne01, div_ne01);
- const uint32_t pref_ir = next_ir + next_block_size;
- if (pref_ir < src0_end_row) {
- const uint32_t pref_block_size = unary_block_size(pref_ir, src0_end_row, BLOCK, src0_contig,
- ne01, div_ne01);
- const size_t src0_pref_off = src0_contig ? ((size_t) pref_ir * nb01) :
- unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03);
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm, data_src + src0_pref_off),
- src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size);
+ const size_t tb_dst = (size_t) tw * nb0;
+ dma_queue_push(dma_q,
+ dma_make_data(data_dst + dst_row_off + (size_t) col * nb0, d_vtcm),
+ tb_dst, tb_dst, tb_dst, 1);
+
+ const uint32_t pt = t + 2;
+ if (pt < tiles_per_row) {
+ const uint32_t pcol = pt * col_tile;
+ const uint32_t ptw = MIN(col_tile, ne0 - pcol);
+ const size_t ptb0 = (size_t) ptw * nb00;
dma_queue_push(dma_q,
- dma_make_data(src2_vtcm, data_src2 + src0_pref_off),
- src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size);
+ dma_make_data((void *) s0_vtcm, data_src + src0_row_off + (size_t) pcol * nb00),
+ ptb0, ptb0, ptb0, 1);
+ if (has_src1_mul) {
+ const size_t ptb1 = (size_t) ptw * nb10;
+ dma_queue_push(dma_q,
+ dma_make_data((void *) s1_vtcm, data_src1 + src1_row_off + (size_t) pcol * nb10),
+ ptb1, ptb1, ptb1, 1);
+ }
+ if (has_src2_add) {
+ const size_t ptb2 = (size_t) ptw * nb20;
+ dma_queue_push(dma_q,
+ dma_make_data((void *) s2_vtcm, data_src2 + src2_row_off + (size_t) pcol * nb20),
+ ptb2, ptb2, ptb2, 1);
+ }
}
}
- ir += block_size;
+
+ dma_queue_flush(dma_q);
}
+}
- dma_queue_flush(dma_q);
+static void unary_tri_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx;
+ unary_tri_compute_fn_t compute = (unary_tri_compute_fn_t) s->uctx->compute;
+ compute(in_spad, out_spad, task->len, task->row, s->uctx);
}
// 3. TRI row-block task with row index ir.
@@ -1582,84 +3599,111 @@ static void unary_thread_tri_f32(const htp_thread_t * th, unsigned int nth, unsi
struct htp_ops_context * octx = uctx->octx;
const struct htp_tensor * src = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
htp_unary_preamble;
- const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx;
- const size_t src0_data_row_size = uctx->src0_data_row_size;
- const size_t dst_data_row_size = uctx->dst_data_row_size;
- const size_t src0_row_size_aligned = uctx->src0_row_size_aligned;
- const size_t dst_row_size_aligned = uctx->dst_row_size_aligned;
-
- const uint32_t src0_nrows = uctx->src0_nrows;
- const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows);
-
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
if (src0_start_row >= src0_end_row) {
return;
}
- const dma_addr_t data_src = uctx->data_src0;
- const dma_addr_t data_dst = uctx->data_dst;
-
uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
- uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
-
- const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size;
- const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size;
- const uint32_t BLOCK = uctx->block;
-
- dma_queue * dma_q = th->dma_q;
-
- for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) {
- const uint32_t block_size = MIN(BLOCK, src0_end_row - ir);
-
- dma_queue_push(dma_q,
- dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)),
- nb1, dst_row_size_aligned, dst_data_row_size, 0);
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
+
+ struct unary_row_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_dst = uctx->data_dst,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb1 = nb1,
+ .block = uctx->block,
+ .src0_contig = true,
+ .block_contig = true,
+ .src0_slice_dma = false,
+ .ir = src0_start_row,
+ .ir_end = src0_end_row,
+ };
- const size_t src0_off = (size_t) ir * nb01;
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off),
- src0_row_size_aligned, nb01, src0_data_row_size, block_size);
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ unary_row_next_task, unary_row_push_in, unary_tri_compute, unary_row_push_out);
+}
+
+struct unary_tiled_pipe_state {
+ const struct htp_unary_context * uctx;
+ dma_addr_t data_src0;
+ dma_addr_t data_dst;
+ uint32_t ne0, ne01, ne02;
+ uint32_t nb00, nb01, nb02, nb03;
+ uint32_t nb0, nb1;
+ uint32_t col_tile;
+ uint32_t tiles_per_row;
+ uint32_t row;
+ uint32_t row_end;
+ uint32_t col;
+ uint32_t tile_in_row;
+ uint32_t i01;
+ int32_t tri_ttype;
+ bool src0_contig;
+};
- ir += block_size;
+static bool unary_tiled_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx;
+ if (s->row >= s->row_end) {
+ return false;
+ }
+
+ const uint32_t tw = MIN(s->col_tile, s->ne0 - s->col);
+ task->row = s->row;
+ task->off = s->col;
+ task->len = tw;
+ task->aux = s->i01;
+
+ s->tile_in_row++;
+ s->col += s->col_tile;
+ if (s->tile_in_row == s->tiles_per_row) {
+ s->tile_in_row = 0;
+ s->col = 0;
+ s->row++;
+ s->i01++;
+ if (s->i01 == s->ne01) {
+ s->i01 = 0;
+ }
}
+ return true;
+}
- unary_tri_compute_fn_t compute = (unary_tri_compute_fn_t) uctx->compute;
-
- for (uint32_t ir = src0_start_row; ir < src0_end_row; ) {
- const uint32_t block_size = MIN(BLOCK, src0_end_row - ir);
-
- void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
+static void unary_tiled_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx;
+ const struct htp_unary_context * uctx = s->uctx;
+ const size_t tb = (size_t) task->len * s->nb00;
+ const size_t soff = (s->src0_contig ? ((size_t) task->row * s->nb01) :
+ unary_row_offset(task->row, s->ne01, s->ne02,
+ &uctx->kparams->div_ne01, &uctx->kparams->div_ne02, &uctx->kparams->div_ne012,
+ s->nb01, s->nb02, s->nb03)) +
+ (size_t) task->off * s->nb00;
+ dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src0 + soff), tb, tb, tb, 1);
+}
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir);
- compute(src0_vtcm, dst_vtcm, block_size, ir, uctx);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir);
+static void unary_tiled_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx;
+ const size_t doff = (size_t) task->row * s->nb1 + (size_t) task->off * s->nb0;
+ const size_t tb = (size_t) task->len * s->nb0;
+ dma_queue_push(dma_q, dma_make_data(s->data_dst + doff, out_spad), tb, tb, tb, 1);
+}
- const size_t dst_off = (size_t) ir * nb1;
- dma_queue_push(dma_q,
- dma_make_data(data_dst + dst_off, dst_vtcm),
- nb1, dst_row_size_aligned, dst_data_row_size, block_size);
-
- const uint32_t next_ir = ir + block_size;
- if (next_ir < src0_end_row) {
- const uint32_t next_block_size = MIN(BLOCK, src0_end_row - next_ir);
- const uint32_t pref_ir = next_ir + next_block_size;
- if (pref_ir < src0_end_row) {
- const uint32_t pref_block_size = MIN(BLOCK, src0_end_row - pref_ir);
- const size_t src0_pref_off = (size_t) pref_ir * nb01;
- dma_queue_push(dma_q,
- dma_make_data(src0_vtcm, data_src + src0_pref_off),
- src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size);
- }
- }
- ir += block_size;
- }
+static void unary_tiled_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx;
+ unary_compute_fn_t compute = (unary_compute_fn_t) s->uctx->compute;
+ compute(in_spad, out_spad, 1, task->len, s->uctx);
+}
- dma_queue_flush(dma_q);
+static void unary_tiled_tri_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx;
+ unary_tiled_tri_compute_fn_t compute = (unary_tiled_tri_compute_fn_t) s->uctx->compute;
+ compute(in_spad, out_spad, task->len, task->off, task->aux, s->ne0, s->tri_ttype);
}
// 4. Pointwise tiled unary task.
@@ -1669,108 +3713,39 @@ static void unary_thread_tiled(const htp_thread_t * th, unsigned int nth, unsign
struct htp_ops_context * octx = uctx->octx;
const struct htp_tensor * src = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
htp_unary_preamble;
- const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx;
- const uint32_t col_tile = uctx->col_tile;
-
- const uint32_t src0_nrows = uctx->src0_nrows;
- const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows);
-
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
if (src0_start_row >= src0_end_row) {
return;
}
- const dma_addr_t data_src = uctx->data_src0;
- const dma_addr_t data_dst = uctx->data_dst;
-
uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
- uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
-
- const size_t src0_half = uctx->src0_vtcm_half_size;
- const size_t dst_half = uctx->dst_vtcm_half_size;
-
- dma_queue * dma_q = th->dma_q;
-
- const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01;
- const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02;
- const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012;
- const struct fastdiv_values * div_tpr = &uctx->kparams->div_tpr;
-
- const uint32_t tiles_per_row = uctx->kparams->tiles_per_row;
- const bool src0_contig = uctx->kparams->src0_contig;
-
- const uint32_t total_tiles = (src0_end_row - src0_start_row) * tiles_per_row;
-
- for (uint32_t t = 0, vtcm_idx = 0; t < total_tiles && vtcm_idx < 2; t++, vtcm_idx++) {
- const uint32_t row = src0_start_row + fastdiv(t, div_tpr);
- const uint32_t col = fastmodulo(t, tiles_per_row, div_tpr) * col_tile;
- const uint32_t tw = MIN(col_tile, ne0 - col);
- const size_t tb = (size_t) tw * sizeof(float);
- const size_t soff = (src0_contig ? ((size_t) row * nb01) :
- unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03)) +
- (size_t) col * sizeof(float);
-
- dma_queue_push(dma_q, dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_half)), 0, 0, 0, 0);
- dma_queue_push(dma_q, dma_make_data(src0_vtcm_data + (vtcm_idx * src0_half), data_src + soff), tb, tb, tb, 1);
- }
-
- unary_tile_compute_fn_t compute = (unary_tile_compute_fn_t) uctx->compute;
-
- uint32_t row = src0_start_row;
- uint32_t col = 0;
- uint32_t tile_in_row = 0;
-
- uint32_t prow = src0_start_row + fastdiv(2, div_tpr);
- uint32_t pcol = fastmodulo(2, tiles_per_row, div_tpr) * col_tile;
- uint32_t ptile_in_row = fastmodulo(2, tiles_per_row, div_tpr);
-
- for (uint32_t t = 0; t < total_tiles; t++) {
- void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * src_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
-
- const uint32_t tw = MIN(col_tile, ne0 - col);
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, t);
- compute(dst_vtcm, src_vtcm, tw, uctx);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, t);
-
- const size_t doff = (size_t) row * nb1 + (size_t) col * sizeof(float);
- const size_t tb = (size_t) tw * sizeof(float);
- dma_queue_push(dma_q, dma_make_data(data_dst + doff, dst_vtcm), tb, tb, tb, 1);
-
- const uint32_t pt = t + 2;
- if (pt < total_tiles) {
- const uint32_t ptw = MIN(col_tile, ne0 - pcol);
- const size_t ptb = (size_t) ptw * sizeof(float);
- const size_t psoff = (src0_contig ? ((size_t) prow * nb01) :
- unary_row_offset(prow, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02,
- nb03)) +
- (size_t) pcol * sizeof(float);
- dma_queue_push(dma_q, dma_make_data(src_vtcm, data_src + psoff), ptb, ptb, ptb, 1);
- }
-
- tile_in_row++;
- col += col_tile;
- if (tile_in_row == tiles_per_row) {
- tile_in_row = 0;
- col = 0;
- row++;
- }
-
- ptile_in_row++;
- pcol += col_tile;
- if (ptile_in_row == tiles_per_row) {
- ptile_in_row = 0;
- pcol = 0;
- prow++;
- }
- }
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
+
+ struct unary_tiled_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_dst = uctx->data_dst,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb00 = nb00, .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb0 = nb0, .nb1 = nb1,
+ .col_tile = uctx->col_tile,
+ .tiles_per_row = uctx->kparams->tiles_per_row,
+ .row = src0_start_row,
+ .row_end = src0_end_row,
+ .col = 0,
+ .tile_in_row = 0,
+ .i01 = 0,
+ .tri_ttype = 0,
+ .src0_contig = uctx->kparams->src0_contig,
+ };
- dma_queue_flush(dma_q);
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ unary_tiled_next_task, unary_tiled_push_in, unary_tiled_compute, unary_tiled_push_out);
}
// 5. TRI tiled task.
@@ -1780,107 +3755,39 @@ static void unary_thread_tiled_tri_f32(const htp_thread_t * th, unsigned int nth
struct htp_ops_context * octx = uctx->octx;
const struct htp_tensor * src = octx->src[0];
const struct htp_tensor * dst = octx->dst;
- struct htp_thread_trace * tr = th->trace;
-
htp_unary_preamble;
- const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx;
- const int32_t * op_params = octx->op_params;
- const uint32_t col_tile = uctx->col_tile;
-
- const uint32_t src0_nrows = uctx->src0_nrows;
- const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith;
- const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows);
-
+ const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith;
+ const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows);
if (src0_start_row >= src0_end_row) {
return;
}
- const dma_addr_t data_src = uctx->data_src0;
- const dma_addr_t data_dst = uctx->data_dst;
-
uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx);
- uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
-
- const size_t src0_half = uctx->src0_vtcm_half_size;
- const size_t dst_half = uctx->dst_vtcm_half_size;
-
- dma_queue * dma_q = th->dma_q;
-
- const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01;
- const struct fastdiv_values * div_tpr = &uctx->kparams->div_tpr;
-
- const uint32_t tiles_per_row = uctx->kparams->tiles_per_row;
- const int32_t tri_ttype = op_params[0];
-
- const uint32_t total_tiles = (src0_end_row - src0_start_row) * tiles_per_row;
-
- for (uint32_t t = 0, vtcm_idx = 0; t < total_tiles && vtcm_idx < 2; t++, vtcm_idx++) {
- const uint32_t row = src0_start_row + fastdiv(t, div_tpr);
- const uint32_t col = fastmodulo(t, tiles_per_row, div_tpr) * col_tile;
- const uint32_t tw = MIN(col_tile, ne0 - col);
- const size_t tb = (size_t) tw * sizeof(float);
- const size_t soff = (size_t) row * nb01 + (size_t) col * sizeof(float);
-
- dma_queue_push(dma_q, dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_half)), 0, 0, 0, 0);
- dma_queue_push(dma_q, dma_make_data(src0_vtcm_data + (vtcm_idx * src0_half), data_src + soff), tb, tb, tb, 1);
- }
-
- unary_tiled_tri_compute_fn_t compute = (unary_tiled_tri_compute_fn_t) uctx->compute;
-
- uint32_t row = src0_start_row;
- uint32_t col = 0;
- uint32_t tile_in_row = 0;
- uint32_t i01 = fastmodulo(row, ne01, div_ne01);
-
- uint32_t prow = src0_start_row + fastdiv(2, div_tpr);
- uint32_t pcol = fastmodulo(2, tiles_per_row, div_tpr) * col_tile;
- uint32_t ptile_in_row = fastmodulo(2, tiles_per_row, div_tpr);
-
- for (uint32_t t = 0; t < total_tiles; t++) {
- void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src;
- void * src_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst;
-
- const uint32_t tw = MIN(col_tile, ne0 - col);
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, t);
- compute(src_vtcm, dst_vtcm, tw, col, i01, ne0, tri_ttype);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, t);
-
- const size_t doff = (size_t) row * nb1 + (size_t) col * sizeof(float);
- const size_t tb = (size_t) tw * sizeof(float);
- dma_queue_push(dma_q, dma_make_data(data_dst + doff, dst_vtcm), tb, tb, tb, 1);
-
- const uint32_t pt = t + 2;
- if (pt < total_tiles) {
- const uint32_t ptw = MIN(col_tile, ne0 - pcol);
- const size_t ptb = (size_t) ptw * sizeof(float);
- const size_t psoff = (size_t) prow * nb01 + (size_t) pcol * sizeof(float);
- dma_queue_push(dma_q, dma_make_data(src_vtcm, data_src + psoff), ptb, ptb, ptb, 1);
- }
-
- tile_in_row++;
- col += col_tile;
- if (tile_in_row == tiles_per_row) {
- tile_in_row = 0;
- col = 0;
- row++;
- i01++;
- if (i01 == ne01) {
- i01 = 0;
- }
- }
-
- ptile_in_row++;
- pcol += col_tile;
- if (ptile_in_row == tiles_per_row) {
- ptile_in_row = 0;
- pcol = 0;
- prow++;
- }
- }
+ uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx);
+ void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size };
+ void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size };
+
+ struct unary_tiled_pipe_state s = {
+ .uctx = uctx,
+ .data_src0 = uctx->data_src0,
+ .data_dst = uctx->data_dst,
+ .ne0 = ne0, .ne01 = ne01, .ne02 = ne02,
+ .nb00 = sizeof(float), .nb01 = nb01, .nb02 = nb02, .nb03 = nb03,
+ .nb0 = sizeof(float), .nb1 = nb1,
+ .col_tile = uctx->col_tile,
+ .tiles_per_row = uctx->kparams->tiles_per_row,
+ .row = src0_start_row,
+ .row_end = src0_end_row,
+ .col = 0,
+ .tile_in_row = 0,
+ .i01 = fastmodulo(src0_start_row, ne01, &uctx->kparams->div_ne01),
+ .tri_ttype = octx->op_params[0],
+ .src0_contig = true,
+ };
- dma_queue_flush(dma_q);
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ unary_tiled_next_task, unary_tiled_push_in, unary_tiled_tri_compute, unary_tiled_push_out);
}
static int execute_op_unary(struct htp_ops_context * octx) {
@@ -1894,33 +3801,33 @@ static int execute_op_unary(struct htp_ops_context * octx) {
const char * op_type = NULL;
switch (octx->op) {
- case HTP_OP_NORM: op_type = is_f16 ? "norm-f16" : "norm-f32"; break;
- case HTP_OP_RMS_NORM: op_type = is_f16 ? "rmsnorm-f16" : "rmsnorm-f32"; break;
- case HTP_OP_RMS_NORM_MUL: op_type = "rmsnorm-mul-f32"; break;
- case HTP_OP_RMS_NORM_MUL_ADD: op_type = "rmsnorm-mul-add-f32"; break;
- case HTP_OP_SCALE: op_type = is_f16 ? "scale-f16" : "scale-f32"; break;
- case HTP_OP_CLAMP: op_type = is_f16 ? "clamp-f16" : "clamp-f32"; break;
- case HTP_OP_LEAKY_RELU: op_type = "leaky-relu-f32"; break;
- case HTP_OP_SQR: op_type = is_f16 ? "sqr-f16" : "sqr-f32"; break;
- case HTP_OP_SQRT: op_type = is_f16 ? "sqrt-f16" : "sqrt-f32"; break;
- case HTP_OP_UNARY_NEG: op_type = "neg-f32"; break;
- case HTP_OP_UNARY_EXP: op_type = "exp-f32"; break;
- case HTP_OP_UNARY_SIGMOID: op_type = "sigmoid-f32"; break;
- case HTP_OP_UNARY_SILU: op_type = "silu-f32"; break;
- case HTP_OP_UNARY_GELU: op_type = "gelu-f32"; break;
- case HTP_OP_UNARY_GELU_QUICK: op_type = "gelu-quick-f32"; break;
- case HTP_OP_UNARY_GELU_ERF: op_type = "gelu-erf-f32"; break;
- case HTP_OP_UNARY_SOFTPLUS: op_type = "softplus-f32"; break;
- case HTP_OP_UNARY_TANH: op_type = "tanh-f32"; break;
- case HTP_OP_UNARY_ABS: op_type = is_f16 ? "abs-f16" : "abs-f32"; break;
- case HTP_OP_UNARY_LOG: op_type = is_f16 ? "log-f16" : "log-f32"; break;
- case HTP_OP_UNARY_RELU: op_type = "relu-f32"; break;
- case HTP_OP_UNARY_STEP: op_type = is_f16 ? "step-f16" : "step-f32"; break;
- case HTP_OP_UNARY_CEIL: op_type = is_f16 ? "ceil-f16" : "ceil-f32"; break;
- case HTP_OP_UNARY_SGN: op_type = is_f16 ? "sgn-f16" : "sgn-f32"; break;
- case HTP_OP_L2_NORM: op_type = is_f16 ? "l2norm-f16" : "l2norm-f32"; break;
- case HTP_OP_TRI: op_type = "tri-f32"; break;
- case HTP_OP_HADAMARD: op_type = is_f16 ? "hadamard-f16" : "hadamard-f32"; break;
+ case HTP_OP_NORM: op_type = is_f16 ? "norm-f16" : "norm-f32"; break;
+ case HTP_OP_RMS_NORM: op_type = is_f16 ? "rmsnorm-f16" : "rmsnorm-f32"; break;
+ case HTP_OP_RMS_NORM_MUL: op_type = is_f16 ? "rmsnorm-mul-f16" : "rmsnorm-mul-f32"; break;
+ case HTP_OP_RMS_NORM_MUL_ADD: op_type = is_f16 ? "rmsnorm-mul-add-f16" : "rmsnorm-mul-add-f32"; break;
+ case HTP_OP_SCALE: op_type = is_f16 ? "scale-f16" : "scale-f32"; break;
+ case HTP_OP_CLAMP: op_type = is_f16 ? "clamp-f16" : "clamp-f32"; break;
+ case HTP_OP_LEAKY_RELU: op_type = is_f16 ? "leaky-relu-f16" : "leaky-relu-f32"; break;
+ case HTP_OP_SQR: op_type = is_f16 ? "sqr-f16" : "sqr-f32"; break;
+ case HTP_OP_SQRT: op_type = is_f16 ? "sqrt-f16" : "sqrt-f32"; break;
+ case HTP_OP_UNARY_NEG: op_type = is_f16 ? "neg-f16" : "neg-f32"; break;
+ case HTP_OP_UNARY_EXP: op_type = is_f16 ? "exp-f16" : "exp-f32"; break;
+ case HTP_OP_UNARY_SIGMOID: op_type = is_f16 ? "sigmoid-f16" : "sigmoid-f32"; break;
+ case HTP_OP_UNARY_SILU: op_type = is_f16 ? "silu-f16" : "silu-f32"; break;
+ case HTP_OP_UNARY_GELU: op_type = is_f16 ? "gelu-f16" : "gelu-f32"; break;
+ case HTP_OP_UNARY_GELU_QUICK: op_type = is_f16 ? "gelu-quick-f16" : "gelu-quick-f32"; break;
+ case HTP_OP_UNARY_GELU_ERF: op_type = is_f16 ? "gelu-erf-f16" : "gelu-erf-f32"; break;
+ case HTP_OP_UNARY_SOFTPLUS: op_type = is_f16 ? "softplus-f16" : "softplus-f32"; break;
+ case HTP_OP_UNARY_TANH: op_type = is_f16 ? "tanh-f16" : "tanh-f32"; break;
+ case HTP_OP_UNARY_ABS: op_type = is_f16 ? "abs-f16" : "abs-f32"; break;
+ case HTP_OP_UNARY_LOG: op_type = is_f16 ? "log-f16" : "log-f32"; break;
+ case HTP_OP_UNARY_RELU: op_type = is_f16 ? "relu-f16" : "relu-f32"; break;
+ case HTP_OP_UNARY_STEP: op_type = is_f16 ? "step-f16" : "step-f32"; break;
+ case HTP_OP_UNARY_CEIL: op_type = is_f16 ? "ceil-f16" : "ceil-f32"; break;
+ case HTP_OP_UNARY_SGN: op_type = is_f16 ? "sgn-f16" : "sgn-f32"; break;
+ case HTP_OP_L2_NORM: op_type = is_f16 ? "l2norm-f16" : "l2norm-f32"; break;
+ case HTP_OP_TRI: op_type = "tri-f32"; break;
+ case HTP_OP_HADAMARD: op_type = is_f16 ? "hadamard-f16" : "hadamard-f32"; break;
default:
FARF(ERROR, "Unsupported unary Op %u\n", octx->op);
return HTP_STATUS_NO_SUPPORT;
@@ -1932,19 +3839,28 @@ static int execute_op_unary(struct htp_ops_context * octx) {
return HTP_STATUS_INVAL_PARAMS;
}
+ const bool has_src1_mul = (octx->op == HTP_OP_RMS_NORM_MUL || octx->op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src2_add = (octx->op == HTP_OP_RMS_NORM_MUL_ADD);
+
+ const struct htp_tensor * src1 = has_src1_mul ? octx->src[1] : NULL;
+ const struct htp_tensor * src2 = has_src2_add ? octx->src[2] : NULL;
+
const size_t src0_elem_size = is_f16 ? sizeof(_Float16) : sizeof(float);
const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(_Float16) : sizeof(float);
+ const size_t src1_elem_size = (has_src1_mul && src1->type == HTP_TYPE_F16) ? sizeof(_Float16) : sizeof(float);
+ const size_t src2_elem_size = (has_src2_add && src2->type == HTP_TYPE_F16) ? sizeof(_Float16) : sizeof(float);
+
const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3];
const size_t src0_data_row_size = src0->ne[0] * src0_elem_size;
const size_t dst_data_row_size = dst->ne[0] * dst_elem_size;
+ const size_t src1_data_row_size = has_src1_mul ? (src1->ne[0] * src1_elem_size) : 0;
+ const size_t src2_data_row_size = has_src2_add ? (src2->ne[0] * src2_elem_size) : 0;
uint32_t row_start = 0;
uint32_t nrows = src0_nrows;
if (octx->ctx->mdev.count > 1) {
- uint32_t rows_per_chunk = 0;
- htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) dst_elem_size, (uint32_t) dst_data_row_size, &rows_per_chunk);
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -1955,36 +3871,21 @@ static int execute_op_unary(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
- // Always 0 for F16 - htp_unary_solve_layout() keeps F16 on the row-block path,
- // since only F32 has unary_task_f32_tiled_* kernels.
const uint32_t col_tile = kparams->col_tile;
- size_t src1_data_row_size = 0;
- bool broadcast_weight = kparams->broadcast_weight;
- const struct htp_tensor * src1 = NULL;
-
- const bool has_weight = (octx->op == HTP_OP_RMS_NORM_MUL || octx->op == HTP_OP_RMS_NORM_MUL_ADD);
- const bool has_src2 = (octx->op == HTP_OP_RMS_NORM_MUL_ADD);
-
- // RMS_NORM_MUL* fusion is F32-only (its weight tensor is always F32; see
- // try_fuse_node()'s type guard), so this never triggers when is_f16 is true.
- if (has_weight) {
- src1 = octx->src[1];
- src1_data_row_size = src1->ne[0] * sizeof(float);
- }
+ bool broadcast_src1 = kparams->broadcast_src1;
+ const uint32_t src1_nrows = broadcast_src1 ? (uint32_t) src1->ne[1] : 0;
if ((!col_tile && kparams->block == 0) || octx->ctx->vtcm_size < (size_t) kparams->vtcm_size) {
FARF(ERROR, "unary-%s : current VTCM reservation %zu is too small, needed %zu\n", op_type, octx->ctx->vtcm_size, (size_t) kparams->vtcm_size);
return HTP_STATUS_VTCM_TOO_SMALL;
}
- octx->src0_spad.src = NULL;
- octx->src1_spad.src = NULL;
- octx->dst_spad.src = NULL;
struct htp_unary_vtcm_layout L;
- htp_unary_vtcm_layout_build(&L, octx->op, src0_data_row_size, dst_data_row_size, src1_data_row_size,
- src0_elem_size, col_tile, kparams->block, broadcast_weight, kparams->n_hvx);
+ htp_unary_vtcm_layout_build(&L, octx->op, src0_data_row_size, dst_data_row_size, src1_data_row_size, src2_data_row_size,
+ src0_elem_size, dst_elem_size, src1_elem_size, src2_elem_size,
+ col_tile, kparams->block, broadcast_src1, src1_nrows, kparams->n_hvx);
FARF(HIGH, "%s: (%ux%ux%ux%u) -> (%ux%ux%ux%u) : src0-vtcm-size %zu src1-vtcm-size %zu dst-vtcm-size %zu\n", op_type,
src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3],
@@ -1999,26 +3900,35 @@ static int execute_op_unary(struct htp_ops_context * octx) {
.row_start = row_start,
.data_src0 = src0->data,
- .data_src1 = has_weight ? src1->data : 0,
- .data_src2 = has_src2 ? octx->src[2]->data : 0,
+ .data_src1 = has_src1_mul ? src1->data : 0,
+ .data_src2 = has_src2_add ? src2->data : 0,
.data_dst = dst->data,
.src0_data_row_size = src0_data_row_size,
.src1_data_row_size = src1_data_row_size,
+ .src2_data_row_size = src2_data_row_size,
.dst_data_row_size = dst_data_row_size,
.src0_row_size_aligned = L.src0_row_size_aligned,
.src1_row_size_aligned = L.src1_row_size_aligned,
+ .src1_block_stride = (broadcast_src1 && src1_nrows <= 1) ? 0 : L.src1_row_size_aligned,
+ .src2_row_size_aligned = L.src2_row_size_aligned,
.dst_row_size_aligned = L.dst_row_size_aligned,
.src0_vtcm_half_size = L.src0_bytes >> 1,
- .src1_vtcm_half_size = has_weight ? (L.src1_bytes >> (broadcast_weight ? 0 : 1)) : 0,
+ .src1_vtcm_half_size = has_src1_mul ? (L.src1_bytes >> ((broadcast_src1 && !col_tile) ? 0 : 1)) : 0,
+ .src2_vtcm_half_size = L.src2_bytes >> 1,
.dst_vtcm_half_size = L.dst_bytes >> 1,
.block = kparams->block,
.nc = src0->ne[0],
.col_tile = col_tile,
- .broadcast_weight = broadcast_weight,
+ .src1_nrows = src1_nrows,
+ .broadcast_src1 = broadcast_src1,
+ .src0_f16 = is_f16,
+ .src1_f16 = has_src1_mul && (src1->type == HTP_TYPE_F16),
+ .src2_f16 = has_src2_add && (src2->type == HTP_TYPE_F16),
+ .dst_f16 = (dst->type == HTP_TYPE_F16),
.vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0),
.vtcm_src1 = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_src1, L.src1_bytes > 0),
@@ -2033,96 +3943,98 @@ static int execute_op_unary(struct htp_ops_context * octx) {
FARF(HIGH, "%s: %s mode (col_tile %u)\n", op_type, col_tile ? "tiled" : "row-block", col_tile);
- work_queue_func_t task_func = NULL;
+ work_queue_func_t task_func = col_tile ? unary_thread_tiled : unary_thread_row_block;
void * compute_func = NULL;
- if (col_tile) {
- task_func = unary_thread_tiled;
- switch (octx->op) {
- case HTP_OP_SCALE: compute_func = (void *) tile_scale_f32; break;
- case HTP_OP_CLAMP: compute_func = (void *) tile_clamp_f32; break;
- case HTP_OP_LEAKY_RELU: compute_func = (void *) tile_leaky_relu_f32; break;
- case HTP_OP_SQR: compute_func = (void *) tile_sqr_f32; break;
- case HTP_OP_SQRT: compute_func = (void *) tile_sqrt_f32; break;
- case HTP_OP_UNARY_NEG: compute_func = (void *) tile_neg_f32; break;
- case HTP_OP_UNARY_EXP: compute_func = (void *) tile_exp_f32; break;
- case HTP_OP_UNARY_SIGMOID: compute_func = (void *) tile_sigmoid_f32; break;
- case HTP_OP_UNARY_SILU: compute_func = (void *) tile_silu_f32; break;
- case HTP_OP_UNARY_GELU: compute_func = (void *) tile_gelu_f32; break;
- case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) tile_gelu_quick_f32; break;
- case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) tile_gelu_erf_f32; break;
- case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) tile_softplus_f32; break;
- case HTP_OP_UNARY_TANH: compute_func = (void *) tile_tanh_f32; break;
- case HTP_OP_UNARY_ABS: compute_func = (void *) tile_abs_f32; break;
- case HTP_OP_UNARY_LOG: compute_func = (void *) tile_log_f32; break;
- case HTP_OP_UNARY_RELU: compute_func = (void *) tile_relu_f32; break;
- case HTP_OP_UNARY_STEP: compute_func = (void *) tile_step_f32; break;
- case HTP_OP_UNARY_CEIL: compute_func = (void *) tile_ceil_f32; break;
- case HTP_OP_UNARY_SGN: compute_func = (void *) tile_sgn_f32; break;
- case HTP_OP_TRI:
- task_func = unary_thread_tiled_tri_f32;
- compute_func = (void *) tri_apply_tile_f32;
- break;
- default: break;
- }
- } else if (is_f16) {
- task_func = unary_thread_row_block;
+ switch (octx->op) {
+ case HTP_OP_RMS_NORM:
+ task_func = col_tile ? unary_thread_tiled_rms_norm : unary_thread_row_block;
+ compute_func = (void *) rms_norm_rows_table[is_f16][uctx.dst_f16];
+ uctx.rms_tile_sum_sq_fn = is_f16 ? rms_norm_tile_sum_sq_f16 : rms_norm_tile_sum_sq_f32;
+ uctx.rms_apply_row_fn = rms_norm_apply_row_table[is_f16][uctx.dst_f16];
+ break;
+ case HTP_OP_RMS_NORM_MUL:
+ task_func = col_tile ? unary_thread_tiled_rms_norm : (broadcast_src1 ? unary_thread_rms_norm_mul_bc : unary_thread_rms_norm_mul);
+ compute_func = (void *) rms_norm_mul_rows_table[is_f16][uctx.src1_f16][uctx.dst_f16];
+ if (!col_tile && broadcast_src1 && uctx.src1_nrows == 1 && is_f16 && !uctx.src1_f16 && uctx.dst_f16) {
+ if (src0->ne[0] == 128) {
+ compute_func = (void *) rms_norm_mul_rows_f16_f32_f16_ne128_bc;
+ } else if (src0->ne[0] == 256) {
+ compute_func = (void *) rms_norm_mul_rows_f16_f32_f16_ne256_bc;
+ }
+ }
+ uctx.rms_tile_sum_sq_fn = is_f16 ? rms_norm_tile_sum_sq_f16 : rms_norm_tile_sum_sq_f32;
+ uctx.rms_apply_row_fn = rms_norm_mul_apply_row_table[is_f16][uctx.src1_f16][uctx.dst_f16];
+ break;
+ case HTP_OP_RMS_NORM_MUL_ADD:
+ task_func = col_tile ? unary_thread_tiled_rms_norm : unary_thread_rms_norm_mul_add;
+ compute_func = (void *) rms_norm_mul_add_rows_table[is_f16][uctx.src1_f16][uctx.src2_f16][uctx.dst_f16];
+ uctx.rms_tile_sum_sq_fn = is_f16 ? rms_norm_tile_sum_sq_f16 : rms_norm_tile_sum_sq_f32;
+ uctx.rms_apply_row_fn = rms_norm_mul_add_apply_row_table[is_f16][uctx.src1_f16][uctx.src2_f16][uctx.dst_f16];
+ break;
+ default:
+ break;
+ }
+
+ const bool has_scale_bias = (kparams->has_scale_bias != 0);
+
+ if (!compute_func && is_f16) {
switch (octx->op) {
- case HTP_OP_NORM: compute_func = (void *) norm_f16; break;
- case HTP_OP_RMS_NORM: compute_func = (void *) rms_norm_f16; break;
- case HTP_OP_SCALE: compute_func = (void *) scale_f16; break;
- case HTP_OP_CLAMP: compute_func = (void *) clamp_f16; break;
- case HTP_OP_SQR: compute_func = (void *) sqr_f16; break;
- case HTP_OP_SQRT: compute_func = (void *) sqrt_f16; break;
- case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f16; break;
- case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f16; break;
- case HTP_OP_UNARY_LOG: compute_func = (void *) log_f16; break;
- case HTP_OP_UNARY_STEP: compute_func = (void *) step_f16; break;
- case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f16; break;
- case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f16; break;
- case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f16; break;
- default: break;
+ case HTP_OP_NORM: compute_func = (void *) norm_f16; break;
+ case HTP_OP_SCALE: compute_func = (void *) scale_f16; break;
+ case HTP_OP_CLAMP: compute_func = (void *) clamp_f16; break;
+ case HTP_OP_LEAKY_RELU: compute_func = (void *) leaky_relu_f16; break;
+ case HTP_OP_SQR: compute_func = (void *) sqr_f16; break;
+ case HTP_OP_SQRT: compute_func = (void *) sqrt_f16; break;
+ case HTP_OP_UNARY_NEG: compute_func = (void *) neg_f16; break;
+ case HTP_OP_UNARY_EXP: compute_func = (void *) (has_scale_bias ? exp_scale_bias_f16 : exp_f16); break;
+ case HTP_OP_UNARY_SIGMOID: compute_func = (void *) (has_scale_bias ? sigmoid_scale_bias_f16 : sigmoid_f16); break;
+ case HTP_OP_UNARY_SILU: compute_func = (void *) (has_scale_bias ? silu_scale_bias_f16 : silu_f16); break;
+ case HTP_OP_UNARY_GELU: compute_func = (void *) (has_scale_bias ? gelu_scale_bias_f16 : gelu_f16); break;
+ case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) (has_scale_bias ? gelu_quick_scale_bias_f16 : gelu_quick_f16); break;
+ case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) (has_scale_bias ? gelu_erf_scale_bias_f16 : gelu_erf_f16); break;
+ case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) (has_scale_bias ? softplus_scale_bias_f16 : softplus_f16); break;
+ case HTP_OP_UNARY_TANH: compute_func = (void *) (has_scale_bias ? tanh_scale_bias_f16 : tanh_f16); break;
+ case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f16; break;
+ case HTP_OP_UNARY_LOG: compute_func = (void *) log_f16; break;
+ case HTP_OP_UNARY_RELU: compute_func = (void *) relu_f16; break;
+ case HTP_OP_UNARY_STEP: compute_func = (void *) step_f16; break;
+ case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f16; break;
+ case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f16; break;
+ case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f16; break;
+ case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f16; break;
+ default: break;
}
- } else {
- task_func = unary_thread_row_block;
+ } else if (!compute_func) {
switch (octx->op) {
- case HTP_OP_NORM: compute_func = (void *) norm_f32; break;
- case HTP_OP_RMS_NORM: compute_func = (void *) rms_norm_f32; break;
- case HTP_OP_RMS_NORM_MUL:
- task_func = unary_thread_rms_norm_mul_f32;
- compute_func = (void *) rms_norm_mul_f32;
- break;
- case HTP_OP_RMS_NORM_MUL_ADD:
- task_func = unary_thread_rms_norm_mul_add_f32;
- compute_func = (void *) rms_norm_mul_add_f32;
- break;
- case HTP_OP_SCALE: compute_func = (void *) scale_f32; break;
- case HTP_OP_CLAMP: compute_func = (void *) clamp_f32; break;
- case HTP_OP_LEAKY_RELU: compute_func = (void *) leaky_relu_f32; break;
- case HTP_OP_SQR: compute_func = (void *) sqr_f32; break;
- case HTP_OP_SQRT: compute_func = (void *) sqrt_f32; break;
- case HTP_OP_UNARY_NEG: compute_func = (void *) neg_f32; break;
- case HTP_OP_UNARY_EXP: compute_func = (void *) exp_f32; break;
- case HTP_OP_UNARY_SIGMOID: compute_func = (void *) sigmoid_f32; break;
- case HTP_OP_UNARY_SILU: compute_func = (void *) silu_f32; break;
- case HTP_OP_UNARY_GELU: compute_func = (void *) gelu_f32; break;
- case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) gelu_quick_f32; break;
- case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) gelu_erf_f32; break;
- case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) softplus_f32; break;
- case HTP_OP_UNARY_TANH: compute_func = (void *) tanh_f32; break;
- case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f32; break;
- case HTP_OP_UNARY_LOG: compute_func = (void *) log_f32; break;
- case HTP_OP_UNARY_RELU: compute_func = (void *) relu_f32; break;
- case HTP_OP_UNARY_STEP: compute_func = (void *) step_f32; break;
- case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f32; break;
- case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f32; break;
- case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f32; break;
- case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f32; break;
+ case HTP_OP_NORM: compute_func = (void *) norm_f32; break;
+ case HTP_OP_SCALE: compute_func = (void *) scale_f32; break;
+ case HTP_OP_CLAMP: compute_func = (void *) clamp_f32; break;
+ case HTP_OP_LEAKY_RELU: compute_func = (void *) leaky_relu_f32; break;
+ case HTP_OP_SQR: compute_func = (void *) sqr_f32; break;
+ case HTP_OP_SQRT: compute_func = (void *) sqrt_f32; break;
+ case HTP_OP_UNARY_NEG: compute_func = (void *) neg_f32; break;
+ case HTP_OP_UNARY_EXP: compute_func = (void *) (has_scale_bias ? exp_scale_bias_f32 : exp_f32); break;
+ case HTP_OP_UNARY_SIGMOID: compute_func = (void *) (has_scale_bias ? sigmoid_scale_bias_f32 : sigmoid_f32); break;
+ case HTP_OP_UNARY_SILU: compute_func = (void *) (has_scale_bias ? silu_scale_bias_f32 : silu_f32); break;
+ case HTP_OP_UNARY_GELU: compute_func = (void *) (has_scale_bias ? gelu_scale_bias_f32 : gelu_f32); break;
+ case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) (has_scale_bias ? gelu_quick_scale_bias_f32 : gelu_quick_f32); break;
+ case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) (has_scale_bias ? gelu_erf_scale_bias_f32 : gelu_erf_f32); break;
+ case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) (has_scale_bias ? softplus_scale_bias_f32 : softplus_f32); break;
+ case HTP_OP_UNARY_TANH: compute_func = (void *) (has_scale_bias ? tanh_scale_bias_f32 : tanh_f32); break;
+ case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f32; break;
+ case HTP_OP_UNARY_LOG: compute_func = (void *) log_f32; break;
+ case HTP_OP_UNARY_RELU: compute_func = (void *) relu_f32; break;
+ case HTP_OP_UNARY_STEP: compute_func = (void *) step_f32; break;
+ case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f32; break;
+ case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f32; break;
+ case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f32; break;
+ case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f32; break;
case HTP_OP_TRI:
- task_func = unary_thread_tri_f32;
- compute_func = (void *) tri_f32;
+ task_func = col_tile ? unary_thread_tiled_tri_f32 : unary_thread_tri_f32;
+ compute_func = col_tile ? (void *) tri_apply_tile_f32 : (void *) tri_f32;
break;
- default: break;
+ default: break;
}
}
diff --git a/ggml/src/ggml-hexagon/htp/unary-ops.h b/ggml/src/ggml-hexagon/htp/unary-ops.h
index e03b2ac73..da11e3d76 100644
--- a/ggml/src/ggml-hexagon/htp/unary-ops.h
+++ b/ggml/src/ggml-hexagon/htp/unary-ops.h
@@ -11,14 +11,21 @@ struct htp_unary_kernel_params {
uint32_t n_hvx;
uint32_t col_tile;
uint32_t block;
- uint32_t broadcast_weight;
+ uint32_t broadcast_src1;
uint32_t src0_contig;
uint32_t src1_contig;
+ uint32_t src0_slice_dma;
uint32_t vtcm_size;
uint32_t tiles_per_row;
+ uint32_t has_scale_bias;
+ float in_scale;
+ float in_bias;
+ float out_scale;
+ float out_bias;
+
// Fastdiv helpers
struct fastdiv_values div_ne01;
struct fastdiv_values div_ne02;
@@ -94,6 +101,7 @@ struct htp_unary_vtcm_layout {
size_t src0_row_size_aligned;
size_t src1_row_size_aligned;
+ size_t src2_row_size_aligned;
size_t dst_row_size_aligned;
size_t src0_bytes;
@@ -108,30 +116,36 @@ static inline void htp_unary_vtcm_layout_build(
size_t src0_data_row_size,
size_t dst_data_row_size,
size_t src1_data_row_size,
- size_t elem_size,
+ size_t src2_data_row_size,
+ size_t src0_elem_size,
+ size_t dst_elem_size,
+ size_t src1_elem_size,
+ size_t src2_elem_size,
uint32_t col_tile,
uint32_t block,
- bool broadcast_weight,
+ bool broadcast_src1,
+ uint32_t src1_nrows,
uint32_t n_hvx
) {
- const bool has_weight = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src1_mul = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src2_add = (op == HTP_OP_RMS_NORM_MUL_ADD);
L->src0_row_size_aligned = hex_round_up(src0_data_row_size, 128);
L->dst_row_size_aligned = hex_round_up(dst_data_row_size, 128);
- L->src1_row_size_aligned = has_weight ? hex_round_up(src1_data_row_size, 128) : 0;
+ L->src1_row_size_aligned = has_src1_mul ? hex_round_up(src1_data_row_size, 128) : 0;
+ L->src2_row_size_aligned = has_src2_add ? hex_round_up(src2_data_row_size, 128) : 0;
if (col_tile > 0) {
- const size_t col_tile_bytes = col_tile * elem_size;
- L->src0_bytes = col_tile_bytes * 2;
- L->dst_bytes = col_tile_bytes * 2;
- L->src1_bytes = 0;
- L->src2_bytes = 0;
+ L->src0_bytes = (size_t) col_tile * src0_elem_size * 2;
+ L->dst_bytes = (size_t) col_tile * dst_elem_size * 2;
+ L->src1_bytes = has_src1_mul ? ((size_t) col_tile * src1_elem_size * 2) : 0;
+ L->src2_bytes = has_src2_add ? ((size_t) col_tile * src2_elem_size * 2) : 0;
} else {
L->src0_bytes = L->src0_row_size_aligned * block * 2;
- L->src2_bytes = (op == HTP_OP_RMS_NORM_MUL_ADD) ? L->src0_bytes : 0;
+ L->src2_bytes = has_src2_add ? (L->src2_row_size_aligned * block * 2) : 0;
L->dst_bytes = L->dst_row_size_aligned * block * 2;
- if (has_weight) {
- L->src1_bytes = broadcast_weight ? L->src1_row_size_aligned : (L->src1_row_size_aligned * block * 2);
+ if (has_src1_mul) {
+ L->src1_bytes = broadcast_src1 ? (L->src1_row_size_aligned * src1_nrows) : (L->src1_row_size_aligned * block * 2);
} else {
L->src1_bytes = 0;
}
@@ -152,36 +166,43 @@ static inline void htp_unary_solve_layout(
uint32_t ne10,
uint32_t ne11,
uint32_t max_block,
- bool broadcast_weight,
+ bool broadcast_src1,
+ uint32_t src1_nrows,
uint32_t n_hvx,
size_t vtcm_size,
- size_t elem_size,
+ size_t src0_elem_size,
+ size_t dst_elem_size,
+ size_t src1_elem_size,
+ size_t src2_elem_size,
uint32_t * out_col_tile,
uint32_t * out_vtcm_row_per_hvx
) {
- const bool has_weight = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src1_mul = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool has_src2_add = (op == HTP_OP_RMS_NORM_MUL_ADD);
- const size_t dst_elem_size = (op == HTP_OP_HADAMARD) ? sizeof(float) : elem_size;
- const size_t src0_data_row_size = ne00 * elem_size;
- const size_t dst_data_row_size = ne10 * dst_elem_size;
- const size_t src1_data_row_size = has_weight ? (ne11 * sizeof(float)) : 0;
+ const size_t eff_dst_elem_size = (op == HTP_OP_HADAMARD) ? sizeof(float) : dst_elem_size;
+ const size_t src0_data_row_size = ne00 * src0_elem_size;
+ const size_t dst_data_row_size = ne10 * eff_dst_elem_size;
+ const size_t src1_data_row_size = has_src1_mul ? (ne11 * src1_elem_size) : 0;
+ const size_t src2_data_row_size = has_src2_add ? (ne00 * src2_elem_size) : 0;
const size_t src0_row_size_aligned = hex_round_up(src0_data_row_size, 128);
const size_t dst_row_size_aligned = hex_round_up(dst_data_row_size, 128);
- const size_t src1_row_size_aligned = has_weight ? hex_round_up(src1_data_row_size, 128) : 0;
+ const size_t src1_row_size_aligned = has_src1_mul ? hex_round_up(src1_data_row_size, 128) : 0;
+ const size_t src2_row_size_aligned = has_src2_add ? hex_round_up(src2_data_row_size, 128) : 0;
size_t vtcm_size_per_row = 0;
size_t vtcm_row_per_hvx = 0;
if (op == HTP_OP_RMS_NORM_MUL_ADD) {
- size_t src1_vtcm_total = n_hvx * src1_row_size_aligned;
+ size_t src1_vtcm_total = n_hvx * src1_row_size_aligned * src1_nrows;
size_t available_vtcm = (vtcm_size > src1_vtcm_total) ? (vtcm_size - src1_vtcm_total) : 0;
- vtcm_size_per_row = 2 * (2 * src0_row_size_aligned + dst_row_size_aligned);
+ vtcm_size_per_row = 2 * (src0_row_size_aligned + src2_row_size_aligned + dst_row_size_aligned);
vtcm_row_per_hvx = available_vtcm / (n_hvx * vtcm_size_per_row);
} else if (op == HTP_OP_RMS_NORM_MUL) {
- if (broadcast_weight) {
+ if (broadcast_src1) {
size_t available_vtcm = vtcm_size;
- size_t src1_vtcm_total = n_hvx * src1_row_size_aligned;
+ size_t src1_vtcm_total = n_hvx * src1_row_size_aligned * src1_nrows;
if (available_vtcm > src1_vtcm_total) {
available_vtcm -= src1_vtcm_total;
} else {
@@ -202,27 +223,22 @@ static inline void htp_unary_solve_layout(
vtcm_row_per_hvx = max_block;
}
- const bool is_reduction = (op == HTP_OP_NORM || op == HTP_OP_RMS_NORM ||
- op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD ||
- op == HTP_OP_L2_NORM || op == HTP_OP_HADAMARD);
- // The tiled fallback path below only has F32 task functions (unary_task_f32_tiled_*);
- // F16 has no tiled kernels, so it must stay on the row-block path like reduction ops.
- // NOTE: if F16 ends up with vtcm_row_per_hvx == 0 here (row too large for the VTCM
- // budget), execute_op_unary() will see BLOCK == 0 and skip computation for that op
- // (logged via FARF(ERROR, ...)) since there is no F16 tiled fallback. This is a known
- // limitation; supporting it would require adding F16 tiled kernels.
- const bool is_f16 = (elem_size == sizeof(_Float16));
+ const bool is_rms_norm = (op == HTP_OP_RMS_NORM || op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD);
+ const bool is_reduction = (op == HTP_OP_NORM || is_rms_norm || op == HTP_OP_L2_NORM || op == HTP_OP_HADAMARD);
uint32_t col_tile = 0;
- if (vtcm_row_per_hvx == 0 && !is_reduction && !is_f16) {
+ if (vtcm_row_per_hvx == 0 && (!is_reduction || is_rms_norm)) {
const size_t per_hvx_budget = vtcm_size / n_hvx;
- const size_t col_tile_bytes = hex_align_down(per_hvx_budget / 4, 128);
- col_tile = (uint32_t) (col_tile_bytes / elem_size);
+ const size_t tile_elem_bytes = 2 * (src0_elem_size + eff_dst_elem_size +
+ (has_src1_mul ? src1_elem_size : 0) +
+ (has_src2_add ? src2_elem_size : 0));
+ col_tile = (uint32_t) hex_align_down(per_hvx_budget / tile_elem_bytes, 64);
}
const uint32_t block = col_tile ? 0 : (uint32_t) vtcm_row_per_hvx;
- htp_unary_vtcm_layout_build(L, op, src0_data_row_size, dst_data_row_size, src1_data_row_size,
- elem_size, col_tile, block, broadcast_weight, n_hvx);
+ htp_unary_vtcm_layout_build(L, op, src0_data_row_size, dst_data_row_size, src1_data_row_size, src2_data_row_size,
+ src0_elem_size, eff_dst_elem_size, src1_elem_size, src2_elem_size,
+ col_tile, block, broadcast_src1, src1_nrows, n_hvx);
*out_col_tile = col_tile;
*out_vtcm_row_per_hvx = (uint32_t) vtcm_row_per_hvx;
diff --git a/ggml/src/ggml-hexagon/htp/upscale-ops.c b/ggml/src/ggml-hexagon/htp/upscale-ops.c
index 59ab7914a..fe68a70d7 100644
--- a/ggml/src/ggml-hexagon/htp/upscale-ops.c
+++ b/ggml/src/ggml-hexagon/htp/upscale-ops.c
@@ -1,11 +1,10 @@
-#pragma clang diagnostic ignored "-Wunused-variable"
-
#include <float.h>
#include <math.h>
#include <HAP_farf.h>
#include "hex-common.h"
#include "dma-queue.h"
+#include "dma-pipeline.h"
#include "htp-trace.h"
#include "htp-ctx.h"
#include "htp-ops.h"
@@ -756,7 +755,64 @@ static inline void dma_push_src_chunk(
}
}
-static void upscale_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+struct upscale_pipe_state {
+ struct upscale_context * ctx;
+ const struct htp_upscale_kernel_params * p;
+ const struct htp_tensor * src0;
+ const struct htp_tensor * dst;
+ const void * lut_y;
+ float * R_buf;
+ float * gather_tmp;
+ uint32_t dst_row_size;
+ uint32_t dst_stride;
+ uint32_t chunk;
+ uint32_t chunk_end;
+};
+
+static bool upscale_next_task(void * ctx, struct dma_pipe_task * task) {
+ struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx;
+ if (s->chunk >= s->chunk_end) {
+ return false;
+ }
+ task->row = s->chunk++;
+ task->off = 0;
+ task->len = 0;
+ task->aux = 0;
+ return true;
+}
+
+static void upscale_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) {
+ struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx;
+ dma_addr_t slice_src_off;
+ uint32_t src_ys, src_yc;
+ resolve_src_slice(s->src0, s->dst, s->p, s->lut_y, task->row, &slice_src_off, &src_ys, &src_yc);
+ dma_push_src_chunk(dma_q, (float *) in_spad, s->src0, slice_src_off, src_ys, src_yc);
+}
+
+static void upscale_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) {
+ struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx;
+ dma_addr_t slice_dst_off;
+ uint32_t dst_ys, dst_yc;
+ resolve_dst_slice(s->dst, s->p, task->row, &slice_dst_off, &dst_ys, &dst_yc);
+
+ uint32_t src_ys, src_yc;
+ get_src_y_window(s->src0, s->dst, s->p, s->lut_y, dst_ys, dst_yc, &src_ys, &src_yc);
+
+ s->ctx->compute_chunk(s->ctx, (const float *) in_spad, (float *) out_spad, s->R_buf, s->gather_tmp, dst_ys, dst_yc, src_ys);
+}
+
+static void upscale_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) {
+ struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx;
+ dma_addr_t slice_dst_off;
+ uint32_t dst_ys, dst_yc;
+ resolve_dst_slice(s->dst, s->p, task->row, &slice_dst_off, &dst_ys, &dst_yc);
+
+ const dma_addr_t dst_addr = s->dst->data + slice_dst_off + (dma_addr_t) dst_ys * s->dst_stride;
+ dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), s->dst_stride, s->dst_row_size, s->dst_row_size, dst_yc);
+}
+
+static void upscale_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ (void) nth;
struct upscale_context * ctx = (struct upscale_context *) data;
const struct htp_upscale_kernel_params * p = ctx->kparams;
const struct htp_upscale_vtcm_layout * L = &ctx->layout;
@@ -770,74 +826,31 @@ static void upscale_worker(const htp_thread_t * th, unsigned int nth, unsigned i
return;
}
- struct htp_thread_trace * tr = th->trace;
- dma_queue * dma_q = th->dma_q;
-
const uint32_t src_spad_half = (uint32_t) L->src_spad_half_size;
const uint32_t dst_spad_half = (uint32_t) L->dst_spad_half_size;
uint8_t * vtcm_base = (uint8_t *) ctx->octx->ctx->vtcm_base;
uint8_t * src_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_src) + ith * L->src_bytes_per_hvx;
uint8_t * dst_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_dst) + ith * L->dst_bytes_per_hvx;
- float * R_buf = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_r) + ith * (L->r_bytes_per_hvx / sizeof(float));
- float * gather_tmp = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_gather) + ith * (L->gather_bytes_per_hvx / sizeof(float));
- const void * lut_y = ctx->lut_y;
-
- float * srcb2[2] = { (float *) src_spad, (float *) (src_spad + src_spad_half) };
- float * dstb2[2] = { (float *) dst_spad, (float *) (dst_spad + dst_spad_half) };
-
- const uint32_t dst_row_size = dst->ne[0] * sizeof(float);
- const uint32_t dst_stride = dst->nb[1];
-
- const uint32_t total = last - first;
-
- // Warmup: prime pipeline with initial transfers
- for (uint32_t i = 0; i < total && i < 2; ++i) {
- dma_queue_push(dma_q, dma_make_data(dst->data, dstb2[i]), dst_stride, dst_row_size, dst_row_size, 0);
-
- dma_addr_t slice_src_off;
- uint32_t src_ys, src_yc;
- resolve_src_slice(src0, dst, p, lut_y, first + i, &slice_src_off, &src_ys, &src_yc);
-
- dma_push_src_chunk(dma_q, srcb2[i], src0, slice_src_off, src_ys, src_yc);
- }
-
- // Steady state loop
- for (uint32_t i = 0; i < total; ++i) {
- const uint32_t buf = i & 1u;
- float * srcb = srcb2[buf];
- float * dstb = dstb2[buf];
-
- dma_queue_pop(dma_q);
- dma_queue_pop(dma_q);
-
- dma_addr_t slice_dst_off;
- uint32_t dst_ys, dst_yc;
- resolve_dst_slice(dst, p, first + i, &slice_dst_off, &dst_ys, &dst_yc);
-
- uint32_t src_ys, src_yc;
- get_src_y_window(src0, dst, p, lut_y, dst_ys, dst_yc, &src_ys, &src_yc);
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (first + i));
- ctx->compute_chunk(ctx, srcb, dstb, R_buf, gather_tmp, dst_ys, dst_yc, src_ys);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (first + i));
-
- const dma_addr_t dst_addr = dst->data + slice_dst_off + (dma_addr_t) dst_ys * dst_stride;
- dma_queue_push(dma_q, dma_make_data(dst_addr, dstb), dst_stride, dst_row_size, dst_row_size, dst_yc);
-
- const uint32_t next = i + 2;
- if (next < total) {
- dma_addr_t next_src_off;
- uint32_t next_src_ys, next_src_yc;
- resolve_src_slice(src0, dst, p, lut_y, first + next, &next_src_off, &next_src_ys, &next_src_yc);
-
- dma_push_src_chunk(dma_q, srcb, src0, next_src_off, next_src_ys, next_src_yc);
- }
- }
-
- dma_queue_flush(dma_q);
+ void * in_buf[2] = { src_spad, src_spad + src_spad_half };
+ void * out_buf[2] = { dst_spad, dst_spad + dst_spad_half };
+
+ struct upscale_pipe_state s = {
+ .ctx = ctx,
+ .p = p,
+ .src0 = src0,
+ .dst = dst,
+ .lut_y = ctx->lut_y,
+ .R_buf = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_r) + ith * (L->r_bytes_per_hvx / sizeof(float)),
+ .gather_tmp = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_gather) + ith * (L->gather_bytes_per_hvx / sizeof(float)),
+ .dst_row_size = dst->ne[0] * sizeof(float),
+ .dst_stride = dst->nb[1],
+ .chunk = first,
+ .chunk_end = last,
+ };
- (void) nth;
+ dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
+ upscale_next_task, upscale_push_in, upscale_compute, upscale_push_out);
}
int op_upscale(struct htp_ops_context * octx) {
@@ -856,7 +869,7 @@ int op_upscale(struct htp_ops_context * octx) {
if (octx->ctx->mdev.count > 1) {
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- chunk_count, htp_tensor_mdev_data_aligned(dst) ? p->chunks_per_group : 0,
+ chunk_count, 1,
octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
chunk_start = range.start;
chunk_count = range.count;
@@ -952,7 +965,7 @@ int op_upscale(struct htp_ops_context * octx) {
htp_upscale_vtcm_layout_build(&ctx.layout, src_x, src_y, dst_x, dst_y,
p->dst_nrows_per_chunk, p->inv_sf1, p->filter_radius1, n_hvx);
- work_queue_run(octx->ctx->hvx_queue, upscale_worker, &ctx, n_hvx);
+ work_queue_run(octx->ctx->hvx_queue, upscale_thread, &ctx, n_hvx);
return HTP_STATUS_OK;
}
diff --git a/ggml/src/ggml-hexagon/htp/upscale-ops.h b/ggml/src/ggml-hexagon/htp/upscale-ops.h
index 592bf7f00..b98d6cadb 100644
--- a/ggml/src/ggml-hexagon/htp/upscale-ops.h
+++ b/ggml/src/ggml-hexagon/htp/upscale-ops.h
@@ -44,7 +44,6 @@ struct htp_upscale_kernel_params {
float invscale1;
uint32_t n_hvx;
- uint32_t chunks_per_group;
uint32_t dst_nrows_per_chunk;
uint32_t chunks_per_slice;
diff --git a/ggml/src/ggml-hexagon/htp/work-queue.c b/ggml/src/ggml-hexagon/htp/work-queue.c
index 5d274274a..9839e1023 100644
--- a/ggml/src/ggml-hexagon/htp/work-queue.c
+++ b/ggml/src/ggml-hexagon/htp/work-queue.c
@@ -14,38 +14,30 @@
#define LOWEST_USABLE_QURT_PRIO (254)
-// internal structure kept in thread-local storage per instance of work queue
typedef struct {
htp_thread_t th;
work_queue_t queue;
} worker_context_t;
-struct work_queue_task_s {
+struct work_queue_s {
+ // Hot dispatch state: written by main thread, read by workers
+ // seqn encodes (counter << 8) | (n_threads & 0xff)
work_queue_func_t func;
void * data;
+ atomic_uint seqn;
+ atomic_uint active;
+ atomic_bool killed;
+
+ // Completion barrier: decremented by all workers on every seqn
+ atomic_uint barrier __attribute__((aligned(HEX_L2_LINE_SIZE)));
+
+ // Cold metadata
+ uint32_t last_seqn;
+ qurt_thread_t thread[HTP_MAX_NTHREADS];
+ worker_context_t context[HTP_MAX_NTHREADS];
+ void * stack[HTP_MAX_NTHREADS];
unsigned int n_threads;
- atomic_uint barrier;
-};
-
-// internal structure kept in thread-local storage per instance of work queue
-struct work_queue_s {
- atomic_uint seqn; // seqno used to detect new jobs
- atomic_uint idx_read; // Updated by producer (pop/reclaim)
- atomic_uint idx_write; // Updated by producer (push)
- uint32_t idx_mask;
- uint32_t capacity;
-
- qurt_thread_t thread[HTP_MAX_NTHREADS]; // thread ID's of the workers
- worker_context_t context[HTP_MAX_NTHREADS]; // worker contexts (0 = main, 1..n_workers = workers)
- void * stack[HTP_MAX_NTHREADS]; // thread stack pointers
- unsigned int n_threads; // total threads (workers + main)
- unsigned int n_workers; // number of active threads (just workers)
-
- atomic_uint active; // workers are polling/active
- atomic_bool killed; // threads need to exit
- bool external_mem; // memory owned externally
-
- struct work_queue_task_s queue[] __attribute__((aligned(HEX_L2_LINE_SIZE)));
+ unsigned int n_workers;
};
static void work_queue_thread(void * context) {
@@ -57,7 +49,7 @@ static void work_queue_thread(void * context) {
unsigned int prev_seqn = 0;
- while (!atomic_load_explicit(&q->killed, memory_order_relaxed)) {
+ while (!atomic_load_explicit(&q->killed, memory_order_acquire)) {
unsigned int seqn = atomic_load_explicit(&q->seqn, memory_order_acquire);
if (seqn == prev_seqn) {
if (atomic_load_explicit(&q->active, memory_order_relaxed)) {
@@ -71,34 +63,24 @@ static void work_queue_thread(void * context) {
prev_seqn = seqn;
- // Process all active tasks in the queue
- unsigned int ir = atomic_load_explicit(&q->idx_read, memory_order_relaxed);
- unsigned int iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed);
-
- while (ir != iw) {
- struct work_queue_task_s * task = &q->queue[ir];
-
- unsigned int n = task->n_threads;
- if (id < n) {
- task->func(&me->th, n, id, task->data);
-
- atomic_fetch_sub_explicit(&task->barrier, 1, memory_order_release);
- } else {
- while (atomic_load_explicit(&task->barrier, memory_order_relaxed) > 0) {
- hex_pause();
- }
- }
-
- ir = (ir + 1) & q->idx_mask;
+ unsigned int n = seqn & 0xffu;
+ if (id < n) {
+ q->func(&me->th, n, id, q->data);
}
+
+ atomic_fetch_sub_explicit(&q->barrier, 1, memory_order_release);
}
FARF(HIGH, "work-queue: thread %u (tid %u) stopped", id, me->th.tid);
}
bool work_queue_run(work_queue_t q, work_queue_func_t func, void * data, unsigned int n) {
- if (n <= 1) {
- func(&q->context[0].th, n, 0, data);
+ if (n == 0) {
+ return true;
+ }
+
+ if (n == 1) {
+ func(&q->context[0].th, 1, 0, data);
return true;
}
@@ -107,46 +89,33 @@ bool work_queue_run(work_queue_t q, work_queue_func_t func, void * data, unsigne
return false;
}
- unsigned int ir = atomic_load_explicit(&q->idx_read, memory_order_relaxed);
- unsigned int iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed);
-
- if (((iw + 1) & q->idx_mask) == ir) {
- FARF(ERROR, "work-queue-push: queue is full\n");
- return false;
+ if (!atomic_load_explicit(&q->active, memory_order_relaxed)) {
+ work_queue_wakeup(q);
}
- struct work_queue_task_s * task = &q->queue[iw];
- task->func = func;
- task->data = data;
- task->n_threads = n;
- atomic_store_explicit(&task->barrier, n, memory_order_relaxed);
-
- atomic_store_explicit(&q->idx_write, (iw + 1) & q->idx_mask, memory_order_relaxed);
+ q->func = func;
+ q->data = data;
+ atomic_store_explicit(&q->barrier, q->n_workers, memory_order_relaxed);
- // publish job to workers (already awake and polling)
- atomic_fetch_add_explicit(&q->seqn, 1, memory_order_release);
+ // publish job to all workers (every worker decrements barrier before returning)
+ atomic_store_explicit(&q->seqn, (++q->last_seqn << 8) | (n & 0xffu), memory_order_release);
// main thread runs job #0
func(&q->context[0].th, n, 0, data);
- atomic_fetch_sub_explicit(&task->barrier, 1, memory_order_release);
-
- while (atomic_load_explicit(&task->barrier, memory_order_relaxed) > 0) {
+ while (atomic_load_explicit(&q->barrier, memory_order_relaxed) > 0) {
hex_pause();
}
atomic_thread_fence(memory_order_acquire);
- atomic_store_explicit(&q->idx_read, (ir + 1) & q->idx_mask, memory_order_relaxed);
-
return true;
}
-size_t work_queue_sizeof(uint32_t n_threads, uint32_t capacity, uint32_t stack_size) {
- capacity = hex_ceil_pow2(capacity);
- uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0;
- size_t size_stacks = stack_size * n_workers;
- size_t size_q = hex_align_up(sizeof(struct work_queue_s) + capacity * sizeof(struct work_queue_task_s), HEX_L2_LINE_SIZE);
+size_t work_queue_sizeof(uint32_t n_threads, uint32_t stack_size) {
+ uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0;
+ size_t size_stacks = hex_align_up((size_t) stack_size * n_workers, HEX_L2_LINE_SIZE);
+ size_t size_q = hex_align_up(sizeof(struct work_queue_s), HEX_L2_LINE_SIZE);
return size_stacks + size_q;
}
@@ -154,18 +123,22 @@ size_t work_queue_alignof(void) {
return 4096;
}
-work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace) {
- capacity = hex_ceil_pow2(capacity);
- uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0;
- unsigned char * mem_blob = (unsigned char *) ptr;
+work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace) {
+ if (n_threads == 0 || n_threads > HTP_MAX_NTHREADS) {
+ FARF(ERROR, "work-queue: invalid n_threads %u (max %u)", n_threads, HTP_MAX_NTHREADS);
+ return NULL;
+ }
+
+ uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0;
+ size_t size_stacks = hex_align_up((size_t) stack_size * n_workers, HEX_L2_LINE_SIZE);
+ unsigned char * mem_blob = (unsigned char *) ptr;
- work_queue_t q = (work_queue_t) (mem_blob + stack_size * n_workers);
- memset(q, 0, sizeof(struct work_queue_s) + capacity * sizeof(struct work_queue_task_s));
+ work_queue_t q = (work_queue_t) (mem_blob + size_stacks);
+ memset(q, 0, sizeof(struct work_queue_s));
q->n_threads = n_threads;
q->n_workers = n_workers;
- q->external_mem = true;
- q->capacity = capacity;
+ q->last_seqn = 0;
for (unsigned int i = 0; i < n_threads; i++) {
htp_thread_init(&q->context[i].th, dma, trace);
@@ -173,22 +146,15 @@ work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity,
}
for (unsigned int i = 0; i < n_workers; i++) {
- q->stack[i] = mem_blob; mem_blob += stack_size;
+ q->stack[i] = mem_blob;
+ mem_blob += stack_size;
q->thread[i] = 0;
}
- atomic_init(&q->idx_read, 0);
- atomic_init(&q->idx_write, 0);
- atomic_init(&q->seqn, 0);
- atomic_init(&q->active, 0);
- q->idx_mask = capacity - 1;
- q->killed = 0;
- for (int i = 0; i < (int) capacity; i++) {
- atomic_init(&q->queue[i].barrier, 0);
- q->queue[i].func = NULL;
- q->queue[i].data = NULL;
- q->queue[i].n_threads = 0;
- }
+ atomic_init(&q->seqn, 0);
+ atomic_init(&q->active, 0);
+ atomic_init(&q->killed, false);
+ atomic_init(&q->barrier, 0);
// launch the workers
qurt_thread_attr_t attr;
@@ -225,12 +191,15 @@ work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity,
}
void work_queue_free(work_queue_t q) {
- if (!q) { return; }
+ if (!q) {
+ return;
+ }
- atomic_store_explicit(&q->killed, 1, memory_order_relaxed);
- atomic_store_explicit(&q->active, 1, memory_order_release);
- atomic_fetch_add_explicit(&q->seqn, 1, memory_order_release);
- qurt_futex_wake(&q->active, q->n_workers);
+ atomic_store_explicit(&q->killed, true, memory_order_release);
+ atomic_store_explicit(&q->active, 1, memory_order_release);
+ if (q->n_workers > 0) {
+ qurt_futex_wake(&q->active, q->n_workers);
+ }
for (unsigned int i = 0; i < q->n_workers; i++) {
if (q->thread[i]) {
@@ -243,7 +212,9 @@ void work_queue_free(work_queue_t q) {
void work_queue_wakeup(work_queue_t q) {
if (!atomic_load_explicit(&q->active, memory_order_relaxed)) {
atomic_store_explicit(&q->active, 1, memory_order_release);
- qurt_futex_wake(&q->active, q->n_workers);
+ if (q->n_workers > 0) {
+ qurt_futex_wake(&q->active, q->n_workers);
+ }
}
}
diff --git a/ggml/src/ggml-hexagon/htp/work-queue.h b/ggml/src/ggml-hexagon/htp/work-queue.h
index 446b72c46..bc5e4a3d6 100644
--- a/ggml/src/ggml-hexagon/htp/work-queue.h
+++ b/ggml/src/ggml-hexagon/htp/work-queue.h
@@ -12,9 +12,9 @@ typedef void (*work_queue_func_t)(const htp_thread_t * th, unsigned int n, unsig
struct work_queue_s;
typedef struct work_queue_s * work_queue_t;
-size_t work_queue_sizeof(uint32_t n_threads, uint32_t capacity, uint32_t stack_size);
+size_t work_queue_sizeof(uint32_t n_threads, uint32_t stack_size);
size_t work_queue_alignof(void);
-work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace);
+work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace);
void work_queue_free(work_queue_t q);
void work_queue_wakeup(work_queue_t q);
diff --git a/scripts/snapdragon/ggml-hexagon-trace.py b/scripts/snapdragon/ggml-hexagon-trace.py
index 308591b83..b9cae66fb 100755
--- a/scripts/snapdragon/ggml-hexagon-trace.py
+++ b/scripts/snapdragon/ggml-hexagon-trace.py
@@ -414,10 +414,107 @@ def write_trace_packet_to_file(f, packet_bytes):
# Write as field 1 of top-level Trace message
f.write(pb_length_delimited(1, packet_bytes))
+
# --- End Protobuf Encoder ---
+MERGE_DMA_DEFAULT_DEPTH = 8
+
+
+def merge_dma_events(completed_events: List[Dict[str, Any]], max_depth: int) -> List[Dict[str, Any]]:
+ other_events: List[Dict[str, Any]] = []
+ dma_by_thread: Dict[Any, List[Dict[str, Any]]] = defaultdict(list)
+
+ for e in completed_events:
+ if normalize_event_name(e['event'], e['info']) == "DMA":
+ dma_by_thread[(e['device'], e['thread'])].append(e)
+ else:
+ other_events.append(e)
+
+ if not dma_by_thread:
+ return completed_events
-def generate_perfetto_trace(filtered_ops, trace_events, output_path):
+ merged_dma: List[Dict[str, Any]] = []
+ merged_events_cnt = 0
+ merged_bursts_cnt = 0
+
+ for th_events in dma_by_thread.values():
+ th_events.sort(key=lambda e: (e['ts_ns'], e['ts_ns'] + e['dur_ns']))
+
+ clusters: List[List[Dict[str, Any]]] = []
+ cur_cluster = [th_events[0]]
+ cur_end = th_events[0]['ts_ns'] + th_events[0]['dur_ns']
+
+ for e in th_events[1:]:
+ e_end = e['ts_ns'] + e['dur_ns']
+ if e['ts_ns'] < cur_end:
+ cur_cluster.append(e)
+ if e_end > cur_end:
+ cur_end = e_end
+ else:
+ clusters.append(cur_cluster)
+ cur_cluster = [e]
+ cur_end = e_end
+ clusters.append(cur_cluster)
+
+ for cluster in clusters:
+ if len(cluster) <= max_depth:
+ merged_dma.extend(cluster)
+ continue
+
+ # (-1) sorts before (+1) at equal timestamps so back-to-back slices reuse slots
+ endpoints = []
+ for e in cluster:
+ endpoints.append((e['ts_ns'], 1))
+ endpoints.append((e['ts_ns'] + e['dur_ns'], -1))
+ endpoints.sort()
+
+ depth = 0
+ peak_depth = 0
+ for _, delta in endpoints:
+ depth += delta
+ if depth > peak_depth:
+ peak_depth = depth
+
+ if peak_depth <= max_depth:
+ merged_dma.extend(cluster)
+ continue
+
+ start_ts = cluster[0]['ts_ns']
+ end_ts = max(e['ts_ns'] + e['dur_ns'] for e in cluster)
+ first = cluster[0]
+ line_nums = [e['line_num'] for e in cluster if e.get('line_num') is not None]
+
+ merged_evt: Dict[str, Any] = {
+ 'thread': first['thread'],
+ 'event': first['event'],
+ 'info': first['info'],
+ 'start_cyc': min(e['start_cyc'] for e in cluster),
+ 'end_cyc': max(e['end_cyc'] for e in cluster),
+ 'ts_ns': start_ts,
+ 'dur_ns': max(end_ts - start_ts, 1),
+ 'line_num': min(line_nums) if line_nums else None,
+ 'device': first['device'],
+ 'merged_count': len(cluster),
+ 'max_depth': peak_depth,
+ }
+ if any(e.get('missing_start') for e in cluster):
+ merged_evt['missing_start'] = True
+ if any(e.get('missing_stop') for e in cluster):
+ merged_evt['missing_stop'] = True
+
+ merged_dma.append(merged_evt)
+ merged_events_cnt += len(cluster)
+ merged_bursts_cnt += 1
+
+ if merged_bursts_cnt > 0:
+ logger.info(f"Merged {merged_events_cnt} DMA events into {merged_bursts_cnt} slices (max_depth > {max_depth})")
+
+ result = other_events + merged_dma
+ result.sort(key=lambda e: (e['ts_ns'], e['start_cyc']))
+ return result
+
+
+def generate_perfetto_trace(filtered_ops, trace_events, output_path, merge_dma=None):
if not filtered_ops:
logger.warning("No operators found after filtering.")
return
@@ -516,6 +613,9 @@ def generate_perfetto_trace(filtered_ops, trace_events, output_path):
dur_ns = tm.dur_cycles_to_ns(e['start_cyc'], e['end_cyc'] - e['start_cyc'])
e['dur_ns'] = max(dur_ns, 1)
+ if merge_dma is not None:
+ completed_events = merge_dma_events(completed_events, merge_dma)
+
# Identify HMX threads dynamically from HMX* events
hmx_threads = {(e['device'], e['thread']) for e in completed_events if e['event'].startswith('HMX')}
@@ -688,7 +788,10 @@ def generate_perfetto_trace(filtered_ops, trace_events, output_path):
for e in completed_events:
norm_name = normalize_event_name(e['event'], e['info'])
if norm_name == "DMA":
- name = f"DMA {e['info']}"
+ if 'merged_count' in e:
+ name = f"DMA x{e['merged_count']}"
+ else:
+ name = f"DMA {e['info']}"
elif norm_name == "FENCE":
name = f"FENCE {e['info']}" if e.get('info') is not None and e['info'] != 0 else "FENCE"
else:
@@ -702,6 +805,9 @@ def generate_perfetto_trace(filtered_ops, trace_events, output_path):
debug_annots.append(make_debug_annotation("line", int_val=e['line_num']))
if norm_name == "FENCE" and e.get('info') is not None:
debug_annots.append(make_debug_annotation("seq", int_val=e['info']))
+ elif norm_name == "DMA" and 'merged_count' in e:
+ debug_annots.append(make_debug_annotation("count", int_val=e['merged_count']))
+ debug_annots.append(make_debug_annotation("max_depth", int_val=e['max_depth']))
elif norm_name == "DMA" and e.get('info') is not None:
debug_annots.append(make_debug_annotation("channel", int_val=e['info']))
elif e.get('info') is not None and e['info'] != 0:
@@ -731,12 +837,35 @@ def main():
parser.add_argument("-o", "--output", default="optrace.perfetto-trace", help="Output trace file path (default: optrace.perfetto-trace)")
parser.add_argument("--filter", type=str, help="Regex filter matching against the original profile-op line")
parser.add_argument("--device", type=str, help="Device to filter by (e.g. HTP0, HTP0:0) or 'split' to generate separate files per device")
+ parser.add_argument("--merge-dma", type=int, nargs="?", const=MERGE_DMA_DEFAULT_DEPTH, default=None, metavar="MAX_DEPTH",
+ help=f"Merge overlapping DMA bursts deeper than MAX_DEPTH into a single slice (default: {MERGE_DMA_DEFAULT_DEPTH}, use 1 to merge all)")
group = parser.add_mutually_exclusive_group()
group.add_argument("--head", type=int, help="Limit to first N ops")
group.add_argument("--tail", type=int, help="Limit to last N ops")
- args = parser.parse_args()
+ # Prevent nargs='?' on --merge-dma from consuming the positional logfile when no integer follows
+ raw_args = sys.argv[1:]
+ norm_args = []
+ i = 0
+ while i < len(raw_args):
+ if raw_args[i] == "--":
+ norm_args.extend(raw_args[i:])
+ break
+ if raw_args[i] == "--merge-dma":
+ if i + 1 < len(raw_args) and re.fullmatch(r"-?\d+", raw_args[i + 1]):
+ norm_args.append(f"--merge-dma={raw_args[i + 1]}")
+ i += 2
+ continue
+ norm_args.append(f"--merge-dma={MERGE_DMA_DEFAULT_DEPTH}")
+ i += 1
+ continue
+ norm_args.append(raw_args[i])
+ i += 1
+
+ args = parser.parse_args(norm_args)
+ if args.merge_dma is not None and args.merge_dma < 1:
+ parser.error("--merge-dma MAX_DEPTH must be >= 1")
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
op_filter_re = None
@@ -814,9 +943,9 @@ def main():
dev_ops = [op for op in ops if device_matches(op['device'], dev)]
dev_traces = [t for t in traces if device_matches(t['device'], dev)]
out_path = get_split_output_path(args.output, dev)
- generate_perfetto_trace(dev_ops, dev_traces, out_path)
+ generate_perfetto_trace(dev_ops, dev_traces, out_path, merge_dma=args.merge_dma)
else:
- generate_perfetto_trace(ops, traces, args.output)
+ generate_perfetto_trace(ops, traces, args.output, merge_dma=args.merge_dma)
if __name__ == "__main__":
diff --git a/scripts/snapdragon/run.py b/scripts/snapdragon/run.py
index 91b39a3f7..88b70ef96 100755
--- a/scripts/snapdragon/run.py
+++ b/scripts/snapdragon/run.py
@@ -20,6 +20,7 @@ MANAGED_ENV_NAMES = (
"GGML_HEXAGON_PROFILE",
"GGML_HEXAGON_NHVX",
"GGML_HEXAGON_NHMX",
+ "GGML_HEXAGON_POWER_MODE",
"GGML_HEXAGON_HOSTBUF",
"GGML_HEXAGON_DMA64",
"GGML_HEXAGON_OPBATCH",
@@ -27,12 +28,14 @@ MANAGED_ENV_NAMES = (
"GGML_HEXAGON_OPPOLL",
"GGML_HEXAGON_OPFILTER",
"GGML_HEXAGON_OPFUSION",
+ "GGML_HEXAGON_OPLOWER",
"GGML_HEXAGON_RT_REPACK",
"GGML_HEXAGON_VMEM",
+ "GGML_HEXAGON_VTCM_SIZE",
"GGML_HEXAGON_MBUF",
"GGML_HEXAGON_MM_SELECT",
"GGML_HEXAGON_FA_SELECT",
- "GGML_HEXAGON_FA_HEAD_SPLIT",
+ "GGML_HEXAGON_FA_SPLIT",
"GGML_HEXAGON_LI_SELECT",
"GGML_HEXAGON_GDN_SELECT",
"GGML_HEXAGON_SSM_SELECT",
@@ -212,15 +215,16 @@ def main():
parser.add_argument("--hex-dma64", nargs="?", const="1", help="Enable (1) or disable (0) 64-bit DMA for model weights (GGML_HEXAGON_DMA64)")
parser.add_argument("--hex-opbatch", help="Maximum number of operations to batch into a single HTP execution (GGML_HEXAGON_OPBATCH)")
parser.add_argument("--hex-opqueue", help="Size of the asynchronous NPU operation queue (GGML_HEXAGON_OPQUEUE)")
- parser.add_argument("--hex-oppoll", default="1", help="Enable (1) or Disable (0) polling for NPU opbatch completion (GGML_HEXAGON_OPPOLL) (default: 1)")
+ parser.add_argument("--hex-oppoll", default=None, help="NPU opbatch polling: 0=block, 1=poll, >1=hybrid poll budget in ms (GGML_HEXAGON_OPPOLL)")
parser.add_argument("--hex-opfilter", help="Regex pattern to filter/select which operators are offloaded to NPU (GGML_HEXAGON_OPFILTER)")
parser.add_argument("--hex-opfusion", help="NPU graph node fusion optimization level (0: disabled, 1: enabled) (GGML_HEXAGON_OPFUSION)")
- parser.add_argument("--hex-rt-repack", help="Runtime weight repacking mode (0: disabled, 1: quantized only, 2: always) (GGML_HEXAGON_RT_REPACK)")
+ parser.add_argument("--hex-oplower", help="NPU graph FP16 activation lowering (0: disabled, 1: enabled) (GGML_HEXAGON_OPLOWER)")
+ parser.add_argument("--hex-rt-repack", help="Runtime weight repacking mode (0: disabled, 1: all tileable weights) (GGML_HEXAGON_RT_REPACK)")
parser.add_argument("--hex-vmem", help="Maximum NPU VMEM size limit in MB to allocate (GGML_HEXAGON_VMEM)")
parser.add_argument("--hex-mbuf", help="Host buffer size limits in MB (supports K/M/G suffix): <dyn>[,<static>[,<total>]] (default: 512,1024,0) (GGML_HEXAGON_MBUF)")
- parser.add_argument("--hex-mm-select", help="Select MUL_MAT and MUL_MAT_ID kernel (GGML_HEXAGON_MM_SELECT) 2:HMX,1:HVX,0:disable")
- parser.add_argument("--hex-fa-select", help="Select Flash Attention kernel (GGML_HEXAGON_FA_SELECT) 2:HMX,1:HVX,0:disable")
- parser.add_argument("--hex-fa-head-split", help="Enable (1) or disable (0) head-parallel flash_attn partitioning (GGML_HEXAGON_FA_HEAD_SPLIT)")
+ parser.add_argument("--hex-mm-select", help="Select MUL_MAT and MUL_MAT_ID kernel (GGML_HEXAGON_MM_SELECT) 4:HMX-W8A8,3:HMX-W8A8-hybrid,2:HMX,1:HVX,0:disable")
+ parser.add_argument("--hex-fa-select", help="Select Flash Attention kernel (GGML_HEXAGON_FA_SELECT) 3:HMX-W8A8,2:HMX,1:HVX,0:disable")
+ parser.add_argument("--hex-fa-split", "--hex-fa-head-split", dest="hex_fa_split", help="Enable (1) or disable (0) Flash Attention head/team split (GGML_HEXAGON_FA_SPLIT)")
parser.add_argument("--hex-li-select", help="Select Lightning Indexer kernel (GGML_HEXAGON_LI_SELECT) 2:HMX,1:HVX,0:disable")
parser.add_argument("--hex-gdn-select", help="Select Gated Delta Net kernel (GGML_HEXAGON_GDN_SELECT) 2:HMX,1:HVX,0:disable")
parser.add_argument("--hex-ssm-select", help="Select SSM Scan kernel (GGML_HEXAGON_SSM_SELECT) 2:HMX,1:HVX,0:disable")
@@ -371,12 +375,13 @@ def main():
set_env("GGML_HEXAGON_OPPOLL", args.hex_oppoll)
set_env("GGML_HEXAGON_OPFILTER", args.hex_opfilter)
set_env("GGML_HEXAGON_OPFUSION", args.hex_opfusion)
+ set_env("GGML_HEXAGON_OPLOWER", args.hex_oplower)
set_env("GGML_HEXAGON_RT_REPACK", args.hex_rt_repack)
set_env("GGML_HEXAGON_VMEM", args.hex_vmem)
set_env("GGML_HEXAGON_MBUF", args.hex_mbuf)
set_env("GGML_HEXAGON_MM_SELECT", args.hex_mm_select)
set_env("GGML_HEXAGON_FA_SELECT", args.hex_fa_select)
- set_env("GGML_HEXAGON_FA_HEAD_SPLIT", args.hex_fa_head_split)
+ set_env("GGML_HEXAGON_FA_SPLIT", args.hex_fa_split)
set_env("GGML_HEXAGON_LI_SELECT", args.hex_li_select)
set_env("GGML_HEXAGON_GDN_SELECT", args.hex_gdn_select)
set_env("GGML_HEXAGON_SSM_SELECT", args.hex_ssm_select)
@@ -407,7 +412,7 @@ def main():
# Resolve executable path
executable = cmd_args[0]
- known_binaries = ["llama-cli", "llama-bench", "llama-completion", "llama-mtmd-cli", "test-backend-ops", "test-llama-archs"]
+ known_binaries = ["llama-cli", "llama-bench", "llama-completion", "llama-mtmd-cli", "llama-perplexity", "test-backend-ops", "test-llama-archs"]
if executable in known_binaries:
if target_type in ("android", "linux"):
resolved_exec = f"./bin/{executable}"
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index 03e8decb7..7df1c380f 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -1263,6 +1263,11 @@ struct test_case {
return build_graph(ctx);
}
+ static bool is_htp_backend(ggml_backend_t backend) {
+ ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend));
+ return reg && strcmp(ggml_backend_reg_name(reg), "HTP") == 0;
+ }
+
virtual double max_nmse_err() {
return 1e-7;
}
@@ -2599,6 +2604,7 @@ struct test_get_rows : public test_case {
}
}
}
+
};
// GGML_OP_GET_ROWS on a weight also used by GGML_OP_MUL_MAT (tied embeddings)
@@ -3627,6 +3633,7 @@ struct test_bin_bcast : public test_case {
bool src_overlap; // src0 and src1 are overlapping views of the same buffer
const ggml_type type_b; // type of src1, GGML_TYPE_COUNT -> same as src0
bool weights;
+ const ggml_type type_dst; // GGML_TYPE_COUNT -> op default
bool run_whole_graph() override { return nf > 1; }
@@ -3638,6 +3645,9 @@ struct test_bin_bcast : public test_case {
if (weights) {
s += ",weights=1";
}
+ if (type_dst != GGML_TYPE_COUNT) {
+ s += "," + VAR_TO_STR(type_dst);
+ }
return s;
}
@@ -3650,8 +3660,9 @@ struct test_bin_bcast : public test_case {
std::array<int, 4> nr = {1, 2, 1, 1},
int nf = 1,
bool perm1 = false, bool src_overlap = false,
- ggml_type type_b = GGML_TYPE_COUNT, bool weights = false)
- : op(op), type(type), ne(ne), nr(nr), nf(nf), perm1(perm1), src_overlap(src_overlap), type_b(type_b), weights(weights) {}
+ ggml_type type_b = GGML_TYPE_COUNT, bool weights = false,
+ ggml_type type_dst = GGML_TYPE_COUNT)
+ : op(op), type(type), ne(ne), nr(nr), nf(nf), perm1(perm1), src_overlap(src_overlap), type_b(type_b), weights(weights), type_dst(type_dst) {}
bool use_weight_context() override {
return weights;
@@ -3687,7 +3698,7 @@ struct test_bin_bcast : public test_case {
}
// The backward pass supports broadcasting only for GGML_ADD:
- const bool grad_supported = op == ggml_add && ggml_are_same_shape(a, b[0]) && nf == 1 && !perm1;
+ const bool grad_supported = op == ggml_add && type_dst == GGML_TYPE_COUNT && ggml_are_same_shape(a, b[0]) && nf == 1 && !perm1;
if (grad_supported) {
ggml_set_param(a);
ggml_set_param(b[0]);
@@ -3702,7 +3713,7 @@ struct test_bin_bcast : public test_case {
}
for (int i = 0; i < nf; ++i) {
- out = op(ctx, out, b[i]);
+ out = type_dst == GGML_TYPE_COUNT ? op(ctx, out, b[i]) : ggml_add_cast(ctx, out, b[i], type_dst);
}
ggml_set_name(out, "out");
@@ -4207,10 +4218,11 @@ struct test_rms_norm_mul_add : public test_case {
const bool multi_add; // test a sequence of adds feeding into rms_norm
const bool post_mul;
const bool alias_rms_input;
- const bool weight_broadcast;
+ const int weight_broadcast;
const ggml_type type_w; // type of b and d, GGML_TYPE_COUNT -> same as a
const ggml_type type_add; // type of c, GGML_TYPE_COUNT -> same as b
const bool swap; // the norm chain is the second operand of MUL and ADD
+ const bool has_add;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
@@ -4230,17 +4242,20 @@ struct test_rms_norm_mul_add : public test_case {
if (swap) {
s += "," + VAR_TO_STR(swap);
}
+ if (!has_add) {
+ s += "," + VAR_TO_STR(has_add);
+ }
return s;
}
test_rms_norm_mul_add(ggml_type type = GGML_TYPE_F32,
std::array<int64_t, 4> ne = {64, 5, 4, 3},
float eps = 1e-6f, bool broadcast = false, bool multi_add = false, bool post_mul = false,
- bool alias_rms_input = false, bool weight_broadcast = false, ggml_type type_w = GGML_TYPE_COUNT,
- ggml_type type_add = GGML_TYPE_COUNT, bool swap = false)
+ bool alias_rms_input = false, int weight_broadcast = 0, ggml_type type_w = GGML_TYPE_COUNT,
+ ggml_type type_add = GGML_TYPE_COUNT, bool swap = false, bool has_add = true)
: type(type), ne(ne), eps(eps), broadcast(broadcast), multi_add(multi_add), post_mul(post_mul),
alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast), type_w(type_w), type_add(type_add),
- swap(swap) {}
+ swap(swap), has_add(has_add) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
std::array<int64_t, 4> broadcast_dims = {ne[0]*2, ne[1]*3, ne[2]*3, ne[3]*4};
@@ -4249,7 +4264,7 @@ struct test_rms_norm_mul_add : public test_case {
const ggml_type ta = type_add == GGML_TYPE_COUNT ? tw : type_add;
ggml_tensor * a = ggml_new_tensor(ctx, type, 4, broadcast ? broadcast_dims.data() : ne.data());
- ggml_tensor * b = weight_broadcast ? ggml_new_tensor_1d(ctx, tw, ne[0]) : ggml_new_tensor(ctx, tw, 4, ne.data());
+ ggml_tensor * b = weight_broadcast > 0 ? ggml_new_tensor_2d(ctx, tw, ne[0], weight_broadcast) : ggml_new_tensor(ctx, tw, 4, ne.data());
ggml_tensor * c = ggml_new_tensor(ctx, ta, 4, ne.data());
ggml_tensor * d = nullptr;
@@ -4273,7 +4288,7 @@ struct test_rms_norm_mul_add : public test_case {
}
ggml_tensor * norm = ggml_rms_norm(ctx, a, eps);
ggml_tensor * mul = swap ? ggml_mul(ctx, b, norm) : ggml_mul(ctx, norm, b);
- ggml_tensor * out = alias_rms_input ? ggml_add_inplace(ctx, a, mul) : swap ? ggml_add(ctx, c, mul) : ggml_add(ctx, mul, c);
+ ggml_tensor * out = !has_add ? mul : (alias_rms_input ? ggml_add_inplace(ctx, a, mul) : (swap ? ggml_add(ctx, c, mul) : ggml_add(ctx, mul, c)));
if (post_mul) {
out = ggml_mul(ctx, out, d);
}
@@ -4290,7 +4305,10 @@ struct test_rms_norm_mul_add : public test_case {
double max_nmse_err() override {
// fused ops round to BF16 once, the CPU rounds after each op
- return type == GGML_TYPE_BF16 ? 1e-4 : test_case::max_nmse_err();
+ if (type == GGML_TYPE_BF16) {
+ return 1e-4;
+ }
+ return test_case::max_nmse_err();
}
float grad_eps() override {
@@ -4733,6 +4751,86 @@ struct test_add_unary_mul : public test_case {
}
};
+struct test_unary_scale_fusion : public test_case {
+ const ggml_unary_op op;
+ const ggml_type type;
+ const std::array<int64_t, 4> ne;
+ const float in_scale;
+ const float in_bias;
+ const float out_scale;
+ const float out_bias;
+ const std::string mode_str;
+
+ std::string op_desc(ggml_tensor * t) override {
+ GGML_UNUSED(t);
+ return "UNARY_SCALE_FUSION";
+ }
+
+ bool run_whole_graph() override { return true; }
+
+ double max_nmse_err(ggml_backend_t backend) override {
+ if (type == GGML_TYPE_F16 || (mode_str == "lower" && is_htp_backend(backend))) {
+ return 5e-5;
+ }
+ return 1e-6;
+ }
+
+ std::string vars() override {
+ std::string op_name = ggml_unary_op_name(op);
+ return VARS_TO_STR8(op_name, type, ne, in_scale, in_bias, out_scale, out_bias, mode_str);
+ }
+
+ test_unary_scale_fusion(
+ ggml_unary_op op,
+ ggml_type type,
+ std::array<int64_t, 4> ne,
+ float in_scale,
+ float in_bias,
+ float out_scale,
+ float out_bias,
+ std::string mode_str = "pre_post")
+ : op(op), type(type), ne(ne),
+ in_scale(in_scale), in_bias(in_bias),
+ out_scale(out_scale), out_bias(out_bias),
+ mode_str(std::move(mode_str)) {}
+
+ ggml_tensor * build_graph(ggml_context * ctx) override {
+ ggml_tensor * a = (mode_str == "lower")
+ ? ggml_new_tensor_4d(ctx, type, ne[0], 1, 1, 1)
+ : ggml_new_tensor(ctx, type, 4, ne.data());
+ ggml_set_name(a, "a");
+
+ ggml_tensor * cur = a;
+ if (mode_str == "lower") {
+ ggml_tensor * b_shape = ggml_new_tensor(ctx, type, 4, ne.data());
+ ggml_set_name(b_shape, "b_shape");
+ cur = ggml_repeat(ctx, cur, b_shape);
+ ggml_set_name(cur, "rep");
+ }
+ if (mode_str == "pre" || mode_str == "pre_post" || mode_str == "lower" || mode_str == "glu_guard") {
+ cur = (in_bias != 0.0f) ? ggml_scale_bias(ctx, cur, in_scale, in_bias) : ggml_scale(ctx, cur, in_scale);
+ ggml_set_name(cur, "scale_in");
+ }
+ cur = ggml_unary(ctx, cur, op);
+ ggml_set_name(cur, "unary");
+ if (mode_str == "post" || mode_str == "pre_post" || mode_str == "lower") {
+ cur = (out_bias != 0.0f) ? ggml_scale_bias(ctx, cur, out_scale, out_bias) : ggml_scale(ctx, cur, out_scale);
+ ggml_set_name(cur, "scale_out");
+ }
+ if (mode_str == "glu_guard") {
+ ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
+ ggml_set_name(b, "b");
+ cur = ggml_mul(ctx, cur, b);
+ } else if (mode_str == "lower") {
+ ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
+ ggml_set_name(b, "b");
+ cur = ggml_add(ctx, cur, b);
+ }
+ ggml_set_name(cur, "out");
+ return cur;
+ }
+};
+
// SNAKE activation fusion: y = x + sin(a*x)^2 * inv_b
// CUDA backend matches the naive 5-op chain (mul, sin, sqr, mul, add)
// and dispatches a single fused kernel.
@@ -4984,24 +5082,120 @@ struct test_dsv4_hc_post : public test_dsv4_hc {
}
};
+struct test_dsv4_hc_chain : public test_case {
+ const ggml_type wtype;
+ const int64_t n_embd;
+ const int64_t n_tokens;
+ const bool gated_pre;
+ const bool identity_post;
+
+ test_dsv4_hc_chain(ggml_type wtype = GGML_TYPE_Q4_0, int64_t n_embd = 96, int64_t n_tokens = 1,
+ bool gated_pre = true, bool identity_post = true)
+ : wtype(wtype), n_embd(n_embd), n_tokens(n_tokens), gated_pre(gated_pre), identity_post(identity_post) {}
+
+ std::string op_desc(ggml_tensor * t) override {
+ GGML_UNUSED(t);
+ return "DSV4_HC_POST";
+ }
+
+ std::string vars() override {
+ return VARS_TO_STR5(wtype, n_embd, n_tokens, gated_pre, identity_post);
+ }
+
+ bool run_whole_graph() override { return true; }
+
+ double max_nmse_err(ggml_backend_t backend) override {
+ return is_htp_backend(backend) ? 5e-3 : 5e-4;
+ }
+
+ ggml_tensor * build_graph(ggml_context * ctx) override {
+ constexpr int64_t n_hc = 4;
+ constexpr int64_t n_vocab = 64;
+
+ ggml_tensor * tok_embd = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
+ ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_tokens);
+ ggml_tensor * embd = ggml_get_rows(ctx, tok_embd, inp_tokens);
+ ggml_tensor * res_hc = ggml_repeat_4d(ctx, ggml_reshape_3d(ctx, embd, n_embd, 1, n_tokens), n_embd, n_hc, n_tokens, 1);
+
+ for (int l = 0; l < 2; ++l) {
+ ggml_tensor * w_norm = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_hc);
+ ggml_tensor * xn = ggml_mul(ctx, ggml_rms_norm(ctx, res_hc, 1e-5f), w_norm);
+ ggml_tensor * xn_2d = ggml_reshape_2d(ctx, xn, n_hc * n_embd, n_tokens);
+
+ ggml_tensor * mixed = nullptr;
+ if (gated_pre) {
+ ggml_tensor * w_gate = ggml_new_tensor_2d(ctx, wtype, n_hc * n_embd, n_hc * n_embd);
+ ggml_tensor * gate = ggml_mul_mat(ctx, w_gate, xn_2d);
+ mixed = ggml_dsv4_hc_pre_gated(ctx, xn, ggml_reshape_3d(ctx, gate, n_embd, n_hc, n_tokens), 1.0f / (float) n_hc);
+ } else {
+ ggml_tensor * w_pre = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_hc * n_embd, n_hc);
+ ggml_tensor * pre_w = ggml_sigmoid(ctx, ggml_mul_mat(ctx, w_pre, xn_2d));
+ mixed = ggml_dsv4_hc_pre(ctx, xn, pre_w);
+ }
+
+ ggml_tensor * w_blk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
+ ggml_tensor * blk_out = ggml_mul_mat(ctx, w_blk, mixed);
+
+ ggml_tensor * w_post = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_hc * n_embd, n_hc);
+ ggml_tensor * post_w = ggml_scale(ctx, ggml_sigmoid(ctx, ggml_scale(ctx, ggml_mul_mat(ctx, w_post, xn_2d), 1.0f / (float) n_hc)), 2.0f);
+
+ ggml_tensor * comb_w = nullptr;
+ if (!identity_post) {
+ ggml_tensor * w_comb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_hc * n_embd, n_hc * n_hc);
+ comb_w = ggml_reshape_3d(ctx, ggml_soft_max(ctx, ggml_mul_mat(ctx, w_comb, xn_2d)), n_hc, n_hc, n_tokens);
+ }
+
+ res_hc = ggml_dsv4_hc_post(ctx, blk_out, res_hc, post_w, comb_w);
+ }
+
+ ggml_set_name(res_hc, "out");
+ return res_hc;
+ }
+
+ void initialize_tensors(ggml_context * ctx) override {
+ for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
+ if (t->op != GGML_OP_NONE) {
+ continue;
+ }
+ if (t->type == GGML_TYPE_I32) {
+ std::vector<int32_t> data(ggml_nelements(t));
+ for (size_t i = 0; i < data.size(); ++i) {
+ data[i] = (int32_t) (i % 64);
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(int32_t));
+ } else {
+ init_tensor_uniform(t, -0.1f, 0.1f);
+ }
+ }
+ }
+};
+
// GGML_OP_SSM_CONV
struct test_ssm_conv : public test_case {
const ggml_type type;
const std::array<int64_t, 4> ne_a;
const std::array<int64_t, 4> ne_b;
+ const bool non_cont;
std::string vars() override {
- return VARS_TO_STR3(type, ne_a, ne_b);
+ return VARS_TO_STR4(type, ne_a, ne_b, non_cont);
}
test_ssm_conv(ggml_type type = GGML_TYPE_F32,
std::array<int64_t, 4> ne_a = {10, 10, 10, 1},
- std::array<int64_t, 4> ne_b = {3, 3, 1, 1})
- : type(type), ne_a(ne_a), ne_b(ne_b) {}
+ std::array<int64_t, 4> ne_b = {3, 3, 1, 1},
+ bool non_cont = false)
+ : type(type), ne_a(ne_a), ne_b(ne_b), non_cont(non_cont) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
- ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
+ ggml_tensor * a;
+ if (non_cont) {
+ ggml_tensor * a_full = ggml_new_tensor_4d(ctx, type, ne_a[0], ne_a[1], 2 * ne_a[2], ne_a[3]);
+ a = ggml_view_3d(ctx, a_full, ne_a[0], ne_a[1], ne_a[2], a_full->nb[1], 2 * a_full->nb[2], a_full->nb[2]);
+ } else {
+ a = ggml_new_tensor(ctx, type, 4, ne_a.data());
+ }
ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data());
ggml_tensor * out = ggml_ssm_conv(ctx, a, b);
return out;
@@ -5014,6 +5208,7 @@ struct test_ssm_conv_bias_silu : public test_case {
const std::array<int64_t, 4> ne_a;
const std::array<int64_t, 4> ne_b;
const bool fuse_bias;
+ const bool non_cont;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
@@ -5023,15 +5218,22 @@ struct test_ssm_conv_bias_silu : public test_case {
bool run_whole_graph() override { return true; }
std::string vars() override {
- return VARS_TO_STR4(type, ne_a, ne_b, fuse_bias);
+ return VARS_TO_STR5(type, ne_a, ne_b, fuse_bias, non_cont);
}
test_ssm_conv_bias_silu(ggml_type type, std::array<int64_t, 4> ne_a, std::array<int64_t, 4> ne_b,
- bool fuse_bias)
- : type(type), ne_a(ne_a), ne_b(ne_b), fuse_bias(fuse_bias) {}
+ bool fuse_bias, bool non_cont = false)
+ : type(type), ne_a(ne_a), ne_b(ne_b), fuse_bias(fuse_bias), non_cont(non_cont) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
- ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
+ ggml_tensor * a;
+ if (non_cont) {
+ ggml_tensor * a_full = ggml_new_tensor_4d(ctx, type, ne_a[0], ne_a[1], 2 * ne_a[2], ne_a[3]);
+ ggml_set_name(a_full, "a_full");
+ a = ggml_view_3d(ctx, a_full, ne_a[0], ne_a[1], ne_a[2], a_full->nb[1], 2 * a_full->nb[2], a_full->nb[2]);
+ } else {
+ a = ggml_new_tensor(ctx, type, 4, ne_a.data());
+ }
ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data());
ggml_set_name(a, "a");
ggml_set_name(b, "b");
@@ -5051,6 +5253,103 @@ struct test_ssm_conv_bias_silu : public test_case {
}
};
+// GGML_OP_CONCAT(conv_state, transpose(x), 0) + optional GGML_OP_CPY(state_out) + GGML_OP_SSM_CONV + optional GGML_OP_UNARY(SILU)
+struct test_ssm_conv_concat_fusion : public test_case {
+ const ggml_type type;
+ const int64_t d_conv;
+ const int64_t d_inner;
+ const int64_t n_t;
+ const int64_t n_s;
+ const bool use_silu;
+ const bool has_state_cpy;
+
+ ggml_tensor * conv_out_node = nullptr;
+ ggml_tensor * state_out_node = nullptr;
+
+ std::string op_desc(ggml_tensor * t) override {
+ GGML_UNUSED(t);
+ return "SSM_CONV_CONCAT_FUSION";
+ }
+
+ bool run_whole_graph() override { return true; }
+
+ std::string vars() override {
+ return VARS_TO_STR7(type, d_conv, d_inner, n_t, n_s, use_silu, has_state_cpy);
+ }
+
+ test_ssm_conv_concat_fusion(ggml_type type, int64_t d_conv, int64_t d_inner, int64_t n_t, int64_t n_s,
+ bool use_silu, bool has_state_cpy)
+ : type(type), d_conv(d_conv), d_inner(d_inner), n_t(n_t), n_s(n_s),
+ use_silu(use_silu), has_state_cpy(has_state_cpy) {}
+
+ double max_nmse_err(ggml_backend_t backend) override {
+ return is_htp_backend(backend) ? 1e-4 : test_case::max_nmse_err(backend);
+ }
+
+ std::vector<ggml_tensor *> fusion_test_nodes() override {
+ if (has_state_cpy && state_out_node) {
+ return { conv_out_node, state_out_node };
+ }
+ return { conv_out_node };
+ }
+
+ ggml_tensor * build_graph(ggml_context * ctx) override {
+ const int64_t s_cols = d_conv - 1;
+
+ ggml_tensor * state = ggml_new_tensor_3d(ctx, type, s_cols, d_inner, n_s);
+ ggml_set_name(state, "state");
+
+ ggml_tensor * x_raw = ggml_new_tensor_3d(ctx, type, d_inner, n_t, n_s);
+ ggml_set_name(x_raw, "x_raw");
+
+ // Feed rms_norm output into concat/ssm_conv so internal activations can be lowered while state stays F32
+ ggml_tensor * x = ggml_rms_norm(ctx, x_raw, 1e-5f);
+ ggml_set_name(x, "x");
+
+ ggml_tensor * weight = ggml_new_tensor_2d(ctx, type, d_conv, d_inner);
+ ggml_set_name(weight, "weight");
+
+ ggml_tensor * conv_x = ggml_concat(ctx, state, ggml_transpose(ctx, x), 0);
+ ggml_set_name(conv_x, "conv_x");
+
+ if (has_state_cpy) {
+ const int64_t mem_size = n_s + 2;
+ const int64_t kv_head = 1;
+
+ ggml_tensor * last = ggml_view_3d(ctx, conv_x,
+ s_cols, d_inner, n_s,
+ conv_x->nb[1], conv_x->nb[2],
+ ggml_row_size(conv_x->type, n_t));
+ ggml_set_name(last, "conv_x_tail");
+
+ ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, s_cols * d_inner, mem_size);
+ ggml_set_name(cache, "cache");
+
+ ggml_tensor * cell = ggml_view_2d(ctx, cache,
+ s_cols * d_inner, n_s,
+ cache->nb[1], kv_head * cache->nb[1]);
+ ggml_set_name(cell, "cell");
+
+ state_out_node = ggml_cpy(ctx, last, cell);
+ ggml_set_name(state_out_node, "state_cpy");
+ ggml_build_forward_expand(gf, state_out_node);
+ }
+
+ ggml_tensor * out = ggml_ssm_conv(ctx, conv_x, weight);
+ ggml_set_name(out, "conv_raw");
+
+ if (use_silu) {
+ out = ggml_silu(ctx, out);
+ ggml_set_name(out, "conv_silu");
+ }
+
+ // Consume conv output via rms_norm so conv output is an internal activation
+ conv_out_node = ggml_rms_norm(ctx, out, 1e-5f);
+ ggml_set_name(conv_out_node, "out");
+ return conv_out_node;
+ }
+};
+
// GGML_OP_SSM_SCAN
struct test_ssm_scan : public test_case {
const ggml_type type;
@@ -5402,6 +5701,13 @@ struct test_gated_delta_net : public test_case {
return s;
}
+ double max_nmse_err(ggml_backend_t backend) override {
+ if (is_htp_backend(backend) && !kda && (head_size == 64 || head_size == 128) && n_seq_tokens >= 8) {
+ return 5e-3;
+ }
+ return test_case::max_nmse_err(backend);
+ }
+
test_gated_delta_net(ggml_type type = GGML_TYPE_F32,
int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1,
int v_repeat = 1, bool permuted = false, bool kda = false, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f)
@@ -5414,21 +5720,27 @@ struct test_gated_delta_net : public test_case {
ggml_tensor * v;
if (permuted) {
// create with dims 1 and 2 swapped, then permute back to get non-contiguous layout
- q = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3);
- k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3);
- v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3);
+ q = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs);
+ k = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs);
+ v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs);
+ ggml_set_name(q, "q");
+ ggml_set_name(k, "k");
+ ggml_set_name(v, "v");
+ q = ggml_permute(ctx, q, 0, 2, 1, 3);
+ k = ggml_permute(ctx, k, 0, 2, 1, 3);
+ v = ggml_permute(ctx, v, 0, 2, 1, 3);
} else {
q = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs);
k = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs);
v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, head_count * v_repeat, n_seq_tokens, n_seqs);
+ ggml_set_name(q, "q");
+ ggml_set_name(k, "k");
+ ggml_set_name(v, "v");
}
if (padded_v) {
- ggml_set_name(v, "v");
v = ggml_view_4d(ctx, v, head_size, head_count * v_repeat, n_seq_tokens, n_seqs, v->nb[1], v->nb[2], v->nb[3], 0);
}
- ggml_set_name(q, "q");
- ggml_set_name(k, "k");
- ggml_set_name(v, "v");
+
const int64_t g_ne0 = kda ? head_size : 1;
ggml_tensor * g = ggml_new_tensor_4d(ctx, type, g_ne0, head_count * v_repeat, n_seq_tokens, n_seqs);
ggml_tensor * beta = ggml_new_tensor_4d(ctx, type, 1, head_count * v_repeat, n_seq_tokens, n_seqs);
@@ -5493,6 +5805,13 @@ struct test_gated_delta_net_replay : public test_case {
return VARS_TO_STR8(head_count, head_size, n_seq_tokens, n_seqs, v_repeat, kda, n_pend, keep);
}
+ double max_nmse_err(ggml_backend_t backend) override {
+ if (is_htp_backend(backend) && !kda && (head_size == 64 || head_size == 128) && n_seq_tokens >= 8) {
+ return 5e-3;
+ }
+ return test_case::max_nmse_err(backend);
+ }
+
test_gated_delta_net_replay(int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 4, int64_t n_seqs = 1,
int v_repeat = 1, bool kda = false, int64_t n_pend = 4, bool keep = true)
: head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs),
@@ -5598,16 +5917,35 @@ struct test_gated_delta_net_cache_fusion : public test_case {
const int64_t head_size;
const int64_t n_seq_tokens;
const int64_t n_seqs;
+ const bool kda;
+ const int64_t n_slots; // >0: use GET_ROWS(state_cache, s_copy) with non-zero slot index
- ggml_tensor * cpy_node = nullptr;
+ ggml_tensor * cpy_node = nullptr;
+ ggml_tensor * attn_out_node = nullptr;
std::string vars() override {
- return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
+ std::string s = VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
+ if (kda) {
+ s += "," + VAR_TO_STR(kda);
+ }
+ if (n_slots > 0) {
+ s += "," + VAR_TO_STR(n_slots);
+ }
+ return s;
+ }
+
+ double max_nmse_err(ggml_backend_t backend) override {
+ if (is_htp_backend(backend) && !kda && (head_size == 64 || head_size == 128) && n_seq_tokens >= 64) {
+ return 2e-2;
+ }
+ return is_htp_backend(backend) ? 1e-4 : test_case::max_nmse_err(backend);
}
test_gated_delta_net_cache_fusion(ggml_type type = GGML_TYPE_F32,
- int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1)
- : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
+ int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1,
+ bool kda = false, int64_t n_slots = 0)
+ : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs),
+ kda(kda), n_slots(n_slots) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
const int64_t S_v = head_size;
@@ -5615,17 +5953,31 @@ struct test_gated_delta_net_cache_fusion : public test_case {
const int64_t H_k = head_count;
const int64_t D = S_v * S_v * H_v;
- ggml_tensor * q = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
- ggml_tensor * k = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
- ggml_tensor * v = ggml_new_tensor_4d(ctx, type, head_size, H_v, n_seq_tokens, n_seqs);
+ ggml_tensor * q = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
+ ggml_tensor * k = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
+ ggml_tensor * v = ggml_new_tensor_4d(ctx, type, head_size, H_v, n_seq_tokens, n_seqs);
ggml_set_name(q, "q");
ggml_set_name(k, "k");
ggml_set_name(v, "v");
- ggml_tensor * g = ggml_new_tensor_4d(ctx, type, 1, H_v, n_seq_tokens, n_seqs);
+
+ const int64_t g_ne0 = kda ? head_size : 1;
+ ggml_tensor * g = ggml_new_tensor_4d(ctx, type, g_ne0, H_v, n_seq_tokens, n_seqs);
ggml_tensor * beta = ggml_new_tensor_4d(ctx, type, 1, H_v, n_seq_tokens, n_seqs);
- ggml_tensor * state = ggml_new_tensor_4d(ctx, type, head_size, head_size, H_v, n_seqs);
ggml_set_name(g, "g");
ggml_set_name(beta, "beta");
+
+ ggml_tensor * state = nullptr;
+ if (n_slots > 0) {
+ ggml_tensor * state_cache = ggml_new_tensor_2d(ctx, type, D, n_slots);
+ ggml_tensor * s_copy = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
+ ggml_set_name(state_cache, "state_cache");
+ ggml_set_name(s_copy, "s_copy");
+ ggml_tensor * states_all = ggml_get_rows(ctx, state_cache, s_copy);
+ ggml_tensor * states_view = ggml_view_2d(ctx, states_all, D, n_seqs, states_all->nb[1], 0);
+ state = ggml_reshape_4d(ctx, states_view, head_size, head_size, H_v, n_seqs);
+ } else {
+ state = ggml_new_tensor_4d(ctx, type, head_size, head_size, H_v, n_seqs);
+ }
ggml_set_name(state, "state");
q = ggml_l2_norm(ctx, q, 1e-6f);
@@ -5660,9 +6012,13 @@ struct test_gated_delta_net_cache_fusion : public test_case {
ggml_set_name(cpy, "gdn_cache_cpy");
cpy_node = cpy;
- // read the cpy output (not the plain dst view, which would not pull the cpy into the graph)
- // so that neither the gdn nor the cpy is the graph output
- ggml_tensor * out = ggml_sum(ctx, cpy);
+ ggml_tensor * attn_out = ggml_dup(ctx, attn);
+ ggml_set_name(attn_out, "attn_out");
+ ggml_set_output(attn_out);
+ attn_out_node = attn_out;
+
+ // read both cpy and attn_out so that cpy immediately follows gdn_out and attn view is live
+ ggml_tensor * out = ggml_add(ctx, ggml_sum(ctx, cpy), ggml_sum(ctx, attn_out));
return out;
}
@@ -5672,7 +6028,7 @@ struct test_gated_delta_net_cache_fusion : public test_case {
}
bool run_whole_graph() override { return true; }
- std::vector<ggml_tensor *> fusion_test_nodes() override { return { cpy_node }; }
+ std::vector<ggml_tensor *> fusion_test_nodes() override { return { cpy_node, attn_out_node }; }
uint64_t op_flops(ggml_tensor * t) override {
GGML_UNUSED(t);
@@ -5686,7 +6042,13 @@ struct test_gated_delta_net_cache_fusion : public test_case {
void initialize_tensors(ggml_context * ctx) override {
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
if (ggml_is_view_op(t->op)) { continue; }
- if (strcmp(t->name, "g") == 0) {
+ if (strcmp(t->name, "s_copy") == 0) {
+ std::vector<int32_t> ids(n_seqs);
+ for (int64_t i = 0; i < n_seqs; ++i) {
+ ids[i] = (int32_t) ((2 + i) % n_slots);
+ }
+ ggml_backend_tensor_set(t, ids.data(), 0, ids.size() * sizeof(int32_t));
+ } else if (strcmp(t->name, "g") == 0) {
init_tensor_uniform(t, -20.0f, -1e-4f);
} else if (strcmp(t->name, "beta") == 0) {
init_tensor_uniform(t, 0.0f, 1.0f);
@@ -8037,6 +8399,121 @@ struct test_top_k_inf : public test_top_k {
}
};
+// MoE router pattern: MUL_MAT[prec=F32] -> SOFT_MAX -> ARGSORT -> VIEW
+struct test_moe_router_prec_f32 : public test_case {
+ const int64_t k_dim;
+ const int64_t n_exp;
+ const int64_t n_tok;
+ const int64_t top_k;
+
+ test_moe_router_prec_f32(int64_t k_dim = 128, int64_t n_exp = 64, int64_t n_tok = 4, int64_t top_k = 8)
+ : k_dim(k_dim), n_exp(n_exp), n_tok(n_tok), top_k(top_k) {}
+
+ std::string vars() override {
+ return VARS_TO_STR4(k_dim, n_exp, n_tok, top_k);
+ }
+
+ std::string op_desc(ggml_tensor * t) override {
+ GGML_UNUSED(t);
+ return "ARGSORT";
+ }
+
+ bool run_whole_graph() override { return true; }
+
+ ggml_tensor * build_graph(ggml_context * ctx) override {
+ ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k_dim, n_exp);
+ ggml_tensor * x = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k_dim, n_tok);
+ ggml_set_name(w, "gate_inp_w");
+ ggml_set_name(x, "ffn_norm");
+
+ ggml_tensor * logits = ggml_mul_mat(ctx, w, x);
+ ggml_prec_set_acc(logits, GGML_PREC_F32);
+ ggml_set_name(logits, "router_logits");
+
+ ggml_tensor * probs = ggml_soft_max(ctx, logits);
+ ggml_set_name(probs, "router_probs");
+
+ ggml_tensor * sorted = ggml_argsort(ctx, probs, GGML_SORT_ORDER_DESC);
+ ggml_set_name(sorted, "router_sorted");
+
+ ggml_tensor * top = ggml_view_2d(ctx, sorted, top_k, n_tok, sorted->nb[1], 0);
+ ggml_tensor * out = ggml_cont(ctx, top);
+ ggml_set_name(out, "out");
+ return out;
+ }
+
+ void initialize_tensors(ggml_context * ctx) override {
+ for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
+ if (strcmp(t->name, "gate_inp_w") == 0) {
+ std::vector<float> data(k_dim * n_exp, 0.0f);
+ for (int64_t r = 0; r < n_exp; ++r) {
+ data[r * k_dim + (r % k_dim)] = 1.0f + 0.03125f * (float) (r + 1);
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float));
+ } else if (strcmp(t->name, "ffn_norm") == 0) {
+ std::vector<float> data(k_dim * n_tok);
+ for (int64_t tok = 0; tok < n_tok; ++tok) {
+ for (int64_t c = 0; c < k_dim; ++c) {
+ data[tok * k_dim + c] = 1.0f + 0.015625f * (float) ((c + tok * 7) % k_dim);
+ }
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float));
+ } else if (t->type == GGML_TYPE_I32) {
+ std::vector<int32_t> data(ggml_nelements(t), 0);
+ ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
+ } else if (t->type == GGML_TYPE_F32) {
+ init_tensor_uniform(t);
+ }
+ }
+ }
+};
+
+// Two-block pre-norm FFN residual chain: rms_norm -> mul -> mul_mat -> silu -> mul_mat -> add
+struct test_ffn_residual_fusion : public test_case {
+ const ggml_type wtype;
+ const int64_t n_embd;
+ const int64_t n_ff;
+ const int64_t n_tok;
+
+ test_ffn_residual_fusion(ggml_type wtype = GGML_TYPE_Q4_0, int64_t n_embd = 128, int64_t n_ff = 256, int64_t n_tok = 4)
+ : wtype(wtype), n_embd(n_embd), n_ff(n_ff), n_tok(n_tok) {}
+
+ std::string vars() override {
+ return VARS_TO_STR4(wtype, n_embd, n_ff, n_tok);
+ }
+
+ std::string op_desc(ggml_tensor * t) override {
+ GGML_UNUSED(t);
+ return "MUL_MAT_FUSION";
+ }
+
+ bool run_whole_graph() override { return true; }
+
+ double max_nmse_err(ggml_backend_t backend) override {
+ return is_htp_backend(backend) ? 5e-3 : 5e-4;
+ }
+
+ ggml_tensor * build_graph(ggml_context * ctx) override {
+ ggml_tensor * inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_tok);
+ ggml_tensor * nw0 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
+ ggml_tensor * wu0 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
+ ggml_tensor * wd0 = ggml_new_tensor_2d(ctx, wtype, n_ff, n_embd);
+ ggml_tensor * nw1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
+ ggml_tensor * wu1 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
+
+ ggml_tensor * cur0 = ggml_mul(ctx, ggml_rms_norm(ctx, inpL, 1e-5f), nw0);
+ cur0 = ggml_silu(ctx, ggml_mul_mat(ctx, wu0, cur0));
+ cur0 = ggml_mul_mat(ctx, wd0, cur0);
+ ggml_tensor * res0 = ggml_add(ctx, cur0, inpL);
+
+ ggml_tensor * cur1 = ggml_mul(ctx, ggml_rms_norm(ctx, res0, 1e-5f), nw1);
+ cur1 = ggml_mul_mat(ctx, wu1, cur1);
+ ggml_tensor * out = ggml_add(ctx, cur1, res0);
+ ggml_set_name(out, "out");
+ return out;
+ }
+};
+
// qwen4exp QSA indexer top-k fusion: expand per-block scores to cells, add the f16 mask, top-k.
struct test_topk_qsa : public test_case {
const int64_t n_blocks;
@@ -11171,6 +11648,14 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 128, 2, 2, 2 }, v));
test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 5, 7, 11, 13 }, v));
+ if (type == GGML_TYPE_F16) {
+ test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 33, 2, 2, 2 }, v));
+ test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 65, 2, 2, 2 }, v));
+ test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 127, 2, 2, 2 }, v));
+ if (v == 0) {
+ test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 65536, 2, 1, 1 }, v));
+ }
+ }
}
}
}
@@ -11223,6 +11708,25 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
// a unary op with no fused kernel must fall back to the three-op chain
test_cases.emplace_back(new test_add_unary_mul(GGML_UNARY_OP_GELU, GGML_TYPE_F32, { 32, 7, 1, 1 }));
+ // fused [SCALE ->] UNARY [-> SCALE] chains
+ for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) {
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_EXP, type, { 256, 16, 1, 1 }, -0.5f, 0.0f, 2.0f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 2.0f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, type, { 133, 7, 1, 1 }, 0.25f, 0.0f, 2.0f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SILU, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 1.0f, 0.0f, "pre"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, type, { 256, 16, 1, 1 }, 1.0f, 0.0f, 1.0f, 1e-4f, "post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU, type, { 256, 16, 1, 1 }, 0.5f, 0.1f, 1.5f, -0.1f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU_QUICK, type, { 256, 16, 1, 1 }, 0.5f, 0.1f, 1.5f, -0.1f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU_ERF, type, { 256, 16, 1, 1 }, 0.5f, 0.1f, 1.5f, -0.1f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SOFTPLUS, type, { 256, 16, 1, 1 }, 0.69314718f, 0.0f, 1.44269504f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_TANH, type, { 256, 16, 1, 1 }, 1.0f / 30.0f, 0.0f, 30.0f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_TANH, type, { 32768, 2, 1, 1 }, 1.0f / 30.0f, 0.0f, 30.0f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_TANH, type, { 100032, 8, 1, 1 }, 1.0f / 30.0f, 0.0f, 30.0f, 0.0f, "pre_post"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SILU, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 1.0f, 0.0f, "glu_guard"));
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 1.0f, 0.0f, "glu_guard"));
+ }
+ test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, GGML_TYPE_F32, { 256, 16, 1, 1 }, 0.25f, 0.0f, 2.0f, 0.0f, "lower"));
+
// SNAKE activation fusion: x + sin(a*x)^2 * inv_b
for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16 }) {
test_cases.emplace_back(new test_snake_fuse(type, { 5, 7, 1, 1})); // primes sub-block
@@ -11268,6 +11772,12 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_dsv4_hc_post(31, 17, false, true));
test_cases.emplace_back(new test_dsv4_hc_post(4096, 1)); // DeepSeek-V4-Flash decode
test_cases.emplace_back(new test_dsv4_hc_post(2560, 1, true, true)); // Qwen4-Exp decode
+ for (int64_t n_embd : {96, 256}) {
+ for (int64_t n_tokens : {1, 64}) {
+ test_cases.emplace_back(new test_dsv4_hc_chain(GGML_TYPE_Q4_0, n_embd, n_tokens, true, true));
+ test_cases.emplace_back(new test_dsv4_hc_chain(GGML_TYPE_Q4_0, n_embd, n_tokens, false, false));
+ }
+ }
for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
// blocks with extra cells and scores (k-pool)
@@ -11375,6 +11885,11 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
test_cases.emplace_back(new test_get_rows(GGML_TYPE_F32, 256, 8, 2, 1, 1, false, true, 3));
+ test_cases.emplace_back(new test_get_rows(GGML_TYPE_F16, 256, 8, 2, 1, 1, false, true, 3));
+ for (int n : { 31, 33, 64, 128, 256 }) {
+ test_cases.emplace_back(new test_get_rows(GGML_TYPE_F16, n, 8, 5, 3, 2, false, false));
+ test_cases.emplace_back(new test_get_rows(GGML_TYPE_F16, n, 8, 5, 3, 2, false, true, 4));
+ }
test_cases.emplace_back(new test_get_rows_back(GGML_TYPE_F32, 1, 8, 2, 1, false));
test_cases.emplace_back(new test_get_rows_back(GGML_TYPE_F32, 1, 70000, 4, 1, false)); // row count > CUDA grid-y limit (65535)
@@ -11417,6 +11932,22 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_I32, { 256, 5, 1, 3 }, { 1, 1, }, 1, false));
test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, false));
+ for (ggml_type dst_type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
+ for (ggml_type idx_type : {GGML_TYPE_I32, GGML_TYPE_I64}) {
+ for (int64_t ne0 : {31, 33, 64, 128, 256}) {
+ for (bool v : {false, true}) {
+ test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, dst_type, idx_type, { ne0, 5, 2, 2 }, { 1, 1 }, 4, v));
+ }
+ }
+ }
+ }
+ for (ggml_type idx_type : {GGML_TYPE_I32, GGML_TYPE_I64}) {
+ for (int64_t ne0 : {64, 128, 256}) {
+ for (bool v : {false, true}) {
+ test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_Q8_0, idx_type, { ne0, 5, 2, 2 }, { 1, 1 }, 4, v));
+ }
+ }
+ }
for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) {
for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
@@ -12107,6 +12638,16 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
+ for (auto op : {ggml_add, ggml_sub, ggml_mul, ggml_div}) {
+ test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {33, 5, 2, 1}, {1, 1, 1, 1}, 1, false, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {127, 1, 1, 1}, {1, 5, 2, 1}, 1, false, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {1, 1, 1, 1}, {256, 5, 2, 1}, 1, false, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {33, 2, 1, 1}, {2, 3, 1, 1}, 1, false, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {33, 5, 4, 3}, {1, 1, 1, 1}, 1, true, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {256, 3, 2, 1}, {1, 1, 1, 1}, 1, false, false, GGML_TYPE_F32));
+ }
+ test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F16, {127, 5, 2, 1}, {1, 1, 1, 1}, 1, false, false, GGML_TYPE_F32, false, GGML_TYPE_F32));
+
for (auto op : {ggml_add, ggml_mul}) {
test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F32, {1, 2, 2, 2}, {17, 1, 1, 1}, 1, false, false, GGML_TYPE_COUNT, true));
}
@@ -12200,7 +12741,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
for (uint32_t n : {1, 127, 129, 511, 513, 2816, 4096, 16385}) {
test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {n, 3, 2, 1}));
test_cases.emplace_back(new test_rms_norm_mul_rope({n, 3, 2, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NORMAL, true, false));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {n, 3, 2, 1}, 1e-6f, false, false, false, false, 1));
}
// BF16 x with F32 weights, n > 1 because the NMSE of a single BF16 output is too noisy
@@ -12208,11 +12749,11 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
for (uint32_t n : {127, 128, 512, 1024, 2048, 2816, 4096, 8192, 16385}) {
test_cases.emplace_back(new test_rms_norm(GGML_TYPE_BF16, {n, 3, 2, 1}));
test_cases.emplace_back(new test_rms_norm_mul_rope({n, 3, 2, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NORMAL, true, false, GGML_TYPE_F16, false, true, GGML_TYPE_BF16));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, 1, GGML_TYPE_F32));
// BF16 residual added after the norm (post-norm models, e.g. Gemma)
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true, GGML_TYPE_F32, GGML_TYPE_BF16));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, 1, GGML_TYPE_F32, GGML_TYPE_BF16));
for (bool multi_add : {false, true}) {
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 1, 1, 1}, 1e-6f, false, multi_add, false, false, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 1, 1, 1}, 1e-6f, false, multi_add, false, false, 0, GGML_TYPE_F32));
}
}
@@ -12230,10 +12771,10 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
for (uint32_t n : { 64, 1025 }) {
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false));
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_COUNT, GGML_TYPE_COUNT, true));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_F32));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32, GGML_TYPE_BF16));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false, false, false, false, 0, GGML_TYPE_COUNT, GGML_TYPE_COUNT, true));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, false, false, false, false, 0, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, 0, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, 0, GGML_TYPE_F32, GGML_TYPE_BF16));
test_cases.emplace_back(new test_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false));
test_cases.emplace_back(new test_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true));
test_cases.emplace_back(new test_add_rms_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false));
@@ -12273,13 +12814,29 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 1536, 1, 1, 1 }, 1e-6f, false, false, true));
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 1, 1 }, 1e-6f, false, false, true));
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true, false, true));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true, false, 1));
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true));
test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 1, 1 }, 1e-6f, false, false, false, true));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, false, GGML_TYPE_F32));
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, false, GGML_TYPE_F32, GGML_TYPE_BF16));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, 0, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, 0, GGML_TYPE_F32, GGML_TYPE_BF16));
// the ADD operand is the BF16 input itself, added in place
- test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true, false, GGML_TYPE_F32));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true, 0, GGML_TYPE_F32));
+ // dim-1 broadcast weights [ne0, ne1, 1, 1] across [ne0, ne1, ne2, ne3]
+ for (bool has_add : { false, true }) {
+ for (bool post_mul : { false, true }) {
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 2560, 4, 33, 1 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 5120, 4, 33, 1 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 3, 5, 2 }, 1e-6f, false, false, post_mul, false, 3, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 4, 3, 2 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_F32, GGML_TYPE_COUNT, false, has_add));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 3, 5, 2 }, 1e-6f, false, false, post_mul, false, 3, GGML_TYPE_F32, GGML_TYPE_COUNT, false, has_add));
+ if (has_add) {
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 4, 3, 2 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_F32, GGML_TYPE_BF16, false, true));
+ test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 3, 5, 2 }, 1e-6f, false, false, post_mul, false, 3, GGML_TYPE_F32, GGML_TYPE_BF16, false, true));
+ }
+ }
+ }
+
test_cases.emplace_back(new test_rms_norm_mul_rope({128, 4, 7, 2}));
test_cases.emplace_back(new test_rms_norm_mul_rope({128, 4, 7, 2}, 1e-6f, false, true));
@@ -12358,6 +12915,30 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
+ for (bool use_silu : {false, true}) {
+ for (bool has_state_cpy : {false, true}) {
+ for (int64_t n_t : {1, 2, 64, 200}) {
+ for (int64_t n_s : {1, 2}) {
+ test_cases.emplace_back(new test_ssm_conv_concat_fusion(
+ GGML_TYPE_F32, 4, 256, n_t, n_s, use_silu, has_state_cpy));
+ }
+ test_cases.emplace_back(new test_ssm_conv_concat_fusion(
+ GGML_TYPE_F32, 4, 160, n_t, 1, use_silu, has_state_cpy));
+ test_cases.emplace_back(new test_ssm_conv_concat_fusion(
+ GGML_TYPE_F32, 4, 144, n_t, 2, use_silu, has_state_cpy));
+ }
+ for (int64_t d_conv : {3, 5}) {
+ for (int64_t n_t : {1, 2, 64}) {
+ test_cases.emplace_back(new test_ssm_conv_concat_fusion(
+ GGML_TYPE_F32, d_conv, 256, n_t, 1, use_silu, has_state_cpy));
+ test_cases.emplace_back(new test_ssm_conv_concat_fusion(
+ GGML_TYPE_F32, d_conv, 160, n_t, 2, use_silu, has_state_cpy));
+ }
+ }
+ }
+ }
+
+
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 16, 1, 1024, 1, 32, 4)); // Mamba-1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 64, 64, 112, 2, 32, 4)); // Zamba2 (real hparams: d_inner=7168, dt_rank=112, n_group=2 -> head_dim=7168/112=64)
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 64, 64, 112, 2, 1, 1)); // Zamba2 decode (single-token, matches real per-token decode workload)
@@ -12576,6 +13157,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_MXFP4, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1}));
+
// m == 1, with n on both sides of MMVF_MAX_BATCH_SIZE (8): mmvf below, operand swap above
for (int64_t n : {1, 7, 8, 9, 16, 127, 128, 511, 512}) {
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 1, n, 2048, {1, 1}, {1, 1}));
@@ -13066,6 +13648,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
+
for (ggml_type type_a : base_types) {
for (ggml_type type_b : {GGML_TYPE_F32, GGML_TYPE_F16}) {
for (int n : {1, 16}) {
@@ -13139,6 +13722,12 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_clamp (type, {1024, 1024, 1, 1}));
test_cases.emplace_back(new test_leaky_relu(type, {7, 1, 5, 3}));
test_cases.emplace_back(new test_leaky_relu(type, {1024, 1024, 1, 1}));
+ if (type == GGML_TYPE_F16) {
+ test_cases.emplace_back(new test_leaky_relu(type, {33, 2, 2, 2}));
+ test_cases.emplace_back(new test_leaky_relu(type, {65, 2, 2, 2}));
+ test_cases.emplace_back(new test_leaky_relu(type, {127, 2, 2, 2}));
+ test_cases.emplace_back(new test_leaky_relu(type, {65536, 2, 1, 1}));
+ }
test_cases.emplace_back(new test_floor (type, {7, 1, 5, 3}));
test_cases.emplace_back(new test_floor (type, {1024, 1024, 1, 1}));
test_cases.emplace_back(new test_ceil (type, {7, 1, 5, 3}));
@@ -13212,6 +13801,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {643251, 3, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 65537, 1, 1}));
+
for (float max_bias : {0.0f, 8.0f}) {
for (float scale : {1.0f, 0.1f}) {
for (int64_t ne0 : {16, 1024}) {
@@ -13281,9 +13871,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_rope(type, { 36, 16, 2457, 1}, 36, rmode, 512, fs, ef, af, ff, 2, fw));
}
}
-
- all = false;
}
+
+ all = false;
}
}
}
@@ -13334,11 +13924,26 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
- // Real-model RoPE: F32 forward, packed Q, 512-token prefill.
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global
+ // Partial n_dims < ne0 (e.g. Qwen3.5 partial RoPE: n_dims = 64, 96 with ne0 = 128) across modes, freq_factors, and strided views.
+ for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
+ for (int n_dims : {64, 96}) {
+ for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE}) {
+ for (bool ff : {false, true}) {
+ for (int v : {0, 1, 2}) {
+ test_cases.emplace_back(new test_rope(type, {128, 16, 2, 1}, n_dims, mode, 512, 1.0f, 0.0f, 1.0f, ff, v, true));
+ }
+ }
+ }
+ }
+ }
+
+ // Real-model RoPE: F32/F16 forward, packed Q, 512-token prefill.
+ for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
+ test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B
+ test_cases.emplace_back(new test_rope(type, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B
+ test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding
+ test_cases.emplace_back(new test_rope(type, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global
+ }
for (int v : { 0, 1, 2, 3, 16 }) {
for (int dim : { 0, 1, 2, 3, }) {
@@ -13383,13 +13988,16 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_concat(GGML_TYPE_F16, {98306, 8, 1, 1}, 286, 0, 0));
// GDN conv_input
- for (int64_t ne_b_d : { 31, 32, 33, 64 }) {
- test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 10240, 1, 1}, ne_b_d, 0, 16));
- test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {1, 37, 1, 1}, ne_b_d, 0, 16));
+ for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) {
+ for (int64_t ne_b_d : { 31, 32, 33, 64 }) {
+ test_cases.emplace_back(new test_concat(type, {3, 10240, 1, 1}, ne_b_d, 0, 16));
+ test_cases.emplace_back(new test_concat(type, {1, 37, 1, 1}, ne_b_d, 0, 16));
+ }
+ test_cases.emplace_back(new test_concat(type, {64, 37, 1, 1}, 32, 0, 16));
+ // Empty src0
+ test_cases.emplace_back(new test_concat(type, {0, 64, 1, 1}, 33, 0, 16));
}
- test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {64, 37, 1, 1}, 32, 0, 16));
- // Empty src0
- test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {0, 64, 1, 1}, 33, 0, 16));
+
for (ggml_sort_order order : {GGML_SORT_ORDER_ASC, GGML_SORT_ORDER_DESC}) {
for (uint32_t i = 4; i <= 1024*1024; i *= 2) {
@@ -13473,6 +14081,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_topk_qsa(256, 2048, 4, 2, 2000));
test_cases.emplace_back(new test_topk_qsa(64, 256, 2, 1, 200)); // small k: unfused fallback
+
// exhaustive top_k tests
//for (int i = 1; i < 9999; ++i) {
// test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {i, 2, 1, 3}, rand() % i + 1));
@@ -14118,6 +14727,12 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
// on DGX Spark also the expert gate and up matmuls at 8 tokens, instead of the fused MMVQ path
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 8, 128, 2048, true, 16, 4, true));
+ for (int64_t n_tok : {1, 4, 16}) {
+ test_cases.emplace_back(new test_moe_router_prec_f32(128, 64, n_tok, 8));
+ test_cases.emplace_back(new test_ffn_residual_fusion(GGML_TYPE_Q4_0, 128, 256, n_tok));
+ test_cases.emplace_back(new test_ffn_residual_fusion(GGML_TYPE_Q8_0, 128, 256, n_tok));
+ }
+
for (auto gate : {GATING_FUNC_SOFTMAX, GATING_FUNC_SIGMOID, GATING_FUNC_SOFTMAX_WEIGHT, GATING_FUNC_SQRT_SOFTPLUS}) {
for (bool with_norm : {false, true}) {
for (bool bias_probs : {false, true}) {
@@ -14285,6 +14900,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1));
test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 1, 1, false, 4));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 64, 1, false, 4));
#if 0
// these tests are disabled to save execution time, sbut they can be handy for debugging
@@ -14824,11 +15441,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
}
}
- // Real-model RoPE: F32 forward, packed Q, 512-token prefill.
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding
- test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global
+ // Real-model RoPE: F32/F16 forward, packed Q, 512-token prefill.
+ for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
+ test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B
+ test_cases.emplace_back(new test_rope(type, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B
+ test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding
+ test_cases.emplace_back(new test_rope(type, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global
+ }
std::vector<std::array<int64_t, 4>> reduce_rows_cases = {
{ 8192, 1, 1, 1 },