Download code/harness/n35.py from quocbao747/embedding-model-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness/n35.py
- Command line
-
hf download hf://quocbao747/embedding-model-benchmark/code/harness/n35.py
-
curl -L -o n35.py https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness/n35.py
10.2 kB
| """Nemotron-3.5-Embed text-only encoder (card's Transformers path) + faithful NVFP4 W4A4 emulation. | |
| Input format (card "Transformers Usage" + chat_template.jinja "nemo-mistral-retrieval-v1"): | |
| processor.apply_chat_template([{"role":"system","content":"query:"|"passage:"},{"role":"user","content":[{"type":"text","text":t}]}], | |
| tokenize=True) -> "<prefix.rstrip(' ')> " + t with "[" -> "[" and "<" -> "<"; no BOS/EOS. | |
| mean pooling over attention_mask (prompt tokens included), L2 normalize. Bidirectional (config is_causal=false). | |
| render() reproduces the template string; it is checked against apply_chat_template in n35_test.py. | |
| NVFP4 (compressed-tensors "nvfp4-pack-quantized", W4A4) on GPUs without FP4 tensor cores: | |
| The checkpoint is loaded by transformers' compressed-tensors integration (weights stay packed: weight_packed uint8, | |
| weight_scale fp8-e4m3 per 16, weight_global_scale, input_global_scale). Each packed Linear is then replaced by EmuLinear: | |
| input : compressed_tensors.quantization.lifecycle.forward.forward_quantize(self, x, "input", scheme.input_activations) | |
| (library code: dynamic local per-16 FP8 scales x static input_global_scale, FP4 E2M1 round-to-nearest-even, dequant) | |
| weight: NVFP4PackedCompressor.decompress (library) -> bf16, either cached once ("cache", ~15 GiB for 8B) | |
| or re-done per forward from the packed tensors ("packed", when memory is short); fast_unpack() is a hand-written | |
| LUT version used for "packed" and is tested bit-for-bit against the library. | |
| y = F.linear(x_qdq, W_dq) (bf16 matmul, fp32 accumulation) | |
| """ | |
| import os, math | |
| import numpy as np, torch | |
| import torch.nn.functional as F | |
| BF16 = torch.bfloat16 | |
| def render(prefix, text): | |
| t = text.replace("[", "[").replace("<", "<") | |
| return prefix.rstrip(" ") + " " + t | |
| def local_path(repo): | |
| from huggingface_hub import snapshot_download | |
| return snapshot_download(repo, local_files_only=True) | |
| # ---------------------------------------------------------------- NVFP4 emulation | |
| _LUT = {} | |
| def _lut(device): | |
| """256 x 2 table: byte -> (low-nibble value, high-nibble value), same order as compressed_tensors unpack_fp4_from_uint8.""" | |
| if device not in _LUT: | |
| from compressed_tensors.compressors.nvfp4.helpers import kE2M1ToFloat | |
| b = torch.arange(256) | |
| nib = torch.stack((b & 0x0F, (b & 0xF0) >> 4), 1) | |
| v = kE2M1ToFloat[nib & 0x07] * torch.where((nib & 0x08).bool(), -1.0, 1.0) | |
| _LUT[device] = v.to(BF16).to(device) # values are exactly representable in bf16 | |
| return _LUT[device] | |
| def fast_unpack(packed, scale_fp8, global_scale): | |
| """Hand-written equivalent of NVFP4PackedCompressor.decompress(...)['weight'] (bf16).""" | |
| m, n2 = packed.shape | |
| q = _lut(packed.device)[packed.long()].reshape(m, n2 * 2) # bf16 fp4 values | |
| s = scale_fp8.to(BF16) # _decompress_scale(scale, unpacked.dtype) | |
| s = s / global_scale # _dequantize: scale = scale / global_scale (bf16 / fp32 -> fp32) | |
| out = q.unflatten(-1, (s.shape[1], -1)).to(s.dtype) * s.unsqueeze(-1) | |
| return out.flatten(-2).to(BF16) | |
| def lib_unpack(packed, scale_fp8, global_scale, scheme): | |
| from compressed_tensors.compressors.nvfp4 import NVFP4PackedCompressor | |
| sd = NVFP4PackedCompressor.decompress({"weight_packed": packed, "weight_scale": scale_fp8, "weight_global_scale": global_scale}, scheme) | |
| return sd["weight"] | |
| class EmuLinear(torch.nn.Module): | |
| def __init__(self, src, mode="cache", act_quant=True): | |
| super().__init__() | |
| from compressed_tensors.quantization import QuantizationStatus | |
| self.in_features, self.out_features = src.in_features, src.out_features | |
| self.quantization_scheme = src.quantization_scheme | |
| self.quantization_status = QuantizationStatus.FROZEN # weight already quantized: forward_quantize only touches inputs | |
| self.register_buffer("input_global_scale", src.input_global_scale.data.clone(), persistent=False) | |
| self.mode, self.act_quant = mode, act_quant | |
| self.bias = None if getattr(src, "bias", None) is None else src.bias | |
| p, s, g = src.weight_packed.data, src.weight_scale.data, src.weight_global_scale.data | |
| if mode == "cache": | |
| self.register_buffer("w", lib_unpack(p, s, g, self.quantization_scheme), persistent=False) | |
| else: | |
| self.register_buffer("p", p, persistent=False); self.register_buffer("s", s, persistent=False) | |
| self.register_buffer("g", g, persistent=False) | |
| def weight_dq(self): | |
| return self.w if self.mode == "cache" else fast_unpack(self.p, self.s, self.g) | |
| def forward(self, x): | |
| if self.act_quant: | |
| from compressed_tensors.quantization.lifecycle.forward import forward_quantize | |
| x = forward_quantize(self, x, "input", self.quantization_scheme.input_activations) | |
| return F.linear(x, self.weight_dq(), self.bias) | |
| def emulate(model, mode="cache", act_quant=True, only_text=True): | |
| """Swap every packed NVFP4 Linear (language model only by default) for EmuLinear. Returns the count.""" | |
| targets = [] | |
| for name, mod in model.named_modules(): | |
| if hasattr(mod, "weight_packed") and getattr(mod, "quantization_scheme", None) is not None: | |
| if only_text and "language_model" not in name: | |
| continue | |
| targets.append(name) | |
| for name in targets: | |
| parent, _, child = name.rpartition(".") | |
| pm = model.get_submodule(parent) | |
| src = getattr(pm, child) | |
| setattr(pm, child, EmuLinear(src, mode=mode, act_quant=act_quant)) | |
| del src | |
| torch.cuda.empty_cache() | |
| return len(targets) | |
| def fix_global_scales(m, path): | |
| """transformers 5.25 + compressed-tensors 0.17 allocate weight/input_global_scale as shape [1] while the checkpoint stores | |
| scalars, so the loader re-initialises them (reported as MISMATCH). Copy every one back from the safetensors files and verify.""" | |
| import glob | |
| from safetensors import safe_open | |
| params = dict(m.named_parameters()); params.update(dict(m.named_buffers())) | |
| n = 0 | |
| for f in sorted(glob.glob(os.path.join(path, "*.safetensors"))): | |
| with safe_open(f, "pt") as h: | |
| for k in h.keys(): | |
| if not k.endswith(("weight_global_scale", "input_global_scale")): | |
| continue | |
| name = k[len("model."):] if k.startswith("model.") and k not in params else k | |
| p = params[name] | |
| v = h.get_tensor(k).to(p.dtype).reshape(p.shape).to(p.device) | |
| p.data.copy_(v) | |
| assert torch.equal(p.data.cpu(), h.get_tensor(k).to(p.dtype).reshape(p.shape)) | |
| n += 1 | |
| return n | |
| def load_lib(path, device="cuda"): | |
| """Library reference load: transformers' compressed-tensors integration, weights left packed (dequantize=False).""" | |
| from transformers import AutoModel, CompressedTensorsConfig | |
| m = AutoModel.from_pretrained(path, dtype=BF16, attn_implementation="sdpa", device_map={"": device}, use_kernels=False, | |
| quantization_config=CompressedTensorsConfig(dequantize=False), ignore_mismatched_sizes=True).eval() | |
| m.n_global_scales_restored = fix_global_scales(m, path) | |
| return m | |
| def load_model(repo, fp4=False, mode="cache", act_quant=True, device="cuda", drop_vision=True): | |
| from transformers import AutoModel | |
| path = local_path(repo) | |
| if fp4: | |
| m = load_lib(path, device) | |
| else: | |
| m = AutoModel.from_pretrained(path, dtype=BF16, attn_implementation="sdpa", device_map={"": device}, use_kernels=False).eval() | |
| if fp4: | |
| if hasattr(m, "ct_decompress_hook"): # library would decompress the whole model on the first forward | |
| m.ct_decompress_hook.remove(); del m.ct_decompress_hook | |
| n = emulate(m, mode=mode, act_quant=act_quant) | |
| assert n > 0, "no packed NVFP4 linears found" | |
| m.n_emulated = n | |
| if drop_vision: # text-only inputs never reach the vision tower / projector (no pixel_values) | |
| for a in ("vision_tower", "multi_modal_projector"): | |
| if hasattr(m, a): | |
| setattr(m, a, None) | |
| torch.cuda.empty_cache() | |
| return m, path | |
| class Nemo35: | |
| """Card-format text encoder. encode(texts, prefix) -> L2-normalised fp32 numpy [n, d].""" | |
| def __init__(self, repo, fp4=False, mode="cache", max_len=512, tok_budget=16384, device="cuda", act_quant=True): | |
| from transformers import AutoTokenizer | |
| self.m, path = load_model(repo, fp4=fp4, mode=mode, device=device, act_quant=act_quant) | |
| self.tok = AutoTokenizer.from_pretrained(path) | |
| self.max_len, self.tok_budget, self.device = max_len, tok_budget, device | |
| self.pad = self.tok.pad_token_id if self.tok.pad_token_id is not None else 11 | |
| def ids(self, texts): | |
| return [x[: self.max_len] for x in self.tok(texts, add_special_tokens=False)["input_ids"]] | |
| def encode_ids(self, ids): | |
| order = np.argsort([-len(x) for x in ids], kind="stable") | |
| out = [None] * len(ids) | |
| i = 0 | |
| while i < len(order): | |
| L = len(ids[order[i]]) | |
| n = int(os.environ["N35_FIXED_BS"]) if os.environ.get("N35_FIXED_BS") else max(1, min(256, self.tok_budget // max(L, 1))) # fixed docs/batch (unified speed run) | |
| idx = order[i:i + n]; i += n | |
| X = torch.full((len(idx), L), self.pad, dtype=torch.long) | |
| M = torch.zeros((len(idx), L), dtype=torch.long) | |
| for r, j in enumerate(idx): | |
| X[r, :len(ids[j])] = torch.tensor(ids[j]); M[r, :len(ids[j])] = 1 | |
| X, M = X.to(self.device), M.to(self.device) | |
| h = self.m(input_ids=X, attention_mask=M).last_hidden_state | |
| mk = M.unsqueeze(-1).to(h.dtype) | |
| e = (h * mk).sum(1) / mk.sum(1) | |
| e = F.normalize(e.float(), dim=-1).cpu().numpy() | |
| for r, j in enumerate(idx): | |
| out[j] = e[r] | |
| return np.stack(out).astype(np.float32) | |
| def encode(self, texts, prefix): | |
| return self.encode_ids(self.ids([render(prefix, t) for t in texts])) | |