Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio MLX images: convert Q4_K / Q5_K / Q6_K and Q5_0 / Q5_1 GGUFs (#14794)
Daniel Han5186735e9d77
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.pyindex f773861ed9f..663415dc53c 100644--- a/studio/backend/core/inference/diffusion_engine_router.py+++ b/studio/backend/core/inference/diffusion_engine_router.py@@ -26,8 +26,9 @@ Env knobs:The MLX engine (``mlx_diffusion_backend``) is considered only when UNSLOTH_DIFFUSION_MLX=1, on macOS 14+ onApple Silicon, for a GGUF of a family that declares ``mlx_model_config`` in a quant the converter handles-(Q4_0 / Q4_1 / Q8_0 / BF16 / F16), with ``mlx`` and ``mflux`` installed. Every refusal is recorded-(``mlx_fallback_reason`` in the status) and falls through to the choice this module makes without it.+(Q4_0 / Q4_1 / Q5_0 / Q5_1 / Q8_0, the Q4_K / Q5_K / Q6_K mixes, BF16 / F16), with ``mlx`` and ``mflux`` installed.+Every refusal is recorded (``mlx_fallback_reason`` in the status) and falls through to the choice this module makes+without it."""from __future__ import annotationsdiff --git a/studio/backend/core/inference/mlx_diffusion_convert.py b/studio/backend/core/inference/mlx_diffusion_convert.pyindex a95097f8907..cf85584483b 100644--- a/studio/backend/core/inference/mlx_diffusion_convert.py+++ b/studio/backend/core/inference/mlx_diffusion_convert.py@@ -5,7 +5,11 @@Q4_0 / Q4_1 / Q8_0 map exactly onto MLX affine group-32 (dequant = q * scale + bias):Q4_0: scale d, bias -8d; Q4_1: scale d, bias m; Q8_0: q = qs + 128, scale d, bias -128d.-K-quants are refused (not converted yet): their per-sub-block scale products do not round-trip exactly through MLX's 16-bit group scales, and Q6_K uses 16-element groups.+Q5_0 / Q5_1 likewise onto 5-bit (Q5_0: bias -16d; Q5_1: bias m), the fifth bit coming from the block's qh word.+Q4_K / Q5_K keep their codes too: each 32-wide sub-block is affine with scale d * sc and bias -dmin * m, so they land+on MLX 4 / 5-bit group-32; only the scale product is rounded to the 16-bit scale dtype, as the d of Q4_0 already is.+Q6_K uses 16-wide groups, which MLX does not have: its exact dequantized values are re-quantized to 8-bit group-32,+whose step is at most a quarter of Q6_K's own. Q2_K / Q3_K (16-wide, 2-3 bits) are refused."""from __future__ import annotations@@ -26,11 +30,51 @@ GROUP_SIZE = 32OUTPUT_FILENAME = "0.safetensors"MARKER_FILENAME = "unsloth_mlx_convert.json"-CONVERTIBLE_TYPES = frozenset({"Q4_0", "Q4_1", "Q8_0", "BF16", "F16", "F32"})-CONVERTIBLE_QUANT_TOKENS = frozenset({"Q4_0", "Q4_1", "Q8_0", "BF16", "F16", "F32"})--_BLOCK_BYTES = {"Q4_0": 18, "Q4_1": 20, "Q8_0": 34}-_BLOCK_BITS = {"Q4_0": 4, "Q4_1": 4, "Q8_0": 8}+CONVERTIBLE_TYPES = frozenset(+ {"Q4_0", "Q4_1", "Q5_0", "Q5_1", "Q8_0", "Q4_K", "Q5_K", "Q6_K", "BF16", "F16", "F32"}+)+# File-name tokens whose mixes hold only the types above (a Q4_K_M also carries Q5_K / Q6_K, a Q5_K_M Q6_K).+CONVERTIBLE_QUANT_TOKENS = frozenset(+ {+ "Q4_0",+ "Q4_1",+ "Q5_0",+ "Q5_1",+ "Q8_0",+ "Q4_K_S",+ "Q4_K_M",+ "Q5_K_S",+ "Q5_K_M",+ "Q6_K",+ "BF16",+ "F16",+ "F32",+ }+)+_SUPPORTED_NAMES = "Q4_0/Q4_1/Q5_0/Q5_1/Q8_0/Q4_K/Q5_K/Q6_K/BF16"++_BLOCK_BYTES = {+ "Q4_0": 18,+ "Q4_1": 20,+ "Q5_0": 22,+ "Q5_1": 24,+ "Q8_0": 34,+ "Q4_K": 144,+ "Q5_K": 176,+ "Q6_K": 210,+}+# Bits of the MLX layer each block type becomes.+_BLOCK_BITS = {+ "Q4_0": 4,+ "Q4_1": 4,+ "Q5_0": 5,+ "Q5_1": 5,+ "Q8_0": 8,+ "Q4_K": 4,+ "Q5_K": 5,+ "Q6_K": 8,+}+_QK_K = 256_DENSE_TYPES = frozenset({"BF16", "F16", "F32"})_PAD_TOKENS = ("cap_pad_token", "x_pad_token")_QKV_PARTS = ("to_q", "to_k", "to_v")@@ -62,41 +106,63 @@ def quant_convertible(gguf_filename: Optional[str]) -> tuple[bool, Optional[str]if not gguf_filename:return (False,- "GGUF quant unknown (no GGUF filename); the MLX engine needs Q4_0/Q4_1/Q8_0/BF16",+ f"GGUF quant unknown (no GGUF filename); the MLX engine needs {_SUPPORTED_NAMES}",)token = _quant_token(str(gguf_filename))if not token:return False, (f"GGUF quant unknown for {Path(str(gguf_filename)).name!r}; the MLX engine needs "- "Q4_0/Q4_1/Q8_0/BF16"+ f"{_SUPPORTED_NAMES}")upper = str(token).upper()+ if upper.startswith("UD-"):+ upper = upper[3:]if upper in CONVERTIBLE_QUANT_TOKENS:return True, None- return False, (f"GGUF quant {token} is not convertible to MLX yet (only Q4_0/Q4_1/Q8_0/BF16)")+ return False, (f"GGUF quant {token} is not convertible to MLX yet (only {_SUPPORTED_NAMES})")# ── Block math ──────────────────────────────────────────────────────────────────────────────────+_ROW_CHUNK = 256++def _pack(q: np.ndarray, bits: int) -> np.ndarray:- """(R, C) integers in [0, 2**bits) -> (R, C * bits / 32) uint32, element i at bits*(i % per_word)."""- per_word = 32 // bits+ """(R, C) integers in [0, 2**bits) -> (R, C * bits / 32) uint32: MLX's layout, a little-endian bit stream per row+ (for 4 and 8 bits, element i at bits * (i % per_word) of word i // per_word)."""rows, cols = q.shape- if cols % per_word:+ if (cols * bits) % 32:raise ValueError(f"{cols} columns do not pack into {bits}-bit words")- q = q.reshape(rows, cols // per_word, per_word).astype(np.uint32)- shifts = (bits * np.arange(per_word, dtype = np.uint32)).astype(np.uint32)- return np.bitwise_or.reduce(q << shifts, axis = -1).astype(np.uint32)+ if 32 % bits == 0:+ per_word = 32 // bits+ q = q.reshape(rows, cols // per_word, per_word).astype(np.uint32)+ shifts = (bits * np.arange(per_word, dtype = np.uint32)).astype(np.uint32)+ return np.bitwise_or.reduce(q << shifts, axis = -1).astype(np.uint32)+ out = np.empty((rows, cols * bits // 32), dtype = np.uint32)+ shifts = np.arange(bits, dtype = np.uint8)+ for start in range(0, rows, _ROW_CHUNK):+ chunk = np.asarray(q[start : start + _ROW_CHUNK]).astype(np.uint8)+ stream = ((chunk[..., None] >> shifts) & 1).reshape(chunk.shape[0], -1)+ packed = np.packbits(stream, axis = -1, bitorder = "little")+ out[start : start + _ROW_CHUNK] = np.ascontiguousarray(packed).view("<u4")+ return outdef _unpack(packed: np.ndarray, bits: int) -> np.ndarray:- per_word = 32 // bitsrows, words = packed.shape- shifts = (bits * np.arange(per_word, dtype = np.uint32)).astype(np.uint32)- mask = np.uint32((1 << bits) - 1)- q = (packed.astype(np.uint32)[..., None] >> shifts) & mask- return q.reshape(rows, words * per_word)+ if 32 % bits == 0:+ per_word = 32 // bits+ shifts = (bits * np.arange(per_word, dtype = np.uint32)).astype(np.uint32)+ mask = np.uint32((1 << bits) - 1)+ q = (packed.astype(np.uint32)[..., None] >> shifts) & mask+ return q.reshape(rows, words * per_word)+ stream = np.unpackbits(+ np.ascontiguousarray(packed.astype("<u4")).view(np.uint8), axis = -1, bitorder = "little"+ )+ cols = words * 32 // bits+ weights = (1 << np.arange(bits, dtype = np.uint32)).astype(np.uint32)+ return (stream.reshape(rows, cols, bits).astype(np.uint32) * weights).sum(axis = -1)def _f16_field(blocks: np.ndarray, start: int) -> np.ndarray:@@ -106,10 +172,12 @@ def _f16_field(blocks: np.ndarray, start: int) -> np.ndarray:def affine_from_ggml(kind: str, raw: np.ndarray, rows: int, cols: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]:- """Q4_0 / Q4_1 / Q8_0 block bytes -> (packed uint32, scales f32, biases f32, bits), MLX affine g32."""+ """GGUF block bytes -> (packed uint32, scales f32, biases f32, bits), MLX affine g32 (see the module docstring)."""kind = str(kind).upper()if kind not in _BLOCK_BYTES:raise UnsupportedGGUFError(f"{kind} blocks have no exact MLX affine mapping")+ if kind in _KQUANT_TYPES:+ return _affine_from_kquant(kind, raw, rows, cols)if cols % GROUP_SIZE:raise ValueError(f"{cols} columns are not a whole number of {GROUP_SIZE}-wide blocks")nb = cols // GROUP_SIZE@@ -129,11 +197,68 @@ def affine_from_ggml(qs = blocks[..., 4:]q = np.concatenate([qs & 0xF, qs >> 4], axis = -1).reshape(rows, cols)return _pack(q, 4), d, m, 4+ if kind in ("Q5_0", "Q5_1"):+ d = _f16_field(blocks, 0)+ start = 2 if kind == "Q5_0" else 4+ qh = blocks[..., start : start + 4].copy().view("<u4")+ qs = blocks[..., start + 4 :]+ hi = ((qh >> np.arange(32, dtype = np.uint32)) & 1).astype(np.uint8)+ q = np.concatenate([qs & 0xF, qs >> 4], axis = -1) | (hi << 4)+ bias = -16.0 * d if kind == "Q5_0" else _f16_field(blocks, 2)+ return _pack(q.reshape(rows, cols), 5), d, bias, 5d = _f16_field(blocks, 0)qs = blocks[..., 2:].copy().view(np.int8).astype(np.int16) + 128return _pack(qs.astype(np.uint8).reshape(rows, cols), 8), d, -128.0 * d, 8+_KQUANT_TYPES = frozenset({"Q4_K", "Q5_K", "Q6_K"})+++def _kquant_blocks(kind: str, raw: np.ndarray, rows: int, cols: int) -> np.ndarray:+ if cols % _QK_K:+ raise ValueError(+ f"{kind}: {cols} columns are not a whole number of {_QK_K}-wide super-blocks"+ )+ raw = np.ascontiguousarray(np.asarray(raw)).view(np.uint8).reshape(-1)+ expected = rows * (cols // _QK_K) * _BLOCK_BYTES[kind]+ if raw.size != expected:+ raise ValueError(f"{kind}: {raw.size} bytes for {rows}x{cols}, expected {expected}")+ return raw.reshape(-1, _BLOCK_BYTES[kind])+++def _affine_from_kquant(+ kind: str, raw: np.ndarray, rows: int, cols: int+) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]:+ """Same block layout as gguf-py's dequantizers (``gguf.quants``), which the tests hold this to."""+ blocks = _kquant_blocks(kind, raw, rows, cols)+ n = blocks.shape[0]+ if kind == "Q6_K":+ from gguf.quants import Q6_K++ values = Q6_K.dequantize_blocks(blocks).reshape(rows, cols)+ packed, scales, biases = quantize_dense_affine(values, 8)+ return packed, scales, biases, 8+ from gguf.quants import Q4_K++ d = blocks[:, 0:2].copy().view(np.float16).astype(np.float32)+ dmin = blocks[:, 2:4].copy().view(np.float16).astype(np.float32)+ sc, m = Q4_K.get_scale_min(blocks[:, 4:16])+ scale = (d * sc.astype(np.float32)).reshape(rows, cols // GROUP_SIZE)+ bias = -(dmin * m.astype(np.float32)).reshape(rows, cols // GROUP_SIZE)+ if kind == "Q4_K":+ qs = blocks[:, 16:]+ q = (+ qs.reshape(n, -1, 1, 32) >> np.array([0, 4], dtype = np.uint8).reshape(1, 1, 2, 1)+ ) & 0x0F+ return _pack(q.reshape(rows, cols), 4), scale, bias, 4+ qh = blocks[:, 16:48]+ qs = blocks[:, 48:]+ ql = (qs.reshape(n, -1, 1, 32) >> np.array([0, 4], dtype = np.uint8).reshape(1, 1, 2, 1)) & 0x0F+ hi = (qh.reshape(n, -1, 1, 32) >> np.arange(8, dtype = np.uint8).reshape(1, 1, 8, 1)) & 0x01+ q = ql.reshape(n, -1, 32) | (hi.reshape(n, -1, 32) << 4)+ return _pack(q.reshape(rows, cols), 5), scale, bias, 5++def _f32_to_bf16_bits(a: np.ndarray) -> np.ndarray:"""float32 -> bf16 bit patterns (uint16), round to nearest even; NaN stays NaN."""a = np.ascontiguousarray(a, dtype = np.float32)@@ -269,7 +394,7 @@ def _scale_store(a: np.ndarray, scale_dtype: str) -> np.ndarray:def _plan(reader: Any, *, dense_bits: int, scale_dtype: str) -> tuple[list[_Job], dict]:sdt = "F16" if scale_dtype == "f16" else "BF16"jobs: list[_Job] = []- bits_count = {4: 0, 8: 0}+ bits_count = {4: 0, 5: 0, 8: 0}for tensor in reader.tensors:kind = _type_name(tensor)name = zimage_rename(str(tensor.name))@@ -379,7 +504,7 @@ def _check_types(reader: Any) -> dict[str, int]:listed = ", ".join(f"{v} x {k}" for k, v in sorted(bad.items()))raise UnsupportedGGUFError(f"GGUF holds tensor types MLX conversion does not support yet: {listed} "- "(supported: Q4_0, Q4_1, Q8_0, BF16, F16, F32)"+ "(supported: Q4_0, Q4_1, Q8_0, Q4_K, Q5_K, Q6_K, BF16, F16, F32)")return counts@@ -428,8 +553,9 @@ def convert_gguf_to_mflux(names = [e[0] for e in entries]if len(set(names)) != len(names):raise UnsupportedGGUFError("tensor names collide after the mflux rename")- if bits_count[4] or bits_count[8]:- level = "8" if bits_count[8] > bits_count[4] else "4"+ if any(bits_count.values()):+ # mflux reads each layer's bits from its shapes; the level only marks the file as pre-quantized.+ level = str(max(bits_count, key = lambda b: (bits_count[b], b)))else:level = "None"metadata = {diff --git a/studio/backend/tests/test_diffusion_mlx_engine_router.py b/studio/backend/tests/test_diffusion_mlx_engine_router.pyindex bfb8b494f90..e5793ff18f0 100644--- a/studio/backend/tests/test_diffusion_mlx_engine_router.py+++ b/studio/backend/tests/test_diffusion_mlx_engine_router.py@@ -201,8 +201,8 @@ def test_default_keeps_sd_cpp_where_sd_cpp_is_chosen_today(monkeypatch):[("sdxl", "sdxl-Q4_0.gguf", "gguf", "no MLX implementation"),("qwen-image", "qwen-image-Q4_0.gguf", "gguf", "no MLX implementation"),- ("z-image", "z-image-turbo-Q4_K_M.gguf", "gguf", "Q4_K_M"),- ("z-image", "z-image-turbo-Q6_K.gguf", "gguf", "Q6_K"),+ ("z-image", "z-image-turbo-Q3_K_M.gguf", "gguf", "Q3_K_M"),+ ("z-image", "z-image-turbo-Q2_K.gguf", "gguf", "Q2_K"),("z-image", "z-image-turbo-UD-Q4_K_XL.gguf", "gguf", "not convertible"),("z-image", None, "gguf", "unknown"),("z-image", None, "pipeline", "GGUF picks only"),@@ -315,15 +315,15 @@ def test_refusal_falls_through_to_sd_cpp_when_that_is_todays_choice(monkeypatch)monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")monkeypatch.setattr(r, "ensure_sd_cpp_binary", lambda **_: "/usr/bin/sd-cli")monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "v0"))- gguf = "z-image-turbo-Q4_K_M.gguf"+ gguf = "z-image-turbo-Q3_K_M.gguf"assert _predict(gguf = gguf) == _select(gguf = gguf) == ENGINE_SD_CPP- assert "Q4_K_M" in (r.annotate_status({})["mlx_fallback_reason"] or "")+ assert "Q3_K_M" in (r.annotate_status({})["mlx_fallback_reason"] or "")def test_a_later_default_selection_clears_the_mlx_reason(monkeypatch):_apple(monkeypatch)monkeypatch.setenv("UNSLOTH_DIFFUSION_MLX", "1")- _select(gguf = "z-image-turbo-Q4_K_M.gguf")+ _select(gguf = "z-image-turbo-Q3_K_M.gguf")assert r.annotate_status({})["mlx_fallback_reason"]monkeypatch.delenv("UNSLOTH_DIFFUSION_MLX")_select()@@ -335,7 +335,9 @@ def test_a_later_default_selection_clears_the_mlx_reason(monkeypatch):@pytest.mark.parametrize("env", [None, "0", "auto", "1"])@pytest.mark.parametrize("backend", ["mps", "cpu", "cuda"])[email protected]("gguf", [_Q4, "z-image-turbo-Q4_K_M.gguf", None])+ "gguf", [_Q4, "z-image-turbo-Q4_K_M.gguf", "z-image-turbo-Q3_K_M.gguf", None]+)@pytest.mark.parametrize("fam", ["z-image", "flux.1"])def test_predict_matches_selection(monkeypatch, env, backend, gguf, fam):_host(monkeypatch)@@ -346,7 +348,8 @@ def test_predict_matches_selection(monkeypatch, env, backend, gguf, fam):predicted = _predict(fam, gguf)r._active_engine_name = ENGINE_DIFFUSERSassert _select(fam, gguf) == predicted- expect_mlx = env == "1" and backend != "cuda" and gguf == _Q4 and fam == "z-image"+ convertible = gguf in (_Q4, "z-image-turbo-Q4_K_M.gguf")+ expect_mlx = env == "1" and backend != "cuda" and convertible and fam == "z-image"assert (predicted == ENGINE_MLX) is expect_mlxdiff --git a/studio/backend/tests/test_mlx_diffusion_backend.py b/studio/backend/tests/test_mlx_diffusion_backend.pyindex e1110466614..29cf7b280f2 100644--- a/studio/backend/tests/test_mlx_diffusion_backend.py+++ b/studio/backend/tests/test_mlx_diffusion_backend.py@@ -249,7 +249,7 @@ def test_local_files_only_reaches_every_fetch(env):"kwargs, needle",[({"gguf_filename": None}, "gguf_filename is required"),- ({"gguf_filename": "z-image-turbo-Q4_K_M.gguf"}, "Q4_K_M"),+ ({"gguf_filename": "z-image-turbo-Q3_K_M.gguf"}, "Q3_K_M"),({"gguf_filename": GGUF, "model_kind": "pipeline"}, "GGUF"),({"gguf_filename": "sdxl-Q4_0.gguf", "family_override": "sdxl"}, "no MLX implementation"),({"gguf_filename": GGUF, "loras": [("a/b", 1.0)]}, "LoRA"),diff --git a/studio/backend/tests/test_mlx_diffusion_convert.py b/studio/backend/tests/test_mlx_diffusion_convert.pyindex 1bc8319dd94..ca2401da911 100644--- a/studio/backend/tests/test_mlx_diffusion_convert.py+++ b/studio/backend/tests/test_mlx_diffusion_convert.py@@ -31,13 +31,13 @@ def _blocks(return quants.quantize(x, kind)[email protected]("kind", [T.Q4_0, T.Q4_1, T.Q8_0])[email protected]("kind", [T.Q4_0, T.Q4_1, T.Q5_0, T.Q5_1, T.Q8_0])@pytest.mark.parametrize("cols", [64, 96])def test_affine_matches_gguf_dequantize_exactly(kind, cols):raw = _blocks(kind, 6, cols, seed = cols)reference = quants.dequantize(raw, kind).astype(np.float32)w, s, b, bits = conv.affine_from_ggml(kind.name, raw, 6, cols)- assert bits == (8 if kind == T.Q8_0 else 4)+ assert bits == {T.Q8_0: 8, T.Q5_0: 5, T.Q5_1: 5}.get(kind, 4)assert w.dtype == np.uint32 and w.shape == (6, cols * bits // 32)assert s.shape == b.shape == (6, cols // 32)got = conv.dequantize_affine(w, s, b, bits)@@ -49,7 +49,7 @@ def test_affine_matches_gguf_dequantize_exactly(kind, cols):assert np.array_equal(conv.dequantize_affine(w, s16, b16, bits), reference)[email protected]("kind", [T.Q4_0, T.Q4_1, T.Q8_0])[email protected]("kind", [T.Q4_0, T.Q4_1, T.Q5_0, T.Q5_1, T.Q8_0])def test_affine_bf16_scales_within_rounding_bound(kind):raw = _blocks(kind, 8, 128, seed = 3)reference = quants.dequantize(raw, kind).astype(np.float32)@@ -63,11 +63,83 @@ def test_affine_bf16_scales_within_rounding_bound(kind):assert np.all(np.abs(sb - s) <= np.abs(s) * 2.0**-8)-def test_affine_rejects_kquant_and_bad_sizes():- with pytest.raises(conv.UnsupportedGGUFError):- conv.affine_from_ggml("Q4_K", np.zeros(144, np.uint8), 1, 256)+def test_affine_rejects_16_wide_kquants_and_bad_sizes():+ for kind, size in (("Q2_K", 84), ("Q3_K", 110)):+ with pytest.raises(conv.UnsupportedGGUFError):+ conv.affine_from_ggml(kind, np.zeros(size, np.uint8), 1, 256)with pytest.raises(ValueError):conv.affine_from_ggml("Q4_0", np.zeros(17, np.uint8), 1, 32)+ with pytest.raises(ValueError):+ conv.affine_from_ggml("Q4_K", np.zeros(143, np.uint8), 1, 256)+++# Field offsets of the 256-wide super-blocks (ggml-common.h block_q4_K / block_q5_K / block_q6_K).+_KQUANT_FP16_FIELDS = {"Q4_K": (0, 2), "Q5_K": (0, 2), "Q6_K": (208,)}+++def _kquant_raw(+ kind,+ rows,+ cols,+ seed = 0,+):+ """Random K-quant blocks with finite, realistic fp16 super-block scales (gguf-py cannot quantize these)."""+ size = conv._BLOCK_BYTES[kind]+ rng = _rng(seed)+ raw = rng.integers(0, 256, size = (rows * cols // 256, size), dtype = np.uint8)+ for offset in _KQUANT_FP16_FIELDS[kind]:+ d = (rng.uniform(1e-4, 3e-3, size = raw.shape[0])).astype(np.float16)+ raw[:, offset : offset + 2] = d.view(np.uint8).reshape(-1, 2)+ return raw++[email protected]("kind", ["Q4_K", "Q5_K"])+def test_kquant_codes_and_scales_reproduce_gguf_dequantize_exactly(kind):+ raw = _kquant_raw(kind, 4, 512, seed = 5)+ reference = quants.dequantize(raw, getattr(T, kind)).astype(np.float32).reshape(4, 512)+ w, s, b, bits = conv.affine_from_ggml(kind, raw, 4, 512)+ assert bits == (4 if kind == "Q4_K" else 5)+ assert w.shape == (4, 512 * bits // 32) and s.shape == b.shape == (4, 16)+ # Same fp32 products as gguf-py: exact before the 16-bit scale store.+ assert np.array_equal(conv.dequantize_affine(w, s, b, bits), reference)+ # The fp16 store rounds d * sc only: error bounded by the rounding of each group's scale and bias.+ s16 = s.astype(np.float16).astype(np.float32)+ b16 = b.astype(np.float16).astype(np.float32)+ q = conv._unpack(w, bits).astype(np.float32).reshape(4, 16, 32)+ bound = (q * np.abs(s16 - s)[..., None] + np.abs(b16 - b)[..., None]).reshape(4, 512)+ got = conv.dequantize_affine(w, s16, b16, bits)+ assert np.all(np.abs(got - reference) <= bound * 1.0001 + 1e-12)+ assert np.max(np.abs(got - reference)) <= 2.0**-10 * np.max(np.abs(reference))+++def test_q6_k_requantizes_to_8_bits_within_a_quarter_of_its_own_step():+ raw = _kquant_raw("Q6_K", 4, 512, seed = 9)+ reference = quants.dequantize(raw, T.Q6_K).astype(np.float32).reshape(4, 512)+ w, s, b, bits = conv.affine_from_ggml("Q6_K", raw, 4, 512)+ assert bits == 8+ got = conv.dequantize_affine(w, s, b, bits)+ # Q6_K's own step per 16 values is |d * scale|; the 8-bit group-32 step over the same values is <= 64 / 255 of+ # the larger one, so the rounding error stays within half of that.+ blocks = raw.reshape(-1, 210)+ d = blocks[:, 208:210].copy().view(np.float16).astype(np.float32)+ sc = blocks[:, 192:208].view(np.int8).astype(np.float32)+ step = np.abs(d * sc).reshape(4, 32)+ group_step = np.maximum(step[:, 0::2], step[:, 1::2])+ err = np.abs(got - reference).reshape(4, 16, 32).max(axis = -1)+ assert np.all(err <= group_step * 0.25 + 1e-7)++[email protected]("bits", [3, 4, 5, 6, 8])+def test_pack_matches_mlx_layout_bit_for_bit(bits):+ mx = pytest.importorskip("mlx.core")+ w = mx.array(_rng(bits).standard_normal((8, 256)).astype(np.float32))+ packed, scales, biases = mx.quantize(w, group_size = 32, bits = bits)+ deq = np.array(mx.dequantize(packed, scales, biases, group_size = 32, bits = bits))+ q = np.rint(+ (deq.reshape(8, 8, 32) - np.array(biases)[..., None]) / np.array(scales)[..., None]+ ).astype(np.int64)+ assert np.array_equal(conv._pack(q.reshape(8, 256), bits), np.array(packed))+ assert np.array_equal(conv._unpack(np.array(packed), bits), q.reshape(8, 256))@pytest.mark.parametrize("bits", [4, 8])@@ -118,10 +190,16 @@ def test_zimage_rename(src, dst):("z-image-turbo-Q8_0.gguf", True),("z-image-turbo-BF16.gguf", True),("z-image-turbo-F16.gguf", True),- ("z_image_turbo-Q4_K_M.gguf", False),+ ("z_image_turbo-Q4_K_M.gguf", True),+ ("z-image-turbo-Q4_K_S.gguf", True),+ ("z-image-turbo-Q5_K_M.gguf", True),+ ("z-image-turbo-Q5_K_S.gguf", True),+ ("z-image-turbo-Q6_K.gguf", True),+ ("z-image-turbo-Q5_0.gguf", True),+ ("z-image-turbo-Q5_1.gguf", True),("z-image-turbo-UD-Q4_K_XL.gguf", False),- ("z-image-turbo-Q6_K.gguf", False),- ("z-image-turbo-Q5_0.gguf", False),+ ("z-image-turbo-Q3_K_M.gguf", False),+ ("z-image-turbo-Q2_K.gguf", False),("z-image-turbo-IQ4_XS.gguf", False),("z-image-turbo-MXFP4.gguf", False),("z-image-turbo.gguf", False),@@ -137,8 +215,8 @@ def test_quant_convertible(name, ok):def test_quant_convertible_names_the_kquant():- _ok, reason = conv.quant_convertible("z_image_turbo-Q4_K_M.gguf")- assert "Q4_K_M" in reason and "not convertible" in reason+ _ok, reason = conv.quant_convertible("z_image_turbo-Q3_K_M.gguf")+ assert "Q3_K_M" in reason and "not convertible" in reason# ── End to end on a tiny synthetic GGUF ─────────────────────────────────────────────────────────@@ -291,14 +369,14 @@ def test_convert_dense_bits_quantizes_dense_linears(tmp_path):def test_convert_refuses_kquant_before_writing(tmp_path):- src = tmp_path / "z-image-turbo-Q4_K_M.gguf"+ src = tmp_path / "z-image-turbo-Q3_K_M.gguf"def extra(w):- raw = _rng(2).integers(0, 255, size = (4, 144), dtype = np.uint8)- w.add_tensor("layers.0.feed_forward.w2.weight", raw, raw_dtype = T.Q4_K)+ raw = _rng(2).integers(0, 255, size = (4, 110), dtype = np.uint8)+ w.add_tensor("layers.0.feed_forward.w2.weight", raw, raw_dtype = T.Q3_K)_write_gguf(src, extra = extra)- with pytest.raises(conv.UnsupportedGGUFError, match = "Q4_K"):+ with pytest.raises(conv.UnsupportedGGUFError, match = "Q3_K"):conv.convert_gguf_to_mflux(src, tmp_path / "out")assert not (tmp_path / "out" / "transformer" / "0.safetensors").exists()assert not conv.conversion_complete(tmp_path / "out")@@ -363,3 +441,54 @@ def test_mlx_loads_the_output_when_available(tmp_path):).astype(mx.float32)kind, raw = sources["layers.0.attention.out.weight"]np.testing.assert_allclose(np.array(got), quants.dequantize(raw, kind), atol = 2e-3, rtol = 0)+++def test_a_q4_k_m_mixture_converts_and_mlx_reads_every_layer(tmp_path):+ """Q4_K + Q5_K + Q6_K + Q5_0 beside the Q4_0 / Q8_0 / BF16 tensors, read back with MLX's own dequantize."""+ mx = pytest.importorskip("mlx.core")+ src = tmp_path / "z-image-turbo-Q4_K_M.gguf"+ extra_sources = {}++ def extra(w):+ for name, kind, seed in (+ ("layers.1.feed_forward.w1.weight", "Q4_K", 1),+ ("layers.1.feed_forward.w2.weight", "Q5_K", 2),+ ("layers.1.feed_forward.w3.weight", "Q6_K", 3),+ ):+ raw = _kquant_raw(kind, 4, 256, seed = seed)+ extra_sources[name] = (kind, raw)+ w.add_tensor(name, raw.reshape(4, -1), raw_dtype = getattr(T, kind))+ x = (_rng(4).standard_normal((4, 64)) * 0.05).astype(np.float32)+ raw = quants.quantize(x, T.Q5_0)+ extra_sources["layers.1.attention.out.weight"] = ("Q5_0", raw)+ w.add_tensor("layers.1.attention.out.weight", raw, raw_dtype = T.Q5_0)++ _write_gguf(src, extra = extra)+ summary = conv.convert_gguf_to_mflux(src, tmp_path / "out")+ assert {"Q4_K", "Q5_K", "Q6_K", "Q5_0"} <= set(summary["counts"])+ loaded, meta = mx.load(+ str(tmp_path / "out" / "transformer" / "0.safetensors"), return_metadata = True+ )+ assert meta["quantization_level"] not in (None, "None")+ renamed = {+ "layers.1.feed_forward.w1.weight": ("layers.1.feed_forward.w1", 4),+ "layers.1.feed_forward.w2.weight": ("layers.1.feed_forward.w2", 5),+ "layers.1.feed_forward.w3.weight": ("layers.1.feed_forward.w3", 8),+ "layers.1.attention.out.weight": ("layers.1.attention.to_out.0", 5),+ }+ for name, (kind, raw) in extra_sources.items():+ base, bits = renamed[name]+ got = mx.dequantize(+ loaded[base + ".weight"],+ loaded[base + ".scales"],+ loaded[base + ".biases"],+ group_size = 32,+ bits = bits,+ ).astype(mx.float32)+ reference = (+ quants.dequantize(raw, getattr(T, kind)).astype(np.float32).reshape(np.array(got).shape)+ )+ # bf16 scales and biases, and MLX dequantizes into bf16: a few bf16 ulps of the largest weight (a layout+ # error would be off by the weight itself).+ tol = 2.0**-6 * np.max(np.abs(reference))+ np.testing.assert_allclose(np.array(got), reference, atol = tol, rtol = 0)