File size: 15,456 Bytes
b1690c1 | 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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | #!/usr/bin/env python3
"""Build tiny FORMAT fixtures, optionally capture via integrated QFS layer-outer.
No optimizer-quality claim: deterministic CPU minmax/conservative-scale RTN.
MXFP4 uses ceil(log2(group_max/6)); this is NOT CT's MX observer or Kimi QAT.
NVFP4 uses a tensor maximum global, rounded E4M3 group scales, then E2M1
nearest-even RTN. FP8 uses ceil(log2(block_max/448)) UE8M0 + E4M3 RTN.
No calibration, activation quantization, kernel parity, training or model code.
"""
from __future__ import annotations
import argparse
from collections import defaultdict
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
PINS = {
"malaiwah/glm-moe-dsa-tiny-random-bf16": "a1a973330e4e912678adbd8ea41e8b86b1c9dccb",
"malaiwah/qwen3-5-tiny-random-bf16": "a430e41d5814ba5e7bfa5ee29d86935aac56d95d",
}
FORMATS = ("ct-mxfp4", "ct-nvfp4", "modelopt-nvfp4", "fp8-ue8m0", "modelopt-mixed")
MIXED_FORMATS = ("modelopt-nvfp4", "modelopt-fp8-tensor", "modelopt-fp8-block")
def fp4_codes(x):
"""Literal round-to-nearest-even thresholds, independently of the decoder."""
import torch
a = x.abs()
code = torch.zeros_like(a, dtype=torch.uint8)
for value, boundary, inclusive in [(1, .25, False), (2, .75, True),
(3, 1.25, False), (4, 1.75, True), (5, 2.5, False),
(6, 3.5, True), (7, 5., False)]:
code = torch.where(a >= boundary if inclusive else a > boundary, value, code)
return code | (torch.signbit(x).to(torch.uint8) << 3)
def oracle_fp4(packed):
"""Independent bit-field E2M1, not the surface LUT/unpack helper."""
import torch
code = torch.empty((*packed.shape[:-1], packed.shape[-1] * 2), dtype=torch.int32)
code[..., 0::2] = packed.to(torch.int32) & 15
code[..., 1::2] = packed.to(torch.int32) >> 4
exponent, mantissa = (code >> 1) & 3, code & 1
magnitude = torch.where(exponent == 0, mantissa.float() * .5,
torch.ldexp(1 + mantissa.float() * .5, exponent - 1))
return torch.copysign(magnitude, torch.where((code & 8) != 0, -1., 1.))
def encode(weight, fmt):
import torch
x = weight.float().cpu()
if not torch.isfinite(x).all():
raise ValueError("nonfinite source weight")
if fmt == "modelopt-fp8-block":
parts, oracle = encode(x, "fp8-ue8m0")
scale = torch.exp2(parts["scale"].float() - 127).to(torch.bfloat16)
return {"weight": parts["weight"], "weight_scale_inv": scale}, oracle
if fmt == "modelopt-fp8-tensor":
scale = (x.abs().max() / 448.).clamp(min=2**-126).to(torch.bfloat16).reshape(1)
q = (x / scale.float()).clamp(-448,448).to(torch.float8_e4m3fn)
return {"weight": q, "weight_scale": scale}, q.float() * scale.float()
if fmt == "fp8-ue8m0":
n, k = x.shape[-2:]
scales = torch.empty((*x.shape[:-2], (n + 127)//128, (k + 127)//128), dtype=torch.uint8)
q = torch.empty_like(x, dtype=torch.float8_e4m3fn)
oracle = torch.empty_like(x)
for i in range(scales.shape[-2]):
for j in range(scales.shape[-1]):
block = x[..., i*128:(i+1)*128, j*128:(j+1)*128]
amax = block.abs().amax(dim=(-2,-1))
exponent = torch.where(amax == 0, 0., torch.ceil(torch.log2(amax / 448.))).clamp(-127, 127)
scale = torch.exp2(exponent)
scales[..., i, j] = (exponent + 127).to(torch.uint8)
qb = (block / scale[..., None, None]).clamp(-448,448).to(torch.float8_e4m3fn)
q[..., i*128:(i+1)*128, j*128:(j+1)*128] = qb
oracle[..., i*128:(i+1)*128, j*128:(j+1)*128] = qb.float() * scale[..., None, None]
return {"weight": q, "scale": scales}, oracle
group = 32 if fmt == "ct-mxfp4" else 16
blocks = x.reshape(*x.shape[:-1], -1, group)
amax = blocks.abs().amax(dim=-1)
extra = {}
if fmt == "ct-mxfp4":
exponent = torch.where(amax == 0, 0., torch.ceil(torch.log2(amax / 6.))).clamp(-127, 127)
stored_scale = (exponent + 127).to(torch.uint8)
effective = torch.exp2(exponent)
else:
global_multiplier = torch.clamp(x.abs().max() / (6. * 448.), min=torch.finfo(torch.float32).tiny)
if not bool(x.abs().max()):
global_multiplier = torch.tensor(1., dtype=torch.float32)
if fmt == "ct-nvfp4":
global_value = global_multiplier.reciprocal().reshape(1)
unrounded = amax / 6. * global_value
role = "weight_global_scale"
else:
global_value = global_multiplier.reshape(1)
unrounded = amax / 6. / global_value
role = "weight_scale_2"
unrounded = torch.where(amax == 0, 0., unrounded.clamp(min=2**-9, max=448.))
stored_scale = unrounded.to(torch.float8_e4m3fn)
effective = stored_scale.float() / global_value if fmt == "ct-nvfp4" else stored_scale.float() * global_value
extra[role] = global_value
normalized = blocks / torch.where(effective == 0, 1., effective).unsqueeze(-1)
codes = fp4_codes(normalized).reshape(x.shape)
packed = codes[..., 0::2] | (codes[..., 1::2] << 4)
oracle = (oracle_fp4(packed).reshape(blocks.shape) * effective.unsqueeze(-1)).reshape(x.shape)
return {"weight" if fmt == "modelopt-nvfp4" else "weight_packed": packed,
"weight_scale": stored_scale, **extra}, oracle
def quant_config(fmt, targets):
if fmt == "modelopt-mixed":
declarations = ({"quant_algo":"NVFP4","group_size":16},
{"quant_algo":"FP8"}, {"quant_algo":"FP8_PB_WO","group_size":128})
return {"quant_method":"modelopt", "quant_algo":"MIXED_PRECISION",
"quantized_layers":{target:dict(declarations[i % 3]) for i,target in enumerate(targets)}}
if fmt == "fp8-ue8m0":
return {"quant_method": "fp8", "fmt": "e4m3", "scale_fmt": "ue8m0",
"activation_scheme": "dynamic", "weight_block_size": [128, 128]}
if fmt == "modelopt-nvfp4":
return {"quant_method": "modelopt", "quant_algo": "NVFP4", "group_size": 16,
"num_bits": 4, "with_input_scale": False}
mx = fmt == "ct-mxfp4"
packing = "mxfp4-pack-quantized" if mx else "nvfp4-pack-quantized"
return {"quant_method": "compressed-tensors", "format": packing,
"quantization_status": "compressed", "ignore": [],
"config_groups": {"group_0": {"format": packing, "targets": targets,
"input_activations": None, "output_activations": None,
"weights": {"num_bits": 4, "type": "float", "group_size": 32 if mx else 16,
"strategy": "group" if mx else "tensor_group", "symmetric": True,
"dynamic": False, "scale_dtype": "torch.uint8" if mx else "torch.float8_e4m3fn"}}}}
def metadata(tensors):
import torch
codes = {torch.uint8: "U8", torch.int8: "I8", torch.int32: "I32", torch.int64: "I64",
torch.float32: "F32", torch.float16: "F16", torch.bfloat16: "BF16", torch.float8_e4m3fn: "F8_E4M3"}
return {k: {"shape": list(v.shape), "dtype": codes[v.dtype]} for k,v in tensors.items()}
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def capture(args):
command = [sys.executable,str(args.qfs_root/"engines/tools/hf_capture.py"),
"--model",str(args.out),"--model-revision",args.candidate_revision,"--weights-repository",args.candidate_repo,
"--panel",str(args.panel),"--out",str(args.out.parent/(args.out.name+"-capture")),
"--role","quant","--lane","streaming","--device",args.device,"--dtype","bfloat16",
"--schedule",args.schedule,"--dataset-id","fidelity--tiny.microfloat."+args.format,
"--dataset-name","Tiny "+args.format+" FORMAT fixture", "--scope-file",str(args.out/"scope.json"),
"--codec",args.format]
if args.format != "modelopt-mixed":
command += ["--declared-bits","8" if args.format == "fp8-ue8m0" else "4"]
subprocess.run(command,check=True)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--qfs-root", type=Path, default=Path("/tmp/qfs-explorer-development"))
p.add_argument("--source-repo", choices=sorted(PINS), default=next(iter(PINS)))
p.add_argument("--format", choices=FORMATS, required=True)
p.add_argument("--out", type=Path, required=True)
p.add_argument("--schedule", choices=["layer-outer"], default="layer-outer")
p.add_argument("--capture", action="store_true")
p.add_argument("--panel", type=Path)
p.add_argument("--candidate-repo")
p.add_argument("--candidate-revision")
p.add_argument("--device", default="cpu")
args = p.parse_args()
if args.capture and (not args.panel or not args.candidate_repo or not re.fullmatch(r"[0-9a-f]{40}", args.candidate_revision or "")):
p.error("capture requires --panel, --candidate-repo and exact --candidate-revision (publish/pin separately)")
if args.out.exists():
if args.capture:
provenance = json.loads((args.out / "provenance.json").read_text())
if provenance["source"] != {"repository":args.source_repo,"revision":PINS[args.source_repo]} or provenance["format"] != args.format:
p.error("existing fixture provenance does not match requested source/format")
for name, sha in provenance["output_sha256"].items():
if digest(args.out / name) != sha:
p.error("existing fixture changed after build: " + name)
capture(args)
return
p.error("--out must not exist; never overwrite a fixture")
sys.path.insert(0, str(args.qfs_root / "engines/tools"))
from microscale_surface import plan_modules, decode_module
from fp8_scope import assignments_from_census, classify, decoder_layers
from huggingface_hub import snapshot_download
from safetensors.torch import load_file, save_file
import torch
pin = PINS[args.source_repo]
source = Path(snapshot_download(args.source_repo, revision=pin,
allow_patterns=["*.json", "*.safetensors", "tokenizer*", "vocab*", "merges.txt", "LICENSE*", "*.model"],
ignore_patterns=["*.py", "*.md"]))
files = sorted(source.glob("*.safetensors"))
if not files or sum(f.stat().st_size for f in files) > 128 * 1024**2:
raise ValueError("only tiny fixture roots below 128MiB are permitted")
config = json.loads((source / "config.json").read_text())
if config.get("quantization_config") or (config.get("text_config") or {}).get("quantization_config"):
raise ValueError("source must be native, not quantized")
original = {}
for shard in files:
for key,value in load_file(str(shard)).items():
if key in original: raise ValueError("duplicate source key " + key)
original[key] = value
transformed, oracle, targets = {}, {}, []
encoded_formats = {}
for key,value in original.items():
eligible = (key.endswith(".weight") and value.ndim in (2,3) and value.is_floating_point()
and ".layers." in key and (args.format == "fp8-ue8m0" or value.shape[-1] % (32 if args.format == "ct-mxfp4" else 16) == 0)
and not any(s in key for s in ("embed", "norm", ".mlp.gate.weight", ".router.")))
if not eligible:
transformed[key] = value
continue
module = key.rsplit(".",1)[0]
selected_format = MIXED_FORMATS[len(targets) % 3] if args.format == "modelopt-mixed" else args.format
parts, expected = encode(value, selected_format)
encoded_formats[key] = selected_format
targets.append(module)
oracle[key] = expected
transformed.update({module + "." + role: tensor.contiguous() for role,tensor in parts.items()})
if not oracle: raise ValueError("no eligible source matrices")
if args.format == "modelopt-mixed" and len(targets) < 3:
raise ValueError("mixed fixture requires at least three matrices for all constituents")
config["quantization_config"] = quant_config(args.format, targets)
plan = plan_modules(config, metadata(transformed))
errors = {}
for key,spec in plan["modules"].items():
decoded = decode_module({r:transformed[k] for r,k in spec["components"].items()},spec,dtype=torch.float32,device="cpu")
if not torch.equal(decoded.view(torch.int32), oracle[key].view(torch.int32)):
raise ValueError("independent encoder reconstruction disagrees: " + key)
errors[key] = float((decoded - original[key].float()).abs().max())
if not any(v > 0 for v in errors.values()):
raise ValueError("fixture unexpectedly has no quantization error")
args.out.mkdir(parents=True)
for source_file in source.iterdir():
if source_file.is_file() and source_file.name not in ("config.json", "model.safetensors.index.json") and source_file.suffix != ".safetensors" and source_file.suffix != ".py":
shutil.copy2(source_file, args.out / source_file.name)
(args.out / "config.json").write_text(json.dumps(config,indent=2)+"\n")
save_file(transformed, str(args.out / "model.safetensors"), metadata={"format":"pt"})
index = {"metadata":{"total_size":sum(v.numel()*v.element_size() for v in transformed.values())},
"weight_map":{k:"model.safetensors" for k in transformed}}
(args.out / "model.safetensors.index.json").write_text(json.dumps(index,indent=2)+"\n")
census = defaultdict(list)
for key,value in original.items():
changed = key in oracle
fmt = encoded_formats[key] if changed else {torch.float32:"fp32",torch.bfloat16:"bf16",torch.float16:"fp16"}.get(value.dtype,str(value.dtype))
census[classify(key,decoder_layers(config))].append((key,"quantized" if changed else "native",fmt,8 if changed and "fp8" in fmt else 4 if changed else value.element_size()*8))
scope = {"policy":"mixed", "head_policy":"native", "kv_cache_dtype":"bf16", "mtp_included":bool(census.get("mtp")),
"activation_quantization":None,
"assignments":assignments_from_census(census,"FORMAT fixture CPU RTN; reconstructed weights only; activation-not-captured, no optimizer/native-kernel quality claim")}
(args.out / "scope.json").write_text(json.dumps(scope,indent=2)+"\n")
provenance = {"source":{"repository":args.source_repo,"revision":pin}, "format":args.format,
"algorithm":__doc__, "claim":"FORMAT fixture, not Kimi QAT/ModelOpt calibration/CT observer quality",
"reconstruction_scope":plan["activation_quantization"], "encoded_tensors":errors,
"encoded_formats":encoded_formats,
"source_sha256":{f.name:digest(f) for f in [source/"config.json",*files]},
"output_sha256":{f.name:digest(f) for f in args.out.iterdir() if f.is_file()},
"tool_sha256":digest(__file__), "reader_sha256":digest(args.qfs_root/"engines/tools/microscale_surface.py"),
"reference":plan["reference"], "verification":"independent CPU FP32 encoder reconstruction per encoded weight; no GPU parity"}
(args.out / "provenance.json").write_text(json.dumps(provenance,indent=2)+"\n")
print(json.dumps({"model":str(args.out),"format":args.format,"encoded_modules":len(oracle),"max_weight_error":max(errors.values())}))
if args.capture:
capture(args)
if __name__ == "__main__":
main()
|