Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

NVFP4 routed experts: converter, pack, decode, prompt path, AVX-512 CPU rows

sergiywithe51b4379dc8c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0f6426a45..bd5551032 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1268,10 +1268,12 @@ if(STRATA_NATIVE_EXPERTS)
# one-pass static linking has no cycle to resolve)
target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp
src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp
- src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp)
+ src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp
+ src/kernels/cpu/nvfp4_avx512.cpp)
target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml)
if(MSVC)
- set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
+ set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp
+ PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
# the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops
@@ -1282,7 +1284,7 @@ if(STRATA_NATIVE_EXPERTS)
# the older CPUs' i-quant expert rows (iq_avx1.hpp): 128-bit SSSE3/SSE2 integer, SSE2 float, no FMA/F16C
set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
else()
- set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS
+ set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
@@ -1363,6 +1365,7 @@ if(STRATA_NATIVE_EXPERTS)
# #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA
# only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable)
add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu
+ src/prefill/mmq_nvfp4_w4a8.cu
src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu)
# q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and
# STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch
@@ -1377,6 +1380,20 @@ if(STRATA_NATIVE_EXPERTS)
foreach(_t IN LISTS _strata_mmq_cuda_types)
target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
endforeach()
+ # NVFP4: W4A8 (default) in mmq_nvfp4_w4a8.cu with the plain architectures; the opt-in W4A4 needs RTX 50's FP4 MMA,
+ # which exists only in the arch-specific target, so its one unit alone is built with 12x -> 12xa (the default
+ # binary is unchanged and runs on sm_121; a card without that image falls back to W4A8 at run time)
+ set(_strata_w4a4_archs ${CMAKE_CUDA_ARCHITECTURES})
+ list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])(-real|-virtual)?$" "\\1a\\2")
+ add_library(strata_mmq_w4a4 STATIC src/prefill/mmq_nvfp4_w4a4.cu)
+ set_target_properties(strata_mmq_w4a4 PROPERTIES CUDA_ARCHITECTURES "${_strata_w4a4_archs}")
+ target_include_directories(strata_mmq_w4a4 PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq})
+ target_compile_options(strata_mmq_w4a4 PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
+ if(MSVC)
+ target_compile_options(strata_mmq_w4a4 PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=/bigobj>)
+ endif()
+ target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target})
+ target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4)
target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_compile_options(strata_mmq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
@@ -1415,6 +1432,9 @@ if(STRATA_NATIVE_EXPERTS)
add_test(NAME prefill_mmq_kquant_test COMMAND prefill_mmq_kquant_test)
set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120)
endif()
+ # the NVFP4 expert products (w4a8 / w4a4, STRATA_PREFILL_NVFP4) against a double-precision reference
+ add_executable(mmq_nvfp4_parity src/prefill/mmq_nvfp4_parity.cpp)
+ target_link_libraries(mmq_nvfp4_parity PRIVATE strata_mmq ggml-base CUDA::cudart)
elseif(STRATA_PREFILL_MMQ)
# Compile only the pinned GGML MMQ and activation-quantizer sources used by prefill. This uses
# common.cuh's native HIP path without enabling a second GGML HIP backend.
@@ -1487,6 +1507,13 @@ if(STRATA_NATIVE_EXPERTS)
add_executable(hip_ple_iq4 tests/hip/ple_iq4.cpp)
target_link_libraries(hip_ple_iq4 PRIVATE strata_kernels strata_hip_runtime ggml-base)
endif()
+ # the NVFP4 AVX-512 rows vs ggml-cpu's vec_dot, and their speed (CPU only; optional arg: a pack's experts.bin)
+ add_executable(nvfp4_avx512_parity src/kernels/cpu/nvfp4_avx512_parity.cpp)
+ target_link_libraries(nvfp4_avx512_parity PRIVATE strata_kernels_cpu)
+ if(STRATA_ENABLE_CUDA) # the NVFP4 decode kernels vs ggml's reference
+ add_executable(nvfp4_expert_gpu_parity src/kernels/nvfp4_expert_gpu_parity.cpp)
+ target_link_libraries(nvfp4_expert_gpu_parity PRIVATE strata_kernels ggml-base CUDA::cudart)
+ endif()
if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_executable(native_expert_parity src/kernels/native_expert_parity.cpp)
target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories})
diff --git a/docs/NVFP4.md b/docs/NVFP4.md
new file mode 100644
index 000000000..818f08fc8
--- /dev/null
+++ b/docs/NVFP4.md
@@ -0,0 +1,147 @@
+# NVFP4 routed experts
+
+The engine can serve a Qwen3.8-Flash-Next whose routed experts are NVFP4, as NVIDIA's ModelOpt stores them: 64-value
+blocks of E2M1 codes with four UE4M3 sub-block scales, plus one FP32 `weight_scale_2` per expert and projection.
+Everything else (attention, GDN, shared experts, routers, the head) stays in the formats the native path already
+reads. Measured on Windows 11, RTX 5090 (32 GB), Ryzen 9 9950X3D, 128 GB DDR5-5600.
+
+## Getting a model
+
+```
+python tools/nvfp4_convert.py --model <ModelOpt NVFP4 checkpoint dir> --outfile <model>.gguf
+python tools/iq_pack.py --gguf <model>.gguf --out <pack dir>
+```
+
+- `nvfp4_convert.py` runs llama.cpp's own converter (`third_party/llama.cpp`, the commit setup pins) with the type
+ policy the engine needs. The experts are repacked without loss: `tools/nvfp4_verify.py` compares them with the
+ checkpoint bit for bit, and `tools/nvfp4_verify_gguf.py` checks the GGUF.
+ - The small projections the BF16 kernels read (routers, SSM gates, indexer, PLE and hyper-connection projections)
+ are written as BF16.
+ - Everything served natively goes to Q8_0: attention, `ssm_out`, the shared experts, the output head, and the
+ token embedding.
+ - The 51.2e9-value PLE table is left out.
+- `iq_pack.py` writes `experts.bin` for an NVFP4 GGUF by itself. Each blob is `[gate | up | down]` plus a 16-byte
+ tail `{s_gate, s_up, s_down, 0}`. The GGUF has no room for these scales, so the engine reads NVFP4 experts from
+ `experts.bin` only.
+
+Run it like an IQ pack, with the GGUF as its own dense-weight source and the PLE table from an IQ GGUF's PLE shard:
+
+```
+strata --pack <pack dir> --native <model>.gguf --native-dense-gguf <model>.gguf \
+ --ple-gguf <an IQ model's shard with per_layer_token_embd> --mtp <mtp/rt> \
+ --expert-profile data/expert-profile.bin --expert-cache auto --prefill auto --spec 4 ...
+```
+
+The NVFP4 checkpoints change only the routed experts. The PLE table, the MTP layer and the expert profile of the
+original model therefore work as they are.
+
+Tested end to end with `jpezzulli/OrcaRouter-Qwen3.8-Flash-Next-Uncensored-ModelOpt-NVFP4`. By its
+`hf_quant_config.json`, NVIDIA's `nvidia/Qwen3.8-Flash-Next-NVFP4` quantizes the routed experts the same way
+(NVFP4, group 16; the other layers BF16, the PLE table FP8, the MTP experts FP8), so it takes the same path. It has
+not been run here.
+
+## Measured
+
+RTX 5090, 64K context, int8 K/V, `--vram-reserve-mib 1500`:
+
+| | NVFP4 pack | IQ2_XS, same engine |
+| --- | ---: | ---: |
+| experts in RAM | 63.3 GiB | 33.0 GiB |
+| expert cache slots | ~8,350 | ~17,300 |
+| decode, 400-token answer | 114-116 tokens/s | 132-139 tokens/s |
+| a 32K prompt | 3,900 tokens/s | 5,600 tokens/s |
+
+An NVFP4 expert blob is 2.76 MB, against 1.51 MB for IQ2_XS: the cache holds half as many, and a miss costs twice
+the bytes over PCIe. The PCIe share of the missed experts is therefore 0.25 for an NVFP4 pack, not the usual 0.55.
+At 0.55 the copy kernel was 40% of all GPU kernel time (nsys, 300-token decode). A sweep at 262K context gave the
+following decode rates:
+
+| PCIe share | short prompt | 32K prompt |
+| --- | ---: | ---: |
+| 0.55 | 103 tokens/s | 105 |
+| 0.40 | 110 | 117 |
+| 0.25 | 117 | 124 |
+| 0.10 | 112 | 118 |
+
+## Where the global scales go
+
+Each scale multiplies its own projection's FP32 output, as llama.cpp applies `.scale`:
+`h = silu(s_gate * (G x)) * (s_up * (U x))`, `y = s_down * (D h)`.
+
+The scales are ~1e-4 each. Folding `s_down` into up is algebraically the same, but it leaves the hidden near 1e-5.
+The hidden is then rounded to Q8_0 (CPU) or q8_1 (GPU) blocks with an FP16 scale, and `amax / 127` lands deep in
+FP16's subnormals: one expert's output was off by 2-12% instead of 1.1% (`nvfp4_avx512_parity --expert`). The FP16
+prompt path had the same problem in its dequantized up weights (~1e-8). Any future fold must be checked against
+FP16's range.
+
+## Prompt path precision
+
+`STRATA_PREFILL_NVFP4` picks how the batched prompt path multiplies the experts:
+
+| mode | kernel | activations | one product vs FP64 (`mmq_nvfp4_parity`) |
+|---|---|---|---|
+| `w4a8` (default) | llama.cpp MMQ, int8 tensor cores | q8_1, float block scales | 0.53% |
+| `w4a4` | llama.cpp MMQ, Blackwell FP4 MMA (sm_120a only) | NVFP4 | 8.6% |
+| `fp16` | dequantize + cuBLAS FP16 GEMM | FP16 | reference |
+
+`src/prefill/mmq_nvfp4_w4a8.cu` compiles mmq.cuh's int8 NVFP4 path with Blackwell's FP4 MMA hidden from both the
+device code and the host's tile config, so it is the same on every architecture; decode already multiplies at this
+precision. The FP4 MMA exists only in the arch-specific target, so `src/prefill/mmq_nvfp4_w4a4.cu` (the FP4 x FP4
+kernel and its FP4 activation quantizer) is the one unit CMake builds with `12x` -> `12xa` (`strata_mmq_w4a4`);
+the rest of the engine keeps the architectures as given and runs on sm_121 too. A card without that unit's image
+(another architecture, or sm_121 against a 120a build) falls back to `w4a8` with a note.
+
+First-token KL divergence against `fp16`, 8 prompts (code and prose, 1K-8K tokens). The noise floor is the same
+`fp16` path cut into 4096-token chunks instead of 8192: another summation order, same arithmetic.
+
+| mode | KL mean | KL median | KL max | top-1 agreement | prefill, 4-8K prompts |
+|---|---|---|---|---|---|
+| noise floor | 0.00023 | 0.00003 | 0.0016 | 8/8 | - |
+| `w4a8` | 0.0018 | 0.0010 | 0.0096 | 8/8 | 2,503 tok/s |
+| `w4a4` | 0.0080 | 0.0027 | 0.040 | 7/8 | 2,904 tok/s |
+| `fp16` | reference | | | | 1,905 tok/s |
+
+`w4a8` is the default. It is 4.5x closer to the reference than `w4a4`, at 86% of its speed, and it is the precision
+every generated token already runs at. `fp16` is the choice when the prompt must be read exactly.
+
+`STRATA_DUMP_MOE_INPUT` + `mmq_nvfp4_parity --real` test one product on a real prompt's rows: layer 20, its 12
+busiest experts, max|x|/rms 4 median and 9 at most. The errors:
+
+| mode | gate/up | down (heavier SwiGLU tails) |
+| --- | ---: | ---: |
+| `w4a8` | 0.46% | 0.90% |
+| `w4a4` | 7.2% | 8.4% |
+| `fp16` | 0.017% | 0.021% |
+
+## CPU experts
+
+`src/kernels/cpu/nvfp4_avx512.cpp` computes the CPU pool's NVFP4 rows in 512-bit lanes. Each 64-value block is
+decoded once for every token of a verify window: `vpdpbusd` on |E2M1| codes, with the sign moved onto the
+activation. The arithmetic is ggml-cpu's `ggml_vec_dot_nvfp4_q8_0`, with the float additions ordered differently
+(worst 4.5e-7 relative, `nvfp4_avx512_parity`). `STRATA_NO_NVFP4_512=1` falls back to ggml-cpu, which is also the
+path of CPUs without AVX-512.
+
+| tokens | ggml-cpu | AVX-512 | speedup |
+|---|---|---|---|
+| 1 | 0.102 ms | 0.058 ms | 1.76x |
+| 4 | 0.410 ms | 0.125 ms | 3.29x |
+| 7 | 0.719 ms | 0.196 ms | 3.66x |
+
+These are one expert's gate+up (1280 rows of 2560, cache-resident). The pool itself is bound by DRAM.
+
+## Other GPUs
+
+Only the optional `w4a4` needs Blackwell. The default `w4a8` is ggml's int8 MMQ (sm_75 and up), and decode uses the
+engine's own q8_1 kernels, which decode UE4M3/E2M1 in software. The engine was built for sm_75/86/89 as PTX and run
+on the RTX 5090 with the host answering as that generation. On those builds `mmq_nvfp4_parity` and
+`nvfp4_expert_gpu_parity` gave results identical to sm_120.
+
+HIP: the decode kernels use no CUDA-only intrinsics. The NVFP4 MMQ instance and the W4A8 unit are CUDA-only and
+guarded (`GGML_USE_HIP`). Neither was built for HIP here.
+
+## Tests
+
+- `nvfp4_expert_gpu_parity`: the decode kernels against ggml's reference.
+- `nvfp4_avx512_parity`: the CPU rows against ggml-cpu (with `--expert`: one whole expert).
+- `mmq_nvfp4_parity`: the prompt path's products against FP64 (with `--real`: rows dumped by `STRATA_DUMP_MOE_INPUT`).
+- `tools/nvfp4_verify.py` and `tools/nvfp4_verify_gguf.py`: the conversion, bit for bit.
diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp
index 1be014326..9c3eab2ea 100644
--- a/include/strata/artifact/gguf_reader.hpp
+++ b/include/strata/artifact/gguf_reader.hpp
@@ -210,6 +210,10 @@ inline bool block_geometry(uint32_t t, int& elems, int& bytes) {
elems = 1;
bytes = 1;
return true;
+ case 40: // NVFP4: 64 values = 4 UE4M3 sub-block scales + 32 bytes of E2M1 codes
+ elems = 64;
+ bytes = 36;
+ return true;
case 42:
elems = 64;
bytes = 18;
diff --git a/include/strata/kernels/cpu/native_expert.hpp b/include/strata/kernels/cpu/native_expert.hpp
index c41a1991b..895f90c20 100644
--- a/include/strata/kernels/cpu/native_expert.hpp
+++ b/include/strata/kernels/cpu/native_expert.hpp
@@ -27,7 +27,14 @@ struct NativeFmt {
size_t up_off = 0, down_off = 0; ///< inside the blob
size_t bytes = 0; ///< the whole blob
size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act)
+ /// NVFP4 (ggml type 40) only: the blob ends with {s_gate, s_up, s_down, 0} at this offset, the per-expert
+ /// weight_scale_2 the block format has no room for (tools/iq_pack.py). 0 = no tail. Each scale goes on its own
+ /// projection's FP32 output: gate * s_gate, up * s_up, down * s_down. Do not fold s_down into up: the hidden
+ /// drops to ~1e-5 and its q8 block scale becomes an FP16 subnormal (expert error 2-12% instead of 1.1%).
+ size_t tail_off = 0;
};
+constexpr int kNvfp4Type = 40;
+constexpr size_t kNvfp4Tail = 16;
/// Whether this build has the ggml-cpu path.
bool native_experts_available() noexcept;
diff --git a/include/strata/kernels/cpu/nvfp4_avx512.hpp b/include/strata/kernels/cpu/nvfp4_avx512.hpp
new file mode 100644
index 000000000..d9ba296d6
--- /dev/null
+++ b/include/strata/kernels/cpu/nvfp4_avx512.hpp
@@ -0,0 +1,28 @@
+// include/strata/kernels/cpu/nvfp4_avx512.hpp - NVFP4 expert rows in 512-bit lanes, several tokens at once.
+//
+// ggml-cpu's NVFP4 dot product (ggml_vec_dot_nvfp4_q8_0) is AVX2 and single-token: every token of a verify window
+// re-decodes the same weights. These decode a 64-value block once and apply it to every token. The arithmetic is
+// ggml's: an exact integer sum per 16-value sub-block, times the sub-block's UE4M3 scale and the Q8_0 block's scale;
+// only the order of the float additions differs. Activations are Q8_0, NVFP4's vec_dot_type in ggml-cpu.
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace strata::kernels::cpu {
+
+/// Whether rows of `n` values fit the kernels (whole 64-value blocks, at most 64 of them).
+bool nvfp4_512_fits(int n);
+
+/// Gate/up rows [r0, r1) of an NVFP4 expert blob for `nt` tokens: ff[t][r] = silu(s_gate * g) * (s_up * u), where g
+/// and u are the raw NVFP4 dot products of gate row r and up row r (at `up_off`) with activation t (Q8_0, `n` values).
+/// `s_gate` / `s_up` are the expert's global scales from its blob tail.
+void nvfp4_512_gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
+ float* const* ff, int r0, int r1, float s_gate, float s_up);
+
+/// Plain rows [r0, r1) of an NVFP4 matrix (`row_bytes` apart) against `nt` Q8_0 activations of `n` values, times
+/// `scale` (the down matrix's s_down).
+void nvfp4_512_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
+ int r0, int r1, float scale = 1.f);
+
+} // namespace strata::kernels::cpu
diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp
index bd7599f7b..0a39f6460 100644
--- a/include/strata/kernels/iq_kernels.hpp
+++ b/include/strata/kernels/iq_kernels.hpp
@@ -25,17 +25,20 @@ void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y,
/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column).
void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream);
-/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32.
-void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream);
+/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32; fp16 times `*scale` when given (device:
+/// an NVFP4 expert's s_down, read by the kernel itself so the source may be released right after it).
+void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale = nullptr);
void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream);
/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped
/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256).
void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
int64_t n_embd, float* out, void* stream);
/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path
-/// uses: row 2r = gate row r, row 2r+1 = up row r.
+/// uses: row 2r = gate row r, row 2r+1 = up row r. `tail` (device, NVFP4 only): the blob's {s_gate, s_up,
+/// s_down, 0}; gate rows are scaled by s_gate and up rows by s_up (s_down goes on the down matrix: folded into up,
+/// the up weights would sit near 1e-8, deep in FP16's subnormals).
void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst,
- void* stream);
+ void* stream, const float* tail = nullptr);
/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.
struct NativeExpertLayout {
@@ -44,6 +47,7 @@ struct NativeExpertLayout {
size_t gu_row = 0, d_row = 0; // bytes per row
size_t up_off = 0, down_off = 0; // byte offsets inside the blob
size_t bytes = 0; // the whole blob
+ size_t tail_off = 0; // NVFP4: {s_gate, s_up, s_down, 0} at the blob's end; 0 = none
};
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the
diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp
index 34cc5f662..c98bea9e1 100644
--- a/include/strata/prefill/kernels.hpp
+++ b/include/strata/prefill/kernels.hpp
@@ -87,7 +87,7 @@ void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream);
void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream);
/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :]
void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
- int64_t T, void* stream);
+ int64_t T, void* stream, const float* row_sd = nullptr);
/// --peer-device's prompt share as sums: bo[t, :] = (sum over the k with slot[t, k] < rows_local of w[t, k] *
/// D[slot[t, k], :], in k order) + peer[t, :] + shared[t, :] * sigmoid(sg[t]). `peer` (the peer's per-token sums)
/// may be mapped host memory.
diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp
index 5c5dd7122..7c37fb419 100644
--- a/include/strata/prefill/moe_mmq.hpp
+++ b/include/strata/prefill/moe_mmq.hpp
@@ -12,14 +12,19 @@ namespace strata::prefill::mmq {
/// This build has the MMQ path (the ggml sources were available to the build).
bool built();
-/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, and with STRATA_MMQ_KQUANTS the
-/// K-quants Q4_K / Q5_K / Q5_1 / Q6_K: Unsloth's UD-Q4_K_XL experts (CUDA), and the dense GGUF projections of
-/// the mixed-quant packs through Gemm::native's STRATA_DENSE_MMQ path (HIP); IQ1_M is not covered).
+/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, NVFP4 unless fp16, and with
+/// STRATA_MMQ_KQUANTS the K-quants Q4_K / Q5_K / Q5_1 / Q6_K: Unsloth's UD-Q4_K_XL experts (CUDA), and the dense GGUF
+/// projections of the mixed-quant packs through Gemm::native's STRATA_DENSE_MMQ path (HIP); IQ1_M is not covered).
bool supported(int ggml_type);
/// #420: `supported`, and on every visible GPU llama.cpp's MMQ has a tile for this type and a weight matrix of
/// `w_rows` rows that fits the card's shared memory - the same test its tile choice makes, which aborts the process
/// ("J_best=0") when nothing fits. false (said once per type) keeps that product on the non-MMQ path.
bool fits(int ggml_type, int64_t w_rows);
+/// NVFP4 prompt precision, STRATA_PREFILL_NVFP4: w4a8 (default) - int8 tensor cores, Q8_1 activations, what decode
+/// runs at; w4a4 - Blackwell's FP4 x FP4 MMA, activations rounded to NVFP4 (faster, first-token KL up to 0.03 vs
+/// fp16); fp16 - the dequantize + FP16 GEMM path (the reference).
+enum class Nvfp4Mode { W4A8, W4A4, FP16 };
+Nvfp4Mode nvfp4_mode();
/// Bytes of one expert's gate+up ([2*n_ff, n_embd]) or down ([n_embd, n_ff]) weights in `ggml_type`.
size_t matrix_bytes(int ggml_type, int64_t rows, int64_t cols);
/// Bytes of `rows` activation rows of `cols` values quantized for MMQ (the row padded to 512 values).
@@ -28,7 +33,19 @@ size_t q8_bytes(int64_t rows, int64_t cols);
/// q8_1 activations for MMQ against weights of `ggml_type`: row i of the output is row ids[i] of x (or row i when
/// ids is null); `x` has `ld` floats per row.
void quantize(const float* x, const int32_t* ids, void* xq, int ggml_type, int64_t cols, int64_t ld, int64_t rows,
- void* stream);
+ void* stream, float* yscale = nullptr);
+/// NVFP4 on Blackwell in w4a4 mode: the MMQ kernel multiplies FP4 x FP4, so its activations are NVFP4 too, with
+/// one float scale per row that `quantize` writes to `yscale` and the product reads as Product::y_scale. Decided
+/// by the mode and a device probe of the same compile.
+bool fp4_activations(int ggml_type);
+/// NVFP4 expert tails: GU rows [row0, row0 + nrows) of a group of `n` experts (absolute `bounds`, n + 1 of them,
+/// on the device) scaled by their expert's {s_gate, s_up, s_down, 0} (`tails`, 4 floats each, on the device): the
+/// gate half by s_gate, the up half by s_up.
+void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, int n, const float* tails,
+ int64_t row0, int64_t nrows, void* stream);
+/// The down product's rows [0, nrows) (`ld` floats each, relative `bounds`) times their expert's s_down - on the FP32
+/// output, not folded into up, where the hidden would sit near 1e-5 (FP16-subnormal block scales in q8 formats).
+void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream);
/// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows
/// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into
@@ -46,6 +63,7 @@ struct Product {
int64_t total_rows = 0, max_rows = 0;
float* dst = nullptr;
int64_t ld_dst = 0;
+ const float* y_scale = nullptr; ///< NVFP4 w4a4: the per-row activation scales (fp4_activations)
};
/// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path.
@@ -63,18 +81,24 @@ private:
/// A GGUF-native expert (gate at `gate`, up at `up`, down at `down`, each its GGUF rows) into a group buffer's
/// slot: gate rows then up rows at `gu_dst`, down at `d_dst`.
+/// `tail` (16 bytes, may be null) goes to `tail_dst`; `zero_bytes` zeroed right after gu_dst's and d_dst's copies
+/// (the MMQ tail after a group's last expert).
void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes,
- void* gu_dst, void* d_dst, void* stream);
+ void* gu_dst, void* d_dst, void* stream, const void* tail = nullptr, void* tail_dst = nullptr,
+ size_t zero_bytes = 0);
/// gather_native for an MMQ group's experts [first, n) in ONE launch: expert q's blob (`blob[q]`; gate at +0, up at
/// +up_off, down at +down_off) to gu_dst + q * gu_stride and d_dst + q * d_stride - the same bytes as one gather_native
/// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time).
+/// NVFP4: `tail_off` (0 = none) is each blob's 16-byte tail, copied to tail_dst + 16 q; `zero_bytes` are zeroed after
+/// the last expert's gu and d slots (the MMQ tail).
constexpr int kGatherGroupMax = 16;
struct GatherGroup {
const uint8_t* blob[kGatherGroupMax] = {};
int first = 0, n = 0;
};
bool gather_native_group(const GatherGroup& g, size_t up_off, size_t gu_half_bytes, size_t down_off, size_t d_bytes,
- void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream);
+ void* gu_dst, size_t gu_stride, void* d_dst, size_t d_stride, void* stream,
+ size_t tail_off = 0, void* tail_dst = nullptr, size_t zero_bytes = 0);
/// A Strata-pack Q2_0 expert blob (codes and fp16 scales in separate planes, gate/up rows interleaved) into GGUF
/// Q2_0 blocks: gate/up [1280, 2560] at `gu_dst` (rows stay interleaved), down [2560, 640] at `d_dst`. Same values.
void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream);
@@ -82,6 +106,11 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre
/// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split
/// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats).
void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream);
+/// swiglu of an NVFP4 group's gate/up rows (split halves) with scale_gu_rows' scales applied as they are read.
+void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n,
+ const float* tails, int64_t row0, void* stream);
+/// sd[r] = the s_down of row r's expert (group-local bounds): the combine applies it as it reads the row.
+void down_row_scales(float* sd, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream);
/// dst[i] = i for i < n (the identity row map MMQ's MoE mode writes through).
void iota(int32_t* dst, int64_t n, void* stream);
diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp
index 78e3cbaa0..5b54e4743 100644
--- a/src/kernels/cpu/native_expert.cpp
+++ b/src/kernels/cpu/native_expert.cpp
@@ -7,6 +7,7 @@
#include "strata/kernels/cpu/iq_avx2.hpp"
#include "strata/kernels/cpu/iq_avx1.hpp"
#include "strata/kernels/cpu/kq_avx2.hpp"
+#include "strata/kernels/cpu/nvfp4_avx512.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "ggml.h"
@@ -14,6 +15,7 @@
#include <cmath>
#include <cstdlib>
+#include <cstring>
#include <mutex>
namespace strata::kernels::cpu {
@@ -74,6 +76,14 @@ bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt
f.up_off = f.gu_row * (size_t) n_ff;
f.down_off = 2 * f.up_off;
f.bytes = f.down_off + f.d_row * (size_t) n_embd;
+ if (gu_type == kNvfp4Type || d_type == kNvfp4Type) {
+ if (gu_type != kNvfp4Type || d_type != kNvfp4Type) {
+ err = "native experts: NVFP4 must cover gate, up and down alike (one scale tail per blob)";
+ return false;
+ }
+ f.tail_off = f.bytes;
+ f.bytes += kNvfp4Tail;
+ }
f.act_bytes = ggml_row_size(tg->vec_dot_type, n_embd);
f.h_bytes = ggml_row_size(td->vec_dot_type, n_ff);
if (f.act_bytes > kNativeActBytes || f.h_bytes > kNativeHBytes) {
@@ -182,8 +192,24 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
iq128_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1);
return;
}
- const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot;
const int n = (int) f.n_embd;
+ // NVFP4: the per-expert global scales from the blob's tail (1 and 1 otherwise). s_down goes on the down output:
+ // folded into up it left the hidden near 1e-5, whose Q8_0 block scale is an FP16 subnormal (expert error 2-12%)
+ float sg = 1.f, su = 1.f;
+ if (f.tail_off) {
+ float tail[4];
+ std::memcpy(tail, blob + f.tail_off, sizeof tail);
+ sg = tail[0];
+ su = tail[1];
+ }
+ // NVFP4 in 512-bit lanes: ggml's arithmetic, blocks decoded once per window; 1.8x at one token, 3.7x at seven
+ // (nvfp4_avx512_parity). STRATA_NO_NVFP4_512 falls back to ggml-cpu.
+ static const bool nvfp4_512 = cpu_avx512_ok() && std::getenv("STRATA_NO_NVFP4_512") == nullptr;
+ if (f.gu_type == kNvfp4Type && nvfp4_512 && nvfp4_512_fits(n)) {
+ nvfp4_512_gu_rows(blob, f.gu_row, f.up_off, n, act, nt, ff, r0, r1, sg, su);
+ return;
+ }
+ const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot;
for (int r = r0; r < r1; ++r) {
const uint8_t* gr = blob + (size_t) r * f.gu_row;
const uint8_t* ur = blob + f.up_off + (size_t) r * f.gu_row;
@@ -191,6 +217,8 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
float g = 0.f, u = 0.f;
dot(n, &g, 0, gr, 0, act[t], 0, 1);
dot(n, &u, 0, ur, 0, act[t], 0, 1);
+ g *= sg;
+ u *= su;
ff[t][r] = (g / (1.f + std::exp(-g))) * u;
}
}
@@ -220,14 +248,21 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const
iq128_down_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1);
return;
}
- const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot;
const int n = (int) f.n_ff;
+ float sd = 1.f; // NVFP4: the expert's s_down (see native_gu_rows)
+ if (f.tail_off) std::memcpy(&sd, blob + f.tail_off + 2 * sizeof(float), sizeof sd);
+ static const bool nvfp4_512 = cpu_avx512_ok() && std::getenv("STRATA_NO_NVFP4_512") == nullptr;
+ if (f.d_type == kNvfp4Type && nvfp4_512 && nvfp4_512_fits(n)) {
+ nvfp4_512_rows(blob + f.down_off, f.d_row, n, hq, nt, out, r0, r1, sd);
+ return;
+ }
+ const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot;
for (int r = r0; r < r1; ++r) {
const uint8_t* dr = blob + f.down_off + (size_t) r * f.d_row;
for (int t = 0; t < nt; ++t) {
float s = 0.f;
dot(n, &s, 0, dr, 0, hq[t], 0, 1);
- out[t][r] = s;
+ out[t][r] = s * sd;
}
}
}
diff --git a/src/kernels/cpu/nvfp4_avx512.cpp b/src/kernels/cpu/nvfp4_avx512.cpp
new file mode 100644
index 000000000..b5e2cbf02
--- /dev/null
+++ b/src/kernels/cpu/nvfp4_avx512.cpp
@@ -0,0 +1,186 @@
+// src/kernels/cpu/nvfp4_avx512.cpp - see include/strata/kernels/cpu/nvfp4_avx512.hpp.
+//
+// Per 64-value block, once: the 64 E2M1 codes in element order, their magnitudes from |kvalues_fp4| (0..12, the
+// doubled E2M1 values), a sign mask (code bit 3), and the four sub-block scales. Per token: the sign moves onto the
+// activation (a masked subtract - Q8_0 is quantized to [-127, 127], so negation never overflows), one vpdpbusd gives
+// 16 int32 lanes = four per 16-value sub-block, and one FMA applies ue4m3(d[s]) * d_q8. The UE4M3 decode is ggml's
+// CPU one (ggml-impl.h ggml_ue4m3_to_fp32): halved for the doubled table, 0x7F read as 0.
+//
+// Needs AVX512F/BW/VL and VNNI - what cpu_avx512_ok() checks before anything here is called.
+#include "strata/kernels/cpu/nvfp4_avx512.hpp"
+
+#define GGML_COMMON_DECL_CPP
+#define GGML_COMMON_IMPL_CPP
+#include "ggml-common.h"
+
+#include <immintrin.h>
+
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+
+namespace strata::kernels::cpu {
+namespace {
+
+struct Ue4m3Table {
+ float v[256];
+ Ue4m3Table() {
+ for (int x = 0; x < 256; ++x) {
+ if (x == 0 || x == 0x7F) { v[x] = 0.0f; continue; }
+ const int e = (x >> 3) & 0xF, m = x & 0x7;
+ const float raw = e == 0 ? std::ldexp((float) m, -9) : std::ldexp(1.0f + (float) m / 8.0f, e - 7);
+ v[x] = raw * 0.5f;
+ }
+ }
+};
+const Ue4m3Table kUe4m3;
+
+// software prefetch distance in bytes (STRATA_NVFP4_PREFETCH, 0 = off): the rows stream from DRAM through 4 KB
+// pages, where the hardware prefetchers stop at every page boundary; the IQ kernel's E-2 knob, same default
+const int prefetch_ahead = [] {
+ const char* v = std::getenv("STRATA_NVFP4_PREFETCH");
+ return v ? std::atoi(v) : 2048;
+}();
+
+inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); }
+
+// The block's 64 codes in element order. Sub-block s keeps its codes in qs[8 s .. 8 s + 7]: byte j holds value j
+// in its low nibble and value j + 8 in its high one, so a sub-block is [low nibbles, high nibbles] of its 8 bytes.
+inline __m512i codes64(const uint8_t* qs) {
+ const __m256i q = _mm256_loadu_si256((const __m256i*) qs);
+ const __m256i m4 = _mm256_set1_epi8(0x0F);
+ const __m256i lo = _mm256_and_si256(q, m4);
+ const __m256i hi = _mm256_and_si256(_mm256_srli_epi16(q, 4), m4);
+ const __m256i ul = _mm256_unpacklo_epi64(lo, hi); // [lo 0-7, hi 0-7 | lo 16-23, hi 16-23]
+ const __m256i uh = _mm256_unpackhi_epi64(lo, hi); // [lo 8-15, hi 8-15 | lo 24-31, hi 24-31]
+ const __m256i s01 = _mm256_permute2x128_si256(ul, uh, 0x20); // sub-blocks 0, 1
+ const __m256i s23 = _mm256_permute2x128_si256(ul, uh, 0x31); // sub-blocks 2, 3
+ return _mm512_inserti64x4(_mm512_castsi256_si512(s01), s23, 1);
+}
+
+// lanes 4 s .. 4 s + 3 = ue4m3(d[s])
+inline __m512 sub_scales(const uint8_t* d) {
+ const __m128 s4 = _mm_setr_ps(kUe4m3.v[d[0]], kUe4m3.v[d[1]], kUe4m3.v[d[2]], kUe4m3.v[d[3]]);
+ const __m512i idx = _mm512_setr_epi32(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3);
+ return _mm512_permutexvar_ps(idx, _mm512_castps128_ps512(s4));
+}
+
+// Per token and block, the activation's scales as lanes: 0-7 -> the first Q8_0 block's d (sub-blocks 0, 1),
+// 8-15 -> the second's (sub-blocks 2, 3). Built once per call, reused by every row.
+constexpr int kMaxBlocks = 64; // rows of up to 4096 values (n_embd 2560)
+struct Acts {
+ int nt = 0, nb = 0;
+ const block_q8_0* y[7] = {};
+ __m512 dy[7 * kMaxBlocks]; // [t * nb + ib]; on the stack, no allocation
+ Acts(const void* const* act, int nt_, int nb_) : nt(nt_), nb(nb_) {
+ for (int t = 0; t < nt; ++t) {
+ y[t] = (const block_q8_0*) act[t];
+ for (int ib = 0; ib < nb; ++ib) {
+ const block_q8_0* yb = y[t] + 2 * ib;
+ dy[(size_t) t * nb + ib] = _mm512_mask_blend_ps((__mmask16) 0xFF00, _mm512_set1_ps(h2f(yb[0].d)),
+ _mm512_set1_ps(h2f(yb[1].d)));
+ }
+ }
+ }
+};
+
+template <int NT>
+inline void row_dot(const uint8_t* row, const Acts& a, float* res) {
+ const __m512i mag = _mm512_broadcast_i32x4(_mm_setr_epi8(0, 1, 2, 3, 4, 6, 8, 12, 0, 1, 2, 3, 4, 6, 8, 12));
+ const __m512i eight = _mm512_set1_epi8(8);
+ const __m512i zero = _mm512_setzero_si512();
+ __m512 acc[NT];
+ for (int t = 0; t < NT; ++t) acc[t] = _mm512_setzero_ps();
+ const block_nvfp4* x = (const block_nvfp4*) row;
+ for (int ib = 0; ib < a.nb; ++ib) {
+ if (prefetch_ahead > 0) _mm_prefetch((const char*) (x + ib) + prefetch_ahead, _MM_HINT_T0);
+ const __m512i codes = codes64(x[ib].qs);
+ const __m512i g = _mm512_shuffle_epi8(mag, codes);
+ const __mmask64 neg = _mm512_test_epi8_mask(codes, eight);
+ const __m512 sw = sub_scales(x[ib].d);
+ for (int t = 0; t < NT; ++t) {
+ const block_q8_0* yb = a.y[t] + 2 * ib;
+ const __m512i yv = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_loadu_si256((const __m256i*) yb[0].qs)),
+ _mm256_loadu_si256((const __m256i*) yb[1].qs), 1);
+ const __m512i ys = _mm512_mask_sub_epi8(yv, neg, zero, yv);
+ const __m512i p = _mm512_dpbusd_epi32(zero, g, ys);
+ acc[t] = _mm512_fmadd_ps(_mm512_mul_ps(sw, a.dy[(size_t) t * a.nb + ib]), _mm512_cvtepi32_ps(p), acc[t]);
+ }
+ }
+ for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]);
+}
+
+template <int NT>
+void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, const Acts& a, float* const* ff, int r0, int r1,
+ float sg, float su) {
+ float g[NT], u[NT];
+ for (int r = r0; r < r1; ++r) {
+ row_dot<NT>(blob + (size_t) r * gu_row, a, g);
+ row_dot<NT>(blob + up_off + (size_t) r * gu_row, a, u);
+ for (int t = 0; t < NT; ++t) {
+ const float gs = g[t] * sg;
+ ff[t][r] = (gs / (1.f + std::exp(-gs))) * (u[t] * su);
+ }
+ }
+}
+
+template <int NT>
+void dot_rows(const uint8_t* w, size_t row_bytes, const Acts& a, float* const* out, int r0, int r1, float scale) {
+ float res[NT];
+ for (int r = r0; r < r1; ++r) {
+ row_dot<NT>(w + (size_t) r * row_bytes, a, res);
+ for (int t = 0; t < NT; ++t) out[t][r] = res[t] * scale;
+ }
+}
+
+} // namespace
+
+bool nvfp4_512_fits(int n) { return n % QK_NVFP4 == 0 && n / QK_NVFP4 <= kMaxBlocks; }
+
+// Windows wider than 7 run in balanced slices of at most 7: at 8 the accumulators no longer fit beside the loads and
+// MSVC spills (measured 0.32 ms for 8 tokens against 2 x 0.13 for 4 + 4).
+template <typename F>
+inline void slices(int nt, F&& run) {
+ const int k = (nt + 6) / 7;
+ for (int i = 0, t0 = 0; i < k; ++i) {
+ const int w = nt / k + (i < nt % k ? 1 : 0);
+ run(t0, w);
+ t0 += w;
+ }
+}
+
+void nvfp4_512_gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
+ float* const* ff, int r0, int r1, float s_gate, float s_up) {
+ slices(nt, [&](int t0, int w) {
+ const Acts a(act + t0, w, n / QK_NVFP4);
+ float* const* f = ff + t0;
+ switch (w) {
+ case 1: gu_rows<1>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ case 2: gu_rows<2>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ case 3: gu_rows<3>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ case 4: gu_rows<4>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ case 5: gu_rows<5>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ case 6: gu_rows<6>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ default: gu_rows<7>(blob, gu_row, up_off, a, f, r0, r1, s_gate, s_up); break;
+ }
+ });
+}
+
+void nvfp4_512_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
+ int r0, int r1, float scale) {
+ slices(nt, [&](int t0, int k) {
+ const Acts a(act + t0, k, n / QK_NVFP4);
+ float* const* o = out + t0;
+ switch (k) {
+ case 1: dot_rows<1>(w, row_bytes, a, o, r0, r1, scale); break;
+ case 2: dot_rows<2>(w, row_bytes, a, o, r0, r1, scale); break;
+ case 3: dot_rows<3>(w, row_bytes, a, o, r0, r1, scale); break;
+ case 4: dot_rows<4>(w, row_bytes, a, o, r0, r1, scale); break;
+ case 5: dot_rows<5>(w, row_bytes, a, o, r0, r1, scale); break;
+ case 6: dot_rows<6>(w, row_bytes, a, o, r0, r1, scale); break;
+ default: dot_rows<7>(w, row_bytes, a, o, r0, r1, scale); break;
+ }
+ });
+}
+
+} // namespace strata::kernels::cpu
diff --git a/src/kernels/cpu/nvfp4_avx512_parity.cpp b/src/kernels/cpu/nvfp4_avx512_parity.cpp
new file mode 100644
index 000000000..4ce78e353
--- /dev/null
+++ b/src/kernels/cpu/nvfp4_avx512_parity.cpp
@@ -0,0 +1,320 @@
+// src/kernels/cpu/nvfp4_avx512_parity.cpp - the AVX-512 NVFP4 rows against ggml-cpu's own dot product.
+//
+// nvfp4_avx512_parity [pack/experts.bin]
+//
+// Parity: every row x every token of the multi-token kernel against ggml_vec_dot_nvfp4_q8_0 on the same Q8_0
+// activation. Both sum each 16-value sub-block exactly in integers; only the float additions are ordered differently,
+// so the check is a relative tolerance, not equality. Random blocks cover every code and a wide scale range; a real
+// expert (layer 0, expert 0 of a pack's experts.bin) covers the checkpoint's own distribution.
+// Also the down rows (n 640) and gate/up through silu with the blob tail's scales, 1..9 tokens (past one slice).
+// Speed: gate+up rows of one expert for 1..8 tokens, both ways, as the CPU pool runs them.
+//
+// nvfp4_avx512_parity --bw THREADS TOKENS [ggml]
+// nvfp4_avx512_parity --expert pack/experts.bin [layer expert]
+//
+// --expert: one whole expert as decode runs it (Q8_0 input, gate/up + silu, Q8_0 of the hidden, down) against a
+// double-precision reference with the checkpoint's global scales, with s_down folded into up (the hidden becomes
+// ~1e-5 and its Q8_0 scale an FP16 subnormal) and with s_down applied to the output instead.
+//
+// DRAM rate: THREADS threads each run whole experts (gate/up through silu, then down) out of 4.2 GB of blobs -
+// 40x the L3 - for TOKENS tokens; GB/s of weights read. STRATA_NVFP4_PREFETCH sets the kernel's prefetch distance.
+#include "strata/kernels/cpu/nvfp4_avx512.hpp"
+
+#include "ggml.h"
+#include "ggml-cpu.h"
+
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <random>
+#include <thread>
+#include <string>
+#include <vector>
+
+using strata::kernels::cpu::nvfp4_512_gu_rows;
+using strata::kernels::cpu::nvfp4_512_rows;
+
+namespace {
+
+constexpr int N = 2560, ROWS = 1280, BLK = 36; // an expert's gate+up: 1280 rows of 2560 values
+constexpr int FF = 640; // its down: 2560 rows of 640
+constexpr size_t ROW_BYTES = (size_t) N / 64 * BLK, D_ROW = (size_t) FF / 64 * BLK;
+constexpr size_t BLOB = (size_t) ROWS * ROW_BYTES + (size_t) N * D_ROW + 16;
+
+double now_ms() {
+ return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+struct Acts {
+ std::vector<std::vector<uint8_t>> q;
+ std::vector<const void*> p;
+ Acts(int n, int nt, std::mt19937& rng) : q(nt), p(nt) {
+ const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::vector<float> x(n);
+ for (int t = 0; t < nt; ++t) {
+ for (float& v : x) v = nd(rng) * (t + 1); // several magnitudes
+ q[t].resize(ggml_row_size(GGML_TYPE_Q8_0, n));
+ ta->from_float(x.data(), q[t].data(), n);
+ p[t] = q[t].data();
+ }
+ }
+};
+
+float ref_dot(const uint8_t* row, int n, const void* a) {
+ float s = 0.f;
+ ggml_get_type_traits_cpu(GGML_TYPE_NVFP4)->vec_dot(n, &s, 0, row, 0, a, 0, 1);
+ return s;
+}
+
+int report(const std::vector<std::vector<float>>& mine, const std::vector<std::vector<float>>& ref,
+ int nt, int rows, double& worst) {
+ int bad = 0;
+ for (int t = 0; t < nt; ++t) {
+ double scale = 0;
+ for (int r = 0; r < rows; ++r) scale = std::fmax(scale, std::fabs(ref[t][r]));
+ for (int r = 0; r < rows; ++r) {
+ const double e = std::fabs((double) mine[t][r] - ref[t][r]) / (scale > 0 ? scale : 1);
+ worst = std::fmax(worst, e);
+ if (!(e <= 1e-5)) ++bad;
+ }
+ }
+ return bad;
+}
+
+// plain rows: `rows` rows of `n` values, `row_bytes` apart
+int check_rows(const uint8_t* w, int n, size_t row_bytes, int rows, const char* what, std::mt19937& rng) {
+ constexpr int NT = 9; // past one slice: 9 = 5 + 4
+ Acts a(n, NT, rng);
+ std::vector<std::vector<float>> mine(NT, std::vector<float>(rows)), ref(NT, std::vector<float>(rows));
+ std::vector<float*> op(NT);
+ for (int t = 0; t < NT; ++t) op[t] = mine[t].data();
+ int bad = 0;
+ double worst = 0;
+ for (int nt = 1; nt <= NT; ++nt) {
+ nvfp4_512_rows(w, row_bytes, n, a.p.data(), nt, op.data(), 0, rows);
+ for (int t = 0; t < nt; ++t)
+ for (int r = 0; r < rows; ++r) ref[t][r] = ref_dot(w + (size_t) r * row_bytes, n, a.p[t]);
+ bad += report(mine, ref, nt, rows, worst);
+ }
+ std::printf("%-34s worst |mine - ggml| / max|ggml| = %.2e over %d rows x 1..%d tokens, %d beyond 1e-5\n", what,
+ worst, rows, NT, bad);
+ return bad;
+}
+
+// gate/up with the blob tail's scales: silu(s_gate g) * (s_up u), as native_gu_rows' ggml path computes it
+int check_gu(const uint8_t* blob, std::mt19937& rng) {
+ constexpr int NT = 9, F = ROWS / 2;
+ float tail[4];
+ std::memcpy(tail, blob + BLOB - 16, sizeof tail);
+ const float sg = tail[0], su = tail[1];
+ const size_t up_off = (size_t) F * ROW_BYTES;
+ Acts a(N, NT, rng);
+ std::vector<std::vector<float>> mine(NT, std::vector<float>(F)), ref(NT, std::vector<float>(F));
+ std::vector<float*> op(NT);
+ for (int t = 0; t < NT; ++t) op[t] = mine[t].data();
+ int bad = 0;
+ double worst = 0;
+ for (int nt = 1; nt <= NT; ++nt) {
+ nvfp4_512_gu_rows(blob, ROW_BYTES, up_off, N, a.p.data(), nt, op.data(), 0, F, sg, su);
+ for (int t = 0; t < nt; ++t)
+ for (int r = 0; r < F; ++r) {
+ const float g = ref_dot(blob + (size_t) r * ROW_BYTES, N, a.p[t]) * sg;
+ const float u = ref_dot(blob + up_off + (size_t) r * ROW_BYTES, N, a.p[t]) * su;
+ ref[t][r] = (g / (1.f + std::exp(-g))) * u;
+ }
+ bad += report(mine, ref, nt, F, worst);
+ }
+ std::printf("%-34s worst |mine - ggml| / max|ggml| = %.2e over %d rows x 1..%d tokens, %d beyond 1e-5 "
+ "(s_gate %.3g, s_up %.3g)\n", "expert 0: silu(gate) * up", worst, F, NT, bad, sg, su);
+ return bad;
+}
+
+void speed(const std::vector<uint8_t>& w, std::mt19937& rng) {
+ const ggml_type_traits_cpu* tw = ggml_get_type_traits_cpu(GGML_TYPE_NVFP4);
+ const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(tw->vec_dot_type);
+ const size_t act_bytes = ggml_row_size(tw->vec_dot_type, N);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::vector<std::vector<uint8_t>> act(8, std::vector<uint8_t>(act_bytes));
+ std::vector<float> x(N), sink(8 * ROWS);
+ const void* ap[8];
+ float* op[8];
+ for (int t = 0; t < 8; ++t) {
+ for (float& v : x) v = nd(rng);
+ ta->from_float(x.data(), act[t].data(), N);
+ ap[t] = act[t].data();
+ op[t] = sink.data() + (size_t) t * ROWS;
+ }
+ std::printf("\n%-6s %12s %12s %8s (one expert's gate+up, %d rows; best of 20)\n", "tokens", "ggml ms", "avx512 ms",
+ "speedup", ROWS);
+ for (int nt = 1; nt <= 8; ++nt) {
+ double tg = 1e30, tm = 1e30;
+ for (int rep = 0; rep < 20; ++rep) {
+ double t0 = now_ms();
+ for (int t = 0; t < nt; ++t)
+ for (int r = 0; r < ROWS; ++r) tw->vec_dot(N, &op[t][r], 0, w.data() + (size_t) r * ROW_BYTES, 0, ap[t], 0, 1);
+ tg = std::fmin(tg, now_ms() - t0);
+ t0 = now_ms();
+ nvfp4_512_rows(w.data(), ROW_BYTES, N, ap, nt, op, 0, ROWS);
+ tm = std::fmin(tm, now_ms() - t0);
+ }
+ std::printf("%-6d %12.3f %12.3f %7.2fx\n", nt, tg, tm, tg / tm);
+ }
+}
+
+int bandwidth(int threads, int nt, bool use_ggml) {
+ constexpr int E = 1536;
+ std::vector<uint8_t> blobs((size_t) E * BLOB);
+ {
+ std::vector<std::thread> fill;
+ for (int t = 0; t < 16; ++t)
+ fill.emplace_back([&, t] {
+ uint64_t x = 0x9E3779B97F4A7C15ull * (t + 1);
+ const size_t n8 = blobs.size() / 8, a = n8 * t / 16, b = n8 * (t + 1) / 16;
+ for (size_t i = a; i < b; ++i) {
+ x ^= x << 13; x ^= x >> 7; x ^= x << 17;
+ uint64_t v = x & 0x3F3F3F3F3F3F3F3Full; // scale bytes stay finite; codes are any nibble
+ std::memcpy(blobs.data() + 8 * i, &v, 8);
+ }
+ });
+ for (auto& f : fill) f.join();
+ }
+ std::mt19937 rng(7);
+ Acts ax(N, nt, rng), ah(FF, nt, rng);
+ const ggml_type_traits_cpu* tw = ggml_get_type_traits_cpu(GGML_TYPE_NVFP4);
+ double best = 1e30;
+ for (int pass = 0; pass < 3; ++pass) {
+ const double t0 = now_ms();
+ std::vector<std::thread> pool;
+ for (int w = 0; w < threads; ++w)
+ pool.emplace_back([&, w] {
+ std::vector<float> ff((size_t) nt * (ROWS / 2)), out((size_t) nt * N);
+ std::vector<float*> fp(nt), op(nt);
+ for (int t = 0; t < nt; ++t) { fp[t] = ff.data() + (size_t) t * (ROWS / 2); op[t] = out.data() + (size_t) t * N; }
+ for (int e = w; e < E; e += threads) {
+ const uint8_t* b = blobs.data() + (size_t) e * BLOB;
+ const size_t up_off = (size_t) (ROWS / 2) * ROW_BYTES, d_off = (size_t) ROWS * ROW_BYTES;
+ if (!use_ggml) {
+ nvfp4_512_gu_rows(b, ROW_BYTES, up_off, N, ax.p.data(), nt, fp.data(), 0, ROWS / 2, 1.f, 1.f);
+ nvfp4_512_rows(b + d_off, D_ROW, FF, ah.p.data(), nt, op.data(), 0, N);
+ } else {
+ for (int r = 0; r < ROWS / 2; ++r)
+ for (int t = 0; t < nt; ++t) {
+ float g = 0.f, u = 0.f;
+ tw->vec_dot(N, &g, 0, b + (size_t) r * ROW_BYTES, 0, ax.p[t], 0, 1);
+ tw->vec_dot(N, &u, 0, b + up_off + (size_t) r * ROW_BYTES, 0, ax.p[t], 0, 1);
+ fp[t][r] = (g / (1.f + std::exp(-g))) * u;
+ }
+ for (int r = 0; r < N; ++r)
+ for (int t = 0; t < nt; ++t) tw->vec_dot(FF, &op[t][r], 0, b + d_off + (size_t) r * D_ROW, 0, ah.p[t], 0, 1);
+ }
+ }
+ });
+ for (auto& p : pool) p.join();
+ best = std::fmin(best, now_ms() - t0);
+ }
+ const char* pf = std::getenv("STRATA_NVFP4_PREFETCH");
+ std::printf("%s threads %d tokens %d prefetch %s: %.1f ms for %d experts -> %.1f GB/s, %.1f us/expert/thread\n",
+ use_ggml ? "ggml " : "avx512", threads, nt, use_ggml ? "-" : (pf ? pf : "2048"), best, E,
+ (double) E * BLOB / best / 1e6, best * 1000.0 * threads / E);
+ return 0;
+}
+
+int expert_e2e(const char* path, int layer, int e) {
+ constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
+ std::vector<uint8_t> b(BLOB);
+ std::ifstream f(path, std::ios::binary);
+ f.seekg((std::streamoff) (layer * LAYER + (size_t) e * STRIDE));
+ if (!f.read((char*) b.data(), (std::streamsize) b.size())) { std::fprintf(stderr, "cannot read %s\n", path); return 2; }
+ float tail[4];
+ std::memcpy(tail, b.data() + BLOB - 16, sizeof tail);
+ const float sg = tail[0], s_up = tail[1], s_down = tail[2];
+ const int F = ROWS / 2;
+ const size_t up_off = (size_t) F * ROW_BYTES, d_off = (size_t) ROWS * ROW_BYTES;
+ const ggml_type_traits* tt = ggml_get_type_traits(GGML_TYPE_NVFP4);
+ std::vector<float> wg((size_t) F * N), wu((size_t) F * N), wd((size_t) N * FF);
+ tt->to_float(b.data(), wg.data(), (int64_t) F * N);
+ tt->to_float(b.data() + up_off, wu.data(), (int64_t) F * N);
+ tt->to_float(b.data() + d_off, wd.data(), (int64_t) N * FF);
+ const ggml_type_traits_cpu* q8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
+ std::mt19937 rng(9);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ double e_fold = 0, e_out = 0, den = 0, hmax_fold = 0;
+ for (int trial = 0; trial < 8; ++trial) {
+ std::vector<float> x(N);
+ for (float& v : x) v = nd(rng);
+ std::vector<double> h(F), y(N, 0.0);
+ for (int r = 0; r < F; ++r) {
+ double g = 0, u = 0;
+ for (int k = 0; k < N; ++k) { g += (double) wg[(size_t) r * N + k] * x[k]; u += (double) wu[(size_t) r * N + k] * x[k]; }
+ g *= sg; u *= s_up;
+ h[r] = g / (1 + std::exp(-g)) * u;
+ }
+ for (int r = 0; r < N; ++r) {
+ double s = 0;
+ for (int k = 0; k < F; ++k) s += (double) wd[(size_t) r * FF + k] * h[k];
+ y[r] = s * s_down;
+ }
+ std::vector<uint8_t> xq(ggml_row_size(GGML_TYPE_Q8_0, N)), hq(ggml_row_size(GGML_TYPE_Q8_0, FF));
+ q8->from_float(x.data(), xq.data(), N);
+ const void* ap[1] = {xq.data()};
+ std::vector<float> ff(F), out(N);
+ float* fp[1] = {ff.data()};
+ float* op[1] = {out.data()};
+ for (int mode = 0; mode < 2; ++mode) { // 0: s_down folded into up; 1: s_down on the output
+ nvfp4_512_gu_rows(b.data(), ROW_BYTES, up_off, N, ap, 1, fp, 0, F, sg, mode == 0 ? s_up * s_down : s_up);
+ if (mode == 0) for (float v : ff) hmax_fold = std::fmax(hmax_fold, std::fabs(v));
+ q8->from_float(ff.data(), hq.data(), FF);
+ const void* hp[1] = {hq.data()};
+ nvfp4_512_rows(b.data() + d_off, D_ROW, FF, hp, 1, op, 0, N);
+ double err = 0;
+ for (int r = 0; r < N; ++r) {
+ const double got = mode == 0 ? out[r] : (double) out[r] * s_down;
+ err += (got - y[r]) * (got - y[r]);
+ }
+ (mode == 0 ? e_fold : e_out) += err;
+ }
+ for (int r = 0; r < N; ++r) den += y[r] * y[r];
+ }
+ std::printf("layer %d expert %d: s_gate %.3g s_up %.3g s_down %.3g; folded hidden max |h| %.3g (Q8_0 d %.3g, FP16 "
+ "normal from 6.1e-05)\n", layer, e, sg, s_up, s_down, hmax_fold, hmax_fold / 127);
+ std::printf(" s_down folded into up : expert output rel. error %.3f%%\n", 100 * std::sqrt(e_fold / den));
+ std::printf(" s_down on the output : expert output rel. error %.3f%%\n", 100 * std::sqrt(e_out / den));
+ return 0;
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ ggml_cpu_init();
+ if (argc >= 3 && std::string(argv[1]) == "--expert")
+ return expert_e2e(argv[2], argc >= 4 ? std::atoi(argv[3]) : 0, argc >= 5 ? std::atoi(argv[4]) : 0);
+ if (argc >= 4 && std::string(argv[1]) == "--bw")
+ return bandwidth(std::atoi(argv[2]), std::atoi(argv[3]), argc >= 5 && std::string(argv[4]) == "ggml");
+ std::mt19937 rng(20260929);
+ std::vector<uint8_t> w(BLOB);
+ // random blocks: every code, scales 0x20..0x5f (sign bit clear, never 0x7F), as ModelOpt writes them
+ std::uniform_int_distribution<int> byte(0, 255), sc(0x20, 0x5f);
+ for (size_t b = 0; b + BLK <= BLOB - 16; b += BLK) {
+ for (int s = 0; s < 4; ++s) w[b + s] = (uint8_t) sc(rng);
+ for (int q = 4; q < BLK; ++q) w[b + q] = (uint8_t) byte(rng);
+ }
+ int bad = check_rows(w.data(), N, ROW_BYTES, ROWS, "random blocks, n 2560", rng);
+ bad += check_rows(w.data(), FF, D_ROW, N, "random blocks, n 640", rng);
+ if (argc >= 2) { // layer 0, expert 0 of the pack
+ std::ifstream f(argv[1], std::ios::binary);
+ if (!f.read((char*) w.data(), (std::streamsize) w.size())) {
+ std::fprintf(stderr, "cannot read %zu bytes of %s\n", w.size(), argv[1]);
+ return 2;
+ }
+ bad += check_rows(w.data(), N, ROW_BYTES, ROWS, "expert 0: gate+up rows", rng);
+ bad += check_rows(w.data() + (size_t) ROWS * ROW_BYTES, FF, D_ROW, N, "expert 0: down rows", rng);
+ bad += check_gu(w.data(), rng);
+ }
+ speed(w, rng);
+ std::printf("\nRESULT: %s\n", bad ? "MISMATCH" : "parity OK");
+ return bad ? 1 : 0;
+}
diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu
index c2e44270f..42ba5136f 100644
--- a/src/kernels/cuda/iq_kernels.cu
+++ b/src/kernels/cuda/iq_kernels.cu
@@ -566,6 +566,36 @@ __device__ __forceinline__ float vec_dot_q8_0_q8_1(const void* __restrict__ vbq,
const float d8_0 = __half2float(bq8_0->d), d8_1 = __low2float(bq8_1->ds);
return d8_0 * d8_1 * ((float) sumi);
}
+// NVFP4 (ModelOpt): 64 values = 4 sub-blocks of 16, one UE4M3 scale each, E2M1 codes split-half like Q4_0.
+// kvalues_fp4 holds the E2M1 values doubled (0, 1, 2, 3, 4, 6, 8, 12), so the scale is halved here - exactly
+// ggml's ggml_cuda_ue4m3_to_fp32, decoded in software so the GPU and ggml-cpu agree bit for bit (NaN -> 0).
+__device__ __forceinline__ float ue4m3_to_f32_half(uint8_t x) {
+ if (x == 0 || x == 0x7F) return 0.0f;
+ const int exp = (x >> 3) & 0xF, man = x & 0x7;
+ const float raw = exp == 0 ? ldexpf((float) man, -9) : ldexpf(1.0f + (float) man / 8.0f, exp - 7);
+ return raw * 0.5f;
+}
+
+// One call = two sub-blocks (32 values); `bq8_1` is the block's first q8_1 block (two per 64 values).
+__device__ __forceinline__ float vec_dot_nvfp4_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
+ const int& kbx, const int& iqs) {
+ const block_nvfp4* bq4 = (const block_nvfp4*) vbq + kbx;
+ float sum = 0.0f;
+#pragma unroll
+ for (int i = 0; i < 2; i++) {
+ const int iqs0 = iqs + 2 * i, iqs1 = iqs0 + 1, is = iqs0 >> 1;
+ const int2 v0 = get_int_from_table_16(get_int_b4(bq4->qs, iqs0), kvalues_fp4);
+ const int2 v1 = get_int_from_table_16(get_int_b4(bq4->qs, iqs1), kvalues_fp4);
+ const block_q8_1* bq8 = bq8_1 + (is >> 1);
+ const int i8 = (is & 1) << 2;
+ int sumi = ggml_cuda_dp4a(v0.x, get_int_b4(bq8->qs, i8 + 0), 0);
+ sumi = ggml_cuda_dp4a(v0.y, get_int_b4(bq8->qs, i8 + 2), sumi);
+ sumi = ggml_cuda_dp4a(v1.x, get_int_b4(bq8->qs, i8 + 1), sumi);
+ sumi = ggml_cuda_dp4a(v1.y, get_int_b4(bq8->qs, i8 + 3), sumi);
+ sum += ue4m3_to_f32_half(bq4->d[is]) * __low2float(bq8->ds) * (float) sumi;
+ }
+ return sum;
+}
// ---------------------------------------------------------------- the formats
// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls.
@@ -608,12 +638,14 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0,
// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every
// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
#ifdef STRATA_Q6K_EXPERTS // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start
-#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8)
+#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40)
#else
-#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8)
+#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40)
#endif
-#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8)
-#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8)
+#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(40)
+#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40)
+template<> struct Fmt<40> { static constexpr int qk = 64, ipb = 2, step = 4; // NVFP4: 2 calls of 32 values
+ __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_nvfp4_q8_1(v, y, kbx, iqs); } };
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
@@ -1224,11 +1256,19 @@ __global__ void __launch_bounds__(256) native_gu_kernel(const unsigned long long
const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
const int ng = *n_groups;
for (int g = blockIdx.y; g < ng; g += gridDim.y) {
- const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];
+ const uint8_t* wr = blob + off;
+ // NVFP4: the expert's global scales from the blob's tail; s_down goes on the down output (native_down_kernel):
+ // folded into up it left the hidden near 1e-5, whose q8_1 block scale is an FP16 subnormal
+ float scale = 1.0f;
+ if (L.tail_off) {
+ const float* tail = (const float*) (blob + L.tail_off);
+ scale = is_up ? tail[1] : tail[0];
+ }
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; ++e) {
const float s = row_dot<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
- if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s;
+ if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s * scale;
}
}
}
@@ -1349,11 +1389,13 @@ __global__ void __launch_bounds__(256) native_down_kernel(const unsigned long lo
const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
const int ng = *n_groups;
for (int g = blockIdx.y; g < ng; g += gridDim.y) { // as native_gu_kernel
- const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];
+ const uint8_t* wr = blob + off;
+ const float sd = L.tail_off ? ((const float*) (blob + L.tail_off))[2] : 1.0f; // NVFP4: s_down
const int e0 = grp_start[g], e1 = grp_start[g + 1];
for (int e = e0; e < e1; ++e) {
const float s = row_dot<TD>(wr, hq + (size_t) e * hb, nb, lane);
- if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s;
+ if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s * sd;
}
}
}
@@ -1868,6 +1910,20 @@ __device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) {
for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt<dst_t>(__uint_as_float((uint32_t) x[j] << 16));
}
+// NVFP4: one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values of block tid / 8.
+// Sub-block s (16 values) keeps its codes in qs[8 s .. 8 s + 7]: byte j = value j (low nibble) and j + 8 (high).
+template<typename dst_t>
+__device__ void dq_nvfp4(const void* vx, int64_t ibs, dst_t* yy, int tid) {
+ const block_nvfp4* x = (const block_nvfp4*) vx + ibs * 4;
+ const int b = tid / 8, part = tid % 8;
+ for (int j = 0; j < 8; ++j) {
+ const int i = part * 8 + j, s = i / 16, k = i % 16;
+ const uint8_t byte = x[b].qs[s * 8 + (k & 7)];
+ const int code = k < 8 ? (byte & 0x0F) : (byte >> 4);
+ yy[b * 64 + i] = cvt<dst_t>((float) kvalues_fp4[code] * ue4m3_to_f32_half(x[b].d[s]));
+ }
+}
+
// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others,
// so the default is unreachable.
template<typename dst_t>
@@ -1892,6 +1948,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,
case 6: dq_q5_0(vx, ibs, y, tid); break;
case 2: dq_q4_0(vx, ibs, y, tid); break;
case 3: dq_q4_1(vx, ibs, y, tid); break;
+ case 40: dq_nvfp4(vx, ibs, y, tid); break;
case 8: dq_q8_0(vx, ibs, y, tid); break;
case 30: dq_bf16(vx, ibs, y, tid); break;
default: break;
@@ -1900,26 +1957,44 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,
// flat: superblock i -> y + 256 i
template<typename dst_t>
-__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y) {
+__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y,
+ const float* __restrict__ scale) {
const int64_t i = blockIdx.x;
dq_dispatch<dst_t>(ty, vx, i, y + i * QK_K, threadIdx.x);
+ if (scale != nullptr) { // NVFP4 down: s_down (the weights stay in FP16's normal range)
+ __syncwarp();
+ const float sc = *scale;
+ for (int k = 0; k < 8; ++k) {
+ const int j = threadIdx.x * 8 + k;
+ y[i * QK_K + j] = cvt<dst_t>((float) y[i * QK_K + j] * sc);
+ }
+ }
}
// gate/up: superblock i of a role matrix (n_embd/256 per row) -> interleaved row 2r + parity
__global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const void* __restrict__ up, int64_t per_row,
- __half* __restrict__ y) {
+ __half* __restrict__ y, const float* __restrict__ tail) {
const int64_t i = blockIdx.x;
const int parity = blockIdx.y;
const int64_t r = i / per_row, c = i % per_row;
- dq_dispatch<__half>(ty, parity ? up : gate, i, y + ((2 * r + parity) * per_row + c) * QK_K, threadIdx.x);
+ __half* dst = y + ((2 * r + parity) * per_row + c) * QK_K;
+ dq_dispatch<__half>(ty, parity ? up : gate, i, dst, threadIdx.x);
+ if (tail != nullptr) { // NVFP4: gate * s_gate, up * s_up (s_down on the down output: FP16 would underflow)
+ __syncwarp();
+ const float sc = parity ? tail[1] : tail[0];
+ for (int k = 0; k < 8; ++k) {
+ const int j = threadIdx.x * 8 + k;
+ dst[j] = __float2half(__half2float(dst[j]) * sc);
+ }
+ }
}
// the types dq_dispatch dequantizes
bool is_iq(int t) {
return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
#ifdef STRATA_Q6K_EXPERTS
- t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
+ t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40;
#else
- t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
+ t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40;
#endif
}
// values per block of the types the grouped expert kernels take (0 = none)
@@ -2720,6 +2795,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {
case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
case 2: return (size_t) (n / 32) * sizeof(block_q4_0);
case 3: return (size_t) (n / 32) * sizeof(block_q4_1);
+ case 40: return (size_t) (n / 64) * sizeof(block_nvfp4);
case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
default: return 0;
@@ -2747,9 +2823,9 @@ void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n
check("iq_mmvq");
}
-void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream) {
+void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale) {
if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
- dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst);
+ dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst, scale);
check("iq_dequant_f16");
}
@@ -2774,16 +2850,17 @@ void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* to
void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) {
if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }
- dequant_flat_kernel<float><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst);
+ dequant_flat_kernel<float><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst, nullptr);
check("iq_dequant_f32");
}
-void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) {
+void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream,
+ const float* tail) {
// checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error
if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
const int64_t per_row = n_embd / 256;
dequant_gu_kernel<<<dim3((unsigned) (n_ff * per_row), 2), 32, 0, (cudaStream_t) stream>>>(t, gate, up, per_row,
- (__half*) dst);
+ (__half*) dst, tail);
check("iq_dequant_gu_f16");
}
@@ -2804,6 +2881,10 @@ NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd,
L.up_off = (size_t) n_ff * L.gu_row;
L.down_off = 2 * L.up_off;
L.bytes = L.down_off + (size_t) n_embd * L.d_row;
+ if (gu_type == 40 && d_type == 40) { // NVFP4: {s_gate, s_up, s_down, 0} after down (tools/iq_pack.py)
+ L.tail_off = L.bytes;
+ L.bytes += 16;
+ }
return L;
}
diff --git a/src/kernels/nvfp4_expert_gpu_parity.cpp b/src/kernels/nvfp4_expert_gpu_parity.cpp
new file mode 100644
index 000000000..2837a3a33
--- /dev/null
+++ b/src/kernels/nvfp4_expert_gpu_parity.cpp
@@ -0,0 +1,107 @@
+// src/kernels/nvfp4_expert_gpu_parity.cpp - the decode path's GPU experts (native_expert_grouped) on real NVFP4
+// blobs with their global scales, against a double-precision expert.
+//
+// nvfp4_expert_gpu_parity pack/experts.bin [layer expert ...]
+//
+// Eight tokens of N(0,1) activations through one expert: q8_1 input, gate/up with s_gate / s_up, SwiGLU, q8_1 of the
+// hidden, down with s_down on its output. Only the two activation roundings separate it from the reference (~1%).
+#include "strata/kernels/iq_kernels.hpp"
+
+#include "ggml.h"
+
+#include <cuda_runtime.h>
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <random>
+#include <vector>
+
+namespace k = strata::kernels;
+
+namespace {
+void ck(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ if (argc < 2) { std::fprintf(stderr, "usage: nvfp4_expert_gpu_parity pack/experts.bin [layer expert ...]\n"); return 2; }
+ constexpr int64_t N = 2560, FF = 640;
+ constexpr int T = 8;
+ const k::NativeExpertLayout L = k::native_expert_layout(40, 40, N, FF);
+ const size_t layer_bytes = 512 * L.bytes; // L.bytes counts the 16-byte tail
+ std::vector<int> picks;
+ for (int i = 2; i + 1 < argc; i += 2) { picks.push_back(std::atoi(argv[i])); picks.push_back(std::atoi(argv[i + 1])); }
+ if (picks.empty()) picks = {0, 0, 0, 7, 12, 100, 24, 300, 40, 5, 47, 511};
+ std::ifstream f(argv[1], std::ios::binary);
+ std::mt19937 rng(9);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ const ggml_type_traits* tt = ggml_get_type_traits(GGML_TYPE_NVFP4);
+ double worst = 0;
+ for (size_t pi = 0; pi < picks.size(); pi += 2) {
+ const int layer = picks[pi], e = picks[pi + 1];
+ std::vector<uint8_t> blob(L.bytes);
+ f.seekg((std::streamoff) (layer * layer_bytes + (size_t) e * L.bytes));
+ if (!f.read((char*) blob.data(), (std::streamsize) blob.size())) { std::fprintf(stderr, "cannot read\n"); return 2; }
+ float tail[4];
+ std::memcpy(tail, blob.data() + L.tail_off, sizeof tail);
+ std::vector<float> wg((size_t) FF * N), wu((size_t) FF * N), wd((size_t) N * FF), x((size_t) T * N);
+ tt->to_float(blob.data(), wg.data(), FF * N);
+ tt->to_float(blob.data() + L.up_off, wu.data(), FF * N);
+ tt->to_float(blob.data() + L.down_off, wd.data(), N * FF);
+ for (float& v : x) v = nd(rng);
+ std::vector<double> ref((size_t) T * N);
+ for (int t = 0; t < T; ++t) {
+ std::vector<double> h(FF);
+ for (int64_t r = 0; r < FF; ++r) {
+ double g = 0, u = 0;
+ for (int64_t c = 0; c < N; ++c) {
+ g += (double) wg[(size_t) r * N + c] * x[(size_t) t * N + c];
+ u += (double) wu[(size_t) r * N + c] * x[(size_t) t * N + c];
+ }
+ g *= tail[0];
+ u *= tail[1];
+ h[r] = g / (1 + std::exp(-g)) * u;
+ }
+ for (int64_t r = 0; r < N; ++r) {
+ double s = 0;
+ for (int64_t c = 0; c < FF; ++c) s += (double) wd[(size_t) r * FF + c] * h[c];
+ ref[(size_t) t * N + r] = s * tail[2];
+ }
+ }
+ uint8_t* db; float *dx, *dout; void *dxq, *scr; unsigned long long* dptr; int32_t *dstart, *dng, *ddst, *dtok;
+ ck(cudaMalloc(&db, blob.size()), "blob");
+ ck(cudaMemcpy(db, blob.data(), blob.size(), cudaMemcpyHostToDevice), "blob");
+ ck(cudaMalloc(&dx, x.size() * 4), "x");
+ ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
+ ck(cudaMalloc(&dxq, (size_t) T * N / 32 * 36), "xq");
+ ck(cudaMalloc(&dout, (size_t) T * N * 4), "out");
+ ck(cudaMalloc(&scr, k::native_expert_scratch_bytes(T, FF)), "scratch");
+ const unsigned long long ptr = (unsigned long long) db;
+ const int32_t start[2] = {0, T}, ng = 1, ids[T] = {0, 1, 2, 3, 4, 5, 6, 7};
+ ck(cudaMalloc(&dptr, 8), "p"); ck(cudaMemcpy(dptr, &ptr, 8, cudaMemcpyHostToDevice), "p");
+ ck(cudaMalloc(&dstart, 8), "s"); ck(cudaMemcpy(dstart, start, 8, cudaMemcpyHostToDevice), "s");
+ ck(cudaMalloc(&dng, 4), "n"); ck(cudaMemcpy(dng, &ng, 4, cudaMemcpyHostToDevice), "n");
+ ck(cudaMalloc(&ddst, 4 * T), "d"); ck(cudaMemcpy(ddst, ids, 4 * T, cudaMemcpyHostToDevice), "d");
+ ck(cudaMalloc(&dtok, 4 * T), "t"); ck(cudaMemcpy(dtok, ids, 4 * T, cudaMemcpyHostToDevice), "t");
+ k::quantize_q8_1_rows(dx, T, N, dxq, nullptr);
+ k::native_expert_grouped(L, dptr, dstart, dng, ddst, dtok, 1, T, dxq, scr, dout, nullptr);
+ ck(cudaDeviceSynchronize(), "run");
+ std::vector<float> got((size_t) T * N);
+ ck(cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost), "out");
+ for (void* p : {(void*) db, (void*) dx, dxq, (void*) dout, scr, (void*) dptr, (void*) dstart, (void*) dng,
+ (void*) ddst, (void*) dtok})
+ cudaFree(p);
+ double num = 0, den = 0;
+ for (size_t i = 0; i < got.size(); ++i) { num += (got[i] - ref[i]) * (got[i] - ref[i]); den += ref[i] * ref[i]; }
+ const double rel = std::sqrt(num / den);
+ worst = std::fmax(worst, rel);
+ std::printf("layer %2d expert %3d: s_gate %.3g s_up %.3g s_down %.3g -> expert output rel. error %.3f%%\n", layer,
+ e, tail[0], tail[1], tail[2], 100 * rel);
+ }
+ std::printf("RESULT: %s (worst %.3f%%)\n", worst < 0.03 ? "ok" : "TOO FAR", 100 * worst);
+ return worst < 0.03 ? 0 : 1;
+}
diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu
index 6e12086e8..f58a189c6 100644
--- a/src/prefill/kernels.cu
+++ b/src/prefill/kernels.cu
@@ -1576,13 +1576,18 @@ __global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32
}
__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
const float* __restrict__ w, const float* __restrict__ shared,
- const float* __restrict__ sg, float* __restrict__ bo, int64_t T) {
+ const float* __restrict__ sg, float* __restrict__ bo, int64_t T,
+ const float* __restrict__ row_sd) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * N) return;
const int64_t t = i / N, d = i % N;
float s = 0.0f;
#pragma unroll
- for (int k = 0; k < 10; ++k) s = fmaf(w[t * 10 + k], Dm[(int64_t) slot[t * 10 + k] * N + d], s);
+ for (int k = 0; k < 10; ++k) {
+ const int64_t r = slot[t * 10 + k];
+ const float v = row_sd ? Dm[r * N + d] * row_sd[r] : Dm[r * N + d]; // the product scale_down_rows stored
+ s = fmaf(w[t * 10 + k], v, s);
+ }
bo[i] = s + shared[i] * sigm(sg[t]);
}
@@ -1590,7 +1595,8 @@ __global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t*
// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16).
__global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
const float* __restrict__ w, const float4* __restrict__ shared,
- const float* __restrict__ sg, float4* __restrict__ bo, int64_t T) {
+ const float* __restrict__ sg, float4* __restrict__ bo, int64_t T,
+ const float* __restrict__ row_sd) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // float4 index
if (i >= T * (N / 4)) return;
const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4;
@@ -1600,7 +1606,12 @@ __global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t*
#pragma unroll
for (int k = 0; k < 10; ++k) {
ww[k] = w[t * 10 + k];
- v[k] = *reinterpret_cast<const float4*>(Dm + (int64_t) slot[t * 10 + k] * N + d);
+ const int64_t r = slot[t * 10 + k];
+ v[k] = *reinterpret_cast<const float4*>(Dm + r * N + d);
+ if (row_sd) { // NVFP4 in MMQ: the row's s_down, as moe_combine_kernel applies it
+ const float sd = row_sd[r];
+ v[k] = make_float4(v[k].x * sd, v[k].y * sd, v[k].z * sd, v[k].w * sd);
+ }
}
#pragma unroll
for (int k = 0; k < 10; ++k) {
@@ -2163,16 +2174,16 @@ void peer_scatter_add(float* sum, const float* rows, const float* wk, const int3
check("peer_scatter_add");
}
void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
- int64_t T, void* stream) {
+ int64_t T, void* stream, const float* row_sd) {
#ifndef STRATA_W_NO_COMB
if (((reinterpret_cast<uintptr_t>(Dm) | reinterpret_cast<uintptr_t>(shared) | reinterpret_cast<uintptr_t>(bo)) & 15) == 0) {
moe_combine4_kernel<<<blocks_for(T * (N / 4)), 256, 0, (cudaStream_t) stream>>>(
- Dm, slot, w, reinterpret_cast<const float4*>(shared), sg, reinterpret_cast<float4*>(bo), T);
+ Dm, slot, w, reinterpret_cast<const float4*>(shared), sg, reinterpret_cast<float4*>(bo), T, row_sd);
check("moe_combine");
return;
}
#endif
- moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T);
+ moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T, row_sd);
check("moe_combine");
}
void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) {
diff --git a/src/prefill/mmq_nvfp4_parity.cpp b/src/prefill/mmq_nvfp4_parity.cpp
new file mode 100644
index 000000000..a4e65419f
--- /dev/null
+++ b/src/prefill/mmq_nvfp4_parity.cpp
@@ -0,0 +1,350 @@
+// src/prefill/mmq_nvfp4_parity.cpp - the prompt path's NVFP4 expert products (MMQ) against an exact reference.
+//
+// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin [rows ...]
+// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin --group
+// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin --layers [expert]
+// STRATA_PREFILL_NVFP4=w4a8|w4a4 mmq_nvfp4_parity pack/experts.bin --real moe_input.bin layer
+//
+// --group: the prompt path's launch shape - 20 experts of layer 0 with 0..60 rows each, one activation array in
+// expert order, gate/up in two launches (experts 0-15, then 16-19 through the same absolute bounds, 16 in), and the
+// second group's down from its own rows through relative bounds.
+// --layers: one expert (default 7) of every one of the 48 layers, 64 rows - scales differ by layer.
+// --real: a layer's MoE input from a prompt (STRATA_DUMP_MOE_INPUT) through its 12 most-routed experts, gate/up on
+// the real rows and down on the hidden they produce; also an FP16-activation product (the fp16 path) and the rows'
+// outlier ratio (max |x| / rms x).
+//
+// One real expert (layer 0, expert 0): gate/up [1280, 2560] and down [2560, 640], as the prompt path gathers them.
+// Activations are random rows; the reference dequantizes the weights with ggml's own NVFP4 decode and sums in double.
+// Reported per product: relative Frobenius error and the worst element relative to the row's largest output.
+// 8-bit activations land near 0.5%; FP4 activations near 10% - the difference between the two modes.
+#include "strata/prefill/moe_mmq.hpp"
+
+#include "ggml.h"
+
+#include <cuda_runtime.h>
+#include <immintrin.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <string>
+#include <random>
+#include <vector>
+
+namespace mmq = strata::prefill::mmq;
+
+namespace {
+
+void ck(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
+}
+
+// one product: x [T, cols] times w [rows, cols]^T
+float half_round(float v) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtps_ph(_mm_set_ss(v), 0))); }
+
+int product(const uint8_t* w_host, int64_t rows, int64_t cols, int T, const char* what, std::mt19937& rng,
+ const std::vector<float>* given = nullptr, double* rel_out = nullptr, double* rel16_out = nullptr,
+ std::vector<double>* ref_out = nullptr) {
+ const size_t wbytes = mmq::matrix_bytes(GGML_TYPE_NVFP4, rows, cols);
+ std::vector<float> wf((size_t) rows * cols);
+ ggml_get_type_traits(GGML_TYPE_NVFP4)->to_float(w_host, wf.data(), rows * cols);
+ std::vector<float> x((size_t) T * cols);
+ if (given) {
+ x = *given;
+ } else {
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::uniform_real_distribution<float> mag(0.1f, 10.f);
+ for (int t = 0; t < T; ++t) {
+ const float m = mag(rng); // rows of different magnitude, like a residual
+ for (int64_t k = 0; k < cols; ++k) x[(size_t) t * cols + k] = nd(rng) * m;
+ }
+ }
+ std::vector<double> ref((size_t) T * rows);
+ for (int t = 0; t < T; ++t)
+ for (int64_t r = 0; r < rows; ++r) {
+ double s = 0;
+ const float* a = x.data() + (size_t) t * cols;
+ const float* b = wf.data() + (size_t) r * cols;
+ for (int64_t k = 0; k < cols; ++k) s += (double) a[k] * b[k];
+ ref[(size_t) t * rows + r] = s;
+ }
+
+ uint8_t* dw = nullptr; float* dx = nullptr; void* dq = nullptr; float* dys = nullptr; float* dd = nullptr;
+ int32_t* dids = nullptr; int32_t* dbounds = nullptr;
+ ck(cudaMalloc(&dw, wbytes + 4096), "w");
+ ck(cudaMemset(dw, 0, wbytes + 4096), "w");
+ ck(cudaMemcpy(dw, w_host, wbytes, cudaMemcpyHostToDevice), "w");
+ ck(cudaMalloc(&dx, x.size() * sizeof(float)), "x");
+ ck(cudaMemcpy(dx, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "x");
+ ck(cudaMalloc(&dq, mmq::q8_bytes(T, cols)), "xq");
+ ck(cudaMalloc(&dys, T * sizeof(float)), "yscale");
+ ck(cudaMalloc(&dd, (size_t) T * rows * sizeof(float)), "dst");
+ ck(cudaMalloc(&dids, T * sizeof(int32_t)), "ids");
+ ck(cudaMalloc(&dbounds, 2 * sizeof(int32_t)), "bounds");
+ const int32_t bounds[2] = {0, T};
+ ck(cudaMemcpy(dbounds, bounds, sizeof bounds, cudaMemcpyHostToDevice), "bounds");
+ mmq::iota(dids, T, nullptr);
+ mmq::quantize(dx, nullptr, dq, GGML_TYPE_NVFP4, cols, cols, T, nullptr, dys);
+ mmq::Context ctx;
+ mmq::Product p;
+ p.w = dw; p.type = GGML_TYPE_NVFP4; p.w_rows = rows; p.w_cols = cols; p.expert_bytes = wbytes; p.n = 1;
+ p.xq = dq; p.bounds = dbounds; p.ids = dids; p.total_rows = T; p.max_rows = T; p.dst = dd; p.ld_dst = rows;
+ p.y_scale = mmq::fp4_activations(GGML_TYPE_NVFP4) ? dys : nullptr;
+ ctx.run(p, nullptr);
+ ck(cudaDeviceSynchronize(), "run");
+ std::vector<float> got((size_t) T * rows);
+ ck(cudaMemcpy(got.data(), dd, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "dst");
+ cudaFree(dw); cudaFree(dx); cudaFree(dq); cudaFree(dys); cudaFree(dd); cudaFree(dids); cudaFree(dbounds);
+
+ double num = 0, den = 0, worst = 0;
+ for (int t = 0; t < T; ++t) {
+ double rmax = 0;
+ for (int64_t r = 0; r < rows; ++r) rmax = std::fmax(rmax, std::fabs(ref[(size_t) t * rows + r]));
+ for (int64_t r = 0; r < rows; ++r) {
+ const double e = (double) got[(size_t) t * rows + r] - ref[(size_t) t * rows + r];
+ num += e * e;
+ den += ref[(size_t) t * rows + r] * ref[(size_t) t * rows + r];
+ worst = std::fmax(worst, std::fabs(e) / (rmax > 0 ? rmax : 1));
+ }
+ }
+ const double rel = std::sqrt(num / den);
+ if (rel_out) *rel_out = rel;
+ if (ref_out) *ref_out = ref;
+ if (rel16_out) { // the fp16 path: activations rounded to FP16
+ double n16 = 0;
+ for (int t = 0; t < T; ++t) {
+ std::vector<float> xh(cols);
+ for (int64_t k = 0; k < cols; ++k) xh[k] = half_round(x[(size_t) t * cols + k]);
+ for (int64_t r = 0; r < rows; ++r) {
+ double s = 0;
+ for (int64_t k = 0; k < cols; ++k) s += (double) xh[k] * wf[(size_t) r * cols + k];
+ const double e = s - ref[(size_t) t * rows + r];
+ n16 += e * e;
+ }
+ }
+ *rel16_out = std::sqrt(n16 / den);
+ return rel > 0.2 ? 1 : 0;
+ }
+ std::printf("%-8s T %4d [%lld x %lld] rel. error %.4f%% worst %.4f%% of the row max%s\n", what, T,
+ (long long) rows, (long long) cols, 100 * rel, 100 * worst, rel > 0.05 ? " <-- FP4-level or wrong" : "");
+ return rel > 0.2 ? 1 : 0;
+}
+
+double dot_ref(const float* a, const float* b, int64_t n) {
+ double s = 0;
+ for (int64_t k = 0; k < n; ++k) s += (double) a[k] * b[k];
+ return s;
+}
+
+struct Err {
+ double num = 0, den = 0;
+ void add(double got, double ref) { num += (got - ref) * (got - ref); den += ref * ref; }
+ double rel() const { return den > 0 ? std::sqrt(num / den) : 0; }
+};
+
+int group(const char* path) {
+ constexpr int64_t N = 2560, FF = 640;
+ constexpr int E = 20;
+ constexpr size_t STRIDE = 2764816; // one layer-0 blob in experts.bin
+ const size_t gub = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N), db = mmq::matrix_bytes(GGML_TYPE_NVFP4, N, FF);
+ std::vector<uint8_t> all((size_t) E * STRIDE);
+ std::ifstream f(path, std::ios::binary);
+ if (!f.read((char*) all.data(), (std::streamsize) all.size())) { std::fprintf(stderr, "cannot read %s\n", path); return 2; }
+ std::vector<uint8_t> G((size_t) E * gub + 4096, 0), D((size_t) E * db + 4096, 0);
+ for (int e = 0; e < E; ++e) {
+ std::memcpy(G.data() + e * gub, all.data() + e * STRIDE, gub);
+ std::memcpy(D.data() + e * db, all.data() + e * STRIDE + gub, db);
+ }
+ std::mt19937 rng(5);
+ std::uniform_int_distribution<int> cntd(0, 60);
+ std::vector<int32_t> bounds(E + 1, 0);
+ int maxA = 0, maxB = 0;
+ for (int e = 0; e < E; ++e) {
+ const int c = (e % 7 == 3) ? 0 : cntd(rng);
+ bounds[e + 1] = bounds[e] + c;
+ if (e < 16) maxA = std::max(maxA, c); else maxB = std::max(maxB, c);
+ }
+ const int T = bounds[E];
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::uniform_real_distribution<float> mag(0.1f, 10.f);
+ std::vector<float> x((size_t) T * N);
+ for (int t = 0; t < T; ++t) { const float m = mag(rng); for (int64_t k = 0; k < N; ++k) x[(size_t) t * N + k] = nd(rng) * m; }
+ // group B's down input: its own rows of FF values
+ const int rB = bounds[16], nB = T - rB;
+ std::vector<float> h((size_t) std::max(nB, 1) * FF);
+ for (auto& v : h) v = nd(rng);
+ std::vector<int32_t> relB(5);
+ for (int i = 0; i <= 4; ++i) relB[i] = bounds[16 + i] - rB;
+
+ uint8_t *dG, *dD; float *dx, *dh, *dgu, *ddn, *dys, *dhs; void *dxq, *dhq; int32_t *dids, *dbounds, *drel;
+ ck(cudaMalloc(&dG, G.size()), "G"); ck(cudaMemcpy(dG, G.data(), G.size(), cudaMemcpyHostToDevice), "G");
+ ck(cudaMalloc(&dD, D.size()), "D"); ck(cudaMemcpy(dD, D.data(), D.size(), cudaMemcpyHostToDevice), "D");
+ ck(cudaMalloc(&dx, x.size() * 4), "x"); ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
+ ck(cudaMalloc(&dh, h.size() * 4), "h"); ck(cudaMemcpy(dh, h.data(), h.size() * 4, cudaMemcpyHostToDevice), "h");
+ ck(cudaMalloc(&dgu, (size_t) T * 2 * FF * 4), "gu"); ck(cudaMemset(dgu, 0, (size_t) T * 2 * FF * 4), "gu");
+ ck(cudaMalloc(&ddn, (size_t) std::max(nB, 1) * N * 4), "dn");
+ ck(cudaMalloc(&dxq, mmq::q8_bytes(T, N)), "xq"); ck(cudaMalloc(&dhq, mmq::q8_bytes(std::max(nB, 1), FF)), "hq");
+ ck(cudaMalloc(&dys, T * 4), "ys"); ck(cudaMalloc(&dhs, std::max(nB, 1) * 4), "hs");
+ ck(cudaMalloc(&dids, T * 4), "ids"); ck(cudaMalloc(&dbounds, (E + 1) * 4), "b"); ck(cudaMalloc(&drel, 5 * 4), "rel");
+ ck(cudaMemcpy(dbounds, bounds.data(), (E + 1) * 4, cudaMemcpyHostToDevice), "b");
+ ck(cudaMemcpy(drel, relB.data(), 5 * 4, cudaMemcpyHostToDevice), "rel");
+ mmq::iota(dids, T, nullptr);
+ const bool fp4 = mmq::fp4_activations(GGML_TYPE_NVFP4);
+ mmq::quantize(dx, nullptr, dxq, GGML_TYPE_NVFP4, N, N, T, nullptr, dys);
+ mmq::Context ctx;
+ for (int grp = 0; grp < 2; ++grp) {
+ mmq::Product p;
+ p.w = dG + (grp ? 16 * gub : 0); p.type = GGML_TYPE_NVFP4; p.w_rows = 2 * FF; p.w_cols = N; p.expert_bytes = gub;
+ p.n = grp ? 4 : 16; p.xq = dxq; p.bounds = dbounds + (grp ? 16 : 0); p.ids = dids; p.total_rows = T;
+ p.max_rows = grp ? maxB : maxA; p.dst = dgu; p.ld_dst = 2 * FF; p.y_scale = fp4 ? dys : nullptr;
+ ctx.run(p, nullptr);
+ }
+ mmq::quantize(dh, nullptr, dhq, GGML_TYPE_NVFP4, FF, FF, nB, nullptr, dhs);
+ {
+ mmq::Product p;
+ p.w = dD + 16 * db; p.type = GGML_TYPE_NVFP4; p.w_rows = N; p.w_cols = FF; p.expert_bytes = db; p.n = 4;
+ p.xq = dhq; p.bounds = drel; p.ids = dids; p.total_rows = nB; p.max_rows = maxB; p.dst = ddn; p.ld_dst = N;
+ p.y_scale = fp4 ? dhs : nullptr;
+ ctx.run(p, nullptr);
+ }
+ ck(cudaDeviceSynchronize(), "run");
+ std::vector<float> gu((size_t) T * 2 * FF), dn((size_t) std::max(nB, 1) * N);
+ ck(cudaMemcpy(gu.data(), dgu, gu.size() * 4, cudaMemcpyDeviceToHost), "gu");
+ ck(cudaMemcpy(dn.data(), ddn, dn.size() * 4, cudaMemcpyDeviceToHost), "dn");
+ cudaFree(dG); cudaFree(dD); cudaFree(dx); cudaFree(dh); cudaFree(dgu); cudaFree(ddn); cudaFree(dxq); cudaFree(dhq);
+ cudaFree(dys); cudaFree(dhs); cudaFree(dids); cudaFree(dbounds); cudaFree(drel);
+
+ Err ea, eb, ed;
+ std::vector<float> wf((size_t) 2 * FF * N), wd((size_t) N * FF);
+ for (int e = 0; e < E; ++e) {
+ ggml_get_type_traits(GGML_TYPE_NVFP4)->to_float(G.data() + e * gub, wf.data(), 2 * FF * N);
+ for (int t = bounds[e]; t < bounds[e + 1]; ++t)
+ for (int64_t r = 0; r < 2 * FF; ++r)
+ (e < 16 ? ea : eb).add(gu[(size_t) t * 2 * FF + r], dot_ref(x.data() + (size_t) t * N, wf.data() + r * N, N));
+ if (e >= 16) {
+ ggml_get_type_traits(GGML_TYPE_NVFP4)->to_float(D.data() + e * db, wd.data(), N * FF);
+ for (int t = bounds[e]; t < bounds[e + 1]; ++t)
+ for (int64_t r = 0; r < N; ++r)
+ ed.add(dn[(size_t) (t - rB) * N + r], dot_ref(h.data() + (size_t) (t - rB) * FF, wd.data() + r * FF, FF));
+ }
+ }
+ std::printf("group: %d rows over %d experts (max %d / %d per expert)\n", T, E, maxA, maxB);
+ std::printf(" gate/up, experts 0-15 (bounds from 0) rel. error %.4f%%\n", 100 * ea.rel());
+ std::printf(" gate/up, experts 16-19 (bounds from 16) rel. error %.4f%%\n", 100 * eb.rel());
+ std::printf(" down, experts 16-19 (relative bounds) rel. error %.4f%%\n", 100 * ed.rel());
+ const double worst = std::max(ea.rel(), std::max(eb.rel(), ed.rel()));
+ std::printf("RESULT: %s\n", worst > 0.2 ? "WRONG (error beyond 20%)" : "ok");
+ return worst > 0.2 ? 1 : 0;
+}
+
+int layers(const char* path, int e) {
+ constexpr int64_t N = 2560, FF = 640;
+ constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
+ const size_t gub = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N), db = mmq::matrix_bytes(GGML_TYPE_NVFP4, N, FF);
+ std::vector<uint8_t> blob(gub + db);
+ std::ifstream f(path, std::ios::binary);
+ std::mt19937 rng(3);
+ int bad = 0;
+ for (int l = 0; l < 48; ++l) {
+ f.seekg((std::streamoff) (l * LAYER + (size_t) e * STRIDE));
+ if (!f.read((char*) blob.data(), (std::streamsize) blob.size())) { std::fprintf(stderr, "cannot read layer %d\n", l); return 2; }
+ char name[32];
+ std::snprintf(name, sizeof name, "L%02d gu", l);
+ bad += product(blob.data(), 2 * FF, N, 64, name, rng);
+ std::snprintf(name, sizeof name, "L%02d dn", l);
+ bad += product(blob.data() + gub, N, FF, 64, name, rng);
+ }
+ std::printf("RESULT: %s\n", bad ? "WRONG (error beyond 20%)" : "ok");
+ return bad ? 1 : 0;
+}
+
+int real(const char* experts_bin, const char* dump, int layer) {
+ std::ifstream d(dump, std::ios::binary);
+ int64_t hdr[3];
+ if (!d.read((char*) hdr, sizeof hdr)) { std::fprintf(stderr, "cannot read %s\n", dump); return 2; }
+ const int64_t T = hdr[0], N = hdr[1], K = hdr[2], FF = 640;
+ std::vector<float> x((size_t) (T * N));
+ std::vector<int32_t> ids((size_t) (T * K));
+ d.read((char*) x.data(), (std::streamsize) (x.size() * 4));
+ d.read((char*) ids.data(), (std::streamsize) (ids.size() * 4));
+ // the rows' outlier ratio
+ std::vector<double> ratio;
+ for (int64_t t = 0; t < T; ++t) {
+ double mx = 0, ss = 0;
+ for (int64_t k = 0; k < N; ++k) { const double v = x[(size_t) (t * N + k)]; mx = std::fmax(mx, std::fabs(v)); ss += v * v; }
+ ratio.push_back(mx / std::sqrt(ss / N + 1e-30));
+ }
+ std::sort(ratio.begin(), ratio.end());
+ std::printf("layer %d: %lld tokens, max|x| / rms: median %.1f, p99 %.1f, max %.1f\n", layer, (long long) T,
+ ratio[ratio.size() / 2], ratio[ratio.size() * 99 / 100], ratio.back());
+ std::vector<int> cnt(512, 0);
+ for (int32_t e : ids) if (e >= 0 && e < 512) ++cnt[e];
+ std::vector<int> order(512);
+ for (int i = 0; i < 512; ++i) order[i] = i;
+ std::sort(order.begin(), order.end(), [&](int a, int b) { return cnt[a] > cnt[b]; });
+ constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
+ const size_t gub = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N);
+ std::ifstream f(experts_bin, std::ios::binary);
+ std::vector<uint8_t> blob(STRIDE);
+ std::mt19937 rng(1);
+ double s_gu = 0, s_gu16 = 0, s_dn = 0, s_dn16 = 0;
+ int n = 0;
+ std::printf("%6s %5s %10s %10s %10s %10s\n", "expert", "rows", "gu mmq", "gu fp16", "down mmq", "down fp16");
+ for (int i = 0; i < 12; ++i) {
+ const int e = order[i];
+ f.seekg((std::streamoff) (layer * LAYER + (size_t) e * STRIDE));
+ f.read((char*) blob.data(), (std::streamsize) blob.size());
+ float tail[4];
+ std::memcpy(tail, blob.data() + STRIDE - 16, sizeof tail);
+ std::vector<float> xe;
+ for (int64_t t = 0; t < T; ++t)
+ for (int64_t k = 0; k < K; ++k)
+ if (ids[(size_t) (t * K + k)] == e) xe.insert(xe.end(), x.begin() + t * N, x.begin() + (t + 1) * N);
+ const int Te = (int) (xe.size() / N);
+ double gu = 0, gu16 = 0, dn = 0, dn16 = 0;
+ std::vector<double> ref;
+ product(blob.data(), 2 * FF, N, Te, "gu", rng, &xe, &gu, &gu16, &ref);
+ std::vector<float> h((size_t) Te * FF); // the hidden the exact gate/up gives
+ for (int t = 0; t < Te; ++t)
+ for (int64_t r = 0; r < FF; ++r) {
+ const double g = ref[(size_t) t * 2 * FF + r] * tail[0], u = ref[(size_t) t * 2 * FF + FF + r] * tail[1];
+ h[(size_t) t * FF + r] = (float) (g / (1 + std::exp(-g)) * u);
+ }
+ product(blob.data() + gub, N, FF, Te, "down", rng, &h, &dn, &dn16);
+ std::printf("%6d %5d %9.3f%% %9.3f%% %9.3f%% %9.3f%%\n", e, Te, 100 * gu, 100 * gu16, 100 * dn, 100 * dn16);
+ s_gu += gu; s_gu16 += gu16; s_dn += dn; s_dn16 += dn16; ++n;
+ }
+ std::printf("%6s %5s %9.3f%% %9.3f%% %9.3f%% %9.3f%%\n", "mean", "", 100 * s_gu / n, 100 * s_gu16 / n,
+ 100 * s_dn / n, 100 * s_dn16 / n);
+ return 0;
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ if (argc < 2) { std::fprintf(stderr, "usage: mmq_nvfp4_parity pack/experts.bin [rows ...]\n"); return 2; }
+ constexpr int64_t N = 2560, FF = 640;
+ const size_t gu_bytes = mmq::matrix_bytes(GGML_TYPE_NVFP4, 2 * FF, N), d_bytes = mmq::matrix_bytes(GGML_TYPE_NVFP4, N, FF);
+ std::vector<uint8_t> blob(gu_bytes + d_bytes);
+ std::ifstream f(argv[1], std::ios::binary);
+ if (!f.read((char*) blob.data(), (std::streamsize) blob.size())) { std::fprintf(stderr, "cannot read %s\n", argv[1]); return 2; }
+ if (argc >= 3 && std::string(argv[2]) == "--group") return group(argv[1]);
+ if (argc >= 5 && std::string(argv[2]) == "--real") return real(argv[1], argv[3], std::atoi(argv[4]));
+ if (argc >= 3 && std::string(argv[2]) == "--layers") return layers(argv[1], argc >= 4 ? std::atoi(argv[3]) : 7);
+ const char* mode = std::getenv("STRATA_PREFILL_NVFP4");
+ std::printf("mode %s, FP4 activations: %s\n", mode ? mode : "default", mmq::fp4_activations(GGML_TYPE_NVFP4) ? "yes" : "no");
+ std::vector<int> Ts;
+ for (int i = 2; i < argc; ++i) Ts.push_back(std::atoi(argv[i]));
+ if (Ts.empty()) Ts = {1, 7, 37, 128, 300};
+ std::mt19937 rng(11);
+ int bad = 0;
+ for (int T : Ts) {
+ bad += product(blob.data(), 2 * FF, N, T, "gate/up", rng);
+ bad += product(blob.data() + gu_bytes, N, FF, T, "down", rng);
+ }
+ std::printf("RESULT: %s\n", bad ? "WRONG (error beyond 20%)" : "ok");
+ return bad ? 1 : 0;
+}
diff --git a/src/prefill/mmq_nvfp4_w4a4.cu b/src/prefill/mmq_nvfp4_w4a4.cu
new file mode 100644
index 000000000..cf6ba22a9
--- /dev/null
+++ b/src/prefill/mmq_nvfp4_w4a4.cu
@@ -0,0 +1,53 @@
+// src/prefill/mmq_nvfp4_w4a4.cu - NVFP4 MMQ with FP4 activations on Blackwell (W4A4, opt-in: STRATA_PREFILL_NVFP4=w4a4).
+//
+// RTX 50's FP4 MMA exists only in the arch-specific target (sm_120a), so this is the one translation unit CMake
+// builds with 12x -> 12xa (strata_mmq_w4a4); everything else, the default NVFP4 path included, keeps the plain
+// architectures and runs on every Blackwell card (sm_121 too). Here mmq.cuh's NVFP4 tile loader and quantize.cu's
+// FP4 activation quantizer see BLACKWELL_MMA_AVAILABLE together - they must agree on the activations' layout.
+// Their non-static symbols are renamed so they cannot fold with strata_mmq's plain-arch copies.
+#include "common.cuh"
+
+#define mul_mat_q_switch_J strata_w4a4_mul_mat_q_switch_J
+#define mul_mat_q_case strata_w4a4_mul_mat_q_case
+#define quantize_row_q8_1_cuda strata_w4a4_quantize_row_q8_1_cuda
+#define quantize_mmq_q8_1_cuda strata_w4a4_quantize_mmq_q8_1_cuda
+#define quantize_scatter_mmq_q8_1_cuda strata_w4a4_quantize_scatter_mmq_q8_1_cuda
+#define quantize_scatter_mmq_fp4_cuda strata_w4a4_quantize_scatter_mmq_fp4_cuda
+#define quantize_mmq_fp4_cuda strata_w4a4_quantize_mmq_fp4_cuda
+#include "mmq.cuh"
+#include "quantize.cu"
+
+DECL_MMQ_CASE(GGML_TYPE_NVFP4);
+
+namespace {
+// 1 when this unit's device code has the FP4 MMA (built for the running card's 12xa); a card without an image
+// here (an architecture not in the list, or sm_121 against a 120a build) fails the launch: W4A4 is then off
+__global__ void w4a4_probe_kernel(int* out) {
+#if defined(BLACKWELL_MMA_AVAILABLE)
+ *out = 1;
+#else
+ *out = 0;
+#endif
+}
+} // namespace
+
+namespace strata::prefill::mmq {
+bool w4a4_available() {
+ int* d = nullptr;
+ int h = 0;
+ if (cudaMalloc(&d, sizeof(int)) != cudaSuccess) { (void) cudaGetLastError(); return false; }
+ w4a4_probe_kernel<<<1, 1>>>(d);
+ const bool ran = cudaGetLastError() == cudaSuccess && cudaMemcpy(&h, d, sizeof(int), cudaMemcpyDeviceToHost) == cudaSuccess;
+ (void) cudaGetLastError();
+ cudaFree(d);
+ return ran && h == 1;
+}
+void run_nvfp4_w4a4(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s) {
+ strata_w4a4_mul_mat_q_case<GGML_TYPE_NVFP4>(ctx, a, s);
+}
+void quantize_nvfp4_w4a4(const float* x, const int32_t* ids, void* xq, float* yscale, bool aligned, int64_t cols,
+ int64_t ld, int64_t rows, int64_t padded, cudaStream_t s) {
+ strata_w4a4_quantize_mmq_fp4_cuda(x, ids, xq, yscale, GGML_TYPE_NVFP4, aligned, cols, ld, rows * ld, rows * ld,
+ padded, rows, 1, 1, s);
+}
+} // namespace strata::prefill::mmq
diff --git a/src/prefill/mmq_nvfp4_w4a8.cu b/src/prefill/mmq_nvfp4_w4a8.cu
new file mode 100644
index 000000000..e8ce27ee2
--- /dev/null
+++ b/src/prefill/mmq_nvfp4_w4a8.cu
@@ -0,0 +1,24 @@
+// src/prefill/mmq_nvfp4_w4a8.cu - NVFP4 MMQ with 8-bit activations on Blackwell (W4A8).
+//
+// On sm_120 mmq.cuh compiles NVFP4 as FP4 x FP4 (W4A4): the activations are rounded to E2M1 too, and the first
+// token's distribution drifts by KL 0.0004-0.03 from the exact FP16 prefill (8 prompts). Every other GPU gets
+// mmq.cuh's int8 path for NVFP4 instead - weights decoded to int8, activations Q8_1, int8 tensor cores - which is
+// the precision decode already runs at (vec_dot_nvfp4_q8_1, ggml-cpu's Q8_0). This TU compiles that path for
+// sm_120 by hiding Blackwell's FP4 MMA from mmq.cuh on both sides: the device code (BLACKWELL_MMA_AVAILABLE) and
+// the host's tile config (blackwell_mma_available(cc)) - they must agree, the host sizes shared memory for the
+// device's layout. The two non-static templates are renamed so the linker cannot fold them with the W4A4 instance.
+#include "common.cuh"
+
+#undef BLACKWELL_MMA_AVAILABLE
+#define blackwell_mma_available(cc) false
+#define mul_mat_q_switch_J strata_w4a8_mul_mat_q_switch_J
+#define mul_mat_q_case strata_w4a8_mul_mat_q_case
+#include "mmq.cuh"
+
+DECL_MMQ_CASE(GGML_TYPE_NVFP4);
+
+namespace strata::prefill::mmq {
+void run_nvfp4_w4a8(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s) {
+ strata_w4a8_mul_mat_q_case<GGML_TYPE_NVFP4>(ctx, a, s);
+}
+} // namespace strata::prefill::mmq
diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu
index b0446f8ee..65e84e6c3 100644
--- a/src/prefill/moe_mmq.cu
+++ b/src/prefill/moe_mmq.cu
@@ -9,6 +9,7 @@
#include <cstdio>
#include <cstdlib>
+#include <cstring>
namespace strata::prefill::mmq {
namespace {
@@ -22,12 +23,20 @@ void ck(cudaError_t e, const char* what) {
int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; }
+// ... plus, in the same launch, the expert's 16-byte NVFP4 tail (tail -> tail_dst) and the zeroed MMQ tails after
+// the group's last slot (nz uint4 after ab_dst's and c_dst's copies): one launch per expert instead of a kernel,
+// a 16-byte copy and, per group, two memsets.
__global__ void copy16_kernel(const uint4* __restrict__ a, int64_t na, const uint4* __restrict__ b, int64_t nb,
- uint4* __restrict__ ab_dst, const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst) {
+ uint4* __restrict__ ab_dst, const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst,
+ const uint4* __restrict__ tail, uint4* __restrict__ tail_dst, int64_t nz) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
+ const int64_t n = na + nb + nc;
if (i < na) ab_dst[i] = a[i];
else if (i < na + nb) ab_dst[i] = b[i - na];
- else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb];
+ else if (i < n) c_dst[i - na - nb] = c[i - na - nb];
+ else if (i < n + nz) ab_dst[na + nb + (i - n)] = make_uint4(0, 0, 0, 0);
+ else if (i < n + 2 * nz) c_dst[nc + (i - n - nz)] = make_uint4(0, 0, 0, 0);
+ else if (i == n + 2 * nz && tail != nullptr) *tail_dst = *tail;
}
// copy16_kernel for an MMQ group: blockIdx.y is the expert (first + y)
struct GroupArgs {
@@ -94,6 +103,29 @@ __global__ void swiglu_kernel(const float* __restrict__ gu, float* __restrict__
h[i] = g / (1.0f + __expf(-g)) * u;
}
+// swiglu_kernel on the MMQ gate/up output with each expert's gate and up scales applied as it is read: the products
+// scale_gu_rows stored, without the pass that stored them
+__global__ void swiglu_scaled_kernel(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff,
+ const int32_t* __restrict__ bounds, int n, const float* __restrict__ tails,
+ int64_t row0) {
+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
+ if (i >= rows * n_ff) return;
+ const int64_t r = i / n_ff, k = i % n_ff, ra = row0 + r;
+ int q = 0;
+ while (q + 1 < n && ra >= bounds[q + 1]) ++q;
+ const float* row = gu + r * 2 * n_ff;
+ const float g = row[k] * tails[4 * q], u = row[n_ff + k] * tails[4 * q + 1];
+ h[i] = g / (1.0f + __expf(-g)) * u;
+}
+__global__ void down_row_scales_kernel(float* __restrict__ sd, const int32_t* __restrict__ bounds, int n,
+ const float* __restrict__ tails, int64_t nrows) {
+ const int64_t r = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
+ if (r >= nrows) return;
+ int q = 0;
+ while (q + 1 < n && r >= bounds[q + 1]) ++q;
+ sd[r] = tails[4 * q + 2];
+}
+
__global__ void iota_kernel(int32_t* dst, int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) dst[i] = (int32_t) i;
@@ -116,8 +148,28 @@ unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); }
} // namespace
+// mmq_nvfp4_w4a8.cu: mmq.cuh's int8 NVFP4 path, compiled for this GPU with Blackwell's FP4 MMA hidden
+void run_nvfp4_w4a8(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s);
+// mmq_nvfp4_w4a4.cu (the one unit built for 12xa): FP4 x FP4 and its activation quantizer, if this card runs it
+bool w4a4_available();
+void run_nvfp4_w4a4(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s);
+void quantize_nvfp4_w4a4(const float* x, const int32_t* ids, void* xq, float* yscale, bool aligned, int64_t cols,
+ int64_t ld, int64_t rows, int64_t padded, cudaStream_t s);
+
bool built() { return true; }
+Nvfp4Mode nvfp4_mode() {
+ static const Nvfp4Mode m = [] {
+ const char* e = std::getenv("STRATA_PREFILL_NVFP4");
+ if (e == nullptr || std::strcmp(e, "w4a8") == 0) return Nvfp4Mode::W4A8;
+ if (std::strcmp(e, "w4a4") == 0) return Nvfp4Mode::W4A4;
+ if (std::strcmp(e, "fp16") == 0) return Nvfp4Mode::FP16;
+ std::fprintf(stderr, "STRATA_PREFILL_NVFP4=%s: expected w4a8, w4a4 or fp16\n", e);
+ std::exit(1);
+ }();
+ return m;
+}
+
bool supported(int t) {
switch ((ggml_type) t) {
case GGML_TYPE_Q2_0:
@@ -134,6 +186,10 @@ bool supported(int t) {
#endif
#endif
return true;
+#if !defined(GGML_USE_HIP)
+ case GGML_TYPE_NVFP4:
+ return nvfp4_mode() != Nvfp4Mode::FP16;
+#endif
default:
return false;
}
@@ -175,8 +231,68 @@ size_t q8_bytes(int64_t rows, int64_t cols) {
return (size_t) rows * (size_t) pad512(cols) * sizeof(block_q8_1_mmq) / (4 * QK8_1) + 128 * sizeof(block_q8_1_mmq);
}
-void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream) {
+namespace {
+__global__ void scale_gu_rows_kernel(float* __restrict__ gu, int64_t ld, int64_t n_ff, const int32_t* __restrict__ bounds,
+ int n, const float* __restrict__ tails, int64_t row0) {
+ const int64_t r = row0 + blockIdx.x;
+ int q = 0;
+ while (q + 1 < n && r >= bounds[q + 1]) ++q;
+ const float sg = tails[4 * q], su = tails[4 * q + 1];
+ float* row = gu + r * ld;
+ for (int64_t k = threadIdx.x; k < 2 * n_ff; k += blockDim.x) row[k] *= k < n_ff ? sg : su;
+}
+__global__ void scale_down_rows_kernel(float* __restrict__ d, int64_t ld, const int32_t* __restrict__ bounds, int n,
+ const float* __restrict__ tails) {
+ const int64_t r = blockIdx.x;
+ int q = 0;
+ while (q + 1 < n && r >= bounds[q + 1]) ++q;
+ const float sd = tails[4 * q + 2];
+ float* row = d + r * ld;
+ for (int64_t k = threadIdx.x; k < ld; k += blockDim.x) row[k] *= sd;
+}
+} // namespace
+
+bool fp4_activations(int t) {
+#if defined(GGML_USE_HIP) // no NVFP4 MMQ on HIP (and no W4A4 unit)
+ (void) t;
+ return false;
+#else
+ if (t != GGML_TYPE_NVFP4 || nvfp4_mode() != Nvfp4Mode::W4A4) return false;
+ static const bool on = [] {
+ const bool ok = w4a4_available();
+ if (!ok) std::fprintf(stderr, "prefill mmq: STRATA_PREFILL_NVFP4=w4a4 needs an sm_12x card in a 12x build; W4A8\n");
+ return ok;
+ }();
+ return on;
+#endif
+}
+
+void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, int n, const float* tails,
+ int64_t row0, int64_t nrows, void* stream) {
+ if (nrows <= 0 || n <= 0) return;
+ scale_gu_rows_kernel<<<(unsigned) nrows, 256, 0, (cudaStream_t) stream>>>(gu, ld, n_ff, bounds, n, tails, row0);
+ ck(cudaGetLastError(), "scale_gu_rows");
+}
+
+void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream) {
+ if (nrows <= 0 || n <= 0) return;
+ scale_down_rows_kernel<<<(unsigned) nrows, 256, 0, (cudaStream_t) stream>>>(d, ld, bounds, n, tails);
+ ck(cudaGetLastError(), "scale_down_rows");
+}
+
+void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream,
+ float* yscale) {
if (rows <= 0) return;
+#if !defined(GGML_USE_HIP)
+ if (fp4_activations(t)) {
+ if (yscale == nullptr) { std::fprintf(stderr, "prefill mmq: NVFP4 activations need a scale buffer\n"); std::exit(1); }
+ const bool aligned = ((uintptr_t) x % 32 == 0) && ((size_t) ld * sizeof(float)) % 32 == 0;
+ quantize_nvfp4_w4a4(x, ids, xq, yscale, aligned, cols, ld, rows, pad512(cols), (cudaStream_t) stream);
+ ck(cudaGetLastError(), "quantize");
+ return;
+ }
+#endif
+ (void) yscale;
quantize_mmq_q8_1_cuda(x, ids, xq, (ggml_type) t, cols, ld, rows * ld, rows * ld, pad512(cols), rows, 1, 1,
(cudaStream_t) stream);
ck(cudaGetLastError(), "quantize");
@@ -193,7 +309,7 @@ void Context::run(const Product& p, void* stream) {
if (p.n <= 0 || p.max_rows <= 0) return;
const ggml_type t = (ggml_type) p.type;
const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk;
- const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, nullptr,
+ const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, p.y_scale,
p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst,
p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0,
1, 1, 0, 0, 0,
@@ -220,6 +336,12 @@ void Context::run(const Product& p, void* stream) {
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
#endif
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
+#endif
+#if !defined(GGML_USE_HIP) // NVFP4: CUDA only (no HIP instance, no W4A8 unit)
+ case GGML_TYPE_NVFP4:
+ if (fp4_activations(t)) run_nvfp4_w4a4(ctx, a, s);
+ else run_nvfp4_w4a8(ctx, a, s);
+ break;
#endif
default:
std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t);
@@ -229,15 +351,21 @@ void Context::run(const Product& p, void* stream) {
}
void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes,
- void* gu_dst, void* d_dst, void* stream) {
+ void* gu_dst, void* d_dst, void* stream, const void* tail, void* tail_dst, size_t zero_bytes) {
const cudaStream_t s = (cudaStream_t) stream;
const bool a16 = ((uintptr_t) gate | (uintptr_t) up | (uintptr_t) down | (uintptr_t) gu_dst | (uintptr_t) d_dst |
- gu_half_bytes | d_bytes) % 16 == 0;
+ (uintptr_t) tail | (uintptr_t) tail_dst | gu_half_bytes | d_bytes | zero_bytes) % 16 == 0;
if (a16) {
- const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16;
- copy16_kernel<<<blocks(2 * na + nc), 256, 0, s>>>((const uint4*) gate, na, (const uint4*) up, na, (uint4*) gu_dst,
- (const uint4*) down, nc, (uint4*) d_dst);
+ const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16, nz = (int64_t) zero_bytes / 16;
+ copy16_kernel<<<blocks(2 * na + nc + 2 * nz + 1), 256, 0, s>>>(
+ (const uint4*) gate, na, (const uint4*) up, na, (uint4*) gu_dst, (const uint4*) down, nc, (uint4*) d_dst,
+ (const uint4*) tail, (uint4*) tail_dst, nz);
} else {
+ if (tail) cudaMemcpyAsync(tail_dst, tail, 16, cudaMemcpyDeviceToDevice, s);
+ if (zero_bytes) {
+ cudaMemsetAsync((uint8_t*) gu_dst + 2 * gu_half_bytes, 0, zero_bytes, s);
+ cudaMemsetAsync((uint8_t*) d_dst + d_bytes, 0, zero_bytes, s);
+ }
const int64_t na = (int64_t) gu_half_bytes, nc = (int64_t) d_bytes;
copy1_kernel<<<blocks(2 * na + nc), 256, 0, s>>>((const uint8_t*) gate, na, (const uint8_t*) up, na,
(uint8_t*) gu_dst, (const uint8_t*) down, nc, (uint8_t*) d_dst);
@@ -270,6 +398,18 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre
ck(cudaGetLastError(), "gather_strata_q2");
}
+void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n,
+ const float* tails, int64_t row0, void* stream) {
+ if (rows <= 0) return;
+ swiglu_scaled_kernel<<<blocks(rows * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h, rows, n_ff, bounds, n, tails, row0);
+ ck(cudaGetLastError(), "swiglu_scaled");
+}
+void down_row_scales(float* sd, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream) {
+ if (nrows <= 0 || n <= 0) return;
+ down_row_scales_kernel<<<blocks(nrows), 256, 0, (cudaStream_t) stream>>>(sd, bounds, n, tails, nrows);
+ ck(cudaGetLastError(), "down_row_scales");
+}
+
void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream) {
if (rows <= 0) return;
swiglu_kernel<<<blocks(rows * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h, rows, n_ff, interleaved);
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index d13fdd197..aeb4e31e6 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -66,14 +66,18 @@ bool supported(int) { return false; }
bool fits(int, int64_t) { return false; }
size_t matrix_bytes(int, int64_t, int64_t) { return 0; }
size_t q8_bytes(int64_t, int64_t) { return 0; }
-void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*) {}
+void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*, float*) {}
+bool fp4_activations(int) { return false; }
Context::Context() {}
Context::~Context() {}
void Context::run(const Product&, void*) {}
-void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*) {}
-bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*) { return false; }
+void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*, const void*, void*, size_t) {}
+bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*, size_t,
+ void*, size_t) { return false; }
void gather_strata_q2(const uint8_t*, void*, void*, void*) {}
void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
+void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {}
+void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {}
void iota(int32_t*, int64_t, void*) {}
} // namespace strata::prefill::mmq
#endif
@@ -784,6 +788,8 @@ struct Prefill::Impl {
float* H = nullptr;
int32_t *ids_identity = nullptr, *bounds_dev = nullptr;
uint8_t *grp_gu = nullptr, *grp_d = nullptr;
+ float *Xscale = nullptr, *Hscale = nullptr, *grp_tail = nullptr; // NVFP4: activation scales, expert tails
+ float* row_sd = nullptr; // NVFP4 in MMQ: each Dm row's s_down, applied by the combine as it reads the row
std::vector<int32_t> bounds_host;
std::unique_ptr<mmq::Context> mmq_ctx;
std::vector<int32_t> ids_host, slot_host, src_host, cnt, off;
@@ -1053,6 +1059,8 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
a.take<uint8_t>(mb.xq, ok);
a.take<float>(mb.h, ok);
a.take<uint8_t>(mb.hq, ok);
+ a.take<float>(T * K, ok); a.take<float>(T * K, ok); a.take<float>(MMQ_GROUP * 4, ok);
+ a.take<float>(T * K, ok);
}
return a.used;
}
@@ -1271,6 +1279,9 @@ bool Prefill::carve(size_t T, void* alloc) {
m.Xq = c.take<uint8_t>(mb.xq, ok);
m.H = c.take<float>(mb.h, ok);
m.Hq = c.take<uint8_t>(mb.hq, ok);
+ m.Xscale = c.take<float>(T * K, ok); m.Hscale = c.take<float>(T * K, ok);
+ m.grp_tail = c.take<float>(MMQ_GROUP * 4, ok);
+ m.row_sd = c.take<float>(T * K, ok);
}
if (base == nullptr) ok = false;
}
@@ -1655,6 +1666,11 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e
const bool host_route_ok = [] { const char* v = std::getenv("STRATA_PF_PEER_HOST"); return v == nullptr || std::atoi(v) != 0; }();
if (!peer->p2p() && !host_route_ok) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; }
if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; }
+ { // NVFP4: the peer's MMQ products have no per-expert scales (grp_tail, row_sd); its decode rows do
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ for (const auto& f : lay.fmt)
+ if (lay.native && f.tail_off) { err = "prefill peer: not for NVFP4 experts yet"; return false; }
+ }
auto pp = std::make_unique<PeerPrefill>();
pp->peer = peer;
pp->p2p = peer->p2p();
@@ -3320,6 +3336,23 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return false;
}
}
+ // Diagnostics: STRATA_DUMP_MOE_INPUT=path, STRATA_DUMP_MOE_LAYER=l - the first chunk's MoE input
+ // of layer l ({T, N, K} int64, T x N floats, T x K expert ids) for testing products on real rows
+ static const char* dump_moe = std::getenv("STRATA_DUMP_MOE_INPUT");
+ static bool dumped_moe = false;
+ if (dump_moe && !dumped_moe && l == std::atoi(std::getenv("STRATA_DUMP_MOE_LAYER") ? std::getenv("STRATA_DUMP_MOE_LAYER") : "0")) {
+ dumped_moe = true;
+ std::vector<float> x((size_t) (T * N));
+ cudaMemcpyAsync(x.data(), m.mixed, x.size() * sizeof(float), cudaMemcpyDeviceToHost, m.cs);
+ cudaStreamSynchronize(m.cs);
+ if (std::FILE* f = std::fopen(dump_moe, "wb")) {
+ const int64_t hdr[3] = {(int64_t) T, (int64_t) N, (int64_t) K};
+ std::fwrite(hdr, sizeof hdr, 1, f);
+ std::fwrite(x.data(), sizeof(float), x.size(), f);
+ std::fwrite(ids_h, sizeof(int32_t), (size_t) (T * K), f);
+ std::fclose(f);
+ }
+ }
n_order = order.size();
// set_cpu_pool: the CPU's experts on a thread while this one streams and runs the GPU's; their
// unweighted rows land in Dm's row order, so the combine weights them as any other row
@@ -3385,7 +3418,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
pt.mark(kPfGather, cs);
if (use_mmq) {
// step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
- mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs);
+ mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale);
// each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
// reads the group's own quantized H)
const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
@@ -3767,7 +3800,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
mmq::GatherGroup gg;
int gg_slots[MMQ_GROUP];
int gg_nslots = 0; // ring slots gathered by the next flush
- auto flush = [&]() {
+ // `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush)
+ auto flush = [&](size_t zero) {
if (gg.n <= gg.first) return;
const auto& f = lay.fmt[(size_t) l];
if (gg_nslots > 0) { // the copies land in order: the last one covers the others
@@ -3775,12 +3809,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
cudaStreamWaitEvent(m.cs, m.copied[gg_slots[gg_nslots - 1]], 0);
pt.mark(kPfDequant, cs);
}
+ // NVFP4: each expert's scales go next to its group slot in the same launch
if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub,
- m.grp_d, mmq_db, m.cs)) {
+ m.grp_d, mmq_db, m.cs, f.tail_off,
+ f.tail_off ? m.grp_tail : nullptr, zero)) {
for (int i = gg.first; i < gg.n; ++i) { // not 16-byte aligned: one at a time
const uint8_t* b = gg.blob[i];
mmq::gather_native(b, b + f.up_off, mmq_gub / 2, b + f.down_off, mmq_db,
- m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs);
+ m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs,
+ f.tail_off ? b + f.tail_off : nullptr,
+ f.tail_off ? m.grp_tail + i * 4 : nullptr, i + 1 == gg.n ? zero : 0);
}
}
if (gg_nslots > 0) {
@@ -3799,19 +3837,28 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (use_mmq) {
// gather the expert into its group slot (GGUF blocks, unchanged or converted)
const size_t q = j % MMQ_GROUP;
+ // the group's last expert also zeroes the MMQ tail after its slot (see MMQ_TAIL)
+ const bool last_of_group = q + 1 == MMQ_GROUP || j + 1 == order.size();
if (group_gather) {
gg.blob[q] = blob_dev;
gg.n = (int) q + 1;
if (slot >= 0) gg_slots[gg_nslots++] = slot;
- if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
- flush();
+ if (!last_of_group) return true;
+ flush(MMQ_TAIL);
gg = mmq::GatherGroup{};
} else if (lay.native) {
const auto& f = lay.fmt[(size_t) l];
+ // NVFP4: this expert's scales go next to its group slot in the same launch
mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
- mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
+ mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs,
+ f.tail_off ? blob_dev + f.tail_off : nullptr,
+ f.tail_off ? m.grp_tail + q * 4 : nullptr, last_of_group ? MMQ_TAIL : 0);
} else {
mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
+ if (last_of_group) {
+ cudaMemsetAsync(m.grp_gu + (size_t) (q + 1) * mmq_gub, 0, MMQ_TAIL, m.cs);
+ cudaMemsetAsync(m.grp_d + (size_t) (q + 1) * mmq_db, 0, MMQ_TAIL, m.cs);
+ }
}
if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
@@ -3822,23 +3869,28 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
int64_t maxr = 0;
for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
pt.mark(kPfGemmGU, cs);
- // the zeroed tail after the group's last expert (see MMQ_TAIL)
- cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs);
- cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs);
mmq::Product gu;
gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
+ gu.y_scale = mmq::fp4_activations(mmq_gt) ? m.Xscale : nullptr;
m.mmq_ctx->run(gu, m.cs);
- mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
+ if (lay.native && lay.fmt[(size_t) l].tail_off) // gate/up scales applied as read
+ mmq::swiglu_scaled(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, m.bounds_dev + j0, ngx,
+ m.grp_tail, r0, m.cs);
+ else
+ mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
pt.mark(kPfGemmD, cs);
- mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs);
+ mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs, m.Hscale);
mmq::Product dn;
dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
dn.ld_dst = N;
+ dn.y_scale = mmq::fp4_activations(mmq_dt) ? m.Hscale : nullptr;
m.mmq_ctx->run(dn, m.cs);
+ if (lay.native && lay.fmt[(size_t) l].tail_off) // s_down: applied by the combine
+ mmq::down_row_scales(m.row_sd + r0, dn.bounds, ngx, m.grp_tail, nr, m.cs);
return true;
}
const int q = (int) (j % DQ);
@@ -3846,8 +3898,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
const auto& f = lay.fmt[(size_t) l];
strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
- m.dq_gu[q], m.cs);
- strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
+ m.dq_gu[q], m.cs,
+ f.tail_off ? (const float*) (blob_dev + f.tail_off) : nullptr);
+ strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs,
+ f.tail_off ? (const float*) (blob_dev + f.tail_off) + 2 : nullptr);
} else {
blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
}
@@ -3891,7 +3945,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const size_t kend = seq_start[(size_t) l + 1];
auto release_to = [&](int32_t e_stop) {
while (k < kend && seq[k].e < e_stop) {
- if (gg_nslots > 0) flush(); // the open group's slots get their event first
+ if (gg_nslots > 0) flush(0); // the open group's slots get their event first
const int sl = (int) (k % (size_t) m.ring);
cudaEventRecord(m.used[sl], m.cs);
m.used_of[sl] = sl;
@@ -3959,7 +4013,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
else if (peer_now && m.pp->sums)
moe_combine_peer(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.pp->host_sum, m.pp->back_at, m.bo, T, m.cs);
else
- moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);
+ moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs,
+ use_mmq && !fused_l && lay.native && lay.fmt[(size_t) l].tail_off ? m.row_sd : nullptr);
// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values
if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {
cudaStreamSynchronize(m.cs);
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 7a93c0a3e..587a29fd7 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -2783,8 +2783,13 @@ int main(int argc, char** argv) {
// link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The
// real H2D bandwidth is probed once; from 20 GB/s up (x16 PCIe 4/5) the measured default stays. The canonical
// pack keeps 0.2 as its start value (0.1.43: PcieAuto refines it on CUDA). `--calibrate` measures it outright.
+ // NVFP4 packs: 0.25. Their 2.76 MB experts cross the link twice as long as the i-quants' the 0.55 was
+ // measured on, and that copy sits on the GPU's critical path while the CPU pool runs beside it: decode
+ // 103 -> 117 tok/s short, 105 -> 124 at 32K (RTX 5090, PCIe 5 x16, 9950X3D; 0.10 and 0.40 both slower).
if (o.pcie_frac < 0.0) {
- const double base = native_pack ? 0.55 : 0.2;
+ const auto& lay0 = strata::kernels::cpu::expert_layout();
+ const bool nvfp4_pack = native_pack && !lay0.fmt.empty() && lay0.fmt[0].gu_type == 40;
+ const double base = nvfp4_pack ? 0.25 : native_pack ? 0.55 : 0.2;
std::string bursts;
const char* pfd = std::getenv("STRATA_PCIE_FRAC_DEFAULT");
const bool pf_old = pfd != nullptr && std::strcmp(pfd, "old") == 0;
diff --git a/tools/iq_pack.py b/tools/iq_pack.py
index 5ce0e4a52..41ca26d18 100644
--- a/tools/iq_pack.py
+++ b/tools/iq_pack.py
@@ -201,6 +201,7 @@ def check_split(files) -> None:
ROLES = ("gate", "up", "down")
N_EXPERT = 512
ALIGN = 64
+NVFP4_TAIL = 16 # {s_gate, s_up, s_down, 0} after an NVFP4 expert blob
def read_index(path: pathlib.Path):
@@ -451,11 +452,26 @@ def expert_layout(model: Model, src: pathlib.Path):
if per[0] != per[1] or ts[0].type_name != ts[1].type_name:
return "layer %d: gate and up differ in type" % l
blob = per[0] + per[1] + per[2]
+ nvfp4 = ts[0].type_name == "NVFP4" or ts[2].type_name == "NVFP4"
+ if nvfp4:
+ # NVFP4 (ModelOpt) carries one F32 weight_scale_2 per expert and projection, which the block format has
+ # no room for. Each blob gets a 16-byte tail {s_gate, s_up, s_down, 0} so every consumer that already
+ # moves whole blobs (the arena, the device cache, the prefill staging, a second GPU) moves the scales
+ # with the weights; the gate/up kernels read it. See tools/nvfp4_convert.py.
+ if ts[0].type_name != "NVFP4" or ts[2].type_name != "NVFP4":
+ return "layer %d: NVFP4 must cover gate, up and down alike" % l
+ if any("blk.%d.ffn_%s_exps.scale" % (l, r) not in T for r in ROLES):
+ return "layer %d: NVFP4 experts without their .scale tensors" % l
+ blob += NVFP4_TAIL
layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts))
ws = [model.where[n] for n in names]
files = ["" if w[3] == src else w[3].name for w in ws]
column = files[0] if len(set(files)) == 1 else ",".join(files)
n_split += len(set(files)) != 1
+ if nvfp4: # no GGUF offsets: experts.bin is the only source that carries the scale tails
+ lines.append("%d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob))
+ offset += blob * n_expert
+ continue
line = "%d %d %d %d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob,
*[w[0].data_start + w[1].offset for w in ws])
lines.append(line + ("" if not column else " " + column))
@@ -522,14 +538,33 @@ def main() -> int:
print(got)
return 1
layout, text, n_expert, offset = got
+ if any(ts[0].type_name == "NVFP4" for *_, ts in layout):
+ a.experts_bin = True # the GGUF holds the weights without the scale tails: the engine must read experts.bin
path = out / "experts.bin"
sidecar = out / "experts.bin.src.json"
want = experts_source(model, text, offset)
reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want
- def layer_blobs(blob, ts):
- chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1)
- assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert
+ def nvfp4_tails(l, ts):
+ """(n_expert, NVFP4_TAIL) bytes {s_gate, s_up, s_down, 0} of an NVFP4 layer; None for a bad scale."""
+ s = [np.frombuffer(model.bytes("blk.%d.ffn_%s_exps.scale" % (l, r)).tobytes(), dtype=np.float32) for r in ROLES]
+ tail = np.zeros((n_expert, NVFP4_TAIL // 4), dtype=np.float32)
+ tail[:, 0], tail[:, 1], tail[:, 2] = s[0], s[1], s[2]
+ if not np.isfinite(tail).all() or (tail[:, :3] <= 0).any():
+ print("layer %d: a non-finite or non-positive NVFP4 scale" % l)
+ return None
+ return tail.view(np.uint8)
+
+ def layer_blobs(l, blob, ts):
+ """(n_expert, blob): gate | up | down [| the NVFP4 scale tail] per expert; None for a bad NVFP4 scale."""
+ parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts]
+ if ts[0].type_name == "NVFP4":
+ tail = nvfp4_tails(l, ts)
+ if tail is None:
+ return None
+ parts.append(tail)
+ chunk = np.concatenate(parts, axis=1)
+ assert chunk.shape == (n_expert, blob)
return chunk
if reuse:
@@ -541,6 +576,9 @@ def main() -> int:
for e in (0, n_expert - 1):
f.seek(off + e * blob)
want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts)
+ if ts[0].type_name == "NVFP4":
+ tail = nvfp4_tails(l, ts)
+ want_blob += tail[e].tobytes() if tail is not None else b""
if f.read(blob) != want_blob:
reuse = False
if not reuse:
@@ -586,7 +624,10 @@ def main() -> int:
part = out / "experts.bin.tmp"
with open(part, "wb") as fo:
for l, gt, dt, off, blob, ts in layout:
- fo.write(layer_blobs(blob, ts).tobytes())
+ chunk = layer_blobs(l, blob, ts)
+ if chunk is None:
+ return 1
+ fo.write(chunk.tobytes())
if l % 8 == 0:
print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob,
off / 2**30), flush=True)
diff --git a/tools/nvfp4_convert.py b/tools/nvfp4_convert.py
new file mode 100644
index 000000000..31eb8a6aa
--- /dev/null
+++ b/tools/nvfp4_convert.py
@@ -0,0 +1,128 @@
+"""tools/nvfp4_convert.py - a ModelOpt NVFP4 Qwen3.8-Flash-Next checkpoint -> a GGUF Strata can pack.
+
+ python tools/nvfp4_convert.py --model <ModelOpt NVFP4 dir> --outfile <model.gguf>
+
+This is llama.cpp's own converter (third_party/llama.cpp at the commit setup.py pins), run with the type policy
+Strata's engine needs. The converter already repacks ModelOpt NVFP4 experts into ggml's block_nvfp4 without loss
+(tools/nvfp4_verify.py proves it bit for bit) and writes each expert's weight_scale_2 as a separate F32 tensor
+`blk.N.ffn_{gate,up,down}_exps.scale`, one value per expert. What it does not know is Strata's layout:
+
+ * the small projections the residual, router, GDN, QSA and PLE kernels read as BF16 (iq_pack.BF16_PROJECTIONS)
+ must be BF16 - the converter would otherwise write routers and indexer projections as F32, which iq_pack
+ refuses, and the rest as the --outtype;
+ * everything the engine serves natively (attention, ssm_out, shared experts, output) goes to Q8_0: the native
+ GEMV has no BF16 path, and Q8_0 is the closest to the checkpoint's BF16 it has;
+ * token_embd goes to Q8_0 too. The abliteration edited embed_tokens, so another model's table cannot be reused,
+ and gguf-py cannot write the IQ types the native embedding reads today - the engine learns Q8_0 instead;
+ * the 51.2B-parameter PLE n-gram table is left out. The engine only reads it as IQ4_NL (ngram.cpp), and
+ dequantizing the checkpoint's FP8 copy would need ~205 GB of RAM. The abliteration did not touch this table,
+ so the engine is pointed at ISTA-DASLab's IQ4_NL shard 2 with --ple-gguf. The PLE hash constants and the
+ row width still come from this checkpoint and are written into the metadata.
+
+The MTP head is dropped here as llama.cpp does; tools/mtp_pack.py packs it separately.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import pathlib
+import subprocess
+import sys
+import time
+
+ENGINE = pathlib.Path(__file__).resolve().parents[1]
+LLAMA = ENGINE / "third_party" / "llama.cpp"
+sys.path.insert(0, str(LLAMA / "gguf-py"))
+sys.path.insert(0, str(LLAMA))
+
+import gguf # noqa: E402
+from conversion import qwen4exp as Q4 # noqa: E402
+
+T = gguf.GGMLQuantizationType
+
+# Strata reads these as BF16 (tools/iq_pack.py BF16_PROJECTIONS + BF16_OUTPUT, and the routers).
+BF16_SUFFIXES = (
+ "hc_attn_down.weight", "hc_attn_up.weight", "hc_attn_inject.weight",
+ "hc_ffn_down.weight", "hc_ffn_up.weight", "hc_ffn_inject.weight",
+ "ssm_alpha.weight", "ssm_beta.weight", "indexer.q_proj.weight", "indexer.k_proj.weight",
+ "ple_value.weight", "ple_key.weight", "ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight",
+ "output_hc_down.weight", "output_hc_up.weight",
+)
+F16_SUFFIXES = ("ple_conv1d.weight",)
+Q8_NAMES = {"token_embd.weight", "output.weight"}
+
+dropped_ple: list[str] = []
+
+
+def install_policy() -> None:
+ cls = Q4.Qwen4ExpTextModel
+ base_force = cls.tensor_force_quant
+
+ def tensor_force_quant(self, name, new_name, bid, n_dims):
+ if n_dims >= 2:
+ if new_name.endswith(BF16_SUFFIXES):
+ return T.BF16
+ if new_name.endswith(F16_SUFFIXES):
+ return T.F16
+ if new_name in Q8_NAMES:
+ return T.Q8_0
+ return base_force(self, name, new_name, bid, n_dims)
+
+ def place_ple_shard(self, data_torch, name):
+ # Record the shard so the parts check in prepare_tensors still holds, and the row width for the
+ # metadata; write nothing - the table comes from the IQ4_NL PLE GGUF at run time.
+ idx = int(name.rsplit("shard_", 1)[1].split(".", 1)[0])
+ self._ple_shards[idx] = name
+ self._ple_row_dim = int(data_torch.shape[-1])
+ dropped_ple.append(name)
+ return []
+
+ cls.tensor_force_quant = tensor_force_quant
+ cls._place_ple_shard = place_ple_shard
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--model", required=True, help="the ModelOpt NVFP4 checkpoint directory")
+ ap.add_argument("--outfile", required=True)
+ ap.add_argument("--dry-run", action="store_true")
+ a = ap.parse_args()
+ model = pathlib.Path(a.model)
+ out = pathlib.Path(a.outfile)
+ out.parent.mkdir(parents=True, exist_ok=True)
+
+ install_policy()
+ import convert_hf_to_gguf as C # noqa: E402 (after the policy is installed on the class)
+
+ argv = [str(model), "--outtype", "q8_0", "--outfile", str(out)]
+ if a.dry_run:
+ argv.append("--dry-run")
+ sys.argv = ["convert_hf_to_gguf.py"] + argv
+ t0 = time.time()
+ rc = C.main()
+ took = time.time() - t0
+
+ try: # a release bundle ships the converter's files without git: its COMMIT file names the commit
+ commit = subprocess.run(["git", "-C", str(LLAMA), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
+ except OSError:
+ commit = ""
+ if not commit and (LLAMA / "COMMIT").exists():
+ commit = (LLAMA / "COMMIT").read_text(encoding="utf-8").strip()
+ manifest = {
+ "source": str(model),
+ "llama_cpp_commit": commit,
+ "policy": {"bf16": list(BF16_SUFFIXES), "f16": list(F16_SUFFIXES), "q8_0": sorted(Q8_NAMES),
+ "default_2d": "Q8_0", "experts": "NVFP4 (lossless repack) + per-expert F32 .scale"},
+ "ple_table": {"written": False, "shards_dropped": len(dropped_ple),
+ "use": "--ple-gguf with an IQ4_NL per_layer_token_embd (ISTA-DASLab shard 2)"},
+ "mtp": "dropped here; pack with tools/mtp_pack.py",
+ "seconds": round(took, 1),
+ }
+ if not a.dry_run:
+ out.with_suffix(".manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ print("nvfp4_convert: done in %.0f s, PLE shards dropped: %d" % (took, len(dropped_ple)))
+ return rc or 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/nvfp4_verify.py b/tools/nvfp4_verify.py
new file mode 100644
index 000000000..fc7ed8412
--- /dev/null
+++ b/tools/nvfp4_verify.py
@@ -0,0 +1,121 @@
+"""tools/nvfp4_verify.py - prove the ModelOpt -> ggml NVFP4 repack is lossless on a real checkpoint.
+
+ python tools/nvfp4_verify.py --model <ModelOpt NVFP4 dir> [--experts 4] [--scan-all]
+
+llama.cpp's converter repacks ModelOpt NVFP4 by moving bits: nibbles into ggml's split-half order, and each
+E4M3 block scale into a UE4M3 byte by stripping its sign bit. That is lossless only while every scale is a
+finite, non-negative E4M3 - a negative scale would silently flip, a NaN would propagate. So this checks two
+things independently of the converter's own code path:
+
+ 1. every weight_scale byte in the checkpoint (--scan-all): no sign bit set, no NaN encoding (0x7F / 0xFF);
+ 2. for a few experts: dequantize ModelOpt directly (E2M1 value x E4M3 scale x weight_scale_2) and compare
+ with gguf-py's dequantization of the repacked block_nvfp4 bytes times the same weight_scale_2. They must
+ agree bit for bit in float32.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import pathlib
+import sys
+
+import numpy as np
+import torch
+from safetensors import safe_open
+
+LLAMA = pathlib.Path(__file__).resolve().parents[1] / "third_party" / "llama.cpp"
+sys.path.insert(0, str(LLAMA / "gguf-py"))
+sys.path.insert(0, str(LLAMA))
+from gguf import GGMLQuantizationType as Q, quants # noqa: E402
+from conversion.base import ModelBase # noqa: E402
+
+E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
+
+
+def modelopt_dequant(weight: torch.Tensor, scale: torch.Tensor, scale2: torch.Tensor) -> np.ndarray:
+ """The ModelOpt definition, written out independently of the converter."""
+ rows = weight.shape[0]
+ lo = (weight & 0x0F).long()
+ hi = (weight >> 4).long()
+ nib = torch.stack([lo, hi], dim=-1).reshape(rows, -1) # element 2j low, 2j+1 high
+ vals = E2M1[nib]
+ s = scale.float().repeat_interleave(16, dim=1)
+ return (vals * s * scale2.float()).numpy().astype(np.float32)
+
+
+def check_scales(model: pathlib.Path) -> int:
+ index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
+ by_shard: dict[str, list[str]] = {}
+ for name, shard in index.items():
+ if name.endswith(".weight_scale"):
+ by_shard.setdefault(shard, []).append(name)
+ n_bytes = n_sign = n_nan = n_tensors = 0
+ worst = []
+ for i, (shard, names) in enumerate(sorted(by_shard.items())):
+ with safe_open(model / shard, framework="pt") as f:
+ for name in names:
+ t = f.get_tensor(name)
+ if t.dtype != torch.float8_e4m3fn or t.ndim != 2:
+ continue # FP8 per-channel scales are not NVFP4
+ b = t.view(torch.uint8)
+ sign = int((b & 0x80).count_nonzero())
+ nan = int(((b & 0x7F) == 0x7F).sum())
+ n_bytes += b.numel()
+ n_sign += sign
+ n_nan += nan
+ n_tensors += 1
+ if sign or nan:
+ worst.append((name, sign, nan))
+ if i % 40 == 0:
+ print(" scanned %3d/%d shards, %d scale tensors" % (i + 1, len(by_shard), n_tensors), flush=True)
+ print("scale bytes %.2f GiB in %d tensors: sign bit set %d, NaN %d" % (n_bytes / 2**30, n_tensors, n_sign, n_nan))
+ for w in worst[:10]:
+ print(" BAD", *w)
+ return 1 if (n_sign or n_nan) else 0
+
+
+def check_experts(model: pathlib.Path, n: int) -> int:
+ index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
+ picks = [name for name in sorted(index)
+ if ".experts." in name and name.endswith(".weight") and ".mtp." not in name
+ and name.replace(".weight", ".weight_scale") in index][:: max(1, 50000 // max(1, n))][:n * 3]
+ bad = 0
+ for name in picks:
+ shard = model / index[name]
+ with safe_open(shard, framework="pt") as f:
+ w = f.get_tensor(name)
+ s = f.get_tensor(name.replace(".weight", ".weight_scale"))
+ s2_name = name.replace(".weight", ".weight_scale_2")
+ s2 = f.get_tensor(s2_name) if s2_name in f.keys() else torch.tensor(1.0)
+ ref = modelopt_dequant(w, s, s2)
+ raw, shape = ModelBase._nvfp4_pack(w, s)
+ got = quants.dequantize(np.ascontiguousarray(raw), Q.NVFP4).reshape(shape).astype(np.float32)
+ got = (torch.from_numpy(got) * s2.float()).numpy()
+ # E2M1 code 8 is -0.0; ggml's kvalues_fp4 stores both zeros as integer 0, so the repacked weights give
+ # +0.0 where ModelOpt gives -0.0. That is the same value in every sum (x + -0 == x), so normalise zeros
+ # (adding +0.0 turns -0.0 into +0.0) and keep the comparison bitwise for everything else.
+ neg_zero = int(np.count_nonzero((ref == 0) & np.signbit(ref)))
+ same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got + np.float32(0)).view(np.uint32))
+ diff = float(np.abs(ref - got).max())
+ print(" %-70s %-12s bitwise %s max|diff| %.3g (-0.0 in source: %d)"
+ % (name[-70:], tuple(shape), "OK " if same else "NO ", diff, neg_zero))
+ bad += not same
+ return 1 if bad else 0
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--experts", type=int, default=4, help="how many experts to compare (3 projections each)")
+ ap.add_argument("--scan-all", action="store_true", help="check every weight_scale byte in the checkpoint")
+ a = ap.parse_args()
+ model = pathlib.Path(a.model)
+ rc = check_experts(model, a.experts)
+ if a.scan_all:
+ rc |= check_scales(model)
+ print("RESULT:", "lossless" if rc == 0 else "NOT lossless")
+ return rc
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/nvfp4_verify_gguf.py b/tools/nvfp4_verify_gguf.py
new file mode 100644
index 000000000..45bddfea3
--- /dev/null
+++ b/tools/nvfp4_verify_gguf.py
@@ -0,0 +1,161 @@
+"""tools/nvfp4_verify_gguf.py - check a converted NVFP4 GGUF against its ModelOpt source, and a PLE GGUF against it.
+
+ python tools/nvfp4_verify_gguf.py --model <ModelOpt dir> --gguf <converted.gguf> [--ple-gguf <IQ4_NL PLE gguf>]
+
+nvfp4_verify.py proves the repack function is lossless. This checks what was actually written, where the
+converter's own bookkeeping could go wrong without the function being wrong:
+
+ * expert order: 512 experts are sorted and stacked per (layer, projection); expert e of the stacked tensor
+ must be the source's expert e - checked bit for bit (signed zeros normalised) on sampled (layer, expert);
+ * scale order: `.scale[e]` must be that expert's weight_scale_2;
+ * the dense policy: every tensor's type against the policy, and every non-PLE tensor name of the reference
+ layout present;
+ * the PLE table (with --ple-gguf): the engine will read another file's IQ4_NL table, which is only valid if it
+ is the same table. Sampled rows of it are compared with this checkpoint's FP8 rows by cosine similarity -
+ two quantizations of one table agree to ~0.99, different tables do not.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import pathlib
+import random
+import sys
+
+import numpy as np
+import torch
+from safetensors import safe_open
+
+LLAMA = pathlib.Path(__file__).resolve().parents[1] / "third_party" / "llama.cpp"
+sys.path.insert(0, str(LLAMA / "gguf-py"))
+from gguf import GGUFReader, GGMLQuantizationType as Q, quants # noqa: E402
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+from nvfp4_verify import modelopt_dequant # noqa: E402
+
+PROJ = {"gate": "gate_proj", "up": "up_proj", "down": "down_proj"}
+
+
+def tensor_map(reader: GGUFReader) -> dict:
+ return {t.name: t for t in reader.tensors}
+
+
+def check_experts(model: pathlib.Path, T: dict, samples: int, rng: random.Random) -> int:
+ index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
+ bad = 0
+ for _ in range(samples):
+ layer, expert, role = rng.randrange(48), rng.randrange(512), rng.choice(list(PROJ))
+ g = T["blk.%d.ffn_%s_exps.weight" % (layer, role)]
+ s = T["blk.%d.ffn_%s_exps.scale" % (layer, role)]
+ if g.tensor_type != Q.NVFP4:
+ print(" blk.%d.ffn_%s_exps is %s, not NVFP4" % (layer, role, g.tensor_type.name))
+ bad += 1
+ continue
+ raw = np.asarray(g.data).reshape(512, -1)[expert] # one expert's block_nvfp4 bytes
+ rows = int(g.shape[1]) # ggml shape: [cols, rows, experts]
+ cols = int(g.shape[0])
+ got = quants.dequantize(np.ascontiguousarray(raw), Q.NVFP4).reshape(rows, cols).astype(np.float32)
+ scale_file = float(np.asarray(s.data).reshape(-1)[expert])
+ src = "model.language_model.layers.%d.mlp.experts.%d.%s.weight" % (layer, expert, PROJ[role])
+ with safe_open(model / index[src], framework="pt") as f:
+ w = f.get_tensor(src)
+ sc = f.get_tensor(src.replace(".weight", ".weight_scale"))
+ s2 = f.get_tensor(src.replace(".weight", ".weight_scale_2"))
+ ref = modelopt_dequant(w, sc, s2)
+ got = got * np.float32(scale_file)
+ same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got + np.float32(0)).view(np.uint32))
+ scale_ok = scale_file == float(s2.float())
+ print(" blk.%-2d expert %-3d %-4s weights %s scale %s (%.6g)"
+ % (layer, expert, role, "bitwise" if same else "DIFFER ", "ok" if scale_ok else "WRONG", scale_file))
+ bad += (not same) + (not scale_ok)
+ return bad
+
+
+def check_policy(T: dict, reference: pathlib.Path | None) -> int:
+ bf16 = ("hc_attn_down", "hc_attn_up", "hc_attn_inject", "hc_ffn_down", "hc_ffn_up", "hc_ffn_inject",
+ "ssm_alpha", "ssm_beta", "indexer.q_proj", "indexer.k_proj", "ple_value", "ple_key",
+ "ffn_gate_inp", "ffn_gate_inp_shexp", "output_hc_down", "output_hc_up")
+ bad = 0
+ counts: dict[str, int] = {}
+ for name, t in T.items():
+ typ = t.tensor_type.name
+ counts[typ] = counts.get(typ, 0) + 1
+ stem = name.rsplit(".weight", 1)[0].split(".", 2)[-1] if name.startswith("blk.") else name.rsplit(".weight", 1)[0]
+ if name.endswith("_exps.weight") and typ != "NVFP4":
+ bad += 1; print(" policy: %s is %s" % (name, typ))
+ elif any(name.endswith(b + ".weight") for b in bf16) and typ != "BF16":
+ bad += 1; print(" policy: %s is %s, expected BF16" % (name, typ))
+ elif name in ("token_embd.weight", "output.weight") and typ != "Q8_0":
+ bad += 1; print(" policy: %s is %s, expected Q8_0" % (name, typ))
+ print(" types: " + ", ".join("%s x%d" % kv for kv in sorted(counts.items(), key=lambda kv: -kv[1])))
+ if reference and reference.exists():
+ want = {line.rsplit(":", 1)[0].strip() for line in reference.read_text(encoding="utf-8").splitlines()
+ if line and not line.startswith("#") and ":" in line}
+ missing = sorted(want - set(T))
+ extra = sorted(n for n in set(T) - want if not n.endswith((".scale", ".input_scale")))
+ print(" reference layout: %d names, missing here %d, unexpected here %d"
+ % (len(want), len(missing), len(extra)))
+ for n in (missing + extra)[:10]:
+ print(" ", "missing" if n in missing else "extra ", n)
+ bad += len(missing) + len(extra)
+ return bad
+
+
+def check_ple(model: pathlib.Path, ple: pathlib.Path, samples: int, rng: random.Random) -> int:
+ reader = GGUFReader(ple)
+ t = {x.name: x for x in reader.tensors}.get("per_layer_token_embd.weight")
+ if t is None:
+ print(" PLE: per_layer_token_embd.weight not in", ple.name)
+ return 1
+ width, rows = int(t.shape[0]), int(t.shape[1])
+ print(" PLE file: %s %s, %d rows x %d" % (ple.name, t.tensor_type.name, rows, width))
+ if t.tensor_type != Q.IQ4_NL:
+ print(" PLE: the engine reads IQ4_NL only")
+ return 1
+ table = np.asarray(t.data).reshape(rows, -1)
+ index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
+ shard_rows = 2500012
+ worst, sims = 1.0, []
+ for _ in range(samples):
+ r = rng.randrange(rows)
+ shard, off = divmod(r, shard_rows)
+ name = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_%d.weight" % shard
+ with safe_open(model / index[name], framework="pt") as f:
+ src = f.get_slice(name)[off:off + 1].float().numpy().reshape(-1)
+ sname = name.replace(".weight", ".weight_scale")
+ if sname in f.keys():
+ src = src * float(f.get_tensor(sname).float())
+ mine = quants.dequantize(np.ascontiguousarray(table[r]), Q.IQ4_NL).reshape(-1)
+ cos = float(np.dot(src, mine) / (np.linalg.norm(src) * np.linalg.norm(mine) + 1e-30))
+ sims.append(cos)
+ worst = min(worst, cos)
+ print(" PLE rows vs FP8 source: cosine mean %.4f, worst %.4f over %d random rows"
+ % (float(np.mean(sims)), worst, samples))
+ return 0 if worst > 0.95 else 1
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--gguf", required=True)
+ ap.add_argument("--ple-gguf")
+ ap.add_argument("--reference", help="an rco-allocation.txt listing the reference tensor names")
+ ap.add_argument("--samples", type=int, default=12)
+ a = ap.parse_args()
+ rng = random.Random(20260929)
+ model = pathlib.Path(a.model)
+ T = tensor_map(GGUFReader(a.gguf))
+ print("GGUF: %d tensors" % len(T))
+ print("experts, sampled:")
+ bad = check_experts(model, T, a.samples, rng)
+ print("dense policy:")
+ bad += check_policy(T, pathlib.Path(a.reference) if a.reference else None)
+ if a.ple_gguf:
+ print("PLE table:")
+ bad += check_ple(model, pathlib.Path(a.ple_gguf), 64, rng)
+ print("RESULT:", "OK" if bad == 0 else "%d problems" % bad)
+ return 1 if bad else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())