[PR #4114] [Engine] Native RDNA4 (gfx1201) NVFP4 engine (--gfx1201-nvfp4) #4905

Open
opened 2026-11-07 16:31:14 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/4114
Author: @dimitri91209
Created: 10/25/2026
Status: 🔄 Open

Base: main ← Head: feat/gfx1201-flydsl-nvfp4


📝 Commits (1)

  • b5e1887 feat(gfx1201-nvfp4): add native RDNA4 (gfx1201) ModelOpt NVFP4 inference engine for Qwen3.8-Flash-Next

📊 Changes

21 files changed (+58689 additions, -7 deletions)

View changed files

📝 CMakeLists.txt (+31 -5)
➕ include/strata/artifact/qwen_tokenizer.hpp (+283 -0)
➕ include/strata/artifact/safetensors_reader.hpp (+77 -0)
➕ include/strata/core/nvfp4_engine.hpp (+439 -0)
➕ include/strata/kernels/cpu/nvfp4_modelopt.hpp (+117 -0)
➕ include/strata/kernels/gfx1201_nvfp4_kernels.hpp (+66 -0)
➕ include/strata/kernels/nvfp4_mtp_kernels.hpp (+361 -0)
➕ include/strata/program/nvfp4_generate.hpp (+8 -0)
➕ include/strata/spec/nvfp4_ngram_drafter.hpp (+75 -0)
➕ scripts/compile_deepseek_kernels.py (+2340 -0)
📝 serve/server.py (+38 -0)
➕ src/core/nvfp4_engine.cpp (+3471 -0)
➕ src/kernels/cpu/nvfp4_modelopt_avx2.cpp (+352 -0)
➕ src/kernels/cpu/nvfp4_modelopt_avx512.cpp (+411 -0)
➕ src/kernels/cpu/nvfp4_modelopt_pool.cpp (+313 -0)
➕ src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp (+48626 -0)
➕ src/kernels/cuda/gfx1201_nvfp4_kernels.cpp (+160 -0)
📝 src/program/generate.cpp (+32 -0)
➕ src/program/nvfp4_generate.cpp (+799 -0)
➕ src/spec/nvfp4_ngram_drafter.cpp (+685 -0)

...and 1 more files

📄 Description

Draft PR (Work in Progress) — Native RDNA4 (gfx1201) ModelOpt NVFP4 inference engine for Qwen3.8-Flash-Next-NVFP4, including 102 precompiled pure-FlyDSL .hsaco device kernels, cooperative 1-barrier LDS Mega-mHC + Layer-0 uniform-stream fusion, native Multi-Token Prediction (MTP) + DSpark hardware-aware speculative decoding, Native Sparse Attention (NSA) sink/window pinning + 16-pass 4-ary radix top-k block selection with 100% VRAM-resident elastic 1M-context block keys, 42 MiB 4-way set-associative Layer-1 PLE cache with fused FP8 dequant+GEMV, and 3-tier adaptive VRAM/PCIe/AVX-512_BF16 MoE execution.


1. Overview

This PR adds a standalone, zero-external-dependency RDNA4 (gfx1201) ModelOpt NVFP4 inference engine (--gfx1201-nvfp4 / --nvfp4 / --safetensors, plus automatic .safetensors directory detection under --native, --model, or --pack) for Qwen3.8-Flash-Next-NVFP4 (qwen4_exp: 48 layers = 36 Gated DeltaNet [GDN] + 12 Qwen Sparse Attention [QSA], 4-stream Hyper-Connections [mHC], 512 NVFP4 routed experts + 1 BF16 shared expert per layer, Layer-1 Per-Layer Embedding [PLE] N-gram lookup, and a native 49th Multi-Token Prediction [MTP] layer with 512 FP8 routed experts).

All additions are strictly opt-in behind STRATA_ENABLE_HIP and leave existing CUDA/GGUF/CPU paths untouched when --gfx1201-nvfp4 is not selected.


2. Complete Summary of Additions & Modifications Over main (21 files)

Target / Subsystem File Path Status Lines Description
Build System CMakeLists.txt Modified +31 / -5 Wires gfx1201_nvfp4_hsaco.cpp & gfx1201_nvfp4_kernels.cpp into strata_kernels (STRATA_ENABLE_HIP), nvfp4_engine.cpp into strata_engine, nvfp4_generate.cpp (STRATA_HAVE_GFX1201_NVFP4=1) into strata, nvfp4_ngram_drafter.cpp into strata_spec, and nvfp4_modelopt_{avx512,avx2,pool}.cpp into strata_kernels_cpu (with -mavx512bf16 on nvfp4_modelopt_avx512.cpp).
Artifact & Tokenizer include/strata/artifact/safetensors_reader.hpp Added +77 Zero-copy JSON header parser (TensorSlice index) and aligned pread_exact helper for multi-shard .safetensors checkpoints.
Artifact & Tokenizer include/strata/artifact/qwen_tokenizer.hpp Added +283 Standalone GPT-2 byte-level BPE + special-token Qwen tokenizer (vocab.json + merges.txt / tokenizer.json / tokens.bin) for CLI mode.
GPU Kernel Runtime include/strata/kernels/gfx1201_nvfp4_kernels.hpp Added +66 EmbeddedKernelDesc descriptor struct, PleConsts, and Gfx1201KernelCache lazy hipModuleLoadData / hipModuleLaunchKernel cache with optional per-kernel HIP event profiling.
GPU Kernel Runtime src/kernels/cuda/gfx1201_nvfp4_kernels.cpp Added +160 Implementation of Gfx1201KernelCache: on-demand loading of embedded .hsaco ELF images via hipModuleLoadData, default-grid dispatch, and STRATA_NVFP4_PROFILE timing aggregation.
GPU Kernel Runtime src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp Added +48,626 102 precompiled RDNA4 (gfx1201) FlyDSL .hsaco device binaries (alignas(64) const uint8_t kHsaco_0[]..kHsaco_101[]) embedded directly as C++ byte arrays — zero Python, ROCm-LLVM, or FlyDSL dependency at build or run time.
GPU Kernel Runtime include/strata/kernels/nvfp4_mtp_kernels.hpp Added +361 Host launch wrappers for all fused DeepSeek MTP, DSpark confidence/margin argmax, NSA/QSA sink+window block scoring, strided/out-of-place GDN, batched PLE state update, and auto-dispatched M=1..16+ BF16 GEMV/GEMM kernels.
GPU Kernel Runtime scripts/compile_deepseek_kernels.py Added +2,340 Standalone offline compiler script that builds all 102 FlyDSL gfx1201 .hsaco kernels (including cooperative 1-barrier LDS Mega-mHC, fused Layer-0 embed_hc_premix_*_l0, fused ple_dequant_gemv_*, and 16-pass 4-ary radix qsa_topk_blocks) and embeds them into src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp.
CPU Expert Pool include/strata/kernels/cpu/nvfp4_modelopt.hpp Added +117 Data structures (CpuExpertJob, kMaxJobToks = 64), per-expert byte offsets for NVFP4 (618,240 B) and MTP FP8 (4,916,288 B), and Nvfp4CpuPool persistent thread-pool interface.
CPU Expert Pool src/kernels/cpu/nvfp4_modelopt_avx512.cpp Added +411 Zen 4 AVX-512 VNNI + AVX-512_BF16 CPU expert kernels: vpdpbusd int8$\times$uint8 dot products, hardware _mm512_cvtneps_pbh BF16 rounding (bf16_round16_avx512), 16-wide Cody-Waite exp_neg16_avx512, 16-wide swiglu16_bf16_avx512, and register-decoded FP8 (e4m3fn) MTP expert kernels (gu_tile32_fp8_avx512, down_tile80_decode_fp8_avx512).
CPU Expert Pool src/kernels/cpu/nvfp4_modelopt_avx2.cpp Added +352 Portable AVX2 + FMA + F16C fallback implementation of all NVFP4 and FP8 CPU expert kernels for CPUs without AVX-512 VNNI/BF16.
CPU Expert Pool src/kernels/cpu/nvfp4_modelopt_pool.cpp Added +313 Runtime CPUID dispatcher (__builtin_cpu_supports checking avx512f/bw/vl/dq/vnni/bf16) and lock-free atomic work-stealing thread pool pinned to physical CPU cores (strata::kernels::cpu::physical_cores).
CPU ISA Guard tools/check_isa_guard.py Modified +5 / -2 Registers nvfp4_modelopt_avx512.cpp (WIDE_OBJECTS), nvfp4_modelopt_avx2.cpp (INIT_FREE_OBJECTS), and the 6 public *_avx512 entry points (WIDE_PUBLIC). Verified 0 violations across both libstrata_kernels_cpu.a and strata.
Speculative Drafter include/strata/spec/nvfp4_ngram_drafter.hpp Added +75 Nvfp4NgramDrafter interface: multi-order 5/4/3/2/1-gram hash index, DSpark online survival calibration, and hardware-cost-aware prefix scheduler.
Speculative Drafter src/spec/nvfp4_ngram_drafter.cpp Added +685 DSpark (2607.05147) Speculative Scheduler: Algorithm 1 throughput optimizer R(m) = (1 + \sum_{k=1}^m S(k)) / T_{\text{verify}}(1+m), Eq. 11 causal survival EMA calibration, target confidence/margin conditioning, and rejection memory.
Core NVFP4 Engine include/strata/core/nvfp4_engine.hpp Added +439 Qwen4ExpGfx1201Engine class declaration, weight structures (Nvfp4HcWeights, Nvfp4GdnWeights, Nvfp4QsaWeights, Nvfp4MoeWeights, Nvfp4PleWeights, Nvfp4MtpWeights), 42 MiB 4-way set-associative PleCacheEntry table, and VmmRange arenas.
Core NVFP4 Engine src/core/nvfp4_engine.cpp Added +3,471 Complete 48-layer + MTP inference engine: parallel .safetensors loader, selective .hsaco module preloading, 3-tier MoE execution + 2-pass accepted-prefix VRAM victim cache, 1M-context tiered NVFP4 KV cache with 100% VRAM-resident elastic block keys, out-of-place GDN verification checkpointing, 4-way Layer-0 overlapped PLE cache, and native MTP neural drafting.
CLI & Serve Runner include/strata/program/nvfp4_generate.hpp Added +8 Declares strata::program::run_nvfp4(int argc, char** argv).
CLI & Serve Runner src/program/nvfp4_generate.cpp Added +799 CLI & --serve IPC loop (INFO, READY, GEN, RESUME, PP, T, DONE, VRAM, STOP, QUIT), hybrid N-gram + neural MTP speculative decoding loop, and lossless point-mass speculative rejection sampling.
CLI Entrypoint src/program/generate.cpp Modified +32 Dispatches --gfx1201-nvfp4, --nvfp4, --safetensors, or .safetensors-only model directories to strata::program::run_nvfp4.
HTTP Server serve/server.py Modified +38 Preserves <think>...</think> reasoning blocks across multi-turn tool-call rounds when keep_Earlier_thinking is active and updates _last_conv_ids on normal finish == "stop" turns for instant multi-turn KV prefix reuse.

3. Detailed Technical Architecture

3.1 102 Embedded Pure-FlyDSL RDNA4 (gfx1201) Kernels (src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp)

All 102 GPU kernels are compiled directly to native RDNA4 (gfx1201) machine code via FlyDSL (v_wmma_f32_16x16x16_bf16, wave32 DPP/permute reductions, software-pipelined LDS double-buffering) and embedded in gfx1201_nvfp4_hsaco.cpp (with 9 superseded legacy kernels skipped during hipModuleLoadData startup preload to save ~18 MiB of 2 MiB-aligned HIP module code pages in VRAM):

  • Automatic Multi-Row BF16 Linear Dispatch (launch_nvfp4_linear_auto & launch_nvfp4_lm_head_auto):
    • M = 1: wave32-coalesced bf16_gemv_<N>_<K> (1856x2560, 2560x640, 2560x2560, 2560x6144, 10240x2560, 12800x2560, 13952x2560, 16480x2560, 248320x2560).
    • 2 \le M \le 4: wave32-coalesced 4-row bf16_gemv_m4_<N>_<K> reading the weight matrix once across up to 4 tokens in registers.
    • 5 \le M \le 8 (LM Head): wave32-coalesced 8-row bf16_gemv_m8_248320_2560 reading the 1.271 GB lm_head.weight once for up to 8 tokens.
    • M > 8 (LM Head) / M > 4 (Dense): 16-row RDNA4 WMMA tile GEMMs bf16_linear_<N>_<K> (including bf16_linear_248320_2560), allowing verification batches up to M = 16 per chunk to read lm_head.weight in a single pass.
  • 1-Barrier 0.0-ULP Bit-Exact Cooperative LDS Mega-mHC (hc_premix_decode_c0/c1_u0/u1 & hc_premix_c0/c1_u0/u1) & Layer-0 Uniform-Stream Fusion (embed_hc_premix_decode_l0 & embed_hc_premix_l0):
    • Stream-Per-Wave Preload (s_w = wave for wave = 0..3, 128 threads/WG): Each wave loads all 10 chunks (2,560 elements) of stream s_w with zero wave divergence, accumulates sq_w in the exact sequential order j = 0..9, e = 0..7 for 0.0-ULP bit-exact RSTD, XO, H, and INJ, and synchronizes via a single gpu.barrier() per launch (down from 8 barriers).
    • Occupancy-Optimal Packed BF16 LDS Layouts: hc_premix_decode_c* (T = 1 decode, grid = (81/80, 1, 1)) stages packed BF16 (xv, nv) pairs in 40 KiB LDS (Int32[10240], 3 workgroups/WGP = 96 > 81 concurrent blocks on GPU, eliminating all NW global loads in the WD loop); hc_premix_c* (M >= 1 batched verify, grid = (81/80, M, 1)) stages packed BF16 (xv[2p], xv[2p+1]) pairs in 20 KiB LDS (Int32[5120]), doubling WGP occupancy to 6 workgroups/WGP (192 concurrent workgroups across 32 WGPs) and accelerating batched verification by 1.78x–1.98x at $M = 8..15$ (64.62 us -> 36.26 us at M=8, 91.44 us -> 46.07 us at M=12, 112.29 us -> 59.17 us at M=15).
    • First-Layer (l == 0 attn_hc) Uniform-Stream Fusion (embed_hc_premix_decode_l0 & embed_hc_premix_l0): Exploits the Layer-0 invariant X_{0,0} = X_{0,1} = X_{0,2} = X_{0,3} = E[\text{token\_id}] (has_prev_update = false) to fuse embed_hc_gather directly into Layer 0 attn_hc hc_premix on both decode and batched verify/prefill. Only Wave 0 loads E[token_id] (5 KiB per token instead of 20 KiB 4-stream global write + 20 KiB 4-stream global read), computes rstd once, and stages E[token_id] into 5 KiB LDS while blk == 0 writes all 4 streams of X and RSTD (44.55 us -> 26.22 us [1.70x] at $T = 1$, 50.46 us -> 30.95 us [1.63x] at $M = 4$, 49.52 us -> 30.54 us [1.62x] at $M = 8$, 0.0-ULP bit-exact).
  • Strided & Out-of-Place Fused Gated DeltaNet (gated_deltanet_fused_strided) & Strided Shared-Expert SiLU (silu_mul_640_strided):
    • gated_deltanet_fused_strided reads QKV [10240], Z [6144], A [48], B [48] directly from the fused [M, 16480] projection buffer via in_stride = 16480, eliminating all 36 gdn_proj_split kernel launches per batch, and supports separate S_IN and S_OUT ([48, 128, 128] FP32 = 3 MiB/layer, 108 MiB across 36 layers) so speculative verification writes updated recurrent states out-of-place to d_gdn_state_ckpt_. This reduces save_recurrent_ckpt() from 112.39 MiB (0.42 ms) to 4.39 MiB (0.014 ms, 25.6$\times$ smaller) and makes full-acceptance state commit an O(1) std::swap (0.000 ms).
    • silu_mul_640_strided reads sh_gate [640] and sh_up [640] directly from d_proj_scratch_ with in_stride = 1856, eliminating all 48 moe_sh_gu_extract launches per verification/prefill batch.
  • Batched 5-in-1 QSA Prep + NVFP4 KV Cache Write (qsa_prep_and_cache_write_batch_nvfp4):
    • Fuses qsa_proj_split + qsa_q_extract + Q qk_norm_partial_rope + K qk_norm_partial_rope + tiered NVFP4 K_CACHE/V_CACHE quantization and RAW_K_CACHE write into 1 launch (grid = (4, M, 1)), replacing 60 kernel launches per verification/prefill batch with 12.
  • Native Sparse Attention (NSA 2502.11089) Tiered Block Scorer (qsa_score_blocks_tiered_pinned & qsa_score_blocks_batched), 16-Pass 4-Ary Radix qsa_topk_blocks, & Elastic 1M-Context VRAM Block Keys:
    • 100% VRAM-Resident Elastic Block-Key Mirror (P3-1): Decouples vram_blocks_ from vram_cap_ / 4 (vram_blocks_ = max_blocks_ = 262,144 blocks = 1,048,576 tokens when HIP VMM kv_vmm_ok_ == true, mapping init_bk_blks = (init_vram_seq + 3) / 4 at pos = 0 and elastically growing in 2 MiB VMM chunks in ensure_context_capacity()), keeping qsa_score_blocks_tiered_pinned and qsa_score_blocks_batched 100% VRAM-resident (512 GB/s) up to 1M context while preserving 7,013 hot experts in VRAM at startup.
    • Fused Sink + Sliding-Window Pinning & nb <= 512 Bypass: Fuses initial attention sink (16 blocks = 64 tokens) and local sliding-window (64 blocks = 256 tokens) score pinning directly into the block-key scorer in registers (eliminating all 12 qsa_pin_sink_and_window launches per decode token), and skips launching qsa_score_blocks_tiered_pinned / qsa_score_blocks_batched across all 12 QSA layers on the host when nb <= 512 (pos < 2048).
    • 16-Pass 4-Ary Radix qsa_topk_blocks & 1M-Context Prefix-Sum Fix (P3-2): Replaces the 31-pass binary threshold search (62 barriers) with a 1-pass bypass when nb <= 512, a 1-load-pass VGPR register-cached (s_reg[0..15], bounds-clamped bi_safe) 16-pass 4-ary radix search (c1, c2, c3 testing 2 bits/pass packed into 3×10-bit Int32 reductions with 1 barrier/pass = 16 barriers total) for 512 < nb <= 8192 (pos <= 32,768), a 16-pass 4-ary radix multi-chunk search for nb > 8192, and 10-bit ng (& 0x3FF) / 21-bit ne (<< 10) Hillis-Steele prefix-sum packing supporting up to 2,097,151 blocks (8.38M tokens > 1M max context) without overflow (88.78 us -> 18.84 us [4.71x] at pos = 16,000, 124.48 us -> 18.83 us [6.61x] at pos = 32,000, 176.62 us -> 152.16 us [1.16x] at pos = 64,000).
    • qsa_block_keys_from_batch + qsa_refresh_raw_k_tail eliminate RAW_K_CACHE 1024-token ring buffer wrap-around for arbitrary prefill chunk sizes (M \le 4096).
  • Engram / Layer-1 PLE 42 MiB 4-Way Set-Associative Cache, Layer-0 Async Overlap, Fused ple_dequant_gemv_12800_2560 & ple_dequant_gemv_m4_12800_2560, & ple_state_update_batch:
    • 4-Way Set-Associative Zipfian Cache (42 MiB) & Layer-0 Overlap (P3-4): Expands ple_cache_ in Host RAM from 4,096 direct-mapped slots (672 KiB) to 65,536 sets \times 4 ways (262,144 entries = 42 MiB), pre-populated during prefill and asynchronously prefetched + uploaded (hipMemcpyAsync) in Layer 0 immediately after moe_decode_down / moe_down so host lookup and PCIe H2D transfer overlap with Layer 0 moe_merge_routed without delaying run_cpu_moe_layer(0).
    • Fused FP8 Dequant + K/V Projection (ple_dequant_gemv_12800_2560 & ple_dequant_gemv_m4_12800_2560): Fuses ple_embed_dequant (fp8_e4m3 * scale -> bf16 in registers) directly into the Layer-1 PLE K/V projection on both T = 1 decode (kHsaco_98, 41.07 us -> 39.24 us) and M = 1..4 batched verification (kHsaco_99, writing separate row-strided OutK [M, 10240] and OutV [M, 2560] buffers and replacing 3 launches in step_prefill_batch with 1 launch: 64.97 us -> 53.10 us [-11.87 us faster] at $M = 4$, 0.000000 bit-exact).
    • Batched Conv State Update (ple_state_update_batch): Updates the [9, 10240] BF16 Layer-1 PLE causal conv state across all M tokens in a single launch (grid = (40, 1, 1)), eliminating the serial $M$-launch loop.
  • Fused Tiered NVFP4 Sink + Sliding-Window Decode Attention for MTP (qsa_swa_sink_decode_fused_nvfp4):
    • Single-launch Flash-Decoding over the 64 initial sink tokens + 1,024-token sliding window with fused output sigmoid gating (grid = (24, 1, 1)), keeping MTP attention latency constant at ~25 us even at 50k–1M context.
  • Single-Pass Target & Pruned-Vocab Argmax + Softmax Probability + Top-2 Margin (argmax_prob_margin_248320, mtp_dvocab_gemv, argmax_prob_margin_dvocab):
    • Computes exact online log-sum-exp softmax probability p_1 and top-1/top-2 logit margin z_{(1)} - z_{(2)} in a single pass for DSpark confidence gating, and provides a 6.1x faster 40,525-token pruned + dynamic context vocabulary head for MTP drafting.

3.2 Three-Tier Adaptive MoE Execution (VRAM + Zero-Copy PCIe + 16-Core AVX-512_BF16 CPU Pool)

  • Profile-Guided VRAM Placement + Two-Pass Accepted-Prefix Victim Cache (P3-5):
    • Ranks all 48 x 512 = 24,576 NVFP4 experts (618,240 B each) using data/expert-profile.bin and places 7,013–7,683 hot experts in VRAM (n_pinned static + up to 32 dynamic VmmRange victim slots per layer, boosted by skipping startup hipModuleLoadData preloads for 9 unused legacy kernels) while mapping the remaining ~17,563 experts in 2 MiB hugepage-backed pinned host memory.
    • Pinned host pointer mirrors (h_ptrs and h_ptrs_prefill, 2.31 MiB page-locked arena) allow adapt_vram_experts(int l, int32_t valid_toks) (valid_toks = n_accept + 1) to run a 2-pass accepted-prefix update: Pass 1 records hit_count and marks slot_last_used = step_counter_ across all accepted tokens in the batch before Pass 2 promotes hot cold-pinned experts via non-blocking async SDMA, ensuring token 0 never evicts a VRAM expert needed by later accepted tokens in the same batch.
  • Hybrid GPU PCIe + 16-Core Zen 4 AVX-512_BF16 Execution:
    • In single-token decode (M = 1), moe_topk_and_silu_mul_640 routes VRAM experts + up to 1/3 of cold experts to GPU coalesced moe_decode_gate_up / moe_decode_down over PCIe 5.0 x16 while dispatching the remaining cold experts across the 16-core AVX-512 VNNI/BF16 CPU pool in parallel.
    • In small-batch verification (2 <= M <= 16), moe_cap_gpu_cold + moe_small_align pack VRAM-resident experts into deduplicated 16-row RDNA4 WMMA tiles (moe_gate_up + moe_down) while the 16-core CPU pool batches shared non-VRAM experts across tokens (kMaxJobToks = 64).

3.3 Native Multi-Token Prediction (MTP) + DSpark Speculative Decoding

  • Hybrid Drafter (src/program/nvfp4_generate.cpp & src/spec/nvfp4_ngram_drafter.cpp):
    • Combines the zero-overhead multi-order suffix N-gram drafter (up to K = 15 tokens on cold/medium context and dynamically expanding up to K = 23 tokens / $M = 24$ when empirical acceptance is high, scheduled by DSpark Algorithm 1 using live verification latency EMAs and per-bucket survival probabilities) with the native GPU/CPU FP8 MTP neural drafter (up to K = 3 tokens / M = 4, gated by target top-1 probability, top-2 logit margin, and cumulative prefix survival).
    • Supports both greedy verification (temperature = 0) and exact lossless point-mass speculative rejection sampling (DSpark §3.3.1 Eq. 8) when temperature > 0, with single-pass 16-row LM-head execution and lazy per-row D2H logit copies.

4. Verification & Benchmarks

Test System:

  • GPU: AMD Radeon AI PRO R9700 (gfx1201, RDNA 4, 64 CUs, 32 GiB GDDR6, PCIe 5.0 x16)
  • CPU: AMD Ryzen 9 7950X3D (16 physical Zen 4 cores / 32 threads, AVX-512 VNNI + AVX-512_BF16, 128 MiB L3 V-Cache, 96 GiB DDR5-6000)
  • ISA Guard & Lint:
    • python3 tools/check_isa_guard.py build/libstrata_kernels_cpu.a -> 0 not allowed
    • python3 tools/check_isa_guard.py build/strata -> checked 6153 functions, 43 hold wide-ISA instructions, 0 not allowed
    • python3 tools/test_source_nul_bytes.py -> OK

Measured Performance (Qwen3.8-Flash-Next-NVFP4 via strata.py serve + OpenCode multi-turn agent sessions):

  • Model Load Time: 16.37 s (7,013 profile-ranked hot experts in VRAM, 17,563 in pinned host RAM, native MTP layer + 40,525 draft vocab)
  • Cold-Context CLI Benchmark (Neural MTP active, 21 prompt tokens -> 256 generated tokens):
    • Prefill (21 tokens): 69.32 tok/s (0.303 s)
    • Decode (255 steps): 54.88 tok/s (18.22 ms/tok) (accepted 139 / 218 drafted tokens [63.8%])
  • Multi-Turn Agent & Long-Context Sessions (600 to 55,200 context tokens):
    • Prefill Throughput: 550.0–607.5 tok/s on 2K–18K token chunks (607.5 tok/s at 11.9K, 597.9 tok/s at 15.0K, 591.9 tok/s at 25.5K, 582.9 tok/s at 29.8K, and 561.2 tok/s at 49.1K context); instant < 0.4 s prefix checkpoint reuse on multi-turn continuations.
    • Decode Throughput (600–36.3K context): 50.04–65.85 tok/s (59.15 tok/s at 7.8K, 62.15 tok/s at 15.0K, 64.54 tok/s at 25.5K, 59.25 tok/s at 33.1K, 54.77 tok/s at 35.7K, and 52.23 tok/s at 36.3K with max_k=24/24 accepted in a single verify pass).
    • Sustained Long-Context Decode (46.7K–55.2K context across tiered VRAM + Host RAM KV): 50.67–59.69 tok/s across multi-thousand-token generations (53.50 tok/s at 54.0K context, 50.67 tok/s at 54.9K -> 55.2K context).

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/4114 **Author:** [@dimitri91209](https://github.com/dimitri91209) **Created:** 10/25/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `feat/gfx1201-flydsl-nvfp4` --- ### 📝 Commits (1) - [`b5e1887`](https://github.com/Niko1221/Strata/commit/b5e1887ef6c5f235d6be59f438099c3ea6c898e7) feat(gfx1201-nvfp4): add native RDNA4 (gfx1201) ModelOpt NVFP4 inference engine for Qwen3.8-Flash-Next ### 📊 Changes **21 files changed** (+58689 additions, -7 deletions) <details> <summary>View changed files</summary> 📝 `CMakeLists.txt` (+31 -5) ➕ `include/strata/artifact/qwen_tokenizer.hpp` (+283 -0) ➕ `include/strata/artifact/safetensors_reader.hpp` (+77 -0) ➕ `include/strata/core/nvfp4_engine.hpp` (+439 -0) ➕ `include/strata/kernels/cpu/nvfp4_modelopt.hpp` (+117 -0) ➕ `include/strata/kernels/gfx1201_nvfp4_kernels.hpp` (+66 -0) ➕ `include/strata/kernels/nvfp4_mtp_kernels.hpp` (+361 -0) ➕ `include/strata/program/nvfp4_generate.hpp` (+8 -0) ➕ `include/strata/spec/nvfp4_ngram_drafter.hpp` (+75 -0) ➕ `scripts/compile_deepseek_kernels.py` (+2340 -0) 📝 `serve/server.py` (+38 -0) ➕ `src/core/nvfp4_engine.cpp` (+3471 -0) ➕ `src/kernels/cpu/nvfp4_modelopt_avx2.cpp` (+352 -0) ➕ `src/kernels/cpu/nvfp4_modelopt_avx512.cpp` (+411 -0) ➕ `src/kernels/cpu/nvfp4_modelopt_pool.cpp` (+313 -0) ➕ `src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp` (+48626 -0) ➕ `src/kernels/cuda/gfx1201_nvfp4_kernels.cpp` (+160 -0) 📝 `src/program/generate.cpp` (+32 -0) ➕ `src/program/nvfp4_generate.cpp` (+799 -0) ➕ `src/spec/nvfp4_ngram_drafter.cpp` (+685 -0) _...and 1 more files_ </details> ### 📄 Description > **Draft PR (Work in Progress)** — Native RDNA4 (`gfx1201`) ModelOpt NVFP4 inference engine for **Qwen3.8-Flash-Next-NVFP4**, including 102 precompiled pure-FlyDSL `.hsaco` device kernels, cooperative 1-barrier LDS `Mega-mHC` + Layer-0 uniform-stream fusion, native Multi-Token Prediction (MTP) + DSpark hardware-aware speculative decoding, Native Sparse Attention (NSA) sink/window pinning + 16-pass 4-ary radix top-$k$ block selection with 100% VRAM-resident elastic 1M-context block keys, 42 MiB 4-way set-associative Layer-1 PLE cache with fused FP8 dequant+GEMV, and 3-tier adaptive VRAM/PCIe/AVX-512_BF16 MoE execution. --- ## 1. Overview This PR adds a standalone, zero-external-dependency **RDNA4 (`gfx1201`) ModelOpt NVFP4** inference engine (`--gfx1201-nvfp4` / `--nvfp4` / `--safetensors`, plus automatic `.safetensors` directory detection under `--native`, `--model`, or `--pack`) for **Qwen3.8-Flash-Next-NVFP4** (`qwen4_exp`: 48 layers = 36 Gated DeltaNet [GDN] + 12 Qwen Sparse Attention [QSA], 4-stream Hyper-Connections [mHC], 512 NVFP4 routed experts + 1 BF16 shared expert per layer, Layer-1 Per-Layer Embedding [PLE] N-gram lookup, and a native 49th Multi-Token Prediction [MTP] layer with 512 FP8 routed experts). All additions are strictly opt-in behind `STRATA_ENABLE_HIP` and leave existing CUDA/GGUF/CPU paths untouched when `--gfx1201-nvfp4` is not selected. --- ## 2. Complete Summary of Additions & Modifications Over `main` (`21` files) | Target / Subsystem | File Path | Status | Lines | Description | |---|---|---|---|---| | **Build System** | `CMakeLists.txt` | Modified | `+31 / -5` | Wires `gfx1201_nvfp4_hsaco.cpp` & `gfx1201_nvfp4_kernels.cpp` into `strata_kernels` (`STRATA_ENABLE_HIP`), `nvfp4_engine.cpp` into `strata_engine`, `nvfp4_generate.cpp` (`STRATA_HAVE_GFX1201_NVFP4=1`) into `strata`, `nvfp4_ngram_drafter.cpp` into `strata_spec`, and `nvfp4_modelopt_{avx512,avx2,pool}.cpp` into `strata_kernels_cpu` (with `-mavx512bf16` on `nvfp4_modelopt_avx512.cpp`). | | **Artifact & Tokenizer** | `include/strata/artifact/safetensors_reader.hpp` | Added | `+77` | Zero-copy JSON header parser (`TensorSlice` index) and aligned `pread_exact` helper for multi-shard `.safetensors` checkpoints. | | **Artifact & Tokenizer** | `include/strata/artifact/qwen_tokenizer.hpp` | Added | `+283` | Standalone GPT-2 byte-level BPE + special-token Qwen tokenizer (`vocab.json` + `merges.txt` / `tokenizer.json` / `tokens.bin`) for CLI mode. | | **GPU Kernel Runtime** | `include/strata/kernels/gfx1201_nvfp4_kernels.hpp` | Added | `+66` | `EmbeddedKernelDesc` descriptor struct, `PleConsts`, and `Gfx1201KernelCache` lazy `hipModuleLoadData` / `hipModuleLaunchKernel` cache with optional per-kernel HIP event profiling. | | **GPU Kernel Runtime** | `src/kernels/cuda/gfx1201_nvfp4_kernels.cpp` | Added | `+160` | Implementation of `Gfx1201KernelCache`: on-demand loading of embedded `.hsaco` ELF images via `hipModuleLoadData`, default-grid dispatch, and `STRATA_NVFP4_PROFILE` timing aggregation. | | **GPU Kernel Runtime** | `src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp` | Added | `+48,626` | **102 precompiled RDNA4 (`gfx1201`) FlyDSL `.hsaco` device binaries** (`alignas(64) const uint8_t kHsaco_0[]..kHsaco_101[]`) embedded directly as C++ byte arrays — zero Python, ROCm-LLVM, or FlyDSL dependency at build or run time. | | **GPU Kernel Runtime** | `include/strata/kernels/nvfp4_mtp_kernels.hpp` | Added | `+361` | Host launch wrappers for all fused DeepSeek MTP, DSpark confidence/margin argmax, NSA/QSA sink+window block scoring, strided/out-of-place GDN, batched PLE state update, and auto-dispatched $M=1..16+$ BF16 GEMV/GEMM kernels. | | **GPU Kernel Runtime** | `scripts/compile_deepseek_kernels.py` | Added | `+2,340` | Standalone offline compiler script that builds all 102 FlyDSL `gfx1201` `.hsaco` kernels (including cooperative 1-barrier LDS `Mega-mHC`, fused Layer-0 `embed_hc_premix_*_l0`, fused `ple_dequant_gemv_*`, and 16-pass 4-ary radix `qsa_topk_blocks`) and embeds them into `src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp`. | | **CPU Expert Pool** | `include/strata/kernels/cpu/nvfp4_modelopt.hpp` | Added | `+117` | Data structures (`CpuExpertJob`, `kMaxJobToks = 64`), per-expert byte offsets for NVFP4 (`618,240 B`) and MTP FP8 (`4,916,288 B`), and `Nvfp4CpuPool` persistent thread-pool interface. | | **CPU Expert Pool** | `src/kernels/cpu/nvfp4_modelopt_avx512.cpp` | Added | `+411` | **Zen 4 `AVX-512 VNNI` + `AVX-512_BF16` CPU expert kernels**: `vpdpbusd` int8$\times$uint8 dot products, hardware `_mm512_cvtneps_pbh` BF16 rounding (`bf16_round16_avx512`), 16-wide Cody-Waite `exp_neg16_avx512`, 16-wide `swiglu16_bf16_avx512`, and register-decoded FP8 (`e4m3fn`) MTP expert kernels (`gu_tile32_fp8_avx512`, `down_tile80_decode_fp8_avx512`). | | **CPU Expert Pool** | `src/kernels/cpu/nvfp4_modelopt_avx2.cpp` | Added | `+352` | Portable `AVX2 + FMA + F16C` fallback implementation of all NVFP4 and FP8 CPU expert kernels for CPUs without AVX-512 VNNI/BF16. | | **CPU Expert Pool** | `src/kernels/cpu/nvfp4_modelopt_pool.cpp` | Added | `+313` | Runtime CPUID dispatcher (`__builtin_cpu_supports` checking `avx512f/bw/vl/dq/vnni/bf16`) and lock-free atomic work-stealing thread pool pinned to physical CPU cores (`strata::kernels::cpu::physical_cores`). | | **CPU ISA Guard** | `tools/check_isa_guard.py` | Modified | `+5 / -2` | Registers `nvfp4_modelopt_avx512.cpp` (`WIDE_OBJECTS`), `nvfp4_modelopt_avx2.cpp` (`INIT_FREE_OBJECTS`), and the 6 public `*_avx512` entry points (`WIDE_PUBLIC`). Verified `0 violations` across both `libstrata_kernels_cpu.a` and `strata`. | | **Speculative Drafter** | `include/strata/spec/nvfp4_ngram_drafter.hpp` | Added | `+75` | `Nvfp4NgramDrafter` interface: multi-order 5/4/3/2/1-gram hash index, DSpark online survival calibration, and hardware-cost-aware prefix scheduler. | | **Speculative Drafter** | `src/spec/nvfp4_ngram_drafter.cpp` | Added | `+685` | **DSpark (`2607.05147`) Speculative Scheduler**: Algorithm 1 throughput optimizer $R(m) = (1 + \sum_{k=1}^m S(k)) / T_{\text{verify}}(1+m)$, Eq. 11 causal survival EMA calibration, target confidence/margin conditioning, and rejection memory. | | **Core NVFP4 Engine** | `include/strata/core/nvfp4_engine.hpp` | Added | `+439` | `Qwen4ExpGfx1201Engine` class declaration, weight structures (`Nvfp4HcWeights`, `Nvfp4GdnWeights`, `Nvfp4QsaWeights`, `Nvfp4MoeWeights`, `Nvfp4PleWeights`, `Nvfp4MtpWeights`), `42 MiB` 4-way set-associative `PleCacheEntry` table, and `VmmRange` arenas. | | **Core NVFP4 Engine** | `src/core/nvfp4_engine.cpp` | Added | `+3,471` | Complete 48-layer + MTP inference engine: parallel `.safetensors` loader, selective `.hsaco` module preloading, 3-tier MoE execution + 2-pass accepted-prefix VRAM victim cache, 1M-context tiered NVFP4 KV cache with 100% VRAM-resident elastic block keys, out-of-place GDN verification checkpointing, 4-way Layer-0 overlapped PLE cache, and native MTP neural drafting. | | **CLI & Serve Runner** | `include/strata/program/nvfp4_generate.hpp` | Added | `+8` | Declares `strata::program::run_nvfp4(int argc, char** argv)`. | | **CLI & Serve Runner** | `src/program/nvfp4_generate.cpp` | Added | `+799` | CLI & `--serve` IPC loop (`INFO`, `READY`, `GEN`, `RESUME`, `PP`, `T`, `DONE`, `VRAM`, `STOP`, `QUIT`), hybrid N-gram + neural MTP speculative decoding loop, and lossless point-mass speculative rejection sampling. | | **CLI Entrypoint** | `src/program/generate.cpp` | Modified | `+32` | Dispatches `--gfx1201-nvfp4`, `--nvfp4`, `--safetensors`, or `.safetensors`-only model directories to `strata::program::run_nvfp4`. | | **HTTP Server** | `serve/server.py` | Modified | `+38` | Preserves `<think>...</think>` reasoning blocks across multi-turn tool-call rounds when `keep_Earlier_thinking` is active and updates `_last_conv_ids` on normal `finish == "stop"` turns for instant multi-turn KV prefix reuse. | --- ## 3. Detailed Technical Architecture ### 3.1 102 Embedded Pure-FlyDSL RDNA4 (`gfx1201`) Kernels (`src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp`) All 102 GPU kernels are compiled directly to native RDNA4 (`gfx1201`) machine code via FlyDSL (`v_wmma_f32_16x16x16_bf16`, wave32 DPP/permute reductions, software-pipelined LDS double-buffering) and embedded in `gfx1201_nvfp4_hsaco.cpp` (with 9 superseded legacy kernels skipped during `hipModuleLoadData` startup preload to save `~18 MiB` of 2 MiB-aligned HIP module code pages in VRAM): - **Automatic Multi-Row BF16 Linear Dispatch (`launch_nvfp4_linear_auto` & `launch_nvfp4_lm_head_auto`)**: - $M = 1$: wave32-coalesced `bf16_gemv_<N>_<K>` (`1856x2560`, `2560x640`, `2560x2560`, `2560x6144`, `10240x2560`, `12800x2560`, `13952x2560`, `16480x2560`, `248320x2560`). - $2 \le M \le 4$: wave32-coalesced 4-row `bf16_gemv_m4_<N>_<K>` reading the weight matrix once across up to 4 tokens in registers. - $5 \le M \le 8$ (LM Head): wave32-coalesced 8-row `bf16_gemv_m8_248320_2560` reading the `1.271 GB` `lm_head.weight` **once** for up to 8 tokens. - $M > 8$ (LM Head) / $M > 4$ (Dense): 16-row RDNA4 WMMA tile GEMMs `bf16_linear_<N>_<K>` (including `bf16_linear_248320_2560`), allowing verification batches up to $M = 16$ per chunk to read `lm_head.weight` in a **single pass**. - **1-Barrier `0.0`-ULP Bit-Exact Cooperative LDS `Mega-mHC` (`hc_premix_decode_c0/c1_u0/u1` & `hc_premix_c0/c1_u0/u1`) & Layer-0 Uniform-Stream Fusion (`embed_hc_premix_decode_l0` & `embed_hc_premix_l0`)**: - **Stream-Per-Wave Preload (`s_w = wave` for `wave = 0..3`, `128` threads/WG)**: Each wave loads all 10 chunks (`2,560` elements) of stream `s_w` with zero wave divergence, accumulates `sq_w` in the exact sequential order `j = 0..9, e = 0..7` for `0.0`-ULP bit-exact `RSTD`, `XO`, `H`, and `INJ`, and synchronizes via a **single `gpu.barrier()`** per launch (down from 8 barriers). - **Occupancy-Optimal Packed BF16 LDS Layouts**: `hc_premix_decode_c*` (`T = 1` decode, `grid = (81/80, 1, 1)`) stages packed BF16 `(xv, nv)` pairs in `40 KiB` LDS (`Int32[10240]`, `3` workgroups/WGP = `96 > 81` concurrent blocks on GPU, eliminating all `NW` global loads in the `WD` loop); `hc_premix_c*` (`M >= 1` batched verify, `grid = (81/80, M, 1)`) stages packed BF16 `(xv[2p], xv[2p+1])` pairs in `20 KiB` LDS (`Int32[5120]`), doubling WGP occupancy to **`6` workgroups/WGP (`192` concurrent workgroups across 32 WGPs)** and accelerating batched verification by **`1.78x–1.98x` at $M = 8..15$** (`64.62 us -> 36.26 us` at $M=8$, `91.44 us -> 46.07 us` at $M=12$, `112.29 us -> 59.17 us` at $M=15$). - **First-Layer (`l == 0` `attn_hc`) Uniform-Stream Fusion (`embed_hc_premix_decode_l0` & `embed_hc_premix_l0`)**: Exploits the Layer-0 invariant $X_{0,0} = X_{0,1} = X_{0,2} = X_{0,3} = E[\text{token\_id}]$ (`has_prev_update = false`) to fuse `embed_hc_gather` directly into Layer 0 `attn_hc` `hc_premix` on both decode and batched verify/prefill. Only Wave 0 loads `E[token_id]` (`5 KiB` per token instead of `20 KiB` 4-stream global write + `20 KiB` 4-stream global read), computes `rstd` once, and stages `E[token_id]` into `5 KiB` LDS while `blk == 0` writes all 4 streams of `X` and `RSTD` (**`44.55 us -> 26.22 us` [`1.70x`] at $T = 1$**, **`50.46 us -> 30.95 us` [`1.63x`] at $M = 4$**, **`49.52 us -> 30.54 us` [`1.62x`] at $M = 8$**, `0.0`-ULP bit-exact). - **Strided & Out-of-Place Fused Gated DeltaNet (`gated_deltanet_fused_strided`) & Strided Shared-Expert SiLU (`silu_mul_640_strided`)**: - `gated_deltanet_fused_strided` reads `QKV [10240]`, `Z [6144]`, `A [48]`, `B [48]` directly from the fused `[M, 16480]` projection buffer via `in_stride = 16480`, eliminating all 36 `gdn_proj_split` kernel launches per batch, and supports separate `S_IN` and `S_OUT` (`[48, 128, 128]` FP32 = `3 MiB`/layer, `108 MiB` across 36 layers) so speculative verification writes updated recurrent states out-of-place to `d_gdn_state_ckpt_`. This reduces `save_recurrent_ckpt()` from `112.39 MiB` (`0.42 ms`) to **`4.39 MiB` (`0.014 ms`, 25.6$\times$ smaller)** and makes full-acceptance state commit an $O(1)$ `std::swap` (`0.000 ms`). - `silu_mul_640_strided` reads `sh_gate [640]` and `sh_up [640]` directly from `d_proj_scratch_` with `in_stride = 1856`, eliminating all 48 `moe_sh_gu_extract` launches per verification/prefill batch. - **Batched 5-in-1 QSA Prep + NVFP4 KV Cache Write (`qsa_prep_and_cache_write_batch_nvfp4`)**: - Fuses `qsa_proj_split` + `qsa_q_extract` + Q `qk_norm_partial_rope` + K `qk_norm_partial_rope` + tiered NVFP4 `K_CACHE`/`V_CACHE` quantization and `RAW_K_CACHE` write into **1 launch** (`grid = (4, M, 1)`), replacing 60 kernel launches per verification/prefill batch with 12. - **Native Sparse Attention (NSA `2502.11089`) Tiered Block Scorer (`qsa_score_blocks_tiered_pinned` & `qsa_score_blocks_batched`), 16-Pass 4-Ary Radix `qsa_topk_blocks`, & Elastic 1M-Context VRAM Block Keys**: - **100% VRAM-Resident Elastic Block-Key Mirror (`P3-1`)**: Decouples `vram_blocks_` from `vram_cap_ / 4` (`vram_blocks_ = max_blocks_ = 262,144` blocks = `1,048,576` tokens when HIP VMM `kv_vmm_ok_ == true`, mapping `init_bk_blks = (init_vram_seq + 3) / 4` at `pos = 0` and elastically growing in `2 MiB` VMM chunks in `ensure_context_capacity()`), keeping `qsa_score_blocks_tiered_pinned` and `qsa_score_blocks_batched` 100% VRAM-resident (`512 GB/s`) up to `1M` context while preserving `7,013` hot experts in VRAM at startup. - **Fused Sink + Sliding-Window Pinning & `nb <= 512` Bypass**: Fuses initial attention sink (`16` blocks = `64` tokens) and local sliding-window (`64` blocks = `256` tokens) score pinning directly into the block-key scorer in registers (eliminating all 12 `qsa_pin_sink_and_window` launches per decode token), and skips launching `qsa_score_blocks_tiered_pinned` / `qsa_score_blocks_batched` across all 12 QSA layers on the host when `nb <= 512` (`pos < 2048`). - **16-Pass 4-Ary Radix `qsa_topk_blocks` & `1M`-Context Prefix-Sum Fix (`P3-2`)**: Replaces the 31-pass binary threshold search (`62` barriers) with a 1-pass bypass when `nb <= 512`, a **1-load-pass VGPR register-cached (`s_reg[0..15]`, bounds-clamped `bi_safe`) 16-pass 4-ary radix search** (`c1, c2, c3` testing 2 bits/pass packed into 3×10-bit `Int32` reductions with `1` barrier/pass = `16` barriers total) for `512 < nb <= 8192` (`pos <= 32,768`), a 16-pass 4-ary radix multi-chunk search for `nb > 8192`, and **`10-bit ng (`& 0x3FF`) / 21-bit ne (`<< 10`)`** Hillis-Steele prefix-sum packing supporting up to `2,097,151` blocks (`8.38M` tokens > `1M` max context) without overflow (**`88.78 us -> 18.84 us` [`4.71x`] at `pos = 16,000`**, **`124.48 us -> 18.83 us` [`6.61x`] at `pos = 32,000`**, **`176.62 us -> 152.16 us` [`1.16x`] at `pos = 64,000`**). - `qsa_block_keys_from_batch` + `qsa_refresh_raw_k_tail` eliminate `RAW_K_CACHE` 1024-token ring buffer wrap-around for arbitrary prefill chunk sizes ($M \le 4096$). - **Engram / Layer-1 `PLE` `42 MiB` 4-Way Set-Associative Cache, Layer-0 Async Overlap, Fused `ple_dequant_gemv_12800_2560` & `ple_dequant_gemv_m4_12800_2560`, & `ple_state_update_batch`**: - **4-Way Set-Associative Zipfian Cache (`42 MiB`) & Layer-0 Overlap (`P3-4`)**: Expands `ple_cache_` in Host RAM from `4,096` direct-mapped slots (`672 KiB`) to `65,536` sets $\times$ `4` ways (`262,144` entries = `42 MiB`), pre-populated during prefill and asynchronously prefetched + uploaded (`hipMemcpyAsync`) in Layer 0 immediately after `moe_decode_down` / `moe_down` so host lookup and PCIe H2D transfer overlap with Layer 0 `moe_merge_routed` without delaying `run_cpu_moe_layer(0)`. - **Fused FP8 Dequant + K/V Projection (`ple_dequant_gemv_12800_2560` & `ple_dequant_gemv_m4_12800_2560`)**: Fuses `ple_embed_dequant` (`fp8_e4m3 * scale -> bf16` in registers) directly into the Layer-1 PLE K/V projection on both `T = 1` decode (`kHsaco_98`, `41.07 us -> 39.24 us`) and `M = 1..4` batched verification (`kHsaco_99`, writing separate row-strided `OutK [M, 10240]` and `OutV [M, 2560]` buffers and replacing 3 launches in `step_prefill_batch` with 1 launch: **`64.97 us -> 53.10 us` [`-11.87 us` faster] at $M = 4$**, `0.000000` bit-exact). - **Batched Conv State Update (`ple_state_update_batch`)**: Updates the `[9, 10240]` BF16 Layer-1 PLE causal conv state across all $M$ tokens in a single launch (`grid = (40, 1, 1)`), eliminating the serial $M$-launch loop. - **Fused Tiered NVFP4 Sink + Sliding-Window Decode Attention for MTP (`qsa_swa_sink_decode_fused_nvfp4`)**: - Single-launch Flash-Decoding over the 64 initial sink tokens + 1,024-token sliding window with fused output sigmoid gating (`grid = (24, 1, 1)`), keeping MTP attention latency constant at `~25 us` even at 50k–1M context. - **Single-Pass Target & Pruned-Vocab Argmax + Softmax Probability + Top-2 Margin (`argmax_prob_margin_248320`, `mtp_dvocab_gemv`, `argmax_prob_margin_dvocab`)**: - Computes exact online log-sum-exp softmax probability $p_1$ and top-1/top-2 logit margin $z_{(1)} - z_{(2)}$ in a single pass for DSpark confidence gating, and provides a `6.1x` faster `40,525`-token pruned + dynamic context vocabulary head for MTP drafting. ### 3.2 Three-Tier Adaptive MoE Execution (`VRAM + Zero-Copy PCIe + 16-Core AVX-512_BF16 CPU Pool`) - **Profile-Guided VRAM Placement + Two-Pass Accepted-Prefix Victim Cache (`P3-5`)**: - Ranks all `48 x 512 = 24,576` NVFP4 experts (`618,240 B` each) using `data/expert-profile.bin` and places **`7,013`–`7,683` hot experts in VRAM** (`n_pinned` static + up to `32` dynamic `VmmRange` victim slots per layer, boosted by skipping startup `hipModuleLoadData` preloads for 9 unused legacy kernels) while mapping the remaining `~17,563` experts in `2 MiB` hugepage-backed pinned host memory. - Pinned host pointer mirrors (`h_ptrs` and `h_ptrs_prefill`, `2.31 MiB` page-locked arena) allow `adapt_vram_experts(int l, int32_t valid_toks)` (`valid_toks = n_accept + 1`) to run a **2-pass accepted-prefix update**: Pass 1 records `hit_count` and marks `slot_last_used = step_counter_` across all accepted tokens in the batch before Pass 2 promotes hot cold-pinned experts via non-blocking async SDMA, ensuring token `0` never evicts a VRAM expert needed by later accepted tokens in the same batch. - **Hybrid GPU PCIe + 16-Core Zen 4 `AVX-512_BF16` Execution**: - In single-token decode (`M = 1`), `moe_topk_and_silu_mul_640` routes VRAM experts + up to `1/3` of cold experts to GPU coalesced `moe_decode_gate_up` / `moe_decode_down` over PCIe 5.0 x16 while dispatching the remaining cold experts across the 16-core AVX-512 VNNI/BF16 CPU pool in parallel. - In small-batch verification (`2 <= M <= 16`), `moe_cap_gpu_cold` + `moe_small_align` pack VRAM-resident experts into deduplicated 16-row RDNA4 WMMA tiles (`moe_gate_up` + `moe_down`) while the 16-core CPU pool batches shared non-VRAM experts across tokens (`kMaxJobToks = 64`). ### 3.3 Native Multi-Token Prediction (MTP) + DSpark Speculative Decoding - **Hybrid Drafter (`src/program/nvfp4_generate.cpp` & `src/spec/nvfp4_ngram_drafter.cpp`)**: - Combines the zero-overhead multi-order suffix N-gram drafter (up to $K = 15$ tokens on cold/medium context and dynamically expanding up to **$K = 23$ tokens / $M = 24$** when empirical acceptance is high, scheduled by DSpark Algorithm 1 using live verification latency EMAs and per-bucket survival probabilities) with the native GPU/CPU FP8 MTP neural drafter (up to $K = 3$ tokens / $M = 4$, gated by target top-1 probability, top-2 logit margin, and cumulative prefix survival). - Supports both greedy verification (`temperature = 0`) and **exact lossless point-mass speculative rejection sampling** (`DSpark §3.3.1 Eq. 8`) when `temperature > 0`, with single-pass 16-row LM-head execution and lazy per-row D2H logit copies. --- ## 4. Verification & Benchmarks **Test System**: - **GPU**: AMD Radeon AI PRO R9700 (`gfx1201`, RDNA 4, 64 CUs, 32 GiB GDDR6, PCIe 5.0 x16) - **CPU**: AMD Ryzen 9 7950X3D (16 physical Zen 4 cores / 32 threads, `AVX-512 VNNI` + `AVX-512_BF16`, 128 MiB L3 V-Cache, 96 GiB DDR5-6000) - **ISA Guard & Lint**: - `python3 tools/check_isa_guard.py build/libstrata_kernels_cpu.a` -> **`0 not allowed`** - `python3 tools/check_isa_guard.py build/strata` -> **`checked 6153 functions, 43 hold wide-ISA instructions, 0 not allowed`** - `python3 tools/test_source_nul_bytes.py` -> **`OK`** **Measured Performance (`Qwen3.8-Flash-Next-NVFP4` via `strata.py serve` + OpenCode multi-turn agent sessions)**: - **Model Load Time**: **`16.37 s`** (`7,013` profile-ranked hot experts in VRAM, `17,563` in pinned host RAM, native MTP layer + `40,525` draft vocab) - **Cold-Context CLI Benchmark (Neural MTP active, `21` prompt tokens -> `256` generated tokens)**: - **Prefill (`21` tokens)**: **`69.32 tok/s`** (`0.303 s`) - **Decode (`255` steps)**: **`54.88 tok/s` (`18.22 ms/tok`)** (`accepted 139 / 218 drafted tokens [63.8%]`) - **Multi-Turn Agent & Long-Context Sessions (`600` to `55,200` context tokens)**: - **Prefill Throughput**: **`550.0–607.5 tok/s`** on `2K–18K` token chunks (`607.5 tok/s` at `11.9K`, `597.9 tok/s` at `15.0K`, `591.9 tok/s` at `25.5K`, `582.9 tok/s` at `29.8K`, and **`561.2 tok/s` at `49.1K` context**); instant `< 0.4 s` prefix checkpoint reuse on multi-turn continuations. - **Decode Throughput (`600–36.3K` context)**: **`50.04–65.85 tok/s`** (`59.15 tok/s` at `7.8K`, `62.15 tok/s` at `15.0K`, `64.54 tok/s` at `25.5K`, `59.25 tok/s` at `33.1K`, `54.77 tok/s` at `35.7K`, and `52.23 tok/s` at `36.3K` with **`max_k=24/24`** accepted in a single verify pass). - **Sustained Long-Context Decode (`46.7K–55.2K` context across tiered VRAM + Host RAM KV)**: **`50.67–59.69 tok/s`** across multi-thousand-token generations (`53.50 tok/s` at `54.0K` context, `50.67 tok/s` at `54.9K -> 55.2K` context). --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#4905
No description provided.