mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #4114] [Engine] Native RDNA4 (gfx1201) NVFP4 engine (--gfx1201-nvfp4) #4905
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4905
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 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)
b5e1887feat(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
1. Overview
This PR adds a standalone, zero-external-dependency RDNA4 (
gfx1201) ModelOpt NVFP4 inference engine (--gfx1201-nvfp4/--nvfp4/--safetensors, plus automatic.safetensorsdirectory 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_HIPand leave existing CUDA/GGUF/CPU paths untouched when--gfx1201-nvfp4is not selected.2. Complete Summary of Additions & Modifications Over
main(21files)CMakeLists.txt+31 / -5gfx1201_nvfp4_hsaco.cpp&gfx1201_nvfp4_kernels.cppintostrata_kernels(STRATA_ENABLE_HIP),nvfp4_engine.cppintostrata_engine,nvfp4_generate.cpp(STRATA_HAVE_GFX1201_NVFP4=1) intostrata,nvfp4_ngram_drafter.cppintostrata_spec, andnvfp4_modelopt_{avx512,avx2,pool}.cppintostrata_kernels_cpu(with-mavx512bf16onnvfp4_modelopt_avx512.cpp).include/strata/artifact/safetensors_reader.hpp+77TensorSliceindex) and alignedpread_exacthelper for multi-shard.safetensorscheckpoints.include/strata/artifact/qwen_tokenizer.hpp+283vocab.json+merges.txt/tokenizer.json/tokens.bin) for CLI mode.include/strata/kernels/gfx1201_nvfp4_kernels.hpp+66EmbeddedKernelDescdescriptor struct,PleConsts, andGfx1201KernelCachelazyhipModuleLoadData/hipModuleLaunchKernelcache with optional per-kernel HIP event profiling.src/kernels/cuda/gfx1201_nvfp4_kernels.cpp+160Gfx1201KernelCache: on-demand loading of embedded.hsacoELF images viahipModuleLoadData, default-grid dispatch, andSTRATA_NVFP4_PROFILEtiming aggregation.src/kernels/cuda/gfx1201_nvfp4_hsaco.cpp+48,626gfx1201) FlyDSL.hsacodevice 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.include/strata/kernels/nvfp4_mtp_kernels.hpp+361M=1..16+BF16 GEMV/GEMM kernels.scripts/compile_deepseek_kernels.py+2,340gfx1201.hsacokernels (including cooperative 1-barrier LDSMega-mHC, fused Layer-0embed_hc_premix_*_l0, fusedple_dequant_gemv_*, and 16-pass 4-ary radixqsa_topk_blocks) and embeds them intosrc/kernels/cuda/gfx1201_nvfp4_hsaco.cpp.include/strata/kernels/cpu/nvfp4_modelopt.hpp+117CpuExpertJob,kMaxJobToks = 64), per-expert byte offsets for NVFP4 (618,240 B) and MTP FP8 (4,916,288 B), andNvfp4CpuPoolpersistent thread-pool interface.src/kernels/cpu/nvfp4_modelopt_avx512.cpp+411AVX-512 VNNI+AVX-512_BF16CPU expert kernels:vpdpbusdint8$\times$uint8 dot products, hardware_mm512_cvtneps_pbhBF16 rounding (bf16_round16_avx512), 16-wide Cody-Waiteexp_neg16_avx512, 16-wideswiglu16_bf16_avx512, and register-decoded FP8 (e4m3fn) MTP expert kernels (gu_tile32_fp8_avx512,down_tile80_decode_fp8_avx512).src/kernels/cpu/nvfp4_modelopt_avx2.cpp+352AVX2 + FMA + F16Cfallback implementation of all NVFP4 and FP8 CPU expert kernels for CPUs without AVX-512 VNNI/BF16.src/kernels/cpu/nvfp4_modelopt_pool.cpp+313__builtin_cpu_supportscheckingavx512f/bw/vl/dq/vnni/bf16) and lock-free atomic work-stealing thread pool pinned to physical CPU cores (strata::kernels::cpu::physical_cores).tools/check_isa_guard.py+5 / -2nvfp4_modelopt_avx512.cpp(WIDE_OBJECTS),nvfp4_modelopt_avx2.cpp(INIT_FREE_OBJECTS), and the 6 public*_avx512entry points (WIDE_PUBLIC). Verified0 violationsacross bothlibstrata_kernels_cpu.aandstrata.include/strata/spec/nvfp4_ngram_drafter.hpp+75Nvfp4NgramDrafterinterface: multi-order 5/4/3/2/1-gram hash index, DSpark online survival calibration, and hardware-cost-aware prefix scheduler.src/spec/nvfp4_ngram_drafter.cpp+6852607.05147) Speculative Scheduler: Algorithm 1 throughput optimizerR(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.include/strata/core/nvfp4_engine.hpp+439Qwen4ExpGfx1201Engineclass declaration, weight structures (Nvfp4HcWeights,Nvfp4GdnWeights,Nvfp4QsaWeights,Nvfp4MoeWeights,Nvfp4PleWeights,Nvfp4MtpWeights),42 MiB4-way set-associativePleCacheEntrytable, andVmmRangearenas.src/core/nvfp4_engine.cpp+3,471.safetensorsloader, selective.hsacomodule 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.include/strata/program/nvfp4_generate.hpp+8strata::program::run_nvfp4(int argc, char** argv).src/program/nvfp4_generate.cpp+799--serveIPC 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.src/program/generate.cpp+32--gfx1201-nvfp4,--nvfp4,--safetensors, or.safetensors-only model directories tostrata::program::run_nvfp4.serve/server.py+38<think>...</think>reasoning blocks across multi-turn tool-call rounds whenkeep_Earlier_thinkingis active and updates_last_conv_idson normalfinish == "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 ingfx1201_nvfp4_hsaco.cpp(with 9 superseded legacy kernels skipped duringhipModuleLoadDatastartup preload to save~18 MiBof 2 MiB-aligned HIP module code pages in VRAM):launch_nvfp4_linear_auto&launch_nvfp4_lm_head_auto):M = 1: wave32-coalescedbf16_gemv_<N>_<K>(1856x2560,2560x640,2560x2560,2560x6144,10240x2560,12800x2560,13952x2560,16480x2560,248320x2560).2 \le M \le 4: wave32-coalesced 4-rowbf16_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-rowbf16_gemv_m8_248320_2560reading the1.271 GBlm_head.weightonce for up to 8 tokens.M > 8(LM Head) /M > 4(Dense): 16-row RDNA4 WMMA tile GEMMsbf16_linear_<N>_<K>(includingbf16_linear_248320_2560), allowing verification batches up toM = 16per chunk to readlm_head.weightin a single pass.0.0-ULP Bit-Exact Cooperative LDSMega-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):s_w = waveforwave = 0..3,128threads/WG): Each wave loads all 10 chunks (2,560elements) of streams_wwith zero wave divergence, accumulatessq_win the exact sequential orderj = 0..9, e = 0..7for0.0-ULP bit-exactRSTD,XO,H, andINJ, and synchronizes via a singlegpu.barrier()per launch (down from 8 barriers).hc_premix_decode_c*(T = 1decode,grid = (81/80, 1, 1)) stages packed BF16(xv, nv)pairs in40 KiBLDS (Int32[10240],3workgroups/WGP =96 > 81concurrent blocks on GPU, eliminating allNWglobal loads in theWDloop);hc_premix_c*(M >= 1batched verify,grid = (81/80, M, 1)) stages packed BF16(xv[2p], xv[2p+1])pairs in20 KiBLDS (Int32[5120]), doubling WGP occupancy to6workgroups/WGP (192concurrent workgroups across 32 WGPs) and accelerating batched verification by1.78x–1.98xat $M = 8..15$ (64.62 us -> 36.26 usatM=8,91.44 us -> 46.07 usatM=12,112.29 us -> 59.17 usatM=15).l == 0attn_hc) Uniform-Stream Fusion (embed_hc_premix_decode_l0&embed_hc_premix_l0): Exploits the Layer-0 invariantX_{0,0} = X_{0,1} = X_{0,2} = X_{0,3} = E[\text{token\_id}](has_prev_update = false) to fuseembed_hc_gatherdirectly into Layer 0attn_hchc_premixon both decode and batched verify/prefill. Only Wave 0 loadsE[token_id](5 KiBper token instead of20 KiB4-stream global write +20 KiB4-stream global read), computesrstdonce, and stagesE[token_id]into5 KiBLDS whileblk == 0writes all 4 streams ofXandRSTD(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).gated_deltanet_fused_strided) & Strided Shared-Expert SiLU (silu_mul_640_strided):gated_deltanet_fused_stridedreadsQKV [10240],Z [6144],A [48],B [48]directly from the fused[M, 16480]projection buffer viain_stride = 16480, eliminating all 36gdn_proj_splitkernel launches per batch, and supports separateS_INandS_OUT([48, 128, 128]FP32 =3 MiB/layer,108 MiBacross 36 layers) so speculative verification writes updated recurrent states out-of-place tod_gdn_state_ckpt_. This reducessave_recurrent_ckpt()from112.39 MiB(0.42 ms) to4.39 MiB(0.014 ms, 25.6$\times$ smaller) and makes full-acceptance state commit anO(1)std::swap(0.000 ms).silu_mul_640_stridedreadssh_gate [640]andsh_up [640]directly fromd_proj_scratch_within_stride = 1856, eliminating all 48moe_sh_gu_extractlaunches per verification/prefill batch.qsa_prep_and_cache_write_batch_nvfp4):qsa_proj_split+qsa_q_extract+ Qqk_norm_partial_rope+ Kqk_norm_partial_rope+ tiered NVFP4K_CACHE/V_CACHEquantization andRAW_K_CACHEwrite into 1 launch (grid = (4, M, 1)), replacing 60 kernel launches per verification/prefill batch with 12.2502.11089) Tiered Block Scorer (qsa_score_blocks_tiered_pinned&qsa_score_blocks_batched), 16-Pass 4-Ary Radixqsa_topk_blocks, & Elastic 1M-Context VRAM Block Keys:P3-1): Decouplesvram_blocks_fromvram_cap_ / 4(vram_blocks_ = max_blocks_ = 262,144blocks =1,048,576tokens when HIP VMMkv_vmm_ok_ == true, mappinginit_bk_blks = (init_vram_seq + 3) / 4atpos = 0and elastically growing in2 MiBVMM chunks inensure_context_capacity()), keepingqsa_score_blocks_tiered_pinnedandqsa_score_blocks_batched100% VRAM-resident (512 GB/s) up to1Mcontext while preserving7,013hot experts in VRAM at startup.nb <= 512Bypass: Fuses initial attention sink (16blocks =64tokens) and local sliding-window (64blocks =256tokens) score pinning directly into the block-key scorer in registers (eliminating all 12qsa_pin_sink_and_windowlaunches per decode token), and skips launchingqsa_score_blocks_tiered_pinned/qsa_score_blocks_batchedacross all 12 QSA layers on the host whennb <= 512(pos < 2048).qsa_topk_blocks&1M-Context Prefix-Sum Fix (P3-2): Replaces the 31-pass binary threshold search (62barriers) with a 1-pass bypass whennb <= 512, a 1-load-pass VGPR register-cached (s_reg[0..15], bounds-clampedbi_safe) 16-pass 4-ary radix search (c1, c2, c3testing 2 bits/pass packed into 3×10-bitInt32reductions with1barrier/pass =16barriers total) for512 < nb <= 8192(pos <= 32,768), a 16-pass 4-ary radix multi-chunk search fornb > 8192, and10-bit ng (& 0x3FF) / 21-bit ne (<< 10)Hillis-Steele prefix-sum packing supporting up to2,097,151blocks (8.38Mtokens >1Mmax context) without overflow (88.78 us -> 18.84 us[4.71x] atpos = 16,000,124.48 us -> 18.83 us[6.61x] atpos = 32,000,176.62 us -> 152.16 us[1.16x] atpos = 64,000).qsa_block_keys_from_batch+qsa_refresh_raw_k_taileliminateRAW_K_CACHE1024-token ring buffer wrap-around for arbitrary prefill chunk sizes (M \le 4096).PLE42 MiB4-Way Set-Associative Cache, Layer-0 Async Overlap, Fusedple_dequant_gemv_12800_2560&ple_dequant_gemv_m4_12800_2560, &ple_state_update_batch:42 MiB) & Layer-0 Overlap (P3-4): Expandsple_cache_in Host RAM from4,096direct-mapped slots (672 KiB) to65,536sets\times4ways (262,144entries =42 MiB), pre-populated during prefill and asynchronously prefetched + uploaded (hipMemcpyAsync) in Layer 0 immediately aftermoe_decode_down/moe_downso host lookup and PCIe H2D transfer overlap with Layer 0moe_merge_routedwithout delayingrun_cpu_moe_layer(0).ple_dequant_gemv_12800_2560&ple_dequant_gemv_m4_12800_2560): Fusesple_embed_dequant(fp8_e4m3 * scale -> bf16in registers) directly into the Layer-1 PLE K/V projection on bothT = 1decode (kHsaco_98,41.07 us -> 39.24 us) andM = 1..4batched verification (kHsaco_99, writing separate row-stridedOutK [M, 10240]andOutV [M, 2560]buffers and replacing 3 launches instep_prefill_batchwith 1 launch:64.97 us -> 53.10 us[-11.87 usfaster] at $M = 4$,0.000000bit-exact).ple_state_update_batch): Updates the[9, 10240]BF16 Layer-1 PLE causal conv state across allMtokens in a single launch (grid = (40, 1, 1)), eliminating the serial $M$-launch loop.qsa_swa_sink_decode_fused_nvfp4):grid = (24, 1, 1)), keeping MTP attention latency constant at~25 useven at 50k–1M context.argmax_prob_margin_248320,mtp_dvocab_gemv,argmax_prob_margin_dvocab):p_1and top-1/top-2 logit marginz_{(1)} - z_{(2)}in a single pass for DSpark confidence gating, and provides a6.1xfaster40,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)P3-5):48 x 512 = 24,576NVFP4 experts (618,240 Beach) usingdata/expert-profile.binand places7,013–7,683hot experts in VRAM (n_pinnedstatic + up to32dynamicVmmRangevictim slots per layer, boosted by skipping startuphipModuleLoadDatapreloads for 9 unused legacy kernels) while mapping the remaining~17,563experts in2 MiBhugepage-backed pinned host memory.h_ptrsandh_ptrs_prefill,2.31 MiBpage-locked arena) allowadapt_vram_experts(int l, int32_t valid_toks)(valid_toks = n_accept + 1) to run a 2-pass accepted-prefix update: Pass 1 recordshit_countand marksslot_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 token0never evicts a VRAM expert needed by later accepted tokens in the same batch.AVX-512_BF16Execution:M = 1),moe_topk_and_silu_mul_640routes VRAM experts + up to1/3of cold experts to GPU coalescedmoe_decode_gate_up/moe_decode_downover PCIe 5.0 x16 while dispatching the remaining cold experts across the 16-core AVX-512 VNNI/BF16 CPU pool in parallel.2 <= M <= 16),moe_cap_gpu_cold+moe_small_alignpack 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
src/program/nvfp4_generate.cpp&src/spec/nvfp4_ngram_drafter.cpp):K = 15tokens on cold/medium context and dynamically expanding up toK = 23tokens / $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 toK = 3tokens /M = 4, gated by target top-1 probability, top-2 logit margin, and cumulative prefix survival).temperature = 0) and exact lossless point-mass speculative rejection sampling (DSpark §3.3.1 Eq. 8) whentemperature > 0, with single-pass 16-row LM-head execution and lazy per-row D2H logit copies.4. Verification & Benchmarks
Test System:
gfx1201, RDNA 4, 64 CUs, 32 GiB GDDR6, PCIe 5.0 x16)AVX-512 VNNI+AVX-512_BF16, 128 MiB L3 V-Cache, 96 GiB DDR5-6000)python3 tools/check_isa_guard.py build/libstrata_kernels_cpu.a->0 not allowedpython3 tools/check_isa_guard.py build/strata->checked 6153 functions, 43 hold wide-ISA instructions, 0 not allowedpython3 tools/test_source_nul_bytes.py->OKMeasured Performance (
Qwen3.8-Flash-Next-NVFP4viastrata.py serve+ OpenCode multi-turn agent sessions):16.37 s(7,013profile-ranked hot experts in VRAM,17,563in pinned host RAM, native MTP layer +40,525draft vocab)21prompt tokens ->256generated tokens):21tokens):69.32 tok/s(0.303 s)255steps):54.88 tok/s(18.22 ms/tok) (accepted 139 / 218 drafted tokens [63.8%])600to55,200context tokens):550.0–607.5 tok/son2K–18Ktoken chunks (607.5 tok/sat11.9K,597.9 tok/sat15.0K,591.9 tok/sat25.5K,582.9 tok/sat29.8K, and561.2 tok/sat49.1Kcontext); instant< 0.4 sprefix checkpoint reuse on multi-turn continuations.600–36.3Kcontext):50.04–65.85 tok/s(59.15 tok/sat7.8K,62.15 tok/sat15.0K,64.54 tok/sat25.5K,59.25 tok/sat33.1K,54.77 tok/sat35.7K, and52.23 tok/sat36.3Kwithmax_k=24/24accepted in a single verify pass).46.7K–55.2Kcontext across tiered VRAM + Host RAM KV):50.67–59.69 tok/sacross multi-thousand-token generations (53.50 tok/sat54.0Kcontext,50.67 tok/sat54.9K -> 55.2Kcontext).🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.