File size: 6,553 Bytes
e349bd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python3
"""Offline NVFP4 quantizer for DWarp-v1 checkpoints (`dwarp.safetensors` -> `dwarp_nvfp4.safetensors`).

Quantizes ONLY the 36 backbone linear projections across the 4 DWarp layers (9 per layer):
  layers.{l}.{q_proj,k_proj,v_proj,k_proj_ctx,v_proj_ctx,o_proj,gate_proj,up_proj,down_proj}.weight
using per-16-block adaptive Four Over Six (4/6-MSE) NVFP4 quantization (`den = 1536.0`,
E2M1 packed u8 + E4M3FN block scales + FP32 amax/den), cutting active drafter backbone
weights ~3.7x (~734 MB BF16 -> ~197 MB NVFP4).

Method Credit:
  Four Over Six (4/6-MSE) adaptive NVFP4 block scaling is due to:
  Cook et al., "Four Over Six: More Accurate NVFP4 Quantization with Adaptive Block Scaling"
  (MIT & NVIDIA, arXiv:2512.02010, 2025).

All sensitive/small tensors (norms, DynConv2, embeddings, sampler MLP, Markov head, pivot_mlp, fuse_weight)
remain untouched in BF16 inside the output `dwarp_nvfp4.safetensors`, making the output directory 100%
self-contained while leaving the original BF16 `--in-dir` completely untouched.
"""
import argparse
import shutil
import time
from pathlib import Path

import numpy as np
import torch
from safetensors.torch import load_file, save_file

BACKBONE_PROJS = (
    ".q_proj.weight",
    ".k_proj.weight",
    ".v_proj.weight",
    ".k_proj_ctx.weight",
    ".v_proj_ctx.weight",
    ".o_proj.weight",
    ".gate_proj.weight",
    ".up_proj.weight",
    ".down_proj.weight",
)

DEN = 1536.0


def build_e4m3_pos_lut():
    lut = np.zeros(127, dtype=np.float32)
    for b in range(127):
        e = (b >> 3) & 0xF
        m = b & 7
        lut[b] = (m * 2.0**-9) if e == 0 else ((1.0 + m / 8.0) * 2.0**(e - 7))
    return lut


E4M3_POS = build_e4m3_pos_lut()
E2M1_POS = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=np.float32)
E2M1_THR = np.array([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], dtype=np.float32)


def quant_e4m3_pos(x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    xc = np.clip(x, 0.0, 448.0)
    idx = np.searchsorted(E4M3_POS, xc)
    idx = np.clip(idx, 0, 126)
    prev = np.maximum(idx - 1, 0)
    choose_prev = np.abs(xc - E4M3_POS[prev]) <= np.abs(E4M3_POS[idx] - xc)
    codes = np.where(choose_prev, prev, idx).astype(np.uint8)
    return codes, E4M3_POS[codes]


def quant_e2m1(x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    sign = (x < 0).astype(np.uint8) << 3
    a = np.abs(x)
    mag_code = np.searchsorted(E2M1_THR, a).astype(np.uint8)
    val = np.where(sign != 0, -E2M1_POS[mag_code], E2M1_POS[mag_code])
    return (sign | mag_code), val


def quantize_matrix_nvfp4(w_f32: np.ndarray) -> tuple[np.ndarray, np.ndarray, float, float, float]:
    n, k = w_f32.shape
    assert k % 32 == 0, f"K={k} must be a multiple of 32"
    amax = float(np.max(np.abs(w_f32)))
    if amax == 0.0:
        return np.zeros((n, k // 2), dtype=np.uint8), np.zeros((n, k // 16), dtype=np.uint8), 0.0, DEN, 0.0

    outer = amax / DEN
    blk = w_f32.reshape(-1, 16)
    bmax = np.max(np.abs(blk), axis=1, keepdims=True)

    c6, s6 = quant_e4m3_pos(bmax / (6.0 * outer))
    d6 = s6 * outer
    inv6 = np.where(d6 > 0, 1.0 / d6, 0.0)
    q6, r6 = quant_e2m1(blk * inv6)
    rec6 = r6 * d6
    mse6 = np.sum((rec6 - blk) ** 2, axis=1, keepdims=True)

    c4, s4 = quant_e4m3_pos(bmax / (4.0 * outer))
    d4 = s4 * outer
    inv4 = np.where(d4 > 0, 1.0 / d4, 0.0)
    q4, r4 = quant_e2m1(blk * inv4)
    rec4 = r4 * d4
    mse4 = np.sum((rec4 - blk) ** 2, axis=1, keepdims=True)

    use4 = mse4 < mse6
    q = np.where(use4, q4, q6)
    sc = np.where(use4[:, 0], c4[:, 0], c6[:, 0]).reshape(n, k // 16)
    rec = np.where(use4, rec4, rec6)
    rel_rmse = float(np.sqrt(np.mean((rec - blk) ** 2)) / max(np.sqrt(np.mean(blk ** 2)), 1e-12))

    # Pack 2 nibbles/byte (low = even col, high = odd col)
    q2 = q.reshape(n, k // 2, 2)
    packed = (q2[:, :, 0] | (q2[:, :, 1] << 4)).astype(np.uint8)
    return packed, sc.astype(np.uint8), amax, DEN, rel_rmse


def is_backbone_proj(name: str) -> bool:
    return name.startswith("layers.") and any(name.endswith(sfx) for sfx in BACKBONE_PROJS)


def main():
    ap = argparse.ArgumentParser(
        description="Create a standalone NVFP4 copy of a DWarp-v1 checkpoint without modifying the original BF16 directory."
    )
    ap.add_argument("--in-dir", type=Path, required=True, help="Original BF16 directory with dwarp.safetensors + dwarp_config.json (untouched)")
    ap.add_argument(
        "--out-dir",
        type=Path,
        default=None,
        help="Output standalone NVFP4 directory (default: <in-dir>_nvfp4); receives dwarp_config.json + dwarp_nvfp4.safetensors",
    )
    ap.add_argument(
        "--out",
        type=Path,
        default=None,
        help="Optional explicit output .safetensors path (overrides --out-dir; copies dwarp_config.json if parent differs from --in-dir)",
    )
    args = ap.parse_args()

    in_dir = args.in_dir.resolve()
    src = in_dir / "dwarp.safetensors"
    src_cfg = in_dir / "dwarp_config.json"
    if args.out is not None:
        dst = args.out
        out_dir = dst.parent
    else:
        out_dir = args.out_dir if args.out_dir is not None else in_dir.with_name(f"{in_dir.name}_nvfp4")
        dst = out_dir / "dwarp_nvfp4.safetensors"
    out_dir.mkdir(parents=True, exist_ok=True)
    if src_cfg.exists() and out_dir.resolve() != in_dir:
        shutil.copy2(src_cfg, out_dir / "dwarp_config.json")

    t0 = time.perf_counter()
    sd = load_file(str(src))
    out = {}
    rmses = []
    n_quant = 0
    for k, v in sd.items():
        if is_backbone_proj(k) and v.ndim == 2 and v.shape[1] % 32 == 0:
            w = v.float().cpu().numpy()
            packed, sc, amax, den, rel_rmse = quantize_matrix_nvfp4(w)
            out[f"{k}_nvfp4"] = torch.from_numpy(packed).contiguous()
            out[f"{k}_nvfp4_scale"] = torch.from_numpy(sc).contiguous()
            out[f"{k}_nvfp4_gs"] = torch.tensor([amax, den], dtype=torch.float32)
            rmses.append(rel_rmse)
            n_quant += 1
        else:
            out[k] = v.contiguous()
    save_file(out, str(dst))
    dt = time.perf_counter() - t0
    sz_in = src.stat().st_size / 1e6
    sz_out = dst.stat().st_size / 1e6
    avg_rmse = float(np.mean(rmses)) if rmses else 0.0
    print(
        f"Quantized {n_quant} backbone matrices in {dt:.1f}s: {sz_in:.1f} MB -> {sz_out:.1f} MB "
        f"(mean rel_rmse={avg_rmse*100:.2f}%)\n"
        f"  Original BF16 (untouched): {in_dir}\n"
        f"  Standalone NVFP4 copy:     {out_dir}"
    )


if __name__ == "__main__":
    main()