geudrik/clairic-sm120-work / src_v2 /quantization /quantize_nvfp4_mixed.py
geudrik's picture
download
raw
18 kB
"""ModelOpt Calibrated Mixed NVFP4 + FP8 Post-Training Quantization for Cloudflare/clairic on SM120.
Layer sensitivity map (adapted from NVIDIA Qwen3.8-27B-NVFP4 sensitivity bounds for Clairic):
- NVFP4 (`group_size=16`, E2M1 weights + FP8 E4M3 per-16 scales + FP32 global scale + calibrated activation scale):
- 52 interior SwiGLU MLPs (`layers.4..55.mlp.{gate,up,down}_proj` -> 156 linear layers)
- 38 interior Gated DeltaNet blocks (`in_proj_qkv`, `in_proj_z`, `out_proj` in layers 6..56 -> 114 linear layers)
- FP8 (`E4M3` calibrated weight + activation scale):
- 12 boundary SwiGLU MLPs (`layers.{0..3, 56..63}.mlp.{gate,up,down}_proj` -> 36 linear layers, protecting entry representations and final-layer `ClairicHead` arithmetic hidden states)
- All 16 full-attention GQA blocks (`self_attn.{q,k,v,o}_proj` -> 64 linear layers)
- 10 boundary Gated DeltaNet blocks (`layers.{0,1,2,4,5,57,58,60,61,62}.linear_attn.{in_proj_qkv,in_proj_z,out_proj}` -> 30 linear layers)
- BF16 / FP32 (Unquantized):
- `lm_head` and `embed_tokens` (preserves post-grammar-mask `confidence`, `p_null`, and `ClairicHead.read_slots`)
- Entire 27-layer `model.visual` ViT + DeepStack mergers (preserves OCR / receipt / multi-page PO vision fidelity)
- All Gated DeltaNet recurrent/conv parameters (`in_proj_a`, `in_proj_b`, `conv1d`, `A_log`, `dt_bias`, `norm`) and RMSNorms
- `clair_head.safetensors` (FP32)
Calibration uses an independent, held-out 24-sample multimodal + structured JSON + typed-slot corpus
(completely disjoint from `workload_suite.py`).
"""
from __future__ import annotations
import argparse
import copy
import gc
import io
import json
import shutil
import sys
import time
from pathlib import Path
from typing import Any
import torch
from PIL import Image, ImageDraw
EDGE_GDN_FP8_LAYERS = (0, 1, 2, 4, 5, 57, 58, 60, 61, 62)
BOUNDARY_MLP_FP8_LAYERS = (0, 1, 2, 3, 56, 57, 58, 59, 60, 61, 62, 63)
def build_mixed_nvfp4_fp8_cfg(protect_boundary_mlps: bool = True) -> dict[str, Any]:
import modelopt.torch.quantization as mtq
cfg = copy.deepcopy(mtq.NVFP4_DEFAULT_CFG)
quant_rules: list[dict[str, Any]] = list(cfg["quant_cfg"])
fp8_override_rules: list[dict[str, Any]] = [
{
"quantizer_name": "*self_attn.q_proj*weight_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.q_proj*input_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.k_proj*weight_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.k_proj*input_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.v_proj*weight_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.v_proj*input_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.o_proj*weight_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
{
"quantizer_name": "*self_attn.o_proj*input_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
},
]
for layer_idx in EDGE_GDN_FP8_LAYERS:
for proj in ("in_proj_qkv", "in_proj_z", "out_proj"):
fp8_override_rules.append(
{
"quantizer_name": f"*layers.{layer_idx}.linear_attn.{proj}*weight_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
}
)
fp8_override_rules.append(
{
"quantizer_name": f"*layers.{layer_idx}.linear_attn.{proj}*input_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
}
)
if protect_boundary_mlps:
for layer_idx in BOUNDARY_MLP_FP8_LAYERS:
for proj in ("gate_proj", "up_proj", "down_proj"):
fp8_override_rules.append(
{
"quantizer_name": f"*layers.{layer_idx}.mlp.{proj}*weight_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
}
)
fp8_override_rules.append(
{
"quantizer_name": f"*layers.{layer_idx}.mlp.{proj}*input_quantizer",
"cfg": {"num_bits": (4, 3), "axis": None},
}
)
# Insert FP8 overrides right after global NVFP4 weight/input rules and before explicit disable rules
insert_pos = 3
cfg["quant_cfg"] = quant_rules[:insert_pos] + fp8_override_rules + quant_rules[insert_pos:]
cfg["algorithm"] = "max"
return cfg
def _make_heldout_calib_image(seed_idx: int) -> Image.Image:
img = Image.new("RGB", (640, 480), color=(250, 249, 246))
draw = ImageDraw.Draw(img)
draw.rectangle([20, 20, 620, 90], fill=(30, 45, 75))
draw.text((36, 44), f"HELD-OUT CALIBRATION MANIFEST #{100 + seed_idx}", fill=(255, 255, 255))
rows = [
("SKU-4410", "Rack PDU 30A", f"{2 + seed_idx}", f"${(2 + seed_idx) * 315.00:,.2f}"),
("SKU-8821", "Twinax DAC 3m", f"{8 + seed_idx}", f"${(8 + seed_idx) * 42.50:,.2f}"),
("SKU-9904", "Transceiver 100G", f"{4 + seed_idx}", f"${(4 + seed_idx) * 189.00:,.2f}"),
]
y = 125
for sku, desc, qty, amt in rows:
draw.text((36, y), f"{sku} | {desc} | Qty: {qty} | Subtotal: {amt}", fill=(20, 20, 20))
y += 45
draw.line([36, 290, 600, 290], fill=(80, 80, 80), width=2)
draw.text((36, 315), f"Carrier: FreightLine-{seed_idx} Payment Terms: Net 45", fill=(30, 30, 30))
return img
def build_heldout_calibration_batches(processor: Any, tokenizer: Any, device: torch.device) -> list[dict[str, Any]]:
"""Construct 24 held-out text, JSON, tabular, typed-slot, and multimodal batches disjoint from evaluation."""
text_samples = [
"<|im_start|>system\nExtract structured procurement attributes as JSON.<|im_end|>\n<|im_start|>user\nVendor: Borealis Optics GmbH\nQuote: Q-77412\nCurrency: EUR\nLine 1: 12x DWDM Muxponders @ 4,150.00 EUR\nLine 2: 24x LC-LC Patch Cords @ 18.50 EUR\nValid Until: 2027-03-31<|im_end|>\n<|im_start|>assistant\n{\"vendor\":\"Borealis Optics GmbH\",\"currency\":\"EUR\"",
"<|im_start|>system\nRead telemetry snapshot and summarize anomalies.<|im_end|>\n<|im_start|>user\n{\"cluster\":\"fra-edge-09\",\"cpu_pct\":84.2,\"mem_gib\":191.4,\"drops_per_sec\":142,\"bgp_sessions\":[{\"peer\":\"AS64512\",\"state\":\"Established\"},{\"peer\":\"AS64519\",\"state\":\"Active\"}]}<|im_end|>\n<|im_start|>assistant\n{\"degraded_peer\":\"AS64519\"",
"<|im_start|>system\nExtract quarterly balance sheet items.<|im_end|>\n<|im_start|>user\nCash and equivalents: $412.8M | Accounts receivable: $189.3M | Deferred revenue: $94.1M | Long-term debt: $255.0M | Operating margin: 18.6%<|im_end|>\n<|im_start|>assistant\n{\"cash_musd\":412.8",
"<|im_start|>system\nParse clinical trial enrollment log.<|im_end|>\n<|im_start|>user\nSite 04 (Toronto): 38 screened, 29 randomized, 2 withdrawn. Protocol amendment v3.2 ratified on 2026-06-19. Primary endpoint: 12-week HbA1c delta.<|im_end|>\n<|im_start|>assistant\n{\"site\":\"Toronto\",\"randomized\":29",
"<|im_start|>system\nExtract maritime bill of lading details.<|im_end|>\n<|im_start|>user\nVessel: MV Baltic Horizon | Voyage: 418E | Port of Loading: Rotterdam | Port of Discharge: Yokohama | Containers: 4x 40HC Reefer (-18C) | Gross Weight: 98,420 kg<|im_end|>\n<|im_start|>assistant\n{\"vessel\":\"MV Baltic Horizon\"",
"<|im_start|>system\nEvaluate SLA credit eligibility.<|im_end|>\n<|im_start|>user\nOutage window: 2026-08-03T02:14:00Z to 2026-08-03T03:09:00Z (55 minutes). Monthly uptime commitment: 99.95% (max 21.6m downtime). Tier 1 credit = 10%, Tier 2 (>45m) = 25%.<|im_end|>\n<|im_start|>assistant\n{\"downtime_minutes\":55,\"credit_pct\":25",
# ClairicHead typed-slot style prompts containing `<|fim_pad|>` slot markers
"<|im_start|>user\nContext:\nHistorical monthly demand (units): [1240, 1310, 1295, 1420, 1510, 1585, 1620, 1710]\nLead time: 14 days. Unit landed cost: $68.40.\n\nFields:\nnext_month_demand: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|>\nsafety_stock_cost: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|><|im_end|>\n",
"<|im_start|>user\nContext:\n Ticket opened 2026-04-11 09:15 UTC, triaged 09:27 UTC, mitigated 11:02 UTC, resolved 14:45 UTC.\nHourly incident burn rate: $3,200/hr.\n\nFields:\ntime_to_mitigate: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|>\ntotal_incident_cost: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|><|im_end|>\n",
"<|im_start|>user\nContext:\n" + ("\n".join(f"Row {i:02d}: region=us-east-{i%4} reqs={1400+i*37} err_rate={0.001*(i%7):.4f} p99_ms={42.5+i*1.8:.1f}" for i in range(48))) + "\n\nFields:\npeak_p99_ms: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|>\ntotal_reqs: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|><|im_end|>\n",
"<|im_start|>system\nExtract multilingual support ticket fields.<|im_end|>\n<|im_start|>user\nCliente: Industrias Solís S.A. de C.V. | Prioridad: Alta | Módulo: Facturación CFDI 4.0 | Error reportado: Timbrado rechazado por código postal receptor.<|im_end|>\n<|im_start|>assistant\n{\"priority\":\"Alta\"",
"<|im_start|>system\nParse semiconductor wafer lot summary.<|im_end|>\n<|im_start|>user\nLot ID: WF-29981-B | Node: 5nm FinFET | Wafers started: 25 | Wafers yielded: 24 | Mean die yield: 88.4% | Parametric bin1: 81.2%<|im_end|>\n<|im_start|>assistant\n{\"lot_id\":\"WF-29981-B\",\"yield_pct\":88.4",
"<|im_start|>system\nExtract lease schedule terms.<|im_end|>\n<|im_start|>user\nPremises: Suite 1400, 52,000 RSF | Base Rent: $64.50/RSF/yr escalating 3.0% annually | Commencement: 2027-01-01 | Term: 84 months | TI Allowance: $95.00/RSF<|im_end|>\n<|im_start|>assistant\n{\"rsf\":52000,\"term_months\":84",
"<|im_start|>system\nParse renewable energy generation log.<|im_end|>\n<|im_start|>user\nSubstation: West-Mesa-230kV | Solar MWh: 1,842.6 | Wind MWh: 2,415.0 | BESS Charge MWh: 310.4 | BESS Discharge MWh: 289.1 | Curtailment: 44.2 MWh<|im_end|>\n<|im_start|>assistant\n{\"curtailment_mwh\":44.2",
"<|im_start|>system\nExtract software dependency advisory.<|im_end|>\n<|im_start|>user\nAdvisory: GHSA-992x-441p | Package: libquic- framing | Affected: >=2.1.0, <2.4.3 | Patched: 2.4.3 | CVSS v3.1: 8.2 (High)<|im_end|>\n<|im_start|>assistant\n{\"patched_version\":\"2.4.3\",\"cvss\":8.2",
"<|im_start|>system\nExtract aviation maintenance logbook entry.<|im_end|>\n<|im_start|>user\nTail: N784CF | Cycles: 11,428 | Hours: 29,104.5 | Inspection: C-Check Phase 2 | Replaced #2 IDG oil cooler seal P/N 77210-04; leak check normal.<|im_end|>\n<|im_start|>assistant\n{\"tail\":\"N784CF\",\"cycles\":11428",
"<|im_start|>system\nExtract warehouse cold-chain excursion report.<|im_end|>\n<|im_start|>user\nZone: Bay-C4 | Setpoint: 2.0C to 8.0C | Peak observed: 10.4C for 19 minutes during defrost cycle | Batch quarantined: false | Mean kinetic temp: 5.8C<|im_end|>\n<|im_start|>assistant\n{\"peak_c\":10.4,\"quarantined\":false",
"<|im_start|>user\nContext:\nCohort Q1ARR=$4.20M, gross churn=$0.18M, expansion=$0.63M.\nCohort Q2ARR=$4.65M, gross churn=$0.15M, expansion=$0.71M.\n\nFields:\nnet_dollar_retention: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|>\nq3_arr_forecast: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|><|im_end|>\n",
"<|im_start|>user\nContext:\nTransformer tap settings: Tap-1=13.8kV, Tap-2=13.455kV, Tap-3=13.11kV.\nMeasured secondary load: 412.0 A at 0.92 lagging power factor.\n\nFields:\napparent_power_kva: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|>\nreal_power_kw: <|fim_pad|><|fim_pad|><|fim_pad|><|fim_pad|><|im_end|>\n",
]
batches: list[dict[str, Any]] = []
for txt in text_samples:
enc = tokenizer(txt, return_tensors="pt")
batches.append(
{
"input_ids": enc["input_ids"].to(device),
"attention_mask": enc["attention_mask"].to(device),
}
)
# Add 6 multimodal image+text calibration samples
for i in range(6):
img = _make_heldout_calib_image(i)
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": img},
{
"type": "text",
"text": "Extract manifest number, carrier, payment terms, and line item subtotals as JSON.",
},
],
}
]
prompt_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
mm_inputs = processor(text=[prompt_text], images=[img], return_tensors="pt")
batch_dev: dict[str, Any] = {}
for k, v in mm_inputs.items():
if isinstance(v, torch.Tensor):
batch_dev[k] = v.to(device, dtype=torch.bfloat16 if v.is_floating_point() else None)
else:
batch_dev[k] = v
batches.append(batch_dev)
return batches
def copy_clairic_sidecars(src_dir: Path, dst_dir: Path) -> None:
for item in src_dir.iterdir():
if item.name in ("config.json", "model.safetensors.index.json", "hf_quant_config.json"):
continue
if item.name.startswith("model") and item.name.endswith(".safetensors"):
continue
if item.name == "__pycache__":
continue
target = dst_dir / item.name
if item.is_dir():
if target.exists():
shutil.rmtree(target)
shutil.copytree(item, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
else:
shutil.copy2(item, target)
def patch_exported_config_for_sglang(dst_dir: Path, num_layers: int = 64) -> None:
cfg_path = dst_dir / "config.json"
cfg = json.loads(cfg_path.read_text())
qcfg = cfg.get("quantization_config", {})
ignore = list(qcfg.get("ignore", []))
extra_ignores = [
"lm_head",
"model.embed_tokens",
"model.language_model.embed_tokens",
"model.visual*",
"visual*",
"mtp*",
]
for idx in range(num_layers):
extra_ignores.append(f"model.language_model.layers.{idx}.linear_attn.in_proj_ba")
for item in extra_ignores:
if item not in ignore:
ignore.append(item)
qcfg["ignore"] = ignore
cfg["quantization_config"] = qcfg
cfg_path.write_text(json.dumps(cfg, indent=2) + "\n")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--src-dir", default="/tmp/clairic")
ap.add_argument("--dst-dir", default="/tmp/clairic-nvfp4")
args = ap.parse_args()
src_dir = Path(args.src_dir).resolve()
dst_dir = Path(args.dst_dir).resolve()
if dst_dir.exists():
shutil.rmtree(dst_dir)
dst_dir.mkdir(parents=True, exist_ok=True)
import modelopt.torch.quantization as mtq
from modelopt.torch.export import export_hf_checkpoint
from transformers import AutoModelForImageTextToText, AutoProcessor, AutoTokenizer
device = torch.device("cuda")
t0 = time.perf_counter()
print(f"Loading BF16 model from {src_dir} onto {device} for ModelOpt NVFP4+FP8 PTQ...", flush=True)
tokenizer = AutoTokenizer.from_pretrained(src_dir, local_files_only=True)
processor = AutoProcessor.from_pretrained(src_dir, local_files_only=True)
model = AutoModelForImageTextToText.from_pretrained(
src_dir,
dtype=torch.bfloat16,
attn_implementation="sdpa",
local_files_only=True,
).to(device)
model.eval()
print(
f"Loaded model in {time.perf_counter()-t0:.1f}s | alloc={torch.cuda.memory_allocated()/(1024**3):.2f} GiB",
flush=True,
)
calib_batches = build_heldout_calibration_batches(processor, tokenizer, device)
quant_cfg = build_mixed_nvfp4_fp8_cfg()
def forward_loop(m: Any) -> None:
with torch.inference_mode():
for idx, batch in enumerate(calib_batches, start=1):
m(**batch, use_cache=False)
if idx % 6 == 0 or idx == len(calib_batches):
print(f" Calibrated {idx}/{len(calib_batches)} held-out batches...", flush=True)
t_q = time.perf_counter()
print("Running ModelOpt mixed NVFP4 + FP8 calibration...", flush=True)
# Keep Conv3d /Conv1d and ViT attention as native PyTorch modules (never quantized)
for cls_to_skip in (torch.nn.Conv3d, torch.nn.Conv2d, torch.nn.Conv1d, type(model.model.visual.blocks[0].attn)):
try:
mtq.QuantModuleRegistry.unregister(cls_to_skip)
except Exception:
pass
model = mtq.quantize(model, quant_cfg, forward_loop=forward_loop)
torch.cuda.synchronize()
print(f"Calibration finished in {time.perf_counter()-t_q:.1f}s. Exporting HF checkpoint to {dst_dir}...", flush=True)
t_exp = time.perf_counter()
with torch.inference_mode():
export_hf_checkpoint(
model,
dtype=torch.bfloat16,
export_dir=dst_dir,
max_shard_size="5GB",
)
patch_exported_config_for_sglang(dst_dir)
copy_clairic_sidecars(src_dir, dst_dir)
del model
gc.collect()
torch.cuda.empty_cache()
total_bytes = sum(p.stat().st_size for p in dst_dir.glob("*.safetensors"))
print(
f"Exported Mixed NVFP4+FP8 checkpoint in {time.perf_counter()-t_exp:.1f}s "
f"(total {time.perf_counter()-t0:.1f}s) | safetensors size = {total_bytes/(1024**3):.2f} GiB",
flush=True,
)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
18 kB
·
Xet hash:
2108f286ec097616bf9279ffb0dfc43cfb95bca7df84eb9c5acef36fc0a007d6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.