Commit c2d2fc6a1 for llama.cpp
commit c2d2fc6a1066f773b57ff63d4aaec32132240186
Author: Max Krasnyansky <maxk@qti.qualcomm.com>
Date: Mon Nov 30 06:23:29 2026 -0800
hexagon: add support for online FWHT-32 and Quant Scales (#33347)
* hexagon : add online FWHT-32 rotation for HMX W8A8 matmul
* hexagon : add quant scale tensor support and fuse weight scales into matmul
* hexagon : add support for F8_E4M3
* hexagon : fuse rms_norm into mul_mat
* hexagon : split matmul-ops.c into separate HMX-F16, HMX-W8A8, and HVX files
* hexagon : refactor fusion, lowering, and kparams solver
diff --git a/docs/backend/snapdragon/README.md b/docs/backend/snapdragon/README.md
index aea52a067..35329136e 100644
--- a/docs/backend/snapdragon/README.md
+++ b/docs/backend/snapdragon/README.md
@@ -309,16 +309,25 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs
By default, the Hexagon backend is tuned for higher NPU throughput and lower memory bandwidth while preserving strong
end-to-end accuracy across typical models. Specifically, batched matrix multiplications default to `W8A8` integer HMX
(`--hex-mm-select 3`), which dynamically quantizes activations into 8-bit (`uint8` x `int8`) blocks with a 2048-element
-`K`-group scale (using HVX when `M <= 4`),
-and internal `FP32` activation tensors within each HTP subgraph are automatically lowered in-place to `FP16`
-(`--hex-oplower 1`). If a particular model or workload exhibits accuracy degradation (for example due to large activation
-outliers or `FP16` residual overflow), try stepping down to higher-precision configurations in the following order:
-
-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
+`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:
+
+| MMSEL | FWHT | OPLWR | Matmul | Intermediates | Notes |
+| :---: | :--: | :---: | --------------- | :-----------: | ----------------------------------------------------------------------------------- |
+| 3 | 0 | 1 | `W8A8` HMX | `FP16` | Default; maximum prefill speed |
+| 3 | 1 | 1 | `W8A8` HMX+FWHT | `FP16` | Higher accuracy on models with activation outliers |
+| 3 | 1 | 0 | `W8A8` HMX+FWHT | `FP32` | Avoids `FP16` activation/residual overflow while keeping `W8A8` HMX (higher DDR BW) |
+| 2 | - | 1 | `FP16` HMX | `FP16` | Higher matmul precision without `W8A8` quantization |
+| 2 | - | 0 | `FP16` HMX | `FP32` | Maximum HMX precision (`FP16` HMX + `FP32` intermediates) |
+
+Notes:
+- `MMSEL`: `GGML_HEXAGON_MM_SELECT` (`--hex-mm-select` in `run.py`); see `GGML_HEXAGON_MM_SELECT` below for `W8A8` integer HMX mode details
+- `FWHT`: `GGML_HEXAGON_MM_FWHT` (`--hex-mm-fwht` in `run.py`)
+- `OPLWR`: `GGML_HEXAGON_OPLOWER` (`--hex-oplower` in `run.py`)
+- Under `MMSEL=3`, projections tagged with `GGML_PREC_F32` automatically use `FP16` HMX.
## Environment variables
@@ -369,14 +378,8 @@ outliers or `FP16` residual overflow), try stepping down to higher-precision con
Unknown values are logged as a warning and fall back to `burst`.
- This must be set in the environment before the process initializes the backend registry, so
- there is no `llama-*` CLI flag for it. The `run.py` runner exposes it as `--hex-power-mode`.
-
- Examples:
-
- `GGML_HEXAGON_POWER_MODE=balanced llama-completion ...`
- `./scripts/snapdragon/run.py --hex-power-mode sustained_high_performance ...`
-
+ This must be set in the environment before the process initializes the backend registry.
+ The `run.py` runner exposes it as `--hex-power-mode`.
- `GGML_HEXAGON_VERBOSE=1`
Enables verbose logging of Ops from the backend. Example output:
@@ -426,9 +429,16 @@ outliers or `FP16` residual overflow), try stepping down to higher-precision con
- `0`: Disabled (falls back to CPU or GPU)
- `1`: HVX vector kernels only
- - `2`: FP16 HMX matrix engine (`M > 4`) with HVX decode (`M <= 4`)
- - `3`: Hybrid INT HMX `W8A8` (`uint8` activations x `int8` weights) with FP16 HMX fallback on post-GLU / `GGML_PREC_F32` projections and HVX decode (`M <= 4`) (default; automatically defaults to 2 on multi-session v73 hardware unless overridden)
- - `4`: Pure INT HMX `W8A8` everywhere (`M > 4`) with HVX decode (`M <= 4`)
+ - `2`: `FP16` HMX matrix engine
+ - `3`: `W8A8` integer HMX matrix engine (default)
+
+ All HMX modes fall back to HVX vector kernels for small batch sizes (`M <= 4`).
+
+- `GGML_HEXAGON_MM_FWHT=0|1`
+ Enables online block-32 Fast Walsh-Hadamard Transform (FWHT) rotation along `K` in `W8A8` HMX matmul (configurable via `--hex-mm-fwht` in `run.py`):
+
+ - `0`: Disabled (default)
+ - `1`: Enabled - higher accuracy on models with activation outliers
- `GGML_HEXAGON_OPPOLL=N`
Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`):
@@ -437,4 +447,5 @@ outliers or `FP16` residual overflow), try stepping down to higher-precision con
- `1`: Full polling (keeps the host CPU awake for minimum wakeup latency; best for peak benchmarking and profiling)
- `> 1`: Hybrid polling budget in milliseconds - polls for up to `N` ms per opbatch before falling back to a blocking wait (default: `50` when supported by the FastRPC driver, `0` otherwise)
- The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills). For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling.
+ The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills).
+ For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling.
diff --git a/docs/backend/snapdragon/developer.md b/docs/backend/snapdragon/developer.md
index 9602848c6..74c084676 100644
--- a/docs/backend/snapdragon/developer.md
+++ b/docs/backend/snapdragon/developer.md
@@ -119,6 +119,13 @@ columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns
- **Scales** (bytes 512..575): UE4M3 bytes, `tile[512 + 32*u + row]` for sub-block `u = 0..1` of the k-tile.
- The per-tensor F32 scale is not part of the tile.
+- **F8_E4M3** (1024 bytes per tile, `HTP_TENSOR_TILE_SIZE_F8_E4M3`, lossless tiling with same size as flat FP8):
+ - **Values** (bytes 0..1023, 8 HVX vectors `p = 0..7`):
+ Contains 32 rows x 32 columns of signed 8-bit E4M3 floating-point values (`S:1, E:4 bias 7, M:3`; `0x7F`/`0xFF` = NaN decoded as 0).
+ Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`) in 4-K-grouped (`vrmpy`) byte order:
+ `tile[p * 128 + row * 4 + j] = W[row][4*p + j]` for `row = 0..31`, `j = 0..3`.
+ - Optional F32 weight scale (per-tensor, per-channel, or per-expert) is passed separately and folded in-kernel.
+
- **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`):
- **Quants** (bytes 0..511, 512 bytes):
Same 4-K-grouped nibble layout as `Q4_0`.
diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp
index b5f05b8f1..ddbd35a9e 100644
--- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp
+++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp
@@ -135,6 +135,7 @@ size_t opt_mbuf_static = 1ul * 1024 * 1024 * 1024; // max static (weight/KV) buf
size_t opt_mbuf_total = 0; // total buffer space limit (0 = unconstrained)
int opt_mm_select = 3; // 3 = W8A8 INT HMX -> FP16 HMX -> HVX -> CPU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
+int opt_mm_fwht = 0; // 1 = enable online block-32 FWHT rotation in W8A8 HMX matmul, 0 = off (default)
int opt_fa_select = 3; // 3 = INT HMX W8A8 (default) -> FP16 HMX -> HVX -> CPU, 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
int opt_fa_split = 1; // 1 = head-split + team-split when n_kv_heads < N_cores (default), 0 = off
int opt_li_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported)
@@ -365,7 +366,7 @@ struct ggml_hexagon_session {
std::unordered_map<uint64_t, volatile uint32_t *> cpy_fence_slots;
void enqueue_mdev_group();
- void enqueue_op(const htp_opnode & node, bool allow_fuse = true);
+ void enqueue_op(const htp_opnode & node, bool fusable = false);
void enqueue_cpy(const ggml_tensor * src, ggml_tensor * dst, const ggml_tensor * sync_tensor = nullptr, uint32_t fence_seq = 0);
void enqueue_fence(const ggml_tensor * sync_tensor, uint32_t fence_seq = 0, bool wait = true);
void enqueue_allreduce(const ggml_tensor * dst, const std::vector<const ggml_tensor *> & src_tensors,
@@ -1342,26 +1343,27 @@ struct ggml_hexagon_tensor_map {
};
struct ggml_hexagon_opbatch {
- ggml_hexagon_session* sess;
+ ggml_hexagon_session* sess;
- std::vector<htp_opnode> ops; // htp_opnode of ops
- std::vector<htp_buf_desc> h_bufs; // htp buffer descriptors
- std::vector<htp_tensor> h_tens; // htp tensor descriptors
- std::vector<htp_op_desc> h_ops; // htp op descriptors
+ std::vector<htp_opnode> ops; // htp_opnode of ops
+ std::vector<htp_buf_desc> h_bufs; // htp buffer descriptors
+ std::vector<htp_tensor> h_tens; // htp tensor descriptors
+ std::vector<htp_op_desc> h_ops; // htp op descriptors
- ggml_hexagon_tensor_map t_map; // tensor hash to index
+ ggml_hexagon_tensor_map t_map; // tensor hash to index
- unsigned int n_bufs; // num buffers in the batch
- unsigned int n_tens; // num tensors ...
- unsigned int n_ops; // num ops ...
- size_t b_vmem; // sum of non-extended buffer sizes
- bool last_op_fusable;
+ unsigned int n_bufs; // num buffers in the batch
+ unsigned int n_tens; // num tensors ...
+ unsigned int n_ops; // num ops ...
+ size_t b_vmem; // sum of non-extended buffer sizes
unsigned int n_bufs_max;
unsigned int n_tens_max;
unsigned int n_ops_max;
size_t b_vmem_max;
+ bool last_op_fusable;
+
void reset() {
n_bufs = 0;
n_tens = 0;
@@ -1586,14 +1588,14 @@ struct ggml_hexagon_opbatch {
}
// caller must ensure the op fits
- void add_op(const htp_opnode & node, bool save_op = true) {
+ void add_op(const htp_opnode & node, bool save_op = true, bool fusable = false) {
unsigned int n = n_ops++;
GGML_ASSERT(n_ops <= n_ops_max);
if (save_op) {
ops[n] = node;
}
- last_op_fusable = save_op;
+ last_op_fusable = fusable;
h_ops[n].flags = 0;
if (opt_verbose) {
@@ -1656,6 +1658,7 @@ struct ggml_hexagon_opbatch {
htp_lower_opnode(sess, last_node);
sync_op_desc(n_ops - 1, last_node);
+ last_op_fusable = false;
HEX_VERBOSE("ggml-hex: %s fused %s (N=%zu, #%u)\n",
sess->c_name(), last_node.name().c_str(), last_node.fused.size() + 1, n_ops - 1);
return true;
@@ -1970,7 +1973,7 @@ void ggml_hexagon_session::flush_batch(size_t min_ops) {
op_batch->reset();
}
-void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse) {
+void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool fusable) {
auto register_tensor = [&](const ggml_tensor * t) {
if (!t) return;
auto * sbuf = static_cast<ggml_hexagon_shared_buffer *>(t->buffer->context);
@@ -2000,7 +2003,7 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse)
}
const bool fits_tensors = op_batch->fit_tensors(node);
- if (opt_opfusion && allow_fuse && fits_tensors && op_batch->try_fuse(node)) {
+ if (opt_opfusion && fits_tensors && op_batch->try_fuse(node)) {
return;
}
@@ -2015,7 +2018,8 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse)
}
}
- op_batch->add_op(node, opt_profile || (opt_opfusion && allow_fuse));
+ const bool mark_fusable = opt_opfusion && fusable;
+ op_batch->add_op(node, opt_profile || mark_fusable, mark_fusable);
}
void ggml_hexagon_session::enqueue_mdev_group() {
@@ -2104,7 +2108,7 @@ void ggml_hexagon_session::enqueue_allreduce(
this, dst, rank, n_ranks, false, false, /*is_shard_ok=*/ false,
ar_node.kparams<htp_allreduce_kernel_params>());
- this->enqueue_op(ar_node);
+ this->enqueue_op(ar_node, /*fusable=*/ true);
}
void ggml_hexagon_session::mmap_buffers() {
@@ -2629,6 +2633,30 @@ static void ggml_hexagon_graph_repack(const ggml_cgraph * graph, ggml_hexagon_se
}
}
+static void ggml_hexagon_graph_append_opnode(
+ const ggml_hexagon_session * sess,
+ std::vector<htp_opnode> & nodes,
+ htp_opnode && node
+) {
+ const ggml_tensor * n = node.node;
+ const ggml_tensor * scale = ggml_get_src_scale(n, 0);
+ const bool fused_scale = scale != nullptr &&
+ (node.opcode == HTP_OP_MUL_MAT || node.opcode == HTP_OP_MUL_MAT_ID) &&
+ (node.kparams<htp_mm_kernel_params>()->scale_mask != 0);
+ if (fused_scale) {
+ node.inputs.push_back(scale);
+ }
+ if (nodes.empty() || !opt_opfusion || !htp_fusion_try_fuse(sess, nodes.back(), node)) {
+ nodes.push_back(std::move(node));
+ }
+
+ if (scale && !fused_scale) {
+ htp_opnode scale_node = htp_mm_make_scale_opnode(n, scale);
+ GGML_ASSERT(htp_kparams_solve(sess, scale_node));
+ nodes.push_back(std::move(scale_node));
+ }
+}
+
static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, ggml_cgraph * graph) {
auto sess = static_cast<ggml_hexagon_session *>(backend->context);
@@ -2662,9 +2690,7 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg
htp_opnode node(opcode, n);
GGML_ASSERT(htp_kparams_solve(sess, node));
- if (nodes.empty() || !opt_opfusion || !htp_fusion_try_fuse(sess, nodes.back(), node)) {
- nodes.push_back(std::move(node));
- }
+ ggml_hexagon_graph_append_opnode(sess, nodes, std::move(node));
}
if (opt_opfusion) {
@@ -2677,7 +2703,7 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg
}
for (const auto & node : sess->cached_nodes) {
- sess->enqueue_op(node, false);
+ sess->enqueue_op(node);
}
if (sess->last_error > HTP_STATUS_OK) {
@@ -3233,10 +3259,7 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons
return false;
}
- if (ggml_get_src_scale(op, 0)) {
- return false;
- }
-
+ // src_scale(op, 1) is an activation quantization hint for quantized-activation backends, ignored for F32/F16 activations
bool supp = false;
if (ggml_op_is_empty(op->op) || ggml_is_empty(op)) {
supp = true;
@@ -3636,6 +3659,8 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
"please update hexagon_type to match ggml_type");
static_assert((unsigned int) HTP_TYPE_Q2_0 == (unsigned int) GGML_TYPE_Q2_0,
"please update hexagon_type to match ggml_type");
+ static_assert((unsigned int) HTP_TYPE_F8_E4M3 == (unsigned int) GGML_TYPE_F8_E4M3,
+ "please update hexagon_type to match ggml_type");
static_assert((unsigned int) HTP_TYPE_BF16 == (unsigned int) GGML_TYPE_BF16,
"please update hexagon_type to match ggml_type");
@@ -3653,6 +3678,7 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
const char * str_nhmx = getenv("GGML_HEXAGON_NHMX");
const char * str_vtcm_size = getenv("GGML_HEXAGON_VTCM_SIZE");
const char * str_mm_select = getenv("GGML_HEXAGON_MM_SELECT");
+ const char * str_mm_fwht = getenv("GGML_HEXAGON_MM_FWHT");
const char * str_fa_select = getenv("GGML_HEXAGON_FA_SELECT");
const char * str_fa_split = getenv("GGML_HEXAGON_FA_SPLIT");
const char * str_li_select = getenv("GGML_HEXAGON_LI_SELECT");
@@ -3727,6 +3753,7 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
opt_nhmx = str_nhmx ? atoi(str_nhmx) : opt_nhmx;
opt_vtcm_size = str_vtcm_size ? parse_size(str_vtcm_size) : opt_vtcm_size;
opt_mm_select = str_mm_select ? atoi(str_mm_select) : opt_mm_select;
+ opt_mm_fwht = str_mm_fwht ? atoi(str_mm_fwht) : opt_mm_fwht;
opt_fa_select = str_fa_select ? atoi(str_fa_select) : opt_fa_select;
opt_fa_split = str_fa_split ? atoi(str_fa_split) : opt_fa_split;
opt_li_select = str_li_select ? atoi(str_li_select) : opt_li_select;
@@ -3954,10 +3981,6 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) {
for (size_t i = 0; i < opt_ndev; i++) {
total_sessions += opt_device_configs[i].mdev_group.size();
}
- if (!str_mm_select && hw_arch == 73 && total_sessions > 1) {
- opt_mm_select = 2;
- GGML_LOG_INFO("ggml-hex: defaulting MM_SELECT=2 on multi-session v73 hardware\n");
- }
if (!str_fa_select && hw_arch == 73 && total_sessions > 1) {
opt_fa_select = 2;
GGML_LOG_INFO("ggml-hex: defaulting FA_SELECT=2 on multi-session v73 hardware\n");
diff --git a/ggml/src/ggml-hexagon/htp-common.h b/ggml/src/ggml-hexagon/htp-common.h
index 5b76b97bd..0bf2fc835 100644
--- a/ggml/src/ggml-hexagon/htp-common.h
+++ b/ggml/src/ggml-hexagon/htp-common.h
@@ -21,6 +21,7 @@ extern size_t opt_mbuf_static;
extern size_t opt_mbuf_total;
extern int opt_mm_select;
+extern int opt_mm_fwht;
extern int opt_fa_select;
extern int opt_fa_split;
extern int opt_li_select;
@@ -154,4 +155,38 @@ uint32_t htp_session_mdev_count(const struct ggml_hexagon_session * sess);
htp_op_code htp_op_remap(const struct ggml_tensor * t);
+enum htp_mm_scale_mode {
+ HTP_MM_SCALE_NONE = 0,
+ HTP_MM_SCALE_PER_TENSOR,
+ HTP_MM_SCALE_PER_CHANNEL,
+ HTP_MM_SCALE_PER_EXPERT,
+ HTP_MM_SCALE_PER_CHANNEL_EXPERT,
+};
+
+// classify weight scale (src_scale(op, 0)) of GGML_OP_MUL_MAT / GGML_OP_MUL_MAT_ID
+static inline enum htp_mm_scale_mode htp_get_mm_scale_mode(const struct ggml_tensor * op) {
+ const struct ggml_tensor * scale = ggml_get_src_scale(op, 0);
+ if (!scale) {
+ return HTP_MM_SCALE_NONE;
+ }
+ if (ggml_is_scalar(scale)) {
+ return HTP_MM_SCALE_PER_TENSOR;
+ }
+ if (op->op == GGML_OP_MUL_MAT_ID) {
+ const int64_t n_out = op->src[0]->ne[1];
+ const int64_t n_expert = op->src[0]->ne[2];
+ if (scale->ne[0] == n_out && scale->ne[1] == n_expert && scale->ne[2] == 1 && scale->ne[3] == 1) {
+ return HTP_MM_SCALE_PER_CHANNEL_EXPERT;
+ }
+ if (ggml_is_vector(scale) && scale->ne[0] == n_expert) {
+ return HTP_MM_SCALE_PER_EXPERT;
+ }
+ GGML_ABORT("invalid MUL_MAT_ID weight scale shape");
+ }
+ if (ggml_is_vector(scale) && scale->ne[0] == op->src[0]->ne[1]) {
+ return HTP_MM_SCALE_PER_CHANNEL;
+ }
+ GGML_ABORT("invalid MUL_MAT weight scale shape");
+}
+
#endif // HTP_COMMON_H
diff --git a/ggml/src/ggml-hexagon/htp-fusion.cpp b/ggml/src/ggml-hexagon/htp-fusion.cpp
index 35972964f..3ec84acfc 100644
--- a/ggml/src/ggml-hexagon/htp-fusion.cpp
+++ b/ggml/src/ggml-hexagon/htp-fusion.cpp
@@ -1,5 +1,6 @@
#include "htp-fusion.h"
#include "htp-kparams.h"
+#include "htp-repack.h"
#include "ggml-impl.h"
#include <algorithm>
@@ -38,33 +39,23 @@ static inline bool htp_match_consumer(
if (!ggml_hexagon_tensor_is_fuseable(prev_out)) {
return false;
}
- if (htp_same_tensor_data(cur.src0(), prev_out)) {
+ auto matches = [&](const ggml_tensor * in) {
+ return htp_same_tensor_data(in, prev_out) &&
+ in->type == prev_out->type &&
+ ggml_are_same_shape(in, prev_out) &&
+ ggml_are_same_stride(in, prev_out);
+ };
+ if (matches(cur.src0())) {
if (other_src) *other_src = cur.src1();
return true;
}
- if (commutative && htp_same_tensor_data(cur.src1(), prev_out)) {
+ if (commutative && matches(cur.src1())) {
if (other_src) *other_src = cur.src0();
return true;
}
return false;
}
-static bool is_supported_mul_mat_nx_kernel(const ggml_tensor * src0, const struct htp_mm_kernel_params * kparams) {
- if (kparams->n_hmx) {
- 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);
-}
-
-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 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);
-}
-
// --- Fusion rules ---
static bool fuse_allreduce_add(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) {
@@ -110,7 +101,6 @@ static bool fuse_allreduce_add(const ggml_hexagon_session * sess, htp_opnode & p
}
const bool scatter_ok = kparams.n_dsts > 1;
- kparams.mode = scatter_ok ? HTP_ALLREDUCE_SHARDED_FANOUT : HTP_ALLREDUCE_FULL;
for (uint32_t r = 0; r < n_ranks; r++) {
const ggml_tensor * ar_src = prev.inputs[r];
@@ -122,7 +112,7 @@ static bool fuse_allreduce_add(const ggml_hexagon_session * sess, htp_opnode & p
prev.opcode = HTP_OP_ALLREDUCE_ADD;
prev.inputs.push_back(res_tensor);
- if (kparams.mode != HTP_ALLREDUCE_SHARDED_FANOUT) {
+ if (!(kparams.flags & HTP_ALLREDUCE_FLAG_SHARDED_FANOUT)) {
prev.outputs = { add_dst };
}
prev.fused.push_back(cur.node);
@@ -148,18 +138,17 @@ static bool fuse_rms_norm_mul(const ggml_hexagon_session * sess, htp_opnode & pr
const bool is_same_shape = ggml_are_same_shape(src0, weight);
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)) {
- HEX_VERBOSE("ggml-hex: %s skip RMS_NORM_MUL fusion: VTCM needed (%d) > budget (%zu)\n",
- htp_session_name(sess), kparams.vtcm_size, htp_session_vtcm_size(sess));
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_RMS_NORM_MUL;
+ cand.inputs = { src0, weight };
+ cand.outputs = { dst };
+ cand.fused.push_back(cur.node);
+ if (!htp_kparams_solve(sess, cand)) {
+ HEX_VERBOSE("ggml-hex: %s skip RMS_NORM_MUL fusion: solver failed\n", htp_session_name(sess));
return false;
}
- prev.opcode = HTP_OP_RMS_NORM_MUL;
- prev.inputs = { src0, weight };
- prev.outputs = { dst };
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -178,14 +167,14 @@ static bool fuse_rms_norm_mul_add(const ggml_hexagon_session * sess, htp_opnode
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, r, dst, &kparams)) return false;
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_RMS_NORM_MUL_ADD;
+ cand.inputs.push_back(r);
+ cand.outputs[0] = dst;
+ cand.fused.push_back(cur.node);
+ if (!htp_kparams_solve(sess, cand)) return false;
- prev.opcode = HTP_OP_RMS_NORM_MUL_ADD;
- prev.inputs.push_back(r);
- prev.outputs[0] = dst;
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -250,31 +239,40 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre
}
const auto * orig_kparams = prev.kparams<htp_mm_kernel_params>();
- struct htp_mm_kernel_params kparams;
- if (!htp_kparams_solve_matmul_add(sess, src0, src1, src2, dst, &kparams)) {
+ const ggml_tensor * scale_w = (orig_kparams->scale_mask != 0 && prev.inputs.size() >= 3) ? prev.inputs[2] : nullptr;
+ if (scale_w && htp_tensors_overlap(dst, scale_w)) {
+ return false;
+ }
+
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_MUL_MAT_ADD;
+ cand.inputs = { src0, src1, src2 };
+ if (scale_w) {
+ cand.inputs.push_back(scale_w);
+ }
+ cand.outputs = { dst };
+ cand.fused.push_back(cur.node);
+ if (!htp_kparams_solve(sess, cand)) {
return false;
}
+ const auto * kparams = cand.kparams<htp_mm_kernel_params>();
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 && (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_act_hvx < orig_kparams->n_act_hvx) {
+ if (kparams->n_hmx > 0 && orig_kparams->n_hmx > 0) {
+ if (kparams->m_chunk < orig_kparams->m_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,
- orig_kparams->n_chunk, kparams.n_chunk,
- orig_kparams->n_act_hvx, kparams.n_act_hvx);
+ htp_session_name(sess), orig_kparams->m_chunk, kparams->m_chunk,
+ orig_kparams->n_chunk, kparams->n_chunk,
+ orig_kparams->n_act_hvx, kparams->n_act_hvx);
return false;
}
}
- prev.opcode = HTP_OP_MUL_MAT_ADD;
- prev.inputs = { src0, src1, src2 };
- prev.outputs = { dst };
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -282,7 +280,16 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev
if (prev.opcode != HTP_OP_MUL_MAT && prev.opcode != HTP_OP_MUL_MAT_NX) return false;
const uint32_t curr_n = (uint32_t) prev.outputs.size();
- if (curr_n >= HTP_OP_MAX_OUTPUTS || curr_n + 1 >= HTP_OP_MAX_INPUTS) return false;
+ const uint32_t new_n = curr_n + 1;
+
+ auto * orig_kparams = prev.kparams<htp_mm_kernel_params>();
+ const auto * cur_kparams = cur.kparams<htp_mm_kernel_params>();
+
+ const bool prev_has_scale = (orig_kparams->scale_mask != 0);
+ const bool cur_has_scale = (cur_kparams->scale_mask != 0);
+ const bool any_scale = prev_has_scale || cur_has_scale;
+ const size_t needed_in = any_scale ? (2 * new_n + 1) : (new_n + 1);
+ if (curr_n >= HTP_OP_MAX_OUTPUTS || needed_in > HTP_OP_MAX_INPUTS) return false;
const ggml_tensor * w0 = prev.inputs[0];
const ggml_tensor * x_orig = prev.node->src[1];
@@ -290,10 +297,8 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev
const ggml_tensor * x_in = cur.node->src[1];
const ggml_tensor * d_in = cur.node;
- auto * orig_kparams = prev.kparams<htp_mm_kernel_params>();
- 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] ||
+ (ggml_needs_scale(w0->type) && prev_has_scale != cur_has_scale) ||
!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 ||
@@ -304,6 +309,39 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev
const bool collapse = htp_matmul_can_collapse(w0, x_orig, prev.node) && htp_matmul_can_collapse(w_in, x_in, d_in);
if (!ggml_is_matrix(x_orig) && !collapse) return false;
+ const ggml_tensor * weights[HTP_OP_MAX_OUTPUTS] = {};
+ const ggml_tensor * scales[HTP_OP_MAX_OUTPUTS] = {};
+ uint8_t smodes[HTP_OP_MAX_OUTPUTS] = {};
+ for (uint32_t i = 0; i < curr_n; ++i) {
+ weights[i] = prev.inputs[i];
+ if ((orig_kparams->scale_mask >> i) & 1u) {
+ const size_t sidx = (prev.opcode == HTP_OP_MUL_MAT) ? 2 : (curr_n + 1 + i);
+ scales[i] = (sidx < prev.inputs.size()) ? prev.inputs[sidx] : nullptr;
+ smodes[i] = (uint8_t) htp_mm_scale_mode_get(orig_kparams->scale_mode, i);
+ }
+ }
+ weights[curr_n] = w_in;
+ if (cur_has_scale && cur.inputs.size() >= 3) {
+ scales[curr_n] = cur.inputs[2];
+ smodes[curr_n] = (uint8_t) htp_mm_scale_mode_get(cur_kparams->scale_mode, 0);
+ }
+
+ uint8_t new_scale_mask = 0;
+ uint16_t new_scale_mode = 0;
+ size_t hmx_scale_size = 0;
+ size_t hvx_scale_size = 0;
+ for (uint32_t i = 0; i < new_n; ++i) {
+ if (scales[i]) {
+ new_scale_mask |= (uint8_t) (1u << i);
+ new_scale_mode |= (uint16_t) (smodes[i] << (2u * i));
+ const size_t sb = htp_mm_fused_scale_vtcm_bytes((uint32_t) weights[i]->ne[1], (uint32_t) weights[i]->ne[2], smodes[i], true);
+ if (sb > hmx_scale_size) {
+ hmx_scale_size = sb;
+ }
+ hvx_scale_size += htp_mm_fused_scale_vtcm_bytes((uint32_t) weights[i]->ne[1], (uint32_t) weights[i]->ne[2], smodes[i], 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) {
@@ -314,25 +352,44 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev
}
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;
+ const size_t req_scale_sz = orig_kparams->n_hmx ? hmx_scale_size : hvx_scale_size;
- 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;
- 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;
+ auto append_to = [&](htp_opnode & target) {
+ if (any_scale) {
+ target.inputs.clear();
+ for (uint32_t i = 0; i < new_n; ++i) {
+ target.inputs.push_back(weights[i]);
+ }
+ target.inputs.push_back(x_orig);
+ for (uint32_t i = 0; i < new_n; ++i) {
+ target.inputs.push_back(scales[i]);
+ }
+ } else {
+ target.inputs.insert(target.inputs.begin() + curr_n, w_in);
+ }
+ target.outputs.push_back(d_in);
+ target.fused.push_back(cur.node);
+ };
- prev.set_kparams(kparams);
- 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) &&
+ req_scale_sz <= orig_kparams->vtcm_scale_size) {
+ orig_kparams->n_weights = new_n;
+ orig_kparams->scale_mask = new_scale_mask;
+ orig_kparams->scale_mode = new_scale_mode;
+ append_to(prev);
+ return true;
}
- prev.inputs.insert(prev.inputs.begin() + curr_n, w_in);
- prev.outputs.push_back(d_in);
- prev.fused.push_back(cur.node);
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_MUL_MAT_NX;
+ append_to(cand);
+ auto * kp = cand.kparams<htp_mm_kernel_params>();
+ kp->scale_mask = new_scale_mask;
+ kp->scale_mode = new_scale_mode;
+ if (!htp_kparams_solve(sess, cand)) return false;
+
+ prev = std::move(cand);
return true;
}
@@ -342,7 +399,8 @@ static bool htp_is_fuseable_mmnx_glu_op(uint32_t op) {
}
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) {
+ if (prev.opcode != HTP_OP_MUL_MAT_NX || prev.outputs.size() != 2 ||
+ (prev.inputs.size() != 3 && prev.inputs.size() != 5)) {
return false;
}
if (!htp_is_fuseable_mmnx_glu_op(cur.opcode) || cur.inputs.size() != 2 || cur.outputs.size() != 1 || !cur.src1()) {
@@ -371,20 +429,35 @@ static bool fuse_mul_mat_nx_glu(const ggml_hexagon_session * sess, htp_opnode &
const ggml_tensor * w_up = nullptr;
const ggml_tensor * out_gate = nullptr;
const ggml_tensor * out_up = nullptr;
+ uint32_t gate_idx = 0;
+ uint32_t up_idx = 1;
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;
+ gate_idx = 0;
+ up_idx = 1;
} 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;
+ gate_idx = 1;
+ up_idx = 0;
} else {
return false;
}
+ const ggml_tensor * s_gate = (((orig_kparams->scale_mask >> gate_idx) & 1u) != 0 && prev.inputs.size() == 5)
+ ? prev.inputs[3 + gate_idx] : nullptr;
+ const ggml_tensor * s_up = (((orig_kparams->scale_mask >> up_idx) & 1u) != 0 && prev.inputs.size() == 5)
+ ? prev.inputs[3 + up_idx] : nullptr;
+ const uint32_t smode_gate = s_gate ? htp_mm_scale_mode_get(orig_kparams->scale_mode, gate_idx) : 0;
+ const uint32_t smode_up = s_up ? htp_mm_scale_mode_get(orig_kparams->scale_mode, up_idx) : 0;
+ const uint8_t glu_smask = (uint8_t) ((s_gate ? 1u : 0u) | (s_up ? 2u : 0u));
+ const uint8_t glu_smode = (uint8_t) (smode_gate | (smode_up << 2u));
+
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] ||
@@ -398,7 +471,8 @@ static bool fuse_mul_mat_nx_glu(const ggml_hexagon_session * sess, htp_opnode &
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)) {
+ if (htp_tensors_overlap(dst, w_gate) || htp_tensors_overlap(dst, w_up) || htp_tensors_overlap(dst, act) ||
+ (s_gate && htp_tensors_overlap(dst, s_gate)) || (s_up && htp_tensors_overlap(dst, s_up))) {
return false;
}
@@ -407,22 +481,27 @@ static bool fuse_mul_mat_nx_glu(const ggml_hexagon_session * sess, htp_opnode &
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;
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_MUL_MAT_NX_GLU;
+ cand.inputs = { w_gate, w_up, act };
+ if (glu_smask != 0) {
+ cand.inputs.push_back(s_gate);
+ cand.inputs.push_back(s_up);
}
-
- prev.opcode = HTP_OP_MUL_MAT_NX_GLU;
- prev.inputs = { w_gate, w_up, act };
- prev.outputs = { dst };
- prev.fused.push_back(cur.node);
+ cand.outputs = { dst };
+ cand.fused.push_back(cur.node);
for (const ggml_tensor * f : cur.fused) {
- prev.fused.push_back(f);
+ cand.fused.push_back(f);
}
- prev.set_kparams(kparams);
+ auto * kp = cand.kparams<htp_mm_kernel_params>();
+ kp->glu_op = (uint8_t) cur.opcode;
+ kp->scale_mask = glu_smask;
+ kp->scale_mode = glu_smode;
+ if (!htp_kparams_solve(sess, cand)) {
+ return false;
+ }
+
+ prev = std::move(cand);
return true;
}
@@ -430,7 +509,16 @@ static bool fuse_mul_mat_id_nx(const ggml_hexagon_session * sess, htp_opnode & p
if (prev.opcode != HTP_OP_MUL_MAT_ID && prev.opcode != HTP_OP_MUL_MAT_ID_NX) return false;
const uint32_t curr_n = (uint32_t) prev.outputs.size();
- if (curr_n >= HTP_OP_MAX_OUTPUTS || curr_n + 2 >= HTP_OP_MAX_INPUTS) return false;
+ const uint32_t new_n = curr_n + 1;
+
+ auto * orig_kparams = prev.kparams<htp_mm_kernel_params>();
+ const auto * cur_kparams = cur.kparams<htp_mm_kernel_params>();
+
+ const bool prev_has_scale = (orig_kparams->scale_mask != 0);
+ const bool cur_has_scale = (cur_kparams->scale_mask != 0);
+ const bool any_scale = prev_has_scale || cur_has_scale;
+ const size_t needed_in = any_scale ? (2 * new_n + 2) : (new_n + 2);
+ if (curr_n >= HTP_OP_MAX_OUTPUTS || needed_in > HTP_OP_MAX_INPUTS) return false;
const ggml_tensor * w0 = prev.inputs[0];
const ggml_tensor * x = prev.inputs[curr_n];
@@ -440,30 +528,100 @@ static bool fuse_mul_mat_id_nx(const ggml_hexagon_session * sess, htp_opnode & p
const ggml_tensor * ids_in = cur.node->src[2];
const ggml_tensor * d_in = cur.dst();
- auto * orig_kparams = prev.kparams<htp_mm_kernel_params>();
- const auto * cur_kparams = cur.kparams<htp_mm_kernel_params>();
-
if (x_in != x || ids_in != ids || w_in->type != w0->type ||
+ (ggml_needs_scale(w0->type) && prev_has_scale != cur_has_scale) ||
w_in->ne[0] != w0->ne[0] || w_in->ne[2] != w0->ne[2] ||
ggml_hexagon_tensor_is_tiled(w_in) != ggml_hexagon_tensor_is_tiled(w0) ||
orig_kparams->n_hmx != cur_kparams->n_hmx) {
return false;
}
- struct htp_mm_kernel_params kparams;
- if (d_in->nb[1] == prev.node->nb[1]) {
- kparams = *orig_kparams;
- kparams.n_weights = curr_n + 1;
- } else if (!htp_kparams_solve_mmidnx(sess, w0, x, d_in, curr_n + 1, &kparams)) {
+ const ggml_tensor * weights[HTP_OP_MAX_OUTPUTS] = {};
+ const ggml_tensor * scales[HTP_OP_MAX_OUTPUTS] = {};
+ uint8_t smodes[HTP_OP_MAX_OUTPUTS] = {};
+ for (uint32_t i = 0; i < curr_n; ++i) {
+ weights[i] = prev.inputs[i];
+ if ((orig_kparams->scale_mask >> i) & 1u) {
+ const size_t sidx = (prev.opcode == HTP_OP_MUL_MAT_ID) ? 3 : (curr_n + 2 + i);
+ scales[i] = (sidx < prev.inputs.size()) ? prev.inputs[sidx] : nullptr;
+ smodes[i] = (uint8_t) htp_mm_scale_mode_get(orig_kparams->scale_mode, i);
+ }
+ }
+ weights[curr_n] = w_in;
+ if (cur_has_scale && cur.inputs.size() >= 4) {
+ scales[curr_n] = cur.inputs[3];
+ smodes[curr_n] = (uint8_t) htp_mm_scale_mode_get(cur_kparams->scale_mode, 0);
+ }
+
+ uint8_t new_scale_mask = 0;
+ uint16_t new_scale_mode = 0;
+ size_t hmx_scale_size = 0;
+ size_t hvx_scale_size = 0;
+ for (uint32_t i = 0; i < new_n; ++i) {
+ if (scales[i]) {
+ new_scale_mask |= (uint8_t) (1u << i);
+ new_scale_mode |= (uint16_t) (smodes[i] << (2u * i));
+ const size_t sb = htp_mm_fused_scale_vtcm_bytes((uint32_t) weights[i]->ne[1], (uint32_t) weights[i]->ne[2], smodes[i], true);
+ if (sb > hmx_scale_size) {
+ hmx_scale_size = sb;
+ }
+ hvx_scale_size += htp_mm_fused_scale_vtcm_bytes((uint32_t) weights[i]->ne[1], (uint32_t) weights[i]->ne[2], smodes[i], false);
+ }
+ }
+
+ const ggml_tensor * prev_w = prev.inputs[0];
+ ggml_type prev_dst_type = prev.outputs[0]->type;
+ for (uint32_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;
+ const size_t req_scale_sz = orig_kparams->n_hmx ? hmx_scale_size : hvx_scale_size;
+
+ auto append_to = [&](htp_opnode & target) {
+ if (any_scale) {
+ target.inputs.clear();
+ for (uint32_t i = 0; i < new_n; ++i) {
+ target.inputs.push_back(weights[i]);
+ }
+ target.inputs.push_back(x);
+ target.inputs.push_back(ids);
+ for (uint32_t i = 0; i < new_n; ++i) {
+ target.inputs.push_back(scales[i]);
+ }
+ } else {
+ target.inputs.insert(target.inputs.begin() + curr_n, w_in);
+ }
+ target.outputs.push_back(d_in);
+ target.fused.push_back(cur.node);
+ };
+
+ if (prev.opcode == HTP_OP_MUL_MAT_ID_NX && w_for_solve == prev_w &&
+ ggml_type_size(max_dst_type) == ggml_type_size(prev_dst_type) &&
+ req_scale_sz <= orig_kparams->vtcm_scale_size) {
+ orig_kparams->n_weights = new_n;
+ orig_kparams->scale_mask = new_scale_mask;
+ orig_kparams->scale_mode = new_scale_mode;
+ append_to(prev);
+ return true;
+ }
+
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_MUL_MAT_ID_NX;
+ append_to(cand);
+ auto * kp = cand.kparams<htp_mm_kernel_params>();
+ kp->scale_mask = new_scale_mask;
+ kp->scale_mode = new_scale_mode;
+ if (!htp_kparams_solve(sess, cand)) {
return false;
}
- if (!is_supported_mul_mat_id_nx_kernel(w0, &kparams)) return false;
- prev.opcode = HTP_OP_MUL_MAT_ID_NX;
- prev.inputs.insert(prev.inputs.begin() + curr_n, w_in);
- prev.outputs.push_back(d_in);
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -509,19 +667,18 @@ static bool fuse_ssm_conv_silu(const ggml_hexagon_session * sess, htp_opnode & p
if (prev.opcode != HTP_OP_SSM_CONV) return false;
auto * kparams = prev.kparams<htp_ssm_conv_kernel_params>();
- if (kparams->silu) return false;
+ if (kparams->flags & HTP_SSM_CONV_FLAG_SILU) return false;
if (!htp_match_consumer(prev, cur, /*commutative=*/ false)) return false;
const ggml_tensor * conv_dst = prev.dst();
const ggml_tensor * dst = cur.dst();
- 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;
htp_opnode cand = prev;
cand.outputs[0] = dst;
cand.fused.push_back(cur.node);
- cand.kparams<htp_ssm_conv_kernel_params>()->silu = 1;
+ cand.kparams<htp_ssm_conv_kernel_params>()->flags |= HTP_SSM_CONV_FLAG_SILU;
if (!htp_kparams_solve(sess, cand)) return false;
prev = std::move(cand);
@@ -540,14 +697,14 @@ static bool fuse_repeat_get_rows(const ggml_hexagon_session * sess, htp_opnode &
if (repeat_src0->ne[0] != repeat_out->ne[0] || repeat_src0->ne[1] != repeat_out->ne[1]) return false;
if (repeat_src0->type != repeat_out->type) return false;
- struct htp_get_rows_kernel_params kparams;
- if (!htp_kparams_solve_repeat_get_rows(sess, repeat_src0, gr_src1, gr_dst, &kparams) || kparams.vtcm_size == 0) return false;
+ htp_opnode cand = prev;
+ cand.opcode = HTP_OP_GET_ROWS;
+ cand.inputs = { repeat_src0, gr_src1 };
+ cand.outputs = { gr_dst };
+ cand.fused.push_back(cur.node);
+ if (!htp_kparams_solve(sess, cand) || cand.kparams<htp_get_rows_kernel_params>()->vtcm_size == 0) return false;
- prev.opcode = HTP_OP_GET_ROWS;
- prev.inputs = { repeat_src0, gr_src1 };
- prev.outputs = { gr_dst };
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -569,7 +726,7 @@ static inline bool htp_is_scale_bias_unary(uint32_t opcode) {
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 (cur.kparams<htp_unary_kernel_params>()->flags & HTP_UNARY_FLAG_SCALE_BIAS) return false;
if (!htp_match_consumer(prev, cur, /*commutative=*/ false)) return false;
const ggml_tensor * src0 = prev.src0();
@@ -590,12 +747,12 @@ static bool fuse_scale_unary(const ggml_hexagon_session * sess, htp_opnode & pre
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;
+ auto * kp = cand.kparams<htp_unary_kernel_params>();
+ kp->flags |= HTP_UNARY_FLAG_SCALE_BIAS;
+ 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);
@@ -621,20 +778,21 @@ static bool fuse_unary_scale(const ggml_hexagon_session * sess, htp_opnode & pre
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;
+ const bool has_sb = (prev_kp->flags & HTP_UNARY_FLAG_SCALE_BIAS) != 0;
+ const float in_scale = has_sb ? prev_kp->in_scale : 1.0f;
+ const float in_bias = has_sb ? prev_kp->in_bias : 0.0f;
+ const float out_scale = (has_sb ? prev_kp->out_scale : 1.0f) * s_out;
+ const float out_bias = (has_sb ? 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;
+ auto * kp = cand.kparams<htp_unary_kernel_params>();
+ kp->flags |= HTP_UNARY_FLAG_SCALE_BIAS;
+ 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);
@@ -653,7 +811,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;
+ if (prev.kparams<htp_unary_kernel_params>()->flags & HTP_UNARY_FLAG_SCALE_BIAS) return false;
const ggml_tensor * up = nullptr;
if (!htp_match_consumer(prev, cur, /*commutative=*/ true, &up)) return false;
@@ -680,7 +838,7 @@ static bool fuse_mul_mul_scalar(const ggml_hexagon_session * sess, htp_opnode &
const auto * k0 = prev.kparams<htp_binary_kernel_params>();
const auto * k1 = cur.kparams<htp_binary_kernel_params>();
if (k0->kernel_type != HTP_BINARY_KERNEL_SCALAR || k1->kernel_type != HTP_BINARY_KERNEL_SCALAR) return false;
- if (k0->src1_strided || k1->src1_strided) return false;
+ if ((k0->flags & HTP_BINARY_FLAG_SRC1_STRIDED) || (k1->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) return false;
const ggml_tensor * src2 = nullptr;
if (!htp_match_consumer(prev, cur, /*commutative=*/ false, &src2)) return false;
@@ -691,23 +849,13 @@ static bool fuse_mul_mul_scalar(const ggml_hexagon_session * sess, htp_opnode &
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;
- const size_t vtcm_size = htp_session_vtcm_size(sess);
- struct htp_binary_kernel_params kparams = *k0;
- kparams.src2_size = kparams.src1_size;
- kparams.rows_per_buffer = 0;
- if (kparams.src1_size > 65536 || kparams.src1_size + kparams.src2_size > vtcm_size) return false;
-
- 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 = L.total_bytes;
+ htp_opnode cand = prev;
+ cand.inputs.push_back(src2);
+ cand.outputs[0] = dst;
+ cand.fused.push_back(cur.node);
+ if (!htp_kparams_solve(sess, cand)) return false;
- prev.inputs.push_back(src2);
- prev.outputs[0] = dst;
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -720,9 +868,9 @@ static bool fuse_binary_nx(const ggml_hexagon_session * sess, htp_opnode & prev,
const auto * k0 = prev.kparams<htp_binary_kernel_params>();
const auto * k1 = cur.kparams<htp_binary_kernel_params>();
const bool k0_ok = (k0->kernel_type == HTP_BINARY_KERNEL_SAME_SHAPE) ||
- (k0->kernel_type == HTP_BINARY_KERNEL_CHUNKED && !k0->is_scalar);
+ (k0->kernel_type == HTP_BINARY_KERNEL_CHUNKED && !(k0->flags & HTP_BINARY_FLAG_SCALAR));
const bool k1_ok = (k1->kernel_type == HTP_BINARY_KERNEL_SAME_SHAPE) ||
- (k1->kernel_type == HTP_BINARY_KERNEL_CHUNKED && !k1->is_scalar);
+ (k1->kernel_type == HTP_BINARY_KERNEL_CHUNKED && !(k1->flags & HTP_BINARY_FLAG_SCALAR));
if (!k0_ok || !k1_ok) return false;
const bool is_comm = (cur.opcode == HTP_OP_ADD || cur.opcode == HTP_OP_MUL);
@@ -742,52 +890,14 @@ static bool fuse_binary_nx(const ggml_hexagon_session * sess, htp_opnode & prev,
}
if (htp_inputs_overlap_unsafe(prev, dst, new_src)) return false;
- const size_t vtcm_size = htp_session_vtcm_size(sess);
- struct htp_binary_kernel_params kparams = *k0;
- struct htp_binary_vtcm_layout L;
- memset(&L, 0, sizeof(L));
-
- const uint32_t n_srcs = curr_n + 1;
- if (k0->kernel_type == HTP_BINARY_KERNEL_SAME_SHAPE || k1->kernel_type == HTP_BINARY_KERNEL_SAME_SHAPE) {
- if (k0->kernel_type != HTP_BINARY_KERNEL_SAME_SHAPE) {
- kparams = *k1;
- }
- kparams.n_srcs = (uint8_t) n_srcs;
- kparams.rows_per_buffer = 0;
-
- auto check_split = [&](const ggml_tensor * t) {
- if (src0->ne[2] > 1 && t->nb[2] != t->ne[1] * t->nb[1]) kparams.split_at_ne01 = 1;
- if (src0->ne[3] > 1 && t->nb[3] != t->ne[2] * t->nb[2]) kparams.split_at_ne02 = 1;
- };
- for (const auto * in : prev.inputs) check_split(in);
- check_split(new_src);
- check_split(dst);
-
- htp_binary_vtcm_layout_build(&L, &kparams, vtcm_size);
- }
-
- if (L.rows_per_buffer == 0 || L.total_bytes == 0 || L.total_bytes > vtcm_size) {
- bool all_contig = ggml_is_contiguous(new_src) && ggml_is_contiguous(dst);
- for (const auto * in : prev.inputs) {
- all_contig = all_contig && ggml_is_contiguous(in);
- }
- if (!all_contig) return false;
-
- 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, elem_size, elem_size, max_hvx, n_srcs, false, vtcm_size)) {
- return false;
- }
- }
-
- kparams.rows_per_buffer = L.rows_per_buffer;
- kparams.vtcm_size = (uint32_t) L.total_bytes;
+ htp_opnode cand = prev;
+ cand.inputs.push_back(new_src);
+ cand.outputs[0] = dst;
+ cand.fused.push_back(cur.node);
+ cand.kparams<htp_binary_kernel_params>()->n_srcs = (uint8_t) cand.inputs.size();
+ if (!htp_kparams_solve(sess, cand)) return false;
- prev.inputs.push_back(new_src);
- prev.outputs[0] = dst;
- prev.fused.push_back(cur.node);
- prev.set_kparams(kparams);
+ prev = std::move(cand);
return true;
}
@@ -798,11 +908,11 @@ 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 htp_is_quantized_weight_type(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);
+ return a->src[2] != nullptr && htp_is_quantized_weight_type(a->src[0]->type);
default:
return false;
}
@@ -817,7 +927,15 @@ bool htp_fusion_can_stack(const struct ggml_tensor * a, const struct ggml_tensor
}
const ggml_tensor * w0 = a->src[0];
const ggml_tensor * w1 = b->src[0];
- return w0->type == w1->type && w0->ne[0] == w1->ne[0] && w0->ne[2] == w1->ne[2];
+ if (w0->type != w1->type || w0->ne[0] != w1->ne[0] || w0->ne[2] != w1->ne[2]) {
+ return false;
+ }
+ const bool a_has_scale = ggml_get_src_scale(a, 0) != nullptr;
+ const bool b_has_scale = ggml_get_src_scale(b, 0) != nullptr;
+ if (ggml_needs_scale(w0->type) && a_has_scale != b_has_scale) {
+ return false;
+ }
+ return ggml_hexagon_tensor_is_tiled(w0) == ggml_hexagon_tensor_is_tiled(w1);
}
int htp_fusion_max(const struct ggml_cgraph * graph, int idx) {
@@ -869,6 +987,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 (!prev.node || !cur.node) return false;
if (!cur.fused.empty()) return false;
switch (cur.opcode) {
@@ -917,6 +1036,96 @@ bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_op
}
}
+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 bool htp_has_intervening_write(
+ const std::vector<struct htp_opnode> & nodes,
+ size_t lo,
+ size_t hi,
+ size_t skip_idx,
+ const ggml_tensor * const * protected_tensors,
+ size_t n_protected
+) {
+ for (size_t k = lo; k < hi; ++k) {
+ if (k == skip_idx) {
+ continue;
+ }
+ for (const ggml_tensor * out : nodes[k].outputs) {
+ if (!out) {
+ continue;
+ }
+ for (size_t i = 0; i < n_protected; ++i) {
+ if (protected_tensors[i] && htp_tensors_overlap(out, protected_tensors[i])) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+// Check that fusing producer p into consumer c has no external consumers of targets
+// (checked by view lineage to avoid buffer-reuse false positives) and no intervening writes.
+static bool htp_post_fuse_is_safe(
+ const std::vector<struct htp_opnode> & nodes,
+ size_t p,
+ size_t c,
+ const ggml_tensor * const * targets,
+ size_t n_targets,
+ const ggml_tensor * const * protected_tensors,
+ size_t n_protected,
+ uint32_t c_skip_input_mask
+) {
+ for (size_t i = 0; i < n_targets; ++i) {
+ if (!targets[i] || ggml_is_view(targets[i])) {
+ return false;
+ }
+ }
+ for (size_t j = 0; j < nodes[c].inputs.size(); ++j) {
+ if ((c_skip_input_mask >> j) & 1u) {
+ continue;
+ }
+ for (size_t i = 0; i < n_targets; ++i) {
+ if (htp_tensor_reads_from(nodes[c].inputs[j], targets[i])) {
+ return false;
+ }
+ }
+ }
+ for (size_t k = 0; k < nodes.size(); ++k) {
+ if (k == p || k == c) {
+ continue;
+ }
+ for (const ggml_tensor * in : nodes[k].inputs) {
+ for (size_t i = 0; i < n_targets; ++i) {
+ if (htp_tensor_is_view_of(in, targets[i])) {
+ return false;
+ }
+ }
+ }
+ }
+ return !htp_has_intervening_write(nodes, p + 1, c, nodes.size(), protected_tensors, n_protected);
+}
+
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 ||
@@ -966,28 +1175,11 @@ static void htp_fuse_gdn_state(const struct ggml_hexagon_session * sess, std::ve
}
}
- 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;
- }
- }
- }
+ const ggml_tensor * targets[] = { base_s };
+ const ggml_tensor * protected_t[] = { gr_src0, gr_src1, base_s };
+ if (!htp_post_fuse_is_safe(nodes, p, c, targets, 1, protected_t, 3, 1u << 5)) {
+ continue;
}
- if (!safe) continue;
htp_opnode cand = nodes[c];
cand.inputs[5] = gr_src0;
@@ -1021,28 +1213,6 @@ static bool htp_unwrap_transpose_01(const ggml_tensor * t, const ggml_tensor **
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 ||
@@ -1153,26 +1323,12 @@ static void htp_fuse_concat_ssm_conv(const struct ggml_hexagon_session * sess, s
}
}
- 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;
- }
- }
+ const ggml_tensor * protected_t[] = { cat_state, cat_x, conv_x, conv_weight, has_cpy ? cpy_dst : nullptr };
+ if (htp_has_intervening_write(nodes, p + 1, c, has_cpy ? q : nodes.size(), protected_t, 5)) {
+ continue;
}
- if (has_cpy && safe) {
+ bool safe = true;
+ if (has_cpy) {
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) {
@@ -1229,7 +1385,8 @@ static void htp_fuse_mul_mat_nx_glu(const struct ggml_hexagon_session * sess, st
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) {
+ if (nodes[i].opcode != HTP_OP_MUL_MAT_NX || nodes[i].outputs.size() != 2 ||
+ (nodes[i].inputs.size() != 3 && nodes[i].inputs.size() != 5)) {
continue;
}
const ggml_tensor * o0 = nodes[i].outputs[0];
@@ -1247,37 +1404,114 @@ static void htp_fuse_mul_mat_nx_glu(const struct ggml_hexagon_session * sess, st
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 * sc0 = (nodes[p].inputs.size() == 5) ? nodes[p].inputs[3] : nullptr;
+ const ggml_tensor * sc1 = (nodes[p].inputs.size() == 5) ? nodes[p].inputs[4] : nullptr;
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;
- }
+ const ggml_tensor * targets[] = { o0, o1 };
+ const ggml_tensor * protected_t[] = { w0, w1, act, sc0, sc1, o0, o1 };
+ if (!htp_post_fuse_is_safe(nodes, p, c, targets, 2, protected_t, 7, (1u << 0) | (1u << 1))) {
+ 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;
+ }
+}
+
+static void htp_fuse_rms_norm_mul_mm(const struct ggml_hexagon_session * sess, std::vector<struct htp_opnode> & nodes) {
+ for (size_t c = 0; c < nodes.size(); ++c) {
+ const htp_op_code op = nodes[c].opcode;
+ if (op != HTP_OP_MUL_MAT && op != HTP_OP_MUL_MAT_ADD &&
+ op != HTP_OP_MUL_MAT_NX && op != HTP_OP_MUL_MAT_NX_GLU) {
+ continue;
+ }
+ const auto * cur_kp = nodes[c].kparams<htp_mm_kernel_params>();
+ if (!cur_kp->n_hmx || cur_kp->norm_w_idx != 0) {
+ continue;
+ }
+ if (nodes[c].inputs.size() >= HTP_OP_MAX_INPUTS) {
+ continue;
+ }
+
+ const size_t act_idx = (op == HTP_OP_MUL_MAT_NX) ? nodes[c].outputs.size()
+ : (op == HTP_OP_MUL_MAT_NX_GLU ? 2 : 1);
+ if (act_idx >= nodes[c].inputs.size()) {
+ continue;
+ }
+ const ggml_tensor * act = nodes[c].inputs[act_idx];
+ if (!act || (act->flags & GGML_TENSOR_FLAG_OUTPUT)) {
+ continue;
+ }
+
+ size_t p = c;
+ for (size_t i = c; i > 0; --i) {
+ const size_t idx = i - 1;
+ if (nodes[idx].opcode == HTP_OP_RMS_NORM_MUL &&
+ nodes[idx].inputs.size() == 2 && nodes[idx].outputs.size() == 1 &&
+ nodes[idx].outputs[0] == act) {
+ p = idx;
+ 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 (p == c) {
+ continue;
+ }
+ if (nodes[c].fused.size() + 1 + nodes[p].fused.size() > HTP_OP_MAX_FUSED) {
+ continue;
+ }
+
+ float norm_eps = 0.0f;
+ float norm_scale = 0.0f;
+ memcpy(&norm_eps, &nodes[p].params[0], sizeof(float));
+ memcpy(&norm_scale, &nodes[p].params[1], sizeof(float));
+ if (norm_scale != 0.0f) {
+ continue;
+ }
+
+ const ggml_tensor * norm_x = nodes[p].inputs[0];
+ const ggml_tensor * norm_w = nodes[p].inputs[1];
+ const ggml_tensor * norm_out = nodes[p].outputs[0];
+ if (!ggml_is_vector(norm_w)) {
+ continue;
+ }
+
+ bool out_overlap = false;
+ for (const ggml_tensor * out : nodes[c].outputs) {
+ if (out && (htp_tensors_overlap(out, norm_x) || htp_tensors_overlap(out, norm_w))) {
+ out_overlap = true;
+ break;
}
}
- if (!safe) {
+ if (out_overlap) {
continue;
}
- htp_opnode cand = nodes[p];
- if (!fuse_mul_mat_nx_glu(sess, cand, nodes[c])) {
+ const ggml_tensor * targets[] = { norm_out };
+ const ggml_tensor * protected_t[] = { norm_x, norm_w, norm_out };
+ if (!htp_post_fuse_is_safe(nodes, p, c, targets, 1, protected_t, 3, 1u << act_idx)) {
+ continue;
+ }
+
+ htp_opnode cand = nodes[c];
+ const uint8_t norm_w_idx = (uint8_t) cand.inputs.size();
+ cand.inputs[act_idx] = norm_x;
+ cand.inputs.push_back(norm_w);
+ cand.fused.push_back(nodes[p].node);
+ for (const ggml_tensor * f : nodes[p].fused) {
+ cand.fused.push_back(f);
+ }
+ auto * cand_kp = cand.kparams<htp_mm_kernel_params>();
+ cand_kp->norm_eps = norm_eps;
+ cand_kp->norm_w_idx = norm_w_idx;
+ if (!htp_kparams_solve(sess, cand)) {
continue;
}
@@ -1293,6 +1527,9 @@ void htp_fusion_optimize_nodes(const struct ggml_hexagon_session * sess, const s
if (htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX_GLU)) {
htp_fuse_mul_mat_nx_glu(sess, nodes);
}
+ if (htp_fusion_enabled(HTP_FUSE_RMS_NORM_MUL_MM)) {
+ htp_fuse_rms_norm_mul_mm(sess, nodes);
+ }
if (htp_fusion_enabled(HTP_FUSE_GDN_STATE)) {
htp_fuse_gdn_state(sess, nodes);
}
diff --git a/ggml/src/ggml-hexagon/htp-fusion.h b/ggml/src/ggml-hexagon/htp-fusion.h
index 6a2b39196..e1ef620d1 100644
--- a/ggml/src/ggml-hexagon/htp-fusion.h
+++ b/ggml/src/ggml-hexagon/htp-fusion.h
@@ -21,6 +21,7 @@ enum htp_fusion_flags {
HTP_FUSE_GDN_STATE = (1 << 15), // 32768
HTP_FUSE_CONCAT_SSM_CONV = (1 << 16), // 65536
HTP_FUSE_MUL_MAT_NX_GLU = (1 << 17), // 131072
+ HTP_FUSE_RMS_NORM_MUL_MM = (1 << 18), // 262144
};
static inline bool htp_fusion_enabled(int flag) {
diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp
index 3fa04be92..85c359520 100644
--- a/ggml/src/ggml-hexagon/htp-kparams.cpp
+++ b/ggml/src/ggml-hexagon/htp-kparams.cpp
@@ -121,7 +121,9 @@ bool htp_kparams_solve_allreduce(
memset(kparams, 0, sizeof(*kparams));
kparams->rank = (int32_t) rank;
kparams->n_ranks = (int32_t) n_ranks;
- kparams->is_row_bcast = (has_add && is_row_bcast) ? 1 : 0;
+ if (has_add && is_row_bcast) {
+ kparams->flags |= HTP_ALLREDUCE_FLAG_ROW_BCAST;
+ }
const uint32_t max_hvx = htp_session_n_hvx(sess);
const size_t vtcm_size = htp_session_vtcm_size(sess);
@@ -133,7 +135,6 @@ bool htp_kparams_solve_allreduce(
const uint32_t ne0 = (uint32_t) dst->ne[0];
const uint32_t ne1 = (uint32_t) ggml_nrows(dst);
kparams->ne0 = (int32_t) ne0;
- kparams->ne1 = (int32_t) ne1;
const bool use_1d = is_contiguous && !(has_add && is_row_bcast && ne1 > 1);
@@ -173,7 +174,9 @@ bool htp_kparams_solve_allreduce(
}
}
- kparams->mode = (kparams->n_dsts > 1) ? HTP_ALLREDUCE_SHARDED_FANOUT : HTP_ALLREDUCE_FULL;
+ if (kparams->n_dsts > 1) {
+ kparams->flags |= HTP_ALLREDUCE_FLAG_SHARDED_FANOUT;
+ }
if (use_1d) {
const uint32_t rank_nelem = (uint32_t) kparams->rank_nelem;
@@ -389,15 +392,14 @@ static bool htp_kparams_solve_flash_attn(
kparams->scale = scale;
kparams->max_bias = max_bias;
kparams->logit_softcap = logit_softcap;
- kparams->head_split = (opt_fa_split != 0) ? 1 : 0;
- kparams->flags = 0;
+ kparams->flags = (opt_fa_split != 0) ? HTP_FA_FLAG_HEAD_SPLIT : 0;
kparams->G = G;
// team-split only when a team has >1 member (n_kv_heads < N_cores)
uint32_t fa_teams = 1, fa_team_size = 1;
const uint32_t mdev_count = htp_session_mdev_count(sess);
if (opt_fa_split && mdev_count > 1) {
- htp_fa_mdev_teams(n_kv_heads, mdev_count, kparams->head_split != 0, &fa_teams, &fa_team_size);
+ htp_fa_mdev_teams(n_kv_heads, mdev_count, (kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) != 0, &fa_teams, &fa_team_size);
if (fa_team_size > 1) {
kparams->flags |= HTP_FA_FLAG_TEAM_SPLIT;
}
@@ -432,7 +434,9 @@ static bool htp_kparams_solve_flash_attn(
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) {
+ if (hmx_fa_find_chunk_size(&lp, neq1, nek1, vtcm_size, fa_team_size) == 0 &&
+ (nek1 + lp.Bc - 1) / lp.Bc <= FA_MAX_KV_BLOCKS) {
+ const uint32_t n_kv_blocks = (nek1 + lp.Bc - 1) / lp.Bc;
kparams->kernel_type = lp.kernel_type;
if (logit_softcap == 0.0f) {
kparams->scale = scale * (float) M_LOG2E;
@@ -443,14 +447,19 @@ static bool htp_kparams_solve_flash_attn(
}
kparams->Br = lp.Br;
kparams->Bc = lp.Bc;
- kparams->n_kv_blocks = (nek1 + lp.Bc - 1) / lp.Bc;
+ kparams->n_kv_blocks = (uint16_t) n_kv_blocks;
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;
+ if (mask_broadcast) {
+ kparams->flags |= HTP_FA_FLAG_MASK_BCAST;
+ }
// 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;
+ const bool pipeline = (kparams->n_kv_blocks >= 3 && n_hvx >= 2 && (!has_mask || mask_broadcast));
+ if (pipeline) {
+ kparams->flags |= HTP_FA_FLAG_PIPELINE;
+ }
lp.n_hvx = kparams->n_hvx;
- lp.pipeline = (kparams->u.hmx.pipeline != 0);
+ lp.pipeline = pipeline;
kparams->vtcm_size = hmx_fa_compute_vtcm_usage(&lp);
kparams->u.hmx.div_G = init_fastdiv_values(G);
if (mask) {
@@ -461,10 +470,15 @@ static bool htp_kparams_solve_flash_attn(
}
}
+ const uint32_t n_kv_blocks = (k->ne[1] + 64 - 1) / 64;
+ if (n_kv_blocks > FA_MAX_KV_BLOCKS || n_head > 512) {
+ return false;
+ }
+
kparams->kernel_type = HTP_FA_KERNEL_HVX;
kparams->Br = 1;
kparams->Bc = 64;
- kparams->n_kv_blocks = (k->ne[1] + 64 - 1) / 64;
+ kparams->n_kv_blocks = (uint16_t) n_kv_blocks;
kparams->n_hvx = n_hvx;
const size_t size_q_row_padded = hex_round_up(htp_tensor_get_row_size(q->type, q->ne[0]), 128);
@@ -492,10 +506,6 @@ static bool htp_kparams_solve_flash_attn(
kparams->u.hvx.size_v_row_padded = size_v_row_padded;
kparams->u.hvx.src0_div21 = init_fastdiv_values(q->ne[2] * q->ne[1]);
kparams->u.hvx.src0_div1 = init_fastdiv_values(q->ne[1]);
- 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 (mask) {
kparams->src3_div2 = init_fastdiv_values(mask->ne[2]);
kparams->src3_div3 = init_fastdiv_values(mask->ne[3]);
@@ -687,7 +697,7 @@ static bool htp_matmul_is_hmx_eligible(
}
const bool is_tiled = ggml_hexagon_tensor_will_tile(src0);
- if (ggml_is_quantized((ggml_type) wtype) && !is_tiled) {
+ if (htp_is_quantized_weight_type((ggml_type) wtype) && !is_tiled) {
return false;
}
if (!is_matmul_id && is_batched && is_tiled) {
@@ -706,6 +716,40 @@ static bool htp_matmul_is_hmx_eligible(
return true;
}
+static inline uint8_t htp_mm_scale_to_fused_mode(enum htp_mm_scale_mode mode) {
+ switch (mode) {
+ case HTP_MM_SCALE_PER_TENSOR: return HTP_MM_FUSED_SCALE_PER_TENSOR;
+ case HTP_MM_SCALE_PER_CHANNEL: return HTP_MM_FUSED_SCALE_PER_CHANNEL;
+ case HTP_MM_SCALE_PER_EXPERT: return HTP_MM_FUSED_SCALE_PER_EXPERT;
+ case HTP_MM_SCALE_PER_CHANNEL_EXPERT: return HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT;
+ default: return 0;
+ }
+}
+
+static inline size_t htp_mm_scale_vtcm_bytes(const struct ggml_tensor * src0, enum htp_mm_scale_mode mode, bool for_hmx) {
+ switch (mode) {
+ case HTP_MM_SCALE_PER_TENSOR:
+ return 128;
+ case HTP_MM_SCALE_PER_CHANNEL:
+ return hex_round_up((size_t) src0->ne[1] * sizeof(float), 128);
+ case HTP_MM_SCALE_PER_EXPERT:
+ return for_hmx ? 128 : hex_round_up((size_t) src0->ne[2] * sizeof(float), 128);
+ case HTP_MM_SCALE_PER_CHANNEL_EXPERT:
+ return for_hmx
+ ? hex_round_up((size_t) src0->ne[1] * sizeof(float), 128)
+ : hex_round_up((size_t) src0->ne[1] * (size_t) src0->ne[2] * sizeof(float), 128);
+ default:
+ return 0;
+ }
+}
+
+static inline bool htp_mm_can_fuse_scale(const struct ggml_tensor * src0, const struct ggml_tensor * scale) {
+ return scale != nullptr &&
+ scale->type == GGML_TYPE_F32 &&
+ ggml_hexagon_tensor_will_tile(src0) &&
+ ggml_is_contiguous(scale);
+}
+
static bool htp_kparams_solve_hmx_mm(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
@@ -723,7 +767,9 @@ static bool htp_kparams_solve_hmx_mm(
bool is_batched,
size_t vtcm_budget,
struct htp_mm_kernel_params * kparams,
- bool is_glu = false
+ bool is_glu = false,
+ size_t scale_size = 0,
+ bool has_norm = false
) {
GGML_UNUSED(act);
const bool bias_is_2d = bias && (bias->ne[1] > 1);
@@ -751,22 +797,33 @@ static bool htp_kparams_solve_hmx_mm(
bool use_grouped = false;
int act_hvx_selected = 0;
- 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 >= 3) && (!dst || ggml_prec_get_acc(dst) != GGML_PREC_F32);
- if (is_tiled && htp_is_int_hmx_weight_type((int) wtype) && allow_w8a8 &&
+ const uint8_t f16_kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_F16_BATCHED : HTP_MM_KERNEL_HMX_F16_2D;
+ uint8_t kernel_type = f16_kernel_type;
+ const uint32_t min_k = htp_hmx_w8a8_min_k((int) wtype);
+ const bool needs_scale = ggml_needs_scale((ggml_type) wtype);
+ const bool allow_w8a8 = (opt_mm_select >= 3) && (!dst || ggml_prec_get_acc(dst) != GGML_PREC_F32);
+ if (is_tiled && htp_is_hmx_w8a8_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;
}
+ // unscaled NVFP4/F8_E4M3 weights can overflow FP16 HMX accumulation
+ const bool has_fused_scale = (scale_size > 0);
+ if (needs_scale && !has_fused_scale && !htp_mm_kernel_is_hmx_w8a8(kernel_type)) {
+ return false;
+ }
+
if (is_glu && !htp_mm_kernel_is_hmx_2d(kernel_type)) {
return false;
}
+ if (has_norm && (ne00_padded % 64) != 0) {
+ return false;
+ }
+ const size_t norm_size = has_norm ? htp_mm_fused_norm_vtcm_bytes((uint32_t) ne00_padded) : 0;
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 (!is_glu && !has_norm && 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;
}
@@ -790,23 +847,23 @@ static bool htp_kparams_solve_hmx_mm(
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;
- // 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;
+ // Non-grouped HMX_F16_BATCHED dispatches to hmx_f16_mm_2d (full 2D layout, not grouped-batched layout).
+ const uint8_t solve_ktype = htp_mm_kernel_is_hmx_w8a8(kernel_type) ? kernel_type : HTP_MM_KERNEL_HMX_F16_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)) {
+ 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, scale_size, norm_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
+ if (htp_mm_kernel_is_hmx_w8a8(kernel_type) && !(needs_scale && !has_fused_scale)) {
+ kernel_type = HTP_MM_KERNEL_HMX_F16_2D;
+ if (!htp_mm_hmx_solve_2d_params_glu(HTP_MM_KERNEL_HMX_F16_2D, wtype, ne00_padded, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, aligned_tile_size, res_out_elem_size, scale_size, norm_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)) {
+ } else if (!htp_mm_hmx_solve_2d_params_ex_scaled(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, scale_size, norm_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_w8a8(kernel_type) && !(needs_scale && !has_fused_scale)) {
+ kernel_type = f16_kernel_type;
+ if (!htp_mm_hmx_solve_2d_params_ex_scaled(HTP_MM_KERNEL_HMX_F16_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, scale_size, norm_size, res_in_elem_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) {
return false;
}
} else {
@@ -815,14 +872,25 @@ static bool htp_kparams_solve_hmx_mm(
}
}
- const uint32_t hmx_n_groups = htp_mm_kernel_is_hmx_int(kernel_type)
+ const uint32_t hmx_n_groups = htp_mm_kernel_is_hmx_w8a8(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);
+ uint8_t flags = 0;
+ if (pipeline) {
+ flags |= HTP_MM_FLAG_PIPELINE;
+ }
+ if (htp_mm_kernel_is_hmx_w8a8(kernel_type) && opt_mm_fwht != 0) {
+ flags |= HTP_MM_FLAG_FWHT;
+ }
+ if (use_grouped) {
+ flags |= HTP_MM_FLAG_GROUPED;
+ }
+
kparams->n_hmx = 1;
kparams->hmx_n_groups = (int32_t) hmx_n_groups;
- kparams->pipeline = pipeline ? 1 : 0;
+ kparams->flags = flags;
kparams->m_chunk = m_chunk;
kparams->n_chunk = n_chunk;
kparams->n_hvx = n_hvx;
@@ -835,6 +903,7 @@ static bool htp_kparams_solve_hmx_mm(
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->vtcm_scale_size = (int32_t) scale_size;
kparams->kernel_type = kernel_type;
return true;
}
@@ -855,7 +924,8 @@ static void htp_kparams_solve_hvx_mm(
bool is_matmul_id,
const size_t bias_row_size,
size_t vtcm_budget,
- struct htp_mm_kernel_params * kparams
+ struct htp_mm_kernel_params * kparams,
+ size_t scale_size = 0
) {
if (opt_mm_select < 1) {
kparams->kernel_type = HTP_MM_KERNEL_UNSUPPORTED;
@@ -888,9 +958,9 @@ static void htp_kparams_solve_hvx_mm(
uint32_t max_prefetch = (src1_nrows > HTP_MM_HMX_MIN_NROWS) ? 2 : 16;
uint32_t best_n_prefetch = 2;
for (uint32_t d = max_prefetch; d >= 2; d /= 2) {
- htp_mm_hvx_vtcm_layout_build(
+ htp_mm_hvx_vtcm_layout_build_ex(
&L, kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx,
- dst_row_size, src0->nb[1], act_elem_size, 0, d, true, false
+ dst_row_size, src0->nb[1], act_elem_size, 0, scale_size, d, true, false
);
if (L.total_bytes <= vtcm_budget) {
best_n_prefetch = d;
@@ -901,9 +971,10 @@ static void htp_kparams_solve_hvx_mm(
kparams->kernel_type = HTP_MM_KERNEL_UNSUPPORTED;
return;
}
- kparams->n_prefetch = best_n_prefetch;
- kparams->vtcm_size = L.total_bytes;
- kparams->vtcm_bias_size = 0;
+ kparams->n_prefetch = best_n_prefetch;
+ kparams->vtcm_size = L.total_bytes;
+ kparams->vtcm_bias_size = 0;
+ kparams->vtcm_scale_size = (int32_t) L.scale_bytes;
return;
} else {
if (k_align && opt_mm_select >= 1) {
@@ -915,9 +986,9 @@ static void htp_kparams_solve_hvx_mm(
uint32_t max_prefetch = (src1_nrows > HTP_MM_HMX_MIN_NROWS) ? 2 : 16;
uint32_t best_n_prefetch = 2;
for (uint32_t d = max_prefetch; d >= 2; d /= 2) {
- htp_mm_hvx_vtcm_layout_build(
+ htp_mm_hvx_vtcm_layout_build_ex(
&L, kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx,
- dst_row_size, src0->nb[1], act_elem_size, bias_row_size, d, false, false
+ dst_row_size, src0->nb[1], act_elem_size, bias_row_size, scale_size, d, false, false
);
if (L.total_bytes <= vtcm_budget) {
best_n_prefetch = d;
@@ -926,14 +997,15 @@ static void htp_kparams_solve_hvx_mm(
}
uint32_t m_chunk = 0;
- if (htp_mm_hvx_solve_vtcm_params(
+ if (htp_mm_hvx_solve_vtcm_params_ex(
kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx,
- dst_row_size, src0->nb[1], act_elem_size, bias_row_size, best_n_prefetch, vtcm_budget,
+ dst_row_size, src0->nb[1], act_elem_size, bias_row_size, scale_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;
- kparams->vtcm_size = L.total_bytes;
- kparams->vtcm_bias_size = L.bias_bytes;
+ kparams->n_prefetch = best_n_prefetch;
+ kparams->m_chunk = (m_chunk < (uint32_t) src1_nrows) ? m_chunk : 0;
+ kparams->vtcm_size = L.total_bytes;
+ kparams->vtcm_bias_size = L.bias_bytes;
+ kparams->vtcm_scale_size = (int32_t) L.scale_bytes;
return;
}
}
@@ -979,7 +1051,11 @@ static bool htp_kparams_solve_matmul_impl(
const struct ggml_tensor * src1,
const struct ggml_tensor * bias,
const struct ggml_tensor * dst,
- struct htp_mm_kernel_params * kparams
+ struct htp_mm_kernel_params * kparams,
+ enum htp_mm_scale_mode scale_mode = HTP_MM_SCALE_NONE,
+ size_t hmx_scale_size_override = 0,
+ size_t hvx_scale_size_override = 0,
+ bool has_norm = false
) {
memset(kparams, 0, sizeof(*kparams));
@@ -999,20 +1075,29 @@ static bool htp_kparams_solve_matmul_impl(
const int ne11_padded = hex_round_up(ne11, 32);
const int ne01_tiled = hex_round_up(ne01, 32);
- const bool is_matmul_id = (dst->op == GGML_OP_MUL_MAT_ID);
- const bool is_batched = (ne02 * ne03 > 1 || ne12 * ne13 > 1);
- const size_t vtcm_budget = htp_session_vtcm_size(sess);
+ const bool is_matmul_id = (dst->op == GGML_OP_MUL_MAT_ID);
+ const bool is_batched = (ne02 * ne03 > 1 || ne12 * ne13 > 1);
+ const size_t vtcm_budget = htp_session_vtcm_size(sess);
+ const size_t hmx_scale_size = hmx_scale_size_override ? hmx_scale_size_override : htp_mm_scale_vtcm_bytes(src0, scale_mode, true);
+ const size_t hvx_scale_size = hvx_scale_size_override ? hvx_scale_size_override : htp_mm_scale_vtcm_bytes(src0, scale_mode, false);
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, bias, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, is_matmul_id, is_batched, 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, false, hmx_scale_size, has_norm)) {
goto finalize;
}
}
+ if (has_norm) {
+ return false;
+ }
- 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);
+ 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, hvx_scale_size);
finalize:
+ if (scale_mode != HTP_MM_SCALE_NONE) {
+ kparams->scale_mask = 1;
+ kparams->scale_mode = htp_mm_scale_to_fused_mode(scale_mode);
+ }
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);
@@ -1073,6 +1158,12 @@ static bool htp_matmul_check_types(
}
return true;
+ case GGML_TYPE_F8_E4M3:
+ if (!ggml_is_contiguous(src0) || ggml_is_permuted(src0) || ggml_is_view(src0)) {
+ return false;
+ }
+ return src0->ne[0] >= 32 && (src0->ne[0] % 32 == 0) && src0->ne[3] == 1;
+
case GGML_TYPE_F16:
case GGML_TYPE_F32:
case GGML_TYPE_BF16:
@@ -1116,6 +1207,12 @@ static bool htp_matmul_check_types(
}
return src0->ne[0] % ggml_blck_size(src0->type) == 0;
+ case GGML_TYPE_F8_E4M3:
+ if (!ggml_is_contiguous(src0) || ggml_is_permuted(src0) || ggml_is_view(src0)) {
+ return false;
+ }
+ return src0->ne[0] >= 32 && (src0->ne[0] % 32 == 0) && src0->ne[3] == 1;
+
case GGML_TYPE_F32:
case GGML_TYPE_F16:
case GGML_TYPE_BF16:
@@ -1126,6 +1223,23 @@ static bool htp_matmul_check_types(
}
}
+htp_opnode htp_mm_make_scale_opnode(
+ const struct ggml_tensor * op,
+ const struct ggml_tensor * scale
+) {
+ const enum htp_mm_scale_mode mode = htp_get_mm_scale_mode(op);
+ const bool use_mul_id = (mode == HTP_MM_SCALE_PER_EXPERT || mode == HTP_MM_SCALE_PER_CHANNEL_EXPERT);
+ htp_opnode scale_node(use_mul_id ? HTP_OP_MUL_ID : HTP_OP_MUL);
+ scale_node.inputs.push_back(op);
+ scale_node.inputs.push_back(scale);
+ if (use_mul_id) {
+ scale_node.inputs.push_back(op->src[2]);
+ scale_node.params[0] = (mode == HTP_MM_SCALE_PER_EXPERT) ? 1 : 0;
+ }
+ scale_node.outputs.push_back(op);
+ return scale_node;
+}
+
static bool htp_kparams_solve_matmul(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * op,
@@ -1138,41 +1252,39 @@ static bool htp_kparams_solve_matmul(
if (!htp_matmul_check_types(src0, src1, dst)) {
return false;
}
- 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, nullptr, &dst_collapsed, kparams);
+
+ const bool can_collapse = htp_matmul_can_collapse(src0, src1, dst);
+ const ggml_tensor src1_collapsed = can_collapse ? htp_tensor_collapse_rows(src1) : *src1;
+ const ggml_tensor dst_collapsed = can_collapse ? htp_tensor_collapse_rows(dst) : *dst;
+ const struct ggml_tensor * p_src1 = can_collapse ? &src1_collapsed : src1;
+ const struct ggml_tensor * p_dst = can_collapse ? &dst_collapsed : dst;
+
+ if (const struct ggml_tensor * scale = ggml_get_src_scale(op, 0)) {
+ const enum htp_mm_scale_mode mode = htp_get_mm_scale_mode(op);
+ if (htp_mm_can_fuse_scale(src0, scale)) {
+ if (htp_kparams_solve_matmul_impl(sess, src0, p_src1, nullptr, p_dst, kparams, mode)) {
+ return true;
+ }
+ }
+ htp_opnode scale_node = htp_mm_make_scale_opnode(op, scale);
+ if (!htp_kparams_solve(sess, scale_node)) {
+ return false;
+ }
}
- 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 * bias,
- const struct ggml_tensor * dst,
- struct htp_mm_kernel_params * kparams
-) {
- 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 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);
+ return htp_kparams_solve_matmul_impl(sess, src0, p_src1, nullptr, p_dst, kparams);
}
-bool htp_kparams_solve_mmnx(
+static 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
+ struct htp_mm_kernel_params * kparams,
+ size_t hmx_scale_size,
+ size_t hvx_scale_size,
+ bool has_norm
) {
const uint32_t n_hvx = htp_session_n_hvx(sess);
const uint32_t n_hmx = htp_session_n_hmx(sess);
@@ -1200,11 +1312,14 @@ bool htp_kparams_solve_mmnx(
const bool hmx_enabled = (n_hmx > 0) && (opt_mm_select >= 2);
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)) {
+ 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, false, hmx_scale_size, has_norm)) {
kparams->n_weights = n_weights;
goto finalize;
}
}
+ if (has_norm) {
+ return false;
+ }
if (!is_tiled || (act->type != GGML_TYPE_F32 && act->type != GGML_TYPE_F16) || ne10 % 32 != 0) {
kparams->kernel_type = HTP_MM_KERNEL_UNSUPPORTED;
@@ -1224,9 +1339,9 @@ bool htp_kparams_solve_mmnx(
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(
+ htp_mm_hvx_vtcm_layout_build_ex(
&L, hvx_ktype, wtype, ne10, act_nrows, n_hvx,
- dst_row_size, src0_row_size, act_elem_size, 0, d, false, true
+ dst_row_size, src0_row_size, act_elem_size, 0, hvx_scale_size, d, false, true
);
if (L.total_bytes <= vtcm_budget) {
best_n_prefetch = d;
@@ -1235,9 +1350,9 @@ bool htp_kparams_solve_mmnx(
}
struct htp_mm_hvx_vtcm_layout L;
- htp_mm_hvx_vtcm_layout_build(
+ htp_mm_hvx_vtcm_layout_build_ex(
&L, hvx_ktype, wtype, ne10, act_nrows, n_hvx,
- dst_row_size, src0_row_size, act_elem_size, 0, best_n_prefetch, false, true
+ dst_row_size, src0_row_size, act_elem_size, 0, hvx_scale_size, best_n_prefetch, false, true
);
if (opt_mm_select >= 1 && L.total_bytes <= vtcm_budget) {
@@ -1246,6 +1361,7 @@ bool htp_kparams_solve_mmnx(
kparams->aligned_tile_size = htp_tensor_get_tile_padded_size(wtype);
kparams->act_row_size = act_row_size;
kparams->vtcm_bias_size = 0;
+ kparams->vtcm_scale_size = (uint32_t) L.scale_bytes;
kparams->vtcm_size = L.total_bytes;
kparams->n_prefetch = best_n_prefetch;
kparams->n_weights = n_weights;
@@ -1264,14 +1380,16 @@ finalize:
return (size_t) kparams->vtcm_size <= vtcm_budget;
}
-bool htp_kparams_solve_mmnx_glu(
+static 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
+ struct htp_mm_kernel_params * kparams,
+ size_t scale_size,
+ bool has_norm
) {
if (htp_session_n_hmx(sess) == 0 || opt_mm_select < 2) {
return false;
@@ -1311,7 +1429,7 @@ bool htp_kparams_solve_mmnx_glu(
!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)) {
+ 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, scale_size, has_norm)) {
return false;
}
@@ -1325,67 +1443,66 @@ bool htp_kparams_solve_mmnx_glu(
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(
+static bool htp_kparams_solve_mmidnx(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * act,
const struct ggml_tensor * dst,
int32_t n_weights,
- struct htp_mm_kernel_params * kparams
+ struct htp_mm_kernel_params * kparams,
+ size_t hmx_scale_size,
+ size_t hvx_scale_size
) {
- const bool ok = htp_kparams_solve_matmul_impl(sess, src0, act, nullptr, dst, kparams);
+ const bool ok = htp_kparams_solve_matmul_impl(sess, src0, act, nullptr, dst, kparams, HTP_MM_SCALE_NONE, hmx_scale_size, hvx_scale_size);
kparams->n_weights = n_weights;
return ok;
}
-static bool htp_kparams_solve_binary(
+static bool htp_kparams_solve_binary_impl(
const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * op_tensor,
- struct htp_binary_kernel_params * kparams
+ 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_binary_kernel_params * kparams,
+ bool mul_id_scalar = false
) {
memset(kparams, 0, sizeof(*kparams));
- const uint32_t op = htp_op_remap(op_tensor);
- const struct ggml_tensor * src0 = op_tensor->src[0];
- const struct ggml_tensor * src1 = op_tensor->src[1];
- 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)) {
+ (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
+ !ggml_are_same_shape(src0, dst)) {
return false;
}
const bool is_add_id = (op == HTP_OP_ADD_ID);
- if (is_add_id) {
- if (src2->type != GGML_TYPE_I32) {
- return false;
- }
- if (!ggml_are_same_shape(src0, dst)) {
- return false;
- }
- if (src1->ne[0] != src0->ne[0] || src1->ne[2] != 1 || src1->ne[3] != 1) {
+ const bool is_mul_id = (op == HTP_OP_MUL_ID);
+ const bool is_id_op = is_add_id || is_mul_id;
+ if (is_id_op) {
+ if (!src2 || src2->type != GGML_TYPE_I32 ||
+ src2->ne[0] != src0->ne[1] || src2->ne[1] != src0->ne[2] || !ggml_is_matrix(src2)) {
return false;
}
- if (src2->ne[0] != src0->ne[1] || src2->ne[1] != src0->ne[2]) {
+ if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst) || !ggml_is_contiguous_rows(src2) ||
+ src2->nb[1] < ggml_row_size(src2->type, src2->ne[0])) {
return false;
}
- 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] < ggml_row_size(src2->type, src2->ne[0])) {
- return false;
+ if (mul_id_scalar) {
+ if (!ggml_is_vector(src1)) {
+ return false;
+ }
+ } else {
+ if (src1->ne[0] != src0->ne[0] || !ggml_is_matrix(src1)) {
+ return false;
+ }
+ if (is_add_id ? !ggml_is_contiguous(src1) : (!ggml_is_contiguous_rows(src1) && !ggml_is_permuted(src1))) {
+ return false;
+ }
}
} else {
- if (ggml_is_permuted(src0) || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) {
- return false;
- }
- if (!ggml_can_repeat(src1, src0)) {
+ if (ggml_is_permuted(src0) || ggml_is_permuted(dst) || !ggml_can_repeat(src1, src0)) {
return false;
}
if (!ggml_is_contiguous_rows(src1) && !ggml_is_permuted(src1)) {
@@ -1396,12 +1513,15 @@ 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 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_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 table_elem_size = (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)
+ ? sizeof(ggml_fp16_t)
+ : sizeof(float);
+ 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);
@@ -1415,69 +1535,83 @@ static bool htp_kparams_solve_binary(
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] &&
- 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) &&
- (src1->ne[3] == src0->ne[3] || src1->ne[3] == 1);
- const bool is_complex = !is_add_id && !is_scalar && !is_same_shape && !is_row_bcast && (src1->ne[0] == src0->ne[0]);
- const bool is_contig = ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst);
- 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)) {
- kparams->src0_row_size_aligned = src0_row_size_aligned;
- kparams->src1_row_size_aligned = src1_row_size_aligned;
- kparams->dst_row_size_aligned = dst_row_size_aligned;
- struct htp_binary_vtcm_layout L;
- 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;
size_t src1_size = 0;
size_t src2_size = 0;
- if (is_add_id) {
- kernel_type = HTP_BINARY_KERNEL_ADD_ID;
- src1_size = hex_round_up(src1->ne[1] * src1_row_size_aligned, 128);
- src2_size = hex_round_up(ggml_nelements(src2) * sizeof(int32_t), 128);
- if (src1_size + src2_size > vtcm_size) {
- return false;
- }
- } else if (is_row_bcast) {
- kernel_type = HTP_BINARY_KERNEL_ROW_BCAST;
- 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) * ((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;
+ if (is_id_op) {
+ if (is_add_id) {
+ kernel_type = HTP_BINARY_KERNEL_ADD_ID;
+ src1_size = hex_round_up(src1->ne[1] * src1_row_size_aligned, 128);
+ } else if (mul_id_scalar) {
+ kernel_type = HTP_BINARY_KERNEL_MUL_ID_SCALAR;
+ src1_size = hex_round_up(src1->ne[0] * table_elem_size, 128);
+ if (src1->nb[0] != src1_elem_size) {
+ kparams->flags |= HTP_BINARY_FLAG_SRC1_STRIDED;
+ }
+ } else {
+ kernel_type = HTP_BINARY_KERNEL_MUL_ID;
+ src1_size = hex_round_up(src1->ne[1] * src1_row_size_aligned, 128);
+ if (src1->nb[0] != src1_elem_size) {
+ kparams->flags |= HTP_BINARY_FLAG_SRC1_STRIDED;
+ }
}
- kernel_type = HTP_BINARY_KERNEL_SCALAR;
- kparams->src1_strided = !ggml_is_contiguous(src1) ? 1 : 0;
- } else if (is_same_shape) {
- kernel_type = HTP_BINARY_KERNEL_SAME_SHAPE;
- } else if (is_complex) {
- src1_size = hex_round_up(ggml_nelements(src1) * src1_elem_size + 128, 128);
- if (src1_size > vtcm_size) {
+ src2_size = hex_round_up(ggml_nelements(src2) * sizeof(int32_t), 128);
+ if (src1_size + src2_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) * src1_elem_size + 128, 128);
- if (src1_size > vtcm_size) {
- return false;
+ const bool is_contig = ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst);
+ const bool is_scalar_broadcast = ggml_nelements(src1) == 1;
+ if (is_contig && (ggml_are_same_shape(src0, src1) || is_scalar_broadcast)) {
+ kparams->src0_row_size_aligned = src0_row_size_aligned;
+ kparams->src1_row_size_aligned = src1_row_size_aligned;
+ kparams->dst_row_size_aligned = dst_row_size_aligned;
+ struct htp_binary_vtcm_layout L;
+ 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);
+ }
+
+ const bool is_scalar = src1->ne[0] == 1;
+ const bool is_row_bcast = !is_scalar &&
+ src1->ne[0] == src0->ne[0] &&
+ ggml_nrows(src0) > 1 &&
+ ggml_is_vector(src1);
+ const bool is_same_shape = !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) &&
+ (src1->ne[3] == src0->ne[3] || src1->ne[3] == 1);
+
+ if (is_row_bcast) {
+ kernel_type = HTP_BINARY_KERNEL_ROW_BCAST;
+ src1_size = hex_round_up(src1->ne[0] * table_elem_size, 128);
+ if (src1->nb[0] != src1_elem_size) {
+ kparams->flags |= HTP_BINARY_FLAG_SRC1_STRIDED;
+ }
+ } else if (is_scalar) {
+ src1_size = hex_round_up(ggml_nelements(src1) * table_elem_size, 128);
+ if (src1_size > vtcm_size) {
+ return false;
+ }
+ kernel_type = HTP_BINARY_KERNEL_SCALAR;
+ if (!ggml_is_contiguous(src1)) {
+ kparams->flags |= HTP_BINARY_FLAG_SRC1_STRIDED;
+ }
+ } else if (is_same_shape) {
+ kernel_type = HTP_BINARY_KERNEL_SAME_SHAPE;
+ } else {
+ src1_size = hex_round_up(ggml_nelements(src1) * src1_elem_size + 128, 128);
+ if (src1_size > vtcm_size) {
+ return false;
+ }
+ kernel_type = (src1->ne[0] == src0->ne[0]) ? HTP_BINARY_KERNEL_COMPLEX : HTP_BINARY_KERNEL_REPEAT;
+ if (!ggml_is_contiguous(src1)) {
+ kparams->flags |= HTP_BINARY_FLAG_SRC1_STRIDED;
+ }
}
- kernel_type = HTP_BINARY_KERNEL_REPEAT;
- kparams->src1_strided = !ggml_is_contiguous(src1) ? 1 : 0;
}
const uint32_t src0_nrows = ggml_nrows(src0);
@@ -1511,7 +1645,9 @@ static bool htp_kparams_solve_binary(
split_at_ne01 = true;
}
}
- kparams->split_at_ne01 = split_at_ne01 ? 1 : 0;
+ if (split_at_ne01) {
+ kparams->flags |= HTP_BINARY_FLAG_SPLIT_NE01;
+ }
bool split_at_ne02 = false;
if (src0->ne[3] > 1) {
@@ -1523,10 +1659,11 @@ static bool htp_kparams_solve_binary(
split_at_ne02 = true;
}
}
- kparams->split_at_ne02 = split_at_ne02 ? 1 : 0;
+ if (split_at_ne02) {
+ kparams->flags |= HTP_BINARY_FLAG_SPLIT_NE02;
+ }
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]);
@@ -1535,12 +1672,6 @@ static bool htp_kparams_solve_binary(
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) {
- 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) src0_elem_size, (uint32_t) src1_elem_size, (uint32_t) dst_elem_size,
- max_hvx_sess, 2, is_scalar_broadcast, vtcm_size);
- }
return false;
}
@@ -1550,6 +1681,16 @@ static bool htp_kparams_solve_binary(
return true;
}
+static bool htp_kparams_solve_binary(
+ const struct ggml_hexagon_session * sess,
+ const struct ggml_tensor * op_tensor,
+ struct htp_binary_kernel_params * kparams
+) {
+ const uint32_t op = htp_op_remap(op_tensor);
+ const struct ggml_tensor * src2 = (op == HTP_OP_ADD_ID) ? op_tensor->src[2] : nullptr;
+ return htp_kparams_solve_binary_impl(sess, op, op_tensor->src[0], op_tensor->src[1], src2, op_tensor, kparams);
+}
+
static bool htp_kparams_solve_binary_nx(
const struct ggml_hexagon_session * sess,
const htp_opnode & node,
@@ -1620,21 +1761,20 @@ static bool htp_kparams_solve_binary_nx(
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;
+ kparams->flags |= HTP_BINARY_FLAG_SPLIT_NE01;
}
if (src0->ne[3] > 1 && in->nb[3] != in->ne[2] * in->nb[2]) {
- kparams->split_at_ne02 = 1;
+ kparams->flags |= HTP_BINARY_FLAG_SPLIT_NE02;
}
}
if (src0->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) {
- kparams->split_at_ne01 = 1;
+ kparams->flags |= HTP_BINARY_FLAG_SPLIT_NE01;
}
if (src0->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) {
- kparams->split_at_ne02 = 1;
+ kparams->flags |= HTP_BINARY_FLAG_SPLIT_NE02;
}
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]);
@@ -1767,7 +1907,9 @@ static bool htp_kparams_solve_unary_impl(
broadcast_src1 = true;
}
const uint32_t src1_nrows = broadcast_src1 ? (uint32_t) src1->ne[1] : 0;
- kparams->broadcast_src1 = broadcast_src1;
+ if (broadcast_src1) {
+ kparams->flags |= HTP_UNARY_FLAG_BCAST_SRC1;
+ }
const size_t src0_data_row_size = (size_t) src0->ne[0] * src0_elem_size;
const uint32_t ne01 = (uint32_t) src0->ne[1];
@@ -1786,9 +1928,9 @@ static bool htp_kparams_solve_unary_impl(
max_block = (max_block / ne01) * ne01;
}
- kparams->src0_contig = src0_contig ? 1 : 0;
- kparams->src1_contig = src1_contig ? 1 : 0;
- kparams->src0_slice_dma = src0_slice_dma ? 1 : 0;
+ if (src0_contig) { kparams->flags |= HTP_UNARY_FLAG_SRC0_CONTIG; }
+ if (src1_contig) { kparams->flags |= HTP_UNARY_FLAG_SRC1_CONTIG; }
+ if (src0_slice_dma) { kparams->flags |= HTP_UNARY_FLAG_SRC0_SLICE_DMA; }
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);
@@ -1812,33 +1954,11 @@ static bool htp_kparams_solve_unary_impl(
kparams->div_ne01 = init_fastdiv_values(src0->ne[1]);
kparams->div_ne02 = init_fastdiv_values(src0->ne[2]);
kparams->div_ne012 = init_fastdiv_values(src0->ne[1] * src0->ne[2]);
- kparams->div_tpr = init_fastdiv_values(tiles_per_row);
return (col_tile > 0 || vtcm_row_per_hvx > 0) && L.total_bytes <= vtcm_size;
}
-bool htp_kparams_solve_rms_norm_mul(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * dst,
- struct htp_unary_kernel_params * kparams
-) {
- 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, src2, dst, kparams);
-}
-
-bool htp_kparams_solve_repeat_get_rows(
+static bool htp_kparams_solve_repeat_get_rows(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
@@ -2034,11 +2154,17 @@ 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 bool src0_f16 = (src0->type == GGML_TYPE_F16);
+ const bool dst_f16 = (dst->type == GGML_TYPE_F16);
+ const bool use_src1 = (src1 != nullptr);
+ const bool use_f16 = (src1 != nullptr && src1->type == GGML_TYPE_F16);
+ const bool use_src2 = (src2 != nullptr);
+
+ kparams->flags = (src0_f16 ? HTP_SOFTMAX_FLAG_SRC0_F16 : 0) |
+ (dst_f16 ? HTP_SOFTMAX_FLAG_DST_F16 : 0) |
+ (use_src1 ? HTP_SOFTMAX_FLAG_USE_SRC1 : 0) |
+ (use_f16 ? HTP_SOFTMAX_FLAG_SRC1_F16 : 0) |
+ (use_src2 ? HTP_SOFTMAX_FLAG_USE_SRC2 : 0);
const uint32_t ne00 = src0->ne[0];
const uint32_t ne10 = src1 ? src1->ne[0] : 1;
@@ -2048,11 +2174,11 @@ static bool htp_kparams_solve_softmax(
ne00,
ne10,
n_head,
- kparams->src0_f16 != 0,
- kparams->dst_f16 != 0,
- kparams->use_src1 != 0,
- kparams->use_f16 != 0,
- kparams->use_src2 != 0,
+ src0_f16,
+ dst_f16,
+ use_src1,
+ use_f16,
+ use_src2,
n_hvx);
if (layout.total_bytes > htp_session_vtcm_size(sess)) {
return false;
@@ -2061,18 +2187,18 @@ static bool htp_kparams_solve_softmax(
kparams->n_hvx = n_hvx;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
- if (kparams->src0_f16) {
- if (!kparams->use_src1) {
+ if (src0_f16) {
+ if (!use_src1) {
kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_NOMASK;
- } else if (kparams->use_f16) {
+ } else if (use_f16) {
kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_MASK_F16;
} else {
kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_MASK_F32;
}
} else {
- if (!kparams->use_src1) {
+ if (!use_src1) {
kparams->kernel_type = HTP_SOFTMAX_KERNEL_NOMASK;
- } else if (kparams->use_f16) {
+ } else if (use_f16) {
kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F16;
} else {
kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F32;
@@ -2313,22 +2439,26 @@ static bool htp_kparams_solve_sum_rows(
const size_t src0_elem_size = ggml_type_size(src0->type);
const uint32_t elems_per_vec = (uint32_t) (128 / src0_elem_size);
+ auto fit_vtcm = [&](struct htp_sum_vtcm_layout * L, uint32_t & chunk_elems, uint32_t & n_hvx) -> bool {
+ 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);
+ }
+ return L->total_bytes <= vtcm_size;
+ };
+
if (op->op == GGML_OP_SUM) {
const uint32_t total_elems = (uint32_t) ggml_nelements(src0);
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) {
+ if (!fit_vtcm(&L, chunk_elems, n_hvx)) {
return false;
}
@@ -2343,16 +2473,7 @@ static bool htp_kparams_solve_sum_rows(
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) {
+ if (!fit_vtcm(&L, chunk_elems, n_hvx)) {
return false;
}
@@ -2369,16 +2490,7 @@ static bool htp_kparams_solve_sum_rows(
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) {
+ if (!fit_vtcm(&L, chunk_elems, n_hvx)) {
return false;
}
@@ -2390,7 +2502,7 @@ static bool htp_kparams_solve_sum_rows(
return true;
}
-bool htp_kparams_solve_unary_mul_glu(
+static bool htp_kparams_solve_unary_mul_glu(
const struct ggml_hexagon_session * sess,
uint32_t op,
const struct ggml_tensor * src0,
@@ -2432,6 +2544,7 @@ bool htp_kparams_solve_unary_mul_glu(
const size_t row_size_aligned = hex_round_up(dst_row_size, 128);
uint32_t vtcm_row_per_hvx = (uint32_t) (vtcm_size / (n_hvx * 3 * row_size_aligned));
+ vtcm_row_per_hvx &= ~1u;
if (vtcm_row_per_hvx < 2) {
return false;
}
@@ -2546,9 +2659,6 @@ static bool htp_kparams_solve_repeat(
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;
@@ -2795,7 +2905,7 @@ static bool htp_kparams_solve_ssm_conv_token_major(
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->flags |= HTP_SSM_CONV_FLAG_TOKEN_MAJOR;
kparams->n_t_tile = n_t_tile;
kparams->n_t_blocks = (n_t + n_t_tile - 1) / n_t_tile;
@@ -3109,7 +3219,7 @@ static bool htp_kparams_solve_pool_2d(
return true;
}
-bool htp_kparams_solve_upscale(
+static bool htp_kparams_solve_upscale(
const struct ggml_hexagon_session * sess,
const struct ggml_tensor * src0,
const struct ggml_tensor * dst,
@@ -3239,8 +3349,8 @@ bool htp_kparams_solve_upscale(
kparams->kernel_type = kernel_type;
kparams->mode = (uint8_t) mode_raw;
- kparams->align_corners = align_corners ? 1 : 0;
- kparams->antialias = antialias ? 1 : 0;
+ kparams->flags = (align_corners ? HTP_UPSCALE_FLAG_ALIGN_CORNERS : 0) |
+ (antialias ? HTP_UPSCALE_FLAG_ANTIALIAS : 0);
kparams->inv_sf0 = inv_sf0;
kparams->inv_sf1 = inv_sf1;
@@ -3398,10 +3508,12 @@ static bool htp_kparams_solve_concat(
return false;
}
- kparams->kernel_type = HTP_CONCAT_KERNEL_TRANSPOSED;
- 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]);
+ kparams->kernel_type = HTP_CONCAT_KERNEL_TRANSPOSED;
+ 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]);
+ kparams->u.transposed.div_ne11 = init_fastdiv_values((uint32_t) src1->ne[1]);
+ kparams->u.transposed.div_ne12_ne11 = init_fastdiv_values((uint32_t) (src1->ne[1] * src1->ne[2]));
return true;
}
@@ -3795,7 +3907,6 @@ static bool htp_kparams_solve_im2col(
kparams->owb = OW;
kparams->wb = IW;
kparams->nbpr = 1;
- kparams->N = N;
kparams->IC = IC;
kparams->ID = 1;
kparams->IH = IH;
@@ -3850,7 +3961,6 @@ static bool htp_kparams_solve_im2col(
kparams->owb = owb;
kparams->wb = (uint32_t) Wb;
kparams->nbpr = nbpr;
- kparams->N = N;
kparams->IC = IC;
kparams->ID = 1;
kparams->IH = IH;
@@ -3976,7 +4086,6 @@ static bool htp_kparams_solve_im2col_3d(
kparams->owb = OW;
kparams->wb = IW;
kparams->nbpr = 1;
- kparams->N = N;
kparams->IC = IC;
kparams->ID = ID;
kparams->IH = IH;
@@ -4025,7 +4134,6 @@ static bool htp_kparams_solve_im2col_3d(
kparams->owb = owb;
kparams->wb = (uint32_t) Wb;
kparams->nbpr = (OW + owb - 1) / owb;
- kparams->N = N;
kparams->IC = IC;
kparams->ID = ID;
kparams->IH = IH;
@@ -4687,8 +4795,8 @@ static bool htp_kparams_solve_solve_tri(
kparams->total_jobs = total_jobs;
kparams->k_chunks = k_chunks;
kparams->col_block = col_block;
- kparams->batched = batched ? 1 : 0;
- kparams->a_full = a_full;
+ kparams->flags = (batched ? HTP_SOLVE_TRI_FLAG_BATCHED : 0) |
+ (a_full ? HTP_SOLVE_TRI_FLAG_A_FULL : 0);
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);
@@ -4930,9 +5038,8 @@ static bool htp_kparams_conv2d_win(
const uint32_t n_cs = (32 + CS - 1) / CS;
kp->kernel_type = (uint8_t) HTP_CONV2D_KERNEL_HMX_WINDOW;
+ kp->flags = (cwhn ? HTP_CONV2D_FLAG_CWHN : 0) | (!w_rows ? HTP_CONV2D_FLAG_W_KMAJOR : 0);
kp->n_hvx = (uint8_t) n_hvx;
- kp->cwhn = cwhn ? 1 : 0;
- kp->w_kmajor = !w_rows ? 1 : 0;
kp->n_row_tiles = n_rt;
kp->ct_chunk = ct;
kp->rt_block = rt_block;
@@ -5150,9 +5257,8 @@ static bool htp_kparams_conv2d_tiled(
}
kp->kernel_type = (uint8_t) HTP_CONV2D_KERNEL_HMX_TILED;
+ kp->flags = (cwhn ? HTP_CONV2D_FLAG_CWHN : 0) | (kmajor ? HTP_CONV2D_FLAG_W_KMAJOR : 0);
kp->n_hvx = (uint8_t) nth;
- kp->cwhn = cwhn ? 1 : 0;
- kp->w_kmajor = kmajor ? 1 : 0;
kp->n_row_tiles = n_rt;
kp->ct_chunk = ct;
kp->rt_block = rt_block;
@@ -5326,7 +5432,7 @@ static bool htp_kparams_solve_conv2d_dw(
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));
+ const uint32_t w_size = (uint32_t) ggml_nbytes(src0);
uint32_t max_hvx_sess = (uint32_t) htp_session_n_hvx(sess);
uint32_t oh_chunk = oh_u;
@@ -5367,15 +5473,13 @@ static bool htp_kparams_solve_conv2d_dw(
htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, n_hvx);
kparams->kernel_type = kernel_type;
+ kparams->flags = (cwhn ? HTP_CONV2D_DW_FLAG_CWHN : 0) | (src0->type == GGML_TYPE_F16 ? HTP_CONV2D_DW_FLAG_F16 : 0);
kparams->n_hvx = (uint8_t) n_hvx;
- kparams->cwhn = cwhn ? 1 : 0;
- kparams->is_f16 = (src0->type == GGML_TYPE_F16) ? 1 : 0;
kparams->total_tasks = total_tasks;
kparams->vtcm_size = (uint32_t) layout.total_bytes;
kparams->w = w;
kparams->h = h;
kparams->c = c;
- kparams->n = n;
kparams->kw = kw;
kparams->kh = kh;
kparams->ow = ow_u;
@@ -5795,54 +5899,75 @@ static inline bool htp_kparams_invoke(
return SolveFn(sess, op, kparams ? (KParams *) kparams : &tmp);
}
-bool htp_kparams_solve(
+static bool htp_kparams_solve_unary_node(
const struct ggml_hexagon_session * sess,
- htp_opnode & node
+ htp_opnode & tmp
) {
- ggml_tensor scratch[HTP_OP_MAX_INPUTS + HTP_OP_MAX_OUTPUTS];
- htp_opnode tmp = node;
- htp_lower_opnode(sess, tmp, scratch);
+ auto * kp = tmp.kparams<htp_unary_kernel_params>();
+ const bool has_scale_bias = (kp->flags & HTP_UNARY_FLAG_SCALE_BIAS) != 0;
+ 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 * src0 = tmp.inputs.empty() ? nullptr : tmp.inputs[0];
+ const ggml_tensor * src1 = tmp.inputs.size() > 1 ? tmp.inputs[1] : nullptr;
+ 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, tmp.dst(), kp);
+ if (has_scale_bias) {
+ kp->flags |= HTP_UNARY_FLAG_SCALE_BIAS;
+ kp->in_scale = in_scale;
+ kp->in_bias = in_bias;
+ kp->out_scale = out_scale;
+ kp->out_bias = out_bias;
+ }
+ return ok;
+}
+static bool htp_kparams_solve_mm_node(
+ const struct ggml_hexagon_session * sess,
+ htp_opnode & tmp
+) {
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();
- auto commit = [&](bool ok) {
- if (ok) {
- memcpy(node.kernel_params, tmp.kernel_params, sizeof(node.kernel_params));
- }
- 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 commit(htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, tmp.kparams<htp_mm_kernel_params>()));
+ auto * kp = tmp.kparams<htp_mm_kernel_params>();
+ const bool had_fused_scale = (kp->scale_mask != 0);
+ const uint8_t norm_w_idx = kp->norm_w_idx;
+ const float norm_eps = kp->norm_eps;
+ const bool has_norm = (norm_w_idx != 0);
+ const bool try_fuse_scale = (kp->kernel_type == HTP_MM_KERNEL_UNSUPPORTED) || had_fused_scale;
+ const ggml_tensor * scale = try_fuse_scale ? ggml_get_src_scale(tmp.node, 0) : nullptr;
+ if (scale && htp_mm_can_fuse_scale(src0, scale)) {
+ const enum htp_mm_scale_mode mode = htp_get_mm_scale_mode(tmp.node);
+ if (htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, kp, mode, 0, 0, has_norm)) {
+ kp->norm_w_idx = norm_w_idx;
+ kp->norm_eps = norm_eps;
+ return true;
+ }
+ }
+ if (had_fused_scale) {
+ return false;
+ }
+ if (!htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, kp, HTP_MM_SCALE_NONE, 0, 0, has_norm)) {
+ return false;
+ }
+ kp->norm_w_idx = norm_w_idx;
+ kp->norm_eps = norm_eps;
+ return true;
}
+
if (tmp.opcode == HTP_OP_MUL_MAT_ADD) {
- if (tmp.inputs.size() != 3) {
+ auto * kp = tmp.kparams<htp_mm_kernel_params>();
+ const uint8_t norm_w_idx = kp->norm_w_idx;
+ const float norm_eps = kp->norm_eps;
+ const bool has_norm = (norm_w_idx != 0);
+ const size_t norm_extra = has_norm ? 1 : 0;
+ if (tmp.inputs.size() != 3 + norm_extra && tmp.inputs.size() != 4 + norm_extra) {
return false;
}
const ggml_tensor * bias = tmp.inputs[2];
@@ -5851,17 +5976,35 @@ bool htp_kparams_solve(
!htp_matmul_check_types(src0, src1, dst)) {
return false;
}
- return commit(htp_kparams_solve_matmul_impl(sess, src0, src1, bias, dst, tmp.kparams<htp_mm_kernel_params>()));
+ const bool has_scale = (kp->scale_mask != 0) || (!has_norm && tmp.inputs.size() == 4 && tmp.inputs[3] != nullptr);
+ const enum htp_mm_scale_mode smode = has_scale ? htp_get_mm_scale_mode(tmp.node) : HTP_MM_SCALE_NONE;
+ if (!htp_kparams_solve_matmul_impl(sess, src0, src1, bias, dst, kp, smode, 0, 0, has_norm)) {
+ return false;
+ }
+ kp->norm_w_idx = norm_w_idx;
+ kp->norm_eps = norm_eps;
+ return true;
}
- if (tmp.opcode == HTP_OP_MUL_MAT_NX) {
+
+ if (tmp.opcode == HTP_OP_MUL_MAT_NX || tmp.opcode == HTP_OP_MUL_MAT_ID_NX) {
+ const bool is_id = (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 + 1) {
+ auto * kp = tmp.kparams<htp_mm_kernel_params>();
+ const uint8_t scale_mask = kp->scale_mask;
+ const uint16_t scale_mode = kp->scale_mode;
+ const uint8_t norm_w_idx = is_id ? 0 : kp->norm_w_idx;
+ const float norm_eps = is_id ? 0.0f : kp->norm_eps;
+ const bool has_norm = (norm_w_idx != 0);
+ const size_t base_extra = (is_id ? 2 : 1) + (has_norm ? 1 : 0);
+ if (n_w == 0 || (tmp.inputs.size() != n_w + base_extra && tmp.inputs.size() != 2 * n_w + base_extra)) {
return false;
}
- const ggml_tensor * act = tmp.inputs[n_w];
+ 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;
+ size_t hmx_scale_sz = 0;
+ size_t hvx_scale_sz = 0;
for (size_t i = 0; i < n_w; ++i) {
if (!htp_matmul_check_types(tmp.inputs[i], act, tmp.outputs[i])) {
return false;
@@ -5872,88 +6015,84 @@ bool htp_kparams_solve(
if (ggml_type_size(tmp.outputs[i]->type) > ggml_type_size(max_dst_type)) {
max_dst_type = tmp.outputs[i]->type;
}
+ if ((scale_mask >> i) & 1u) {
+ const uint32_t sm = htp_mm_scale_mode_get(scale_mode, (uint32_t) i);
+ const size_t sb = htp_mm_fused_scale_vtcm_bytes((uint32_t) tmp.inputs[i]->ne[1], (uint32_t) tmp.inputs[i]->ne[2], sm, true);
+ if (sb > hmx_scale_sz) {
+ hmx_scale_sz = sb;
+ }
+ hvx_scale_sz += htp_mm_fused_scale_vtcm_bytes((uint32_t) tmp.inputs[i]->ne[1], (uint32_t) tmp.inputs[i]->ne[2], sm, false);
+ }
}
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>())) {
+ const bool solved = is_id
+ ? htp_kparams_solve_mmidnx(sess, w_for_solve, act, &d_for_solve, (int32_t) n_w, kp, hmx_scale_sz, hvx_scale_sz)
+ : htp_kparams_solve_mmnx(sess, w_for_solve, act, &d_for_solve, (int32_t) n_w, kp, hmx_scale_sz, hvx_scale_sz, has_norm);
+ if (!solved) {
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_MUL_MAT_NX_GLU) {
- if (tmp.inputs.size() != 3 || tmp.outputs.size() != 1) {
- return false;
+ kp->scale_mask = scale_mask;
+ kp->scale_mode = scale_mode;
+ if (!is_id) {
+ kp->norm_w_idx = norm_w_idx;
+ kp->norm_eps = norm_eps;
}
- 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>()));
+ return 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));
}
- 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) {
+
+ if (tmp.opcode == HTP_OP_MUL_MAT_NX_GLU) {
+ auto * kp = tmp.kparams<htp_mm_kernel_params>();
+ const uint8_t glu_op = kp->glu_op;
+ const uint8_t scale_mask = kp->scale_mask;
+ const uint16_t scale_mode = kp->scale_mode;
+ const uint8_t norm_w_idx = kp->norm_w_idx;
+ const float norm_eps = kp->norm_eps;
+ const bool has_norm = (norm_w_idx != 0);
+ const size_t norm_extra = has_norm ? 1 : 0;
+ if ((tmp.inputs.size() != 3 + norm_extra && tmp.inputs.size() != 5 + norm_extra) || tmp.outputs.size() != 1) {
return false;
}
- 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;
+ size_t scale_size = 0;
+ for (uint32_t i = 0; i < 2; ++i) {
+ if ((scale_mask >> i) & 1u) {
+ const uint32_t sm = htp_mm_scale_mode_get(scale_mode, i);
+ scale_size += htp_mm_fused_scale_vtcm_bytes((uint32_t) tmp.inputs[i]->ne[1], (uint32_t) tmp.inputs[i]->ne[2], sm, true);
}
}
- 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>())) {
+ if (!htp_kparams_solve_mmnx_glu(sess, tmp.inputs[0], tmp.inputs[1], tmp.inputs[2], tmp.outputs[0], glu_op, kp, scale_size, has_norm)) {
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>()));
+ kp->scale_mask = scale_mask;
+ kp->scale_mode = scale_mode;
+ kp->norm_w_idx = norm_w_idx;
+ kp->norm_eps = norm_eps;
+ return true;
}
+
+ return false;
+}
+
+static bool htp_kparams_solve_ssm_gdn_node(
+ const struct ggml_hexagon_session * sess,
+ htp_opnode & tmp
+) {
if (tmp.opcode == HTP_OP_SSM_CONV) {
auto * kp = tmp.kparams<htp_ssm_conv_kernel_params>();
- const uint32_t silu = kp->silu;
+ const uint32_t silu_flag = kp->flags & HTP_SSM_CONV_FLAG_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);
+ ok = htp_kparams_solve_ssm_conv_token_major(sess, tmp.inputs[0], tmp.inputs[1], 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);
+ ok = htp_kparams_solve_ssm_conv(sess, tmp.inputs[0], tmp.inputs[1], tmp.dst(), kp);
}
- kp->silu = silu;
- return commit(ok);
+ kp->flags |= silu_flag;
+ return 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) {
@@ -5970,7 +6109,33 @@ bool htp_kparams_solve(
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>()));
+ return htp_kparams_solve_gated_delta_net(sess, &op_view, dst_cache, tmp.kparams<htp_gdn_kernel_params>());
+ }
+
+ return false;
+}
+
+static bool htp_kparams_solve_binary_node(
+ const struct ggml_hexagon_session * sess,
+ htp_opnode & tmp,
+ bool * handled
+) {
+ *handled = true;
+ if (tmp.opcode == HTP_OP_MUL_ID) {
+ if (tmp.inputs.size() != 3 || tmp.outputs.size() != 1) {
+ return false;
+ }
+ return htp_kparams_solve_binary_impl(
+ sess, HTP_OP_MUL_ID, tmp.inputs[0], tmp.inputs[1], tmp.inputs[2], tmp.outputs[0],
+ tmp.kparams<htp_binary_kernel_params>(), tmp.params[0] != 0);
+ }
+ if (!tmp.node && tmp.opcode == HTP_OP_MUL) {
+ if (tmp.inputs.size() != 2 || tmp.outputs.size() != 1) {
+ return false;
+ }
+ return htp_kparams_solve_binary_impl(
+ sess, HTP_OP_MUL, tmp.inputs[0], tmp.inputs[1], nullptr, tmp.outputs[0],
+ tmp.kparams<htp_binary_kernel_params>(), false);
}
if (!tmp.fused.empty() &&
@@ -5979,8 +6144,103 @@ bool htp_kparams_solve(
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_binary_nx(sess, tmp, kp);
+ }
+ if (tmp.opcode == HTP_OP_MUL && kp->kernel_type == HTP_BINARY_KERNEL_SCALAR &&
+ tmp.inputs.size() == 3 && tmp.outputs.size() == 1) {
+ const ggml_tensor * s0 = tmp.inputs[0];
+ const ggml_tensor * s1 = tmp.inputs[1];
+ const ggml_tensor * s2 = tmp.inputs[2];
+ const ggml_tensor * d = tmp.outputs[0];
+ if (s0->type != s1->type || s2->type != s1->type || d->type != s1->type) {
+ return false;
+ }
+ struct htp_binary_kernel_params solved;
+ if (!htp_kparams_solve_binary_impl(sess, HTP_OP_MUL, s0, s1, nullptr, d, &solved, false)) {
+ return false;
+ }
+ if (solved.kernel_type != HTP_BINARY_KERNEL_SCALAR || (solved.flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
+ return false;
+ }
+ const size_t vtcm_size = htp_session_vtcm_size(sess);
+ solved.src2_size = solved.src1_size;
+ solved.rows_per_buffer = 0;
+ if (solved.src1_size > 65536 || solved.src1_size + solved.src2_size > vtcm_size) {
+ return false;
+ }
+ struct htp_binary_vtcm_layout L;
+ htp_binary_vtcm_layout_build(&L, &solved, vtcm_size);
+ if (L.rows_per_buffer == 0 || L.total_bytes > vtcm_size) {
+ return false;
+ }
+ solved.rows_per_buffer = L.rows_per_buffer;
+ solved.vtcm_size = L.total_bytes;
+ *kp = solved;
+ return true;
+ }
+ }
+
+ *handled = false;
+ return false;
+}
+
+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);
+
+ 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 * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr;
+ const ggml_tensor * src3 = tmp.inputs.size() > 3 ? tmp.inputs[3] : nullptr;
+ const ggml_tensor * dst = tmp.dst();
+
+ auto commit = [&](bool ok) {
+ if (ok) {
+ memcpy(node.kernel_params, tmp.kernel_params, sizeof(node.kernel_params));
}
+ return ok;
+ };
+
+ if (htp_op_is_unary(tmp.opcode)) {
+ return commit(htp_kparams_solve_unary_node(sess, tmp));
+ }
+ 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>()));
+ }
+
+ switch (tmp.opcode) {
+ case HTP_OP_MUL_MAT:
+ case HTP_OP_MUL_MAT_ID:
+ case HTP_OP_MUL_MAT_ADD:
+ case HTP_OP_MUL_MAT_NX:
+ case HTP_OP_MUL_MAT_NX_GLU:
+ case HTP_OP_MUL_MAT_ID_NX:
+ return commit(htp_kparams_solve_mm_node(sess, tmp));
+ case HTP_OP_SSM_CONV:
+ case HTP_OP_GATED_DELTA_NET:
+ return commit(htp_kparams_solve_ssm_gdn_node(sess, tmp));
+ case HTP_OP_UPSCALE:
+ return commit(htp_kparams_solve_upscale(sess, src0, dst, tmp.kparams<htp_upscale_kernel_params>()));
+ case 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>()));
+ case HTP_OP_DSV4_HC_POST:
+ return commit(htp_kparams_solve_dsv4_hc_post_impl(sess, src0, src1, src2, src3, dst, tmp.kparams<htp_dsv4_hc_post_kernel_params>()));
+ case HTP_OP_LIGHTNING_INDEXER:
+ return commit(htp_kparams_solve_lightning_indexer_impl(sess, src0, src1, src2, src3, dst, tmp.kparams<htp_lid_kernel_params>()));
+ case HTP_OP_GET_ROWS:
+ return commit(htp_kparams_solve_repeat_get_rows(sess, src0, src1, dst, tmp.kparams<htp_get_rows_kernel_params>()));
+ default:
+ break;
+ }
+
+ bool binary_handled = false;
+ const bool binary_ok = htp_kparams_solve_binary_node(sess, tmp, &binary_handled);
+ if (binary_handled) {
+ return commit(binary_ok);
}
if (!tmp.fused.empty()) {
diff --git a/ggml/src/ggml-hexagon/htp-kparams.h b/ggml/src/ggml-hexagon/htp-kparams.h
index 1927c7d7b..58de391fd 100644
--- a/ggml/src/ggml-hexagon/htp-kparams.h
+++ b/ggml/src/ggml-hexagon/htp-kparams.h
@@ -80,90 +80,9 @@ bool htp_kparams_solve_allreduce(
struct htp_allreduce_kernel_params * kparams
);
-bool htp_kparams_solve_rms_norm_mul(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * dst,
- struct htp_unary_kernel_params * kparams
-);
-
-bool htp_kparams_solve_rms_norm_mul_add(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * src2,
- const struct ggml_tensor * dst,
- struct htp_unary_kernel_params * kparams
-);
-
-bool htp_kparams_solve_matmul_add(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * bias,
- const struct ggml_tensor * dst,
- struct htp_mm_kernel_params * kparams
-);
-
-bool htp_kparams_solve_mmnx(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * act,
- const struct ggml_tensor * dst,
- int32_t n_weights,
- struct htp_mm_kernel_params * kparams
-);
-
-bool htp_kparams_solve_mmnx_glu(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * w_gate,
- const struct ggml_tensor * w_up,
- const struct ggml_tensor * act,
- const struct ggml_tensor * dst,
- uint8_t glu_op,
- struct htp_mm_kernel_params * kparams
-);
-
-bool htp_kparams_solve_mmidnx(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * act,
- const struct ggml_tensor * dst,
- int32_t n_weights,
- struct htp_mm_kernel_params * kparams
-);
-
-bool htp_kparams_solve_repeat_get_rows(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * dst,
- struct htp_get_rows_kernel_params * kparams
-);
-
-bool htp_kparams_solve_unary_mul_glu(
- const struct ggml_hexagon_session * sess,
- uint32_t op,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * src1,
- const struct ggml_tensor * dst,
- struct htp_glu_kernel_params * kparams
-);
-
-bool htp_kparams_solve_upscale(
- const struct ggml_hexagon_session * sess,
- const struct ggml_tensor * src0,
- const struct ggml_tensor * dst,
- struct htp_upscale_kernel_params * kparams
-);
-
-static inline bool htp_kparams_solve_upscale(
- const struct ggml_hexagon_session * sess,
+struct htp_opnode htp_mm_make_scale_opnode(
const struct ggml_tensor * op,
- struct htp_upscale_kernel_params * kparams
-) {
- return htp_kparams_solve_upscale(sess, op->src[0], op, kparams);
-}
+ const struct ggml_tensor * scale
+);
#endif // HTP_KPARAMS_H
diff --git a/ggml/src/ggml-hexagon/htp-lower.cpp b/ggml/src/ggml-hexagon/htp-lower.cpp
index 372bccb26..ed4913813 100644
--- a/ggml/src/ggml-hexagon/htp-lower.cpp
+++ b/ggml/src/ggml-hexagon/htp-lower.cpp
@@ -23,7 +23,8 @@ bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride) {
bool htp_matmul_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst) {
size_t s1, sd;
- return (dst->op == GGML_OP_MUL_MAT || dst->op == GGML_OP_ADD) &&
+ return (dst->op == GGML_OP_MUL_MAT || dst->op == GGML_OP_ADD ||
+ dst->op == GGML_OP_GLU || dst->op == GGML_OP_MUL) &&
src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] * src1->ne[3] > 1 &&
src1->nb[0] == ggml_type_size(src1->type) && htp_rows_stride(src1->ne, src1->nb, &s1) &&
dst->nb[0] == ggml_type_size(dst->type) && htp_rows_stride(dst->ne, dst->nb, &sd);
@@ -427,26 +428,16 @@ void htp_lightning_indexer_collapse_tensors(
}
}
-void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch) {
- const uint32_t n_hvx = htp_session_n_hvx(sess);
- const size_t n_in = node.inputs.size();
- const size_t n_out = node.outputs.size();
-
- ggml_tensor in_mat[HTP_OP_MAX_INPUTS] = {};
- ggml_tensor out_mat[HTP_OP_MAX_OUTPUTS] = {};
- bool in_dirty[HTP_OP_MAX_INPUTS] = {};
- bool out_dirty[HTP_OP_MAX_OUTPUTS] = {};
-
- for (size_t i = 0; i < n_in; ++i) {
- if (node.inputs[i]) {
- in_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.inputs[i]);
- in_mat[i] = htp_tensor_lower_f16(node.inputs[i]);
- }
- }
- for (size_t i = 0; i < n_out; ++i) {
- out_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.outputs[i]);
- out_mat[i] = htp_tensor_lower_f16(node.outputs[i]);
- }
+static void htp_collapse_opnode_tensors(
+ uint32_t n_hvx,
+ const htp_opnode & node,
+ ggml_tensor (& in_mat)[HTP_OP_MAX_INPUTS],
+ ggml_tensor (& out_mat)[HTP_OP_MAX_OUTPUTS],
+ bool (& in_dirty)[HTP_OP_MAX_INPUTS],
+ bool (& out_dirty)[HTP_OP_MAX_OUTPUTS]
+) {
+ const size_t n_in = node.inputs.size();
+ const size_t n_out = node.outputs.size();
if (htp_op_is_unary(node.opcode) && htp_unary_is_elementwise(node.opcode)) {
if (n_in >= 1 && n_out >= 1 &&
@@ -497,8 +488,9 @@ void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & nod
}
}
} else if (node.opcode == HTP_OP_MUL_MAT_NX) {
- const size_t n_w = n_out;
- if (n_w > 0 && n_in == n_w + 1) {
+ const size_t n_w = n_out;
+ const size_t norm_extra = (node.kparams<htp_mm_kernel_params>()->norm_w_idx != 0) ? 1 : 0;
+ if (n_w > 0 && (n_in == n_w + 1 + norm_extra || n_in == 2 * n_w + 1 + norm_extra)) {
bool can_collapse = true;
for (size_t i = 0; i < n_w; ++i) {
if (!htp_matmul_can_collapse(&in_mat[i], &in_mat[n_w], &out_mat[i])) {
@@ -516,7 +508,8 @@ void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & nod
}
}
} else if (node.opcode == HTP_OP_MUL_MAT_NX_GLU) {
- if (n_in == 3 && n_out == 1 &&
+ const size_t norm_extra = (node.kparams<htp_mm_kernel_params>()->norm_w_idx != 0) ? 1 : 0;
+ if ((n_in == 3 + norm_extra || n_in == 5 + norm_extra) && n_out == 1 &&
htp_matmul_can_collapse(&in_mat[0], &in_mat[2], &out_mat[0]) &&
htp_matmul_can_collapse(&in_mat[1], &in_mat[2], &out_mat[0])) {
in_mat[2] = htp_tensor_collapse_rows(&in_mat[2]);
@@ -591,6 +584,30 @@ void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & nod
out_dirty[0] = true;
}
}
+}
+
+void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch) {
+ const uint32_t n_hvx = htp_session_n_hvx(sess);
+ const size_t n_in = node.inputs.size();
+ const size_t n_out = node.outputs.size();
+
+ ggml_tensor in_mat[HTP_OP_MAX_INPUTS] = {};
+ ggml_tensor out_mat[HTP_OP_MAX_OUTPUTS] = {};
+ bool in_dirty[HTP_OP_MAX_INPUTS] = {};
+ bool out_dirty[HTP_OP_MAX_OUTPUTS] = {};
+
+ for (size_t i = 0; i < n_in; ++i) {
+ if (node.inputs[i]) {
+ in_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.inputs[i]);
+ in_mat[i] = htp_tensor_lower_f16(node.inputs[i]);
+ }
+ }
+ for (size_t i = 0; i < n_out; ++i) {
+ out_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.outputs[i]);
+ out_mat[i] = htp_tensor_lower_f16(node.outputs[i]);
+ }
+
+ htp_collapse_opnode_tensors(n_hvx, node, in_mat, out_mat, in_dirty, out_dirty);
size_t n_scratch = 0;
auto commit_tensor = [&](const ggml_tensor & m) -> const ggml_tensor * {
@@ -714,13 +731,19 @@ static bool htp_lower_is_mm_opcode(uint32_t opcode) {
opcode == HTP_OP_MUL_MAT_NX_GLU || opcode == HTP_OP_MUL_MAT_ID_NX;
}
-static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node, const ggml_tensor * tensor) {
+static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node, const ggml_tensor * tensor, uint32_t * out_w_idx) {
+ if (out_w_idx) {
+ *out_w_idx = 0;
+ }
if (!htp_lower_is_mm_opcode(node.opcode)) {
return nullptr;
}
if (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX) {
for (size_t p = 0; p < node.outputs.size(); ++p) {
if (node.outputs[p] == tensor) {
+ if (out_w_idx) {
+ *out_w_idx = (uint32_t) p;
+ }
if (p == 0) {
return node.node;
}
@@ -732,10 +755,14 @@ static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node,
return node.node;
}
-static bool htp_lower_mm_blocks_output_f16(const ggml_tensor * orig_mm) {
+static bool htp_lower_mm_blocks_output_f16(const htp_opnode & owner, const ggml_tensor * orig_mm, uint32_t w_idx) {
if (!orig_mm) {
return false;
}
+ const auto * kp = owner.kparams<htp_mm_kernel_params>();
+ if (((kp->scale_mask >> w_idx) & 1u) == 0 && ggml_get_src_scale(orig_mm, 0) != nullptr) {
+ return true;
+ }
if (ggml_prec_get_acc(orig_mm) == GGML_PREC_F32) {
return true;
}
@@ -752,14 +779,21 @@ static bool htp_lower_respect_prec_hints(
const std::unordered_map<const ggml_tensor *, std::vector<size_t>> & root_users
) {
if (htp_lower_is_mm_opcode(owner.opcode)) {
- const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(owner, r);
- if (htp_lower_mm_blocks_output_f16(orig_mm)) {
+ uint32_t w_idx = 0;
+ const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(owner, r, &w_idx);
+ if (owner.opcode == HTP_OP_MUL_MAT_NX_GLU && orig_mm && owner.inputs.size() >= 2 && orig_mm->src[0] == owner.inputs[1]) {
+ w_idx = 1;
+ }
+ if (htp_lower_mm_blocks_output_f16(owner, orig_mm, w_idx)) {
return false;
}
if (owner.opcode == HTP_OP_MUL_MAT_NX_GLU) {
for (const ggml_tensor * f : owner.fused) {
- if (f && f->op == GGML_OP_MUL_MAT && htp_lower_mm_blocks_output_f16(f)) {
- return false;
+ if (f && f->op == GGML_OP_MUL_MAT) {
+ const uint32_t f_idx = (owner.inputs.size() >= 2 && f->src[0] == owner.inputs[1]) ? 1u : 0u;
+ if (htp_lower_mm_blocks_output_f16(owner, f, f_idx)) {
+ return false;
+ }
}
}
}
@@ -769,9 +803,12 @@ static bool htp_lower_respect_prec_hints(
auto oit = owner_idx.find(in_root);
if (oit != owner_idx.end()) {
const htp_opnode & node = nodes[oit->second];
- if (htp_lower_is_mm_opcode(node.opcode) &&
- htp_lower_mm_blocks_output_f16(htp_lower_orig_mm_for_output(node, in_root))) {
- return false;
+ if (htp_lower_is_mm_opcode(node.opcode)) {
+ uint32_t w_idx = 0;
+ const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(node, in_root, &w_idx);
+ if (htp_lower_mm_blocks_output_f16(node, orig_mm, w_idx)) {
+ return false;
+ }
}
}
}
@@ -1201,7 +1238,7 @@ void htp_lower_graph(const struct ggml_hexagon_session * sess, const struct ggml
}
for (const ggml_tensor * inp : tnode->inputs) {
const ggml_tensor * inp_root = inp ? htp_tensor_root(inp) : nullptr;
- if (inp_root && can_lower(inp_root) && is_selected_root(inp_root) && apply_root(inp_root)) {
+ if (inp_root && can_lower(inp_root) && apply_root(inp_root)) {
expanded = true;
}
}
diff --git a/ggml/src/ggml-hexagon/htp-opnode.cpp b/ggml/src/ggml-hexagon/htp-opnode.cpp
index f9b98cdbf..7ef383016 100644
--- a/ggml/src/ggml-hexagon/htp-opnode.cpp
+++ b/ggml/src/ggml-hexagon/htp-opnode.cpp
@@ -3,6 +3,7 @@
#include "htp/allreduce-ops.h"
#include "htp/argsort-ops.h"
#include "htp/binary-ops.h"
+#include "htp/conv2d-ops.h"
#include "htp/cumsum-ops.h"
#include "htp/diag-ops.h"
#include "htp/dsv4-hc-ops.h"
@@ -11,11 +12,13 @@
#include "htp/gated-delta-net-ops.h"
#include "htp/get-rows-ops.h"
#include "htp/glu-ops.h"
+#include "htp/im2col-ops.h"
#include "htp/lightning-indexer-ops.h"
#include "htp/matmul-ops.h"
#include "htp/pad-ops.h"
#include "htp/repeat-ops.h"
#include "htp/roll-ops.h"
+#include "htp/set-rows-ops.h"
#include "htp/softmax-ops.h"
#include "htp/solve-tri-ops.h"
#include "htp/ssm-conv.h"
@@ -48,6 +51,7 @@ std::string htp_opnode::name() const {
}
}
case HTP_OP_MUL_MAT_ID_NX: return "MUL_MAT_ID_NX";
+ case HTP_OP_MUL_ID: return "MUL_ID";
case HTP_OP_ADD:
case HTP_OP_SUB:
case HTP_OP_MUL:
@@ -64,6 +68,15 @@ std::string htp_opnode::name() const {
}
}
}
+ if (!node) {
+ switch (opcode) {
+ case HTP_OP_ADD: return "ADD";
+ case HTP_OP_SUB: return "SUB";
+ case HTP_OP_MUL: return "MUL";
+ case HTP_OP_DIV: return "DIV";
+ default: break;
+ }
+ }
break;
default:
break;
@@ -161,10 +174,11 @@ static std::string format_kernel_params(const htp_opnode & node) {
const auto * kparams = node.kparams<htp_mm_kernel_params>();
int32_t type = kparams->kernel_type;
if (htp_mm_kernel_is_hmx_w8a8(type)) {
- snprintf(str, max_size, "hmx-w8a8 nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ snprintf(str, max_size, "hmx-w8a8%s nhvx %u vtcm %u",
+ kparams->norm_w_idx ? "+norm" : "", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else {
const char * path = "unknown";
- if (type == HTP_MM_KERNEL_HMX_2D || type == HTP_MM_KERNEL_HMX_BATCHED) {
+ if (htp_mm_kernel_is_hmx_f16(type)) {
path = (kparams->tile_size > 0) ? "hmx-tiled" : "hmx-flat";
} else if (type == HTP_MM_KERNEL_HVX_F16_F16_VTCM || type == HTP_MM_KERNEL_HVX_F32_F32_VTCM ||
type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM) {
@@ -172,16 +186,17 @@ static std::string format_kernel_params(const htp_opnode & node) {
} else if (type == HTP_MM_KERNEL_HVX_QUANT_ROW || type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) {
path = "hvx-tiled";
}
- snprintf(str, max_size, "%s nhvx %u vtcm %u", path, (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ snprintf(str, max_size, "%s%s nhvx %u vtcm %u", path, kparams->norm_w_idx ? "+norm" : "",
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
}
} else if (node.opcode == HTP_OP_FLASH_ATTN_EXT) {
const auto * kparams = node.kparams<htp_fa_kernel_params>();
const char * path = "unknown";
int32_t type = kparams->kernel_type;
if (type == HTP_FA_KERNEL_HMX_F16) {
- path = kparams->u.hmx.pipeline ? "hmx-f16-pipe" : "hmx-f16-seq";
+ path = (kparams->flags & HTP_FA_FLAG_PIPELINE) ? "hmx-f16-pipe" : "hmx-f16-seq";
} else if (type == HTP_FA_KERNEL_HMX_W8A8) {
- path = kparams->u.hmx.pipeline ? "hmx-w8a8-pipe" : "hmx-w8a8-seq";
+ path = (kparams->flags & HTP_FA_FLAG_PIPELINE) ? "hmx-w8a8-pipe" : "hmx-w8a8-seq";
} else if (type == HTP_FA_KERNEL_HVX) {
path = "hvx";
}
@@ -194,11 +209,14 @@ static std::string format_kernel_params(const htp_opnode & node) {
snprintf(str, max_size, "idx %d count %d", (int) node.node->op_params[0], (int) node.dst()->ne[1]);
} else if ((node.opcode == HTP_OP_FENCE || node.opcode == HTP_OP_CPY_FENCE) && node.node) {
snprintf(str, max_size, "seq 0x%x", (uint32_t) node.node->op_params[0]);
- } else if (node.opcode == HTP_OP_ALLREDUCE && node.node) {
- snprintf(str, max_size, "seq 0x%x -> 0x%x", (uint32_t) node.node->op_params[0], (uint32_t) node.node->op_params[1]);
+ } else if ((node.opcode == HTP_OP_ALLREDUCE || node.opcode == HTP_OP_ALLREDUCE_ADD) && node.node) {
+ const auto * kparams = node.kparams<htp_allreduce_kernel_params>();
+ snprintf(str, max_size, "seq 0x%x -> 0x%x nhvx %u vtcm %u",
+ (uint32_t) node.node->op_params[0], (uint32_t) node.node->op_params[1],
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SSM_CONV) {
const auto * kparams = node.kparams<htp_ssm_conv_kernel_params>();
- const char * mode = kparams->token_major
+ const char * mode = (kparams->flags & HTP_SSM_CONV_FLAG_TOKEN_MAJOR)
? (kparams->n_t == 1 ? "tok-decode" : "tok-prefill")
: (kparams->n_t == 1 ? "decode" : "prefill");
snprintf(str, max_size, "%s nhvx %u vtcm %u", mode,
@@ -236,7 +254,7 @@ static std::string format_kernel_params(const htp_opnode & node) {
(unsigned int) kparams->n_hvx, (unsigned int) kparams->n_tokens_tile,
(unsigned int) kparams->kv_block, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_MUL || node.opcode == HTP_OP_ADD || node.opcode == HTP_OP_ADD_ID ||
- node.opcode == HTP_OP_SUB || node.opcode == HTP_OP_DIV) {
+ node.opcode == HTP_OP_MUL_ID || node.opcode == HTP_OP_SUB || node.opcode == HTP_OP_DIV) {
const auto * kparams = node.kparams<htp_binary_kernel_params>();
snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_ARGSORT || node.opcode == HTP_OP_TOP_K) {
@@ -273,16 +291,43 @@ static std::string format_kernel_params(const htp_opnode & node) {
snprintf(str, max_size, "%s nhvx %u tile %u x%u vtcm %u", ktype_str, (unsigned int) kparams->n_hvx, (unsigned int) kparams->tile_cols, (unsigned int) kparams->n_col_tiles, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_FILL) {
const auto * kparams = node.kparams<htp_fill_kernel_params>();
- snprintf(str, max_size, "%s nhvx %u", kparams->kernel_type == HTP_FILL_KERNEL_CONTIGUOUS ? "contig" : "strided", (unsigned int) kparams->n_hvx);
+ snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->kernel_type == HTP_FILL_KERNEL_CONTIGUOUS ? "contig" : "strided",
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_ROLL) {
const auto * kparams = node.kparams<htp_roll_kernel_params>();
- snprintf(str, max_size, "k%d nhvx %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx);
+ snprintf(str, max_size, "k%d nhvx %u vtcm %u", (int) kparams->kernel_type,
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_DIAG) {
const auto * kparams = node.kparams<htp_diag_kernel_params>();
snprintf(str, max_size, "nhvx %u chunk %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->chunk_elems, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_SOLVE_TRI) {
const auto * kparams = node.kparams<htp_solve_tri_kernel_params>();
- snprintf(str, max_size, "%s nhvx %u", kparams->batched ? "batched" : "chunked", (unsigned int) kparams->n_hvx);
+ snprintf(str, max_size, "%s nhvx %u vtcm %u", (kparams->flags & HTP_SOLVE_TRI_FLAG_BATCHED) ? "batched" : "chunked",
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ } else if (node.opcode == HTP_OP_SUM_ROWS || node.opcode == HTP_OP_SUM || node.opcode == HTP_OP_ARGMAX) {
+ const auto * kparams = node.kparams<htp_sum_rows_kernel_params>();
+ snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ } else if (node.opcode == HTP_OP_SET_ROWS) {
+ const auto * kparams = node.kparams<htp_set_rows_kernel_params>();
+ snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ } else if (node.opcode == HTP_OP_CONV_2D || node.opcode == HTP_OP_CONV_3D) {
+ const auto * kparams = node.kparams<htp_conv2d_kernel_params>();
+ snprintf(str, max_size, "%s nhvx %u vtcm %u",
+ kparams->kernel_type == HTP_CONV2D_KERNEL_HMX_WINDOW ? "window" : "tiled",
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ } else if (node.opcode == HTP_OP_CONV_2D_DW) {
+ const auto * kparams = node.kparams<htp_conv2d_dw_kernel_params>();
+ snprintf(str, max_size, "k%d nhvx %u vtcm %u", (int) kparams->kernel_type,
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ } else if (node.opcode == HTP_OP_IM2COL || node.opcode == HTP_OP_IM2COL_3D) {
+ const auto * kparams = node.kparams<htp_im2col_kernel_params>();
+ snprintf(str, max_size, "%s nhvx %u vtcm %u",
+ kparams->kernel_type == HTP_IM2COL_KERNEL_PATCHEMBED_DMA ? "patchembed" : "blocked",
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
+ } else if (node.opcode == HTP_OP_REPEAT) {
+ const auto * kparams = node.kparams<htp_repeat_kernel_params>();
+ snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->pipelined ? "pipe" : "tiled",
+ (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size);
} else if (node.opcode == HTP_OP_UPSCALE) {
const auto * kparams = node.kparams<htp_upscale_kernel_params>();
const char * ktype_str = "unknown";
@@ -290,7 +335,7 @@ static std::string format_kernel_params(const htp_opnode & node) {
case HTP_UPSCALE_KERNEL_NEAREST: ktype_str = "nearest"; break;
case HTP_UPSCALE_KERNEL_NEAREST_2X: ktype_str = "nearest-2x"; break;
case HTP_UPSCALE_KERNEL_NEAREST_4X: ktype_str = "nearest-4x"; break;
- case HTP_UPSCALE_KERNEL_BILINEAR: ktype_str = kparams->align_corners ? "bilinear-ac" : "bilinear"; break;
+ case HTP_UPSCALE_KERNEL_BILINEAR: ktype_str = (kparams->flags & HTP_UPSCALE_FLAG_ALIGN_CORNERS) ? "bilinear-ac" : "bilinear"; break;
case HTP_UPSCALE_KERNEL_BILINEAR_2X: ktype_str = "bilinear-2x"; break;
case HTP_UPSCALE_KERNEL_BILINEAR_AA: ktype_str = "bilinear-aa"; break;
case HTP_UPSCALE_KERNEL_BICUBIC: ktype_str = "bicubic"; break;
diff --git a/ggml/src/ggml-hexagon/htp-opnode.h b/ggml/src/ggml-hexagon/htp-opnode.h
index 904c9f5a9..cf4e5ef7e 100644
--- a/ggml/src/ggml-hexagon/htp-opnode.h
+++ b/ggml/src/ggml-hexagon/htp-opnode.h
@@ -91,6 +91,13 @@ struct htp_opnode {
// Build inputs (preserving optional nullptrs)
if (htp_is_hadamard(this->node)) {
this->inputs.push_back(this->node->src[1]);
+ } else if (this->node->op == GGML_OP_MUL_MAT) {
+ this->inputs.push_back(this->node->src[0]);
+ this->inputs.push_back(this->node->src[1]);
+ } else if (this->node->op == GGML_OP_MUL_MAT_ID) {
+ this->inputs.push_back(this->node->src[0]);
+ this->inputs.push_back(this->node->src[1]);
+ this->inputs.push_back(this->node->src[2]);
} else if (this->node->op != GGML_OP_FILL) {
int n_inputs = n_active_src(this->node);
for (int i = 0; i < n_inputs; i++) {
diff --git a/ggml/src/ggml-hexagon/htp-repack.cpp b/ggml/src/ggml-hexagon/htp-repack.cpp
index 57c3363ef..86ecef81d 100644
--- a/ggml/src/ggml-hexagon/htp-repack.cpp
+++ b/ggml/src/ggml-hexagon/htp-repack.cpp
@@ -1602,6 +1602,54 @@ static void repack_tiled_nvfp4(void * data, const ggml_tensor * t, size_t offset
}
}
+// --- F8_E4M3 (1024 B tile: 32x32 in 4-K-grouped vrmpy byte order, lossless) ---
+
+static void repack_f8_e4m3_to_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) {
+ repack_to_tiled_grid_32<uint8_t, 32>(t, data, offset, size, HTP_TENSOR_TILE_SIZE_F8_E4M3,
+ [](uint8_t * tile_dst, const uint8_t * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) {
+ for (int p = 0; p < 8; p++) {
+ const int64_t c_base = (int64_t) kt * 32 + p * 4;
+ for (int row = 0; row < 32; row++) {
+ const int64_t r = (int64_t) ct * 32 + row;
+ const uint8_t * r_ptr = (r < ne1) ? &src_slice[r * row_stride] : nullptr;
+ uint8_t * dst = tile_dst + p * 128 + row * 4;
+ if (r_ptr && c_base + 4 <= ne0) {
+ memcpy(dst, r_ptr + c_base, 4);
+ } else {
+ for (int j = 0; j < 4; j++) {
+ dst[j] = (r_ptr && c_base + j < ne0) ? r_ptr[c_base + j] : 0;
+ }
+ }
+ }
+ }
+ });
+}
+
+static void unpack_f8_e4m3_from_tiled(void * data, const ggml_tensor * t, size_t offset, size_t size) {
+ unpack_from_tiled_grid_32<uint8_t, 32>(data, t, offset, size, HTP_TENSOR_TILE_SIZE_F8_E4M3,
+ [](uint8_t * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) {
+ for (int p = 0; p < 8; p++) {
+ const int64_t c_base = (int64_t) kt * 32 + p * 4;
+ for (int row = 0; row < 32; row++) {
+ const int64_t r = (int64_t) ct * 32 + row;
+ if (r >= start_row && r < end_row) {
+ uint8_t * r_ptr = dst_slice + (r - start_row) * row_stride;
+ const uint8_t * src = tile_src + p * 128 + row * 4;
+ if (c_base + 4 <= ne0) {
+ memcpy(r_ptr + c_base, src, 4);
+ } else {
+ for (int j = 0; j < 4; j++) {
+ if (c_base + j < ne0) {
+ r_ptr[c_base + j] = src[j];
+ }
+ }
+ }
+ }
+ }
+ }
+ });
+}
+
// --- Top-level Repack / Unpack Dispatchers ---
void htp_repack_tensor_tiled(ggml_tensor * tensor, const void * data, size_t size) {
@@ -1631,6 +1679,9 @@ void htp_repack_tensor_tiled(ggml_tensor * tensor, const void * data, size_t siz
case GGML_TYPE_NVFP4:
repack_nvfp4_tiled(tensor, data, 0, size);
break;
+ case GGML_TYPE_F8_E4M3:
+ repack_f8_e4m3_to_tiled(tensor, data, 0, size);
+ break;
case GGML_TYPE_IQ2_XXS:
repack_iq2_xxs_tiled(tensor, data, 0, size);
break;
@@ -1698,6 +1749,9 @@ void htp_unpack_tensor_tiled(void * data, const ggml_tensor * tensor, size_t off
case GGML_TYPE_NVFP4:
repack_tiled_nvfp4(data, tensor, offset, size);
break;
+ case GGML_TYPE_F8_E4M3:
+ unpack_f8_e4m3_from_tiled(data, tensor, offset, size);
+ break;
case GGML_TYPE_IQ2_XXS:
repack_tiled_iq2_xxs(data, tensor, offset, size);
break;
diff --git a/ggml/src/ggml-hexagon/htp-repack.h b/ggml/src/ggml-hexagon/htp-repack.h
index fc1c0d7b5..47563bd42 100644
--- a/ggml/src/ggml-hexagon/htp-repack.h
+++ b/ggml/src/ggml-hexagon/htp-repack.h
@@ -17,7 +17,11 @@ static inline bool htp_is_tiled_weight_type(enum ggml_type type) {
type == GGML_TYPE_Q2_K || type == GGML_TYPE_Q3_K ||
type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K ||
type == GGML_TYPE_F16 || type == GGML_TYPE_F32 ||
- type == GGML_TYPE_BF16;
+ type == GGML_TYPE_BF16 || type == GGML_TYPE_F8_E4M3;
+}
+
+static inline bool htp_is_quantized_weight_type(enum ggml_type type) {
+ return ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3;
}
static inline bool htp_is_tiled_weight_tensor(const struct ggml_tensor * t) {
@@ -30,7 +34,7 @@ static inline bool htp_is_tiled_weight_tensor(const struct ggml_tensor * t) {
if (t->ne[0] < 32 || (t->ne[0] % 32 != 0) || t->ne[3] != 1) {
return false;
}
- if (!ggml_is_quantized(t->type)) {
+ if (!htp_is_quantized_weight_type(t->type)) {
return t->ne[1] > 1;
}
return true;
diff --git a/ggml/src/ggml-hexagon/htp/CMakeLists.txt b/ggml/src/ggml-hexagon/htp/CMakeLists.txt
index 409adae2b..2da061973 100644
--- a/ggml/src/ggml-hexagon/htp/CMakeLists.txt
+++ b/ggml/src/ggml-hexagon/htp/CMakeLists.txt
@@ -23,6 +23,9 @@ add_library(${HTP_LIB} SHARED
hmx-queue.c
htp-tensor.c
matmul-ops.c
+ matmul-hmx-w8a8.c
+ matmul-hmx-f16.c
+ matmul-hvx.c
flash-attn-ops.c
gated-delta-net-ops.c
binary-ops.c
diff --git a/ggml/src/ggml-hexagon/htp/allreduce-ops.c b/ggml/src/ggml-hexagon/htp/allreduce-ops.c
index 8af3b1e8f..6dc2b759e 100644
--- a/ggml/src/ggml-hexagon/htp/allreduce-ops.c
+++ b/ggml/src/ggml-hexagon/htp/allreduce-ops.c
@@ -21,7 +21,6 @@ struct htp_allreduce_context {
uint32_t n_dsts;
uint32_t nelem;
uint32_t ne0;
- uint32_t ne1;
uint32_t row_size_aligned;
uint32_t rank_elem_start;
uint32_t rank_nelem;
@@ -251,38 +250,6 @@ DEFINE_ALLREDUCE_THREAD_DMA_2D(add_f32, float, hvx_add_f32_aaa, 1, 0)
DEFINE_ALLREDUCE_THREAD_DMA_2D(add_bcast_f16, __fp16, hvx_add_f16_aaa, 1, 1)
DEFINE_ALLREDUCE_THREAD_DMA_2D(add_bcast_f32, float, hvx_add_f32_aaa, 1, 1)
-static int validate_allreduce(
- struct htp_ops_context * octx,
- const struct htp_allreduce_kernel_params * kparams,
- uint32_t n_ranks
-) {
- if (kparams->n_hvx == 0 || (uint32_t) kparams->n_hvx > octx->ctx->n_hvx) {
- return HTP_STATUS_INVAL_PARAMS;
- }
- octx->n_hvx = (uint32_t) kparams->n_hvx;
-
- if (kparams->vtcm_size_per_hvx <= 0 || kparams->vtcm_size <= 0) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
- const bool has_add = (octx->op == HTP_OP_ALLREDUCE_ADD);
- const size_t n_vtcm_buffers = htp_allreduce_vtcm_buffer_count(
- n_ranks, octx->n_hvx, has_add, kparams->is_row_bcast != 0);
- const size_t vtcm_size = n_vtcm_buffers * (size_t) kparams->vtcm_size_per_hvx;
- if (vtcm_size != (size_t) kparams->vtcm_size) {
- return HTP_STATUS_INVAL_PARAMS;
- }
- if (vtcm_size > octx->ctx->vtcm_size) {
- return HTP_STATUS_VTCM_TOO_SMALL;
- }
-
- if (octx->dst->type != HTP_TYPE_F16 && octx->dst->type != HTP_TYPE_F32) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- return HTP_STATUS_OK;
-}
-
int op_allreduce(struct htp_ops_context * octx) {
if (octx->ctx->mdev.count > 1 && octx->ctx->mdev.idx > 0) {
return HTP_STATUS_OK;
@@ -294,28 +261,24 @@ int op_allreduce(struct htp_ops_context * octx) {
const uint32_t rank = (uint32_t) kparams->rank;
const uint32_t n_ranks = (uint32_t) kparams->n_ranks;
- if (n_ranks < 2 || n_ranks > HTP_ALLREDUCE_MAX_RANKS || rank >= n_ranks) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
const uint32_t fence_seq_entry = (uint32_t) octx->op_params[0];
const uint32_t fence_seq_exit = (uint32_t) octx->op_params[1];
const struct htp_tensor * my_sync = octx->src[n_ranks + rank];
atomic_uint * my_fence = (atomic_uint *) (uintptr_t) my_sync->data;
- const int status = validate_allreduce(octx, kparams, n_ranks);
- if (status != HTP_STATUS_OK) {
- if (status == HTP_STATUS_NO_SUPPORT) {
- FARF(ERROR, "ggml-hex: allreduce unsupported type %d : rank %u\n", dst->type, rank);
- }
- htp_fence_write(my_fence, fence_seq_exit, status);
- return status;
+ if (!htp_ops_context_set_n_hvx(octx, (uint32_t) kparams->n_hvx)) {
+ htp_fence_write(my_fence, fence_seq_exit, HTP_STATUS_INVAL_PARAMS);
+ return HTP_STATUS_INVAL_PARAMS;
+ }
+ if ((size_t) kparams->vtcm_size > octx->ctx->vtcm_size) {
+ htp_fence_write(my_fence, fence_seq_exit, HTP_STATUS_VTCM_TOO_SMALL);
+ return HTP_STATUS_VTCM_TOO_SMALL;
}
const bool has_add = (octx->op == HTP_OP_ALLREDUCE_ADD);
const uint32_t nelem = dst->ne[0] * dst->ne[1] * dst->ne[2] * dst->ne[3];
- const int32_t mode = kparams->mode;
+ const bool sharded_fanout = (kparams->flags & HTP_ALLREDUCE_FLAG_SHARDED_FANOUT) != 0;
// 1. Entry Barrier: Synchronize all ranks before reading
struct htp_thread_trace * tr0 = &octx->ctx->trace[0];
@@ -368,14 +331,13 @@ int op_allreduce(struct htp_ops_context * octx) {
actx.n_dsts = (uint32_t) kparams->n_dsts ? (uint32_t) kparams->n_dsts : n_ranks;
actx.nelem = nelem;
actx.ne0 = (uint32_t) kparams->ne0;
- actx.ne1 = (uint32_t) kparams->ne1;
actx.row_size_aligned = (uint32_t) kparams->row_size_aligned;
actx.rank_elem_start = (uint32_t) kparams->rank_elem_start;
actx.rank_nelem = (uint32_t) kparams->rank_nelem;
actx.elems_per_hvx = elems_per_hvx;
actx.block_elems = block_elems;
actx.vtcm_size_per_hvx = vtcm_size_per_hvx;
- actx.is_row_bcast = (kparams->is_row_bcast != 0);
+ actx.is_row_bcast = (kparams->flags & HTP_ALLREDUCE_FLAG_ROW_BCAST) != 0;
work_queue_func_t reduce_fun = NULL;
switch (kparams->kernel_type) {
@@ -388,7 +350,7 @@ int op_allreduce(struct htp_ops_context * octx) {
break;
case HTP_ALLREDUCE_KERNEL_DMA_2D:
if (has_add) {
- if (kparams->is_row_bcast) {
+ if (actx.is_row_bcast) {
reduce_fun = (dst->type == HTP_TYPE_F16) ? allreduce_thread_dma_2d_add_bcast_f16 : allreduce_thread_dma_2d_add_bcast_f32;
} else {
reduce_fun = (dst->type == HTP_TYPE_F16) ? allreduce_thread_dma_2d_add_f16 : allreduce_thread_dma_2d_add_f32;
@@ -430,7 +392,7 @@ int op_allreduce(struct htp_ops_context * octx) {
htp_trace_event_start(tr0, HTP_TRACE_EVT_FENCE, (uint16_t) fence_seq_exit);
// drain fan-out DMA writes before exit barrier
- if (mode == HTP_ALLREDUCE_SHARDED_FANOUT) {
+ if (sharded_fanout) {
asm volatile ("syncht" : : : "memory");
}
diff --git a/ggml/src/ggml-hexagon/htp/allreduce-ops.h b/ggml/src/ggml-hexagon/htp/allreduce-ops.h
index 1fb486cb6..89b7b44da 100644
--- a/ggml/src/ggml-hexagon/htp/allreduce-ops.h
+++ b/ggml/src/ggml-hexagon/htp/allreduce-ops.h
@@ -17,9 +17,9 @@ enum htp_allreduce_kernel_type {
HTP_ALLREDUCE_KERNEL_DMA_2D,
};
-enum htp_allreduce_mode {
- HTP_ALLREDUCE_FULL = 0, // all ranks reduce full tensor
- HTP_ALLREDUCE_SHARDED_FANOUT = 1, // each rank reduces 1/N shard and fans out to all buffers
+enum htp_allreduce_flags {
+ HTP_ALLREDUCE_FLAG_ROW_BCAST = (1u << 0),
+ HTP_ALLREDUCE_FLAG_SHARDED_FANOUT = (1u << 1), // each rank reduces 1/N shard and fans out to all buffers
};
static inline size_t htp_allreduce_vtcm_buffer_count(
@@ -33,6 +33,7 @@ static inline size_t htp_allreduce_vtcm_buffer_count(
struct htp_allreduce_kernel_params {
uint8_t kernel_type;
+ uint8_t flags; // bitmask of enum htp_allreduce_flags
int32_t rank;
int32_t n_ranks;
int32_t n_hvx;
@@ -41,13 +42,10 @@ struct htp_allreduce_kernel_params {
int32_t vtcm_size_per_hvx;
int32_t vtcm_size;
int32_t ne0;
- int32_t ne1;
int32_t row_size_aligned;
int32_t rank_elem_start;
int32_t rank_nelem;
int32_t n_dsts;
- int32_t is_row_bcast;
- int32_t mode; // enum htp_allreduce_mode: FULL or SHARDED_FANOUT
};
#if defined(__cplusplus)
diff --git a/ggml/src/ggml-hexagon/htp/argsort-ops.c b/ggml/src/ggml-hexagon/htp/argsort-ops.c
index d8560e5ae..218c8d271 100644
--- a/ggml/src/ggml-hexagon/htp/argsort-ops.c
+++ b/ggml/src/ggml-hexagon/htp/argsort-ops.c
@@ -1454,10 +1454,6 @@ static void htp_top_k_identity_job(const htp_thread_t * th, unsigned int n, unsi
}
static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) {
- if (octx->src[0]->type != HTP_TYPE_F32 && octx->src[0]->type != HTP_TYPE_F16) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
const struct htp_tensor * src0 = octx->src[0];
const struct htp_tensor * dst = octx->dst;
diff --git a/ggml/src/ggml-hexagon/htp/binary-ops.c b/ggml/src/ggml-hexagon/htp/binary-ops.c
index cb8d7b428..dfdcc04f1 100644
--- a/ggml/src/ggml-hexagon/htp/binary-ops.c
+++ b/ggml/src/ggml-hexagon/htp/binary-ops.c
@@ -28,7 +28,6 @@ struct htp_binary_context {
uint8_t * vtcm_base;
struct fastdiv_values src0_dim1_div; // ne01
- struct fastdiv_values src0_dim2_div; // ne02
struct fastdiv_values src0_dim12_div;// ne03
struct fastdiv_values src1_dim1_div; // ne11
@@ -479,6 +478,7 @@ DEFINE_BINARY_MIXED_OP(sub, BINARY_OP_SUB, _Pragma("unroll(2)"))
DEFINE_BINARY_MIXED_OP(mul, BINARY_OP_MUL, _Pragma("unroll(2)"))
DEFINE_BINARY_MIXED_OP(div, BINARY_OP_DIV, )
DEFINE_BINARY_MIXED_F16_F16_F16(binary_add_f16_f16_f16, BINARY_OP_ADD)
+DEFINE_BINARY_MIXED_F16_F16_F16(binary_mul_f16_f16_f16, BINARY_OP_MUL)
#define DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, TYPES) \
DEFINE_COMPUTE_SAME_SHAPE(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) \
@@ -699,6 +699,60 @@ DEFINE_COMPUTE_ADD_ID(f32_f16_f16, binary_add_f32_f16_f16, add_id_copy_f32_f
DEFINE_COMPUTE_ADD_ID(f32_f16_f32, binary_add_f32_f16_f32, add_id_copy_f32_f32)
DEFINE_COMPUTE_ADD_ID(f32_f32_f16, binary_add_f32_f32_f16, add_id_copy_f32_f16)
+#define DEFINE_COMPUTE_MUL_ID(NAME, MUL_FN, COPY_FN) \
+static void compute_mul_id_##NAME( \
+ uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, \
+ uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, \
+ uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00) { \
+ for (uint32_t r = 0; r < n_rows; r++) { \
+ const uint32_t r_i01 = i01 + r; \
+ const int32_t idx = src2_ids[i02 * ne01 + r_i01]; \
+ const uint8_t * r_src0 = src0 + r * src0_stride; \
+ uint8_t * r_dst = dst + r * dst_stride; \
+ if (idx < 0) { \
+ COPY_FN(r_dst, r_src0, ne00); \
+ continue; \
+ } \
+ const uint8_t * r_src1 = src1_data + idx * src1_stride; \
+ MUL_FN(r_dst, r_src0, r_src1, ne00); \
+ } \
+}
+
+DEFINE_COMPUTE_MUL_ID(f16_f16_f16, binary_mul_f16_f16_f16, add_id_copy_f16_f16)
+DEFINE_COMPUTE_MUL_ID(f32_f32_f32, hvx_mul_f32_aaa, add_id_copy_f32_f32)
+DEFINE_COMPUTE_MUL_ID(f16_f16_f32, binary_mul_f16_f16_f32, add_id_copy_f16_f32)
+DEFINE_COMPUTE_MUL_ID(f16_f32_f16, binary_mul_f16_f32_f16, add_id_copy_f16_f16)
+DEFINE_COMPUTE_MUL_ID(f16_f32_f32, binary_mul_f16_f32_f32, add_id_copy_f16_f32)
+DEFINE_COMPUTE_MUL_ID(f32_f16_f16, binary_mul_f32_f16_f16, add_id_copy_f32_f16)
+DEFINE_COMPUTE_MUL_ID(f32_f16_f32, binary_mul_f32_f16_f32, add_id_copy_f32_f32)
+DEFINE_COMPUTE_MUL_ID(f32_f32_f16, binary_mul_f32_f32_f16, add_id_copy_f32_f16)
+
+#define DEFINE_COMPUTE_MUL_ID_SCALAR(NAME, TYPE, MUL_FN, COPY_FN) \
+static void compute_mul_id_scalar_##NAME( \
+ uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, \
+ uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, \
+ uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00) { \
+ (void) src1_stride; \
+ const TYPE * table = (const TYPE *) src1_data; \
+ for (uint32_t r = 0; r < n_rows; r++) { \
+ const uint32_t r_i01 = i01 + r; \
+ const int32_t idx = src2_ids[i02 * ne01 + r_i01]; \
+ const uint8_t * r_src0 = src0 + r * src0_stride; \
+ uint8_t * r_dst = dst + r * dst_stride; \
+ if (idx < 0) { \
+ COPY_FN(r_dst, r_src0, ne00); \
+ continue; \
+ } \
+ MUL_FN(r_dst, r_src0, table[idx], ne00); \
+ } \
+}
+
+DEFINE_COMPUTE_MUL_ID_SCALAR(f16_f16_f16, _Float16, hvx_mul_scalar_f16_aa, add_id_copy_f16_f16)
+DEFINE_COMPUTE_MUL_ID_SCALAR(f16_f32_f16, float, binary_scalar_mul_f16_f16, add_id_copy_f16_f16)
+DEFINE_COMPUTE_MUL_ID_SCALAR(f16_f32_f32, float, binary_scalar_mul_f16_f32, add_id_copy_f16_f32)
+DEFINE_COMPUTE_MUL_ID_SCALAR(f32_f32_f16, float, binary_scalar_mul_f32_f16, add_id_copy_f32_f16)
+DEFINE_COMPUTE_MUL_ID_SCALAR(f32_f32_f32, float, hvx_mul_scalar_f32_aa, add_id_copy_f32_f32)
+
struct binary_io_pipe_state {
const struct htp_binary_context * bctx;
dma_addr_t src0_data;
@@ -1378,7 +1432,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
const uint32_t table_type_key = type_key == 0 ? 0 : (type_key | 2);
if (kparams->kernel_type == HTP_BINARY_KERNEL_CHUNKED) {
- const bool is_scalar = kparams->is_scalar;
+ const bool is_scalar = (kparams->flags & HTP_BINARY_FLAG_SCALAR) != 0;
compute_binary_chunked_t compute = NULL;
compute_binary_scalar_chunked_f32_t compute_scalar_f32 = NULL;
@@ -1707,6 +1761,35 @@ static int execute_op_binary(struct htp_ops_context * octx) {
}
}
break;
+ case HTP_BINARY_KERNEL_MUL_ID:
+ if (octx->op == HTP_OP_MUL_ID) {
+ worker_func = binary_thread_add_id;
+ switch (type_key) {
+ case 0: compute_func = (void *) compute_mul_id_f16_f16_f16; break;
+ case 1: compute_func = (void *) compute_mul_id_f16_f16_f32; break;
+ case 2: compute_func = (void *) compute_mul_id_f16_f32_f16; break;
+ case 3: compute_func = (void *) compute_mul_id_f16_f32_f32; break;
+ case 4: compute_func = (void *) compute_mul_id_f32_f16_f16; break;
+ case 5: compute_func = (void *) compute_mul_id_f32_f16_f32; break;
+ case 6: compute_func = (void *) compute_mul_id_f32_f32_f16; break;
+ case 7: compute_func = (void *) compute_mul_id_f32_f32_f32; break;
+ default: break;
+ }
+ }
+ break;
+ case HTP_BINARY_KERNEL_MUL_ID_SCALAR:
+ if (octx->op == HTP_OP_MUL_ID) {
+ worker_func = binary_thread_add_id;
+ switch (table_type_key) {
+ case 0: compute_func = (void *) compute_mul_id_scalar_f16_f16_f16; break;
+ case 2: compute_func = (void *) compute_mul_id_scalar_f16_f32_f16; break;
+ case 3: compute_func = (void *) compute_mul_id_scalar_f16_f32_f32; break;
+ case 6: compute_func = (void *) compute_mul_id_scalar_f32_f32_f16; break;
+ case 7: compute_func = (void *) compute_mul_id_scalar_f32_f32_f32; break;
+ default: break;
+ }
+ }
+ break;
default: break;
}
@@ -1717,7 +1800,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
dma_queue * dma_q = octx->ctx->dma[0];
uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src1);
if (kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST) {
- if (!kparams->src1_strided) {
+ if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1->ne[0] * src1_elem_size, 1);
} else {
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0]);
@@ -1725,7 +1808,7 @@ static int execute_op_binary(struct htp_ops_context * octx) {
} else if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR ||
kparams->kernel_type == HTP_BINARY_KERNEL_REPEAT ||
kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX) {
- if (!kparams->src1_strided) {
+ if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
const size_t src1_bytes = (size_t) src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3] * src1_elem_size;
dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1_bytes, 1);
if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR && octx->src[2] != NULL) {
@@ -1763,12 +1846,41 @@ static int execute_op_binary(struct htp_ops_context * octx) {
}
}
}
- } else if (kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID) {
+ } else if (kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID ||
+ kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID) {
const struct htp_tensor * src2 = octx->src[2];
uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2);
- dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
- kparams->src1_row_size_aligned, src1->nb[1],
- src1->ne[0] * src1_elem_size, src1->ne[1]);
+ if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
+ kparams->src1_row_size_aligned, src1->nb[1],
+ src1->ne[0] * src1_elem_size, src1->ne[1]);
+ } else {
+ for (uint32_t i11 = 0; i11 < src1->ne[1]; i11++) {
+ dma_addr_t src_addr = src1->data + i11 * src1->nb[1];
+ uint8_t * dst_ptr = vtcm_src1 + i11 * kparams->src1_row_size_aligned;
+ while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr),
+ src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0])) {
+ dma_queue_pop(dma_q);
+ }
+ }
+ }
+ const size_t src2_row_bytes = src2->ne[0] * sizeof(int32_t);
+ while (!dma_queue_push(dma_q, dma_make_data(vtcm_src2, src2->data),
+ src2_row_bytes, src2->nb[1],
+ src2_row_bytes, src2->ne[1])) {
+ dma_queue_pop(dma_q);
+ }
+ } else if (kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID_SCALAR) {
+ const struct htp_tensor * src2 = octx->src[2];
+ uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2);
+ if (!(kparams->flags & HTP_BINARY_FLAG_SRC1_STRIDED)) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
+ bctx.vtcm_layout.src1_size, 0,
+ src1->ne[0] * src1_elem_size, 1);
+ } else {
+ dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data),
+ src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0]);
+ }
const size_t src2_row_bytes = src2->ne[0] * sizeof(int32_t);
dma_queue_push(dma_q, dma_make_data(vtcm_src2, src2->data),
src2_row_bytes, src2->nb[1],
@@ -1793,24 +1905,27 @@ static int execute_op_binary(struct htp_ops_context * octx) {
bctx.src1_table_elem_size = table_type_key == 0 ? sizeof(_Float16) : sizeof(float);
bctx.src0_dim1_div = kparams->div_ne01;
- bctx.src0_dim2_div = kparams->div_ne02;
bctx.src0_dim12_div = kparams->div_ne012;
bctx.src1_dim1_div = kparams->div_ne11;
bctx.src1_dim2_div = kparams->div_ne12;
bctx.src1_dim3_div = kparams->div_ne13;
- bctx.split_at_ne01 = kparams->split_at_ne01;
- bctx.split_at_ne02 = kparams->split_at_ne02;
+ bctx.split_at_ne01 = (kparams->flags & HTP_BINARY_FLAG_SPLIT_NE01) != 0;
+ bctx.split_at_ne02 = (kparams->flags & HTP_BINARY_FLAG_SPLIT_NE02) != 0;
bctx.compute = compute_func;
if (kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST ||
kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR ||
kparams->kernel_type == HTP_BINARY_KERNEL_REPEAT ||
kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX ||
- kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID) {
+ kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID ||
+ kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID ||
+ kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID_SCALAR) {
dma_queue_flush(dma_q);
- if ((kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST || kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR) &&
+ if ((kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST ||
+ kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR ||
+ kparams->kernel_type == HTP_BINARY_KERNEL_MUL_ID_SCALAR) &&
type_key != 0 && src1_type == HTP_TYPE_F16) {
binary_expand_f16_to_f32(vtcm_src1, (uint32_t) (src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3]));
}
diff --git a/ggml/src/ggml-hexagon/htp/binary-ops.h b/ggml/src/ggml-hexagon/htp/binary-ops.h
index b6706db05..bc6a994c5 100644
--- a/ggml/src/ggml-hexagon/htp/binary-ops.h
+++ b/ggml/src/ggml-hexagon/htp/binary-ops.h
@@ -15,24 +15,28 @@ enum htp_binary_kernel_type {
HTP_BINARY_KERNEL_ROW_BCAST,
HTP_BINARY_KERNEL_SCALAR,
HTP_BINARY_KERNEL_ADD_ID,
+ HTP_BINARY_KERNEL_MUL_ID,
+ HTP_BINARY_KERNEL_MUL_ID_SCALAR,
HTP_BINARY_KERNEL_COMPLEX,
HTP_BINARY_KERNEL_REPEAT,
HTP_BINARY_KERNEL_CHUNKED,
};
+enum htp_binary_flags {
+ HTP_BINARY_FLAG_SPLIT_NE01 = (1u << 0),
+ HTP_BINARY_FLAG_SPLIT_NE02 = (1u << 1),
+ HTP_BINARY_FLAG_SRC1_STRIDED = (1u << 2),
+ HTP_BINARY_FLAG_SCALAR = (1u << 3),
+};
+
struct htp_binary_kernel_params {
uint8_t kernel_type;
- uint8_t split_at_ne01;
- uint8_t split_at_ne02;
- uint8_t src1_strided;
-
+ uint8_t flags; // bitmask of enum htp_binary_flags
uint8_t n_srcs;
- uint8_t is_scalar;
uint8_t src0_elem_size;
- uint8_t src1_elem_size;
+ uint8_t src1_elem_size;
uint8_t dst_elem_size;
- uint8_t pad[3];
uint32_t n_hvx;
uint32_t rows_per_buffer;
@@ -46,10 +50,8 @@ struct htp_binary_kernel_params {
uint32_t vtcm_size;
uint32_t chunk_size;
- uint32_t chunk_bytes;
struct fastdiv_values div_ne01;
- struct fastdiv_values div_ne02;
struct fastdiv_values div_ne012;
struct fastdiv_values div_ne11;
@@ -127,19 +129,21 @@ static inline void htp_binary_vtcm_layout_build(
return;
}
+ const bool is_scalar = (kparams->flags & HTP_BINARY_FLAG_SCALAR) != 0;
+
L->src0_bytes_per_hvx = 2 * src0_chunk_bytes;
- L->src1_bytes_per_hvx = kparams->is_scalar ? 0 : (2 * (n_srcs - 1) * src1_chunk_bytes);
+ L->src1_bytes_per_hvx = is_scalar ? 0 : (2 * (n_srcs - 1) * src1_chunk_bytes);
L->dst_bytes_per_hvx = 2 * dst_chunk_bytes;
L->src0_spad_half_size = src0_chunk_bytes;
- L->src1_spad_half_size = kparams->is_scalar ? 0 : src1_chunk_bytes;
+ L->src1_spad_half_size = is_scalar ? 0 : src1_chunk_bytes;
L->dst_spad_half_size = dst_chunk_bytes;
L->rows_per_buffer = 1;
L->src1_size = 0;
const size_t src0_total = n_hvx * L->src0_bytes_per_hvx;
- const size_t src1_total = kparams->is_scalar ? 128 : (n_hvx * L->src1_bytes_per_hvx);
+ const size_t src1_total = is_scalar ? 128 : (n_hvx * L->src1_bytes_per_hvx);
const size_t dst_total = n_hvx * L->dst_bytes_per_hvx;
size_t off = 0;
@@ -234,7 +238,6 @@ static inline bool htp_binary_solve_chunked(
const uint32_t chunk_size = (target_chunk_elems < min_chunk_elems) ? min_chunk_elems
: (target_chunk_elems > max_chunk_elems) ? max_chunk_elems
: target_chunk_elems;
- const uint32_t chunk_bytes = hex_round_up(chunk_size * elem_size, 128);
const uint32_t total_chunks = (total_elems + chunk_size - 1) / chunk_size;
const uint32_t n_hvx = (total_chunks >= 2) ? (max_hvx < total_chunks ? max_hvx : total_chunks) : 1;
@@ -242,14 +245,16 @@ static inline bool htp_binary_solve_chunked(
kparams->n_hvx = n_hvx;
kparams->n_srcs = (uint8_t) n_srcs;
kparams->rows_per_buffer = 1;
- kparams->src1_row_size_aligned = is_scalar ? 0 : kparams->src0_row_size_aligned;
kparams->src0_elem_size = (uint8_t) src0_elem_size;
kparams->src1_elem_size = (uint8_t) src1_elem_size;
kparams->dst_elem_size = (uint8_t) dst_elem_size;
kparams->src1_size = 0;
kparams->chunk_size = chunk_size;
- kparams->chunk_bytes = chunk_bytes;
- kparams->is_scalar = is_scalar ? 1 : 0;
+ if (is_scalar) {
+ kparams->flags |= HTP_BINARY_FLAG_SCALAR;
+ } else {
+ kparams->flags &= ~HTP_BINARY_FLAG_SCALAR;
+ }
htp_binary_vtcm_layout_build(L, kparams, vtcm_size);
if (L->total_bytes == 0 || L->total_bytes > vtcm_size) {
diff --git a/ggml/src/ggml-hexagon/htp/concat-ops.c b/ggml/src/ggml-hexagon/htp/concat-ops.c
index 7be12c55b..6198155ab 100644
--- a/ggml/src/ggml-hexagon/htp/concat-ops.c
+++ b/ggml/src/ggml-hexagon/htp/concat-ops.c
@@ -779,9 +779,8 @@ static int concat_transposed(struct htp_ops_context * octx, const struct htp_con
rstart1 = range1.start;
nrows1 = range1.count;
}
- const struct fastdiv_values div_ne11 = init_fastdiv_values(src1->ne[1]);
- const struct fastdiv_values div_ne12_ne11 = init_fastdiv_values(src1->ne[1] * src1->ne[2]);
- concat_regular_side(octx, &view1, src1, rstart1, nrows1, &div_ne11, &div_ne12_ne11);
+ concat_regular_side(octx, &view1, src1, rstart1, nrows1,
+ &kparams->u.transposed.div_ne11, &kparams->u.transposed.div_ne12_ne11);
}
return HTP_STATUS_OK;
diff --git a/ggml/src/ggml-hexagon/htp/concat-ops.h b/ggml/src/ggml-hexagon/htp/concat-ops.h
index 228cd81bb..8c13b6456 100644
--- a/ggml/src/ggml-hexagon/htp/concat-ops.h
+++ b/ggml/src/ggml-hexagon/htp/concat-ops.h
@@ -25,6 +25,8 @@ struct htp_concat_regular_params {
struct htp_concat_transposed_params {
struct fastdiv_values div_ne2;
+ struct fastdiv_values div_ne11;
+ struct fastdiv_values div_ne12_ne11;
};
struct htp_concat_kernel_params {
diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-ops.c
index 1bcab08fd..7de19582f 100644
--- a/ggml/src/ggml-hexagon/htp/conv2d-ops.c
+++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.c
@@ -455,7 +455,7 @@ static uint32_t conv2d_hmx_issue_seg(const struct htp_ops_context * octx, const
const uint32_t n = fastdiv(row, &kp->tiled.div_oh);
const uint32_t oh = row - n * OH;
- if (kp->cwhn) {
+ if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
conv2d_hmx_stage_cwhn(octx, kp, dmaq, stage, n, oh, owt * 32, G);
} else {
conv2d_hmx_stage(octx, kp, g, dmaq, stage, n, oh, owt * 32, G);
@@ -813,7 +813,7 @@ static void conv2d_hmx_pack(const struct htp_conv2d_hmx_context * hc, const htp_
// Reuse output staging after unpack has drained its DMA.
HVX_Vector * gather_tmp = (HVX_Vector *) (thr + (size_t) n_stage * kp->stage_size);
- const HVX_Vector offsets = kp->cwhn || s0 <= 2 ? Q6_V_vzero() : hvx_vec_gather_offsets_w(s0 * sizeof(float));
+ const HVX_Vector offsets = (kp->flags & HTP_CONV2D_FLAG_CWHN) || s0 <= 2 ? Q6_V_vzero() : hvx_vec_gather_offsets_w(s0 * sizeof(float));
uint32_t ng[2] = { 0, 0 };
uint32_t tq = t0;
@@ -832,7 +832,7 @@ static void conv2d_hmx_pack(const struct htp_conv2d_hmx_context * hc, const htp_
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) t);
- if (kp->cwhn) {
+ if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
const uint32_t Wb = 32 * G * s0 + (KW - 1) * d0;
conv2d_hmx_cwhn_f16(stage16, stage, KH, kp->tiled.stage_row, Wb * Cin);
for (uint32_t g = 0; g < G; g++) {
@@ -1020,7 +1020,7 @@ static int conv2d_hmx_tiled(struct htp_ops_context * octx, const struct htp_conv
for (uint32_t rt0 = 0; rt0 < kp->n_row_tiles; rt0 += kp->rt_block) {
hc.rt0 = rt0;
hc.n_rt = MIN(kp->rt_block, kp->n_row_tiles - rt0);
- work_queue_run(octx->ctx->hvx_queue, kp->w_kmajor ? conv2d_hmx_wpack_kmajor_thread : conv2d_hmx_wpack_thread, &hc, nth);
+ work_queue_run(octx->ctx->hvx_queue, (kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) ? conv2d_hmx_wpack_kmajor_thread : conv2d_hmx_wpack_thread, &hc, nth);
conv2d_hmx_run_phase(&hc, 0, -1, nth);
@@ -1550,7 +1550,7 @@ static void conv2d_hmx_win_wpack_rows(const struct htp_conv2d_win_context * wc,
static void conv2d_hmx_win_wpack_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
const struct htp_conv2d_win_context * wc = (const struct htp_conv2d_win_context *) data;
- if (wc->kp->w_kmajor) {
+ if (wc->kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) {
conv2d_hmx_win_wpack_kmajor(wc, th, nth, ith);
} else {
conv2d_hmx_win_wpack_rows(wc, th, nth, ith);
@@ -1573,7 +1573,7 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d
const uint32_t p0 = octx->op_params[2];
const uint32_t p1 = octx->op_params[3];
const uint32_t span = kp->window.seg_b * 32;
- const bool cwhn = kp->cwhn;
+ const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0;
// rows of one image are contiguous when there is no column padding
const bool rows_contig = p0 == 0 && input->nb[1] == (size_t) IW * input->nb[0];
@@ -1693,7 +1693,7 @@ static uint32_t conv2d_hmx_win_stage_fold(const struct htp_conv2d_win_context *
// rows of one image are contiguous in DDR
const uint32_t nr = cont ? MIN(vr_b - vr, (uint32_t) (IH - ih)) : 1;
const dma_addr_t src = input->data + (size_t) n * input->nb[3] + (size_t) ih * input->nb[1];
- if (kp->cwhn) {
+ if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
// raw[vr - vr_a][iw][c]
const size_t sz = (size_t) nr * IW * Cin * sizeof(float);
dma_queue_push(dmaq, dma_make_data(raw + (size_t) (vr - vr_a) * IW * Cin, src), sz, sz, sz, 1);
@@ -1734,7 +1734,7 @@ static void conv2d_hmx_win_croutons(const struct htp_conv2d_win_context * wc, co
return;
}
- if (kp->cwhn) {
+ if (kp->flags & HTP_CONV2D_FLAG_CWHN) {
for (uint32_t cc = 0; cc < n_cc; cc++) {
const uint32_t nc = MIN(32, Cin - cc * 32);
const HVX_VectorPred qc = Q6_Q_vsetq2_R(nc * sizeof(float));
@@ -2040,7 +2040,7 @@ static void conv2d_hmx_win_pack(const struct htp_conv2d_win_context * wc, const
}
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) b);
- if (kp->window.fold && kp->cwhn) {
+ if (kp->window.fold && (kp->flags & HTP_CONV2D_FLAG_CWHN)) {
conv2d_hmx_win_croutons_fold_cwhn(wc, stages[si], act, b, nb, (ts + b) * 32);
} else if (kp->window.fold) {
conv2d_hmx_win_croutons_fold(wc, stages[si], act, b, nb, (ts + b) * 32);
@@ -2287,7 +2287,7 @@ static int conv2d_hmx_win(struct htp_ops_context * octx, const struct htp_conv2d
// small Cin: croutons are built by scattering the staged values into zeroed croutons
const uint32_t n_ch = octx->src[1]->ne[2] * (kp->window.fold ? KW : 1);
- if (!kp->cwhn && n_ch <= 2 * CONV2D_WIN_SCAT_MAX) {
+ if (!(kp->flags & HTP_CONV2D_FLAG_CWHN) && n_ch <= 2 * CONV2D_WIN_SCAT_MAX) {
wctx.n_scat = (n_ch + 1) / 2;
work_queue_run(octx->ctx->hvx_queue, conv2d_hmx_win_zero_thread, &wctx, kp->n_hvx);
}
@@ -2395,7 +2395,7 @@ static inline void conv2d_dw_get_slice(
uint32_t n;
uint32_t c = 0;
- if (kp->cwhn) {
+ if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) {
n = fastdiv(task, &kp->div_n_chunks);
chunk_idx = task - n * kp->n_chunks;
} else {
@@ -2428,7 +2428,7 @@ static inline void conv2d_dw_get_slice(
slice->ih_first = ih_first;
slice->c = c;
- if (kp->cwhn) {
+ if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) {
slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) ih_first * src1->nb[1];
slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh_start * dst->nb[1];
} else {
@@ -3201,7 +3201,7 @@ static void conv2d_dw_dma_thread(const htp_thread_t * th, unsigned int nth, unsi
dma_queue_flush(dma_q);
FARF(HIGH, "conv2d_dw-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n",
- ith, nth, kp->w, kp->h, kp->c, kp->n, kp->ow, kp->oh, kp->c, kp->n, first, last);
+ ith, nth, kp->w, kp->h, kp->c, dst->ne[3], kp->ow, kp->oh, kp->c, dst->ne[3], first, last);
}
int op_conv_2d_dw(struct htp_ops_context * octx) {
@@ -3223,7 +3223,8 @@ int op_conv_2d_dw(struct htp_ops_context * octx) {
const uint32_t max_dst_bytes = kp->oh_chunk * kp->row_dst_bytes + 128;
const struct htp_tensor * src0 = octx->src[0];
- const uint32_t elem_size = kp->is_f16 ? sizeof(__fp16) : sizeof(float);
+ const bool is_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0;
+ const uint32_t elem_size = is_f16 ? sizeof(__fp16) : sizeof(float);
const uint32_t w_size = src0->size;
struct htp_conv2d_dw_vtcm_layout layout;
@@ -3262,7 +3263,7 @@ int op_conv_2d_dw(struct htp_ops_context * octx) {
.kp = kp,
.layout = layout,
.w_vtcm = w_vtcm,
- .compute_fn = conv2d_dw_kernels[kp->kernel_type][kp->is_f16 ? 1 : 0],
+ .compute_fn = conv2d_dw_kernels[kp->kernel_type][is_f16 ? 1 : 0],
.task_start = task_start,
.task_count = task_count,
.tasks_per_hvx = tasks_per_hvx,
diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.h b/ggml/src/ggml-hexagon/htp/conv2d-ops.h
index 29dfa812f..054a9bd9f 100644
--- a/ggml/src/ggml-hexagon/htp/conv2d-ops.h
+++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.h
@@ -58,11 +58,15 @@ struct htp_conv2d_window_params {
struct fastdiv_values div_cs;
};
+enum htp_conv2d_flags {
+ HTP_CONV2D_FLAG_CWHN = (1u << 0),
+ HTP_CONV2D_FLAG_W_KMAJOR = (1u << 1),
+};
+
struct htp_conv2d_kernel_params {
uint8_t kernel_type;
+ uint8_t flags; // bitmask of enum htp_conv2d_flags
uint8_t n_hvx;
- uint8_t cwhn;
- uint8_t w_kmajor;
uint32_t total_rows;
uint32_t n_row_tiles;
@@ -96,18 +100,21 @@ enum htp_conv2d_dw_kernel_type {
HTP_CONV2D_DW_KERNEL_COUNT,
};
+enum htp_conv2d_dw_flags {
+ HTP_CONV2D_DW_FLAG_CWHN = (1u << 0),
+ HTP_CONV2D_DW_FLAG_F16 = (1u << 1),
+};
+
struct htp_conv2d_dw_kernel_params {
uint8_t kernel_type;
+ uint8_t flags; // bitmask of enum htp_conv2d_dw_flags
uint8_t n_hvx;
- uint8_t cwhn;
- uint8_t is_f16;
uint32_t total_tasks;
uint32_t vtcm_size;
uint32_t w;
uint32_t h;
uint32_t c;
- uint32_t n;
uint32_t kw;
uint32_t kh;
uint32_t ow;
diff --git a/ggml/src/ggml-hexagon/htp/diag-ops.c b/ggml/src/ggml-hexagon/htp/diag-ops.c
index 1f1aae281..a8f5a0ce6 100644
--- a/ggml/src/ggml-hexagon/htp/diag-ops.c
+++ b/ggml/src/ggml-hexagon/htp/diag-ops.c
@@ -245,12 +245,7 @@ static int op_diag_impl(struct htp_ops_context * octx, size_t elem_size, dma_pip
}
int op_diag(struct htp_ops_context * octx) {
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
-
- if (src0->type != dst->type) {
- return HTP_STATUS_NO_SUPPORT;
- }
+ const struct htp_tensor * dst = octx->dst;
switch (dst->type) {
case HTP_TYPE_F32:
diff --git a/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c b/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c
index 247f8bbc1..4190ae7f9 100644
--- a/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c
+++ b/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c
@@ -569,6 +569,10 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) {
const struct htp_dsv4_hc_pre_kernel_params * kparams =
(const struct htp_dsv4_hc_pre_kernel_params *) octx->kernel_params;
+ if (kparams->total_jobs == 0) {
+ return HTP_STATUS_OK;
+ }
+
const uint32_t n_hvx = kparams->n_hvx;
if (!htp_ops_context_set_n_hvx_div(octx, n_hvx, kparams->div_n_hvx)) {
return HTP_STATUS_INVAL_PARAMS;
@@ -1019,6 +1023,11 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) {
const struct htp_dsv4_hc_post_kernel_params * kparams =
(const struct htp_dsv4_hc_post_kernel_params *) octx->kernel_params;
+
+ if (kparams->total_jobs == 0) {
+ return HTP_STATUS_OK;
+ }
+
const struct htp_tensor * comb = kparams->has_comb ? octx->src[3] : NULL;
const uint32_t n_hvx = kparams->n_hvx;
diff --git a/ggml/src/ggml-hexagon/htp/flash-attn-ops.c b/ggml/src/ggml-hexagon/htp/flash-attn-ops.c
index bb0cd2c9e..a0ad618d3 100644
--- a/ggml/src/ggml-hexagon/htp/flash-attn-ops.c
+++ b/ggml/src/ggml-hexagon/htp/flash-attn-ops.c
@@ -30,7 +30,7 @@
#include "flash-attn-ops.h"
#include "hvx-fa-kernels.h"
-#include "hmx-fa-kernels.h"
+#include "hmx-fa-fp16-kernels.h"
#include "hmx-fa-w8a8-kernels.h"
// Must be multiple of 32
@@ -3382,9 +3382,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
factx.n_kv_blocks = kparams->n_kv_blocks;
factx.is_q_fp32 = (q->type == HTP_TYPE_F32);
factx.is_dst_fp32 = (dst->type == HTP_TYPE_F32);
- factx.pipeline = (kparams->u.hmx.pipeline != 0);
+ factx.pipeline = (kparams->flags & HTP_FA_FLAG_PIPELINE) != 0;
factx.is_w8a8 = (kparams->kernel_type == HTP_FA_KERNEL_HMX_W8A8);
- factx.mask_broadcast = (kparams->u.hmx.mask_broadcast != 0);
+ factx.mask_broadcast = (kparams->flags & HTP_FA_FLAG_MASK_BCAST) != 0;
if (mask) {
factx.src3_div2 = kparams->src3_div2;
factx.src3_div3 = kparams->src3_div3;
@@ -3425,7 +3425,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
if (kparams->flags & HTP_FA_FLAG_TEAM_SPLIT) {
// KV heads split across teams, Q-blocks split within a team
uint32_t n_teams, team_size;
- htp_fa_mdev_teams(n_kv_heads, mdev_count, kparams->head_split != 0, &n_teams, &team_size);
+ htp_fa_mdev_teams(n_kv_heads, mdev_count, (kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) != 0, &n_teams, &team_size);
const uint32_t team = mdev_idx / team_size;
const uint32_t member = mdev_idx - team * team_size;
@@ -3444,7 +3444,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) {
q_start_min = b0 * Br;
q_start_max = MIN((b0 + nblk) * Br, neq1);
- } else if (kparams->head_split && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
+ } else if ((kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
const uint32_t kv_per_core = n_kv_heads / mdev_count;
kv_head_min = mdev_idx * kv_per_core;
kv_head_max = kv_head_min + kv_per_core;
@@ -4097,19 +4097,8 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const struct htp_tensor * v = octx->src[2];
const struct htp_tensor * mask = octx->src[3];
- // Check support
- if ((q->type != HTP_TYPE_F16 && q->type != HTP_TYPE_F32) ||
- (k->type != HTP_TYPE_F16 && k->type != HTP_TYPE_Q8_0) ||
- (v->type != HTP_TYPE_F16 && v->type != HTP_TYPE_Q8_0)) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
const struct htp_fa_kernel_params * kparams = (const struct htp_fa_kernel_params *) octx->kernel_params;
- if (kparams->kernel_type == HTP_FA_KERNEL_UNSUPPORTED || kparams->n_kv_blocks > FA_MAX_KV_BLOCKS) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) {
return HTP_STATUS_INVAL_PARAMS;
}
@@ -4156,9 +4145,6 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
factx.m1 = kparams->m1;
const uint32_t n_head = q->ne[2];
- if (n_head > 512) {
- return HTP_STATUS_NO_SUPPORT;
- }
factx.ddr = (struct hvx_fa_ddr_spad *) fa_get_ddr_spad(octx, sizeof(struct hvx_fa_ddr_spad));
if (!factx.ddr) {
@@ -4187,7 +4173,7 @@ int op_flash_attn_ext(struct htp_ops_context * octx) {
const uint32_t n_kv_heads = k->ne[2];
// head range is contiguous in flat row space only when neq3 == 1
- if (kparams->head_split && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
+ if ((kparams->flags & HTP_FA_FLAG_HEAD_SPLIT) && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) {
const uint32_t G = kparams->G;
const uint32_t kv_per_core = n_kv_heads / mdev_count;
const uint32_t heads_per_core = kv_per_core * G;
diff --git a/ggml/src/ggml-hexagon/htp/flash-attn-ops.h b/ggml/src/ggml-hexagon/htp/flash-attn-ops.h
index 32f15dde2..64c07c63f 100644
--- a/ggml/src/ggml-hexagon/htp/flash-attn-ops.h
+++ b/ggml/src/ggml-hexagon/htp/flash-attn-ops.h
@@ -40,8 +40,12 @@ enum htp_fa_kernel_type {
HTP_FA_KERNEL_HMX_W8A8,
};
-// Multicore: gcd(n_kv_heads, N) teams own the KV heads, team members share the Q-blocks
-#define HTP_FA_FLAG_TEAM_SPLIT 0x01
+enum htp_fa_flags {
+ HTP_FA_FLAG_TEAM_SPLIT = (1u << 0), // gcd(n_kv_heads, N) teams own the KV heads, team members share the Q-blocks
+ HTP_FA_FLAG_HEAD_SPLIT = (1u << 1), // partition by KV heads in multicore (0 = token partition)
+ HTP_FA_FLAG_MASK_BCAST = (1u << 2), // mask broadcast across heads
+ HTP_FA_FLAG_PIPELINE = (1u << 3), // pipelined HMX execution
+};
static inline void htp_fa_mdev_teams(uint32_t n_kv_heads, uint32_t mdev_count, bool head_split,
uint32_t * n_teams, uint32_t * team_size) {
@@ -52,8 +56,7 @@ static inline void htp_fa_mdev_teams(uint32_t n_kv_heads, uint32_t mdev_count, b
struct htp_fa_kernel_params {
uint8_t kernel_type; // enum htp_fa_kernel_type
- uint8_t head_split; // 1 = partition by KV heads in multicore, 0 = token partition
- uint8_t flags; // HTP_FA_FLAG_*
+ uint8_t flags; // bitmask of enum htp_fa_flags
uint8_t n_hvx; // Number of threads to run
// Common parameters
@@ -82,8 +85,6 @@ struct htp_fa_kernel_params {
union {
struct {
uint32_t g_br;
- int32_t mask_broadcast;
- int32_t pipeline;
struct fastdiv_values div_G;
} hmx;
struct {
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 c468ffdbd..159a12a7e 100644
--- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
+++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
@@ -16,7 +16,7 @@
#include "htp-tensor.h"
#include "htp-vtcm.h"
#include "hmx-utils.h"
-#include "hmx-fa-kernels.h"
+#include "hmx-fa-fp16-kernels.h"
#include "hmx-queue.h"
#include "gated-delta-net-ops.h"
diff --git a/ggml/src/ggml-hexagon/htp/get-rows-ops.c b/ggml/src/ggml-hexagon/htp/get-rows-ops.c
index 7ab526b18..f85a78097 100644
--- a/ggml/src/ggml-hexagon/htp/get-rows-ops.c
+++ b/ggml/src/ggml-hexagon/htp/get-rows-ops.c
@@ -464,22 +464,6 @@ int op_get_rows(struct htp_ops_context * octx) {
const uint32_t ne00 = octx->src[0]->ne[0];
const uint32_t src0_row_size = htp_tensor_get_row_size(octx->src[0]->type, ne00);
const uint32_t dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00);
- if (src0_row_size == 0 || dst_row_size == 0) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- if (kparams->kernel_type == HTP_GET_ROWS_KERNEL_SAMETYPE) {
- if (octx->src[0]->type != octx->dst->type) {
- return HTP_STATUS_NO_SUPPORT;
- }
- } else if ((octx->dst->type != HTP_TYPE_F32 && octx->dst->type != HTP_TYPE_F16) ||
- (octx->src[0]->type == HTP_TYPE_F32 && octx->dst->type == HTP_TYPE_F32)) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- if (octx->src[1]->type != HTP_TYPE_I32 && octx->src[1]->type != HTP_TYPE_I64) {
- return HTP_STATUS_NO_SUPPORT;
- }
const uint32_t total_tasks = kparams->total_tasks;
diff --git a/ggml/src/ggml-hexagon/htp/glu-ops.h b/ggml/src/ggml-hexagon/htp/glu-ops.h
index 5e248f7d4..df503399e 100644
--- a/ggml/src/ggml-hexagon/htp/glu-ops.h
+++ b/ggml/src/ggml-hexagon/htp/glu-ops.h
@@ -58,12 +58,12 @@ static inline void htp_glu_vtcm_layout_build(
const size_t row_size_aligned = hex_round_up(dst_row_size, 128);
L->row_size_aligned = row_size_aligned;
- L->vtcm_row_per_hvx = vtcm_row_per_hvx;
L->block = vtcm_row_per_hvx >> 1;
+ L->vtcm_row_per_hvx = 2 * L->block;
- L->src0_bytes_per_hvx = row_size_aligned * vtcm_row_per_hvx;
- L->src1_bytes_per_hvx = row_size_aligned * vtcm_row_per_hvx;
- L->dst_bytes_per_hvx = row_size_aligned * vtcm_row_per_hvx;
+ L->src0_bytes_per_hvx = 2 * L->block * row_size_aligned;
+ L->src1_bytes_per_hvx = 2 * L->block * row_size_aligned;
+ L->dst_bytes_per_hvx = 2 * L->block * row_size_aligned;
size_t off = 0;
VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx);
diff --git a/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h b/ggml/src/ggml-hexagon/htp/hmx-fa-fp16-kernels.h
similarity index 100%
rename from ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h
rename to ggml/src/ggml-hexagon/htp/hmx-fa-fp16-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
index 3e398faf3..73e6e96cb 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h
@@ -6,7 +6,7 @@
#include <stdint.h>
#include "hex-fastdiv.h"
-#include "hmx-int-utils.h"
+#include "hmx-w8a8-utils.h"
#include "hmx-utils.h"
#include "hvx-utils.h"
@@ -406,7 +406,7 @@ static inline HVX_Vector hmx_fa_w8a8_k_pack4(const uint8_t * p, size_t stride) {
return Q6_V_lo_W(Q6_W_vshuff_VVR(p23, p01, -8));
}
-// Same math as int_hmx_rescale_pair_wb, using vadd(-1) instead of vcombine+vmpyacc to avoid Vdd pair spills.
+// Same math as hmx_w8a8_rescale_pair_wb, using vadd(-1) instead of vcombine+vmpyacc to avoid Vdd pair spills.
static inline void hmx_fa_w8a8_k_rescale_pair(
HVX_Vector v_q0,
HVX_Vector v_q1,
@@ -431,7 +431,7 @@ static inline void hmx_fa_w8a8_k_rescale_pair(
HVX_Vector v_W1 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_p23_hi, 1),
Q6_Vh_vasl_VhR(v_p23_lo, 1));
#endif
- int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
+ hmx_w8a8_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
}
// Q8_0 K -> S8 weight.b 32x32 tiles for one column tile (32 KV rows).
@@ -469,10 +469,10 @@ static __attribute__((noinline)) void hmx_fa_w8a8_k_prep_tile(
}
HVX_Vector v_max_sf, v_inv127_qf;
- int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+ hmx_w8a8_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
for (uint32_t kt = 0; kt < n_dot; ++kt) {
- tile_dst_all[kt * 8 + 7] = int_hmx_m_b4_from_f16(tile_dst_all[kt * 8 + 7], v_inv127_qf);
+ tile_dst_all[kt * 8 + 7] = hmx_w8a8_m_b4_from_f16(tile_dst_all[kt * 8 + 7], v_inv127_qf);
}
// Step 2: 32x32-byte vshuffvdd transpose of int8 quants and rescale in-place to weight.b
@@ -527,7 +527,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_k_prep_tile(
}
// Step 3: emit per-channel scales and HMX bias banks
- emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
}
// Decode one 4-row x 32-col W8A8 S tile (out_hi + out_lo) into 4 FP32 vectors.
@@ -657,7 +657,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
v_max_sc = hvx_vec_reduce_max_f16(v_max_sc);
HVX_Vector v_max_sf, v_inv127_qf;
- int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+ hmx_w8a8_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
// Pass 2: 4-row vshuff interleave + per-KV-row int8 scale multiply -> S8 weight.b
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
@@ -700,7 +700,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
}
// Pass 3: emit zp=0 per-channel scales and HMX bias banks
- emit_int_hmx_scales_and_bias_zp0(v_max_sf, 128.0f / 127.0f, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias_zp0(v_max_sf, 128.0f / 127.0f, v_l1_w, dst_scales, bias_out);
}
static inline void hmx_fa_w8a8_gemm_run(
diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h b/ggml/src/ggml-hexagon/htp/hmx-mm-f16-kernels.h
similarity index 74%
rename from ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h
rename to ggml/src/ggml-hexagon/htp/hmx-mm-f16-kernels.h
index 05eb3ebfc..688f550c0 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-mm-f16-kernels.h
@@ -34,6 +34,8 @@ struct tiled_dequantize_state {
uint32_t k_block;
size_t row_stride;
uint32_t weight_type;
+ const float * w_scale;
+ uint32_t w_scale_ct_stride;
};
static void dequantize_tiled_weight_to_fp16_task_q1_0(
@@ -458,25 +460,8 @@ static void dequantize_tiled_weight_to_fp16_task_q6_k(
}
}
-#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,
@@ -516,6 +501,124 @@ static void dequantize_tiled_weight_to_fp16_task_nvfp4(
}
}
+// NVFP4 with fused F32 weight scale folded into UE4M3 micro-scales before FP16 conversion
+static void dequantize_tiled_weight_to_fp16_task_nvfp4_scaled(
+ 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 uint32_t n_k_tiles = state->n_k_tiles;
+ const float * w_scale = state->w_scale;
+ const uint32_t w_scale_ct_stride = state->w_scale_ct_stride;
+ 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;
+
+ uint32_t ct = fastdiv(start_tile, &state->n_k_tiles_div);
+ uint32_t kt = start_tile - ct * n_k_tiles;
+
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ HVX_Vector v_d_raw = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF))));
+ HVX_VectorPair vp_d_f32 = hvx_vec_f16_to_f32(v_d_raw);
+ HVX_Vector v_ws = hvx_vmem(w_scale + (size_t) ct * w_scale_ct_stride);
+ HVX_Vector v_d0 = hvx_vec_mul_f32_f32(Q6_V_lo_W(vp_d_f32), v_ws);
+ HVX_Vector v_d1 = hvx_vec_mul_f32_f32(Q6_V_hi_W(vp_d_f32), v_ws);
+ HVX_Vector v_d = hvx_vec_f32_to_f16(v_d0, v_d1);
+ 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_q = Q6_W_vdeal_VVR(v_hi, v_lo, -2);
+ HVX_VectorPair vp_s = Q6_W_vshuff_VVR(Q6_V_hi_W(vp_q), Q6_V_lo_W(vp_q), -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;
+ if (++kt == n_k_tiles) {
+ kt = 0;
+ ++ct;
+ }
+ }
+}
+
+static void dequantize_tiled_weight_to_fp16_task_f8_e4m3(
+ 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_F8_E4M3);
+ 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;
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + i * 128));
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -4);
+ hvx_vmem(dst_ptr + (2 * i + 0) * 64) = f8_e4m3_to_f16(Q6_V_lo_W(vp_k));
+ hvx_vmem(dst_ptr + (2 * i + 1) * 64) = f8_e4m3_to_f16(Q6_V_hi_W(vp_k));
+ }
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ }
+}
+
+// F8_E4M3 with fused F32 weight scale applied in F32 before FP16 conversion to avoid HMX overflow
+static void dequantize_tiled_weight_to_fp16_task_f8_e4m3_scaled(
+ 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_F8_E4M3);
+ const uint32_t n_k_tiles = state->n_k_tiles;
+ const float * w_scale = state->w_scale;
+ const uint32_t w_scale_ct_stride = state->w_scale_ct_stride;
+ 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;
+
+ uint32_t ct = fastdiv(start_tile, &state->n_k_tiles_div);
+ uint32_t kt = start_tile - ct * n_k_tiles;
+
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t t = start_tile; t < end_tile; t++) {
+ HVX_Vector v_ws = hvx_vmem(w_scale + (size_t) ct * w_scale_ct_stride);
+
+ for (int i = 0; i < 8; i++) {
+ HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + i * 128));
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -4);
+
+ HVX_VectorPair vp0 = hvx_vec_f16_to_f32_shuff(f8_e4m3_to_f16(Q6_V_lo_W(vp_k)));
+ HVX_Vector q0e = Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(vp0), v_ws);
+ HVX_Vector q0o = Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(vp0), v_ws);
+ hvx_vmem(dst_ptr + (2 * i + 0) * 64) = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(q0o, q0e));
+
+ HVX_VectorPair vp1 = hvx_vec_f16_to_f32_shuff(f8_e4m3_to_f16(Q6_V_hi_W(vp_k)));
+ HVX_Vector q1e = Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(vp1), v_ws);
+ HVX_Vector q1o = Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(vp1), v_ws);
+ hvx_vmem(dst_ptr + (2 * i + 1) * 64) = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(q1o, q1e));
+ }
+ tile_src += tile_stride;
+ dst_ptr += HTP_MM_HMX_TILE_N_ELMS;
+ if (++kt == n_k_tiles) {
+ kt = 0;
+ ++ct;
+ }
+ }
+}
+
// 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,
@@ -911,42 +1014,14 @@ static void core_dot_chunk_fp16(__fp16 *restrict output, const __fp16 *restrict
}
}
-// 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);
-}
+// output : f16 -> f32 / f16
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);
+ return hvx_vec_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) {
@@ -954,7 +1029,7 @@ static inline HVX_Vector hmx_add_bias_to_f16_vec64_f32(HVX_Vector v_f16, const v
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);
+ return hvx_vec_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) {
@@ -962,39 +1037,108 @@ static inline HVX_Vector hmx_add_bias_to_f16_tail_f16(HVX_Vector v_f16, const vo
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);
+ return hvx_vec_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);
+ return hvx_vec_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)))
+static inline HVX_Vector hmx_scale_f16_vec64_f32(HVX_Vector v_f16, const float * restrict w_scale, size_t c, uint32_t c_mask) {
+ HVX_VectorPair vp = hvx_vec_f16_to_f32(v_f16);
+ HVX_Vector v0 = hvx_vec_mul_f32_f32(Q6_V_lo_W(vp), hvx_vmem(w_scale + (c & c_mask)));
+ HVX_Vector v1 = hvx_vec_mul_f32_f32(Q6_V_hi_W(vp), hvx_vmem(w_scale + ((c + 32) & c_mask)));
+ return hvx_vec_f32_to_f16_clamped(v0, v1);
+}
-#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))
+static inline HVX_Vector hmx_scale_f16_tail_f32(HVX_Vector v_f16, const float * restrict w_scale, size_t c, uint32_t c_mask, size_t valid_c) {
+ HVX_VectorPair vp = hvx_vec_f16_to_f32(v_f16);
+ HVX_Vector v0 = hvx_vec_mul_f32_f32(Q6_V_lo_W(vp), hvx_vmem(w_scale + (c & c_mask)));
+ HVX_Vector v1 = (valid_c > 32) ? hvx_vec_mul_f32_f32(Q6_V_hi_W(vp), hvx_vmem(w_scale + ((c + 32) & c_mask))) : Q6_V_vzero();
+ return hvx_vec_f32_to_f16_clamped(v0, v1);
+}
+
+static inline HVX_Vector hmx_scale_add_bias_to_f16_vec64_f16(
+ HVX_Vector v_f16, const void * restrict bias_row_base, size_t c, const float * restrict w_scale, uint32_t c_mask) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_VectorPair vp_bias = hvx_vec_f16_to_f32(hvx_vmemu((const __fp16 *) bias_row_base + c));
+ HVX_Vector v0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_lo_W(vp_dst), hvx_vmem(w_scale + (c & c_mask))), Q6_V_lo_W(vp_bias));
+ HVX_Vector v1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_hi_W(vp_dst), hvx_vmem(w_scale + ((c + 32) & c_mask))), Q6_V_hi_W(vp_bias));
+ return hvx_vec_f32_to_f16_clamped(v0, v1);
+}
-#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))
+static inline HVX_Vector hmx_scale_add_bias_to_f16_vec64_f32(
+ HVX_Vector v_f16, const void * restrict bias_row_base, size_t c, const float * restrict w_scale, uint32_t c_mask) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_lo_W(vp_dst), hvx_vmem(w_scale + (c & c_mask))), hmx_load_bias_f32_32_f32(bias_row_base, c));
+ HVX_Vector v1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_hi_W(vp_dst), hvx_vmem(w_scale + ((c + 32) & c_mask))), hmx_load_bias_f32_32_f32(bias_row_base, c + 32));
+ return hvx_vec_f32_to_f16_clamped(v0, v1);
+}
-#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))
+static inline HVX_Vector hmx_scale_add_bias_to_f16_tail_f16(
+ HVX_Vector v_f16, const void * restrict bias_row_base, size_t c, const float * restrict w_scale, uint32_t c_mask, size_t valid_c) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_lo_W(vp_dst), hvx_vmem(w_scale + (c & c_mask))), hmx_load_bias_f32_32_f16(bias_row_base, c));
+ HVX_Vector v1 = (valid_c > 32)
+ ? hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_hi_W(vp_dst), hvx_vmem(w_scale + ((c + 32) & c_mask))), hmx_load_bias_f32_32_f16(bias_row_base, c + 32))
+ : Q6_V_vzero();
+ return hvx_vec_f32_to_f16_clamped(v0, v1);
+}
-#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))
+static inline HVX_Vector hmx_scale_add_bias_to_f16_tail_f32(
+ HVX_Vector v_f16, const void * restrict bias_row_base, size_t c, const float * restrict w_scale, uint32_t c_mask, size_t valid_c) {
+ HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16);
+ HVX_Vector v0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_lo_W(vp_dst), hvx_vmem(w_scale + (c & c_mask))), hmx_load_bias_f32_32_f32(bias_row_base, c));
+ HVX_Vector v1 = (valid_c > 32)
+ ? hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_hi_W(vp_dst), hvx_vmem(w_scale + ((c + 32) & c_mask))), hmx_load_bias_f32_32_f32(bias_row_base, c + 32))
+ : Q6_V_vzero();
+ return hvx_vec_f32_to_f16_clamped(v0, v1);
+}
-#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_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_F32_SCALED_NONE(v_out, row_ptr, c) hvx_vec_mul_f32_f32((v_out), hvx_vmem(w_scale + ((c) & w_scale_c_mask)))
+#define HMX_FP16_ADD_BIAS_F32_SCALED_F16(v_out, row_ptr, c) hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32((v_out), hvx_vmem(w_scale + ((c) & w_scale_c_mask))), hmx_load_bias_f32_32_f16((row_ptr), (c)))
+#define HMX_FP16_ADD_BIAS_F32_SCALED_F32(v_out, row_ptr, c) hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32((v_out), hvx_vmem(w_scale + ((c) & w_scale_c_mask))), 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_64_SCALED_NONE(v_out, row_ptr, c) hmx_scale_f16_vec64_f32((v_out), w_scale, (c), w_scale_c_mask)
+#define HMX_FP16_ADD_BIAS_F16_64_SCALED_F16(v_out, row_ptr, c) hmx_scale_add_bias_to_f16_vec64_f16((v_out), (row_ptr), (c), w_scale, w_scale_c_mask)
+#define HMX_FP16_ADD_BIAS_F16_64_SCALED_F32(v_out, row_ptr, c) hmx_scale_add_bias_to_f16_vec64_f32((v_out), (row_ptr), (c), w_scale, w_scale_c_mask)
+
+#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_ADD_BIAS_F16_TAIL_SCALED_NONE(v_out, row_ptr, c, vc) hmx_scale_f16_tail_f32((v_out), w_scale, (c), w_scale_c_mask, (vc))
+#define HMX_FP16_ADD_BIAS_F16_TAIL_SCALED_F16(v_out, row_ptr, c, vc) hmx_scale_add_bias_to_f16_tail_f16((v_out), (row_ptr), (c), w_scale, w_scale_c_mask, (vc))
+#define HMX_FP16_ADD_BIAS_F16_TAIL_SCALED_F32(v_out, row_ptr, c, vc) hmx_scale_add_bias_to_f16_tail_f32((v_out), (row_ptr), (c), w_scale, w_scale_c_mask, (vc))
+
+#define HMX_FP16_BIAS_ROW0_none(bias, off) NULL
+#define HMX_FP16_BIAS_ROW0_scaled_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_ROW0_scaled_f16(bias, off) ((const uint8_t *) (bias) + (off))
+#define HMX_FP16_BIAS_ROW0_scaled_f32(bias, off) ((const uint8_t *) (bias) + (off))
+
+#define HMX_FP16_BIAS_ROW1_none(row0, rb) NULL
+#define HMX_FP16_BIAS_ROW1_scaled_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_ROW1_scaled_f16(row0, rb) ((row0) + (rb))
+#define HMX_FP16_BIAS_ROW1_scaled_f32(row0, rb) ((row0) + (rb))
+
+#define HMX_FP16_BIAS_STEP_none(ptr, step) (void) 0
+#define HMX_FP16_BIAS_STEP_scaled_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_FP16_BIAS_STEP_scaled_f16(ptr, step) ((ptr) += (step))
+#define HMX_FP16_BIAS_STEP_scaled_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))
@@ -1061,7 +1205,9 @@ static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp32_col_chu
uint32_t dst_stride, \
uint32_t bias_stride, \
uint32_t dst_cols, \
- size_t bias_elem_size \
+ size_t bias_elem_size, \
+ const float * restrict __attribute__((unused)) w_scale, \
+ uint32_t __attribute__((unused)) w_scale_c_mask \
) { \
float * restrict dst = (float *) dst_ptr; \
const size_t tile_row_stride = hmx_ceil_div(total_n_cols, \
@@ -1099,9 +1245,12 @@ static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp32_col_chu
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_FP16_TO_FP32_COL_CHUNK(none, HMX_FP16_ADD_BIAS_F32_NONE)
+DEFINE_FP16_TO_FP32_COL_CHUNK(scaled_none, HMX_FP16_ADD_BIAS_F32_SCALED_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_FP16_TO_FP32_COL_CHUNK(scaled_f16, HMX_FP16_ADD_BIAS_F32_SCALED_F16)
+DEFINE_FP16_TO_FP32_COL_CHUNK(scaled_f32, HMX_FP16_ADD_BIAS_F32_SCALED_F32)
#define HMX_FP16_TO_FP16_PAIR_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL) \
do { \
@@ -1173,7 +1322,9 @@ static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp16_col_chu
uint32_t dst_stride, \
uint32_t bias_stride, \
uint32_t dst_cols, \
- size_t bias_elem_size \
+ size_t bias_elem_size, \
+ const float * restrict __attribute__((unused)) w_scale, \
+ uint32_t __attribute__((unused)) w_scale_c_mask \
) { \
__fp16 * restrict dst = (__fp16 *) dst_ptr; \
const size_t tile_row_stride = hmx_ceil_div(total_n_cols, \
@@ -1210,9 +1361,12 @@ static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp16_col_chu
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)
+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(scaled_none, HMX_FP16_ADD_BIAS_F16_64_SCALED_NONE, HMX_FP16_ADD_BIAS_F16_TAIL_SCALED_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)
+DEFINE_FP16_TO_FP16_COL_CHUNK(scaled_f16, HMX_FP16_ADD_BIAS_F16_64_SCALED_F16, HMX_FP16_ADD_BIAS_F16_TAIL_SCALED_F16)
+DEFINE_FP16_TO_FP16_COL_CHUNK(scaled_f32, HMX_FP16_ADD_BIAS_F16_64_SCALED_F32, HMX_FP16_ADD_BIAS_F16_TAIL_SCALED_F32)
typedef void (*hmx_fp16_output_col_chunk_fn_t)(
void * restrict dst,
@@ -1225,32 +1379,55 @@ typedef void (*hmx_fp16_output_col_chunk_fn_t)(
uint32_t dst_stride,
uint32_t bias_stride,
uint32_t dst_cols,
- size_t bias_elem_size
+ size_t bias_elem_size,
+ const float * restrict w_scale,
+ uint32_t w_scale_c_mask
);
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
+ bool dst_aligned_nt,
+ const float * w_scale
) {
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) {
+ if (w_scale) {
+ return !bias ? transfer_output_chunk_fp16_to_fp16_col_chunk_scaled_none_nt
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp16_col_chunk_scaled_f16_nt
+ : transfer_output_chunk_fp16_to_fp16_col_chunk_scaled_f32_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);
}
+ if (w_scale) {
+ return !bias ? transfer_output_chunk_fp16_to_fp16_col_chunk_scaled_none_u
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp16_col_chunk_scaled_f16_u
+ : transfer_output_chunk_fp16_to_fp16_col_chunk_scaled_f32_u);
+ }
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) {
+ if (w_scale) {
+ return !bias ? transfer_output_chunk_fp16_to_fp32_col_chunk_scaled_none_nt
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp32_col_chunk_scaled_f16_nt
+ : transfer_output_chunk_fp16_to_fp32_col_chunk_scaled_f32_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);
}
+ if (w_scale) {
+ return !bias ? transfer_output_chunk_fp16_to_fp32_col_chunk_scaled_none_u
+ : (bias_f16 ? transfer_output_chunk_fp16_to_fp32_col_chunk_scaled_f16_u
+ : transfer_output_chunk_fp16_to_fp32_col_chunk_scaled_f32_u);
+ }
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);
@@ -1270,6 +1447,8 @@ typedef struct {
uint32_t dst_stride; // DDR row stride
uint32_t bias_stride; // DDR row stride for residual
uint32_t dst_cols; // Actual output columns
+ const float *w_scale;
+ uint32_t w_scale_c_mask;
} output_transfer_task_state_t;
// activations : fp32 -> fp16
@@ -1326,7 +1505,7 @@ static void transfer_activation_row_pair_fp32_to_fp16(
}
// 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
+// (src1). Same shape as the F16 Q-prep in hmx-fa-fp16-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.
@@ -1504,349 +1683,7 @@ static void transfer_activation_row_pair_f16_to_f16_col_chunk(
}
}
-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;
- }
-}
+// --- F16-HMX GLU Epilogue ---
static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp16(
const void * st_void,
@@ -2018,9 +1855,196 @@ static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp32(
}
}
+static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp16_scaled(
+ 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 float * ws_gate = st->vtcm_wt_scales_gate;
+ const float * ws_up = st->vtcm_wt_scales_up;
+ const uint32_t g_mask = st->w_scale_gate_c_mask;
+ const uint32_t u_mask = st->w_scale_up_c_mask;
+ 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 c_abs = c_first + c;
+ 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] = ws_gate ? hmx_scale_f16_vec64_f32(Q6_V_lo_W(gp0), ws_gate, c_abs, g_mask) : Q6_V_lo_W(gp0);
+ g_hf[1] = ws_gate ? hmx_scale_f16_vec64_f32(Q6_V_hi_W(gp0), ws_gate, c_abs, g_mask) : Q6_V_hi_W(gp0);
+ u_hf[0] = ws_up ? hmx_scale_f16_vec64_f32(Q6_V_lo_W(up0), ws_up, c_abs, u_mask) : Q6_V_lo_W(up0);
+ u_hf[1] = ws_up ? hmx_scale_f16_vec64_f32(Q6_V_hi_W(up0), ws_up, c_abs, u_mask) : 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] = ws_gate ? hmx_scale_f16_vec64_f32(Q6_V_lo_W(gp1), ws_gate, c_abs, g_mask) : Q6_V_lo_W(gp1);
+ g_hf[3] = ws_gate ? hmx_scale_f16_vec64_f32(Q6_V_hi_W(gp1), ws_gate, c_abs, g_mask) : Q6_V_hi_W(gp1);
+ u_hf[2] = ws_up ? hmx_scale_f16_vec64_f32(Q6_V_lo_W(up1), ws_up, c_abs, u_mask) : Q6_V_lo_W(up1);
+ u_hf[3] = ws_up ? hmx_scale_f16_vec64_f32(Q6_V_hi_W(up1), ws_up, c_abs, u_mask) : 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 c_abs = c_first + c;
+ 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] = ws_gate ? hmx_scale_f16_tail_f32(Q6_V_lo_W(gp0), ws_gate, c_abs, g_mask, valid_c) : Q6_V_lo_W(gp0);
+ g_hf[1] = ws_gate ? hmx_scale_f16_tail_f32(Q6_V_hi_W(gp0), ws_gate, c_abs, g_mask, valid_c) : Q6_V_hi_W(gp0);
+ u_hf[0] = ws_up ? hmx_scale_f16_tail_f32(Q6_V_lo_W(up0), ws_up, c_abs, u_mask, valid_c) : Q6_V_lo_W(up0);
+ u_hf[1] = ws_up ? hmx_scale_f16_tail_f32(Q6_V_hi_W(up0), ws_up, c_abs, u_mask, valid_c) : 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] = ws_gate ? hmx_scale_f16_tail_f32(Q6_V_lo_W(gp1), ws_gate, c_abs, g_mask, valid_c) : Q6_V_lo_W(gp1);
+ g_hf[3] = ws_gate ? hmx_scale_f16_tail_f32(Q6_V_hi_W(gp1), ws_gate, c_abs, g_mask, valid_c) : Q6_V_hi_W(gp1);
+ u_hf[2] = ws_up ? hmx_scale_f16_tail_f32(Q6_V_lo_W(up1), ws_up, c_abs, u_mask, valid_c) : Q6_V_lo_W(up1);
+ u_hf[3] = ws_up ? hmx_scale_f16_tail_f32(Q6_V_hi_W(up1), ws_up, c_abs, u_mask, valid_c) : 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_scaled(
+ 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 float * ws_gate = st->vtcm_wt_scales_gate;
+ const float * ws_up = st->vtcm_wt_scales_up;
+ const uint32_t g_mask = st->w_scale_gate_c_mask;
+ const uint32_t u_mask = st->w_scale_up_c_mask;
+ 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 c_abs = c_first + c;
+ 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);
+ const HVX_Vector v_wsg = ws_gate ? hvx_vmem(ws_gate + (c_abs & g_mask)) : hvx_vec_splat_f32(1.0f);
+ const HVX_Vector v_wsu = ws_up ? hvx_vmem(ws_up + (c_abs & u_mask)) : hvx_vec_splat_f32(1.0f);
+ g_q[0] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp0)), v_wsg);
+ g_q[1] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp0)), v_wsg);
+ u_q[0] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up0)), v_wsu);
+ u_q[1] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up0)), v_wsu);
+ 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] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp1)), v_wsg);
+ g_q[3] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp1)), v_wsg);
+ u_q[2] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up1)), v_wsu);
+ u_q[3] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up1)), v_wsu);
+ }
+ 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 c_abs = c_first + c;
+ 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);
+ const HVX_Vector v_wsg = ws_gate ? hvx_vmem(ws_gate + (c_abs & g_mask)) : hvx_vec_splat_f32(1.0f);
+ const HVX_Vector v_wsu = ws_up ? hvx_vmem(ws_up + (c_abs & u_mask)) : hvx_vec_splat_f32(1.0f);
+ g_q[0] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp0)), v_wsg);
+ g_q[1] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp0)), v_wsg);
+ u_q[0] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up0)), v_wsu);
+ u_q[1] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up0)), v_wsu);
+ 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] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp1)), v_wsg);
+ g_q[3] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp1)), v_wsg);
+ u_q[2] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up1)), v_wsu);
+ u_q[3] = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up1)), v_wsu);
+ }
+ 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,
+ bool has_epilogue_scale,
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,
@@ -2028,8 +2052,13 @@ static inline bool resolve_fp16_output_glu_fns(
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;
+ if (has_epilogue_scale) {
+ *col_chunk_fn = (dst_elem_size == sizeof(__fp16)) ? transfer_output_chunk_fp16_glu_fp16_scaled
+ : transfer_output_chunk_fp16_glu_fp32_scaled;
+ } else {
+ *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-w8a8-kernels.h
similarity index 75%
rename from ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h
rename to ggml/src/ggml-hexagon/htp/hmx-mm-w8a8-kernels.h
index 7329e8f6c..7a1ea9b62 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-mm-w8a8-kernels.h
@@ -1,6 +1,6 @@
// --- INT HMX W8A8 SM kernels ---
-#include "hmx-int-utils.h"
+#include "hmx-w8a8-utils.h"
typedef void (*int_rescale_superblock_fn_t)(
const uint8_t * restrict src_base,
@@ -16,6 +16,8 @@ typedef struct {
uint8_t * dst_wt_base;
uint8_t * dst_bias_base;
float * dst_scales_base;
+ const float * w_scale;
+ uint32_t w_scale_ct_stride;
const uint8_t * src_raw;
uint32_t n_col_tiles;
uint32_t n_k_tiles;
@@ -24,9 +26,11 @@ typedef struct {
uint32_t aligned_tile_size;
uint32_t raw_shift;
uint32_t n_tot_units;
- uint32_t n_units_per_task;
+ uint32_t n_units_base;
+ uint32_t n_units_rem;
uint32_t n_tasks;
struct fastdiv_values n_groups_div;
+ struct fastdiv_values n_groups_m1_div;
} int_weight_rescale_state_t;
static const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_x8_lut[128] = {
@@ -34,21 +38,241 @@ static const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_x8_lut[128] =
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(
+// Rudin-Shapiro-32 sign sequence (max |H_32(D)| = 8 vs 32) to prevent DC spikes on one-sided activations.
+static const uint32_t hmx_w8a8_fwht32_rs_s8[8] = {
+ 0xff010101u, 0x01ff0101u, 0xff010101u, 0xff01ffffu,
+ 0xff010101u, 0x01ff0101u, 0x01ffffffu, 0x01ff0101u,
+};
+
+static const uint32_t hmx_w8a8_fwht32_rs_xor[8] = {
+ 0xff000000u, 0x00ff0000u, 0xff000000u, 0xff00ffffu,
+ 0xff000000u, 0x00ff0000u, 0x00ffffffu, 0x00ff0000u,
+};
+
+static const uint32_t hmx_w8a8_fwht32_rs_xor_h_even[8] = {
+ 0x00000000u, 0xffff0000u, 0x00000000u, 0x0000ffffu,
+ 0x00000000u, 0xffff0000u, 0xffffffffu, 0xffff0000u,
+};
+
+static const uint32_t hmx_w8a8_fwht32_rs_xor_h_odd[8] = {
+ 0xffff0000u, 0x00000000u, 0xffff0000u, 0xffffffffu,
+ 0xffff0000u, 0x00000000u, 0x0000ffffu, 0x00000000u,
+};
+
+static const float __attribute__((aligned(VLEN))) hmx_w8a8_fwht32_rs_f32[32] = {
+ 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,
+ 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f,
+ 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,
+ -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,
+};
+
+static const uint16_t __attribute__((aligned(VLEN))) hmx_w8a8_fwht32_rs_f16_quarter[64] = {
+ 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u,
+ 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0xb400u, 0xb400u, 0x3400u, 0xb400u,
+ 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u,
+ 0xb400u, 0xb400u, 0xb400u, 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u,
+ 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u,
+ 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0xb400u, 0xb400u, 0x3400u, 0xb400u,
+ 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u,
+ 0xb400u, 0xb400u, 0xb400u, 0x3400u, 0x3400u, 0x3400u, 0xb400u, 0x3400u,
+};
+
+static __attribute__((always_inline)) inline void hmx_w8a8_fwht32_i16_butterfly_pair(HVX_Vector * a, HVX_Vector * b) {
+ HVX_Vector x = *a;
+ HVX_Vector y = *b;
+ *a = Q6_Vh_vadd_VhVh(x, y);
+ *b = Q6_Vh_vsub_VhVh(x, y);
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_fwht32_s12_from_i16(
+ HVX_Vector lo,
+ HVX_Vector hi,
+ HVX_Vector * restrict lo_out,
+ HVX_Vector * restrict hi_out) {
+ HVX_Vector s1 = Q6_Vh_vadd_VhVh(lo, hi);
+ HVX_Vector d1 = Q6_Vh_vsub_VhVh(lo, hi);
+ HVX_VectorPair p = Q6_W_vshuff_VVR(d1, s1, 2);
+ HVX_Vector s2 = Q6_Vh_vadd_VhVh(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ HVX_Vector d2 = Q6_Vh_vsub_VhVh(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ HVX_VectorPair q = Q6_W_vshuff_VVR(d2, s2, 2);
+ *lo_out = Q6_V_lo_W(q);
+ *hi_out = Q6_V_hi_W(q);
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_fwht32_s12_i16(
+ HVX_Vector v_w8,
+ HVX_Vector v_one_s8,
+ HVX_Vector * restrict lo_out,
+ HVX_Vector * restrict hi_out) {
+ HVX_VectorPair vp = Q6_Wh_vmpy_VbVb(v_w8, v_one_s8);
+ hmx_w8a8_fwht32_s12_from_i16(Q6_V_lo_W(vp), Q6_V_hi_W(vp), lo_out, hi_out);
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_fwht8_i16_inplace(HVX_Vector v[8]) {
+ #pragma unroll
+ for (int p = 0; p < 8; p += 2) {
+ hmx_w8a8_fwht32_i16_butterfly_pair(&v[p], &v[p + 1]);
+ }
+ #pragma unroll
+ for (int p = 0; p < 8; p += 4) {
+ hmx_w8a8_fwht32_i16_butterfly_pair(&v[p + 0], &v[p + 2]);
+ hmx_w8a8_fwht32_i16_butterfly_pair(&v[p + 1], &v[p + 3]);
+ }
+ #pragma unroll
+ for (int p = 0; p < 4; ++p) {
+ hmx_w8a8_fwht32_i16_butterfly_pair(&v[p], &v[p + 4]);
+ }
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_fwht32_s345_store(
+ HVX_Vector lo[8],
+ HVX_Vector hi[8],
+ HVX_Vector * restrict tile_dst,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w,
+ int shift) {
+ const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1);
+#if __HVX_ARCH__ >= 79
+ const HVX_Vector v_one_h = Q6_Vh_vsplat_R(1);
+#endif
+ hmx_w8a8_fwht8_i16_inplace(lo);
+ hmx_w8a8_fwht8_i16_inplace(hi);
+ #pragma unroll
+ for (int t = 0; t < 8; ++t) {
+#if __HVX_ARCH__ >= 79
+ // Alternate half-up (even t) and half-down (odd t) ties to avoid systematic rounding bias.
+ HVX_Vector v_hi = (t & 1) ? Q6_Vh_vsub_VhVh(hi[t], v_one_h) : hi[t];
+ HVX_Vector v_lo = (t & 1) ? Q6_Vh_vsub_VhVh(lo[t], v_one_h) : lo[t];
+ HVX_Vector v_W = Q6_Vb_vasr_VhVhR_rnd_sat(v_hi, v_lo, shift);
+#else
+ HVX_Vector v_hi = hi[t];
+ HVX_Vector v_lo = lo[t];
+ #pragma unroll
+ for (int s = 0; s < 8 - shift; ++s) {
+ v_hi = Q6_Vh_vadd_VhVh_sat(v_hi, v_hi);
+ v_lo = Q6_Vh_vadd_VhVh_sat(v_lo, v_lo);
+ }
+ HVX_Vector v_W = Q6_Vb_vround_VhVh_sat(v_hi, v_lo);
+#endif
+ tile_dst[t] = v_W;
+ *v_sum_w = Q6_Vw_vrmpyacc_VwVbVb(*v_sum_w, v_W, v_one_s8);
+ *v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(*v_l1_w, Q6_Vb_vabs_Vb(v_W), v_one_s8);
+ }
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_store_or_fwht32_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,
+ HVX_Vector fwht_lo[8],
+ HVX_Vector fwht_hi[8],
+ bool use_fwht) {
+ if (use_fwht) {
+ HVX_Vector v_s0 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_s8[2 * pair_idx + 0]);
+ HVX_Vector v_s1 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_s8[2 * pair_idx + 1]);
+ hmx_w8a8_fwht32_s12_i16(v_W0, v_s0, &fwht_lo[2 * pair_idx + 0], &fwht_hi[2 * pair_idx + 0]);
+ hmx_w8a8_fwht32_s12_i16(v_W1, v_s1, &fwht_lo[2 * pair_idx + 1], &fwht_hi[2 * pair_idx + 1]);
+ } else {
+ hmx_w8a8_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
+ }
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_rescale_pair_wb_ex(
+ 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 fwht_lo[8],
+ HVX_Vector fwht_hi[8],
+ bool use_fwht) {
+ if (!use_fwht) {
+ hmx_w8a8_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, pair_idx, v_sum_w, v_l1_w);
+ return;
+ }
+ // Keep 3 fractional bits (Q3 in [-1016, +1016]) through FWHT-32 to avoid double rounding.
+ HVX_Vector v_xor0 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor[2 * pair_idx + 0]);
+ HVX_Vector v_xor1 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor[2 * pair_idx + 1]);
+ HVX_Vector v_m0 = Q6_Vb_vsub_VbVb(Q6_V_vxor_VV(v_m_b4, v_xor0), v_xor0);
+ HVX_Vector v_m1 = Q6_Vb_vsub_VbVb(Q6_V_vxor_VV(v_m_b4, v_xor1), v_xor1);
+ HVX_Vector v_r8 = Q6_Vh_vsplat_R(8);
+ HVX_Vector v_r7 = Q6_Vh_vsplat_R(7);
+ HVX_VectorPair vp0 = Q6_Wh_vmpyacc_WhVbVb(Q6_W_vcombine_VV(v_r8, v_r8), v_q0, v_m0);
+ HVX_VectorPair vp1 = Q6_Wh_vmpyacc_WhVbVb(Q6_W_vcombine_VV(v_r7, v_r7), v_q1, v_m1);
+ hmx_w8a8_fwht32_s12_from_i16(
+ Q6_Vh_vasr_VhR(Q6_V_lo_W(vp0), 4), Q6_Vh_vasr_VhR(Q6_V_hi_W(vp0), 4),
+ &fwht_lo[2 * pair_idx + 0], &fwht_hi[2 * pair_idx + 0]);
+ hmx_w8a8_fwht32_s12_from_i16(
+ Q6_Vh_vasr_VhR(Q6_V_lo_W(vp1), 4), Q6_Vh_vasr_VhR(Q6_V_hi_W(vp1), 4),
+ &fwht_lo[2 * pair_idx + 1], &fwht_hi[2 * pair_idx + 1]);
+}
+
+static __attribute__((always_inline)) inline void hmx_w8a8_rescale_4bit_lut_step_ex(
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) {
-
+ HVX_Vector * restrict v_l1_w,
+ HVX_Vector fwht_lo[8],
+ HVX_Vector fwht_hi[8],
+ bool use_fwht) {
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);
+ hmx_w8a8_rescale_pair_wb_ex(v_q0, v_q1, v_m_b4, tile_dst, pair_idx, v_sum_w, v_l1_w, fwht_lo, fwht_hi, use_fwht);
+}
+
+#define DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(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, false); \
+} \
+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, false); \
+} \
+static __attribute__((noinline)) void rescale_##NAME##_fwht32_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, true); \
+} \
+static __attribute__((noinline)) void rescale_##NAME##_fwht32_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, true); \
}
#define DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(NAME) \
@@ -74,7 +298,7 @@ static __attribute__((noinline)) void rescale_##NAME##_weight_superblock_tail(
src_base, dst_wt, dst_scales, bias_out, tiles_per_group, dst_tile_stride); \
}
-static inline HVX_Vector int_hmx_scan_max_f16_scales(
+static inline HVX_Vector hmx_w8a8_scan_max_f16_scales(
const uint8_t * restrict src_base,
size_t tile_stride,
size_t scale_offset,
@@ -110,7 +334,7 @@ static inline void rescale_q4_0_tile_step(
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);
+ hmx_w8a8_rescale_pair_wb(v_lo, v_hi, v_m_b4, tile_dst, i, v_sum_w, v_l1_w);
}
}
@@ -131,21 +355,21 @@ static __attribute__((always_inline)) inline void rescale_q4_0_weight_superblock
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_sc = hmx_w8a8_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);
+ hmx_w8a8_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);
+ HVX_Vector v_m_b4 = hmx_w8a8_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);
+ HVX_Vector v_m_next = hmx_w8a8_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;
@@ -153,22 +377,153 @@ static __attribute__((always_inline)) inline void rescale_q4_0_weight_superblock
}
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);
+ hmx_w8a8_emit_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(
+static inline HVX_VectorPair hvx_fwht_i8_stage_pair(HVX_Vector v0, HVX_Vector v1, int32_t b) {
+ HVX_VectorPair p = Q6_W_vshuff_VVR(v1, v0, b);
+ HVX_Vector s = Q6_Vb_vadd_VbVb(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ HVX_Vector d = Q6_Vb_vsub_VbVb(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ return Q6_W_vshuff_VVR(d, s, b);
+}
+
+static inline void hvx_fwht32_i8_butterfly_pair(HVX_Vector * a, HVX_Vector * b) {
+ HVX_Vector x = *a;
+ HVX_Vector y = *b;
+ *a = Q6_Vb_vadd_VbVb(x, y);
+ *b = Q6_Vb_vsub_VbVb(x, y);
+}
+
+static inline void rescale_q4_0_tile_step_fwht32(
const uint8_t * restrict tile_src,
HVX_Vector * restrict tile_dst,
HVX_Vector v_m_b4,
+ HVX_Vector mask_0f,
+ HVX_Vector v_i8,
HVX_Vector * restrict v_sum_w,
HVX_Vector * restrict v_l1_w) {
+ // Stages 1-4 on sign-flipped Q4_0 nibbles [-8, +8] fit in int8 ([-128, +127] with sat at stage 4).
+ HVX_Vector v[8];
+
+ #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_0f), v_i8);
+ HVX_Vector v_hi = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(vq, 4), v_i8);
+ HVX_Vector v_m0 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor[2 * i + 0]);
+ HVX_Vector v_m1 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor[2 * i + 1]);
+ v_lo = Q6_Vb_vsub_VbVb(Q6_V_vxor_VV(v_lo, v_m0), v_m0);
+ v_hi = Q6_Vb_vsub_VbVb(Q6_V_vxor_VV(v_hi, v_m1), v_m1);
+
+ HVX_VectorPair p = hvx_fwht_i8_stage_pair(v_lo, v_hi, 1);
+ p = hvx_fwht_i8_stage_pair(Q6_V_lo_W(p), Q6_V_hi_W(p), 2);
+ v[2 * i + 0] = Q6_V_lo_W(p);
+ v[2 * i + 1] = Q6_V_hi_W(p);
+ }
+
+ #pragma unroll
+ for (int t = 0; t < 8; t += 2) {
+ hvx_fwht32_i8_butterfly_pair(&v[t], &v[t + 1]);
+ }
+ #pragma unroll
+ for (int t = 0; t < 8; t += 4) {
+ HVX_Vector a0 = v[t + 0], b0 = v[t + 2];
+ v[t + 0] = Q6_Vb_vadd_VbVb_sat(a0, b0);
+ v[t + 2] = Q6_Vb_vsub_VbVb_sat(a0, b0);
+ HVX_Vector a1 = v[t + 1], b1 = v[t + 3];
+ v[t + 1] = Q6_Vb_vadd_VbVb_sat(a1, b1);
+ v[t + 3] = Q6_Vb_vsub_VbVb_sat(a1, b1);
+ }
+
+ // Multiply by int8 scale first ([-16256, +16256]), then run stage 5 in exact int16 ([-32512, +32512]).
+ const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1);
+ #pragma unroll
+ for (int t = 0; t < 4; ++t) {
+ HVX_VectorPair vp_a = Q6_Wh_vmpy_VbVb(v[t], v_m_b4);
+ HVX_VectorPair vp_b = Q6_Wh_vmpy_VbVb(v[t + 4], v_m_b4);
+ HVX_Vector lo_s = Q6_Vh_vadd_VhVh(Q6_V_lo_W(vp_a), Q6_V_lo_W(vp_b));
+ HVX_Vector hi_s = Q6_Vh_vadd_VhVh(Q6_V_hi_W(vp_a), Q6_V_hi_W(vp_b));
+ HVX_Vector lo_d = Q6_Vh_vsub_VhVh(Q6_V_lo_W(vp_a), Q6_V_lo_W(vp_b));
+ HVX_Vector hi_d = Q6_Vh_vsub_VhVh(Q6_V_hi_W(vp_a), Q6_V_hi_W(vp_b));
+#if __HVX_ARCH__ >= 79
+ HVX_Vector v_Ws = Q6_Vb_vasr_VhVhR_rnd_sat(hi_s, lo_s, 6);
+ HVX_Vector v_Wd = Q6_Vb_vasr_VhVhR_rnd_sat(hi_d, lo_d, 6);
+#else
+ HVX_Vector hi_s2 = Q6_Vh_vadd_VhVh_sat(hi_s, hi_s);
+ HVX_Vector lo_s2 = Q6_Vh_vadd_VhVh_sat(lo_s, lo_s);
+ HVX_Vector hi_d2 = Q6_Vh_vadd_VhVh_sat(hi_d, hi_d);
+ HVX_Vector lo_d2 = Q6_Vh_vadd_VhVh_sat(lo_d, lo_d);
+ HVX_Vector v_Ws = Q6_Vb_vround_VhVh_sat(Q6_Vh_vadd_VhVh_sat(hi_s2, hi_s2), Q6_Vh_vadd_VhVh_sat(lo_s2, lo_s2));
+ HVX_Vector v_Wd = Q6_Vb_vround_VhVh_sat(Q6_Vh_vadd_VhVh_sat(hi_d2, hi_d2), Q6_Vh_vadd_VhVh_sat(lo_d2, lo_d2));
+#endif
+ tile_dst[t] = v_Ws;
+ tile_dst[t + 4] = v_Wd;
+ *v_sum_w = Q6_Vw_vrmpyacc_VwVbVb(Q6_Vw_vrmpyacc_VwVbVb(*v_sum_w, v_Ws, v_ones_s8), v_Wd, v_ones_s8);
+ *v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(Q6_Vw_vrmpyacc_VwVubVb(*v_l1_w, Q6_Vb_vabs_Vb(v_Ws), v_ones_s8), Q6_Vb_vabs_Vb(v_Wd), v_ones_s8);
+ }
+}
+
+static __attribute__((always_inline)) inline void rescale_q4_0_fwht32_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_0f = Q6_Vb_vsplat_R(0x0F);
+ const HVX_Vector v_i8 = Q6_Vb_vsplat_R(8);
+
+ HVX_Vector v_max_sc = hmx_w8a8_scan_max_f16_scales(src_base, tile_stride, 512, tiles_per_group);
+
+ HVX_Vector v_max_sf, v_inv127_qf;
+ hmx_w8a8_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 = hmx_w8a8_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 = hmx_w8a8_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 512), v_inv127_qf);
+ rescale_q4_0_tile_step_fwht32(tile_src, tile_dst, v_m_b4, mask_0f, v_i8, &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_fwht32(tile_src, tile_dst, v_m_b4, mask_0f, v_i8, &v_sum_w, &v_l1_w);
+
+ // Unnormalized H_32 satisfies H_32 * H_32^T = 32 * I; q_rot * m >> 6 gives scale (64/32) / 127 = 2/127.
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, 2.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q4_0_fwht32)
+
+static __attribute__((always_inline)) 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,
+ bool use_fwht) {
+
+ HVX_Vector fwht_lo[8], fwht_hi[8];
#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);
+ hmx_w8a8_rescale_pair_wb_ex(vq0, vq1, v_m_b4, tile_dst, i, v_sum_w, v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, v_sum_w, v_l1_w, 6);
}
}
@@ -178,53 +533,59 @@ static __attribute__((always_inline)) inline void rescale_q8_0_weight_superblock
float * restrict dst_scales,
HVX_Vector * restrict bias_out,
uint32_t tiles_per_group,
- size_t dst_tile_stride) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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_sc = hmx_w8a8_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);
+ hmx_w8a8_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);
+ HVX_Vector v_m_b4 = hmx_w8a8_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);
+ HVX_Vector v_m_next = hmx_w8a8_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, use_fwht);
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);
+ rescale_q8_0_tile_step(tile_src, tile_dst, v_m_b4, &v_sum_w, &v_l1_w, use_fwht);
- emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (32.0f / 127.0f) : (128.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q8_0)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q8_0)
-static inline void rescale_4bit_lut_tile_step(
+static __attribute__((always_inline)) 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) {
+ HVX_Vector * restrict v_l1_w,
+ bool use_fwht) {
+ HVX_Vector fwht_lo[8], fwht_hi[8];
#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);
+ hmx_w8a8_rescale_4bit_lut_step_ex(hvx_vmem(tile_src + i * 128), v_lut, v_m_b4, tile_dst, i, v_sum_w, v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, v_sum_w, v_l1_w, 6);
}
}
-static inline HVX_Vector int_hmx_mxfp4_e8m0_to_f32(HVX_Vector v_raw) {
+static inline HVX_Vector hmx_w8a8_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));
@@ -237,7 +598,8 @@ static __attribute__((always_inline)) inline void rescale_mxfp4_weight_superbloc
float * restrict dst_scales,
HVX_Vector * restrict bias_out,
uint32_t tiles_per_group,
- size_t dst_tile_stride) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0);
@@ -247,13 +609,13 @@ static __attribute__((always_inline)) inline void rescale_mxfp4_weight_superbloc
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)));
+ v_max0 = Q6_Vsf_vmax_VsfVsf(v_max0, hmx_w8a8_mxfp4_e8m0_to_f32(hvx_vmem(sc_ptr)));
+ v_max1 = Q6_Vsf_vmax_VsfVsf(v_max1, hmx_w8a8_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_inv127_qf = hmx_w8a8_inv127_from_max_f32(v_max_sf);
HVX_Vector v_sum_w = Q6_V_vzero();
HVX_Vector v_l1_w = Q6_V_vzero();
@@ -261,24 +623,26 @@ static __attribute__((always_inline)) inline void rescale_mxfp4_weight_superbloc
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);
+ HVX_Vector v_sc_qf = hvx_vec_f32_to_qf32(hmx_w8a8_mxfp4_e8m0_to_f32(hvx_vmem(tile_src + 512)));
+ HVX_Vector v_m_b4 = hmx_w8a8_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, use_fwht);
}
- emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (2.0f / 127.0f) : (8.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(mxfp4)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(mxfp4)
-static inline void rescale_q5_0_tile_step(
+static __attribute__((always_inline)) 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 * restrict v_l1_w,
+ bool use_fwht) {
HVX_Vector v_plane = hvx_vmem(tile_src + 512);
+ HVX_Vector fwht_lo[8], fwht_hi[8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
HVX_Vector vq = hvx_vmem(tile_src + i * 128);
@@ -286,7 +650,10 @@ static inline void rescale_q5_0_tile_step(
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);
+ hmx_w8a8_rescale_pair_wb_ex(v_lo, v_hi, v_m_b4, tile_dst, i, v_sum_w, v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, v_sum_w, v_l1_w, 6);
}
}
@@ -296,38 +663,39 @@ static __attribute__((always_inline)) inline void rescale_q5_0_weight_superblock
float * restrict dst_scales,
HVX_Vector * restrict bias_out,
uint32_t tiles_per_group,
- size_t dst_tile_stride) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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_sc = hmx_w8a8_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);
+ hmx_w8a8_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);
+ HVX_Vector v_m_b4 = hmx_w8a8_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);
+ HVX_Vector v_m_next = hmx_w8a8_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, use_fwht);
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);
+ rescale_q5_0_tile_step(tile_src, tile_dst, v_m_b4, mask_78, &v_sum_w, &v_l1_w, use_fwht);
- emit_int_hmx_scales_and_bias(v_max_sf, 16.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (4.0f / 127.0f) : (16.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q5_0)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q5_0)
static __attribute__((always_inline)) inline void rescale_iq4_nl_weight_superblock_impl(
const uint8_t * restrict src_base,
@@ -335,17 +703,18 @@ static __attribute__((always_inline)) inline void rescale_iq4_nl_weight_superblo
float * restrict dst_scales,
HVX_Vector * restrict bias_out,
uint32_t tiles_per_group,
- size_t dst_tile_stride) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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_sc = hmx_w8a8_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);
+ hmx_w8a8_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();
@@ -355,23 +724,24 @@ static __attribute__((always_inline)) inline void rescale_iq4_nl_weight_superblo
#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);
+ HVX_Vector v_m_b4 = hmx_w8a8_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, use_fwht);
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);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (32.0f / 127.0f) : (128.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(iq4_nl)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(iq4_nl)
-static inline void rescale_q1_0_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q1_0);
const uint32_t raw_tiles = tiles_per_group >> 2;
@@ -383,38 +753,45 @@ static inline void rescale_q1_0_weight_superblock_impl(
}
HVX_Vector v_max_sf, v_inv127_qf;
- int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+ hmx_w8a8_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
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_pos_m = hmx_w8a8_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);
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
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);
+ hmx_w8a8_store_or_fwht32_pair(tile_dst, i, v_W0, v_W1, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ // Binary weights need H_32 / 16 (shift 4) to avoid clipping after rotation.
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 4);
}
}
}
- emit_int_hmx_scales_and_bias(v_max_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (0.5f / 127.0f) : (1.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q1_0)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q1_0)
-static inline void rescale_q2_0_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_0);
const uint32_t raw_tiles = tiles_per_group >> 1;
@@ -428,36 +805,43 @@ static inline void rescale_q2_0_weight_superblock_impl(
}
HVX_Vector v_max_sf, v_inv127_qf;
- int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
+ hmx_w8a8_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf);
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);
+ HVX_Vector v_m_b4 = hmx_w8a8_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);
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
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);
+ hmx_w8a8_rescale_pair_wb_ex(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ // Q2_0 values are half-scale ([-32, +64]); shift 5 keeps +6 dB precision.
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 5);
}
}
}
- emit_int_hmx_scales_and_bias(v_max_sf, 4.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (0.5f / 127.0f) : (4.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q2_0)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q2_0)
-static inline void rescale_nvfp4_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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;
@@ -470,7 +854,7 @@ static inline void rescale_nvfp4_weight_superblock_impl(
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);
+ hmx_w8a8_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();
@@ -481,18 +865,119 @@ static inline void rescale_nvfp4_weight_superblock_impl(
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);
+ hmx_w8a8_m_b4_pair_from_f16(v_sc, v_inv127_qf, &v_m_b0, &v_m_b1);
- #pragma clang loop pipeline(disable) unroll(disable)
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
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);
+ hmx_w8a8_rescale_4bit_lut_step_ex(hvx_vmem(tile_src + i * 128), v_lut, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
}
}
- emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (2.0f / 127.0f) : (8.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(nvfp4)
+
+static __attribute__((always_inline)) inline void hmx_w8a8_f8_e4m3_vec_to_i16_pair(
+ HVX_Vector v_src,
+ HVX_Vector v_inv_sf,
+ HVX_Vector * restrict v_h02_out,
+ HVX_Vector * restrict v_h13_out) {
+
+ HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(v_src);
+ HVX_VectorPair vp_eo = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -2);
+
+ HVX_VectorPair vp02 = hvx_vec_f16_to_f32_shuff(f8_e4m3_to_f16(Q6_V_lo_W(vp_eo)));
+ HVX_Vector v_i0 = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(vp02), v_inv_sf));
+ HVX_Vector v_i2 = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(vp02), v_inv_sf));
+ *v_h02_out = Q6_Vh_vshuffe_VhVh(v_i2, v_i0);
+
+ HVX_VectorPair vp13 = hvx_vec_f16_to_f32_shuff(f8_e4m3_to_f16(Q6_V_hi_W(vp_eo)));
+ HVX_Vector v_i1 = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(vp13), v_inv_sf));
+ HVX_Vector v_i3 = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(vp13), v_inv_sf));
+ *v_h13_out = Q6_Vh_vshuffe_VhVh(v_i3, v_i1);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(nvfp4)
+
+static __attribute__((always_inline)) inline void rescale_f8_e4m3_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,
+ bool use_fwht) {
+
+ const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_F8_E4M3);
+ const HVX_Vector v_mask_7f = Q6_Vb_vsplat_R(NVFP4_UE4M3_MASK);
+ const HVX_Vector v_zero = Q6_V_vzero();
+
+ // F8_E4M3 magnitude is monotonic in (byte & 0x7F) once 0x7F NaN is zeroed.
+ HVX_Vector v_max_u8 = v_zero;
+ #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;
+ #pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ HVX_Vector v_abs = Q6_V_vand_VV(hvx_vmem(tile_src + i * 128), v_mask_7f);
+ HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VbVb(v_abs, v_mask_7f);
+ v_abs = Q6_V_vmux_QVV(q_nan, v_zero, v_abs);
+ v_max_u8 = Q6_Vub_vmax_VubVub(v_max_u8, v_abs);
+ }
+ }
+ v_max_u8 = Q6_Vub_vmax_VubVub(v_max_u8, Q6_Vuw_vlsr_VuwR(v_max_u8, 16));
+ v_max_u8 = Q6_Vub_vmax_VubVub(v_max_u8, Q6_Vuw_vlsr_VuwR(v_max_u8, 8));
+
+ HVX_Vector v_max_sf = nvfp4_ue4m3_to_f32(v_max_u8);
+ HVX_Vector v_inv_sf = Q6_Vsf_equals_Vqf32(hmx_w8a8_scale_qf_from_max_f32(v_max_sf, 127.0f));
+
+ HVX_Vector v_sum_w = v_zero;
+ HVX_Vector v_l1_w = v_zero;
+ const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1);
+ const HVX_Vector v_min_127 = Q6_Vh_vsplat_R(-127);
+ const HVX_Vector v_max_127 = Q6_Vh_vsplat_R(127);
+
+ #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);
+
+ for (int i = 0; i < 8; ++i) {
+ HVX_Vector v_h02, v_h13;
+ hmx_w8a8_f8_e4m3_vec_to_i16_pair(hvx_vmem(tile_src + i * 128), v_inv_sf, &v_h02, &v_h13);
+ v_h02 = Q6_Vh_vmax_VhVh(v_min_127, Q6_Vh_vmin_VhVh(v_max_127, v_h02));
+ v_h13 = Q6_Vh_vmax_VhVh(v_min_127, Q6_Vh_vmin_VhVh(v_max_127, v_h13));
+ HVX_Vector v_W = Q6_Vb_vshuffe_VbVb(v_h13, v_h02);
+ tile_dst[i] = v_W;
+ if (!use_fwht) {
+ v_sum_w = Q6_Vw_vrmpyacc_VwVbVb(v_sum_w, v_W, v_ones_s8);
+ v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(v_l1_w, Q6_Vb_vabs_Vb(v_W), v_ones_s8);
+ }
+ }
+ }
+
+ if (use_fwht) {
+ #pragma clang loop pipeline(disable) unroll(disable)
+ for (uint32_t kt = 0; kt < tiles_per_group; ++kt) {
+ HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride);
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ HVX_Vector v_W = tile_dst[i];
+ HVX_Vector v_rs = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor[i]);
+ v_W = Q6_Vb_vsub_VbVb(Q6_V_vxor_VV(v_W, v_rs), v_rs);
+ hmx_w8a8_fwht32_s12_i16(v_W, v_ones_s8, &fwht_lo[i], &fwht_hi[i]);
+ }
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 4);
+ }
+ }
+
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (0.5f / 127.0f) : (1.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
+}
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(f8_e4m3)
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);
@@ -500,13 +985,14 @@ static inline HVX_Vector unpack_q3_k_group_shl5(const HVX_Vector * restrict vptr
return Q6_V_vandor_VQR(v_lo2, q_neg, 0x80808080);
}
-static inline void rescale_q3_k_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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);
@@ -519,36 +1005,43 @@ static inline void rescale_q3_k_weight_superblock_impl(
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);
+ hmx_w8a8_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[3], v_inv127_qf, &v_m_b0, &v_m_b1);
+ hmx_w8a8_m_b4_pair_from_f16(vptr[3], v_inv127_qf, &v_m_b0, &v_m_b1);
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
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);
+ hmx_w8a8_rescale_pair_wb_ex(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
}
}
- emit_int_hmx_scales_and_bias(v_max_sf, 4.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (1.0f / 127.0f) : (4.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q3_k)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q3_k)
-static inline void rescale_q6_k_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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);
@@ -563,7 +1056,7 @@ static inline void rescale_q6_k_weight_superblock_impl(
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);
+ hmx_w8a8_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();
@@ -573,22 +1066,26 @@ static inline void rescale_q6_k_weight_superblock_impl(
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);
+ hmx_w8a8_m_b4_pair_from_f16(vptr[6], v_inv127_qf, &v_m_b0, &v_m_b1);
- #pragma clang loop pipeline(disable) unroll(disable)
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
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);
+ hmx_w8a8_rescale_pair_wb_ex(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
}
}
- emit_int_hmx_scales_and_bias(v_max_sf, 32.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (8.0f / 127.0f) : (32.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q6_k)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q6_k)
-static inline void int_hmx_pack_q6_pair(
+static __attribute__((always_inline)) inline void hmx_w8a8_pack_q6_pair(
HVX_Vector v_hi0,
HVX_Vector v_lo0,
HVX_Vector v_hi1,
@@ -604,7 +1101,44 @@ static inline void int_hmx_pack_q6_pair(
#endif
}
-static inline HVX_Vector int_hmx_asym_update_wmax_qf(
+static __attribute__((always_inline)) inline void hmx_w8a8_store_or_fwht32_q6_pair(
+ HVX_Vector v_p0_e,
+ HVX_Vector v_p0_o,
+ HVX_Vector v_p1_e,
+ HVX_Vector v_p1_o,
+ HVX_Vector * restrict tile_dst,
+ int pair_idx,
+ HVX_Vector * restrict v_sum_w,
+ HVX_Vector * restrict v_l1_w,
+ HVX_Vector fwht_lo[8],
+ HVX_Vector fwht_hi[8],
+ bool use_fwht) {
+ if (!use_fwht) {
+ HVX_Vector v_W0, v_W1;
+ hmx_w8a8_pack_q6_pair(v_p0_o, v_p0_e, v_p1_o, v_p1_e, &v_W0, &v_W1);
+ hmx_w8a8_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
+ return;
+ }
+ // Keep 3 fractional bits (Q6 -> Q3 in [-1016, +1016]) through FWHT-32 to avoid double rounding.
+ const HVX_Vector v_r4 = Q6_Vh_vsplat_R(4);
+ const HVX_Vector v_r3 = Q6_Vh_vsplat_R(3);
+ HVX_Vector v_xe0 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor_h_even[2 * pair_idx + 0]);
+ HVX_Vector v_xo0 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor_h_odd[2 * pair_idx + 0]);
+ HVX_Vector v_xe1 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor_h_even[2 * pair_idx + 1]);
+ HVX_Vector v_xo1 = Q6_V_vsplat_R(hmx_w8a8_fwht32_rs_xor_h_odd[2 * pair_idx + 1]);
+ HVX_Vector lo0 = Q6_Vh_vasr_VhR(Q6_Vh_vadd_VhVh(v_p0_e, v_r4), 3);
+ HVX_Vector hi0 = Q6_Vh_vasr_VhR(Q6_Vh_vadd_VhVh(v_p0_o, v_r4), 3);
+ HVX_Vector lo1 = Q6_Vh_vasr_VhR(Q6_Vh_vadd_VhVh(v_p1_e, v_r3), 3);
+ HVX_Vector hi1 = Q6_Vh_vasr_VhR(Q6_Vh_vadd_VhVh(v_p1_o, v_r3), 3);
+ lo0 = Q6_Vh_vsub_VhVh(Q6_V_vxor_VV(lo0, v_xe0), v_xe0);
+ hi0 = Q6_Vh_vsub_VhVh(Q6_V_vxor_VV(hi0, v_xo0), v_xo0);
+ lo1 = Q6_Vh_vsub_VhVh(Q6_V_vxor_VV(lo1, v_xe1), v_xe1);
+ hi1 = Q6_Vh_vsub_VhVh(Q6_V_vxor_VV(hi1, v_xo1), v_xo1);
+ hmx_w8a8_fwht32_s12_from_i16(lo0, hi0, &fwht_lo[2 * pair_idx + 0], &fwht_hi[2 * pair_idx + 0]);
+ hmx_w8a8_fwht32_s12_from_i16(lo1, hi1, &fwht_lo[2 * pair_idx + 1], &fwht_hi[2 * pair_idx + 1]);
+}
+
+static inline HVX_Vector hmx_w8a8_asym_update_wmax_qf(
HVX_Vector v_wmax_sf,
HVX_Vector vd_qf,
HVX_Vector vm_qf,
@@ -618,7 +1152,7 @@ static inline HVX_Vector int_hmx_asym_update_wmax_qf(
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(
+static inline void hmx_w8a8_asym_alpha_beta_wb(
HVX_Vector vd_qf,
HVX_Vector vm_qf,
HVX_Vector v_scale_q6_qf,
@@ -631,7 +1165,7 @@ static inline void int_hmx_asym_alpha_beta_wb(
*v_beta_h_out = Q6_Vh_vshuffe_VhVh(v_b_bias, v_b_bias);
}
-static inline void int_hmx_rescale_asym_pair_wb(
+static __attribute__((always_inline)) inline void hmx_w8a8_rescale_asym_pair_wb_ex(
HVX_Vector v_q0,
HVX_Vector v_q1,
HVX_Vector v_alpha_h,
@@ -639,7 +1173,10 @@ static inline void int_hmx_rescale_asym_pair_wb(
HVX_Vector * restrict tile_dst,
int pair_idx,
HVX_Vector * restrict v_sum_w,
- HVX_Vector * restrict v_l1_w) {
+ HVX_Vector * restrict v_l1_w,
+ HVX_Vector fwht_lo[8],
+ HVX_Vector fwht_hi[8],
+ bool use_fwht) {
const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1);
HVX_VectorPair vp0 = Q6_Wh_vmpy_VbVb(v_q0, v_one_s8);
@@ -648,12 +1185,10 @@ static inline void int_hmx_rescale_asym_pair_wb(
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);
+ hmx_w8a8_store_or_fwht32_q6_pair(v_p0_e, v_p0_o, v_p1_e, v_p1_o, tile_dst, pair_idx, v_sum_w, v_l1_w, fwht_lo, fwht_hi, use_fwht);
}
-static inline void int_hmx_iq2xxs_decode_pair(
+static inline void hmx_w8a8_iq2xxs_decode_pair(
HVX_Vector v_c2,
HVX_Vector v_sgn,
int l,
@@ -684,7 +1219,7 @@ static inline void int_hmx_iq2xxs_decode_pair(
*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) {
+static inline HVX_Vector hmx_w8a8_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)
@@ -696,13 +1231,14 @@ static inline HVX_Vector int_hmx_iq2xxs_gather_d(const uint8_t * restrict sb) {
return v_dd;
}
-static inline void rescale_iq2_xxs_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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);
@@ -714,7 +1250,7 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
#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_sf = Q6_V_lo_W(hvx_vec_f16_to_f32(hmx_w8a8_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();
@@ -729,7 +1265,7 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
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_scale_q6_qf = hmx_w8a8_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);
@@ -737,7 +1273,7 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
#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_qf = hvx_vec_f32_to_qf32(Q6_V_lo_W(hvx_vec_f16_to_f32(hmx_w8a8_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)
@@ -758,34 +1294,37 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
HVX_Vector v_m_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_sc_qf, v_ls_qf));
HVX_Vector v_alpha_h = Q6_Vh_vshuffe_VhVh(v_m_bias, v_m_bias);
+ HVX_Vector fwht_lo[8], fwht_hi[8];
#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);
+ hmx_w8a8_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);
+ hmx_w8a8_store_or_fwht32_q6_pair(v_p0_e, v_p0_o, v_p1_e, v_p1_o, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
}
}
}
- 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);
+ hmx_w8a8_emit_scales_and_bias(v_max_sf, use_fwht ? (0.03125f * 43.0f / 127.0f) : (0.125f * 43.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(iq2_xxs)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(iq2_xxs)
-static inline void rescale_q4_1_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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);
@@ -796,10 +1335,10 @@ static inline void rescale_q4_1_weight_superblock_impl(
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);
+ v_wmax_sf = hmx_w8a8_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_scale_q6_qf = hmx_w8a8_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();
@@ -809,28 +1348,33 @@ static inline void rescale_q4_1_weight_superblock_impl(
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);
+ hmx_w8a8_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)
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #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_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);
+ hmx_w8a8_rescale_asym_pair_wb_ex(v_lo, v_hi, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
}
}
- emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_wmax_sf, use_fwht ? (0.25f / 127.0f) : (1.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q4_1)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q4_1)
-static inline void rescale_q5_k_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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);
@@ -841,10 +1385,10 @@ static inline void rescale_q5_k_weight_superblock_impl(
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);
+ v_wmax_sf = hmx_w8a8_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_scale_q6_qf = hmx_w8a8_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();
@@ -855,22 +1399,26 @@ static inline void rescale_q5_k_weight_superblock_impl(
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);
+ hmx_w8a8_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)
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #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_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);
+ hmx_w8a8_rescale_asym_pair_wb_ex(v_lo, v_hi, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
+ }
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
}
}
- emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_wmax_sf, use_fwht ? (0.25f / 127.0f) : (1.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q5_k)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q5_k)
-static inline void int_hmx_q2_k_load_dmin(
+static inline void hmx_w8a8_q2_k_load_dmin(
const uint8_t * restrict sb,
HVX_Vector * restrict v_d,
HVX_Vector * restrict v_m) {
@@ -888,13 +1436,14 @@ static inline void int_hmx_q2_k_load_dmin(
*v_m = Q6_V_vmux_QVV(q_lo, v_r, v_dd);
}
-static inline void rescale_q2_k_weight_superblock_impl(
+static __attribute__((always_inline)) 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) {
+ size_t dst_tile_stride,
+ bool use_fwht) {
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);
@@ -906,7 +1455,7 @@ static inline void rescale_q2_k_weight_superblock_impl(
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);
+ hmx_w8a8_q2_k_load_dmin(sb, &v_d, &v_dm);
#pragma clang loop pipeline(disable) unroll(disable)
for (uint32_t j = 0; j < 8; ++j) {
@@ -915,12 +1464,12 @@ static inline void rescale_q2_k_weight_superblock_impl(
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);
+ v_wmax_sf = hmx_w8a8_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 = hmx_w8a8_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_scale_q6_qf = hmx_w8a8_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();
@@ -928,7 +1477,7 @@ static inline void rescale_q2_k_weight_superblock_impl(
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);
+ hmx_w8a8_q2_k_load_dmin(sb, &v_d, &v_dm);
#pragma clang loop pipeline(disable) unroll(disable)
for (uint32_t j = 0; j < 8; ++j) {
@@ -940,59 +1489,73 @@ static inline void rescale_q2_k_weight_superblock_impl(
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)
+ HVX_Vector fwht_lo[8], fwht_hi[8];
+ #pragma unroll
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);
+ hmx_w8a8_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);
+ hmx_w8a8_rescale_asym_pair_wb_ex(v_q0, v_q1, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w, fwht_lo, fwht_hi, use_fwht);
}
}
+ if (use_fwht) {
+ hmx_w8a8_fwht32_s345_store(fwht_lo, fwht_hi, tile_dst, &v_sum_w, &v_l1_w, 6);
+ }
}
}
- emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out);
+ hmx_w8a8_emit_scales_and_bias(v_wmax_sf, use_fwht ? (0.25f / 127.0f) : (1.0f / 127.0f), v_sum_w, v_l1_w, dst_scales, bias_out);
}
-DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q2_k)
+DEFINE_RESCALE_WEIGHT_SUPERBLOCK_BOTH_ENTRIES(q2_k)
+
+#define RESOLVE_RESCALE_FNS(NAME) \
+ *fn_2k = use_fwht ? rescale_##NAME##_fwht32_weight_superblock_2k \
+ : rescale_##NAME##_weight_superblock_2k; \
+ *fn_tail = use_fwht ? rescale_##NAME##_fwht32_weight_superblock_tail \
+ : rescale_##NAME##_weight_superblock_tail
static inline void resolve_int_weight_rescale_fns(
int32_t weight_type,
+ bool use_fwht,
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_0: RESOLVE_RESCALE_FNS(q4_0); break;
+ case HTP_TYPE_Q8_0: RESOLVE_RESCALE_FNS(q8_0); break;
+ case HTP_TYPE_IQ4_NL: RESOLVE_RESCALE_FNS(iq4_nl); break;
+ case HTP_TYPE_MXFP4: RESOLVE_RESCALE_FNS(mxfp4); break;
+ case HTP_TYPE_Q5_0: RESOLVE_RESCALE_FNS(q5_0); break;
+ case HTP_TYPE_Q1_0: RESOLVE_RESCALE_FNS(q1_0); break;
+ case HTP_TYPE_Q2_0: RESOLVE_RESCALE_FNS(q2_0); break;
+ case HTP_TYPE_NVFP4: RESOLVE_RESCALE_FNS(nvfp4); break;
+ case HTP_TYPE_F8_E4M3: RESOLVE_RESCALE_FNS(f8_e4m3); break;
+ case HTP_TYPE_Q3_K: RESOLVE_RESCALE_FNS(q3_k); break;
+ case HTP_TYPE_Q6_K: RESOLVE_RESCALE_FNS(q6_k); break;
+ case HTP_TYPE_IQ2_XXS: RESOLVE_RESCALE_FNS(iq2_xxs); 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_Q4_K: RESOLVE_RESCALE_FNS(q4_1); 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;
+ case HTP_TYPE_Q5_K: RESOLVE_RESCALE_FNS(q5_k); break;
+ case HTP_TYPE_Q2_K: RESOLVE_RESCALE_FNS(q2_k); break;
+ default: *fn_2k = NULL; *fn_tail = NULL; break;
}
}
+#undef RESOLVE_RESCALE_FNS
-static void rescale_int_weight_to_int8_task(
+static inline void rescale_int_weight_unit(
const int_weight_rescale_state_t * state,
- uint32_t start_unit,
- uint32_t end_unit) {
+ uint32_t ct,
+ uint32_t g,
+ uint32_t u) {
const uint32_t n_k_tiles = state->n_k_tiles;
const uint32_t n_groups = state->n_groups;
@@ -1003,34 +1566,45 @@ static void rescale_int_weight_to_int8_task(
const int_rescale_superblock_fn_t tail_fn = (tail_tiles == HTP_MM_HMX_W8A8_KGROUP_TILES)
? rescale_2k_fn
: state->rescale_tail_fn;
+ const uint32_t n_col_paired = state->n_col_tiles & ~1u;
+ 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));
- 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;
+ fn(src_base, dst_wt, dst_scales, bias_out, tiles_in_group, dst_tile_stride);
+ if (state->w_scale) {
+ HVX_Vector v_ws = hvx_vmem(state->w_scale + (size_t) ct * state->w_scale_ct_stride);
+ *(HVX_Vector *) dst_scales = hvx_vec_mul_f32_f32(*(const HVX_Vector *) dst_scales, v_ws);
+ }
+}
- 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));
+static void rescale_int_weight_to_int8_task(
+ const int_weight_rescale_state_t * state,
+ uint32_t start_unit,
+ uint32_t end_unit) {
- fn(src_base, dst_wt, dst_scales, bias_out, tiles_in_group, dst_tile_stride);
+ const uint32_t n_groups = state->n_groups;
+ uint32_t ct = fastdiv(start_unit, &state->n_groups_div);
+ uint32_t g = start_unit - ct * n_groups;
+ for (uint32_t u = start_unit; u < end_unit; ++u) {
+ rescale_int_weight_unit(state, ct, g, u);
if (++g == n_groups) {
g = 0;
++ct;
@@ -1523,52 +2097,623 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
}
}
-#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); \
- } \
- } \
- } \
+static inline HVX_VectorPair hvx_w8a8_fwht_stage_pair(HVX_Vector v0, HVX_Vector v1, int32_t b) {
+ HVX_VectorPair p = Q6_W_vshuff_VVR(v1, v0, b);
+ HVX_Vector s = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ HVX_Vector d = Q6_Vqf32_vsub_Vqf32Vqf32(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ return Q6_W_vshuff_VVR(d, s, b);
}
-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)
+static inline HVX_VectorPair hvx_w8a8_fwht32_pair_qf(HVX_Vector v0, HVX_Vector v1) {
+ HVX_VectorPair p;
+ p = hvx_w8a8_fwht_stage_pair(v0, v1, 4);
+ p = hvx_w8a8_fwht_stage_pair(Q6_V_lo_W(p), Q6_V_hi_W(p), 8);
+ p = hvx_w8a8_fwht_stage_pair(Q6_V_lo_W(p), Q6_V_hi_W(p), 16);
+ p = hvx_w8a8_fwht_stage_pair(Q6_V_lo_W(p), Q6_V_hi_W(p), 32);
+ p = hvx_w8a8_fwht_stage_pair(Q6_V_lo_W(p), Q6_V_hi_W(p), 64);
+ return p;
+}
+
+static inline void hvx_w8a8_fwht_stage_quad_qf(HVX_VectorPair * p01, HVX_VectorPair * p23, int32_t b) {
+ HVX_VectorPair t01 = Q6_W_vshuff_VVR(Q6_V_hi_W(*p01), Q6_V_lo_W(*p01), b);
+ HVX_VectorPair t23 = Q6_W_vshuff_VVR(Q6_V_hi_W(*p23), Q6_V_lo_W(*p23), b);
+ HVX_Vector s01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_lo_W(t01), Q6_V_hi_W(t01));
+ HVX_Vector d01 = Q6_Vqf32_vsub_Vqf32Vqf32(Q6_V_lo_W(t01), Q6_V_hi_W(t01));
+ HVX_Vector s23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_lo_W(t23), Q6_V_hi_W(t23));
+ HVX_Vector d23 = Q6_Vqf32_vsub_Vqf32Vqf32(Q6_V_lo_W(t23), Q6_V_hi_W(t23));
+ *p01 = Q6_W_vshuff_VVR(d01, s01, b);
+ *p23 = Q6_W_vshuff_VVR(d23, s23, b);
+}
+
+static inline void hvx_w8a8_fwht32_quad_qf(
+ HVX_Vector v0, HVX_Vector v1, HVX_Vector v2, HVX_Vector v3,
+ HVX_Vector * y0, HVX_Vector * y1, HVX_Vector * y2, HVX_Vector * y3) {
+ HVX_VectorPair p01 = Q6_W_vcombine_VV(v1, v0);
+ HVX_VectorPair p23 = Q6_W_vcombine_VV(v3, v2);
+ hvx_w8a8_fwht_stage_quad_qf(&p01, &p23, 4);
+ hvx_w8a8_fwht_stage_quad_qf(&p01, &p23, 8);
+ hvx_w8a8_fwht_stage_quad_qf(&p01, &p23, 16);
+ hvx_w8a8_fwht_stage_quad_qf(&p01, &p23, 32);
+ hvx_w8a8_fwht_stage_quad_qf(&p01, &p23, 64);
+ *y0 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p01));
+ *y1 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p01));
+ *y2 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p23));
+ *y3 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p23));
+}
+
+static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_2k_fwht32(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_a_out,
+ float * p0,
+ float * p1,
+ float * p2,
+ float * p3,
+ uint32_t rg,
+ uint32_t k_start,
+ uint32_t valid_rows) {
+
+ float * p0_base = p0 + k_start;
+ float * p1_base = p1 + k_start;
+ float * p2_base = p2 + k_start;
+ 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));
+
+ const HVX_Vector v_rs_f32 = *(const HVX_Vector *) hmx_w8a8_fwht32_rs_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();
+
+ // Fuse FWHT-32 with vmax reduction and write rotated floats back for pass 2.
+ if (valid_rows == 1) {
+ for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; kt += 4) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 0), v_rs_f32);
+ HVX_Vector vx1 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 32), v_rs_f32);
+ HVX_Vector vx2 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 64), v_rs_f32);
+ HVX_Vector vx3 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 96), v_rs_f32);
+ HVX_Vector y0, y1, y2, y3;
+ hvx_w8a8_fwht32_quad_qf(vx0, vx1, vx2, vx3, &y0, &y1, &y2, &y3);
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y0));
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y1));
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y2));
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y3));
+ hvx_vmem(p0_base + off + 0) = y0;
+ hvx_vmem(p0_base + off + 32) = y1;
+ hvx_vmem(p0_base + off + 64) = y2;
+ hvx_vmem(p0_base + off + 96) = y3;
+ }
+ } else if (valid_rows == 4) {
+ for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off), v_rs_f32);
+ HVX_Vector vx1 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off), v_rs_f32);
+ HVX_Vector vx2 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2_base + off), v_rs_f32);
+ HVX_Vector vx3 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p3_base + off), v_rs_f32);
+ HVX_Vector y0, y1, y2, y3;
+ hvx_w8a8_fwht32_quad_qf(vx0, vx1, vx2, vx3, &y0, &y1, &y2, &y3);
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(y1));
+ vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(y2));
+ vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(y3));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p1_base + off) = y1;
+ hvx_vmem(p2_base + off) = y2;
+ hvx_vmem(p3_base + off) = y3;
+ }
+ } else if (valid_rows == 2) {
+ for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off), v_rs_f32);
+ HVX_Vector vx1 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off), v_rs_f32);
+ HVX_VectorPair r01 = hvx_w8a8_fwht32_pair_qf(vx0, vx1);
+ HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(r01));
+ HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(r01));
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(y1));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p1_base + off) = y1;
+ }
+ } else {
+ for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) {
+ const uint32_t off = kt * 32;
+ HVX_Vector vx0 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off), v_rs_f32);
+ HVX_Vector vx1 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off), v_rs_f32);
+ HVX_Vector vx2 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2_base + off), v_rs_f32);
+ HVX_Vector y0, y1, y2, y3;
+ hvx_w8a8_fwht32_quad_qf(vx0, vx1, vx2, vx2, &y0, &y1, &y2, &y3);
+ vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(y0));
+ vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(y1));
+ vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(y2));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p1_base + off) = y1;
+ hvx_vmem(p2_base + off) = y2;
+ }
+ }
+
+ 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_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 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
+ HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
+ HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
+ HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
+
+ 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
+}
+
+static __attribute__((noinline)) void hvx_w8a8_fwht32_rows_f32_range(
+ uint8_t * restrict curr_buf,
+ size_t row_bytes,
+ uint32_t valid_rows,
+ uint32_t k_start,
+ uint32_t k_end,
+ uint32_t k_valid) {
+ float * p0 = (float *) curr_buf;
+ float * p1 = (valid_rows > 1) ? (float *) (curr_buf + 1 * row_bytes) : p0;
+ float * p2 = (valid_rows > 2) ? (float *) (curr_buf + 2 * row_bytes) : p0;
+ float * p3 = (valid_rows > 3) ? (float *) (curr_buf + 3 * row_bytes) : p0;
+
+ const HVX_Vector v_rs_f32 = *(const HVX_Vector *) hmx_w8a8_fwht32_rs_f32;
+ 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);
+ for (uint32_t c = k_start; c < c_end_full; c += 32) {
+ HVX_Vector vx0 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0 + c), v_rs_f32);
+ HVX_Vector vx1 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1 + c), v_rs_f32);
+ HVX_VectorPair r01 = hvx_w8a8_fwht32_pair_qf(vx0, vx1);
+ if (valid_rows > 2) {
+ HVX_Vector vx2 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2 + c), v_rs_f32);
+ HVX_Vector vx3 = Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p3 + c), v_rs_f32);
+ HVX_VectorPair r23 = hvx_w8a8_fwht32_pair_qf(vx2, vx3);
+ hvx_vmem(p2 + c) = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(r23));
+ if (valid_rows > 3) {
+ hvx_vmem(p3 + c) = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(r23));
+ }
+ }
+ hvx_vmem(p0 + c) = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(r01));
+ if (valid_rows > 1) {
+ hvx_vmem(p1 + c) = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(r01));
+ }
+ }
+ 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) {
+ HVX_VectorPred mask = Q6_Q_vsetq2_R((k_valid - c) * sizeof(float));
+ vx0 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero()), v_rs_f32);
+ vx1 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero()), v_rs_f32);
+ vx2 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero()), v_rs_f32);
+ vx3 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero()), v_rs_f32);
+ }
+ HVX_VectorPair r01 = hvx_w8a8_fwht32_pair_qf(vx0, vx1);
+ if (valid_rows > 2) {
+ HVX_VectorPair r23 = hvx_w8a8_fwht32_pair_qf(vx2, vx3);
+ hvx_vmem(p2 + c) = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(r23));
+ if (valid_rows > 3) {
+ hvx_vmem(p3 + c) = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(r23));
+ }
+ }
+ hvx_vmem(p0 + c) = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(r01));
+ if (valid_rows > 1) {
+ hvx_vmem(p1 + c) = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(r01));
+ }
+ }
+}
+
+static inline HVX_VectorPair hvx_w8a8_fwht_stage_pair_qf16(HVX_Vector v0, HVX_Vector v1, int32_t b) {
+ HVX_VectorPair p = Q6_W_vshuff_VVR(v1, v0, b);
+ HVX_Vector s = Q6_Vqf16_vadd_Vqf16Vqf16(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ HVX_Vector d = Q6_Vqf16_vsub_Vqf16Vqf16(Q6_V_lo_W(p), Q6_V_hi_W(p));
+ return Q6_W_vshuff_VVR(d, s, b);
+}
+
+// Four independent 32-point FWHTs in qf16 across two 64-element f16 vectors, pre-scaled by v_quarter (0.25).
+static inline HVX_VectorPair hvx_w8a8_fwht32_pair_qf16(HVX_Vector v0_hf, HVX_Vector v1_hf, HVX_Vector v_quarter) {
+ HVX_Vector v0 = Q6_Vqf16_vmpy_VhfVhf(v0_hf, v_quarter);
+ HVX_Vector v1 = Q6_Vqf16_vmpy_VhfVhf(v1_hf, v_quarter);
+ HVX_VectorPair p;
+ p = hvx_w8a8_fwht_stage_pair_qf16(v0, v1, 2);
+ p = hvx_w8a8_fwht_stage_pair_qf16(Q6_V_lo_W(p), Q6_V_hi_W(p), 4);
+ p = hvx_w8a8_fwht_stage_pair_qf16(Q6_V_lo_W(p), Q6_V_hi_W(p), 8);
+ p = hvx_w8a8_fwht_stage_pair_qf16(Q6_V_lo_W(p), Q6_V_hi_W(p), 16);
+ p = hvx_w8a8_fwht_stage_pair_qf16(Q6_V_lo_W(p), Q6_V_hi_W(p), 32);
+ return Q6_W_vcombine_VV(Q6_Vhf_equals_Vqf16(Q6_V_hi_W(p)), Q6_Vhf_equals_Vqf16(Q6_V_lo_W(p)));
+}
+
+static inline void hvx_w8a8_fwht_stage_quad_qf16(HVX_VectorPair * p01, HVX_VectorPair * p23, int32_t b) {
+ HVX_VectorPair t01 = Q6_W_vshuff_VVR(Q6_V_hi_W(*p01), Q6_V_lo_W(*p01), b);
+ HVX_VectorPair t23 = Q6_W_vshuff_VVR(Q6_V_hi_W(*p23), Q6_V_lo_W(*p23), b);
+ HVX_Vector s01 = Q6_Vqf16_vadd_Vqf16Vqf16(Q6_V_lo_W(t01), Q6_V_hi_W(t01));
+ HVX_Vector d01 = Q6_Vqf16_vsub_Vqf16Vqf16(Q6_V_lo_W(t01), Q6_V_hi_W(t01));
+ HVX_Vector s23 = Q6_Vqf16_vadd_Vqf16Vqf16(Q6_V_lo_W(t23), Q6_V_hi_W(t23));
+ HVX_Vector d23 = Q6_Vqf16_vsub_Vqf16Vqf16(Q6_V_lo_W(t23), Q6_V_hi_W(t23));
+ *p01 = Q6_W_vshuff_VVR(d01, s01, b);
+ *p23 = Q6_W_vshuff_VVR(d23, s23, b);
+}
+
+static inline void hvx_w8a8_fwht32_quad_qf16(
+ HVX_Vector v0_hf, HVX_Vector v1_hf, HVX_Vector v2_hf, HVX_Vector v3_hf, HVX_Vector v_quarter,
+ HVX_Vector * y0, HVX_Vector * y1, HVX_Vector * y2, HVX_Vector * y3) {
+ HVX_Vector v0 = Q6_Vqf16_vmpy_VhfVhf(v0_hf, v_quarter);
+ HVX_Vector v1 = Q6_Vqf16_vmpy_VhfVhf(v1_hf, v_quarter);
+ HVX_Vector v2 = Q6_Vqf16_vmpy_VhfVhf(v2_hf, v_quarter);
+ HVX_Vector v3 = Q6_Vqf16_vmpy_VhfVhf(v3_hf, v_quarter);
+ HVX_VectorPair p01 = Q6_W_vcombine_VV(v1, v0);
+ HVX_VectorPair p23 = Q6_W_vcombine_VV(v3, v2);
+ hvx_w8a8_fwht_stage_quad_qf16(&p01, &p23, 2);
+ hvx_w8a8_fwht_stage_quad_qf16(&p01, &p23, 4);
+ hvx_w8a8_fwht_stage_quad_qf16(&p01, &p23, 8);
+ hvx_w8a8_fwht_stage_quad_qf16(&p01, &p23, 16);
+ hvx_w8a8_fwht_stage_quad_qf16(&p01, &p23, 32);
+ *y0 = Q6_Vhf_equals_Vqf16(Q6_V_lo_W(p01));
+ *y1 = Q6_Vhf_equals_Vqf16(Q6_V_hi_W(p01));
+ *y2 = Q6_Vhf_equals_Vqf16(Q6_V_lo_W(p23));
+ *y3 = Q6_Vhf_equals_Vqf16(Q6_V_hi_W(p23));
+}
+
+static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_2k_fwht32(
+ uint8_t * restrict tile_row_base,
+ float * restrict d_a_out,
+ __fp16 * p0,
+ __fp16 * p1,
+ __fp16 * p2,
+ __fp16 * p3,
+ uint32_t rg,
+ uint32_t k_start,
+ uint32_t valid_rows) {
+
+ __fp16 * p0_base = p0 + k_start;
+ __fp16 * p1_base = p1 + k_start;
+ __fp16 * p2_base = p2 + k_start;
+ __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_quarter_f16 = *(const HVX_Vector *) hmx_w8a8_fwht32_rs_f16_quarter;
+ 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();
+
+ if (valid_rows == 1) {
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; step += 4) {
+ const uint32_t off = step * 64;
+ HVX_Vector y0, y1, y2, y3;
+ hvx_w8a8_fwht32_quad_qf16(
+ hvx_vmem(p0_base + off), hvx_vmem(p0_base + off + 64),
+ hvx_vmem(p0_base + off + 128), hvx_vmem(p0_base + off + 192),
+ v_quarter_f16, &y0, &y1, &y2, &y3);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y0, v_abs_f16));
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y1, v_abs_f16));
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y2, v_abs_f16));
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y3, v_abs_f16));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p0_base + off + 64) = y1;
+ hvx_vmem(p0_base + off + 128) = y2;
+ hvx_vmem(p0_base + off + 192) = y3;
+ }
+ } else if (valid_rows == 4) {
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector y0, y1, y2, y3;
+ hvx_w8a8_fwht32_quad_qf16(
+ hvx_vmem(p0_base + off), hvx_vmem(p1_base + off),
+ hvx_vmem(p2_base + off), hvx_vmem(p3_base + off),
+ v_quarter_f16, &y0, &y1, &y2, &y3);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(y1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(y2, v_abs_f16));
+ vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(y3, v_abs_f16));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p1_base + off) = y1;
+ hvx_vmem(p2_base + off) = y2;
+ hvx_vmem(p3_base + off) = y3;
+ }
+ } else if (valid_rows == 2) {
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) {
+ const uint32_t off = step * 64;
+ HVX_VectorPair r01 = hvx_w8a8_fwht32_pair_qf16(
+ hvx_vmem(p0_base + off), hvx_vmem(p1_base + off), v_quarter_f16);
+ HVX_Vector y0 = Q6_V_lo_W(r01);
+ HVX_Vector y1 = Q6_V_hi_W(r01);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(y1, v_abs_f16));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p1_base + off) = y1;
+ }
+ } else {
+ for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) {
+ const uint32_t off = step * 64;
+ HVX_Vector vh2 = hvx_vmem(p2_base + off);
+ HVX_Vector y0, y1, y2, y3;
+ hvx_w8a8_fwht32_quad_qf16(
+ hvx_vmem(p0_base + off), hvx_vmem(p1_base + off), vh2, vh2,
+ v_quarter_f16, &y0, &y1, &y2, &y3);
+ vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(y0, v_abs_f16));
+ vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(y1, v_abs_f16));
+ vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(y2, v_abs_f16));
+ hvx_vmem(p0_base + off) = y0;
+ hvx_vmem(p1_base + off) = y1;
+ hvx_vmem(p2_base + off) = y2;
+ }
+ }
+
+ 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();
+
+ // Compensate the 0.25f pre-scale directly in d_a_out (4.0f / 127.0f).
+ const HVX_Vector v_scale_out = hvx_vec_splat_f32(4.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_scale_out);
+ HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_scale_out);
+ HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_scale_out);
+ HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_scale_out);
+ 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_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_min_u8, v_max_u8);
+ }
+}
+
+static __attribute__((noinline)) void hvx_w8a8_fwht32_rows_f16_range(
+ uint8_t * restrict curr_buf,
+ size_t row_bytes,
+ uint32_t valid_rows,
+ uint32_t k_start,
+ uint32_t k_end,
+ uint32_t k_valid) {
+ const HVX_Vector v_quarter = *(const HVX_Vector *) hmx_w8a8_fwht32_rs_f16_quarter;
+ __fp16 * p0 = (__fp16 *) curr_buf;
+ __fp16 * p1 = (valid_rows > 1) ? (__fp16 *) (curr_buf + 1 * row_bytes) : p0;
+ __fp16 * p2 = (valid_rows > 2) ? (__fp16 *) (curr_buf + 2 * row_bytes) : p0;
+ __fp16 * p3 = (valid_rows > 3) ? (__fp16 *) (curr_buf + 3 * row_bytes) : p0;
+
+ 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);
+ for (uint32_t c = k_start; c < c_end_full; c += 64) {
+ HVX_VectorPair r01 = hvx_w8a8_fwht32_pair_qf16(hvx_vmem(p0 + c), hvx_vmem(p1 + c), v_quarter);
+ if (valid_rows > 2) {
+ HVX_VectorPair r23 = hvx_w8a8_fwht32_pair_qf16(hvx_vmem(p2 + c), hvx_vmem(p3 + c), v_quarter);
+ hvx_vmem(p2 + c) = Q6_V_lo_W(r23);
+ if (valid_rows > 3) {
+ hvx_vmem(p3 + c) = Q6_V_hi_W(r23);
+ }
+ }
+ hvx_vmem(p0 + c) = Q6_V_lo_W(r01);
+ if (valid_rows > 1) {
+ hvx_vmem(p1 + c) = Q6_V_hi_W(r01);
+ }
+ }
+ 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) {
+ HVX_VectorPred mask = Q6_Q_vsetq2_R((k_valid - c) * sizeof(__fp16));
+ 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());
+ }
+ HVX_VectorPair r01 = hvx_w8a8_fwht32_pair_qf16(vh0, vh1, v_quarter);
+ if (valid_rows > 2) {
+ HVX_VectorPair r23 = hvx_w8a8_fwht32_pair_qf16(vh2, vh3, v_quarter);
+ hvx_vmem(p2 + c) = Q6_V_lo_W(r23);
+ if (valid_rows > 3) {
+ hvx_vmem(p3 + c) = Q6_V_hi_W(r23);
+ }
+ }
+ hvx_vmem(p0 + c) = Q6_V_lo_W(r01);
+ if (valid_rows > 1) {
+ hvx_vmem(p1 + c) = Q6_V_hi_W(r01);
+ }
+ }
+}
+
+static __attribute__((noinline)) void quantize_act_step_rows_f16_w8a8(
+ uint8_t * restrict vtcm_act_dst,
+ float * restrict vtcm_act_scales,
+ 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,
+ bool use_fwht) {
+ 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;
+ __fp16 * p0 = (__fp16 *) curr_buf;
+ __fp16 * p1 = (valid_rows > 1) ? (__fp16 *) (curr_buf + 1 * row_bytes) : p0;
+ __fp16 * p2 = (valid_rows > 2) ? (__fp16 *) (curr_buf + 2 * row_bytes) : p0;
+ __fp16 * p3 = (valid_rows > 3) ? (__fp16 *) (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) {
+ if (use_fwht) {
+ quantize_act_superblock_quad_f16_to_u8_sm_2k_fwht32(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, valid_rows);
+ } else {
+ quantize_act_superblock_quad_f16_to_u8_sm_2k(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, valid_rows);
+ }
+ } else {
+ uint32_t k_valid_eff = k_valid;
+ if (use_fwht) {
+ hvx_w8a8_fwht32_rows_f16_range(curr_buf, row_bytes, valid_rows, k_start, k_start + k_group, k_valid);
+ k_valid_eff = k_start + k_group;
+ }
+ quantize_act_superblock_quad_f16_to_u8_sm(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, k_group, k_valid_eff, valid_rows);
+ if (use_fwht) {
+ for (uint32_t s = 0; s < 4; ++s) {
+ d_a_out[s] *= 4.0f;
+ }
+ }
+ }
+ }
+ }
+}
+
+static __attribute__((noinline)) void quantize_act_step_rows_f32_w8a8(
+ uint8_t * restrict vtcm_act_dst,
+ float * restrict vtcm_act_scales,
+ 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,
+ bool use_fwht) {
+ 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;
+ float * p0 = (float *) curr_buf;
+ float * p1 = (valid_rows > 1) ? (float *) (curr_buf + 1 * row_bytes) : p0;
+ float * p2 = (valid_rows > 2) ? (float *) (curr_buf + 2 * row_bytes) : p0;
+ float * p3 = (valid_rows > 3) ? (float *) (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) {
+ if (use_fwht) {
+ quantize_act_superblock_quad_f32_to_u8_sm_2k_fwht32(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, valid_rows);
+ } else {
+ quantize_act_superblock_quad_f32_to_u8_sm_2k(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, valid_rows);
+ }
+ } else {
+ uint32_t k_valid_eff = k_valid;
+ if (use_fwht) {
+ hvx_w8a8_fwht32_rows_f32_range(curr_buf, row_bytes, valid_rows, k_start, k_start + k_group, k_valid);
+ k_valid_eff = k_start + k_group;
+ }
+ quantize_act_superblock_quad_f32_to_u8_sm(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, k_group, k_valid_eff, valid_rows);
+ }
+ }
+ }
+}
// Core HMX W8A8 SM dot-product kernel over all superblocks g = 0..n_groups-1.
static void core_dot_chunk_w8a8_sm(
@@ -1741,14 +2886,14 @@ static inline uint32_t (*stage_act_scales_to_l1d(
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(
+ return hvx_vec_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(
+ return hvx_vec_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)));
}
@@ -1758,25 +2903,25 @@ static inline HVX_Vector hmx_pack_f32_to_f16_tail_bias_f16(
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);
+ return hvx_vec_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);
+ return hvx_vec_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))
+ hvx_vec_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))
+ hvx_vec_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) \
@@ -2785,10 +3930,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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); \
+ hvx_vmemu(out_row0 + c) = hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi); \
} \
if (limit_c_aligned < limit_c) { \
const size_t c = limit_c_aligned; \
@@ -2802,10 +3947,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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)); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi)); \
}
#define W8A8_SCAT_STEP_2G_FP16 \
@@ -2816,10 +3961,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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); \
+ hvx_vmemu(out_row0 + c) = hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi); \
} \
if (limit_c_aligned < limit_c) { \
const size_t c = limit_c_aligned; \
@@ -2833,10 +3978,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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)); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi)); \
}
#define W8A8_SCAT_STEP_NG_FP16 \
@@ -2847,10 +3992,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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); \
+ hvx_vmemu(out_row0 + c) = hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi); \
} \
if (limit_c_aligned < limit_c) { \
const size_t c = limit_c_aligned; \
@@ -2864,10 +4009,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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)); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi)); \
}
#define W8A8_SCAT_STEP_CHUNKED_FP16 \
@@ -2880,10 +4025,10 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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); \
+ hvx_vmemu(out_row0 + c) = hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi); \
+ if (out_row1) hvx_vmemu(out_row1 + c) = hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi); \
+ if (out_row2) hvx_vmemu(out_row2 + c) = hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi); \
+ if (out_row3) hvx_vmemu(out_row3 + c) = hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi); \
} \
if (limit_c_aligned < limit_c) { \
const size_t c = limit_c_aligned; \
@@ -2899,13 +4044,13 @@ DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2
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)); \
+ hvx_vec_store_u(out_row0 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v0_lo, v0_hi)); \
+ if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v1_lo, v1_hi)); \
+ if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v2_lo, v2_hi)); \
+ if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hvx_vec_f32_to_f16_clamped(v3_lo, v3_hi)); \
}
-typedef void (*int_output_col_chunk_fn_t)(
+typedef void (*w8a8_output_col_chunk_fn_t)(
void * restrict dst,
const void * restrict bias,
const void * restrict vtcm_src,
@@ -2923,7 +4068,7 @@ typedef void (*int_output_col_chunk_fn_t)(
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) \
+#define HMX_SELECT_W8A8_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 \
@@ -2932,7 +4077,7 @@ typedef void (*int_output_col_chunk_fn_t)(
: ((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(
+static inline w8a8_output_col_chunk_fn_t resolve_w8a8_output_col_chunk_fn(
uint32_t n_groups,
size_t dst_elem_size,
const void * bias,
@@ -2942,26 +4087,26 @@ static inline int_output_col_chunk_fn_t resolve_int_output_col_chunk_fn(
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);
+ return HMX_SELECT_W8A8_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);
+ return HMX_SELECT_W8A8_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_W8A8_COL_FN(fp16, ng, bias, bias_f16, dst_aligned_nt);
}
- return HMX_SELECT_INT_COL_FN(fp16, chunked, bias, bias_f16, dst_aligned_nt);
+ return HMX_SELECT_W8A8_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);
+ return HMX_SELECT_W8A8_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);
+ return HMX_SELECT_W8A8_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_W8A8_COL_FN(fp32, ng, bias, bias_f16, dst_aligned_nt);
}
- return HMX_SELECT_INT_COL_FN(fp32, chunked, bias, bias_f16, dst_aligned_nt);
+ return HMX_SELECT_W8A8_COL_FN(fp32, chunked, bias, bias_f16, dst_aligned_nt);
}
// --- Fused W8A8 GLU Epilogue (paired gate/up -> f(gate) * up) ---
@@ -2992,10 +4137,10 @@ static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_pair_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);
+ out_hf[0] = hvx_vec_f32_to_f16_clamped(lo0, hi0);
+ out_hf[1] = hvx_vec_f32_to_f16_clamped(lo1, hi1);
+ out_hf[2] = hvx_vec_f32_to_f16_clamped(lo2, hi2);
+ out_hf[3] = hvx_vec_f32_to_f16_clamped(lo3, hi3);
}
static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_strip_hf(
@@ -3011,10 +4156,10 @@ static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_strip_hf(
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);
+ hvx_vmem(dst + c + 0 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo0, hi0);
+ hvx_vmem(dst + c + 1 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo1, hi1);
+ hvx_vmem(dst + c + 2 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo2, hi2);
+ hvx_vmem(dst + c + 3 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo3, hi3);
}
}
@@ -3038,10 +4183,10 @@ static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_pair_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);
+ out_hf[0] = hvx_vec_f32_to_f16_clamped(lo0, hi0);
+ out_hf[1] = hvx_vec_f32_to_f16_clamped(lo1, hi1);
+ out_hf[2] = hvx_vec_f32_to_f16_clamped(lo2, hi2);
+ out_hf[3] = hvx_vec_f32_to_f16_clamped(lo3, hi3);
}
static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_strip_hf(
@@ -3059,10 +4204,10 @@ static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_strip_hf(
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);
+ hvx_vmem(dst + c + 0 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo0, hi0);
+ hvx_vmem(dst + c + 1 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo1, hi1);
+ hvx_vmem(dst + c + 2 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo2, hi2);
+ hvx_vmem(dst + c + 3 * dst_stride) = hvx_vec_f32_to_f16_clamped(lo3, hi3);
}
}
@@ -3090,10 +4235,10 @@ static __attribute__((noinline)) void w8a8_sm_glu_eval_chunked_quad(
}
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]);
+ out_hf[0] = hvx_vec_f32_to_f16_clamped(q[0], q[4]);
+ out_hf[1] = hvx_vec_f32_to_f16_clamped(q[1], q[5]);
+ out_hf[2] = hvx_vec_f32_to_f16_clamped(q[2], q[6]);
+ out_hf[3] = hvx_vec_f32_to_f16_clamped(q[3], q[7]);
}
static __attribute__((noinline)) void w8a8_sm_glu_pack_and_store_tail_fp16(
@@ -3107,24 +4252,24 @@ static __attribute__((noinline)) void w8a8_sm_glu_pack_and_store_tail_fp16(
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]);
+ g_hf[0] = hvx_vec_f32_to_f16_clamped(g_q[0], g_q[4]);
+ g_hf[1] = hvx_vec_f32_to_f16_clamped(g_q[1], g_q[5]);
+ g_hf[2] = hvx_vec_f32_to_f16_clamped(g_q[2], g_q[6]);
+ g_hf[3] = hvx_vec_f32_to_f16_clamped(g_q[3], g_q[7]);
+ u_hf[0] = hvx_vec_f32_to_f16_clamped(u_q[0], u_q[4]);
+ u_hf[1] = hvx_vec_f32_to_f16_clamped(u_q[1], u_q[5]);
+ u_hf[2] = hvx_vec_f32_to_f16_clamped(u_q[2], u_q[6]);
+ u_hf[3] = hvx_vec_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);
+ g_hf[0] = hvx_vec_f32_to_f16_clamped(g_q[0], z);
+ g_hf[1] = hvx_vec_f32_to_f16_clamped(g_q[1], z);
+ g_hf[2] = hvx_vec_f32_to_f16_clamped(g_q[2], z);
+ g_hf[3] = hvx_vec_f32_to_f16_clamped(g_q[3], z);
+ u_hf[0] = hvx_vec_f32_to_f16_clamped(u_q[0], z);
+ u_hf[1] = hvx_vec_f32_to_f16_clamped(u_q[1], z);
+ u_hf[2] = hvx_vec_f32_to_f16_clamped(u_q[2], z);
+ u_hf[3] = hvx_vec_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);
@@ -3429,7 +4574,7 @@ static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SF
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(
+static inline bool resolve_w8a8_output_glu_fns(
uint32_t n_groups,
uint8_t glu_op,
size_t dst_elem_size,
diff --git a/ggml/src/ggml-hexagon/htp/hmx-int-utils.h b/ggml/src/ggml-hexagon/htp/hmx-w8a8-utils.h
similarity index 87%
rename from ggml/src/ggml-hexagon/htp/hmx-int-utils.h
rename to ggml/src/ggml-hexagon/htp/hmx-w8a8-utils.h
index d29179965..4204d8c4f 100644
--- a/ggml/src/ggml-hexagon/htp/hmx-int-utils.h
+++ b/ggml/src/ggml-hexagon/htp/hmx-w8a8-utils.h
@@ -1,5 +1,5 @@
-#ifndef HMX_INT_UTILS_H
-#define HMX_INT_UTILS_H
+#ifndef HMX_W8A8_UTILS_H
+#define HMX_W8A8_UTILS_H
#include <stddef.h>
#include <stdint.h>
@@ -31,7 +31,7 @@ static inline HVX_Vector hmx_qf32_to_i32_zp128(HVX_Vector v_qf) {
return Q6_Vw_equals_Vsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(v_qf, v_128p5)));
}
-static inline void emit_int_hmx_scales_and_bias(
+static inline void hmx_w8a8_emit_scales_and_bias(
HVX_Vector v_max_sf,
float scale_const,
HVX_Vector v_sum_w,
@@ -58,7 +58,7 @@ static inline void emit_int_hmx_scales_and_bias(
bias_out[3] = v_ib;
}
-static inline void emit_int_hmx_scales_and_bias_zp0(
+static inline void hmx_w8a8_emit_scales_and_bias_zp0(
HVX_Vector v_max_sf,
float scale_const,
HVX_Vector v_l1_w,
@@ -84,51 +84,51 @@ static inline void emit_int_hmx_scales_and_bias_zp0(
bias_out[3] = v_ib;
}
-static inline HVX_Vector int_hmx_scale_qf_from_max_f32(HVX_Vector v_max_sf, float num) {
+static inline HVX_Vector hmx_w8a8_scale_qf_from_max_f32(HVX_Vector v_max_sf, float num) {
HVX_VectorPred q_pos = Q6_Q_vcmp_gt_VsfVsf(v_max_sf, hvx_vec_splat_f32(1e-30f));
HVX_Vector v_inv_raw = hvx_vec_inverse_f32(v_max_sf);
HVX_Vector v_scale_sf = Q6_V_vmux_QVV(q_pos, hvx_vec_mul_f32_f32(v_inv_raw, hvx_vec_splat_f32(num)), Q6_V_vzero());
return hvx_vec_f32_to_qf32(v_scale_sf);
}
-static inline HVX_Vector int_hmx_inv127_from_max_f32(HVX_Vector v_max_sf) {
- return int_hmx_scale_qf_from_max_f32(v_max_sf, 127.0f);
+static inline HVX_Vector hmx_w8a8_inv127_from_max_f32(HVX_Vector v_max_sf) {
+ return hmx_w8a8_scale_qf_from_max_f32(v_max_sf, 127.0f);
}
-static inline void int_hmx_inv127_from_max_f16(
+static inline void hmx_w8a8_inv127_from_max_f16(
HVX_Vector v_max_sc,
HVX_Vector * restrict v_max_sf_out,
HVX_Vector * restrict v_inv127_qf_out) {
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
HVX_Vector v_max_sf = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_max_sc), v_one_f16)));
*v_max_sf_out = v_max_sf;
- *v_inv127_qf_out = int_hmx_inv127_from_max_f32(v_max_sf);
+ *v_inv127_qf_out = hmx_w8a8_inv127_from_max_f32(v_max_sf);
}
-static inline HVX_Vector int_hmx_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) {
+static inline HVX_Vector hmx_w8a8_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) {
HVX_Vector v_m_biased = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf));
HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased);
return Q6_Vh_vshuff_Vh(Q6_Vb_vshuff_Vb(Q6_Vb_vpacke_VhVh(v_m_h, v_m_h)));
}
-static inline HVX_Vector int_hmx_m_b4_from_f16(HVX_Vector v_sc, HVX_Vector v_inv127_qf) {
+static inline HVX_Vector hmx_w8a8_m_b4_from_f16(HVX_Vector v_sc, HVX_Vector v_inv127_qf) {
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
HVX_Vector v_sc_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_sc), v_one_f16));
- return int_hmx_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf);
+ return hmx_w8a8_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf);
}
-static inline void int_hmx_m_b4_pair_from_f16(
+static inline void hmx_w8a8_m_b4_pair_from_f16(
HVX_Vector v_sc,
HVX_Vector v_inv127_qf,
HVX_Vector * restrict v_m_b0_out,
HVX_Vector * restrict v_m_b1_out) {
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
HVX_VectorPair vp_sc_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_sc), v_one_f16);
- *v_m_b0_out = int_hmx_m_b4_from_sc_qf(Q6_V_lo_W(vp_sc_qf), v_inv127_qf);
- *v_m_b1_out = int_hmx_m_b4_from_sc_qf(Q6_V_hi_W(vp_sc_qf), v_inv127_qf);
+ *v_m_b0_out = hmx_w8a8_m_b4_from_sc_qf(Q6_V_lo_W(vp_sc_qf), v_inv127_qf);
+ *v_m_b1_out = hmx_w8a8_m_b4_from_sc_qf(Q6_V_hi_W(vp_sc_qf), v_inv127_qf);
}
-static inline void int_hmx_store_and_accum_pair(
+static inline void hmx_w8a8_store_and_accum_pair(
HVX_Vector * restrict tile_dst,
int pair_idx,
HVX_Vector v_W0,
@@ -144,7 +144,7 @@ static inline void int_hmx_store_and_accum_pair(
*v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(Q6_Vw_vrmpyacc_VwVubVb(*v_l1_w, Q6_Vb_vabs_Vb(v_W0), v_ones_s8), Q6_Vb_vabs_Vb(v_W1), v_ones_s8);
}
-static inline void int_hmx_rescale_pair_wb(
+static inline void hmx_w8a8_rescale_pair_wb(
HVX_Vector v_q0,
HVX_Vector v_q1,
HVX_Vector v_m_b4,
@@ -167,7 +167,7 @@ static inline void int_hmx_rescale_pair_wb(
HVX_Vector v_W1 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p23), 1),
Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p23), 1));
#endif
- int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
+ hmx_w8a8_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w);
}
#if __HVX_ARCH__ >= 81
@@ -214,4 +214,4 @@ static inline void hmx_pack_hf_quad_to_u8_cm_pair(
}
#endif
-#endif /* HMX_INT_UTILS_H */
+#endif /* HMX_W8A8_UTILS_H */
diff --git a/ggml/src/ggml-hexagon/htp/htp-ops.h b/ggml/src/ggml-hexagon/htp/htp-ops.h
index 25a2b6459..c7098209e 100644
--- a/ggml/src/ggml-hexagon/htp/htp-ops.h
+++ b/ggml/src/ggml-hexagon/htp/htp-ops.h
@@ -36,8 +36,9 @@ enum htp_data_type {
HTP_TYPE_BF16 = 30,
HTP_TYPE_MXFP4 = 39,
HTP_TYPE_NVFP4 = 40,
- HTP_TYPE_Q1_0 = 41,
- HTP_TYPE_Q2_0 = 42,
+ HTP_TYPE_Q1_0 = 41,
+ HTP_TYPE_Q2_0 = 42,
+ HTP_TYPE_F8_E4M3 = 43,
HTP_TYPE_INVALID
};
@@ -130,6 +131,7 @@ enum htp_op_code {
HTP_OP_SSM_SCAN,
HTP_OP_TIMESTEP_EMBEDDING,
HTP_OP_MUL_MAT_NX_GLU,
+ HTP_OP_MUL_ID,
HTP_OP_INVALID
};
diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.h b/ggml/src/ggml-hexagon/htp/htp-tensor.h
index 23122959d..9d2de3081 100644
--- a/ggml/src/ggml-hexagon/htp/htp-tensor.h
+++ b/ggml/src/ggml-hexagon/htp/htp-tensor.h
@@ -12,8 +12,9 @@
#define HTP_TENSOR_TILE_N_COLS 32
#define HTP_TENSOR_TILE_N_ROWS 32
-#define HTP_TENSOR_TILE_SIZE_F16 2048
-#define HTP_TENSOR_TILE_SIZE_Q4_0 576
+#define HTP_TENSOR_TILE_SIZE_F16 2048
+#define HTP_TENSOR_TILE_SIZE_F8_E4M3 1024
+#define HTP_TENSOR_TILE_SIZE_Q4_0 576
#define HTP_TENSOR_TILE_SIZE_Q4_1 640
#define HTP_TENSOR_TILE_SIZE_Q5_0 704
#define HTP_TENSOR_TILE_SIZE_Q5_1 768
@@ -36,7 +37,7 @@
#define HTP_TENSOR_TILE_K_Q2_0 64
#define HTP_TENSOR_TILE_SIZE_Q2_0 576
-// Tiled weight tensor layouts (Q4_0, Q5_0, Q5_1, Q8_0, IQ4_NL, MXFP4, NVFP4, IQ2_XXS, Q1_0, Q2_0, K-quants):
+// Tiled weight tensor layouts (Q4_0, Q5_0, Q5_1, Q8_0, IQ4_NL, MXFP4, NVFP4, F8_E4M3, IQ2_XXS, Q1_0, Q2_0, K-quants):
// See docs/backend/snapdragon/developer.md ("Tiled Weight Formats").
struct htp_tensor_mdev_range {
@@ -115,8 +116,9 @@ static inline uint32_t htp_tensor_get_tile_size(int type) {
case HTP_TYPE_MXFP4: return HTP_TENSOR_TILE_SIZE_MXFP4;
case HTP_TYPE_NVFP4: return HTP_TENSOR_TILE_SIZE_NVFP4;
case HTP_TYPE_IQ2_XXS: return HTP_TENSOR_TILE_SIZE_IQ2_XXS;
- case HTP_TYPE_F16: return HTP_TENSOR_TILE_SIZE_F16;
- default: return 0;
+ case HTP_TYPE_F16: return HTP_TENSOR_TILE_SIZE_F16;
+ case HTP_TYPE_F8_E4M3: return HTP_TENSOR_TILE_SIZE_F8_E4M3;
+ default: return 0;
}
}
@@ -143,6 +145,7 @@ static inline uint32_t htp_tensor_get_row_size(int type, uint32_t ne00) {
case HTP_TYPE_F32: return ne00 * 4;
case HTP_TYPE_F16:
case HTP_TYPE_BF16: return ne00 * 2;
+ case HTP_TYPE_F8_E4M3: return ne00;
case HTP_TYPE_Q8_0: return (ne00 / 32) * 34;
case HTP_TYPE_Q4_0:
case HTP_TYPE_IQ4_NL: return (ne00 / 32) * 18;
diff --git a/ggml/src/ggml-hexagon/htp/hvx-base.h b/ggml/src/ggml-hexagon/htp/hvx-base.h
index dd5a36b1d..758d544f5 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-base.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-base.h
@@ -166,6 +166,31 @@ static inline HVX_Vector hvx_vec_f32_to_f16(HVX_Vector v0, HVX_Vector v1) {
return Q6_Vh_vdeal_Vh(hvx_vec_f32_to_f16_shuff(v0, v1));
}
+static inline HVX_Vector hvx_vec_f32_to_f16_clamped(HVX_Vector v0, HVX_Vector v1) {
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0));
+ v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1));
+ return hvx_vec_f32_to_f16(v0, v1);
+}
+
+// Multiply 64 F16 lanes to F32: lo = lanes 0..31, hi = lanes 32..63
+static inline HVX_VectorPair hvx_vec_mul_f16_f16_to_f32_pair(HVX_Vector v1, HVX_Vector v2) {
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair p = Q6_Wsf_vmpy_VhfVhf(v1, v2);
+ return Q6_W_vshuff_VVR(Q6_V_hi_W(p), Q6_V_lo_W(p), -4);
+#else
+ HVX_VectorPair p = Q6_Wqf32_vmpy_VhfVhf(v1, v2);
+ HVX_Vector hi = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p));
+ HVX_Vector lo = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p));
+ return Q6_W_vshuff_VVR(hi, lo, -4);
+#endif
+}
+
+static inline HVX_Vector hvx_vec_mul_f16_f16_to_f32_lower32(HVX_Vector v1, HVX_Vector v2) {
+ return Q6_V_lo_W(hvx_vec_mul_f16_f16_to_f32_pair(v1, v2));
+}
+
#if __HVX_ARCH__ >= 79
static inline HVX_VectorPair hvx_vec_f16_to_f32_shuff(HVX_Vector v) {
const HVX_Vector one = hvx_vec_splat_f16(1.0);
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 1b4784665..ba5d3ac36 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h
@@ -265,18 +265,6 @@ static void quantize_row_f32_q8_1_s16_tiled(float * restrict x, uint8_t * restri
}
}
-static inline HVX_Vector hvx_vec_reduce_abs_max_half_f16(HVX_Vector v) {
- HVX_Vector m = hvx_vec_abs_f16(v);
- m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 2));
- m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 4));
- m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 8));
- m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 16));
- m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 32));
- HVX_Vector m_lo = hvx_vec_repl_f16(m);
- HVX_Vector m_hi = hvx_vec_repl_f16(Q6_V_vror_VR(m, 64));
- return Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), m_lo, m_hi);
-}
-
__attribute__((always_inline))
static inline void quantize_block_f16_q8_1_tiled_impl(const __fp16 * restrict x, uint8_t * restrict y_block, const bool sums16,
const __fp16 * restrict x_sb) {
@@ -581,41 +569,6 @@ static void quantize_row_f16_f16_tiled(const __fp16 * restrict x, uint8_t * rest
// Dot kernels & helpers that consume tiled activations
-static inline HVX_Vector hvx_vec_mul_f16_f16_to_f32_lower32(HVX_Vector v1, HVX_Vector v2) {
-#if __HVX_ARCH__ >= 79
- HVX_VectorPair p = Q6_Wsf_vmpy_VhfVhf(v1, v2);
- return Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(p), Q6_V_lo_W(p), -4));
-#else
- HVX_VectorPair p = Q6_Wqf32_vmpy_VhfVhf(v1, v2);
- HVX_Vector hi = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p));
- HVX_Vector lo = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p));
- return Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -4));
-#endif
-}
-
-// both halves of hvx_vec_mul_f16_f16_to_f32_lower32: lo = products of lanes 0..31, hi = lanes 32..63
-static inline HVX_VectorPair hvx_vec_mul_f16_f16_to_f32_pair(HVX_Vector v1, HVX_Vector v2) {
-#if __HVX_ARCH__ >= 79
- HVX_VectorPair p = Q6_Wsf_vmpy_VhfVhf(v1, v2);
- return Q6_W_vshuff_VVR(Q6_V_hi_W(p), Q6_V_lo_W(p), -4);
-#else
- HVX_VectorPair p = Q6_Wqf32_vmpy_VhfVhf(v1, v2);
- HVX_Vector hi = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(p));
- HVX_Vector lo = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(p));
- return Q6_W_vshuff_VVR(hi, lo, -4);
-#endif
-}
-
-static inline HVX_Vector unpack_q1_0_group(
- HVX_Vector v_plane,
- int g,
- HVX_Vector v_neg_one,
- HVX_Vector v_pos_one
-) {
- HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << g);
- return Q6_V_vmux_QVV(q, v_pos_one, v_neg_one);
-}
-
static inline HVX_Vector accum_q1_0_32x1(
HVX_Vector v_plane,
const HVX_Vector * restrict v_act,
@@ -785,12 +738,6 @@ static inline HVX_VectorPair accum_q8_0_32x2(
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
-// Q5_K: OR 0x10 into every lane of v whose flag j is set in the plane (see HTP_TENSOR_TILE_SIZE_Q5_K)
-static inline HVX_Vector hvx_q5k_or_hibit(HVX_Vector v, HVX_Vector v_plane, int j) {
- HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
- return Q6_V_vandor_VQR(v, q, 0x10101010);
-}
-
static inline HVX_Vector accum_5bit_32x1(
const HVX_Vector * restrict vptr,
const HVX_Vector * restrict v_act
@@ -838,12 +785,6 @@ static inline HVX_VectorPair accum_5bit_32x2(
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
-// OR 0xF0 into every lane of v whose flag j is set in the plane, i.e. 4-bit value | 0xF0 = q - 16 where the 5th bit is clear (Q5_0)
-static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j) {
- HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
- return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0);
-}
-
static inline HVX_Vector accum_q5_0_32x1(
const HVX_Vector * restrict vptr,
const HVX_Vector * restrict v_act
@@ -891,14 +832,6 @@ static inline HVX_VectorPair accum_q5_0_32x2(
return Q6_W_vcombine_VV(v_sum1, v_sum0);
}
-// Q6_K weights are stored unsigned (0..63), see HTP_TENSOR_TILE_SIZE_Q6_K. Unpack k-group g of a tile to signed bytes (q - 32)
-static inline HVX_Vector unpack_q6_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_0f, HVX_Vector mask_03, HVX_Vector i32) {
- HVX_Vector v_lo = (g & 1) ? Q6_Vub_vlsr_VubR(vptr[g >> 1], 4) : Q6_V_vand_VV(vptr[g >> 1], mask_0f);
- HVX_Vector v_hi = (g & 3) ? Q6_Vub_vlsr_VubR(vptr[4 + (g >> 2)], 2 * (g & 3)) : vptr[4 + (g >> 2)];
- HVX_Vector v_q = Q6_V_vor_VV(v_lo, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_hi, mask_03), 4));
- return Q6_Vb_vsub_VbVb(v_q, i32);
-}
-
// k 0..15 and k 16..31 of a Q6_K tile have different scales: lo half of the pair sums k 0..15, hi half sums k 16..31
static inline HVX_VectorPair accum_q6_k_32x1(
const HVX_Vector * restrict vptr,
@@ -958,24 +891,6 @@ static inline HVX_Vector scale_q6_k_32x1(HVX_VectorPair v_sums, HVX_Vector v_sca
return hvx_vec_add_f32_f32(v_lo, v_hi);
}
-// Q3_K / Q2_K: low 2 bits of k-group g, see HTP_TENSOR_TILE_SIZE_Q3_K
-static inline HVX_Vector unpack_q3_k_low2(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
- HVX_Vector v = vptr[g >> 2];
- if ((g & 3) == 3) {
- return Q6_Vub_vlsr_VubR(v, 6);
- }
- if (g & 3) {
- v = Q6_Vub_vlsr_VubR(v, 2 * (g & 3));
- }
- return Q6_V_vand_VV(v, mask_03);
-}
-
-// Q3_K k-group g as signed bytes: low2 | 0xFC (= low2 - 4) where bit g of vector 2 is set
-static inline HVX_Vector unpack_q3_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
- HVX_VectorPred q_neg = Q6_Q_vand_VR(vptr[2], 0x01010101u << g);
- return Q6_V_vandor_VQR(unpack_q3_k_low2(vptr, g, mask_03), q_neg, 0xFCFCFCFC);
-}
-
// same half split as accum_q6_k_32x1
static inline HVX_VectorPair accum_q3_k_32x1(
const HVX_Vector * restrict vptr,
@@ -1117,33 +1032,6 @@ static inline void accum_q2_0_32x2(
*v_sum1 = Q6_Vw_vadd_VwVw(v_sum1_lo, v_sum1_hi);
}
-// Q2_K: fp16 d (*v_d) and -dmin (*v_m) of the 32 rows of a super-block (8 tiles, VTCM stride 384), each in both vector halves
-static inline void q2_k_load_dmin(const uint8_t * restrict sb, HVX_Vector * restrict v_d, HVX_Vector * restrict v_m) {
- HVX_Vector v_dd = Q6_V_vzero(); // lanes 0..31: d, lanes 32..63: -dmin
-
- #pragma unroll
- for (int j = 0; j < 8; j++) {
- HVX_Vector v = hvx_vmem(sb + j * 384 + 256); // the slice is at bytes 64..79
- v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(16 * j), v_dd, Q6_V_vror_VR(v, (64 - 16 * j) & 127));
- }
-
- HVX_VectorPred q_lo = Q6_Q_vsetq_R(64);
- HVX_Vector v_r = Q6_V_vror_VR(v_dd, 64);
- *v_d = Q6_V_vmux_QVV(q_lo, v_dd, v_r);
- *v_m = Q6_V_vmux_QVV(q_lo, v_r, v_dd);
-}
-
-// Q2_K: fp16 D = d * scale and M = -dmin * min of a tile from its scale bytes, in the lanes of the Q6_K scales
-static inline void q2_k_unpack_scales(const uint8_t * restrict tile, HVX_Vector v_d, HVX_Vector v_m,
- HVX_Vector * restrict v_D, HVX_Vector * restrict v_M) {
- HVX_Vector v_sc = hvx_vmem(tile + 256);
- HVX_Vector v_l = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_V_vand_VV(v_sc, Q6_Vb_vsplat_R(0x0F))));
- HVX_Vector v_mn = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_Vub_vlsr_VubR(v_sc, 4)));
- // qf32 product: rounds like GGML_FP32_TO_FP16(d * scale) (qf16 is off by 1 ulp for many values on v73)
- *v_D = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_l), v_d));
- *v_M = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_mn), v_m));
-}
-
// Q2_K scale and min nibbles of a tile as halfword pairs: word r = sub-block 1 << 16 | sub-block 0 of row r
static inline void q2_k_scale_pairs(const uint8_t * restrict tile, HVX_Vector * restrict v_sc2, HVX_Vector * restrict v_mn2) {
HVX_Vector v_h = Q6_Vh_vshuff_Vh(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile + 256))));
@@ -1213,6 +1101,40 @@ static __attribute__((noinline)) void hvx_tiled_store_row_f16_f16(void * restric
hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
}
+static __attribute__((noinline)) void hvx_tiled_store_row_f32_scale(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vmemu(sz));
+ hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
+}
+
+static __attribute__((noinline)) void hvx_tiled_store_row_f16_scale(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vmemu(sz));
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum));
+ hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
+}
+
+static __attribute__((noinline)) void hvx_tiled_store_row_f32_scale_scalar(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vec_repl4(hvx_vmemu(sz)));
+ hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum);
+}
+
+static __attribute__((noinline)) void hvx_tiled_store_row_f16_scale_scalar(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) {
+ v_sum = hvx_vec_mul_f32_f32(v_sum, hvx_vec_repl4(hvx_vmemu(sz)));
+ const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f);
+ const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f);
+ v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum));
+ hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero()));
+}
+
+static inline hvx_tiled_store_row_fn_t resolve_hvx_tiled_store_row_scaled_fn(uint32_t dst_elem_size, bool scalar_scale) {
+ const bool dst_f16 = (dst_elem_size == sizeof(__fp16));
+ if (dst_f16) {
+ return scalar_scale ? hvx_tiled_store_row_f16_scale_scalar : hvx_tiled_store_row_f16_scale;
+ }
+ return scalar_scale ? hvx_tiled_store_row_f32_scale_scalar : hvx_tiled_store_row_f32_scale;
+}
+
static inline hvx_tiled_store_row_fn_t resolve_hvx_tiled_store_row_fn(uint32_t dst_elem_size, bool has_bias, uint32_t bias_elem_size) {
const bool dst_f16 = (dst_elem_size == sizeof(__fp16));
const bool bias_f16 = (bias_elem_size == sizeof(__fp16));
@@ -1958,108 +1880,6 @@ static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, void * restrict s0, void
store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-#define IQ2XXS_GROUPS 4 // 8-element grid entries per tile row
-#define IQ2XXS_TILES_PER_SB 8 // 256 / 32
-#define IQ2XXS_CODE_SHIFT 1 // log2(2 B per grid code)
-#define IQ2XXS_WORD_BYTES 4
-#define IQ2XXS_IDX_BITS 8
-#define IQ2XXS_IDX_MASK 0xFF
-#define IQ2XXS_SIGN_BITS 7
-#define IQ2XXS_SIGN_MASK 0x7F
-#define IQ2XXS_PARITY_SHIFT 7
-#define IQ2XXS_SCALE_SHIFT 28
-#define IQ2XXS_D_SLICE_OFF 256 // 4 fp16 d of the tile, after the 32 rows x 8 B
-#define IQ2XXS_D_SCALE 0.125f // db = d * (2 * scale + 1) / 8
-#define IQ2XXS_D_SLICE_BYTES 8
-#define IQ2XXS_SIGN_PRED_LO 0x08040201 // sign bit of bytes 0..3 of an 8-element group
-#define IQ2XXS_SIGN_PRED_HI 0x80402010 // sign bit of bytes 4..7
-#define IQ2XXS_IDX_LO_MASK 0x1FE // index byte << 1, halfword 0 of a lane
-#define IQ2XXS_IDX_HI_MASK 0x1FE0000 // index byte << 1, halfword 1 of a lane
-#define IQ2XXS_NIB_LO_MASK 0x00000F0F // nibbles of the code bytes, lane bytes 0..1
-#define IQ2XXS_NIB_HI_MASK 0x0F0F0000 // nibbles of the code bytes, lane bytes 2..3
-
-static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) {
- return (HVX_Vector *) (tile + htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS) - HTP_TENSOR_TILE_SCRATCH_IQ2_XXS);
-}
-
-// IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words
-static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) {
- HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
- const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES;
-
- // lo: 4 grid indices per row, hi: 4 sign indices + scale per row
- HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES);
- HVX_Vector v_idx = Q6_V_lo_W(p);
-
- // one halfword gather per 2 groups: lane i gets the codes of groups 2h and 2h+1 in halfwords 0 and 1
- HVX_Vector v_off0 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
- Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
- HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
- Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
- Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0);
- Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1);
-
- return Q6_V_hi_W(p);
-}
-
-// IQ2_XXS: wait for the gathers of iq2xxs_gather_issue and read the grid codes
-static inline void iq2xxs_gather_wait(const uint8_t * restrict tile, HVX_Vector * restrict v_c) {
- HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
- hvx_gather_sync(&v_scr[1]);
- v_c[0] = v_scr[0];
- v_c[1] = v_scr[1];
-}
-
-// IQ2_XXS: 8 int8 weight words (k = 4g..4g+3 per row lane) and the odd group scale (2 * scale + 1) of a 32x32 tile
-static inline void iq2xxs_decode_expand(const HVX_Vector * restrict v_c, HVX_Vector v_sgn, HVX_Vector * restrict v_w, HVX_Vector * restrict v_ls) {
- const HVX_Vector v_zero = Q6_V_vzero();
- const HVX_Vector v_one = Q6_V_vsplat_R(1);
- const HVX_Vector v_sgn_mask = Q6_V_vsplat_R(IQ2XXS_SIGN_MASK);
- const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut);
-
- #pragma unroll
- for (int l = 0; l < IQ2XXS_GROUPS; l++) {
- // 7 stored sign bits + even-parity bit
- HVX_Vector v_s7 = Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SIGN_BITS * l), v_sgn_mask);
- HVX_Vector v_t = Q6_Vh_vpopcount_Vh(v_s7);
- HVX_Vector v_s = Q6_V_vor_VV(v_s7, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_t, v_one), IQ2XXS_PARITY_SHIFT));
- HVX_Vector v_s16 = Q6_V_vor_VV(v_s, Q6_Vw_vasl_VwR(v_s, 8));
- HVX_Vector v_rep = Q6_V_vor_VV(v_s16, Q6_Vw_vasl_VwR(v_s16, 16));
- HVX_VectorPred q_lo = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_LO);
- HVX_VectorPred q_hi = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_HI);
-
- HVX_Vector v_c2 = v_c[l >> 1];
- // code halfword duplicated in both halves of each lane
- HVX_Vector v_d = (l & 1) ? Q6_Vh_vshuffo_VhVh(v_c2, v_c2) : Q6_Vh_vshuffe_VhVh(v_c2, v_c2);
- // lane bytes: nibbles 0, 2, 1, 3 of the code, so vlut16 returns elements 0..3 / 4..7 as words
- HVX_Vector v_n = Q6_V_vor_VV(Q6_V_vand_VV(v_d, Q6_V_vsplat_R(IQ2XXS_NIB_LO_MASK)),
- Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_d, 4), Q6_V_vsplat_R(IQ2XXS_NIB_HI_MASK)));
- HVX_VectorPair p_g = Q6_Wh_vlut16_VbVhR(v_n, v_nib_lut, 0);
- HVX_Vector v_g0 = Q6_V_lo_W(p_g);
- HVX_Vector v_g1 = Q6_V_hi_W(p_g);
-
- v_w[2 * l + 0] = Q6_V_vmux_QVV(q_lo, Q6_Vb_vsub_VbVb(v_zero, v_g0), v_g0);
- v_w[2 * l + 1] = Q6_V_vmux_QVV(q_hi, Q6_Vb_vsub_VbVb(v_zero, v_g1), v_g1);
- }
-
- *v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SCALE_SHIFT), 1), v_one);
-}
-
-// IQ2_XXS: fp16 d of the 32 rows of a super-block (8 tiles) in halfword lanes 0..31
-static inline HVX_Vector iq2xxs_gather_d(const uint8_t * restrict sb) {
- const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
- HVX_Vector v_dd = Q6_V_vzero();
-
- #pragma unroll
- for (int j = 0; j < IQ2XXS_TILES_PER_SB; j++) {
- HVX_Vector v = hvx_vmem(sb + j * padded + IQ2XXS_D_SLICE_OFF);
- v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(IQ2XXS_D_SLICE_BYTES * j), v_dd,
- Q6_V_vror_VR(v, (VLEN - IQ2XXS_D_SLICE_BYTES * j) & (VLEN - 1)));
- }
-
- return v_dd;
-}
-
// IQ2_XXS: fp32 d / 8 of the 32 rows of a super-block (8 tiles) in lanes 0..31
static inline HVX_Vector iq2xxs_load_d(const uint8_t * restrict sb) {
// db = d * (0.5 + scale) * 0.25 = d * (2 * scale + 1) / 8
@@ -2246,29 +2066,6 @@ static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, void * restrict s0, void
store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
-#define NVFP4_SCALE_OFF 512 // UE4M3 scales after the 32 rows x 16 B of quants
-#define NVFP4_UE4M3_MASK 0x7F // code bits; 0x7F is the NaN code, decoded as 0
-#define NVFP4_UE4M3_MIN_NORMAL 0x08 // exponent field 1
-#define NVFP4_UE4M3_MAN_SHIFT 20 // 23 - 3 mantissa bits
-#define NVFP4_UE4M3_REBIAS 0x3C000000 // (127 - 7) << 23
-#define NVFP4_UE4M3_SUB_SCALE 0x1p-9f // subnormal: mantissa * 2^-9
-#define NVFP4_VECS_PER_GROUP 2 // quant vectors per scale group
-#define NVFP4_ACT_PER_GROUP 4 // activation vectors per scale group
-
-// UE4M3 codes in the low byte of each word -> fp32 (without the 0.5 of kvalues_mxfp4)
-static inline HVX_Vector nvfp4_ue4m3_to_f32(HVX_Vector v_code) {
- HVX_Vector v_mask = Q6_V_vsplat_R(NVFP4_UE4M3_MASK);
- HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask);
-
- HVX_Vector v_norm = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(v_x, NVFP4_UE4M3_MAN_SHIFT), Q6_V_vsplat_R(NVFP4_UE4M3_REBIAS));
- HVX_Vector v_sub = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vw(v_x), hvx_vec_splat_f32(NVFP4_UE4M3_SUB_SCALE));
-
- HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VwVw(Q6_V_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x);
- HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VwVw(v_x, v_mask);
-
- return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm));
-}
-
// fp32 scales of the two 16-element sub-blocks of a tile, one lane per row
static inline void nvfp4_load_scales(const uint8_t * restrict tile, HVX_Vector * restrict v_d0, HVX_Vector * restrict v_d1) {
HVX_VectorPair v_code = Q6_Wuw_vunpack_Vuh(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile + NVFP4_SCALE_OFF))));
@@ -2391,6 +2188,54 @@ static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, void * restrict s0, void
store_row(s1, valid_rows, v_sum_float_c1, sz1);
}
+static void tiled_vec_dot_f8_e4m3_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) {
+ const HVX_Vector * restrict vptr = (const HVX_Vector *) vx;
+ const HVX_Vector * restrict v_act = (const HVX_Vector *) vy;
+ const uint32_t n_vecs = ((n + 31) / 32) * 8;
+
+ HVX_VectorPair acc = Q6_W_vzero();
+
+ for (uint32_t i = 0; i < n_vecs; i++) {
+ HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(vptr[i]);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -4);
+ HVX_Vector v_w0 = f8_e4m3_to_f16(Q6_V_lo_W(vp_k));
+ HVX_Vector v_w1 = f8_e4m3_to_f16(Q6_V_hi_W(vp_k));
+ acc = hvx_vec_mpyacc_f32_f16(acc, v_w0, v_act[2 * i + 0]);
+ acc = hvx_vec_mpyacc_f32_f16(acc, v_w1, v_act[2 * i + 1]);
+ }
+
+ HVX_Vector v_sum = hvx_vec_add_f32_f32(Q6_V_lo_W(acc), Q6_V_hi_W(acc));
+
+ store_row(s, valid_rows, v_sum, sz);
+}
+
+static void tiled_vec_dot_f8_e4m3_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) {
+ const HVX_Vector * restrict vptr = (const HVX_Vector *) vx;
+ const HVX_Vector * restrict v_act0 = (const HVX_Vector *) vy0;
+ const HVX_Vector * restrict v_act1 = (const HVX_Vector *) vy1;
+ const uint32_t n_vecs = ((n + 31) / 32) * 8;
+
+ HVX_VectorPair acc0 = Q6_W_vzero();
+ HVX_VectorPair acc1 = Q6_W_vzero();
+
+ for (uint32_t i = 0; i < n_vecs; i++) {
+ HVX_VectorPair vp_u16 = Q6_Wuh_vunpack_Vub(vptr[i]);
+ HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_u16), Q6_V_lo_W(vp_u16), -4);
+ HVX_Vector v_w0 = f8_e4m3_to_f16(Q6_V_lo_W(vp_k));
+ HVX_Vector v_w1 = f8_e4m3_to_f16(Q6_V_hi_W(vp_k));
+ acc0 = hvx_vec_mpyacc_f32_f16(acc0, v_w0, v_act0[2 * i + 0]);
+ acc1 = hvx_vec_mpyacc_f32_f16(acc1, v_w0, v_act1[2 * i + 0]);
+ acc0 = hvx_vec_mpyacc_f32_f16(acc0, v_w1, v_act0[2 * i + 1]);
+ acc1 = hvx_vec_mpyacc_f32_f16(acc1, v_w1, v_act1[2 * i + 1]);
+ }
+
+ HVX_Vector v_sum0 = hvx_vec_add_f32_f32(Q6_V_lo_W(acc0), Q6_V_hi_W(acc0));
+ HVX_Vector v_sum1 = hvx_vec_add_f32_f32(Q6_V_lo_W(acc1), Q6_V_hi_W(acc1));
+
+ store_row(s0, valid_rows, v_sum0, sz0);
+ store_row(s1, valid_rows, v_sum1, sz1);
+}
+
static void tiled_vec_dot_f16_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) {
const HVX_Vector * restrict vptr = (const HVX_Vector *) vx;
const HVX_Vector * restrict v_act = (const HVX_Vector *) vy;
diff --git a/ggml/src/ggml-hexagon/htp/hvx-reduce.h b/ggml/src/ggml-hexagon/htp/hvx-reduce.h
index 1b6a6f133..ad31a2c9e 100644
--- a/ggml/src/ggml-hexagon/htp/hvx-reduce.h
+++ b/ggml/src/ggml-hexagon/htp/hvx-reduce.h
@@ -8,6 +8,7 @@
#include "hex-utils.h"
#include "hvx-base.h"
+#include "hvx-repl.h"
#include "hvx-types.h"
static inline HVX_Vector hvx_vec_reduce_sum_n_i32(HVX_Vector in, unsigned int n) {
@@ -399,6 +400,19 @@ static inline void hvx_argmax_f32(
*out_idx = best_idx;
}
+// Reduce abs-max independently across low 32 and high 32 F16 lanes
+static inline HVX_Vector hvx_vec_reduce_abs_max_half_f16(HVX_Vector v) {
+ HVX_Vector m = hvx_vec_abs_f16(v);
+ m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 2));
+ m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 4));
+ m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 8));
+ m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 16));
+ m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 32));
+ HVX_Vector m_lo = hvx_vec_repl_f16(m);
+ HVX_Vector m_hi = hvx_vec_repl_f16(Q6_V_vror_VR(m, 64));
+ return Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), m_lo, m_hi);
+}
+
#undef hvx_reduce_loop_body
#undef HVX_REDUCE_MAX_OP
#undef HVX_REDUCE_SUM_OP
diff --git a/ggml/src/ggml-hexagon/htp/im2col-ops.c b/ggml/src/ggml-hexagon/htp/im2col-ops.c
index 8bba8dede..7575bf7c2 100644
--- a/ggml/src/ggml-hexagon/htp/im2col-ops.c
+++ b/ggml/src/ggml-hexagon/htp/im2col-ops.c
@@ -38,7 +38,6 @@ struct htp_im2col_context {
uint32_t pe_gather_nvec; // vectors per gathered patch (KH == 1 blocked path)
// Precomputed dimensions for worker threads
- uint32_t N;
uint32_t IC;
uint32_t ID, IH, IW;
uint32_t KD, KH, KW;
@@ -970,7 +969,6 @@ int op_im2col(struct htp_ops_context * octx) {
ictx.pe_owb = kparams->owb;
ictx.pe_wb = kparams->wb;
ictx.pe_nbpr = kparams->nbpr;
- ictx.N = kparams->N;
ictx.IC = kparams->IC;
ictx.ID = kparams->ID;
ictx.IH = kparams->IH;
@@ -1069,7 +1067,6 @@ int op_im2col_3d(struct htp_ops_context * octx) {
ictx.pe_owb = kparams->owb;
ictx.pe_wb = kparams->wb;
ictx.pe_nbpr = kparams->nbpr;
- ictx.N = kparams->N;
ictx.IC = kparams->IC;
ictx.ID = kparams->ID;
ictx.IH = kparams->IH;
diff --git a/ggml/src/ggml-hexagon/htp/im2col-ops.h b/ggml/src/ggml-hexagon/htp/im2col-ops.h
index d845f6cf1..6f6871359 100644
--- a/ggml/src/ggml-hexagon/htp/im2col-ops.h
+++ b/ggml/src/ggml-hexagon/htp/im2col-ops.h
@@ -58,7 +58,6 @@ struct htp_im2col_kernel_params {
uint32_t wb;
uint32_t nbpr;
- uint32_t N;
uint32_t IC;
uint32_t ID, IH, IW;
uint32_t KD, KH, KW;
diff --git a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c
index 1d3f85e61..1021fa503 100644
--- a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c
+++ b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c
@@ -16,7 +16,7 @@
#include "hvx-quant.h"
#include "hvx-fa-kernels.h"
#include "hmx-utils.h"
-#include "hmx-fa-kernels.h"
+#include "hmx-fa-fp16-kernels.h"
#include "hmx-queue.h"
#include "lightning-indexer-ops.h"
diff --git a/ggml/src/ggml-hexagon/htp/main.c b/ggml/src/ggml-hexagon/htp/main.c
index a944d7c51..34fa37330 100644
--- a/ggml/src/ggml-hexagon/htp/main.c
+++ b/ggml/src/ggml-hexagon/htp/main.c
@@ -966,6 +966,7 @@ static int execute_op(struct htp_ops_context * octx) {
case HTP_OP_SUB:
case HTP_OP_DIV:
case HTP_OP_ADD_ID:
+ case HTP_OP_MUL_ID:
return op_binary(octx);
case HTP_OP_NORM:
diff --git a/ggml/src/ggml-hexagon/htp/matmul-hmx-f16.c b/ggml/src/ggml-hexagon/htp/matmul-hmx-f16.c
new file mode 100644
index 000000000..70a0e02e5
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-hmx-f16.c
@@ -0,0 +1,2859 @@
+#include "matmul-hmx-f16.h"
+#include "hmx-mm-f16-kernels.h"
+
+// --- F16 HMX Threaded Helpers ---
+
+static void hmx_f16_dequant_weight_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ tiled_dequantize_state_t * state = (tiled_dequantize_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 < (unsigned int) state->n_tasks; task_id += n) {
+ 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);
+}
+
+static void hmx_f16_transfer_output_row_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ output_transfer_task_state_t * st = (output_transfer_task_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ int start_chunk_idx = i * st->n_chunks_per_task;
+ 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) {
+ 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);
+
+ 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,
+ st->w_scale, st->w_scale_c_mask);
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, start_chunk_idx);
+}
+
+typedef struct {
+ __fp16 * dst;
+ dma_addr_t act_dma_addr;
+ float * vtcm_f32_act;
+ uint32_t n_tasks;
+ uint32_t n_tot_chunks;
+ uint32_t n_chunks_per_task;
+ uint32_t k_block;
+ uint32_t k_stride;
+ uint32_t k_valid;
+ size_t vtcm_f32_act_bytes_per_hvx;
+ uint32_t step_rows;
+ uint32_t step_rows_shift;
+ uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
+ const float * vtcm_norm;
+ float norm_eps;
+} hmx_f16_act_state_t;
+
+typedef struct {
+ __fp16 * dst;
+ dma_addr_t act_dma_addr;
+ float * vtcm_f32_act;
+ uint32_t n_rows;
+ uint32_t k_block;
+ uint32_t k_stride;
+ uint32_t k_valid;
+ uint32_t n_col_chunks;
+ struct fastdiv_values n_hvx_div;
+ size_t vtcm_f32_act_bytes;
+ uint32_t step_rows;
+ uint32_t step_rows_shift;
+ uint32_t act_elem_size;
+} hmx_f16_act_col_state_t;
+
+static void hmx_f16_transfer_act_col_chunk(
+ dma_queue * dma_q,
+ __fp16 * restrict vtcm_dst,
+ dma_addr_t act_dma_addr,
+ uint32_t n_rows,
+ uint32_t k_block,
+ uint32_t k_stride,
+ uint32_t k_chunk_valid,
+ uint32_t c_first,
+ uint32_t c_len,
+ uint8_t * act_spad,
+ uint32_t act_elem_size,
+ struct htp_thread_trace * tr,
+ uint32_t step_rows,
+ uint32_t step_rows_shift) {
+ const uint32_t R = step_rows;
+ const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ const uint32_t n_steps = n_rows_padded >> 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;
+
+ 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(act_spad, act_dma_addr + src_col_offset),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
+ }
+ 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);
+ 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 << step_rows_shift;
+ uint8_t * curr_buf = act_spad;
+
+ if (r < n_rows) {
+ curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
+ 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);
+
+ uint32_t next_s = s + 2;
+ uint32_t next_r = next_s << 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 * src_row_bytes + src_col_offset),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
+ }
+ }
+}
+
+static void hmx_f16_transfer_act_col_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ hmx_f16_act_col_state_t * st = (hmx_f16_act_col_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ uint32_t n_blocks = st->k_block / 32;
+ 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;
+
+ if (c_len == 0) {
+ return;
+ }
+
+ uint32_t k_chunk_valid = 0;
+ if (st->k_valid > c_first) {
+ k_chunk_valid = hex_smin(st->k_valid, c_last) - c_first;
+ }
+
+ 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;
+
+ hmx_f16_transfer_act_col_chunk(
+ th->dma_q, st->dst, st->act_dma_addr, st->n_rows, st->k_block, st->k_stride, k_chunk_valid,
+ c_first, c_len, act_spad, st->act_elem_size, tr, st->step_rows, st->step_rows_shift);
+}
+
+static void hmx_f16_transfer_act_rows(
+ dma_queue * dma_q,
+ __fp16 * restrict vtcm_dst,
+ dma_addr_t act_dma_addr,
+ uint32_t n_rows,
+ uint32_t k_block,
+ uint32_t k_stride,
+ uint32_t k_valid,
+ uint8_t * act_spad,
+ uint32_t act_elem_size,
+ const float * vtcm_norm,
+ float norm_eps,
+ struct htp_thread_trace * tr,
+ uint32_t step_rows,
+ uint32_t step_rows_shift) {
+ const uint32_t R = step_rows;
+ const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ const uint32_t n_steps = n_rows_padded >> step_rows_shift;
+
+ const bool act_is_f16 = (act_elem_size == sizeof(__fp16));
+ const size_t row_bytes = (size_t) k_block * act_elem_size;
+ const size_t src_row_bytes = (size_t) k_stride * act_elem_size;
+ const size_t width_bytes = (size_t) k_valid * act_elem_size;
+
+ 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(act_spad, act_dma_addr),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
+ }
+ 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);
+ 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 << step_rows_shift;
+ uint8_t * curr_buf = act_spad;
+
+ if (r < n_rows) {
+ curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst;
+ }
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
+ if (act_is_f16) {
+ if (vtcm_norm != NULL && r < n_rows) {
+ hvx_rms_norm_mul_rows_f16(curr_buf, row_bytes, hex_smin(n_rows - r, R), k_valid, vtcm_norm, norm_eps);
+ }
+ 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(vtcm_dst, pair_buf, pair_buf + k_block, row_idx, k_block, k_valid, r0_valid, r1_valid);
+ }
+ } else {
+ if (vtcm_norm != NULL && r < n_rows) {
+ hvx_rms_norm_mul_rows_f32(curr_buf, row_bytes, hex_smin(n_rows - r, R), k_valid, vtcm_norm, norm_eps);
+ }
+ 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(vtcm_dst, pair_buf, pair_buf + k_block, row_idx, k_block, k_valid, r0_valid, r1_valid);
+ }
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
+
+ uint32_t next_s = s + 2;
+ uint32_t next_r = next_s << 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 * src_row_bytes),
+ row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
+ }
+ }
+}
+
+static void hmx_f16_transfer_act_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ hmx_f16_act_state_t * st = (hmx_f16_act_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ 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);
+
+ __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 * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx;
+ hmx_f16_transfer_act_rows(
+ th->dma_q, dst, act_dma_addr, chunk_size, st->k_block, st->k_stride, st->k_valid, act_spad, st->act_elem_size,
+ st->vtcm_norm, st->norm_eps, tr, st->step_rows, st->step_rows_shift);
+ }
+}
+
+typedef struct {
+ const struct mmid_row_mapping * matrix_rows;
+ __fp16 * dst;
+ 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;
+ uint32_t mapping_stride;
+ uint32_t ne11;
+ struct fastdiv_values ne11_div;
+ size_t nb11;
+ size_t nb12;
+ uint32_t start_row;
+ uint32_t k_valid;
+} hmx_f16_act_gathered_state_t;
+
+static void hmx_f16_transfer_act_gathered_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ hmx_f16_act_gathered_state_t * st = (hmx_f16_act_gathered_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+ dma_queue * dma_q = th->dma_q;
+
+ const uint32_t vtcm_start_row = i * st->n_chunks_per_task;
+ if (vtcm_start_row >= st->mc_pad) {
+ return;
+ }
+ 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_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_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 = 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;
+
+ if (valid_rows > 0) {
+ if (!double_buf) {
+ push_gathered_act_rows(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_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 inline tiled_dequant_task_fn_t hmx_f16_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_F8_E4M3: return dequantize_tiled_weight_to_fp16_task_f8_e4m3;
+ 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;
+ case HTP_TYPE_Q5_1:
+ case HTP_TYPE_Q5_K: return dequantize_tiled_weight_to_fp16_task_q5_k;
+ case HTP_TYPE_Q6_K: return dequantize_tiled_weight_to_fp16_task_q6_k;
+ case HTP_TYPE_Q3_K: return dequantize_tiled_weight_to_fp16_task_q3_k;
+ case HTP_TYPE_Q2_K: return dequantize_tiled_weight_to_fp16_task_q2_k;
+ case HTP_TYPE_Q1_0: return dequantize_tiled_weight_to_fp16_task_q1_0;
+ case HTP_TYPE_Q2_0: return dequantize_tiled_weight_to_fp16_task_q2_0;
+ case HTP_TYPE_F16: return is_tiled ? NULL : convert_f16_weight_to_fp16_tiles_task;
+ case HTP_TYPE_BF16: return convert_bf16_weight_to_fp16_tiles_task;
+ case HTP_TYPE_F32: return quantize_f32_weight_to_fp16_tiles_task;
+ default: return NULL;
+ }
+}
+
+static inline bool hmx_f16_scales_in_dequant(int weight_type) {
+ return weight_type == HTP_TYPE_NVFP4 || weight_type == HTP_TYPE_F8_E4M3;
+}
+
+typedef struct {
+ __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;
+ const float * w_scale;
+ uint32_t w_scale_ct_stride;
+} hmx_f16_dequant_weight_params_t;
+
+static void hmx_f16_dequant_weight_chunk(
+ struct htp_ops_context * octx,
+ const hmx_f16_dequant_weight_params_t * p) {
+ if (!p->dequant_worker_fn) {
+ return;
+ }
+
+ assert(p->k_block % HTP_MM_HMX_TILE_N_COLS == 0);
+
+ const int n_hvx = (int) octx->n_hvx;
+ const size_t n_col_tiles = hmx_ceil_div(p->n_cols, HTP_MM_HMX_TILE_N_COLS);
+ const uint32_t n_weight_tiles = p->k_block / htp_tensor_get_tile_k(p->weight_type);
+ const size_t n_tot_tiles = n_col_tiles * n_weight_tiles;
+ if (n_tot_tiles == 0) {
+ return;
+ }
+
+ 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 = 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 = p->vtcm_dst;
+ state.src = (const uint8_t *) p->weight_src_ddr;
+ state.task_fn = (p->weight_type == HTP_TYPE_NVFP4 && p->w_scale) ? dequantize_tiled_weight_to_fp16_task_nvfp4_scaled
+ : (p->weight_type == HTP_TYPE_F8_E4M3 && p->w_scale) ? dequantize_tiled_weight_to_fp16_task_f8_e4m3_scaled
+ : p->dequant_worker_fn;
+ state.n_cols = p->n_cols;
+ state.k_block = p->k_block;
+ state.row_stride = p->row_stride;
+ state.weight_type = p->weight_type;
+ state.n_k_tiles = p->n_k_tiles;
+ state.n_weight_tiles = n_weight_tiles;
+ state.n_k_tiles_div = p->n_k_tiles_div;
+ state.w_scale = p->w_scale;
+ state.w_scale_ct_stride = p->w_scale_ct_stride;
+
+ 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;
+
+ work_queue_run(octx->ctx->hvx_queue, hmx_f16_dequant_weight_worker, &state, (int) state.n_tasks);
+}
+
+typedef struct {
+ hmx_fp16_output_col_chunk_fn_t col_chunk_fn;
+ void * dst;
+ const __fp16 * vtcm_src;
+ const void * bias;
+ const float * w_scale;
+ uint32_t w_scale_c_mask;
+ 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;
+} hmx_f16_output_col_state_t;
+
+static void hmx_f16_transfer_output_col_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ hmx_f16_output_col_state_t * st = (hmx_f16_output_col_state_t *) data;
+ struct htp_thread_trace * tr = th->trace;
+
+ 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)) {
+ 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 void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) c_first * st->bias_elem_size) : NULL;
+ const float * w_scale = st->w_scale ? (st->w_scale + (c_first & st->w_scale_c_mask)) : 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) {
+ 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,
+ w_scale, st->w_scale_c_mask);
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first);
+}
+
+typedef struct {
+ 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;
+ const float * w_scale;
+ uint32_t w_scale_c_mask;
+} hmx_f16_output_params_t;
+
+static void hmx_f16_transfer_output(
+ struct htp_ops_context * octx,
+ const hmx_f16_output_params_t * p) {
+ if (p->n_rows <= 0 || p->dst_cols <= 0) {
+ return;
+ }
+
+ const bool dst_aligned_nt = ((((uintptr_t) p->dst | ((size_t) p->dst_stride * p->dst_elem_size)) & 127u) == 0);
+ const hmx_fp16_output_col_chunk_fn_t col_chunk_fn =
+ resolve_fp16_output_col_chunk_fn(p->dst_elem_size, p->bias, p->bias_elem_size, dst_aligned_nt, p->w_scale);
+
+ const int n_hvx = (int) octx->n_hvx;
+ const uint32_t n_blocks = hmx_ceil_div((uint32_t) p->n_cols, 32);
+ const uint32_t n_units = (p->dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks;
+ const bool prefer_row_chunk = ((uint32_t) p->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) p->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) {
+ hmx_f16_output_col_state_t col_state;
+ col_state.col_chunk_fn = col_chunk_fn;
+ col_state.dst = p->dst;
+ col_state.bias = p->bias;
+ col_state.w_scale = p->w_scale;
+ col_state.w_scale_c_mask = p->w_scale_c_mask;
+ col_state.vtcm_src = p->vtcm_src;
+ col_state.n_rows = (uint32_t) p->n_rows;
+ col_state.n_cols = (uint32_t) p->n_cols;
+ col_state.dst_stride = (uint32_t) p->dst_stride;
+ col_state.bias_stride = p->bias_stride;
+ col_state.dst_cols = (uint32_t) p->dst_cols;
+ col_state.dst_elem_size = p->dst_elem_size;
+ col_state.bias_elem_size = p->bias_elem_size;
+ col_state.n_hvx_div = octx->n_hvx_div;
+
+ work_queue_run(octx->ctx->hvx_queue, hmx_f16_transfer_output_col_worker, &col_state, n_hvx);
+ return;
+ }
+ }
+
+ const uint32_t chunk_align = prefer_row_chunk ? 32u : 2u;
+ uint32_t n_chunks_per_task = (n_hvx <= 1) ? (uint32_t) p->n_rows
+ : fastdiv((uint32_t) p->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) p->n_rows + 1) >> 1);
+
+ output_transfer_task_state_t state;
+ state.col_chunk_fn = col_chunk_fn;
+ state.n_tasks = (uint32_t) actual_hvx;
+ state.n_tot_chunks = (uint32_t) p->n_rows;
+ state.n_chunks_per_task = n_chunks_per_task;
+ state.dst = p->dst;
+ state.bias = p->bias;
+ state.w_scale = p->w_scale;
+ state.w_scale_c_mask = p->w_scale_c_mask;
+ state.vtcm_src = p->vtcm_src;
+ state.n_cols = (uint32_t) p->n_cols;
+ state.dst_stride = (uint32_t) p->dst_stride;
+ state.bias_stride = p->bias_stride;
+ state.dst_cols = (uint32_t) p->dst_cols;
+ state.dst_elem_size = p->dst_elem_size;
+ state.bias_elem_size = p->bias_elem_size;
+
+ work_queue_run(octx->ctx->hvx_queue, hmx_f16_transfer_output_row_worker, &state, actual_hvx);
+}
+
+struct hmx_f16_act_params {
+ struct htp_context * ctx;
+ __fp16 * dst;
+ dma_addr_t act_dma_addr;
+ int n_rows;
+ int k_block;
+ int k_stride;
+ int n_hvx;
+ const struct fastdiv_values * act_hvx_div;
+ const struct fastdiv_values * k_div;
+ int k_valid;
+ float * vtcm_f32_act;
+ size_t vtcm_f32_act_bytes;
+ uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
+ const float * vtcm_norm;
+ float norm_eps;
+};
+
+static void hmx_f16_transfer_act(const struct hmx_f16_act_params * params) {
+ struct htp_context * ctx = params->ctx;
+ __fp16 * dst = params->dst;
+ const dma_addr_t act_dma_addr = params->act_dma_addr;
+ int n_rows = params->n_rows;
+ int k_block = params->k_block;
+ int k_stride = params->k_stride;
+ int n_hvx = params->n_hvx;
+ const struct fastdiv_values * act_hvx_div = params->act_hvx_div;
+ const struct fastdiv_values * k_div = params->k_div;
+ int k_valid = params->k_valid;
+ float * vtcm_f32_act = params->vtcm_f32_act;
+ size_t vtcm_f32_act_bytes = params->vtcm_f32_act_bytes;
+ const uint32_t act_elem_size = params->act_elem_size ? params->act_elem_size : (uint32_t) sizeof(float);
+
+ if (n_rows <= 0) {
+ return;
+ }
+
+ const size_t n_tasks = (n_rows + 31) >> 5;
+ 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 (!params->vtcm_norm && n_hvx > 1 && col_chunk_ok && n_tasks < (size_t) n_hvx) {
+ uint32_t step_rows = 2;
+ uint32_t step_rows_shift = 1;
+ if (vtcm_f32_act_bytes > 0) {
+ 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 step_rows_max = fastdiv(scratch_elems_per_hvx / 2, k_div);
+ if (step_rows_max >= 4) {
+ step_rows = 4;
+ step_rows_shift = 2;
+ }
+ }
+
+ hmx_f16_act_col_state_t col_state;
+ col_state.dst = dst;
+ col_state.act_dma_addr = act_dma_addr;
+ col_state.n_rows = n_rows;
+ col_state.k_block = k_block;
+ col_state.k_stride = k_stride;
+ col_state.k_valid = k_valid;
+ col_state.n_col_chunks = n_hvx;
+ col_state.n_hvx_div = *act_hvx_div;
+ col_state.vtcm_f32_act = vtcm_f32_act;
+ col_state.vtcm_f32_act_bytes = vtcm_f32_act_bytes;
+ col_state.step_rows = step_rows;
+ col_state.step_rows_shift = step_rows_shift;
+ col_state.act_elem_size = act_elem_size;
+
+ work_queue_run(ctx->hvx_queue, hmx_f16_transfer_act_col_worker, &col_state, n_hvx);
+ return;
+ }
+
+ assert(k_block % HTP_MM_HMX_TILE_N_COLS == 0 && k_stride % HTP_MM_HMX_TILE_N_COLS == 0);
+
+ size_t n_tot_chunks = n_rows;
+ size_t n_chunks_per_task = (n_hvx == 1) ? n_tot_chunks : 32;
+
+ hmx_f16_act_state_t state;
+ state.n_tasks = (n_hvx == 1) ? 1 : hmx_ceil_div(n_tot_chunks, 32);
+ state.n_tot_chunks = n_tot_chunks;
+ state.n_chunks_per_task = n_chunks_per_task;
+ state.dst = dst;
+ state.act_dma_addr = act_dma_addr;
+ state.k_block = k_block;
+ state.k_stride = k_stride;
+ state.k_valid = k_valid;
+ state.vtcm_f32_act = vtcm_f32_act;
+ state.act_elem_size = act_elem_size;
+ state.vtcm_norm = params->vtcm_norm;
+ state.norm_eps = params->norm_eps;
+
+ state.vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128);
+
+ uint32_t step_rows = 2;
+ uint32_t step_rows_shift = 1;
+ if (state.vtcm_f32_act_bytes_per_hvx > 0) {
+ size_t scratch_elems_per_hvx = state.vtcm_f32_act_bytes_per_hvx / act_elem_size;
+ size_t step_rows_max = fastdiv(scratch_elems_per_hvx / 2, k_div);
+ if (step_rows_max >= 4) {
+ step_rows = 4;
+ step_rows_shift = 2;
+ }
+ }
+ state.step_rows = step_rows;
+ state.step_rows_shift = step_rows_shift;
+
+ int active_hvx = hex_smin(n_hvx, (int) state.n_tasks);
+ work_queue_run(ctx->hvx_queue, hmx_f16_transfer_act_worker, &state, active_hvx);
+}
+
+typedef struct {
+ __fp16 * dst;
+ dma_addr_t act_dma_addr;
+ size_t act_elem_size;
+ int start_row;
+ int n_rows;
+ int k_block;
+ const struct mmid_row_mapping * matrix_rows;
+ int cur_a;
+ int mapping_stride;
+ int ne11;
+ size_t nb11;
+ size_t nb12;
+ int k_valid;
+ int n_hvx;
+ const struct fastdiv_values * act_hvx_div;
+ const struct fastdiv_values * ne11_div;
+ float * vtcm_f32_act;
+ size_t vtcm_f32_act_bytes;
+} hmx_f16_act_gathered_params_t;
+
+static void hmx_f16_transfer_act_gathered(
+ struct htp_ops_context * octx,
+ const hmx_f16_act_gathered_params_t * p) {
+ if (p->n_rows <= 0) {
+ return;
+ }
+ const uint32_t mc_pad = hex_align_up((uint32_t) p->n_rows, HTP_MM_HMX_TILE_N_ROWS);
+ uint32_t chunks_per_hvx = (p->n_hvx <= 1) ? mc_pad
+ : fastdiv(mc_pad + (uint32_t) p->n_hvx - 1u, p->act_hvx_div);
+ chunks_per_hvx = hex_align_up(chunks_per_hvx, 2u);
+
+ const int actual_hvx = (int) hmx_ceil_div(mc_pad, chunks_per_hvx);
+
+ hmx_f16_act_gathered_state_t state = {
+ .dst = p->dst,
+ .act_dma_addr = p->act_dma_addr,
+ .vtcm_f32_act = p->vtcm_f32_act,
+ .vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(p->vtcm_f32_act_bytes, p->act_hvx_div), 128),
+ .act_elem_size = p->act_elem_size,
+ .n_rows = (uint32_t) p->n_rows,
+ .mc_pad = mc_pad,
+ .n_chunks_per_task = chunks_per_hvx,
+ .k_block = (uint32_t) p->k_block,
+ .matrix_rows = p->matrix_rows,
+ .cur_a = (uint32_t) p->cur_a,
+ .mapping_stride = (uint32_t) p->mapping_stride,
+ .ne11 = (uint32_t) p->ne11,
+ .ne11_div = *p->ne11_div,
+ .nb11 = p->nb11,
+ .nb12 = p->nb12,
+ .start_row = (uint32_t) p->start_row,
+ .k_valid = (uint32_t) p->k_valid,
+ };
+
+ work_queue_run(octx->ctx->hvx_queue, hmx_f16_transfer_act_gathered_worker, &state, actual_hvx);
+}
+
+// --- Async F16 HMX Matmul Task ---
+
+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_f16_matmul_task_t;
+
+static void hmx_f16_matmul_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ hmx_f16_matmul_task_t * task = (hmx_f16_matmul_task_t *) data;
+ FARF(HIGH, "hmx-mm-f16-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_f16_matmul_task_init(
+ hmx_f16_matmul_task_t * task,
+ __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) {
+ task->output = output;
+ task->activation = activation;
+ task->weight = weight;
+ task->scales = scales;
+ task->n_row_tiles = n_row_tiles;
+ task->n_col_tiles = n_col_tiles;
+ task->n_dot_tiles = n_dot_tiles;
+}
+
+// --- F16 HMX Drivers ---
+
+typedef struct {
+ struct htp_ops_context * octx;
+ const hmx_mm_2d_params_t * p;
+ struct hmx_f16_act_params act_params;
+ hmx_f16_dequant_weight_params_t deq_p;
+ hmx_f16_output_params_t out_p;
+ __fp16 * vtcm_weight_raw[2];
+ __fp16 * vtcm_f16_act;
+ __fp16 * vtcm_output;
+ void * vtcm_scratch0;
+ void * vtcm_scratch1;
+ void * vtcm_scratch2;
+ void * vtcm_res_in[2];
+ void * vtcm_res_out[2];
+ __fp16 * vtcm_scales;
+ void * vtcm_bias;
+ float * vtcm_scale;
+ size_t m_chunk_n_rows;
+ size_t n_chunk_n_cols;
+ uint32_t n_chunk_cnt;
+ uint32_t dma_dst_stride;
+ uint32_t dma_src_stride;
+ uint32_t dma_width_bytes;
+ int n_k_tiles;
+ int n_weight_tiles;
+ bool is_tiled;
+ bool has_bias;
+ bool has_2d_bias;
+ bool scale_in_dequant;
+ bool scale_in_epilogue;
+} hmx_f16_mm_2d_rt_t;
+
+static __attribute__((noinline)) void hmx_f16_mm_2d_pipelined(hmx_f16_mm_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const hmx_mm_2d_params_t * p = rt->p;
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t dst_dma_addr = p->dst_dma_addr;
+ const dma_addr_t bias_addr = p->bias_addr;
+ const bool scale_per_channel = p->scale_per_channel;
+ const dma_addr_t act_dma_addr = p->act_dma_addr;
+ const dma_addr_t weight = p->weight;
+ const int m = p->m;
+ const int n = p->n;
+ const int act_stride = p->act_stride;
+ const uint32_t act_elem_size = p->act_elem_size;
+ const int weight_stride = p->weight_stride;
+ const int dst_stride = p->dst_stride;
+ const uint32_t bias_stride = p->bias_stride;
+ const int dst_cols = p->dst_cols;
+ const uint32_t dst_elem_size = p->dst_elem_size;
+ const uint32_t bias_elem_size = p->bias_elem_size;
+ const size_t m_chunk_n_rows = rt->m_chunk_n_rows;
+ const size_t n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const uint32_t dma_dst_stride = rt->dma_dst_stride;
+ const uint32_t dma_src_stride = rt->dma_src_stride;
+ const uint32_t dma_width_bytes = rt->dma_width_bytes;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const bool is_tiled = rt->is_tiled;
+ const bool has_bias = rt->has_bias;
+ const bool has_2d_bias = rt->has_2d_bias;
+ const bool scale_in_dequant = rt->scale_in_dequant;
+ const bool scale_in_epilogue = rt->scale_in_epilogue;
+ tiled_dequant_task_fn_t dequant_worker_fn = rt->deq_p.dequant_worker_fn;
+
+ hmx_f16_matmul_task_t task_slots[2];
+ void * vtcm_raw_bufs[4] = {
+ rt->vtcm_weight_raw[0],
+ rt->vtcm_weight_raw[1],
+ dequant_worker_fn ? (void *) rt->vtcm_weight_raw[0] : rt->vtcm_scratch0,
+ dequant_worker_fn ? (void *) rt->vtcm_weight_raw[1] : rt->vtcm_scratch1,
+ };
+ void * vtcm_weight_bufs[4] = {
+ dequant_worker_fn ? rt->vtcm_scratch0 : (void *) rt->vtcm_weight_raw[0],
+ dequant_worker_fn ? rt->vtcm_scratch1 : (void *) rt->vtcm_weight_raw[1],
+ rt->vtcm_scratch0,
+ rt->vtcm_scratch1,
+ };
+ __fp16 * vtcm_output_bufs[2] = { rt->vtcm_output, (__fp16 *) rt->vtcm_scratch2 };
+
+ 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;
+
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.bias_stride = has_2d_bias ? res_in_stride_elems : bias_stride;
+
+ 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);
+
+ rt->act_params.act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size;
+ rt->act_params.n_rows = (int) n_rows;
+ hmx_f16_transfer_act(&rt->act_params);
+
+ {
+ 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((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(rt->vtcm_res_in[0], bias_addr + (mr * bias_stride) * bias_elem_size),
+ res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ for (uint32_t 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);
+
+ void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ rt->deq_p.vtcm_dst = (__fp16 *) vtcm_weight_bufs[i % 4];
+ rt->deq_p.weight_src_ddr = curr_raw;
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = scale_in_dequant ? (rt->vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+
+ if (i == 0) {
+ hmx_f16_matmul_task_init(&task_slots[0], vtcm_output_bufs[0],
+ rt->vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[0],
+ rt->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_f16_matmul_worker, &task_slots[0]));
+
+ 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(rt->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);
+
+ hmx_queue_pop(ctx->hmx_queue);
+ hmx_f16_matmul_task_init(&task_slots[i & 1], vtcm_output_bufs[i & 1],
+ rt->vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4],
+ rt->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_f16_matmul_worker, &task_slots[i & 1]));
+
+ if (has_2d_bias) {
+ dma_queue_pop(weight_dma);
+ }
+
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.dst = rt->vtcm_res_out[prev];
+ rt->out_p.bias = has_2d_bias ? rt->vtcm_res_in[prev]
+ : (has_bias ? ((const uint8_t *) rt->vtcm_bias + (mr * bias_stride + nc_prev) * bias_elem_size) : NULL);
+ rt->out_p.vtcm_src = vtcm_output_bufs[prev];
+ rt->out_p.n_cols = (int) n_cols_p;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ rt->out_p.w_scale = scale_in_epilogue ? (rt->vtcm_scale + (scale_per_channel ? nc_prev : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->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(rt->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);
+ }
+ }
+ }
+
+ {
+ 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) {
+ rt->out_p.dst = rt->vtcm_res_out[last];
+ rt->out_p.bias = has_2d_bias ? rt->vtcm_res_in[last]
+ : (has_bias ? ((const uint8_t *) rt->vtcm_bias + (mr * bias_stride + nc_last) * bias_elem_size) : NULL);
+ rt->out_p.vtcm_src = vtcm_output_bufs[last];
+ rt->out_p.n_cols = (int) n_cols_last;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ rt->out_p.w_scale = scale_in_epilogue ? (rt->vtcm_scale + (scale_per_channel ? nc_last : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+}
+
+static __attribute__((noinline)) void hmx_f16_mm_2d_seq(hmx_f16_mm_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const hmx_mm_2d_params_t * p = rt->p;
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t dst_dma_addr = p->dst_dma_addr;
+ const bool scale_per_channel = p->scale_per_channel;
+ const dma_addr_t act_dma_addr = p->act_dma_addr;
+ const dma_addr_t weight = p->weight;
+ const int m = p->m;
+ const int n = p->n;
+ const int act_stride = p->act_stride;
+ const uint32_t act_elem_size = p->act_elem_size;
+ const int weight_stride = p->weight_stride;
+ const int dst_stride = p->dst_stride;
+ const uint32_t bias_stride = p->bias_stride;
+ const int dst_cols = p->dst_cols;
+ const uint32_t dst_elem_size = p->dst_elem_size;
+ const uint32_t bias_elem_size = p->bias_elem_size;
+ const size_t m_chunk_n_rows = rt->m_chunk_n_rows;
+ const size_t n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const uint32_t dma_dst_stride = rt->dma_dst_stride;
+ const uint32_t dma_src_stride = rt->dma_src_stride;
+ const uint32_t dma_width_bytes = rt->dma_width_bytes;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const bool is_tiled = rt->is_tiled;
+ const bool has_bias = rt->has_bias;
+ const bool scale_in_dequant = rt->scale_in_dequant;
+ const bool scale_in_epilogue = rt->scale_in_epilogue;
+ tiled_dequant_task_fn_t dequant_worker_fn = rt->deq_p.dequant_worker_fn;
+
+ hmx_f16_matmul_task_t task;
+ void * vtcm_raw_bufs[2] = { rt->vtcm_weight_raw[0], dequant_worker_fn ? (void *) rt->vtcm_weight_raw[0] : rt->vtcm_scratch0 };
+ void * vtcm_weight_bufs[2] = { dequant_worker_fn ? rt->vtcm_scratch0 : (void *) rt->vtcm_weight_raw[0], rt->vtcm_scratch0 };
+
+ 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);
+
+ rt->out_p.dst = rt->vtcm_res_out[0];
+ rt->out_p.vtcm_src = rt->vtcm_output;
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.bias_stride = bias_stride;
+
+ 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);
+
+ rt->act_params.act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size;
+ rt->act_params.n_rows = (int) n_rows;
+ hmx_f16_transfer_act(&rt->act_params);
+
+ 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;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height);
+ }
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ for (uint32_t 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_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_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);
+ }
+
+ rt->deq_p.vtcm_dst = (__fp16 *) vtcm_weight_bufs[i % 2];
+ rt->deq_p.weight_src_ddr = curr_raw;
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = scale_in_dequant ? (rt->vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+
+ const size_t nc_next = nc + 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);
+ }
+
+ hmx_f16_matmul_task_init(&task, rt->vtcm_output, rt->vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2],
+ rt->vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_f16_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.bias = has_bias ? ((const uint8_t *) rt->vtcm_bias + (mr * bias_stride + nc) * bias_elem_size) : NULL;
+ rt->out_p.n_cols = (int) n_cols;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ rt->out_p.w_scale = scale_in_epilogue ? (rt->vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &rt->out_p);
+ }
+ 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, rt->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);
+ }
+ }
+}
+
+int hmx_f16_mm_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_2d_params_t * p) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t bias_addr = p->bias_addr;
+ const size_t bias_bytes = p->bias_bytes;
+ const dma_addr_t scale_addr = p->scale_addr;
+ const size_t scale_bytes = p->scale_bytes;
+ const bool scale_per_channel = p->scale_per_channel;
+ const int m = p->m;
+ const int k = p->k;
+ const int n = p->n;
+ const int act_stride = p->act_stride;
+ const uint32_t act_elem_size = p->act_elem_size;
+ const int weight_stride = p->weight_stride;
+ const int weight_type = p->weight_type;
+ const int k_valid = p->k_valid;
+ const uint32_t dst_elem_size = p->dst_elem_size;
+ const uint32_t bias_elem_size = p->bias_elem_size;
+
+ const int m_chunk = kparams->m_chunk;
+ const int n_chunk = kparams->n_chunk;
+ const int pipeline = (kparams->flags & HTP_MM_FLAG_PIPELINE) != 0;
+ 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;
+ const int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+ const struct fastdiv_values n_k_tiles_div = kparams->div_n_k_tiles;
+
+ const bool is_tiled = (tile_size > 0);
+ const size_t row_stride = htp_tensor_get_row_size(weight_type, k);
+
+ tiled_dequant_task_fn_t dequant_worker_fn = hmx_f16_get_dequant_worker_fn(weight_type, is_tiled);
+
+ 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 size_t vtcm_budget = ctx->vtcm_size;
+
+ const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride;
+ 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 m_chunk_n_rows = m_chunk;
+ const size_t n_chunk_n_cols = n_chunk;
+
+ const struct htp_tensor * norm_w = (kparams->norm_w_idx != 0) ? octx->src[kparams->norm_w_idx] : NULL;
+ const size_t vtcm_norm_bytes = norm_w ? htp_mm_fused_norm_vtcm_bytes((uint32_t) k) : 0;
+
+ const bool has_bias = (bias_bytes > 0 && bias_addr != 0);
+ const bool has_2d_bias = (pipeline && !has_bias && bias_addr != 0);
+ const bool has_scale = (scale_bytes > 0 && scale_addr != 0);
+ const size_t vtcm_scale_bytes = has_scale ? hex_align_up(scale_bytes, 128) : 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_ex_scaled(&L, HTP_MM_KERNEL_HMX_F16_2D, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, bias_bytes,
+ vtcm_scale_bytes, res_in_elem_size, res_out_elem_size, vtcm_norm_bytes);
+
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-f16-mm-2d: VTCM overflow: used %zu budget %zu, m %d k %d n %d mc %zu nc %zu",
+ L.total_bytes, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols);
+ return -1;
+ }
+
+ uint8_t * const base = (uint8_t *) ctx->vtcm_base;
+ __fp16 * vtcm_weight_raw[2] = {
+ VTCM_LAYOUT_PTR(__fp16, base, L.off_weight[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(__fp16, 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_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);
+ 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(__fp16, base, L.off_scales);
+
+ 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);
+ }
+
+ 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, bias_addr), hex_align_up(bias_bytes, 128), 0, bias_bytes, 1);
+ dma_queue_pop(weight_dma);
+ }
+
+ float * vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, has_scale);
+ if (has_scale) {
+ htp_mm_load_scale(weight_dma, vtcm_scale, scale_addr, scale_bytes, !scale_per_channel);
+ }
+ float * vtcm_norm = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_norm, norm_w != NULL);
+ if (norm_w) {
+ htp_mm_load_norm(weight_dma, vtcm_norm, vtcm_f32_act, norm_w, (uint32_t) k_valid, act_elem_size == sizeof(__fp16));
+ }
+ const bool scale_in_dequant = has_scale && hmx_f16_scales_in_dequant(weight_type);
+ const bool scale_in_epilogue = has_scale && !scale_in_dequant;
+ const uint32_t scale_ct_stride = scale_per_channel ? 32u : 0u;
+ const uint32_t scale_c_mask = scale_per_channel ? ~0u : 0u;
+
+ FARF(HIGH, "hmx-f16-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, L.total_bytes, vtcm_budget);
+
+ const uint32_t n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ hmx_f16_mm_2d_rt_t rt = {
+ .octx = octx,
+ .p = p,
+ .act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .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,
+ .vtcm_norm = vtcm_norm,
+ .norm_eps = kparams->norm_eps,
+ },
+ .deq_p = {
+ .k_block = k,
+ .row_stride = row_stride,
+ .weight_type = weight_type,
+ .n_k_tiles = n_k_tiles,
+ .n_k_tiles_div = n_k_tiles_div,
+ .dequant_worker_fn = dequant_worker_fn,
+ .w_scale_ct_stride = scale_ct_stride,
+ },
+ .out_p = {
+ .dst_elem_size = dst_elem_size,
+ .bias_elem_size = bias_elem_size,
+ .w_scale_c_mask = scale_c_mask,
+ },
+ .vtcm_weight_raw = { vtcm_weight_raw[0], vtcm_weight_raw[1] },
+ .vtcm_f16_act = vtcm_f16_act,
+ .vtcm_output = vtcm_output,
+ .vtcm_scratch0 = vtcm_scratch0,
+ .vtcm_scratch1 = vtcm_scratch1,
+ .vtcm_scratch2 = vtcm_scratch2,
+ .vtcm_res_in = { vtcm_res_in[0], vtcm_res_in[1] },
+ .vtcm_res_out = { vtcm_res_out[0], vtcm_res_out[1] },
+ .vtcm_scales = vtcm_scales,
+ .vtcm_bias = vtcm_bias,
+ .vtcm_scale = vtcm_scale,
+ .m_chunk_n_rows = m_chunk_n_rows,
+ .n_chunk_n_cols = n_chunk_n_cols,
+ .n_chunk_cnt = n_chunk_cnt,
+ .dma_dst_stride = dma_dst_stride,
+ .dma_src_stride = dma_src_stride,
+ .dma_width_bytes = dma_width_bytes,
+ .n_k_tiles = n_k_tiles,
+ .n_weight_tiles = n_weight_tiles,
+ .is_tiled = is_tiled,
+ .has_bias = has_bias,
+ .has_2d_bias = has_2d_bias,
+ .scale_in_dequant = scale_in_dequant,
+ .scale_in_epilogue = scale_in_epilogue,
+ };
+
+ if (pipeline) {
+ hmx_f16_mm_2d_pipelined(&rt);
+ } else {
+ hmx_f16_mm_2d_seq(&rt);
+ }
+
+ return 0;
+}
+
+static int hmx_f16_mm_batched_simple(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_batched_params_t * params) {
+ hmx_mm_2d_params_t p2d = {
+ .weight_dma = params->weight_dma,
+ .bias_bytes = params->bias_bytes,
+ .scale_addr = params->scale_addr,
+ .scale_bytes = params->scale_bytes,
+ .scale_per_channel = params->scale_per_channel != 0,
+ .m = params->m,
+ .k = params->k,
+ .n = params->n,
+ .act_stride = params->act_stride,
+ .act_elem_size = params->act_elem_size,
+ .weight_stride = params->weight_stride,
+ .weight_type = params->weight_type,
+ .k_valid = params->k,
+ .dst_stride = params->dst_stride,
+ .bias_stride = params->bias_stride,
+ .dst_cols = params->dst_cols,
+ .dst_elem_size = params->dst_elem_size,
+ .bias_elem_size = params->bias_elem_size,
+ };
+
+ int ret = 0;
+ for (int b3 = 0; b3 < params->ne13 && ret == 0; ++b3) {
+ for (int b2 = 0; b2 < params->ne12 && ret == 0; ++b2) {
+ p2d.dst_dma_addr = hmx_mm_dst_batch_addr(params, b2, b3);
+ p2d.bias_addr = params->bias_addr ? (params->bias_addr + b2 * params->bias_nb2 + b3 * params->bias_nb3) : 0;
+ p2d.act_dma_addr = hmx_mm_act_batch_addr(params, b2, b3);
+ p2d.weight = hmx_mm_weight_batch_data(params, b2, b3);
+ ret = hmx_f16_mm_2d(octx, kparams, &p2d);
+ }
+ }
+ return ret;
+}
+
+int hmx_f16_mm_batched(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_batched_params_t * params) {
+ struct htp_context * ctx = octx->ctx;
+ const int m_chunk = kparams->m_chunk;
+ const int n_chunk = kparams->n_chunk;
+ 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;
+ const int vtcm_size = kparams->vtcm_size;
+
+ const int group_size = params->r2;
+ const size_t vtcm_budget = ctx->vtcm_size;
+
+ bool run_grouped = ((kparams->flags & HTP_MM_FLAG_GROUPED) != 0 && (size_t) vtcm_size <= vtcm_budget);
+ if (!run_grouped) {
+ return hmx_f16_mm_batched_simple(octx, kparams, params);
+ }
+
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ size_t m_chunk_n_rows = m_chunk;
+ size_t n_chunk_n_cols = n_chunk;
+
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_ex(&L, HTP_MM_KERNEL_HMX_F16_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_f16_mm_batched_simple(octx, kparams, params);
+ }
+
+ 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);
+ __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);
+ 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);
+ }
+
+ hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00));
+
+ FARF(HIGH, "%s: grouped path m=%d k=%d n=%d group=%d streams=%d mc=%zu nc=%zu vtcm=%zu/%zu",
+ __func__, params->m, params->k, params->n, group_size, params->ne13,
+ m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget);
+
+ const size_t f16_row_bytes = (size_t) params->k * sizeof(__fp16);
+ const size_t weight_row_bytes = (size_t) params->weight_stride;
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ hmx_f16_matmul_task_t task;
+ struct hmx_f16_act_params act_params = {
+ .ctx = ctx,
+ .k_block = params->k,
+ .k_stride = params->act_stride,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .k_div = k_div,
+ .k_valid = params->k,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = params->act_elem_size,
+ };
+ 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);
+ hmx_f16_output_params_t out_p = {
+ .dst = vtcm_res_out,
+ .vtcm_src = vtcm_output,
+ .dst_stride = res_out_stride_elems,
+ .bias_stride = params->bias_stride,
+ .dst_elem_size = params->dst_elem_size,
+ .bias_elem_size = params->bias_elem_size,
+ };
+
+ for (int b3 = 0; b3 < params->ne13; ++b3) {
+ for (int b2_base = 0; b2_base < params->ne12; b2_base += group_size) {
+ const dma_addr_t weight_group = hmx_mm_weight_batch_data(params, b2_base, b3);
+ dma_queue * weight_dma = params->weight_dma;
+
+ for (size_t mr = 0; mr < (size_t) params->m; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin((size_t) params->m - mr, m_chunk_n_rows);
+ const size_t n_row_tiles = hmx_ceil_div((int) n_rows, HTP_MM_HMX_TILE_N_ROWS);
+
+ act_params.n_rows = (int) n_rows;
+ for (int g = 0; g < group_size; ++g) {
+ act_params.dst = vtcm_f16_act + (size_t) g * L.act_head_stride;
+ act_params.act_dma_addr = hmx_mm_act_batch_addr(params, b2_base + g, b3) +
+ (size_t) mr * params->act_stride * params->act_elem_size;
+ hmx_f16_transfer_act(&act_params);
+ }
+
+ 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),
+ f16_row_bytes, weight_row_bytes, f16_row_bytes, n_cols_first);
+ }
+
+ out_p.n_rows = (int) n_rows;
+
+ 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;
+ if (nc > 0) {
+ dma_queue_pop(weight_dma);
+ }
+
+ 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;
+ 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);
+ 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),
+ f16_row_bytes, weight_row_bytes, f16_row_bytes, n_cols_next);
+ }
+
+ const __fp16 * vtcm_act_g = vtcm_f16_act + (size_t) g * L.act_head_stride;
+ hmx_f16_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_f16_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = params->dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ out_p.bias = has_bias ? ((const uint8_t *) vtcm_bias + (mr * params->bias_stride + nc) * params->bias_elem_size) : NULL;
+ out_p.n_cols = (int) n_cols;
+ out_p.dst_cols = chunk_dst_cols;
+ hmx_f16_transfer_output(octx, &out_p);
+ }
+ 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);
+ }
+ }
+ }
+ }
+
+ return 0;
+}
+
+typedef struct {
+ struct htp_ops_context * octx;
+ hmx_output_glu_state_t glu_state;
+ struct hmx_f16_act_params act_params;
+ hmx_f16_dequant_weight_params_t deq_p;
+ void * vtcm_weight_raw[2];
+ __fp16 * vtcm_f16_act;
+ __fp16 * vtcm_scales;
+ __fp16 * vtcm_gate[2];
+ __fp16 * vtcm_up[2];
+ void * vtcm_scratch[2];
+ void * vtcm_res_out[2];
+ float * vtcm_scale_gate;
+ float * vtcm_scale_up;
+ dma_addr_t act_dma_addr;
+ dma_addr_t w_gate;
+ dma_addr_t w_up;
+ dma_addr_t dst_dma_addr;
+ size_t w_gate_stride;
+ size_t w_up_stride;
+ size_t dst_stride;
+ size_t dst_row_bytes;
+ size_t dst_elem_size;
+ size_t res_out_stride_bytes;
+ size_t n;
+ size_t m_start;
+ size_t mr_end;
+ int m_chunk_n_rows;
+ int n_chunk_n_cols;
+ int act_stride;
+ int dst_cols;
+ int n_k_tiles;
+ int n_weight_tiles;
+ uint32_t act_elem_size;
+ uint32_t n_chunk_cnt;
+ uint32_t dma_dst_stride;
+ uint32_t dma_width_bytes;
+ uint32_t dma_src_stride_g;
+ uint32_t dma_src_stride_u;
+ uint32_t gate_ct_stride;
+ uint32_t up_ct_stride;
+ bool is_tiled;
+ bool gate_per_ch;
+ bool up_per_ch;
+ bool scale_in_dequant;
+ bool scale_in_epilogue;
+} hmx_f16_mm_nx_glu_2d_rt_t;
+
+static __attribute__((noinline)) void hmx_f16_mm_nx_glu_2d_pipelined(hmx_f16_mm_nx_glu_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ dma_queue * weight_dma = ctx->dma[0];
+ tiled_dequant_task_fn_t dequant_worker_fn = rt->deq_p.dequant_worker_fn;
+ const size_t n = rt->n;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const uint32_t dma_dst_stride = rt->dma_dst_stride;
+ const uint32_t dma_width_bytes = rt->dma_width_bytes;
+ const uint32_t dma_src_stride_g = rt->dma_src_stride_g;
+ const uint32_t dma_src_stride_u = rt->dma_src_stride_u;
+ const size_t dst_elem_size = rt->dst_elem_size;
+ const size_t dst_stride = rt->dst_stride;
+ const size_t dst_row_bytes = rt->dst_row_bytes;
+ const size_t res_out_stride_bytes = rt->res_out_stride_bytes;
+ const int dst_cols = rt->dst_cols;
+ const bool is_tiled = rt->is_tiled;
+ const bool scale_in_dequant = rt->scale_in_dequant;
+ const bool scale_in_epilogue = rt->scale_in_epilogue;
+
+ void * gate_raw_buf[2] = { rt->vtcm_weight_raw[0], dequant_worker_fn ? rt->vtcm_weight_raw[0] : rt->vtcm_scratch[0] };
+ void * up_raw_buf[2] = { rt->vtcm_weight_raw[1], dequant_worker_fn ? rt->vtcm_weight_raw[1] : rt->vtcm_scratch[1] };
+ void * gate_hmx_buf[2] = { dequant_worker_fn ? rt->vtcm_scratch[0] : rt->vtcm_weight_raw[0], rt->vtcm_scratch[0] };
+ void * up_hmx_buf[2] = { dequant_worker_fn ? rt->vtcm_scratch[1] : rt->vtcm_weight_raw[1], rt->vtcm_scratch[1] };
+
+ hmx_f16_matmul_task_t task_gate[2];
+ hmx_f16_matmul_task_t task_up[2];
+
+ for (size_t mr = rt->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);
+
+ rt->act_params.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_params.n_rows = (int) n_rows;
+ hmx_f16_transfer_act(&rt->act_params);
+
+ {
+ 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], rt->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], rt->w_up),
+ dma_dst_stride, dma_src_stride_u, dma_width_bytes, height0);
+ }
+
+ for (uint32_t 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);
+
+ dma_queue_pop(weight_dma);
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ if (dequant_worker_fn) {
+ rt->deq_p.vtcm_dst = (__fp16 *) gate_hmx_buf[cur];
+ rt->deq_p.weight_src_ddr = gate_raw_buf[cur];
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = (scale_in_dequant && rt->vtcm_scale_gate) ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc : 0)) : NULL;
+ rt->deq_p.w_scale_ct_stride = rt->gate_ct_stride;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+ }
+
+ hmx_f16_matmul_task_init(&task_gate[cur], rt->vtcm_gate[cur], rt->vtcm_f16_act, (__fp16 *) gate_hmx_buf[cur],
+ rt->vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_f16_matmul_worker, &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], rt->w_gate + nc_n * rt->w_gate_stride),
+ dma_dst_stride, dma_src_stride_g, dma_width_bytes, height_n);
+ }
+
+ dma_queue_pop(weight_dma);
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ if (dequant_worker_fn) {
+ rt->deq_p.vtcm_dst = (__fp16 *) up_hmx_buf[cur];
+ rt->deq_p.weight_src_ddr = up_raw_buf[cur];
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = (scale_in_dequant && rt->vtcm_scale_up) ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc : 0)) : NULL;
+ rt->deq_p.w_scale_ct_stride = rt->up_ct_stride;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+ }
+
+ hmx_f16_matmul_task_init(&task_up[cur], rt->vtcm_up[cur], rt->vtcm_f16_act, (__fp16 *) up_hmx_buf[cur],
+ rt->vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_f16_matmul_worker, &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], rt->w_up + nc_n * rt->w_up_stride),
+ dma_dst_stride, dma_src_stride_u, dma_width_bytes, height_n);
+ }
+
+ 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) {
+ const float * wsg_ep = (scale_in_epilogue && rt->vtcm_scale_gate) ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc_prev : 0)) : NULL;
+ const float * wsu_ep = (scale_in_epilogue && rt->vtcm_scale_up) ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc_prev : 0)) : NULL;
+ hmx_transfer_output_glu(
+ octx, &rt->glu_state, rt->vtcm_res_out[prev], rt->vtcm_gate[prev], rt->vtcm_up[prev],
+ wsg_ep, wsu_ep, (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(rt->dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, rt->vtcm_res_out[prev]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ }
+
+ {
+ 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) {
+ const float * wsg_ep = (scale_in_epilogue && rt->vtcm_scale_gate) ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc_last : 0)) : NULL;
+ const float * wsu_ep = (scale_in_epilogue && rt->vtcm_scale_up) ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc_last : 0)) : NULL;
+ hmx_transfer_output_glu(
+ octx, &rt->glu_state, rt->vtcm_res_out[last], rt->vtcm_gate[last], rt->vtcm_up[last],
+ wsg_ep, wsu_ep, (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(rt->dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, rt->vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+}
+
+static __attribute__((noinline)) void hmx_f16_mm_nx_glu_2d_seq(hmx_f16_mm_nx_glu_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ dma_queue * weight_dma = ctx->dma[0];
+ tiled_dequant_task_fn_t dequant_worker_fn = rt->deq_p.dequant_worker_fn;
+ const size_t n = rt->n;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const uint32_t dma_dst_stride = rt->dma_dst_stride;
+ const uint32_t dma_width_bytes = rt->dma_width_bytes;
+ const uint32_t dma_src_stride_g = rt->dma_src_stride_g;
+ const uint32_t dma_src_stride_u = rt->dma_src_stride_u;
+ const size_t dst_elem_size = rt->dst_elem_size;
+ const size_t dst_stride = rt->dst_stride;
+ const size_t dst_row_bytes = rt->dst_row_bytes;
+ const size_t res_out_stride_bytes = rt->res_out_stride_bytes;
+ const int dst_cols = rt->dst_cols;
+ const bool is_tiled = rt->is_tiled;
+ const bool scale_in_dequant = rt->scale_in_dequant;
+ const bool scale_in_epilogue = rt->scale_in_epilogue;
+
+ void * w_hmx = dequant_worker_fn ? rt->vtcm_scratch[0] : rt->vtcm_weight_raw[0];
+ hmx_f16_matmul_task_t task;
+ rt->deq_p.vtcm_dst = (__fp16 *) w_hmx;
+ rt->deq_p.weight_src_ddr = rt->vtcm_weight_raw[0];
+
+ for (size_t mr = rt->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);
+
+ rt->act_params.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_params.n_rows = (int) n_rows;
+ hmx_f16_transfer_act(&rt->act_params);
+
+ for (uint32_t 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(rt->vtcm_weight_raw[0], rt->w_gate + nc * rt->w_gate_stride),
+ dma_dst_stride, dma_src_stride_g, dma_width_bytes, height);
+ dma_queue_pop(weight_dma);
+ if (dequant_worker_fn) {
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = (scale_in_dequant && rt->vtcm_scale_gate) ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc : 0)) : NULL;
+ rt->deq_p.w_scale_ct_stride = rt->gate_ct_stride;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+ }
+ hmx_f16_matmul_task_init(&task, rt->vtcm_gate[0], rt->vtcm_f16_act, (__fp16 *) w_hmx,
+ rt->vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_f16_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], rt->w_up + nc * rt->w_up_stride),
+ dma_dst_stride, dma_src_stride_u, dma_width_bytes, height);
+ dma_queue_pop(weight_dma);
+ if (dequant_worker_fn) {
+ rt->deq_p.w_scale = (scale_in_dequant && rt->vtcm_scale_up) ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc : 0)) : NULL;
+ rt->deq_p.w_scale_ct_stride = rt->up_ct_stride;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+ }
+ hmx_f16_matmul_task_init(&task, rt->vtcm_up[0], rt->vtcm_f16_act, (__fp16 *) w_hmx,
+ rt->vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_f16_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ const float * wsg_ep = (scale_in_epilogue && rt->vtcm_scale_gate) ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc : 0)) : NULL;
+ const float * wsu_ep = (scale_in_epilogue && rt->vtcm_scale_up) ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc : 0)) : NULL;
+ hmx_transfer_output_glu(
+ octx, &rt->glu_state, rt->vtcm_res_out[0], rt->vtcm_gate[0], rt->vtcm_up[0],
+ wsg_ep, wsu_ep, (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(rt->dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, rt->vtcm_res_out[0]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+}
+
+int hmx_f16_mm_nx_glu_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 (n == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ const size_t row_stride = htp_tensor_get_row_size(weight_type, k);
+
+ const struct htp_tensor * s_gate = ((kparams->scale_mask & 1u) != 0) ? octx->src[3] : NULL;
+ const struct htp_tensor * s_up = ((kparams->scale_mask & 2u) != 0) ? octx->src[4] : NULL;
+ const bool has_any_scale = (s_gate != NULL || s_up != NULL);
+ const bool scale_in_dequant = has_any_scale && hmx_f16_scales_in_dequant(weight_type);
+ const bool scale_in_epilogue = has_any_scale && !scale_in_dequant;
+
+ hmx_output_glu_state_t glu_state;
+ if (!resolve_fp16_output_glu_fns(kparams->glu_op, dst_elem_size, scale_in_epilogue,
+ &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 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_f16_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->flags & HTP_MM_FLAG_PIPELINE) != 0;
+ 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;
+
+ const struct htp_tensor * norm_w = (kparams->norm_w_idx != 0) ? octx->src[kparams->norm_w_idx] : NULL;
+ const size_t vtcm_norm_bytes = norm_w ? htp_mm_fused_norm_vtcm_bytes((uint32_t) k) : 0;
+
+ 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, (size_t) kparams->vtcm_scale_size, vtcm_norm_bytes);
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-f16-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)
+ };
+ __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)
+ };
+
+ const bool gate_per_ch = s_gate && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, 0));
+ const bool up_per_ch = s_up && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, 1));
+ const uint32_t gate_ct_stride = gate_per_ch ? 32u : 0u;
+ const uint32_t up_ct_stride = up_per_ch ? 32u : 0u;
+ const size_t gate_scale_bytes = s_gate ? (gate_per_ch ? (n * sizeof(float)) : sizeof(float)) : 0;
+ const size_t up_scale_bytes = s_up ? (up_per_ch ? (n * sizeof(float)) : sizeof(float)) : 0;
+ const size_t gate_scale_off = L.off_scale;
+ const size_t up_scale_off = L.off_scale + (s_gate ? hex_round_up(gate_scale_bytes, 128) : 0);
+ float * vtcm_scale_gate = VTCM_LAYOUT_PTR_OPTIONAL(float, base, gate_scale_off, s_gate != NULL);
+ float * vtcm_scale_up = VTCM_LAYOUT_PTR_OPTIONAL(float, base, up_scale_off, s_up != NULL);
+ if (s_gate) {
+ htp_mm_load_scale(octx->ctx->dma[0], vtcm_scale_gate, s_gate->data, gate_scale_bytes, !gate_per_ch);
+ }
+ if (s_up) {
+ htp_mm_load_scale(octx->ctx->dma[0], vtcm_scale_up, s_up->data, up_scale_bytes, !up_per_ch);
+ }
+ float * vtcm_norm = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_norm, norm_w != NULL);
+ if (norm_w) {
+ htp_mm_load_norm(octx->ctx->dma[0], vtcm_norm, vtcm_f32_act, norm_w, (uint32_t) k_valid, act_elem_size == sizeof(__fp16));
+ }
+
+ hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00));
+ 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-f16-mm-nx-glu: 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 w_gate_stride = src_gate->nb[1];
+ const size_t w_up_stride = src_up->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);
+
+ glu_state.vtcm_act_scales = NULL;
+ glu_state.vtcm_wt_scales_up = NULL;
+ glu_state.w_scale_gate_c_mask = gate_per_ch ? ~0u : 0u;
+ glu_state.w_scale_up_c_mask = up_per_ch ? ~0u : 0u;
+ glu_state.n_groups = 1u;
+ glu_state.dst_stride = (uint32_t) res_out_stride_elems;
+ glu_state.dst_elem_size = dst_elem_size;
+
+ hmx_f16_mm_nx_glu_2d_rt_t rt = {
+ .octx = octx,
+ .glu_state = glu_state,
+ .act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .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,
+ .vtcm_norm = vtcm_norm,
+ .norm_eps = kparams->norm_eps,
+ },
+ .deq_p = {
+ .k_block = k,
+ .row_stride = row_stride,
+ .weight_type = weight_type,
+ .n_k_tiles = n_k_tiles,
+ .n_k_tiles_div = n_k_tiles_div,
+ .dequant_worker_fn = dequant_worker_fn,
+ },
+ .vtcm_weight_raw = { vtcm_weight_raw[0], vtcm_weight_raw[1] },
+ .vtcm_f16_act = vtcm_f16_act,
+ .vtcm_scales = vtcm_scales,
+ .vtcm_gate = { vtcm_gate[0], vtcm_gate[1] },
+ .vtcm_up = { vtcm_up[0], vtcm_up[1] },
+ .vtcm_scratch = { vtcm_scratch[0], vtcm_scratch[1] },
+ .vtcm_res_out = { vtcm_res_out[0], vtcm_res_out[1] },
+ .vtcm_scale_gate = vtcm_scale_gate,
+ .vtcm_scale_up = vtcm_scale_up,
+ .act_dma_addr = act_dma_addr,
+ .w_gate = src_gate->data,
+ .w_up = src_up->data,
+ .dst_dma_addr = dst->data,
+ .w_gate_stride = w_gate_stride,
+ .w_up_stride = w_up_stride,
+ .dst_stride = dst->nb[1] / dst_elem_size,
+ .dst_row_bytes = dst->nb[1],
+ .dst_elem_size = dst_elem_size,
+ .res_out_stride_bytes = res_out_stride_bytes,
+ .n = n,
+ .m_start = (size_t) m_start,
+ .mr_end = (size_t) (m_start + m_rows),
+ .m_chunk_n_rows = m_chunk_n_rows,
+ .n_chunk_n_cols = n_chunk_n_cols,
+ .act_stride = act_stride,
+ .dst_cols = (int) dst->ne[0],
+ .n_k_tiles = n_k_tiles,
+ .n_weight_tiles = n_weight_tiles,
+ .act_elem_size = act_elem_size,
+ .n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols),
+ .dma_dst_stride = is_tiled ? (uint32_t) aligned_tile_size : (uint32_t) row_stride,
+ .dma_width_bytes = is_tiled ? (uint32_t) tile_size : (uint32_t) row_stride,
+ .dma_src_stride_g = is_tiled ? (uint32_t) tile_size : (uint32_t) w_gate_stride,
+ .dma_src_stride_u = is_tiled ? (uint32_t) tile_size : (uint32_t) w_up_stride,
+ .gate_ct_stride = gate_ct_stride,
+ .up_ct_stride = up_ct_stride,
+ .is_tiled = is_tiled,
+ .gate_per_ch = gate_per_ch,
+ .up_per_ch = up_per_ch,
+ .scale_in_dequant = scale_in_dequant,
+ .scale_in_epilogue = scale_in_epilogue,
+ };
+
+ if (pipeline) {
+ hmx_f16_mm_nx_glu_2d_pipelined(&rt);
+ } else {
+ hmx_f16_mm_nx_glu_2d_seq(&rt);
+ }
+
+ return HTP_STATUS_OK;
+}
+
+typedef struct {
+ struct htp_ops_context * octx;
+ const struct htp_mm_kernel_params * kparams;
+ struct hmx_f16_act_params act_params;
+ hmx_f16_dequant_weight_params_t deq_p;
+ hmx_f16_output_params_t out_p;
+ __fp16 * vtcm_weight_raw[2];
+ __fp16 * vtcm_f16_act;
+ __fp16 * vtcm_output;
+ void * vtcm_scratch0;
+ void * vtcm_scratch1;
+ void * vtcm_scratch2;
+ void * vtcm_res_out[2];
+ __fp16 * vtcm_scales;
+ float * vtcm_scale;
+ dma_addr_t act_dma_addr;
+ size_t m_start;
+ size_t mr_end;
+ uint32_t n_weights;
+ uint32_t act_elem_size;
+ uint32_t dma_dst_stride;
+ uint32_t dma_width_bytes;
+ int act_stride;
+ int m_chunk_n_rows;
+ int n_chunk_n_cols;
+ int n_k_tiles;
+ int n_weight_tiles;
+ int tile_size;
+ int weight_type;
+ bool is_tiled;
+} hmx_f16_mm_nx_2d_rt_t;
+
+static __attribute__((noinline)) void hmx_f16_mm_nx_2d_pipelined(hmx_f16_mm_nx_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const struct htp_mm_kernel_params * kparams = rt->kparams;
+ tiled_dequant_task_fn_t dequant_worker_fn = rt->deq_p.dequant_worker_fn;
+ const uint32_t n_weights = rt->n_weights;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int weight_type = rt->weight_type;
+ const bool is_tiled = rt->is_tiled;
+ const uint32_t dma_dst_stride = rt->dma_dst_stride;
+ const uint32_t dma_width_bytes = rt->dma_width_bytes;
+
+ hmx_f16_matmul_task_t task_slots[2];
+ void * vtcm_raw_bufs[4] = {
+ rt->vtcm_weight_raw[0],
+ rt->vtcm_weight_raw[1],
+ dequant_worker_fn ? (void *) rt->vtcm_weight_raw[0] : rt->vtcm_scratch0,
+ dequant_worker_fn ? (void *) rt->vtcm_weight_raw[1] : rt->vtcm_scratch1,
+ };
+ void * vtcm_weight_bufs[4] = {
+ dequant_worker_fn ? rt->vtcm_scratch0 : (void *) rt->vtcm_weight_raw[0],
+ dequant_worker_fn ? rt->vtcm_scratch1 : (void *) rt->vtcm_weight_raw[1],
+ rt->vtcm_scratch0,
+ rt->vtcm_scratch1,
+ };
+ __fp16 * vtcm_output_bufs[2] = { rt->vtcm_output, (__fp16 *) rt->vtcm_scratch2 };
+
+ for (size_t mr = rt->m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+
+ rt->act_params.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_params.n_rows = (int) n_rows;
+ hmx_f16_transfer_act(&rt->act_params);
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ 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 dma_addr_t weight = src_w->data;
+ 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_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 uint32_t n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols);
+ const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
+
+ const struct htp_tensor * p_scale = (((kparams->scale_mask >> p) & 1u) != 0) ? octx->src[n_weights + 1 + p] : NULL;
+ const bool p_per_ch = p_scale && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, p));
+ const uint32_t p_ct_stride = p_per_ch ? 32u : 0u;
+ const uint32_t p_c_mask = p_per_ch ? ~0u : 0u;
+ const bool p_scale_in_deq = p_scale && hmx_f16_scales_in_dequant(weight_type);
+ const bool p_scale_in_ep = p_scale && !p_scale_in_deq;
+ if (p_scale) {
+ const size_t p_sbytes = p_per_ch ? (n * sizeof(float)) : sizeof(float);
+ htp_mm_load_scale(weight_dma, rt->vtcm_scale, p_scale->data, p_sbytes, !p_per_ch);
+ }
+
+ rt->deq_p.w_scale_ct_stride = p_ct_stride;
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.dst_elem_size = dst_elem_size;
+ rt->out_p.w_scale_c_mask = p_c_mask;
+
+ {
+ 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 - (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 + (size_t) n_chunk_n_cols * weight_stride),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height_A1);
+ }
+
+ for (uint32_t 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, (size_t) n_chunk_n_cols);
+
+ void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
+ rt->deq_p.vtcm_dst = (__fp16 *) vtcm_weight_bufs[i % 4];
+ rt->deq_p.weight_src_ddr = curr_raw;
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = p_scale_in_deq ? (rt->vtcm_scale + (p_per_ch ? nc : 0)) : NULL;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+
+ if (i == 0) {
+ hmx_f16_matmul_task_init(&task_slots[0], vtcm_output_bufs[0],
+ rt->vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[0],
+ rt->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_f16_matmul_worker, &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);
+
+ hmx_queue_pop(ctx->hmx_queue);
+ hmx_f16_matmul_task_init(&task_slots[i & 1], vtcm_output_bufs[i & 1],
+ rt->vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4],
+ rt->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_f16_matmul_worker, &task_slots[i & 1]));
+
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.dst = rt->vtcm_res_out[prev];
+ rt->out_p.vtcm_src = vtcm_output_bufs[prev];
+ rt->out_p.n_cols = (int) n_cols_p;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ rt->out_p.w_scale = p_scale_in_ep ? (rt->vtcm_scale + (p_per_ch ? nc_prev : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->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);
+ }
+ }
+ }
+
+ {
+ 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) {
+ rt->out_p.dst = rt->vtcm_res_out[last];
+ rt->out_p.vtcm_src = vtcm_output_bufs[last];
+ rt->out_p.n_cols = (int) n_cols_last;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ rt->out_p.w_scale = p_scale_in_ep ? (rt->vtcm_scale + (p_per_ch ? nc_last : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+ }
+}
+
+static __attribute__((noinline)) void hmx_f16_mm_nx_2d_seq(hmx_f16_mm_nx_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const struct htp_mm_kernel_params * kparams = rt->kparams;
+ tiled_dequant_task_fn_t dequant_worker_fn = rt->deq_p.dequant_worker_fn;
+ const uint32_t n_weights = rt->n_weights;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int weight_type = rt->weight_type;
+ const bool is_tiled = rt->is_tiled;
+ const uint32_t dma_dst_stride = rt->dma_dst_stride;
+ const uint32_t dma_width_bytes = rt->dma_width_bytes;
+
+ hmx_f16_matmul_task_t task;
+ void * vtcm_raw_bufs[2] = { rt->vtcm_weight_raw[0], dequant_worker_fn ? (void *) rt->vtcm_weight_raw[0] : rt->vtcm_scratch0 };
+ void * vtcm_weight_bufs[2] = { dequant_worker_fn ? rt->vtcm_scratch0 : (void *) rt->vtcm_weight_raw[0], rt->vtcm_scratch0 };
+
+ rt->out_p.dst = rt->vtcm_res_out[0];
+ rt->out_p.vtcm_src = rt->vtcm_output;
+
+ for (size_t mr = rt->m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+
+ rt->act_params.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_params.n_rows = (int) n_rows;
+ hmx_f16_transfer_act(&rt->act_params);
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ 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 dma_addr_t weight = src_w->data;
+ 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_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 uint32_t n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols);
+ const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
+
+ const struct htp_tensor * p_scale = (((kparams->scale_mask >> p) & 1u) != 0) ? octx->src[n_weights + 1 + p] : NULL;
+ const bool p_per_ch = p_scale && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, p));
+ const uint32_t p_ct_stride = p_per_ch ? 32u : 0u;
+ const uint32_t p_c_mask = p_per_ch ? ~0u : 0u;
+ const bool p_scale_in_deq = p_scale && hmx_f16_scales_in_dequant(weight_type);
+ const bool p_scale_in_ep = p_scale && !p_scale_in_deq;
+ if (p_scale) {
+ const size_t p_sbytes = p_per_ch ? (n * sizeof(float)) : sizeof(float);
+ htp_mm_load_scale(weight_dma, rt->vtcm_scale, p_scale->data, p_sbytes, !p_per_ch);
+ }
+
+ rt->deq_p.w_scale_ct_stride = p_ct_stride;
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.dst_elem_size = dst_elem_size;
+ rt->out_p.w_scale_c_mask = p_c_mask;
+
+ if (n > 0) {
+ 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 (uint32_t 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, (size_t) 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_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);
+ }
+
+ rt->deq_p.vtcm_dst = (__fp16 *) vtcm_weight_bufs[i % 2];
+ rt->deq_p.weight_src_ddr = curr_raw;
+ rt->deq_p.n_cols = (int) n_cols;
+ rt->deq_p.w_scale = p_scale_in_deq ? (rt->vtcm_scale + (p_per_ch ? nc : 0)) : NULL;
+ hmx_f16_dequant_weight_chunk(octx, &rt->deq_p);
+
+ 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, (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_f16_matmul_task_init(&task, rt->vtcm_output, rt->vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2],
+ rt->vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_f16_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.n_cols = (int) n_cols;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ rt->out_p.w_scale = p_scale_in_ep ? (rt->vtcm_scale + (p_per_ch ? nc : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &rt->out_p);
+ }
+ 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, rt->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);
+ }
+ }
+ }
+}
+
+int hmx_f16_mm_nx_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 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 int weight_type = (int) src0->type;
+ const int k = (int) act->ne[0];
+ const int k_valid = (int) act->ne[0];
+ 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 int act_stride = (int) (act->nb[1] / act_elem_size);
+ const dma_addr_t act_dma_addr = act->data;
+ const size_t row_stride = htp_tensor_get_row_size(weight_type, k);
+
+ 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;
+ const bool is_tiled = (tile_size > 0);
+ tiled_dequant_task_fn_t dequant_worker_fn = hmx_f16_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->flags & HTP_MM_FLAG_PIPELINE) != 0;
+ 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;
+
+ 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;
+ }
+ }
+
+ const struct htp_tensor * norm_w = (kparams->norm_w_idx != 0) ? octx->src[kparams->norm_w_idx] : NULL;
+ const size_t vtcm_norm_bytes = norm_w ? htp_mm_fused_norm_vtcm_bytes((uint32_t) k) : 0;
+
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_ex_scaled(&L, HTP_MM_KERNEL_HMX_F16_2D, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, 0,
+ (size_t) kparams->vtcm_scale_size, 0, max_dst_elem_size, vtcm_norm_bytes);
+
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-f16-mm-nx-2d: VTCM overflow: used %zu budget %zu, m %d k %d mc %d nc %d",
+ L.total_bytes, vtcm_budget, m, k, m_chunk_n_rows, n_chunk_n_cols);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * const base = (uint8_t *) ctx->vtcm_base;
+ __fp16 * vtcm_weight_raw[2] = {
+ VTCM_LAYOUT_PTR(__fp16, base, L.off_weight[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(__fp16, 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_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);
+ 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(__fp16, base, L.off_scales);
+ float * vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, kparams->scale_mask != 0);
+ float * vtcm_norm = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_norm, norm_w != NULL);
+ if (norm_w) {
+ htp_mm_load_norm(octx->ctx->dma[0], vtcm_norm, vtcm_f32_act, norm_w, (uint32_t) k_valid, act_elem_size == sizeof(__fp16));
+ }
+
+ hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00));
+ 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-f16-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);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ hmx_f16_mm_nx_2d_rt_t rt = {
+ .octx = octx,
+ .kparams = kparams,
+ .act_params = {
+ .ctx = ctx,
+ .dst = vtcm_f16_act,
+ .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,
+ .vtcm_norm = vtcm_norm,
+ .norm_eps = kparams->norm_eps,
+ },
+ .deq_p = {
+ .k_block = k,
+ .row_stride = row_stride,
+ .weight_type = weight_type,
+ .n_k_tiles = n_k_tiles,
+ .n_k_tiles_div = n_k_tiles_div,
+ .dequant_worker_fn = dequant_worker_fn,
+ },
+ .out_p = {
+ .bias_elem_size = sizeof(float),
+ },
+ .vtcm_weight_raw = { vtcm_weight_raw[0], vtcm_weight_raw[1] },
+ .vtcm_f16_act = vtcm_f16_act,
+ .vtcm_output = vtcm_output,
+ .vtcm_scratch0 = vtcm_scratch0,
+ .vtcm_scratch1 = vtcm_scratch1,
+ .vtcm_scratch2 = vtcm_scratch2,
+ .vtcm_res_out = { vtcm_res_out[0], vtcm_res_out[1] },
+ .vtcm_scales = vtcm_scales,
+ .vtcm_scale = vtcm_scale,
+ .act_dma_addr = act_dma_addr,
+ .m_start = (size_t) m_start,
+ .mr_end = (size_t) (m_start + m_rows),
+ .n_weights = n_weights,
+ .act_elem_size = act_elem_size,
+ .dma_dst_stride = dma_dst_stride,
+ .dma_width_bytes = dma_width_bytes,
+ .act_stride = act_stride,
+ .m_chunk_n_rows = m_chunk_n_rows,
+ .n_chunk_n_cols = n_chunk_n_cols,
+ .n_k_tiles = n_k_tiles,
+ .n_weight_tiles = n_weight_tiles,
+ .tile_size = tile_size,
+ .weight_type = weight_type,
+ .is_tiled = is_tiled,
+ };
+
+ if (pipeline) {
+ hmx_f16_mm_nx_2d_pipelined(&rt);
+ } else {
+ hmx_f16_mm_nx_2d_seq(&rt);
+ }
+
+ return HTP_STATUS_OK;
+}
+
+int hmx_f16_mm_id_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_id_2d_params_t * p) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t dst = p->dsts[0];
+ const dma_addr_t activation = p->activation;
+ const size_t act_elem_size = p->act_elem_size;
+ const size_t dst_elem_size = p->dst_elem_size;
+ const dma_addr_t weight = p->weights[0];
+ const int m = p->m;
+ const int k = p->k;
+ const int n = p->n;
+ const int k_valid = p->k_valid;
+ const int ne11 = p->ne11;
+ const size_t act_nb1 = p->act_nb1;
+ const size_t act_nb2 = p->act_nb2;
+ const size_t dst_nb1 = p->dst_nb1;
+ const size_t dst_nb2 = p->dst_nb2;
+ const int weight_stride = p->weight_stride;
+ const int weight_type = p->weight_type;
+ const struct mmid_row_mapping * matrix_rows = p->matrix_rows;
+ const int cur_a = p->cur_a;
+ const int mapping_stride = p->mapping_stride;
+ const int m_start = p->m_start;
+ const int m_end = p->m_end;
+ const dma_addr_t scale_addr = (p->scale_addrs && p->scale_bytes_arr) ? p->scale_addrs[0] : 0;
+ const size_t scale_bytes = (p->scale_addrs && p->scale_bytes_arr) ? p->scale_bytes_arr[0] : 0;
+ const bool scale_per_channel = (p->scale_per_ch_arr != NULL) && (p->scale_per_ch_arr[0] != 0);
+
+ const int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+
+ 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);
+ const size_t row_stride = htp_tensor_get_row_size(weight_type, k);
+
+ const int n_k_tiles = k / HTP_MM_HMX_TILE_N_COLS;
+ const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(weight_type);
+ const struct fastdiv_values n_k_tiles_div = kparams->div_n_k_tiles;
+ const size_t vtcm_budget = ctx->vtcm_size;
+ size_t vtcm_used = 0;
+
+ const bool is_tiled = (tile_size > 0);
+ tiled_dequant_task_fn_t dequant_worker_fn = hmx_f16_get_dequant_worker_fn(weight_type, is_tiled);
+
+ const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride;
+ 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 bool has_scale = (scale_bytes > 0 && scale_addr != 0);
+ const size_t vtcm_scale_bytes = has_scale ? hex_align_up(scale_bytes, 128) : 0;
+
+ size_t m_chunk_n_rows = 0, n_chunk_n_cols = 0;
+ int act_hvx = 0;
+ if (!htp_mm_hmx_solve_2d_params_ex_scaled(
+ HTP_MM_KERNEL_HMX_F16_2D, 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, vtcm_scale_bytes, 0, 0, dst_elem_size, vtcm_budget,
+ &m_chunk_n_rows, &n_chunk_n_cols, &act_hvx, &vtcm_used)) {
+ FARF(ERROR, "hmx-f16-mm-id-2d: 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_scaled(
+ &L, HTP_MM_KERNEL_HMX_F16_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, vtcm_scale_bytes, 0, dst_elem_size, 0);
+
+ 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);
+ float * vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, has_scale);
+ 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 (has_scale) {
+ htp_mm_load_scale(weight_dma, vtcm_scale, scale_addr, scale_bytes, !scale_per_channel);
+ }
+ const bool scale_in_dequant = has_scale && hmx_f16_scales_in_dequant(weight_type);
+ const bool scale_in_epilogue = has_scale && !scale_in_dequant;
+ const uint32_t scale_ct_stride = scale_per_channel ? 32u : 0u;
+ const uint32_t scale_c_mask = scale_per_channel ? ~0u : 0u;
+ if (L.lut_bytes > 0) {
+ iq2xxs_lut_copy(vtcm_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);
+ hmx_f16_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 uint32_t n_chunk_cnt = (uint32_t) 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_f16_act_gathered_params_t act_p = {
+ .dst = vtcm_f16_act,
+ .act_dma_addr = activation,
+ .act_elem_size = act_elem_size,
+ .k_block = k,
+ .matrix_rows = matrix_rows,
+ .cur_a = cur_a,
+ .mapping_stride = mapping_stride,
+ .ne11 = ne11,
+ .nb11 = act_nb1,
+ .nb12 = act_nb2,
+ .k_valid = k_valid,
+ .n_hvx = act_hvx,
+ .act_hvx_div = &act_hvx_div,
+ .ne11_div = &kparams->div_ne1,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ };
+ hmx_f16_dequant_weight_params_t deq_p = {
+ .k_block = k,
+ .row_stride = row_stride,
+ .weight_type = weight_type,
+ .n_k_tiles = n_k_tiles,
+ .n_k_tiles_div = n_k_tiles_div,
+ .dequant_worker_fn = dequant_worker_fn,
+ .w_scale_ct_stride = scale_ct_stride,
+ };
+ hmx_f16_output_params_t out_p = {
+ .dst = vtcm_res_out,
+ .vtcm_src = vtcm_output,
+ .dst_stride = res_out_stride_elems,
+ .dst_elem_size = dst_elem_size,
+ .bias_elem_size = sizeof(float),
+ .w_scale_c_mask = scale_c_mask,
+ };
+
+ 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);
+
+ act_p.start_row = (int) mr;
+ act_p.n_rows = (int) n_rows;
+ hmx_f16_transfer_act_gathered(octx, &act_p);
+
+ 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;
+ dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
+ dma_dst_stride, dma_src_stride, dma_width_bytes, height);
+ }
+
+ out_p.n_rows = (int) n_rows;
+
+ for (uint32_t 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 = (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);
+ }
+ }
+
+ deq_p.vtcm_dst = (__fp16 *) vtcm_weight_bufs[i % 2];
+ deq_p.weight_src_ddr = curr_raw;
+ deq_p.n_cols = (int) n_cols;
+ deq_p.w_scale = scale_in_dequant ? (vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_f16_dequant_weight_chunk(octx, &deq_p);
+
+ 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 = 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_f16_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_f16_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ out_p.n_cols = (int) n_cols;
+ out_p.dst_cols = (int) n_cols;
+ out_p.w_scale = scale_in_epilogue ? (vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_f16_transfer_output(octx, &out_p);
+
+ if (overlap_w_next) {
+ push_scattered_dst_rows(
+ 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(
+ 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);
+ }
+ }
+ }
+
+ return 0;
+}
diff --git a/ggml/src/ggml-hexagon/htp/matmul-hmx-f16.h b/ggml/src/ggml-hexagon/htp/matmul-hmx-f16.h
new file mode 100644
index 000000000..85e99355f
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-hmx-f16.h
@@ -0,0 +1,25 @@
+#ifndef HTP_MATMUL_HMX_F16_H
+#define HTP_MATMUL_HMX_F16_H
+
+#include "matmul-internal.h"
+
+int hmx_f16_mm_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_2d_params_t * p);
+
+int hmx_f16_mm_batched(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_batched_params_t * params);
+
+int hmx_f16_mm_nx_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
+
+int hmx_f16_mm_nx_glu_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
+
+int hmx_f16_mm_id_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_id_2d_params_t * p);
+
+#endif // HTP_MATMUL_HMX_F16_H
diff --git a/ggml/src/ggml-hexagon/htp/matmul-hmx-w8a8.c b/ggml/src/ggml-hexagon/htp/matmul-hmx-w8a8.c
new file mode 100644
index 000000000..a8a7f78a6
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-hmx-w8a8.c
@@ -0,0 +1,2493 @@
+#include "matmul-hmx-w8a8.h"
+#include "hmx-mm-w8a8-kernels.h"
+
+// --- W8A8 HMX Threaded Helpers ---
+
+static void hmx_w8a8_rescale_weight_worker(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);
+ const uint32_t n_tasks = state->n_tasks;
+ const uint32_t n_tot_units = state->n_tot_units;
+ const uint32_t n_groups = state->n_groups;
+ const uint32_t n_col_tiles = state->n_col_tiles;
+ if (n_groups > 1u && state->tail_tiles < HTP_MM_HMX_W8A8_KGROUP_TILES && n_tot_units > n_tasks) {
+ // Assign shorter tail superblocks first in strided order so threads with an extra unit get a tail unit.
+ const uint32_t n_groups_m1 = n_groups - 1u;
+ for (uint32_t idx = i; idx < n_tot_units; idx += n) {
+ uint32_t ct, g;
+ if (idx < n_col_tiles) {
+ ct = idx;
+ g = n_groups_m1;
+ } else {
+ const uint32_t j = idx - n_col_tiles;
+ ct = fastdiv(j, &state->n_groups_m1_div);
+ g = j - ct * n_groups_m1;
+ }
+ rescale_int_weight_unit(state, ct, g, ct * n_groups + g);
+ }
+ } else {
+ const uint32_t base = state->n_units_base;
+ const uint32_t rem = state->n_units_rem;
+ for (unsigned int task_id = i; task_id < n_tasks; task_id += n) {
+ const uint32_t start = task_id * base + (task_id < rem ? task_id : rem);
+ const uint32_t count = base + (task_id < rem ? 1u : 0u);
+ rescale_int_weight_to_int8_task(state, start, start + count);
+ }
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i);
+}
+
+typedef struct {
+ void * vtcm_weight_buf;
+ size_t weight_bias_offset;
+ float * dst_scales;
+ const void * src_raw;
+ uint32_t n_cols;
+ uint32_t k_block;
+ uint32_t n_groups;
+ const struct fastdiv_values * n_groups_div;
+ uint32_t aligned_tile_size;
+ int32_t weight_type;
+ const float * w_scale;
+ uint32_t w_scale_ct_stride;
+} hmx_w8a8_rescale_weight_params_t;
+
+static void hmx_w8a8_rescale_weight_chunk(
+ struct htp_ops_context * octx,
+ const hmx_w8a8_rescale_weight_params_t * p) {
+ const uint32_t n_hvx = octx->n_hvx;
+ const uint32_t n_col_tiles = (uint32_t) hmx_ceil_div(p->n_cols, 32);
+ const uint32_t n_k_tiles = p->k_block >> 5;
+ const uint32_t tail_tiles = n_k_tiles - (p->n_groups - 1u) * HTP_MM_HMX_W8A8_KGROUP_TILES;
+ const uint32_t n_tot_units = n_col_tiles * p->n_groups;
+ if (n_tot_units == 0) {
+ return;
+ }
+
+ const uint32_t n_tasks = hex_smin(n_tot_units, n_hvx);
+ const uint32_t n_units_base = (n_tasks <= 1u) ? n_tot_units
+ : ((n_tasks == n_hvx) ? fastdiv(n_tot_units, &octx->n_hvx_div) : 1u);
+ const uint32_t n_units_rem = n_tot_units - n_units_base * n_tasks;
+
+ const bool use_fwht = (((const struct htp_mm_kernel_params *) octx->kernel_params)->flags & HTP_MM_FLAG_FWHT) != 0;
+ int_weight_rescale_state_t state;
+ resolve_int_weight_rescale_fns(p->weight_type, use_fwht, &state.rescale_2k_fn, &state.rescale_tail_fn);
+ state.dst_wt_base = (uint8_t *) p->vtcm_weight_buf;
+ state.dst_bias_base = (uint8_t *) p->vtcm_weight_buf + p->weight_bias_offset;
+ state.dst_scales_base = p->dst_scales;
+ state.w_scale = p->w_scale;
+ state.w_scale_ct_stride = p->w_scale_ct_stride;
+ state.src_raw = (const uint8_t *) p->src_raw;
+ state.n_col_tiles = n_col_tiles;
+ state.n_k_tiles = n_k_tiles;
+ state.n_groups = p->n_groups;
+ state.tail_tiles = tail_tiles;
+ state.aligned_tile_size = p->aligned_tile_size;
+ state.raw_shift = (p->weight_type == HTP_TYPE_Q1_0) ? 2u
+ : ((p->weight_type == HTP_TYPE_Q2_0) ? 1u : 0u);
+ state.n_tot_units = n_tot_units;
+ state.n_units_base = n_units_base;
+ state.n_units_rem = n_units_rem;
+ state.n_tasks = n_tasks;
+ state.n_groups_div = *p->n_groups_div;
+ state.n_groups_m1_div = (p->n_groups > 1u) ? init_fastdiv_values(p->n_groups - 1u) : (struct fastdiv_values){0, 0};
+
+ work_queue_run(octx->ctx->hvx_queue, hmx_w8a8_rescale_weight_worker, &state, (int) state.n_tasks);
+}
+
+typedef void (*hmx_w8a8_act_transfer_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,
+ bool use_fwht,
+ const float * vtcm_norm,
+ float norm_eps,
+ struct htp_thread_trace * tr);
+
+typedef struct {
+ hmx_w8a8_act_transfer_fn_t transfer_fn;
+ uint8_t * vtcm_act_dst;
+ float * vtcm_act_scales;
+ dma_addr_t act_dma_addr;
+ float * vtcm_f32_act;
+ const float * vtcm_norm;
+ float norm_eps;
+ 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;
+ bool use_fwht;
+} hmx_w8a8_act_state_t;
+
+#define DEFINE_HMX_W8A8_TRANSFER_ACT(SFX, ACT_T) \
+static void hmx_w8a8_transfer_act_##SFX( \
+ 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, \
+ bool use_fwht, \
+ const float * vtcm_norm, \
+ float norm_eps, \
+ 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); \
+ if (vtcm_norm != NULL && valid_rows > 0) { \
+ hvx_rms_norm_mul_rows_##SFX(curr_buf, row_bytes, valid_rows, k_valid, vtcm_norm, norm_eps); \
+ } \
+ quantize_act_step_rows_##SFX##_w8a8( \
+ vtcm_act_dst, vtcm_act_scales, curr_buf, row_bytes, \
+ r, valid_rows, mc_pad, n_k_tiles, n_groups, k_valid, use_fwht); \
+ 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_HMX_W8A8_TRANSFER_ACT(f16, __fp16)
+DEFINE_HMX_W8A8_TRANSFER_ACT(f32, float)
+
+static inline hmx_w8a8_act_transfer_fn_t resolve_hmx_w8a8_act_transfer_fn(uint32_t act_elem_size) {
+ return (act_elem_size == sizeof(__fp16)) ? hmx_w8a8_transfer_act_f16
+ : hmx_w8a8_transfer_act_f32;
+}
+
+static void hmx_w8a8_transfer_act_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ hmx_w8a8_act_state_t * st = (hmx_w8a8_act_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->transfer_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, st->use_fwht,
+ st->vtcm_norm, st->norm_eps, tr);
+ }
+}
+
+typedef struct {
+ 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;
+ bool use_fwht;
+ const float * vtcm_norm;
+ float norm_eps;
+} hmx_w8a8_act_params_t;
+
+static void hmx_w8a8_transfer_act(const hmx_w8a8_act_params_t * p) {
+ if (p->n_rows <= 0) {
+ return;
+ }
+
+ const uint32_t mc_pad = hex_align_up((uint32_t) p->n_rows, 64u);
+ const uint32_t resolved_esize = p->act_elem_size ? p->act_elem_size : (uint32_t) sizeof(float);
+ uint32_t rows_per_task = (p->n_hvx <= 1) ? mc_pad : fastdiv(mc_pad + (uint32_t) p->n_hvx - 1, p->act_hvx_div);
+ rows_per_task = hex_align_up(rows_per_task, 4u);
+
+ hmx_w8a8_act_state_t state;
+ state.transfer_fn = resolve_hmx_w8a8_act_transfer_fn(resolved_esize);
+ state.vtcm_act_dst = p->vtcm_act_dst;
+ state.vtcm_act_scales = p->vtcm_act_scales;
+ state.act_dma_addr = p->act_dma_addr;
+ state.vtcm_f32_act = p->vtcm_f32_act;
+ state.vtcm_norm = p->vtcm_norm;
+ state.norm_eps = p->norm_eps;
+ state.n_rows = (uint32_t) p->n_rows;
+ state.mc_pad = mc_pad;
+ state.n_rows_per_task = rows_per_task;
+ state.n_tasks = (uint32_t) hex_smin(p->n_hvx, (int) (mc_pad >> 2));
+ state.k_block = (uint32_t) p->k_block;
+ state.k_stride = (uint32_t) p->k_stride;
+ state.k_valid = (uint32_t) p->k_valid;
+ state.n_groups = (uint32_t) p->n_groups;
+ state.vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(p->vtcm_f32_act_bytes, p->act_hvx_div), 128);
+ state.use_fwht = p->use_fwht;
+
+ work_queue_run(p->ctx->hvx_queue, hmx_w8a8_transfer_act_worker, &state, (int) state.n_tasks);
+}
+
+typedef struct {
+ w8a8_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;
+} hmx_w8a8_output_state_t;
+
+static void hmx_w8a8_transfer_output_col_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ (void) n;
+ hmx_w8a8_output_state_t * st = (hmx_w8a8_output_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 hmx_w8a8_transfer_output_row_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ hmx_w8a8_output_state_t * st = (hmx_w8a8_output_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);
+}
+
+typedef struct {
+ 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;
+} hmx_w8a8_output_params_t;
+
+static void hmx_w8a8_transfer_output(
+ struct htp_ops_context * octx,
+ const hmx_w8a8_output_params_t * p) {
+ if (p->n_rows <= 0 || p->dst_cols <= 0) {
+ return;
+ }
+
+ const int n_hvx = (int) octx->n_hvx;
+ const uint32_t mc_pad = hex_align_up((uint32_t) p->n_rows, 64u);
+ const bool dst_aligned_nt = ((((uintptr_t) p->dst | ((size_t) p->dst_stride * p->dst_elem_size)) & 127u) == 0);
+
+ hmx_w8a8_output_state_t state;
+ state.col_chunk_fn = resolve_w8a8_output_col_chunk_fn((uint32_t) p->n_groups, p->dst_elem_size, p->bias, p->bias_elem_size, dst_aligned_nt);
+ state.dst = p->dst;
+ state.bias = p->bias;
+ state.vtcm_src = (const uint8_t *) p->vtcm_src;
+ state.vtcm_act_scales = p->vtcm_act_scales;
+ state.vtcm_weight_scales = p->vtcm_weight_scales;
+ state.n_rows = (uint32_t) p->n_rows;
+ state.mc_pad = mc_pad;
+ state.n_cols = (uint32_t) p->n_cols;
+ state.n_groups = (uint32_t) p->n_groups;
+ state.dst_stride = (uint32_t) p->dst_stride;
+ state.bias_stride = p->bias_stride;
+ state.dst_cols = (uint32_t) p->dst_cols;
+ state.dst_elem_size = p->dst_elem_size;
+ state.bias_elem_size = p->bias_elem_size;
+ state.n_hvx_div = octx->n_hvx_div;
+
+ const uint32_t n_blocks = hmx_ceil_div((uint32_t) p->n_cols, 32);
+ const uint32_t n_units = (p->dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks;
+ const bool prefer_row_chunk = ((uint32_t) p->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, hmx_w8a8_transfer_output_col_worker, &state, n_hvx);
+ return;
+ }
+
+ const int actual_hvx = hex_smin(n_hvx, (p->n_rows + 3) >> 2);
+ work_queue_run(octx->ctx->hvx_queue, hmx_w8a8_transfer_output_row_worker, &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;
+ bool use_fwht;
+} hmx_w8a8_act_gathered_state_t;
+
+static void hmx_w8a8_transfer_act_gathered_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+ hmx_w8a8_act_gathered_state_t * st = (hmx_w8a8_act_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_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_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_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, st->use_fwht);
+ } 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, st->use_fwht);
+ }
+ 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_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);
+ }
+ }
+ }
+}
+
+typedef struct {
+ 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;
+ const struct fastdiv_values * ne11_div;
+ float * vtcm_f32_act;
+ size_t vtcm_f32_act_bytes;
+ bool use_fwht;
+} hmx_w8a8_act_gathered_params_t;
+
+static void hmx_w8a8_transfer_act_gathered(const hmx_w8a8_act_gathered_params_t * p) {
+ if (p->n_rows <= 0) {
+ return;
+ }
+
+ const uint32_t mc_pad = hex_align_up((uint32_t) p->n_rows, 64u);
+ const uint32_t resolved_esize = p->act_elem_size ? p->act_elem_size : (uint32_t) sizeof(float);
+
+ hmx_w8a8_act_gathered_state_t state = {
+ .matrix_rows = p->matrix_rows,
+ .vtcm_act_dst = p->vtcm_act_dst,
+ .vtcm_act_scales = p->vtcm_act_scales,
+ .act_dma_addr = p->act_dma_addr,
+ .vtcm_f32_act = p->vtcm_f32_act,
+ .act_elem_size = resolved_esize,
+ .n_tasks = (uint32_t) hex_smin(p->n_hvx, (int) (mc_pad >> 2)),
+ .n_rows = (uint32_t) p->n_rows,
+ .mc_pad = mc_pad,
+ .k_block = (uint32_t) p->k_block,
+ .k_valid = (uint32_t) p->k_valid,
+ .n_groups = (uint32_t) p->n_groups,
+ .vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(p->vtcm_f32_act_bytes, p->act_hvx_div), 128),
+ .start_row = (uint32_t) p->start_row,
+ .cur_a = (uint32_t) p->cur_a,
+ .mapping_stride = (uint32_t) p->mapping_stride,
+ .ne11 = (uint32_t) p->ne11,
+ .ne11_div = *p->ne11_div,
+ .nb11 = p->nb11,
+ .nb12 = p->nb12,
+ .use_fwht = p->use_fwht,
+ };
+
+ work_queue_run(p->ctx->hvx_queue, hmx_w8a8_transfer_act_gathered_worker, &state, (int) state.n_tasks);
+}
+
+// --- Async W8A8 HMX Matmul Task ---
+
+typedef struct {
+ uint8_t * output;
+ const uint8_t * activation;
+ const uint8_t * weight;
+ 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_w8a8_matmul_task_t;
+
+static void hmx_w8a8_matmul_worker(const htp_thread_t * th, void * data) {
+ (void) th;
+ hmx_w8a8_matmul_task_t * task = (hmx_w8a8_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(task->output, task->activation, task->weight, task->weight_bias,
+ task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles, task->n_groups);
+}
+
+static inline void hmx_w8a8_matmul_task_init(
+ hmx_w8a8_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 = (uint8_t *) output;
+ task->activation = (const uint8_t *) activation;
+ task->weight = (const uint8_t *) weight_buf;
+ 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;
+}
+
+// --- W8A8 HMX Drivers ---
+
+typedef struct {
+ struct htp_ops_context * octx;
+ const hmx_mm_2d_params_t * p;
+ const struct htp_mm_hmx_vtcm_layout * L;
+ hmx_w8a8_act_params_t act_p;
+ hmx_w8a8_rescale_weight_params_t rescale_p;
+ hmx_w8a8_output_params_t out_p;
+ void * vtcm_weight_raw[2];
+ uint8_t * vtcm_act;
+ void * vtcm_output[2];
+ void * vtcm_scratch[2];
+ void * vtcm_res_in[2];
+ void * vtcm_res_out[2];
+ void * vtcm_bias;
+ float * vtcm_scale;
+ size_t m_chunk_n_rows;
+ size_t n_chunk_n_cols;
+ uint32_t n_chunk_cnt;
+ int n_k_tiles;
+ int n_weight_tiles;
+ int tile_size;
+ int aligned_tile_size;
+ int n_groups;
+ bool has_bias;
+ bool has_2d_bias;
+ bool has_scale;
+} hmx_w8a8_mm_2d_rt_t;
+
+static __attribute__((noinline)) void hmx_w8a8_mm_2d_pipelined(hmx_w8a8_mm_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const hmx_mm_2d_params_t * p = rt->p;
+ const struct htp_mm_hmx_vtcm_layout * L = rt->L;
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t dst_dma_addr = p->dst_dma_addr;
+ const dma_addr_t bias_addr = p->bias_addr;
+ const bool scale_per_channel = p->scale_per_channel;
+ const dma_addr_t act_dma_addr = p->act_dma_addr;
+ const dma_addr_t weight = p->weight;
+ const int m = p->m;
+ const int n = p->n;
+ const int act_stride = p->act_stride;
+ const uint32_t act_elem_size = p->act_elem_size;
+ const int weight_stride = p->weight_stride;
+ const int dst_stride = p->dst_stride;
+ const uint32_t bias_stride = p->bias_stride;
+ const int dst_cols = p->dst_cols;
+ const uint32_t dst_elem_size = p->dst_elem_size;
+ const uint32_t bias_elem_size = p->bias_elem_size;
+ const size_t m_chunk_n_rows = rt->m_chunk_n_rows;
+ const size_t n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int aligned_tile_size = rt->aligned_tile_size;
+ const int n_groups = rt->n_groups;
+ const bool has_bias = rt->has_bias;
+ const bool has_2d_bias = rt->has_2d_bias;
+ const bool has_scale = rt->has_scale;
+
+ hmx_w8a8_matmul_task_t task_slots[2];
+
+ 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;
+
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.bias_stride = has_2d_bias ? res_in_stride_elems : bias_stride;
+
+ const bool preissue_w0 = 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_A0 = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height_A0 = hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(rt->vtcm_weight_raw[0], weight),
+ aligned_tile_size, tile_size, tile_size, height_A0);
+ }
+
+ rt->act_p.act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size;
+ rt->act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act(&rt->act_p);
+
+ if (!preissue_w0) {
+ const size_t n_cols_A0 = hex_smin((size_t) n, n_chunk_n_cols);
+ const uint32_t height_A0 = hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], weight),
+ aligned_tile_size, tile_size, tile_size, height_A0);
+ }
+ if (1 < n_chunk_cnt) {
+ const size_t n_cols_A1 = hex_smin((size_t) n - n_chunk_n_cols, n_chunk_n_cols);
+ const uint32_t height_A1 = hmx_ceil_div(n_cols_A1, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[1], weight + n_chunk_n_cols * weight_stride),
+ aligned_tile_size, tile_size, tile_size, 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(rt->vtcm_res_in[0], bias_addr + (mr * bias_stride) * bias_elem_size),
+ res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ for (uint32_t 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);
+
+ 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;
+ }
+
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[i & 1];
+ rt->rescale_p.dst_scales = (float *) ((uint8_t *) rt->vtcm_scratch[i & 1] + L->weight_scales_offset);
+ rt->rescale_p.src_raw = curr_raw;
+ rt->rescale_p.n_cols = (uint32_t) n_cols;
+ rt->rescale_p.w_scale = has_scale ? (rt->vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+
+ if (i == 0) {
+ hmx_w8a8_matmul_task_init(&task_slots[0], rt->vtcm_output[0],
+ rt->vtcm_act, rt->vtcm_scratch[0], L->weight_bias_offset,
+ hmx_ceil_div(n_rows, 64u),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_w8a8_matmul_worker, &task_slots[0]));
+
+ 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 = hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], weight + nc2 * weight_stride),
+ aligned_tile_size, tile_size, tile_size, 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(rt->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);
+
+ hmx_queue_pop(ctx->hmx_queue);
+ hmx_w8a8_matmul_task_init(&task_slots[i & 1], rt->vtcm_output[i & 1],
+ rt->vtcm_act, rt->vtcm_scratch[i & 1], L->weight_bias_offset,
+ hmx_ceil_div(n_rows, 64u),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_w8a8_matmul_worker, &task_slots[i & 1]));
+
+ if (has_2d_bias) {
+ dma_queue_pop(weight_dma);
+ }
+
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.dst = rt->vtcm_res_out[prev];
+ rt->out_p.bias = has_2d_bias ? rt->vtcm_res_in[prev]
+ : (has_bias ? ((const uint8_t *) rt->vtcm_bias + (mr * bias_stride + nc_prev) * bias_elem_size) : NULL);
+ rt->out_p.vtcm_src = rt->vtcm_output[prev];
+ rt->out_p.vtcm_weight_scales = (const float *) ((const uint8_t *) rt->vtcm_scratch[prev] + L->weight_scales_offset);
+ rt->out_p.n_cols = (int) n_cols_p;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ hmx_w8a8_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->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 = hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[(i + 2) & 1], weight + nc_p2 * weight_stride),
+ aligned_tile_size, tile_size, tile_size, 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(rt->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);
+ }
+ }
+ }
+
+ {
+ 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) {
+ rt->out_p.dst = rt->vtcm_res_out[last];
+ rt->out_p.bias = has_2d_bias ? rt->vtcm_res_in[last]
+ : (has_bias ? ((const uint8_t *) rt->vtcm_bias + (mr * bias_stride + nc_last) * bias_elem_size) : NULL);
+ rt->out_p.vtcm_src = rt->vtcm_output[last];
+ rt->out_p.vtcm_weight_scales = (const float *) ((const uint8_t *) rt->vtcm_scratch[last] + L->weight_scales_offset);
+ rt->out_p.n_cols = (int) n_cols_last;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ hmx_w8a8_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+}
+
+static __attribute__((noinline)) void hmx_w8a8_mm_2d_seq(hmx_w8a8_mm_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const hmx_mm_2d_params_t * p = rt->p;
+ const struct htp_mm_hmx_vtcm_layout * L = rt->L;
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t dst_dma_addr = p->dst_dma_addr;
+ const bool scale_per_channel = p->scale_per_channel;
+ const dma_addr_t act_dma_addr = p->act_dma_addr;
+ const dma_addr_t weight = p->weight;
+ const int m = p->m;
+ const int n = p->n;
+ const int act_stride = p->act_stride;
+ const uint32_t act_elem_size = p->act_elem_size;
+ const int weight_stride = p->weight_stride;
+ const int dst_stride = p->dst_stride;
+ const uint32_t bias_stride = p->bias_stride;
+ const int dst_cols = p->dst_cols;
+ const uint32_t dst_elem_size = p->dst_elem_size;
+ const uint32_t bias_elem_size = p->bias_elem_size;
+ const size_t m_chunk_n_rows = rt->m_chunk_n_rows;
+ const size_t n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int aligned_tile_size = rt->aligned_tile_size;
+ const int n_groups = rt->n_groups;
+ const bool has_bias = rt->has_bias;
+ const bool has_scale = rt->has_scale;
+
+ hmx_w8a8_matmul_task_t task;
+
+ 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);
+
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[0];
+ rt->rescale_p.dst_scales = (float *) ((uint8_t *) rt->vtcm_scratch[0] + L->weight_scales_offset);
+ rt->out_p.dst = rt->vtcm_res_out[0];
+ rt->out_p.vtcm_src = rt->vtcm_output[0];
+ rt->out_p.vtcm_weight_scales = (const float *) ((const uint8_t *) rt->vtcm_scratch[0] + L->weight_scales_offset);
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.bias_stride = bias_stride;
+
+ const bool preissue_w0 = 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 = hmx_ceil_div(n_cols, 32) * n_weight_tiles;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(rt->vtcm_weight_raw[0], weight),
+ aligned_tile_size, tile_size, tile_size, height);
+ }
+
+ rt->act_p.act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size;
+ rt->act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act(&rt->act_p);
+
+ if (!preissue_w0 && n > 0) {
+ 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(rt->vtcm_weight_raw[0], weight),
+ aligned_tile_size, tile_size, tile_size, height);
+ }
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ for (uint32_t 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_row_tiles = hmx_ceil_div(n_rows, 64u);
+ const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS);
+
+ 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);
+ }
+
+ rt->rescale_p.src_raw = curr_raw;
+ rt->rescale_p.n_cols = (uint32_t) n_cols;
+ rt->rescale_p.w_scale = has_scale ? (rt->vtcm_scale + (scale_per_channel ? nc : 0)) : NULL;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+
+ const size_t nc_next = nc + 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 = hmx_ceil_div(n_cols_next, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], weight + nc_next * weight_stride),
+ aligned_tile_size, tile_size, tile_size, height_next);
+ }
+
+ hmx_w8a8_matmul_task_init(&task, rt->vtcm_output[0], rt->vtcm_act, rt->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_w8a8_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.bias = has_bias ? ((const uint8_t *) rt->vtcm_bias + (mr * bias_stride + nc) * bias_elem_size) : NULL;
+ rt->out_p.n_cols = (int) n_cols;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ hmx_w8a8_transfer_output(octx, &rt->out_p);
+ }
+ 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, rt->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);
+ }
+ }
+}
+
+int hmx_w8a8_mm_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_2d_params_t * p) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t bias_addr = p->bias_addr;
+ const size_t bias_bytes = p->bias_bytes;
+ const dma_addr_t scale_addr = p->scale_addr;
+ const size_t scale_bytes = p->scale_bytes;
+ const bool scale_per_channel = p->scale_per_channel;
+ const int m = p->m;
+ const int k = p->k;
+ const int n = p->n;
+ const int act_stride = p->act_stride;
+ const uint32_t act_elem_size = p->act_elem_size;
+ const int weight_type = p->weight_type;
+ const int k_valid = p->k_valid;
+ const uint32_t dst_elem_size = p->dst_elem_size;
+ const uint32_t bias_elem_size = p->bias_elem_size;
+
+ const int m_chunk = kparams->m_chunk;
+ const int n_chunk = kparams->n_chunk;
+ const int pipeline = (kparams->flags & HTP_MM_FLAG_PIPELINE) != 0;
+ const int act_hvx = kparams->n_act_hvx;
+ const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx;
+ const int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+ const int32_t kernel_type = kparams->kernel_type;
+ const int n_groups = kparams->hmx_n_groups;
+ const struct fastdiv_values n_groups_div = kparams->div_hmx_n_groups;
+
+ 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 size_t vtcm_budget = ctx->vtcm_size;
+
+ const size_t m_chunk_n_rows = m_chunk;
+ const size_t n_chunk_n_cols = n_chunk;
+
+ const struct htp_tensor * norm_w = (kparams->norm_w_idx != 0) ? octx->src[kparams->norm_w_idx] : NULL;
+ const size_t vtcm_norm_bytes = norm_w ? htp_mm_fused_norm_vtcm_bytes((uint32_t) k) : 0;
+
+ const bool has_bias = (bias_bytes > 0 && bias_addr != 0);
+ const bool has_2d_bias = (pipeline && !has_bias && bias_addr != 0);
+ const bool has_scale = (scale_bytes > 0 && scale_addr != 0);
+ const size_t vtcm_scale_bytes = has_scale ? hex_align_up(scale_bytes, 128) : 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_ex_scaled(&L, kernel_type, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, bias_bytes,
+ vtcm_scale_bytes, res_in_elem_size, res_out_elem_size, vtcm_norm_bytes);
+
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-w8a8-mm-2d: VTCM overflow: used %zu budget %zu, m %d k %d n %d mc %zu nc %zu",
+ L.total_bytes, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols);
+ return -1;
+ }
+
+ 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_output[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_dst[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[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_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),
+ };
+
+ if (L.lut_bytes > 0) {
+ iq2xxs_lut_copy(base + L.off_lut);
+ }
+
+ 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, bias_addr), hex_align_up(bias_bytes, 128), 0, bias_bytes, 1);
+ dma_queue_pop(weight_dma);
+ }
+
+ float * vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, has_scale);
+ if (has_scale) {
+ htp_mm_load_scale(weight_dma, vtcm_scale, scale_addr, scale_bytes, !scale_per_channel);
+ }
+ float * vtcm_norm = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_norm, norm_w != NULL);
+ if (norm_w) {
+ htp_mm_load_norm(weight_dma, vtcm_norm, vtcm_f32_act, norm_w, (uint32_t) k_valid, act_elem_size == sizeof(__fp16));
+ }
+ const uint32_t scale_ct_stride = scale_per_channel ? 32u : 0u;
+
+ FARF(HIGH, "hmx-w8a8-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, L.total_bytes, vtcm_budget);
+
+ const uint32_t n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ hmx_w8a8_mm_2d_rt_t rt = {
+ .octx = octx,
+ .p = p,
+ .L = &L,
+ .act_p = {
+ .ctx = ctx,
+ .vtcm_act_dst = vtcm_act,
+ .vtcm_act_scales = vtcm_act_scales,
+ .k_block = k,
+ .k_stride = act_stride,
+ .k_valid = k_valid,
+ .n_groups = n_groups,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ .use_fwht = (kparams->flags & HTP_MM_FLAG_FWHT) != 0,
+ .vtcm_norm = vtcm_norm,
+ .norm_eps = kparams->norm_eps,
+ },
+ .rescale_p = {
+ .weight_bias_offset = L.weight_bias_offset,
+ .k_block = (uint32_t) k,
+ .n_groups = (uint32_t) n_groups,
+ .n_groups_div = &n_groups_div,
+ .aligned_tile_size = (uint32_t) aligned_tile_size,
+ .weight_type = weight_type,
+ .w_scale_ct_stride = scale_ct_stride,
+ },
+ .out_p = {
+ .vtcm_act_scales = vtcm_act_scales,
+ .n_groups = n_groups,
+ .dst_elem_size = dst_elem_size,
+ .bias_elem_size = bias_elem_size,
+ },
+ .vtcm_weight_raw = { vtcm_weight_raw[0], vtcm_weight_raw[1] },
+ .vtcm_act = vtcm_act,
+ .vtcm_output = { vtcm_output[0], vtcm_output[1] },
+ .vtcm_scratch = { vtcm_scratch[0], vtcm_scratch[1] },
+ .vtcm_res_in = { vtcm_res_in[0], vtcm_res_in[1] },
+ .vtcm_res_out = { vtcm_res_out[0], vtcm_res_out[1] },
+ .vtcm_bias = vtcm_bias,
+ .vtcm_scale = vtcm_scale,
+ .m_chunk_n_rows = m_chunk_n_rows,
+ .n_chunk_n_cols = n_chunk_n_cols,
+ .n_chunk_cnt = n_chunk_cnt,
+ .n_k_tiles = n_k_tiles,
+ .n_weight_tiles = n_weight_tiles,
+ .tile_size = tile_size,
+ .aligned_tile_size = aligned_tile_size,
+ .n_groups = n_groups,
+ .has_bias = has_bias,
+ .has_2d_bias = has_2d_bias,
+ .has_scale = has_scale,
+ };
+
+ if (pipeline) {
+ hmx_w8a8_mm_2d_pipelined(&rt);
+ } else {
+ hmx_w8a8_mm_2d_seq(&rt);
+ }
+
+ return 0;
+}
+
+int hmx_w8a8_mm_batched(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_batched_params_t * params) {
+ hmx_mm_2d_params_t p2d = {
+ .weight_dma = params->weight_dma,
+ .bias_bytes = params->bias_bytes,
+ .scale_addr = params->scale_addr,
+ .scale_bytes = params->scale_bytes,
+ .scale_per_channel = params->scale_per_channel != 0,
+ .m = params->m,
+ .k = params->k,
+ .n = params->n,
+ .act_stride = params->act_stride,
+ .act_elem_size = params->act_elem_size,
+ .weight_stride = params->weight_stride,
+ .weight_type = params->weight_type,
+ .k_valid = params->k,
+ .dst_stride = params->dst_stride,
+ .bias_stride = params->bias_stride,
+ .dst_cols = params->dst_cols,
+ .dst_elem_size = params->dst_elem_size,
+ .bias_elem_size = params->bias_elem_size,
+ };
+
+ int ret = 0;
+ for (int b3 = 0; b3 < params->ne13 && ret == 0; ++b3) {
+ for (int b2 = 0; b2 < params->ne12 && ret == 0; ++b2) {
+ p2d.dst_dma_addr = hmx_mm_dst_batch_addr(params, b2, b3);
+ p2d.bias_addr = params->bias_addr ? (params->bias_addr + b2 * params->bias_nb2 + b3 * params->bias_nb3) : 0;
+ p2d.act_dma_addr = hmx_mm_act_batch_addr(params, b2, b3);
+ p2d.weight = hmx_mm_weight_batch_data(params, b2, b3);
+ ret = hmx_w8a8_mm_2d(octx, kparams, &p2d);
+ }
+ }
+ return ret;
+}
+
+typedef struct {
+ struct htp_ops_context * octx;
+ const struct htp_mm_hmx_vtcm_layout * L;
+ hmx_output_glu_state_t glu_state;
+ hmx_w8a8_act_params_t act_p;
+ hmx_w8a8_rescale_weight_params_t rescale_p;
+ void * vtcm_weight_raw[2];
+ uint8_t * vtcm_act;
+ void * vtcm_gate[2];
+ void * vtcm_up[2];
+ void * vtcm_scratch[2];
+ float * vtcm_wt_scales_gate[2];
+ float * vtcm_wt_scales_up[2];
+ void * vtcm_res_out[2];
+ float * vtcm_scale_gate;
+ float * vtcm_scale_up;
+ dma_addr_t act_dma_addr;
+ dma_addr_t w_gate;
+ dma_addr_t w_up;
+ dma_addr_t dst_dma_addr;
+ size_t w_gate_stride;
+ size_t w_up_stride;
+ size_t dst_stride;
+ size_t dst_row_bytes;
+ size_t dst_elem_size;
+ size_t res_out_stride_bytes;
+ size_t n;
+ size_t m_start;
+ size_t mr_end;
+ int m_chunk_n_rows;
+ int n_chunk_n_cols;
+ int act_stride;
+ int dst_cols;
+ int n_k_tiles;
+ int n_weight_tiles;
+ int tile_size;
+ int aligned_tile_size;
+ int n_groups;
+ uint32_t act_elem_size;
+ uint32_t n_chunk_cnt;
+ uint32_t gate_ct_stride;
+ uint32_t up_ct_stride;
+ bool gate_per_ch;
+ bool up_per_ch;
+} hmx_w8a8_mm_nx_glu_2d_rt_t;
+
+static __attribute__((noinline)) void hmx_w8a8_mm_nx_glu_2d_pipelined(hmx_w8a8_mm_nx_glu_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const struct htp_mm_hmx_vtcm_layout * L = rt->L;
+ dma_queue * weight_dma = ctx->dma[0];
+ const size_t n = rt->n;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int aligned_tile_size = rt->aligned_tile_size;
+ const int n_groups = rt->n_groups;
+ const size_t dst_elem_size = rt->dst_elem_size;
+ const size_t dst_stride = rt->dst_stride;
+ const size_t dst_row_bytes = rt->dst_row_bytes;
+ const size_t res_out_stride_bytes = rt->res_out_stride_bytes;
+ const int dst_cols = rt->dst_cols;
+
+ hmx_w8a8_matmul_task_t task_gate[2];
+ hmx_w8a8_matmul_task_t task_up[2];
+ const bool preissue_gate0 = L->can_preissue_weight && n > 0;
+
+ for (size_t mr = rt->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(rt->vtcm_weight_raw[0], rt->w_gate),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+
+ rt->act_p.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act(&rt->act_p);
+
+ {
+ 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(rt->vtcm_weight_raw[0], rt->w_gate),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[1], rt->w_up),
+ aligned_tile_size, tile_size, tile_size, height0);
+ }
+
+ for (uint32_t 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);
+
+ 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);
+ }
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[0];
+ rt->rescale_p.dst_scales = rt->vtcm_wt_scales_gate[cur];
+ rt->rescale_p.src_raw = rt->vtcm_weight_raw[0];
+ rt->rescale_p.n_cols = (uint32_t) n_cols;
+ rt->rescale_p.w_scale = rt->vtcm_scale_gate ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc : 0)) : NULL;
+ rt->rescale_p.w_scale_ct_stride = rt->gate_ct_stride;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+
+ hmx_w8a8_matmul_task_init(&task_gate[cur], rt->vtcm_gate[cur],
+ rt->vtcm_act, rt->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_w8a8_matmul_worker, &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(rt->vtcm_weight_raw[0], rt->w_gate + nc_n * rt->w_gate_stride),
+ aligned_tile_size, tile_size, tile_size, height_n);
+ }
+
+ dma_queue_pop(weight_dma);
+ if (s > 0) {
+ hmx_queue_pop(ctx->hmx_queue);
+ }
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[1];
+ rt->rescale_p.dst_scales = rt->vtcm_wt_scales_up[cur];
+ rt->rescale_p.src_raw = rt->vtcm_weight_raw[1];
+ rt->rescale_p.w_scale = rt->vtcm_scale_up ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc : 0)) : NULL;
+ rt->rescale_p.w_scale_ct_stride = rt->up_ct_stride;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+
+ hmx_w8a8_matmul_task_init(&task_up[cur], rt->vtcm_up[cur],
+ rt->vtcm_act, rt->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_w8a8_matmul_worker, &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(rt->vtcm_weight_raw[1], rt->w_up + nc_n * rt->w_up_stride),
+ aligned_tile_size, tile_size, tile_size, height_n);
+ }
+
+ 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) {
+ hmx_transfer_output_glu(
+ octx, &rt->glu_state, rt->vtcm_res_out[prev], rt->vtcm_gate[prev], rt->vtcm_up[prev],
+ rt->vtcm_wt_scales_gate[prev], rt->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(rt->dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, rt->vtcm_res_out[prev]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ }
+ }
+
+ {
+ 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) {
+ hmx_transfer_output_glu(
+ octx, &rt->glu_state, rt->vtcm_res_out[last], rt->vtcm_gate[last], rt->vtcm_up[last],
+ rt->vtcm_wt_scales_gate[last], rt->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(rt->dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, rt->vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+}
+
+static __attribute__((noinline)) void hmx_w8a8_mm_nx_glu_2d_seq(hmx_w8a8_mm_nx_glu_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const struct htp_mm_hmx_vtcm_layout * L = rt->L;
+ dma_queue * weight_dma = ctx->dma[0];
+ const size_t n = rt->n;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const uint32_t n_chunk_cnt = rt->n_chunk_cnt;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int aligned_tile_size = rt->aligned_tile_size;
+ const int n_groups = rt->n_groups;
+ const size_t dst_elem_size = rt->dst_elem_size;
+ const size_t dst_stride = rt->dst_stride;
+ const size_t dst_row_bytes = rt->dst_row_bytes;
+ const size_t res_out_stride_bytes = rt->res_out_stride_bytes;
+ const int dst_cols = rt->dst_cols;
+
+ hmx_w8a8_matmul_task_t task;
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[0];
+ rt->rescale_p.src_raw = rt->vtcm_weight_raw[0];
+
+ for (size_t mr = rt->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);
+
+ rt->act_p.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act(&rt->act_p);
+
+ for (uint32_t 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(rt->vtcm_weight_raw[0], rt->w_gate + nc * rt->w_gate_stride),
+ aligned_tile_size, tile_size, tile_size, height);
+ dma_queue_pop(weight_dma);
+ rt->rescale_p.dst_scales = rt->vtcm_wt_scales_gate[0];
+ rt->rescale_p.n_cols = (uint32_t) n_cols;
+ rt->rescale_p.w_scale = rt->vtcm_scale_gate ? (rt->vtcm_scale_gate + (rt->gate_per_ch ? nc : 0)) : NULL;
+ rt->rescale_p.w_scale_ct_stride = rt->gate_ct_stride;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+ hmx_w8a8_matmul_task_init(&task, rt->vtcm_gate[0], rt->vtcm_act, rt->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_w8a8_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], rt->w_up + nc * rt->w_up_stride),
+ aligned_tile_size, tile_size, tile_size, height);
+ dma_queue_pop(weight_dma);
+ rt->rescale_p.dst_scales = rt->vtcm_wt_scales_up[0];
+ rt->rescale_p.w_scale = rt->vtcm_scale_up ? (rt->vtcm_scale_up + (rt->up_per_ch ? nc : 0)) : NULL;
+ rt->rescale_p.w_scale_ct_stride = rt->up_ct_stride;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+ hmx_w8a8_matmul_task_init(&task, rt->vtcm_up[0], rt->vtcm_act, rt->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_w8a8_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ const int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ hmx_transfer_output_glu(
+ octx, &rt->glu_state, rt->vtcm_res_out[0], rt->vtcm_gate[0], rt->vtcm_up[0],
+ rt->vtcm_wt_scales_gate[0], rt->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(rt->dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, rt->vtcm_res_out[0]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+}
+
+int hmx_w8a8_mm_nx_glu_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 (n == 0) {
+ return HTP_STATUS_OK;
+ }
+
+ hmx_output_glu_state_t glu_state;
+ if (!resolve_w8a8_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 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;
+
+ 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->flags & HTP_MM_FLAG_PIPELINE) != 0;
+ const int act_hvx = kparams->n_act_hvx;
+ const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx;
+
+ const struct htp_tensor * norm_w = (kparams->norm_w_idx != 0) ? octx->src[kparams->norm_w_idx] : NULL;
+ const size_t vtcm_norm_bytes = norm_w ? htp_mm_fused_norm_vtcm_bytes((uint32_t) k) : 0;
+
+ 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, (size_t) kparams->vtcm_scale_size, vtcm_norm_bytes);
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-w8a8-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)
+ };
+
+ const struct htp_tensor * s_gate = ((kparams->scale_mask & 1u) != 0) ? octx->src[3] : NULL;
+ const struct htp_tensor * s_up = ((kparams->scale_mask & 2u) != 0) ? octx->src[4] : NULL;
+ const bool gate_per_ch = s_gate && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, 0));
+ const bool up_per_ch = s_up && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, 1));
+ const uint32_t gate_ct_stride = gate_per_ch ? 32u : 0u;
+ const uint32_t up_ct_stride = up_per_ch ? 32u : 0u;
+ const size_t gate_scale_bytes = s_gate ? (gate_per_ch ? (n * sizeof(float)) : sizeof(float)) : 0;
+ const size_t up_scale_bytes = s_up ? (up_per_ch ? (n * sizeof(float)) : sizeof(float)) : 0;
+ const size_t gate_scale_off = L.off_scale;
+ const size_t up_scale_off = L.off_scale + (s_gate ? hex_round_up(gate_scale_bytes, 128) : 0);
+ float * vtcm_scale_gate = VTCM_LAYOUT_PTR_OPTIONAL(float, base, gate_scale_off, s_gate != NULL);
+ float * vtcm_scale_up = VTCM_LAYOUT_PTR_OPTIONAL(float, base, up_scale_off, s_up != NULL);
+ if (s_gate) {
+ htp_mm_load_scale(octx->ctx->dma[0], vtcm_scale_gate, s_gate->data, gate_scale_bytes, !gate_per_ch);
+ }
+ if (s_up) {
+ htp_mm_load_scale(octx->ctx->dma[0], vtcm_scale_up, s_up->data, up_scale_bytes, !up_per_ch);
+ }
+ float * vtcm_norm = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_norm, norm_w != NULL);
+ if (norm_w) {
+ htp_mm_load_norm(octx->ctx->dma[0], vtcm_norm, vtcm_f32_act, norm_w, (uint32_t) k_valid, act_elem_size == sizeof(__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-w8a8-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 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);
+
+ 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;
+
+ hmx_w8a8_mm_nx_glu_2d_rt_t rt = {
+ .octx = octx,
+ .L = &L,
+ .glu_state = glu_state,
+ .act_p = {
+ .ctx = ctx,
+ .vtcm_act_dst = vtcm_act,
+ .vtcm_act_scales = vtcm_act_scales,
+ .k_block = k,
+ .k_stride = act_stride,
+ .k_valid = k_valid,
+ .n_groups = n_groups,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ .use_fwht = (kparams->flags & HTP_MM_FLAG_FWHT) != 0,
+ .vtcm_norm = vtcm_norm,
+ .norm_eps = kparams->norm_eps,
+ },
+ .rescale_p = {
+ .weight_bias_offset = L.weight_bias_offset,
+ .k_block = (uint32_t) k,
+ .n_groups = (uint32_t) n_groups,
+ .n_groups_div = &n_groups_div,
+ .aligned_tile_size = (uint32_t) aligned_tile_size,
+ .weight_type = weight_type,
+ },
+ .vtcm_weight_raw = { vtcm_weight_raw[0], vtcm_weight_raw[1] },
+ .vtcm_act = vtcm_act,
+ .vtcm_gate = { vtcm_gate[0], vtcm_gate[1] },
+ .vtcm_up = { vtcm_up[0], vtcm_up[1] },
+ .vtcm_scratch = { vtcm_scratch[0], vtcm_scratch[1] },
+ .vtcm_wt_scales_gate = { vtcm_wt_scales_gate[0], vtcm_wt_scales_gate[1] },
+ .vtcm_wt_scales_up = { vtcm_wt_scales_up[0], vtcm_wt_scales_up[1] },
+ .vtcm_res_out = { vtcm_res_out[0], vtcm_res_out[1] },
+ .vtcm_scale_gate = vtcm_scale_gate,
+ .vtcm_scale_up = vtcm_scale_up,
+ .act_dma_addr = act_dma_addr,
+ .w_gate = src_gate->data,
+ .w_up = src_up->data,
+ .dst_dma_addr = dst->data,
+ .w_gate_stride = src_gate->nb[1],
+ .w_up_stride = src_up->nb[1],
+ .dst_stride = dst->nb[1] / dst_elem_size,
+ .dst_row_bytes = dst->nb[1],
+ .dst_elem_size = dst_elem_size,
+ .res_out_stride_bytes = res_out_stride_bytes,
+ .n = n,
+ .m_start = (size_t) m_start,
+ .mr_end = (size_t) (m_start + m_rows),
+ .m_chunk_n_rows = m_chunk_n_rows,
+ .n_chunk_n_cols = n_chunk_n_cols,
+ .act_stride = act_stride,
+ .dst_cols = (int) dst->ne[0],
+ .n_k_tiles = n_k_tiles,
+ .n_weight_tiles = n_weight_tiles,
+ .tile_size = tile_size,
+ .aligned_tile_size = aligned_tile_size,
+ .n_groups = n_groups,
+ .act_elem_size = act_elem_size,
+ .n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols),
+ .gate_ct_stride = gate_ct_stride,
+ .up_ct_stride = up_ct_stride,
+ .gate_per_ch = gate_per_ch,
+ .up_per_ch = up_per_ch,
+ };
+
+ if (pipeline) {
+ hmx_w8a8_mm_nx_glu_2d_pipelined(&rt);
+ } else {
+ hmx_w8a8_mm_nx_glu_2d_seq(&rt);
+ }
+
+ return HTP_STATUS_OK;
+}
+
+typedef struct {
+ struct htp_ops_context * octx;
+ const struct htp_mm_kernel_params * kparams;
+ const struct htp_mm_hmx_vtcm_layout * L;
+ hmx_w8a8_act_params_t act_p;
+ hmx_w8a8_rescale_weight_params_t rescale_p;
+ hmx_w8a8_output_params_t out_p;
+ void * vtcm_weight_raw[2];
+ uint8_t * vtcm_act;
+ void * vtcm_output[2];
+ void * vtcm_scratch[2];
+ void * vtcm_res_out[2];
+ float * vtcm_scale;
+ dma_addr_t act_dma_addr;
+ size_t m_start;
+ size_t mr_end;
+ uint32_t n_weights;
+ uint32_t act_elem_size;
+ int act_stride;
+ int m_chunk_n_rows;
+ int n_chunk_n_cols;
+ int n_k_tiles;
+ int n_weight_tiles;
+ int tile_size;
+ int aligned_tile_size;
+ int n_groups;
+} hmx_w8a8_mm_nx_2d_rt_t;
+
+static __attribute__((noinline)) void hmx_w8a8_mm_nx_2d_pipelined(hmx_w8a8_mm_nx_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const struct htp_mm_kernel_params * kparams = rt->kparams;
+ const struct htp_mm_hmx_vtcm_layout * L = rt->L;
+ const uint32_t n_weights = rt->n_weights;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int aligned_tile_size = rt->aligned_tile_size;
+ const int n_groups = rt->n_groups;
+
+ hmx_w8a8_matmul_task_t task_slots[2];
+
+ const bool preissue_p0 = L->can_preissue_weight && n_weights > 0
+ && octx->src[0] && octx->dsts[0] && octx->src[0]->ne[1] > 0;
+
+ for (size_t mr = rt->m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+
+ 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 = hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles;
+ dma_proxy_push(ctx->dma_proxy, dma_make_data(rt->vtcm_weight_raw[0], src_w0->data),
+ aligned_tile_size, tile_size, tile_size, height_A0);
+ }
+
+ rt->act_p.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act(&rt->act_p);
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ 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 dma_addr_t weight = src_w->data;
+ 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_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 uint32_t n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols);
+ const bool p_preissued = (p == 0 && preissue_p0);
+
+ const struct htp_tensor * p_scale = (((kparams->scale_mask >> p) & 1u) != 0) ? octx->src[n_weights + 1 + p] : NULL;
+ const bool p_per_ch = p_scale && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, p));
+ const uint32_t p_ct_stride = p_per_ch ? 32u : 0u;
+ if (p_scale) {
+ const size_t p_sbytes = p_per_ch ? (n * sizeof(float)) : sizeof(float);
+ htp_mm_load_scale(weight_dma, rt->vtcm_scale, p_scale->data, p_sbytes, !p_per_ch);
+ }
+
+ rt->rescale_p.w_scale_ct_stride = p_ct_stride;
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.dst_elem_size = dst_elem_size;
+
+ if (!p_preissued) {
+ const size_t n_cols_A0 = hex_smin(n, (size_t) n_chunk_n_cols);
+ const uint32_t height_A0 = hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], weight),
+ aligned_tile_size, tile_size, tile_size, height_A0);
+ }
+
+ if (1 < n_chunk_cnt) {
+ 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 = hmx_ceil_div(n_cols_A1, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[1], weight + (size_t) n_chunk_n_cols * weight_stride),
+ aligned_tile_size, tile_size, tile_size, height_A1);
+ }
+
+ for (uint32_t 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, (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;
+ }
+
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[i & 1];
+ rt->rescale_p.dst_scales = (float *) ((uint8_t *) rt->vtcm_scratch[i & 1] + L->weight_scales_offset);
+ rt->rescale_p.src_raw = curr_raw;
+ rt->rescale_p.n_cols = (uint32_t) n_cols;
+ rt->rescale_p.w_scale = p_scale ? (rt->vtcm_scale + (p_per_ch ? nc : 0)) : NULL;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+
+ if (i == 0) {
+ hmx_w8a8_matmul_task_init(&task_slots[0], rt->vtcm_output[0],
+ rt->vtcm_act, rt->vtcm_scratch[0], L->weight_bias_offset,
+ hmx_ceil_div(n_rows, 64u),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_w8a8_matmul_worker, &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 = hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[0], weight + nc2 * weight_stride),
+ aligned_tile_size, tile_size, tile_size, 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);
+
+ hmx_queue_pop(ctx->hmx_queue);
+ hmx_w8a8_matmul_task_init(&task_slots[i & 1], rt->vtcm_output[i & 1],
+ rt->vtcm_act, rt->vtcm_scratch[i & 1], L->weight_bias_offset,
+ hmx_ceil_div(n_rows, 64u),
+ hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS),
+ (uint32_t) n_k_tiles, (uint32_t) n_groups);
+ hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_w8a8_matmul_worker, &task_slots[i & 1]));
+
+ const int chunk_dst_cols = dst_cols - (int) nc_prev;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.dst = rt->vtcm_res_out[prev];
+ rt->out_p.vtcm_src = rt->vtcm_output[prev];
+ rt->out_p.vtcm_weight_scales = (const float *) ((const uint8_t *) rt->vtcm_scratch[prev] + L->weight_scales_offset);
+ rt->out_p.n_cols = (int) n_cols_p;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ hmx_w8a8_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->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 = hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles;
+ dma_queue_push(weight_dma, dma_make_data(rt->vtcm_weight_raw[(i + 2) & 1], weight + nc_p2 * weight_stride),
+ aligned_tile_size, tile_size, tile_size, height_p2);
+ }
+ }
+ }
+
+ {
+ 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) {
+ rt->out_p.dst = rt->vtcm_res_out[last];
+ rt->out_p.vtcm_src = rt->vtcm_output[last];
+ rt->out_p.vtcm_weight_scales = (const float *) ((const uint8_t *) rt->vtcm_scratch[last] + L->weight_scales_offset);
+ rt->out_p.n_cols = (int) n_cols_last;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ hmx_w8a8_transfer_output(octx, &rt->out_p);
+ }
+
+ 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, rt->vtcm_res_out[last]),
+ dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0);
+ dma_queue_pop(weight_dma);
+ }
+ }
+ }
+}
+
+static __attribute__((noinline)) void hmx_w8a8_mm_nx_2d_seq(hmx_w8a8_mm_nx_2d_rt_t * rt) {
+ struct htp_ops_context * octx = rt->octx;
+ struct htp_context * ctx = octx->ctx;
+ const struct htp_mm_kernel_params * kparams = rt->kparams;
+ const struct htp_mm_hmx_vtcm_layout * L = rt->L;
+ const uint32_t n_weights = rt->n_weights;
+ const size_t mr_end = rt->mr_end;
+ const int m_chunk_n_rows = rt->m_chunk_n_rows;
+ const int n_chunk_n_cols = rt->n_chunk_n_cols;
+ const int n_k_tiles = rt->n_k_tiles;
+ const int n_weight_tiles = rt->n_weight_tiles;
+ const int tile_size = rt->tile_size;
+ const int aligned_tile_size = rt->aligned_tile_size;
+ const int n_groups = rt->n_groups;
+
+ hmx_w8a8_matmul_task_t task;
+ rt->rescale_p.vtcm_weight_buf = rt->vtcm_scratch[0];
+ rt->rescale_p.dst_scales = (float *) ((uint8_t *) rt->vtcm_scratch[0] + L->weight_scales_offset);
+ rt->out_p.dst = rt->vtcm_res_out[0];
+ rt->out_p.vtcm_src = rt->vtcm_output[0];
+ rt->out_p.vtcm_weight_scales = (const float *) ((const uint8_t *) rt->vtcm_scratch[0] + L->weight_scales_offset);
+
+ for (size_t mr = rt->m_start; mr < mr_end; mr += m_chunk_n_rows) {
+ const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows);
+
+ rt->act_p.act_dma_addr = rt->act_dma_addr + (size_t) mr * rt->act_stride * rt->act_elem_size;
+ rt->act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act(&rt->act_p);
+
+ rt->out_p.n_rows = (int) n_rows;
+
+ 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 dma_addr_t weight = src_w->data;
+ 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_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 uint32_t n_chunk_cnt = (uint32_t) hmx_ceil_div(n, n_chunk_n_cols);
+
+ const struct htp_tensor * p_scale = (((kparams->scale_mask >> p) & 1u) != 0) ? octx->src[n_weights + 1 + p] : NULL;
+ const bool p_per_ch = p_scale && htp_mm_scale_is_per_channel(htp_mm_scale_mode_get(kparams->scale_mode, p));
+ const uint32_t p_ct_stride = p_per_ch ? 32u : 0u;
+ if (p_scale) {
+ const size_t p_sbytes = p_per_ch ? (n * sizeof(float)) : sizeof(float);
+ htp_mm_load_scale(weight_dma, rt->vtcm_scale, p_scale->data, p_sbytes, !p_per_ch);
+ }
+
+ rt->rescale_p.w_scale_ct_stride = p_ct_stride;
+ rt->out_p.dst_stride = res_out_stride_elems;
+ rt->out_p.dst_elem_size = dst_elem_size;
+
+ if (n > 0) {
+ const size_t n_cols = hex_smin(n, (size_t) 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(rt->vtcm_weight_raw[0], weight),
+ aligned_tile_size, tile_size, tile_size, height);
+ }
+
+ for (uint32_t 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, (size_t) n_chunk_n_cols);
+ const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u);
+ 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);
+ }
+
+ rt->rescale_p.src_raw = curr_raw;
+ rt->rescale_p.n_cols = (uint32_t) n_cols;
+ rt->rescale_p.w_scale = p_scale ? (rt->vtcm_scale + (p_per_ch ? nc : 0)) : NULL;
+ hmx_w8a8_rescale_weight_chunk(octx, &rt->rescale_p);
+
+ 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, (size_t) 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(rt->vtcm_weight_raw[0], weight + nc_next * weight_stride),
+ aligned_tile_size, tile_size, tile_size, height_next);
+ }
+
+ hmx_w8a8_matmul_task_init(&task, rt->vtcm_output[0], rt->vtcm_act, rt->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_w8a8_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ int chunk_dst_cols = dst_cols - (int) nc;
+ if (chunk_dst_cols > 0) {
+ rt->out_p.n_cols = (int) n_cols;
+ rt->out_p.dst_cols = chunk_dst_cols;
+ hmx_w8a8_transfer_output(octx, &rt->out_p);
+ }
+ 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, rt->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);
+ }
+ }
+ }
+}
+
+int hmx_w8a8_mm_nx_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 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 int weight_type = (int) src0->type;
+ const int k = (int) act->ne[0];
+ const int k_valid = (int) act->ne[0];
+ 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 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 struct fastdiv_values n_groups_div = kparams->div_hmx_n_groups;
+
+ 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 int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+ 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->flags & HTP_MM_FLAG_PIPELINE) != 0;
+ const int act_hvx = kparams->n_act_hvx;
+ const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx;
+
+ 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;
+ }
+ }
+
+ const struct htp_tensor * norm_w = (kparams->norm_w_idx != 0) ? octx->src[kparams->norm_w_idx] : NULL;
+ const size_t vtcm_norm_bytes = norm_w ? htp_mm_fused_norm_vtcm_bytes((uint32_t) k) : 0;
+
+ struct htp_mm_hmx_vtcm_layout L;
+ htp_mm_hmx_vtcm_layout_build_ex_scaled(&L, kernel_type, weight_type, k,
+ m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, 0,
+ (size_t) kparams->vtcm_scale_size, 0, max_dst_elem_size, vtcm_norm_bytes);
+
+ if (L.total_bytes > vtcm_budget) {
+ FARF(ERROR, "hmx-w8a8-mm-nx-2d: VTCM overflow: used %zu budget %zu, m %d k %d mc %d nc %d",
+ L.total_bytes, vtcm_budget, m, k, 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_output[2] = {
+ VTCM_LAYOUT_PTR(void, base, L.off_dst[0]),
+ VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[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),
+ };
+ float * vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, kparams->scale_mask != 0);
+ float * vtcm_norm = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_norm, norm_w != NULL);
+ if (norm_w) {
+ htp_mm_load_norm(octx->ctx->dma[0], vtcm_norm, vtcm_f32_act, norm_w, (uint32_t) k_valid, act_elem_size == sizeof(__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-w8a8-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);
+
+ hmx_w8a8_mm_nx_2d_rt_t rt = {
+ .octx = octx,
+ .kparams = kparams,
+ .L = &L,
+ .act_p = {
+ .ctx = ctx,
+ .vtcm_act_dst = vtcm_act,
+ .vtcm_act_scales = vtcm_act_scales,
+ .k_block = k,
+ .k_stride = act_stride,
+ .k_valid = k_valid,
+ .n_groups = n_groups,
+ .n_hvx = act_hvx,
+ .act_hvx_div = act_hvx_div,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .act_elem_size = act_elem_size,
+ .use_fwht = (kparams->flags & HTP_MM_FLAG_FWHT) != 0,
+ .vtcm_norm = vtcm_norm,
+ .norm_eps = kparams->norm_eps,
+ },
+ .rescale_p = {
+ .weight_bias_offset = L.weight_bias_offset,
+ .k_block = (uint32_t) k,
+ .n_groups = (uint32_t) n_groups,
+ .n_groups_div = &n_groups_div,
+ .aligned_tile_size = (uint32_t) aligned_tile_size,
+ .weight_type = weight_type,
+ },
+ .out_p = {
+ .vtcm_act_scales = vtcm_act_scales,
+ .n_groups = n_groups,
+ .bias_elem_size = sizeof(float),
+ },
+ .vtcm_weight_raw = { vtcm_weight_raw[0], vtcm_weight_raw[1] },
+ .vtcm_act = vtcm_act,
+ .vtcm_output = { vtcm_output[0], vtcm_output[1] },
+ .vtcm_scratch = { vtcm_scratch[0], vtcm_scratch[1] },
+ .vtcm_res_out = { vtcm_res_out[0], vtcm_res_out[1] },
+ .vtcm_scale = vtcm_scale,
+ .act_dma_addr = act_dma_addr,
+ .m_start = (size_t) m_start,
+ .mr_end = (size_t) (m_start + m_rows),
+ .n_weights = n_weights,
+ .act_elem_size = act_elem_size,
+ .act_stride = act_stride,
+ .m_chunk_n_rows = m_chunk_n_rows,
+ .n_chunk_n_cols = n_chunk_n_cols,
+ .n_k_tiles = n_k_tiles,
+ .n_weight_tiles = n_weight_tiles,
+ .tile_size = tile_size,
+ .aligned_tile_size = aligned_tile_size,
+ .n_groups = n_groups,
+ };
+
+ if (pipeline) {
+ hmx_w8a8_mm_nx_2d_pipelined(&rt);
+ } else {
+ hmx_w8a8_mm_nx_2d_seq(&rt);
+ }
+
+ return HTP_STATUS_OK;
+}
+
+int hmx_w8a8_mm_id_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_id_2d_params_t * p) {
+ struct htp_context * ctx = octx->ctx;
+ struct htp_thread_trace * tr = &ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ dma_queue * const weight_dma = p->weight_dma;
+ const dma_addr_t * const dsts = p->dsts;
+ const dma_addr_t activation = p->activation;
+ const size_t act_elem_size = p->act_elem_size;
+ const size_t dst_elem_size = p->dst_elem_size;
+ const dma_addr_t * const weights = p->weights;
+ const uint32_t n_weights = p->n_weights;
+ const int m = p->m;
+ const int k = p->k;
+ const int n = p->n;
+ const int k_valid = p->k_valid;
+ const int ne11 = p->ne11;
+ const size_t act_nb1 = p->act_nb1;
+ const size_t act_nb2 = p->act_nb2;
+ const size_t dst_nb1 = p->dst_nb1;
+ const size_t dst_nb2 = p->dst_nb2;
+ const int weight_stride = p->weight_stride;
+ const int weight_type = p->weight_type;
+ const struct mmid_row_mapping * matrix_rows = p->matrix_rows;
+ const int cur_a = p->cur_a;
+ const int mapping_stride = p->mapping_stride;
+ const int m_start = p->m_start;
+ const int m_end = p->m_end;
+ const dma_addr_t * const scale_addrs = p->scale_addrs;
+ const size_t * const scale_bytes_arr = p->scale_bytes_arr;
+ const uint8_t * const scale_per_ch_arr = p->scale_per_ch_arr;
+
+ const int tile_size = kparams->tile_size;
+ const int aligned_tile_size = kparams->aligned_tile_size;
+ const int32_t kernel_type = kparams->kernel_type;
+
+ 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);
+
+ const uint32_t n_groups = kparams->hmx_n_groups;
+ 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 = kparams->div_hmx_n_groups;
+
+ size_t vtcm_scale_bytes = 0;
+ if (scale_addrs && scale_bytes_arr) {
+ for (uint32_t w = 0; w < n_weights; ++w) {
+ if (scale_addrs[w] != 0 && scale_bytes_arr[w] > 0) {
+ const size_t sb = hex_align_up(scale_bytes_arr[w], 128);
+ if (sb > vtcm_scale_bytes) {
+ vtcm_scale_bytes = sb;
+ }
+ }
+ }
+ }
+ const bool has_any_scale = (vtcm_scale_bytes > 0);
+
+ 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_hmx_solve_2d_params_ex_scaled(
+ 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, vtcm_scale_bytes, 0, 0, dst_elem_size, vtcm_budget,
+ &m_chunk_n_rows, &n_chunk_n_cols, &act_hvx, &vtcm_used)) {
+ FARF(ERROR, "hmx-w8a8-mm-id-2d: 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_scaled(
+ &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, vtcm_scale_bytes, 0, dst_elem_size, 0);
+
+ 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]);
+ float * vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, has_any_scale);
+ 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 uint32_t n_chunk_cnt = (uint32_t) 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_w8a8_matmul_task_t task;
+
+ hmx_w8a8_act_gathered_params_t act_p = {
+ .ctx = ctx,
+ .vtcm_act_dst = vtcm_act,
+ .vtcm_act_scales = vtcm_act_scales,
+ .act_dma_addr = activation,
+ .act_elem_size = (uint32_t) act_elem_size,
+ .k_block = k,
+ .k_valid = k_valid,
+ .n_groups = (int) n_groups,
+ .matrix_rows = matrix_rows,
+ .cur_a = cur_a,
+ .mapping_stride = mapping_stride,
+ .ne11 = ne11,
+ .nb11 = act_nb1,
+ .nb12 = act_nb2,
+ .n_hvx = act_hvx,
+ .act_hvx_div = &act_hvx_div,
+ .ne11_div = &kparams->div_ne1,
+ .vtcm_f32_act = vtcm_f32_act,
+ .vtcm_f32_act_bytes = L.act_f32_bytes,
+ .use_fwht = (kparams->flags & HTP_MM_FLAG_FWHT) != 0,
+ };
+ hmx_w8a8_rescale_weight_params_t rescale_p = {
+ .vtcm_weight_buf = vtcm_scratch0,
+ .weight_bias_offset = L.weight_bias_offset,
+ .dst_scales = (float *) ((uint8_t *) vtcm_scratch0 + L.weight_scales_offset),
+ .k_block = (uint32_t) k,
+ .n_groups = n_groups,
+ .n_groups_div = &n_groups_div,
+ .aligned_tile_size = (uint32_t) aligned_tile_size,
+ .weight_type = weight_type,
+ };
+ hmx_w8a8_output_params_t out_p = {
+ .dst = vtcm_res_out,
+ .vtcm_src = vtcm_output,
+ .vtcm_act_scales = vtcm_act_scales,
+ .vtcm_weight_scales = (const float *) ((const uint8_t *) vtcm_scratch0 + L.weight_scales_offset),
+ .n_groups = (int) n_groups,
+ .dst_stride = res_out_stride_elems,
+ .dst_elem_size = dst_elem_size,
+ .bias_elem_size = sizeof(float),
+ };
+
+ 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);
+ }
+
+ act_p.start_row = (int) mr;
+ act_p.n_rows = (int) n_rows;
+ hmx_w8a8_transfer_act_gathered(&act_p);
+
+ out_p.n_rows = (int) n_rows;
+
+ for (uint32_t w = 0; w < n_weights; ++w) {
+ const dma_addr_t weight_p = weights[w];
+ const dma_addr_t dst_p = dsts[w];
+ const bool p_preissued = (w == 0 && preissue_p0);
+ const bool p_has_scale = (scale_addrs && scale_bytes_arr && scale_addrs[w] != 0 && scale_bytes_arr[w] > 0);
+ const bool p_per_ch = p_has_scale && scale_per_ch_arr && (scale_per_ch_arr[w] != 0);
+ const uint32_t p_ct_stride = p_per_ch ? 32u : 0u;
+ if (p_has_scale) {
+ htp_mm_load_scale(weight_dma, vtcm_scale, scale_addrs[w], scale_bytes_arr[w], !p_per_ch);
+ }
+
+ rescale_p.w_scale_ct_stride = p_ct_stride;
+
+ 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 (uint32_t 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_p.src_raw = curr_raw;
+ rescale_p.n_cols = (uint32_t) n_cols;
+ rescale_p.w_scale = p_has_scale ? (vtcm_scale + (p_per_ch ? nc : 0)) : NULL;
+ hmx_w8a8_rescale_weight_chunk(octx, &rescale_p);
+
+ 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_w8a8_matmul_task_init(&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_w8a8_matmul_worker, &task));
+ hmx_queue_pop(ctx->hmx_queue);
+
+ out_p.n_cols = (int) n_cols;
+ out_p.dst_cols = (int) n_cols;
+ hmx_w8a8_transfer_output(octx, &out_p);
+
+ if (overlap_w_next) {
+ push_scattered_dst_rows(
+ 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(
+ 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;
+}
diff --git a/ggml/src/ggml-hexagon/htp/matmul-hmx-w8a8.h b/ggml/src/ggml-hexagon/htp/matmul-hmx-w8a8.h
new file mode 100644
index 000000000..fb1f5ef4e
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-hmx-w8a8.h
@@ -0,0 +1,25 @@
+#ifndef HTP_MATMUL_HMX_W8A8_H
+#define HTP_MATMUL_HMX_W8A8_H
+
+#include "matmul-internal.h"
+
+int hmx_w8a8_mm_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_2d_params_t * p);
+
+int hmx_w8a8_mm_batched(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_batched_params_t * params);
+
+int hmx_w8a8_mm_nx_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
+
+int hmx_w8a8_mm_nx_glu_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams);
+
+int hmx_w8a8_mm_id_2d(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const hmx_mm_id_2d_params_t * p);
+
+#endif // HTP_MATMUL_HMX_W8A8_H
diff --git a/ggml/src/ggml-hexagon/htp/matmul-hvx.c b/ggml/src/ggml-hexagon/htp/matmul-hvx.c
new file mode 100644
index 000000000..603a11d52
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-hvx.c
@@ -0,0 +1,2442 @@
+#include "matmul-hvx.h"
+#define GGML_COMMON_DECL_C
+#include "ggml-common.h"
+#include "hvx-mm-kernels-tiled.h"
+#include "hvx-mm-kernels-float.h"
+
+#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;
+
+
+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;
+ float * vtcm_scale;
+ uint8_t * vtcm_dst;
+ uint8_t * vtcm_act_raw;
+
+ uint32_t scale_ct_stride;
+ uint32_t scale_exp_stride;
+ float * vtcm_scales[HTP_OP_MAX_OUTPUTS];
+ uint32_t scales_ct_stride[HTP_OP_MAX_OUTPUTS];
+ uint32_t scales_exp_stride[HTP_OP_MAX_OUTPUTS];
+ uint8_t scales_scalar_exp[HTP_OP_MAX_OUTPUTS];
+
+ // 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 act_nrows = 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_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;
+
+ const dma_addr_t src0_row = src0->data;
+
+ 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 ct_start = src0_start_row / 32;
+ uint32_t ct_end = (src0_end_row + 31) / 32;
+
+ 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;
+ const float * w_scale_ptr = mmctx->vtcm_scale ? (mmctx->vtcm_scale + (size_t) ct * mmctx->scale_ct_stride) : NULL;
+
+ 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 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, w_scale_ptr, w_scale_ptr, mmctx->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, w_scale_ptr, mmctx->store_row);
+ }
+ 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 (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);
+ }
+ }
+}
+
+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_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);
+
+ 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;
+ uint8_t * act_data = mmctx->vtcm_act;
+
+ float * tmp = (float *) vtcm_dst_ptr;
+
+ const dma_addr_t src0_row = src0->data;
+
+ const uint8_t * restrict act_col = (const uint8_t *) act_data;
+
+ 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) {
+ 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) {
+ 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++) {
+ 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;
+ }
+
+ const hvx_tiled_store_row_fn_t vec_store = mmctx->vtcm_scale ? hvx_tiled_store_row_f32_scale : hvx_tiled_store_row_f32_none;
+
+ for (uint32_t ct = ct_start; ct < ct_end; ct++) {
+ const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
+ const float * w_scale_ptr = mmctx->vtcm_scale ? (mmctx->vtcm_scale + (size_t) ct * mmctx->scale_ct_stride) : NULL;
+
+ float * dst_ptr = &tmp[ct * 32 - src0_start_row];
+ int valid_rows = (int)ne0 - (int)(ct * 32);
+ 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, w_scale_ptr, vec_store);
+ 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++;
+ }
+ }
+
+ const uint32_t end_row = (uint32_t) MIN(src0_end_row, ne0);
+ if (end_row > src0_start_row) {
+ const uint32_t copy_cnt = end_row - src0_start_row;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct_end);
+ 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 (uint32_t c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = MIN(32u, 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 (uint32_t c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = MIN(32u, 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);
+ }
+}
+
+static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_mm_context * mmctx = data;
+ struct htp_ops_context * octx = mmctx->octx;
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ const uint32_t n_weights = kparams->n_weights;
+
+ const struct htp_tensor * restrict act = octx->src[n_weights]; /* x */
+ const uint32_t ne10 = act->ne[0];
+ const uint32_t act_nrows = act->ne[1] * act->ne[2] * act->ne[3];
+ 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;
+ const uint32_t n_prefetch = kparams->n_prefetch;
+ assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0);
+
+ for (uint32_t widx = 0; widx < n_weights; widx++) {
+ const struct htp_tensor * restrict src_w = octx->src[widx];
+ const struct htp_tensor * restrict dst = octx->dsts[widx];
+ if (!src_w || !dst) continue;
+ dma_queue * dma_q = th->dma_q;
+
+ 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 float * w_scale_base = mmctx->vtcm_scales[widx];
+ const uint32_t w_scale_ct_stride = mmctx->scales_ct_stride[widx];
+ const hvx_tiled_store_row_fn_t store_row = w_scale_base
+ ? resolve_hvx_tiled_store_row_scaled_fn(dst_elem_size, false)
+ : 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);
+ 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;
+
+ uint32_t src0_start_row = 0;
+ uint32_t src0_end_row = ne01;
+ if (octx->ctx->mdev.count > 1) {
+ 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;
+ }
+
+ const uint32_t nrows = src0_end_row - src0_start_row;
+ uint32_t src0_nrows_per_hvx = fastdiv(nrows + nth - 1, &octx->n_hvx_div);
+ src0_nrows_per_hvx = hex_round_up(src0_nrows_per_hvx, 32);
+
+ const uint32_t start_row = src0_start_row + src0_nrows_per_hvx * ith;
+ const uint32_t end_row = MIN(start_row + src0_nrows_per_hvx, src0_end_row);
+ if (start_row >= end_row) continue;
+
+ uint32_t ct_start = start_row / 32;
+ uint32_t ct_end = (end_row + 31) / 32;
+
+ 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);
+ }
+
+ for (uint32_t ct = ct_start; ct < ct_end; ct++) {
+ const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
+ const float * w_scale_ptr = w_scale_base ? (w_scale_base + (size_t) ct * w_scale_ct_stride) : NULL;
+ int valid_rows = (int)dst->ne[0] - (int)(ct * 32);
+ valid_rows = MIN(32, MAX(0, valid_rows));
+
+ 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, w_scale_ptr, 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, 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 (uint32_t ct = ct_start; ct < ct_end; ct++) {
+ const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
+ const float * w_scale_ptr = w_scale_base ? (w_scale_base + (size_t) ct * w_scale_ct_stride) : NULL;
+ 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 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, w_scale_ptr, w_scale_ptr, 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, w_scale_ptr, 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);
+ }
+ }
+ }
+ }
+}
+
+static void hvx_mm_transfer_act(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams,
+ const struct htp_tensor * act,
+ uint8_t * dst_base,
+ size_t dst_row_size,
+ uint32_t m_start,
+ uint32_t m_rows
+) {
+ if (m_rows == 0) {
+ return;
+ }
+
+ dma_queue * dma_q = octx->ctx->dma[0];
+ const uint32_t ne0 = act->ne[0];
+ const size_t elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const size_t row_bytes = ne0 * elem_size;
+ const size_t act_nb1 = act->nb[1];
+ const dma_addr_t act_base = act->data;
+
+ const bool is_contiguous = (act->nb[2] == act->ne[1] * act_nb1) &&
+ (act->nb[3] == act->ne[2] * act->nb[2]);
+
+ if (is_contiguous) {
+ const dma_addr_t src_addr = act_base + m_start * act_nb1;
+ dma_queue_push(dma_q, dma_make_data(dst_base, src_addr),
+ dst_row_size, act_nb1, row_bytes, m_rows);
+ dma_queue_pop(dma_q);
+ } else {
+ const uint32_t ne12_ne1 = act->ne[2] * act->ne[1];
+ for (uint32_t ir = 0; ir < m_rows; ++ir) {
+ const uint32_t ir1 = m_start + ir;
+ 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]);
+ uint8_t * row_dst = dst_base + ir * dst_row_size;
+ dma_queue_push(dma_q, dma_make_data(row_dst, row_src),
+ dst_row_size, act_nb1, row_bytes, 1);
+ dma_queue_pop(dma_q);
+ }
+ }
+
+ if (dst_row_size > row_bytes) {
+ struct htp_thread_trace * tr = &octx->ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) m_start);
+ const uint32_t pad_elems = (dst_row_size - row_bytes) / elem_size;
+ if (elem_size == sizeof(float)) {
+ for (uint32_t ir = 0; ir < m_rows; ++ir) {
+ hvx_splat_f32_u(dst_base + ir * dst_row_size + row_bytes, 0.0f, pad_elems);
+ }
+ } else {
+ for (uint32_t ir = 0; ir < m_rows; ++ir) {
+ hvx_splat_f16_u(dst_base + ir * dst_row_size + row_bytes, (_Float16) 0.0f, pad_elems);
+ }
+ }
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) m_start);
+ }
+}
+
+#define QUANTIZE_IMPL(name, log_name, kernel_fn, dst_row_size_expr) \
+static void name(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { \
+ (void) nth; \
+ struct htp_mm_context * mmctx = data; \
+ 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; \
+ const uint32_t nrows_per_hvx = mmctx->n_quant_rows_per_hvx; \
+ \
+ const uint32_t ir_first = nrows_per_hvx * ith; \
+ if (ir_first >= nrows) { \
+ return; \
+ } \
+ \
+ struct htp_thread_trace * tr = th->trace; \
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, ir_first); \
+ \
+ uint8_t * restrict dst = mmctx->vtcm_act; \
+ const uint32_t ir_last = MIN(ir_first + nrows_per_hvx, nrows); \
+ const size_t raw_row_size = mmctx->vtcm_act_raw_stride; \
+ const size_t dst_row_size = (dst_row_size_expr); \
+ \
+ const uint8_t * restrict src_data = (const uint8_t *) mmctx->vtcm_act_raw + (raw_row_size * ir_first); \
+ uint8_t * restrict dst_data = (uint8_t *) dst + (dst_row_size * ir_first); \
+ kernel_fn(src_data, dst_data, NULL, ne0, ir_last - ir_first, raw_row_size, dst_row_size); \
+ \
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, ir_first); \
+}
+
+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_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)
+
+static void quantize_f32_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;
+ }
+ 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_f32_q8_0_tiled_block_kernel(
+ (const float *) 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]
+ );
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
+}
+
+static void quantize_f32_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_tensor * src = mmctx->act;
+
+ quantize_f32_q8_1_tiled_block_kernel(
+ (const float *) 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_f32_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_f32_q8_1_s16_tiled_block_kernel(
+ (const float *) 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_f32_f16_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_f32_f16_tiled_block_kernel(
+ (const float *) 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_f16_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_f16_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_f16_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_f16_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_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;
+ }
+ 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_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]
+ );
+
+ 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_tensor * src = mmctx->act;
+
+ 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/F8_E4M3, 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 || weight_type == HTP_TYPE_F8_E4M3) {
+ 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 || weight_type == HTP_TYPE_F8_E4M3) {
+ 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;
+ const uint32_t ct_end = (src0_end_row + 31) / 32;
+
+ if (src0_start_row >= src0_end_row || cur_m_rows == 0) {
+ return;
+ }
+
+ const uint32_t total_batches = ne12 * ne13;
+ const uint32_t b_start = fastdiv(cur_m_start, &kparams->div_ne1);
+ uint32_t b_end = fastdiv(cur_m_start + cur_m_rows + ne11 - 1, &kparams->div_ne1);
+ b_end = MIN(b_end, total_batches);
+
+ uint32_t b_grp_start = b_start;
+ while (b_grp_start < b_end) {
+ const uint32_t b3 = fastdiv(b_grp_start, &kparams->div_ne12);
+ const uint32_t b2 = b_grp_start - b3 * ne12;
+ const uint32_t i02 = fastdiv(b2, &kparams->div_r2);
+ const uint32_t i03 = fastdiv(b3, &kparams->div_r3);
+
+ uint32_t b_grp_end = b_grp_start + 1;
+ while (b_grp_end < b_end) {
+ const uint32_t cur_b3 = fastdiv(b_grp_end, &kparams->div_ne12);
+ const uint32_t cur_b2 = b_grp_end - cur_b3 * ne12;
+ const uint32_t cur_i02 = fastdiv(cur_b2, &kparams->div_r2);
+ const uint32_t cur_i03 = fastdiv(cur_b3, &kparams->div_r3);
+ if (cur_i02 != i02 || cur_i03 != i03) {
+ break;
+ }
+ b_grp_end++;
+ }
+
+ const uint32_t slice_idx = i03 * ne02 + i02;
+ const dma_addr_t src0_slice = src0->data + (dma_addr_t) slice_idx * src0_slice_stride;
+
+ 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;
+ const float * w_scale_ptr = mmctx->vtcm_scale ? (mmctx->vtcm_scale + (size_t) ct * mmctx->scale_ct_stride) : NULL;
+
+ 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++) {
+ const uint32_t b_m_start = b * ne11;
+ const uint32_t m_first = MAX(cur_m_start, b_m_start);
+ const uint32_t m_last = MIN(cur_m_start + cur_m_rows, b_m_start + ne11);
+ if (m_first >= m_last) continue;
+
+ const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
+ const uint32_t cur_b2 = b - cur_b3 * ne12;
+ 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 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, w_scale_ptr, w_scale_ptr, 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, w_scale_ptr, 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 (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);
+ }
+ }
+ b_grp_start = b_grp_end;
+ }
+}
+
+static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ htp_matmul_preamble;
+
+ 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 act_nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : mmctx->act_nrows;
+ 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);
+ const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
+
+ struct htp_thread_trace * tr = th->trace;
+
+ const size_t dst_row_size = nb1;
+ const size_t src0_row_size = nb01;
+ 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-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;
+
+ const dma_addr_t src0_row = src0->data;
+
+
+ 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);
+ 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);
+
+ 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) {
+ 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);
+ 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);
+ }
+}
+
+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_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 src0_row_size = nb01;
+ 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;
+
+ // 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;
+
+ float * tmp = (float *) vtcm_dst_ptr;
+
+ const dma_addr_t src0_row = src0->data;
+ const uint8_t * restrict act_col = (const uint8_t *) act_data;
+
+ const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
+
+ 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;
+
+ // Prefill vtcm with 2x src0 rows
+ if (src0_start_row < src0_end_row) {
+ 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) {
+ 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) {
+ const uint32_t is0 = (ir0 - src0_start_row);
+ if (is0 >= 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;
+ }
+
+ // 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;
+ 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, hvx_flat_store_2x1_f32);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
+
+ // Prefetch next (n + vtcm_nrows) row
+ const uint32_t pr0 = (ir0 + n_prefetch);
+ const uint32_t 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),
+ src0_stride, src0_row_size, src0_row_size, 2);
+ }
+ }
+
+ // Process the last row (if any)
+ if (src0_end_row != src0_end_row_x2) {
+ const uint32_t ir0 = src0_end_row_x2;
+ const uint32_t 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),
+ 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, hvx_flat_store_1x1_f32);
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
+ }
+
+ if (src0_end_row > src0_start_row) {
+ const uint32_t copy_cnt = src0_end_row - src0_start_row;
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, src0_end_row);
+ 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 (uint32_t c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = MIN(32u, 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 (uint32_t c = 0; c < copy_cnt; c += 32) {
+ const uint32_t valid_c = MIN(32u, 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);
+ }
+}
+
+static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ htp_matmul_preamble;
+
+ 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 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);
+ const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
+
+ struct htp_thread_trace * tr = th->trace;
+
+ const size_t dst_row_size = nb1;
+ 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;
+
+
+ if (src0_start_row >= src0_end_row || cur_m_rows == 0) {
+ return;
+ }
+
+ const uint32_t total_batches = ne12 * ne13;
+ const uint32_t b_start = fastdiv(cur_m_start, &kparams->div_ne1);
+ uint32_t b_end = fastdiv(cur_m_start + cur_m_rows + ne11 - 1, &kparams->div_ne1);
+ b_end = MIN(b_end, total_batches);
+
+ uint32_t b_grp_start = b_start;
+ while (b_grp_start < b_end) {
+ const uint32_t b3 = fastdiv(b_grp_start, &kparams->div_ne12);
+ const uint32_t b2 = b_grp_start - b3 * ne12;
+ const uint32_t i02 = fastdiv(b2, &kparams->div_r2);
+ const uint32_t i03 = fastdiv(b3, &kparams->div_r3);
+
+ uint32_t b_grp_end = b_grp_start + 1;
+ while (b_grp_end < b_end) {
+ const uint32_t cur_b3 = fastdiv(b_grp_end, &kparams->div_ne12);
+ const uint32_t cur_b2 = b_grp_end - cur_b3 * ne12;
+ const uint32_t cur_i02 = fastdiv(cur_b2, &kparams->div_r2);
+ const uint32_t cur_i03 = fastdiv(cur_b3, &kparams->div_r3);
+ if (cur_i02 != i02 || cur_i03 != i03) {
+ break;
+ }
+ b_grp_end++;
+ }
+
+ 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;
+
+ 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++) {
+ const uint32_t b_m_start = b * ne11;
+ const uint32_t m_first = MAX(cur_m_start, b_m_start);
+ const uint32_t m_last = MIN(cur_m_start + cur_m_rows, b_m_start + ne11);
+ if (m_first >= m_last) continue;
+
+ const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
+ const uint32_t cur_b2 = b - cur_b3 * ne12;
+ 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 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);
+
+ 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) {
+ 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);
+ for (uint32_t b = b_grp_start; b < b_grp_end; b++) {
+ const uint32_t b_m_start = b * ne11;
+ const uint32_t m_first = MAX(cur_m_start, b_m_start);
+ const uint32_t m_last = MIN(cur_m_start + cur_m_rows, b_m_start + ne11);
+ if (m_first >= m_last) continue;
+
+ const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
+ const uint32_t cur_b2 = b - cur_b3 * ne12;
+ 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 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);
+ }
+
+ b_grp_start = b_grp_end;
+ }
+}
+
+#define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id) * mmctx->mapping_stride + (i1)]
+
+static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ htp_matmul_preamble;
+
+ 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);
+
+
+ if (src0_start_row >= src0_end_row) {
+ return;
+ }
+
+ 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 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 uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+
+ const size_t act_stride = mmctx->vtcm_act_stride;
+
+ // 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) {
+ const int32_t cne1 = matrix_row_counts[cur_a];
+ if (cne1 == 0) {
+ continue;
+ }
+
+ const dma_addr_t src0_row = src0->data + (dma_addr_t) cur_a * nb02;
+ const float * exp_scale = mmctx->vtcm_scale ? (mmctx->vtcm_scale + (size_t) cur_a * mmctx->scale_exp_stride) : NULL;
+
+ 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 ct_start = src0_start_row / 32;
+ const uint32_t ct_end = (src0_end_row + 31) / 32;
+
+ 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;
+ const float * w_scale_ptr = exp_scale ? (exp_scale + (size_t) ct * mmctx->scale_ct_stride) : NULL;
+
+ 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 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, w_scale_ptr, 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 (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);
+ }
+ }
+ }
+}
+
+static void hvx_mv_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_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);
+
+
+ if (src0_start_row >= src0_end_row) {
+ return;
+ }
+
+ 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);
+
+ assert(ne13 % ne03 == 0);
+
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+
+ const uint32_t n_aids = ids->ne[0]; // num activated experts
+ const uint32_t n_ids = ne02; // num experts
+ (void) n_ids;
+
+ // 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 = mmctx->ids_data[ie1];
+ if (eid < 0) {
+ continue;
+ }
+ assert(eid >= 0 && eid < (int32_t) n_ids);
+
+ const dma_addr_t src0_row = src0->data + (dma_addr_t) eid * nb02;
+ const float * exp_scale = mmctx->vtcm_scale ? (mmctx->vtcm_scale + (size_t) eid * mmctx->scale_exp_stride) : NULL;
+ const uint8_t * restrict act_col = (const uint8_t *) act_data;
+ const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * nb1;
+
+ 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 + (dma_addr_t) 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;
+ const float * w_scale_ptr = exp_scale ? (exp_scale + (size_t) ct * mmctx->scale_ct_stride) : NULL;
+
+ int valid_rows = (int)ne0 - (int)(ct * 32);
+ valid_rows = MIN(32, MAX(0, valid_rows));
+
+ htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
+ mmctx->vec_dot_32x1(ne10, vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size, w_tile, act_col, valid_rows, w_scale_ptr, 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 + (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);
+ }
+}
+
+static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_mm_context * mmctx = (struct htp_mm_context *) data;
+ struct htp_ops_context * octx = mmctx->octx;
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ 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);
+
+ 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 = mmctx->ids_data[ie1];
+ if (eid < 0) continue;
+ assert(eid < (int32_t) n_ids);
+
+ 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;
+ dma_queue * dma_q = th->dma_q;
+
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const float * exp_scale = mmctx->vtcm_scales[p] ? (mmctx->vtcm_scales[p] + (size_t) eid * mmctx->scales_exp_stride[p]) : NULL;
+ const uint32_t w_scale_ct_stride = mmctx->scales_ct_stride[p];
+ const hvx_tiled_store_row_fn_t store_row = exp_scale
+ ? resolve_hvx_tiled_store_row_scaled_fn(dst_elem_size, mmctx->scales_scalar_exp[p] != 0)
+ : 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 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;
+ }
+
+ const uint32_t nrows = end_row - start_row;
+ uint32_t src0_nrows_per_hvx = fastdiv(nrows + nth - 1, &octx->n_hvx_div);
+ src0_nrows_per_hvx = hex_round_up(src0_nrows_per_hvx, 32);
+
+ const uint32_t src0_start_row = start_row + src0_nrows_per_hvx * ith;
+ 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 + (dma_addr_t) eid * src_w->nb[2];
+ const uint8_t * restrict act_col = (const uint8_t *) act_data;
+ const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * dst->nb[1];
+
+ 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 + (dma_addr_t) 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;
+ const float * w_scale_ptr = exp_scale ? (exp_scale + (size_t) ct * w_scale_ct_stride) : NULL;
+
+ int valid_rows = (int)dst->ne[0] - (int)(ct * 32);
+ 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], vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size, w_tile, act_col, valid_rows, w_scale_ptr, 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 + (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);
+ }
+ }
+}
+
+static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
+ struct htp_mm_context * mmctx = (struct htp_mm_context *) data;
+ struct htp_ops_context * octx = mmctx->octx;
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ 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];
+
+
+ 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];
+
+ const uint32_t * matrix_row_counts = mmctx->matrix_row_counts;
+ const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows;
+
+ 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) {
+ const int32_t cne1 = matrix_row_counts[cur_a];
+ if (cne1 == 0) 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;
+ dma_queue * dma_q = th->dma_q;
+
+ const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const float * exp_scale = mmctx->vtcm_scales[p] ? (mmctx->vtcm_scales[p] + (size_t) cur_a * mmctx->scales_exp_stride[p]) : NULL;
+ const uint32_t w_scale_ct_stride = mmctx->scales_ct_stride[p];
+ const hvx_tiled_store_row_fn_t store_row = exp_scale
+ ? resolve_hvx_tiled_store_row_scaled_fn(dst_elem_size, mmctx->scales_scalar_exp[p] != 0)
+ : 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 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;
+ }
+
+ const uint32_t nrows = end_row - start_row;
+ uint32_t src0_nrows_per_hvx = fastdiv(nrows + nth - 1, &octx->n_hvx_div);
+ src0_nrows_per_hvx = hex_round_up(src0_nrows_per_hvx, 32);
+
+ const uint32_t src0_start_row = start_row + src0_nrows_per_hvx * ith;
+ 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 + (dma_addr_t) cur_a * src_w->nb[2];
+
+ 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 ct_start = src0_start_row / 32;
+ const uint32_t ct_end = (src0_end_row + 31) / 32;
+
+ 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;
+ const float * w_scale_ptr = exp_scale ? (exp_scale + (size_t) ct * w_scale_ct_stride) : NULL;
+
+ 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 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, w_scale_ptr, 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 (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);
+ }
+ }
+ }
+ }
+}
+
+static int hvx_mm_init_tiled_vec_dot(struct htp_mm_context * mmctx, enum htp_data_type type) {
+ switch (type) {
+ case HTP_TYPE_Q4_0:
+ mmctx->type = "q4_0_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q4_0_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q4_0_32x2;
+ return 0;
+ case HTP_TYPE_Q4_1:
+ case HTP_TYPE_Q4_K:
+ mmctx->type = "q4_1_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q4_1_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q4_1_32x2;
+ return 0;
+ case HTP_TYPE_Q8_0:
+ mmctx->type = "q8_0_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q8_0_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q8_0_32x2;
+ return 0;
+ case HTP_TYPE_Q5_0:
+ mmctx->type = "q5_0_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q5_0_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q5_0_32x2;
+ return 0;
+ case HTP_TYPE_Q5_1:
+ case HTP_TYPE_Q5_K:
+ mmctx->type = "q5_k_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q5_k_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q5_k_32x2;
+ return 0;
+ case HTP_TYPE_Q6_K:
+ mmctx->type = "q6_k_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q6_k_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q6_k_32x2;
+ return 0;
+ case HTP_TYPE_Q3_K:
+ mmctx->type = "q3_k_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q3_k_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q3_k_32x2;
+ return 0;
+ case HTP_TYPE_Q2_K:
+ mmctx->type = "q2_k_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q2_k_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q2_k_32x2;
+ return 0;
+ case HTP_TYPE_Q2_0:
+ mmctx->type = "q2_0_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q2_0_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q2_0_32x2;
+ return 0;
+ case HTP_TYPE_IQ4_NL:
+ mmctx->type = "iq4nl_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_iq4nl_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_iq4nl_32x2;
+ return 0;
+ case HTP_TYPE_IQ2_XXS:
+ mmctx->type = "iq2xxs_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_iq2xxs_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_iq2xxs_32x2;
+ return 0;
+ case HTP_TYPE_MXFP4:
+ mmctx->type = "mxfp4_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_mxfp4_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_mxfp4_32x2;
+ return 0;
+ case HTP_TYPE_NVFP4:
+ mmctx->type = "nvfp4_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_nvfp4_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_nvfp4_32x2;
+ return 0;
+ case HTP_TYPE_F8_E4M3:
+ mmctx->type = "f8_e4m3_tiled-f16";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_f8_e4m3_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_f8_e4m3_32x2;
+ return 0;
+ case HTP_TYPE_Q1_0:
+ mmctx->type = "q1_0_tiled-f32";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_q1_0_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_q1_0_32x2;
+ return 0;
+ case HTP_TYPE_F16:
+ mmctx->type = "f16_tiled-f16";
+ mmctx->vec_dot_32x1 = tiled_vec_dot_f16_32x1;
+ mmctx->vec_dot_32x2 = tiled_vec_dot_f16_32x2;
+ return 0;
+ default:
+ return -1;
+ }
+}
+
+int hvx_mm_matmul(struct htp_ops_context * octx) {
+ htp_matmul_tensors_preamble;
+
+ struct htp_thread_trace * tr = &octx->ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ struct htp_mm_context mmctx_struct = {0};
+ struct htp_mm_context * mmctx = &mmctx_struct;
+ mmctx->octx = octx;
+ mmctx->act = act;
+
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+
+ const uint32_t src0_nrows = ne01;
+ const uint32_t act_nrows = ne11 * ne12 * ne13;
+ mmctx->act_nrows = act_nrows;
+
+ 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 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) {
+ return HTP_STATUS_OK;
+ }
+
+ const uint32_t nrows = src0_row_end - src0_row_start;
+ mmctx->src0_row_start = src0_row_start;
+ mmctx->src0_row_end = src0_row_end;
+
+ const bool is_tiled = htp_tensor_is_tiled(src0);
+
+ // Compute src0_nrows_per_hvx
+ mmctx->src0_nrows_per_hvx = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div);
+ if (is_tiled) {
+ mmctx->src0_nrows_per_hvx = hex_round_up(mmctx->src0_nrows_per_hvx, 32);
+ } else {
+ mmctx->src0_nrows_per_hvx += (mmctx->src0_nrows_per_hvx & 1); // round up to even
+ }
+
+ const size_t src0_row_size = nb01;
+ 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_task_func;
+ uint32_t n_quant_tasks = 1;
+ const bool is_batched = (ne12 > 1 || ne13 > 1 || ne02 > 1 || ne03 > 1);
+ if (is_batched) {
+ matmul_task_func = is_tiled ? hvx_mm_4d_tiled : hvx_mm_4d_flat;
+ } else if (act_nrows > 1) {
+ matmul_task_func = is_tiled ? hvx_mm_2d_tiled : hvx_mm_2d_flat;
+ } else {
+ matmul_task_func = is_tiled ? hvx_mv_2d_tiled : hvx_mv_2d_flat;
+ }
+
+ const struct htp_tensor * scale = ((kparams->scale_mask & 1) != 0)
+ ? ((octx->op == HTP_OP_MUL_MAT_ADD) ? octx->src[3] : octx->src[2])
+ : NULL;
+ const bool use_mv = !is_batched && act_nrows == 1;
+ if (scale && !use_mv) {
+ mmctx->store_row = resolve_hvx_tiled_store_row_scaled_fn(dst_elem_size, false);
+ } else {
+ 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) {
+ case HTP_MM_KERNEL_HVX_F16_F16_VTCM:
+ quant_task_func = (act->type == HTP_TYPE_F32) ? quantize_f32_f16 : quantize_f16_f16;
+ need_quant = (act->type == HTP_TYPE_F32);
+ mmctx->type = (act->type == HTP_TYPE_F32) ? "f32-f16" : "f16-f16";
+ 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;
+ break;
+
+ case HTP_MM_KERNEL_HVX_F32_F32_VTCM:
+ 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;
+ break;
+
+ case HTP_MM_KERNEL_HVX_BF16_F32_VTCM:
+ 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;
+ break;
+
+ case HTP_MM_KERNEL_HVX_QUANT_BLOCK:
+ case HTP_MM_KERNEL_HVX_QUANT_ROW:
+ default: {
+ if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) != 0) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (ne10 + qk - 1) / qk;
+ const uint32_t total_nb = act_nrows * nb;
+
+ if (act_nrows < octx->n_hvx && !is_batched) {
+ n_quant_tasks = MIN(total_nb, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
+ for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
+ uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
+ uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
+ mmctx->quant_ib_first[ith] = ib_first;
+ mmctx->quant_ib_last[ith] = ib_last;
+ mmctx->quant_r[ith] = ib_first / nb;
+ mmctx->quant_c[ith] = ib_first % nb;
+ }
+ } else {
+ n_quant_tasks = MIN(act_nrows, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
+ }
+ break;
+ }
+ }
+
+ const uint32_t m_chunk = (kparams->m_chunk > 0 && (uint32_t) kparams->m_chunk < act_nrows)
+ ? (uint32_t) kparams->m_chunk : act_nrows;
+ const uint32_t m_layout_rows = m_chunk;
+
+ struct htp_mm_hvx_vtcm_layout L;
+ htp_mm_hvx_vtcm_layout_build_ex(&L, kparams->kernel_type, src0->type, ne10, m_layout_rows, octx->n_hvx,
+ dst_row_size, src0_row_size, act_elem_size, bias ? bias->nb[1] : 0,
+ (size_t) kparams->vtcm_scale_size, kparams->n_prefetch, false, false);
+
+ mmctx->vtcm_act_size_per_hvx = L.act_bytes;
+ mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div);
+ mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
+
+ const size_t vtcm_size = L.total_bytes;
+
+ FARF(HIGH, "matmul-%s : src0-vtcm-size %zu act-vtcm-size %zu dst-vtcm-size %zu (%zu)\n", mmctx->type,
+ L.src0_bytes, L.act_bytes, L.dst_bytes, vtcm_size);
+
+ FARF(HIGH, "matmul-%s : %ux%ux%ux%u * %ux%ux%ux%u-> %ux%ux%ux%u (0x%p, 0x%p, 0x%p)\n", mmctx->type, src0->ne[0],
+ src0->ne[1], src0->ne[2], src0->ne[3], act->ne[0], act->ne[1], act->ne[2], act->ne[3], dst->ne[0],
+ dst->ne[1], dst->ne[2], dst->ne[3], src0->data, act->data, dst->data);
+
+ if (octx->ctx->vtcm_size < vtcm_size) {
+ FARF(ERROR, "matmul-%s : current VTCM reservation %zu is too small, needed %zu\n", mmctx->type,
+ octx->ctx->vtcm_size, vtcm_size);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
+ mmctx->vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
+ mmctx->vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0);
+ mmctx->vtcm_bias = VTCM_LAYOUT_PTR(uint8_t, base, L.off_bias);
+ mmctx->vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, scale != NULL);
+ 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);
+ hvx_mm_iq2xxs_lut_init(base, &L);
+
+ if (scale) {
+ const uint32_t smode = htp_mm_scale_mode_get(kparams->scale_mode, 0);
+ const bool per_ch = htp_mm_scale_is_per_channel(smode);
+ const size_t scale_bytes = per_ch ? ((size_t) ne01 * sizeof(float)) : sizeof(float);
+ mmctx->scale_ct_stride = per_ch ? 32u : 0u;
+ htp_mm_load_scale(octx->ctx->dma[0], mmctx->vtcm_scale, scale->data, scale_bytes, !per_ch);
+ }
+
+ 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, 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;
+ }
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ if (kparams->m_chunk > 0 && (uint32_t) kparams->m_chunk < act_nrows) {
+ for (uint32_t m_start = 0; m_start < act_nrows; m_start += m_chunk) {
+ const uint32_t cur_m_rows = MIN(act_nrows - m_start, m_chunk);
+ mmctx->cur_m_start = m_start;
+ mmctx->cur_m_rows = cur_m_rows;
+
+ if (need_quant) {
+ hvx_mm_transfer_act(octx, kparams, act, mmctx->vtcm_act_raw, mmctx->vtcm_act_raw_stride, m_start, cur_m_rows);
+
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (ne10 + qk - 1) / qk;
+ const uint32_t total_nb = cur_m_rows * nb;
+ uint32_t quant_tasks;
+ work_queue_func_t q_func;
+ if (cur_m_rows < octx->n_hvx && (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW)) {
+ quant_tasks = MIN(total_nb, octx->n_hvx);
+ q_func = htp_mm_act_quant_block_func(src0->type, act->type);
+ for (uint32_t ith = 0; ith < quant_tasks; ++ith) {
+ uint32_t ib_first = (total_nb * ith) / quant_tasks;
+ uint32_t ib_last = (total_nb * (ith + 1)) / quant_tasks;
+ mmctx->quant_ib_first[ith] = ib_first;
+ mmctx->quant_ib_last[ith] = ib_last;
+ mmctx->quant_r[ith] = ib_first / nb;
+ mmctx->quant_c[ith] = ib_first % nb;
+ }
+ } else {
+ quant_tasks = MIN(cur_m_rows, octx->n_hvx);
+ q_func = quant_task_func;
+ mmctx->n_quant_rows_per_hvx = (cur_m_rows + quant_tasks - 1) / quant_tasks;
+ }
+ mmctx->n_quant_tasks = quant_tasks;
+ work_queue_run(octx->ctx->hvx_queue, q_func, mmctx, quant_tasks);
+ } else {
+ hvx_mm_transfer_act(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, m_start, cur_m_rows);
+ }
+
+ work_queue_run(octx->ctx->hvx_queue, matmul_task_func, mmctx, octx->n_hvx);
+ }
+ } else {
+ mmctx->cur_m_start = 0;
+ mmctx->cur_m_rows = act_nrows;
+
+ if (need_quant) {
+ hvx_mm_transfer_act(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(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, 0, act_nrows);
+ }
+
+ work_queue_run(octx->ctx->hvx_queue, matmul_task_func, mmctx, octx->n_hvx);
+ }
+
+ return HTP_STATUS_OK;
+}
+
+static int hvx_mm_matmul_id_impl(
+ struct htp_ops_context * octx,
+ struct htp_mm_context * mmctx,
+ work_queue_func_t hvx_mmid_task_func
+) {
+ htp_matmul_tensors_preamble;
+ const struct htp_tensor * restrict __attribute__((unused)) ids = octx->src[2];
+ 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];
+ 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 size_t src0_row_size = nb01;
+
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (ne10 + qk - 1) / qk;
+ const uint32_t total_nb = act_nrows * nb;
+
+ work_queue_func_t quant_task_func;
+ uint32_t n_quant_tasks = 1;
+ if (act_nrows < octx->n_hvx) {
+ n_quant_tasks = MIN(total_nb, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
+ for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
+ uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
+ uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
+ mmctx->quant_ib_first[ith] = ib_first;
+ mmctx->quant_ib_last[ith] = ib_last;
+ mmctx->quant_r[ith] = ib_first / nb;
+ mmctx->quant_c[ith] = ib_first % nb;
+ }
+ } else {
+ n_quant_tasks = MIN(act_nrows, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
+ }
+ 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_ex(&L, kparams->kernel_type, src0->type, ne10, act_nrows, octx->n_hvx,
+ dst_row_size, src0_row_size, act_elem_size, 0,
+ (size_t) kparams->vtcm_scale_size, kparams->n_prefetch, true, false);
+
+ const size_t vtcm_size = L.total_bytes;
+
+ FARF(HIGH, "matmul-id-%s : src0-spad-size %zu act-spad-size %zu bias-spad-size 0 dst-spad-size %zu (%zu)\n", mmctx->type,
+ L.src0_bytes, L.act_bytes, L.dst_bytes, vtcm_size);
+
+ FARF(HIGH, "matmul-id-%s : %ux%ux%ux%u * %ux%ux%ux%u (%ux%ux%ux%u) -> %ux%ux%ux%u (0x%p, 0x%p, 0x%p)\n", mmctx->type,
+ src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], act->ne[0], act->ne[1], act->ne[2], act->ne[3],
+ ids->ne[0], ids->ne[1], ids->ne[2], ids->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], src0->data,
+ act->data, dst->data);
+
+ // Make sure the reserved vtcm size is sufficient
+ if (octx->ctx->vtcm_size < vtcm_size) {
+ FARF(ERROR, "matmul-id-%s : current VTCM reservation %zu is too small, needed %zu\n", mmctx->type, octx->ctx->vtcm_size, vtcm_size);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ const struct htp_tensor * scale = ((kparams->scale_mask & 1) != 0) ? octx->src[3] : NULL;
+
+ uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
+ mmctx->vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
+ mmctx->vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0);
+ mmctx->vtcm_bias = NULL;
+ mmctx->vtcm_scale = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_scale, scale != NULL);
+ 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);
+ hvx_mm_iq2xxs_lut_init(base, &L);
+
+ if (scale) {
+ const uint32_t smode = htp_mm_scale_mode_get(kparams->scale_mode, 0);
+ size_t scale_bytes = sizeof(float);
+ bool splat_scalar = false;
+ if (smode == HTP_MM_FUSED_SCALE_PER_TENSOR) {
+ scale_bytes = sizeof(float);
+ splat_scalar = true;
+ mmctx->scale_ct_stride = 0;
+ mmctx->scale_exp_stride = 0;
+ } else if (smode == HTP_MM_FUSED_SCALE_PER_CHANNEL) {
+ scale_bytes = (size_t) ne01 * sizeof(float);
+ mmctx->scale_ct_stride = 32;
+ mmctx->scale_exp_stride = 0;
+ } else if (smode == HTP_MM_FUSED_SCALE_PER_EXPERT) {
+ scale_bytes = (size_t) ne02 * sizeof(float);
+ mmctx->scale_ct_stride = 0;
+ mmctx->scale_exp_stride = 1;
+ } else {
+ scale_bytes = (size_t) ne01 * ne02 * sizeof(float);
+ mmctx->scale_ct_stride = 32;
+ mmctx->scale_exp_stride = ne01;
+ }
+ htp_mm_load_scale(octx->ctx->dma[0], mmctx->vtcm_scale, scale->data, scale_bytes, splat_scalar);
+ }
+
+ 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, 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;
+ mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
+
+ mmctx->cur_m_start = 0;
+ mmctx->cur_m_rows = act_nrows;
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ hvx_mm_transfer_act(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);
+
+ work_queue_run(octx->ctx->hvx_queue, hvx_mmid_task_func, mmctx, octx->n_hvx);
+
+ return HTP_STATUS_OK;
+}
+
+
+int hvx_mm_matmul_id(struct htp_ops_context * octx, const struct htp_mmid_mapping * map) {
+ htp_matmul_tensors_preamble;
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+
+ const uint32_t src0_nrows = ne01;
+ const uint32_t act_nrows = ne11 * ne12 * ne13;
+
+ 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 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) {
+ return HTP_STATUS_OK;
+ }
+
+ struct htp_mm_context mmctx_struct = {0};
+ struct htp_mm_context * mmctx = &mmctx_struct;
+ mmctx->octx = octx;
+ mmctx->act = act;
+ mmctx->ids_data = map->ids_data;
+ mmctx->matrix_row_counts = map->matrix_row_counts;
+ mmctx->matrix_rows = map->matrix_rows;
+ mmctx->mapping_stride = map->mapping_stride;
+ mmctx->mm_div_ne11 = kparams->div_ne1;
+ mmctx->src0_row_size_padded = hex_round_up(nb01, 128);
+ mmctx->act_nrows = act_nrows;
+ mmctx->cur_m_start = 0;
+ mmctx->cur_m_rows = act_nrows;
+
+ const uint32_t nrows = src0_row_end - src0_row_start;
+ mmctx->src0_row_start = src0_row_start;
+ mmctx->src0_row_end = src0_row_end;
+ 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);
+
+ const bool has_scale = (kparams->scale_mask & 1) != 0 && octx->src[3] != NULL;
+ const bool scalar_exp = has_scale && (htp_mm_scale_mode_get(kparams->scale_mode, 0) == HTP_MM_FUSED_SCALE_PER_EXPERT);
+ mmctx->store_row = has_scale
+ ? resolve_hvx_tiled_store_row_scaled_fn(dst_elem_size, scalar_exp)
+ : resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float));
+
+ if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) == 0) {
+ return hvx_mm_matmul_id_impl(octx, mmctx, act_nrows > 1 ? hvx_mm_id_tiled : hvx_mv_id_tiled);
+ }
+ return HTP_STATUS_NO_SUPPORT;
+}
+
+static int hvx_mm_matmul_id_nx_impl(
+ struct htp_ops_context * octx,
+ struct htp_mm_context * mmctx,
+ work_queue_func_t hvx_mmid_task_func
+) {
+ const uint32_t act_nrows = mmctx->act_nrows;
+
+ struct htp_thread_trace * tr = &octx->ctx->trace[0];
+ 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 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 size_t src0_row_size = src0->nb[1];
+
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (act->ne[0] + qk - 1) / qk;
+ const uint32_t total_nb = act_nrows * nb;
+
+ work_queue_func_t quant_task_func;
+ uint32_t n_quant_tasks = 1;
+ if (act_nrows < octx->n_hvx) {
+ n_quant_tasks = MIN(total_nb, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
+ for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
+ uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
+ uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
+ mmctx->quant_ib_first[ith] = ib_first;
+ mmctx->quant_ib_last[ith] = ib_last;
+ mmctx->quant_r[ith] = ib_first / nb;
+ mmctx->quant_c[ith] = ib_first % nb;
+ }
+ } else {
+ n_quant_tasks = MIN(act_nrows, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
+ }
+ 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_ex(&L, kparams->kernel_type, src0->type, act->ne[0], act_nrows, octx->n_hvx,
+ max_dst_row_size, src0_row_size, act_elem_size, 0,
+ (size_t) kparams->vtcm_scale_size, kparams->n_prefetch, true, false);
+
+ const size_t vtcm_size = L.total_bytes;
+
+ if (octx->ctx->vtcm_size < vtcm_size) {
+ FARF(ERROR, "matmul-id-nx: current VTCM reservation %zu is too small, needed %zu\n",
+ octx->ctx->vtcm_size, vtcm_size);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
+ 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);
+ hvx_mm_iq2xxs_lut_init(base, &L);
+
+ if (kparams->scale_mask != 0) {
+ size_t scale_off = L.off_scale;
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ if (((kparams->scale_mask >> p) & 1u) == 0) {
+ continue;
+ }
+ const struct htp_tensor * sc = octx->src[n_weights + 2 + p];
+ const struct htp_tensor * sw = octx->src[p];
+ if (!sc || !sw) {
+ continue;
+ }
+ const uint32_t smode = htp_mm_scale_mode_get(kparams->scale_mode, p);
+ size_t scale_bytes = sizeof(float);
+ bool splat_scalar = false;
+ if (smode == HTP_MM_FUSED_SCALE_PER_TENSOR) {
+ scale_bytes = sizeof(float);
+ splat_scalar = true;
+ mmctx->scales_ct_stride[p] = 0;
+ mmctx->scales_exp_stride[p] = 0;
+ mmctx->scales_scalar_exp[p] = 0;
+ } else if (smode == HTP_MM_FUSED_SCALE_PER_CHANNEL) {
+ scale_bytes = (size_t) sw->ne[1] * sizeof(float);
+ mmctx->scales_ct_stride[p] = 32;
+ mmctx->scales_exp_stride[p] = 0;
+ mmctx->scales_scalar_exp[p] = 0;
+ } else if (smode == HTP_MM_FUSED_SCALE_PER_EXPERT) {
+ scale_bytes = (size_t) sw->ne[2] * sizeof(float);
+ mmctx->scales_ct_stride[p] = 0;
+ mmctx->scales_exp_stride[p] = 1;
+ mmctx->scales_scalar_exp[p] = 1;
+ } else {
+ scale_bytes = (size_t) sw->ne[1] * sw->ne[2] * sizeof(float);
+ mmctx->scales_ct_stride[p] = 32;
+ mmctx->scales_exp_stride[p] = sw->ne[1];
+ mmctx->scales_scalar_exp[p] = 0;
+ }
+ mmctx->vtcm_scales[p] = VTCM_LAYOUT_PTR(float, base, scale_off);
+ htp_mm_load_scale(octx->ctx->dma[0], mmctx->vtcm_scales[p], sc->data, scale_bytes, splat_scalar);
+ scale_off += hex_round_up(scale_bytes, 128);
+ }
+ }
+
+ 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], 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;
+ mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
+
+ mmctx->cur_m_start = 0;
+ mmctx->cur_m_rows = act_nrows;
+
+ FARF(HIGH, "matmul-id-nx: src0 %d:%d:%d type %s nrows %u, act %d:%d:%d nrows %u, vtcm %zu/%zu, nhvx %d\n",
+ src0->ne[0], src0->ne[1], src0->ne[2], mmctx->type, src0->ne[1],
+ act->ne[0], act->ne[1], act->ne[2], act_nrows,
+ L.total_bytes, octx->ctx->vtcm_size, octx->n_hvx);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ hvx_mm_transfer_act(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);
+
+ work_queue_run(octx->ctx->hvx_queue, hvx_mmid_task_func, mmctx, octx->n_hvx);
+
+ return HTP_STATUS_OK;
+}
+
+
+int hvx_mm_matmul_id_nx(struct htp_ops_context * octx, const struct htp_mmid_mapping * map) {
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ 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 uint32_t act_nrows = act->ne[1] * act->ne[2] * act->ne[3];
+
+ struct htp_mm_context mmctx_struct = {0};
+ struct htp_mm_context * mmctx = &mmctx_struct;
+ mmctx->octx = octx;
+ mmctx->act = act;
+ mmctx->ids_data = map->ids_data;
+ mmctx->matrix_row_counts = map->matrix_row_counts;
+ mmctx->matrix_rows = map->matrix_rows;
+ mmctx->mapping_stride = map->mapping_stride;
+ mmctx->mm_div_ne11 = kparams->div_ne1;
+ mmctx->src0_row_size_padded = hex_round_up(src0->nb[1], 128);
+ mmctx->act_nrows = act_nrows;
+ mmctx->cur_m_start = 0;
+ mmctx->cur_m_rows = act_nrows;
+
+ if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) == 0) {
+ return hvx_mm_matmul_id_nx_impl(octx, mmctx, act_nrows > 1 ? hvx_mm_id_nx_tiled : hvx_mv_id_nx_tiled);
+ }
+ return HTP_STATUS_NO_SUPPORT;
+}
+
+int hvx_mm_matmul_nx(struct htp_ops_context * octx) {
+ const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
+ struct htp_thread_trace * tr = &octx->ctx->trace[0];
+ htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+
+ const uint32_t n_weights = kparams->n_weights;
+
+ const struct htp_tensor * restrict src0 = octx->src[0]; // first weight
+ const struct htp_tensor * restrict act = octx->src[n_weights]; // activation x
+
+ struct htp_mm_context mmctx_struct = {0};
+ struct htp_mm_context * mmctx = &mmctx_struct;
+ mmctx->octx = octx;
+ mmctx->act = act;
+
+ const uint32_t act_nrows = act->ne[1] * act->ne[2] * act->ne[3];
+ mmctx->act_nrows = act_nrows;
+ mmctx->cur_m_start = 0;
+ mmctx->cur_m_rows = act_nrows;
+
+ const size_t src0_row_size = src0->nb[1];
+
+ if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) != 0) {
+ return HTP_STATUS_NO_SUPPORT;
+ }
+
+ const uint32_t qk = HTP_MM_ACT_BLOCK_K;
+ const uint32_t nb = (act->ne[0] + qk - 1) / qk;
+ const uint32_t total_nb = act_nrows * nb;
+
+ work_queue_func_t quant_task_func;
+ uint32_t n_quant_tasks = 1;
+ if (act_nrows < octx->n_hvx) {
+ n_quant_tasks = MIN(total_nb, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
+ for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
+ uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
+ uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
+ mmctx->quant_ib_first[ith] = ib_first;
+ mmctx->quant_ib_last[ith] = ib_last;
+ mmctx->quant_r[ith] = ib_first / nb;
+ mmctx->quant_c[ith] = ib_first % nb;
+ }
+ } else {
+ n_quant_tasks = MIN(act_nrows, octx->n_hvx);
+ quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
+ }
+
+ 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_ex(&L, kparams->kernel_type, src0->type, act->ne[0], act_nrows, octx->n_hvx,
+ max_dst_row_size, src0_row_size, act_elem_size, 0,
+ (size_t) kparams->vtcm_scale_size, kparams->n_prefetch, false, true);
+
+ const size_t vtcm_size = L.total_bytes;
+
+ if (octx->ctx->vtcm_size < vtcm_size) {
+ FARF(ERROR, "matmul-nx: current VTCM reservation %zu is too small, needed %zu\n",
+ octx->ctx->vtcm_size, vtcm_size);
+ return HTP_STATUS_VTCM_TOO_SMALL;
+ }
+
+ uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
+ 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_OPTIONAL(uint8_t, base, L.off_act_raw, quant_task_func != NULL);
+ hvx_mm_iq2xxs_lut_init(base, &L);
+
+ if (kparams->scale_mask != 0) {
+ size_t scale_off = L.off_scale;
+ for (uint32_t p = 0; p < n_weights; ++p) {
+ if (((kparams->scale_mask >> p) & 1u) == 0) {
+ continue;
+ }
+ const struct htp_tensor * sc = octx->src[n_weights + 1 + p];
+ const struct htp_tensor * sw = octx->src[p];
+ if (!sc || !sw) {
+ continue;
+ }
+ const uint32_t smode = htp_mm_scale_mode_get(kparams->scale_mode, p);
+ const bool per_ch = htp_mm_scale_is_per_channel(smode);
+ const size_t scale_bytes = per_ch ? ((size_t) sw->ne[1] * sizeof(float)) : sizeof(float);
+ mmctx->scales_ct_stride[p] = per_ch ? 32u : 0u;
+ mmctx->vtcm_scales[p] = VTCM_LAYOUT_PTR(float, base, scale_off);
+ htp_mm_load_scale(octx->ctx->dma[0], mmctx->vtcm_scales[p], sc->data, scale_bytes, !per_ch);
+ scale_off += hex_round_up(scale_bytes, 128);
+ }
+ }
+
+ 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], 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;
+ mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
+
+ htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
+
+ if (quant_task_func) {
+ hvx_mm_transfer_act(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(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);
+
+ return HTP_STATUS_OK;
+}
+
diff --git a/ggml/src/ggml-hexagon/htp/matmul-hvx.h b/ggml/src/ggml-hexagon/htp/matmul-hvx.h
new file mode 100644
index 000000000..b9aea98d7
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-hvx.h
@@ -0,0 +1,11 @@
+#ifndef HTP_MATMUL_HVX_H
+#define HTP_MATMUL_HVX_H
+
+#include "matmul-internal.h"
+
+int hvx_mm_matmul(struct htp_ops_context * octx);
+int hvx_mm_matmul_nx(struct htp_ops_context * octx);
+int hvx_mm_matmul_id(struct htp_ops_context * octx, const struct htp_mmid_mapping * map);
+int hvx_mm_matmul_id_nx(struct htp_ops_context * octx, const struct htp_mmid_mapping * map);
+
+#endif // HTP_MATMUL_HVX_H
diff --git a/ggml/src/ggml-hexagon/htp/matmul-internal.h b/ggml/src/ggml-hexagon/htp/matmul-internal.h
new file mode 100644
index 000000000..de4221c47
--- /dev/null
+++ b/ggml/src/ggml-hexagon/htp/matmul-internal.h
@@ -0,0 +1,676 @@
+#ifndef HTP_MATMUL_INTERNAL_H
+#define HTP_MATMUL_INTERNAL_H
+
+#include <HAP_farf.h>
+#include <HAP_perf.h>
+#include <HAP_compute_res.h>
+
+#include <math.h>
+#include <string.h>
+#include <stdatomic.h>
+
+#include "dma-queue.h"
+#include "hvx-utils.h"
+#include "hvx-dump.h"
+#include "hvx-arith.h"
+#include "hvx-reduce.h"
+#include "hvx-copy.h"
+#include "hvx-norm.h"
+#include "hmx-utils.h"
+#include "hmx-queue.h"
+
+#include "htp-ctx.h"
+#include "htp-ops.h"
+#include "htp-tensor.h"
+#include "matmul-ops.h"
+#include "htp-vtcm.h"
+
+#define htp_matmul_tensors_preamble \
+ const struct htp_tensor * restrict __attribute__((unused)) src0 = octx->src[0]; \
+ const struct htp_tensor * restrict __attribute__((unused)) src1 = octx->src[1]; \
+ const struct htp_tensor * restrict __attribute__((unused)) bias = \
+ (octx->op == HTP_OP_MUL_MAT_ADD) ? octx->src[2] : NULL; \
+ const struct htp_tensor * restrict __attribute__((unused)) dst = octx->dst; \
+ const struct htp_tensor * restrict __attribute__((unused)) act = src1; \
+ \
+ const uint32_t __attribute__((unused)) ne00 = src0->ne[0]; \
+ const uint32_t __attribute__((unused)) ne01 = src0->ne[1]; \
+ const uint32_t __attribute__((unused)) ne02 = src0->ne[2]; \
+ const uint32_t __attribute__((unused)) ne03 = src0->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) ne10 = src1->ne[0]; \
+ const uint32_t __attribute__((unused)) ne11 = src1->ne[1]; \
+ const uint32_t __attribute__((unused)) ne12 = src1->ne[2]; \
+ const uint32_t __attribute__((unused)) ne13 = src1->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \
+ const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \
+ const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \
+ const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb00 = src0->nb[0]; \
+ const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \
+ const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \
+ const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb10 = src1->nb[0]; \
+ const uint32_t __attribute__((unused)) nb11 = src1->nb[1]; \
+ const uint32_t __attribute__((unused)) nb12 = src1->nb[2]; \
+ const uint32_t __attribute__((unused)) nb13 = src1->nb[3]; \
+ \
+ const uint32_t __attribute__((unused)) nb0 = dst->nb[0]; \
+ const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \
+ const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \
+ const uint32_t __attribute__((unused)) nb3 = dst->nb[3];
+
+// --- Shared LUTs (defined in matmul-ops.c) ---
+
+extern const uint8_t expand_x32_e8m0[128];
+extern const uint8_t kvalues_iq4nl_lut[];
+extern const uint8_t kvalues_mxfp4_lut[];
+extern const uint8_t * iq2xxs_vtcm_lut;
+
+void iq2xxs_lut_copy(uint8_t * restrict lut);
+
+static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct htp_mm_hvx_vtcm_layout * restrict L) {
+ if (L->lut_bytes == 0) {
+ return;
+ }
+ iq2xxs_lut_copy(base + L->off_lut);
+}
+
+// --- Shared Quant Unpack Helpers ---
+
+static inline HVX_Vector unpack_q1_0_group(
+ HVX_Vector v_plane,
+ int g,
+ HVX_Vector v_neg_one,
+ HVX_Vector v_pos_one
+) {
+ HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << g);
+ return Q6_V_vmux_QVV(q, v_pos_one, v_neg_one);
+}
+
+// Q5_K: OR 0x10 into every lane of v whose flag j is set in the plane (see HTP_TENSOR_TILE_SIZE_Q5_K)
+static inline HVX_Vector hvx_q5k_or_hibit(HVX_Vector v, HVX_Vector v_plane, int j) {
+ HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
+ return Q6_V_vandor_VQR(v, q, 0x10101010);
+}
+
+// OR 0xF0 into every lane of v whose flag j is set in the plane, i.e. 4-bit value | 0xF0 = q - 16 where the 5th bit is clear (Q5_0)
+static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j) {
+ HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j);
+ return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0);
+}
+
+// Q6_K weights are stored unsigned (0..63), see HTP_TENSOR_TILE_SIZE_Q6_K. Unpack k-group g of a tile to signed bytes (q - 32)
+static inline HVX_Vector unpack_q6_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_0f, HVX_Vector mask_03, HVX_Vector i32) {
+ HVX_Vector v_lo = (g & 1) ? Q6_Vub_vlsr_VubR(vptr[g >> 1], 4) : Q6_V_vand_VV(vptr[g >> 1], mask_0f);
+ HVX_Vector v_hi = (g & 3) ? Q6_Vub_vlsr_VubR(vptr[4 + (g >> 2)], 2 * (g & 3)) : vptr[4 + (g >> 2)];
+ HVX_Vector v_q = Q6_V_vor_VV(v_lo, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_hi, mask_03), 4));
+ return Q6_Vb_vsub_VbVb(v_q, i32);
+}
+
+// Q3_K / Q2_K: low 2 bits of k-group g, see HTP_TENSOR_TILE_SIZE_Q3_K
+static inline HVX_Vector unpack_q3_k_low2(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
+ HVX_Vector v = vptr[g >> 2];
+ if ((g & 3) == 3) {
+ return Q6_Vub_vlsr_VubR(v, 6);
+ }
+ if (g & 3) {
+ v = Q6_Vub_vlsr_VubR(v, 2 * (g & 3));
+ }
+ return Q6_V_vand_VV(v, mask_03);
+}
+
+// Q3_K k-group g as signed bytes: low2 | 0xFC (= low2 - 4) where bit g of vector 2 is set
+static inline HVX_Vector unpack_q3_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) {
+ HVX_VectorPred q_neg = Q6_Q_vand_VR(vptr[2], 0x01010101u << g);
+ return Q6_V_vandor_VQR(unpack_q3_k_low2(vptr, g, mask_03), q_neg, 0xFCFCFCFC);
+}
+
+// Q2_K: fp16 d (*v_d) and -dmin (*v_m) of the 32 rows of a super-block (8 tiles, VTCM stride 384), each in both vector halves
+static inline void q2_k_load_dmin(const uint8_t * restrict sb, HVX_Vector * restrict v_d, HVX_Vector * restrict v_m) {
+ HVX_Vector v_dd = Q6_V_vzero(); // lanes 0..31: d, lanes 32..63: -dmin
+
+ #pragma unroll
+ for (int j = 0; j < 8; j++) {
+ HVX_Vector v = hvx_vmem(sb + j * 384 + 256); // the slice is at bytes 64..79
+ v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(16 * j), v_dd, Q6_V_vror_VR(v, (64 - 16 * j) & 127));
+ }
+
+ HVX_VectorPred q_lo = Q6_Q_vsetq_R(64);
+ HVX_Vector v_r = Q6_V_vror_VR(v_dd, 64);
+ *v_d = Q6_V_vmux_QVV(q_lo, v_dd, v_r);
+ *v_m = Q6_V_vmux_QVV(q_lo, v_r, v_dd);
+}
+
+// Q2_K: fp16 D = d * scale and M = -dmin * min of a tile from its scale bytes, in the lanes of the Q6_K scales
+static inline void q2_k_unpack_scales(const uint8_t * restrict tile, HVX_Vector v_d, HVX_Vector v_m,
+ HVX_Vector * restrict v_D, HVX_Vector * restrict v_M) {
+ HVX_Vector v_sc = hvx_vmem(tile + 256);
+ HVX_Vector v_l = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_V_vand_VV(v_sc, Q6_Vb_vsplat_R(0x0F))));
+ HVX_Vector v_mn = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(Q6_Vub_vlsr_VubR(v_sc, 4)));
+ // qf32 product: rounds like GGML_FP32_TO_FP16(d * scale) (qf16 is off by 1 ulp for many values on v73)
+ *v_D = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_l), v_d));
+ *v_M = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_mn), v_m));
+}
+
+#define IQ2XXS_GROUPS 4 // 8-element grid entries per tile row
+#define IQ2XXS_TILES_PER_SB 8 // 256 / 32
+#define IQ2XXS_CODE_SHIFT 1 // log2(2 B per grid code)
+#define IQ2XXS_WORD_BYTES 4
+#define IQ2XXS_IDX_BITS 8
+#define IQ2XXS_IDX_MASK 0xFF
+#define IQ2XXS_SIGN_BITS 7
+#define IQ2XXS_SIGN_MASK 0x7F
+#define IQ2XXS_PARITY_SHIFT 7
+#define IQ2XXS_SCALE_SHIFT 28
+#define IQ2XXS_D_SLICE_OFF 256 // 4 fp16 d of the tile, after the 32 rows x 8 B
+#define IQ2XXS_D_SCALE 0.125f // db = d * (2 * scale + 1) / 8
+#define IQ2XXS_D_SLICE_BYTES 8
+#define IQ2XXS_SIGN_PRED_LO 0x08040201 // sign bit of bytes 0..3 of an 8-element group
+#define IQ2XXS_SIGN_PRED_HI 0x80402010 // sign bit of bytes 4..7
+#define IQ2XXS_IDX_LO_MASK 0x1FE // index byte << 1, halfword 0 of a lane
+#define IQ2XXS_IDX_HI_MASK 0x1FE0000 // index byte << 1, halfword 1 of a lane
+#define IQ2XXS_NIB_LO_MASK 0x00000F0F // nibbles of the code bytes, lane bytes 0..1
+#define IQ2XXS_NIB_HI_MASK 0x0F0F0000 // nibbles of the code bytes, lane bytes 2..3
+
+static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) {
+ return (HVX_Vector *) (tile + htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS) - HTP_TENSOR_TILE_SCRATCH_IQ2_XXS);
+}
+
+// IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words
+static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) {
+ HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
+ const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES;
+
+ // lo: 4 grid indices per row, hi: 4 sign indices + scale per row
+ HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES);
+ HVX_Vector v_idx = Q6_V_lo_W(p);
+
+ // one halfword gather per 2 groups: lane i gets the codes of groups 2h and 2h+1 in halfwords 0 and 1
+ HVX_Vector v_off0 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
+ Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
+ HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)),
+ Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK)));
+ Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0);
+ Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1);
+
+ return Q6_V_hi_W(p);
+}
+
+// IQ2_XXS: wait for the gathers of iq2xxs_gather_issue and read the grid codes
+static inline void iq2xxs_gather_wait(const uint8_t * restrict tile, HVX_Vector * restrict v_c) {
+ HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile);
+ hvx_gather_sync(&v_scr[1]);
+ v_c[0] = v_scr[0];
+ v_c[1] = v_scr[1];
+}
+
+// IQ2_XXS: 8 int8 weight words (k = 4g..4g+3 per row lane) and the odd group scale (2 * scale + 1) of a 32x32 tile
+static inline void iq2xxs_decode_expand(const HVX_Vector * restrict v_c, HVX_Vector v_sgn, HVX_Vector * restrict v_w, HVX_Vector * restrict v_ls) {
+ const HVX_Vector v_zero = Q6_V_vzero();
+ const HVX_Vector v_one = Q6_V_vsplat_R(1);
+ const HVX_Vector v_sgn_mask = Q6_V_vsplat_R(IQ2XXS_SIGN_MASK);
+ const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut);
+
+ #pragma unroll
+ for (int l = 0; l < IQ2XXS_GROUPS; l++) {
+ // 7 stored sign bits + even-parity bit
+ HVX_Vector v_s7 = Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SIGN_BITS * l), v_sgn_mask);
+ HVX_Vector v_t = Q6_Vh_vpopcount_Vh(v_s7);
+ HVX_Vector v_s = Q6_V_vor_VV(v_s7, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_t, v_one), IQ2XXS_PARITY_SHIFT));
+ HVX_Vector v_s16 = Q6_V_vor_VV(v_s, Q6_Vw_vasl_VwR(v_s, 8));
+ HVX_Vector v_rep = Q6_V_vor_VV(v_s16, Q6_Vw_vasl_VwR(v_s16, 16));
+ HVX_VectorPred q_lo = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_LO);
+ HVX_VectorPred q_hi = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_HI);
+
+ HVX_Vector v_c2 = v_c[l >> 1];
+ // code halfword duplicated in both halves of each lane
+ HVX_Vector v_d = (l & 1) ? Q6_Vh_vshuffo_VhVh(v_c2, v_c2) : Q6_Vh_vshuffe_VhVh(v_c2, v_c2);
+ // lane bytes: nibbles 0, 2, 1, 3 of the code, so vlut16 returns elements 0..3 / 4..7 as words
+ HVX_Vector v_n = Q6_V_vor_VV(Q6_V_vand_VV(v_d, Q6_V_vsplat_R(IQ2XXS_NIB_LO_MASK)),
+ Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_d, 4), Q6_V_vsplat_R(IQ2XXS_NIB_HI_MASK)));
+ HVX_VectorPair p_g = Q6_Wh_vlut16_VbVhR(v_n, v_nib_lut, 0);
+ HVX_Vector v_g0 = Q6_V_lo_W(p_g);
+ HVX_Vector v_g1 = Q6_V_hi_W(p_g);
+
+ v_w[2 * l + 0] = Q6_V_vmux_QVV(q_lo, Q6_Vb_vsub_VbVb(v_zero, v_g0), v_g0);
+ v_w[2 * l + 1] = Q6_V_vmux_QVV(q_hi, Q6_Vb_vsub_VbVb(v_zero, v_g1), v_g1);
+ }
+
+ *v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SCALE_SHIFT), 1), v_one);
+}
+
+// IQ2_XXS: fp16 d of the 32 rows of a super-block (8 tiles) in halfword lanes 0..31
+static inline HVX_Vector iq2xxs_gather_d(const uint8_t * restrict sb) {
+ const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS);
+ HVX_Vector v_dd = Q6_V_vzero();
+
+ #pragma unroll
+ for (int j = 0; j < IQ2XXS_TILES_PER_SB; j++) {
+ HVX_Vector v = hvx_vmem(sb + j * padded + IQ2XXS_D_SLICE_OFF);
+ v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(IQ2XXS_D_SLICE_BYTES * j), v_dd,
+ Q6_V_vror_VR(v, (VLEN - IQ2XXS_D_SLICE_BYTES * j) & (VLEN - 1)));
+ }
+
+ return v_dd;
+}
+
+#define NVFP4_SCALE_OFF 512 // UE4M3 scales after the 32 rows x 16 B of quants
+#define NVFP4_UE4M3_MASK 0x7F // code bits; 0x7F is the NaN code, decoded as 0
+#define NVFP4_UE4M3_MIN_NORMAL 0x08 // exponent field 1
+#define NVFP4_UE4M3_MAN_SHIFT 20 // 23 - 3 mantissa bits
+#define NVFP4_UE4M3_REBIAS 0x3C000000 // (127 - 7) << 23
+#define NVFP4_UE4M3_SUB_SCALE 0x1p-9f // subnormal: mantissa * 2^-9
+#define NVFP4_VECS_PER_GROUP 2 // quant vectors per scale group
+#define NVFP4_ACT_PER_GROUP 4 // activation vectors per scale group
+#define NVFP4_UE4M3_F16_MAN_SHIFT 7 // 10 - 3 mantissa bits
+#define NVFP4_UE4M3_F16_REBIAS 0x2000 // (15 - 7) << 10
+#define NVFP4_UE4M3_F16_SUB_SCALE 0x1800 // 2^-9 as fp16 bits
+
+// UE4M3 codes in the low byte of each word -> fp32 (without the 0.5 of kvalues_mxfp4)
+static inline HVX_Vector nvfp4_ue4m3_to_f32(HVX_Vector v_code) {
+ HVX_Vector v_mask = Q6_V_vsplat_R(NVFP4_UE4M3_MASK);
+ HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask);
+
+ HVX_Vector v_norm = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(v_x, NVFP4_UE4M3_MAN_SHIFT), Q6_V_vsplat_R(NVFP4_UE4M3_REBIAS));
+ HVX_Vector v_sub = hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vw(v_x), hvx_vec_splat_f32(NVFP4_UE4M3_SUB_SCALE));
+
+ HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VwVw(Q6_V_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x);
+ HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VwVw(v_x, v_mask);
+
+ return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm));
+}
+
+// UE4M3 codes in the low byte of each halfword -> fp16
+static inline HVX_Vector nvfp4_ue4m3_to_f16(HVX_Vector v_code) {
+ HVX_Vector v_mask = Q6_Vh_vsplat_R(NVFP4_UE4M3_MASK);
+ HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask);
+
+ HVX_Vector v_norm = Q6_Vh_vadd_VhVh(Q6_Vh_vasl_VhR(v_x, NVFP4_UE4M3_F16_MAN_SHIFT), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_REBIAS));
+ HVX_Vector v_sub = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_x), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_SUB_SCALE)));
+
+ HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VhVh(Q6_Vh_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x);
+ HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VhVh(v_x, v_mask);
+
+ return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm));
+}
+
+#define F8_E4M3_SIGN_MASK 0x80 // sign bit in FP8 E4M3
+#define F8_E4M3_F16_MAN_SHIFT 7 // 10 - 3 mantissa bits
+#define F8_E4M3_F16_REBIAS 0x2000 // (15 - 7) << 10
+#define F8_E4M3_F16_SUB_SCALE 0x1800 // 2^-9 as fp16 bits
+
+// Signed F8_E4M3 codes in the low byte of each halfword -> fp16 (0x7F/0xFF NaN -> 0)
+static inline HVX_Vector f8_e4m3_to_f16(HVX_Vector v_code) {
+ HVX_Vector v_mask = Q6_Vh_vsplat_R(NVFP4_UE4M3_MASK);
+ HVX_Vector v_abs = Q6_V_vand_VV(v_code, v_mask);
+ HVX_Vector v_sign = Q6_Vh_vasl_VhR(Q6_V_vand_VV(v_code, Q6_Vh_vsplat_R(F8_E4M3_SIGN_MASK)), 8);
+
+ HVX_Vector v_norm = Q6_Vh_vadd_VhVh(Q6_Vh_vasl_VhR(v_abs, F8_E4M3_F16_MAN_SHIFT), Q6_Vh_vsplat_R(F8_E4M3_F16_REBIAS));
+ HVX_Vector v_sub = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_abs), Q6_Vh_vsplat_R(F8_E4M3_F16_SUB_SCALE)));
+
+ HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VhVh(Q6_Vh_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_abs);
+ HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VhVh(v_abs, v_mask);
+
+ return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vor_VV(Q6_V_vmux_QVV(q_sub, v_sub, v_norm), v_sign));
+}
+
+// --- Shared HMX Bias / Packing Helpers ---
+
+static inline HVX_Vector hmx_load_bias_f32_32_f16(const void * bias_row_base, size_t c) {
+ const __fp16 * p = (const __fp16 *) bias_row_base + c;
+ return Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(p)));
+}
+
+static inline HVX_Vector hmx_load_bias_f32_32_f32(const void * bias_row_base, size_t c) {
+ const float * p = (const float *) bias_row_base + c;
+ return hvx_vmemu(p);
+}
+
+static inline HVX_VectorPair hmx_load_bias_f32_64_f16(const void * bias_row_base, size_t c) {
+ const __fp16 * p = (const __fp16 *) bias_row_base + c;
+ return hvx_vec_f16_to_f32(hvx_vmemu(p));
+}
+
+static inline HVX_VectorPair hmx_load_bias_f32_64_f32(const void * bias_row_base, size_t c) {
+ const float * p = (const float *) bias_row_base + c;
+ return Q6_W_vcombine_VV(hvx_vmemu(p + 32), hvx_vmemu(p));
+}
+
+// --- Shared HMX Scale / Norm / GLU / Batched / MMID Helpers ---
+
+static inline void htp_mm_load_scale(
+ dma_queue * dma_q,
+ float * vtcm_scale,
+ dma_addr_t scale_addr,
+ size_t scale_bytes,
+ bool splat_scalar) {
+ dma_queue_push(dma_q, dma_make_data(vtcm_scale, scale_addr), hex_align_up(scale_bytes, 128), 0, scale_bytes, 1);
+ dma_queue_pop(dma_q);
+ if (splat_scalar) {
+ hvx_vmem(vtcm_scale) = hvx_vec_repl4(hvx_vmem(vtcm_scale));
+ }
+}
+
+static inline void htp_mm_load_norm(
+ dma_queue * dma_q,
+ float * vtcm_norm,
+ void * vtcm_tmp,
+ const struct htp_tensor * norm_w,
+ uint32_t k_valid,
+ bool deinterleave_f16) {
+ if (norm_w->type == HTP_TYPE_F16) {
+ const size_t nbytes = (size_t) k_valid * sizeof(__fp16);
+ dma_queue_push(dma_q, dma_make_data(vtcm_tmp, norm_w->data), hex_align_up(nbytes, 128), 0, nbytes, 1);
+ dma_queue_pop(dma_q);
+ hvx_copy_f32_f16_aa((uint8_t *) vtcm_norm, (const uint8_t *) vtcm_tmp, k_valid);
+ } else {
+ const size_t nbytes = (size_t) k_valid * sizeof(float);
+ dma_queue_push(dma_q, dma_make_data(vtcm_norm, norm_w->data), hex_align_up(nbytes, 128), 0, nbytes, 1);
+ dma_queue_pop(dma_q);
+ }
+ if (deinterleave_f16) {
+ const uint32_t k_pad = hex_align_up(k_valid, 64u);
+ if (k_pad > k_valid) {
+ memset(vtcm_norm + k_valid, 0, (size_t) (k_pad - k_valid) * sizeof(float));
+ }
+ HVX_Vector * vw = (HVX_Vector *) vtcm_norm;
+ const uint32_t npairs = k_pad >> 6;
+ for (uint32_t i = 0; i < npairs; ++i) {
+ HVX_VectorPair wp = Q6_W_vdeal_VVR(vw[2 * i + 1], vw[2 * i], -4);
+ vw[2 * i] = Q6_V_lo_W(wp);
+ vw[2 * i + 1] = Q6_V_hi_W(wp);
+ }
+ }
+}
+
+void hvx_rms_norm_mul_rows_f32(
+ uint8_t * restrict curr_buf,
+ size_t row_bytes,
+ uint32_t valid_rows,
+ uint32_t k_valid,
+ const float * restrict vtcm_norm,
+ float norm_eps);
+
+void hvx_rms_norm_mul_rows_f16(
+ uint8_t * restrict curr_buf,
+ size_t row_bytes,
+ uint32_t valid_rows,
+ uint32_t k_valid,
+ const float * restrict vtcm_norm,
+ float norm_eps);
+
+typedef void (*hmx_glu_store_quad_fn_t)(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_vec,
+ const HVX_Vector * restrict u_vec,
+ uint32_t valid_rows);
+
+typedef void (*hmx_glu_store_tail_fn_t)(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const HVX_Vector * restrict g_vec,
+ const HVX_Vector * restrict u_vec,
+ uint32_t rows_and_bytes);
+
+typedef void (*hmx_glu_store_strip_fn_t)(
+ void * restrict dst_ptr,
+ size_t dst_stride,
+ const __fp16 * restrict u_buf,
+ size_t u_stride,
+ size_t n_pairs);
+
+typedef void (*hmx_output_glu_col_chunk_fn_t)(
+ const void * st_void,
+ void * restrict dst_ptr,
+ uint32_t start_row,
+ uint32_t n_rows,
+ uint32_t c_first,
+ uint32_t c_len_and_dst_cols);
+
+typedef struct {
+ void * dst;
+ const uint8_t * vtcm_gate;
+ const uint8_t * vtcm_up;
+ const float * vtcm_act_scales;
+ const float * vtcm_wt_scales_gate;
+ const float * vtcm_wt_scales_up;
+ uint32_t w_scale_gate_c_mask;
+ uint32_t w_scale_up_c_mask;
+ uint32_t n_rows;
+ uint32_t mc_pad;
+ uint32_t n_cols;
+ uint32_t n_groups;
+ uint32_t dst_stride;
+ uint32_t dst_cols;
+ size_t dst_elem_size;
+ uint32_t n_tasks;
+ uint32_t n_chunks_per_task;
+ struct fastdiv_values n_hvx_div;
+ hmx_output_glu_col_chunk_fn_t col_chunk_fn;
+ hmx_glu_store_quad_fn_t store_quad_fn;
+ hmx_glu_store_tail_fn_t store_tail_fn;
+ hmx_glu_store_strip_fn_t store_strip_fn;
+} hmx_output_glu_state_t;
+
+bool resolve_hmx_glu_store_fns(
+ uint8_t glu_op,
+ size_t dst_elem_size,
+ hmx_glu_store_quad_fn_t * store_quad_fn,
+ hmx_glu_store_tail_fn_t * store_tail_fn,
+ hmx_glu_store_strip_fn_t * store_strip_fn);
+
+void hmx_transfer_output_glu(
+ struct htp_ops_context * octx,
+ hmx_output_glu_state_t * state,
+ void * dst,
+ const void * vtcm_gate,
+ const void * vtcm_up,
+ const float * vtcm_wt_scales_gate,
+ const float * vtcm_wt_scales_up,
+ int n_rows,
+ int n_cols,
+ int dst_cols);
+
+typedef struct {
+ dma_queue * weight_dma;
+ dma_addr_t dst_dma_addr;
+ dma_addr_t bias_addr;
+ size_t bias_bytes;
+ dma_addr_t scale_addr;
+ size_t scale_bytes;
+ bool scale_per_channel;
+ dma_addr_t act_dma_addr;
+ dma_addr_t weight;
+ int m;
+ int k;
+ int n;
+ int act_stride;
+ uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
+ int weight_stride;
+ int weight_type;
+ int k_valid;
+ int dst_stride;
+ uint32_t bias_stride;
+ int dst_cols;
+ uint32_t dst_elem_size; // 4=F32 dst, 2=F16 dst
+ uint32_t bias_elem_size; // 4=F32 bias, 2=F16 bias
+} hmx_mm_2d_params_t;
+
+typedef struct {
+ dma_queue * weight_dma;
+ const dma_addr_t * dsts;
+ dma_addr_t activation;
+ size_t act_elem_size;
+ size_t dst_elem_size;
+ const dma_addr_t * weights;
+ uint32_t n_weights;
+ int m;
+ int k;
+ int n;
+ int k_valid;
+ int ne11;
+ size_t act_nb1;
+ size_t act_nb2;
+ size_t dst_nb1;
+ size_t dst_nb2;
+ int weight_stride;
+ int weight_type;
+ const struct mmid_row_mapping * matrix_rows;
+ int cur_a;
+ int mapping_stride;
+ int m_start;
+ int m_end;
+ const dma_addr_t * scale_addrs;
+ const size_t * scale_bytes_arr;
+ const uint8_t * scale_per_ch_arr;
+} hmx_mm_id_2d_params_t;
+
+typedef struct {
+ dma_addr_t dst_dma_addr;
+ dma_addr_t bias_addr;
+ size_t bias_bytes;
+ dma_addr_t scale_addr;
+ size_t scale_bytes;
+ uint8_t scale_per_channel;
+ dma_addr_t act_dma_addr;
+ dma_addr_t weight;
+ dma_queue * weight_dma;
+ int m;
+ int k;
+ int n;
+ int act_stride;
+ uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
+ uint32_t dst_elem_size; // 4=F32 dst, 2=F16 dst
+ uint32_t bias_elem_size; // 4=F32 bias, 2=F16 bias
+ int weight_stride;
+ int weight_type;
+ int dst_stride;
+ int dst_cols;
+ uint32_t bias_stride;
+ int ne02;
+ int ne03;
+ int ne12;
+ int ne13;
+ size_t src0_nb2;
+ size_t src0_nb3;
+ size_t act_nb2;
+ size_t act_nb3;
+ size_t bias_nb2;
+ size_t bias_nb3;
+ size_t dst_nb2;
+ size_t dst_nb3;
+ int r2;
+ int r3;
+ struct fastdiv_values div_r2;
+ struct fastdiv_values div_r3;
+} hmx_mm_batched_params_t;
+
+static inline dma_addr_t hmx_mm_weight_batch_data(const hmx_mm_batched_params_t * params, int dst_b2, int dst_b3) {
+ const size_t b2_idx = (params->r2 <= 1) ? (size_t) dst_b2 : (size_t) fastdiv((uint32_t) dst_b2, ¶ms->div_r2);
+ const size_t b3_idx = (params->r3 <= 1) ? (size_t) dst_b3 : (size_t) fastdiv((uint32_t) dst_b3, ¶ms->div_r3);
+ return params->weight + b2_idx * params->src0_nb2 + b3_idx * params->src0_nb3;
+}
+
+static inline dma_addr_t hmx_mm_act_batch_addr(const hmx_mm_batched_params_t * params, int dst_b2, int dst_b3) {
+ return params->act_dma_addr + dst_b2 * params->act_nb2 + dst_b3 * params->act_nb3;
+}
+
+static inline dma_addr_t hmx_mm_dst_batch_addr(const hmx_mm_batched_params_t * params, int dst_b2, int dst_b3) {
+ return params->dst_dma_addr + (size_t) dst_b2 * params->dst_nb2 + (size_t) dst_b3 * params->dst_nb3;
+}
+
+static inline void push_gathered_act_rows(
+ dma_queue * dma_q,
+ uint8_t * slot_buf,
+ dma_addr_t act_dma_addr,
+ uint32_t valid_rows,
+ uint32_t start_row,
+ uint32_t r,
+ size_t row_bytes,
+ size_t valid_bytes,
+ const struct mmid_row_mapping * matrix_rows,
+ uint32_t cur_a,
+ uint32_t mapping_stride,
+ uint32_t ne11,
+ const struct fastdiv_values * ne11_div,
+ size_t nb11,
+ size_t nb12) {
+ const size_t base_idx = (size_t) cur_a * mapping_stride + start_row + r;
+ if (ne11 == 1) {
+ for (uint32_t s = 0; s < valid_rows; ++s) {
+ const struct mmid_row_mapping mapping = matrix_rows[base_idx + s];
+ const dma_addr_t src_row = act_dma_addr + (size_t) mapping.i2 * nb12;
+ dma_queue_push(dma_q, dma_make_data(slot_buf + (size_t) s * row_bytes, src_row),
+ valid_bytes, valid_bytes, valid_bytes, 1);
+ }
+ } else {
+ for (uint32_t s = 0; s < valid_rows; ++s) {
+ const struct mmid_row_mapping mapping = matrix_rows[base_idx + s];
+ const uint32_t i11 = fastmodulo(mapping.i1, ne11, ne11_div);
+ const dma_addr_t src_row = act_dma_addr + (size_t) i11 * nb11 + (size_t) mapping.i2 * nb12;
+ dma_queue_push(dma_q, dma_make_data(slot_buf + (size_t) s * row_bytes, src_row),
+ valid_bytes, valid_bytes, valid_bytes, 1);
+ }
+ }
+}
+
+static inline void push_scattered_dst_rows(
+ dma_queue * dma_q,
+ dma_addr_t dst_dma_addr,
+ const uint8_t * vtcm_src,
+ uint32_t start_row,
+ uint32_t n_rows,
+ size_t vtcm_row_bytes,
+ size_t copy_bytes,
+ const struct mmid_row_mapping * matrix_rows,
+ uint32_t cur_a,
+ uint32_t mapping_stride,
+ size_t dst_nb1,
+ size_t dst_nb2) {
+ const size_t base_idx = (size_t) cur_a * mapping_stride + start_row;
+ for (uint32_t r = 0; r < n_rows; ++r) {
+ const struct mmid_row_mapping mapping = matrix_rows[base_idx + r];
+ const dma_addr_t dst_row = dst_dma_addr + (size_t) mapping.i1 * dst_nb1 + (size_t) mapping.i2 * dst_nb2;
+ dma_queue_push(dma_q, dma_make_data(dst_row, vtcm_src + (size_t) r * vtcm_row_bytes),
+ copy_bytes, copy_bytes, copy_bytes, 1);
+ }
+}
+
+static inline void sync_scattered_dst_rows(
+ dma_queue * dma_q,
+ dma_addr_t dst_dma_addr,
+ const uint8_t * vtcm_src,
+ uint32_t start_row,
+ uint32_t n_rows,
+ size_t vtcm_row_bytes,
+ size_t copy_bytes,
+ const struct mmid_row_mapping * matrix_rows,
+ uint32_t cur_a,
+ uint32_t mapping_stride,
+ size_t dst_nb1,
+ size_t dst_nb2) {
+ for (uint32_t r = 0; r < n_rows; r += 128u) {
+ const uint32_t batch = hex_smin(n_rows - r, 128u);
+ push_scattered_dst_rows(dma_q, dst_dma_addr, vtcm_src + (size_t) r * vtcm_row_bytes,
+ start_row + r, batch, vtcm_row_bytes, copy_bytes,
+ matrix_rows, cur_a, mapping_stride, dst_nb1, dst_nb2);
+ for (uint32_t s = 0; s < batch; ++s) {
+ dma_queue_pop(dma_q);
+ }
+ }
+}
+
+struct htp_mmid_mapping {
+ const int32_t * ids_data;
+ uint32_t * matrix_row_counts;
+ struct mmid_row_mapping * matrix_rows;
+ uint32_t mapping_stride;
+ uint32_t n_skipped;
+};
+
+#endif // HTP_MATMUL_INTERNAL_H
diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.c b/ggml/src/ggml-hexagon/htp/matmul-ops.c
index 1dc0a9332..d8dddef1f 100644
--- a/ggml/src/ggml-hexagon/htp/matmul-ops.c
+++ b/ggml/src/ggml-hexagon/htp/matmul-ops.c
@@ -1,88 +1,12 @@
-#include <HAP_farf.h>
-#include <HAP_perf.h>
-#include <HAP_compute_res.h>
-
-#include <math.h>
-#include <string.h>
-#include <stdatomic.h>
-
-#include "dma-queue.h"
-#include "hvx-utils.h"
-#include "hvx-dump.h"
-#include "hvx-arith.h"
-#include "hvx-reduce.h"
-#include "hvx-copy.h"
-
-#define GGML_COMMON_DECL_C
-#include "ggml-common.h"
-#include "htp-ctx.h"
-#include "htp-ops.h"
-#include "htp-tensor.h"
-#include "matmul-ops.h"
-#include "htp-vtcm.h"
-
-typedef struct {
- 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;
- dma_queue * weight_dma;
- int m;
- int k;
- int n;
- int act_stride;
- uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
- uint32_t dst_elem_size; // 4=F32 dst, 2=F16 dst
- uint32_t bias_elem_size; // 4=F32 bias, 2=F16 bias
- int weight_stride;
- int weight_type;
- int dst_stride;
- int dst_cols;
- uint32_t bias_stride;
- int tile_size;
- int aligned_tile_size;
- int ne02;
- int ne03;
- int ne12;
- int ne13;
- size_t src0_nb2;
- size_t src0_nb3;
- size_t act_nb2;
- size_t act_nb3;
- size_t bias_nb2;
- size_t bias_nb3;
- size_t dst_nb2;
- size_t dst_nb3;
- int r2;
- int r3;
- struct fastdiv_values div_r2;
- struct fastdiv_values div_r3;
- 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;
+#include "matmul-internal.h"
+#include "matmul-hmx-w8a8.h"
+#include "matmul-hmx-f16.h"
+#include "matmul-hvx.h"
-static int htp_mm_init_context(
- struct htp_ops_context * octx,
- const struct htp_mm_kernel_params * kparams
-) {
- if (!htp_ops_context_set_n_hvx(octx, (uint32_t) kparams->n_hvx)) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
- if (kparams->n_hmx) {
- if (kparams->n_act_hvx <= 0 || kparams->n_act_hvx > (int32_t) octx->n_hvx) {
- return HTP_STATUS_INVAL_PARAMS;
- }
- }
-
- return HTP_STATUS_OK;
-}
+// --- Shared LUTs ---
// vdelta control to expand first 32 e8m0 values into 32 uint32 elements
-static const uint8_t __attribute__((aligned(128))) expand_x32_e8m0[128] = {
+const uint8_t __attribute__((aligned(128))) expand_x32_e8m0[128] = {
0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x02, 0x00, 0x08, 0x08, 0x01, 0x02, 0x00, 0x04, 0x04, 0x00, 0x00,
0x00, 0x11, 0x10, 0x10, 0x10, 0x02, 0x00, 0x04, 0x00, 0x01, 0x02, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x01, 0x04,
0x00, 0x00, 0x22, 0x20, 0x20, 0x20, 0x21, 0x22, 0x20, 0x24, 0x04, 0x00, 0x00, 0x00, 0x09, 0x08, 0x00, 0x00, 0x02,
@@ -94,7 +18,7 @@ static const uint8_t __attribute__((aligned(128))) expand_x32_e8m0[128] = {
// IQ4_NL dequantization LUT: maps 4-bit index (0-15) to int8 kvalue
// kvalues: -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113
-static const uint8_t __attribute__((aligned(VLEN))) kvalues_iq4nl_lut[] = {
+const uint8_t __attribute__((aligned(VLEN))) kvalues_iq4nl_lut[] = {
0x81, 0, 0x98, 0, 0xAD, 0, 0xBF, 0, 0xCF, 0, 0xDD, 0, 0xEA, 0, 0xF6, 0, 0x01, 0, 0x0D, 0, 0x19, 0, 0x26, 0,
0x35, 0, 0x45, 0, 0x59, 0, 0x71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -102,7 +26,7 @@ static const uint8_t __attribute__((aligned(VLEN))) kvalues_iq4nl_lut[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
-static const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_lut[] = {
+const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_lut[] = {
0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0xff, 0, 0xfe, 0, 0xfd, 0, 0xfc, 0,
0xfa, 0, 0xf8, 0, 0xf4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -112,5865 +36,755 @@ static const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_lut[] = {
#include "iq2xxs-tables.h"
-// VTCM copy of htp_iq2xxs_lut for the current op (set by hvx_mm_iq2xxs_lut_init)
-static const uint8_t * iq2xxs_vtcm_lut;
+const uint8_t * iq2xxs_vtcm_lut;
-static inline void iq2xxs_lut_copy(uint8_t * restrict lut) {
+void iq2xxs_lut_copy(uint8_t * restrict lut) {
for (uint32_t i = 0; i < HTP_IQ2XXS_LUT_BYTES / VLEN; i++) {
hvx_vmem(lut + i * VLEN) = hvx_vmem(htp_iq2xxs_lut + i * VLEN);
}
iq2xxs_vtcm_lut = lut;
}
-static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct htp_mm_hvx_vtcm_layout * restrict L) {
- if (L->lut_bytes == 0) {
- return;
- }
- iq2xxs_lut_copy(base + L->off_lut);
-}
-
-#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;
-
-
-
-
-// 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-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 act_nrows = 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_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;
-
- const dma_addr_t src0_row = src0->data;
-
- 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 ct_start = src0_start_row / 32;
- uint32_t ct_end = (src0_end_row + 31) / 32;
-
- 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);
- 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);
- }
- 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);
- }
- 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 (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);
- }
- }
-}
-
-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_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);
-
- 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;
- uint8_t * act_data = mmctx->vtcm_act;
-
- float * tmp = (float *) vtcm_dst_ptr;
-
- const dma_addr_t src0_row = src0->data;
-
- const uint8_t * restrict act_col = (const uint8_t *) act_data;
-
- 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) {
- 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) {
- 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++) {
- 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;
- }
-
- for (uint32_t ct = ct_start; ct < ct_end; ct++) {
- const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst;
-
- float * dst_ptr = &tmp[ct * 32 - src0_start_row];
- int valid_rows = (int)ne0 - (int)(ct * 32);
- 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, hvx_tiled_store_row_f32_none);
- 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++;
- }
- }
-
- 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);
- 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);
- }
-}
-
-static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_mm_context * mmctx = data;
- struct htp_ops_context * octx = mmctx->octx;
- const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- const uint32_t n_weights = kparams->n_weights;
+// --- Shared Fused RMSNorm Helpers ---
- const struct htp_tensor * restrict act = octx->src[n_weights]; /* x */
- const uint32_t ne10 = act->ne[0];
- const uint32_t act_nrows = act->ne[1] * act->ne[2] * act->ne[3];
- const size_t act_stride = mmctx->vtcm_act_stride;
+__attribute__((noinline)) void hvx_rms_norm_mul_rows_f32(
+ uint8_t * restrict curr_buf,
+ size_t row_bytes,
+ uint32_t valid_rows,
+ uint32_t k_valid,
+ const float * restrict vtcm_norm,
+ float norm_eps) {
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) vtcm_norm;
+ const int nvec = (int) (k_valid / VLEN_FP32);
+ const int nloe = (int) (k_valid % VLEN_FP32);
+ const HVX_Vector denom_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) k_valid));
+ const HVX_Vector epsilon_v = hvx_vec_splat_f32(norm_eps);
- 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;
+ for (uint32_t rr = 0; rr < valid_rows; ++rr) {
+ HVX_Vector * restrict v_row = (HVX_Vector *) (curr_buf + rr * row_bytes);
- 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);
-
- for (uint32_t widx = 0; widx < n_weights; widx++) {
- const struct htp_tensor * restrict src_w = octx->src[widx];
- const struct htp_tensor * restrict dst = octx->dsts[widx];
- if (!src_w || !dst) continue;
- dma_queue * dma_q = th->dma_q;
-
- 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);
- 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;
-
- uint32_t src0_start_row = 0;
- uint32_t src0_end_row = ne01;
- if (octx->ctx->mdev.count > 1) {
- 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;
+ HVX_Vector sum_v = Q6_V_vzero();
+ #pragma unroll(4)
+ for (int i = 0; i < nvec; ++i) {
+ HVX_Vector v1 = v_row[i];
+ sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(v1, v1));
}
-
- const uint32_t nrows = src0_end_row - src0_start_row;
- uint32_t src0_nrows_per_hvx = fastdiv(nrows + nth - 1, &octx->n_hvx_div);
- src0_nrows_per_hvx = hex_round_up(src0_nrows_per_hvx, 32);
-
- const uint32_t start_row = src0_start_row + src0_nrows_per_hvx * ith;
- const uint32_t end_row = MIN(start_row + src0_nrows_per_hvx, src0_end_row);
- if (start_row >= end_row) continue;
-
- uint32_t ct_start = start_row / 32;
- uint32_t ct_end = (end_row + 31) / 32;
-
- 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);
- }
-
- 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));
-
- 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);
-
- 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 (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 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);
- }
- }
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP32);
+ HVX_Vector v1 = Q6_V_vand_QV(bmask, v_row[nvec]);
+ sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(v1, v1));
}
- }
-}
-static void hvx_mm_transfer_act_dma(
- struct htp_ops_context * octx,
- const struct htp_mm_kernel_params * kparams,
- const struct htp_tensor * act,
- uint8_t * dst_base,
- size_t dst_row_size,
- uint32_t m_start,
- uint32_t m_rows
-) {
- if (m_rows == 0) {
- return;
- }
+ sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v));
+ 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));
- dma_queue * dma_q = octx->ctx->dma[0];
- const uint32_t ne0 = act->ne[0];
- const size_t elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
- const size_t row_bytes = ne0 * elem_size;
- const size_t act_nb1 = act->nb[1];
- const dma_addr_t act_base = act->data;
-
- const bool is_contiguous = (act->nb[2] == act->ne[1] * act_nb1) &&
- (act->nb[3] == act->ne[2] * act->nb[2]);
-
- if (is_contiguous) {
- const dma_addr_t src_addr = act_base + m_start * act_nb1;
- dma_queue_push(dma_q, dma_make_data(dst_base, src_addr),
- dst_row_size, act_nb1, row_bytes, m_rows);
- dma_queue_pop(dma_q);
- } else {
- const uint32_t ne12_ne1 = act->ne[2] * act->ne[1];
- for (uint32_t ir = 0; ir < m_rows; ++ir) {
- const uint32_t ir1 = m_start + ir;
- 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]);
- uint8_t * row_dst = dst_base + ir * dst_row_size;
- dma_queue_push(dma_q, dma_make_data(row_dst, row_src),
- dst_row_size, act_nb1, row_bytes, 1);
- dma_queue_pop(dma_q);
+ #pragma unroll(4)
+ for (int i = 0; i < nvec; ++i) {
+ HVX_Vector s = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_row[i], scale_v));
+ v_row[i] = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s, v_w[i]));
}
- }
-
- if (dst_row_size > row_bytes) {
- struct htp_thread_trace * tr = &octx->ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) m_start);
- const uint32_t pad_elems = (dst_row_size - row_bytes) / elem_size;
- if (elem_size == sizeof(float)) {
- for (uint32_t ir = 0; ir < m_rows; ++ir) {
- hvx_splat_f32_u(dst_base + ir * dst_row_size + row_bytes, 0.0f, pad_elems);
- }
- } else {
- for (uint32_t ir = 0; ir < m_rows; ++ir) {
- hvx_splat_f16_u(dst_base + ir * dst_row_size + row_bytes, (_Float16) 0.0f, pad_elems);
- }
+ if (nloe > 0) {
+ HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP32);
+ HVX_Vector v1 = Q6_V_vand_QV(bmask, v_row[nvec]);
+ HVX_Vector s = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v1, scale_v));
+ hvx_vec_store_a(&v_row[nvec], nloe * SIZEOF_FP32, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s, v_w[nvec])));
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) m_start);
}
}
-#define QUANTIZE_IMPL(name, log_name, kernel_fn, dst_row_size_expr) \
-static void name(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { \
- (void) nth; \
- struct htp_mm_context * mmctx = data; \
- 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; \
- const uint32_t nrows_per_hvx = mmctx->n_quant_rows_per_hvx; \
- \
- const uint32_t ir_first = nrows_per_hvx * ith; \
- if (ir_first >= nrows) { \
- return; \
- } \
- \
- struct htp_thread_trace * tr = th->trace; \
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, ir_first); \
- \
- uint8_t * restrict dst = mmctx->vtcm_act; \
- const uint32_t ir_last = MIN(ir_first + nrows_per_hvx, nrows); \
- const size_t raw_row_size = mmctx->vtcm_act_raw_stride; \
- const size_t dst_row_size = (dst_row_size_expr); \
- \
- const uint8_t * restrict src_data = (const uint8_t *) mmctx->vtcm_act_raw + (raw_row_size * ir_first); \
- uint8_t * restrict dst_data = (uint8_t *) dst + (dst_row_size * ir_first); \
- kernel_fn(src_data, dst_data, NULL, ne0, ir_last - ir_first, raw_row_size, dst_row_size); \
- \
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, ir_first); \
-}
-
-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_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)
-
-static void quantize_f32_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;
+__attribute__((noinline)) void hvx_rms_norm_mul_rows_f16(
+ uint8_t * restrict curr_buf,
+ size_t row_bytes,
+ uint32_t valid_rows,
+ uint32_t k_valid,
+ const float * restrict vtcm_norm,
+ float norm_eps) {
+ const HVX_Vector * restrict v_w = (const HVX_Vector *) vtcm_norm;
+ const int nvec = (int) (k_valid / VLEN_FP16);
+ const int nloe = (int) (k_valid % VLEN_FP16);
+ const HVX_Vector denom_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) k_valid));
+ const HVX_Vector epsilon_v = hvx_vec_splat_f32(norm_eps);
+
+ for (uint32_t rr = 0; rr < valid_rows; ++rr) {
+ HVX_Vector * restrict v_row = (HVX_Vector *) (curr_buf + rr * row_bytes);
+
+#if __HVX_ARCH__ >= 79
+ HVX_VectorPair sum_p = Q6_W_vzero();
+ for (int i = 0; i < nvec; ++i) {
+ HVX_Vector v = v_row[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 v = Q6_V_vand_QV(bmask, v_row[nvec]);
+ sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, 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();
+ for (int i = 0; i < nvec; ++i) {
+ HVX_Vector v = v_row[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_row[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 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));
+
+ for (int i = 0; i < nvec; ++i) {
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_row[i]);
+ HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v));
+ HVX_Vector s1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v));
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, v_w[2 * i]));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, v_w[2 * i + 1]));
+ v_row[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_row[nvec]);
+ HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1);
+ HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v));
+ HVX_Vector s1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v));
+ HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, v_w[2 * nvec]));
+ HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, v_w[2 * nvec + 1]));
+ hvx_vec_store_a(&v_row[nvec], nloe * SIZEOF_FP16, hvx_vec_f32_to_f16_shuff(r0, r1));
+ }
+ }
+}
+
+// --- Shared HMX GLU Store & Dispatch Helpers ---
+
+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_f16( \
+ 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_f16( \
+ 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_f16(dst, dst_stride, g_hf, u_hf, (valid_rows << 16) | 128u); \
+} \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_tail_f32( \
+ 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_f32( \
+ 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_f32(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_F16(NAME, ARG_F16) \
+static __attribute__((noinline)) void hmx_glu_##NAME##_store_strip_f16( \
+ 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_F16(swiglu, HMX_GLU_ARG_SWIGLU_F16)
+DEFINE_HMX_SIG_GLU_STRIP_F16(geglu, HMX_GLU_ARG_GEGLU_F16)
+DEFINE_HMX_SIG_GLU_STRIP_F16(geglu_quick, HMX_GLU_ARG_GEGLU_QUICK_F16)
+
+static __attribute__((noinline)) void hmx_glu_reglu_store_tail_f16(
+ 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_f16(
+ 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_f16(
+ 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_f32(
+ 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_f32(
+ 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]);
+ }
+}
+
+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_f16;
+ *store_tail_fn = hmx_glu_swiglu_store_tail_f16;
+ *store_strip_fn = hmx_glu_swiglu_store_strip_f16;
+ return true;
+ case HTP_OP_GLU_GEGLU:
+ *store_quad_fn = hmx_glu_geglu_store_quad_f16;
+ *store_tail_fn = hmx_glu_geglu_store_tail_f16;
+ *store_strip_fn = hmx_glu_geglu_store_strip_f16;
+ return true;
+ case HTP_OP_GLU_GEGLU_QUICK:
+ *store_quad_fn = hmx_glu_geglu_quick_store_quad_f16;
+ *store_tail_fn = hmx_glu_geglu_quick_store_tail_f16;
+ *store_strip_fn = hmx_glu_geglu_quick_store_strip_f16;
+ return true;
+ case HTP_OP_GLU_REGLU:
+ *store_quad_fn = hmx_glu_reglu_store_quad_f16;
+ *store_tail_fn = hmx_glu_reglu_store_tail_f16;
+ *store_strip_fn = hmx_glu_reglu_store_strip_f16;
+ 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_f32;
+ *store_tail_fn = hmx_glu_swiglu_store_tail_f32;
+ return true;
+ case HTP_OP_GLU_GEGLU:
+ *store_quad_fn = hmx_glu_geglu_store_quad_f32;
+ *store_tail_fn = hmx_glu_geglu_store_tail_f32;
+ return true;
+ case HTP_OP_GLU_GEGLU_QUICK:
+ *store_quad_fn = hmx_glu_geglu_quick_store_quad_f32;
+ *store_tail_fn = hmx_glu_geglu_quick_store_tail_f32;
+ return true;
+ case HTP_OP_GLU_REGLU:
+ *store_quad_fn = hmx_glu_reglu_store_quad_f32;
+ *store_tail_fn = hmx_glu_reglu_store_tail_f32;
+ return true;
+ default:
+ return false;
}
- 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_f32_q8_0_tiled_block_kernel(
- (const float *) 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]
- );
-
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
}
-static void quantize_f32_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;
- }
+static void hmx_transfer_output_glu_col_worker(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;
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
-
- const struct htp_tensor * src = mmctx->act;
-
- quantize_f32_q8_1_tiled_block_kernel(
- (const float *) 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_f32_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;
+ 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);
}
- 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_f32_q8_1_s16_tiled_block_kernel(
- (const float *) 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_f32_f16_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]) {
+ if (b_first >= b_last) {
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_f32_f16_tiled_block_kernel(
- (const float *) 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_f16_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_f16_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]) {
+ 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;
}
- 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_f16_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_f16_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_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;
- }
- 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_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]
- );
-
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]);
+ 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 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;
- }
+static void hmx_transfer_output_glu_row_worker(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;
- 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_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]) {
+ 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;
}
- 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;
+ 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 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;
- const uint32_t ct_end = (src0_end_row + 31) / 32;
-
- if (src0_start_row >= src0_end_row || cur_m_rows == 0) {
+void hmx_transfer_output_glu(
+ struct htp_ops_context * octx,
+ hmx_output_glu_state_t * state,
+ void * dst,
+ const void * vtcm_gate,
+ const void * vtcm_up,
+ const float * vtcm_wt_scales_gate,
+ const float * vtcm_wt_scales_up,
+ int n_rows,
+ int n_cols,
+ int dst_cols) {
+ if (n_rows <= 0 || dst_cols <= 0) {
return;
}
- const uint32_t total_batches = ne12 * ne13;
- const uint32_t b_start = fastdiv(cur_m_start, &kparams->div_ne1);
- uint32_t b_end = fastdiv(cur_m_start + cur_m_rows + ne11 - 1, &kparams->div_ne1);
- b_end = MIN(b_end, total_batches);
-
- uint32_t b_grp_start = b_start;
- while (b_grp_start < b_end) {
- const uint32_t b3 = fastdiv(b_grp_start, &kparams->div_ne12);
- const uint32_t b2 = b_grp_start - b3 * ne12;
- const uint32_t i02 = fastdiv(b2, &kparams->div_r2);
- const uint32_t i03 = fastdiv(b3, &kparams->div_r3);
-
- uint32_t b_grp_end = b_grp_start + 1;
- while (b_grp_end < b_end) {
- const uint32_t cur_b3 = fastdiv(b_grp_end, &kparams->div_ne12);
- const uint32_t cur_b2 = b_grp_end - cur_b3 * ne12;
- const uint32_t cur_i02 = fastdiv(cur_b2, &kparams->div_r2);
- const uint32_t cur_i03 = fastdiv(cur_b3, &kparams->div_r3);
- if (cur_i02 != i02 || cur_i03 != i03) {
- break;
- }
- b_grp_end++;
- }
-
- const uint32_t slice_idx = i03 * ne02 + i02;
- const dma_addr_t src0_slice = src0->data + (dma_addr_t) slice_idx * src0_slice_stride;
-
- 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++) {
- const uint32_t b_m_start = b * ne11;
- const uint32_t m_first = MAX(cur_m_start, b_m_start);
- const uint32_t m_last = MIN(cur_m_start + cur_m_rows, b_m_start + ne11);
- if (m_first >= m_last) continue;
-
- const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
- const uint32_t cur_b2 = b - cur_b3 * ne12;
- 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 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 (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);
- }
- }
- b_grp_start = b_grp_end;
- }
-}
-
-static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_matmul_preamble;
-
- 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 act_nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : mmctx->act_nrows;
- 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);
- const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
-
- struct htp_thread_trace * tr = th->trace;
-
- const size_t dst_row_size = nb1;
- const size_t src0_row_size = nb01;
- 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-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;
-
- const dma_addr_t src0_row = src0->data;
-
+ 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;
- if (src0_start_row >= src0_end_row) {
+ 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, hmx_transfer_output_glu_col_worker, state, n_hvx);
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);
- 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);
-
- 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) {
- 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);
- 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);
- }
-}
-
-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_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 src0_row_size = nb01;
- 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;
-
- // 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;
-
- float * tmp = (float *) vtcm_dst_ptr;
-
- const dma_addr_t src0_row = src0->data;
- const uint8_t * restrict act_col = (const uint8_t *) act_data;
-
- const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
-
- 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;
-
- // Prefill vtcm with 2x src0 rows
- if (src0_start_row < src0_end_row) {
- 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) {
- 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) {
- const uint32_t is0 = (ir0 - src0_start_row);
- if (is0 >= 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;
- }
-
- // 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;
- 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, hvx_flat_store_2x1_f32);
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0);
-
- // Prefetch next (n + vtcm_nrows) row
- const uint32_t pr0 = (ir0 + n_prefetch);
- const uint32_t 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),
- src0_stride, src0_row_size, src0_row_size, 2);
- }
- }
-
- // Process the last row (if any)
- if (src0_end_row != src0_end_row_x2) {
- const uint32_t ir0 = src0_end_row_x2;
- const uint32_t 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),
- 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, 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);
- 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);
- }
-}
-
-static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_matmul_preamble;
-
- 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 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);
- const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U);
-
- struct htp_thread_trace * tr = th->trace;
-
- const size_t dst_row_size = nb1;
- 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;
-
-
- if (src0_start_row >= src0_end_row || cur_m_rows == 0) {
- return;
- }
-
- const uint32_t total_batches = ne12 * ne13;
- const uint32_t b_start = fastdiv(cur_m_start, &kparams->div_ne1);
- uint32_t b_end = fastdiv(cur_m_start + cur_m_rows + ne11 - 1, &kparams->div_ne1);
- b_end = MIN(b_end, total_batches);
-
- uint32_t b_grp_start = b_start;
- while (b_grp_start < b_end) {
- const uint32_t b3 = fastdiv(b_grp_start, &kparams->div_ne12);
- const uint32_t b2 = b_grp_start - b3 * ne12;
- const uint32_t i02 = fastdiv(b2, &kparams->div_r2);
- const uint32_t i03 = fastdiv(b3, &kparams->div_r3);
-
- uint32_t b_grp_end = b_grp_start + 1;
- while (b_grp_end < b_end) {
- const uint32_t cur_b3 = fastdiv(b_grp_end, &kparams->div_ne12);
- const uint32_t cur_b2 = b_grp_end - cur_b3 * ne12;
- const uint32_t cur_i02 = fastdiv(cur_b2, &kparams->div_r2);
- const uint32_t cur_i03 = fastdiv(cur_b3, &kparams->div_r3);
- if (cur_i02 != i02 || cur_i03 != i03) {
- break;
- }
- b_grp_end++;
- }
-
- 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;
-
- 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++) {
- const uint32_t b_m_start = b * ne11;
- const uint32_t m_first = MAX(cur_m_start, b_m_start);
- const uint32_t m_last = MIN(cur_m_start + cur_m_rows, b_m_start + ne11);
- if (m_first >= m_last) continue;
-
- const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
- const uint32_t cur_b2 = b - cur_b3 * ne12;
- 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 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);
-
- 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) {
- 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);
- for (uint32_t b = b_grp_start; b < b_grp_end; b++) {
- const uint32_t b_m_start = b * ne11;
- const uint32_t m_first = MAX(cur_m_start, b_m_start);
- const uint32_t m_last = MIN(cur_m_start + cur_m_rows, b_m_start + ne11);
- if (m_first >= m_last) continue;
-
- const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12);
- const uint32_t cur_b2 = b - cur_b3 * ne12;
- 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 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);
- }
-
- b_grp_start = b_grp_end;
- }
-}
-
-#define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id) * mmctx->mapping_stride + (i1)]
-
-static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- htp_matmul_preamble;
-
- 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);
-
-
- if (src0_start_row >= src0_end_row) {
- return;
- }
-
- 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 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 uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
-
- const size_t act_stride = mmctx->vtcm_act_stride;
-
- // 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) {
- const int32_t cne1 = matrix_row_counts[cur_a];
- if (cne1 == 0) {
- continue;
- }
-
- const dma_addr_t src0_row = src0->data + (dma_addr_t) cur_a * nb02;
-
- 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 ct_start = src0_start_row / 32;
- const uint32_t ct_end = (src0_end_row + 31) / 32;
-
- 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 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 (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);
- }
- }
- }
-}
-
-static void hvx_mv_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_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);
-
-
- if (src0_start_row >= src0_end_row) {
- return;
- }
-
- 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);
-
- assert(ne13 % ne03 == 0);
-
- const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
-
- const uint32_t n_aids = ids->ne[0]; // num activated experts
- const uint32_t n_ids = ne02; // num experts
- (void) n_ids;
-
- // 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 = mmctx->ids_data[ie1];
- if (eid < 0) {
- continue;
- }
- assert(eid >= 0 && eid < (int32_t) n_ids);
-
- const dma_addr_t src0_row = src0->data + (dma_addr_t) eid * nb02;
- const uint8_t * restrict act_col = (const uint8_t *) act_data;
- const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * nb1;
-
- 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 + (dma_addr_t) 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)ne0 - (int)(ct * 32);
- valid_rows = MIN(32, MAX(0, valid_rows));
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- 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 + (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);
- }
-}
-
-static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_mm_context * mmctx = (struct htp_mm_context *) data;
- struct htp_ops_context * octx = mmctx->octx;
- const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- 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);
-
- 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 = mmctx->ids_data[ie1];
- if (eid < 0) continue;
- assert(eid < (int32_t) n_ids);
-
- 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;
- 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 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;
- }
-
- const uint32_t nrows = end_row - start_row;
- uint32_t src0_nrows_per_hvx = fastdiv(nrows + nth - 1, &octx->n_hvx_div);
- src0_nrows_per_hvx = hex_round_up(src0_nrows_per_hvx, 32);
-
- const uint32_t src0_start_row = start_row + src0_nrows_per_hvx * ith;
- 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 + (dma_addr_t) eid * src_w->nb[2];
- const uint8_t * restrict act_col = (const uint8_t *) act_data;
- const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * dst->nb[1];
-
- 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 + (dma_addr_t) 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));
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct);
- 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 + (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);
- }
- }
-}
-
-static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
- struct htp_mm_context * mmctx = (struct htp_mm_context *) data;
- struct htp_ops_context * octx = mmctx->octx;
- const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- 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];
-
-
- 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];
-
- const uint32_t * matrix_row_counts = mmctx->matrix_row_counts;
- const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows;
-
- 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) {
- const int32_t cne1 = matrix_row_counts[cur_a];
- if (cne1 == 0) 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;
- 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 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;
- }
-
- const uint32_t nrows = end_row - start_row;
- uint32_t src0_nrows_per_hvx = fastdiv(nrows + nth - 1, &octx->n_hvx_div);
- src0_nrows_per_hvx = hex_round_up(src0_nrows_per_hvx, 32);
-
- const uint32_t src0_start_row = start_row + src0_nrows_per_hvx * ith;
- 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 + (dma_addr_t) cur_a * src_w->nb[2];
-
- 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 ct_start = src0_start_row / 32;
- const uint32_t ct_end = (src0_end_row + 31) / 32;
-
- 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 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 (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);
- }
- }
- }
- }
-}
-
-static int hvx_mm_init_tiled_vec_dot(struct htp_mm_context * mmctx, enum htp_data_type type) {
- switch (type) {
- case HTP_TYPE_Q4_0:
- mmctx->type = "q4_0_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q4_0_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q4_0_32x2;
- return 0;
- case HTP_TYPE_Q4_1:
- case HTP_TYPE_Q4_K:
- mmctx->type = "q4_1_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q4_1_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q4_1_32x2;
- return 0;
- case HTP_TYPE_Q8_0:
- mmctx->type = "q8_0_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q8_0_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q8_0_32x2;
- return 0;
- case HTP_TYPE_Q5_0:
- mmctx->type = "q5_0_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q5_0_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q5_0_32x2;
- return 0;
- case HTP_TYPE_Q5_1:
- case HTP_TYPE_Q5_K:
- mmctx->type = "q5_k_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q5_k_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q5_k_32x2;
- return 0;
- case HTP_TYPE_Q6_K:
- mmctx->type = "q6_k_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q6_k_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q6_k_32x2;
- return 0;
- case HTP_TYPE_Q3_K:
- mmctx->type = "q3_k_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q3_k_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q3_k_32x2;
- return 0;
- case HTP_TYPE_Q2_K:
- mmctx->type = "q2_k_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q2_k_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q2_k_32x2;
- return 0;
- case HTP_TYPE_Q2_0:
- mmctx->type = "q2_0_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q2_0_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q2_0_32x2;
- return 0;
- case HTP_TYPE_IQ4_NL:
- mmctx->type = "iq4nl_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_iq4nl_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_iq4nl_32x2;
- return 0;
- case HTP_TYPE_IQ2_XXS:
- mmctx->type = "iq2xxs_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_iq2xxs_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_iq2xxs_32x2;
- return 0;
- case HTP_TYPE_MXFP4:
- mmctx->type = "mxfp4_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_mxfp4_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_mxfp4_32x2;
- return 0;
- case HTP_TYPE_NVFP4:
- mmctx->type = "nvfp4_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_nvfp4_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_nvfp4_32x2;
- return 0;
- case HTP_TYPE_Q1_0:
- mmctx->type = "q1_0_tiled-f32";
- mmctx->vec_dot_32x1 = tiled_vec_dot_q1_0_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_q1_0_32x2;
- return 0;
- case HTP_TYPE_F16:
- mmctx->type = "f16_tiled-f16";
- mmctx->vec_dot_32x1 = tiled_vec_dot_f16_32x1;
- mmctx->vec_dot_32x2 = tiled_vec_dot_f16_32x2;
- return 0;
- default:
- return -1;
- }
-}
-
-static int hvx_mm_matmul(struct htp_ops_context * octx) {
- htp_matmul_tensors_preamble;
-
- struct htp_thread_trace * tr = &octx->ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
-
- struct htp_mm_context mmctx_struct = {0};
- struct htp_mm_context * mmctx = &mmctx_struct;
- mmctx->octx = octx;
- mmctx->act = act;
-
- const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
-
- const uint32_t src0_nrows = ne01;
- const uint32_t act_nrows = ne11 * ne12 * ne13;
- mmctx->act_nrows = act_nrows;
-
- 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 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) {
- return HTP_STATUS_OK;
- }
-
- const uint32_t nrows = src0_row_end - src0_row_start;
- mmctx->src0_row_start = src0_row_start;
- mmctx->src0_row_end = src0_row_end;
-
- const bool is_tiled = htp_tensor_is_tiled(src0);
-
- // Compute src0_nrows_per_hvx
- mmctx->src0_nrows_per_hvx = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div);
- if (is_tiled) {
- mmctx->src0_nrows_per_hvx = hex_round_up(mmctx->src0_nrows_per_hvx, 32);
- } else {
- mmctx->src0_nrows_per_hvx += (mmctx->src0_nrows_per_hvx & 1); // round up to even
- }
-
- const size_t src0_row_size = nb01;
- 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_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_task_func = is_tiled ? hvx_mm_4d_tiled : hvx_mm_4d_flat;
- } else if (act_nrows > 1) {
- matmul_task_func = is_tiled ? hvx_mm_2d_tiled : hvx_mm_2d_flat;
- } else {
- 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) {
- case HTP_MM_KERNEL_HVX_F16_F16_VTCM:
- quant_task_func = (act->type == HTP_TYPE_F32) ? quantize_f32_f16 : quantize_f16_f16;
- need_quant = (act->type == HTP_TYPE_F32);
- mmctx->type = (act->type == HTP_TYPE_F32) ? "f32-f16" : "f16-f16";
- 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;
- break;
-
- case HTP_MM_KERNEL_HVX_F32_F32_VTCM:
- 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;
- break;
-
- case HTP_MM_KERNEL_HVX_BF16_F32_VTCM:
- 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;
- break;
-
- case HTP_MM_KERNEL_HVX_QUANT_BLOCK:
- case HTP_MM_KERNEL_HVX_QUANT_ROW:
- default: {
- if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) != 0) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- const uint32_t qk = HTP_MM_ACT_BLOCK_K;
- const uint32_t nb = (ne10 + qk - 1) / qk;
- const uint32_t total_nb = act_nrows * nb;
-
- if (act_nrows < octx->n_hvx && !is_batched) {
- n_quant_tasks = MIN(total_nb, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
- for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
- uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
- uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
- mmctx->quant_ib_first[ith] = ib_first;
- mmctx->quant_ib_last[ith] = ib_last;
- mmctx->quant_r[ith] = ib_first / nb;
- mmctx->quant_c[ith] = ib_first % nb;
- }
- } else {
- n_quant_tasks = MIN(act_nrows, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
- }
- break;
- }
- }
-
- const uint32_t m_chunk = (kparams->m_chunk > 0 && (uint32_t) kparams->m_chunk < act_nrows)
- ? (uint32_t) kparams->m_chunk : act_nrows;
- const uint32_t m_layout_rows = m_chunk;
-
- 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_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 ||
- kparams->kernel_type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM ||
- kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW ||
- kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) {
- mmctx->vtcm_act_size_per_hvx = L.act_bytes;
- } else {
- mmctx->vtcm_act_size_per_hvx = fastdiv(L.act_bytes, &octx->n_hvx_div);
- }
-
- mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div);
- mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
-
- const size_t vtcm_size = L.total_bytes;
-
- FARF(HIGH, "matmul-%s : src0-vtcm-size %zu act-vtcm-size %zu dst-vtcm-size %zu (%zu)\n", mmctx->type,
- L.src0_bytes, L.act_bytes, L.dst_bytes, vtcm_size);
-
- FARF(HIGH, "matmul-%s : %ux%ux%ux%u * %ux%ux%ux%u-> %ux%ux%ux%u (0x%p, 0x%p, 0x%p)\n", mmctx->type, src0->ne[0],
- src0->ne[1], src0->ne[2], src0->ne[3], act->ne[0], act->ne[1], act->ne[2], act->ne[3], dst->ne[0],
- dst->ne[1], dst->ne[2], dst->ne[3], src0->data, act->data, dst->data);
-
- if (octx->ctx->vtcm_size < vtcm_size) {
- FARF(ERROR, "matmul-%s : current VTCM reservation %zu is too small, needed %zu\n", mmctx->type,
- octx->ctx->vtcm_size, vtcm_size);
- return HTP_STATUS_VTCM_TOO_SMALL;
- }
-
- uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
- mmctx->vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
- mmctx->vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0);
- mmctx->vtcm_bias = VTCM_LAYOUT_PTR(uint8_t, base, L.off_bias);
- 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);
- hvx_mm_iq2xxs_lut_init(base, &L);
-
- 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, 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;
- }
-
- htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
-
- if (kparams->m_chunk > 0 && (uint32_t) kparams->m_chunk < act_nrows) {
- for (uint32_t m_start = 0; m_start < act_nrows; m_start += m_chunk) {
- const uint32_t cur_m_rows = MIN(act_nrows - m_start, m_chunk);
- mmctx->cur_m_start = m_start;
- mmctx->cur_m_rows = cur_m_rows;
-
- if (need_quant) {
- hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act_raw, mmctx->vtcm_act_raw_stride, m_start, cur_m_rows);
-
- const uint32_t qk = HTP_MM_ACT_BLOCK_K;
- const uint32_t nb = (ne10 + qk - 1) / qk;
- const uint32_t total_nb = cur_m_rows * nb;
- uint32_t quant_tasks;
- work_queue_func_t q_func;
- if (cur_m_rows < octx->n_hvx && (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW)) {
- quant_tasks = MIN(total_nb, octx->n_hvx);
- q_func = htp_mm_act_quant_block_func(src0->type, act->type);
- for (uint32_t ith = 0; ith < quant_tasks; ++ith) {
- uint32_t ib_first = (total_nb * ith) / quant_tasks;
- uint32_t ib_last = (total_nb * (ith + 1)) / quant_tasks;
- mmctx->quant_ib_first[ith] = ib_first;
- mmctx->quant_ib_last[ith] = ib_last;
- mmctx->quant_r[ith] = ib_first / nb;
- mmctx->quant_c[ith] = ib_first % nb;
- }
- } else {
- quant_tasks = MIN(cur_m_rows, octx->n_hvx);
- q_func = quant_task_func;
- mmctx->n_quant_rows_per_hvx = (cur_m_rows + quant_tasks - 1) / quant_tasks;
- }
- mmctx->n_quant_tasks = quant_tasks;
- work_queue_run(octx->ctx->hvx_queue, q_func, mmctx, quant_tasks);
- } else {
- 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_task_func, mmctx, octx->n_hvx);
- }
- } else {
- mmctx->cur_m_start = 0;
- mmctx->cur_m_rows = act_nrows;
-
- if (need_quant) {
- 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, matmul_task_func, mmctx, octx->n_hvx);
- }
-
- return HTP_STATUS_OK;
-}
-
-static void dequantize_tiled_worker_loop(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
- tiled_dequantize_state_t * state = (tiled_dequantize_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 < (unsigned int) state->n_tasks; task_id += n) {
- 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);
-}
-
-static void transfer_output_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- output_transfer_task_state_t *st = (output_transfer_task_state_t *) data;
-
- struct htp_thread_trace * tr = th->trace;
-
- int start_chunk_idx = i * st->n_chunks_per_task;
- 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) {
- 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);
-
- 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);
-}
-
-typedef struct {
- __fp16 * dst;
- dma_addr_t act_dma_addr;
- float * vtcm_f32_act;
- uint32_t n_tasks;
- uint32_t n_tot_chunks;
- uint32_t n_chunks_per_task;
- uint32_t k_block;
- uint32_t k_stride;
- uint32_t k_valid;
- size_t vtcm_f32_act_bytes_per_hvx;
- uint32_t dma_step_rows;
- uint32_t dma_step_rows_shift;
- uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
-} activation_transfer_task_state_t;
-
-typedef struct {
- __fp16 * dst;
- dma_addr_t act_dma_addr;
- float * vtcm_f32_act;
- uint32_t n_rows;
- uint32_t k_block;
- uint32_t k_stride;
- uint32_t k_valid;
- uint32_t n_col_chunks;
- struct fastdiv_values n_hvx_div;
- 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_to_fp16_dma_pipelined_col_chunk(
- dma_queue *dma_q,
- __fp16 *restrict vtcm_dst,
- dma_addr_t act_dma_addr,
- uint32_t n_rows,
- uint32_t k_block,
- uint32_t k_stride,
- uint32_t k_chunk_valid,
- uint32_t c_first,
- uint32_t c_len,
- 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) {
-
- const uint32_t R = dma_step_rows;
- const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS);
-
- 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(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);
- 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;
- uint8_t *curr_buf = act_spad;
-
- if (r < n_rows) {
- curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst;
- }
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
- 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);
-
- // Push step s + 2
- uint32_t next_s = s + 2;
- 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 * src_row_bytes + src_col_offset),
- row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
- }
- }
-}
-
-static void transfer_activation_chunk_col_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- activation_transfer_col_chunk_state_t *st = (activation_transfer_col_chunk_state_t *) data;
- struct htp_thread_trace * tr = th->trace;
-
- uint32_t n_blocks = st->k_block / 32;
- 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;
-
- if (c_len == 0) {
- return;
- }
-
- uint32_t k_chunk_valid = 0;
- if (st->k_valid > c_first) {
- k_chunk_valid = hex_smin(st->k_valid, c_last) - c_first;
- }
-
- __fp16 *dst = st->dst;
-
- 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_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, act_spad, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift
- );
-}
-
-static void transfer_activation_chunk_to_fp16_dma_pipelined(
- dma_queue *dma_q,
- __fp16 *restrict vtcm_dst,
- dma_addr_t act_dma_addr,
- uint32_t n_rows,
- uint32_t k_block,
- uint32_t k_stride,
- uint32_t k_valid,
- 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) {
-
- const uint32_t R = dma_step_rows;
- const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS);
-
- 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) k_block * act_elem_size; // staging row (DMA dst stride)
- const size_t src_row_bytes = (size_t) k_stride * act_elem_size; // DDR row (DMA src stride)
- const size_t width_bytes = (size_t) k_valid * 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(act_spad, act_dma_addr),
- row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
- }
- // Push step 1 (if valid)
- 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);
- 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 = act_spad;
-
- if (r < n_rows) {
- curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst;
- }
-
- htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
- // Two copies of the pair loop so the type is resolved once per step and the
- // row-pair kernels stay direct (inlinable) calls.
- 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(vtcm_dst, pair_buf, pair_buf + k_block, row_idx, k_block, k_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(vtcm_dst, pair_buf, pair_buf + k_block, row_idx, k_block, k_valid, r0_valid, r1_valid);
- }
- }
- htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, r);
-
- // Push step s + 2
- uint32_t next_s = s + 2;
- 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 * src_row_bytes),
- row_bytes, src_row_bytes, width_bytes, nrows_to_fetch);
- }
- }
-}
-
-static void transfer_activation_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- activation_transfer_task_state_t *st = (activation_transfer_task_state_t *) data;
-
- struct htp_thread_trace * tr = th->trace;
-
- 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);
-
- __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 *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, 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;
- 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;
- uint32_t mapping_stride;
- uint32_t ne11;
- struct fastdiv_values ne11_div;
- size_t nb11;
- size_t nb12;
- uint32_t start_row;
- uint32_t k_valid;
-} activation_transfer_gathered_task_state_t;
-
-static void transfer_activation_chunk_gathered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) {
- (void) n;
- activation_transfer_gathered_task_state_t * st = (activation_transfer_gathered_task_state_t *) data;
- struct htp_thread_trace * tr = th->trace;
- dma_queue * dma_q = th->dma_q;
-
- const uint32_t vtcm_start_row = i * st->n_chunks_per_task;
- if (vtcm_start_row >= st->mc_pad) {
- return;
- }
- 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);
- }
- }
-
- 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;
-
- 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;
- case HTP_TYPE_Q5_1:
- case HTP_TYPE_Q5_K: return dequantize_tiled_weight_to_fp16_task_q5_k;
- case HTP_TYPE_Q6_K: return dequantize_tiled_weight_to_fp16_task_q6_k;
- case HTP_TYPE_Q3_K: return dequantize_tiled_weight_to_fp16_task_q3_k;
- case HTP_TYPE_Q2_K: return dequantize_tiled_weight_to_fp16_task_q2_k;
- case HTP_TYPE_Q1_0: return dequantize_tiled_weight_to_fp16_task_q1_0;
- case HTP_TYPE_Q2_0: return dequantize_tiled_weight_to_fp16_task_q2_0;
- case HTP_TYPE_F16: return is_tiled ? NULL : convert_f16_weight_to_fp16_tiles_task;
- case HTP_TYPE_BF16: return convert_bf16_weight_to_fp16_tiles_task;
- case HTP_TYPE_F32: return quantize_f32_weight_to_fp16_tiles_task;
- default: return NULL;
- }
-}
-
-static void dequantize_tiled_weight_chunk_to_fp16_tiles(
- 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) {
-
- if (!dequant_worker_fn) {
- return;
- }
-
- assert(k_block % HTP_MM_HMX_TILE_N_COLS == 0);
-
- 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;
- if (n_tot_tiles == 0) {
- return;
- }
-
- 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 = 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;
- state.src = (const uint8_t *)weight_src_ddr;
- state.task_fn = dequant_worker_fn;
- state.n_cols = n_cols;
- state.k_block = k_block;
- state.row_stride = row_stride;
- state.weight_type = weight_type;
- state.n_k_tiles = n_k_tiles;
- state.n_weight_tiles = n_weight_tiles;
- state.n_k_tiles_div = n_k_tiles_div;
-
- 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;
-
- work_queue_run(octx->ctx->hvx_queue, dequantize_tiled_worker_loop, &state, (int) state.n_tasks);
-}
-
-typedef struct {
- 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) {
- (void) n;
- output_transfer_col_chunk_state_t *st = (output_transfer_col_chunk_state_t *) data;
- struct htp_thread_trace * tr = th->trace;
-
- // 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;
- 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 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) {
- 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_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;
- }
-
- 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;
- }
- }
-
- 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.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.bias = bias;
- state.vtcm_src = vtcm_src;
- 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 {
- struct htp_context * ctx;
- __fp16 * dst;
- dma_addr_t act_dma_addr;
- int n_rows;
- int k_block;
- int k_stride;
- int n_hvx;
- const struct fastdiv_values * act_hvx_div;
- const struct fastdiv_values * k_div;
- int k_valid;
- float * vtcm_f32_act;
- size_t vtcm_f32_act_bytes;
- uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1
-};
-
-static void transfer_activation_chunk_threaded(const struct activation_transfer_params * params) {
- struct htp_context * ctx = params->ctx;
- __fp16 * dst = params->dst;
- const dma_addr_t act_dma_addr = params->act_dma_addr;
- int n_rows = params->n_rows;
- int k_block = params->k_block;
- int k_stride = params->k_stride;
- int n_hvx = params->n_hvx;
- const struct fastdiv_values * act_hvx_div = params->act_hvx_div;
- const struct fastdiv_values * k_div = params->k_div;
- int k_valid = params->k_valid;
- float * vtcm_f32_act = params->vtcm_f32_act;
- size_t vtcm_f32_act_bytes = params->vtcm_f32_act_bytes;
- // element size of the activation rows (4 = F32, 2 = F16).
- const uint32_t act_elem_size = params->act_elem_size ? params->act_elem_size : (uint32_t) sizeof(float);
-
- if (n_rows <= 0) {
- return;
- }
-
- const size_t n_tasks = (n_rows + 31) >> 5;
- 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 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;
- }
- }
-
- activation_transfer_col_chunk_state_t col_state;
- col_state.dst = dst;
- col_state.act_dma_addr = act_dma_addr;
- col_state.n_rows = n_rows;
- col_state.k_block = k_block;
- col_state.k_stride = k_stride;
- col_state.k_valid = k_valid;
- col_state.n_col_chunks = n_hvx;
- col_state.n_hvx_div = *act_hvx_div;
- col_state.vtcm_f32_act = vtcm_f32_act;
- 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;
- }
-
- assert(k_block % HTP_MM_HMX_TILE_N_COLS == 0 && k_stride % HTP_MM_HMX_TILE_N_COLS == 0);
-
- size_t n_tot_chunks = n_rows;
- size_t n_chunks_per_task = (n_hvx == 1) ? n_tot_chunks : 32; // must be multiple of 32 to ensure correct destination address
-
- activation_transfer_task_state_t state;
- state.n_tasks = (n_hvx == 1) ? 1 : hmx_ceil_div(n_tot_chunks, 32);
- state.n_tot_chunks = n_tot_chunks;
- state.n_chunks_per_task = n_chunks_per_task;
- state.dst = dst;
- state.act_dma_addr = act_dma_addr;
- state.k_block = k_block;
- state.k_stride = k_stride;
- state.k_valid = k_valid;
- state.vtcm_f32_act = vtcm_f32_act;
- state.act_elem_size = act_elem_size;
-
- state.vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128);
-
- uint32_t dma_step_rows = 2;
- uint32_t dma_step_rows_shift = 1;
- if (state.vtcm_f32_act_bytes_per_hvx > 0) {
- 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;
- }
- }
- state.dma_step_rows = dma_step_rows;
- state.dma_step_rows_shift = dma_step_rows_shift;
-
- 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);
-}
-
-// --- 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;
- 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 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,
- const __fp16 * scales,
- uint32_t n_row_tiles,
- uint32_t n_col_tiles,
- uint32_t 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_ops_context *octx,
- dma_queue *weight_dma,
- 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,
- int act_stride,
- uint32_t act_elem_size, // 4=F32 src1, 2=F16 src1
- int weight_stride,
- int weight_type,
- int k_valid,
- int dst_stride,
- uint32_t bias_stride,
- int dst_cols,
- uint32_t dst_elem_size,
- uint32_t bias_elem_size,
- 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 tile_size,
- int aligned_tile_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_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type);
- const int n_groups = is_int_hmx ? hmx_n_groups : 1;
-
- if ((k & 31) != 0) {
- 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) {
- return -1;
- }
-
- tiled_dequant_task_fn_t dequant_worker_fn = hmx_get_dequant_worker_fn(weight_type, is_tiled);
-
- 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 vtcm_budget = ctx->vtcm_size;
-
- const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride;
- const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
- const uint32_t dma_width_bytes = is_tiled ? tile_size : row_stride;
-
- size_t m_chunk_n_rows = m_chunk;
- 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_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) {
- FARF(ERROR, "hmx-mm-2d-precomputed: VTCM overflow: used %zu budget %zu, m %d k %d n %d mc %zu nc %zu",
- vtcm_used, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols);
- return -1;
- }
-
- uint8_t * const base = (uint8_t *) ctx->vtcm_base;
- __fp16 *vtcm_weight_raw[2] = {
- VTCM_LAYOUT_PTR(__fp16, base, L.off_weight[0]),
- VTCM_LAYOUT_PTR_OPTIONAL(__fp16, 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);
- 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);
- 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);
-
- 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);
- }
-
- 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, bias_addr), hex_align_up(bias_bytes, 128), 0, bias_bytes, 1);
- dma_queue_pop(weight_dma);
- }
-
- 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 (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],
- dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch0,
- dequant_worker_fn ? vtcm_weight_raw[1] : vtcm_scratch1,
- };
- void *vtcm_weight_bufs[4] = {
- dequant_worker_fn ? vtcm_scratch0 : vtcm_weight_raw[0],
- dequant_worker_fn ? vtcm_scratch1 : vtcm_weight_raw[1],
- vtcm_scratch0,
- vtcm_scratch1,
- };
- void *vtcm_output_bufs[2] = { vtcm_output, vtcm_scratch2 };
-
- 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;
-
- 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_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((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);
- }
-
- 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);
-
- // 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);
- }
-
- 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 * 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) 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 };
-
- 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);
-
- 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);
- }
-
- 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((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 (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 / 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 < (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)
- 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 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) {
- 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);
- }
- }
- }
-
- 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];
- htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
-
- const uint32_t n_weights = kparams->n_weights;
- if (n_weights == 0 || n_weights > HTP_OP_MAX_OUTPUTS) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
- const struct htp_tensor * restrict src0 = octx->src[0];
- const struct htp_tensor * restrict act = octx->src[n_weights];
-
- const int weight_type = (int) src0->type;
- const int k = (int) act->ne[0];
- const int k_valid = (int) act->ne[0];
- 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 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 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 >> 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;
-
- const bool is_tiled = (tile_size > 0);
- 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;
-
- 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_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",
- L.total_bytes, vtcm_budget, m, k, m_chunk_n_rows, n_chunk_n_cols);
- return HTP_STATUS_VTCM_TOO_SMALL;
- }
-
- uint8_t * const base = (uint8_t *) ctx->vtcm_base;
- __fp16 *vtcm_weight_raw[2] = {
- VTCM_LAYOUT_PTR(__fp16, base, L.off_weight[0]),
- VTCM_LAYOUT_PTR_OPTIONAL(__fp16, 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);
- 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);
- 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);
-
- 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);
- }
-
- 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-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_task_t task_slots[2];
- void *vtcm_raw_bufs[4] = {
- vtcm_weight_raw[0],
- vtcm_weight_raw[1],
- dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch0,
- dequant_worker_fn ? vtcm_weight_raw[1] : vtcm_scratch1,
- };
- void *vtcm_weight_bufs[4] = {
- dequant_worker_fn ? vtcm_scratch0 : vtcm_weight_raw[0],
- dequant_worker_fn ? vtcm_scratch1 : vtcm_weight_raw[1],
- vtcm_scratch0,
- vtcm_scratch1,
- };
- 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);
-
- 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];
- const struct htp_tensor * restrict dst = octx->dsts[p];
- if (!src_w || !dst) continue;
-
- const dma_addr_t weight = src_w->data;
- 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_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);
-
- 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 - (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 + (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 = (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 (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);
- }
-
- 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);
-
- 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]));
-
- const int chunk_dst_cols = dst_cols - (int) nc_prev;
- if (chunk_dst_cols > 0) {
- 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);
- }
- }
- }
-
- {
- 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_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);
-
- 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];
- const struct htp_tensor * restrict dst = octx->dsts[p];
- if (!src_w || !dst) continue;
-
- const dma_addr_t weight = src_w->data;
- 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_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, (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, (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);
- }
-
- 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 + (size_t) n_chunk_n_cols;
- if (nc_next < n) {
- 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);
- }
-
- 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);
-
- int chunk_dst_cols = dst_cols - (int) nc;
- if (chunk_dst_cols > 0) {
- 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);
- }
- }
- }
- }
-
- return HTP_STATUS_OK;
-}
-
-static inline dma_addr_t hmx_mm_weight_batch_data(const hmx_mm_batched_params_t *params,
- int dst_b2, int dst_b3) {
- const size_t b2_idx = (params->r2 <= 1) ? (size_t) dst_b2 : (size_t) fastdiv((uint32_t) dst_b2, ¶ms->div_r2);
- const size_t b3_idx = (params->r3 <= 1) ? (size_t) dst_b3 : (size_t) fastdiv((uint32_t) dst_b3, ¶ms->div_r3);
- return params->weight + b2_idx * params->src0_nb2 + b3_idx * params->src0_nb3;
-}
-
-static inline dma_addr_t hmx_mm_act_batch_addr(const hmx_mm_batched_params_t *params,
- int dst_b2, int dst_b3) {
- return params->act_dma_addr + dst_b2 * params->act_nb2 +
- dst_b3 * params->act_nb3;
-}
-
-static inline dma_addr_t hmx_mm_dst_batch_addr(const hmx_mm_batched_params_t *params,
- int dst_b2, int dst_b3) {
- return params->dst_dma_addr +
- (size_t) dst_b2 * params->dst_nb2 +
- (size_t) dst_b3 * params->dst_nb3;
-}
-
-static 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 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) {
- for (int b2 = 0; b2 < params->ne12 && ret == 0; ++b2) {
- 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(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,
- 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_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; }
- if (params->ne02 <= 0 || params->ne03 <= 0 || params->ne12 <= 0 || params->ne13 <= 0) { return -1; }
- 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 ((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;
-
- // 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 &&
- params->bias_nb2 == 0 && params->bias_nb3 == 0 && (size_t)vtcm_size <= vtcm_budget);
- if (!run_grouped) {
- 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];
- htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+ }
- size_t m_chunk_n_rows = m_chunk;
- size_t n_chunk_n_cols = n_chunk;
+ const int actual_hvx = hex_smin(n_hvx, (n_rows + 3) >> 2);
+ work_queue_run(octx->ctx->hvx_queue, hmx_transfer_output_glu_row_worker, state, actual_hvx);
+}
- struct htp_mm_hmx_vtcm_layout L;
- 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);
+// --- Context Init & MMID Expert Mapping ---
- 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(octx, params, m_chunk, n_chunk, pipeline, act_hvx, vtcm_size, act_hvx_div, k_div);
+static int htp_mm_init_context(
+ struct htp_ops_context * octx,
+ const struct htp_mm_kernel_params * kparams) {
+ if (!htp_ops_context_set_n_hvx(octx, (uint32_t) kparams->n_hvx)) {
+ return HTP_STATUS_INVAL_PARAMS;
}
- 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);
- __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);
- 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);
+ if (kparams->n_hmx) {
+ if (kparams->n_act_hvx <= 0 || kparams->n_act_hvx > (int32_t) octx->n_hvx) {
+ return HTP_STATUS_INVAL_PARAMS;
+ }
}
- hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16
-
- FARF(HIGH, "%s: grouped path m=%d k=%d n=%d group=%d streams=%d mc=%zu nc=%zu vtcm=%zu/%zu",
- __func__, params->m, params->k, params->n, group_size, params->ne13,
- m_chunk_n_rows, n_chunk_n_cols,
- L.total_bytes, vtcm_budget);
-
- const size_t fp16_row_bytes = (size_t) params->k * sizeof(__fp16);
- const size_t weight_row_bytes = (size_t) params->weight_stride;
-
- htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
-
- 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) {
- const dma_addr_t weight_group = hmx_mm_weight_batch_data(params, b2_base, b3);
- dma_queue * weight_dma = params->weight_dma;
-
- for (size_t mr = 0; mr < (size_t) params->m; mr += m_chunk_n_rows) {
- const size_t n_rows = hex_smin((size_t) params->m - mr, m_chunk_n_rows);
- const size_t n_row_tiles = hmx_ceil_div((int) n_rows, HTP_MM_HMX_TILE_N_ROWS);
-
- // Pre-load activations for all heads in the group (once per m_chunk).
- // When the source is strided (permuted Q), use 2D DMA to gather
- // contiguous rows into a VTCM scratch buffer first, then HVX
- // converts from the contiguous VTCM buffer. This avoids L2 cache
- // thrashing from HVX loads at large strides.
- for (int g = 0; g < group_size; ++g) {
- const dma_addr_t act_dma_addr = hmx_mm_act_batch_addr(params, b2_base + g, b3) +
- (size_t) mr * params->act_stride * params->act_elem_size;
- __fp16 *vtcm_act_g = vtcm_f16_act + (size_t) g * L.act_head_stride;
- struct activation_transfer_params act_params = {
- .ctx = ctx,
- .dst = vtcm_act_g,
- .act_dma_addr = act_dma_addr,
- .n_rows = (int) n_rows,
- .k_block = params->k,
- .k_stride = params->act_stride,
- .n_hvx = act_hvx,
- .act_hvx_div = act_hvx_div,
- .k_div = k_div,
- .k_valid = params->k,
- .vtcm_f32_act = vtcm_f32_act,
- .vtcm_f32_act_bytes = L.act_f32_bytes,
- .act_elem_size = params->act_elem_size,
- };
- transfer_activation_chunk_threaded(&act_params);
- }
-
- 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);
- }
+ return HTP_STATUS_OK;
+}
- 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);
+static __attribute__((noinline)) uint32_t scan_expert_ids_n(
+ 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) {
+ uint32_t n_skipped = 0;
- void * curr_raw = (void *) dma_queue_pop(weight_dma).dst;
- if (nc > 0) {
- dma_queue_pop(weight_dma);
- }
+ 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) {
+ n_skipped++;
+ continue;
+ }
+ assert(i02 >= 0 && i02 < (int32_t) n_as);
- 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);
-
- // 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);
- 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);
- }
-
- 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);
-
- 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);
- }
+ if (matrix_rows) {
+ matrix_rows[i02 * mapping_stride + counts[i02]] = (struct mmid_row_mapping) { id, iid1 };
}
+ counts[i02] += 1;
}
}
-
- return 0;
+ return n_skipped;
}
-static void transfer_activation_chunk_gathered_threaded(
- struct htp_ops_context *octx,
- __fp16 *dst,
- dma_addr_t act_dma_addr,
- size_t act_elem_size,
- int start_row,
- int n_rows,
- int k_block,
- const struct mmid_row_mapping *matrix_rows,
- int cur_a,
- int mapping_stride,
- int ne11,
- size_t nb11,
- size_t nb12,
- int k_valid,
- 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;
+static __attribute__((noinline)) uint32_t scan_expert_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) {
+ 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);
}
- 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);
-
- const int actual_hvx = (int) hmx_ceil_div(mc_pad, chunks_per_hvx);
-
- activation_transfer_gathered_task_state_t state = {
- .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_run(octx->ctx->hvx_queue, transfer_activation_chunk_gathered_worker_fn, &state, actual_hvx);
}
-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;
+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) {
+ if (ids_data[id] < 0) {
+ n_skipped++;
+ }
}
+ return n_skipped;
+}
- 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;
- }
+// 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 int32_t * ids_data,
+ uint32_t ids_ne1,
+ uint32_t n_ids,
+ const struct htp_tensor * dst) {
+ const uint32_t elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ uint32_t col_start = 0;
+ uint32_t col_count = dst->ne[0];
- 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;
+ if (octx->ctx->mdev.count > 1) {
+ const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
+ 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;
}
- 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);
+ if (col_count == 0) {
+ return;
}
- 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);
-
- 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);
- }
- }
+ const size_t dst_nb1 = dst->nb[1];
+ const size_t dst_nb2 = dst->nb[2];
+ const size_t col_offset_bytes = (size_t) col_start * elem_size;
+ const size_t row_bytes = (size_t) col_count * elem_size;
- 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);
- }
+ // 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));
- 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);
+ 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) {
+ 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 (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_ops_context *octx,
- dma_queue *weight_dma,
- 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,
- 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) {
- 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 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 ((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) {
- return -1;
+ if (pending > 0) {
+ dma_queue_flush(dma_q);
}
+}
- const int n_k_tiles = k / HTP_MM_HMX_TILE_N_COLS;
- 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 vtcm_budget = ctx->vtcm_size;
- size_t vtcm_used = 0;
-
- const bool is_tiled = (tile_size > 0);
- tiled_dequant_task_fn_t dequant_worker_fn = hmx_get_dequant_worker_fn(weight_type, is_tiled);
-
- const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride;
- const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride;
- const uint32_t dma_width_bytes = is_tiled ? tile_size : row_stride;
-
- size_t m_chunk_n_rows = 0, n_chunk_n_cols = 0;
- 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;
- }
+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,
+ struct htp_mmid_mapping * map,
+ void ** out_ids_alloc,
+ void ** out_map_alloc) {
+ 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;
- 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;
+ 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;
}
- 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 (L.lut_bytes > 0) {
- iq2xxs_lut_copy(vtcm_lut);
+ if (htp_tensor_read(&octx->ctx->main_th, ids_buf, ids_bytes, ids) == 0) {
+ free(ids_alloc);
+ return HTP_STATUS_INTERNAL_ERR;
}
- htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
-
- 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) 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(
- 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);
-
- 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;
- dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight),
- dma_dst_stride, dma_src_stride, dma_width_bytes, height);
- }
+ const int32_t * ids_data = (const int32_t *) ids_buf;
- 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 * map_alloc = NULL;
+ uint8_t * mapping_buf = spad_base;
+ uint32_t mapping_stride = 1;
+ uint32_t * matrix_row_counts = NULL;
+ struct mmid_row_mapping * matrix_rows = NULL;
+ uint32_t n_skipped = 0;
- 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);
- }
+ if (act_nrows > 1) {
+ const size_t matrix_row_counts_size = n_as * sizeof(uint32_t);
+ 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;
- 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;
- 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);
- }
+ hvx_splat_u(matrix_row_counts, Q6_V_vzero(), n_as, sizeof(uint32_t));
+ n_skipped = scan_expert_ids(ids_data, ids->ne[1], n_ids, n_as, matrix_row_counts, NULL, 0);
- 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);
+ uint32_t max_count = hvx_reduce_max_i32((const uint8_t *) matrix_row_counts, n_as);
+ mapping_stride = max_count > 0 ? max_count : 1;
- 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));
+ 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 (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);
+ 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_data, ids->ne[1], n_ids, n_as, matrix_row_counts, matrix_rows, mapping_stride);
+ } else {
+ n_skipped = count_skipped_ids_single(ids_data, n_ids);
}
- return 0;
+ map->ids_data = ids_data;
+ map->matrix_row_counts = matrix_row_counts;
+ map->matrix_rows = matrix_rows;
+ map->mapping_stride = mapping_stride;
+ map->n_skipped = n_skipped;
+ *out_ids_alloc = ids_alloc;
+ *out_map_alloc = map_alloc;
+
+ return HTP_STATUS_OK;
}
-// --- Dispatchers and Public Entry Points ---
+// --- Top-Level Op Dispatchers ---
static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) {
htp_matmul_tensors_preamble;
- int k = (int) src0->ne[0];
- int n = (int) src0->ne[1];
- const int m_total = (int) act->ne[1];
+ const int k = (int) src0->ne[0];
+ const 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 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);
+ 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) {
- 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);
+ 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;
}
@@ -5979,24 +793,37 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
return HTP_STATUS_OK;
}
- 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;
+ 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;
+ 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];
+ 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 struct htp_tensor * scale = ((kparams->scale_mask & 1) != 0)
+ ? ((octx->op == HTP_OP_MUL_MAT_ADD) ? octx->src[3] : octx->src[2])
+ : NULL;
+ dma_addr_t scale_addr = 0;
+ size_t scale_bytes = 0;
+ bool scale_per_channel = false;
+ if (scale) {
+ const uint32_t smode = htp_mm_scale_mode_get(kparams->scale_mode, 0);
+ scale_per_channel = htp_mm_scale_is_per_channel(smode);
+ scale_addr = scale->data;
+ scale_bytes = scale_per_channel ? ((size_t) n * sizeof(float)) : sizeof(float);
}
- 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;
+ 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;
+ const dma_addr_t act_addr = act->data + (size_t) m_start * act_stride * act_elem_size;
+ const bool is_w8a8 = htp_mm_kernel_is_hmx_w8a8(kparams->kernel_type);
int ret = -1;
if (htp_mm_kernel_is_hmx_batched(kparams->kernel_type)) {
@@ -6004,6 +831,9 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
.dst_dma_addr = dst_addr,
.bias_addr = bias_addr,
.bias_bytes = bias_bytes,
+ .scale_addr = scale_addr,
+ .scale_bytes = scale_bytes,
+ .scale_per_channel = scale_per_channel ? 1 : 0,
.act_dma_addr = act_addr,
.weight = src0->data,
.weight_dma = octx->ctx->dma[0],
@@ -6019,8 +849,6 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
.dst_stride = dst_stride,
.dst_cols = (int) dst->ne[0],
.bias_stride = bias_stride,
- .tile_size = kparams->tile_size,
- .aligned_tile_size = kparams->aligned_tile_size,
.ne02 = ne02,
.ne03 = ne03,
.ne12 = ne12,
@@ -6037,32 +865,36 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
.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, &batch_params,
- kparams->m_chunk, kparams->n_chunk,
- kparams->pipeline,
- kparams->n_act_hvx,
- &kparams->div_n_act_hvx,
- &kparams->div_ne00_padded,
- kparams->vtcm_size);
+ ret = is_w8a8 ? hmx_w8a8_mm_batched(octx, kparams, &batch_params)
+ : hmx_f16_mm_batched(octx, kparams, &batch_params);
} else {
- ret = hmx_mm_2d_f32(
- 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, 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->kernel_type, kparams->hmx_n_groups,
- &kparams->div_hmx_n_groups, &kparams->div_n_k_tiles
- );
+ const hmx_mm_2d_params_t p = {
+ .weight_dma = octx->ctx->dma[0],
+ .dst_dma_addr = dst_addr,
+ .bias_addr = bias_addr,
+ .bias_bytes = bias_bytes,
+ .scale_addr = scale_addr,
+ .scale_bytes = scale_bytes,
+ .scale_per_channel = scale_per_channel,
+ .act_dma_addr = act_addr,
+ .weight = src0->data,
+ .m = m_rows,
+ .k = k,
+ .n = n,
+ .act_stride = act_stride,
+ .act_elem_size = act_elem_size,
+ .weight_stride = (int) src0->nb[1],
+ .weight_type = (int) src0->type,
+ .k_valid = (int) act->ne[0],
+ .dst_stride = dst_stride,
+ .bias_stride = bias_stride,
+ .dst_cols = (int) dst->ne[0],
+ .dst_elem_size = dst_elem_size,
+ .bias_elem_size = bias_elem_size,
+ };
+ ret = is_w8a8 ? hmx_w8a8_mm_2d(octx, kparams, &p)
+ : hmx_f16_mm_2d(octx, kparams, &p);
}
if (ret != 0) {
@@ -6072,7 +904,7 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k
return HTP_STATUS_OK;
}
-static int op_matmul_impl(struct htp_ops_context * octx) {
+int op_matmul(struct htp_ops_context * octx) {
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
const int status = htp_mm_init_context(octx, kparams);
@@ -6087,35 +919,62 @@ static int op_matmul_impl(struct htp_ops_context * octx) {
return hvx_mm_matmul(octx);
}
-int op_matmul(struct htp_ops_context * octx) {
- return op_matmul_impl(octx);
-}
-
-static int hmx_mm_op_matmul_id(
- struct htp_ops_context * octx,
- struct htp_mm_context * mmctx
-) {
- const uint32_t * matrix_row_counts = mmctx->matrix_row_counts;
- const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows;
+static int hmx_mm_op_matmul_id(struct htp_ops_context * octx, const struct htp_mmid_mapping * map) {
htp_matmul_tensors_preamble;
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- const int n_as = ne02;
+ const int n_as = ne02;
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;
+ uint32_t n_active = 0;
if (mdev_split) {
for (uint32_t a = 0; a < (uint32_t) n_as; ++a) {
- if (matrix_row_counts[a] > 0) n_active++;
+ if (map->matrix_row_counts[a] > 0) n_active++;
}
}
const bool expert_split = mdev_split && (n_active >= octx->ctx->mdev.count);
+ const struct htp_tensor * scale = ((kparams->scale_mask & 1) != 0) ? octx->src[3] : NULL;
+ const uint32_t smode = scale ? htp_mm_scale_mode_get(kparams->scale_mode, 0) : 0;
+ const bool scale_per_ch = scale && htp_mm_scale_is_per_channel(smode);
+ const size_t scale_bytes = scale ? (scale_per_ch ? ((size_t) ne01 * sizeof(float)) : sizeof(float)) : 0;
+ const bool is_w8a8 = htp_mm_kernel_is_hmx_w8a8(kparams->kernel_type);
+
+ const dma_addr_t dsts[1] = { dst->data };
+ const size_t scale_bytesa[1] = { scale_bytes };
+ const uint8_t scale_per_c[1] = { scale_per_ch ? 1 : 0 };
+ dma_addr_t weights[1] = { 0 };
+ dma_addr_t scale_addrs[1] = { 0 };
+ hmx_mm_id_2d_params_t id_p = {
+ .weight_dma = octx->ctx->dma[0],
+ .dsts = dsts,
+ .activation = act->data,
+ .act_elem_size = act_elem_size,
+ .dst_elem_size = dst_elem_size,
+ .weights = weights,
+ .n_weights = 1,
+ .k = ne00,
+ .n = ne01,
+ .k_valid = ne10,
+ .ne11 = ne11,
+ .act_nb1 = nb11,
+ .act_nb2 = nb12,
+ .dst_nb1 = nb1,
+ .dst_nb2 = nb2,
+ .weight_stride = (int) src0->nb[1],
+ .weight_type = (int) src0->type,
+ .matrix_rows = map->matrix_rows,
+ .mapping_stride = map->mapping_stride,
+ .scale_addrs = scale_addrs,
+ .scale_bytes_arr = scale_bytesa,
+ .scale_per_ch_arr = scale_per_c,
+ };
+
uint32_t target_dev = 0;
for (uint32_t cur_a = 0; cur_a < (uint32_t) n_as; ++cur_a) {
- const int32_t cne1 = matrix_row_counts[cur_a];
+ const int32_t cne1 = map->matrix_row_counts[cur_a];
if (cne1 == 0) continue;
const int m_padded = hex_align_up(cne1, 32);
@@ -6128,152 +987,63 @@ static int hmx_mm_op_matmul_id(
if (!my_expert) continue;
} else if (mdev_split) {
const bool can_split = (uint32_t) cne1 >= octx->ctx->mdev.count;
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m_padded, 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(
+ (uint32_t) m_padded, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
m_start = (int) range.start;
m_end = (int) (range.start + range.count);
}
if (m_start >= m_end || m_start >= cne1) continue;
- 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,
- nb11, nb12,
- nb1, nb2,
- (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 failed for expert %u, error %d\n", cur_a, ret);
- return HTP_STATUS_NO_SUPPORT;
+ dma_addr_t cur_scale_addr = 0;
+ if (scale) {
+ if (smode == HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT) {
+ cur_scale_addr = scale->data + (dma_addr_t) cur_a * scale->nb[1];
+ } else if (smode == HTP_MM_FUSED_SCALE_PER_EXPERT) {
+ cur_scale_addr = scale->data + (dma_addr_t) cur_a * sizeof(float);
+ } else {
+ cur_scale_addr = scale->data;
+ }
}
- }
-
- return HTP_STATUS_OK;
-}
-
-static int hvx_mm_matmul_id(
- struct htp_ops_context * octx,
- struct htp_mm_context * mmctx,
- work_queue_func_t hvx_mmid_task_func
-) {
- htp_matmul_tensors_preamble;
- 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];
- htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
+ weights[0] = src0->data + (dma_addr_t) cur_a * nb02;
+ scale_addrs[0] = cur_scale_addr;
+ id_p.m = cne1;
+ id_p.cur_a = (int) cur_a;
+ id_p.m_start = m_start;
+ id_p.m_end = m_end;
- const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- const size_t src0_row_size = nb01;
-
- const uint32_t qk = HTP_MM_ACT_BLOCK_K;
- const uint32_t nb = (ne10 + qk - 1) / qk;
- const uint32_t total_nb = act_nrows * nb;
-
- work_queue_func_t quant_task_func;
- uint32_t n_quant_tasks = 1;
- if (act_nrows < octx->n_hvx) {
- n_quant_tasks = MIN(total_nb, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
- for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
- uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
- uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
- mmctx->quant_ib_first[ith] = ib_first;
- mmctx->quant_ib_last[ith] = ib_last;
- mmctx->quant_r[ith] = ib_first / nb;
- mmctx->quant_c[ith] = ib_first % nb;
+ int ret = is_w8a8 ? hmx_w8a8_mm_id_2d(octx, kparams, &id_p)
+ : hmx_f16_mm_id_2d(octx, kparams, &id_p);
+ if (ret != 0) {
+ FARF(ERROR, "HMX matmul failed for expert %u, error %d\n", cur_a, ret);
+ return HTP_STATUS_NO_SUPPORT;
}
- } else {
- n_quant_tasks = MIN(act_nrows, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
- }
- 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,
- dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, true, false);
-
- const size_t vtcm_size = L.total_bytes;
-
- FARF(HIGH, "matmul-id-%s : src0-spad-size %zu act-spad-size %zu bias-spad-size 0 dst-spad-size %zu (%zu)\n", mmctx->type,
- L.src0_bytes, L.act_bytes, L.dst_bytes, vtcm_size);
-
- FARF(HIGH, "matmul-id-%s : %ux%ux%ux%u * %ux%ux%ux%u (%ux%ux%ux%u) -> %ux%ux%ux%u (0x%p, 0x%p, 0x%p)\n", mmctx->type,
- src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], act->ne[0], act->ne[1], act->ne[2], act->ne[3],
- ids->ne[0], ids->ne[1], ids->ne[2], ids->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], src0->data,
- act->data, dst->data);
-
- // Make sure the reserved vtcm size is sufficient
- if (octx->ctx->vtcm_size < vtcm_size) {
- FARF(ERROR, "matmul-id-%s : current VTCM reservation %zu is too small, needed %zu\n", mmctx->type, octx->ctx->vtcm_size, vtcm_size);
- return HTP_STATUS_VTCM_TOO_SMALL;
- }
-
- uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
- mmctx->vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act);
- mmctx->vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0);
- mmctx->vtcm_bias = NULL;
- 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);
- hvx_mm_iq2xxs_lut_init(base, &L);
-
- 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, 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;
- mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
-
- mmctx->cur_m_start = 0;
- mmctx->cur_m_rows = act_nrows;
-
- 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);
-
- work_queue_run(octx->ctx->hvx_queue, hvx_mmid_task_func, mmctx, octx->n_hvx);
+ }
return HTP_STATUS_OK;
}
-static int hmx_mm_op_matmul_id_nx(
- struct htp_ops_context * octx,
- struct htp_mm_context * mmctx
-) {
- const uint32_t * matrix_row_counts = mmctx->matrix_row_counts;
- const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows;
+static int hmx_mm_op_matmul_id_nx(struct htp_ops_context * octx, const struct htp_mmid_mapping * map) {
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
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 int n_as = src0->ne[2];
-
+ const int n_as = src0->ne[2];
const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
+ const bool is_w8a8 = htp_mm_kernel_is_hmx_w8a8(kparams->kernel_type);
const bool mdev_split = (octx->ctx->mdev.count > 1);
- uint32_t n_active = 0;
+ uint32_t n_active = 0;
if (mdev_split) {
for (uint32_t a = 0; a < (uint32_t) n_as; ++a) {
- if (matrix_row_counts[a] > 0) n_active++;
+ if (map->matrix_row_counts[a] > 0) n_active++;
}
}
const bool expert_split = mdev_split && (n_active >= octx->ctx->mdev.count);
uint32_t target_dev = 0;
for (uint32_t cur_a = 0; cur_a < (uint32_t) n_as; ++cur_a) {
- const int32_t cne1 = matrix_row_counts[cur_a];
+ const int32_t cne1 = map->matrix_row_counts[cur_a];
if (cne1 == 0) continue;
const int m_padded = hex_align_up(cne1, 32);
@@ -6286,17 +1056,21 @@ static int hmx_mm_op_matmul_id_nx(
if (!my_expert) continue;
} else if (mdev_split) {
const bool can_split = (uint32_t) cne1 >= octx->ctx->mdev.count;
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m_padded, 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(
+ (uint32_t) m_padded, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
m_start = (int) range.start;
m_end = (int) (range.start + range.count);
}
if (m_start >= m_end || m_start >= cne1) continue;
- if (htp_mm_kernel_is_hmx_int(kparams->kernel_type)) {
+ if (is_w8a8) {
const struct htp_tensor * restrict dst0 = octx->dsts[0];
- bool same_shape = true;
+ bool same_shape = true;
dma_addr_t dst_addrs[HTP_OP_MAX_OUTPUTS];
dma_addr_t weight_addrs[HTP_OP_MAX_OUTPUTS];
+ dma_addr_t scale_addrs[HTP_OP_MAX_OUTPUTS];
+ size_t scale_bytesa[HTP_OP_MAX_OUTPUTS];
+ uint8_t scale_per_ch[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];
@@ -6308,18 +1082,56 @@ static int hmx_mm_op_matmul_id_nx(
}
dst_addrs[p] = d->data;
weight_addrs[p] = sw->data + (dma_addr_t) cur_a * sw->nb[2];
+ const struct htp_tensor * sc = (((kparams->scale_mask >> p) & 1u) != 0) ? octx->src[n_weights + 2 + p] : NULL;
+ if (sc) {
+ const uint32_t sm = htp_mm_scale_mode_get(kparams->scale_mode, p);
+ const bool pch = htp_mm_scale_is_per_channel(sm);
+ scale_per_ch[p] = pch ? 1 : 0;
+ scale_bytesa[p] = pch ? ((size_t) sw->ne[1] * sizeof(float)) : sizeof(float);
+ if (sm == HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT) {
+ scale_addrs[p] = sc->data + (dma_addr_t) cur_a * sc->nb[1];
+ } else if (sm == HTP_MM_FUSED_SCALE_PER_EXPERT) {
+ scale_addrs[p] = sc->data + (dma_addr_t) cur_a * sizeof(float);
+ } else {
+ scale_addrs[p] = sc->data;
+ }
+ } else {
+ scale_addrs[p] = 0;
+ scale_bytesa[p] = 0;
+ scale_per_ch[p] = 0;
+ }
}
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);
+ const hmx_mm_id_2d_params_t id_p = {
+ .weight_dma = octx->ctx->dma[0],
+ .dsts = dst_addrs,
+ .activation = act->data,
+ .act_elem_size = act_elem_size,
+ .dst_elem_size = dst0_elem_size,
+ .weights = weight_addrs,
+ .n_weights = n_weights,
+ .m = cne1,
+ .k = src0->ne[0],
+ .n = src0->ne[1],
+ .k_valid = act->ne[0],
+ .ne11 = act->ne[1],
+ .act_nb1 = act->nb[1],
+ .act_nb2 = act->nb[2],
+ .dst_nb1 = dst0->nb[1],
+ .dst_nb2 = dst0->nb[2],
+ .weight_stride = (int) src0->nb[1],
+ .weight_type = (int) src0->type,
+ .matrix_rows = map->matrix_rows,
+ .cur_a = (int) cur_a,
+ .mapping_stride = map->mapping_stride,
+ .m_start = m_start,
+ .m_end = m_end,
+ .scale_addrs = kparams->scale_mask ? scale_addrs : NULL,
+ .scale_bytes_arr = kparams->scale_mask ? scale_bytesa : NULL,
+ .scale_per_ch_arr = kparams->scale_mask ? scale_per_ch : NULL,
+ };
+ int ret = hmx_w8a8_mm_id_2d(octx, kparams, &id_p);
if (ret != 0) {
FARF(ERROR, "HMX matmul ID NX failed for expert %u, error %d\n", cur_a, ret);
return HTP_STATUS_NO_SUPPORT;
@@ -6334,19 +1146,58 @@ static int hmx_mm_op_matmul_id_nx(
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, 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],
- act->nb[1], act->nb[2],
- dst->nb[1], dst->nb[2],
- (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,
- kparams->kernel_type);
+ const struct htp_tensor * sc = (((kparams->scale_mask >> p) & 1u) != 0) ? octx->src[n_weights + 2 + p] : NULL;
+ dma_addr_t cur_scale_addr = 0;
+ size_t cur_scale_bytes = 0;
+ bool cur_scale_per_ch = false;
+ if (sc) {
+ const uint32_t sm = htp_mm_scale_mode_get(kparams->scale_mode, p);
+ cur_scale_per_ch = htp_mm_scale_is_per_channel(sm);
+ cur_scale_bytes = cur_scale_per_ch ? ((size_t) src_w->ne[1] * sizeof(float)) : sizeof(float);
+ if (sm == HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT) {
+ cur_scale_addr = sc->data + (dma_addr_t) cur_a * sc->nb[1];
+ } else if (sm == HTP_MM_FUSED_SCALE_PER_EXPERT) {
+ cur_scale_addr = sc->data + (dma_addr_t) cur_a * sizeof(float);
+ } else {
+ cur_scale_addr = sc->data;
+ }
+ }
+
+ const dma_addr_t dsts[1] = { dst->data };
+ const dma_addr_t weights[1] = { src_w->data + (dma_addr_t) cur_a * src_w->nb[2] };
+ const dma_addr_t scale_addrs[1] = { cur_scale_addr };
+ const size_t scale_bytesa[1] = { cur_scale_bytes };
+ const uint8_t scale_per_c[1] = { cur_scale_per_ch ? 1 : 0 };
+ const hmx_mm_id_2d_params_t id_p = {
+ .weight_dma = octx->ctx->dma[0],
+ .dsts = dsts,
+ .activation = act->data,
+ .act_elem_size = act_elem_size,
+ .dst_elem_size = dst_elem_size,
+ .weights = weights,
+ .n_weights = 1,
+ .m = cne1,
+ .k = src_w->ne[0],
+ .n = src_w->ne[1],
+ .k_valid = act->ne[0],
+ .ne11 = act->ne[1],
+ .act_nb1 = act->nb[1],
+ .act_nb2 = act->nb[2],
+ .dst_nb1 = dst->nb[1],
+ .dst_nb2 = dst->nb[2],
+ .weight_stride = (int) src_w->nb[1],
+ .weight_type = (int) src_w->type,
+ .matrix_rows = map->matrix_rows,
+ .cur_a = (int) cur_a,
+ .mapping_stride = map->mapping_stride,
+ .m_start = m_start,
+ .m_end = m_end,
+ .scale_addrs = scale_addrs,
+ .scale_bytes_arr = scale_bytesa,
+ .scale_per_ch_arr = scale_per_c,
+ };
+ int ret = is_w8a8 ? hmx_w8a8_mm_id_2d(octx, kparams, &id_p)
+ : hmx_f16_mm_id_2d(octx, kparams, &id_p);
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;
@@ -6357,322 +1208,9 @@ static int hmx_mm_op_matmul_id_nx(
return HTP_STATUS_OK;
}
-static int hvx_mm_matmul_id_nx(
- struct htp_ops_context * octx,
- struct htp_mm_context * mmctx,
- work_queue_func_t hvx_mmid_task_func
-) {
- const uint32_t act_nrows = mmctx->act_nrows;
-
- struct htp_thread_trace * tr = &octx->ctx->trace[0];
- 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 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 size_t src0_row_size = src0->nb[1];
-
- const uint32_t qk = HTP_MM_ACT_BLOCK_K;
- const uint32_t nb = (act->ne[0] + qk - 1) / qk;
- const uint32_t total_nb = act_nrows * nb;
-
- work_queue_func_t quant_task_func;
- uint32_t n_quant_tasks = 1;
- if (act_nrows < octx->n_hvx) {
- n_quant_tasks = MIN(total_nb, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
- for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
- uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
- uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
- mmctx->quant_ib_first[ith] = ib_first;
- mmctx->quant_ib_last[ith] = ib_last;
- mmctx->quant_r[ith] = ib_first / nb;
- mmctx->quant_c[ith] = ib_first % nb;
- }
- } else {
- n_quant_tasks = MIN(act_nrows, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
- }
- 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,
- max_dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, true, false);
-
- const size_t vtcm_size = L.total_bytes;
-
- if (octx->ctx->vtcm_size < vtcm_size) {
- FARF(ERROR, "matmul-id-nx: current VTCM reservation %zu is too small, needed %zu\n",
- octx->ctx->vtcm_size, vtcm_size);
- return HTP_STATUS_VTCM_TOO_SMALL;
- }
-
- uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
- 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);
- 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], 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;
- mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
-
- mmctx->cur_m_start = 0;
- mmctx->cur_m_rows = act_nrows;
-
- FARF(HIGH, "matmul-id-nx: src0 %d:%d:%d type %s nrows %u, act %d:%d:%d nrows %u, vtcm %zu/%zu, nhvx %d\n",
- src0->ne[0], src0->ne[1], src0->ne[2], mmctx->type, src0->ne[1],
- act->ne[0], act->ne[1], act->ne[2], act_nrows,
- L.total_bytes, octx->ctx->vtcm_size, octx->n_hvx);
-
- 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);
-
- work_queue_run(octx->ctx->hvx_queue, hvx_mmid_task_func, mmctx, octx->n_hvx);
-
- return HTP_STATUS_OK;
-}
-
-static __attribute__((noinline)) uint32_t scan_expert_ids_n(
- 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
-) {
- uint32_t n_skipped = 0;
-
- 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) {
- 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;
-}
-
-static __attribute__((noinline)) uint32_t scan_expert_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
-) {
- 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 int32_t * ids_data, uint32_t n_ids) {
- uint32_t n_skipped = 0;
- for (uint32_t id = 0; id < n_ids; ++id) {
- if (ids_data[id] < 0) {
- n_skipped++;
- }
- }
- return n_skipped;
-}
-
-// 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 int32_t * ids_data,
- uint32_t ids_ne1,
- uint32_t n_ids,
- const struct htp_tensor * dst
-) {
- const uint32_t elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float);
- uint32_t col_start = 0;
- uint32_t col_count = dst->ne[0];
-
- if (octx->ctx->mdev.count > 1) {
- const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
- 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;
- }
-
- if (col_count == 0) {
- return;
- }
-
- const size_t dst_nb1 = dst->nb[1];
- const size_t dst_nb2 = dst->nb[2];
- 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) {
- 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,
- 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
-) {
- 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 = 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);
- 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_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;
-
- 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 > 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_data, ids->ne[1], n_ids, n_as, matrix_row_counts, matrix_rows, mapping_stride);
- } else {
- n_skipped = count_skipped_ids_single(ids_data, n_ids);
- }
-
- *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;
- *out_n_skipped = n_skipped;
-
- return HTP_STATUS_OK;
-}
-
int op_matmul_id(struct htp_ops_context * octx) {
htp_matmul_tensors_preamble;
-
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- struct htp_mm_context mmctx_struct = {0};
- struct htp_mm_context * mmctx = &mmctx_struct;
const int status = htp_mm_init_context(octx, kparams);
if (status != HTP_STATUS_OK) {
@@ -6682,88 +1220,33 @@ int op_matmul_id(struct htp_ops_context * octx) {
struct htp_thread_trace * tr = &octx->ctx->trace[0];
htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
- mmctx->octx = octx;
- mmctx->act = act;
-
const struct htp_tensor * restrict ids = octx->src[2];
-
- const size_t src0_row_size = nb01;
-
- const size_t src0_row_size_padded = hex_round_up(src0_row_size, 128);
-
- const uint32_t src0_nrows = ne01; // per expert
- const uint32_t act_nrows = ne11 * ne12 * ne13;
-
- // row groups
- const int n_ids = ids->ne[0]; // n_expert_used
- const int n_as = ne02; // n_expert
+ const uint32_t act_nrows = ne11 * ne12 * ne13;
+ const int n_ids = ids->ne[0];
+ const int n_as = ne02;
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;
+ struct htp_mmid_mapping map = {0};
+ void * ids_alloc = NULL;
+ void * map_alloc = NULL;
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);
+ &map, &ids_alloc, &map_alloc);
if (map_status != HTP_STATUS_OK) {
return map_status;
}
- if (n_skipped > 0) {
- zero_skipped_dst_rows(octx, ids_data, ids->ne[1], n_ids, dst);
+ if (map.n_skipped > 0) {
+ zero_skipped_dst_rows(octx, map.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;
- mmctx->mm_div_ne11 = kparams->div_ne1;
- mmctx->src0_row_size_padded = src0_row_size_padded;
- mmctx->act_nrows = act_nrows;
- mmctx->cur_m_start = 0;
- mmctx->cur_m_rows = act_nrows;
-
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
int s;
if (kparams->n_hmx) {
- s = hmx_mm_op_matmul_id(octx, mmctx);
+ s = hmx_mm_op_matmul_id(octx, &map);
} 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 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) {
- free(map_alloc);
- free(ids_alloc);
- return HTP_STATUS_OK;
- }
-
- const uint32_t nrows = src0_row_end - src0_row_start;
- mmctx->src0_row_start = src0_row_start;
- mmctx->src0_row_end = src0_row_end;
-
- 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 {
- s = HTP_STATUS_NO_SUPPORT;
- }
+ s = hvx_mm_matmul_id(octx, &map);
}
free(map_alloc);
@@ -6774,8 +1257,6 @@ int op_matmul_id(struct htp_ops_context * octx) {
int op_matmul_id_nx(struct htp_ops_context * octx) {
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
- struct htp_mm_context mmctx_struct = {0};
- struct htp_mm_context * mmctx = &mmctx_struct;
const int status = htp_mm_init_context(octx, kparams);
if (status != HTP_STATUS_OK) {
@@ -6785,69 +1266,42 @@ int op_matmul_id_nx(struct htp_ops_context * octx) {
struct htp_thread_trace * tr = &octx->ctx->trace[0];
htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
- mmctx->octx = octx;
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];
- mmctx->act = act;
-
- const size_t src0_row_size = src0->nb[1];
- const size_t src0_row_size_padded = hex_round_up(src0_row_size, 128);
-
const uint32_t act_nrows = act->ne[1] * act->ne[2] * act->ne[3];
-
- const int n_ids = ids->ne[0];
- const int n_as = src0->ne[2];
+ const int n_ids = ids->ne[0];
+ const int n_as = src0->ne[2];
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;
+ struct htp_mmid_mapping map = {0};
+ void * ids_alloc = NULL;
+ void * map_alloc = NULL;
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);
+ &map, &ids_alloc, &map_alloc);
if (map_status != HTP_STATUS_OK) {
return map_status;
}
- if (n_skipped > 0) {
+ if (map.n_skipped > 0) {
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_data, ids->ne[1], n_ids, d);
+ zero_skipped_dst_rows(octx, map.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;
- mmctx->mm_div_ne11 = kparams->div_ne1;
- mmctx->src0_row_size_padded = src0_row_size_padded;
- mmctx->act_nrows = act_nrows;
- mmctx->cur_m_start = 0;
- mmctx->cur_m_rows = act_nrows;
-
htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
int s;
if (kparams->n_hmx) {
- s = hmx_mm_op_matmul_id_nx(octx, mmctx);
+ s = hmx_mm_op_matmul_id_nx(octx, &map);
} else {
- if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) == 0) {
- s = hvx_mm_matmul_id_nx(octx, mmctx, act_nrows > 1 ? hvx_mm_id_nx_tiled : hvx_mv_id_nx_tiled);
- } else {
- s = HTP_STATUS_NO_SUPPORT;
- }
+ s = hvx_mm_matmul_id_nx(octx, &map);
}
free(map_alloc);
@@ -6855,7 +1309,8 @@ int op_matmul_id_nx(struct htp_ops_context * octx) {
return s;
}
-static int op_matmul_nx_impl(struct htp_ops_context * octx) {
+
+int op_matmul_nx(struct htp_ops_context * octx) {
const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params;
const int status = htp_mm_init_context(octx, kparams);
@@ -6864,114 +1319,16 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) {
}
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);
+ return htp_mm_kernel_is_hmx_w8a8(kparams->kernel_type)
+ ? hmx_w8a8_mm_nx_glu_2d(octx, kparams)
+ : hmx_f16_mm_nx_glu_2d(octx, kparams);
}
if (kparams->n_hmx) {
- return hmx_mm_nx_2d_f32(octx, kparams);
- }
-
- struct htp_thread_trace * tr = &octx->ctx->trace[0];
- htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0);
-
- const uint32_t n_weights = kparams->n_weights;
-
- const struct htp_tensor * restrict src0 = octx->src[0]; // first weight
- const struct htp_tensor * restrict act = octx->src[n_weights]; // activation x
-
- struct htp_mm_context mmctx_struct = {0};
- struct htp_mm_context * mmctx = &mmctx_struct;
- mmctx->octx = octx;
- mmctx->act = act;
-
- const uint32_t act_nrows = act->ne[1] * act->ne[2] * act->ne[3];
- mmctx->act_nrows = act_nrows;
- mmctx->cur_m_start = 0;
- mmctx->cur_m_rows = act_nrows;
-
- const size_t src0_row_size = src0->nb[1];
-
- if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) != 0) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
- const uint32_t qk = HTP_MM_ACT_BLOCK_K;
- const uint32_t nb = (act->ne[0] + qk - 1) / qk;
- const uint32_t total_nb = act_nrows * nb;
-
- work_queue_func_t quant_task_func;
- uint32_t n_quant_tasks = 1;
- if (act_nrows < octx->n_hvx) {
- n_quant_tasks = MIN(total_nb, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_block_func(src0->type, act->type);
- for (uint32_t ith = 0; ith < n_quant_tasks; ++ith) {
- uint32_t ib_first = (total_nb * ith) / n_quant_tasks;
- uint32_t ib_last = (total_nb * (ith + 1)) / n_quant_tasks;
- mmctx->quant_ib_first[ith] = ib_first;
- mmctx->quant_ib_last[ith] = ib_last;
- mmctx->quant_r[ith] = ib_first / nb;
- mmctx->quant_c[ith] = ib_first % nb;
- }
- } else {
- n_quant_tasks = MIN(act_nrows, octx->n_hvx);
- quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type);
- }
-
- 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;
- }
+ return htp_mm_kernel_is_hmx_w8a8(kparams->kernel_type)
+ ? hmx_w8a8_mm_nx_2d(octx, kparams)
+ : hmx_f16_mm_nx_2d(octx, kparams);
}
- 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,
- max_dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, false, true);
- const size_t vtcm_size = L.total_bytes;
-
- if (octx->ctx->vtcm_size < vtcm_size) {
- FARF(ERROR, "matmul-nx: current VTCM reservation %zu is too small, needed %zu\n",
- octx->ctx->vtcm_size, vtcm_size);
- return HTP_STATUS_VTCM_TOO_SMALL;
- }
-
- uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base;
- 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_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], 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;
- mmctx->vtcm_dst_size_per_hvx = fastdiv(L.dst_bytes, &octx->n_hvx_div);
-
- htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0);
-
- 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);
-
- return HTP_STATUS_OK;
-}
-
-int op_matmul_nx(struct htp_ops_context * octx) {
- return op_matmul_nx_impl(octx);
+ return hvx_mm_matmul_nx(octx);
}
diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.h b/ggml/src/ggml-hexagon/htp/matmul-ops.h
index e3c9569ca..fde8ebb48 100644
--- a/ggml/src/ggml-hexagon/htp/matmul-ops.h
+++ b/ggml/src/ggml-hexagon/htp/matmul-ops.h
@@ -48,8 +48,8 @@ enum htp_mm_kernel_type {
HTP_MM_KERNEL_UNSUPPORTED = 0,
// HMX paths
- HTP_MM_KERNEL_HMX_2D,
- HTP_MM_KERNEL_HMX_BATCHED,
+ HTP_MM_KERNEL_HMX_F16_2D,
+ HTP_MM_KERNEL_HMX_F16_BATCHED,
HTP_MM_KERNEL_HMX_W8A8_2D,
HTP_MM_KERNEL_HMX_W8A8_BATCHED,
@@ -67,19 +67,19 @@ 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_f16(int32_t kt) {
+ return kt == HTP_MM_KERNEL_HMX_F16_2D || kt == HTP_MM_KERNEL_HMX_F16_BATCHED;
}
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;
+ return kt == HTP_MM_KERNEL_HMX_F16_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;
+ return kt == HTP_MM_KERNEL_HMX_F16_BATCHED || kt == HTP_MM_KERNEL_HMX_W8A8_BATCHED;
}
-static inline bool htp_is_int_hmx_weight_type(int wtype) {
+static inline bool htp_is_hmx_w8a8_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 ||
@@ -87,10 +87,11 @@ static inline bool htp_is_int_hmx_weight_type(int wtype) {
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;
+ wtype == HTP_TYPE_Q5_K || wtype == HTP_TYPE_Q2_K ||
+ wtype == HTP_TYPE_F8_E4M3;
}
-static inline uint32_t htp_int_hmx_min_k(int wtype) {
+static inline uint32_t htp_hmx_w8a8_min_k(int wtype) {
switch (wtype) {
case HTP_TYPE_IQ2_XXS:
case HTP_TYPE_Q2_K:
@@ -106,26 +107,75 @@ static inline uint32_t htp_int_hmx_min_k(int wtype) {
}
}
+enum htp_mm_fused_scale_mode {
+ HTP_MM_FUSED_SCALE_PER_TENSOR = 0,
+ HTP_MM_FUSED_SCALE_PER_CHANNEL = 1,
+ HTP_MM_FUSED_SCALE_PER_EXPERT = 2,
+ HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT = 3,
+};
+
+static inline uint32_t htp_mm_scale_mode_get(uint16_t packed_mode, uint32_t w_idx) {
+ return (packed_mode >> (2u * w_idx)) & 3u;
+}
+
+static inline bool htp_mm_scale_is_per_channel(uint32_t mode) {
+ return mode == HTP_MM_FUSED_SCALE_PER_CHANNEL || mode == HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT;
+}
+
+static inline size_t htp_mm_fused_scale_vtcm_bytes(uint32_t ne01, uint32_t ne02, uint32_t smode, bool for_hmx) {
+ switch (smode) {
+ case HTP_MM_FUSED_SCALE_PER_TENSOR:
+ return 128;
+ case HTP_MM_FUSED_SCALE_PER_CHANNEL:
+ return hex_round_up((size_t) ne01 * sizeof(float), 128);
+ case HTP_MM_FUSED_SCALE_PER_EXPERT:
+ return for_hmx ? 128 : hex_round_up((size_t) ne02 * sizeof(float), 128);
+ case HTP_MM_FUSED_SCALE_PER_CHANNEL_EXPERT:
+ return for_hmx
+ ? hex_round_up((size_t) ne01 * sizeof(float), 128)
+ : hex_round_up((size_t) ne01 * (size_t) ne02 * sizeof(float), 128);
+ default:
+ return 0;
+ }
+}
+
+static inline size_t htp_mm_fused_norm_vtcm_bytes(uint32_t k) {
+ return hex_align_up((size_t) k * sizeof(float), 128);
+}
+
+enum htp_mm_flags {
+ HTP_MM_FLAG_PIPELINE = (1u << 0), // Pipelined execution
+ HTP_MM_FLAG_FWHT = (1u << 1), // Online block-32 FWHT rotation along K
+ HTP_MM_FLAG_GROUPED = (1u << 2), // Grouped batched HMX-F16 layout
+};
+
// Op-specific struct for precomputed matmul params
struct htp_mm_kernel_params {
+ // Kernel selection and mode variants
uint8_t kernel_type; // enum htp_mm_kernel_type
- uint8_t pipeline; // 1 = pipelined execution, 0 = standard
+ uint8_t flags; // bitmask of enum htp_mm_flags
+ uint8_t glu_op; // HTP_OP_GLU_* for fused MUL_MAT_NX_GLU (0 if none)
+ uint8_t norm_w_idx; // Input index of norm weight in octx->src[] (0 if none)
+
+ // Execution resources and fusion counts
uint8_t n_hmx; // 1 = use HMX, 0 = use HVX
uint8_t n_hvx; // Number of HVX threads
-
- uint8_t n_act_hvx; // Number of HVX for activation preparation
+ uint8_t n_act_hvx; // Number of HVX threads 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)
- int32_t tile_size; // Weight tile size
- int32_t aligned_tile_size; // Aligned weight tile size (padded to 128)
- 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)
+ uint8_t scale_mask; // Bitmask of weights 0..n_weights-1 with fused scale
+ uint16_t scale_mode; // Packed 2-bit mode per weight (enum htp_mm_fused_scale_mode)
+
+ // Tiling and VTCM layout
+ uint32_t m_chunk; // Row chunk size (M chunk)
+ uint32_t n_chunk; // Col chunk size (N chunk)
+ uint32_t tile_size; // Weight tile size
+ uint32_t aligned_tile_size; // Aligned weight tile size (padded to 128)
+ uint32_t act_row_size; // Row size for activation scratchpad
+ uint32_t vtcm_size; // Total required scratchpad size in VTCM
+ uint32_t vtcm_bias_size; // Bias scratchpad size in VTCM (fused only)
+ uint32_t vtcm_scale_size; // Weight scale scratchpad size in VTCM (fused only)
+ uint32_t hmx_n_groups; // Number of K superblocks for W8A8 HMX kernels (1 for FP16)
// Precomputed division values
struct fastdiv_values div_ne12_ne1;
@@ -137,12 +187,17 @@ struct htp_mm_kernel_params {
struct fastdiv_values div_ne00_padded;
struct fastdiv_values div_hmx_n_groups;
struct fastdiv_values div_n_k_tiles;
+
+ // Fused RMS_NORM_MUL -> HMX activation prep
+ float norm_eps; // RMSNorm epsilon
};
#if defined(__cplusplus)
static_assert(sizeof(struct htp_mm_kernel_params) <= 128, "htp_matmul_kernel_params is too large for kernel_params blob");
+static_assert(HTP_OP_MAX_OUTPUTS <= 8, "HTP_OP_MAX_OUTPUTS exceeds scale_mask (8 bits) and scale_mode (8 x 2 bits)");
#else
_Static_assert(sizeof(struct htp_mm_kernel_params) <= 128, "htp_matmul_kernel_params is too large for kernel_params blob");
+_Static_assert(HTP_OP_MAX_OUTPUTS <= 8, "HTP_OP_MAX_OUTPUTS exceeds scale_mask (8 bits) and scale_mode (8 x 2 bits)");
#endif
struct mmid_row_mapping {
@@ -261,7 +316,7 @@ static inline size_t htp_mm_f16_tiled_row_size(uint32_t ne) {
}
static inline size_t htp_mm_tiled_act_row_size(int weight_type, uint32_t ne) {
- if (weight_type == HTP_TYPE_F16) {
+ if (weight_type == HTP_TYPE_F16 || weight_type == HTP_TYPE_F8_E4M3) {
return htp_mm_f16_tiled_row_size(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);
@@ -288,7 +343,7 @@ static inline void htp_mm_hmx_get_2d_chunk_costs_ex(
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)) {
+ if (htp_mm_kernel_is_hmx_w8a8(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;
@@ -309,7 +364,7 @@ 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,
+ htp_mm_hmx_get_2d_chunk_costs_ex(HTP_MM_KERNEL_HMX_F16_2D, wtype, k, pipeline, aligned_tile_size,
size_per_n_out, size_per_m_out, size_per_mn_out);
}
@@ -351,6 +406,8 @@ struct htp_mm_hmx_vtcm_layout {
size_t off_scratch[2]; // dequantization scratch pads
size_t off_scales; // HMX scales (256 bytes)
size_t off_bias; // bias in VTCM
+ size_t off_scale; // weight scale in VTCM
+ size_t off_norm; // fused RMSNorm weight in VTCM (F32)
size_t off_lut; // IQ2_XXS grid + sign tables (2D only)
// Cached sizes of regions for HMX kernel use
@@ -368,6 +425,8 @@ struct htp_mm_hmx_vtcm_layout {
size_t weight_scales_offset;
size_t act_head_stride;
size_t bias_bytes;
+ size_t scale_bytes;
+ size_t norm_bytes;
size_t lut_bytes;
size_t total_bytes;
@@ -379,6 +438,7 @@ struct htp_mm_hvx_vtcm_layout {
size_t off_act; // vtcm_act (activation)
size_t off_src0; // vtcm_src0 (weight/Wk)
size_t off_bias; // vtcm_bias (bias / fused add only)
+ size_t off_scale; // vtcm_scale (fused weight scale)
size_t off_dst; // vtcm_dst (output scratch)
size_t off_act_raw; // vtcm_act_raw (raw activation DMA staging)
size_t off_lut; // vtcm_lut (IQ2_XXS grid + sign tables)
@@ -387,6 +447,7 @@ struct htp_mm_hvx_vtcm_layout {
size_t src0_bytes;
size_t act_bytes;
size_t bias_bytes;
+ size_t scale_bytes;
size_t dst_bytes;
size_t act_raw_bytes;
size_t lut_bytes;
@@ -408,11 +469,17 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
size_t bias_size,
size_t res_in_elem_size,
size_t res_out_elem_size,
- bool is_glu
+ bool is_glu,
+ size_t scale_size,
+ size_t norm_size
) {
size_t off = 0;
L->lut_bytes = 0;
L->off_lut = 0;
+ L->off_scale = 0;
+ L->scale_bytes = 0;
+ L->off_norm = 0;
+ L->norm_bytes = 0;
L->off_act_scales = 0;
L->can_preissue_weight = false;
L->act_scales_bytes = 0;
@@ -433,7 +500,7 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
L->weight_bias_offset = 0;
L->weight_scales_offset = 0;
- if (kernel_type == HTP_MM_KERNEL_HMX_BATCHED) {
+ if (kernel_type == HTP_MM_KERNEL_HMX_F16_BATCHED) {
const size_t vec_dot_size = k * sizeof(uint16_t);
const size_t act_head_stride = mc * k;
const size_t weight_area_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE);
@@ -482,13 +549,13 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
off = off_group_a + hex_smax(group_b_size, group_c_size);
} else {
- // HTP_MM_KERNEL_HMX_2D / W8A8
- const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type);
+ // HTP_MM_KERNEL_HMX_F16_2D / W8A8
+ const bool is_w8a8 = htp_mm_kernel_is_hmx_w8a8(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 uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(wtype);
- const uint32_t dma_act_mult = is_int_hmx ? 8u : HTP_MM_DMA_ACT_MULTIPLIER;
+ const uint32_t dma_act_mult = is_w8a8 ? 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)
@@ -499,7 +566,7 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
size_t output_area_size = 0;
size_t scratch0_size = 0;
- if (is_int_hmx) {
+ if (is_w8a8) {
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);
@@ -532,10 +599,12 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
// Group A: Scales and activation tiles (must not overlap with Group B or C)
size_t off_group_a = 0;
- VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_scales, HTP_MM_HMX_TILE_SIZE, !is_int_hmx);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_scales, HTP_MM_HMX_TILE_SIZE, !is_w8a8);
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);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_scale, hex_align_up(scale_size, HTP_MM_HMX_TILE_SIZE), scale_size > 0);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_norm, hex_align_up(norm_size, HTP_MM_HMX_TILE_SIZE), norm_size > 0);
// Group B: Compute-only buffers (starts at off_group_a)
size_t off_group_b = off_group_a;
@@ -565,7 +634,7 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
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) {
+ if (is_w8a8 && 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;
@@ -588,6 +657,8 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
L->scratch_bytes[1] = scratch1_size;
L->act_head_stride = 0;
L->bias_bytes = bias_size;
+ L->scale_bytes = scale_size;
+ L->norm_bytes = norm_size;
off = off_group_a + hex_smax(group_b_size, group_c_size);
@@ -598,6 +669,26 @@ static inline void htp_mm_hmx_vtcm_layout_build_core(
L->total_bytes = off;
}
+static inline void htp_mm_hmx_vtcm_layout_build_ex_scaled(
+ 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 scale_size,
+ size_t res_in_elem_size,
+ size_t res_out_elem_size,
+ size_t norm_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, scale_size, norm_size);
+}
+
static inline void htp_mm_hmx_vtcm_layout_build_ex(
struct htp_mm_hmx_vtcm_layout * L,
int kernel_type,
@@ -613,7 +704,7 @@ static inline void htp_mm_hmx_vtcm_layout_build_ex(
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);
+ 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, 0, 0);
}
static inline void htp_mm_hmx_vtcm_layout_build_glu(
@@ -626,9 +717,11 @@ static inline void htp_mm_hmx_vtcm_layout_build_glu(
bool pipeline,
uint32_t act_hvx,
uint32_t aligned_tile_size,
- size_t res_out_elem_size
+ size_t res_out_elem_size,
+ size_t scale_size,
+ size_t norm_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);
+ 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, scale_size, norm_size);
}
static inline void htp_mm_hmx_vtcm_layout_build(
@@ -647,7 +740,7 @@ static inline void htp_mm_hmx_vtcm_layout_build(
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(
+static inline void htp_mm_hvx_vtcm_layout_build_ex(
struct htp_mm_hvx_vtcm_layout * L,
int kernel_type,
int wtype,
@@ -658,6 +751,7 @@ static inline void htp_mm_hvx_vtcm_layout_build(
size_t src0_row_size,
size_t act_elem_size,
size_t bias_row_size,
+ size_t scale_size,
uint32_t n_prefetch,
bool is_matmul_id,
bool is_fused_nx
@@ -667,6 +761,7 @@ static inline void htp_mm_hvx_vtcm_layout_build(
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;
+ const size_t scale_sz = scale_size > 0 ? htp_mm_round_up(scale_size, 128) : 0;
size_t dst_sz = 0;
size_t act_raw_sz = 0;
const size_t lut_sz = (wtype == HTP_TYPE_IQ2_XXS) ? HTP_IQ2XXS_LUT_BYTES : 0;
@@ -759,6 +854,7 @@ static inline void htp_mm_hvx_vtcm_layout_build(
size_t off_group_a = 0;
VTCM_LAYOUT_ALLOC(off_group_a, off_act, act_sz);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_bias, bias_sz, bias_sz > 0);
+ VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_scale, scale_sz, scale_sz > 0);
VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_lut, lut_sz, lut_sz > 0);
// Group B: Compute-only buffers (starts at off_group_a)
@@ -775,13 +871,35 @@ static inline void htp_mm_hvx_vtcm_layout_build(
L->src0_bytes = src0_sz;
L->act_bytes = act_sz;
L->bias_bytes = bias_sz;
+ L->scale_bytes = scale_sz;
L->dst_bytes = dst_sz;
L->act_raw_bytes = act_raw_sz;
L->lut_bytes = lut_sz;
L->total_bytes = off_group_a + hex_smax(group_b_size, group_c_size);
}
-static inline bool htp_mm_hvx_solve_vtcm_params(
+static inline void htp_mm_hvx_vtcm_layout_build(
+ struct htp_mm_hvx_vtcm_layout * L,
+ int kernel_type,
+ int wtype,
+ uint32_t ne10, // k
+ uint32_t act_nrows, // m_total
+ uint32_t n_hvx,
+ size_t dst_row_size,
+ size_t src0_row_size,
+ size_t act_elem_size,
+ size_t bias_row_size,
+ uint32_t n_prefetch,
+ bool is_matmul_id,
+ bool is_fused_nx
+) {
+ htp_mm_hvx_vtcm_layout_build_ex(
+ L, kernel_type, wtype, ne10, act_nrows, n_hvx,
+ dst_row_size, src0_row_size, act_elem_size, bias_row_size, 0, n_prefetch, is_matmul_id, is_fused_nx
+ );
+}
+
+static inline bool htp_mm_hvx_solve_vtcm_params_ex(
int kernel_type,
int wtype,
uint32_t ne10,
@@ -791,6 +909,7 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
size_t src0_row_size,
size_t act_elem_size,
size_t bias_row_size,
+ size_t scale_size,
uint32_t n_prefetch,
size_t vtcm_budget,
struct htp_mm_hvx_vtcm_layout * L_out,
@@ -798,9 +917,9 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
) {
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(
+ htp_mm_hvx_vtcm_layout_build_ex(
&L, kernel_type, wtype, ne10, act_nrows, n_hvx,
- dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, scale_size, n_prefetch, false, false
);
if (L.total_bytes <= vtcm_budget) {
@@ -809,7 +928,7 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
return true;
}
- const size_t fixed_bytes = L.src0_bytes + L.bias_bytes + L.dst_bytes + L.lut_bytes;
+ const size_t fixed_bytes = L.src0_bytes + L.bias_bytes + L.scale_bytes + L.dst_bytes + L.lut_bytes;
if (vtcm_budget <= fixed_bytes) {
return false;
}
@@ -843,24 +962,24 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
return false;
}
- htp_mm_hvx_vtcm_layout_build(
+ htp_mm_hvx_vtcm_layout_build_ex(
&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
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, scale_size, n_prefetch, false, false
);
while (m_chunk > 2 && L.total_bytes > vtcm_budget) {
m_chunk -= 2;
- htp_mm_hvx_vtcm_layout_build(
+ htp_mm_hvx_vtcm_layout_build_ex(
&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
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, scale_size, n_prefetch, false, false
);
}
if (m_chunk > 1 && L.total_bytes > vtcm_budget) {
m_chunk = 1;
- htp_mm_hvx_vtcm_layout_build(
+ htp_mm_hvx_vtcm_layout_build_ex(
&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
+ dst_row_size, src0_row_size, raw_elem_size, bias_row_size, scale_size, n_prefetch, false, false
);
}
@@ -873,12 +992,34 @@ static inline bool htp_mm_hvx_solve_vtcm_params(
return false;
}
+static inline bool htp_mm_hvx_solve_vtcm_params(
+ int kernel_type,
+ int wtype,
+ uint32_t ne10,
+ uint32_t act_nrows,
+ uint32_t n_hvx,
+ size_t dst_row_size,
+ size_t src0_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
+) {
+ return htp_mm_hvx_solve_vtcm_params_ex(
+ kernel_type, wtype, ne10, act_nrows, n_hvx,
+ dst_row_size, src0_row_size, act_elem_size, bias_row_size, 0, n_prefetch, vtcm_budget,
+ L_out, m_chunk_out
+ );
+}
+
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
+ size_t res_in_elem_size, size_t res_out_elem_size, bool is_glu, size_t scale_size, size_t norm_size
) {
struct htp_mm_hmx_vtcm_layout L;
- 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);
+ 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, scale_size, norm_size);
return L.total_bytes;
}
@@ -886,20 +1027,20 @@ 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);
+ 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, 0, 0);
}
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);
+ return htp_mm_hmx_get_2d_vtcm_size_ex(HTP_MM_KERNEL_HMX_F16_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, size_t res_out_elem_size) {
(void)pipeline;
struct htp_mm_hmx_vtcm_layout L;
- 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);
+ htp_mm_hmx_vtcm_layout_build_ex(&L, HTP_MM_KERNEL_HMX_F16_BATCHED, wtype, k, mc, nc, group_size, false, act_hvx, 0, bias_size, 0, res_out_elem_size);
return L.total_bytes;
}
@@ -981,6 +1122,8 @@ static inline bool htp_mm_hmx_solve_2d_params_core(
bool is_matmul_id,
uint32_t aligned_tile_size,
size_t bias_size,
+ size_t scale_size,
+ size_t norm_size,
size_t res_in_elem_size,
size_t res_out_elem_size,
bool is_glu,
@@ -990,8 +1133,8 @@ static inline bool htp_mm_hmx_solve_2d_params_core(
int * act_hvx_out,
size_t * vtcm_size_out
) {
- 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 bool is_w8a8 = htp_mm_kernel_is_hmx_w8a8(kernel_type);
+ const size_t m_align = is_w8a8 ? 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);
@@ -1005,13 +1148,15 @@ static inline bool htp_mm_hmx_solve_2d_params_core(
&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) * (is_w8a8 ? (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);
+ (is_w8a8 ? (HTP_MM_HMX_TILE_SIZE + (pipeline ? 2u : 1u) * 768u) : 0u) +
+ ((is_glu && is_w8a8) ? ((pipeline ? 4u : 2u) * HTP_MM_HMX_TILE_SIZE) : 0u) +
+ (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0u) +
+ (scale_size > 0 ? hex_align_up(scale_size, HTP_MM_HMX_TILE_SIZE) : 0u) +
+ (norm_size > 0 ? hex_align_up(norm_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;
}
@@ -1067,7 +1212,7 @@ static inline bool htp_mm_hmx_solve_2d_params_core(
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);
+ 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, scale_size, norm_size);
if (exact <= vtcm_budget) {
const size_t mblocks = (m_rows + mc - 1u) / mc;
size_t mc_tight = (mblocks > 1u)
@@ -1075,7 +1220,7 @@ static inline bool htp_mm_hmx_solve_2d_params_core(
: 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);
+ 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, scale_size, norm_size);
if (exact_tight <= vtcm_budget) {
mc = mc_tight;
exact = exact_tight;
@@ -1125,7 +1270,7 @@ static inline bool htp_mm_hmx_solve_2d_params_core(
return false;
}
-static inline bool htp_mm_hmx_solve_2d_params_ex(
+static inline bool htp_mm_hmx_solve_2d_params_ex_scaled(
int kernel_type,
int wtype,
uint32_t k,
@@ -1138,6 +1283,8 @@ static inline bool htp_mm_hmx_solve_2d_params_ex(
bool is_matmul_id,
uint32_t aligned_tile_size,
size_t bias_size,
+ size_t scale_size,
+ size_t norm_size,
size_t res_in_elem_size,
size_t res_out_elem_size,
size_t vtcm_budget,
@@ -1147,20 +1294,24 @@ static inline bool htp_mm_hmx_solve_2d_params_ex(
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,
+ n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, scale_size, norm_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(
+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,
@@ -1168,34 +1319,33 @@ static inline bool htp_mm_hmx_solve_2d_params_glu(
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);
+ 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, 0, 0, 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_int_hmx_solve_2d_params(
+static inline bool htp_mm_hmx_solve_2d_params_glu(
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 scale_size,
+ size_t norm_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);
+ 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, scale_size, norm_size, 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_hmx_solve_2d_params(
@@ -1217,7 +1367,7 @@ static inline bool htp_mm_hmx_solve_2d_params(
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,
+ return htp_mm_hmx_solve_2d_params_ex(HTP_MM_KERNEL_HMX_F16_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);
}
diff --git a/ggml/src/ggml-hexagon/htp/pad-ops.c b/ggml/src/ggml-hexagon/htp/pad-ops.c
index 61db555a9..d3bddcc89 100644
--- a/ggml/src/ggml-hexagon/htp/pad-ops.c
+++ b/ggml/src/ggml-hexagon/htp/pad-ops.c
@@ -378,15 +378,9 @@ static void pad_thread_circular(const htp_thread_t * th, unsigned int nth, unsig
}
int op_pad(struct htp_ops_context * octx) {
- const struct htp_tensor * src0 = octx->src[0];
- const struct htp_tensor * dst = octx->dst;
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];
@@ -441,9 +435,9 @@ int op_pad(struct htp_ops_context * octx) {
};
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],
+ (kparams->kernel_type == HTP_PAD_KERNEL_HVX_CIRCULAR) ? "-circ" : "",
+ octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3],
+ octx->dst->ne[0], octx->dst->ne[1], octx->dst->ne[2], octx->dst->ne[3],
lp0, rp0, lp1, rp1, lp2, rp2, lp3, rp3);
switch (kparams->kernel_type) {
diff --git a/ggml/src/ggml-hexagon/htp/repeat-ops.c b/ggml/src/ggml-hexagon/htp/repeat-ops.c
index 43326232b..ba55dffff 100644
--- a/ggml/src/ggml-hexagon/htp/repeat-ops.c
+++ b/ggml/src/ggml-hexagon/htp/repeat-ops.c
@@ -321,12 +321,6 @@ int op_repeat(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 && 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;
@@ -390,10 +384,10 @@ int op_repeat(struct htp_ops_context * octx) {
.dst_reps = kparams->dst_reps,
};
- FARF(HIGH, "repeat: (%ux%ux%ux%u) -> (%ux%ux%ux%u) nr=(%u,%u,%u,%u) pipe=%u\n",
+ FARF(HIGH, "repeat: (%ux%ux%ux%u) -> (%ux%ux%ux%u) nr0=%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->pipelined);
+ kparams->nr0, kparams->pipelined);
work_queue_func_t worker = kparams->pipelined ? repeat_thread : repeat_thread_tiled;
work_queue_run(octx->ctx->hvx_queue, worker, &rctx, n_hvx);
diff --git a/ggml/src/ggml-hexagon/htp/repeat-ops.h b/ggml/src/ggml-hexagon/htp/repeat-ops.h
index 7fcb49470..8efef83fd 100644
--- a/ggml/src/ggml-hexagon/htp/repeat-ops.h
+++ b/ggml/src/ggml-hexagon/htp/repeat-ops.h
@@ -39,9 +39,6 @@ static inline void htp_repeat_vtcm_layout_build(
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;
diff --git a/ggml/src/ggml-hexagon/htp/roll-ops.c b/ggml/src/ggml-hexagon/htp/roll-ops.c
index 6279985ba..b131dfaa0 100644
--- a/ggml/src/ggml-hexagon/htp/roll-ops.c
+++ b/ggml/src/ggml-hexagon/htp/roll-ops.c
@@ -422,15 +422,5 @@ static int execute_op_roll(struct htp_ops_context * octx) {
}
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:
- case HTP_TYPE_F16:
- return execute_op_roll(octx);
-
- default:
- return HTP_STATUS_NO_SUPPORT;
- }
+ return execute_op_roll(octx);
}
diff --git a/ggml/src/ggml-hexagon/htp/set-rows-ops.c b/ggml/src/ggml-hexagon/htp/set-rows-ops.c
index ec6db870b..87db14e68 100644
--- a/ggml/src/ggml-hexagon/htp/set-rows-ops.c
+++ b/ggml/src/ggml-hexagon/htp/set-rows-ops.c
@@ -56,7 +56,6 @@ typedef void (*set_rows_compute_fn_t)(void * restrict dst, const void * restrict
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;
@@ -267,7 +266,6 @@ int op_set_rows(struct htp_ops_context * octx) {
struct set_rows_context srctx;
srctx.octx = octx;
- srctx.kparams = kparams;
srctx.task_start = task_start;
srctx.tasks = tasks;
srctx.tasks_per_hvx = fastdiv(tasks + n_hvx - 1, &octx->n_hvx_div);
diff --git a/ggml/src/ggml-hexagon/htp/softmax-ops.c b/ggml/src/ggml-hexagon/htp/softmax-ops.c
index 44293de06..faf464de6 100644
--- a/ggml/src/ggml-hexagon/htp/softmax-ops.c
+++ b/ggml/src/ggml-hexagon/htp/softmax-ops.c
@@ -729,10 +729,6 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
return HTP_STATUS_INVAL_PARAMS;
}
- if (kparams->kernel_type >= HTP_SOFTMAX_KERNEL_COUNT) {
- return HTP_STATUS_INVAL_PARAMS;
- }
-
if (octx->ctx->vtcm_size < (size_t) kparams->vtcm_size) {
FARF(ERROR, "%s : current VTCM reservation %zu is too small, needed %u\n",
op_type, octx->ctx->vtcm_size, kparams->vtcm_size);
@@ -761,33 +757,39 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
uint8_t * const vtcm_base = (uint8_t *) octx->ctx->vtcm_base;
+ const bool src0_f16 = (kparams->flags & HTP_SOFTMAX_FLAG_SRC0_F16) != 0;
+ const bool dst_f16 = (kparams->flags & HTP_SOFTMAX_FLAG_DST_F16) != 0;
+ const bool use_src1 = (kparams->flags & HTP_SOFTMAX_FLAG_USE_SRC1) != 0;
+ const bool use_f16 = (kparams->flags & HTP_SOFTMAX_FLAG_SRC1_F16) != 0;
+ const bool use_src2 = (kparams->flags & HTP_SOFTMAX_FLAG_USE_SRC2) != 0;
+
struct htp_softmax_vtcm_layout layout;
htp_softmax_vtcm_layout_build(&layout,
src0->ne[0],
- kparams->use_src1 ? octx->src[1]->ne[0] : 0,
+ 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,
+ src0_f16,
+ dst_f16,
+ use_src1,
+ use_f16,
+ use_src2,
kparams->n_hvx);
struct htp_softmax_context smctx = {
.octx = octx,
.kparams = kparams,
.prep = (void *) softmax_prep_kernels[kparams->kernel_type],
- .softmax = (void *) softmax_kernels[kparams->dst_f16 != 0][kparams->use_src2 != 0],
+ .softmax = (void *) softmax_kernels[dst_f16][use_src2],
.data_src0 = src0->data,
- .data_src1 = kparams->use_src1 ? octx->src[1]->data : 0,
+ .data_src1 = use_src1 ? octx->src[1]->data : 0,
.data_dst = dst->data,
.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_src1 = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, vtcm_base, layout.off_src1, use_src1),
+ .vtcm_work = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, vtcm_base, layout.off_work, dst_f16),
+ .vtcm_src2 = VTCM_LAYOUT_PTR_OPTIONAL(float, vtcm_base, layout.off_src2, 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,
@@ -802,10 +804,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,
+ .src0_f16 = src0_f16,
+ .dst_f16 = dst_f16,
+ .use_f16 = use_f16,
+ .use_src2 = use_src2,
.n_head = kparams->n_head,
.n_head_log2 = kparams->n_head_log2,
@@ -825,21 +827,18 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) {
.nrows = nrows,
};
- if (kparams->max_bias > 0.0f && kparams->use_src1) {
- if (kparams->n_head > 512) {
- return HTP_STATUS_INVAL_PARAMS;
- }
+ if (kparams->max_bias > 0.0f && use_src1) {
softmax_init_alibi_slopes(smctx.slopes, kparams->n_head, kparams->n_head_log2, kparams->m0, kparams->m1);
}
- if (kparams->use_src2) {
+ if (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 : softmax_thread;
+ work_queue_func_t task_func = use_src1 ? softmax_thread_mask : softmax_thread;
work_queue_run(octx->ctx->hvx_queue, task_func, &smctx, n_hvx);
return HTP_STATUS_OK;
diff --git a/ggml/src/ggml-hexagon/htp/softmax-ops.h b/ggml/src/ggml-hexagon/htp/softmax-ops.h
index 3ca9ff315..84c83292b 100644
--- a/ggml/src/ggml-hexagon/htp/softmax-ops.h
+++ b/ggml/src/ggml-hexagon/htp/softmax-ops.h
@@ -19,18 +19,22 @@ enum htp_softmax_kernel_type {
HTP_SOFTMAX_KERNEL_COUNT,
};
+enum htp_softmax_flags {
+ HTP_SOFTMAX_FLAG_SRC0_F16 = (1u << 0),
+ HTP_SOFTMAX_FLAG_DST_F16 = (1u << 1),
+ HTP_SOFTMAX_FLAG_USE_SRC1 = (1u << 2),
+ HTP_SOFTMAX_FLAG_SRC1_F16 = (1u << 3),
+ HTP_SOFTMAX_FLAG_USE_SRC2 = (1u << 4),
+};
+
struct htp_softmax_kernel_params {
uint8_t kernel_type;
- uint8_t src0_f16;
- uint8_t dst_f16;
- uint8_t use_src2;
+ uint8_t flags; // bitmask of enum htp_softmax_flags
uint32_t n_hvx;
uint32_t vtcm_size;
uint32_t n_head;
uint32_t n_head_log2;
- uint32_t use_src1;
- uint32_t use_f16;
float scale;
float max_bias;
diff --git a/ggml/src/ggml-hexagon/htp/solve-tri-ops.c b/ggml/src/ggml-hexagon/htp/solve-tri-ops.c
index 082db4043..f49bf7f77 100644
--- a/ggml/src/ggml-hexagon/htp/solve-tri-ops.c
+++ b/ggml/src/ggml-hexagon/htp/solve-tri-ops.c
@@ -356,19 +356,14 @@ int op_solve_tri(struct htp_ops_context * octx) {
const struct htp_tensor * src1 = octx->src[1];
const struct htp_tensor * dst = octx->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 bool batched = (kparams->flags & HTP_SOLVE_TRI_FLAG_BATCHED) != 0;
+ const uint32_t a_full = (kparams->flags & HTP_SOLVE_TRI_FLAG_A_FULL) ? 1 : 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;
@@ -400,7 +395,7 @@ int op_solve_tri(struct htp_ops_context * octx) {
const uint32_t n_hvx = octx->n_hvx;
struct htp_solve_tri_vtcm_layout layout;
- htp_solve_tri_vtcm_layout_build(&layout, src0->ne[0], kparams->a_full, n_hvx);
+ htp_solve_tri_vtcm_layout_build(&layout, src0->ne[0], 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;
@@ -421,7 +416,7 @@ int op_solve_tri(struct htp_ops_context * octx) {
.job_start = job_start,
.k_chunks = k_chunks,
.col_block = col_block,
- .a_full = kparams->a_full,
+ .a_full = a_full,
.a_f16 = a_f16,
.b_f16 = b_f16,
.x_f16 = x_f16,
diff --git a/ggml/src/ggml-hexagon/htp/solve-tri-ops.h b/ggml/src/ggml-hexagon/htp/solve-tri-ops.h
index 965545ad6..4cc61fa1a 100644
--- a/ggml/src/ggml-hexagon/htp/solve-tri-ops.h
+++ b/ggml/src/ggml-hexagon/htp/solve-tri-ops.h
@@ -33,14 +33,18 @@ static inline void htp_solve_tri_vtcm_layout_build(
L->total_bytes = off;
}
+enum htp_solve_tri_flags {
+ HTP_SOLVE_TRI_FLAG_BATCHED = (1u << 0),
+ HTP_SOLVE_TRI_FLAG_A_FULL = (1u << 1),
+};
+
struct htp_solve_tri_kernel_params {
uint32_t n_hvx;
uint32_t total_batches;
uint32_t total_jobs;
uint32_t k_chunks;
uint32_t col_block;
- uint32_t batched;
- uint32_t a_full;
+ uint32_t flags; // bitmask of enum htp_solve_tri_flags
uint32_t vtcm_size;
struct fastdiv_values div_ne02;
diff --git a/ggml/src/ggml-hexagon/htp/ssm-conv.c b/ggml/src/ggml-hexagon/htp/ssm-conv.c
index a7a511ba7..383c3ba74 100644
--- a/ggml/src/ggml-hexagon/htp/ssm-conv.c
+++ b/ggml/src/ggml-hexagon/htp/ssm-conv.c
@@ -1550,8 +1550,10 @@ int op_ssm_conv_f32(struct htp_ops_context * octx) {
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);
+ const bool token_major = (kparams->flags & HTP_SSM_CONV_FLAG_TOKEN_MAJOR) != 0;
+
struct htp_ssm_conv_vtcm_layout L;
- if (kparams->token_major) {
+ if (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);
@@ -1564,9 +1566,9 @@ int op_ssm_conv_f32(struct htp_ops_context * octx) {
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;
+ const bool apply_silu = (kparams->flags & HTP_SSM_CONV_FLAG_SILU) != 0;
- if (kparams->token_major) {
+ if (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);
diff --git a/ggml/src/ggml-hexagon/htp/ssm-conv.h b/ggml/src/ggml-hexagon/htp/ssm-conv.h
index 97a49c59f..f3f8aa4b9 100644
--- a/ggml/src/ggml-hexagon/htp/ssm-conv.h
+++ b/ggml/src/ggml-hexagon/htp/ssm-conv.h
@@ -8,6 +8,11 @@
#include "htp-ops.h"
#include "htp-vtcm.h"
+enum htp_ssm_conv_flags {
+ HTP_SSM_CONV_FLAG_SILU = (1u << 0),
+ HTP_SSM_CONV_FLAG_TOKEN_MAJOR = (1u << 1),
+};
+
struct htp_ssm_conv_kernel_params {
uint32_t n_hvx;
uint32_t d_conv;
@@ -17,8 +22,7 @@ struct htp_ssm_conv_kernel_params {
uint32_t d_inner_tile;
uint32_t vtcm_size;
- uint32_t silu;
- uint32_t token_major;
+ uint32_t flags; // bitmask of enum htp_ssm_conv_flags
uint32_t n_t_tile;
uint32_t n_t_blocks;
diff --git a/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c b/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c
index 65892572c..e6a8eeeb3 100644
--- a/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c
+++ b/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c
@@ -4,7 +4,7 @@
#include "hvx-exp.h"
#include "hvx-utils.h"
-#include "hmx-fa-kernels.h"
+#include "hmx-fa-fp16-kernels.h"
#include "hmx-queue.h"
#include "hmx-utils.h"
diff --git a/ggml/src/ggml-hexagon/htp/sum-rows-ops.c b/ggml/src/ggml-hexagon/htp/sum-rows-ops.c
index c226c1cea..14daf7b17 100644
--- a/ggml/src/ggml-hexagon/htp/sum-rows-ops.c
+++ b/ggml/src/ggml-hexagon/htp/sum-rows-ops.c
@@ -338,11 +338,6 @@ int op_sum_rows(struct htp_ops_context * octx) {
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;
- }
-
const struct htp_sum_rows_kernel_params * kparams =
(const struct htp_sum_rows_kernel_params *) octx->kernel_params;
@@ -531,11 +526,6 @@ 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 && src0->type != HTP_TYPE_F16) ||
- (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) {
- return HTP_STATUS_NO_SUPPORT;
- }
-
const struct htp_sum_rows_kernel_params * kparams =
(const struct htp_sum_rows_kernel_params *) octx->kernel_params;
@@ -932,10 +922,6 @@ 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 && 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;
diff --git a/ggml/src/ggml-hexagon/htp/timestep-ops.c b/ggml/src/ggml-hexagon/htp/timestep-ops.c
index 4835df3bb..aed51b93f 100644
--- a/ggml/src/ggml-hexagon/htp/timestep-ops.c
+++ b/ggml/src/ggml-hexagon/htp/timestep-ops.c
@@ -203,7 +203,7 @@ int op_timestep_embedding(struct htp_ops_context * octx) {
}
FARF(HIGH, "timestep-embedding: %u timesteps dim %u max-period %d split-%s n-hvx %u chunk-rows %u\n",
- kparams->n_rows, kparams->dim, max_period, kparams->split_cols ? "cols" : "rows", kparams->n_hvx, kparams->chunk_rows);
+ kparams->n_rows, kparams->dim, octx->op_params[1], kparams->split_cols ? "cols" : "rows", kparams->n_hvx, kparams->chunk_rows);
work_queue_run(octx->ctx->hvx_queue, timestep_thread, &tctx, kparams->n_hvx);
diff --git a/ggml/src/ggml-hexagon/htp/unary-ops.c b/ggml/src/ggml-hexagon/htp/unary-ops.c
index 258cafaff..223035fb6 100644
--- a/ggml/src/ggml-hexagon/htp/unary-ops.c
+++ b/ggml/src/ggml-hexagon/htp/unary-ops.c
@@ -3250,9 +3250,9 @@ static void unary_thread_row_block(const htp_thread_t * th, unsigned int nth, un
.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,
+ .src0_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
+ .block_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
+ .src0_slice_dma = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_SLICE_DMA) != 0,
.ir = src0_start_row,
.ir_end = src0_end_row,
};
@@ -3297,9 +3297,9 @@ static void unary_thread_rms_norm_mul_bc(const htp_thread_t * th, unsigned int n
.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,
+ .src0_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
+ .block_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
+ .src0_slice_dma = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_SLICE_DMA) != 0,
.ir = src0_start_row,
.ir_end = src0_end_row,
};
@@ -3341,9 +3341,9 @@ static void unary_thread_rms_norm_mul(const htp_thread_t * th, unsigned int nth,
.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_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
+ .src1_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC1_CONTIG) != 0,
+ .block_contig = (uctx->kparams->flags & (HTP_UNARY_FLAG_SRC0_CONTIG | HTP_UNARY_FLAG_SRC1_CONTIG)) == (HTP_UNARY_FLAG_SRC0_CONTIG | HTP_UNARY_FLAG_SRC1_CONTIG),
.src0_slice_dma = false,
.ir = src0_start_row,
.ir_end = src0_end_row,
@@ -3394,8 +3394,8 @@ static void unary_thread_rms_norm_mul_add(const htp_thread_t * th, unsigned int
.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_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
+ .block_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
.src0_slice_dma = false,
.ir = src0_start_row,
.ir_end = src0_end_row,
@@ -3463,8 +3463,8 @@ static void unary_thread_tiled_rms_norm(const htp_thread_t * th, unsigned int nt
const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012;
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;
+ const bool src0_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0;
+ const bool src1_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC1_CONTIG) != 0;
float epsilon = 0.f;
float scale = 0.f;
@@ -3741,7 +3741,7 @@ static void unary_thread_tiled(const htp_thread_t * th, unsigned int nth, unsign
.tile_in_row = 0,
.i01 = 0,
.tri_ttype = 0,
- .src0_contig = uctx->kparams->src0_contig,
+ .src0_contig = (uctx->kparams->flags & HTP_UNARY_FLAG_SRC0_CONTIG) != 0,
};
dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf,
@@ -3873,7 +3873,7 @@ static int execute_op_unary(struct htp_ops_context * octx) {
const uint32_t col_tile = kparams->col_tile;
- bool broadcast_src1 = kparams->broadcast_src1;
+ bool broadcast_src1 = (kparams->flags & HTP_UNARY_FLAG_BCAST_SRC1) != 0;
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) {
@@ -3976,7 +3976,7 @@ static int execute_op_unary(struct htp_ops_context * octx) {
break;
}
- const bool has_scale_bias = (kparams->has_scale_bias != 0);
+ const bool has_scale_bias = (kparams->flags & HTP_UNARY_FLAG_SCALE_BIAS) != 0;
if (!compute_func && is_f16) {
switch (octx->op) {
diff --git a/ggml/src/ggml-hexagon/htp/unary-ops.h b/ggml/src/ggml-hexagon/htp/unary-ops.h
index da11e3d76..0dda17b0d 100644
--- a/ggml/src/ggml-hexagon/htp/unary-ops.h
+++ b/ggml/src/ggml-hexagon/htp/unary-ops.h
@@ -6,21 +6,24 @@
#include "htp-ops.h"
#include "htp-vtcm.h"
+enum htp_unary_flags {
+ HTP_UNARY_FLAG_BCAST_SRC1 = (1u << 0),
+ HTP_UNARY_FLAG_SRC0_CONTIG = (1u << 1),
+ HTP_UNARY_FLAG_SRC1_CONTIG = (1u << 2),
+ HTP_UNARY_FLAG_SRC0_SLICE_DMA = (1u << 3),
+ HTP_UNARY_FLAG_SCALE_BIAS = (1u << 4),
+};
+
// Op-specific struct for precomputed unary params
struct htp_unary_kernel_params {
uint32_t n_hvx;
uint32_t col_tile;
uint32_t block;
- uint32_t broadcast_src1;
-
- uint32_t src0_contig;
- uint32_t src1_contig;
- uint32_t src0_slice_dma;
+ uint32_t flags; // bitmask of enum htp_unary_flags
uint32_t vtcm_size;
uint32_t tiles_per_row;
- uint32_t has_scale_bias;
float in_scale;
float in_bias;
float out_scale;
@@ -30,7 +33,6 @@ struct htp_unary_kernel_params {
struct fastdiv_values div_ne01;
struct fastdiv_values div_ne02;
struct fastdiv_values div_ne012;
- struct fastdiv_values div_tpr;
};
#if defined(__cplusplus)
diff --git a/ggml/src/ggml-hexagon/htp/upscale-ops.c b/ggml/src/ggml-hexagon/htp/upscale-ops.c
index fe68a70d7..060d3f66d 100644
--- a/ggml/src/ggml-hexagon/htp/upscale-ops.c
+++ b/ggml/src/ggml-hexagon/htp/upscale-ops.c
@@ -221,7 +221,7 @@ static inline void get_src_y_window(
const int32_t y1 = ly[last_oy].y[3];
*out_src_y_start = (uint32_t) y0;
*out_src_y_count = (uint32_t) (y1 - y0 + 1);
- } else if (p->antialias) {
+ } else if (p->flags & HTP_UPSCALE_FLAG_ANTIALIAS) {
const struct upscale_antialias_y * ly = (const struct upscale_antialias_y *) lut_y;
const int32_t y0 = ly[dst_y_start].y_min;
const int32_t y1 = ly[last_oy].y_max;
@@ -892,7 +892,7 @@ int op_upscale(struct htp_ops_context * octx) {
if (p->mode == HTP_UPSCALE_MODE_BICUBIC) {
lut_x_size = hex_round_up(dst_x * sizeof(struct upscale_bicubic_x), 128);
elem_y_sz = sizeof(struct upscale_bicubic_y);
- } else if (p->antialias) {
+ } else if (p->flags & HTP_UPSCALE_FLAG_ANTIALIAS) {
lut_x_size = hex_round_up(dst_x * sizeof(struct upscale_antialias_x), 128);
elem_y_sz = sizeof(struct upscale_antialias_y);
} else if (p->mode == HTP_UPSCALE_MODE_BILINEAR) {
@@ -918,7 +918,7 @@ int op_upscale(struct htp_ops_context * octx) {
upscale_init_luts_nearest((uint32_t *) lut_x, (uint32_t *) lut_y, src0, dst, p);
} else if (p->mode == HTP_UPSCALE_MODE_BICUBIC) {
upscale_init_luts_bicubic((struct upscale_bicubic_x *) lut_x, (struct upscale_bicubic_y *) lut_y, src0, dst, p);
- } else if (p->antialias) {
+ } else if (p->flags & HTP_UPSCALE_FLAG_ANTIALIAS) {
upscale_init_luts_antialias((struct upscale_antialias_x *) lut_x, (struct upscale_antialias_y *) lut_y, src0, dst, p);
} else {
upscale_init_luts_bilinear((struct upscale_bilinear_x_chunk *) lut_x, (struct upscale_bilinear_y *) lut_y, src0, dst, p);
diff --git a/ggml/src/ggml-hexagon/htp/upscale-ops.h b/ggml/src/ggml-hexagon/htp/upscale-ops.h
index b98d6cadb..f85e8a2a1 100644
--- a/ggml/src/ggml-hexagon/htp/upscale-ops.h
+++ b/ggml/src/ggml-hexagon/htp/upscale-ops.h
@@ -26,11 +26,15 @@ enum htp_upscale_kernel_type {
HTP_UPSCALE_KERNEL_BICUBIC = 6,
};
+enum htp_upscale_flags {
+ HTP_UPSCALE_FLAG_ALIGN_CORNERS = (1u << 0),
+ HTP_UPSCALE_FLAG_ANTIALIAS = (1u << 1),
+};
+
struct htp_upscale_kernel_params {
uint8_t kernel_type;
uint8_t mode;
- uint8_t align_corners;
- uint8_t antialias;
+ uint8_t flags; // bitmask of enum htp_upscale_flags
float inv_sf0;
float inv_sf1;
diff --git a/scripts/snapdragon/run.py b/scripts/snapdragon/run.py
index 88b70ef96..2e6788807 100755
--- a/scripts/snapdragon/run.py
+++ b/scripts/snapdragon/run.py
@@ -34,6 +34,7 @@ MANAGED_ENV_NAMES = (
"GGML_HEXAGON_VTCM_SIZE",
"GGML_HEXAGON_MBUF",
"GGML_HEXAGON_MM_SELECT",
+ "GGML_HEXAGON_MM_FWHT",
"GGML_HEXAGON_FA_SELECT",
"GGML_HEXAGON_FA_SPLIT",
"GGML_HEXAGON_LI_SELECT",
@@ -222,7 +223,8 @@ def main():
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) 4:HMX-W8A8,3:HMX-W8A8-hybrid,2:HMX,1:HVX,0:disable")
+ parser.add_argument("--hex-mm-select", help="Select MUL_MAT and MUL_MAT_ID kernel (GGML_HEXAGON_MM_SELECT) 3:HMX-W8A8,2:HMX,1:HVX,0:disable")
+ parser.add_argument("--hex-mm-fwht", help="Enable (1) or disable (0) online block-32 FWHT rotation in W8A8 HMX matmul (GGML_HEXAGON_MM_FWHT)")
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")
@@ -380,6 +382,7 @@ def main():
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_MM_FWHT", args.hex_mm_fwht)
set_env("GGML_HEXAGON_FA_SELECT", args.hex_fa_select)
set_env("GGML_HEXAGON_FA_SPLIT", args.hex_fa_split)
set_env("GGML_HEXAGON_LI_SELECT", args.hex_li_select)