diff --git a/conversion/deepseek41.py b/conversion/deepseek41.py index 9a03b9912460..7dff63545069 100644 --- a/conversion/deepseek41.py +++ b/conversion/deepseek41.py @@ -147,6 +147,12 @@ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Call # num_hidden_layers lives in text_config, which is merged only after indexing; MTP stages are skipped anyway return TextModel.index_tensors(self, remote_hf_model_id=remote_hf_model_id) + def _has_fp8_source_scale(self, name: str) -> bool: + # DeepSeek-V4.1 stores FP8 E8M0 block scales as ".scale", + # not the generic ".weight_scale[_inv]" spelling. + return (name.removesuffix(".weight") + ".scale" in self.model_tensors + or super()._has_fp8_source_scale(name)) + def set_gguf_parameters(self): super().set_gguf_parameters() hp = self.hparams @@ -223,7 +229,7 @@ def chunks() -> Iterable[np.ndarray]: self.gguf_writer.add_tensor(self.format_tensor_name(key, bid), data, raw_dtype=gguf.GGMLQuantizationType.MXFP4) def _write_engram_tables(self, layer_ids: list[int]) -> None: - # official lookup e4m3 * 2^(e8m0 - 127), exact in BF16 + # Preserve native MXFP8 with --outtype auto; explicit output types dequantize. parts, dim = [], None for bid in layer_ids: wn, sn = f"layers.{bid}.engram.embed.weight", f"layers.{bid}.engram.embed.scale" @@ -237,6 +243,21 @@ def _write_engram_tables(self, layer_ids: list[int]) -> None: assert dim is not None name = self.format_tensor_name(gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD) n_rows = sum(p[2] for p in parts) + if self._preserve_fp8: + def blocks() -> Iterable[np.ndarray]: + from safetensors import safe_open + for wn, sn, rows, wpart, spart in parts: + with safe_open(wpart, framework="pt") as fw, safe_open(spart, framework="pt") as fs: + ws, ss = fw.get_slice(wn), fs.get_slice(sn) + for r0 in range(0, rows, 1 << 18): + q = ws[r0:r0 + (1 << 18)].view(torch.uint8).reshape(-1, 32).numpy() + e = ss[r0:r0 + (1 << 18)].view(torch.uint8).reshape(-1, 1).numpy() + if (e == 0xFF).any() or ((q & 0x7F) == 0x7F).any(): + raise ValueError(f"{wn}: NaN E8M0 scale or E4M3 code") + yield np.concatenate((e, q), axis=1) + data = cast(np.ndarray, _StreamedBytes((n_rows, dim // 32 * 33), blocks)) + self.gguf_writer.add_tensor(name, data, raw_dtype=gguf.GGMLQuantizationType.MXFP8) + return def chunks() -> Iterable[np.ndarray]: from safetensors import safe_open diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 4666b82d9b3e..cba868230362 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -260,7 +260,9 @@ extern "C" { GGML_TYPE_Q1_0 = 41, GGML_TYPE_Q2_0 = 42, GGML_TYPE_F8_E4M3 = 43, - GGML_TYPE_COUNT = 44, + // packed E8M0 scale + 32 E4M3 values (Engram GET_ROWS only). + GGML_TYPE_MXFP8 = 44, + GGML_TYPE_COUNT = 45, }; // [TAG_GGML_PREC] diff --git a/ggml/src/ggml-common.h b/ggml/src/ggml-common.h index 1dbbe326d0fc..7c34a0cf633a 100644 --- a/ggml/src/ggml-common.h +++ b/ggml/src/ggml-common.h @@ -217,6 +217,12 @@ typedef struct { uint8_t qs[QK_MXFP4/2]; } block_mxfp4; static_assert(sizeof(block_mxfp4) == sizeof(uint8_t) + QK_MXFP4/2, "wrong mxfp4 block size/padding"); +#define QK_MXFP8 32 +typedef struct { + uint8_t e; // E8M0 exponent shared by 32 OCP E4M3 values + uint8_t qs[QK_MXFP8]; +} block_mxfp8; +static_assert(sizeof(block_mxfp8) == 33, "wrong mxfp8 block size/padding"); #define QK_NVFP4 64 #define QK_NVFP4_SUB 16 // sub-block size for per-group scales diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index d01b6c11a905..6ba22e84c2a8 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -681,6 +681,7 @@ void ggml_compute_forward_add( case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_MXFP4: + case GGML_TYPE_MXFP8: case GGML_TYPE_NVFP4: case GGML_TYPE_F8_E4M3: case GGML_TYPE_Q2_K: @@ -1160,6 +1161,10 @@ void ggml_compute_forward_add1( { ggml_compute_forward_add1_q_f32(params, dst); } break; + case GGML_TYPE_MXFP8: + { + GGML_ABORT("ADD1 not supported for MXFP8"); + } break; default: { GGML_ABORT("fatal error"); @@ -1271,6 +1276,7 @@ void ggml_compute_forward_acc( case GGML_TYPE_Q8_0: case GGML_TYPE_Q8_1: case GGML_TYPE_MXFP4: + case GGML_TYPE_MXFP8: case GGML_TYPE_NVFP4: case GGML_TYPE_F8_E4M3: case GGML_TYPE_Q2_K: @@ -5011,6 +5017,7 @@ void ggml_compute_forward_out_prod( case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_MXFP4: + case GGML_TYPE_MXFP8: case GGML_TYPE_NVFP4: case GGML_TYPE_F8_E4M3: case GGML_TYPE_Q2_K: @@ -5342,6 +5349,7 @@ void ggml_compute_forward_set( case GGML_TYPE_Q8_0: case GGML_TYPE_Q8_1: case GGML_TYPE_MXFP4: + case GGML_TYPE_MXFP8: case GGML_TYPE_NVFP4: case GGML_TYPE_F8_E4M3: case GGML_TYPE_Q2_K: @@ -5568,6 +5576,7 @@ void ggml_compute_forward_get_rows( case GGML_TYPE_Q8_0: case GGML_TYPE_Q8_1: case GGML_TYPE_MXFP4: + case GGML_TYPE_MXFP8: case GGML_TYPE_NVFP4: case GGML_TYPE_F8_E4M3: case GGML_TYPE_Q2_K: @@ -6275,6 +6284,7 @@ void ggml_compute_forward_clamp( case GGML_TYPE_Q8_0: case GGML_TYPE_Q8_1: case GGML_TYPE_MXFP4: + case GGML_TYPE_MXFP8: case GGML_TYPE_NVFP4: case GGML_TYPE_F8_E4M3: case GGML_TYPE_Q2_K: diff --git a/ggml/src/ggml-cpu/quants.c b/ggml/src/ggml-cpu/quants.c index 44ea9fae55f1..afabe8c56922 100644 --- a/ggml/src/ggml-cpu/quants.c +++ b/ggml/src/ggml-cpu/quants.c @@ -59,6 +59,10 @@ void quantize_row_mxfp4(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, i quantize_row_mxfp4_ref(x, y, k); } +void quantize_row_mxfp8(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k) { + quantize_row_mxfp8_ref(x, y, k); +} + void quantize_row_nvfp4(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k) { quantize_row_nvfp4_ref(x, y, k); } diff --git a/ggml/src/ggml-cpu/quants.h b/ggml/src/ggml-cpu/quants.h index f04be52f54af..9a86da90b26b 100644 --- a/ggml/src/ggml-cpu/quants.h +++ b/ggml/src/ggml-cpu/quants.h @@ -22,6 +22,7 @@ void quantize_row_q8_0(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, in void quantize_row_q8_1(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k); void quantize_row_mxfp4(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k); +void quantize_row_mxfp8(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k); void quantize_row_nvfp4(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k); void quantize_row_f8_e4m3(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k); diff --git a/ggml/src/ggml-cuda/dequantize.cuh b/ggml/src/ggml-cuda/dequantize.cuh index 651524be7b3e..b2b4eee3af38 100644 --- a/ggml/src/ggml-cuda/dequantize.cuh +++ b/ggml/src/ggml-cuda/dequantize.cuh @@ -1,6 +1,15 @@ #include "common.cuh" #include "convert.cuh" +// Gather-only MXFP8 Engram block: E8M0 scale, then 32 E4M3 values. +static __device__ __forceinline__ void dequantize_mxfp8( + const void * vx, const int64_t ib, const int iqs, float2 & v) { + const block_mxfp8 * x = (const block_mxfp8 *) vx; + const float scale = x[ib].e == 0xFF ? NAN : ggml_cuda_e8m0_to_fp32(x[ib].e); + v.x = ggml_cuda_f8_e4m3_to_fp32(x[ib].qs[iqs ]) * scale; + v.y = ggml_cuda_f8_e4m3_to_fp32(x[ib].qs[iqs + 1]) * scale; +} + static __device__ __forceinline__ void dequantize_q1_0(const void * vx, const int64_t ib, const int iqs, float2 & v){ const block_q1_0 * x = (const block_q1_0 *) vx; diff --git a/ggml/src/ggml-cuda/getrows.cu b/ggml/src/ggml-cuda/getrows.cu index 09b7f02b8f85..06bc2232e3a4 100644 --- a/ggml/src/ggml-cuda/getrows.cu +++ b/ggml/src/ggml-cuda/getrows.cu @@ -408,6 +408,10 @@ static void ggml_cuda_get_rows_switch_src0_type( get_rows_cuda_kq<32, dst_t, dequantize_mxfp4>(src0_d, src1_d, dst_d, ne00, nb01, nb02, nb03, ne10, ne11, ne12, nb10, nb11, nb12, nb1, nb2, nb3, stream); break; + case GGML_TYPE_MXFP8: + get_rows_cuda_q(src0_d, src1_d, dst_d, + ne00, nb01, nb02, nb03, ne10, ne11, ne12, nb10, nb11, nb12, nb1, nb2, nb3, stream); + break; default: GGML_ABORT("%s: unsupported src0 type: %s\n", __func__, ggml_type_name(src0_type)); } diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 8bae60133311..3125e1a25968 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -4305,6 +4305,7 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_F8_E4M3: + case GGML_TYPE_MXFP8: case GGML_TYPE_Q2_K: case GGML_TYPE_Q3_K: case GGML_TYPE_Q4_K: diff --git a/ggml/src/ggml-quants.c b/ggml/src/ggml-quants.c index 40ffe1e6bfda..e3d604b3a32f 100644 --- a/ggml/src/ggml-quants.c +++ b/ggml/src/ggml-quants.c @@ -344,6 +344,34 @@ static inline int best_index_mxfp4(float x, float e) { return best_index; } +// Reference encoder for a 32-value OCP MXFP8 block (E8M0 + 32 E4M3). +void quantize_row_mxfp8_ref(const float * GGML_RESTRICT x, block_mxfp8 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK_MXFP8; + + assert(k % qk == 0); + + const int64_t nb = k / qk; + for (int64_t i = 0; i < nb; i++) { + float amax = 0.0f; + for (int j = 0; j < qk; j++) { + amax = MAX(amax, fabsf(x[i*qk + j])); + } + // Smallest power-of-two scale with amax / scale <= 448 (largest finite E4M3). + int e = 0; + if (amax > 0.0f) { + e = (int) ceilf(log2f(amax / 448.0f)) + 127; + e = MAX(0, MIN(254, e)); + } + const float d = GGML_E8M0_TO_FP32((uint8_t) e); + const float id = 1.0f/d; + + y[i].e = (uint8_t) e; + for (int j = 0; j < qk; ++j) { + // Upstream's E4M3 encoder replaces the equivalent fork-local helper. + y[i].qs[j] = ggml_fp32_to_f8_e4m3(x[i*qk + j]*id); + } + } +} void quantize_row_mxfp4_ref(const float * GGML_RESTRICT x, block_mxfp4 * GGML_RESTRICT y, int64_t k) { static const int qk = QK_MXFP4; @@ -589,6 +617,17 @@ void dequantize_row_mxfp4(const block_mxfp4 * GGML_RESTRICT x, float * GGML_REST } } +// MXFP8 stores one E8M0 scale followed by 32 OCP E4M3 bytes per block. +// Unlike MXFP4, the E4M3 values are *not* stored doubled. +void dequantize_row_mxfp8(const block_mxfp8 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_MXFP8 == 0); + for (int64_t i = 0; i < k / QK_MXFP8; ++i) { + const float scale = x[i].e == 0xFF ? NAN : GGML_E8M0_TO_FP32(x[i].e); + for (int j = 0; j < QK_MXFP8; ++j) { + y[i*QK_MXFP8 + j] = ggml_f8_e4m3_to_fp32(x[i].qs[j]) * scale; + } + } +} void dequantize_row_nvfp4(const block_nvfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { static const int qk = QK_NVFP4; static const int qk_sub = QK_NVFP4_SUB; @@ -2315,6 +2354,12 @@ size_t quantize_mxfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, return nrow * ggml_row_size(GGML_TYPE_MXFP4, n_per_row); } +size_t quantize_mxfp8(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_UNUSED(quant_weights); + quantize_row_mxfp8_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_MXFP8, n_per_row); +} + size_t quantize_nvfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { GGML_UNUSED(quant_weights); quantize_row_nvfp4_ref(src, dst, (int64_t)nrow*n_per_row); @@ -5491,6 +5536,20 @@ static bool validate_e_e8m0(uint8_t e, size_t i) { } \ } +#define VALIDATE_ROW_DATA_MXFP8_IMPL(type, data, nb) \ + const type * q = (const type *) (data); \ + for (size_t i = 0; i < (nb); ++i) { \ + if (!validate_e_e8m0(q[i].e, i)) { \ + return false; \ + } \ + for (int j = 0; j < QK_MXFP8; ++j) { \ + if ((q[i].qs[j] & 0x7f) == 0x7f) { \ + fprintf(stderr, "%s: found NaN E4M3 code at block %zu, element %d\n", __func__, i, j); \ + return false; \ + } \ + } \ + } + #define VALIDATE_ROW_DATA_DVEC_F16_IMPL(type, data, nb, nr) \ const type * q = (const type *) (data); \ for (size_t i = 0; i < (nb); ++i) { \ @@ -5656,6 +5715,10 @@ bool ggml_validate_row_data(enum ggml_type type, const void * data, size_t nbyte { VALIDATE_ROW_DATA_E_E8M0_IMPL(block_mxfp4, data, nb); } break; + case GGML_TYPE_MXFP8: + { + VALIDATE_ROW_DATA_MXFP8_IMPL(block_mxfp8, data, nb); + } break; case GGML_TYPE_NVFP4: { // TODO: validate each unsigned E4M3 scale; NaN encodings and scales with the sign bit set are invalid. diff --git a/ggml/src/ggml-quants.h b/ggml/src/ggml-quants.h index ca36d13695c8..bf140b10bfaa 100644 --- a/ggml/src/ggml-quants.h +++ b/ggml/src/ggml-quants.h @@ -24,6 +24,7 @@ GGML_API void quantize_row_q8_0_ref(const float * GGML_RESTRICT x, block_q8_0 * GGML_API void quantize_row_q8_1_ref(const float * GGML_RESTRICT x, block_q8_1 * GGML_RESTRICT y, int64_t k); GGML_API void quantize_row_mxfp4_ref(const float * GGML_RESTRICT x, block_mxfp4 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_mxfp8_ref(const float * GGML_RESTRICT x, block_mxfp8 * GGML_RESTRICT y, int64_t k); GGML_API void quantize_row_nvfp4_ref(const float * GGML_RESTRICT x, block_nvfp4 * GGML_RESTRICT y, int64_t k); GGML_API void quantize_row_f8_e4m3_ref(const float * GGML_RESTRICT x, ggml_fp8_e4m3_t * GGML_RESTRICT y, int64_t k); @@ -54,6 +55,7 @@ GGML_API void dequantize_row_q8_0(const block_q8_0 * GGML_RESTRICT x, float * GG //GGML_API void dequantize_row_q8_1(const block_q8_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); GGML_API void dequantize_row_mxfp4(const block_mxfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_mxfp8(const block_mxfp8 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); GGML_API void dequantize_row_nvfp4(const block_nvfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); GGML_API void dequantize_row_f8_e4m3(const ggml_fp8_e4m3_t * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); @@ -105,6 +107,7 @@ GGML_API size_t quantize_q5_1(const float * GGML_RESTRICT src, void * GGML_RESTR GGML_API size_t quantize_q8_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); GGML_API size_t quantize_mxfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_mxfp8(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); GGML_API size_t quantize_nvfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); GGML_API size_t quantize_f8_e4m3(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 7da6637bdef6..4a1bc816e4be 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -766,6 +766,14 @@ static const struct ggml_type_traits type_traits[GGML_TYPE_COUNT] = { .to_float = (ggml_to_float_t) dequantize_row_mxfp4, .from_float_ref = (ggml_from_float_t)quantize_row_mxfp4_ref, }, + [GGML_TYPE_MXFP8] = { + .type_name = "mxfp8", + .blck_size = QK_MXFP8, + .type_size = sizeof(block_mxfp8), + .is_quantized = true, + .to_float = (ggml_to_float_t) dequantize_row_mxfp8, + .from_float_ref = (ggml_from_float_t) quantize_row_mxfp8_ref, + }, [GGML_TYPE_NVFP4] = { .type_name = "nvfp4", .blck_size = QK_NVFP4, @@ -8290,6 +8298,7 @@ size_t ggml_quantize_chunk( case GGML_TYPE_Q5_1: result = quantize_q5_1 (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; case GGML_TYPE_Q8_0: result = quantize_q8_0 (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; case GGML_TYPE_MXFP4: result = quantize_mxfp4 (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; + case GGML_TYPE_MXFP8: result = quantize_mxfp8 (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; case GGML_TYPE_NVFP4: result = quantize_nvfp4 (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; case GGML_TYPE_F8_E4M3: result = quantize_f8_e4m3(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; case GGML_TYPE_Q2_K: result = quantize_q2_K (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break; diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 347378e612fa..3dea3a0789ef 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -7511,6 +7511,7 @@ class GGMLQuantizationType(IntEnum): Q1_0 = 41 Q2_0 = 42 F8_E4M3 = 43 + MXFP8 = 44 class ExpertGatingFuncType(IntEnum): @@ -7762,6 +7763,7 @@ class VisionProjectorType: GGMLQuantizationType.Q1_0: (128, 2 + 16), GGMLQuantizationType.Q2_0: (64, 2 + 16), GGMLQuantizationType.F8_E4M3: (1, 1), + GGMLQuantizationType.MXFP8: (32, 33), } diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 38eb0d588ba8..0b344d6c7511 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -287,6 +287,8 @@ static void llama_tensor_dequantize_impl(ggml_type type, // do we allow this tensor to be quantized? static bool tensor_allows_quantization(const llama_model_quantize_params * params, llm_arch arch, const ggml_tensor * tensor) { if (params->only_copy) { return false; } + // Preserve the original MXFP8 Engram bytes, despite the reference encoder. + if (tensor->type == GGML_TYPE_MXFP8) { return false; } // quantize only 2D+ tensors (matrices, experts, conv kernels) if (ggml_n_dims(tensor) < 2) { return false; } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 0d0d020feec0..68c77072e9db 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -12313,6 +12313,15 @@ static std::vector> make_test_cases_eval() { for (int n : {1, 3, 257}) { test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, n, 5, 3, 1, 1, false)); } + // MXFP8 is used for packed Engram lookup tables (GET_ROWS only, no MUL_MAT). + // Exercise single/multiple blocks, batched indices, and a view of the indices. + for (int n : {32, 64, 160}) { + test_cases.emplace_back(new test_get_rows(GGML_TYPE_MXFP8, n, 13, 7, 1, 1, false)); + test_cases.emplace_back(new test_get_rows(GGML_TYPE_MXFP8, n, 13, 7, 2, 1, true)); + } + for (int r : {1, 128}) { + test_cases.emplace_back(new test_get_rows(GGML_TYPE_MXFP8, 160, 4096, r, 1, 1, false)); + } // many rows of a wide table, as a per-layer embedding lookup does test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, 160, 100000, 32768, 1, 1, false)); // past the fused dequant GEMM's column limit the reordered weight goes through the conversion kernels diff --git a/tests/test-quantize-fns.cpp b/tests/test-quantize-fns.cpp index 1542ab656878..fb4ca7656769 100644 --- a/tests/test-quantize-fns.cpp +++ b/tests/test-quantize-fns.cpp @@ -302,6 +302,100 @@ static int test_f8_e4m3(bool verbose) { return num_failed; } +static int test_mxfp8(bool verbose) { + const auto * traits = ggml_get_type_traits(GGML_TYPE_MXFP8); + int num_failed = 0; + + // MXFP8 is 32 E4M3 values plus one E8M0 scale byte, not scalar F8_E4M3. + const bool traits_failed = traits->blck_size != 32 || traits->type_size != 33 || + !traits->is_quantized || !traits->to_float || !traits->from_float_ref || + ggml_row_size(GGML_TYPE_MXFP8, 64) != 66; + num_failed += traits_failed; + if (verbose || traits_failed) { + printf("mxfp8 type traits: %s\n", RESULT_STR[traits_failed]); + } + if (traits_failed) { + return num_failed; + } + + // Reject invalid scales and E4M3 NaN encodings in native packed blocks. + std::vector valid(2 * 33, 0); + valid[0] = 127; + valid[33] = 128; + bool validation_failed = !ggml_validate_row_data(GGML_TYPE_MXFP8, valid.data(), valid.size()); + valid[0] = 0xff; + validation_failed |= ggml_validate_row_data(GGML_TYPE_MXFP8, valid.data(), valid.size()); + valid[0] = 127; + valid[1] = 0x7f; + validation_failed |= ggml_validate_row_data(GGML_TYPE_MXFP8, valid.data(), valid.size()); + valid[1] = 0xff; + validation_failed |= ggml_validate_row_data(GGML_TYPE_MXFP8, valid.data(), valid.size()); + num_failed += validation_failed; + if (verbose || validation_failed) { + printf("mxfp8 row validation: %s\n", RESULT_STR[validation_failed]); + } + + // Known OCP E4M3 codes, both signs, two different block scales, signed zero. + std::vector packed(4 * 33, 0); + packed[ 0] = 127; // scale = 1 + packed[ 1] = 0x38; // +1 + packed[ 2] = 0xb8; // -1 + packed[ 3] = 0x7e; // +448 + packed[ 4] = 0xfe; // -448 + packed[ 5] = 0x80; // -0 + packed[33] = 128; // scale = 2 + packed[34] = 0x38; // +2 after scaling + packed[35] = 0xc0; // -4 after scaling + packed[66] = 0xff; // reserved E8M0 NaN scale + packed[67] = 0x38; + packed[99] = 127; + packed[100] = 0x7f; // E4M3 NaN code + + std::vector decoded(4 * 32); + traits->to_float(packed.data(), decoded.data(), decoded.size()); + const bool decode_failed = decoded[0] != 1.0f || decoded[1] != -1.0f || + decoded[2] != 448.0f || decoded[3] != -448.0f || + decoded[4] != 0.0f || !std::signbit(decoded[4]) || + decoded[32] != 2.0f || decoded[33] != -4.0f || + !std::isnan(decoded[64]) || !std::isnan(decoded[65]) || + !std::isnan(decoded[96]); + num_failed += decode_failed; + if (verbose || decode_failed) { + printf("mxfp8 known-code decode: %s\n", RESULT_STR[decode_failed]); + } + + // Reference encoder: each 32-value block chooses its own E8M0 scale. + std::vector input(3 * 32, 0.0f); + input[ 0] = 448.0f; + input[ 1] = -448.0f; + input[ 2] = 1.0f; + input[32] = 896.0f; + input[33] = -896.0f; + input[34] = 2.0f; + std::vector quantized(3 * 33); + traits->from_float_ref(input.data(), quantized.data(), input.size()); + std::vector roundtrip(input.size()); + traits->to_float(quantized.data(), roundtrip.data(), roundtrip.size()); + const bool roundtrip_failed = quantized[0] != 127 || quantized[33] != 128 || quantized[66] != 0 || + quantized[1] != 0x7e || quantized[2] != 0xfe || + quantized[34] != 0x7e || quantized[35] != 0xfe || + !std::equal(input.begin(), input.end(), roundtrip.begin()); + num_failed += roundtrip_failed; + if (verbose || roundtrip_failed) { + printf("mxfp8 reference roundtrip: %s\n", RESULT_STR[roundtrip_failed]); + } + + // Exercise ggml_quantize_chunk, also used by backend-op test tensor initialization. + std::vector chunk(quantized.size()); + const size_t nbytes = ggml_quantize_chunk(GGML_TYPE_MXFP8, input.data(), chunk.data(), 0, 3, 32, nullptr); + const bool chunk_failed = nbytes != quantized.size() || chunk != quantized; + num_failed += chunk_failed; + if (verbose || chunk_failed) { + printf("mxfp8 quantize_chunk: %s\n", RESULT_STR[chunk_failed]); + } + return num_failed; +} + static int test_vec_dot_q(bool verbose) { int num_failed = 0; @@ -447,6 +541,7 @@ int main(int argc, char * argv[]) { num_failed += test_vec_dot_f32(verbose); num_failed += test_f8_e4m3(verbose); + num_failed += test_mxfp8(verbose); num_failed += test_vec_dot_q(verbose); num_failed += test_quantize_imatrix_degenerate(verbose); diff --git a/tests/test_conversion_fp8.py b/tests/test_conversion_fp8.py index ffc5f6966795..f821b15f23ed 100644 --- a/tests/test_conversion_fp8.py +++ b/tests/test_conversion_fp8.py @@ -21,6 +21,7 @@ from conversion.base import LazyTorchTensor, gguf from conversion.deepseek import DeepseekV2Model +from conversion.deepseek41 import DeepseekV41Model from conversion.inkling2 import Inkling2Model, _E4M3, _E2M1 from conversion.llama import LlamaModel from conversion.nemotron import NemotronHModel @@ -588,6 +589,143 @@ def test_fp8_writes_expert_unit_scales(self): self.assertNotIn(f"blk.0.ffn_{proj}_exps.input_scale", result) +class TestDeepseekV41Mxfp8Conversion(unittest.TestCase): + """Tiny on-disk Engram checkpoints; exercise the real V4.1 writer, not a mock.""" + + @staticmethod + def checkpoint(): + tensors = {"embed.weight": torch.zeros((2, 64), dtype=torch.bfloat16)} + for bid, rows in ((0, 2), (2, 1)): + # Distinct finite E4M3 codes across both 32-element blocks. + codes = ((torch.arange(rows * 64).reshape(rows, 64) * 13 + bid + 3) % 256).to(torch.uint8) + codes[(codes & 0x7f) == 0x7f] = 0x7e + tensors[f"layers.{bid}.engram.embed.weight"] = codes.view(torch.float8_e4m3fn) + tensors[f"layers.{bid}.engram.embed.scale"] = torch.tensor( + [[125 + bid, 127] for _ in range(rows)], dtype=torch.uint8) + return tensors + + def model(self, path, tensors, ftype=gguf.LlamaFileType.GUESSED, **kwargs): + hparams = { + "model_type": "deepseek_v41", + "architectures": ["DeepseekV41ForCausalLM"], + "num_hidden_layers": 3, + "hidden_size": 64, + "num_attention_heads": 1, + "engram_num_embeddings": [2, 1], + "quantization_config": {"weight_block_size": [32, 32], "scale_fmt": "ue8m0"}, + } + (path / "config.json").write_text(json.dumps(hparams)) + save_file(tensors, str(path / "model.safetensors")) + return DeepseekV41Model(path, ftype, path / "out.gguf", hparams=hparams, **kwargs) + + @staticmethod + def packed_bytes(tensors): + parts = [] + for bid in (0, 2): + q = tensors[f"layers.{bid}.engram.embed.weight"].view(torch.uint8).numpy().reshape(-1, 32) + e = tensors[f"layers.{bid}.engram.embed.scale"].numpy().reshape(-1, 1) + parts.append(np.concatenate((e, q), axis=1)) + return np.concatenate(parts).tobytes() + + @staticmethod + def dequant_bytes(tensors, ftype): + parts = [] + for bid in (0, 2): + q = tensors[f"layers.{bid}.engram.embed.weight"].float() + e = tensors[f"layers.{bid}.engram.embed.scale"].float() + values = q * torch.exp2(e - 127).repeat_interleave(32, dim=1) + if ftype == gguf.GGMLQuantizationType.BF16: + values = values.bfloat16() + parts.append(values.view(torch.uint8).numpy().tobytes()) + return b"".join(parts) + + def write_table(self, model, path): + model._write_engram_tables([0, 2]) + info = model.gguf_writer.tensors[0]["per_layer_token_embd.weight"] + with (path / "engram.bin").open("wb") as fout: + info.tensor.tofile(fout) + raw = (path / "engram.bin").read_bytes() + self.assertEqual(len(raw), info.nbytes) + return info, raw + + def test_auto_keeps_mxfp8_bytes_and_tensor_shape(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + tensors = self.checkpoint() + model = self.model(path, tensors) + # AUTO may resolve to BF16 from ordinary weights, but still preserves packed FP8. + self.assertEqual(model.ftype, gguf.LlamaFileType.MOSTLY_BF16) + self.assertTrue(model._preserve_fp8) + info, raw = self.write_table(model, path) + self.assertEqual(info.dtype, gguf.GGMLQuantizationType.MXFP8) + self.assertEqual(tuple(info.shape), (3, 64)) + self.assertEqual(info.nbytes, 3 * 2 * 33) + self.assertEqual(raw, self.packed_bytes(tensors)) + + def test_explicit_types_decode_instead_of_preserving(self): + for ftype, qtype in ( + (gguf.LlamaFileType.MOSTLY_BF16, gguf.GGMLQuantizationType.BF16), + (gguf.LlamaFileType.ALL_F32, gguf.GGMLQuantizationType.F32), + ): + with self.subTest(ftype=ftype), tempfile.TemporaryDirectory() as directory: + path = Path(directory) + tensors = self.checkpoint() + model = self.model(path, tensors, ftype=ftype) + self.assertFalse(model._preserve_fp8) + info, raw = self.write_table(model, path) + self.assertEqual(info.dtype, qtype) + self.assertEqual(tuple(info.shape), (3, 64)) + self.assertEqual(raw, self.dequant_bytes(tensors, qtype)) + + def test_fp8_as_q8_disables_passthrough(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + tensors = self.checkpoint() + model = self.model(path, tensors, fp8_as_q8=True) + self.assertFalse(model._preserve_fp8) + info, raw = self.write_table(model, path) + self.assertEqual(info.dtype, gguf.GGMLQuantizationType.BF16) + self.assertEqual(raw, self.dequant_bytes(tensors, info.dtype)) + + def test_rejects_invalid_mxfp8_bytes(self): + for field, code in (("scale", 0xff), ("weight", 0x7f), ("weight", 0xff)): + with self.subTest(field=field, code=code), tempfile.TemporaryDirectory() as directory: + path = Path(directory) + tensors = self.checkpoint() + name = f"layers.0.engram.embed.{field}" + if field == "weight": + raw = tensors[name].view(torch.uint8).clone() + raw[0, 0] = code + tensors[name] = raw.view(torch.float8_e4m3fn) + else: + tensors[name] = tensors[name].clone() + tensors[name][0, 0] = code + model = self.model(path, tensors) + with self.assertRaisesRegex(ValueError, "NaN E8M0 scale or E4M3 code"): + self.write_table(model, path) + + def test_rejects_incorrect_scale_shape(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + tensors = self.checkpoint() + tensors["layers.0.engram.embed.scale"] = torch.ones((2, 1), dtype=torch.uint8) + model = self.model(path, tensors) + with self.assertRaisesRegex(ValueError, "one e8m0 scale per 32 elements"): + model._write_engram_tables([0, 2]) + + def test_deepseek_dot_scale_name_is_recognized(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + tensors = self.checkpoint() + name = "layers.0.attn.wkv.weight" + tensors[name] = torch.ones((4, 64)).to(torch.float8_e4m3fn) + tensors["layers.0.attn.wkv.scale"] = torch.full((1, 2), 127, dtype=torch.uint8) + model = self.model(path, tensors) + self.assertTrue(model._has_fp8_source_scale(name)) + del model.model_tensors["layers.0.attn.wkv.scale"] + self.assertFalse(model._has_fp8_source_scale(name)) + + class TestInkling2PackedConversion(unittest.TestCase): """Conversion of the packed Inkling2 expert weights (see _dequant_expert_chunk in conversion/inkling2.py).