diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/CMakeLists.txt b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/CMakeLists.txt index b45aa294a..acdd68ee4 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/CMakeLists.txt +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/CMakeLists.txt @@ -60,6 +60,8 @@ file(GLOB SOURCES "*.cpp" "decoder/qwen3_asr_cpu_decoder.cpp" "audio/qwen3_asr_audio_encoder.cpp" + "audio/qwen3_asr_audio_gemm_npu.cpp" + "prefill/qwen3_asr_prefill_npu.cpp" ) file(GLOB HEADERS "../../include/*.hpp" "*.hpp") diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/Makefile b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/Makefile index 191d80846..a095b0c57 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/Makefile +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/Makefile @@ -92,6 +92,8 @@ SOURCES += $(wildcard ../gemm/*.cpp) SOURCES += $(wildcard ../lm_head/*.cpp) SOURCES += decoder/qwen3_asr_cpu_decoder.cpp SOURCES += audio/qwen3_asr_audio_encoder.cpp +SOURCES += audio/qwen3_asr_audio_gemm_npu.cpp +SOURCES += prefill/qwen3_asr_prefill_npu.cpp HEADERS = $(wildcard *.hpp) HEADERS += $(wildcard ../include/*.hpp) @@ -105,14 +107,16 @@ directories: mkdir -p $(BIN_DIR) mkdir -p $(LIB_DIR) +# The prompt attention (modules/mha.hpp) comes from libmha.so, as in the Windows build: a copy compiled in here would +# export MHA's symbols a second time (see the note in ../qwen3_5_omni/Makefile) $(TARGET): $(SOURCES) - $(CXX) $(LIB_FLAGS) -o $@ $^ $(LDFLAGS) + $(CXX) $(LIB_FLAGS) -o $@ $^ -lmha $(LDFLAGS) # Engine-level harness (tools/qwen3_asr_engine_run.cpp): CPU prefill + NPU decode against the goldens harness: all $(CXX) $(CXX_FLAGS) -Idecoder -o $(BIN_DIR)/qwen3_asr_engine_run tools/qwen3_asr_engine_run.cpp \ - -L$(LIB_DIR) -L$(FINAL_LIB_DIR) -lqwen3_asr_npu -lq4_npu_eXpress $(LDFLAGS) \ + -L$(LIB_DIR) -L$(FINAL_LIB_DIR) -lqwen3_asr_npu -lq4_npu_eXpress -lmha $(LDFLAGS) \ -Wl,-rpath,'$$ORIGIN/../lib' -Wl,-rpath,'$$ORIGIN/../../lib' clean: diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/README.md b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/README.md index 31847a4a0..21b69cc46 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/README.md +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/README.md @@ -13,13 +13,25 @@ a 24-layer audio encoder (0.32 B) and a Qwen3-1.7B text decoder. Public header: | Stage | Where | Code | |---|---|---| | log-mel (128 bins, hop 160) | host, in FastFlowLM (the wrapper) | `FastFlowLM/src/common/AutoModel/modeling_qwen3_asr*.cpp` | -| audio encoder (conv x3, 24 pre-LN layers, 104-token window attention, projector) | host, AVX-512, BF16 rounding points of the reference | `audio/` | -| prompt prefill (system + audio tokens + text so far) | host, AVX-512, Q8_0 weights read in place from `model.q4nx` | `decoder/` | -| decode (28 layers + tied lm_head) | NPU, `generic_decoding_layer` model type `QWEN3_ASR_1_7B` (Q8_0, `QMM_LIMB_PRECISION 1`) | `qwen3_asr_npu*.{hpp,cpp}` | - -Why the prefill is on the host: speech prompts are short (about 100-400 tokens) and the NPU prefill has a floor of about a second -below ~300 tokens, so the CPU is faster, and it needs no prefill kernels (the Q8_0 prefill dequant path of the Qwen3 engine is not -used by any model). The prefill hands its K/V rows to the NPU's striped KV cache with `kv_rows_copy`. +| audio encoder (conv x3, 24 pre-LN layers, 104-token window attention, projector) | matrix products (conv2/3, conv_out, qkv, o, fc1, fc2, proj1/2; ~99 % of the FLOPs) on the NPU (`audio_gemm.xclbin`, `FLM_Xclbin/bfp16_gemm`); conv1, LayerNorm, window attention, residuals on the host (AVX-512), BF16 rounding points of the reference | `audio/` | +| prompt prefill (system + audio tokens + text so far) | matrix products (q/k/v, o, up/gate, down) on the NPU (`prefill.xclbin`, `FLM_Xclbin/dequant_mm_mix_bfp16`), reading the mixed decode weights in place; attention on the NPU too for prompts of about 384 tokens or more (the shared prefill attention, in `prefill.xclbin`'s context through `r2t2.switches`; without that file `attn.xclbin` from about 1024 tokens); norms, RoPE, shorter attention, the KV cache and the LM head on the host (AVX-512) | `decoder/`, `prefill/` | +| decode (28 layers + tied lm_head) | NPU, `generic_decoding_layer` model type `QWEN3_ASR_1_7B_MIX` (Q4_1 + Q8_0) | `qwen3_asr_npu*.{hpp,cpp}` | + +The prefill is the CPU decoder (`decoder/`) with its matrix products handed to `prefill/` (the `projections` interface): one +32-core call per product and layer, in jobs of up to 512 rows; the host packs the activations as block float and unpacks the bf16 +results while the NPU runs the next job. The attention moves to the NPU when its work reaches that of a 384-row prompt. With +`r2t2.switches` (`FLM_Xclbin/r2t2_switches`, `prefill/qwen3_asr_launch.hpp`) it runs inside `prefill.xclbin`'s hardware +context: per layer one submission of the mm cold start, the control-packet switch to the attention, the attention and the +switch back, under the system-wide lock d3's switches take. Without the file it runs on `attn.xclbin` in a context of its +own from a 1024-row prompt: switching between two contexts costs about 2.5 ms twice per layer, more than the CPU attention +of shorter prompts. +The prefill hands its K/V rows to the NPU's striped KV cache with `kv_rows_copy`. + +Every NPU call of the engine (decode, prefill products, encoder products) takes one lock (`npu_mu`): the next step's work runs +in the background during the decode, and a run of one hw_context while the decode runlist of another is in flight never +completes. Streaming: that background job encodes the next step's open window on the host (the encoder keeps a host copy of its +weights, 635 MB), hidden under the NPU decode; on the NPU it would wait for the decode, and so would the step. Offline: it +encodes and prefills the next ~60 s piece on the NPU. ## Weights: why Q8_0 @@ -37,14 +49,28 @@ Package: `FLM_Q4NX_Converter -f qwen3-asr` (`configs/qwen3_asr.json`): `model.q4 |---|---| | English WER (120 clips) | 2.98 vs 2.89 (+0.09, 95% CI -0.09 .. +0.27) | | Chinese CER (60 clips) | 8.96 vs 8.96 (+0.00) | -| decode | 35 ms/token (28 layers + head) | +| decode | 26-29 ms/token with the mixed package (28 layers + head) | +| prompt prefill, decoder (NPU products) | 85 tokens 77-83 ms (host 121), 150 tokens 115 ms, 904 tokens 485 ms (host 1069), 2048 tokens 931 ms (host 2589; NPU attention from 1024 tokens) | +| prompt prefill, decoder, with `r2t2.switches` | 512 tokens 209 ms (`attn.xclbin` 346, host attention 233), 2048 tokens 815 ms (919, 1334) | | encoder (host) | 21-35 ms per second of audio | +| encoder (NPU products) | 6.3 ms per second of audio on a 68 s clip (host 11), 8-10 ms/s at 7-18 s; 1 s clips ~44 ms/s (host ~21: the weights are read once per layer) | | prefill + encoder, median clip (~7 s) | about 0.85 s | +NPU encoder, mixed package, 180 clips: English WER 2.76, Chinese CER 6.32 (host encoder on the same build: 2.85 / 5.88; the +paired 95% CI of the Chinese set is about ±5 points, so the two are not told apart). The NPU products keep A and W at bf16 +precision: each is split into its bfp16 value and the scaled rest (more rows of A, more columns of W in the same call); plain bfp16 +products drift the conv stack on quiet input. + ## Debug switches `QWEN3_ASR_NPU_LAYERS=n` runs only n decoder layers on the NPU (bisecting a hang). `QWEN3_ASR_CPU_DECODE=1` decodes on the host -(accuracy A/B of the NPU decode kernel). `TRACE_STEPS=1` makes `tools/qwen3_asr_engine_run` print the top-5 logits of the first steps. +(accuracy A/B of the NPU decode kernel). `QWEN3_ASR_CPU_ENCODER=1` runs the whole audio encoder on the host (also the case +when the package has no `audio_gemm.xclbin`); `QWEN3_ASR_NPU_STREAM_ENCODE=1` runs the streaming background encode on the NPU +as well (no host copy). `QWEN3_ASR_CPU_PREFILL=1` prefills the prompt on the host (also without +`prefill.xclbin`); `QWEN3_ASR_CPU_ATTENTION=1` keeps only the prompt attention there (also without `r2t2.switches` and +`attn.xclbin`); `QWEN3_ASR_NO_SWITCH=1` ignores `r2t2.switches` (attention on `attn.xclbin`); +`QWEN3_ASR_NPU_ATTENTION_MIN=rows` moves the NPU attention threshold (0: always). `QWEN3_ASR_PROF=1` prints the prefill's +matmul / attention / rest split and the pack / NPU / unpack times of each NPU call. `QWEN3_ASR_GEMM_PROF=1` prints pack / NPU / unpack times of each encoder product. `TRACE_STEPS=1` makes `tools/qwen3_asr_engine_run` print the top-5 logits of the first steps. ## Test @@ -54,6 +80,7 @@ make harness # libqwen3_asr_npu.so + tools/qwen3_asr_engine build/qwen3_asr_npu/bin/qwen3_asr_engine_run ... [--mel] [--out-ids f] cd decoder && make && ./test_decoder_goldens ... # CPU decoder alone, no NPU cd audio/test && make run # CPU encoder alone, no NPU +cd audio/test && make run_npu XCLBIN= WEIGHTS=... GOLDENS=... # the encoder with its products on the NPU ``` ## Gotchas diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/README.md b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/README.md index 46c36f616..b1e63b9c6 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/README.md +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/README.md @@ -3,10 +3,12 @@ Portions of this file consist of AI-generated content. --> -# Qwen3-ASR / Confucius4-R2T2 audio encoder (host reference) +# Qwen3-ASR / Confucius4-R2T2 audio encoder -`qwen3_asr_audio_encoder` computes, on the CPU (AVX-512 + OpenMP), what the HF `Qwen3ASRAudioEncoder` computes, with the -window mask applied. No NPU/XRT dependency. It is the CPU path of the future NPU encoder and the reference for it. +`qwen3_asr_audio_encoder` computes what the HF `Qwen3ASRAudioEncoder` computes, with the window mask applied. Given a +`qwen3_asr_audio_gemm` backend (`qwen3_asr_audio_gemm_npu`: `audio_gemm.xclbin`, built from `FLM_Xclbin/bfp16_gemm`), its matrix +products run there; without one (`nullptr`) everything runs on the CPU (AVX-512 + OpenMP), which needs no NPU/XRT and is the +reference for the NPU path. ``` mel [frames][128] fp32 @@ -79,13 +81,19 @@ bug (on zh_0048 the reference itself differs from fp32 with min cosine 0.95). Th **Task level** (`run/enc_e2e.py`): C++ encoder output fed to the reference decoder: 42 of 43 golden clips give a byte-identical transcript; the one difference is only the language label (`English` vs `None`) on a Chinese clip (identical text). -## Seams for the NPU port - -`conv_front`, `add_pos`, `encoder_layer`, `post` are public and operate on `[rows][cols]` fp32-held-bf16 activations. For the NPU: -- all matmuls (conv as im2col GEMM: M=800/208/13 x K=4320/4320/7680 x N=480/480/1024; q/k/v/out 1024x1024; fc1 1024->4096, fc2 4096->1024; - proj1/2) go through the existing generic MM kernel (weights are already in the audio MM tile layout, K 512 / N 64, and must NOT be un-permuted there); -- window attention (16 heads x 64, <= 104 tokens, no mask inside a window) needs a window-attention kernel (the omni `window_attention.xclbin` path: not shipped, see - FLM_Xclbin/kernel_assignment.md) or stays on the host (it is ~1 % of the FLOPs); -- LayerNorm, GELU, position add and residuals stay on the host (as in the omni embedder). +## The NPU path + +- Products on the NPU (`qwen3_asr_audio_gemm_npu`): conv2/conv3 as im2col GEMMs (K = 4320, N = 480; the packer gathers the im2col rows + itself), conv_out (K = 7680), q/k/v fused (N = 3072), out_proj, fc1, fc2, proj1, proj2. All chunks of a call share one conv product per + conv (8 chunks per group). The weights are packed once at load (bfp16, 9 B per 8 values) into device buffers; bias is added on + the cores, GELU on the host once the parts below are summed. +- Precision: every product keeps A and W at bf16 precision. A = A_hi + A_lo / 256 with A_hi its bfp16 value: the rest goes as more rows + of the same call (the weights are read once for both); W likewise as more output columns. The host adds the parts and rounds to bf16. + Plain bfp16 products drift the conv stack on quiet input (syn_quiet_onset fails); NPU vs fp64 relL2 is ~0.0023 with both splits + (bf16 floor 0.0017, plain bfp16 0.0092). +- Host: conv1 (K = 9), LayerNorm (statistics in double: fp32 sums fail syn_quiet_onset), window attention (16 heads x 64, <= 104 tokens, + ~1 % of the FLOPs), GELU, position add, residuals. - Streaming: a window of 104 tokens never changes once complete (same mel), so completed windows can be cached; the mel global-max clamp is the only - thing that changes earlier frames (see plan section 12). + thing that changes earlier frames (`conv_cache`; `test/conv_cache_test`). + +`make run_npu XCLBIN=` runs the gate above with the NPU path; all 8 default clips pass (cos >= 0.99963, relL2 <= 0.028). diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.cpp index bb5e30ca8..3b14dd4fd 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.cpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.cpp @@ -14,12 +14,16 @@ #include #include #include +#include #include #include #include "nlohmann/json.hpp" #include "../file_map.hpp" #include "../omp_threads.hpp" +#include "qwen3_asr_audio_simd.hpp" + +namespace simd = qwen3_asr_audio_simd; // ---------------------------------------------------------------------------------------------------------------- // bf16 helpers (activations are fp32 values that are exactly bf16-representable) @@ -178,87 +182,219 @@ void gemm_bias(const float* A, int M, int K, const packed_w& W, const float* bia } } for (int i = 0; i < T; i++) { - float out[32]; - _mm512_storeu_ps(out, acc0[i]); - _mm512_storeu_ps(out + 16, acc1[i]); float* c = C + (size_t)(m + i) * N + n0; - for (int j = 0; j < 32; j++) { - float v = rbf(out[j] + (bias ? bias[n0 + j] : 0.f)); - if (gelu) v = rbf(gelu_erf(v)); - c[j] = v; + for (int h = 0; h < 2; h++) { + __m512 v = h ? acc1[i] : acc0[i]; + if (bias) v = _mm512_add_ps(v, _mm512_loadu_ps(bias + n0 + 16 * h)); + v = simd::round_bf16(v); + if (gelu) v = simd::round_bf16(simd::gelu_erf(v)); + _mm512_storeu_ps(c + 16 * h, v); } } } } } +/// D: a multiple of 16 void layer_norm(const float* x, int rows, int D, const float* w, const float* b, float eps, float* y) { + assert(D % 16 == 0); #pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) for (int r = 0; r < rows; r++) { const float* xr = x + (size_t)r * D; float* yr = y + (size_t)r * D; - double s = 0, s2 = 0; - for (int i = 0; i < D; i++) s += xr[i]; - const float mean = (float)(s / D); - for (int i = 0; i < D; i++) { float d = xr[i] - mean; s2 += (double)d * d; } - const float rstd = 1.0f / std::sqrt((float)(s2 / D) + eps); - for (int i = 0; i < D; i++) yr[i] = rbf((xr[i] - mean) * rstd * w[i] + b[i]); + // statistics in double: on quiet input a row is a small signal over a large offset, and fp32 sums lose it + __m512d s0 = _mm512_setzero_pd(), s1 = _mm512_setzero_pd(); + for (int i = 0; i < D; i += 16) { + s0 = _mm512_add_pd(s0, _mm512_cvtps_pd(_mm256_loadu_ps(xr + i))); + s1 = _mm512_add_pd(s1, _mm512_cvtps_pd(_mm256_loadu_ps(xr + i + 8))); + } + const __m512 mean = _mm512_set1_ps((float)(_mm512_reduce_add_pd(_mm512_add_pd(s0, s1)) / D)); + s0 = s1 = _mm512_setzero_pd(); + for (int i = 0; i < D; i += 16) { + const __m512 d = _mm512_sub_ps(_mm512_loadu_ps(xr + i), mean); + const __m512d d0 = _mm512_cvtps_pd(_mm512_castps512_ps256(d)), d1 = _mm512_cvtps_pd(_mm256_castpd_ps(_mm512_extractf64x4_pd(_mm512_castps_pd(d), 1))); + s0 = _mm512_fmadd_pd(d0, d0, s0); + s1 = _mm512_fmadd_pd(d1, d1, s1); + } + const __m512 rstd = _mm512_set1_ps(1.0f / std::sqrt((float)(_mm512_reduce_add_pd(_mm512_add_pd(s0, s1)) / D) + eps)); + for (int i = 0; i < D; i += 16) { + const __m512 d = _mm512_mul_ps(_mm512_sub_ps(_mm512_loadu_ps(xr + i), mean), rstd); + _mm512_storeu_ps(yr + i, simd::round_bf16(_mm512_fmadd_ps(d, _mm512_loadu_ps(w + i), _mm512_loadu_ps(b + i)))); + } } } +/// x = rbf(x + t), n a multiple of 16 +void add_residual(float* x, const float* t, size_t n) { +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int64_t i = 0; i < (int64_t)n; i += 16) _mm512_storeu_ps(x + i, simd::round_bf16(_mm512_add_ps(_mm512_loadu_ps(x + i), _mm512_loadu_ps(t + i)))); +} + +/// one (window, head) of attention: o[i] = rbf(softmax_j(q[i] . k[j] * scale) v[j]) for i, j < m. q, k, v rows have stride rs, +/// o rows stride os; hd a multiple of 16. K is transposed first (zero past m), so a row of scores is hd broadcast FMAs per 16 keys. +void window_attention(const float* q, const float* k, const float* v, size_t rs, int m, int hd, float scale, bool round_scores, + bool round_probs, float* o, size_t os, std::vector& kt, std::vector& s) { + constexpr int G = 8; // key vectors per pass (registers) + const int mv = (m + 15) / 16, ld = mv * 16; + kt.assign((size_t)hd * ld, 0.f); + s.resize(ld); + for (int j = 0; j < m; j++) + for (int d = 0; d < hd; d++) kt[(size_t)d * ld + j] = k[(size_t)j * rs + d]; + const __mmask16 tail = (__mmask16)((1u << (m - (mv - 1) * 16)) - 1); + const __m512 vscale = _mm512_set1_ps(scale), ninf = _mm512_set1_ps(-INFINITY); + for (int i = 0; i < m; i++) { + const float* qi = q + (size_t)i * rs; + __m512 mx = ninf; + for (int g0 = 0; g0 < mv; g0 += G) { + const int gn = std::min(G, mv - g0); + __m512 acc[G]; + for (int t = 0; t < G; t++) acc[t] = _mm512_setzero_ps(); + for (int d = 0; d < hd; d++) { + const __m512 qd = _mm512_set1_ps(qi[d]); + const float* kd = kt.data() + (size_t)d * ld + g0 * 16; + for (int t = 0; t < gn; t++) acc[t] = _mm512_fmadd_ps(qd, _mm512_loadu_ps(kd + t * 16), acc[t]); + } + for (int t = 0; t < gn; t++) { + __m512 a = round_scores ? simd::round_bf16(_mm512_mul_ps(simd::round_bf16(acc[t]), vscale)) : _mm512_mul_ps(acc[t], vscale); + if (g0 + t == mv - 1) a = _mm512_mask_mov_ps(ninf, tail, a); + _mm512_storeu_ps(s.data() + (g0 + t) * 16, a); + mx = _mm512_max_ps(mx, a); + } + } + const __m512 vmx = _mm512_set1_ps(_mm512_reduce_max_ps(mx)); + __m512 sum = _mm512_setzero_ps(); + for (int jv = 0; jv < mv; jv++) { + __m512 e = simd::exp(_mm512_sub_ps(_mm512_loadu_ps(s.data() + jv * 16), vmx)); + if (jv == mv - 1) e = _mm512_maskz_mov_ps(tail, e); + _mm512_storeu_ps(s.data() + jv * 16, e); + sum = _mm512_add_ps(sum, e); + } + const __m512 vsum = _mm512_set1_ps(_mm512_reduce_add_ps(sum)); + for (int jv = 0; jv < mv; jv++) { + __m512 p = _mm512_div_ps(_mm512_loadu_ps(s.data() + jv * 16), vsum); + _mm512_storeu_ps(s.data() + jv * 16, round_probs ? simd::round_bf16(p) : p); + } + float* oi = o + (size_t)i * os; + for (int d0 = 0; d0 < hd; d0 += 64) { + const int dn = std::min(4, (hd - d0) / 16); + __m512 acc[4] = {_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps()}; + for (int j = 0; j < m; j++) { + const __m512 p = _mm512_set1_ps(s[j]); + const float* vj = v + (size_t)j * rs + d0; + for (int t = 0; t < dn; t++) acc[t] = _mm512_fmadd_ps(p, _mm512_loadu_ps(vj + t * 16), acc[t]); + } + for (int t = 0; t < dn; t++) _mm512_storeu_ps(oi + d0 + t * 16, simd::round_bf16(acc[t])); + } + } +} + +/// set by encode(..., host = true): this thread's products use the host copies of the backend's weights +thread_local bool tl_host = false; + +/// One projection: host-packed weights, or the id of the weights the gemm backend holds (or both: host_copy) +struct linear { + packed_w w; + std::vector b; + int id = -1; + int N = 0, K = 0; +}; + struct layer_w { - packed_w q, k, v, o, fc1, fc2; // [out][in] - std::vector qb, kb, vb, ob, fc1b, fc2b; + linear qkv, o, fc1, fc2; // [out][in]; qkv = q, k, v stacked (3 d_model outputs) std::vector ln1w, ln1b, ln2w, ln2b; // self_attn_layer_norm, final_layer_norm }; } // namespace struct qwen3_asr_audio_encoder::Impl { + qwen3_asr_audio_gemm* gemm = nullptr; + bool host_copy = false; // with gemm: host weights too // conv stack: weights [480][Kpad] in (kh, kw, cin) order, so an im2col row is a run of cin-contiguous copies - packed_w conv_w[3]; - std::vector conv_b[3]; + linear conv[3]; int conv_cin[3] = {1, 480, 480}; - packed_w conv_out_w; // [1024][7680] + linear conv_out; // [1024][7680] std::vector pos; // [chunk_tokens][d_model], bf16 values std::vector layers; - std::vector ln_post_w, ln_post_b, proj1_b, proj2_b; - packed_w proj1_w, proj2_w; + std::vector ln_post_w, ln_post_b; + linear proj1, proj2; // attention numerics switches (see README): scores / probabilities rounded to bf16 like the eager reference bool round_scores = false, round_probs = false; + + // conv front end scratch, kept between calls (conv_mu) + std::mutex conv_mu; + std::vector in0, act[3], full, rows_buf; + + /// W [N][K]; on the backend when there is one and `host` is false. The backend keeps A and W at bf16 precision + /// (exact_a, exact_w of qwen3_asr_audio_gemm::add_weight): plain bfp16 products drift the conv stack on quiet input. + linear make(const std::vector& W, int N, int K, std::vector b, bool host = false) { + linear L; + L.N = N; + L.K = K; + if (gemm && !host) L.id = gemm->add_weight(W.data(), N, K, b.empty() ? nullptr : b.data(), true, true); + if (!gemm || host || host_copy) { + L.w = pack_bf16(W, N, K); + L.b = std::move(b); + } + return L; + } + void mm(const linear& L, const float* A, int M, float* C, bool gelu) { + if (L.id >= 0 && !tl_host) gemm->run(L.id, [A, K = L.K](int r, float*) { return A + (size_t)r * K; }, M, C, gelu); + else gemm_bias(A, M, L.K, L.w, L.b.empty() ? nullptr : L.b.data(), L.N, C, gelu); + } + /// the same with A given row by row (the backend packs each row as it comes; the host gathers A first, into rows_buf) + void mm_rows(const linear& L, const qwen3_asr_audio_gemm::rows_fn& A, int M, float* C, bool gelu) { + if (L.id >= 0 && !tl_host) return gemm->run(L.id, A, M, C, gelu); + rows_buf.resize((size_t)M * L.K); +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int r = 0; r < M; r++) { + float* dst = rows_buf.data() + (size_t)r * L.K; + const float* p = A(r, dst); + if (p != dst) std::memcpy(dst, p, sizeof(float) * L.K); + } + gemm_bias(rows_buf.data(), M, L.K, L.w, L.b.empty() ? nullptr : L.b.data(), L.N, C, gelu); + } + /// conv front end of `count` chunks at once (one product per conv over all of them): see conv_front() + void conv_chunks(const qwen3_asr_audio_config& cfg, const float* const* mel, const int* valid, int count, float* const* out); }; namespace { -/// im2col for Conv2d(3x3, stride 2, pad 1) on an NHWC activation [H][W][cin]; out [Hout*Wout][kpad], row = (kh, kw, cin). -void im2col_s2(const float* in, int H, int W, int cin, int kpad, float* out) { - const int Ho = (H + 1) / 2, Wo = (W + 1) / 2; -#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) - for (int p = 0; p < Ho * Wo; p++) { - const int ho = p / Wo, wo = p % Wo; - float* row = out + (size_t)p * kpad; - for (int kh = 0; kh < 3; kh++) { - for (int kw = 0; kw < 3; kw++) { - const int h = 2 * ho - 1 + kh, w = 2 * wo - 1 + kw; - float* dst = row + (kh * 3 + kw) * cin; - if (h < 0 || h >= H || w < 0 || w >= W) std::memset(dst, 0, sizeof(float) * cin); - else std::memcpy(dst, in + ((size_t)h * W + w) * cin, sizeof(float) * cin); - } +/// im2col row p (= ho * Wout + wo) of Conv2d(3x3, stride 2, pad 1) on an NHWC activation [H][W][cin]: kpad values, (kh, kw, cin). +void im2col_row(const float* in, int H, int W, int cin, int kpad, int p, float* row) { + const int Wo = (W + 1) / 2, ho = p / Wo, wo = p % Wo; + for (int kh = 0; kh < 3; kh++) { + for (int kw = 0; kw < 3; kw++) { + const int h = 2 * ho - 1 + kh, w = 2 * wo - 1 + kw; + float* dst = row + (kh * 3 + kw) * cin; + if (h < 0 || h >= H || w < 0 || w >= W) std::memset(dst, 0, sizeof(float) * cin); + else std::memcpy(dst, in + ((size_t)h * W + w) * cin, sizeof(float) * cin); } - for (int i = 9 * cin; i < kpad; i++) row[i] = 0.f; } + for (int i = 9 * cin; i < kpad; i++) row[i] = 0.f; } } // namespace -qwen3_asr_audio_encoder::qwen3_asr_audio_encoder(const std::string& path, const qwen3_asr_audio_config& cfg) : cfg_(cfg) { +void qwen3_asr_audio_gemm::run_conv(int weight, const float* in, int count, int H, int W, int cin, int K, float* C, bool gelu) { + const int rows = (H + 1) / 2 * ((W + 1) / 2); // per image + run(weight, [=](int r, float* tmp) { + im2col_row(in + (size_t)(r / rows) * H * W * cin, H, W, cin, K, r % rows, tmp); + return (const float*)tmp; + }, count * rows, C, gelu); +} + +qwen3_asr_audio_encoder::qwen3_asr_audio_encoder(const std::string& path, const qwen3_asr_audio_config& cfg, qwen3_asr_audio_gemm* gemm, + bool host_copy) + : cfg_(cfg) { impl_ = new Impl(); Impl& I = *impl_; + I.gemm = gemm; + I.host_copy = gemm && host_copy; if (const char* e = std::getenv("R2T2_ROUND_SCORES")) I.round_scores = std::atoi(e) != 0; if (const char* e = std::getenv("R2T2_ROUND_PROBS")) I.round_probs = std::atoi(e) != 0; safetensors_file f(path); const int D = cfg_.d_model, C = cfg_.downsample_hidden; - // conv weights [Cout][Cin][3][3] -> [Cout][kpad] with k = (kh*3+kw)*Cin + cin + // conv weights [Cout][Cin][3][3] -> [Cout][kpad] with k = (kh*3+kw)*Cin + cin. conv1 (K = 9) stays on the host. for (int l = 0; l < 3; l++) { const auto& t = f.get("model.audio.conv2d" + std::to_string(l + 1) + ".weight"); const int cin = I.conv_cin[l], kpad = round_up(9 * cin, 16); @@ -266,11 +402,10 @@ qwen3_asr_audio_encoder::qwen3_asr_audio_encoder(const std::string& path, const for (int co = 0; co < C; co++) for (int ci = 0; ci < cin; ci++) for (int k = 0; k < 9; k++) w[(size_t)co * kpad + (size_t)k * cin + ci] = bf2f(t.data[((size_t)co * cin + ci) * 9 + k]); - I.conv_w[l] = pack_bf16(w, C, kpad); - I.conv_b[l] = to_f32(f.get("model.audio.conv2d" + std::to_string(l + 1) + ".bias")); + I.conv[l] = I.make(w, C, kpad, to_f32(f.get("model.audio.conv2d" + std::to_string(l + 1) + ".bias")), /*host=*/l == 0); } const int conv_k = C * (cfg_.num_mel_bins / 8); // 480 * 16 = 7680 - I.conv_out_w = pack_bf16(unpermute_matrix(f.get("model.audio.conv_out.weight"), D, conv_k), D, conv_k); + I.conv_out = I.make(unpermute_matrix(f.get("model.audio.conv_out.weight"), D, conv_k), D, conv_k, {}); // sinusoidal position table (built like SinusoidsPositionEmbedding, then cast to bf16 by the reference) I.pos.resize((size_t)cfg_.chunk_tokens() * D); @@ -289,18 +424,17 @@ qwen3_asr_audio_encoder::qwen3_asr_audio_encoder(const std::string& path, const for (int l = 0; l < cfg_.layers; l++) { const std::string p = "model.audio.layers." + std::to_string(l) + "."; layer_w& L = I.layers[l]; - L.q = pack_bf16(unpermute_matrix(f.get(p + "self_attn.q_proj.weight"), D, D), D, D); - L.k = pack_bf16(unpermute_matrix(f.get(p + "self_attn.k_proj.weight"), D, D), D, D); - L.v = pack_bf16(unpermute_matrix(f.get(p + "self_attn.v_proj.weight"), D, D), D, D); - L.o = pack_bf16(unpermute_matrix(f.get(p + "self_attn.out_proj.weight"), D, D), D, D); - L.fc1 = pack_bf16(unpermute_matrix(f.get(p + "fc1.weight"), cfg_.ffn_dim, D), cfg_.ffn_dim, D); - L.fc2 = pack_bf16(unpermute_matrix(f.get(p + "fc2.weight"), D, cfg_.ffn_dim), D, cfg_.ffn_dim); - L.qb = to_f32(f.get(p + "self_attn.q_proj.bias")); - L.kb = to_f32(f.get(p + "self_attn.k_proj.bias")); - L.vb = to_f32(f.get(p + "self_attn.v_proj.bias")); - L.ob = to_f32(f.get(p + "self_attn.out_proj.bias")); - L.fc1b = to_f32(f.get(p + "fc1.bias")); - L.fc2b = to_f32(f.get(p + "fc2.bias")); + std::vector qkv_w, qkv_b; + for (const char* m : {"q", "k", "v"}) { + const auto w = unpermute_matrix(f.get(p + "self_attn." + m + "_proj.weight"), D, D); + const auto b = to_f32(f.get(p + "self_attn." + m + "_proj.bias")); + qkv_w.insert(qkv_w.end(), w.begin(), w.end()); + qkv_b.insert(qkv_b.end(), b.begin(), b.end()); + } + L.qkv = I.make(qkv_w, 3 * D, D, std::move(qkv_b)); + L.o = I.make(unpermute_matrix(f.get(p + "self_attn.out_proj.weight"), D, D), D, D, to_f32(f.get(p + "self_attn.out_proj.bias"))); + L.fc1 = I.make(unpermute_matrix(f.get(p + "fc1.weight"), cfg_.ffn_dim, D), cfg_.ffn_dim, D, to_f32(f.get(p + "fc1.bias"))); + L.fc2 = I.make(unpermute_matrix(f.get(p + "fc2.weight"), D, cfg_.ffn_dim), D, cfg_.ffn_dim, to_f32(f.get(p + "fc2.bias"))); L.ln1w = to_f32(f.get(p + "self_attn_layer_norm.weight")); L.ln1b = to_f32(f.get(p + "self_attn_layer_norm.bias")); L.ln2w = to_f32(f.get(p + "final_layer_norm.weight")); @@ -308,46 +442,59 @@ qwen3_asr_audio_encoder::qwen3_asr_audio_encoder(const std::string& path, const } I.ln_post_w = to_f32(f.get("model.audio.ln_post.weight")); I.ln_post_b = to_f32(f.get("model.audio.ln_post.bias")); - I.proj1_w = pack_bf16(unpermute_matrix(f.get("model.audio.tower.proj1.weight"), D, D), D, D); - I.proj1_b = to_f32(f.get("model.audio.tower.proj1.bias")); - I.proj2_w = pack_bf16(unpermute_matrix(f.get("model.audio.tower.proj2.weight"), cfg_.output_dim, D), cfg_.output_dim, D); - I.proj2_b = to_f32(f.get("model.audio.tower.proj2.bias")); + I.proj1 = I.make(unpermute_matrix(f.get("model.audio.tower.proj1.weight"), D, D), D, D, to_f32(f.get("model.audio.tower.proj1.bias"))); + I.proj2 = I.make(unpermute_matrix(f.get("model.audio.tower.proj2.weight"), cfg_.output_dim, D), cfg_.output_dim, D, + to_f32(f.get("model.audio.tower.proj2.bias"))); } qwen3_asr_audio_encoder::~qwen3_asr_audio_encoder() { delete impl_; } -void qwen3_asr_audio_encoder::conv_front(const float* mel_chunk, int valid_frames, float* out_tokens) { - Impl& I = *impl_; - const int C = cfg_.downsample_hidden, F = cfg_.num_mel_bins, W0 = cfg_.chunk_frames(); - // conv1 input as NHWC [H=128 (mel bin)][W=100 (time)][1]; frames beyond valid_frames are zero (reference pads the chunk) - std::vector in0((size_t)F * W0, 0.f); - for (int t = 0; t < std::min(valid_frames, W0); t++) - for (int h = 0; h < F; h++) in0[(size_t)h * W0 + t] = rbf(mel_chunk[(size_t)t * F + h]); // mel is cast to bf16 first - +void qwen3_asr_audio_encoder::Impl::conv_chunks(const qwen3_asr_audio_config& cfg, const float* const* mel, const int* valid, int count, + float* const* out) { + const int C = cfg.downsample_hidden, F = cfg.num_mel_bins, W0 = cfg.chunk_frames(); + std::lock_guard lock(conv_mu); + // conv1 input as NHWC [H=128 (mel bin)][W=100 (time)][1] per chunk; frames beyond valid are zero (reference pads the chunk) + in0.assign((size_t)count * F * W0, 0.f); + for (int c = 0; c < count; c++) + for (int t = 0; t < std::min(valid[c], W0); t++) + for (int h = 0; h < F; h++) in0[((size_t)c * F + h) * W0 + t] = rbf(mel[c][(size_t)t * F + h]); // mel is cast to bf16 first + + // each conv product takes its rows (im2col rows) straight from the previous activation int H = F, W = W0; - std::vector cur, patches, nxt; const float* src = in0.data(); for (int l = 0; l < 3; l++) { - const int cin = I.conv_cin[l], kpad = round_up(9 * cin, 16), Ho = (H + 1) / 2, Wo = (W + 1) / 2; - patches.resize((size_t)Ho * Wo * kpad); - im2col_s2(src, H, W, cin, kpad, patches.data()); - nxt.resize((size_t)Ho * Wo * C); - gemm_bias(patches.data(), Ho * Wo, kpad, I.conv_w[l], I.conv_b[l].data(), C, nxt.data(), /*gelu=*/true); - cur.swap(nxt); - src = cur.data(); + const int cin = conv_cin[l], kpad = round_up(9 * cin, 16), Ho = (H + 1) / 2, Wo = (W + 1) / 2; + const int rows = Ho * Wo; // per chunk + act[l].resize((size_t)count * rows * C); + if (conv[l].id >= 0 && !tl_host) + gemm->run_conv(conv[l].id, src, count, H, W, cin, kpad, act[l].data(), /*gelu=*/true); + else { + auto row = [=](int r, float* tmp) { + im2col_row(src + (size_t)(r / rows) * H * W * cin, H, W, cin, kpad, r % rows, tmp); + return (const float*)tmp; + }; + mm_rows(conv[l], row, count * rows, act[l].data(), /*gelu=*/true); + } + src = act[l].data(); H = Ho; W = Wo; } - // cur: [H=16 (f)][W=13 (t)][C]; token t = vector over (c, f) in c-major order: index c*16 + f - const int Fq = H, T = W, K = C * Fq; - std::vector tok((size_t)T * K); - for (int t = 0; t < T; t++) - for (int c = 0; c < C; c++) - for (int fq = 0; fq < Fq; fq++) tok[(size_t)t * K + (size_t)c * Fq + fq] = cur[((size_t)fq * T + t) * C + c]; - const int n_valid = qwen3_asr_audio_tokens(valid_frames); - std::vector full((size_t)T * cfg_.d_model); - gemm_bias(tok.data(), T, K, I.conv_out_w, nullptr, cfg_.d_model, full.data(), false); - std::memcpy(out_tokens, full.data(), sizeof(float) * (size_t)n_valid * cfg_.d_model); + // act[2]: per chunk [H=16 (f)][W=13 (t)][C]; token t = vector over (c, f) in c-major order: index c*16 + f + const int Fq = H, T = W, D = cfg.d_model; + auto token = [=](int ct, float* tmp) { + const float* cc = src + (size_t)(ct / T) * Fq * T * C + (size_t)(ct % T) * C; + for (int fq = 0; fq < Fq; fq++) + for (int ch = 0; ch < C; ch++) tmp[(size_t)ch * Fq + fq] = cc[(size_t)fq * T * C + ch]; + return (const float*)tmp; + }; + full.resize((size_t)count * T * D); + mm_rows(conv_out, token, count * T, full.data(), false); + for (int c = 0; c < count; c++) + std::memcpy(out[c], full.data() + (size_t)c * T * D, sizeof(float) * (size_t)qwen3_asr_audio_tokens(valid[c]) * D); +} + +void qwen3_asr_audio_encoder::conv_front(const float* mel_chunk, int valid_frames, float* out_tokens) { + impl_->conv_chunks(cfg_, &mel_chunk, &valid_frames, 1, &out_tokens); } void qwen3_asr_audio_encoder::add_pos(float* x, int tokens) { @@ -356,59 +503,56 @@ void qwen3_asr_audio_encoder::add_pos(float* x, int tokens) { for (int i = 0; i < D; i++) x[(size_t)t * D + i] = rbf(x[(size_t)t * D + i] + impl_->pos[(size_t)t * D + i]); } +namespace { +/// an encoder layer's activations; encode() keeps one set for all its layers (freed when it returns) +struct layer_scratch { + std::vector a, qkv, o, t1, ff; +}; +thread_local layer_scratch* tl_scratch = nullptr; +struct scratch_scope { + layer_scratch s; + scratch_scope() { tl_scratch = &s; } + ~scratch_scope() { tl_scratch = nullptr; } +}; +} // namespace + void qwen3_asr_audio_encoder::encoder_layer(int layer, float* x, int n) { Impl& I = *impl_; const layer_w& L = I.layers[layer]; const int D = cfg_.d_model, H = cfg_.heads, hd = D / H, FF = cfg_.ffn_dim, WT = cfg_.window_tokens(); - std::vector a((size_t)n * D), q((size_t)n * D), k((size_t)n * D), v((size_t)n * D), o((size_t)n * D), t1((size_t)n * D); + layer_scratch local; + layer_scratch& S = tl_scratch ? *tl_scratch : local; + for (auto* v : {&S.a, &S.o, &S.t1}) v->resize((size_t)n * D); + S.qkv.resize((size_t)n * 3 * D); + S.ff.resize((size_t)n * FF); + std::vector&a = S.a, &qkv = S.qkv, &o = S.o, &t1 = S.t1, &ff = S.ff; layer_norm(x, n, D, L.ln1w.data(), L.ln1b.data(), cfg_.ln_eps, a.data()); - gemm_bias(a.data(), n, D, L.q, L.qb.data(), D, q.data(), false); - gemm_bias(a.data(), n, D, L.k, L.kb.data(), D, k.data(), false); - gemm_bias(a.data(), n, D, L.v, L.vb.data(), D, v.data(), false); + I.mm(L.qkv, a.data(), n, qkv.data(), false); // row t = q[t], k[t], v[t] + const float* q = qkv.data(); + const float* k = qkv.data() + D; + const float* v = qkv.data() + 2 * D; + const size_t RS = (size_t)3 * D; // window attention: tokens [w0, w1) only see each other const float scale = 1.0f / std::sqrt((float)hd); const int nwin = (n + WT - 1) / WT; #pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) schedule(dynamic) for (int wh = 0; wh < nwin * H; wh++) { // one (window, head) pair per iteration - { - const int w = wh / H, h = wh % H; - const int w0 = w * WT, w1 = std::min(n, w0 + WT), m = w1 - w0; - std::vector s((size_t)m * m); - for (int i = 0; i < m; i++) { - const float* qi = q.data() + (size_t)(w0 + i) * D + h * hd; - for (int j = 0; j < m; j++) { - const float* kj = k.data() + (size_t)(w0 + j) * D + h * hd; - float acc = 0.f; - for (int d = 0; d < hd; d++) acc += qi[d] * kj[d]; - if (I.round_scores) acc = rbf(rbf(acc) * scale); else acc *= scale; - s[(size_t)i * m + j] = acc; - } - float mx = -INFINITY; - for (int j = 0; j < m; j++) mx = std::max(mx, s[(size_t)i * m + j]); - float sum = 0.f; - for (int j = 0; j < m; j++) { float e = std::exp(s[(size_t)i * m + j] - mx); s[(size_t)i * m + j] = e; sum += e; } - for (int j = 0; j < m; j++) { float p = s[(size_t)i * m + j] / sum; s[(size_t)i * m + j] = I.round_probs ? rbf(p) : p; } - float* oi = o.data() + (size_t)(w0 + i) * D + h * hd; - for (int d = 0; d < hd; d++) oi[d] = 0.f; - for (int j = 0; j < m; j++) { - const float p = s[(size_t)i * m + j]; - const float* vj = v.data() + (size_t)(w0 + j) * D + h * hd; - for (int d = 0; d < hd; d++) oi[d] += p * vj[d]; - } - for (int d = 0; d < hd; d++) oi[d] = rbf(oi[d]); - } - } + thread_local std::vector kt, s; + const int w = wh / H, h = wh % H; + const int w0 = w * WT, m = std::min(n, w0 + WT) - w0; + const size_t off = (size_t)w0 * RS + h * hd; + window_attention(q + off, k + off, v + off, RS, m, hd, scale, I.round_scores, I.round_probs, o.data() + (size_t)w0 * D + h * hd, D, + kt, s); } - gemm_bias(o.data(), n, D, L.o, L.ob.data(), D, t1.data(), false); - for (size_t i = 0; i < (size_t)n * D; i++) x[i] = rbf(x[i] + t1[i]); + I.mm(L.o, o.data(), n, t1.data(), false); + add_residual(x, t1.data(), (size_t)n * D); layer_norm(x, n, D, L.ln2w.data(), L.ln2b.data(), cfg_.ln_eps, a.data()); - std::vector ff((size_t)n * FF); - gemm_bias(a.data(), n, D, L.fc1, L.fc1b.data(), FF, ff.data(), /*gelu=*/true); - gemm_bias(ff.data(), n, FF, L.fc2, L.fc2b.data(), D, t1.data(), false); - for (size_t i = 0; i < (size_t)n * D; i++) x[i] = rbf(x[i] + t1[i]); + I.mm(L.fc1, a.data(), n, ff.data(), /*gelu=*/true); + I.mm(L.fc2, ff.data(), n, t1.data(), false); + add_residual(x, t1.data(), (size_t)n * D); } void qwen3_asr_audio_encoder::post(const float* x, int n, float* out) { @@ -416,38 +560,63 @@ void qwen3_asr_audio_encoder::post(const float* x, int n, float* out) { const int D = cfg_.d_model; std::vector a((size_t)n * D), b((size_t)n * D); layer_norm(x, n, D, I.ln_post_w.data(), I.ln_post_b.data(), cfg_.ln_eps, a.data()); - gemm_bias(a.data(), n, D, I.proj1_w, I.proj1_b.data(), D, b.data(), /*gelu=*/true); - gemm_bias(b.data(), n, D, I.proj2_w, I.proj2_b.data(), cfg_.output_dim, out, false); + I.mm(I.proj1, a.data(), n, b.data(), /*gelu=*/true); + I.mm(I.proj2, b.data(), n, out, false); } -std::vector qwen3_asr_audio_encoder::encode(const float* mel, int frames, conv_cache* cache) { +std::vector qwen3_asr_audio_encoder::encode(const float* mel, int frames, conv_cache* cache, bool host) { + struct host_scope { + explicit host_scope(bool on) { tl_host = on; } + ~host_scope() { tl_host = false; } + } on_host(host && impl_->host_copy); const int D = cfg_.d_model, CF = cfg_.chunk_frames(); const int n_tokens = qwen3_asr_audio_tokens(frames); const int nchunks = (frames + CF - 1) / CF; std::vector x((size_t)n_tokens * D); - int off = 0; - for (int c = 0; c < nchunks; c++) { - const int valid = std::min(CF, frames - c * CF); - const int nt = qwen3_asr_audio_tokens(valid); - float* rows = x.data() + (size_t)off * D; - const float* chunk_mel = mel + (size_t)c * CF * cfg_.num_mel_bins; - const size_t mel_floats = (size_t)CF * cfg_.num_mel_bins; - if (cache && c < cache->chunks && std::memcmp(cache->mel.data() + (size_t)c * mel_floats, chunk_mel, sizeof(float) * mel_floats) != 0) - cache->truncate(c, cfg_.chunk_tokens() * D, (int)mel_floats); // its mel changed (the clip's clamp moved): redo it and the rest - if (cache && c < cache->chunks) { // a finished chunk seen by an earlier call - std::memcpy(rows, cache->rows.data() + (size_t)c * cfg_.chunk_tokens() * D, sizeof(float) * (size_t)nt * D); - } else { - conv_front(chunk_mel, valid, rows); - add_pos(rows, nt); - if (cache && c == cache->chunks && valid == CF) { - cache->rows.insert(cache->rows.end(), rows, rows + (size_t)nt * D); - cache->mel.insert(cache->mel.end(), chunk_mel, chunk_mel + mel_floats); + const size_t mel_floats = (size_t)CF * cfg_.num_mel_bins, row_floats = (size_t)cfg_.chunk_tokens() * D; + auto chunk_mel = [&](int c) { return mel + (size_t)c * mel_floats; }; + auto chunk_rows = [&](int c) { return x.data() + (size_t)c * row_floats; }; // every chunk but the last has 13 tokens + + // finished chunks seen by an earlier call, while their mel is the same (the clip's clamp can move: then redo it and the rest) + int cached = 0; + if (cache) { + for (int c = 0; c < std::min(cache->chunks, nchunks); c++) + if (std::memcmp(cache->mel.data() + (size_t)c * mel_floats, chunk_mel(c), sizeof(float) * mel_floats) != 0) { + cache->truncate(c, (int)row_floats, (int)mel_floats); + break; + } + cached = std::min(cache->chunks, nchunks); + for (int c = 0; c < cached; c++) + std::memcpy(chunk_rows(c), cache->rows.data() + (size_t)c * row_floats, + sizeof(float) * (size_t)qwen3_asr_audio_tokens(std::min(CF, frames - c * CF)) * D); + } + // the rest, a group of chunks per conv product + constexpr int GROUP = 8; + for (int c0 = cached; c0 < nchunks; c0 += GROUP) { + const int n = std::min(GROUP, nchunks - c0); + const float* mels[GROUP]; + int valid[GROUP]; + float* outs[GROUP]; + for (int i = 0; i < n; i++) { + mels[i] = chunk_mel(c0 + i); + valid[i] = std::min(CF, frames - (c0 + i) * CF); + outs[i] = chunk_rows(c0 + i); + } + impl_->conv_chunks(cfg_, mels, valid, n, outs); + for (int i = 0; i < n; i++) { + const int c = c0 + i, nt = qwen3_asr_audio_tokens(valid[i]); + add_pos(outs[i], nt); + if (cache && c == cache->chunks && valid[i] == CF) { + cache->rows.insert(cache->rows.end(), outs[i], outs[i] + (size_t)nt * D); + cache->mel.insert(cache->mel.end(), mels[i], mels[i] + mel_floats); cache->chunks++; } } - off += nt; } - for (int l = 0; l < cfg_.layers; l++) encoder_layer(l, x.data(), n_tokens); + { + scratch_scope scope; + for (int l = 0; l < cfg_.layers; l++) encoder_layer(l, x.data(), n_tokens); + } std::vector y((size_t)n_tokens * cfg_.output_dim); post(x.data(), n_tokens, y.data()); std::vector out(y.size()); diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.hpp index c6084c345..8495c297b 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.hpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_encoder.hpp @@ -14,10 +14,11 @@ /// layer norm statistics, softmax and erf-GELU run in fp32. Activations are held as fp32 values that are exactly /// bf16-representable; only the result of encode() is converted to bf16 bits. /// -/// This file has no NPU / XRT dependency so it can be built and tested standalone. The per-stage methods are the -/// seams for the NPU port (matmuls on the MM kernel, window attention on a window-attention kernel). +/// This file has no NPU / XRT dependency so it can be built and tested standalone. The matrix products go to a +/// qwen3_asr_audio_gemm when one is given (the NPU in the engine); layer norm, attention and conv1 stay here. #pragma once #include +#include #include #include @@ -45,10 +46,31 @@ struct qwen3_asr_audio_config { /// number of audio tokens for `frames` mel frames (= _get_feat_extract_output_lengths) int qwen3_asr_audio_tokens(int frames); +/// Matrix products of the encoder on another device (the engine passes the NPU's, qwen3_asr_audio_gemm_npu.hpp): +/// C[M][N] = bf16(A[M][K] W[N][K]^T + bias), then bf16(erf GELU) when asked. A and C hold bf16 values in fp32; C is row-major. +/// The device may round the operands further (the NPU: block float, 8 values share an exponent). +class qwen3_asr_audio_gemm { +public: + /// row r of A (K values): a pointer into the caller's data, or `tmp` (K floats) after filling it. Called from several threads. + using rows_fn = std::function; + virtual ~qwen3_asr_audio_gemm() = default; + /// W row-major [N][K] (bf16 values), bias [N] or nullptr; `exact_a` / `exact_w`: the device keeps A / W at bf16 precision + /// (the NPU then also runs the product on the rest of A rounded to its format / on the rest of W). Returns the id run() + /// takes. Called while loading only. + virtual int add_weight(const float* W, int N, int K, const float* bias, bool exact_a, bool exact_w) = 0; + virtual void run(int weight, const rows_fn& A, int M, float* C, bool gelu) = 0; + /// Conv2d(3x3, stride 2, pad 1) of `count` NHWC images in[count][H][W][cin]: A = their im2col rows, (image, ho, wo) order, K + /// values each in (kh, kw, cin) order (K >= 9 cin, zero past 9 cin), as the weight was added. The default builds the rows. + virtual void run_conv(int weight, const float* in, int count, int H, int W, int cin, int K, float* C, bool gelu); +}; + class qwen3_asr_audio_encoder { public: /// \param audio_weight_q4nx path to audio_weight.q4nx (BF16, matrices in the audio MM tile layout) - qwen3_asr_audio_encoder(const std::string& audio_weight_q4nx, const qwen3_asr_audio_config& cfg = {}); + /// \param gemm runs the projections, conv2, conv3 and conv_out when given (the host keeps no copy of those weights unless + /// host_copy: then encode(..., host = true) runs them on the host) + qwen3_asr_audio_encoder(const std::string& audio_weight_q4nx, const qwen3_asr_audio_config& cfg = {}, + qwen3_asr_audio_gemm* gemm = nullptr, bool host_copy = false); ~qwen3_asr_audio_encoder(); /// \param mel row-major [frames][num_mel_bins] fp32 (the feature extractor output, time-major) @@ -75,7 +97,8 @@ class qwen3_asr_audio_encoder { chunks -= n; } }; - std::vector encode(const float* mel, int frames, conv_cache* cache = nullptr); + /// \param host every product on the host (needs host_copy; ignored otherwise) + std::vector encode(const float* mel, int frames, conv_cache* cache = nullptr, bool host = false); // ------------------------------------------------------------------------------------------------------------ // stage seams (all activations are [rows][cols] row-major fp32 holding bf16 values) diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_npu.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_npu.cpp new file mode 100644 index 000000000..2b6319a64 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_npu.cpp @@ -0,0 +1,324 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "qwen3_asr_audio_gemm_npu.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "qwen3_asr_audio_gemm_seq.hpp" +#include "qwen3_asr_audio_simd.hpp" +#include "../omp_threads.hpp" + +namespace seqg = qwen3_asr_audio_gemm_seq; +namespace simd = qwen3_asr_audio_simd; + +namespace { + +constexpr float LO_SCALE = 256.f; // the rest of A is scaled up so the bias the cores add to it costs no precision + +inline uint16_t f32_to_bf16(float f) { // round to nearest even + uint32_t u; + std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x7FFFu + ((u >> 16) & 1u)) >> 16); +} +inline float bf16_to_f32(uint16_t b) { + const uint32_t u = (uint32_t)b << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +/// two bfp16 blocks from 16 floats (rounded to bf16 first), the same integer steps as seqg::encode_block, one block per 8 lanes. +/// rest (optional): (bf16(a) - its bfp16 value) * LO_SCALE +inline void encode2(uint8_t* o0, uint8_t* o1, const float* a, float* rest) { + const __m512i one = _mm512_set1_epi32(1); + __m512i u = _mm512_castps_si512(_mm512_loadu_ps(a)); + u = _mm512_srli_epi32(_mm512_add_epi32(u, _mm512_add_epi32(_mm512_set1_epi32(0x7FFF), _mm512_and_si512(_mm512_srli_epi32(u, 16), one))), 16); + const __m512i ex = _mm512_and_si512(_mm512_srli_epi32(u, 7), _mm512_set1_epi32(0xFF)); + const __m512i x1 = _mm512_set_epi32(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); + const __m512i x2 = _mm512_set_epi32(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2); + const __m512i x4 = _mm512_set_epi32(11, 10, 9, 8, 15, 14, 13, 12, 3, 2, 1, 0, 7, 6, 5, 4); + __m512i mx = _mm512_max_epi32(ex, _mm512_permutexvar_epi32(x1, ex)); + mx = _mm512_max_epi32(mx, _mm512_permutexvar_epi32(x2, mx)); + mx = _mm512_max_epi32(mx, _mm512_permutexvar_epi32(x4, mx)); + __m512i mag = _mm512_slli_epi32(_mm512_and_si512(u, _mm512_set1_epi32(0x7F)), 16); + mag = _mm512_mask_or_epi32(mag, _mm512_test_epi32_mask(ex, ex), mag, _mm512_set1_epi32(0x800000)); + const __m512i s = _mm512_mask_sub_epi32(mag, _mm512_test_epi32_mask(u, _mm512_set1_epi32(0x8000)), _mm512_setzero_si512(), mag); + const __m512i sh = _mm512_min_epi32(_mm512_sub_epi32(_mm512_add_epi32(mx, _mm512_set1_epi32(17)), ex), _mm512_set1_epi32(31)); + __m512i q = _mm512_srav_epi32(s, sh); + const __m512i rem = _mm512_sub_epi32(s, _mm512_sllv_epi32(q, sh)); + const __m512i half = _mm512_sllv_epi32(one, _mm512_sub_epi32(sh, one)); + const __mmask16 up = _mm512_cmpgt_epi32_mask(rem, half) | (_mm512_cmpeq_epi32_mask(rem, half) & _mm512_test_epi32_mask(q, one)); + q = _mm512_min_epi32(_mm512_mask_add_epi32(q, up, q, one), _mm512_set1_epi32(127)); + alignas(16) uint8_t qb[16], eb[16]; + _mm_store_si128((__m128i*)qb, _mm512_cvtepi32_epi8(q)); + _mm_store_si128((__m128i*)eb, _mm512_cvtepi32_epi8(mx)); + o0[0] = eb[0]; + std::memcpy(o0 + 1, qb, 8); + o1[0] = eb[8]; + std::memcpy(o1 + 1, qb + 8, 8); + if (rest) { // block value = q * 2^(mx - 133); blocks under 2^-120 decode to 0 (their rest is then the whole value) + const __m512 scale = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_max_epi32(_mm512_sub_epi32(mx, _mm512_set1_epi32(6)), _mm512_setzero_si512()), 23)); + const __m512 val = _mm512_mul_ps(_mm512_cvtepi32_ps(q), scale); + const __m512 a_bf = _mm512_castsi512_ps(_mm512_slli_epi32(u, 16)); + _mm512_storeu_ps(rest, _mm512_mul_ps(_mm512_sub_ps(a_bf, val), _mm512_set1_ps(LO_SCALE))); + } +} + +/// K padded to the kernel's chunk: 128, or 512 when the weights stream (more than KC_SINGLE chunks) +int pad_k(int K) { + const int k = (K + 127) / 128 * 128; + return k / 128 > (int)seqg::KC_SINGLE ? (K + 511) / 512 * 512 : k; +} + +/// one block of 8 (k = 8 k8 .. ; values past K, or of a missing row, are 0) the slow way: hi, and lo (optional) as in encode2 +void encode_tail(uint8_t* hi, uint8_t* lo, const float* a, int k8, int K) { + uint16_t v[8] = {}, w[8] = {}; + for (int i = 0; i < 8; i++) + if (a && 8 * k8 + i < K) v[i] = f32_to_bf16(a[8 * k8 + i]); + seqg::encode_block(hi, v); + if (!lo) return; + for (int i = 0; i < 8; i++) w[i] = f32_to_bf16((bf16_to_f32(v[i]) - std::ldexp((float)(int8_t)hi[1 + i], (int)hi[0] - 133)) * LO_SCALE); + seqg::encode_block(lo, w); +} + +/// rows [r0, r0 + rows) of A -> x: block (row / 16, kc), then [16 k tiles][2 row halves][8 rows][9 B]; the last block's rows past +/// rows are 0. KC: chunks of 128 k. lo (optional): the same for the rest of A, scaled by LO_SCALE. tmp: 16 K floats per thread for A. +/// A task packs a 16-row block: a block's bytes are written by one thread only, a whole kc at a time. +void pack_x(uint8_t* hi, uint8_t* lo, const qwen3_asr_audio_gemm::rows_fn& A, int K, int r0, int rows, int KC, float* tmp) { + constexpr size_t BLOCK = seqg::X_BLOCK_WORDS * 4; +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) schedule(dynamic) + for (int rb = 0; rb < (rows + 15) / 16; rb++) { + float* t = tmp + (size_t)omp_get_thread_num() * 16 * K; + const float* a[16]; + const bool full = rb * 16 + 16 <= rows; + for (int i = 0; i < 16; i++) a[i] = rb * 16 + i < rows ? A(r0 + rb * 16 + i, t + (size_t)i * K) : nullptr; + alignas(64) uint8_t bh[BLOCK], bl[BLOCK]; + for (int kc = 0; kc < KC; kc++) { + if (!full) { // a zero block is all zero bytes + std::memset(bh, 0, BLOCK); + std::memset(bl, 0, BLOCK); + } + for (int i = 0; i < 16; i++) { + if (!a[i]) continue; + uint8_t* h = bh + (i / 8) * 72 + (i % 8) * 9; + uint8_t* l = bl + (i / 8) * 72 + (i % 8) * 9; + for (int kt = 0; kt < 16; kt += 2) { + const int k8 = kc * 16 + kt; + if (8 * k8 + 16 <= K) { + float rest[16] = {}; + encode2(h + kt * 144, h + (kt + 1) * 144, a[i] + 8 * k8, lo ? rest : nullptr); + if (lo) encode2(l + kt * 144, l + (kt + 1) * 144, rest, nullptr); + } else { + encode_tail(h + kt * 144, lo ? l + kt * 144 : nullptr, a[i], k8, K); + encode_tail(h + (kt + 1) * 144, lo ? l + (kt + 1) * 144 : nullptr, a[i], k8 + 1, K); + } + } + } + std::memcpy(hi + ((size_t)rb * KC + kc) * BLOCK, bh, BLOCK); + if (lo) std::memcpy(lo + ((size_t)rb * KC + kc) * BLOCK, bl, BLOCK); + } + } +} + +/// W [N][K] -> chunk (nb, column, kc, half) = [4 jp][16 k tiles][2][8 columns][9 B], then the half's 64 bf16 biases +void pack_w(uint8_t* dst, const float* W, const float* bias, int N, int K, int n_pad, int k_pad) { + const int KC = k_pad / 128; + const size_t half_bytes = seqg::W_HALF_WORDS * 4; +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int n = 0; n < n_pad; n++) { + const int nb = n / 1024, col = (n / 128) % 8, h = (n / 64) % 2, jp = (n / 16) % 4, j = (n / 8) % 2, c8 = n % 8; + const uint16_t b = (n < N && bias) ? f32_to_bf16(bias[n]) : 0; + for (int kc = 0; kc < KC; kc++) { + uint8_t* chunk = dst + ((((size_t)nb * 8 + col) * KC + kc) * 2 + h) * half_bytes; + for (int kt = 0; kt < 16; kt++) { + uint16_t v[8] = {}; + if (n < N) + for (int i = 0; i < 8; i++) { + const int k = kc * 128 + kt * 8 + i; + if (k < K) v[i] = f32_to_bf16(W[(size_t)n * K + k]); + } + seqg::encode_block(chunk + ((jp * 16 + kt) * 2 + j) * 72 + c8 * 9, v); + } + std::memcpy(chunk + 9216 + 2 * (n % 64), &b, 2); + } + } +} + +} // namespace + +qwen3_asr_audio_gemm_npu::qwen3_asr_audio_gemm_npu(npu_app_manager* mgr, std::mutex* npu_lock) + : mgr_(mgr), io_app_(mgr->create_app()), mu_(npu_lock ? *npu_lock : own_mu_) {} + +int qwen3_asr_audio_gemm_npu::add_weight(const float* W, int N, int K, const float* bias, bool exact_a, bool exact_w) { + if (N % 16) throw std::runtime_error("qwen3_asr_audio_gemm_npu: N must be a multiple of 16"); + auto w = std::make_unique(); + w->N = N; + w->K = K; + w->n_pad = ((exact_w ? 2 : 1) * N + 1023) / 1024 * 1024; + w->k_pad = pad_k(K); + w->split = exact_a; + w->split_w = exact_w; + w->bias.assign(N, 0.f); + if (bias) + for (int n = 0; n < N; n++) w->bias[n] = bf16_to_f32(f32_to_bf16(bias[n])); + std::vector w2, b2; + if (exact_w) { // [W; (W - its bfp16 value) * LO_SCALE], the rest without bias + w2.assign((size_t)2 * N * K, 0.f); + std::memcpy(w2.data(), W, sizeof(float) * N * K); + b2.assign(2 * N, 0.f); + if (bias) std::memcpy(b2.data(), bias, sizeof(float) * N); +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int n = 0; n < N; n++) + for (int k0 = 0; k0 < K; k0 += 8) { + uint16_t v[8] = {}; + uint8_t e[9]; + for (int i = 0; i < 8 && k0 + i < K; i++) v[i] = f32_to_bf16(W[(size_t)n * K + k0 + i]); + seqg::encode_block(e, v); + for (int i = 0; i < 8 && k0 + i < K; i++) + w2[(size_t)(N + n) * K + k0 + i] = (bf16_to_f32(v[i]) - std::ldexp((float)(int8_t)e[1 + i], (int)e[0] - 133)) * LO_SCALE; + } + W = w2.data(); + bias = b2.data(); + N *= 2; + } + w->w = io_app_.create_bo_buffer(seqg::w_bytes(w->n_pad, w->k_pad)); + pack_w(w->w.data(), W, bias, N, K, w->n_pad, w->k_pad); + w->w.sync_to_device(); + weights_.push_back(std::move(w)); + return (int)weights_.size() - 1; +} + +npu_app& qwen3_asr_audio_gemm_npu::app_for(uint32_t rounds, uint32_t kc, uint32_t nb) { + const shape_t s{rounds, kc, nb}; + auto it = apps_.find(s); + if (it != apps_.end()) return *it->second; + auto app = std::make_unique(mgr_->create_app()); + seqg::call_t call{rounds, kc, nb, nb * seqg::BLOCK_COLS, /*act=*/0}; + seqg::gen_gemm(app->seq(), call); + return *apps_.emplace(s, std::move(app)).first->second; +} + +void qwen3_asr_audio_gemm_npu::grow(size_t x_bytes, size_t y_elems, int k) { + if (x_.size() < x_bytes) x_ = io_app_.create_bo_buffer(x_bytes); + if (y_.size() < y_elems) y_ = io_app_.create_bo_buffer(y_elems); + const size_t t = (size_t)qwen3_asr_cpu::asr_threads() * 16 * k; + if (tmp_.size() < t) tmp_.resize(t); +} + +void qwen3_asr_audio_gemm_npu::run(int weight, const rows_fn& A, int M, float* C, bool gelu) { + std::lock_guard lock(mu_); + weight_t& w = *weights_.at(weight); + grow(0, 0, w.K); + run_packed(w, M, C, gelu, [&](uint8_t* hi, uint8_t* lo, int r0, int rows, int KC) { pack_x(hi, lo, A, w.K, r0, rows, KC, tmp_.data()); }); +} + +void qwen3_asr_audio_gemm_npu::run_conv(int weight, const float* in, int count, int H, int W, int cin, int K, float* C, bool gelu) { + if (cin % 16 || K != weights_.at(weight)->K || K < 9 * cin) return qwen3_asr_audio_gemm::run_conv(weight, in, count, H, W, cin, K, C, gelu); + std::lock_guard lock(mu_); + weight_t& w = *weights_.at(weight); + constexpr size_t BLOCK = seqg::X_BLOCK_WORDS * 4; + const int cb = cin / 8, Wo = (W + 1) / 2, per = (H + 1) / 2 * Wo; // blocks per pixel, output pixels per image + const size_t npix = (size_t)count * H * W, pb = (size_t)cb * 9; // bytes of a pixel's blocks + if (px_hi_.size() < npix * pb + pb) px_hi_.resize(npix * pb + pb); // + one zero pixel (the padding) + if (w.split && px_lo_.size() < npix * pb + pb) px_lo_.resize(npix * pb + pb); + uint8_t* lo_px = w.split ? px_lo_.data() : nullptr; +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int64_t p = 0; p <= (int64_t)npix; p++) { // signed: MSVC's OpenMP + uint8_t* h = px_hi_.data() + p * pb; + uint8_t* l = lo_px ? lo_px + p * pb : nullptr; + if (p == (int64_t)npix) { + std::memset(h, 0, pb); + if (l) std::memset(l, 0, pb); + continue; + } + for (int b = 0; b < cb; b += 2) { + float rest[16] = {}; + encode2(h + b * 9, h + (b + 1) * 9, in + p * cin + b * 8, l ? rest : nullptr); + if (l) encode2(l + b * 9, l + (b + 1) * 9, rest, nullptr); + } + } + // a row's 9 taps (kh, kw) are blocks [tap cb, tap cb + cb); blocks from 9 cb on are zero + run_packed(w, count * per, C, gelu, [&](uint8_t* hi, uint8_t* lo, int r0, int rows, int KC) { + const int k8_end = 9 * cb, kc_tail = k8_end / 16; +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) schedule(dynamic) + for (int rb = 0; rb < (rows + 15) / 16; rb++) { + const bool full = rb * 16 + 16 <= rows; + for (int s = 0; s < (lo ? 2 : 1); s++) { + uint8_t* dst = (s ? lo : hi) + (size_t)rb * KC * BLOCK; + const uint8_t* src = s ? lo_px : px_hi_.data(); + const int kc0 = full ? kc_tail : 0; + std::memset(dst + (size_t)kc0 * BLOCK, 0, (size_t)(KC - kc0) * BLOCK); + for (int i = 0; i < 16 && rb * 16 + i < rows; i++) { + const int r = r0 + rb * 16 + i, img = r / per, ho = r % per / Wo, wo = r % per % Wo; + uint8_t* d = dst + (i / 8) * 72 + (i % 8) * 9; + for (int tap = 0; tap < 9; tap++) { + const int y = 2 * ho - 1 + tap / 3, x = 2 * wo - 1 + tap % 3; + const size_t pix = (y < 0 || y >= H || x < 0 || x >= W) ? npix : ((size_t)img * H + y) * W + x; + const uint8_t* sp = src + pix * pb; + for (int b = 0; b < cb; b++) { + const int k8 = tap * cb + b; + std::memcpy(d + (size_t)(k8 / 16) * BLOCK + (k8 % 16) * 144, sp + b * 9, 9); + } + } + } + } + } + }); +} + +void qwen3_asr_audio_gemm_npu::run_packed(weight_t& w, int M, float* C, bool gelu, const pack_fn& pack) { + const uint32_t KC = w.k_pad / 128, NB = w.n_pad / 1024; + const bool stream = KC > seqg::KC_SINGLE; + // split: A's rest goes as more rows of the same call (right after A's rows, from a 16-row boundary), so the weights are + // read once for both + const int parts = w.split ? 2 : 1; + const int cap = (int)(stream ? std::min(seqg::MAX_ROUNDS, seqg::MAX_QUEUE_REPEAT / KC) : seqg::MAX_ROUNDS) * 256 / parts; + const int calls = (M + cap - 1) / cap; + const int per = ((M + calls - 1) / calls + 15) / 16 * 16; // rows of A per call, spread evenly + static const bool prof = std::getenv("QWEN3_ASR_GEMM_PROF") != nullptr; + using clk = std::chrono::steady_clock; + for (int m0 = 0; m0 < M; m0 += per) { + const int rows = std::min(per, M - m0), rows16 = (rows + 15) / 16 * 16, R = (parts * rows16 + 255) / 256; + const size_t xb = seqg::x_bytes(rows16, w.k_pad), xr = seqg::x_bytes(R * 256, w.k_pad), ye = (size_t)rows16 * w.n_pad; + grow(xr, (size_t)R * 256 * w.n_pad, w.K); + const auto t0 = clk::now(); + pack(x_.data(), w.split ? x_.data() + xb : nullptr, m0, rows, KC); + std::memset(x_.data() + parts * xb, 0, xr - parts * xb); + x_.sync_to_device_bytes(xr); + const auto t1 = clk::now(); + app_for((uint32_t)R, KC, NB)(y_, x_, w.w); + const auto t2 = clk::now(); + y_.sync_from_device_bytes(parts * ye * sizeof(u16)); +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int r = 0; r < rows; r++) { + const uint16_t* yh = y_.data() + (size_t)r * w.n_pad; + const uint16_t* yl = yh + ye; + float* out = C + (size_t)(m0 + r) * w.N; + for (int n = 0; n < w.N; n += 16) { + __m512 v = simd::load_bf16(yh + n); + // the rests, scaled by LO_SCALE: A times W's (columns N..), A's times W (more rows, plus the bias) + __m512 rest = _mm512_setzero_ps(); + if (w.split_w) rest = simd::load_bf16(yh + w.N + n); + if (w.split) rest = _mm512_add_ps(rest, _mm512_sub_ps(simd::load_bf16(yl + n), _mm512_loadu_ps(w.bias.data() + n))); + if (w.split || w.split_w) v = simd::round_bf16(_mm512_fmadd_ps(rest, _mm512_set1_ps(1.f / LO_SCALE), v)); + if (gelu) v = simd::round_bf16(simd::gelu_erf(v)); + _mm512_storeu_ps(out + n, v); + } + } + if (prof) { + const auto t3 = clk::now(); + auto ms = [](clk::duration d) { return std::chrono::duration(d).count(); }; + std::fprintf(stderr, "[gemm] M %d K %d N %d R %d x%d: pack %.2f npu %.2f unpack %.2f ms\n", M, w.K, w.N, R, parts, ms(t1 - t0), + ms(t2 - t1), ms(t3 - t2)); + } + } +} diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_npu.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_npu.hpp new file mode 100644 index 000000000..2e0180e33 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_npu.hpp @@ -0,0 +1,67 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file qwen3_asr_audio_gemm_npu.hpp +/// \brief The audio encoder's matrix products on the NPU (audio_gemm.xclbin, built from FLM_Xclbin/bfp16_gemm). +/// +/// Weights are packed to bfp16 once, at load, one BO each (K padded to 128, or 512 when the weights stream; N padded +/// to 1024). A product packs A into the X BO, runs as many calls as its rows need (a call takes at most 31 rounds of +/// 256 rows, and 256 / KC rounds when the weights stream) and unpacks the bf16 result. The bias is added on the cores; +/// the erf GELU runs on the host while unpacking (the cores' tanh form costs too much accuracy). K is not cut into +/// parts added on the host: the conv stack's partial sums over kernel positions nearly cancel on quiet input, and +/// rounding each to bf16 costs accuracy there. +/// +/// bfp16 keeps about 7 bits of an activation, less for values well below the largest of their block of 8. For a product +/// added with exact_a, the rest of A (scaled up) is packed as more rows of the same call and the host adds the two +/// results: A then keeps its bf16 precision. For a weight added with exact_w, the rest of W (scaled up) is packed as N +/// more output columns, so the same call also returns A times the rest; where N is at most 512 those columns are padding +/// anyway (conv2 and conv3). Both keep the encoder as close to its bf16 reference as the host path; without them the +/// conv stack drifts on quiet input, where its output is a small signal over the bias. +/// Calls are serialized: the engine encodes in the foreground and in the background. +#pragma once +#include +#include +#include +#include +#include + +#include "typedef.hpp" +#include "npu_utils/npu_utils.hpp" +#include "qwen3_asr_audio_encoder.hpp" + +class qwen3_asr_audio_gemm_npu : public qwen3_asr_audio_gemm { +public: + /// \param mgr the app manager of audio_gemm.xclbin + /// \param npu_lock held during each call: the engine's lock of the NPU (nullptr: a lock of its own) + explicit qwen3_asr_audio_gemm_npu(npu_app_manager* mgr, std::mutex* npu_lock = nullptr); + int add_weight(const float* W, int N, int K, const float* bias, bool exact_a, bool exact_w) override; + void run(int weight, const rows_fn& A, int M, float* C, bool gelu) override; + /// encodes each input pixel once (cin values = cin / 8 blocks, so a block never spans two pixels), then gathers the blocks + /// of each im2col row: the same bytes as run() on the rows + void run_conv(int weight, const float* in, int count, int H, int W, int cin, int K, float* C, bool gelu) override; + +private: + struct weight_t { + buffer w; // [W; rest of W] when split_w + int N = 0, K = 0, n_pad = 0, k_pad = 0; + bool split = false, split_w = false; + std::vector bias; // bf16 values, what the cores add + }; + using shape_t = std::tuple; // rounds, kc, nb + npu_app& app_for(uint32_t rounds, uint32_t kc, uint32_t nb); + void grow(size_t x_bytes, size_t y_elems, int k); + /// packs rows [r0, r0 + rows) of A into hi (and their rest into lo when lo is given), KC chunks of 128 k + using pack_fn = std::function; + void run_packed(weight_t& w, int M, float* C, bool gelu, const pack_fn& pack); + + npu_app_manager* mgr_; + std::vector> weights_; // never moved: a copied XRT buffer does not own its BO + std::map> apps_; + npu_app io_app_; // owns no sequence: creates the X and Y buffers + buffer x_; // A rounded to bfp16, then its rest (split weights) + buffer y_; + std::vector tmp_; // 16 rows of A per thread + std::vector px_hi_, px_lo_; // run_conv: the input pixels as blocks, [pixel][cin / 8][9 B] + std::mutex own_mu_; + std::mutex& mu_; +}; diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_seq.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_seq.hpp new file mode 100644 index 000000000..dfd296bac --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_gemm_seq.hpp @@ -0,0 +1,243 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file qwen3_asr_audio_gemm_seq.hpp +/// \brief Run-time sequence of the bfp16 GEMM (iron/gemm_aie.py): Y = act(X W^T + b), bf16 out. +/// +/// Copy of FLM_Xclbin/bfp16_gemm/host/seq_gen.hpp and pack_bfp16.hpp in this engine's namespace (engines do not share +/// headers with inline functions); keep the two in sync with the kernel. +/// +/// One call runs R rounds of 256 rows against NB blocks of 1024 output columns, K = 128 KC. +/// Weights go through the memtiles in one of two modes: +/// panel (KC <= 24): a column's whole block of weights stays in its memtile and is sent R times; +/// read from DDR once per call. With KC <= 12 (hybrid) round 1 starts on the first +/// chunk instead of waiting for the whole panel. +/// stream (KC > 24, or forced): the memtile is a ring of chunk slots refilled from DDR; the weights +/// are read once per round. KC multiple of 4, KC R <= 256 per call. +/// DDR layouts (all bfp16ebs8, 9 B per 8 k; see pack_bfp16.hpp for the block encoding): +/// x [M / 16 row blocks][KC][16 k tiles][2 row halves][8 rows][9 B] (2304 B per block and kc) +/// w [NB][8 columns][KC][lo | hi][4 jp][16 k tiles][2][8 columns][9 B] + 64 bf16 bias (9344 B per half) +/// y bf16 row-major, row pitch ldy elements +/// The memtile weight path is not in the design: each call writes its descriptors, panel locks and +/// start queues (check_memtile_bds.py verifies at build time that the design leaves them free). +#pragma once +#include +#include +#include "npu_utils/npu_utils.hpp" + +namespace qwen3_asr_audio_gemm_seq { + +/// 8 bf16 -> one 9 B block: the largest fp32 exponent field of the 8, then each +/// value's signed 24-bit mantissa shifted right by (17 + max_exp - exp), capped at +/// 31, rounded to nearest even (what the core's own bf16 -> bfp16 conversion does +/// under conv_even). A value is mantissa x 2^(exponent - 133). +inline void encode_block(uint8_t* out, const uint16_t* v) { + int ex[8], mx = 0; + for (int i = 0; i < 8; i++) { ex[i] = (v[i] >> 7) & 0xFF; if (ex[i] > mx) mx = ex[i]; } + out[0] = (uint8_t)mx; + for (int i = 0; i < 8; i++) { + int32_t mag = (int32_t)(((uint32_t)v[i] & 0x7Fu) << 16); + if (ex[i]) mag |= 0x800000; + const int32_t s = (v[i] & 0x8000u) ? -mag : mag; + int sh = 17 + mx - ex[i]; if (sh > 31) sh = 31; + int32_t q = s >> sh; + const int32_t rem = s - (int32_t)((uint32_t)q << sh), half = 1 << (sh - 1); + if (rem > half || (rem == half && (q & 1))) q++; + if (q > 127) q = 127; + out[1 + i] = (uint8_t)(int8_t)q; + } +} + +// core RTP (iron/gemm_tile.py RTP_ADDR): [0] KC, [1] rounds of 256 rows (all N blocks), [2] act +static constexpr uint32_t CT_RTP_ADDR = 58112; + +static constexpr uint32_t X_BLOCK_WORDS = 576; // 16 rows x 128 k +static constexpr uint32_t W_HALF_WORDS = 2336; // 64 columns x 128 k + 64 bf16 bias +static constexpr uint32_t W_CHUNK_WORDS = 2 * W_HALF_WORDS; +static constexpr uint32_t ROUND_ROWS = 256, BLOCK_COLS = 1024, COLUMNS = 8, CORE_ROWS = 4; +static constexpr uint32_t MAX_ROUNDS = 31; // panel locks count 2 credits per round, 7-bit lock values +static constexpr uint32_t KC_DOUBLE = 12, KC_SINGLE = 24; // panel fits twice / once in the memtile + +// memtile (row 1); keep in sync with iron/gemm_tile.py and check_memtile_bds.py +static constexpr uint32_t MT_BD_BASE = 0xA0000, MT_BD_STRIDE = 0x20, MT_LOCK_BASE = 0xC0000, MT_LOCK_STRIDE = 0x10; +static constexpr uint32_t MT_OWN_WORDS = 0x80000 / 4, MT_OWN_LOCK = 64; +static constexpr uint32_t MT_PANEL_ADDR[2] = {65536, 294912}; +static constexpr uint32_t MT_S2MM0_BD[2] = {20, 21}, MT_LO_BD[2] = {22, 23}, MT_HI_BD[2] = {44, 45}; +static constexpr uint32_t MT_PANEL_PROD[2] = {8, 9}, MT_PANEL_CONS[2] = {10, 11}; +static constexpr uint32_t MT_S2MM0_QUEUE = 0xA0604, MT_MM2S0_QUEUE = 0xA0634, MT_MM2S1_QUEUE = 0xA063C; +// stream mode: ring at panel 0's address; locks: free slots, lo half ready, hi half ready +static constexpr uint32_t MT_RING_FREE = 8, MT_RING_LO = 10, MT_RING_HI = 11; +// hybrid mode: per panel "chunk lo ready" / "chunk hi ready" locks; rounds 2..R send the panel with these BDs +static constexpr uint32_t MT_CHUNK_LO[2] = {8, 9}, MT_CHUNK_HI[2] = {10, 11}; +static constexpr uint32_t MT_LO_PANEL_BD[2] = {18, 19}, MT_HI_PANEL_BD[2] = {46, 47}; +static constexpr uint32_t MAX_QUEUE_REPEAT = 256; // start queue repeat field: 8 bits + +inline uint32_t mt_lock_word(uint32_t acq_id, int acq_ge, uint32_t rel_id, int rel_val) { + return (1u << 31) | ((uint32_t)(rel_val & 0x7F) << 24) | ((MT_OWN_LOCK + rel_id) << 16) | (1u << 15) | + ((uint32_t)(-acq_ge & 0x7F) << 8) | (MT_OWN_LOCK + acq_id); +} +inline uint32_t mt_release_word(uint32_t rel_id, int rel_val) { + return (1u << 31) | ((uint32_t)(rel_val & 0x7F) << 24) | ((MT_OWN_LOCK + rel_id) << 16); +} +inline uint32_t mt_acquire_word(uint32_t acq_id, int acq_ge) { + return (1u << 31) | (1u << 15) | ((uint32_t)(-acq_ge & 0x7F) << 8) | (MT_OWN_LOCK + acq_id); +} +inline uint32_t mt_dim(uint32_t wrap, uint32_t stride) { return (wrap << 17) | (stride - 1); } +inline uint32_t mt_iter(uint32_t wrap, uint32_t stride) { return ((wrap - 1) << 17) | (stride - 1); } + +/// One call's shape. x_words / y_elems / w_bytes: offsets into the three buffers. +struct call_t { + uint32_t rounds; //!< R: 256-row rounds, <= MAX_ROUNDS + uint32_t kc; //!< K / 128, <= KC_SINGLE + uint32_t nb; //!< N blocks of 1024 columns + uint32_t ldy; //!< row pitch of y in elements (>= 1024 nb) + uint32_t act; //!< 0 none, 1 GELU (tanh form) + size_t x_words = 0; //!< first 16-row block of x + size_t w_words = 0; //!< first N block of w + size_t y_elems = 0; //!< y[0][0] of this call + cache_flag_t x_cache = normal_cache; //!< x is read once per N block + bool stream = false; //!< stream mode even if the panel fits (KC > KC_SINGLE always streams) + bool hybrid = true; //!< KC <= KC_DOUBLE: round 1 sends each chunk as it lands (false: after the whole panel) +}; + +inline bool streams(const call_t& c) { return c.stream || c.kc > KC_SINGLE; } +inline bool hybrids(const call_t& c) { return c.hybrid && !streams(c) && c.kc <= KC_DOUBLE; } + +inline size_t x_bytes(uint32_t m_pad, uint32_t K) { return (size_t)m_pad / 16 * (K / 128) * X_BLOCK_WORDS * 4; } +inline size_t w_bytes(uint32_t N, uint32_t K) { return (size_t)N / 128 * (K / 128) * W_CHUNK_WORDS * 4; } + +/// Arguments: 0 = y (bf16), 1 = x (bfp16), 2 = w (bfp16 + bias). +inline void gen_gemm(npu_sequence* seq, const call_t& c) { + static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + assert(c.rounds >= 1 && c.rounds <= MAX_ROUNDS); + const bool stream = streams(c); + assert(c.kc >= 1 && c.nb >= 1); + assert(!stream || (c.kc % 4 == 0 && c.kc * c.rounds <= MAX_QUEUE_REPEAT)); + assert((uint64_t)16 * c.kc * X_BLOCK_WORDS <= (1u << 20)); // x round stride, in words + assert(c.ldy % 2 == 0 && c.ldy >= BLOCK_COLS * c.nb); + assert((uint64_t)128 * c.ldy <= (1u << 20)); // y round stride, in words + const uint32_t R = c.rounds, KC = c.kc; + const bool two_panels = !stream && KC <= KC_DOUBLE, hybrid = hybrids(c); + const uint32_t panel_words = KC * W_CHUNK_WORDS; + // ring slots divide the chunks of one N block, so a slot sequence restarted per task lands on + // the same addresses as one carried over + const uint32_t slots = (KC * R) % 8 == 0 ? 8 : 4; + + seq->clear_cmds(); + for (int row = 2; row < 6; row++) + for (uint32_t col = 0; col < COLUMNS; col++) { + const npu_tiles t = get_tile(row, col); + seq->rtp_write(t, CT_RTP_ADDR, KC); + seq->rtp_write(t, CT_RTP_ADDR + 4, R * c.nb); + seq->rtp_write(t, CT_RTP_ADDR + 8, c.act); + } + + // memtile weight path. Panel b: S2MM0 fills it once per N block, then MM2S0 (lo halves) and MM2S1 + // (hi halves) send it R times each (start-queue repeats; the descriptor's locks run on every repeat). + // The fill takes 2R producer credits and gives 2R consumer credits; each repeat of either channel takes + // one consumer credit and returns one producer credit. A channel's task has exactly R repeats, so + // neither channel can use the other's credits. + // Stream mode: S2MM0 fills one slot per chunk (takes a free slot, gives "lo ready"), MM2S0 sends its + // lo half (gives "hi ready"), MM2S1 its hi half (frees the slot). One descriptor per channel, its + // iteration walks the ring, the start-queue repeat runs it once per chunk. + // Hybrid mode (two panels): S2MM0 fills the panel chunk by chunk (gives "lo ready"); round 1 sends each + // chunk as it lands (MM2S0: takes "lo ready", gives "hi ready"; MM2S1 takes "hi ready"), rounds 2..R + // send the resident panel without locks. No lock guards the refill: the host has waited for y of + // N block j - 2, the panel's previous user, before it pushes block j. + auto bd_word = [](uint32_t bd, uint32_t w) { return MT_BD_BASE + MT_BD_STRIDE * bd + 4 * w; }; + for (uint32_t col = 0; col < COLUMNS; col++) { + const npu_tiles mt = get_tile(1, col); + if (stream) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_RING_FREE, slots); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_RING_LO, 0); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_RING_HI, 0); + const uint32_t base = MT_OWN_WORDS + MT_PANEL_ADDR[0] / 4, it = mt_iter(slots, W_CHUNK_WORDS); + const uint32_t fill[8] = {W_CHUNK_WORDS, base, 0, 0, 0, 0, it, mt_lock_word(MT_RING_FREE, 1, MT_RING_LO, 1)}; + const uint32_t lo[8] = {W_HALF_WORDS, base, 0, 0, 0, 0, it, mt_lock_word(MT_RING_LO, 1, MT_RING_HI, 1)}; + const uint32_t hi[8] = {W_HALF_WORDS, base + W_HALF_WORDS, 0, 0, 0, 0, it, mt_lock_word(MT_RING_HI, 1, MT_RING_FREE, 1)}; + for (uint32_t w = 0; w < 8; w++) { + seq->rtp_write(mt, bd_word(MT_S2MM0_BD[0], w), fill[w]); + seq->rtp_write(mt, bd_word(MT_LO_BD[0], w), lo[w]); + seq->rtp_write(mt, bd_word(MT_HI_BD[0], w), hi[w]); + } + continue; + } + if (hybrid) { + for (uint32_t b = 0; b < 2; b++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_CHUNK_LO[b], 0); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_CHUNK_HI[b], 0); + const uint32_t base = MT_OWN_WORDS + MT_PANEL_ADDR[b] / 4, it = mt_iter(KC, W_CHUNK_WORDS); + const uint32_t fill[8] = {W_CHUNK_WORDS, base, 0, 0, 0, 0, it, mt_release_word(MT_CHUNK_LO[b], 1)}; + const uint32_t lo[8] = {W_HALF_WORDS, base, 0, 0, 0, 0, it, mt_lock_word(MT_CHUNK_LO[b], 1, MT_CHUNK_HI[b], 1)}; + const uint32_t hi[8] = {W_HALF_WORDS, base + W_HALF_WORDS, 0, 0, 0, 0, it, mt_acquire_word(MT_CHUNK_HI[b], 1)}; + for (uint32_t w = 0; w < 8; w++) { + seq->rtp_write(mt, bd_word(MT_S2MM0_BD[b], w), fill[w]); + seq->rtp_write(mt, bd_word(MT_LO_BD[b], w), lo[w]); + seq->rtp_write(mt, bd_word(MT_HI_BD[b], w), hi[w]); + } + for (uint32_t h = 0; h < 2 && R > 1; h++) { + const uint32_t send[8] = {KC * W_HALF_WORDS, base + h * W_HALF_WORDS, + mt_dim(584, 1), mt_dim(4, 584), mt_dim(KC, W_CHUNK_WORDS), 0, 0, 1u << 31}; + const uint32_t bd = h ? MT_HI_PANEL_BD[b] : MT_LO_PANEL_BD[b]; + for (uint32_t w = 0; w < 8; w++) seq->rtp_write(mt, bd_word(bd, w), send[w]); + } + } + continue; + } + for (uint32_t b = 0; b < (two_panels ? 2u : 1u); b++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_PANEL_PROD[b], 2 * R); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_PANEL_CONS[b], 0); + const uint32_t base = MT_OWN_WORDS + MT_PANEL_ADDR[b] / 4; + const uint32_t fill[8] = {panel_words, base, 0, 0, 0, 0, 0, + mt_lock_word(MT_PANEL_PROD[b], 2 * (int)R, MT_PANEL_CONS[b], 2 * (int)R)}; + for (uint32_t w = 0; w < 8; w++) seq->rtp_write(mt, bd_word(MT_S2MM0_BD[b], w), fill[w]); + for (uint32_t h = 0; h < 2; h++) { + // [kc][lo | hi] -> one half of every chunk: 584 x 4 contiguous words, then the next chunk + const uint32_t send[8] = {KC * W_HALF_WORDS, base + h * W_HALF_WORDS, + mt_dim(584, 1), mt_dim(4, 584), mt_dim(KC, W_CHUNK_WORDS), 0, 0, + mt_lock_word(MT_PANEL_CONS[b], 1, MT_PANEL_PROD[b], 1)}; + const uint32_t bd = h ? MT_HI_BD[b] : MT_LO_BD[b]; + for (uint32_t w = 0; w < 8; w++) seq->rtp_write(mt, bd_word(bd, w), send[w]); + } + } + } + + for (uint32_t j = 0; j < c.nb; j++) { + const uint32_t b = two_panels ? (j & 1) : 0; + const uint32_t o = (j & 1) * 4; + const uint32_t fills = stream ? KC * R : hybrid ? KC : 1, sends = stream ? KC * R : hybrid ? KC : R; + for (uint32_t col = 0; col < COLUMNS; col++) { + const npu_tiles mt = get_tile(1, col); + seq->rtp_write(mt, MT_S2MM0_QUEUE, ((fills - 1) << 16) | MT_S2MM0_BD[b]); + seq->rtp_write(mt, MT_MM2S0_QUEUE, ((sends - 1) << 16) | MT_LO_BD[b]); + seq->rtp_write(mt, MT_MM2S1_QUEUE, ((sends - 1) << 16) | MT_HI_BD[b]); + if (hybrid && R > 1) { + seq->rtp_write(mt, MT_MM2S0_QUEUE, ((R - 2) << 16) | MT_LO_PANEL_BD[b]); + seq->rtp_write(mt, MT_MM2S1_QUEUE, ((R - 2) << 16) | MT_HI_PANEL_BD[b]); + } + } + for (uint32_t col = 0; col < COLUMNS; col++) { + // weights: the column's whole panel of this N block (stream mode: once per round) + seq->npu_dma_memcpy_nd(4, 2, MM2S, IT[col], npu_bd_id(0 + o), it_channel_0, + {0, 0, 0, (uint32_t)(c.w_words + ((size_t)j * COLUMNS + col) * panel_words)}, + {stream ? R : 1, 1, 1, panel_words}, {0, 0, 0, 1}, -1, 0, false, aggressive_cache); + // y: R rounds of 256 rows x the column's 128 columns + seq->npu_dma_memcpy_nd(4, 0, S2MM, IT[col], npu_bd_id(2 + o), it_channel_0, + {0, 0, 0, (uint32_t)((c.y_elems + (size_t)j * BLOCK_COLS + 128 * col) / 2)}, + {R, 1, ROUND_ROWS, 64}, {128 * c.ldy, 0, c.ldy / 2, 1}, -1, 0, true); + } + for (uint32_t r = 0; r < CORE_ROWS; r++) { + // x of core row r: per round, per kc, its 4 strips (16-row blocks 16 t + 4 r + s) + seq->npu_dma_memcpy_nd(4, 1, MM2S, IT[r], npu_bd_id(1 + o), it_channel_1, + {0, 0, 0, (uint32_t)(c.x_words + (size_t)4 * r * KC * X_BLOCK_WORDS)}, + {R, KC, 4, X_BLOCK_WORDS}, {16 * KC * X_BLOCK_WORDS, X_BLOCK_WORDS, KC * X_BLOCK_WORDS, 1}, + -1, 0, false, c.x_cache); + } + if (j > 0) + for (uint32_t col = 0; col < COLUMNS; col++) seq->npu_dma_wait(IT[col], S2MM, it_channel_0); + } + for (uint32_t col = 0; col < COLUMNS; col++) seq->npu_dma_wait(IT[col], S2MM, it_channel_0); + seq->cmds2seq(); +} + +} // namespace qwen3_asr_audio_gemm_seq diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_simd.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_simd.hpp new file mode 100644 index 000000000..4ba96a7b6 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/qwen3_asr_audio_simd.hpp @@ -0,0 +1,58 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file qwen3_asr_audio_simd.hpp +/// \brief AVX-512 helpers of the audio encoder, 16 lanes: bf16 rounding, exp and the exact (erf) GELU. +#pragma once +#include + +namespace qwen3_asr_audio_simd { + +/// round to bf16 (nearest even), kept as fp32 +inline __m512 round_bf16(__m512 v) { + __m512i u = _mm512_castps_si512(v); + u = _mm512_add_epi32(u, _mm512_add_epi32(_mm512_set1_epi32(0x7FFF), _mm512_and_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(1)))); + return _mm512_castsi512_ps(_mm512_and_si512(u, _mm512_set1_epi32((int)0xFFFF0000u))); +} + +/// 16 bf16 bit patterns -> fp32 +inline __m512 load_bf16(const uint16_t* p) { + return _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(_mm256_loadu_si256((const __m256i*)p)), 16)); +} + +/// e^x for x in [-87, 88] (clamped outside), within 2 ulp of std::exp: Cody-Waite reduction, then a degree-7 polynomial +inline __m512 exp(__m512 x) { + x = _mm512_min_ps(_mm512_max_ps(x, _mm512_set1_ps(-87.f)), _mm512_set1_ps(88.f)); + const __m512 n = _mm512_roundscale_ps(_mm512_mul_ps(x, _mm512_set1_ps(1.44269504088896341f)), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); + __m512 r = _mm512_fnmadd_ps(n, _mm512_set1_ps(0.693359375f), x); + r = _mm512_fnmadd_ps(n, _mm512_set1_ps(-2.12194440e-4f), r); + __m512 p = _mm512_fmadd_ps(r, _mm512_set1_ps(1.9875691500e-4f), _mm512_set1_ps(1.3981999507e-3f)); + p = _mm512_fmadd_ps(p, r, _mm512_set1_ps(8.3334519073e-3f)); + p = _mm512_fmadd_ps(p, r, _mm512_set1_ps(4.1665795894e-2f)); + p = _mm512_fmadd_ps(p, r, _mm512_set1_ps(1.6666665459e-1f)); + p = _mm512_fmadd_ps(p, r, _mm512_set1_ps(5.0000001201e-1f)); + p = _mm512_fmadd_ps(p, _mm512_mul_ps(r, r), _mm512_add_ps(r, _mm512_set1_ps(1.f))); + return _mm512_scalef_ps(p, n); +} + +/// 0.5 x (1 + erf(x / sqrt 2)); erf from a rational approximation (fp32 accuracy, its argument clamped to [-4, 4]). Rounded to +/// bf16 it equals the std::erf form but for a few inputs below -3.9, where the result is under 3e-4 and off by one bf16 step. +inline __m512 gelu_erf(__m512 x) { + const __m512 z = _mm512_max_ps(_mm512_min_ps(_mm512_mul_ps(x, _mm512_set1_ps(0.70710678118654752440f)), _mm512_set1_ps(4.f)), + _mm512_set1_ps(-4.f)); + const __m512 z2 = _mm512_mul_ps(z, z); + __m512 p = _mm512_fmadd_ps(z2, _mm512_set1_ps(-2.72614225801306e-10f), _mm512_set1_ps(2.77068142495902e-08f)); + p = _mm512_fmadd_ps(z2, p, _mm512_set1_ps(-2.10102402082508e-06f)); + p = _mm512_fmadd_ps(z2, p, _mm512_set1_ps(-5.69250639462346e-05f)); + p = _mm512_fmadd_ps(z2, p, _mm512_set1_ps(-7.34990630326855e-04f)); + p = _mm512_fmadd_ps(z2, p, _mm512_set1_ps(-2.95459980854025e-03f)); + p = _mm512_fmadd_ps(z2, p, _mm512_set1_ps(-1.60960333262415e-02f)); + p = _mm512_mul_ps(z, p); + __m512 q = _mm512_fmadd_ps(z2, _mm512_set1_ps(-1.45660718464996e-05f), _mm512_set1_ps(-2.13374055278905e-04f)); + q = _mm512_fmadd_ps(z2, q, _mm512_set1_ps(-1.68282697438203e-03f)); + q = _mm512_fmadd_ps(z2, q, _mm512_set1_ps(-7.37332916720468e-03f)); + q = _mm512_fmadd_ps(z2, q, _mm512_set1_ps(-1.42647390514189e-02f)); + return _mm512_mul_ps(_mm512_mul_ps(_mm512_set1_ps(0.5f), x), _mm512_add_ps(_mm512_set1_ps(1.f), _mm512_div_ps(p, q))); +} + +} // namespace qwen3_asr_audio_simd diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/.gitignore b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/.gitignore index 903b749ec..a954da10f 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/.gitignore +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/.gitignore @@ -1,2 +1,3 @@ audio_encoder_test +audio_encoder_test_npu conv_cache_test diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/Makefile b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/Makefile index 3b74fa201..b92c8988f 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/Makefile +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/Makefile @@ -11,11 +11,23 @@ WEIGHTS ?= /path/to/Confucius4-R2T2-NPU2/audio_weight.q4nx GOLDENS ?= /path/to/goldens CLIPS ?= syn_short1s syn_silence3s repo_test ls_4077-13751-0006 zh_0006 zh_0015 syn_quiet_onset syn_long_concat -audio_encoder_test: audio_encoder_test.cpp ../qwen3_asr_audio_encoder.cpp ../qwen3_asr_audio_encoder.hpp +HDRS := ../qwen3_asr_audio_encoder.hpp ../qwen3_asr_audio_simd.hpp + +audio_encoder_test: audio_encoder_test.cpp ../qwen3_asr_audio_encoder.cpp $(HDRS) $(CXX) $(CXXFLAGS) -o $@ audio_encoder_test.cpp ../qwen3_asr_audio_encoder.cpp +# the same with the matrix products on the NPU (XRT): make run_npu XCLBIN= +XRT_ROOT ?= /usr +XCLBIN ?= /path/to/audio_gemm.xclbin +audio_encoder_test_npu: audio_encoder_test.cpp ../qwen3_asr_audio_encoder.cpp ../qwen3_asr_audio_gemm_npu.cpp ../qwen3_asr_audio_gemm_npu.hpp ../qwen3_asr_audio_gemm_seq.hpp $(HDRS) + $(CXX) $(CXXFLAGS) -DAUDIO_TEST_NPU -I$(XRT_ROOT)/include -o $@ audio_encoder_test.cpp ../qwen3_asr_audio_encoder.cpp ../qwen3_asr_audio_gemm_npu.cpp \ + -L$(XRT_ROOT)/lib -lxrt_coreutil ../../../../../../src/lib/xrt/libaiebu.a + +run_npu: audio_encoder_test_npu + env AUDIO_GEMM_XCLBIN=$(XCLBIN) ./audio_encoder_test_npu $(WEIGHTS) $(GOLDENS) $(CLIPS) + # streaming: cached conv front end == uncached over a growing recording (AddressSanitizer build) -conv_cache_test: conv_cache_test.cpp ../qwen3_asr_audio_encoder.cpp ../qwen3_asr_audio_encoder.hpp +conv_cache_test: conv_cache_test.cpp ../qwen3_asr_audio_encoder.cpp $(HDRS) $(CXX) $(CXXFLAGS) -O1 -g -fsanitize=address -o $@ conv_cache_test.cpp ../qwen3_asr_audio_encoder.cpp conv_cache: conv_cache_test @@ -26,6 +38,6 @@ run: audio_encoder_test ./audio_encoder_test $(WEIGHTS) $(GOLDENS) $(CLIPS) clean: - rm -f audio_encoder_test conv_cache_test + rm -f audio_encoder_test audio_encoder_test_npu conv_cache_test -.PHONY: run conv_cache clean +.PHONY: run run_npu conv_cache clean diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/audio_encoder_test.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/audio_encoder_test.cpp index 69122c850..a205fd46b 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/audio_encoder_test.cpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/audio/test/audio_encoder_test.cpp @@ -14,6 +14,9 @@ #include #include "../qwen3_asr_audio_encoder.hpp" +#ifdef AUDIO_TEST_NPU +#include "../qwen3_asr_audio_gemm_npu.hpp" +#endif static std::vector load_npy(const std::string& path, std::vector& shape) { std::ifstream f(path, std::ios::binary); @@ -45,7 +48,16 @@ static float bf2f(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; std::me int main(int argc, char** argv) { if (argc < 4) { std::fprintf(stderr, "usage: %s audio_weight.q4nx goldens_dir clip...\n", argv[0]); return 2; } auto t0 = std::chrono::steady_clock::now(); +#ifdef AUDIO_TEST_NPU // matrix products on the NPU: AUDIO_GEMM_XCLBIN= + const char* xclbin = std::getenv("AUDIO_GEMM_XCLBIN"); + if (!xclbin) { std::fprintf(stderr, "set AUDIO_GEMM_XCLBIN\n"); return 2; } + xrt::device device(0); + npu_xclbin_manager npu(npu_device::device_npu2, &device, false); + qwen3_asr_audio_gemm_npu gemm(npu.register_xclbin(xclbin)); + qwen3_asr_audio_encoder enc(argv[1], {}, &gemm); +#else qwen3_asr_audio_encoder enc(argv[1]); +#endif std::printf("load %.1f s\n", std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); const int D = 2048, WT = enc.config().window_tokens(); int fails = 0; diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.cpp index d2cde34e0..17af1ee00 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.cpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.cpp @@ -429,6 +429,7 @@ struct decoder::impl { std::vector kt_scratch; // attention_blocked's transposed keys int ctx = 0; int peak_ctx = 0; // the longest context since release() + projections* proj = nullptr; // the prompt's matrix products elsewhere (set_projections) impl(const std::string& path, decoder_config c) : cfg(c), file(path) { const int D = cfg.hidden, DH = cfg.head_dim; @@ -487,49 +488,85 @@ struct decoder::impl { const int D = cfg.hidden, DH = cfg.head_dim, H = cfg.heads, KV = cfg.kv_heads; const int DQ = H * DH, DK = KV * DH, I = cfg.inter; const int pos0 = ctx; + projections* P = (proj && n >= proj->min_rows()) ? proj : nullptr; + auto timed = [](auto&& f) { const double s = now_ms(); f(); g_prof.mm += now_ms() - s; }; std::vector h(embeds, embeds + (size_t)n * D); // residual stream, bf16-valued - std::vector x((size_t)n * D), q((size_t)n * DQ), k((size_t)n * DK), v((size_t)n * DK); - std::vector att((size_t)n * DQ), o((size_t)n * D); - std::vector g((size_t)n * I), u((size_t)n * I), dn((size_t)n * D); + std::vector x((size_t)n * D), q((size_t)n * DQ), att((size_t)n * DQ); + // the CPU products' results; with P they go to the row sinks below instead + std::vector k(P ? 0 : (size_t)n * DK), v(P ? 0 : (size_t)n * DK), o(P ? 0 : (size_t)n * D), dn(P ? 0 : (size_t)n * D); + std::vector g(P ? 0 : (size_t)n * I), u(P ? 0 : (size_t)n * I); std::vector cos_t((size_t)n * DH), sin_t((size_t)n * DH); for (int t = 0; t < n; ++t) rope_tables(pos0 + t, &cos_t[(size_t)t * DH], &sin_t[(size_t)t * DH]); + // row t after the products: q (in place) and k per-head norm, then rope; the cache rows of k and v + const auto qkv_row = [&](int li, int t, float* qt, float* kt, const float* vt) { + const layer_weights& L = layers[li]; + for (int hd = 0; hd < H; ++hd) { + rmsnorm_row(qt + hd * DH, L.q_norm.data(), qt + hd * DH, DH, cfg.rms_eps); + apply_rope(qt + hd * DH, &cos_t[(size_t)t * DH], &sin_t[(size_t)t * DH]); + } + for (int hd = 0; hd < KV; ++hd) { + rmsnorm_row(kt + hd * DH, L.k_norm.data(), kt + hd * DH, DH, cfg.rms_eps); + apply_rope(kt + hd * DH, &cos_t[(size_t)t * DH], &sin_t[(size_t)t * DH]); + } + uint16_t* kc = &k_cache[li][(size_t)(pos0 + t) * DK]; + uint16_t* vc = &v_cache[li][(size_t)(pos0 + t) * DK]; + for (int i = 0; i < DK; ++i) { + kc[i] = f2bf(kt[i]); + vc[i] = f2bf(vt[i]); + } + }; + // row t: h = bf16(h + a) (residual), then x = the next norm of h (none after the last layer) + const auto residual_row = [&](int t, const float* a, const float* norm) { + float* ht = &h[(size_t)t * D]; + for (int i = 0; i < D; ++i) ht[i] = bf16r(ht[i] + a[i]); + if (norm) rmsnorm_row(ht, norm, &x[(size_t)t * D], D, cfg.rms_eps); + }; + const auto to_float = [](const uint16_t* s, float* d, int count) { + for (int c = 0; c < count; c += 16) _mm512_storeu_ps(d + c, load_bf16x16(s + c)); + }; + +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int t = 0; t < n; ++t) rmsnorm_row(&h[(size_t)t * D], layers[0].input_norm.data(), &x[(size_t)t * D], D, cfg.rms_eps); for (int li = 0; li < cfg.layers; ++li) { layer_weights& L = layers[li]; - // ---- attention block ---- -#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) - for (int t = 0; t < n; ++t) rmsnorm_row(&h[(size_t)t * D], L.input_norm.data(), &x[(size_t)t * D], D, cfg.rms_eps); - matmul_q8(L.q, x.data(), n, q.data()); - matmul_q8(L.k, x.data(), n, k.data()); - matmul_q8(L.v, x.data(), n, v.data()); - + const float* next_norm = li + 1 < cfg.layers ? layers[li + 1].input_norm.data() : nullptr; + // ---- attention block (x: the input norm of h) ---- std::vector& Kc = k_cache[li]; std::vector& Vc = v_cache[li]; Kc.resize((size_t)(pos0 + n) * DK); Vc.resize((size_t)(pos0 + n) * DK); + if (P) { + timed([&] { + P->qkv(li, x.data(), n, [&](const uint16_t* y, int r0, int rows) { +#pragma omp parallel num_threads(qwen3_asr_cpu::asr_threads()) + { + std::vector kv((size_t)2 * DK); +#pragma omp for + for (int r = 0; r < rows; ++r) { + const uint16_t* yr = y + (size_t)r * (2 * DK + DQ); // [k | v | q] + float* qt = &q[(size_t)(r0 + r) * DQ]; + to_float(yr, kv.data(), 2 * DK); + to_float(yr + 2 * DK, qt, DQ); + qkv_row(li, r0 + r, qt, kv.data(), kv.data() + DK); + } + } + }); + }); + } else { + matmul_q8(L.q, x.data(), n, q.data()); + matmul_q8(L.k, x.data(), n, k.data()); + matmul_q8(L.v, x.data(), n, v.data()); #pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) - for (int t = 0; t < n; ++t) { - float* qt = &q[(size_t)t * DQ]; - float* kt = &k[(size_t)t * DK]; - for (int hd = 0; hd < H; ++hd) { // per-head q norm (over head_dim), then rope - rmsnorm_row(qt + hd * DH, L.q_norm.data(), qt + hd * DH, DH, cfg.rms_eps); - apply_rope(qt + hd * DH, &cos_t[(size_t)t * DH], &sin_t[(size_t)t * DH]); - } - for (int hd = 0; hd < KV; ++hd) { - rmsnorm_row(kt + hd * DH, L.k_norm.data(), kt + hd * DH, DH, cfg.rms_eps); - apply_rope(kt + hd * DH, &cos_t[(size_t)t * DH], &sin_t[(size_t)t * DH]); - } - const float* vt = &v[(size_t)t * DK]; - for (int i = 0; i < DK; ++i) { - Kc[(size_t)(pos0 + t) * DK + i] = f2bf(kt[i]); - Vc[(size_t)(pos0 + t) * DK + i] = f2bf(vt[i]); - } + for (int t = 0; t < n; ++t) qkv_row(li, t, &q[(size_t)t * DQ], &k[(size_t)t * DK], &v[(size_t)t * DK]); } const double att_start = now_ms(); static const bool att_scalar = std::getenv("QWEN3_ASR_ATT_SCALAR") != nullptr; // the per-(token, head) loop below, for A/B - if (DH == 128 && H / KV <= 2 && n >= 4 && !att_scalar) { // one-token decode: the transpose would cost more than it saves + if (P && P->attention(li, q.data(), pos0, n, Kc.data(), Vc.data(), att.data())) { + // done elsewhere + } else if (DH == 128 && H / KV <= 2 && n >= 4 && !att_scalar) { // one-token decode: the transpose would cost more than it saves attention_blocked(q.data(), Kc, Vc, pos0, n, H, KV, DH, att.data(), kt_scratch); } else { // causal attention; 16 query heads share 8 kv heads (2 per group); fp32 inside, bf16 out @@ -573,13 +610,33 @@ struct decoder::impl { } } g_prof.att += now_ms() - att_start; - matmul_q8(L.o, att.data(), n, o.data()); + // a product's rows as the residual of h, then x = norm of h (residual_row) + const auto residual_sink = [&](const float* norm) { + return [&, norm](const uint16_t* y, int r0, int rows) { +#pragma omp parallel num_threads(qwen3_asr_cpu::asr_threads()) + { + std::vector a(D); +#pragma omp for + for (int r = 0; r < rows; ++r) { + to_float(y + (size_t)r * D, a.data(), D); + residual_row(r0 + r, a.data(), norm); + } + } + }; + }; + if (P) { + timed([&] { P->o(li, att.data(), n, residual_sink(L.post_norm.data())); }); + } else { + matmul_q8(L.o, att.data(), n, o.data()); #pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) - for (long long i = 0; i < (long long)n * D; ++i) h[i] = bf16r(h[i] + o[i]); // residual + for (int t = 0; t < n; ++t) residual_row(t, &o[(size_t)t * D], L.post_norm.data()); + } - // ---- MLP block (SwiGLU) ---- -#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) - for (int t = 0; t < n; ++t) rmsnorm_row(&h[(size_t)t * D], L.post_norm.data(), &x[(size_t)t * D], D, cfg.rms_eps); + // ---- MLP block (SwiGLU), then x = the next layer's input norm of h ---- + if (P) { + timed([&] { P->mlp(li, x.data(), n, residual_sink(next_norm)); }); + continue; + } matmul_q8(L.gate, x.data(), n, g.data()); matmul_q8(L.up, x.data(), n, u.data()); #pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) @@ -590,7 +647,7 @@ struct decoder::impl { } matmul_q8(L.down, g.data(), n, dn.data()); #pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) - for (long long i = 0; i < (long long)n * D; ++i) h[i] = bf16r(h[i] + dn[i]); // residual + for (int t = 0; t < n; ++t) residual_row(t, &dn[(size_t)t * D], next_norm); } ctx = pos0 + n; peak_ctx = std::max(peak_ctx, ctx); @@ -606,6 +663,7 @@ struct decoder::impl { decoder::decoder(const std::string& q4nx_path, decoder_config cfg) : p_(new impl(q4nx_path, cfg)) {} decoder::~decoder() = default; const decoder_config& decoder::cfg() const { return p_->cfg; } +void decoder::set_projections(projections* p) { p_->proj = p; } void decoder::embed(int token, float* out) const { const uint16_t* row = p_->embed_table + (size_t)token * p_->cfg.hidden; for (int i = 0; i < p_->cfg.hidden; ++i) out[i] = bf2f(row[i]); diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.hpp index 2c1a80df5..d4aeb5875 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.hpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/decoder/qwen3_asr_cpu_decoder.hpp @@ -6,13 +6,14 @@ /// /// This is the "full CPU path first" of the engine (FLM_DLL/ADDING_A_NEW_MODEL.md): every semantic question /// (norm form, rope, rounding points) is settled here against the BF16 PyTorch reference before any NPU work. -/// It is also the planned prefill of the shipped engine (short prompts: CPU beats the NPU prefill below ~300-400 -/// tokens) and the fallback when the NPU is busy. +/// It also runs the shipped engine's prompt prefill, handing the matrix products (and the attention of long prompts) to +/// the NPU through `projections` (prefill/qwen3_asr_prefill_npu.hpp), and all of it with QWEN3_ASR_CPU_PREFILL=1. /// /// Weight format: model.q4nx from FLM_Q4NX_Converter/configs/qwen3_asr.json: Q8_0 projections in 32x256 blocks /// (512 B of bf16 scales [8 groups][32 rows], then 8192 B of int8 stored column major [256 cols][32 rows]). #pragma once #include +#include #include #include #include @@ -31,6 +32,30 @@ struct decoder_config { float rope_theta = 1000000.0f; }; +/// The matrix products (and optionally the attention) of a decoder layer, done elsewhere for a prompt (the NPU prefill). Inputs +/// are row-major floats holding bf16 values; results go, a block of rows at a time, to a sink of the decoder, which keeps the +/// norms, RoPE, the KV cache, the residual stream and the logits. +class projections { +public: + /// rows [r0, r0 + rows) of a product's result, bf16 [rows][outputs]; may be called while the next rows are computed, so + /// it must not write input rows it has not been given yet + using rows_sink = std::function; + virtual ~projections() = default; + /// prompts of fewer positions stay on the CPU + virtual int min_rows() const = 0; + /// [k | v | q] [n][2 kv_heads * head_dim + heads * head_dim] of the normed input x [n][hidden] + virtual void qkv(int layer, const float* x, int n, const rows_sink& out) = 0; + /// o_proj(att [n][heads * head_dim]), [n][hidden] + virtual void o(int layer, const float* att, int n, const rows_sink& out) = 0; + /// down(silu(gate x) * up x) of the normed input x [n][hidden], [n][hidden]; out may write rows of x it was given + virtual void mlp(int layer, const float* x, int n, const rows_sink& out) = 0; + /// causal attention of the n new positions pos0 .. over the cache rows [0, pos0 + n): q [n][heads * head_dim] after norm and + /// RoPE, k and v the layer's cache [pos0 + n][kv_heads * head_dim] (bf16), att [n][heads * head_dim]; false: the decoder does it + virtual bool attention(int /*layer*/, const float* /*q*/, int /*pos0*/, int /*n*/, const uint16_t* /*k*/, const uint16_t* /*v*/, float* /*att*/) { + return false; + } +}; + class decoder { public: explicit decoder(const std::string& q4nx_path, decoder_config cfg = decoder_config()); @@ -38,6 +63,10 @@ class decoder { const decoder_config& cfg() const; + /// forward() hands the projections of n >= p->min_rows() positions to p (nullptr: all on the CPU); p must outlive the + /// decoder or be reset first + void set_projections(projections* p); + /// bf16-valued row of the (BF16) embedding table void embed(int token, float* out) const; /// the row itself (bf16, `hidden` values, in the mapped file) diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_launch.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_launch.hpp new file mode 100644 index 000000000..4ef07b05a --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_launch.hpp @@ -0,0 +1,210 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +#pragma once +/// \file qwen3_asr_launch.hpp +/// \brief aie2p-launchlib control-packet warm switches for the prompt prefill: the attention kernel runs in the hardware +/// context of prefill.xclbin, so the array switches app inside one context (about 0.1 ms) instead of between two +/// contexts (~2.5 ms each way, per layer). +/// +/// The switches are built offline by aie2p-launchlib (flm-dev-kit/FLM_Xclbin/r2t2_switches) from the kernels' own +/// configuration: per kernel K its instruction stream and control packets; XRT argument 3 + packet_arg takes the +/// packet buffer. They ship as ONE file, xclbins//r2t2.switches: +/// "R2SW1\n", then per kernel a line "K \n", a line "END\n", then the +/// blobs in that order (K.txn, K.pkt, next kernel, ...). +/// Kernels used: cold_mm, mm_then_attn, attn_then_mm. +/// +/// Contract: the array is mm's whenever the prefill is not inside an attention call; a call switches to attn, runs, +/// and switches back, all in one submission (window), which starts from cold_mm whatever ran on the array before. +/// Needs the xclbins the switches were built with (prefill.xclbin is the package's base); nothing checks that, as +/// for every dev-kit artifact. QWEN3_ASR_NO_SWITCH=1 turns it off (attention then uses attn.xclbin's own context). +/// A copy of d3's launcher (detail/d3_npu/d3_launch.hpp) under its own namespace: engines share no inline headers. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#include +#include +#include +#endif + +#if !defined(FLM_USE_HRX) +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace qwen3_asr_launch { + +/// \brief the array to this process for one window. Warm switches rely on the array staying as the last launch left it; +/// another process on the switches (a second r2t2 server, a d3 server: the same lock) must not run its window in +/// between. flock on a file in the temp directory, a named mutex on Windows; a lock that cannot be made leaves the +/// window unlocked. +class array_lock { +#if defined(_WIN32) + HANDLE h = nullptr; +#else + int fd = -1; +#endif +public: + explicit array_lock(bool on) { + if (!on) return; +#if defined(_WIN32) + h = CreateMutexA(nullptr, FALSE, "Global\\flm_d3_array"); + if (h && WaitForSingleObject(h, INFINITE) == WAIT_FAILED) { CloseHandle(h); h = nullptr; } +#else + const char* tmp = std::getenv("TMPDIR"); + const std::string path = std::string(tmp && tmp[0] ? tmp : "/tmp") + "/flm_d3_array.lock"; + const mode_t old = umask(0); // shared between users + fd = open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666); + umask(old); + if (fd >= 0 && flock(fd, LOCK_EX) != 0) { close(fd); fd = -1; } +#endif + } + ~array_lock() { +#if defined(_WIN32) + if (h) { ReleaseMutex(h); CloseHandle(h); } +#else + if (fd >= 0) close(fd); // closing drops the lock +#endif + } + array_lock(const array_lock&) = delete; + array_lock& operator=(const array_lock&) = delete; +}; + +#if !defined(FLM_USE_HRX) +struct switches { + struct Sw { + std::unique_ptr elf; + std::unique_ptr mod; + std::unique_ptr kernel; + xrt::bo pkt; + int arg = 0; + }; + std::map sw; + + /// \brief one switch: aiebu ELF of the instruction stream, an ext kernel in the mm context, the packet BO + void _add(const std::string& name, int arg, const char* txn, size_t txn_size, const char* pkt, size_t pkt_size, + xrt::device* dev, xrt::hw_context* ctx, const std::string& kernel_name) { + if (name != "cold_mm" && name != "mm_then_attn" && name != "attn_then_mm") return; + void* elf_buf = nullptr; + const int elf_size = aiebu_assembler_get_elf(aiebu_assembler_buffer_type_blob_instr_transaction, txn, txn_size, + nullptr, 0, &elf_buf, nullptr, 0, "", "", nullptr, 0); + if (elf_size <= 0 || !elf_buf) throw std::runtime_error("aiebu failed on " + name); + Sw s; + s.elf = std::make_unique((char*)elf_buf, (size_t)elf_size); + free(elf_buf); + s.mod = std::make_unique(*s.elf); + s.kernel = std::make_unique(*ctx, *s.mod, kernel_name); + s.arg = 3 + arg; + s.pkt = xrt::bo(*dev, std::max(pkt_size, 4), XRT_BO_FLAGS_HOST_ONLY, s.kernel->group_id(s.arg)); + std::memcpy(s.pkt.map(), pkt, pkt_size); + s.pkt.sync(XCL_BO_SYNC_BO_TO_DEVICE); + sw.emplace(name, std::move(s)); + } + + /// \brief load the packed switches file (see the top) for the mm app manager's context (throws on any failure) + void load_file(const std::string& path, xrt::device* dev, xrt::hw_context* ctx, const std::string& kernel_name) { + std::ifstream f(path, std::ios::binary); + if (!f) throw std::runtime_error("cannot read " + path); + const std::vector buf((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + const std::string where = path + ": "; + size_t pos = 0; + auto next_line = [&]() { + const char* nl = (const char*)std::memchr(buf.data() + pos, '\n', buf.size() - pos); + if (!nl) throw std::runtime_error(where + "truncated header"); + std::string l(buf.data() + pos, nl - (buf.data() + pos)); + pos = (size_t)(nl - buf.data()) + 1; + return l; + }; + if (next_line() != "R2SW1") throw std::runtime_error(where + "not an R2SW1 file"); + struct Ent { std::string name; int arg; size_t txn, pkt; }; + std::vector ents; + for (std::string l = next_line(); l != "END"; l = next_line()) { + std::istringstream is(l); + Ent e{}; + if (!(is >> e.name >> e.arg >> e.txn >> e.pkt) || e.arg < 0) throw std::runtime_error(where + "bad entry '" + l + "'"); + ents.push_back(e); + } + for (const Ent& e : ents) { + if (e.txn > buf.size() - pos || e.pkt > buf.size() - pos - e.txn) throw std::runtime_error(where + "truncated data"); + _add(e.name, e.arg, buf.data() + pos, e.txn, buf.data() + pos + e.txn, e.pkt, dev, ctx, kernel_name); + pos += e.txn + e.pkt; + } + for (const char* n : {"cold_mm", "mm_then_attn", "attn_then_mm"}) + if (!sw.count(n)) throw std::runtime_error(where + "missing switch " + n); + } + + /// \brief one switch as a run, not started + xrt::run make_run(const std::string& name) { + Sw& s = sw.at(name); + xrt::run r(*s.kernel); + r.set_arg(0, 3); + r.set_arg(1, 0); + r.set_arg(2, 0); + r.set_arg(s.arg, s.pkt); + return r; + } + + /// \brief the array's turn as ONE submission: cold_mm, the switch to attention, its runs, the switch back (a runlist + /// goes to the device as one chain, so no other context takes the array between two of them) + template + void window(Mgr* mgr, std::vector& guest) { + array_lock lock(true); + xrt::runlist rl = mgr->create_runlist(); + rl.add(make_run("cold_mm")); + rl.add(make_run("mm_then_attn")); + for (xrt::run& g : guest) rl.add(g); + rl.add(make_run("attn_then_mm")); + rl.execute(); + rl.wait(); + } +}; + +/// \brief the switches of `path` in mgr's hardware context, or nullptr (QWEN3_ASR_NO_SWITCH=1, no file, or a load failure, +/// logged once by the caller through `why`) +template +std::unique_ptr load(Mgr* mgr, const std::string& path, std::string& why) { + const char* off = std::getenv("QWEN3_ASR_NO_SWITCH"); + if (off && off[0] == '1') { why = "QWEN3_ASR_NO_SWITCH"; return nullptr; } + { + std::ifstream probe(path, std::ios::binary); + if (!probe) { why = "no " + path; return nullptr; } + } + try { + auto s = std::make_unique(); + s->load_file(path, mgr->get_device(), mgr->get_context(), mgr->get_kernel_name()); + return s; + } catch (const std::exception& e) { + why = e.what(); + return nullptr; + } +} +#else +struct switches {}; // HRX: no switches, attention uses attn.xclbin's own context +template +std::unique_ptr load(Mgr*, const std::string&, std::string& why) { + why = "not on HRX"; + return nullptr; +} +#endif + +} // namespace qwen3_asr_launch diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_npu.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_npu.cpp new file mode 100644 index 000000000..ddab6a8ae --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_npu.cpp @@ -0,0 +1,365 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "qwen3_asr_prefill_npu.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "../audio/qwen3_asr_audio_simd.hpp" +#include "../omp_threads.hpp" + +namespace seqg = qwen3_asr_prefill_seq; +namespace simd = qwen3_asr_audio_simd; + +namespace { + +/// two bfp16 blocks (o0: lanes 0..7, o1: lanes 8..15), each 8 values sharing the largest exponent of the 8, rounded to +/// nearest (the same integer steps as the audio encoder's encode2) +inline void encode2(__m512 f, uint8_t* o0, uint8_t* o1) { + const __m512i one = _mm512_set1_epi32(1); + __m512i u = _mm512_castps_si512(f); + u = _mm512_srli_epi32(_mm512_add_epi32(u, _mm512_add_epi32(_mm512_set1_epi32(0x7FFF), _mm512_and_si512(_mm512_srli_epi32(u, 16), one))), 16); + const __m512i ex = _mm512_and_si512(_mm512_srli_epi32(u, 7), _mm512_set1_epi32(0xFF)); + const __m512i x1 = _mm512_set_epi32(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); + const __m512i x2 = _mm512_set_epi32(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2); + const __m512i x4 = _mm512_set_epi32(11, 10, 9, 8, 15, 14, 13, 12, 3, 2, 1, 0, 7, 6, 5, 4); + __m512i mx = _mm512_max_epi32(ex, _mm512_permutexvar_epi32(x1, ex)); + mx = _mm512_max_epi32(mx, _mm512_permutexvar_epi32(x2, mx)); + mx = _mm512_max_epi32(mx, _mm512_permutexvar_epi32(x4, mx)); + __m512i mag = _mm512_slli_epi32(_mm512_and_si512(u, _mm512_set1_epi32(0x7F)), 16); + mag = _mm512_mask_or_epi32(mag, _mm512_test_epi32_mask(ex, ex), mag, _mm512_set1_epi32(0x800000)); + const __m512i s = _mm512_mask_sub_epi32(mag, _mm512_test_epi32_mask(u, _mm512_set1_epi32(0x8000)), _mm512_setzero_si512(), mag); + const __m512i sh = _mm512_min_epi32(_mm512_sub_epi32(_mm512_add_epi32(mx, _mm512_set1_epi32(17)), ex), _mm512_set1_epi32(31)); + __m512i q = _mm512_srav_epi32(s, sh); + const __m512i rem = _mm512_sub_epi32(s, _mm512_sllv_epi32(q, sh)); + const __m512i half = _mm512_sllv_epi32(one, _mm512_sub_epi32(sh, one)); + const __mmask16 up = _mm512_cmpgt_epi32_mask(rem, half) | (_mm512_cmpeq_epi32_mask(rem, half) & _mm512_test_epi32_mask(q, one)); + q = _mm512_min_epi32(_mm512_mask_add_epi32(q, up, q, one), _mm512_set1_epi32(127)); + alignas(16) uint8_t qb[16], eb[16]; + _mm_store_si128((__m128i*)qb, _mm512_cvtepi32_epi8(q)); + _mm_store_si128((__m128i*)eb, _mm512_cvtepi32_epi8(mx)); + o0[0] = eb[0]; + std::memcpy(o0 + 1, qb, 8); + o1[0] = eb[8]; + std::memcpy(o1 + 1, qb + 8, 8); +} + +/// rows [0, rows) of x [rows][Din] -> X as the cores take it, for rows_padded rows (the rest 0) and nb slabs per pass: per pass +/// and core row a block of [512 k round][256 k slice 2][16-row group 8 / nb][128 k half 2][k tile 16][8-row tile 2] of 8 rows +/// x 9 B (seqg::gen_dequant_mm_mix) +void pack_x(uint8_t* out, const float* x, int rows, uint32_t rows_padded, uint32_t Din, uint32_t nb) { + const uint32_t ms = 8 / nb; + const uint32_t m_pass = seqg::mix_pass_rows(nb); + const uint32_t k_rounds = Din / 512; + const size_t round_bytes = (size_t)4 * ms * seqg::MIX_X_PACKET_BYTES; + const int blocks = (int)(rows_padded / m_pass * seqg::MIX_CORE_ROWS); +#pragma omp parallel for collapse(2) schedule(static) num_threads(qwen3_asr_cpu::asr_threads()) + for (int b = 0; b < blocks; b++) { + for (int kr = 0; kr < (int)k_rounds; kr++) { + const uint32_t mp = b / seqg::MIX_CORE_ROWS, r = b % seqg::MIX_CORE_ROWS; + uint8_t* p = out + ((size_t)b * k_rounds + kr) * round_bytes; + for (uint32_t j = 0; j < 2; j++) + for (uint32_t i = 0; i < ms; i++) { + const int r0 = (int)(mp * m_pass + r * 16 * ms + i * 16); + if (r0 >= rows) { // a group past the rows is all zero bytes + std::memset(p, 0, 2 * 16 * 2 * 72); + p += 2 * 16 * 2 * 72; + continue; + } + for (uint32_t v = 0; v < 2; v++) + for (uint32_t kt = 0; kt < 16; kt++) + for (int z = 0; z < 2; z++) { + const size_t k0 = (size_t)kr * 512 + j * 256 + v * 128 + kt * 8; + for (int row = r0 + z * 8; row < r0 + z * 8 + 8; row += 2, p += 18) { + const __m256 a = row < rows ? _mm256_loadu_ps(x + (size_t)row * Din + k0) : _mm256_setzero_ps(); + const __m256 c = row + 1 < rows ? _mm256_loadu_ps(x + (size_t)(row + 1) * Din + k0) : _mm256_setzero_ps(); + encode2(_mm512_insertf32x8(_mm512_castps256_ps512(a), c, 1), p, p + 9); + } + } + } + } + } +} + +/// byte offset in pack_x's layout of the 8 values at k (a multiple of 8) of row `row` +inline size_t x_offset(int row, uint32_t k, uint32_t Din, uint32_t nb) { + const uint32_t ms = 8 / nb, m_pass = seqg::mix_pass_rows(nb), k_rounds = Din / 512; + const uint32_t mp = row / m_pass, rr = row % m_pass, b = mp * seqg::MIX_CORE_ROWS + rr / (16 * ms); + const uint32_t kr = k / 512, j = k / 256 % 2, v = k / 128 % 2, kt = k / 8 % 16; + return ((size_t)b * k_rounds + kr) * 4 * ms * seqg::MIX_X_PACKET_BYTES + (j * ms + rr / 16 % ms) * 2 * 16 * 2 * 72 + + ((v * 16 + kt) * 2 + rr / 8 % 2) * 72 + rr % 8 / 2 * 18 + rr % 2 * 9; +} + +double ms_since(std::chrono::steady_clock::time_point t) { + return std::chrono::duration(std::chrono::steady_clock::now() - t).count(); +} + +} // namespace + +qwen3_asr_prefill_npu::qwen3_asr_prefill_npu(npu_app_manager* mgr, const layout& l, std::vector>& weights, npu_app_manager* attn_mgr, + std::mutex* npu_lock, std::unique_ptr sw) + : mgr_(mgr), l_(l), weights_(weights), io_app_(mgr->create_app()), attn_mgr_(attn_mgr), sw_(std::move(sw)), + mu_(npu_lock ? *npu_lock : own_mu_) { + if (sw_ || attn_mgr_) { + mha_type_t ty = mha_d128_q2; + mha_ = std::make_unique(ty, l.DK / 128); + attn_app_ = std::make_unique((sw_ ? mgr_ : attn_mgr_)->create_app()); + const char* min_env = std::getenv("QWEN3_ASR_NPU_ATTENTION_MIN"); + const int64_t rows = min_env ? std::max(0, std::atoi(min_env)) : sw_ ? ATTN_MIN_SWITCHES : 1024; + attn_min_work_ = rows * (rows + 1); + } + using seqg::MIX_FMT_Q4_1; + using seqg::MIX_FMT_Q8_0; + if (l.D % 512 || l.DQ % 512 || l.I % 512) throw std::runtime_error("qwen3_asr_prefill_npu: dimensions must be multiples of 512"); + calls_[KVQ] = {(uint32_t)l.D, (uint32_t)(2 * l.DK + l.DQ), + {{l.k, (uint32_t)l.DK, MIX_FMT_Q4_1}, {l.v, (uint32_t)l.DK, MIX_FMT_Q8_0}, {l.q, (uint32_t)l.DQ, MIX_FMT_Q4_1}}}; + calls_[O] = {(uint32_t)l.DQ, (uint32_t)l.D, {{l.o, (uint32_t)l.D, MIX_FMT_Q4_1}}}; + calls_[UP_GATE] = {(uint32_t)l.D, (uint32_t)(2 * l.I), {{l.up, (uint32_t)(2 * l.I), MIX_FMT_Q4_1}}}; // up and gate, 512 rows each in turn + calls_[DOWN] = {(uint32_t)l.I, (uint32_t)l.D, {{l.down, (uint32_t)l.D, MIX_FMT_Q8_0}}}; + prof_ = std::getenv("QWEN3_ASR_PROF") != nullptr; +} + +npu_app& qwen3_asr_prefill_npu::app_for(call_id c, uint32_t rows_padded) { + const auto key = std::make_pair((int)c, rows_padded); + auto it = apps_.find(key); + if (it != apps_.end()) return *it->second; + auto app = std::make_unique(mgr_->create_app()); + // generated for the padded rows: they pick the same nb as the rows themselves, so every prompt of a size shares it + seqg::gen_dequant_mm_mix(app->seq(), rows_padded, calls_[c].din, calls_[c].bands, 0, 0); + return *apps_.emplace(key, std::move(app)).first->second; +} + +void qwen3_asr_prefill_npu::run(int layer, const std::vector& jobs) { + const size_t n = jobs.size(); + // every run is created (and its app set up) before the first starts; the two slots fit the largest job + std::vector rp(n); + size_t x_bytes = 0, y_elems = 0; + for (size_t j = 0; j < n; j++) { + const call_t& call = calls_[jobs[j].c]; + rp[j] = seqg::mix_rows_padded(jobs[j].rows, call.dout); + if (!jobs[j].packed) x_bytes = std::max(x_bytes, (size_t)rp[j] * call.din / 8 * 9); + y_elems = std::max(y_elems, (size_t)rp[j] * call.dout); + } + for (int s = 0; s < 2; s++) { + if (x_[s].size() < x_bytes) x_[s] = io_app_.create_bo_buffer(x_bytes); + if (y_[s].size() < y_elems) y_[s] = io_app_.create_bo_buffer(y_elems); + } + std::vector runs; + runs.reserve(n); + for (size_t j = 0; j < n; j++) + runs.push_back(app_for(jobs[j].c, rp[j]).create_run(y_[j % 2], jobs[j].packed ? *jobs[j].packed : x_[j % 2], weights_.at(layer))); + + const auto pack = [&](size_t j) { + const job& J = jobs[j]; + const call_t& call = calls_[J.c]; + const auto t = std::chrono::steady_clock::now(); + if (J.packed) J.packed->sync_to_device_bytes((size_t)rp[j] * call.din / 8 * 9); + else { + pack_x(x_[j % 2].data(), J.x, J.rows, rp[j], call.din, seqg::mix_nb(J.rows, call.dout)); + x_[j % 2].sync_to_device_bytes((size_t)rp[j] * call.din / 8 * 9); + } + if (prof_) prof_ms_[J.c][0] += ms_since(t); + }; + const auto unpack = [&](size_t j) { + const job& J = jobs[j]; + const auto t = std::chrono::steady_clock::now(); + J.unpack(y_[j % 2].data(), J.r0, J.rows); + if (prof_) prof_ms_[J.c][2] += ms_since(t); + }; + std::chrono::steady_clock::time_point started; + for (size_t j = 0; j <= n; j++) { + const bool early = j < n && !(j > 0 && jobs[j].needs_prev); + if (early) pack(j); // while the NPU runs job j - 1 + if (j > 0) { + const job& J = jobs[j - 1]; + flm::npu::wait_for_completion(runs[j - 1], "qwen3_asr_prefill_npu"); + if (prof_) { + prof_ms_[J.c][1] += ms_since(started); + prof_flop_[J.c] += 2.0 * rp[j - 1] * calls_[J.c].din * calls_[J.c].dout; + } + y_[(j - 1) % 2].sync_from_device_bytes((size_t)J.rows * calls_[J.c].dout * sizeof(u16)); + } + if (j < n && !early) { + unpack(j - 1); + pack(j); + } + if (j < n) { + started = std::chrono::steady_clock::now(); + runs[j].start(); + } + if (j > 0 && (early || j == n)) unpack(j - 1); // while the NPU runs job j + } +} + +void qwen3_asr_prefill_npu::qkv(int layer, const float* x, int n, const rows_sink& out) { + std::lock_guard lock(mu_); + std::vector jobs; + for (int r0 = 0; r0 < n; r0 += step(n)) jobs.push_back({KVQ, r0, std::min(step(n), n - r0), x + (size_t)r0 * l_.D, out}); + run(layer, jobs); +} + +void qwen3_asr_prefill_npu::o(int layer, const float* att, int n, const rows_sink& out) { + std::lock_guard lock(mu_); + std::vector jobs; + for (int r0 = 0; r0 < n; r0 += step(n)) jobs.push_back({O, r0, std::min(step(n), n - r0), att + (size_t)r0 * l_.DQ, out}); + run(layer, jobs); +} + +void qwen3_asr_prefill_npu::mlp(int layer, const float* x, int n, const rows_sink& out) { + std::lock_guard lock(mu_); + const int D = l_.D, I = l_.I; + // down's X, packed by the up_gate unpack: two buffers in turn (down s runs before up_gate s + 2 is unpacked) + const size_t xd_bytes = (size_t)seqg::mix_rows_padded(step(n), D) * I / 8 * 9; + for (int s = 0; s < 2; s++) + if (xd_[s].size() < xd_bytes) xd_[s] = io_app_.create_bo_buffer(xd_bytes); + // fused row c is up row (c / 1024) 512 + c % 1024 when c % 1024 < 512, else that gate row (512 earlier); silu and the + // product are rounded to bf16 as on the CPU path, then packed as pack_x would (padding rows 0); a task is 16 rows (one + // row group: whole 72-byte tiles) by 512 k + const auto silu_up = [=](uint8_t* xd, const uint16_t* Y, int rows) { + const uint32_t nb = seqg::mix_nb(rows, D), ms = 8 / nb; + const int groups = (int)seqg::mix_rows_padded(rows, D) / 16; +#pragma omp parallel for collapse(2) schedule(dynamic, 2) num_threads(qwen3_asr_cpu::asr_threads()) + for (int kr = 0; kr < I / 512; kr++) + for (int g = 0; g < groups; g++) { + uint8_t* base = xd + x_offset(g * 16, kr * 512, I, nb); + if (g * 16 >= rows) { // a group past the rows: its two 256 k slices + std::memset(base, 0, 2 * 16 * 2 * 72); + std::memset(base + ms * 2 * 16 * 2 * 72, 0, 2 * 16 * 2 * 72); + continue; + } + for (int rl = 0; rl < 16; rl++) { + const int r = g * 16 + rl; + uint8_t* p = base + rl / 8 * 72 + rl % 8 / 2 * 18 + rl % 2 * 9; + if (r >= rows) { // padding: zero blocks + for (int t = 0; t < 64; t++) std::memset(p + t / 32 * ms * 2 * 16 * 2 * 72 + t % 32 * 144, 0, 9); + continue; + } + const uint16_t* y = Y + (size_t)r * 2 * I + kr * 1024; + for (int c = 0; c < 512; c += 16, p += 2 * 144) { + if (c == 256) p += (ms - 1) * 2 * 16 * 2 * 72; // the second 256 k slice follows this row's ms groups + const __m512 u = simd::load_bf16(y + c), gt = simd::load_bf16(y + c + 512); + const __m512 s = simd::round_bf16(_mm512_div_ps(gt, _mm512_add_ps(_mm512_set1_ps(1.f), simd::exp(_mm512_sub_ps(_mm512_setzero_ps(), gt))))); + encode2(simd::round_bf16(_mm512_mul_ps(s, u)), p, p + 144); + } + } + } + }; + // up_gate 0, up_gate 1, down 0, up_gate 2, down 1, ..., down last: a down job's input is written by its up_gate job's + // unpack, which is two jobs earlier, or (one step) the job just before + std::vector jobs; + const int steps = (n + step(n) - 1) / step(n); + const auto ug = [&](int s) { + const int r0 = s * step(n); + uint8_t* xd = xd_[s % 2].data(); + jobs.push_back({UP_GATE, r0, std::min(step(n), n - r0), x + (size_t)r0 * D, [=](const uint16_t* y, int, int rows) { silu_up(xd, y, rows); }}); + }; + const auto dn = [&](int s) { + const int r0 = s * step(n); + const bool prev = jobs.back().c == UP_GATE && jobs.back().r0 == r0; + jobs.push_back({DOWN, r0, std::min(step(n), n - r0), nullptr, out, prev, &xd_[s % 2]}); + }; + ug(0); + for (int s = 1; s < steps; s++) { + ug(s); + dn(s - 1); + } + dn(steps - 1); + run(layer, jobs); + if (prof_ && layer + 1 == (int)weights_.size()) report(n); +} + +bool qwen3_asr_prefill_npu::attention(int /*layer*/, const float* q, int pos0, int n, const uint16_t* k, const uint16_t* v, float* att) { + if (!attn_app_ || (int64_t)n * (2 * (int64_t)pos0 + n + 1) < attn_min_work_) return false; + std::lock_guard lock(mu_); + const int DQ = l_.DQ, DK = l_.DK, half = DK / 2; + const int chunk = mha_->get_chunk_size(), L = pos0 + n; + const int L0 = pos0 / chunk * chunk, L1 = (L + chunk - 1) / chunk * chunk, rows = L1 - L0, off = pos0 - L0; + auto t = std::chrono::steady_clock::now(); + if ((uint32_t)L0 != attn_l0_ || (uint32_t)L1 != attn_l1_) { + mha_->generate_mha_sequence(attn_app_->seq(), L0, L1, L1, false); // MAX_L = L1: the bands are L1 rows apart + attn_l0_ = L0; + attn_l1_ = L1; + } + if (attn_q_.size() < (size_t)rows * DQ) { + attn_q_ = attn_app_->create_bo_buffer((size_t)rows * DQ); + attn_y_ = attn_app_->create_bo_buffer((size_t)rows * DQ); + } + if (attn_kv_.size() < (size_t)L1 * 2 * DK) attn_kv_ = attn_app_->create_bo_buffer((size_t)L1 * 2 * DK); + // q rows (bf16 values: the top halves), 0 outside the prompt; cache rows split into the bands, 0 past the last row (the + // dropped rows' keys: finite, so their zero weights stay zero) + uint16_t* Q = attn_q_.data(); + uint16_t* KV = attn_kv_.data(); + const size_t band = (size_t)L1 * half; +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int r = 0; r < rows; r++) { + uint16_t* d = Q + (size_t)r * DQ; + if (r < off || r >= off + n) { + std::memset(d, 0, (size_t)DQ * sizeof(u16)); + continue; + } + const float* s = q + (size_t)(r - off) * DQ; + for (int c = 0; c < DQ; c += 16) + _mm256_storeu_si256((__m256i*)(d + c), _mm512_cvtepi32_epi16(_mm512_srli_epi32(_mm512_castps_si512(_mm512_loadu_ps(s + c)), 16))); + } +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int j = 0; j < L1; j++) { + uint16_t* d[4] = {KV + (size_t)j * half, KV + band + (size_t)j * half, KV + 2 * band + (size_t)j * half, KV + 3 * band + (size_t)j * half}; + if (j >= L) { + for (int b = 0; b < 4; b++) std::memset(d[b], 0, (size_t)half * sizeof(u16)); + continue; + } + std::memcpy(d[0], k + (size_t)j * DK, (size_t)half * sizeof(u16)); + std::memcpy(d[1], k + (size_t)j * DK + half, (size_t)half * sizeof(u16)); + std::memcpy(d[2], v + (size_t)j * DK, (size_t)half * sizeof(u16)); + std::memcpy(d[3], v + (size_t)j * DK + half, (size_t)half * sizeof(u16)); + } + attn_q_.sync_to_device_bytes((size_t)rows * DQ * sizeof(u16)); + attn_kv_.sync_to_device_bytes((size_t)L1 * 2 * DK * sizeof(u16)); + if (prof_) { + prof_ms_[CALLS][0] += ms_since(t); + t = std::chrono::steady_clock::now(); + } +#if !defined(FLM_USE_HRX) + if (sw_) { + std::vector guest{attn_app_->create_run(attn_y_, attn_q_, attn_kv_)}; + sw_->window(mgr_, guest); + } else +#endif + (*attn_app_)(attn_y_, attn_q_, attn_kv_); + if (prof_) { + prof_ms_[CALLS][1] += ms_since(t); + // QK and PV over each real row's causal length: 2 x 2 x DQ x (pos0 + i + 1) for i in [0, n) + prof_flop_[CALLS] += 4.0 * DQ * ((double)n * pos0 + (double)n * (n + 1) / 2); + t = std::chrono::steady_clock::now(); + } + attn_y_.sync_from_device_bytes((size_t)(off + n) * DQ * sizeof(u16)); + const uint16_t* Y = attn_y_.data() + (size_t)off * DQ; +#pragma omp parallel for num_threads(qwen3_asr_cpu::asr_threads()) + for (int r = 0; r < n; r++) + for (int c = 0; c < DQ; c += 16) _mm512_storeu_ps(att + (size_t)r * DQ + c, simd::load_bf16(Y + (size_t)r * DQ + c)); + if (prof_) prof_ms_[CALLS][2] += ms_since(t); + return true; +} + +void qwen3_asr_prefill_npu::report(int n) { + static const char* names[CALLS + 1] = {"kvq", "o", "up_gate", "down", "attn"}; + double npu = 0, flop = 0; + for (int c = 0; c <= CALLS; c++) { + if (c == CALLS && prof_ms_[c][1] == 0) break; // the CPU did the attention + std::fprintf(stderr, "[prefill npu] n=%d %-7s pack %.1f npu %.1f unpack %.1f ms, %.2f TOPS\n", n, names[c], prof_ms_[c][0], prof_ms_[c][1], + prof_ms_[c][2], prof_ms_[c][1] > 0 ? prof_flop_[c] / prof_ms_[c][1] * 1e-9 : 0.0); + npu += prof_ms_[c][1]; + flop += prof_flop_[c]; + prof_ms_[c][0] = prof_ms_[c][1] = prof_ms_[c][2] = 0; + prof_flop_[c] = 0; + } + std::fprintf(stderr, "[prefill npu] n=%d all layers: npu %.1f ms, %.2f TOPS (padded rows)\n", n, npu, npu > 0 ? flop / npu * 1e-9 : 0.0); +} diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_npu.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_npu.hpp new file mode 100644 index 000000000..985fd2fa5 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_npu.hpp @@ -0,0 +1,115 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file qwen3_asr_prefill_npu.hpp +/// \brief The prompt prefill's matrix products on the NPU (prefill.xclbin, built from FLM_Xclbin/dequant_mm_mix_bfp16). +/// +/// The kernel reads the decode weights in place: per layer one buffer of Q4_1 (k, q, o, up, gate) and Q8_0 (v, down) +/// units, K|V|Q, o, up|gate (interleaved 512 rows at a time), down (qwen3_asr_desc). A layer is four calls: K, V and Q in +/// one, o, up and gate in one, down. The host packs X as block float (8 values share an exponent, rounded to nearest), +/// hands the bf16 results to the decoder's row sinks, and computes silu(gate) * up between the last two calls, packing it +/// straight into down's X. With attn.xclbin (the shared prefill +/// attention, modules/mha.hpp) long prompts also run their attention on the NPU, between the first two calls; with +/// r2t2.switches (qwen3_asr_launch.hpp) that kernel runs inside prefill.xclbin's own hardware context, so shorter prompts +/// do too. The CPU decoder +/// keeps the rest of the layer (norms, RoPE, short attention, the KV cache), so the streaming and background prefill paths +/// are unchanged. +/// Calls are serialized: the engine prefills in the foreground and in the background. +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#include "typedef.hpp" +#include "npu_utils/npu_utils.hpp" +#include "modules/mha.hpp" +#include "../decoder/qwen3_asr_cpu_decoder.hpp" +#include "qwen3_asr_launch.hpp" +#include "qwen3_asr_prefill_seq.hpp" + +class qwen3_asr_prefill_npu : public qwen3_asr_cpu::projections { +public: + struct layout { + int D = 0, DQ = 0, DK = 0, I = 0; // hidden, q heads x head_dim, kv heads x head_dim, intermediate + size_t k = 0, v = 0, q = 0, o = 0, up = 0, down = 0; // byte offsets of the weights in a layer's buffer + }; + /// \param mgr the app manager of prefill.xclbin + /// \param weights the decode layer's weight buffers, one per layer (read in place) + /// \param attn_mgr the app manager of attn.xclbin (prefill attention, head_dim 128, 2 q heads per kv head); nullptr: the + /// decoder keeps the attention + /// \param npu_lock held during each call: the engine's lock of the NPU (nullptr: a lock of its own) + /// \param sw the control-packet switches loaded in mgr's context (qwen3_asr_launch::load): the attention then runs in that + /// context and attn_mgr is not used; nullptr: attn_mgr's own context + qwen3_asr_prefill_npu(npu_app_manager* mgr, const layout& l, std::vector>& weights, npu_app_manager* attn_mgr = nullptr, + std::mutex* npu_lock = nullptr, std::unique_ptr sw = nullptr); + /// the attention runs on the NPU for long enough prompts (in attn.xclbin's context or on the switches) + bool npu_attention() const { return attn_app_ != nullptr; } + bool switches() const { return sw_ != nullptr; } + int min_rows() const override { return min_rows_; } + void qkv(int layer, const float* x, int n, const rows_sink& out) override; + void o(int layer, const float* att, int n, const rows_sink& out) override; + void mlp(int layer, const float* x, int n, const rows_sink& out) override; + /// one run of attn.xclbin for all heads: rows [L0, L1) (pos0 and pos0 + n rounded out to 128) against the cache copied into + /// its K/V buffer of L1 rows; the rows outside [pos0, pos0 + n) have zero queries and are dropped. False (the CPU decoder + /// does it) for short work, see attn_min_work_ + bool attention(int layer, const float* q, int pos0, int n, const uint16_t* k, const uint16_t* v, float* att) override; + +private: + enum call_id { KVQ, O, UP_GATE, DOWN, CALLS }; + struct call_t { + uint32_t din = 0, dout = 0; + std::vector bands; + }; + /// one NPU call: rows [r0, r0 + rows) of the prompt, input x [rows][din]; unpack reads their bf16 Y [rows][dout] + struct job { + call_id c; + int r0, rows; + const float* x; + rows_sink unpack; + bool needs_prev = false; // x is written by the unpack of the job just before + buffer* packed = nullptr; // X already packed here (by an earlier job's unpack) instead of x + }; + npu_app& app_for(call_id c, uint32_t rows_padded); + /// the jobs of `layer` in order, in two buffer slots: while the NPU runs job j the host packs job j + 1 and unpacks job j - 1 + /// (a job's x must be written by the unpack of a job at least two earlier, or of the job just before with needs_prev) + void run(int layer, const std::vector& jobs); + /// rows per job of an n-row prompt: the kernel reads the weights once per 512 rows anyway, so 512-row jobs cost no more NPU + /// time than one, and the host packs and unpacks them while the NPU runs the next + static int step(int n) { return std::min(n, 512); } + /// QWEN3_ASR_PROF: print the sums of a prompt of n rows and reset them + void report(int n); + + npu_app_manager* mgr_; + layout l_; + std::vector>& weights_; + call_t calls_[CALLS]; + int min_rows_ = 4; + std::map, std::unique_ptr> apps_; + npu_app io_app_; // owns no sequence: creates the X and Y buffers + buffer x_[2]; + buffer y_[2]; + buffer xd_[2]; // silu(gate) * up of a down job, packed + // attention: the sequence is made for one (L0, L1); the K/V buffer holds K of kv heads 0-3, K 4-7, V 0-3, V 4-7, L1 rows each. + // Its app is attn_mgr's, or with the switches mgr's (the run goes into sw_->window) + npu_app_manager* attn_mgr_ = nullptr; + std::unique_ptr sw_; + std::unique_ptr mha_; + std::unique_ptr attn_app_; + uint32_t attn_l0_ = 0, attn_l1_ = 0; + // the NPU runs the attention of n rows after pos0 when n * (2 pos0 + n + 1), twice its causal products per head, reaches + // that of a prompt of QWEN3_ASR_NPU_ATTENTION_MIN rows: 1024 between two contexts (below, the two switches per layer + // between prefill.xclbin and attn.xclbin, ~2.5 ms each, cost more than the CPU attention), less on the switches + int64_t attn_min_work_ = 0; + static constexpr int64_t ATTN_MIN_SWITCHES = 384; + buffer attn_q_, attn_kv_, attn_y_; + std::mutex own_mu_; + std::mutex& mu_; + // QWEN3_ASR_PROF: per call, ms of packing, NPU and unpacking, and its multiply-adds, summed over the layers (ATTN: the + // causal products QK and PV of the real rows) + bool prof_ = false; + double prof_ms_[CALLS + 1][3] = {}, prof_flop_[CALLS + 1] = {}; +}; diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_seq.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_seq.hpp new file mode 100644 index 000000000..f0d1b63a1 --- /dev/null +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_seq.hpp @@ -0,0 +1,187 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file qwen3_asr_prefill_seq.hpp +/// \brief Run-time sequence of the prefill GEMM (prefill.xclbin, built from FLM_Xclbin/dequant_mm_mix_bfp16): Y = X W^T on the +/// mixed Q4_1 / Q8_0 decode weights, read in place. +/// +/// Copy of FLM_Xclbin/dequant_mm_mix_bfp16/host/seq_gen.hpp in this engine's namespace (engines do not share headers with +/// inline functions); keep the two in sync with the kernel. +#pragma once +#include +#include +#include "npu_utils/npu_utils.hpp" + +namespace qwen3_asr_prefill_seq { + +// Core-local buffer addresses assigned by aie-assign-buffer-addresses (K_div_k_* and rtp_act_* of the kernel's +// rtp_addresses.txt, locked in FLM_Xclbin/rtp_addresses.lock.txt). +static constexpr uint32_t CT_rtp_address_even_row = 53760; +static constexpr uint32_t act_rtp_address_even_row = 53824; +static constexpr uint32_t CT_rtp_address_odd_row = 61952; +static constexpr uint32_t act_rtp_address_odd_row = 62016; + +// the weight formats the cores decode (K_div_k[1]) +static constexpr int MIX_FMT_Q4_1 = 0; +static constexpr int MIX_FMT_Q8_0 = 1; +// one 32-row block row of the mixed layout is Din / 512 (Q4_1) or Din / 256 (Q8_0) units of this many bytes +static constexpr uint32_t MIX_UNIT_BYTES = 10240; +static constexpr uint32_t MIX_SLAB_ROWS = 64; +static constexpr uint32_t MIX_COLUMNS = 8; +static constexpr uint32_t MIX_CORE_ROWS = 4; +// bytes of one bfp16ebs8 packet of X a core multiplies: 16 rows x 128 k +static constexpr uint32_t MIX_X_PACKET_BYTES = 16 * 128 * 9 / 8; + +/// One weight of a call: `rows` output rows of format `fmt`, at byte `offset` of the weight buffer. A call may stack several +/// (the K, V and Q projections are one call); their rows must be whole multiples of a column's share. +struct mix_band { + size_t offset; + uint32_t rows; + int fmt; +}; + +/// bytes of one 64-row slab (a pair of 32-row blocks) of a Din-wide weight +inline uint32_t mix_slab_bytes(int fmt, uint32_t Din) { + return 2 * Din / (fmt == MIX_FMT_Q4_1 ? 512 : 256) * MIX_UNIT_BYTES; +} + +/// Slabs each column multiplies per pass. A core always computes 128 x 64 outputs per pass: nb slabs for 128 / nb rows of X. +/// The largest nb whose rows still hold L (up to 8) reads every weight once and X the fewest times. +inline uint32_t mix_nb(uint32_t L, uint32_t Dout) { + uint32_t nb = 8; + while (nb > 1 && (Dout % (MIX_COLUMNS * MIX_SLAB_ROWS * nb) != 0 || L > MIX_CORE_ROWS * 128 / nb)) nb /= 2; + return nb; +} + +/// rows of X (and Y) of one pass +inline uint32_t mix_pass_rows(uint32_t nb) { return MIX_CORE_ROWS * 128 / nb; } + +/// L rounded up to whole passes: the rows the packed X and the output buffer must hold +inline uint32_t mix_rows_padded(uint32_t L, uint32_t Dout) { + const uint32_t m = mix_pass_rows(mix_nb(L, Dout)); + return (L + m - 1) / m * m; +} + +/// Y = X W^T for the mixed-precision weights of the decode layer, read in place. +/// +/// X is bfp16ebs8 in the order the cores consume it (qwen3_asr_prefill_npu.cpp, pack_x); Y is bf16 [rows_padded][Dout] at +/// out_offset (elements); the bands are stacked in order along Dout. Passes go over N (512 nb columns), then M (512 / nb +/// rows). Column c of the array takes slabs c nb .. c nb + nb - 1 of a pass, core row r rows r 128 / nb ..; every X packet +/// goes to all eight columns, every weight chunk to both row pairs of its column. +inline void gen_dequant_mm_mix(npu_sequence* seq, const uint32_t L, const uint32_t Din, const std::vector& bands, + const size_t weight_offset, const size_t out_offset) { + static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + uint32_t Dout = 0; + for (const mix_band& b : bands) Dout += b.rows; + assert(Din % 512 == 0); + + const uint32_t nb = mix_nb(L, Dout); + const uint32_t ms = 8 / nb; // 16-row groups of a core row + const uint32_t m_pass = mix_pass_rows(nb); + const uint32_t n_pass = MIX_COLUMNS * MIX_SLAB_ROWS * nb; + assert(Dout % n_pass == 0); + const uint32_t M_passes = mix_rows_padded(L, Dout) / m_pass; + const uint32_t N_passes = Dout / n_pass; + const uint32_t k_rounds = Din / 512; + // one core row's X of one pass: per 512 k, 2 k slices x ms groups x 2 halves of 128 + const uint32_t x_block_bytes = k_rounds * 4 * ms * MIX_X_PACKET_BYTES; + + seq->clear_cmds(); + + // the slabs of pass np that column c reads, as (byte offset, format) + auto column_weights = [&](uint32_t np, uint32_t c, size_t& off, int& fmt) { + uint32_t row0 = np * n_pass + c * MIX_SLAB_ROWS * nb; + uint32_t band_row = 0; + for (const mix_band& b : bands) { + if (row0 < band_row + b.rows) { + assert(row0 + MIX_SLAB_ROWS * nb <= band_row + b.rows); + fmt = b.fmt; + off = weight_offset + b.offset + (size_t)(row0 - band_row) / MIX_SLAB_ROWS * mix_slab_bytes(b.fmt, Din); + return; + } + band_row += b.rows; + } + assert(false); + }; + auto wait_pass = [&]() { + for (uint32_t r = 0; r < MIX_CORE_ROWS; r++) { + seq->npu_dma_wait(IT[r], S2MM, it_channel_0); + seq->npu_dma_wait(IT[r + 4], S2MM, it_channel_0); + } + }; + + int fmt_set[MIX_COLUMNS]; + for (uint32_t c = 0; c < MIX_COLUMNS; c++) fmt_set[c] = -1; + int round = 0; + for (uint32_t np = 0; np < N_passes; np++) { + size_t w_off[MIX_COLUMNS]; + int fmt[MIX_COLUMNS]; + bool fmt_changed = false; + for (uint32_t c = 0; c < MIX_COLUMNS; c++) { + column_weights(np, c, w_off[c], fmt[c]); + fmt_changed |= fmt[c] != fmt_set[c]; + } + for (uint32_t mp = 0; mp < M_passes; mp++, round++) { + // A core reads its RTPs once a call's first weight chunk is in, so they may only change once every core has + // finished the pass before (its whole output is back): drain it first, then the pipelining starts over. + const bool rewrite = mp == 0 && fmt_changed; + if (rewrite && round > 0) wait_pass(); + if (rewrite) { + for (uint32_t c = 0; c < MIX_COLUMNS; c++) { + for (int row = 2; row < 6; row++) { + npu_tiles tile = get_tile(row, c); + const uint32_t base = (row % 2 == 0) ? CT_rtp_address_even_row : CT_rtp_address_odd_row; + const uint32_t act = (row % 2 == 0) ? act_rtp_address_even_row : act_rtp_address_odd_row; + seq->rtp_write(tile, base, k_rounds); + seq->rtp_write(tile, base + 4, fmt[c]); + seq->rtp_write(tile, base + 8, nb); + seq->rtp_write(tile, act, 0); + } + fmt_set[c] = fmt[c]; + } + } + + const int bd_offset = (round % 2) * 8; + const npu_bd_id y_bd = npu_bd_id(0 + bd_offset); + const npu_bd_id x_bd = npu_bd_id(1 + bd_offset); + const npu_bd_id w_bd = npu_bd_id(2 + bd_offset); + for (uint32_t c = 0; c < MIX_COLUMNS; c++) { + seq->npu_dma_memcpy_nd( + sizeof(char), 2, MM2S, IT[c], w_bd, it_channel_1, + {0, 0, 0, (uint32_t)w_off[c]}, + {1, 1, 1, nb * mix_slab_bytes(fmt[c], Din)}, + {0, 0, 0, 1}, + -1, 0, false, aggressive_cache + ); + } + for (uint32_t r = 0; r < MIX_CORE_ROWS; r++) { + // Y of core row r: columns 0..3 come back through IT[r], 4..7 through IT[r + 4], as rows [slab nb][row of + // the slab's group 16 ms][column 4][64] + const size_t y0 = out_offset + (size_t)(mp * m_pass + r * 16 * ms) * Dout + np * n_pass; + for (uint32_t h = 0; h < 2; h++) { + seq->npu_dma_memcpy_nd( + 2, 0, S2MM, IT[r + 4 * h], y_bd, it_channel_0, + {0, 0, 0, (uint32_t)(y0 + h * 4 * nb * MIX_SLAB_ROWS)}, + {nb, 16 * ms, 4, MIX_SLAB_ROWS}, + {MIX_SLAB_ROWS, Dout, nb * MIX_SLAB_ROWS, 1}, + -1, 0, true + ); + } + // X of core row r, once per slab: the cores multiply every slab against the same rows + seq->npu_dma_memcpy_nd( + 1, 1, MM2S, IT[2 * r], x_bd, it_channel_0, + {0, 0, 0, (uint32_t)((size_t)(mp * MIX_CORE_ROWS + r) * x_block_bytes)}, + {nb, 1, 1, x_block_bytes}, + {0, 0, 0, 1}, + -1, 0, false + ); + } + // keep one pass in flight: wait for the one before (unless it was drained above) + if (round > 0 && !rewrite) wait_pass(); + } + } + wait_pass(); + seq->cmds2seq(); +} + +} // namespace qwen3_asr_prefill_seq diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu.cpp index cfe79ec92..a7c2654e5 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu.cpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu.cpp @@ -92,9 +92,80 @@ void qwen3_asr_npu::Impl::load_weights(Q4NX &q4nx) } this->cpu_decoder = std::make_unique(utils::path_join(config.model_path, "model.q4nx")); this->cpu_kv_length = 0; + { + // the prompt's projections on the NPU, reading the mixed decode weights in place, unless QWEN3_ASR_CPU_PREFILL=1 (or + // the package lacks the kernel) + const char* cpu_env = std::getenv("QWEN3_ASR_CPU_PREFILL"); + const std::string prefill_xclbin = utils::path_join(config.exec_path, "xclbins", config.model_name, "prefill.xclbin"); + if (cpu_env && std::atoi(cpu_env) != 0) + header_print("FLM", "qwen3_asr_npu: prompt prefill on the CPU (QWEN3_ASR_CPU_PREFILL)"); + else if (!this->desc.mixed) + header_print("FLM", "qwen3_asr_npu: no mixed decode weights, prompt prefill on the CPU"); + else if (!std::filesystem::exists(prefill_xclbin)) + header_print("FLM", "qwen3_asr_npu: prefill.xclbin not found, prompt prefill on the CPU"); + else + { + const auto& l0 = *this->desc.weight_desc[0]; + qwen3_asr_prefill_npu::layout l; + l.D = (int)desc.D; + l.DQ = (int)desc.DQ; + l.DK = (int)desc.DK; + l.I = (int)desc.intermediate_size; + l.k = l0.attn_k.offset; + l.v = l0.attn_v.offset; + l.q = l0.attn_q.offset; + l.o = l0.attn_output.offset; + l.up = l0.ffn_up.offset; + l.down = l0.ffn_down.offset; + // the prompt's attention on the NPU too, unless QWEN3_ASR_CPU_ATTENTION=1: in prefill.xclbin's context with the + // control-packet switches (r2t2.switches, unless QWEN3_ASR_NO_SWITCH=1), else on attn.xclbin's own context (if the + // package has it) + const char* cpu_attn_env = std::getenv("QWEN3_ASR_CPU_ATTENTION"); + const std::string xdir = utils::path_join(config.exec_path, "xclbins", config.model_name); + const std::string attn_xclbin = utils::path_join(xdir, "attn.xclbin"); + npu_app_manager* prefill_mgr = npu->register_xclbin(prefill_xclbin); + npu_app_manager* attn_mgr = nullptr; + std::unique_ptr sw; + if (cpu_attn_env && std::atoi(cpu_attn_env) != 0) + header_print("FLM", "qwen3_asr_npu: prompt attention on the CPU (QWEN3_ASR_CPU_ATTENTION)"); + else if (desc.DK % 128 != 0 || desc.DQ != 2 * desc.DK) + header_print("FLM", "qwen3_asr_npu: attention shape not supported by attn.xclbin, prompt attention on the CPU"); + else + { + std::string why; + sw = qwen3_asr_launch::load(prefill_mgr, utils::path_join(xdir, "r2t2.switches"), why); + if (sw) + header_print("FLM", "qwen3_asr_npu: prompt attention in prefill.xclbin's context (control-packet switches)"); + else if (!std::filesystem::exists(attn_xclbin)) + header_print("FLM", "qwen3_asr_npu: attn.xclbin not found, prompt attention on the CPU"); + else + { + header_print("FLM", "qwen3_asr_npu: control-packet switches off (" << why << "), prompt attention on attn.xclbin"); + attn_mgr = npu->register_xclbin(attn_xclbin); + } + } + this->prefill_mm = std::make_unique(prefill_mgr, l, this->proj_weights, attn_mgr, &this->npu_mu, std::move(sw)); + this->cpu_decoder->set_projections(this->prefill_mm.get()); + } + } const std::string audio_path = utils::path_join(config.model_path, "audio_weight.q4nx"); if (std::filesystem::exists(audio_path)) - this->audio_encoder = std::make_unique(audio_path); + { + // matrix products of the encoder on the NPU unless QWEN3_ASR_CPU_ENCODER=1 (or the package lacks the kernel) + const char* cpu_env = std::getenv("QWEN3_ASR_CPU_ENCODER"); + const std::string gemm_xclbin = utils::path_join(config.exec_path, "xclbins", config.model_name, "audio_gemm.xclbin"); + if (cpu_env && std::atoi(cpu_env) != 0) + header_print("FLM", "qwen3_asr_npu: audio encoder on the CPU (QWEN3_ASR_CPU_ENCODER)"); + else if (!std::filesystem::exists(gemm_xclbin)) + header_print("FLM", "qwen3_asr_npu: audio_gemm.xclbin not found, audio encoder on the CPU"); + else + this->audio_gemm = std::make_unique(npu->register_xclbin(gemm_xclbin), &this->npu_mu); + // a host copy of its weights too: the background encode of the next streaming step runs on the CPU, hidden under the NPU + // decode (on the NPU it waits for the decode: npu_mu), unless QWEN3_ASR_NPU_STREAM_ENCODE=1 + const char* stream_env = std::getenv("QWEN3_ASR_NPU_STREAM_ENCODE"); + const bool host_copy = this->audio_gemm && !(stream_env && std::atoi(stream_env) != 0); + this->audio_encoder = std::make_unique(audio_path, qwen3_asr_audio_config{}, this->audio_gemm.get(), host_copy); + } this->clear_context(); } @@ -165,6 +236,7 @@ buffer qwen3_asr_npu::Impl::forward(int ids) this->prefill_logits.data()[i] = (bf16)cpu_logits[i]; return this->prefill_logits; } + std::lock_guard lock(this->npu_mu); // the next step's background encode waits between tokens // the token's row of the bf16 embedding table, which the CPU decoder maps from model.q4nx (no second copy in memory) std::memcpy(this->x.data(), this->cpu_decoder->embed_row(ids), desc.D * sizeof(bf16)); this->x.sync_to_device(); @@ -192,8 +264,9 @@ buffer qwen3_asr_npu::Impl::forward(int ids) buffer qwen3_asr_npu::Impl::prefill(std::vector &ids, void *payload) { - // The prompt is prefilled on the CPU: for the short prompts of speech recognition (about 100-400 tokens: a system - // message, the audio tokens, the text so far) the CPU is faster than the NPU prefill, and it needs no prefill kernels. + // The prompt runs through the CPU decoder, whose matrix products go to prefill.xclbin (prefill_mm; the norms, RoPE, + // attention and the last token's logits stay on the host). Without that kernel, or with QWEN3_ASR_CPU_PREFILL=1, all + // of it runs on the CPU. return this->_prefill_on_cpu(ids, static_cast(payload)); } @@ -412,7 +485,7 @@ void qwen3_asr_npu::Impl::_start_background(const qwen3_asr_payload_t &payload, prefetch_t r; r.frames = frames; r.slice_start = next_start; - r.bits = this->audio_encoder->encode(slice.data(), frames - next_start, &this->stream_cache.conv); + r.bits = this->audio_encoder->encode(slice.data(), frames - next_start, &this->stream_cache.conv, /*host=*/true); r.mel_slice = std::move(slice); return r; }); @@ -466,6 +539,7 @@ buffer qwen3_asr_npu::Impl::get_v_cache(int layer_idx, int idx) buffer qwen3_asr_npu::Impl::get_logits(buffer &predict) { + std::lock_guard lock(this->npu_mu); memcpy(this->x.data(), predict.data(), desc.D * sizeof(bf16)); this->x.sync_to_device(); this->lm_head_run.start(); diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu_detail.hpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu_detail.hpp index 92fcceca8..9b3478545 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu_detail.hpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/qwen3_asr_npu_detail.hpp @@ -7,6 +7,8 @@ #include "qwen3_asr_npu_def.hpp" #include "decoder/qwen3_asr_cpu_decoder.hpp" #include "audio/qwen3_asr_audio_encoder.hpp" +#include "audio/qwen3_asr_audio_gemm_npu.hpp" +#include "prefill/qwen3_asr_prefill_npu.hpp" #include "utils/kv_rows_state.hpp" #include #include @@ -68,9 +70,17 @@ struct qwen3_asr_npu::Impl{ /// @brief model dimensions, weight descriptors and weight loading qwen3_asr_desc desc; - /// @brief CPU prefill (created in load_weights, it reads the same model.q4nx) + /// @brief held by every call that runs the NPU (decode, prefill_mm, audio_gemm): the background job of the next step encodes + /// (and, offline, prefills) during the decode, and a run of one hw_context while the decode runlist of another is in flight + /// never completes (ERT_CMD_STATE_TIMEOUT). Declared before the users it outlives. + std::mutex npu_mu; + /// @brief the prompt prefill's matrix products on the NPU (prefill.xclbin); declared before cpu_decoder, which uses it + std::unique_ptr prefill_mm; + /// @brief the prompt prefill (created in load_weights, it reads the same model.q4nx); its projections run on prefill_mm std::unique_ptr cpu_decoder; - /// @brief host audio encoder (created in load_weights when audio_weight.q4nx is in the package) + /// @brief the audio encoder's matrix products on the NPU (audio_gemm.xclbin); declared before audio_encoder, which uses it + std::unique_ptr audio_gemm; + /// @brief audio encoder (created in load_weights when audio_weight.q4nx is in the package) std::unique_ptr audio_encoder; /// @brief logits of the last prompt token, in plain host memory. NOT the NPU's `logits` buffer: writing that one from the /// host leaves dirty cache lines that are written back over the NPU's output at the next sync_from_device() diff --git a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/tools/qwen3_asr_engine_run.cpp b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/tools/qwen3_asr_engine_run.cpp index 80a9d42cd..6a7925cd4 100644 --- a/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/tools/qwen3_asr_engine_run.cpp +++ b/flm-dev-kit/FLM_DLL/detail/qwen3_asr_npu/tools/qwen3_asr_engine_run.cpp @@ -3,7 +3,8 @@ // Engine-level harness for libqwen3_asr_npu.so: prefill on the CPU, decode on the NPU, against the frozen goldens. // -// qwen3_asr_engine_run [ ...] [--max-length N] [--cpu-decode] +// qwen3_asr_engine_run [ ...] [--max-length N] [--mel] [--out-ids f] +// [--split-at-audio] (two prefills: the text before the audio, then the rest after it) // // pkg_dir: the weights package (config.json, model.q4nx, tokenizer.json); the engine reads // /xclbins//layer.xclbin. @@ -38,13 +39,14 @@ int main(int argc, char** argv) { const std::string pkg = p.string(), xroot = argv[2], gdir = argv[3]; std::vector clips; int max_length = 8192; - bool use_mel = false; + bool use_mel = false, split_at_audio = false; // split: prefill the text before the audio, then the rest after it std::string out_ids; for (int i = 4; i < argc; i++) { std::string a = argv[i]; if (a == "--max-length" && i + 1 < argc) max_length = std::stoi(argv[++i]); else if (a == "--mel") use_mel = true; else if (a == "--out-ids" && i + 1 < argc) out_ids = argv[++i]; + else if (a == "--split-at-audio") split_at_audio = true; else clips.push_back(a); } constexpr int EOS0 = 151645, EOS1 = 151643; @@ -97,7 +99,15 @@ int main(int argc, char** argv) { engine.clear_context(); auto t0 = std::chrono::steady_clock::now(); - buffer logits = engine.prefill(ids, &payload); + buffer logits; + const auto pad = std::find(ids.begin(), ids.end(), payload.audio_pad_id); + if (split_at_audio && pad != ids.begin() && pad != ids.end()) { + std::vector head(ids.begin(), pad), rest(pad, ids.end()); + engine.prefill(head, nullptr); + logits = engine.prefill(rest, &payload); + } else { + logits = engine.prefill(ids, &payload); + } const double prefill_ms = ms_since(t0); std::vector mine; diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/Makefile b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/Makefile new file mode 100755 index 000000000..8966468b5 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/Makefile @@ -0,0 +1,64 @@ +# +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Modified by Alfred + +include makefiles/common.mk +HOME_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) + +KERNEL_ARGS := -DMODEL_TYPE=${MODEL_TYPE} +IRON_ARGS := ${MODEL_TYPE} + +ITERATION ?= 1 + +# Kernel makefile +include makefiles/kernel.mk + +# Bitstream makefile +include makefiles/bitstream.mk + +# Host makefile +include makefiles/host.mk + +.PHONY: run all kernel link bitstream host clean clean_all instructions +all: ${XCLBIN_TARGET} ${INSTS_TARGET} ${HOST_C_TARGET} + +clean_all: + -@rm -rf build + -@rm -rf log + -@rm -rf *.exe + -@rm -rf trace* + -@rm -rf routes + + + +kernel: ${KERNEL_OBJS} + + +instructions: ${INSTS_TARGETS} + + +link: ${IRON_BOTH_MLIR_TARGET} + + +bitstream: ${XCLBIN_TARGETS} + + +host: ${HOST_C_TARGET} + + +clean: + -@rm -rf build/host + -@rm -rf ${HOST_C_TARGET} + + +test: $(HOST_C_TARGET) + export LD_LIBRARY_PATH=/opt/xilinx/xrt/lib && ./$(HOST_C_TARGET) + +route: ${IRON_BOTH_MLIR_TARGET} + mkdir -p routes + aie-opt --aie-create-pathfinder-flows --aie-find-flows ${<} | aie-translate --aie-flows-to-json > ./routes/route.json + python visualize.py -j ./routes/route.json \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/README.md b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/README.md new file mode 100644 index 000000000..27fa9690c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/README.md @@ -0,0 +1,65 @@ + + +# bfp16_gemm + +A 32-core GEMM for bf16 weights: `Y[M, N] = act(X[M, K] W[N, K]^T + b)`, bf16 out, with both operands multiplied as native +block float (`bfp16ebs8`, 8 values sharing one exponent, 9 bytes) and fp32 accumulation. The host packs the weights once at +load time (1.125 bytes per weight instead of 2) and packs X before each call. Bias and an optional GELU (tanh form) are +applied on the core. + +* `iron/gemm_aie.py`, `iron/gemm_tile.py`: the dataflow (8 columns x 4 core rows; a round is 256 rows x 1024 columns). +* `kernel/gemm.h`: the core loop (`gemm_e.cc` / `gemm_o.cc` are the two cores of a vertical pair). +* `host/seq_gen.hpp`: the run-time sequence, the DDR layouts and the weight modes below. An engine includes it. +* `host/pack_bfp16.hpp`: the bf16 -> bfp16 block encoder (round to nearest even on the mantissas). +* `host/host.cpp`: the test (`run.exe`), random operands against an fp32 product of the packed operands. +* `check_memtile_bds.py`: build-time check that the design leaves the memtile descriptors, locks and start queues the host + programs free. + +## Constraints + +* `K % 128 == 0`, `N % 1024 == 0` (pad), `M` any (padded to 256-row rounds, at most 31 rounds per call). +* `K > 3072` (or `--stream 1`): `K % 512 == 0` and `K / 128 x rounds <= 256` per call; an engine splits larger `M` over calls. +* `act` 0 = none, 1 = GELU. Peano only. + +## Weight modes + +The memtile weight path is not in the design: every call writes its descriptors, locks and start queues. + +| mode | when | weights from DDR | starts computing | +|---|---|---|---| +| hybrid | `K <= 1536` | once per call | on the first 128-k chunk; rounds 2.. send the resident panel | +| panel | `1536 < K <= 3072` | once per call | after the whole panel (224 KB per column) landed | +| stream | `K > 3072`, or forced | once per round | on the first chunk (a ring of 4 or 8 chunks) | + +## Speed + +Ryzen AI 9 HX 370, median of 20 warm calls, padded rows, bit-exact against the reference in every case: + +| M x K x N | time | TFLOPS | +|---|---|---| +| 256 x 1024 x 1024 | 157 us | 3.4 | +| 256 x 1024 x 4096 | 243 us | 8.8 | +| 1024 x 1024 x 4096 | 553-600 us | 14.3-15.5 | +| 4096 x 1024 x 4096 | 1750 us | 19.6 | +| 1024 x 3072 x 3072 | 1110 us | 17.4 | +| 2048 x 2048 x 6144 | 2659 us | 19.4 | +| 4096 x 2048 x 8192 | 6318 us | 21.8 | +| 884 x 4096 x 1024 (stream) | 528 us | 16.3 | +| 884 x 7680 x 1024 (stream) | 919 us | 17.5 | + +The cores alone run at about 40 TFLOPS; the calls above are bound by DDR traffic (about 25 GB/s on the test machine). Per +flop a call moves about `1.125 / 2048` bytes of X (re-read for every 1024 columns), `1.125 / (2 M)` of W and `1 / K` of +bf16 Y. That model gives 21.7 TFLOPS at 4096 x 2048 x 8192, as measured; at `K = 1024` the Y writes alone cap a call at +about 25 TFLOPS. Small calls pay about 100 us of weight latency before the first multiply. + +## Test + +``` +make kernel && make bitstream && make host PEANO_INSTALL_DIR= +./run.exe --M 1024 --K 1024 --N 4096 --iters 20 [--act 1] [--stream 1] [--hybrid 0] +``` + +A call that does not finish in 10 s writes `~/.npu_suspect` and holds the hardware context 90 s so the driver can recover. diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/check_memtile_bds.py b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/check_memtile_bds.py new file mode 100644 index 000000000..1267cb165 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/check_memtile_bds.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""Post-build check for the host-programmed memtile weight path (host/seq_gen.hpp). + +The design leaves memtile S2MM0 (weight panel in), MM2S0 (lo halves out) and MM2S1 (hi halves out) +without descriptors; the host sequence writes their descriptors, panel locks and start queues on every +call. This verifies, in the CDO the build produced, that the static y path did not take the descriptor +ids the host writes, that the three channels get no start descriptor, that the panel locks start at 0, +and that the static y descriptors use the base-address and lock-id encoding the host code assumes. + +usage: check_memtile_bds.py [--dump] +""" +import glob, os, struct, sys + +BD_BASE, BD_STRIDE = 0xA0000, 0x20 +LOCK_BASE, LOCK_STRIDE = 0xC0000, 0x10 +# keep in sync with host/seq_gen.hpp +W_BDS = (18, 19, 20, 21, 22, 23, 44, 45, 46, 47) # S2MM0 panel 0 / 1, MM2S0 + MM2S1 panel 0 / 1 (+ hybrid) +PANEL_LOCKS = (8, 9, 10, 11) +W_START_QUEUES = (0xA0604, 0xA0634, 0xA063C) # S2MM0, MM2S0, MM2S1 +MT_OWN_BASE_WORDS = 0x80000 // 4 # memtile own memory in the descriptor address space +MT_OWN_LOCK = 64 # memtile own locks in the descriptor lock-id space +Y_ADDR = 0 # iron/gemm_tile.py MT_Y_ADDR + + +def commands(path): + w = struct.unpack("<%dI" % (os.path.getsize(path) // 4), open(path, "rb").read()) + i = w[0] + 1 + while i < len(w): + h = w[i] + cid, ln = h & 0xFFFF, (h >> 16) & 0xFF + extra = 0 + if ln == 0xFF: + ln, extra = w[i + 1], 1 + yield cid, w[i + 1 + extra:i + 1 + extra + ln] + i += 1 + extra + ln + + +def main(): + root = sys.argv[1] if len(sys.argv) > 1 else "." + dump = "--dump" in sys.argv + hits = glob.glob(os.path.join(root, "**", "main_aie_cdo_init.bin"), recursive=True) or \ + glob.glob(os.path.join(root, "**", "aie_cdo_init.bin"), recursive=True) + if not hits: + print("error: no (main_)aie_cdo_init.bin under", root) + return 1 + bds, queues, locks = {}, {}, {} + for path in hits[:1]: + for cid, pay in commands(path): + if cid == 0x105 and len(pay) >= 3: + a, data = pay[1], pay[2:] + col, row, off = (a >> 25) & 0x7F, (a >> 20) & 0x1F, a & 0xFFFFF + if row == 1 and BD_BASE <= off < BD_BASE + 48 * BD_STRIDE and (off - BD_BASE) % BD_STRIDE == 0: + bds[(col, (off - BD_BASE) // BD_STRIDE)] = data[:8] + elif cid == 0x108 and len(pay) == 3: + a, val = pay[1], pay[2] + col, row, off = (a >> 25) & 0x7F, (a >> 20) & 0x1F, a & 0xFFFFF + if row != 1: + continue + if 0xA0600 <= off < 0xA0700 and off % 8 == 4: + queues[(col, off)] = val + elif LOCK_BASE <= off < LOCK_BASE + 64 * LOCK_STRIDE and (off - LOCK_BASE) % LOCK_STRIDE == 0: + locks[(col, (off - LOCK_BASE) // LOCK_STRIDE)] = val + if dump: + for (col, b), d in sorted(bds.items()): + if col == 0: + print(f"bd {b:2d}: " + " ".join(f"{x:08x}" for x in d)) + for (col, off), v in sorted(queues.items()): + if col == 0: + print(f"start queue {off:#x} = {v:#x}") + for (col, lk), v in sorted(locks.items()): + if col == 0: + print(f"lock {lk} init {v}") + bad = 0 + for col in range(8): + for b in W_BDS: + if (col, b) in bds: + print(f"error: memtile col {col} BD {b} is used by the design; the host writes it") + bad += 1 + for q in W_START_QUEUES: + if (col, q) in queues: + print(f"error: memtile col {col} start queue {q:#x} is pushed by the design") + bad += 1 + for lk in PANEL_LOCKS: + if locks.get((col, lk), 0) != 0: + print(f"error: memtile col {col} panel lock {lk} init {locks[(col, lk)]}, expected 0") + bad += 1 + # the y S2MM descriptors: base = MT_OWN_BASE_WORDS + Y_ADDR / 4 + strip offset, locks own 0-7 (+ MT_OWN_LOCK) + ys = [d for (c, b), d in bds.items() if c == col] + bases = sorted((d[1] & 0x7FFFF) for d in ys) + if not bases or bases[0] != MT_OWN_BASE_WORDS + Y_ADDR // 4: + print(f"error: memtile col {col}: lowest descriptor base {bases[:1]}, expected {MT_OWN_BASE_WORDS + Y_ADDR // 4:#x}") + bad += 1 + lock_ids = sorted({d[7] & 0xFF for d in ys} | {(d[7] >> 16) & 0xFF for d in ys}) + if lock_ids != [MT_OWN_LOCK + i for i in range(8)]: + print(f"error: memtile col {col}: descriptor lock ids {lock_ids}, expected {MT_OWN_LOCK}..{MT_OWN_LOCK + 7}") + bad += 1 + if bad: + return 1 + print(f"check_memtile_bds: 8 memtiles leave BDs {W_BDS}, the weight start queues and panel locks to the host") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/host.cpp b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/host.cpp new file mode 100644 index 000000000..51706efaa --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/host.cpp @@ -0,0 +1,200 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// bfp16 GEMM test: random bf16 X / W / bias, packed to bfp16 on the host, Y = act(X W^T + b) on the NPU, +// checked against an fp32 product of the packed (decoded) operands, and timed. +// ./run.exe --M 1024 --K 1024 --N 4096 [--act 1] [--iters 20] +// A run that does not complete in 10 s leaves ~/.npu_suspect (or $NPU_SUSPECT_FILE) and holds the +// hardware context 90 s, so the driver's job timeout can recover the device before the process exits. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "typedef.hpp" +#include "npu_utils/npu_utils.hpp" +#include "pack_bfp16.hpp" +#include "seq_gen.hpp" + +namespace po = boost::program_options; +using namespace pack_bfp16; + +// x: block (row / 16, kc), then [16 k tiles][2 row halves][8 rows][9 B] +static void pack_x(uint8_t* dst, const std::vector& x, uint32_t M, uint32_t m_pad, uint32_t K) { + const uint32_t KC = K / 128; +#pragma omp parallel for + for (uint32_t r = 0; r < m_pad; r++) + for (uint32_t k8 = 0; k8 < K / 8; k8++) { + const uint32_t kc = k8 / 16, kt = k8 % 16; + uint8_t* o = dst + (((size_t)(r / 16) * KC + kc) * bfp16_gemm::X_BLOCK_WORDS * 4) + kt * 144 + ((r % 16) / 8) * 72 + (r % 8) * 9; + if (r < M) encode_block(o, &x[(size_t)r * K + 8 * k8]); + else std::memset(o, 0, 9); + } +} + +// w: chunk (nb, column, kc, half) = [4 jp][16 k tiles][2][8 columns][9 B], then the half's 64 bf16 biases +static void pack_w(uint8_t* dst, const std::vector& w, const std::vector& bias, uint32_t N, uint32_t K) { + const uint32_t KC = K / 128; + const size_t half_bytes = bfp16_gemm::W_HALF_WORDS * 4; +#pragma omp parallel for + for (uint32_t n = 0; n < N; n++) { + const uint32_t nb = n / 1024, col = (n / 128) % 8, h = (n / 64) % 2, jp = (n / 16) % 4, j = (n / 8) % 2, c8 = n % 8; + for (uint32_t kc = 0; kc < KC; kc++) { + uint8_t* chunk = dst + ((((size_t)nb * 8 + col) * KC + kc) * 2 + h) * half_bytes; + for (uint32_t kt = 0; kt < 16; kt++) + encode_block(chunk + ((jp * 16 + kt) * 2 + j) * 72 + c8 * 9, &w[(size_t)n * K + kc * 128 + kt * 8]); + std::memcpy(chunk + 9216 + 2 * (n % 64), &bias[n], 2); + } + } +} + +// the values the cores multiply: 8 x int8 mantissa x 2^(shared exponent - 133) +static void decode_rows(std::vector& dst, const std::vector& src, size_t rows, uint32_t K) { + dst.resize(rows * K); +#pragma omp parallel for + for (size_t r = 0; r < rows; r++) + for (uint32_t k8 = 0; k8 < K / 8; k8++) { + uint8_t blk[9]; + encode_block(blk, &src[r * K + 8 * k8]); + for (int i = 0; i < 8; i++) dst[r * K + 8 * k8 + i] = std::ldexp((float)(int8_t)blk[1 + i], (int)blk[0] - 133); + } +} + +static float bf16r(float v) { return bf16_to_f32(f32_to_bf16(v)); } + +// getGeluBf16_nonLUT, step by step in bf16 +static float gelu_bf16(float x) { + const float x2 = bf16r(x * x), x3 = bf16r(x * x2), inner = bf16r(x + bf16r(x3 * bf16r(0.044715f))); + const float t = bf16r(std::tanh(inner * bf16r(0.79788456f))); + return bf16r(x * bf16r(0.5f * bf16r(t + 1.0f))); +} + +int main(int argc, char** argv) { + uint32_t M, K, N, act, iters, seed, xcache, reuse, stream, hybrid; + std::string xclbin; + po::options_description desc("bfp16 GEMM test"); + desc.add_options()("help,h", "help") + ("M", po::value(&M)->default_value(256), "rows (padded to 256)") + ("K", po::value(&K)->default_value(1024), "inner size, multiple of 128 (above 3072 or with --stream: of 512)") + ("stream", po::value(&stream)->default_value(0), "1: stream the weights even if they fit") + ("hybrid", po::value(&hybrid)->default_value(1), "K <= 1536: 0 waits for the whole weight panel") + ("N", po::value(&N)->default_value(1024), "output columns, multiple of 1024") + ("act", po::value(&act)->default_value(0), "0 none, 1 GELU") + ("iters", po::value(&iters)->default_value(1), "timed calls") + ("seed", po::value(&seed)->default_value(0), "rng seed") + ("xcache", po::value(&xcache)->default_value(1), "x read cache hint: 0 no, 1 normal, 2 aggressive") + ("reuse", po::value(&reuse)->default_value(0), "1: one run object, started again for every call") + ("xclbin", po::value(&xclbin)->default_value("build/xclbins/gemm.xclbin"), "xclbin"); + po::variables_map vm; + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + if (vm.count("help")) { std::cout << desc << "\n"; return 0; } + const uint32_t m_pad = (M + 255) / 256 * 256, R = m_pad / 256; + bfp16_gemm::call_t call{R, K / 128, N / 1024, N, act}; + call.stream = stream != 0; + call.hybrid = hybrid != 0; + const bool streamed = bfp16_gemm::streams(call); + if (K % 128 || N % 1024 || R > bfp16_gemm::MAX_ROUNDS || act > 1 || + (streamed && (K % 512 || call.kc * R > bfp16_gemm::MAX_QUEUE_REPEAT))) { + std::cerr << "unsupported shape\n"; + return 2; + } + std::printf("M %u (pad %u, %u rounds) K %u N %u act %u iters %u weights %s\n", M, m_pad, R, K, N, act, iters, + streamed ? "streamed" : bfp16_gemm::hybrids(call) ? "resident (hybrid)" : "resident"); + + std::vector x((size_t)M * K), w((size_t)N * K), bias(N); + { + std::mt19937 rng(seed); + std::normal_distribution dx(0.0f, 1.0f), dw(0.0f, 0.03f), db(0.0f, 0.5f); + for (auto& v : x) v = f32_to_bf16(dx(rng)); + for (auto& v : w) v = f32_to_bf16(dw(rng)); + for (auto& v : bias) v = f32_to_bf16(db(rng)); + } + + xrt::device device(0); + npu_xclbin_manager mgr(npu_device::device_npu2, &device, false); + npu_app_manager* gemm_mgr = mgr.register_xclbin(xclbin); + npu_app app = gemm_mgr->create_app(); + call.x_cache = xcache == 0 ? no_cache : xcache == 1 ? normal_cache : aggressive_cache; + bfp16_gemm::gen_gemm(app.seq(), call); + + buffer bx = app.create_bo_buffer(bfp16_gemm::x_bytes(m_pad, K)); + buffer bw = app.create_bo_buffer(bfp16_gemm::w_bytes(N, K)); + buffer by = app.create_bo_buffer((size_t)m_pad * N); + pack_x(bx.data(), x, M, m_pad, K); + pack_w(bw.data(), w, bias, N, K); + std::fill(by.data(), by.data() + by.size(), (uint16_t)0x7FC0); // NaN: shows rows / columns never written + bx.sync_to_device(); + bw.sync_to_device(); + by.sync_to_device(); + + xrt::run kept = app.create_run(by, bx, bw); + auto run_once = [&]() -> bool { + xrt::run run = reuse ? kept : app.create_run(by, bx, bw); + run.start(); + const ert_cmd_state st = run.wait(std::chrono::milliseconds(10000)); + if (st == ERT_CMD_STATE_COMPLETED) return true; + const char* f = std::getenv("NPU_SUSPECT_FILE"); + const std::string path = f ? f : std::string(std::getenv("HOME")) + "/.npu_suspect"; + std::ofstream(path) << "bfp16_gemm run.exe: run state " << (int)st << " (M " << M << " K " << K << " N " << N << ")\n"; + std::cerr << "run did not complete (state " << (int)st << "); wrote " << path << ", holding the context 90 s\n"; + std::this_thread::sleep_for(std::chrono::seconds(90)); + return false; + }; + + std::vector us; + for (uint32_t i = 0; i < std::max(iters, 1u); i++) { + const auto t0 = std::chrono::steady_clock::now(); + if (!run_once()) return 3; + us.push_back(std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + } + by.sync_from_device(); + + // reference on the operands the cores see + std::vector xd, wd; + decode_rows(xd, x, M, K); + decode_rows(wd, w, N, K); + size_t bad = 0, nan = 0, exact = 0; + double se = 0, sr = 0, max_err = 0; +#pragma omp parallel for reduction(+ : bad, nan, exact, se, sr) reduction(max : max_err) + for (uint32_t r = 0; r < M; r++) + for (uint32_t n = 0; n < N; n++) { + float acc = 0; + const float* a = &xd[(size_t)r * K]; + const float* b = &wd[(size_t)n * K]; + for (uint32_t k = 0; k < K; k++) acc += a[k] * b[k]; + float ref = bf16r(acc + bf16_to_f32(bias[n])); + if (act == 1) ref = gelu_bf16(ref); + const uint16_t gb = by.data()[(size_t)r * N + n]; + if ((gb & 0x7FFF) > 0x7F80) { nan++; continue; } // bit test: -ffast-math drops isnan + const float got = bf16_to_f32(gb); + const double e = std::fabs((double)got - ref); + if (got == ref) exact++; + if (r == M - 1 && n >= N - 4) +#pragma omp critical + std::printf(" y[%u][%u] npu %.6g ref %.6g\n", r, n, got, ref); + se += e * e; + sr += (double)ref * ref; + max_err = std::max(max_err, e); + if (e > 0.02 * std::fabs(ref) + 0.02) bad++; + } + std::sort(us.begin(), us.end()); + const double med = us[us.size() / 2]; + const double flop = 2.0 * m_pad * N * K; + std::printf("NPU: min %.1f us median %.1f us -> %.2f TFLOPS (padded rows), %.2f (real rows)\n", us[0], med, + flop / med * 1e-6, flop * M / m_pad / med * 1e-6); + std::printf("vs fp32 of packed operands: rel L2 %.3e max abs %.3e bit-exact %.2f%% out of tolerance %zu unwritten %zu\n", + std::sqrt(se / std::max(sr, 1e-30)), max_err, 100.0 * exact / ((double)M * N), bad, nan); + const bool pass = bad == 0 && nan == 0; + std::printf("%s\n", pass ? "PASSED" : "FAILED"); + return pass ? 0 : 1; +} diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/pack_bfp16.hpp b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/pack_bfp16.hpp new file mode 100644 index 000000000..ca45fa3c4 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/pack_bfp16.hpp @@ -0,0 +1,45 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file pack_bfp16.hpp +/// \brief bf16 <-> fp32 and the bf16 -> bfp16ebs8 block encoder the GEMM's operands use. +#ifndef __PACK_BFP16_HPP__ +#define __PACK_BFP16_HPP__ +#pragma once +#include +#include +#include +#include + +namespace pack_bfp16 { + +inline float bf16_to_f32(uint16_t b) { uint32_t u = (uint32_t)b << 16; float f; std::memcpy(&f, &u, 4); return f; } +inline uint16_t f32_to_bf16(float f) { // round to nearest even + uint32_t u; std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x7FFFu + ((u >> 16) & 1u)) >> 16); +} + +/// 8 bf16 -> one 9 B block: the largest fp32 exponent field of the 8, then each +/// value's signed 24-bit mantissa shifted right by (17 + max_exp - exp), capped at +/// 31, rounded to nearest even (what the core's own bf16 -> bfp16 conversion does +/// under conv_even). A value is mantissa x 2^(exponent - 133). +inline void encode_block(uint8_t* out, const uint16_t* v) { + int ex[8], mx = 0; + for (int i = 0; i < 8; i++) { ex[i] = (v[i] >> 7) & 0xFF; if (ex[i] > mx) mx = ex[i]; } + out[0] = (uint8_t)mx; + for (int i = 0; i < 8; i++) { + int32_t mag = (int32_t)(((uint32_t)v[i] & 0x7Fu) << 16); + if (ex[i]) mag |= 0x800000; + const int32_t s = (v[i] & 0x8000u) ? -mag : mag; + int sh = 17 + mx - ex[i]; if (sh > 31) sh = 31; + int32_t q = s >> sh; + const int32_t rem = s - (int32_t)((uint32_t)q << sh), half = 1 << (sh - 1); + if (rem > half || (rem == half && (q & 1))) q++; + if (q > 127) q = 127; + out[1 + i] = (uint8_t)(int8_t)q; + } +} + +} // namespace pack_bfp16 + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/seq_gen.hpp b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/seq_gen.hpp new file mode 100644 index 000000000..48d0f81cf --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/host/seq_gen.hpp @@ -0,0 +1,222 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +/// \file seq_gen.hpp +/// \brief Run-time sequence of the bfp16 GEMM (iron/gemm_aie.py): Y = act(X W^T + b), bf16 out. +/// +/// One call runs R rounds of 256 rows against NB blocks of 1024 output columns, K = 128 KC. +/// Weights go through the memtiles in one of two modes: +/// panel (KC <= 24): a column's whole block of weights stays in its memtile and is sent R times; +/// read from DDR once per call. With KC <= 12 (hybrid) round 1 starts on the first +/// chunk instead of waiting for the whole panel. +/// stream (KC > 24, or forced): the memtile is a ring of chunk slots refilled from DDR; the weights +/// are read once per round. KC multiple of 4, KC R <= 256 per call. +/// DDR layouts (all bfp16ebs8, 9 B per 8 k; see pack_bfp16.hpp for the block encoding): +/// x [M / 16 row blocks][KC][16 k tiles][2 row halves][8 rows][9 B] (2304 B per block and kc) +/// w [NB][8 columns][KC][lo | hi][4 jp][16 k tiles][2][8 columns][9 B] + 64 bf16 bias (9344 B per half) +/// y bf16 row-major, row pitch ldy elements +/// The memtile weight path is not in the design: each call writes its descriptors, panel locks and +/// start queues (check_memtile_bds.py verifies at build time that the design leaves them free). +#ifndef __BFP16_GEMM_SEQ_GEN_HPP__ +#define __BFP16_GEMM_SEQ_GEN_HPP__ +#pragma once +#include +#include "npu_utils/npu_utils.hpp" + +namespace bfp16_gemm { + +// core RTP (iron/gemm_tile.py RTP_ADDR): [0] KC, [1] rounds of 256 rows (all N blocks), [2] act +static constexpr uint32_t CT_RTP_ADDR = 58112; + +static constexpr uint32_t X_BLOCK_WORDS = 576; // 16 rows x 128 k +static constexpr uint32_t W_HALF_WORDS = 2336; // 64 columns x 128 k + 64 bf16 bias +static constexpr uint32_t W_CHUNK_WORDS = 2 * W_HALF_WORDS; +static constexpr uint32_t ROUND_ROWS = 256, BLOCK_COLS = 1024, COLUMNS = 8, CORE_ROWS = 4; +static constexpr uint32_t MAX_ROUNDS = 31; // panel locks count 2 credits per round, 7-bit lock values +static constexpr uint32_t KC_DOUBLE = 12, KC_SINGLE = 24; // panel fits twice / once in the memtile + +// memtile (row 1); keep in sync with iron/gemm_tile.py and check_memtile_bds.py +static constexpr uint32_t MT_BD_BASE = 0xA0000, MT_BD_STRIDE = 0x20, MT_LOCK_BASE = 0xC0000, MT_LOCK_STRIDE = 0x10; +static constexpr uint32_t MT_OWN_WORDS = 0x80000 / 4, MT_OWN_LOCK = 64; +static constexpr uint32_t MT_PANEL_ADDR[2] = {65536, 294912}; +static constexpr uint32_t MT_S2MM0_BD[2] = {20, 21}, MT_LO_BD[2] = {22, 23}, MT_HI_BD[2] = {44, 45}; +static constexpr uint32_t MT_PANEL_PROD[2] = {8, 9}, MT_PANEL_CONS[2] = {10, 11}; +static constexpr uint32_t MT_S2MM0_QUEUE = 0xA0604, MT_MM2S0_QUEUE = 0xA0634, MT_MM2S1_QUEUE = 0xA063C; +// stream mode: ring at panel 0's address; locks: free slots, lo half ready, hi half ready +static constexpr uint32_t MT_RING_FREE = 8, MT_RING_LO = 10, MT_RING_HI = 11; +// hybrid mode: per panel "chunk lo ready" / "chunk hi ready" locks; rounds 2..R send the panel with these BDs +static constexpr uint32_t MT_CHUNK_LO[2] = {8, 9}, MT_CHUNK_HI[2] = {10, 11}; +static constexpr uint32_t MT_LO_PANEL_BD[2] = {18, 19}, MT_HI_PANEL_BD[2] = {46, 47}; +static constexpr uint32_t MAX_QUEUE_REPEAT = 256; // start queue repeat field: 8 bits + +inline uint32_t mt_lock_word(uint32_t acq_id, int acq_ge, uint32_t rel_id, int rel_val) { + return (1u << 31) | ((uint32_t)(rel_val & 0x7F) << 24) | ((MT_OWN_LOCK + rel_id) << 16) | (1u << 15) | + ((uint32_t)(-acq_ge & 0x7F) << 8) | (MT_OWN_LOCK + acq_id); +} +inline uint32_t mt_release_word(uint32_t rel_id, int rel_val) { + return (1u << 31) | ((uint32_t)(rel_val & 0x7F) << 24) | ((MT_OWN_LOCK + rel_id) << 16); +} +inline uint32_t mt_acquire_word(uint32_t acq_id, int acq_ge) { + return (1u << 31) | (1u << 15) | ((uint32_t)(-acq_ge & 0x7F) << 8) | (MT_OWN_LOCK + acq_id); +} +inline uint32_t mt_dim(uint32_t wrap, uint32_t stride) { return (wrap << 17) | (stride - 1); } +inline uint32_t mt_iter(uint32_t wrap, uint32_t stride) { return ((wrap - 1) << 17) | (stride - 1); } + +/// One call's shape. x_words / y_elems / w_bytes: offsets into the three buffers. +struct call_t { + uint32_t rounds; //!< R: 256-row rounds, <= MAX_ROUNDS + uint32_t kc; //!< K / 128, <= KC_SINGLE + uint32_t nb; //!< N blocks of 1024 columns + uint32_t ldy; //!< row pitch of y in elements (>= 1024 nb) + uint32_t act; //!< 0 none, 1 GELU (tanh form) + size_t x_words = 0; //!< first 16-row block of x + size_t w_words = 0; //!< first N block of w + size_t y_elems = 0; //!< y[0][0] of this call + cache_flag_t x_cache = normal_cache; //!< x is read once per N block + bool stream = false; //!< stream mode even if the panel fits (KC > KC_SINGLE always streams) + bool hybrid = true; //!< KC <= KC_DOUBLE: round 1 sends each chunk as it lands (false: after the whole panel) +}; + +inline bool streams(const call_t& c) { return c.stream || c.kc > KC_SINGLE; } +inline bool hybrids(const call_t& c) { return c.hybrid && !streams(c) && c.kc <= KC_DOUBLE; } + +inline size_t x_bytes(uint32_t m_pad, uint32_t K) { return (size_t)m_pad / 16 * (K / 128) * X_BLOCK_WORDS * 4; } +inline size_t w_bytes(uint32_t N, uint32_t K) { return (size_t)N / 128 * (K / 128) * W_CHUNK_WORDS * 4; } + +/// Arguments: 0 = y (bf16), 1 = x (bfp16), 2 = w (bfp16 + bias). +inline void gen_gemm(npu_sequence* seq, const call_t& c) { + static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + assert(c.rounds >= 1 && c.rounds <= MAX_ROUNDS); + const bool stream = streams(c); + assert(c.kc >= 1 && c.nb >= 1); + assert(!stream || (c.kc % 4 == 0 && c.kc * c.rounds <= MAX_QUEUE_REPEAT)); + assert((uint64_t)16 * c.kc * X_BLOCK_WORDS <= (1u << 20)); // x round stride, in words + assert(c.ldy % 2 == 0 && c.ldy >= BLOCK_COLS * c.nb); + assert((uint64_t)128 * c.ldy <= (1u << 20)); // y round stride, in words + const uint32_t R = c.rounds, KC = c.kc; + const bool two_panels = !stream && KC <= KC_DOUBLE, hybrid = hybrids(c); + const uint32_t panel_words = KC * W_CHUNK_WORDS; + // ring slots divide the chunks of one N block, so a slot sequence restarted per task lands on + // the same addresses as one carried over + const uint32_t slots = (KC * R) % 8 == 0 ? 8 : 4; + + seq->clear_cmds(); + for (int row = 2; row < 6; row++) + for (uint32_t col = 0; col < COLUMNS; col++) { + const npu_tiles t = get_tile(row, col); + seq->rtp_write(t, CT_RTP_ADDR, KC); + seq->rtp_write(t, CT_RTP_ADDR + 4, R * c.nb); + seq->rtp_write(t, CT_RTP_ADDR + 8, c.act); + } + + // memtile weight path. Panel b: S2MM0 fills it once per N block, then MM2S0 (lo halves) and MM2S1 + // (hi halves) send it R times each (start-queue repeats; the descriptor's locks run on every repeat). + // The fill takes 2R producer credits and gives 2R consumer credits; each repeat of either channel takes + // one consumer credit and returns one producer credit. A channel's task has exactly R repeats, so + // neither channel can use the other's credits. + // Stream mode: S2MM0 fills one slot per chunk (takes a free slot, gives "lo ready"), MM2S0 sends its + // lo half (gives "hi ready"), MM2S1 its hi half (frees the slot). One descriptor per channel, its + // iteration walks the ring, the start-queue repeat runs it once per chunk. + // Hybrid mode (two panels): S2MM0 fills the panel chunk by chunk (gives "lo ready"); round 1 sends each + // chunk as it lands (MM2S0: takes "lo ready", gives "hi ready"; MM2S1 takes "hi ready"), rounds 2..R + // send the resident panel without locks. No lock guards the refill: the host has waited for y of + // N block j - 2, the panel's previous user, before it pushes block j. + auto bd_word = [](uint32_t bd, uint32_t w) { return MT_BD_BASE + MT_BD_STRIDE * bd + 4 * w; }; + for (uint32_t col = 0; col < COLUMNS; col++) { + const npu_tiles mt = get_tile(1, col); + if (stream) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_RING_FREE, slots); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_RING_LO, 0); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_RING_HI, 0); + const uint32_t base = MT_OWN_WORDS + MT_PANEL_ADDR[0] / 4, it = mt_iter(slots, W_CHUNK_WORDS); + const uint32_t fill[8] = {W_CHUNK_WORDS, base, 0, 0, 0, 0, it, mt_lock_word(MT_RING_FREE, 1, MT_RING_LO, 1)}; + const uint32_t lo[8] = {W_HALF_WORDS, base, 0, 0, 0, 0, it, mt_lock_word(MT_RING_LO, 1, MT_RING_HI, 1)}; + const uint32_t hi[8] = {W_HALF_WORDS, base + W_HALF_WORDS, 0, 0, 0, 0, it, mt_lock_word(MT_RING_HI, 1, MT_RING_FREE, 1)}; + for (uint32_t w = 0; w < 8; w++) { + seq->rtp_write(mt, bd_word(MT_S2MM0_BD[0], w), fill[w]); + seq->rtp_write(mt, bd_word(MT_LO_BD[0], w), lo[w]); + seq->rtp_write(mt, bd_word(MT_HI_BD[0], w), hi[w]); + } + continue; + } + if (hybrid) { + for (uint32_t b = 0; b < 2; b++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_CHUNK_LO[b], 0); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_CHUNK_HI[b], 0); + const uint32_t base = MT_OWN_WORDS + MT_PANEL_ADDR[b] / 4, it = mt_iter(KC, W_CHUNK_WORDS); + const uint32_t fill[8] = {W_CHUNK_WORDS, base, 0, 0, 0, 0, it, mt_release_word(MT_CHUNK_LO[b], 1)}; + const uint32_t lo[8] = {W_HALF_WORDS, base, 0, 0, 0, 0, it, mt_lock_word(MT_CHUNK_LO[b], 1, MT_CHUNK_HI[b], 1)}; + const uint32_t hi[8] = {W_HALF_WORDS, base + W_HALF_WORDS, 0, 0, 0, 0, it, mt_acquire_word(MT_CHUNK_HI[b], 1)}; + for (uint32_t w = 0; w < 8; w++) { + seq->rtp_write(mt, bd_word(MT_S2MM0_BD[b], w), fill[w]); + seq->rtp_write(mt, bd_word(MT_LO_BD[b], w), lo[w]); + seq->rtp_write(mt, bd_word(MT_HI_BD[b], w), hi[w]); + } + for (uint32_t h = 0; h < 2 && R > 1; h++) { + const uint32_t send[8] = {KC * W_HALF_WORDS, base + h * W_HALF_WORDS, + mt_dim(584, 1), mt_dim(4, 584), mt_dim(KC, W_CHUNK_WORDS), 0, 0, 1u << 31}; + const uint32_t bd = h ? MT_HI_PANEL_BD[b] : MT_LO_PANEL_BD[b]; + for (uint32_t w = 0; w < 8; w++) seq->rtp_write(mt, bd_word(bd, w), send[w]); + } + } + continue; + } + for (uint32_t b = 0; b < (two_panels ? 2u : 1u); b++) { + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_PANEL_PROD[b], 2 * R); + seq->rtp_write(mt, MT_LOCK_BASE + MT_LOCK_STRIDE * MT_PANEL_CONS[b], 0); + const uint32_t base = MT_OWN_WORDS + MT_PANEL_ADDR[b] / 4; + const uint32_t fill[8] = {panel_words, base, 0, 0, 0, 0, 0, + mt_lock_word(MT_PANEL_PROD[b], 2 * (int)R, MT_PANEL_CONS[b], 2 * (int)R)}; + for (uint32_t w = 0; w < 8; w++) seq->rtp_write(mt, bd_word(MT_S2MM0_BD[b], w), fill[w]); + for (uint32_t h = 0; h < 2; h++) { + // [kc][lo | hi] -> one half of every chunk: 584 x 4 contiguous words, then the next chunk + const uint32_t send[8] = {KC * W_HALF_WORDS, base + h * W_HALF_WORDS, + mt_dim(584, 1), mt_dim(4, 584), mt_dim(KC, W_CHUNK_WORDS), 0, 0, + mt_lock_word(MT_PANEL_CONS[b], 1, MT_PANEL_PROD[b], 1)}; + const uint32_t bd = h ? MT_HI_BD[b] : MT_LO_BD[b]; + for (uint32_t w = 0; w < 8; w++) seq->rtp_write(mt, bd_word(bd, w), send[w]); + } + } + } + + for (uint32_t j = 0; j < c.nb; j++) { + const uint32_t b = two_panels ? (j & 1) : 0; + const uint32_t o = (j & 1) * 4; + const uint32_t fills = stream ? KC * R : hybrid ? KC : 1, sends = stream ? KC * R : hybrid ? KC : R; + for (uint32_t col = 0; col < COLUMNS; col++) { + const npu_tiles mt = get_tile(1, col); + seq->rtp_write(mt, MT_S2MM0_QUEUE, ((fills - 1) << 16) | MT_S2MM0_BD[b]); + seq->rtp_write(mt, MT_MM2S0_QUEUE, ((sends - 1) << 16) | MT_LO_BD[b]); + seq->rtp_write(mt, MT_MM2S1_QUEUE, ((sends - 1) << 16) | MT_HI_BD[b]); + if (hybrid && R > 1) { + seq->rtp_write(mt, MT_MM2S0_QUEUE, ((R - 2) << 16) | MT_LO_PANEL_BD[b]); + seq->rtp_write(mt, MT_MM2S1_QUEUE, ((R - 2) << 16) | MT_HI_PANEL_BD[b]); + } + } + for (uint32_t col = 0; col < COLUMNS; col++) { + // weights: the column's whole panel of this N block (stream mode: once per round) + seq->npu_dma_memcpy_nd(4, 2, MM2S, IT[col], npu_bd_id(0 + o), it_channel_0, + {0, 0, 0, (uint32_t)(c.w_words + ((size_t)j * COLUMNS + col) * panel_words)}, + {stream ? R : 1, 1, 1, panel_words}, {0, 0, 0, 1}, -1, 0, false, aggressive_cache); + // y: R rounds of 256 rows x the column's 128 columns + seq->npu_dma_memcpy_nd(4, 0, S2MM, IT[col], npu_bd_id(2 + o), it_channel_0, + {0, 0, 0, (uint32_t)((c.y_elems + (size_t)j * BLOCK_COLS + 128 * col) / 2)}, + {R, 1, ROUND_ROWS, 64}, {128 * c.ldy, 0, c.ldy / 2, 1}, -1, 0, true); + } + for (uint32_t r = 0; r < CORE_ROWS; r++) { + // x of core row r: per round, per kc, its 4 strips (16-row blocks 16 t + 4 r + s) + seq->npu_dma_memcpy_nd(4, 1, MM2S, IT[r], npu_bd_id(1 + o), it_channel_1, + {0, 0, 0, (uint32_t)(c.x_words + (size_t)4 * r * KC * X_BLOCK_WORDS)}, + {R, KC, 4, X_BLOCK_WORDS}, {16 * KC * X_BLOCK_WORDS, X_BLOCK_WORDS, KC * X_BLOCK_WORDS, 1}, + -1, 0, false, c.x_cache); + } + if (j > 0) + for (uint32_t col = 0; col < COLUMNS; col++) seq->npu_dma_wait(IT[col], S2MM, it_channel_0); + } + for (uint32_t col = 0; col < COLUMNS; col++) seq->npu_dma_wait(IT[col], S2MM, it_channel_0); + seq->cmds2seq(); +} + +} // namespace bfp16_gemm + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/gemm_aie.py b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/gemm_aie.py new file mode 100644 index 000000000..473d7ce21 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/gemm_aie.py @@ -0,0 +1,84 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +"""bfp16 x bfp16 GEMM with fp32 accumulation, bias and optional GELU, bf16 out (32 cores). + +Y[M, N] = act(X[M, K] W[N, K]^T + b). X and W arrive pre-packed as bfp16 (bfp16ebs8, 9 B per 8 k). +The array works on rounds of 256 rows x 1024 columns: column c owns 128 columns, core row r owns 64 rows. +The two cores of a vertical pair (rows 2/3 and 4/5) hold the two 64-column halves (lo in the even core, +hi in the odd core) of the current 128 k chunk of their column's weights and both read both halves. + + weights shim c MM2S0 -> memtile c S2MM0 (a whole N block panel, resident while all rows stream past) + memtile c MM2S0 (lo) -> cores (2, c), (4, c) S2MM1; MM2S1 (hi) -> cores (3, c), (5, c) S2MM1 + The memtile weight path (buffer descriptors, locks, repeat counts) is programmed by the host + sequence for each call; the design only reserves the buffers, locks and routes. + x shim r MM2S1 -> the 8 cores of core row 2 + r, S2MM0 (16 rows x 128 k per buffer) + y core (2 + r, c) MM2S0 -> memtile c S2MM(1 + r) -> memtile c MM2S2 -> shim c S2MM0 + +See host/seq_gen.hpp for the DDR layouts and the run-time part. +""" + +import numpy as np +import sys + +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +import aie.dialects.aie as aie + +from utils import connect_dma, generate_tile_map, mlir_context +from gemm_tile import gemm_memtile, gemm_pair + + +def flow_arch(): + total_cols = 8 + total_rows = 4 + + with mlir_mod_ctx() as ctx: + @aie.device(aie.AIEDevice.npu2) + def device_body(): + IT, MT, CT = generate_tile_map(total_rows + 2, total_cols) + + mctx = mlir_context() + mctx.data_ty('acc_ty', (8192,), np.dtype[np.float32]) # 64 rows x 128 columns fp32, bf16 y in place + mctx.data_ty('x_ty', (2304,), np.dtype[np.uint8]) # 16 rows x 128 k bfp16 + mctx.data_ty('w_ty', (9344,), np.dtype[np.uint8]) # 64 columns x 128 k bfp16 + 64 bf16 bias + mctx.data_ty('rtp_ty', (16,), np.dtype[np.int32]) + mctx.data_ty('y_mem_ty', (32768,), np.dtype[bfloat16]) # 4 core rows x 64 rows x 128 columns + mctx.data_ty('panel_ty', (57344,), np.dtype[np.int32]) # 224 KB weight panel + + args = [mctx.acc_ty, mctx.x_ty, mctx.x_ty, mctx.w_ty, mctx.w_ty, mctx.w_ty, mctx.w_ty, mctx.rtp_ty] + mctx.func("gemm_e", args) + mctx.func("gemm_o", args) + + for i in range(total_rows): + for j in range(total_cols): + t = CT[i][j] + mctx.buffer(f"rtp_{t.row}_{t.col}", t, mctx.rtp_ty, use_write_rtp=True) + + for j in range(total_cols): + for i in range(total_rows // 2): + gemm_pair(CT[2 * i][j], CT[2 * i + 1][j], mctx) + gemm_memtile(MT[j], mctx) + + for j in range(total_cols): + # weights + connect_dma(IT[j], MT[j], 0, 0) + connect_dma(MT[j], CT[0][j], 0, 1) + connect_dma(MT[j], CT[2][j], 0, 1) + connect_dma(MT[j], CT[1][j], 1, 1) + connect_dma(MT[j], CT[3][j], 1, 1) + # y + for i in range(total_rows): + connect_dma(CT[i][j], MT[j], 0, 1 + i) + connect_dma(MT[j], IT[j], 2, 0) + + # x: one shim per core row, broadcast along the row + for i in range(total_rows): + for j in range(total_cols): + connect_dma(IT[i], CT[i][j], 1, 0) + + print(ctx.module) + + +if __name__ == "__main__": + flow_arch() diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/gemm_tile.py b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/gemm_tile.py new file mode 100644 index 000000000..f06fbcbad --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/gemm_tile.py @@ -0,0 +1,154 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +from aie.ir import IntegerAttr, IntegerType + +from aie.dialects.aie import * +from aie.dialects.aiex import * +try: # mlir-aie as pinned by CI + from aie.helpers.dialects.ext.scf import _for as range_ +except ImportError: # newer mlir-aie moved it + from aie.helpers.dialects.scf import _for as range_ +from utils import core_link_kwargs, dma_bd_compat, mlir_context, tile_with_location, lock_acquire, lock_release + +# Core memory layout (both cores of a pair; the kernel's statics follow the RTP). Keep in sync with +# kernel/gemm.h (lock ids) and host/seq_gen.hpp (RTP address). +ACC_ADDR = 2048 # 32 KB fp32 accumulators, bf16 y written in place +X_ADDR = (34816, 37120) # 2304 B each +W_ADDR = (39424, 48768) # 9344 B each +RTP_ADDR = 58112 # 16 x int32 + +# core locks +W_PROD = (0, 2) # 2 credits: both cores of the pair read every weight buffer +W_CONS = (1, 3) +X_PROD, X_CONS = 4, 5 +Y_PROD, Y_CONS = 6, 7 + +# memtile layout and locks; the host sequence programs the weight path on these +MT_Y_ADDR = 0 +MT_PANEL_ADDR = (65536, 294912) +MT_Y_PROD = (0, 1, 2, 3) # per core row, 4 strip credits +MT_Y_CONS = (4, 5, 6, 7) +MT_PANEL_LOCKS = (8, 9, 10, 11) # panel 0 / 1 producer, panel 0 / 1 consumer (host-initialized) + + +def _core(ct: tile_with_location, mctx: mlir_context): + tile = ct.tile + i32 = IntegerType.get_signless(32) + + def pinned(ty, name, address): + return aie.buffer(tile=tile, datatype=ty, name=f"{name}_{ct.row}_{ct.col}", address=address) + acc = pinned(mctx.acc_ty, "acc", ACC_ADDR) + x = [pinned(mctx.x_ty, f"x{i}", X_ADDR[i]) for i in range(2)] + w = [pinned(mctx.w_ty, f"w{i}", W_ADDR[i]) for i in range(2)] + rtp = mctx.buffers[f"rtp_{ct.row}_{ct.col}"] + rtp.owner.attributes["address"] = IntegerAttr.get(i32, RTP_ADDR) + + w_prod = [aie.lock(tile, lock_id=W_PROD[i], init=2) for i in range(2)] + w_cons = [aie.lock(tile, lock_id=W_CONS[i], init=0) for i in range(2)] + x_prod = aie.lock(tile, lock_id=X_PROD, init=2) + x_cons = aie.lock(tile, lock_id=X_CONS, init=0) + y_prod = aie.lock(tile, lock_id=Y_PROD, init=4) + y_cons = aie.lock(tile, lock_id=Y_CONS, init=0) + return acc, x, w, rtp, (w_prod, w_cons, x_prod, x_cons, y_prod, y_cons) + + +def _core_dma(ct: tile_with_location, acc, x, w, locks): + w_prod, w_cons, x_prod, x_cons, y_prod, y_cons = locks + + @aie.mem(ct.tile) + def mem_body(block): + aie.dma_start(channel_dir=aie.DMAChannelDir.S2MM, channel_index=0, dest=block[1], chain=block[3]) + for i in range(2): + with block[1 + i]: + lock_acquire(x_prod, 1) + dma_bd_compat(x[i]) + lock_release(x_cons, 1) + aie.next_bd(block[2 - i]) + + with block[3]: + aie.dma_start(channel_dir=aie.DMAChannelDir.S2MM, channel_index=1, dest=block[4], chain=block[6]) + for i in range(2): + with block[4 + i]: + lock_acquire(w_prod[i], 2) + dma_bd_compat(w[i]) + lock_release(w_cons[i], 2) + aie.next_bd(block[5 - i]) + + # y: one 16-row strip per descriptor, the kernel leaves it as eight 16 x 16 bf16 blocks at + # 512 B steps from the strip start; sent as 16 rows of 128 columns + with block[6]: + aie.dma_start(channel_dir=aie.DMAChannelDir.MM2S, channel_index=0, dest=block[7], chain=block[11]) + for s in range(4): + with block[7 + s]: + lock_acquire(y_cons, 1) + dma_bd_compat(acc, offset=2048 * s, len=1024, dimensions=[(16, 8), (8, 128), (8, 1)]) + lock_release(y_prod, 1) + aie.next_bd(block[7 + (s + 1) % 4]) + + with block[11]: + aie.EndOp() + + +def gemm_pair(tile_e: tile_with_location, tile_o: tile_with_location, mctx: mlir_context): + """A vertical pair: the even core holds the lo weight halves, the odd core the hi halves.""" + acc_e, x_e, w_e, rtp_e, locks_e = _core(tile_e, mctx) + acc_o, x_o, w_o, rtp_o, locks_o = _core(tile_o, mctx) + + @aie.core(tile_e.tile, stack_size=2048, **core_link_kwargs("gemm_e.o")) + def core_e(): + for _ in range_(0xFFFFFFFF): + mctx.gemm_e(acc_e, x_e[0], x_e[1], w_e[0], w_e[1], w_o[0], w_o[1], rtp_e) + + @aie.core(tile_o.tile, stack_size=2048, **core_link_kwargs("gemm_o.o")) + def core_o(): + for _ in range_(0xFFFFFFFF): + mctx.gemm_o(acc_o, x_o[0], x_o[1], w_e[0], w_e[1], w_o[0], w_o[1], rtp_o) + + _core_dma(tile_e, acc_e, x_e, w_e, locks_e) + _core_dma(tile_o, acc_o, x_o, w_o, locks_o) + + +def gemm_memtile(tile: tile_with_location, mctx: mlir_context): + mt = tile.tile + y = aie.buffer(tile=mt, datatype=mctx.y_mem_ty, name=f"y_{tile.row}_{tile.col}", address=MT_Y_ADDR) + for i in range(2): + aie.buffer(tile=mt, datatype=mctx.panel_ty, name=f"p{i}_{tile.row}_{tile.col}", address=MT_PANEL_ADDR[i]) + y_prod = [aie.lock(mt, lock_id=MT_Y_PROD[r], init=4) for r in range(4)] + y_cons = [aie.lock(mt, lock_id=MT_Y_CONS[r], init=0) for r in range(4)] + for lid in MT_PANEL_LOCKS: + aie.lock(mt, lock_id=lid, init=0) + + @aie.memtile_dma(mt) + def memtile_dma_body(block): + # each channel's dma_start sits in the chain block of the previous one + def start(chain_from, direction, ch, first): + if chain_from is None: + aie.dma_start(channel_dir=direction, channel_index=ch, dest=block[first], chain=block[first + 4]) + else: + with block[chain_from]: + aie.dma_start(channel_dir=direction, channel_index=ch, dest=block[first], chain=block[first + 4]) + return first + 4 + + # y in: core row r on S2MM 1 + r, one 4 KB strip per descriptor into its 16 KB row block + chain, first = None, 1 + for r in range(4): + chain = start(chain, aie.DMAChannelDir.S2MM, 1 + r, first) + for s in range(4): + with block[first + s]: + lock_acquire(y_prod[r], 1) + dma_bd_compat(y, offset=8192 * r + 2048 * s, len=2048) + lock_release(y_cons[r], 1) + aie.next_bd(block[first + (s + 1) % 4]) + first = chain + 1 + # y out: the 4 row blocks of a round in row order, 64 rows x 128 columns each + chain = start(chain, aie.DMAChannelDir.MM2S, 2, first) + for r in range(4): + with block[first + r]: + lock_acquire(y_cons[r], 4) + dma_bd_compat(y, offset=8192 * r, len=8192) + lock_release(y_prod[r], 4) + aie.next_bd(block[first + (r + 1) % 4]) + with block[chain]: + aie.EndOp() diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/utils.py b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/utils.py new file mode 100644 index 000000000..3c276fb1a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/iron/utils.py @@ -0,0 +1,185 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import os as _os +# Mirrors the makefiles' ENABLE_CHESSCC switch, so the generated MLIR can carry +# Peano-only layout changes. +ENABLE_CHESSCC = _os.environ.get("ENABLE_CHESSCC", "0") == "1" +if ENABLE_CHESSCC: + raise SystemExit("bfp16_gemm is Peano only (the bfp16 block-vector streams and the pinned layout are not built with Chess)") + +from dataclasses import dataclass +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +try: # mlir-aie as pinned by CI + from aie.helpers.dialects.ext.scf import _for as range_ +except ImportError: # newer mlir-aie moved it + from aie.helpers.dialects.scf import _for as range_ +import inspect +from aie.dialects import memref +from typing import Dict, Any, List, Optional +from aie.extras import types as T + +@dataclass +class tile_with_location: + tile: tile + row: int + col: int + +@dataclass +class dma_port: + tile: tile_with_location + channel: int + +# The mlir-aie API moved between the CI toolchain and newer ones; the design builds with both. +# newer: link_with lives on external_func and dma_bd takes sizes/strides/transfer_len; +# CI: link_with lives on the core and dma_bd takes dimensions/len. +NEW_LINK_API = "link_with" in inspect.signature(aie.external_func.__init__).parameters +NEW_DMA_BD_API = "transfer_len" in inspect.signature(aie.dma_bd).parameters + + +def core_link_kwargs(obj_name: str): + """kwargs for @aie.core that link the kernel object (empty on the newer API, where the + external_func declaration carries it).""" + return {} if NEW_LINK_API else {"link_with": obj_name} + + +class mlir_context: + def __init__(self): + self.data_tys = {} + self.funcs = {} + self.buffers = {} + self.parameters = {} + self.object_fifos = {} + self.packet_ids = {} + + def data_ty(self, name: str, shape: List[int], dtype: Any): + d_ty = np.ndarray[shape, dtype] + self.data_tys[name] = d_ty + if not hasattr(self, name): + setattr(self, name, d_ty) + else: + raise ValueError(f"Data type {name} already exists") + return d_ty + + def buffer(self, name: str, tile: tile_with_location, dtype: Any, use_write_rtp: bool = False): + new_buffer = aie.buffer(tile.tile, dtype, name = name, use_write_rtp = use_write_rtp) + self.buffers[name] = new_buffer + if not hasattr(self, name): + setattr(self, name, new_buffer) + else: + raise ValueError(f"Buffer {name} already exists") + + return new_buffer + + def func(self, name: str, inputs: List[Any]): + if NEW_LINK_API: + this_func = aie.external_func(name, inputs, link_with=f"{name}.o") + else: + this_func = aie.external_func(name, inputs) + self.funcs[name] = this_func + if not hasattr(self, name): + setattr(self, name, this_func) + else: + raise ValueError(f"Function {name} already exists") + return this_func + + def parameter(self, name: str, value: Any): + self.parameters[name] = value + if not hasattr(self, name): + setattr(self, name, value) + else: + raise ValueError(f"Parameter {name} already exists") + return value + + def object_fifo(self, name: str, src_tile: tile_with_location, dst_tile: tile_with_location | List[tile_with_location], depth: int, data_ty: Any, *args, **kwargs): + if isinstance(dst_tile, tile_with_location): + fifo = object_fifo(name, src_tile.tile, dst_tile.tile, depth, data_ty, *args, **kwargs) + else: + fifo = object_fifo(name, src_tile.tile, [t.tile for t in dst_tile], depth, data_ty, *args, **kwargs) + self.object_fifos[name] = fifo + if not hasattr(self, name): + setattr(self, name, fifo) + else: + raise ValueError(f"Object fifo {name} already exists") + return fifo + + + +def dma_mm2s_ch(ch: int): + return { + "source_port": WireBundle.DMA, + "source_channel": ch + } + +def dma_s2mm_ch(ch: int): + return { + "dest_port": WireBundle.DMA, + "dest_channel": ch + } + +def flow_mm2s_ch(ch: int): + return { + "source_bundle": WireBundle.DMA, + "source_channel": ch + } + +def flow_s2mm_ch(ch: int): + return { + "dest_bundle": WireBundle.DMA, + "dest_channel": ch + } + +def generate_tile_map(total_rows: int, total_cols: int) -> Tuple[List[tile_with_location], List[tile_with_location], List[List[tile_with_location]]]: + # Tile declarations + ShimTiles = [] + MemTiles = [] + cores = [] + for col in range(total_cols): + ShimTiles.append(tile_with_location(tile(col, 0), 0, col)) + MemTiles.append(tile_with_location(tile(col, 1), 0, col)) + + for row in range(total_rows - 2): + ComputeTilesRow = [] + for col in range(total_cols): + ComputeTilesRow.append(tile_with_location(tile(col, row + 2), row + 2, col)) + + cores.append(ComputeTilesRow) + + return ShimTiles, MemTiles, cores + +def connect_dma(src: tile_with_location, dst: tile_with_location, src_ch: int, dst_ch: int, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src_ch), dest = dst.tile, **flow_s2mm_ch(dst_ch)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src_ch), dest = dst.tile, **dma_s2mm_ch(dst_ch), keep_pkt_header = keep_pkt_header) + +def connect_port(src: dma_port, dst: dma_port, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src.channel), dest = dst.tile, **flow_s2mm_ch(dst.channel)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src.channel), dest = dst.tile, **dma_s2mm_ch(dst.channel), keep_pkt_header = keep_pkt_header) + + +def lock_acquire(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.AcquireGreaterEqual, value = value) + +def lock_release(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.Release, value = value) + + +def dma_bd_compat(buffer, offset=None, len=None, dimensions=None): + """aie.dma_bd(buffer, offset=, len=, dimensions=[(size, stride), ...]) on either API.""" + if not NEW_DMA_BD_API: + kw = {} + if offset is not None: kw["offset"] = offset + if len is not None: kw["len"] = len + if dimensions: kw["dimensions"] = dimensions + return aie.dma_bd(buffer, **kw) + kw = {} + if dimensions: + kw["sizes"] = [d[0] for d in dimensions] + kw["strides"] = [d[1] for d in dimensions] + return aie.dma_bd(buffer, offset=offset, transfer_len=len, **kw) diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/aie_kernel_utils.h b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/aie_kernel_utils.h new file mode 100644 index 000000000..c5314aa0b --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/aie_kernel_utils.h @@ -0,0 +1,186 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +// SPDX-License-Identifier: MIT + +#ifndef _AIE_KERNEL_UTILS_ +#define _AIE_KERNEL_UTILS_ + +#include +typedef bfloat16 bf16; + +#if defined(__chess__) +#define AIE_LOOP_UNROLL(x) [[chess::unroll_loop(x)]] +#define AIE_LOOP_UNROLL_FULL [[chess::unroll_loop()]] +#define AIE_LOOP_NO_UNROLL [[chess::no_unroll]] +#define AIE_LOOP_MIN_ITERATION_COUNT(x) [[chess::min_loop_count(x)]] +#define AIE_LOOP_MAX_ITERATION_COUNT(x) [[chess::max_loop_count(x)]] +#define AIE_LOOP_RANGE(a, ...) \ + [[chess::min_loop_count(a)]] __VA_OPT__( \ + [[chess::max_loop_count(__VA_ARGS__)]]) +#define AIE_PREPARE_FOR_PIPELINING [[chess::prepare_for_pipelining]] +#define AIE_NO_PREPARE_FOR_PIPELINING [[chess::no_prepare_for_pipelining]] +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) \ + [[chess::modulo_scheduling_budget_ratio(x)]] +#define AIE_KEEP_SW_LOOP [[chess::keep_sw_loop]] +#define AIE_PEEL_PIPELINED_LOOP(x) [[chess::peel_pipelined_loop(x)]] +#define AIE_KEEP_FREE_FOR_PIPELINING(x) [[chess::keep_free_for_pipelining(x)]] +#define AIE_ALLOCATE(x) [[chess::allocate(x)]] +#define AIE_NO_HW_LOOP [[chess::no_hw_loop]] +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN chess_flatten_loop + +#elif defined(__AIECC__) +#ifndef __STRINGIFY +#define __STRINGIFY(a) #a +#endif +#define AIE_LOOP_UNROLL(x) _Pragma(__STRINGIFY(clang loop unroll_count(x))) +#define AIE_LOOP_UNROLL_FULL _Pragma("clang loop unroll(full)") +#define AIE_LOOP_NO_UNROLL _Pragma("clang loop unroll(disable)") +#define AIE_LOOP_MIN_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop min_iteration_count(x))) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop max_iteration_count(x))) +#define AIE_LOOP_RANGE(a, ...) \ + AIE_LOOP_MIN_ITERATION_COUNT(a) \ + __VA_OPT__(AIE_LOOP_MAX_ITERATION_COUNT(__VA_ARGS__)) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) \ + _Pragma(__STRINGIFY(clang loop pipeline_initiation_interval(x))) +#define AIE_PREPARE_FOR_POSTPIPELINING _Pragma("clang loop pipeline(disable)") +#define AIE_LOOP_FLATTEN + +#else +#define AIE_LOOP_UNROLL(x) +#define AIE_LOOP_UNROLL_FULL +#define AIE_LOOP_NO_UNROLL +#define AIE_LOOP_MIN_ITERATION_COUNT(x) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) +#define AIE_LOOP_RANGE(a, ...) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN +#endif + +// Some lock utilities +/// \brief Acquire a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 48, num_locks); +} + +/// \brief Release a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 48, num_locks); +} + + +/// \brief Acquire a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _left_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 16, num_locks); +} + +/// \brief Release a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _left_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 16, num_locks); +} + +/// \brief Acquire a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _up_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 32, num_locks); +} + +/// \brief Release a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _up_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 32, num_locks); +} + +/// \brief Acquire a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _down_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id, num_locks); +} + +/// \brief Release a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _down_lock_release(int lock_id, int num_locks = 1){ + release(lock_id, num_locks); +} + +template +void zero_vectorized(T *__restrict c) { + constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit + static_assert((M) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M; + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } +} + +template +void _memcpy(uint8* dst, uint8* src){ + static constexpr int vec_size = 256; + for (int i = 0; i < SIZE; i += vec_size){ + aie::vector data = aie::load_v(src + i); + aie::store_v(dst + i, data); + } +} + +// Ping/pong buffer selectors. Peano's loader does not zero .bss, so under Peano +// they live in .data. They are volatile there too: Peano does not treat a lock +// acquire as a memory barrier, so if it can prove two picks give the same buffer +// it reuses the earlier load, even though the DMA has refilled the buffer in between. +#if defined(__chess__) +#define AIE_PING_FLAG bool +#else +#define AIE_PING_FLAG __attribute__((section(".data"))) volatile bool +#endif + +// bf16 8x8x8 mmul with the BFP16 emulation, for Peano. It issues the same +// intrinsic as aie_api's emulated mac but converts B with the accumulator +// constructor rather than a multiply by one, which would take a multiplier slot +// from the macs. The conversion is exact, so results are unchanged. +#if !defined(__chess__) && defined(AIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16) +#include +struct aie_mmul_bf16_888 { + aie::accum acc; + explicit aie_mmul_bf16_888(const aie::vector &c) { acc.from_vector(c); } + __attribute__((always_inline)) void mac(const aie::vector &a, const aie::vector &b) { + aie::accum acc_a(a); + aie::accum acc_b(aie::transpose(b, 8, 8)); + acc = ::mac_8x8_8x8T_conf(::to_v64bfp16ebs8(acc_a), ::to_v64bfp16ebs8(acc_b), acc, 0, 0, 0); + } + template aie::vector to_vector() const { return acc.template to_vector(); } +}; +#endif + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm.h b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm.h new file mode 100644 index 000000000..9c60ff427 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm.h @@ -0,0 +1,157 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +// bfp16 GEMM core: 64 rows x 128 columns of one round, k in chunks of 128 (see iron/gemm_aie.py). +// Include with GEMM_EVEN 1 (the pair's lower core, holds the lo weight halves) or 0 (upper core, hi halves). +#pragma once +#include "aie_kernel_utils.h" +#include "lut_based_ops.h" + +using MMUL = aie::mmul<8, 8, 8, bfp16ebs8, bfp16ebs8, accauto>; + +// core locks, as in iron/gemm_tile.py +constexpr int W_PROD0 = 0, W_CONS0 = 1, W_PROD1 = 2, W_CONS1 = 3; +constexpr int X_PROD = 4, X_CONS = 5, Y_PROD = 6, Y_CONS = 7; + +constexpr unsigned KT = 16; // 8-k tiles per 128 k chunk +constexpr unsigned UNR = 2, II = 8; +constexpr int W_TILES_BYTES = 9216; // 64 columns x 128 k; the 64 bf16 biases of those columns follow +constexpr int STRIP_FLOATS = 2048; // 16 rows x 128 columns + +// parity of the next weight buffer; a call may take an odd number of chunks, so it carries over +AIE_PING_FLAG w_pong = false; + +// one 2x2 block of 8x8 tiles over the KT k tiles of a chunk; acc = 4 x 64 floats, contiguous. +// x: [KT][rows 0-7 | rows 8-15] tiles; w: [jp 4][KT][2 column tiles], w_tile0 selects jp. +template +static inline __attribute__((always_inline)) void pass2x2(float *__restrict acc, const bfp16ebs8 *__restrict px, const bfp16ebs8 *__restrict pw, unsigned w_tile0) { + aie::block_vector_input_buffer_stream xs(px); + aie::block_vector_input_buffer_stream ws(pw); + ws.seek(w_tile0); + MMUL Y00, Y01, Y10, Y11; + if constexpr (FIRST) { + Y00 = MMUL(aie::zeros()); Y01 = MMUL(aie::zeros()); + Y10 = MMUL(aie::zeros()); Y11 = MMUL(aie::zeros()); + } else { + Y00 = MMUL(aie::load_v<64>(acc)); + Y01 = MMUL(aie::load_v<64>(acc + 64)); + Y10 = MMUL(aie::load_v<64>(acc + 128)); + Y11 = MMUL(aie::load_v<64>(acc + 192)); + } + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(KT / UNR, KT / UNR) + AIE_TRY_INITIATION_INTERVAL(II) + for (unsigned i = 0; i < KT / UNR; ++i) { +#pragma unroll + for (unsigned u = 0; u < UNR; ++u) { + auto X0 = xs.pop(); auto X1 = xs.pop(); + auto W0 = ws.pop(); auto W1 = ws.pop(); + Y00.mac(X0, aie::op_transpose(W0)); + Y01.mac(X0, aie::op_transpose(W1)); + Y10.mac(X1, aie::op_transpose(W0)); + Y11.mac(X1, aie::op_transpose(W1)); + } + } + aie::store_v(acc, Y00.template to_vector()); + aie::store_v(acc + 64, Y01.template to_vector()); + aie::store_v(acc + 128, Y10.template to_vector()); + aie::store_v(acc + 192, Y11.template to_vector()); +} + +// one 16-row strip against the 128 columns of the chunk: 8 blocks of 16 x 16 (4 lo, 4 hi), 256 floats each +template +static inline void strip_pass(float *__restrict acc, const uint8 *__restrict x, const uint8 *__restrict w_lo, const uint8 *__restrict w_hi) { + for (unsigned jp = 0; jp < 4; jp++) pass2x2(acc + jp * 256, (const bfp16ebs8 *)x, (const bfp16ebs8 *)w_lo, jp * 2 * KT); + for (unsigned jp = 0; jp < 4; jp++) pass2x2(acc + (4 + jp) * 256, (const bfp16ebs8 *)x, (const bfp16ebs8 *)w_hi, jp * 2 * KT); +} + +static inline __attribute__((always_inline)) aie::vector to_bf16(const aie::vector &v) { + aie::accum a; + a.from_vector(v); + return a.to_vector(); +} + +// fp32 strip -> bf16, + bias, optional GELU, written in place as eight row-major 16 x 16 blocks at 512 B steps +// (block p of the strip's floats starts at 1024 p, so every block overwrites only blocks already done) +static inline void strip_epilogue(float *acc, const bfloat16 *bias_lo, const bfloat16 *bias_hi, int act) { + bfloat16 *out = (bfloat16 *)acc; + for (int p = 0; p < 8; p++) { + const aie::vector b16 = aie::load_v<16>((p < 4 ? bias_lo : bias_hi) + 16 * (p & 3)); + const aie::vector b0 = b16.extract<8>(0), b1 = b16.extract<8>(1); + // tile element (m, n) sits at 8 m + n, so the 8 column biases repeat 8 times + const aie::vector bias0 = aie::accum(aie::concat(b0, b0, b0, b0, b0, b0, b0, b0)).to_vector(); + const aie::vector bias1 = aie::accum(aie::concat(b1, b1, b1, b1, b1, b1, b1, b1)).to_vector(); + const float *src = acc + 256 * p; + aie::vector v00 = to_bf16(aie::add(aie::load_v<64>(src), bias0)); + aie::vector v01 = to_bf16(aie::add(aie::load_v<64>(src + 64), bias1)); + aie::vector v10 = to_bf16(aie::add(aie::load_v<64>(src + 128), bias0)); + aie::vector v11 = to_bf16(aie::add(aie::load_v<64>(src + 192), bias1)); + if (act == 1) { + v00 = getGeluBf16_nonLUT<64>(v00); v01 = getGeluBf16_nonLUT<64>(v01); + v10 = getGeluBf16_nonLUT<64>(v10); v11 = getGeluBf16_nonLUT<64>(v11); + } + // rows 0-7: [y00 row | y01 row], rows 8-15: [y10 row | y11 row] + const auto [z0, z1] = aie::interleave_zip(v00, v01, 8); + const auto [z2, z3] = aie::interleave_zip(v10, v11, 8); + bfloat16 *o = out + 256 * p; + aie::store_v(o, z0); + aie::store_v(o + 64, z1); + aie::store_v(o + 128, z2); + aie::store_v(o + 192, z3); + } +} + +// weight buffer b of both halves: the lo half lives in the even core, the hi half in the odd core +static inline __attribute__((always_inline)) void w_acquire(bool b) { +#if GEMM_EVEN + if (b) { _lock_acquire(W_CONS1); _up_lock_acquire(W_CONS1); } else { _lock_acquire(W_CONS0); _up_lock_acquire(W_CONS0); } +#else + if (b) { _down_lock_acquire(W_CONS1); _lock_acquire(W_CONS1); } else { _down_lock_acquire(W_CONS0); _lock_acquire(W_CONS0); } +#endif +} + +static inline __attribute__((always_inline)) void w_release(bool b) { +#if GEMM_EVEN + if (b) { _lock_release(W_PROD1); _up_lock_release(W_PROD1); } else { _lock_release(W_PROD0); _up_lock_release(W_PROD0); } +#else + if (b) { _down_lock_release(W_PROD1); _lock_release(W_PROD1); } else { _down_lock_release(W_PROD0); _lock_release(W_PROD0); } +#endif +} + +// RTP: [0] k chunks of 128 (KC), [1] rounds of 256 rows in this call (all N blocks), [2] activation (0 none, 1 GELU) +static inline void gemm_body(float *acc, uint8 *x0, uint8 *x1, uint8 *w_lo0, uint8 *w_lo1, uint8 *w_hi0, uint8 *w_hi1, int *rtp) { + const aie::rounding_mode old_rnd = aie::swap_rounding(aie::rounding_mode::conv_even); + bool b = w_pong; + // the first weight chunk arrives only after the host sequence has written the RTPs + w_acquire(b); + const int kc_n = ((volatile int *)rtp)[0]; + const int rounds = ((volatile int *)rtp)[1]; + const int act = ((volatile int *)rtp)[2]; + for (int t = 0; t < rounds; t++) { + for (int kc = 0; kc < kc_n; kc++) { + if (t != 0 || kc != 0) w_acquire(b); + const uint8 *w_lo = b ? w_lo1 : w_lo0; + const uint8 *w_hi = b ? w_hi1 : w_hi0; + for (int s = 0; s < 4; s++) { + float *a = acc + STRIP_FLOATS * s; + _lock_acquire(X_CONS); + const uint8 *x = (s & 1) ? x1 : x0; + if (kc == 0) { + _lock_acquire(Y_PROD); + strip_pass(a, x, w_lo, w_hi); + } else { + strip_pass(a, x, w_lo, w_hi); + } + _lock_release(X_PROD); + if (kc == kc_n - 1) { + strip_epilogue(a, (const bfloat16 *)(w_lo + W_TILES_BYTES), (const bfloat16 *)(w_hi + W_TILES_BYTES), act); + _lock_release(Y_CONS); + } + } + w_release(b); + b = !b; + } + } + w_pong = b; + aie::set_rounding(old_rnd); +} diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm_e.cc b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm_e.cc new file mode 100644 index 000000000..e2a39d836 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm_e.cc @@ -0,0 +1,11 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#define GEMM_EVEN 1 +#include "gemm.h" + +extern "C" { +void gemm_e(float *acc, uint8 *x0, uint8 *x1, uint8 *w_lo0, uint8 *w_lo1, uint8 *w_hi0, uint8 *w_hi1, int *rtp) { + gemm_body(acc, x0, x1, w_lo0, w_lo1, w_hi0, w_hi1, rtp); +} +} diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm_o.cc b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm_o.cc new file mode 100644 index 000000000..56553c1ad --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/gemm_o.cc @@ -0,0 +1,11 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#define GEMM_EVEN 0 +#include "gemm.h" + +extern "C" { +void gemm_o(float *acc, uint8 *x0, uint8 *x1, uint8 *w_lo0, uint8 *w_lo1, uint8 *w_hi0, uint8 *w_hi1, int *rtp) { + gemm_body(acc, x0, x1, w_lo0, w_lo1, w_hi0, w_hi1, rtp); +} +} diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/lut_based_ops.h b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/lut_based_ops.h new file mode 100644 index 000000000..c01d5603c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/kernel/lut_based_ops.h @@ -0,0 +1,75 @@ +//===--- exp_lut.h - get exponential values from loopup tables ---===// +// +// This file is licensed under the Apache License v2.0 with LLVM Exceptions +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// +// +//===----------------------------------------------------------------------===// +// This is the implementation of getting exponential values for a bfloat16 +// vector from exponential lookup tables. +//===----------------------------------------------------------------------===// +#ifndef __LUT_BASED_OPS_H__ +#define __LUT_BASED_OPS_H__ + +#include "aie_api/aie.hpp" + + +// The tables _ab and _cd are copies of each other +// Also, each table has a copy of data seperated by 256-bit +// This effectively creates 4 copies of the table (located in 4 (256-bit) banks) +// This allows the user to use the "gather" read feature and read 4 values from +// 4 different banks at once Tables entries are in BF16 +// +template +__attribute__((always_inline)) aie::vector getSiluBf16_nonLUT(aie::vector x){ + const bfloat16 half = 0.5f; + const bfloat16 one = 1.0f; + aie::vector v_half = aie::broadcast(half); + aie::vector v_one = aie::broadcast(one); + aie::accum x_mul_half = aie::mul(x, v_half); + aie::vector tanh_x_half = aie::tanh(x_mul_half.template to_vector()); + + aie::vector tanh_x_half_plus_one = aie::add(tanh_x_half, v_one); + aie::vector tanh_x_half_plus_one_div_2 = aie::mul(tanh_x_half_plus_one, v_half).template to_vector(); + + aie::vector res = aie::mul(x, tanh_x_half_plus_one_div_2).template to_vector(); + return res; +} +template +__attribute__((always_inline)) aie::vector getGeluBf16_nonLUT(aie::vector x) { + // Constants + const bfloat16 k0_5 = 0.5f; + const bfloat16 k1 = 1.0f; + const bfloat16 sqrt_2_over_pi = 0.79788456f; // ≈ sqrt(2/π) + const bfloat16 kBeta = 0.044715f; + + auto v05 = aie::broadcast(k0_5); + auto v1 = aie::broadcast(k1); + auto vs2opi = aie::broadcast(sqrt_2_over_pi); + auto vBeta = aie::broadcast(kBeta); + + + // Compute x^3 + aie::vector x2 = aie::mul(x, x).template to_vector(); // x^2 + aie::vector x3 = aie::mul(x, x2).template to_vector(); // x^3 + + // inner = sqrt(2/pi) * (x + 0.044715 * x^3) + aie::vector x3_beta = aie::mul(x3, vBeta).template to_vector(); + aie::vector inner = aie::add(x, x3_beta); + auto inner1 = aie::mul(inner, vs2opi); + + // tanh_out = tanh(inner) + auto tanh_out = aie::tanh(inner1.template to_vector()); + + // result = 0.5 * x * (1 + tanh_out) + aie::vector one_plus_tanh = aie::add(tanh_out, v1); + // Multiply by x and 0.5 + aie::vector mul_v05 = aie::mul(v05, one_plus_tanh).template to_vector(); + auto result = aie::mul(x, mul_v05); + return result.template to_vector(); +} + +#endif //__LUT_BASED_OPS_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/bitstream.mk b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/bitstream.mk new file mode 100755 index 000000000..2932f0796 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/bitstream.mk @@ -0,0 +1,53 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +# MLIR stuff + +MLIR_O_DIR := build/$(MODEL_TYPE)/mlir +BITSTREAM_O_DIR := build/$(MODEL_TYPE)/bitstream + + +IRON_BOTH_SRC := $(wildcard ${HOME_DIR}/iron/*_aie.py) +IRON_OTHER_SRC := $(wildcard ${HOME_DIR}/iron/*.py) +IRON_BOTH_MLIR_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${MLIR_O_DIR}/%.mlir, ${IRON_BOTH_SRC}) +IRON_BOTH_XCLBIN_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.xclbin, ${IRON_BOTH_SRC}) +IRON_BOTH_INSTS_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.txt, ${IRON_BOTH_SRC}) + +.PRECIOUS: ${IRON_BOTH_MLIR_TARGET} + +AIECC_FLAGS := --aie-generate-cdo --no-compile-host +ENABLE_CHESSCC ?= 0 +ifeq ($(ENABLE_CHESSCC),1) +$(error bfp16_gemm is Peano only (pinned layout, bfp16 block-vector streams)) +else +# The core and memtile buffers are pinned (iron/gemm_tile.py), and +# basic-sequential allocation keeps pinned addresses. +AIECC_FLAGS += --no-xchesscc --no-xbridge --alloc-scheme=basic-sequential +endif +# iron generate mlir +${MLIR_O_DIR}/%.mlir: ${HOME_DIR}/iron/%_aie.py ${IRON_OTHER_SRC} + mkdir -p ${@D} + ENABLE_CHESSCC=$(ENABLE_CHESSCC) python3 $< ${IRON_ARGS} > $@ + +# Build xclbin +${BITSTREAM_O_DIR}/from_iron/%.xclbin: ${MLIR_O_DIR}/%.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-xclbin \ + --xclbin-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) + @# the host sequence programs the memtile weight path on descriptors / locks the design leaves free + @python3 ${HOME_DIR}/check_memtile_bds.py ${@D} + mkdir -p build/$(MODEL_TYPE)/xclbins + cp ${@} build/$(MODEL_TYPE)/xclbins/ + @# the test host's seq_gen.hpp CT_RTP_ADDR + cat ${@D}/*/input_with_addresses.mlir | grep "%rtp_" | grep "aie.buffer" | awk '{print $$1, $$6}' | sed 's/%//g' | sort | tee build/$(MODEL_TYPE)/xclbins/rtp_addresses.txt + +${BITSTREAM_O_DIR}/from_iron/%.txt: ${MLIR_O_DIR}/%.mlir + mkdir -p ${@D} + cd ${@D} && aiecc.py -n ${AIECC_FLAGS} --aie-generate-npu-insts \ + --npu-insts-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) + mkdir -p build/$(MODEL_TYPE)/insts + cp ${@} build/$(MODEL_TYPE)/insts/ + +INSTS_TARGETS += ${IRON_BOTH_INSTS_TARGET} +XCLBIN_TARGETS += ${IRON_BOTH_XCLBIN_TARGET} diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/common.mk b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/common.mk new file mode 100755 index 000000000..2d66b1266 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/common.mk @@ -0,0 +1,31 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Created by Alfred + +ifneq ($(filter -j,$(MAKEFLAGS)),) + # Nothing to do; -j is already set +else + MAKEFLAGS += -j8 +endif + +# VITIS related variables (Chess only: ENABLE_CHESSCC=1; Peano builds never expand them) +AIETOOLS_DIR ?= $(or $(AIETOOLS_ROOT),$(patsubst %/bin/,%,$(dir $(shell command -v xchesscc 2>/dev/null)))) +# Expanded only inside the Chess recipes, so it fires only for ENABLE_CHESSCC=1. +AIETOOLS_CHECK = $(if $(strip $(AIETOOLS_DIR)),,$(error ENABLE_CHESSCC=1 needs Vitis AIE Essentials: set AIETOOLS_ROOT (or AIETOOLS_DIR), or put xchesscc on PATH)) +AIE_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/versal_prod/lib +AIE2_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/aie_ml/lib + +AIEOPT_DIR ?= $(shell realpath $(dir $(shell which aie-opt))/..) + +WARNING_FLAGS = -Wno-parentheses -Wno-attributes -Wno-macro-redefined + + +CHESSCCWRAP1_FLAGS = aie $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2_FLAGS = aie2 $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2P_FLAGS = aie2p $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 +PEANOWRAP2_FLAGS = -O2 -v -std=c++20 --target=aie2-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -I ${AIEOPT_DIR}/include +PEANOWRAP2P_FLAGS = -O2 -v -std=c++20 --target=aie2p-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -I ${AIEOPT_DIR}/include diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/host.mk b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/host.mk new file mode 100755 index 000000000..24aa46b0f --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/host.mk @@ -0,0 +1,60 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# ============================================================================= +# Llama NPU Library Makefile +# ============================================================================= +# +# Created: 2024 +# +# This Makefile is used to build the Llama NPU library components. +# +# Usage: +# make - Build all targets +# make clean - Remove all built files +# make help - Show this help message +# +# ============================================================================= + +# Linux build environment +# Use g++-13 directly without CMake + +HOST_C_TARGET := run.exe +HOST_COMMON_DIR := ../host_common +CXX := g++-13 +CXX_FLAGS := -std=c++20 -fPIC -Wall +CXX_FLAGS += -DUSE_AVX2=1 +CXX_FLAGS += -mavx2 -march=native -mfma -ffast-math +# the CPU golden reference (cpu_q4_k.hpp) is a full fp32 matmul; thread it +CXX_FLAGS += -fopenmp +CXX_FLAGS += -Ihost +CXX_FLAGS += -I$(HOST_COMMON_DIR) +CXX_FLAGS += -I/opt/xilinx/xrt/include +CXX_FLAGS += -MMD -MP + +LDFLAGS += -L/opt/xilinx/xrt/lib +LDFLAGS += -L$(HOST_COMMON_DIR) +LDFLAGS += -lxrt_coreutil $(HOST_COMMON_DIR)/../../../src/lib/xrt/libaiebu.a +LDFLAGS += -lboost_program_options -lboost_filesystem +LDFLAGS += -fopenmp + +# Find all source files in host/ directory (including subdirectories) +HOST_SOURCES := $(shell find host -name '*.cpp') +HOST_OBJECTS := $(HOST_SOURCES:%.cpp=build/%.o) +HOST_DEPENDS := $(HOST_OBJECTS:.o=.d) + +# Default target +$(HOST_C_TARGET): build/$(HOST_C_TARGET) + cp build/$(HOST_C_TARGET) ./ + +# Link the executable +build/$(HOST_C_TARGET): $(HOST_OBJECTS) + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) $^ -o $@ $(LDFLAGS) + +# Compile source files and generate dependencies +build/%.o: %.cpp + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) -c $< -o $@ + +# Include dependency files +-include $(HOST_DEPENDS) \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/kernel.mk b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/kernel.mk new file mode 100755 index 000000000..b8d013bbe --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/bfp16_gemm/makefiles/kernel.mk @@ -0,0 +1,25 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Portions of this file consist of AI-generated content. +# Created by Alfred + +# Kernel stuff +KERNEL_O_DIR := build/$(MODEL_TYPE)/kernel +KERNEL_SRCS := $(wildcard ${HOME_DIR}/kernel/*.cc) +KERNEL_OBJS := $(patsubst ${HOME_DIR}/kernel/%.cc, ${KERNEL_O_DIR}/%.o, $(KERNEL_SRCS)) +KERNEL_HEADERS := $(wildcard ${HOME_DIR}/kernel/*.h) + +# Build kernels +ENABLE_CHESSCC ?= 0 + +${KERNEL_O_DIR}/%.o: ${HOME_DIR}/kernel/%.cc ${KERNEL_HEADERS} + mkdir -p ${@D} +ifeq ($(ENABLE_CHESSCC),1) + cd ${@D} && xchesscc_wrapper ${CHESSCCWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} ${EXTRA_KARGS} -c $< -o ${@F} +else + cd ${@D} && ${PEANO_INSTALL_DIR}/bin/clang++ ${PEANOWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} ${EXTRA_KARGS} -c $< -o ${@F} +endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/build_units.json b/flm-dev-kit/FLM_Xclbin/build_units.json index 3522f374b..4d92ecbea 100644 --- a/flm-dev-kit/FLM_Xclbin/build_units.json +++ b/flm-dev-kit/FLM_Xclbin/build_units.json @@ -849,6 +849,12 @@ "xclbins-Whisper_whisper_lm_head_npu_bin" ] }, + "bfp16_gemm": { + "model_types": [], + "artifacts": [ + "xclbins-bfp16_gemm" + ] + }, "conv1d": { "model_types": [], "artifacts": [ @@ -899,12 +905,24 @@ "xclbins-dequant_mm_bfp16_rtm2_glu_512x512x512" ] }, + "dequant_mm_mix_bfp16": { + "model_types": [], + "artifacts": [ + "xclbins-dequant_mm_mix_bfp16" + ] + }, "d3_switches": { "model_types": [], "artifacts": [ "xclbins-d3_switches" ] }, + "r2t2_switches": { + "model_types": [], + "artifacts": [ + "xclbins-r2t2_switches" + ] + }, "generic_decoding_layer": { "model_types": [ "LLAMA_3_2_1B", diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/Makefile b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/Makefile new file mode 100755 index 000000000..9469a9db7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/Makefile @@ -0,0 +1,64 @@ +# +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Modified by Alfred + +include makefiles/common.mk +HOME_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) + +KERNEL_ARGS := -DMODEL_TYPE=${MODEL_TYPE} +IRON_ARGS := ${MODEL_TYPE} + +ITERATION ?= 1 + +# Kernel makefile +include makefiles/kernel.mk + +# Bitstream makefile +include makefiles/bitstream.mk + +# Host makefile +include makefiles/host.mk + +.PHONY: run all kernel link bitstream host clean clean_all instructions +all: ${XCLBIN_TARGET} ${INSTS_TARGET} ${HOST_C_TARGET} + +clean_all: + -@rm -rf build + -@rm -rf log + -@rm -rf *.exe + -@rm -rf trace* + -@rm -rf routes + + + +kernel: ${KERNEL_OBJS} + + +instructions: ${INSTS_TARGETS} + + +link: ${MLIR_TARGET} + + +bitstream: ${XCLBIN_TARGETS} + + +host: ${HOST_C_TARGET} + + +clean: + -@rm -rf build/host + -@rm -rf ${HOST_C_TARGET} + + +test: $(HOST_C_TARGET) + export LD_LIBRARY_PATH=/opt/xilinx/xrt/lib && ./$(HOST_C_TARGET) + +route: ${IRON_BOTH_MLIR_TARGET} + mkdir -p routes + aie-opt --aie-create-pathfinder-flows --aie-find-flows ${<} | aie-translate --aie-flows-to-json > ./routes/route.json + python visualize.py -j ./routes/route.json \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/README.md b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/README.md new file mode 100644 index 000000000..72a3c25c3 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/README.md @@ -0,0 +1,79 @@ + + +# dequant_mm_mix_bfp16 + +The prompt prefill GEMM of `r2t2:1.7b` (Qwen3-1.7B decoder): `Y[L, Dout] = X[L, Din] @ W[Dout, Din]^T`, bf16 out, on all 32 +cores, reading the **decode** weights in place. The decoder's mixed-precision layout keeps q, k, o, up and gate as Q4_1 and v, +down as Q8_0, in 10240-byte units (`FLM_DLL/detail/qwen3_asr_npu`, `reorder_units`); the prefill uses that same buffer, so +the model needs no second copy. The core pairs dequantize the weights to block float (`bfp16ebs8`) once per pass and multiply +them with X, which the host packs as block float in the order the cores consume it. + +It is `dequant_mm_Q4_1_bfp16` with these changes: + +| | `dequant_mm_Q4_1_bfp16` | this kernel | +|---|---|---| +| weights | Q4_1, prefill layout | Q4_1 **and** Q8_0 blocks of the decode layout; the format is a runtime parameter, per column | +| outputs per core and call | 128 rows x 64 | the same 128 x 64 as `nb` slabs of 64 outputs x `128 / nb` rows (`nb` = 1, 2, 4, 8) | +| short prompts | padded to 512 rows | `nb` = 8 for L <= 64: every weight is read once, X is 64 rows | +| one call | one weight | stacked weights (`mix_band`), e.g. the K, V and Q projections in one call | + +## Measured + +Ryzen AI Max+ 395, `host/host.cpp` (5 warm-up calls, median of 20), per decoder-layer call of Qwen3-1.7B, in us: + +| L | K, V, Q (4096 x 2048) | O (2048 x 2048) | up, gate (12288 x 2048) | down (2048 x 6144) | layer | +|---|---|---|---|---|---| +| 28 | 317 | 244 | 610 | 444 | 1.6 ms | +| 255 | 515 | 264 | 1081 | 576 | 2.4 ms | +| 904 | 1280 | 633 | 3405 | 1605 | 6.9 ms | +| 2048 | 2466 | 1168 | 6866 | 3125 | 13.6 ms | + +Short prompts are bound by DDR (20-26 GB/s of weights), long ones by the cores (14-16.5 TFLOPS). Against an fp32 product of the +same dequantized weights and X, both on the block-float grid, the relative L2 error is 0.0041 for every shape: the bf16 +truncation of the output. + +## Constraints + +* `Din % 512 == 0`. Every band's rows are a multiple of `64 nb` for the `nb` that `mix_nb` picks (it lowers `nb` until they are). +* X and Y hold `mix_rows_padded(L, Dout)` rows; padding rows of X are zero, those of Y are ignored. +* The runtime parameters (`K_div_k` = k rounds, format, `nb`; `rtp_act`) are written per column whenever its format changes, after + the previous pass has drained (`gen_dequant_mm_mix`). +* Built with Peano (`ENABLE_CHESSCC=0`). + +## Layouts + +**W**: the decode layout. A 32 x 256 block is `bf16 scales[8][32]`, (Q4_1) `bf16 mins[8][32]`, then the quants column major +(16 B per column for Q4_1, low nibble = even row; 32 B for Q8_0); a 10240 B unit is two Q4_1 blocks of one block row or one Q8_0 +block and padding; units go per pair of block rows and per unit, the first block row's then the second's. `host/cpu_mix.hpp` builds +it from random weights. + +**X**: per pass `mp` (`512 / nb` rows) and core row `r`, one block of + + [512 k round] [256 k slice (2)] [16-row group (8 / nb)] [128 k half (2)] [k tile (16)] [8-row tile (2)] + +tiles of 8 rows x 8 k, 72 B each (per row a shared exponent and 8 mantissas, truncated). `host/host.cpp` has the reference packer +(`pack_x_mix`) and the AVX-512 one (`pack_x_mix_fast`); the test checks they agree byte for byte. + +**Y**: bf16, row-major `[rows_padded, Dout]`. + +## Things learned while building it (Peano / AIE2P) + +* A memtile buffer descriptor dimension wraps at most 512 words: the 1280-word chunk of the weight reorder is 4 x 320. +* The odd core of a pair must not take weight chunks from the DMA lock itself: with one credit each, either core can take both + credits of one chunk and read the other buffer before it is filled. The even core takes both and hands one on through a lock on + the odd tile. +* A core reads its runtime parameters once the call's first weight chunk is in; it may enter the next call as soon as the previous + one ends, before the host has written new ones. + +## Build and test + + make kernel PEANO_INSTALL_DIR= + make bitstream PEANO_INSTALL_DIR= # build/xclbins/dequant_mm.xclbin + make host + KT_L=28,255,904 ./run.exe # K, V, Q bands; prints RESULT lines, PASSED / FAILED + KT_BANDS=q8:2048 KT_DIN=6144 ./run.exe # the down projection + +`KT_BANDS` (`q4:rows,q8:rows,...`), `KT_DIN`, `KT_L` (comma list), `KT_WARMUP`, `KT_ITERS` set the shape and the timing loop. diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/cpu_mix.hpp b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/cpu_mix.hpp new file mode 100644 index 000000000..27dea486d --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/cpu_mix.hpp @@ -0,0 +1,101 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __CPU_MIX_HPP__ +#define __CPU_MIX_HPP__ +#pragma once + +// CPU model of the mixed-precision decode layout (FLM_DLL/detail/qwen3_asr_npu, MIX_FILE), used to build the weights and the +// golden reference of this xclbin without a model on disk. Per 32 x 256 block, w = d q + m (Q4_1) or w = d q (Q8_0): +// +// Q4_1 bf16 scales[8][32], bf16 mins[8][32], uint4 qs[256 cols][32 rows] 5120 B +// Q8_0 bf16 scales[8][32], int8 qs[256 cols][32 rows] 8704 B +// +// qs is plain column major over the whole block (a Q4_1 column is 16 B, byte j holding rows 2j and 2j + 1, low nibble +// first). On the NPU a weight is a sequence of 10240 B units, two Q4_1 blocks or one Q8_0 block and padding, ordered per +// pair of 32-row blocks and per unit: the unit of the first block row, then that of the second (reorder_units). + +#include +#include +#include +#include + +#include "cpu_q4_1.hpp" + +static constexpr int MIX_Q41_BLOCK = 5120; +static constexpr int MIX_Q80_BLOCK = 8704; + +/// @brief Quantize rows x cols weights to Q4_1 (fmt 0) or Q8_0 (fmt 1) blocks, block-row major; w_deq gets what the core +/// rebuilds (its bf16 conversion truncates toward -infinity, see q41_bf16_floor) +inline void mix_quantize(u8* dst, bf16* w_deq, const bf16* w, int rows, int cols, int fmt) { + const int block = fmt == 0 ? MIX_Q41_BLOCK : MIX_Q80_BLOCK; + const int row_blocks = rows / 32; + const int col_blocks = cols / 256; +#pragma omp parallel for collapse(2) schedule(static) + for (int br = 0; br < row_blocks; br++) { + for (int bc = 0; bc < col_blocks; bc++) { + u8* blk = dst + ((size_t)br * col_blocks + bc) * block; + bf16* scales = (bf16*)blk; + bf16* mins = (bf16*)(blk + 512); + u8* qs = blk + (fmt == 0 ? 1024 : 512); + memset(qs, 0, fmt == 0 ? 4096 : 8192); + for (int r = 0; r < 32; r++) { + const int row = br * 32 + r; + const bf16* src = w + (size_t)row * cols + bc * 256; + bf16* deq = w_deq + (size_t)row * cols + bc * 256; + for (int g = 0; g < 8; g++) { + float lo = (float)src[g * 32], hi = lo, amax = 0.0f; + for (int t = 0; t < 32; t++) { + const float v = (float)src[g * 32 + t]; + lo = std::min(lo, v); + hi = std::max(hi, v); + amax = std::max(amax, std::fabs(v)); + } + if (fmt == 0) { + const bf16 d16 = bf16((hi - lo) / 15.0f); + const bf16 m16 = bf16(lo); + const float d = (float)d16, m = (float)m16; + const float inv_d = d > 0.0f ? 1.0f / d : 0.0f; + scales[g * 32 + r] = d16; + mins[g * 32 + r] = m16; + for (int t = 0; t < 32; t++) { + const int c = g * 32 + t; + const int q = std::clamp((int)lrintf(((float)src[c] - m) * inv_d), 0, 15); + qs[c * 16 + r / 2] |= (u8)(q << ((r % 2) * 4)); + deq[c] = bf16(q41_bf16_floor(std::fma((float)q, d, m))); + } + } else { + const bf16 d16 = bf16(amax / 127.0f); + const float d = (float)d16; + const float inv_d = d > 0.0f ? 1.0f / d : 0.0f; + scales[g * 32 + r] = d16; + for (int t = 0; t < 32; t++) { + const int c = g * 32 + t; + const int q = std::clamp((int)lrintf((float)src[c] * inv_d), -127, 127); + qs[c * 32 + r] = (u8)(int8_t)q; + deq[c] = bf16(q41_bf16_floor((float)q * d)); + } + } + } + } + } + } +} + +/// @brief The NPU units of a quantized weight (see the file comment); the same as qwen3_asr_desc::reorder_units +inline void mix_reorder_units(u8* dst, const u8* src, int rows, int cols, int fmt) { + const size_t block = fmt == 0 ? MIX_Q41_BLOCK : MIX_Q80_BLOCK; + const int blocks_per_row = cols / 256; + const int per_unit = fmt == 0 ? 2 : 1; + const int units_per_row = blocks_per_row / per_unit; + u8* d = dst; + for (int r = 0; r < rows / 32; r += 2) + for (int u = 0; u < units_per_row; u++) + for (int i = 0; i < 2; i++, d += 10240) { + const u8* s = src + ((size_t)(r + i) * blocks_per_row + (size_t)u * per_unit) * block; + memcpy(d, s, per_unit * block); + memset(d + per_unit * block, 0, 10240 - per_unit * block); + } +} + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/cpu_q4_1.hpp b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/cpu_q4_1.hpp new file mode 100644 index 000000000..080c4f2e1 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/cpu_q4_1.hpp @@ -0,0 +1,153 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __CPU_Q4_1_HPP__ +#define __CPU_Q4_1_HPP__ +#pragma once + +// CPU model of the q4nx Q4_1 block, used to build a golden reference for this +// xclbin without a converted model on disk. +// +// This mirrors FLM_Q4NX_Converter/q4nx/model_converter.py::_pack_q4nx with +// `m` present and `parallel_size == 16`, i.e. exactly the bytes the NPU kernel +// in kernel/q4_core.h decodes. Per 32x256 chunk: +// +// bf16 scales[COLS / GROUP][ROWS] 512 B, group major +// bf16 mins [COLS / GROUP][ROWS] 512 B, group major +// u4 qs [ROWS / PARALLEL][COLS][PARALLEL/2] 4096 B, plane / column major +// +// 5120 B total, 5 bits per weight. Only the quant plane is parallel-strided: +// the block's 32 rows are two 16-row planes, each laid out column major on its +// own, which is why kernel/common.hpp sets PARALLEL_ROWS = 16. Scales and mins +// are group major over the whole 32-row block regardless. +// +// Chunks are emitted row-block major (all column blocks of row block 0, then of +// row block 1, ...), matching what Q4NX::load_weights hands back; the vertical +// interleave the cores expect is applied afterwards by reorder_cpy. + +#include +#include +#include + +#include "typedef.hpp" +#include "weights_desc.hpp" + +struct q4_1_block { + static constexpr int ROWS = QXNX_ROW_BLOCK_SIZE; // 32 + static constexpr int COLS = QXNX_COL_BLOCK_SIZE; // 256 + static constexpr int GROUP = GGML_GROUP_SIZE; // 32 + static constexpr int PARALLEL = 16; // converter parallel_size + static constexpr int GROUPS = COLS / GROUP; // 8 + static constexpr int SCALE_BYTES = GROUPS * ROWS * (int)sizeof(bf16);// 512 + static constexpr int MIN_BYTES = SCALE_BYTES; // 512 + static constexpr int PLANE_BYTES = COLS * (PARALLEL / 2); // 2048 + static constexpr int PLANES = ROWS / PARALLEL; // 2 + static constexpr int BYTES = SCALE_BYTES + MIN_BYTES + PLANES * PLANE_BYTES; // 5120 + + static_assert(BYTES == ROWS * COLS * 5 / 8, "q4_1 is 5 bits per weight"); +}; + +/// \brief Quantize a bf16 weight matrix to the packed q4nx Q4_1 layout. +/// +/// The dequantized values are written back to \p w_deq so the caller can build a +/// reference that carries the same quantization error the NPU sees; the only +/// remaining difference is the NPU's bf16/bfp16 arithmetic. +/// +/// \param dst packed output, get_quantization_byte_size(rows * cols, flm_q41) bytes +/// \param w_deq rows x cols, the values the kernel reconstructs (may be null) +/// \param w rows x cols row major source weights (out_features x in_features) +/// \param rows out features, must be a multiple of 32 +/// \param cols in features, must be a multiple of 256 +/// \brief fp32 -> bf16 truncating toward -infinity. +/// +/// This is what the AIE srs does on `aie::accum::to_vector()`, and the +/// dequant core's only conversion is the `aie::mac(...).to_vector()` in +/// kernel/q4_core.h. Rounding to nearest here instead costs ~8% of the +/// reconstructed weights a 1 ulp mismatch against hardware. +inline float q41_bf16_floor(float x) { + uint32_t u; std::memcpy(&u, &x, 4); + if (u & 0xFFFFu) { + if (u & 0x80000000u) u += 0x10000u; // negative: away from zero + u &= 0xFFFF0000u; + } + float o; std::memcpy(&o, &u, 4); return o; +} + +inline void q4_1_quantize_pack(u8* dst, bf16* w_deq, const bf16* w, int rows, int cols) { + using B = q4_1_block; + assert(rows % B::ROWS == 0); + assert(cols % B::COLS == 0); + + const int row_blocks = rows / B::ROWS; + const int col_blocks = cols / B::COLS; + +#pragma omp parallel for collapse(2) schedule(static) + for (int br = 0; br < row_blocks; br++) { + for (int bc = 0; bc < col_blocks; bc++) { + u8* blk = dst + ((size_t)br * col_blocks + bc) * B::BYTES; + bf16* scales = (bf16*)blk; + bf16* mins = (bf16*)(blk + B::SCALE_BYTES); + u8* quants = blk + B::SCALE_BYTES + B::MIN_BYTES; + memset(quants, 0, B::PLANES * B::PLANE_BYTES); + + for (int r = 0; r < B::ROWS; r++) { + const int row = br * B::ROWS + r; + const bf16* src = w + (size_t)row * cols + bc * B::COLS; + bf16* deq = w_deq ? w_deq + (size_t)row * cols + bc * B::COLS : nullptr; + // The quant plane is strided: row r lives in plane r / PARALLEL at + // sub-row r % PARALLEL, two sub-rows to a byte, low nibble first. + const int plane = r / B::PARALLEL; + const int sub = r % B::PARALLEL; + u8* plane_base = quants + plane * B::PLANE_BYTES + sub / 2; + const int shift = (sub % 2) * 4; + + for (int g = 0; g < B::GROUPS; g++) { + float lo = (float)src[g * B::GROUP]; + float hi = lo; + for (int t = 1; t < B::GROUP; t++) { + float v = (float)src[g * B::GROUP + t]; + lo = std::min(lo, v); + hi = std::max(hi, v); + } + // ggml q4_1: d = (max - min) / 15, m = min, q = round((x - m) / d). + // Round d and m through bf16 *before* quantizing so the values + // recorded in w_deq are bit-exact with what the kernel rebuilds. + bf16 d16 = bf16((hi - lo) / 15.0f); + bf16 m16 = bf16(lo); + const float d = (float)d16; + const float m = (float)m16; + const float inv_d = d > 0.0f ? 1.0f / d : 0.0f; + // group major over the full row block: scales + g * ROWS + r + scales[g * B::ROWS + r] = d16; + mins[g * B::ROWS + r] = m16; + + for (int t = 0; t < B::GROUP; t++) { + const int c = g * B::GROUP + t; + int q = (int)lrintf(((float)src[c] - m) * inv_d); + q = std::clamp(q, 0, 15); + plane_base[c * (B::PARALLEL / 2)] |= (u8)(q << shift); + if (deq) deq[c] = bf16(q41_bf16_floor(std::fma((float)q, d, m))); + } + } + } + } + } +} + +/// \brief y = x * w^T, accumulated in fp32. +/// \param y L x N row major output +/// \param x L x K row major activations +/// \param w N x K row major (already dequantized) weights +inline void cpu_matmul_nt(bf16* y, const bf16* x, const bf16* w, int L, int N, int K) { +#pragma omp parallel for schedule(static) + for (int l = 0; l < L; l++) { + const bf16* x_row = x + (size_t)l * K; + for (int n = 0; n < N; n++) { + const bf16* w_row = w + (size_t)n * K; + float acc = 0.0f; + for (int k = 0; k < K; k++) acc = std::fma((float)x_row[k], (float)w_row[k], acc); + y[(size_t)l * N + n] = bf16(acc); + } + } +} + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/host.cpp b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/host.cpp new file mode 100755 index 000000000..6e726b875 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/host.cpp @@ -0,0 +1,328 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utils/debug_utils.hpp" + +#include "typedef.hpp" +#include "npu_utils/npu_utils.hpp" +#include "utils/utils.hpp" +#include "utils/vm_args.hpp" +#include +#include "metrices.hpp" +#include "seq_gen.hpp" +#include "cpu_mix.hpp" + +namespace po = boost::program_options; + +/// \brief Put a matrix on the grid aie::mmul actually multiplies on: every block of 8 consecutive k at a fixed row is given +/// a shared exponent and an 8-bit mantissa, truncated toward -infinity. +static void bfp16_floor_k(bf16* v, size_t rows, size_t k) { +#pragma omp parallel for schedule(static) + for (size_t r = 0; r < rows; r++) { + bf16* row = v + r * k; + for (size_t g = 0; g < k; g += 8) { + float mx = 0.0f; + for (int e = 0; e < 8; e++) mx = std::max(mx, std::fabs((float)row[g + e])); + if (mx == 0.0f) continue; + const float st = std::exp2(std::floor(std::log2(mx)) + 1 - 7); + for (int e = 0; e < 8; e++) row[g + e] = bf16(std::floor((float)row[g + e] / st) * st); + } + } +} + +/// One block of 8 values as the NPU stores it: a shared exponent byte, then 8 two's complement mantissa bytes. The core's +/// conversion truncates, so this does too (same arithmetic as the converter in mlir-aie's block datatype helper). +static void bfp16_block8(const float* v, uint8_t* out9) { + unsigned max_exp = 0; + for (int e = 0; e < 8; e++) { + unsigned bits; memcpy(&bits, v + e, 4); + max_exp = std::max(max_exp, (bits >> 23) & 0xFFu); + } + out9[0] = (uint8_t)max_exp; + for (int e = 0; e < 8; e++) { + unsigned bits; memcpy(&bits, v + e, 4); + const unsigned sign = bits & 0x80000000u; + const unsigned exp = (bits >> 23) & 0xFFu; + unsigned mant = bits & 0x007FFFFFu; + if (exp) mant |= 0x00800000u; + mant = sign ? ~mant + 1 : mant; + int8_t q = (int8_t)(mant >> (23 - 7 + 1)); + q = (max_exp - exp >= 32) ? (int8_t)(sign ? 0xFF : 0x00) : (int8_t)(q >> (max_exp - exp)); + out9[1 + e] = (uint8_t)q; + } +} + +/// X as gen_dequant_mm_mix streams it: per pass mp and core row r one block of +/// [512 k round][256 k slice j (2)][16-row group i (8 / nb)][128 k half v (2)][k tile (16)][8-row tile z (2)] +/// tiles of 8 rows x 8 k (72 B), the rows of group i being mp (512 / nb) + r 16 (8 / nb) + 16 i .. Rows past L are zero. +static void pack_x_mix(uint8_t* out, const bf16* x, uint32_t L, uint32_t L_padded, uint32_t Din, uint32_t nb) { + const uint32_t ms = 8 / nb; + const uint32_t m_pass = mix_pass_rows(nb); + const uint32_t k_rounds = Din / 512; + const size_t round_bytes = (size_t)4 * ms * MIX_X_PACKET_BYTES; + const size_t block_bytes = k_rounds * round_bytes; + const uint32_t blocks = L_padded / m_pass * MIX_CORE_ROWS; +#pragma omp parallel for collapse(2) schedule(static) + for (uint32_t b = 0; b < blocks; b++) { + for (uint32_t kr = 0; kr < k_rounds; kr++) { + const uint32_t mp = b / MIX_CORE_ROWS, r = b % MIX_CORE_ROWS; + uint8_t* p = out + b * block_bytes + kr * round_bytes; + for (uint32_t j = 0; j < 2; j++) for (uint32_t i = 0; i < ms; i++) for (uint32_t v = 0; v < 2; v++) + for (uint32_t kt = 0; kt < 16; kt++) for (uint32_t z = 0; z < 2; z++) { + const size_t r0 = (size_t)mp * m_pass + r * 16 * ms + i * 16 + z * 8; + const size_t k0 = (size_t)kr * 512 + j * 256 + v * 128 + kt * 8; + for (int row = 0; row < 8; row++) { + float vals[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + if (r0 + row < L) for (int e = 0; e < 8; e++) vals[e] = (float)x[(r0 + row) * Din + k0 + e]; + bfp16_block8(vals, p); p += 9; + } + } + } + } +} + +/// Two rows of bfp16_block8 at once: lanes 0..7 are 8 k of row a, 8..15 of row b (bf16, zero for a row past L). +static inline void bfp16_block8_x2(__m256i ab, uint8_t* out_a, uint8_t* out_b) { + const __m512i bits = _mm512_slli_epi32(_mm512_cvtepu16_epi32(ab), 16); + const __m512i exp = _mm512_and_si512(_mm512_srli_epi32(bits, 23), _mm512_set1_epi32(0xFF)); + // the largest exponent of each 8 lanes, in every lane of them + __m512i mx = exp; + mx = _mm512_max_epu32(mx, _mm512_permutexvar_epi32(_mm512_set_epi32(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1), mx)); + mx = _mm512_max_epu32(mx, _mm512_permutexvar_epi32(_mm512_set_epi32(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2), mx)); + mx = _mm512_max_epu32(mx, _mm512_permutexvar_epi32(_mm512_set_epi32(11, 10, 9, 8, 15, 14, 13, 12, 3, 2, 1, 0, 7, 6, 5, 4), mx)); + __m512i mant = _mm512_and_si512(bits, _mm512_set1_epi32(0x007FFFFF)); + mant = _mm512_mask_or_epi32(mant, _mm512_test_epi32_mask(exp, exp), mant, _mm512_set1_epi32(0x00800000)); + mant = _mm512_mask_sub_epi32(mant, _mm512_test_epi32_mask(bits, _mm512_set1_epi32((int)0x80000000)), _mm512_setzero_si512(), mant); + // (int8)(mant >> 17) >> (max - exp), as one arithmetic shift (32 or more gives the sign, as the scalar code) + const __m512i q = _mm512_srav_epi32(mant, _mm512_add_epi32(_mm512_sub_epi32(mx, exp), _mm512_set1_epi32(17))); + alignas(16) uint8_t b[16]; + _mm_store_si128((__m128i*)b, _mm512_cvtepi32_epi8(q)); + out_a[0] = (uint8_t)_mm_cvtsi128_si32(_mm512_castsi512_si128(mx)); + out_b[0] = (uint8_t)_mm_cvtsi128_si32(_mm512_extracti32x4_epi32(mx, 2)); + memcpy(out_a + 1, b, 8); + memcpy(out_b + 1, b + 8, 8); +} + +/// pack_x_mix with AVX-512, the one the engine uses +static void pack_x_mix_fast(uint8_t* out, const bf16* x, uint32_t L, uint32_t L_padded, uint32_t Din, uint32_t nb) { + const uint32_t ms = 8 / nb; + const uint32_t m_pass = mix_pass_rows(nb); + const uint32_t k_rounds = Din / 512; + const size_t round_bytes = (size_t)4 * ms * MIX_X_PACKET_BYTES; + const size_t block_bytes = k_rounds * round_bytes; + const uint32_t blocks = L_padded / m_pass * MIX_CORE_ROWS; +#pragma omp parallel for collapse(2) schedule(static) + for (uint32_t b = 0; b < blocks; b++) { + for (uint32_t kr = 0; kr < k_rounds; kr++) { + const uint32_t mp = b / MIX_CORE_ROWS, r = b % MIX_CORE_ROWS; + uint8_t* p = out + b * block_bytes + kr * round_bytes; + for (uint32_t j = 0; j < 2; j++) for (uint32_t i = 0; i < ms; i++) for (uint32_t v = 0; v < 2; v++) + for (uint32_t kt = 0; kt < 16; kt++) for (uint32_t z = 0; z < 2; z++) { + const size_t r0 = (size_t)mp * m_pass + r * 16 * ms + i * 16 + z * 8; + const size_t k0 = (size_t)kr * 512 + j * 256 + v * 128 + kt * 8; + for (int row = 0; row < 8; row += 2, p += 18) { + const __m128i a = r0 + row < L ? _mm_loadu_si128((const __m128i*)(x + (r0 + row) * Din + k0)) : _mm_setzero_si128(); + const __m128i c = r0 + row + 1 < L ? _mm_loadu_si128((const __m128i*)(x + (r0 + row + 1) * Din + k0)) : _mm_setzero_si128(); + bfp16_block8_x2(_mm256_inserti128_si256(_mm256_castsi128_si256(a), c, 1), p, p + 9); + } + } + } + } +} + +static std::vector parse_list(const char* s, std::vector fallback) { + if (!s) return fallback; + std::vector out; + std::stringstream ss(s); + std::string item; + while (std::getline(ss, item, ',')) out.push_back((uint32_t)std::stoul(item)); + return out; +} + +/// "q4:1024,q8:1024,q4:2048": the bands of one call, in output order +static std::vector> parse_bands(const char* s) { + std::vector> out; + std::stringstream ss(s ? s : "q4:1024,q8:1024,q4:2048"); + std::string item; + while (std::getline(ss, item, ',')) { + const size_t colon = item.find(':'); + const std::string f = item.substr(0, colon); + out.push_back({f == "q8" ? MIX_FMT_Q8_0 : MIX_FMT_Q4_1, (uint32_t)std::stoul(item.substr(colon + 1))}); + } + return out; +} + +int main(int argc, char **argv) { + srand(0); + po::options_description desc("Allowed options"); + po::variables_map vm; + arg_utils::add_default_options(desc); + arg_utils::parse_options(argc, argv, desc, vm); + + // Self-contained: random weights are quantized to the mixed decode layout (Q4_1 / Q8_0 blocks in 10240 B units) on the + // CPU, and the golden output is the fp32 product of what the cores multiply: the dequantized weights and X, both on the + // bfp16 grid. Shapes (env): KT_DIN, KT_BANDS (fmt:rows,...), KT_L (comma list), KT_WARMUP, KT_ITERS. + const uint32_t Din = getenv("KT_DIN") ? atoi(getenv("KT_DIN")) : 2048; + const auto band_spec = parse_bands(getenv("KT_BANDS")); + const std::vector Ls = parse_list(getenv("KT_L"), {28, 64, 128, 255, 512, 904}); + const int Warmup = getenv("KT_WARMUP") ? atoi(getenv("KT_WARMUP")) : 10; + const int Iterations = getenv("KT_ITERS") ? atoi(getenv("KT_ITERS")) : 30; + + std::vector bands; + uint32_t Dout = 0; + size_t w_bytes = 0; + for (const auto& [fmt, rows] : band_spec) { + bands.push_back({w_bytes, rows, fmt}); + w_bytes += (size_t)rows / MIX_SLAB_ROWS * mix_slab_bytes(fmt, Din); + Dout += rows; + } + std::cout << "Din " << Din << ", Dout " << Dout << ", weight bytes " << w_bytes << std::endl; + + xrt::device npu_device = xrt::device(0); + npu_xclbin_manager xclbin_mgr(npu_device::device_npu2, &npu_device, false); + npu_app_manager* dequant_mm = xclbin_mgr.register_xclbin("build/xclbins/dequant_mm.xclbin"); + + //////////////////////////// weights //////////////////////////// + header_print("DEBUG", "Quantizing the weights on the CPU"); + buffer w_bfp((size_t)Dout * Din); // what the cores multiply + std::vector w_units(w_bytes); + { + std::mt19937 rng(0); + std::normal_distribution dist(0.0f, 0.02f); + uint32_t row0 = 0; + for (const mix_band& b : bands) { + buffer w((size_t)b.rows * Din); + for (size_t i = 0; i < w.size(); i++) w[i] = bf16(dist(rng)); + const size_t block = b.fmt == MIX_FMT_Q4_1 ? MIX_Q41_BLOCK : MIX_Q80_BLOCK; + std::vector blocks((size_t)b.rows / 32 * Din / 256 * block); + mix_quantize(blocks.data(), w_bfp.data() + (size_t)row0 * Din, w.data(), b.rows, Din, b.fmt); + mix_reorder_units(w_units.data() + b.offset, blocks.data(), b.rows, Din, b.fmt); + row0 += b.rows; + } + bfp16_floor_k(w_bfp.data(), Dout, Din); + } + + bool all_ok = true; + for (const uint32_t L : Ls) { + const uint32_t nb = mix_nb(L, Dout); + const uint32_t L_padded = mix_rows_padded(L, Dout); + std::cout << "==== L " << L << " (nb " << nb << ", rows padded " << L_padded << ")" << std::endl; + + npu_app mm = dequant_mm->create_app(); + gen_dequant_mm_mix(mm.seq(), L, Din, bands, 0, 0); + buffer buffer_w = mm.create_bo_buffer(w_bytes); + buffer buffer_x = mm.create_bo_buffer((size_t)L_padded * Din * 9 / 8); + buffer buffer_y = mm.create_bo_buffer((size_t)L_padded * Dout); + memcpy(buffer_w.data(), w_units.data(), w_bytes); + buffer_w.sync_to_device(); + + buffer x((size_t)L * Din); + { + std::mt19937 rng(1 + L); + std::normal_distribution dist(0.0f, 1.0f); + for (size_t i = 0; i < x.size(); i++) x[i] = bf16(dist(rng)); + } + // the scalar packer is the reference of the fast one; X goes to the NPU from the fast one + std::vector x_ref_packed(buffer_x.size()); + pack_x_mix(x_ref_packed.data(), x.data(), L, L_padded, Din, nb); + pack_x_mix_fast(buffer_x.data(), x.data(), L, L_padded, Din, nb); + time_utils::time_point pack_start = time_utils::now(); + for (int i = 0; i < 5; i++) pack_x_mix_fast(buffer_x.data(), x.data(), L, L_padded, Din, nb); + time_utils::time_point pack_stop = time_utils::now(); + const bool pack_same = memcmp(x_ref_packed.data(), buffer_x.data(), buffer_x.size()) == 0; + std::cout << " fast X packer " << (pack_same ? "matches" : "DIFFERS FROM") << " the scalar one" << std::endl; + all_ok &= pack_same; + buffer_x.sync_to_device(); + buffer_y.memset(bf16(-1.0f)); + buffer_y.sync_to_device(); + + // a strided subset of rows (every pass and core row is hit), all of them when L is small + const uint32_t stride = (L + 255) / 256; + std::vector rows; + for (uint32_t l = 0; l < L; l += stride) rows.push_back(l); + if (rows.back() != L - 1) rows.push_back(L - 1); + buffer x_ref((size_t)rows.size() * Din); + for (size_t i = 0; i < rows.size(); i++) memcpy(x_ref.data() + i * Din, x.data() + (size_t)rows[i] * Din, Din * 2); + bfp16_floor_k(x_ref.data(), rows.size(), Din); + buffer y_ref((size_t)rows.size() * Dout); + cpu_matmul_nt(y_ref.data(), x_ref.data(), w_bfp.data(), rows.size(), Dout, Din); + + // one call first, on its own: a new sequence must finish before it is timed + mm(buffer_y, buffer_x, buffer_w); + for (int i = 0; i < Warmup; i++) mm(buffer_y, buffer_x, buffer_w); + std::vector call_us; + for (int i = 0; i < Iterations; i++) { + time_utils::time_point start = time_utils::now(); + mm(buffer_y, buffer_x, buffer_w); + time_utils::time_point stop = time_utils::now(); + call_us.push_back(time_utils::duration_us(start, stop).first); + } + std::sort(call_us.begin(), call_us.end()); + const double med_us = call_us[call_us.size() / 2]; + buffer_y.sync_from_device(); + + buffer y((size_t)rows.size() * Dout); + for (size_t i = 0; i < rows.size(); i++) memcpy(y.data() + i * Dout, buffer_y.data() + (size_t)rows[i] * Dout, Dout * 2); + error_metrics m = get_error_metrics(y, y_ref); + print_error_metrics(m); + { + // the outputs far off the reference (a handful of ulps is rounding): where they are says what is wrong + size_t bad = 0; + std::map bad_cols; + for (size_t i = 0; i < rows.size(); i++) + for (uint32_t n = 0; n < Dout; n++) { + const float a = (float)y[i * Dout + n], b = (float)y_ref[i * Dout + n]; + if (std::fabs(a - b) > 0.05f * std::fabs(b) + 0.05f) { + if (bad < 8) std::cout << " off: row " << rows[i] << " col " << n << " npu " << a << " ref " << b << std::endl; + bad++; + bad_cols[n / 64]++; + } + } + std::cout << " off: " << bad << " of " << y.size() << " in " << bad_cols.size() << " 64-col slabs"; + int shown = 0; + for (const auto& [s, c] : bad_cols) if (shown++ < 12) std::cout << " " << s << ":" << c; + std::cout << std::endl; + all_ok &= bad == 0; + } + // per band, so a format or a band offset that is wrong shows on its own + uint32_t row0 = 0; + for (const mix_band& b : bands) { + buffer yb((size_t)rows.size() * b.rows), rb((size_t)rows.size() * b.rows); + for (size_t i = 0; i < rows.size(); i++) { + memcpy(yb.data() + i * b.rows, y.data() + i * Dout + row0, b.rows * 2); + memcpy(rb.data() + i * b.rows, y_ref.data() + i * Dout + row0, b.rows * 2); + } + error_metrics mb = get_error_metrics(yb, rb); + std::cout << " band " << (b.fmt == MIX_FMT_Q4_1 ? "q4" : "q8") << ":" << b.rows << " cos " << mb.CosineSimilarity + << " relL2 " << mb.RelativeL2 << std::endl; + // the bf16 truncation of the output alone is ~0.004 (the fp32 cosine of get_error_metrics loses digits over + // millions of outputs, so it is not the gate) + all_ok &= mb.RelativeL2 < 0.006f; + row0 += b.rows; + } + all_ok &= m.RelativeL2 < 0.006f; + + const double flops = 2.0 * L * (double)Din * Dout; + std::cout << "RESULT L=" << L << " nb=" << nb << " Din=" << Din << " Dout=" << Dout << " us=" << med_us + << " min_us=" << call_us.front() << " TFLOPS=" << flops / (med_us * 1e-6) / 1e12 + << " weight_GBps=" << w_bytes / (med_us * 1e-6) / 1e9 + << " pack_x_ms=" << time_utils::duration_us(pack_start, pack_stop).first / 5000.0 + << " cos=" << m.CosineSimilarity << std::endl; + } + std::cout << (all_ok ? "PASSED" : "FAILED") << std::endl; + return all_ok ? 0 : 1; +} diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/seq_gen.hpp b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/seq_gen.hpp new file mode 100644 index 000000000..63d170e2e --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/seq_gen.hpp @@ -0,0 +1,181 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __SEQ_GEN_HPP__ +#define __SEQ_GEN_HPP__ +#pragma once +#include +#include "npu_utils/npu_utils.hpp" + +// Mirror of the engine's FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_prefill_seq.hpp. Keep the two in sync. +// These are core-local buffer addresses assigned by aie-assign-buffer-addresses; a bitstream build lists them in +// build/xclbins/rtp_addresses.txt (K_div_k_* and rtp_act_*), locked in FLM_Xclbin/rtp_addresses.lock.txt. +static constexpr uint32_t CT_rtp_address_even_row = 53760; +static constexpr uint32_t act_rtp_address_even_row = 53824; +static constexpr uint32_t CT_rtp_address_odd_row = 61952; +static constexpr uint32_t act_rtp_address_odd_row = 62016; + +// the weight formats the cores decode (K_div_k[1]); see kernel/common.hpp +static constexpr int MIX_FMT_Q4_1 = 0; +static constexpr int MIX_FMT_Q8_0 = 1; +// one 32-row block row of the mixed layout is Din / 512 (Q4_1) or Din / 256 (Q8_0) units of this many bytes +static constexpr uint32_t MIX_UNIT_BYTES = 10240; +static constexpr uint32_t MIX_SLAB_ROWS = 64; +static constexpr uint32_t MIX_COLUMNS = 8; +static constexpr uint32_t MIX_CORE_ROWS = 4; +// bytes of one bfp16ebs8 packet of X a core multiplies: 16 rows x 128 k +static constexpr uint32_t MIX_X_PACKET_BYTES = 16 * 128 * 9 / 8; + +/// @brief One weight of a call: `rows` output rows of format `fmt`, at byte `offset` of the weight buffer. A call may +/// stack several (the K, V and Q projections are one call); their rows must be whole multiples of a column's share. +struct mix_band { + size_t offset; + uint32_t rows; + int fmt; +}; + +/// @brief bytes of one 64-row slab (a pair of 32-row blocks) of a Din-wide weight +inline uint32_t mix_slab_bytes(int fmt, uint32_t Din) { + return 2 * Din / (fmt == MIX_FMT_Q4_1 ? 512 : 256) * MIX_UNIT_BYTES; +} + +/// @brief Slabs each column multiplies per pass. A core always computes 128 x 64 outputs per pass: nb slabs for 128 / nb rows +/// of X. The largest nb whose rows still hold L (up to 8) reads every weight once and X the fewest times. +inline uint32_t mix_nb(uint32_t L, uint32_t Dout) { + uint32_t nb = 8; + while (nb > 1 && (Dout % (MIX_COLUMNS * MIX_SLAB_ROWS * nb) != 0 || L > MIX_CORE_ROWS * 128 / nb)) nb /= 2; + return nb; +} + +/// @brief rows of X (and Y) of one pass +inline uint32_t mix_pass_rows(uint32_t nb) { return MIX_CORE_ROWS * 128 / nb; } + +/// @brief L rounded up to whole passes: the rows the packed X and the output buffer must hold +inline uint32_t mix_rows_padded(uint32_t L, uint32_t Dout) { + const uint32_t m = mix_pass_rows(mix_nb(L, Dout)); + return (L + m - 1) / m * m; +} + +/// @brief Y = X W^T for the mixed-precision weights of the decode layer, read in place. +/// +/// X is bfp16ebs8, packed by pack_x_mix for this (L, Dout); Y is bf16 [rows_padded][Dout] at out_offset (elements); the +/// bands are stacked in order along Dout. Passes go over N (512 nb columns), then M (512 / nb rows). Column c of the +/// array takes slabs c nb .. c nb + nb - 1 of a pass, core row r rows r 128 / nb ..; every X packet goes to all eight +/// columns, every weight chunk to both row pairs of its column. +inline void gen_dequant_mm_mix(npu_sequence* seq, const uint32_t L, const uint32_t Din, const std::vector& bands, + const size_t weight_offset, const size_t out_offset) { + static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; + uint32_t Dout = 0; + for (const mix_band& b : bands) Dout += b.rows; + assert(Din % 512 == 0); + + const uint32_t nb = mix_nb(L, Dout); + const uint32_t ms = 8 / nb; // 16-row groups of a core row + const uint32_t m_pass = mix_pass_rows(nb); + const uint32_t n_pass = MIX_COLUMNS * MIX_SLAB_ROWS * nb; + assert(Dout % n_pass == 0); + const uint32_t M_passes = mix_rows_padded(L, Dout) / m_pass; + const uint32_t N_passes = Dout / n_pass; + const uint32_t k_rounds = Din / 512; + // one core row's X of one pass: per 512 k, 2 k slices x ms groups x 2 halves of 128 + const uint32_t x_block_bytes = k_rounds * 4 * ms * MIX_X_PACKET_BYTES; + + seq->clear_cmds(); + + // the slabs of pass np that column c reads, as (byte offset, format) + auto column_weights = [&](uint32_t np, uint32_t c, size_t& off, int& fmt) { + uint32_t row0 = np * n_pass + c * MIX_SLAB_ROWS * nb; + uint32_t band_row = 0; + for (const mix_band& b : bands) { + if (row0 < band_row + b.rows) { + assert(row0 + MIX_SLAB_ROWS * nb <= band_row + b.rows); + fmt = b.fmt; + off = weight_offset + b.offset + (size_t)(row0 - band_row) / MIX_SLAB_ROWS * mix_slab_bytes(b.fmt, Din); + return; + } + band_row += b.rows; + } + assert(false); + }; + auto wait_pass = [&]() { + for (uint32_t r = 0; r < MIX_CORE_ROWS; r++) { + seq->npu_dma_wait(IT[r], S2MM, it_channel_0); + seq->npu_dma_wait(IT[r + 4], S2MM, it_channel_0); + } + }; + + int fmt_set[MIX_COLUMNS]; + for (uint32_t c = 0; c < MIX_COLUMNS; c++) fmt_set[c] = -1; + int round = 0; + for (uint32_t np = 0; np < N_passes; np++) { + size_t w_off[MIX_COLUMNS]; + int fmt[MIX_COLUMNS]; + bool fmt_changed = false; + for (uint32_t c = 0; c < MIX_COLUMNS; c++) { + column_weights(np, c, w_off[c], fmt[c]); + fmt_changed |= fmt[c] != fmt_set[c]; + } + for (uint32_t mp = 0; mp < M_passes; mp++, round++) { + // A core reads its RTPs once a call's first weight chunk is in, so they may only change once every core has + // finished the pass before (its whole output is back): drain it first, then the pipelining starts over. + const bool rewrite = mp == 0 && fmt_changed; + if (rewrite && round > 0) wait_pass(); + if (rewrite) { + for (uint32_t c = 0; c < MIX_COLUMNS; c++) { + for (int row = 2; row < 6; row++) { + npu_tiles tile = get_tile(row, c); + const uint32_t base = (row % 2 == 0) ? CT_rtp_address_even_row : CT_rtp_address_odd_row; + const uint32_t act = (row % 2 == 0) ? act_rtp_address_even_row : act_rtp_address_odd_row; + seq->rtp_write(tile, base, k_rounds); + seq->rtp_write(tile, base + 4, fmt[c]); + seq->rtp_write(tile, base + 8, nb); + seq->rtp_write(tile, act, 0); + } + fmt_set[c] = fmt[c]; + } + } + + const int bd_offset = (round % 2) * 8; + const npu_bd_id y_bd = npu_bd_id(0 + bd_offset); + const npu_bd_id x_bd = npu_bd_id(1 + bd_offset); + const npu_bd_id w_bd = npu_bd_id(2 + bd_offset); + for (uint32_t c = 0; c < MIX_COLUMNS; c++) { + seq->npu_dma_memcpy_nd( + sizeof(char), 2, MM2S, IT[c], w_bd, it_channel_1, + {0, 0, 0, (uint32_t)w_off[c]}, + {1, 1, 1, nb * mix_slab_bytes(fmt[c], Din)}, + {0, 0, 0, 1}, + -1, 0, false, aggressive_cache + ); + } + for (uint32_t r = 0; r < MIX_CORE_ROWS; r++) { + // Y of core row r: columns 0..3 come back through IT[r], 4..7 through IT[r + 4], as rows [slab nb][row of + // the slab's group 16 ms][column 4][64] + const size_t y0 = out_offset + (size_t)(mp * m_pass + r * 16 * ms) * Dout + np * n_pass; + for (uint32_t h = 0; h < 2; h++) { + seq->npu_dma_memcpy_nd( + 2, 0, S2MM, IT[r + 4 * h], y_bd, it_channel_0, + {0, 0, 0, (uint32_t)(y0 + h * 4 * nb * MIX_SLAB_ROWS)}, + {nb, 16 * ms, 4, MIX_SLAB_ROWS}, + {MIX_SLAB_ROWS, Dout, nb * MIX_SLAB_ROWS, 1}, + -1, 0, true + ); + } + // X of core row r, once per slab: the cores multiply every slab against the same rows + seq->npu_dma_memcpy_nd( + 1, 1, MM2S, IT[2 * r], x_bd, it_channel_0, + {0, 0, 0, (uint32_t)((size_t)(mp * MIX_CORE_ROWS + r) * x_block_bytes)}, + {nb, 1, 1, x_block_bytes}, + {0, 0, 0, 1}, + -1, 0, false + ); + } + // keep one pass in flight: wait for the one before (unless it was drained above) + if (round > 0 && !rewrite) wait_pass(); + } + } + wait_pass(); + seq->cmds2seq(); +} + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/weights_desc.hpp b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/weights_desc.hpp new file mode 100644 index 000000000..c7a50dcc6 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/host/weights_desc.hpp @@ -0,0 +1,248 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +#ifndef __WEIGHT_DESC_HPP__ +#define __WEIGHT_DESC_HPP__ + +#include +#include +#include +#include +#include +#include + +#include "utils/debug_utils.hpp" + +#define IS_Q8_MASK 0x1 +#define HAS_ZP_MASK 0x2 +#define HAS_BIAS_MASK 0x4 + +const int FLM_TENSOR_MAX_DIMS = 4; + +constexpr int QXNX_ROW_BLOCK_SIZE = 32; +constexpr int QXNX_COL_BLOCK_SIZE = 256; +constexpr int GGML_GROUP_SIZE = 32; +constexpr int Q4K_SUPER_BLOCK_SIZE = 256; + +// Mirror of FLM_DLL/include/weight_desc.hpp; keep the dtype values and the byte +// sizing identical, the sequence generator indexes device memory with them. +typedef enum: uint8_t { + flm_q40 = 0, + flm_q40b = HAS_BIAS_MASK, + flm_q41 = HAS_ZP_MASK, + flm_q41b = HAS_ZP_MASK | HAS_BIAS_MASK, + flm_q80 = IS_Q8_MASK, + flm_q80b = IS_Q8_MASK | HAS_BIAS_MASK, + flm_q81 = IS_Q8_MASK | HAS_ZP_MASK, + flm_q81b = IS_Q8_MASK | HAS_ZP_MASK | HAS_BIAS_MASK, + // 4-bit with a uint8 scale and a uint8 min per 32-element group, re-fit by a + // bf16 S / bf16 M per 256-element super-block. Carries no flag bits, so it is + // matched by identity rather than by mask. + flm_q4k, + flm_u8, + flm_i8, + flm_u16, + flm_i16, + flm_u32, + flm_i32, + flm_u64, + flm_i64, + flm_f32, + flm_bf16, + flm_unknown +} flm_dtype_t; + +inline bool is_quantize(flm_dtype_t qtype) { return qtype < flm_u8; } +inline bool is_q4_k(flm_dtype_t qtype) { return qtype == flm_q4k; } + +inline size_t get_quantization_byte_size(size_t elems, flm_dtype_t qtype) { + static constexpr size_t slice_size = 512; // Byte + static constexpr size_t chunk_elems = QXNX_ROW_BLOCK_SIZE * QXNX_COL_BLOCK_SIZE; + static constexpr size_t chunk_groups = chunk_elems / GGML_GROUP_SIZE; + static constexpr size_t chunk_supers = chunk_elems / Q4K_SUPER_BLOCK_SIZE; + assert(is_quantize(qtype)); // does not apply to other dtype + assert(elems % chunk_elems == 0); + + size_t chunks = elems / chunk_elems; + + if (is_q4_k(qtype)) { + // Half a byte per element, a uint8 scale and a uint8 min per group, and a + // bf16 S / bf16 M per super-block: 4736 B per chunk, i.e. 4.625 bits per + // weight. That is 9.25 slices, so this path counts bytes directly. + size_t chunk_bytes = chunk_elems / 2 // packed quants + + chunk_groups * 2 * sizeof(uint8_t) // scales + mins + + chunk_supers * 2 * sizeof(bf16); // S + M + return chunks * chunk_bytes; + } + + uint32_t slices = 0; + if ((qtype & IS_Q8_MASK) != 0) { + // 8-bit: 1 byte per element + one bf16 scale per 32-element group + slices += (chunk_elems + chunk_groups * sizeof(bf16)) / slice_size; // 16 quant + 1 scale + } + else { + // 4-bit: half a byte per element (hence / 2) + one bf16 scale per group + slices += (chunk_elems / 2 + chunk_groups * sizeof(bf16)) / slice_size; // / 2 for q4 + } + + // Zero-point and bias each occupy one additional slice per chunk when present. + if (qtype & HAS_ZP_MASK) { + slices += 1; + } + + if (qtype & HAS_BIAS_MASK) { + slices += 1; + } + + return chunks * slices * slice_size; +} + + +inline size_t get_dtype_byte(flm_dtype_t dtype) { + int dtype_size = -1; + switch (dtype) { + case flm_u8: + case flm_i8: + dtype_size= 1; + break; + case flm_u16: + case flm_i16: + case flm_bf16: + dtype_size = 2; + break; + case flm_u32: + case flm_i32: + case flm_f32: + dtype_size = 4; + break; + case flm_u64: + case flm_i64: + dtype_size = 8; + break; + case flm_unknown: + default: + dtype_size = 1; // quantized / unknown types have no fixed per-element size + break; + } + + return dtype_size; +} + + +struct flm_shape_t { + std::array _data; + + flm_shape_t() { _data.fill(1); } + + flm_shape_t(std::initializer_list init) { + _data.fill(1); + size_t i = 0; + for (int64_t v : init) { + if (i >= FLM_TENSOR_MAX_DIMS) break; + _data[i++] = v; + } + } + + int64_t& operator[](size_t idx) { return _data[idx]; } + const int64_t& operator[](size_t idx) const { return _data[idx]; } + + auto begin() { return _data.begin(); } + auto end() { return _data.end(); } + auto begin() const { return _data.begin(); } + auto end() const { return _data.end(); } + constexpr size_t size() const { return FLM_TENSOR_MAX_DIMS; } + void fill(int64_t v) { _data.fill(v); } + size_t elems() { return _data[0] * _data[1] * _data[2] * _data[3]; } + + bool operator==(const flm_shape_t& o) const { return _data == o._data; } + bool operator!=(const flm_shape_t& o) const { return _data != o._data; } +}; + + +inline std::pair quantize_rectify(flm_dtype_t& dtype, flm_shape_t& shape){ + // last 2 dims must satisfy 32x256 block + assert(shape[0] % QXNX_COL_BLOCK_SIZE == 0); + assert(shape[1] % QXNX_ROW_BLOCK_SIZE == 0); + + assert(shape[2] > 0); + assert(shape[3] > 0); + + size_t total_size = get_quantization_byte_size(shape.elems(), dtype); + + flm_shape_t new_shape = shape; + + new_shape[0] = shape[0] / QXNX_COL_BLOCK_SIZE; + new_shape[1] = shape[1] / QXNX_ROW_BLOCK_SIZE; + + return std::pair (total_size, new_shape); +} + +struct weight_desc_t { +public: + flm_shape_t shape; + flm_dtype_t dtype; + std::string name; + size_t offset; + + bool added; + bool loaded; + + weight_desc_t() {} + + weight_desc_t(flm_dtype_t dtype, flm_shape_t shape, std::string name) : + shape(shape), dtype(dtype), name(name), offset(0), added(false), loaded(false) {} + + void indp() { added = true; } + void load() { loaded = true; } + + bool ready() { return added & loaded; } + + template + std::string format_name(Args... args) { + int size = std::snprintf(nullptr, 0, name.c_str(), args...); + assert(size >= 0); + std::string out(size, '\0'); + std::snprintf(&out[0], size + 1, name.c_str(), args...); + return out; + } + + size_t get_size() { + if (is_quantize(dtype)) { + auto new_size_shape = quantize_rectify(dtype, shape); + return new_size_shape.first; + } + else { + return shape.elems() * get_dtype_byte(dtype); + } + } +}; + +class weight_container{ + size_t total_size_counter; +public: + weight_container() { + total_size_counter = 0; + } + + size_t add_weight(flm_dtype_t& dtype, flm_shape_t& shape){ + size_t offset = total_size_counter; + if (is_quantize(dtype)) { + auto new_size_shape = quantize_rectify(dtype, shape); + total_size_counter += new_size_shape.first; + } + else { + total_size_counter += shape.elems() * get_dtype_byte(dtype); + } + return offset; + } + + void add_weight(weight_desc_t& weight){ + weight.offset = this->add_weight(weight.dtype, weight.shape); + weight.added = true; + LOG_VERBOSE(1, "Added weight '" << weight.name << "' at offset " << weight.offset + << ", total size now " << total_size_counter); + } + + size_t get_size() { return total_size_counter; } +}; + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/dequant_mm_aie.py b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/dequant_mm_aie.py new file mode 100644 index 000000000..21168719c --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/dequant_mm_aie.py @@ -0,0 +1,122 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +import numpy as np +import sys + +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.extras import types as T +import aie.dialects.aie as aie +import aie.dialects.aiex as aiex +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref + +from utils import dma_mm2s_ch, dma_s2mm_ch, flow_mm2s_ch, flow_s2mm_ch, connect_dma, generate_tile_map, mlir_context +from utils import dma_port, connect_port +from dequant_mm_tile import dequant_mm_memtile, dequant_mm_tile + +def flow_arch(): + dev = aie.AIEDevice.npu2 + total_cols = 8 + total_rows = 4 + + m = 128 + k = 512 + n = 64 + + m_slice = 16 + k_slice = 256 + n_slice = 32 + y_slice = 512 + + x_dtype = np.dtype[bfloat16] + w_dtype = np.dtype[bfloat16] + y_dtype = np.dtype[bfloat16] + y_acc_dtype = np.dtype[np.float32] + qw_dtype = np.dtype[np.uint32] + + # Q4_1 is 5 bits per weight: half a byte of quant plus a bf16 scale and a + # bf16 min per 32-weight group, i.e. 5120 B for a 32x256 block. The buffers + # are typed uint32, hence the extra // 4. + q4_1_bpw = 5 + qw_size = k_slice * n_slice * q4_1_bpw // 8 // 4 + qw_mem_size = k * n * q4_1_bpw // 8 // 4 + with mlir_mod_ctx() as ctx: + @aie.device(dev) + def device_body(): + IT, MT, CT = generate_tile_map(4 + 2, 8) + + mctx = mlir_context() + # X arrives as bfp16ebs8 tiles (9 bytes per 8 values), already in the order the core eats them; both buffers are sized as bf16 words + # core: 16 rows x 128 k = 32 tiles of 72 B = 2304 B; memtile: 128 rows x 512 k = 1024 tiles = 73728 B + x_ty = mctx.data_ty('x_ty', (9, 128), x_dtype) + x_mem_ty = mctx.data_ty('x_mem_ty', (72, 512), x_dtype) + qw_ty = mctx.data_ty('qw_ty', (qw_size, 1), qw_dtype) + # two n slices of bfp16ebs8 tiles (1.125 bytes per weight), sized as bf16 words: 2 * n_slice * k_slice * 9 / 8 / 2 + w_ty = mctx.data_ty('w_ty', (2 * n_slice * 9 // 16, k_slice), w_dtype) + qw_mem_ty = mctx.data_ty('qw_mem_ty', (qw_mem_size, 1), qw_dtype) + y_ty = mctx.data_ty('y_ty', (y_slice,), y_dtype) + y_acc_ty = mctx.data_ty('y_acc_ty', (m * n, ), y_acc_dtype) + y_mem_ty = mctx.data_ty('y_mem_ty', (m, n * 4), y_dtype) + K_div_k_ty = mctx.data_ty('K_div_k_ty', (16, ), np.dtype[np.int32]) + + mctx.parameter('m', m) + mctx.parameter('k', k) + mctx.parameter('n', n) + mctx.parameter('m_slice', m_slice) + mctx.parameter('k_slice', k_slice) + mctx.parameter('n_slice', n_slice) + mctx.parameter('qw_size', qw_size) + mctx.parameter('qw_mem_size', qw_mem_size) + + mctx.func("dequant_mm_e", [mctx.y_ty, mctx.y_ty, mctx.x_ty, mctx.x_ty, mctx.qw_ty, mctx.qw_ty, mctx.w_ty, mctx.y_acc_ty, mctx.K_div_k_ty, mctx.K_div_k_ty]) + mctx.func("dequant_mm_o", [mctx.y_ty, mctx.y_ty, mctx.x_ty, mctx.x_ty, mctx.qw_ty, mctx.qw_ty, mctx.w_ty, mctx.y_acc_ty, mctx.K_div_k_ty, mctx.K_div_k_ty]) + + mm_core = [[CT[i][j] for j in range(total_cols)] for i in range(total_rows)] + K_div_k_buffers = [] + rtp_activate_buffers = [] + + for i in range(total_rows): + for j in range(total_cols): + K_div_k_buffers.append(mctx.buffer(f"K_div_k_{mm_core[i][j].row}_{mm_core[i][j].col}", mm_core[i][j], K_div_k_ty, use_write_rtp = True)) + rtp_activate_buffers.append(mctx.buffer(f"rtp_act_{mm_core[i][j].row}_{mm_core[i][j].col}", mm_core[i][j], K_div_k_ty, use_write_rtp = True)) + + for j in range(total_cols): + for i in range(total_rows // 2): + dequant_mm_tile(mm_core[2 * i][j], mm_core[2 * i + 1][j], mctx) + dequant_mm_memtile(MT[j], mctx) + + # w_in + for j in range(total_cols): + connect_dma(IT[j], MT[j], 1, 5) + for i in range(total_rows // 2): + connect_dma(MT[j], mm_core[2 * i][j], 2, 1) + + # x_in + for i in range(total_rows): + connect_dma(IT[2 * i], MT[2 * i], 0, 0) + for j in range(total_cols): + connect_dma(MT[2 * i], mm_core[i][j], 0, 0) + + # y_out + for i in range(total_rows): + connect_dma(mm_core[i][0], MT[i], 0, 1) + connect_dma(mm_core[i][1], MT[i], 0, 2) + connect_dma(mm_core[i][2], MT[i], 0, 3) + connect_dma(mm_core[i][3], MT[i], 0, 4) + connect_dma(mm_core[i][4], MT[i + 4], 0, 1) + connect_dma(mm_core[i][5], MT[i + 4], 0, 2) + connect_dma(mm_core[i][6], MT[i + 4], 0, 3) + connect_dma(mm_core[i][7], MT[i + 4], 0, 4) + + for j in range(total_cols): + connect_dma(MT[j], IT[j], 1, 0) + + print(ctx.module) + + +if __name__ == "__main__": + flow_arch() \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/dequant_mm_tile.py b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/dequant_mm_tile.py new file mode 100644 index 000000000..8cc252523 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/dequant_mm_tile.py @@ -0,0 +1,365 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. + +import numpy as np +import sys + +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from typing import List +from utils import mlir_context, tile_with_location, connect_dma, connect_port, lock_acquire, lock_release + +def dequant_mm_tile(tile_e: tile_with_location, tile_o: tile_with_location, mctx: mlir_context): + + ct_e = tile_e.tile + ct_e_row = tile_e.row + ct_e_col = tile_e.col + ct_o = tile_o.tile + ct_o_row = tile_o.row + ct_o_col = tile_o.col + + + x_ty = mctx.x_ty + qw_ty = mctx.qw_ty + w_ty = mctx.w_ty + y_ty = mctx.y_ty + y_acc_ty = mctx.y_acc_ty + + dequant_mm_e = mctx.dequant_mm_e + dequant_mm_o = mctx.dequant_mm_o + + m_slice = mctx.m_slice + k_slice = mctx.k_slice + + x_buffer_e_0 = aie.buffer(tile = ct_e, datatype = x_ty, name = f"x_0_{ct_e_row}_{ct_e_col}") + x_buffer_e_1 = aie.buffer(tile = ct_e, datatype = x_ty, name = f"x_1_{ct_e_row}_{ct_e_col}") + qw_buffer_0 = aie.buffer(tile = ct_e, datatype = qw_ty, name = f"w_0_{ct_e_row}_{ct_e_col}") + qw_buffer_1 = aie.buffer(tile = ct_e, datatype = qw_ty, name = f"w_1_{ct_e_row}_{ct_e_col}") + y_buffer_e_0 = aie.buffer(tile = ct_e, datatype = y_ty, name = f"y_0_{ct_e_row}_{ct_e_col}") + y_buffer_e_1 = aie.buffer(tile = ct_e, datatype = y_ty, name = f"y_1_{ct_e_row}_{ct_e_col}") + y_acc_buffer_e = aie.buffer(tile = ct_e, datatype = y_acc_ty, name = f"y_acc_{ct_e_row}_{ct_e_col}") + K_div_k_buffer_e = mctx.buffers[f"K_div_k_{ct_e_row}_{ct_e_col}"] + rtp_activate_e = mctx.buffers[f"rtp_act_{ct_e_row}_{ct_e_col}"] + + w_buffer = aie.buffer(tile = ct_o, datatype = w_ty, name = f"w_{ct_o_row}_{ct_o_col}") + + x_buffer_o_0 = aie.buffer(tile = ct_o, datatype = x_ty, name = f"x_0_{ct_o_row}_{ct_o_col}") + x_buffer_o_1 = aie.buffer(tile = ct_o, datatype = x_ty, name = f"x_1_{ct_o_row}_{ct_o_col}") + y_buffer_o_0 = aie.buffer(tile = ct_o, datatype = y_ty, name = f"y_0_{ct_o_row}_{ct_o_col}") + y_buffer_o_1 = aie.buffer(tile = ct_o, datatype = y_ty, name = f"y_1_{ct_o_row}_{ct_o_col}") + y_acc_buffer_o = aie.buffer(tile = ct_o, datatype = y_acc_ty, name = f"y_acc_{ct_o_row}_{ct_o_col}") + K_div_k_buffer_o = mctx.buffers[f"K_div_k_{ct_o_row}_{ct_o_col}"] + rtp_activate_o = mctx.buffers[f"rtp_act_{ct_o_row}_{ct_o_col}"] + + x_prod_lock = aie.lock(ct_e, lock_id = 0, init = 2) + x_cons_lock = aie.lock(ct_e, lock_id = 1, init = 0) + qw_prod_lock = aie.lock(ct_e, lock_id = 2, init = 4) + qw_cons_lock = aie.lock(ct_e, lock_id = 3, init = 0) + y_prod_lock = aie.lock(ct_e, lock_id = 4, init = 2) + y_cons_lock = aie.lock(ct_e, lock_id = 5, init = 0) + sync_lock = aie.lock(ct_e, lock_id = 6, init = 0) + x_prod_lock_o = aie.lock(ct_o, lock_id = 0, init = 2) + x_cons_lock_o = aie.lock(ct_o, lock_id = 1, init = 0) + y_prod_lock_o = aie.lock(ct_o, lock_id = 4, init = 2) + y_cons_lock_o = aie.lock(ct_o, lock_id = 5, init = 0) + # Second half of the w_buffer rendezvous. One lock only gives a one-way + # signal; the shared buffer needs a real barrier in both directions, both + # after the two dequant halves and after both cores have read the tile. + sync_lock_o = aie.lock(ct_o, lock_id = 6, init = 0) + # The even core takes both credits of every weight chunk from qw_cons_lock and passes one on here, so the two + # cores always dequantize the same chunk. + qready_lock_o = aie.lock(ct_o, lock_id = 2, init = 0) + + @aie.core(ct_e, link_with = "dequant_mm_e.o", stack_size = 1024 * 4) + def core_body(): + for _ in range_(0xFFFFFFFF): + dequant_mm_e(y_buffer_e_0, y_buffer_e_1, x_buffer_e_0, x_buffer_e_1, qw_buffer_0, qw_buffer_1, w_buffer, y_acc_buffer_e, K_div_k_buffer_e, rtp_activate_e) + + @aie.mem(ct_e) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + + with block[1]: + lock_acquire(x_prod_lock, 1) + aie.dma_bd(x_buffer_e_0, offset = 0, len = 9 * 128) + lock_release(x_cons_lock, 1) + aie.next_bd(block[2]) + + with block[2]: + lock_acquire(x_prod_lock, 1) + aie.dma_bd(x_buffer_e_1, offset = 0, len = 9 * 128) + lock_release(x_cons_lock, 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[4], chain=block[6]) + + with block[4]: + lock_acquire(qw_prod_lock, 2) + aie.dma_bd(qw_buffer_0) + lock_release(qw_cons_lock, 2) + aie.next_bd(block[5]) + + with block[5]: + lock_acquire(qw_prod_lock, 2) + aie.dma_bd(qw_buffer_1) + lock_release(qw_cons_lock, 2) + aie.next_bd(block[4]) + + with block[6]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest=block[7], chain=block[9]) + + with block[7]: + lock_acquire(y_cons_lock, 1) + aie.dma_bd(y_buffer_e_0) + lock_release(y_prod_lock, 1) + aie.next_bd(block[8]) + + with block[8]: + lock_acquire(y_cons_lock, 1) + aie.dma_bd(y_buffer_e_1) + lock_release(y_prod_lock, 1) + aie.next_bd(block[7]) + + with block[9]: + aie.EndOp() + + @aie.core(ct_o, link_with = "dequant_mm_o.o", stack_size = 1024 * 4) + def core_body(): + for _ in range_(0xFFFFFFFF): + dequant_mm_o(y_buffer_o_0, y_buffer_o_1, x_buffer_o_0, x_buffer_o_1, qw_buffer_0, qw_buffer_1, w_buffer, y_acc_buffer_o, K_div_k_buffer_o, rtp_activate_o) + + @aie.mem(ct_o) + def mem_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + + with block[1]: + lock_acquire(x_prod_lock_o, 1) + aie.dma_bd(x_buffer_o_0, offset = 0, len = 9 * 128) + lock_release(x_cons_lock_o, 1) + aie.next_bd(block[2]) + + with block[2]: + lock_acquire(x_prod_lock_o, 1) + aie.dma_bd(x_buffer_o_1, offset = 0, len = 9 * 128) + lock_release(x_cons_lock_o, 1) + aie.next_bd(block[1]) + + with block[3]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest=block[4], chain=block[6]) + + with block[4]: + lock_acquire(y_cons_lock_o, 1) + aie.dma_bd(y_buffer_o_0) + lock_release(y_prod_lock_o, 1) + aie.next_bd(block[5]) + + with block[5]: + lock_acquire(y_cons_lock_o, 1) + aie.dma_bd(y_buffer_o_1) + lock_release(y_prod_lock_o, 1) + aie.next_bd(block[4]) + + with block[6]: + aie.EndOp() + + +def dequant_mm_memtile(tile: tile_with_location, mctx: mlir_context): + mt = tile.tile + mt_row = tile.row + mt_col = tile.col + + x_mem_ty = mctx.x_mem_ty + qw_mem_ty = mctx.qw_mem_ty + y_mem_ty = mctx.y_mem_ty + + m = mctx.m + k = mctx.k + n = mctx.n + k_slice = mctx.k_slice + qw_size = mctx.qw_size + + x_buffer_0 = aie.buffer(tile = mt, datatype = x_mem_ty, name = f"x_0_{mt_row}_{mt_col}") + x_buffer_1 = aie.buffer(tile = mt, datatype = x_mem_ty, name = f"x_1_{mt_row}_{mt_col}") + y_buffer_0 = aie.buffer(tile = mt, datatype = y_mem_ty, name = f"y_0_{mt_row}_{mt_col}") + y_buffer_1 = aie.buffer(tile = mt, datatype = y_mem_ty, name = f"y_1_{mt_row}_{mt_col}") + qw_buffer_0 = aie.buffer(tile = mt, datatype = qw_mem_ty, name = f"qw_0_{mt_row}_{mt_col}") + qw_buffer_1 = aie.buffer(tile = mt, datatype = qw_mem_ty, name = f"qw_1_{mt_row}_{mt_col}") + + x_prod_lock = aie.lock(mt, lock_id = 0, init = 2) + x_cons_lock_0 = aie.lock(mt, lock_id = 1, init = 0) + x_cons_lock_1 = aie.lock(mt, lock_id = 2, init = 0) + x_cons_lock_2 = aie.lock(mt, lock_id = 3, init = 0) + x_cons_lock_3 = aie.lock(mt, lock_id = 4, init = 0) + + y_prod_lock_0 = aie.lock(mt, lock_id = 5, init = 2) + y_prod_lock_1 = aie.lock(mt, lock_id = 6, init = 0) + y_prod_lock_2 = aie.lock(mt, lock_id = 7, init = 0) + y_prod_lock_3 = aie.lock(mt, lock_id = 8, init = 0) + y_cons_lock = aie.lock(mt, lock_id = 9, init = 0) + + qw_prod_lock = aie.lock(mt, lock_id = 10, init = 2) + qw_cons_lock = aie.lock(mt, lock_id = 11, init = 0) + + @aie.memtile_dma(mt) + def memtile_dma_body(block): + s0 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 0, dest=block[1], chain=block[3]) + + with block[1]: + lock_acquire(x_prod_lock, 1) + aie.dma_bd(x_buffer_0) + lock_release(x_cons_lock_0, 1) + aie.next_bd(block[2]) + + with block[2]: + lock_acquire(x_prod_lock, 1) + aie.dma_bd(x_buffer_1) + lock_release(x_cons_lock_0, 1) + aie.next_bd(block[1]) + + with block[3]: + s1 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 0, dest=block[4], chain=block[8]) + + with block[4]: + lock_acquire(x_cons_lock_0, 1) + aie.dma_bd(x_buffer_0, offset = 0, len = 72 * 512 // 2) + lock_release(x_cons_lock_1, 1) + aie.next_bd(block[5]) + + with block[5]: + lock_acquire(x_cons_lock_1, 1) + aie.dma_bd(x_buffer_0, offset = 72 * 512 // 2, len = 72 * 512 // 2) + lock_release(x_prod_lock, 1) + aie.next_bd(block[6]) + + with block[6]: + lock_acquire(x_cons_lock_0, 1) + aie.dma_bd(x_buffer_1, offset = 0, len = 72 * 512 // 2) + lock_release(x_cons_lock_1, 1) + aie.next_bd(block[7]) + + with block[7]: + lock_acquire(x_cons_lock_1, 1) + aie.dma_bd(x_buffer_1, offset = 72 * 512 // 2, len = 72 * 512 // 2) + lock_release(x_prod_lock, 1) + aie.next_bd(block[4]) + + with block[8]: + s2 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 1, dest=block[9], chain=block[11]) + + with block[9]: + lock_acquire(y_prod_lock_0, 1) #, dimensions = [(m // 8, 512), (8, 8), (8, 64), (8, 1)] + aie.dma_bd(y_buffer_0, offset = 0, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_prod_lock_1, 1) + aie.next_bd(block[10]) + + with block[10]: + lock_acquire(y_prod_lock_0, 1) + aie.dma_bd(y_buffer_1, offset = 0, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_prod_lock_1, 1) + aie.next_bd(block[9]) + + with block[11]: + s3 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 2, dest=block[12], chain=block[14]) + + with block[12]: + lock_acquire(y_prod_lock_1, 1) + aie.dma_bd(y_buffer_0, offset = m * n, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_prod_lock_2, 1) + aie.next_bd(block[13]) + + with block[13]: + lock_acquire(y_prod_lock_1, 1) + aie.dma_bd(y_buffer_1, offset = m * n, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_prod_lock_2, 1) + aie.next_bd(block[12]) + + with block[14]: + s6 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 3, dest=block[15], chain=block[17]) + + with block[15]: + lock_acquire(y_prod_lock_2, 1) + aie.dma_bd(y_buffer_0, offset = 2 * m * n, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_prod_lock_3, 1) + aie.next_bd(block[16]) + + with block[16]: + lock_acquire(y_prod_lock_2, 1) + aie.dma_bd(y_buffer_1, offset = 2 * m * n, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_prod_lock_3, 1) + aie.next_bd(block[15]) + + with block[17]: + s7 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 4, dest=block[18], chain=block[20]) + + with block[18]: + lock_acquire(y_prod_lock_3, 1) + aie.dma_bd(y_buffer_0, offset = 3 * m * n, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_cons_lock, 1) + aie.next_bd(block[19]) + + with block[19]: + lock_acquire(y_prod_lock_3, 1) + aie.dma_bd(y_buffer_1, offset = 3 * m * n, len = m * n, dimensions = [(m // 8, 8 * n), (8, 8), (8, n), (8, 1)]) + lock_release(y_cons_lock, 1) + aie.next_bd(block[18]) + + with block[20]: + s8 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 1, dest=block[21], chain=block[23]) + + with block[21]: + lock_acquire(y_cons_lock, 1) + aie.dma_bd(y_buffer_0, offset = 0, len = 4 * m * n, dimensions = [(m, n), (4, m * n), (n, 1)]) + lock_release(y_prod_lock_0, 1) + aie.next_bd(block[22]) + + with block[22]: + lock_acquire(y_cons_lock, 1) + aie.dma_bd(y_buffer_1, offset = 0, len = 4 * m * n, dimensions = [(m, n), (4, m * n), (n, 1)]) + lock_release(y_prod_lock_0, 1) + aie.next_bd(block[21]) + + with block[23]: + s9 = aie.dma_start(channel_dir = aie.DMAChannelDir.S2MM, channel_index = 5, dest=block[24], chain=block[26]) + + with block[24]: + lock_acquire(qw_prod_lock, 1) + aie.dma_bd(qw_buffer_0) + lock_release(qw_cons_lock, 1) + aie.next_bd(block[25]) + + with block[25]: + lock_acquire(qw_prod_lock, 1) + aie.dma_bd(qw_buffer_1) + lock_release(qw_cons_lock, 1) + aie.next_bd(block[24]) + + # A round of weights is 64 rows of the mixed decode layout: [32-row block 0: 2 chunks][block 1: 2 chunks], a + # chunk being 5120 B (a Q4_1 block, or half a Q8_0 unit). The cores want both blocks of a chunk index at once, + # so the round goes out as chunks 0, 2, 1, 3 (dimensions in uint32 words; a wrap is at most 512, so 1280 is 4 x 320). + qw_chunk = qw_size + qw_reorder = [(2, qw_chunk), (2, 2 * qw_chunk), (4, qw_chunk // 4), (qw_chunk // 4, 1)] + + with block[26]: + s10 = aie.dma_start(channel_dir = aie.DMAChannelDir.MM2S, channel_index = 2, dest=block[27], chain=block[29]) + + with block[27]: + lock_acquire(qw_cons_lock, 1) + aie.dma_bd(qw_buffer_0, offset = 0, len = 4 * qw_chunk, dimensions = qw_reorder) + lock_release(qw_prod_lock, 1) + aie.next_bd(block[28]) + + with block[28]: + lock_acquire(qw_cons_lock, 1) + aie.dma_bd(qw_buffer_1, offset = 0, len = 4 * qw_chunk, dimensions = qw_reorder) + lock_release(qw_prod_lock, 1) + aie.next_bd(block[27]) + + with block[29]: + aie.EndOp() \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/utils.py b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/utils.py new file mode 100644 index 000000000..bf57a48a0 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/iron/utils.py @@ -0,0 +1,145 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +from dataclasses import dataclass +from ml_dtypes import bfloat16 +from aie.extras.context import mlir_mod_ctx +from aie.dialects.aie import * +from aie.dialects.aiex import * +from aie.helpers.dialects.ext.scf import _for as range_ +import aie.utils.trace as trace_utils +from aie.utils.trace import MemTilePortEvent, MemTileEvent, PortEvent +from aie.utils.trace_events_enum import CoreEvent, MemEvent, ShimTileEvent, MemTileEvent +from aie.dialects import memref +from typing import Dict, Any, List, Optional +from aie.extras import types as T + +@dataclass +class tile_with_location: + tile: tile + row: int + col: int + +@dataclass +class dma_port: + tile: tile_with_location + channel: int + +class mlir_context: + def __init__(self): + self.data_tys = {} + self.funcs = {} + self.buffers = {} + self.parameters = {} + self.object_fifos = {} + self.packet_ids = {} + + def data_ty(self, name: str, shape: List[int], dtype: Any): + d_ty = np.ndarray[shape, dtype] + self.data_tys[name] = d_ty + if not hasattr(self, name): + setattr(self, name, d_ty) + else: + raise ValueError(f"Data type {name} already exists") + return d_ty + + def buffer(self, name: str, tile: tile_with_location, dtype: Any, use_write_rtp: bool = False): + new_buffer = aie.buffer(tile.tile, dtype, name = name, use_write_rtp = use_write_rtp) + self.buffers[name] = new_buffer + if not hasattr(self, name): + setattr(self, name, new_buffer) + else: + raise ValueError(f"Buffer {name} already exists") + + return new_buffer + + def func(self, name: str, inputs: List[Any]): + this_func = aie.external_func(name, inputs) + self.funcs[name] = this_func + if not hasattr(self, name): + setattr(self, name, this_func) + else: + raise ValueError(f"Function {name} already exists") + return this_func + + def parameter(self, name: str, value: Any): + self.parameters[name] = value + if not hasattr(self, name): + setattr(self, name, value) + else: + raise ValueError(f"Parameter {name} already exists") + return value + + def object_fifo(self, name: str, src_tile: tile_with_location, dst_tile: tile_with_location | List[tile_with_location], depth: int, data_ty: Any, *args, **kwargs): + if isinstance(dst_tile, tile_with_location): + fifo = object_fifo(name, src_tile.tile, dst_tile.tile, depth, data_ty, *args, **kwargs) + else: + fifo = object_fifo(name, src_tile.tile, [t.tile for t in dst_tile], depth, data_ty, *args, **kwargs) + self.object_fifos[name] = fifo + if not hasattr(self, name): + setattr(self, name, fifo) + else: + raise ValueError(f"Object fifo {name} already exists") + return fifo + + + +def dma_mm2s_ch(ch: int): + return { + "source_port": WireBundle.DMA, + "source_channel": ch + } + +def dma_s2mm_ch(ch: int): + return { + "dest_port": WireBundle.DMA, + "dest_channel": ch + } + +def flow_mm2s_ch(ch: int): + return { + "source_bundle": WireBundle.DMA, + "source_channel": ch + } + +def flow_s2mm_ch(ch: int): + return { + "dest_bundle": WireBundle.DMA, + "dest_channel": ch + } + +def generate_tile_map(total_rows: int, total_cols: int) -> Tuple[List[tile_with_location], List[tile_with_location], List[List[tile_with_location]]]: + # Tile declarations + ShimTiles = [] + MemTiles = [] + cores = [] + for col in range(total_cols): + ShimTiles.append(tile_with_location(tile(col, 0), 0, col)) + MemTiles.append(tile_with_location(tile(col, 1), 0, col)) + + for row in range(total_rows - 2): + ComputeTilesRow = [] + for col in range(total_cols): + ComputeTilesRow.append(tile_with_location(tile(col, row + 2), row + 2, col)) + + cores.append(ComputeTilesRow) + + return ShimTiles, MemTiles, cores + +def connect_dma(src: tile_with_location, dst: tile_with_location, src_ch: int, dst_ch: int, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src_ch), dest = dst.tile, **flow_s2mm_ch(dst_ch)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src_ch), dest = dst.tile, **dma_s2mm_ch(dst_ch), keep_pkt_header = keep_pkt_header) + +def connect_port(src: dma_port, dst: dma_port, pkt_id: int = -1, keep_pkt_header: bool = False): + if pkt_id < 0: + aie.flow(source = src.tile, **flow_mm2s_ch(src.channel), dest = dst.tile, **flow_s2mm_ch(dst.channel)) + else: + aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src.channel), dest = dst.tile, **dma_s2mm_ch(dst.channel), keep_pkt_header = keep_pkt_header) + + +def lock_acquire(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.AcquireGreaterEqual, value = value) + +def lock_release(lock: Any, value: int): + aie.use_lock(lock, aie.LockAction.Release, value = value) diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/aie_kernel_utils.h b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/aie_kernel_utils.h new file mode 100644 index 000000000..4ee02430a --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/aie_kernel_utils.h @@ -0,0 +1,157 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// SPDX-License-Identifier: MIT + +#ifndef _AIE_KERNEL_UTILS_ +#define _AIE_KERNEL_UTILS_ + +#include +typedef bfloat16 bf16; + +#if defined(__chess__) +#define AIE_LOOP_UNROLL(x) [[chess::unroll_loop(x)]] +#define AIE_LOOP_UNROLL_FULL [[chess::unroll_loop()]] +#define AIE_LOOP_NO_UNROLL [[chess::no_unroll]] +#define AIE_LOOP_MIN_ITERATION_COUNT(x) [[chess::min_loop_count(x)]] +#define AIE_LOOP_MAX_ITERATION_COUNT(x) [[chess::max_loop_count(x)]] +#define AIE_LOOP_RANGE(a, ...) \ + [[chess::min_loop_count(a)]] __VA_OPT__( \ + [[chess::max_loop_count(__VA_ARGS__)]]) +#define AIE_PREPARE_FOR_PIPELINING [[chess::prepare_for_pipelining]] +#define AIE_NO_PREPARE_FOR_PIPELINING [[chess::no_prepare_for_pipelining]] +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) \ + [[chess::modulo_scheduling_budget_ratio(x)]] +#define AIE_KEEP_SW_LOOP [[chess::keep_sw_loop]] +#define AIE_PEEL_PIPELINED_LOOP(x) [[chess::peel_pipelined_loop(x)]] +#define AIE_KEEP_FREE_FOR_PIPELINING(x) [[chess::keep_free_for_pipelining(x)]] +#define AIE_ALLOCATE(x) [[chess::allocate(x)]] +#define AIE_NO_HW_LOOP [[chess::no_hw_loop]] +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN chess_flatten_loop + +#elif defined(__AIECC__) +#ifndef __STRINGIFY +#define __STRINGIFY(a) #a +#endif +#define AIE_LOOP_UNROLL(x) _Pragma(__STRINGIFY(clang loop unroll_count(x))) +#define AIE_LOOP_UNROLL_FULL _Pragma("clang loop unroll(full)") +#define AIE_LOOP_NO_UNROLL _Pragma("clang loop unroll(disable)") +#define AIE_LOOP_MIN_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop min_iteration_count(x))) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) \ + _Pragma(__STRINGIFY(clang loop max_iteration_count(x))) +#define AIE_LOOP_RANGE(a, ...) \ + AIE_LOOP_MIN_ITERATION_COUNT(a) \ + __VA_OPT__(AIE_LOOP_MAX_ITERATION_COUNT(__VA_ARGS__)) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) \ + _Pragma(__STRINGIFY(clang loop pipeline_initiation_interval(x))) +#define AIE_PREPARE_FOR_POSTPIPELINING _Pragma("clang loop pipeline(disable)") +#define AIE_LOOP_FLATTEN + +#else +#define AIE_LOOP_UNROLL(x) +#define AIE_LOOP_UNROLL_FULL +#define AIE_LOOP_NO_UNROLL +#define AIE_LOOP_MIN_ITERATION_COUNT(x) +#define AIE_LOOP_MAX_ITERATION_COUNT(x) +#define AIE_LOOP_RANGE(a, ...) +#define AIE_PREPARE_FOR_PIPELINING +#define AIE_NO_PREPARE_FOR_PIPELINING +#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) +#define AIE_KEEP_SW_LOOP +#define AIE_PEEL_PIPELINED_LOOP(x) +#define AIE_KEEP_FREE_FOR_PIPELINING(x) +#define AIE_ALLOCATE(x) +#define AIE_NO_HW_LOOP +#define AIE_TRY_INITIATION_INTERVAL(x) +#define AIE_PREPARE_FOR_POSTPIPELINING +#define AIE_LOOP_FLATTEN +#endif + +// Some lock utilities +/// \brief Acquire a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 48, num_locks); +} + +/// \brief Release a lock with given lock ID on this CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 48, num_locks); +} + + +/// \brief Acquire a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _left_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 16, num_locks); +} + +/// \brief Release a lock with given lock ID on left CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _left_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 16, num_locks); +} + +/// \brief Acquire a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _up_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id + 32, num_locks); +} + +/// \brief Release a lock with given lock ID on up CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _up_lock_release(int lock_id, int num_locks = 1){ + release(lock_id + 32, num_locks); +} + +/// \brief Acquire a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to acquire +/// \param num_locks The number of locks to acquire +inline void _down_lock_acquire(int lock_id, int num_locks = 1){ + acquire_greater_equal(lock_id, num_locks); +} + +/// \brief Release a lock with given lock ID on down CT and number of locks +/// \param lock_id The lock ID to release +/// \param num_locks The number of locks to release +inline void _down_lock_release(int lock_id, int num_locks = 1){ + release(lock_id, num_locks); +} + +template +void zero_vectorized(T *__restrict c) { + constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit + static_assert((M) % r == 0); + const aie::vector zeros = aie::zeros(); + const T *__restrict c_end = c + M; + for (; c < c_end; c += r) { + aie::store_v(c, zeros); + } +} + +template +void _memcpy(uint8* dst, uint8* src){ + static constexpr int vec_size = 256; + for (int i = 0; i < SIZE; i += vec_size){ + aie::vector data = aie::load_v(src + i); + aie::store_v(dst + i, data); + } +} + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/common.hpp b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/common.hpp new file mode 100644 index 000000000..54017a219 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/common.hpp @@ -0,0 +1,38 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +///@file typedef.hpp +///@brief Define the typedefs for the kernels +#ifndef __COMMON_HPP__ +#define __COMMON_HPP__ + +#include +#include + +typedef bfloat16 bf16; + +constexpr int QXNX_ROW_BLOCK_SIZE = 32; +constexpr int QXNX_COL_BLOCK_SIZE = 256; +constexpr int GGML_GROUP_SIZE = 32; + +// This kernel reads the weights of the mixed-precision decode layer in place (Q4_1 and Q8_0 blocks, see +// models/qwen3-asr-1.7b-mix.h of generic_decoding_layer): their quants are plain column major over the whole +// 32-row block, so the two cores of a row pair read the same bytes and unzip their own 16 rows. +constexpr int PARALLEL_ROWS = QXNX_ROW_BLOCK_SIZE; + +constexpr bfloat16 exp_scale = 1.44269504089; +constexpr int NPU_M_TILE = 128; +constexpr int NPU_K_TILE = 512; +constexpr int NPU_N_TILE = 64; +constexpr int m_slice = 16; +constexpr int k_slice = QXNX_COL_BLOCK_SIZE; +constexpr int n_slice = QXNX_ROW_BLOCK_SIZE; +// the output tile is handed to the DMA in pieces of this many bf16 values (one lock handshake per piece) +constexpr int y_slice = 512; +constexpr int y_num = NPU_M_TILE * NPU_N_TILE / y_slice; +// weight chunk formats (K_div_k[1]) +constexpr int FMT_Q4_1 = 0; +constexpr int FMT_Q8_0 = 1; +// rows of one weight slab: a pair of 32-row blocks, the w_buffer of a row pair +constexpr int SLAB_ROWS = 2 * QXNX_ROW_BLOCK_SIZE; + +#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/dequant_mm_e.cc b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/dequant_mm_e.cc new file mode 100644 index 000000000..570efb65e --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/dequant_mm_e.cc @@ -0,0 +1,185 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "aie_kernel_utils.h" +#include "q4_core.h" +#include "lut_based_ops.h" +#include "common.hpp" +#include "mm_bfp.h" + +constexpr int x_prod_lock = 0; +constexpr int x_cons_lock = 1; +constexpr int qw_prod_lock = 2; +constexpr int qw_cons_lock = 3; +constexpr int y_prod_lock = 4; +constexpr int y_cons_lock = 5; +constexpr int sync_lock = 6; +// on the odd tile: one credit per weight chunk this core has taken in, for the odd core +constexpr int qready_lock_o = 2; +// tiles of one 32 x 256 n slice of w_buffer: 4 n tiles x 32 k tiles +constexpr int W_SLICE_TILES = (n_slice / 8) * (k_slice / 8); + +bool is_y_ping = false; +bool is_qw_ping = false; +bool is_x_ping = false; +// this core's Q8_0 scales of the two 32-row blocks of a slab, kept from a unit's first chunk for its second +alignas(64) bf16 q8_scales[2][GROUPS * CORE_ROWS]; + +/// Takes the next weight chunk. The DMA hands each chunk over with 2 credits, one per core: this core takes both and +/// passes one on, so the odd core always works on the same chunk (taking one each, either core could take both credits +/// of one chunk and read the other buffer before it is filled). +static inline uint8* next_chunk(uint8* qw_ping, uint8* qw_pong) { + _lock_acquire(qw_cons_lock, 2); + _up_lock_release(qready_lock_o, 1); + is_qw_ping = !is_qw_ping; + return is_qw_ping ? qw_ping : qw_pong; +} + +void silu_aie(bf16 *__restrict x, bf16 *__restrict o, int D){ + + bf16 *x_it = x; + + constexpr int vector_size = 64; + + aie::vector x_vec; + aie::vector o_vec; + + const int F = D / vector_size; + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_MIN_ITERATION_COUNT(1) + for (int i = 0; i < F; i++){ + x_vec = aie::load_v(x_it); + o_vec = getSiluBf16_nonLUT(x_vec); + aie::store_v(o, o_vec); + x_it += vector_size; + o += vector_size; + } +} + +void gelu_aie(bf16 *__restrict x, bf16 *__restrict o, int D){ + constexpr int vector_size = 64; + // two independent vectors per step: the activation is a long dependent chain, this lets the compiler overlap two of them + const int F = D / (2 * vector_size); + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_MIN_ITERATION_COUNT(1) + for (int i = 0; i < F; i++){ + aie::vector a = aie::load_v(x); + aie::vector b = aie::load_v(x + vector_size); + aie::vector ga = getGeluBf16_nonLUT(a); + aie::vector gb = getGeluBf16_nonLUT(b); + aie::store_v(o, ga); + aie::store_v(o + vector_size, gb); + x += 2 * vector_size; + o += 2 * vector_size; + } +} + +/// converts `count` fp32 accumulators to bf16 (count is a multiple of 64) +template +void passThrough_aie(const T_in *restrict in, T_out *restrict out, int count) { + const int vec_factor = 64; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_MIN_ITERATION_COUNT(1) + for (int i = 0; i < count / vec_factor; i++) { + aie::accum c_acc_in; + c_acc_in.from_vector(aie::load_v(in + i * vec_factor)); + aie::store_v(out + i * vec_factor, c_acc_in.template to_vector()); + } +} + +extern "C" { + + void dequant_mm_e( + bf16 * y_ping, + bf16 * y_pong, + bf16 * x_ping, + bf16 * x_pong, + uint8 * qw_ping, + uint8 * qw_pong, + bf16 * w_buffer, + float * y_acc, + int * K_div_k, + int * rtp_activate + ) { + // Both cores of the (even, odd) row pair dequantize their half of a 64-row weight slab into the odd tile's + // buffer, rendezvous on sync_lock, then each multiplies its own X rows against the completed slab. + // + // A call covers nb_count slabs (64 output columns each) for 16 * m_count rows of X, nb_count * m_count = 8, so + // y_acc holds the same 128 x 64 values for every nb_count: slab nb owns the rows [nb][m_count 16-row groups]. + // Small batches use many slabs and few rows, so the weights are read once whatever the batch. + zero_vectorized(y_acc); + const int k_div_k_slice = NPU_K_TILE / k_slice; //colA + const int n_div_n_slice = NPU_N_TILE / n_slice; //colB + + // The RTPs are read once the call's first weight chunk is in: the host writes them before it starts the call's + // DMAs, while this core enters the call as soon as the previous one has ended. + uint8* qw_using = next_chunk(qw_ping, qw_pong); + const int k_rounds = K_div_k[0]; + const int fmt = K_div_k[1]; + const int nb_count = K_div_k[2]; + const int m_count = NPU_M_TILE / m_slice / nb_count; + // a Q4_1 k slice is 2 chunks (the 32-row blocks); a Q8_0 one 4 (the blocks' first, then their second halves) + const int chunks = fmt == FMT_Q8_0 ? 4 : 2; + bool first = true; + + for (int nb = 0; nb < nb_count; nb++){ + for (int k = 0; k < k_rounds; k++){ + for (int j = 0; j < k_div_k_slice; j++){ + // The whole k slice of the slab is dequantized first, so that every X tile that arrives can be + // multiplied against both of its n slices: X is the stream that limits the core. + for (int c = 0; c < chunks; c++){ + if (!first) qw_using = next_chunk(qw_ping, qw_pong); + first = false; + if (fmt == FMT_Q8_0) { + _Q8_0_mix_bfp16<0>((bfp16ebs8*)w_buffer, qw_using, c & 1, c >> 1, q8_scales[c & 1]); + } else { + _Q4_1_mix_bfp16<0>((bfp16ebs8*)w_buffer, qw_using, c); + } + _lock_release(qw_prod_lock, 1); + } + + // Barrier A: my halves of w_buffer are written, wait for the partner core's halves. Release + // before acquiring so the two cores cannot deadlock on each other. + _up_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + + for (int i = 0; i < m_count; i++){ + // v must be the inner loop: the two 128-wide halves of this k slice arrive back to back for + // each 16-row group (see pack_x in the host). Both accumulate into the same y_acc tile. + float* y_group = y_acc + (nb * m_count + i) * m_slice * NPU_N_TILE; + for (int v = 0; v < 2; v++){ + _lock_acquire(x_cons_lock); + is_x_ping = !is_x_ping; + const bf16 *x = is_x_ping ? x_ping : x_pong; + for (int p = 0; p < n_div_n_slice; p++){ + mm_bfp_aie( + y_group + p * n_slice * 8, (const bfp16ebs8*)x, + (const bfp16ebs8*)w_buffer, p * W_SLICE_TILES + v * 32); + } + _lock_release(x_prod_lock); + } + } + // Barrier B: done reading w_buffer, so the partner may overwrite its rows for the next k slice. + _up_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + } + } + } + int use_activation = rtp_activate[0]; + for (int i = 0; i < y_num; i++){ + _lock_acquire(y_prod_lock); + is_y_ping = !is_y_ping; + bf16 *y = is_y_ping ? y_ping : y_pong; + + passThrough_aie(y_acc + i * y_slice, y, y_slice); + if (use_activation == 1){ + silu_aie(y, y, y_slice); + } + else if (use_activation == 2){ + gelu_aie(y, y, y_slice); + } + _lock_release(y_cons_lock); + } + } +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/dequant_mm_o.cc b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/dequant_mm_o.cc new file mode 100644 index 000000000..3e2e02bb0 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/dequant_mm_o.cc @@ -0,0 +1,171 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#include "aie_kernel_utils.h" +#include "q4_core.h" +#include "lut_based_ops.h" +#include "common.hpp" +#include "mm_bfp.h" + +constexpr int x_prod_lock = 0; +constexpr int x_cons_lock = 1; +constexpr int qw_prod_lock = 2; +constexpr int qw_cons_lock = 3; +constexpr int y_prod_lock = 4; +constexpr int y_cons_lock = 5; +constexpr int sync_lock = 6; +// on this tile: one credit per weight chunk the even core has taken in for this core +constexpr int qready_lock = 2; +// tiles of one 32 x 256 n slice of w_buffer: 4 n tiles x 32 k tiles +constexpr int W_SLICE_TILES = (n_slice / 8) * (k_slice / 8); + +bool is_y_ping = false; +bool is_qw_ping = false; +bool is_x_ping = false; +// this core's Q8_0 scales of the two 32-row blocks of a slab, kept from a unit's first chunk for its second +alignas(64) bf16 q8_scales[2][GROUPS * CORE_ROWS]; + +/// Takes the next weight chunk, which the even core has taken from the DMA (see next_chunk there). +static inline uint8* next_chunk(uint8* qw_ping, uint8* qw_pong) { + _lock_acquire(qready_lock, 1); + is_qw_ping = !is_qw_ping; + return is_qw_ping ? qw_ping : qw_pong; +} + +void silu_aie(bf16 *__restrict x, bf16 *__restrict o, int D){ + + bf16 *x_it = x; + + constexpr int vector_size = 64; + + aie::vector x_vec; + aie::vector o_vec; + + const int F = D / vector_size; + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_MIN_ITERATION_COUNT(1) + for (int i = 0; i < F; i++){ + x_vec = aie::load_v(x_it); + o_vec = getSiluBf16_nonLUT(x_vec); + aie::store_v(o, o_vec); + x_it += vector_size; + o += vector_size; + } +} + +void gelu_aie(bf16 *__restrict x, bf16 *__restrict o, int D){ + constexpr int vector_size = 64; + // two independent vectors per step: the activation is a long dependent chain, this lets the compiler overlap two of them + const int F = D / (2 * vector_size); + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_MIN_ITERATION_COUNT(1) + for (int i = 0; i < F; i++){ + aie::vector a = aie::load_v(x); + aie::vector b = aie::load_v(x + vector_size); + aie::vector ga = getGeluBf16_nonLUT(a); + aie::vector gb = getGeluBf16_nonLUT(b); + aie::store_v(o, ga); + aie::store_v(o + vector_size, gb); + x += 2 * vector_size; + o += 2 * vector_size; + } +} + +/// converts `count` fp32 accumulators to bf16 (count is a multiple of 64) +template +void passThrough_aie(const T_in *restrict in, T_out *restrict out, int count) { + const int vec_factor = 64; + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_MIN_ITERATION_COUNT(1) + for (int i = 0; i < count / vec_factor; i++) { + aie::accum c_acc_in; + c_acc_in.from_vector(aie::load_v(in + i * vec_factor)); + aie::store_v(out + i * vec_factor, c_acc_in.template to_vector()); + } +} + +extern "C" { + + void dequant_mm_o( + bf16 * y_ping, + bf16 * y_pong, + bf16 * x_ping, + bf16 * x_pong, + uint8 * qw_ping, + uint8 * qw_pong, + bf16 * w_buffer, + float * y_acc, + int * K_div_k, + int * rtp_activate + ) { + // The mirror of dequant_mm_e (see there): this core owns rows 16..31 of every 32-row weight block. + zero_vectorized(y_acc); + const int k_div_k_slice = NPU_K_TILE / k_slice; //colA + const int n_div_n_slice = NPU_N_TILE / n_slice; //colB + + // RTPs only once the call's first weight chunk is in (see dequant_mm_e) + uint8* qw_using = next_chunk(qw_ping, qw_pong); + const int k_rounds = K_div_k[0]; + const int fmt = K_div_k[1]; + const int nb_count = K_div_k[2]; + const int m_count = NPU_M_TILE / m_slice / nb_count; + const int chunks = fmt == FMT_Q8_0 ? 4 : 2; + bool first = true; + + for (int nb = 0; nb < nb_count; nb++){ + for (int k = 0; k < k_rounds; k++){ + for (int j = 0; j < k_div_k_slice; j++){ + for (int c = 0; c < chunks; c++){ + if (!first) qw_using = next_chunk(qw_ping, qw_pong); + first = false; + if (fmt == FMT_Q8_0) { + _Q8_0_mix_bfp16<1>((bfp16ebs8*)w_buffer, qw_using, c & 1, c >> 1, q8_scales[c & 1]); + } else { + _Q4_1_mix_bfp16<1>((bfp16ebs8*)w_buffer, qw_using, c); + } + _down_lock_release(qw_prod_lock, 1); + } + + // Barrier A: my halves of w_buffer are written, wait for the partner core's halves. Release + // before acquiring so the two cores cannot deadlock on each other. + _down_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + + for (int i = 0; i < m_count; i++){ + float* y_group = y_acc + (nb * m_count + i) * m_slice * NPU_N_TILE; + for (int v = 0; v < 2; v++){ + _lock_acquire(x_cons_lock); + is_x_ping = !is_x_ping; + const bf16 *x = is_x_ping ? x_ping : x_pong; + for (int p = 0; p < n_div_n_slice; p++){ + mm_bfp_aie( + y_group + p * n_slice * 8, (const bfp16ebs8*)x, + (const bfp16ebs8*)w_buffer, p * W_SLICE_TILES + v * 32); + } + _lock_release(x_prod_lock); + } + } + // Barrier B: done reading w_buffer, so the partner may overwrite its rows for the next k slice. + _down_lock_release(sync_lock, 1); + _lock_acquire(sync_lock, 1); + } + } + } + int use_activation = rtp_activate[0]; + for (int i = 0; i < y_num; i++){ + _lock_acquire(y_prod_lock); + is_y_ping = !is_y_ping; + bf16 *y = is_y_ping ? y_ping : y_pong; + + passThrough_aie(y_acc + i * y_slice, y, y_slice); + if (use_activation == 1){ + silu_aie(y, y, y_slice); + } + else if (use_activation == 2){ + gelu_aie(y, y, y_slice); + } + _lock_release(y_cons_lock); + } + } +} \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/lut_based_ops.h b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/lut_based_ops.h new file mode 100644 index 000000000..7216561dc --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/lut_based_ops.h @@ -0,0 +1,72 @@ +//===--- exp_lut.h - get exponential values from loopup tables ---===// +// +// This file is licensed under the Apache License v2.0 with LLVM Exceptions +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +// +// +//===----------------------------------------------------------------------===// +// This is the implementation of getting exponential values for a bfloat16 +// vector from exponential lookup tables. +//===----------------------------------------------------------------------===// +#ifndef __LUT_BASED_OPS_H__ +#define __LUT_BASED_OPS_H__ + +#include "aie_api/aie.hpp" + + +// The tables _ab and _cd are copies of each other +// Also, each table has a copy of data seperated by 256-bit +// This effectively creates 4 copies of the table (located in 4 (256-bit) banks) +// This allows the user to use the "gather" read feature and read 4 values from +// 4 different banks at once Tables entries are in BF16 +// +template +__attribute__((always_inline)) aie::vector getSiluBf16_nonLUT(aie::vector x){ + const bfloat16 half = 0.5f; + const bfloat16 one = 1.0f; + aie::vector v_half = aie::broadcast(half); + aie::vector v_one = aie::broadcast(one); + aie::accum x_mul_half = aie::mul(x, v_half); + aie::vector tanh_x_half = aie::tanh(x_mul_half.template to_vector()); + + aie::vector tanh_x_half_plus_one = aie::add(tanh_x_half, v_one); + aie::vector tanh_x_half_plus_one_div_2 = aie::mul(tanh_x_half_plus_one, v_half).template to_vector(); + + aie::vector res = aie::mul(x, tanh_x_half_plus_one_div_2).template to_vector(); + return res; +} +/// gelu with the tanh approximation: 0.5 x (1 + tanh(c (x + b x^3))), c = sqrt(2/pi), b = 0.044715 +/// Written to round to bf16 as rarely as possible: the polynomial is c x (1 + b x^2) = x (c + c b x^2) and the outer factor +/// 0.5 (1 + tanh) is one multiply-accumulate, so only x^2, the polynomial factor, the outer factor and the result are rounded. +template +__attribute__((always_inline)) aie::vector getGeluBf16_nonLUT(aie::vector x) { + const aie::vector v_c = aie::broadcast(bfloat16(0.79788456f)); + const aie::vector v_cb = aie::broadcast(bfloat16(0.79788456f * 0.044715f)); + const aie::vector v_half = aie::broadcast(bfloat16(0.5f)); + + const aie::vector x2 = aie::mul(x, x).template to_vector(); + + // c + c b x^2 + aie::accum poly; + poly.from_vector(v_c); + poly = aie::mac(poly, x2, v_cb); + const aie::vector factor = poly.template to_vector(); + + // tanh(x * factor), the argument stays in float + const aie::vector arg = aie::mul(x, factor).template to_vector(); + const aie::vector t = aie::tanh(arg); + + // 0.5 + 0.5 tanh + aie::accum outer; + outer.from_vector(v_half); + outer = aie::mac(outer, t, v_half); + const aie::vector gate = outer.template to_vector(); + + return aie::mul(x, gate).template to_vector(); +} + +#endif //__LUT_BASED_OPS_H__ \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/mm_bfp.h b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/mm_bfp.h new file mode 100644 index 000000000..c02b5eee7 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/mm_bfp.h @@ -0,0 +1,67 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __MM_BFP_H__ +#define __MM_BFP_H__ +#include +#include "aie_kernel_utils.h" + +/// @brief Accumulates a (16 x colA*8) bf16 slab of X against colB n tiles of block-float weights, into fp32 partial sums. +/// +/// The same blocking as the bf16 multiply it replaces (2 x 2 mmul tiles per step), but B arrives as native bfp16ebs8 +/// tiles that the dequantizer already converted, so the loop only converts the X tiles. +/// +/// @param pY fp32 partial sums, [m tile][n tile][8x8], advanced by the caller per call +/// @param pX bf16 X, mmul A tile order [m tile][k tile][8x8] (tile strides as the bf16 multiply used) +/// @param pW weight tiles, [n tile][k tile], ldB k tiles per n tile +/// @param w_tile0 index of the first weight tile this call reads: the slice's first tile plus 2 per k tile skipped (tiles are +/// stored [n pair][k tile][2 n tiles]) +template +void mm_bfp_aie(float *__restrict pY, const bfp16ebs8 *__restrict pX, const bfp16ebs8 *__restrict pW, unsigned w_tile0) { + using MMUL = aie::mmul<8, 8, 8, bfp16ebs8, bfp16ebs8, accauto>; + + for (unsigned z = 0; z < rowA; z += 2) { + float *__restrict pY1 = pY + (z * colB) * MMUL::size_C * 2; + float *__restrict pY2 = pY + ((z + 1) * colB) * MMUL::size_C * 2; + + for (unsigned j = 0; j < colB; j += 2) { + // X tiles come as [k tile][row tile], so one stream hands out the pair (z, z + 1) tile after tile + aie::block_vector_input_buffer_stream x_stream(pX); + x_stream.seek(z); + + // the n tiles j and j + 1 sit next to each other for every k tile (see _Q4_1_bfp16), so one stream serves both + aie::block_vector_input_buffer_stream w_stream(pW); + w_stream.seek(w_tile0 + (j / 2) * 2 * ldB); + + MMUL Y00(aie::load_v(pY1)); + MMUL Y01(aie::load_v(pY1 + MMUL::size_C)); + MMUL Y10(aie::load_v(pY2)); + MMUL Y11(aie::load_v(pY2 + MMUL::size_C)); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(colA, colA) + AIE_TRY_INITIATION_INTERVAL(4) + for (unsigned i = 0; i < colA; ++i) { + aie::block_vector X0 = x_stream.pop(); + aie::block_vector X1 = x_stream.pop(); + aie::block_vector W0 = w_stream.pop(); + aie::block_vector W1 = w_stream.pop(); + + Y00.mac(X0, aie::op_transpose(W0)); + Y01.mac(X0, aie::op_transpose(W1)); + Y10.mac(X1, aie::op_transpose(W0)); + Y11.mac(X1, aie::op_transpose(W1)); + } + aie::store_v(pY1, Y00.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY1, Y01.template to_vector()); + pY1 += MMUL::size_C; + aie::store_v(pY2, Y10.template to_vector()); + pY2 += MMUL::size_C; + aie::store_v(pY2, Y11.template to_vector()); + pY2 += MMUL::size_C; + } + } +} + +#endif diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/q4_core.h b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/q4_core.h new file mode 100644 index 000000000..b56da1305 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/kernel/q4_core.h @@ -0,0 +1,170 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. + +#ifndef __Q4_CORE_H__ +#define __Q4_CORE_H__ +#include "aie_kernel_utils.h" +#include "common.hpp" + +/// bf16 has an 8 bit exponent and a 7 bit mantissa, so the [128, 256) binade has +/// an ulp of exactly 1: the bit pattern 0x4300 | v *is* the number 128 + v, for +/// every v in [0, 15]. A uint4 -> bf16 conversion is therefore just byte +/// placement -- unpack the nibbles to bytes and zip 0x43 in as the high byte -- +/// instead of aie::to_float's convert chain through the accumulator files. The +/// weights come out biased by 128, which the caller pays back for free. +static constexpr uint8 Q4_BIASED_EXP_BYTE = 0x43; +static constexpr int NIBBLE_BIAS = 128; + +template +static inline __attribute__((always_inline)) aie::vector _q4_biased_bf16( + aie::vector nibble_bytes, + aie::vector bias_bytes +) { + // little endian: low byte is the nibble, high byte the 0x43 exponent field + return aie::vector_cast( + aie::concat(aie::interleave_zip(nibble_bytes, bias_bytes, 1))); +} + +// aie::mmul<8, 8, 8> B tile: 8 k rows x 8 n columns, n fastest +static constexpr int MM_BLK = 8; +static constexpr int LANES = MM_BLK * MM_BLK; +// the row pair splits a 32-row block in half, so a core owns this many rows +static constexpr int CORE_ROWS = QXNX_ROW_BLOCK_SIZE / 2; +// k tiles in one n block of the output: the whole 256 wide column block +static constexpr int K_TILES = QXNX_COL_BLOCK_SIZE / MM_BLK; +static constexpr int GROUPS = QXNX_COL_BLOCK_SIZE / GGML_GROUP_SIZE; +static constexpr int TILES_PER_GROUP = GGML_GROUP_SIZE / MM_BLK; + +/// lane n of an output tile is row (n % 8) of an 8-row half, so each half of a core's 16 per-row values is splatted +/// MM_BLK times across a tile: .first serves rows 0..7, .second rows 8..15 +static inline __attribute__((always_inline)) auto _splat_rows(aie::vector v) { + aie::vector v32 = aie::concat(v, v); + aie::vector v64 = aie::concat(v32, v32); + return aie::interleave_unzip(v64, v64, MM_BLK); +} + +/// turns two bf16 B tiles (k major, n fastest) the way the multiply wants them (k fastest) and writes them as block float +static inline __attribute__((always_inline)) void _push_tiles( + aie::block_vector_output_buffer_stream& out, + aie::vector w_lo, + aie::vector w_hi +) { + aie::accum t_lo; + aie::accum t_hi; + t_lo.from_vector(aie::transpose(w_lo, MM_BLK, MM_BLK)); + t_hi.from_vector(aie::transpose(w_hi, MM_BLK, MM_BLK)); + out.push(t_lo.template to_vector()); + out.push(t_hi.template to_vector()); +} + +/// @brief Dequantize one Q4_1 block of the mixed-precision decode layout into bfp16 B tiles. +/// +/// The block is q41_block_t of generic_decoding_layer/kernels/model_spec.h as the mixed models pack it +/// (PARALLEL_ROWS = 32): w = d q + m with +/// scales bf16 [GROUPS][32 rows] at +0 +/// mins bf16 [GROUPS][32 rows] at +512 +/// qs uint4 [256 cols][32 rows] at +1024, plain column major: a column is 16 B, byte j holding rows 2j (low +/// nibble) and 2j + 1 (high nibble) +/// A k tile (8 columns) is 128 B. An 8-byte unzip of its two 64 B halves gives rows 0..15 (.first) and rows 16..31 +/// (.second) of the 8 columns, each in the order the 16-row plane of the prefill Q4_1 layout has: from there on the +/// conversion is the one of _Q4_1_bfp16 in dequant_mm_bfp16. +/// +/// @tparam H the half of the block this core owns: 0 = rows 0..15 (even core), 1 = rows 16..31 (odd core) +/// @param w_tiles bfp16ebs8 output, tiles [32-row block p][half H][k tile][low n block, high n block] +/// @param qw the block +/// @param p which 32-row block of the 64-row slab this is (0 or 1) +template +void _Q4_1_mix_bfp16(bfp16ebs8* w_tiles, const uint8* qw, int p) { + const bf16* p_scale = (const bf16*)qw; + const bf16* p_min = (const bf16*)(qw + 512); + const uint8* p_quant = qw + 1024; + + aie::block_vector_output_buffer_stream out(w_tiles); + out.seek(p * 4 * K_TILES + H * 2 * K_TILES); + + const aie::vector bias_bytes = aie::broadcast(Q4_BIASED_EXP_BYTE); + + for (int g = 0; g < GROUPS; g++) { + auto scale_vec = _splat_rows(aie::load_v(p_scale + g * QXNX_ROW_BLOCK_SIZE + H * CORE_ROWS)); + auto min = _splat_rows(aie::load_v(p_min + g * QXNX_ROW_BLOCK_SIZE + H * CORE_ROWS)); + aie::accum base_lo; + aie::accum base_hi; + base_lo.from_vector(min.first); + base_hi.from_vector(min.second); + // the MAC operand is 128 + q: pay the extra 128 d back once per group (exact, 128 is a power of two) + base_lo = aie::msc(base_lo, scale_vec.first, bfloat16(NIBBLE_BIAS)); + base_hi = aie::msc(base_hi, scale_vec.second, bfloat16(NIBBLE_BIAS)); + + AIE_PREPARE_FOR_PIPELINING + AIE_LOOP_RANGE(TILES_PER_GROUP, TILES_PER_GROUP) + for (int tile = 0; tile < TILES_PER_GROUP; tile++) { + const uint8* q = p_quant + (g * TILES_PER_GROUP + tile) * 128; + auto halves = aie::interleave_unzip(aie::load_v<64>(q), aie::load_v<64>(q + 64), 8); + aie::vector q_raw = aie::vector_cast(H == 0 ? halves.first : halves.second); + // lane c * 16 + r is row r of column c: unzip at 8 splits each column's 16 rows into the two n blocks + aie::vector q_bytes = aie::unpack(q_raw); + auto rows = aie::interleave_unzip(q_bytes.template extract(0), + q_bytes.template extract(1), + MM_BLK); + aie::vector lo = _q4_biased_bf16(rows.first, bias_bytes); + aie::vector hi = _q4_biased_bf16(rows.second, bias_bytes); + // w = d (128 + q) + (m - 128 d), rounded to bf16, then block float + _push_tiles(out, aie::mac(base_lo, lo, scale_vec.first).template to_vector(), + aie::mac(base_hi, hi, scale_vec.second).template to_vector()); + } + } +} + +/// k tiles of a Q8_0 block in the first 5120 B half of its 10240 B unit (512 B of scales, then 32 B per column) +static constexpr int Q8_H0_TILES = (5120 - 512) / (MM_BLK * QXNX_ROW_BLOCK_SIZE); + +/// @brief Dequantize one half of a Q8_0 block of the mixed-precision decode layout into bfp16 B tiles. +/// +/// The block is q80_block_t (w = d q): scales bf16 [GROUPS][32 rows] (512 B), then qs int8 [256 cols][32 rows] (8 KB), +/// padded to a 10240 B unit. The DMA hands the unit over as two 5120 B chunks: half 0 holds the scales and k tiles +/// 0..17, half 1 k tiles 18..31 (and the padding). Half 0 keeps this core's scales in `scales` ([GROUPS][16]) for half 1. +/// +/// A k tile is 256 B, 2 columns per 64 B load: a 16-byte unzip of two loads picks this core's 16 rows of 4 columns. +/// +/// @tparam H 0 = rows 0..15 (even core), 1 = rows 16..31 (odd core) +/// @param w_tiles bfp16ebs8 output, as _Q4_1_mix_bfp16 +/// @param qw the chunk +/// @param p which 32-row block of the 64-row slab this is (0 or 1) +/// @param half 0 or 1, the chunk of the unit +/// @param scales this core's scales of the block, written by half 0 and read by half 1 +template +void _Q8_0_mix_bfp16(bfp16ebs8* w_tiles, const uint8* qw, int p, int half, bf16* scales) { + const int t0 = half == 0 ? 0 : Q8_H0_TILES; + const int t1 = half == 0 ? Q8_H0_TILES : K_TILES; + const int8* p_quant = (const int8*)(half == 0 ? qw + 512 : qw); + if (half == 0) { + for (int g = 0; g < GROUPS; g++) + aie::store_v(scales + g * CORE_ROWS, + aie::load_v((const bf16*)qw + g * QXNX_ROW_BLOCK_SIZE + H * CORE_ROWS)); + } + + aie::block_vector_output_buffer_stream out(w_tiles); + out.seek(p * 4 * K_TILES + H * 2 * K_TILES + 2 * t0); + + for (int t = t0; t < t1; t++) { + auto scale_vec = _splat_rows(aie::load_v(scales + (t / TILES_PER_GROUP) * CORE_ROWS)); + const int8* q = p_quant + (t - t0) * MM_BLK * QXNX_ROW_BLOCK_SIZE; + auto c03 = aie::interleave_unzip(aie::load_v<64>(q), aie::load_v<64>(q + 64), CORE_ROWS); + auto c47 = aie::interleave_unzip(aie::load_v<64>(q + 128), aie::load_v<64>(q + 192), CORE_ROWS); + // lane c * 16 + r is row r of column c (columns 0..3, then 4..7): unzip at 8 gives the two n blocks + auto rows = aie::interleave_unzip(H == 0 ? c03.first : c03.second, + H == 0 ? c47.first : c47.second, MM_BLK); + // int8 -> bf16 is exact + aie::accum q_lo; + aie::accum q_hi; + q_lo.from_vector(aie::to_float(rows.first, 0)); + q_hi.from_vector(aie::to_float(rows.second, 0)); + aie::vector lo = q_lo.template to_vector(); + aie::vector hi = q_hi.template to_vector(); + // w = d q, rounded to bf16, then block float + _push_tiles(out, aie::mul(lo, scale_vec.first).template to_vector(), + aie::mul(hi, scale_vec.second).template to_vector()); + } +} + +#endif // __Q4_CORE_H__ diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/bitstream.mk b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/bitstream.mk new file mode 100755 index 000000000..eddfff2a2 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/bitstream.mk @@ -0,0 +1,48 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# MLIR stuff + +MLIR_O_DIR := build/$(MODEL_TYPE)/mlir +BITSTREAM_O_DIR := build/$(MODEL_TYPE)/bitstream + + +IRON_BOTH_SRC := $(wildcard ${HOME_DIR}/iron/*_aie.py) +IRON_OTHER_SRC := $(wildcard ${HOME_DIR}/iron/*.py) +IRON_BOTH_MLIR_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${MLIR_O_DIR}/%.mlir, ${IRON_BOTH_SRC}) +IRON_BOTH_XCLBIN_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.xclbin, ${IRON_BOTH_SRC}) +IRON_BOTH_INSTS_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.txt, ${IRON_BOTH_SRC}) + +.PRECIOUS: ${IRON_BOTH_MLIR_TARGET} + +AIECC_FLAGS := --aie-generate-cdo --no-compile-host +ENABLE_CHESSCC ?= 0 +ifeq ($(ENABLE_CHESSCC),1) +AIECC_FLAGS += --xchesscc --xbridge +else +AIECC_FLAGS += --no-xchesscc --no-xbridge +endif +# iron generate mlir +${MLIR_O_DIR}/%.mlir: ${HOME_DIR}/iron/%_aie.py ${IRON_OTHER_SRC} + mkdir -p ${@D} + python3 $< ${IRON_ARGS} > $@ + +# Build xclbin +${BITSTREAM_O_DIR}/from_iron/%.xclbin: ${MLIR_O_DIR}/%.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-xclbin \ + --xclbin-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) + mkdir -p build/$(MODEL_TYPE)/xclbins + cp ${@} build/$(MODEL_TYPE)/xclbins/ + @# the test host's seq_gen.hpp and the engine's qwen3_asr_prefill_seq.hpp hard-code these + cat ${@D}/*/input_with_addresses.mlir | grep -E "%(K_div_k|rtp_act)_" | grep "aie.buffer" | awk '{print $$1, $$6}' | sed 's/%//g' | sort | tee build/$(MODEL_TYPE)/xclbins/rtp_addresses.txt + +${BITSTREAM_O_DIR}/from_iron/%.txt: ${MLIR_O_DIR}/%.mlir + mkdir -p ${@D} + cd ${@D} && aiecc.py -n ${AIECC_FLAGS} --aie-generate-npu-insts \ + --npu-insts-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) + mkdir -p build/$(MODEL_TYPE)/insts + cp ${@} build/$(MODEL_TYPE)/insts/ + +INSTS_TARGETS += ${IRON_BOTH_INSTS_TARGET} +XCLBIN_TARGETS += ${IRON_BOTH_XCLBIN_TARGET} diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/common.mk b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/common.mk new file mode 100755 index 000000000..06e32a187 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/common.mk @@ -0,0 +1,31 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Created by Alfred + +ifneq ($(filter -j,$(MAKEFLAGS)),) + # Nothing to do; -j is already set +else + MAKEFLAGS += -j8 +endif + +# VITIS related variables (Chess only: ENABLE_CHESSCC=1; Peano builds never expand them) +AIETOOLS_DIR ?= $(or $(AIETOOLS_ROOT),$(patsubst %/bin/,%,$(dir $(shell command -v xchesscc 2>/dev/null)))) +# Expanded only inside the Chess recipes, so it fires only for ENABLE_CHESSCC=1. +AIETOOLS_CHECK = $(if $(strip $(AIETOOLS_DIR)),,$(error ENABLE_CHESSCC=1 needs Vitis AIE Essentials: set AIETOOLS_ROOT (or AIETOOLS_DIR), or put xchesscc on PATH)) +AIE_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/versal_prod/lib +AIE2_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/aie_ml/lib + +AIEOPT_DIR ?= $(shell realpath $(dir $(shell which aie-opt))/..) + +WARNING_FLAGS = -Wno-parentheses -Wno-attributes -Wno-macro-redefined + + +CHESSCCWRAP1_FLAGS = aie $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2_FLAGS = aie2 $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include +CHESSCCWRAP2P_FLAGS = aie2p $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 +PEANOWRAP2_FLAGS = -O2 -v -std=c++20 --target=aie2-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -I ${AIEOPT_DIR}/include +PEANOWRAP2P_FLAGS = -O2 -v -std=c++20 --target=aie2p-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -I ${AIEOPT_DIR}/include diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/host.mk b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/host.mk new file mode 100755 index 000000000..8c74f2381 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/host.mk @@ -0,0 +1,60 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# ============================================================================= +# Llama NPU Library Makefile +# ============================================================================= +# +# Created: 2024 +# +# This Makefile is used to build the Llama NPU library components. +# +# Usage: +# make - Build all targets +# make clean - Remove all built files +# make help - Show this help message +# +# ============================================================================= + +# Linux build environment +# Use g++-13 directly without CMake + +HOST_C_TARGET := run.exe +HOST_COMMON_DIR := ../host_common +CXX := g++-13 +CXX_FLAGS := -std=c++20 -fPIC -Wall +CXX_FLAGS += -DUSE_AVX2=1 +CXX_FLAGS += -mavx2 -march=native -mfma -ffast-math +# the CPU golden reference (cpu_q4_1.hpp) is a full fp32 matmul; thread it +CXX_FLAGS += -fopenmp +CXX_FLAGS += -Ihost +CXX_FLAGS += -I$(HOST_COMMON_DIR) +CXX_FLAGS += -I/opt/xilinx/xrt/include +CXX_FLAGS += -MMD -MP + +LDFLAGS += -L/opt/xilinx/xrt/lib +LDFLAGS += -L$(HOST_COMMON_DIR) +LDFLAGS += -lxrt_coreutil $(HOST_COMMON_DIR)/../../../src/lib/xrt/libaiebu.a +LDFLAGS += -lboost_program_options -lboost_filesystem +LDFLAGS += -fopenmp + +# Find all source files in host/ directory (including subdirectories) +HOST_SOURCES := $(shell find host -name '*.cpp') +HOST_OBJECTS := $(HOST_SOURCES:%.cpp=build/%.o) +HOST_DEPENDS := $(HOST_OBJECTS:.o=.d) + +# Default target +$(HOST_C_TARGET): build/$(HOST_C_TARGET) + cp build/$(HOST_C_TARGET) ./ + +# Link the executable +build/$(HOST_C_TARGET): $(HOST_OBJECTS) + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) $^ -o $@ $(LDFLAGS) + +# Compile source files and generate dependencies +build/%.o: %.cpp + @mkdir -p $(dir $@) + $(CXX) $(CXX_FLAGS) -c $< -o $@ + +# Include dependency files +-include $(HOST_DEPENDS) \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/kernel.mk b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/kernel.mk new file mode 100755 index 000000000..344fb6422 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/kernel.mk @@ -0,0 +1,24 @@ +# common.mk +# This file is licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# Copyright (C) 2024, Advanced Micro Devices, Inc. +# Portions of this file consist of AI-generated content. +# Created by Alfred + +# Kernel stuff +ENABLE_CHESSCC ?= 0 +KERNEL_O_DIR := build/$(MODEL_TYPE)/kernel +KERNEL_SRCS := $(wildcard ${HOME_DIR}/kernel/*.cc) +KERNEL_OBJS := $(patsubst ${HOME_DIR}/kernel/%.cc, ${KERNEL_O_DIR}/%.o, $(KERNEL_SRCS)) +KERNEL_HEADERS := $(wildcard ${HOME_DIR}/kernel/*.h) + +# Build kernels +${KERNEL_O_DIR}/%.o: ${HOME_DIR}/kernel/%.cc ${KERNEL_HEADERS} + mkdir -p ${@D} +ifeq ($(ENABLE_CHESSCC),1) + cd ${@D} && xchesscc_wrapper ${CHESSCCWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} -c $< -o ${@F} +else + cd ${@D} && ${PEANO_INSTALL_DIR}/bin/clang++ ${PEANOWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} -c $< -o ${@F} +endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/mlir_bitstream.mk b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/mlir_bitstream.mk new file mode 100755 index 000000000..9d32acfb5 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/dequant_mm_mix_bfp16/makefiles/mlir_bitstream.mk @@ -0,0 +1,39 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. + +# MLIR stuff + +BITSTREAM_O_DIR := build/bitstream + + +MLIR_BOTH_SRC := $(wildcard ${HOME_DIR}/mlir/*.mlir) +MLIR_BOTH_XCLBIN_TARGET := $(patsubst ${HOME_DIR}/mlir/%.mlir, ${BITSTREAM_O_DIR}/from_mlir/%.xclbin, ${MLIR_BOTH_SRC}) +MLIR_BOTH_INSTS_TARGET := $(patsubst ${HOME_DIR}/mlir/%.mlir, ${BITSTREAM_O_DIR}/from_mlir/%.txt, ${MLIR_BOTH_SRC}) + +AIECC_FLAGS := --aie-generate-cdo --no-compile-host +ifeq ($(ENABLE_CHESSCC),1) +AIECC_FLAGS += --xchesscc --xbridge +else +AIECC_FLAGS += --no-xchesscc --no-xbridge +endif + +# Build xclbin +${BITSTREAM_O_DIR}/from_mlir/%.xclbin: ${HOME_DIR}/mlir/%.mlir ${KERNEL_OBJS} + mkdir -p ${@D} + cp ${KERNEL_OBJS} ${@D} + cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-xclbin \ + --xclbin-name=${@F} $(<:${HOME_DIR}/mlir/%=../../../mlir/%) + mkdir -p build/xclbins + cp ${@} build/xclbins/ + +# Build instructions + +${BITSTREAM_O_DIR}/from_mlir/%.txt: ${HOME_DIR}/mlir/%.mlir + mkdir -p ${@D} + cd ${@D} && aiecc.py -n ${AIECC_FLAGS} --aie-generate-npu-insts \ + --npu-insts-name=${@F} $(<:${HOME_DIR}/mlir/%=../../../mlir/%) + mkdir -p build/insts + cp ${@} build/insts/ + + +INSTS_TARGETS += ${MLIR_BOTH_INSTS_TARGET} +XCLBIN_TARGETS += ${MLIR_BOTH_XCLBIN_TARGET} diff --git a/flm-dev-kit/FLM_Xclbin/kernel_assignment.json b/flm-dev-kit/FLM_Xclbin/kernel_assignment.json index 79547de1e..83e21fe9e 100644 --- a/flm-dev-kit/FLM_Xclbin/kernel_assignment.json +++ b/flm-dev-kit/FLM_Xclbin/kernel_assignment.json @@ -591,7 +591,11 @@ "r2t2:1.7b": { "folder": "Confucius4-R2T2-NPU2", "kernels": { - "layer.xclbin": "xclbins-generic_decoding_layer_QWEN3_ASR_1_7B_MIX" + "attn.xclbin": "xclbins-generic_prefill_attention_attention_DH_128_GQA_1_2", + "audio_gemm.xclbin": "xclbins-bfp16_gemm", + "layer.xclbin": "xclbins-generic_decoding_layer_QWEN3_ASR_1_7B_MIX", + "prefill.xclbin": "xclbins-dequant_mm_mix_bfp16", + "r2t2.switches": "xclbins-r2t2_switches" } }, "whisper-v3:turbo": { diff --git a/flm-dev-kit/FLM_Xclbin/kernel_assignment.md b/flm-dev-kit/FLM_Xclbin/kernel_assignment.md index 0293a581a..6362bb65f 100644 --- a/flm-dev-kit/FLM_Xclbin/kernel_assignment.md +++ b/flm-dev-kit/FLM_Xclbin/kernel_assignment.md @@ -748,13 +748,30 @@ conv1d runs on the host. #### `r2t2:1.7b` → `Confucius4-R2T2-NPU2` -Decode only: the prompt is prefilled on the host (AVX-512), the audio encoder is host code too. Mixed decode weights -(`QWEN3_ASR_1_7B_MIX`): Q4_1 for q/k/o/gate/up and the LM head, Q8_0 for v_proj and down_proj (4-bit everywhere breaks this -fine-tune); the package's `npu_q41.q4nx` holds the Q4_1 copies. `QWEN3_ASR_1_7B` is the all-Q8_0 build (packages without that file). +The prompt prefill's projections (q/k/v, o, up/gate, down) run on `prefill.xclbin`, a 32-core GEMM that reads the decode +weights below in place and multiplies them as block float; the host keeps the norms, RoPE and the last token's LM head. +Prompts of about 384 tokens or more also run their attention on the NPU, the shared prefill attention, inside +`prefill.xclbin`'s hardware context through `r2t2.switches` (shorter ones, or with `QWEN3_ASR_CPU_ATTENTION=1`, keep it +on the host). Without `r2t2.switches`, or with `QWEN3_ASR_NO_SWITCH=1`, `attn.xclbin` runs it in its own context from +about 1024 tokens (switching contexts twice per layer costs more below). Without +`prefill.xclbin`, or with `QWEN3_ASR_CPU_PREFILL=1`, the prompt is prefilled on the host (AVX-512). The audio +encoder's matrix products (conv2/3, conv_out, qkv, o, fc1, fc2, proj1/2) run on `audio_gemm.xclbin`, a 32-core block-float +GEMM for its bf16 weights; the host keeps conv1 (K = 9), LayerNorm and window attention. Without that file, or with +`QWEN3_ASR_CPU_ENCODER=1`, the encoder runs on the host. Mixed +decode weights (`QWEN3_ASR_1_7B_MIX`): Q4_1 for q/k/o/gate/up and the LM head, Q8_0 for v_proj and down_proj (4-bit +everywhere breaks this fine-tune); the package's `npu_q41.q4nx` holds the Q4_1 copies. `QWEN3_ASR_1_7B` is the all-Q8_0 +build (packages without that file). | Kernels | Artifacts | Compiler | |---|---|---| +| `attn.xclbin` | `xclbins-generic_prefill_attention_attention_DH_128_GQA_1_2` | Peano | +| `audio_gemm.xclbin` | `xclbins-bfp16_gemm` | Peano | | `layer.xclbin` | `xclbins-generic_decoding_layer_QWEN3_ASR_1_7B_MIX` | Peano | +| `prefill.xclbin` | `xclbins-dequant_mm_mix_bfp16` | Peano | +| `r2t2.switches` | `xclbins-r2t2_switches` | Peano | + +`r2t2.switches` is not a kernel: it packs the aie2p-launchlib control-packet switches between `prefill.xclbin`'s GEMM and +the attention; see `r2t2_switches/README.md`. ### Whisper diff --git a/flm-dev-kit/FLM_Xclbin/r2t2_switches/Makefile b/flm-dev-kit/FLM_Xclbin/r2t2_switches/Makefile new file mode 100644 index 000000000..6916e34d4 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/r2t2_switches/Makefile @@ -0,0 +1,12 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. +# +# make bitstream the r2t2 control-packet switches -> build/xclbins/ (see build.sh) + +.PHONY: bitstream clean +bitstream: + mkdir -p build/xclbins + bash build.sh build/xclbins + +clean: + rm -rf build diff --git a/flm-dev-kit/FLM_Xclbin/r2t2_switches/README.md b/flm-dev-kit/FLM_Xclbin/r2t2_switches/README.md new file mode 100644 index 000000000..09649adb2 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/r2t2_switches/README.md @@ -0,0 +1,41 @@ + + +# r2t2_switches + +The control-packet switches of the r2t2 engine (`FLM_DLL/detail/qwen3_asr_npu`, `prefill/qwen3_asr_launch.hpp`). + +r2t2's prompt prefill runs its matrix products on `prefill.xclbin` (`dequant_mm_mix_bfp16`). The prompt attention +(`generic_prefill_attention/attention_DH_128_GQA_1_2`) is another kernel; as `attn.xclbin` it needs its own hardware +context, and the two switches per layer between contexts (~2.5 ms each) cost more than the NPU saves below ~1,000 tokens. +With aie2p-launchlib the two kernels are apps of one package and the array switches between them with control packets +inside the prefill hardware context. + +`make bitstream` builds the two kernels as their own units do (kernel objects, IRON design, `aiecc.py` with their flags +plus `--aie-generate-txn`), packs them with `aie2p-launchlib/launchlib/tools/make_package.py`, and runs +`switch_files.cpp` (host only, no NPU or XRT needed) over the package: `build/xclbins/r2t2.switches` holds the cold start +of mm and the switches mm to attn and attn to mm, each as an instruction stream and its control packets. The format is in +`qwen3_asr_launch.hpp` (`R2SW1`). `r2t2_switches_base.xclbin` is the mm build's xclbin, there because every unit's output +needs an xclbin; nothing ships it. The mm build's RTP addresses are those of `dequant_mm_mix_bfp16` in +`rtp_addresses.lock.txt`, so the engine's prefill sequences are valid after `cold_mm`. + +`kernel_assignment.json` places `r2t2.switches` in the `Confucius4-R2T2-NPU2` folder next to `prefill.xclbin`. The engine +uses it when it is there: the attention of prompts from 384 tokens then runs on the NPU, one submission per layer +(`cold_mm`, switch, attention, switch back as one `xrt::runlist`), under the same system-wide lock as d3's switches +(flock on `$TMPDIR/flm_d3_array.lock`, a named mutex on Windows), so the two engines' windows never interleave. +`QWEN3_ASR_NO_SWITCH=1` turns it off (then `attn.xclbin` in its own context, from 1,024 tokens); +`QWEN3_ASR_NPU_ATTENTION_MIN` moves the threshold. Without the file nothing changes. + +Measured (Ryzen AI 9 HX 370, Linux, prompt attention of all 28 layers / whole prefill): + +| prompt tokens | CPU attention | `attn.xclbin`, own context | switches | +|---:|---:|---:|---:| +| 512 | 53 / 233 ms | 93 / 346 ms | 42 / 209 ms | +| 1,152 | 189 / 590 ms | 151 / 575 ms | 103 / 458 ms | +| 2,048 | 693 / 1,334 ms | 271 / 919 ms | 222 / 815 ms | + +The output tokens are the same as with `attn.xclbin` in its own context (the same kernel). + +Not covered: HRX (the engine falls back to `attn.xclbin`). diff --git a/flm-dev-kit/FLM_Xclbin/r2t2_switches/build.sh b/flm-dev-kit/FLM_Xclbin/r2t2_switches/build.sh new file mode 100644 index 000000000..0c15da5e2 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/r2t2_switches/build.sh @@ -0,0 +1,51 @@ +#!/bin/bash +# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +# Portions of this file consist of AI-generated content. +# +# The control-packet switches of r2t2 (see ../../FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_launch.hpp): the +# prompt prefill's mm kernel and the prefill attention kernel, built as aie2p-launchlib packages, and from them one +# warm switch per ordered pair (instruction stream + control packets), packed into one file, r2t2.switches. +# +# build.sh out/: r2t2.switches, r2t2_switches_base.xclbin (the mm build's xclbin) +# +# Every app is built as its own unit builds it (the unit's `make kernel`, its IRON design, aiecc with the unit's +# bitstream.mk flags) plus --aie-generate-txn; the toolchain is the one on PATH (the aie-build image, or the +# environment of FLM_Xclbin/README.md). The mm app is dequant_mm_mix_bfp16 (prefill.xclbin): the switches load it +# cold (cold_mm), so the engine's base hardware context only has to be that unit's xclbin, which has the same +# partition. +set -euo pipefail +HERE=$(cd "$(dirname "$0")" && pwd) +X=$(cd "$HERE/.." && pwd) +LL=$(cd "$X/../aie2p-launchlib/launchlib" && pwd) +OUT=$(mkdir -p "$1" && cd "$1" && pwd) +WORK=$HERE/build/work +FLAGS="--aie-generate-cdo --no-compile-host --no-xchesscc --no-xbridge" + +# build_one APP UNIT IRON_SCRIPT EXTRA_AIECC_FLAGS +build_one() { + local app=$1 unit=$X/$2 script=$3 extra=${4:-} + local out=$WORK/$app + echo "== $app ($2)" + (cd "$unit" && rm -rf build && make kernel) + mkdir -p "$out" + python3 "$unit/iron/$script" > "$out/design.mlir" + cp "$unit"/build/*/kernel/*.o "$out/" 2>/dev/null || cp "$unit"/build/kernel/*.o "$out/" + (cd "$out" && aiecc.py $FLAGS $extra --aie-generate-xclbin --xclbin-name="$app.xclbin" \ + --aie-generate-txn --txn-name="${app}_txn.mlir" design.mlir) + # aiecc names the ELFs main_core_C_R.elf; make_package.py wants core_C_R.elf + for f in "$out"/design.mlir.prj/main_core_*.elf; do ln -sf "$(basename "$f")" "$out/design.mlir.prj/${f##*/main_}"; done +} + +rm -rf "$WORK" && mkdir -p "$WORK" +build_one mm dequant_mm_mix_bfp16 dequant_mm_aie.py +build_one attn generic_prefill_attention/attention_DH_128_GQA_1_2 attn_aie.py + +python3 "$LL/tools/make_package.py" -o "$WORK/pkg" mm="$WORK/mm" attn="$WORK/attn" + +# The switch generator needs no NPU and no XRT. +${CXX:-g++} -std=c++20 -O2 -Wall -I "$LL/include" -I "$X/../FLM_DLL/include" "$HERE/switch_files.cpp" -o "$WORK/switch_files" +"$WORK/switch_files" --package "$WORK/pkg" --out "$OUT" --apps mm,attn + +# The base xclbin the switches were built against (the engine's mm context is this unit's xclbin). +cp "$WORK/mm/mm.xclbin" "$OUT/r2t2_switches_base.xclbin" +ls -l "$OUT" diff --git a/flm-dev-kit/FLM_Xclbin/r2t2_switches/switch_files.cpp b/flm-dev-kit/FLM_Xclbin/r2t2_switches/switch_files.cpp new file mode 100644 index 000000000..82aa58365 --- /dev/null +++ b/flm-dev-kit/FLM_Xclbin/r2t2_switches/switch_files.cpp @@ -0,0 +1,68 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. +// Portions of this file consist of AI-generated content. +// +// switch_files.cpp : write the aie2p-launchlib switches of a package for the r2t2 engine (no NPU, no XRT). +// switch_files --package DIR --out DIR --apps mm,attn +// Writes OUT/r2t2.switches: per kernel its instruction stream (the engine turns it into an ELF with aiebu) and +// control packets (XRT argument 3 + packet_arg). Kernels: cold_, and _then_ for every ordered pair. +#include "launch/launch.hpp" + +#include +#include +#include +#include +#include +#include +#include + +static std::vector split(const std::string &s) { + std::vector v; + std::stringstream ss(s); + for (std::string t; std::getline(ss, t, ',');) v.push_back(t); + return v; +} + +int main(int argc, char **argv) { + std::string package, out, apps_arg = "mm,attn"; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string o = argv[i]; + if (o == "--package") package = argv[i + 1]; + else if (o == "--out") out = argv[i + 1]; + else if (o == "--apps") apps_arg = argv[i + 1]; + } + try { + const auto apps = split(apps_arg); + std::vector cfg{launch::cold(apps[0])}; + for (auto &a : apps) + for (auto &b : apps) + if (a != b) cfg.push_back(launch::warm(a, b)); + launch::ConfigList list{package, launch::Transport::ctrlpkt, cfg}; + const auto none = [](launch::Rt &) {}; + launch::SequenceMap seqs; + for (auto &a : apps) seqs[a] = none; + const launch::Result r = launch::build(list, seqs); + // r2t2.switches: "R2SW1\n", per kernel "name packet_arg txn_bytes pkt_bytes\n", "END\n", then the blobs in + // that order (txn, pkt, ...); read by FLM_DLL/detail/qwen3_asr_npu/prefill/qwen3_asr_launch.hpp (load_file). + // packet_arg: XRT argument 3 + packet_arg takes the packet buffer. + std::string head = "R2SW1\n"; + for (const launch::Kernel &k : r.kernels) { + head += k.name + " " + std::to_string(k.packet_arg) + " " + std::to_string(k.words.size() * 4) + " " + + std::to_string(k.packets.size() * 4) + "\n"; + std::printf("%-18s txn %6zu B packets %6zu B packet_arg %d\n", k.name.c_str(), k.words.size() * 4, + k.packets.size() * 4, k.packet_arg); + } + head += "END\n"; + std::ofstream f(out + "/r2t2.switches", std::ios::binary); + f.write(head.data(), head.size()); + for (const launch::Kernel &k : r.kernels) { + f.write((const char *)k.words.data(), k.words.size() * 4); + f.write((const char *)k.packets.data(), k.packets.size() * 4); + } + f.close(); + if (!f) throw std::runtime_error("cannot write " + out + "/r2t2.switches"); + return 0; + } catch (const std::exception &e) { + std::cerr << "error: " << e.what() << "\n"; + return 1; + } +} diff --git a/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt b/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt index 1c69d35ba..0b15b04de 100644 --- a/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt +++ b/flm-dev-kit/FLM_Xclbin/rtp_addresses.lock.txt @@ -486,6 +486,106 @@ RTP_L_attn_qk_core_2_5 57344 RTP_L_attn_qk_core_4_4 57344 RTP_L_attn_qk_core_4_5 57344 +[xclbins-bfp16_gemm/rtp_addresses.txt] +rtp_2_0 58112 +rtp_2_1 58112 +rtp_2_2 58112 +rtp_2_3 58112 +rtp_2_4 58112 +rtp_2_5 58112 +rtp_2_6 58112 +rtp_2_7 58112 +rtp_3_0 58112 +rtp_3_1 58112 +rtp_3_2 58112 +rtp_3_3 58112 +rtp_3_4 58112 +rtp_3_5 58112 +rtp_3_6 58112 +rtp_3_7 58112 +rtp_4_0 58112 +rtp_4_1 58112 +rtp_4_2 58112 +rtp_4_3 58112 +rtp_4_4 58112 +rtp_4_5 58112 +rtp_4_6 58112 +rtp_4_7 58112 +rtp_5_0 58112 +rtp_5_1 58112 +rtp_5_2 58112 +rtp_5_3 58112 +rtp_5_4 58112 +rtp_5_5 58112 +rtp_5_6 58112 +rtp_5_7 58112 + +[xclbins-dequant_mm_mix_bfp16/rtp_addresses.txt] +K_div_k_2_0 53760 +K_div_k_2_1 53760 +K_div_k_2_2 53760 +K_div_k_2_3 53760 +K_div_k_2_4 53760 +K_div_k_2_5 53760 +K_div_k_2_6 53760 +K_div_k_2_7 53760 +K_div_k_3_0 61952 +K_div_k_3_1 61952 +K_div_k_3_2 61952 +K_div_k_3_3 61952 +K_div_k_3_4 61952 +K_div_k_3_5 61952 +K_div_k_3_6 61952 +K_div_k_3_7 61952 +K_div_k_4_0 53760 +K_div_k_4_1 53760 +K_div_k_4_2 53760 +K_div_k_4_3 53760 +K_div_k_4_4 53760 +K_div_k_4_5 53760 +K_div_k_4_6 53760 +K_div_k_4_7 53760 +K_div_k_5_0 61952 +K_div_k_5_1 61952 +K_div_k_5_2 61952 +K_div_k_5_3 61952 +K_div_k_5_4 61952 +K_div_k_5_5 61952 +K_div_k_5_6 61952 +K_div_k_5_7 61952 +rtp_act_2_0 53824 +rtp_act_2_1 53824 +rtp_act_2_2 53824 +rtp_act_2_3 53824 +rtp_act_2_4 53824 +rtp_act_2_5 53824 +rtp_act_2_6 53824 +rtp_act_2_7 53824 +rtp_act_3_0 62016 +rtp_act_3_1 62016 +rtp_act_3_2 62016 +rtp_act_3_3 62016 +rtp_act_3_4 62016 +rtp_act_3_5 62016 +rtp_act_3_6 62016 +rtp_act_3_7 62016 +rtp_act_4_0 53824 +rtp_act_4_1 53824 +rtp_act_4_2 53824 +rtp_act_4_3 53824 +rtp_act_4_4 53824 +rtp_act_4_5 53824 +rtp_act_4_6 53824 +rtp_act_4_7 53824 +rtp_act_5_0 62016 +rtp_act_5_1 62016 +rtp_act_5_2 62016 +rtp_act_5_3 62016 +rtp_act_5_4 62016 +rtp_act_5_5 62016 +rtp_act_5_6 62016 +rtp_act_5_7 62016 + [xclbins-generic_decoding_layer_LLAMA_3_1_8B/rtp_addresses.txt] RTP_L_attn_kv_core_3_3 34816 RTP_L_attn_kv_core_3_4 34816 diff --git a/src/lib/hrx/libqwen3_asr_npu.so b/src/lib/hrx/libqwen3_asr_npu.so index 6e5504eb7..93e84d4bf 100644 Binary files a/src/lib/hrx/libqwen3_asr_npu.so and b/src/lib/hrx/libqwen3_asr_npu.so differ diff --git a/src/lib/hrx/qwen3_asr_npu.dll b/src/lib/hrx/qwen3_asr_npu.dll index 6900b9118..e0dfe9258 100644 Binary files a/src/lib/hrx/qwen3_asr_npu.dll and b/src/lib/hrx/qwen3_asr_npu.dll differ diff --git a/src/lib/hrx/qwen3_asr_npu.lib b/src/lib/hrx/qwen3_asr_npu.lib index 25b3c6b5c..7fbe33839 100644 Binary files a/src/lib/hrx/qwen3_asr_npu.lib and b/src/lib/hrx/qwen3_asr_npu.lib differ diff --git a/src/lib/xrt/libqwen3_asr_npu.so b/src/lib/xrt/libqwen3_asr_npu.so index e85a790f2..0d63bbd5f 100644 Binary files a/src/lib/xrt/libqwen3_asr_npu.so and b/src/lib/xrt/libqwen3_asr_npu.so differ diff --git a/src/lib/xrt/qwen3_asr_npu.dll b/src/lib/xrt/qwen3_asr_npu.dll index b60c06f8e..51c1eecfd 100644 Binary files a/src/lib/xrt/qwen3_asr_npu.dll and b/src/lib/xrt/qwen3_asr_npu.dll differ diff --git a/src/lib/xrt/qwen3_asr_npu.lib b/src/lib/xrt/qwen3_asr_npu.lib index f12605d41..1e5c973e9 100644 Binary files a/src/lib/xrt/qwen3_asr_npu.lib and b/src/lib/xrt/qwen3_asr_npu.lib differ diff --git a/src/xclbins/Confucius4-R2T2-NPU2/attn.xclbin b/src/xclbins/Confucius4-R2T2-NPU2/attn.xclbin new file mode 100644 index 000000000..db68c86d8 Binary files /dev/null and b/src/xclbins/Confucius4-R2T2-NPU2/attn.xclbin differ diff --git a/src/xclbins/Confucius4-R2T2-NPU2/audio_gemm.xclbin b/src/xclbins/Confucius4-R2T2-NPU2/audio_gemm.xclbin new file mode 100644 index 000000000..76e70e800 Binary files /dev/null and b/src/xclbins/Confucius4-R2T2-NPU2/audio_gemm.xclbin differ diff --git a/src/xclbins/Confucius4-R2T2-NPU2/layer.xclbin b/src/xclbins/Confucius4-R2T2-NPU2/layer.xclbin index c4ef255a1..04f292b25 100644 Binary files a/src/xclbins/Confucius4-R2T2-NPU2/layer.xclbin and b/src/xclbins/Confucius4-R2T2-NPU2/layer.xclbin differ diff --git a/src/xclbins/Confucius4-R2T2-NPU2/prefill.xclbin b/src/xclbins/Confucius4-R2T2-NPU2/prefill.xclbin new file mode 100644 index 000000000..d4e76c8c8 Binary files /dev/null and b/src/xclbins/Confucius4-R2T2-NPU2/prefill.xclbin differ diff --git a/src/xclbins/Confucius4-R2T2-NPU2/r2t2.switches b/src/xclbins/Confucius4-R2T2-NPU2/r2t2.switches new file mode 100644 index 000000000..5d859795a Binary files /dev/null and b/src/xclbins/Confucius4-R2T2-NPU2/r2t2.switches differ