File size: 10,216 Bytes
780df29 | 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 | """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"]]
@torch.inference_mode()
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]))
|