Download code/harness/n35_test.py from quocbao747/embedding-model-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness/n35_test.py
- Command line
-
hf download hf://quocbao747/embedding-model-benchmark/code/harness/n35_test.py
-
curl -L -o n35_test.py https://huggingface.co/quocbao747/embedding-model-benchmark/resolve/main/code/harness/n35_test.py
13.1 kB
| """Gate tests for Nemotron-3.5 (text path + NVFP4 W4A4 emulator). Usage: python n35_test.py <1b|8b> [out.json] | |
| Writes a JSON report. Runs on one GPU (CUDA_VISIBLE_DEVICES).""" | |
| import sys, json, time, gc, random | |
| import numpy as np, torch | |
| import torch.nn.functional as F | |
| import n35, data | |
| size = sys.argv[1] | |
| OUT = sys.argv[2] if len(sys.argv) > 2 else f"n35_test_{size}.json" | |
| BF = f"nvidia/Nemotron-3.5-Embed-{size.upper()}-BF16" | |
| FP4 = f"nvidia/Nemotron-3.5-Embed-{size.upper()}-NVFP4" | |
| OLD = f"nvidia/Nemotron-3-Embed-{size.upper()}-BF16" | |
| CARD_BF16 = {"1b": (0.457723, 0.112573), "8b": (0.587303, 0.247357)}[size] # card Transformers usage, text docs | |
| CARD_FP4 = {"1b": (0.466552, 0.104270), "8b": None}[size] # 8B NVFP4 card repeats the BF16 vLLM numbers | |
| Q = "What is NeMo Framework?" | |
| DOCS = ["NeMo Framework offers comprehensive functionalities for developing both LLMs and Multimodal Models.", | |
| "A biological foundation model designed to analyze and generate DNA, RNA, and protein sequences."] | |
| R = {"size": size, "ts": time.strftime("%Y-%m-%d %H:%M:%S")} | |
| rep = lambda k, v: (R.__setitem__(k, v), print(k, json.dumps(v)[:600], flush=True)) | |
| cos = lambda a, b: (a * b).sum(1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)) | |
| # ---------------- 1. input format: render() == chat template (string and token ids) on real benchmark texts | |
| from transformers import AutoProcessor, AutoTokenizer | |
| path = n35.local_path(BF) | |
| proc = AutoProcessor.from_pretrained(path); tok = AutoTokenizer.from_pretrained(path) | |
| texts = [Q] + DOCS | |
| for t in data.TIER1 + data.TIER2: | |
| c, qs, _ = data.load_task(t) | |
| texts += [data.doc_plain(d) for d in random.Random(0).sample(c, min(40, len(c)))] + [q["text"] for q in qs[:20]] | |
| texts += ["a [b] <c> [[x]] << >", "markdown | <td>[1]</td>"] | |
| bad_s = bad_i = 0 | |
| for i, t in enumerate(texts): | |
| for p in ("query:", "passage:"): | |
| conv = [{"role": "system", "content": p}, {"role": "user", "content": [{"type": "text", "text": t}]}] | |
| s = proc.apply_chat_template(conv, tokenize=False) | |
| bad_s += s != n35.render(p, t) | |
| if i < 300: | |
| ids = proc.apply_chat_template(conv, tokenize=True, return_dict=True)["input_ids"] | |
| ids = ids.tolist() if hasattr(ids, "tolist") else ids | |
| ids = ids[0] if isinstance(ids[0], list) else ids | |
| bad_i += list(ids) != tok(n35.render(p, t), add_special_tokens=False)["input_ids"] | |
| rep("format_check", {"n_texts": len(texts), "string_mismatch": bad_s, "token_mismatch_first300": bad_i, | |
| "example": n35.render("query:", "a [b] <c>"), "bos_added": tok("x")["input_ids"][:1]}) | |
| # ---------------- 2. LM weights vs Nemotron-3 (card: LM frozen -> identical text embeddings) | |
| from safetensors import safe_open | |
| import glob, os | |
| def tensors(p, pat): | |
| out = {} | |
| for f in sorted(glob.glob(os.path.join(p, "*.safetensors"))): | |
| with safe_open(f, "pt") as h: | |
| for k in h.keys(): | |
| if pat(k): | |
| out[k] = f | |
| return out | |
| try: | |
| op = n35.local_path(OLD) | |
| new = tensors(path, lambda k: "language_model" in k); old = tensors(op, lambda k: True) | |
| strip = lambda k: k.split("language_model.")[-1].replace("model.", "", 1) if "language_model" in k else k.replace("model.", "", 1) | |
| oldmap = {strip(k): (k, f) for k, f in old.items()} | |
| same = diff = missing = 0; diffs = {} | |
| for k, f in new.items(): | |
| sk = strip(k) | |
| if sk not in oldmap: | |
| missing += 1; continue | |
| with safe_open(f, "pt") as a, safe_open(oldmap[sk][1], "pt") as b: | |
| ta, tb = a.get_tensor(k), b.get_tensor(oldmap[sk][0]) | |
| same_t = torch.equal(ta, tb) | |
| if not same_t and ta.shape == tb.shape and ta.ndim == 2: | |
| rows = (ta != tb).any(1).nonzero().flatten().tolist() | |
| diffs[k] = {"rows_differing": len(rows), "row_ids": rows[:20], "tokens": tok.convert_ids_to_tokens(rows[:20])} | |
| same += same_t; diff += not same_t | |
| rep("lm_vs_nemotron3", {"identical": same, "different": diff, "unmatched": missing, "diffs": diffs}) | |
| except Exception as e: | |
| rep("lm_vs_nemotron3", {"error": repr(e)[:300]}) | |
| # ---------------- 3. card reference (literal card Transformers path, full model) vs our encoder, BF16 | |
| def card_embed(model, prefix, text): | |
| inp = proc.apply_chat_template([{"role": "system", "content": prefix}, {"role": "user", "content": [{"type": "text", "text": text}]}], | |
| tokenize=True, return_dict=True, return_tensors="pt").to("cuda") | |
| with torch.inference_mode(): | |
| h = model(**inp).last_hidden_state | |
| m = inp["attention_mask"].unsqueeze(-1) | |
| e = (h * m).sum(1) / m.sum(1) | |
| return F.normalize(e.float(), dim=-1).cpu().numpy() | |
| zalo, zq, _ = data.load_task("ZacLegalTextRetrieval") | |
| zdocs = [data.doc_plain(d) for d in zalo[:: len(zalo) // 500][:500]] | |
| full, _ = n35.load_model(BF, drop_vision=False) | |
| cq = card_embed(full, "query:", Q); cd = np.concatenate([card_embed(full, "passage:", d) for d in DOCS]) | |
| card_sims = (cq @ cd.T)[0] | |
| del full; gc.collect(); torch.cuda.empty_cache() | |
| enc = n35.Nemo35(BF, tok_budget=8192) | |
| q = enc.encode([Q], "query:"); d = enc.encode(DOCS, "passage:") | |
| ours = (q @ d.T)[0] | |
| rep("card_bf16", {"card": CARD_BF16, "card_path_here": card_sims.round(6).tolist(), "ours": ours.round(6).tolist(), | |
| "max_abs_vs_card": float(np.abs(ours - np.array(CARD_BF16)).max()), | |
| "cos_ours_vs_cardpath": cos(np.concatenate([q, d]), np.concatenate([cq, cd])).round(6).tolist()}) | |
| bf_card = np.concatenate([q, d]) | |
| bf_z = enc.encode(zdocs, "passage:") | |
| bf_zq = enc.encode([x["text"] for x in zq[:100]], "query:") | |
| del enc; gc.collect(); torch.cuda.empty_cache() | |
| # ---------------- 4. NVFP4 emulator | |
| # 4a. hand-written unpack vs library decompress, bit for bit, on every language-model layer | |
| from transformers import AutoModel, CompressedTensorsConfig | |
| fp4path = n35.local_path(FP4) | |
| lib = n35.load_lib(fp4path) | |
| lib.vision_tower = None; lib.multi_modal_projector = None; torch.cuda.empty_cache() # text-only reference: never used | |
| rep("global_scales_restored", lib.n_global_scales_restored) | |
| _ck = tensors(fp4path, lambda k: k.endswith(("weight_packed", "weight_scale", "weight_global_scale", "input_global_scale")) and "language_model" in k) | |
| _pm = dict(lib.named_parameters()); _pm.update(dict(lib.named_buffers())); _nb = 0 | |
| for k, f in _ck.items(): | |
| with safe_open(f, "pt") as h: | |
| ct = h.get_tensor(k); p = _pm[k[len("model."):] if k.startswith("model.") and k not in _pm else k] | |
| _nb += not torch.equal(p.data.cpu().reshape(ct.shape).view(torch.uint8) if ct.dtype != p.dtype and ct.dtype == torch.uint8 else p.data.cpu().reshape(ct.shape).to(ct.dtype), ct) | |
| rep("loaded_params_equal_checkpoint", {"checked": len(_ck), "not_equal": _nb}) | |
| packed = [(n, m) for n, m in lib.named_modules() if hasattr(m, "weight_packed") and "language_model" in n] | |
| ex = packed[0][1] | |
| rep("checkpoint_scheme", {"n_packed_text_linears": len(packed), "example": packed[0][0], | |
| "weight_packed": [str(ex.weight_packed.dtype), list(ex.weight_packed.shape)], | |
| "weight_scale": [str(ex.weight_scale.dtype), list(ex.weight_scale.shape)], | |
| "weight_global_scale": float(ex.weight_global_scale), "input_global_scale": float(ex.input_global_scale), | |
| "input_args": ex.quantization_scheme.input_activations.model_dump(mode="json"), | |
| "status": str(ex.quantization_status)}) | |
| nbad = 0; maxd = 0.0 | |
| for n, m in packed: | |
| a = n35.fast_unpack(m.weight_packed.data, m.weight_scale.data, m.weight_global_scale.data) | |
| b = n35.lib_unpack(m.weight_packed.data, m.weight_scale.data, m.weight_global_scale.data, m.quantization_scheme) | |
| nbad += not torch.equal(a, b); maxd = max(maxd, float((a.float() - b.float()).abs().max())) | |
| del a, b | |
| rep("unpack_bitexact", {"layers": len(packed), "not_equal": nbad, "max_abs_diff": maxd}) | |
| # 4b. one real layer: EmuLinear vs the library's own quantized module forward on real activations | |
| cap = {} | |
| name0, mod0 = packed[0] | |
| h = mod0.register_forward_pre_hook(lambda mod, inp: cap.__setitem__("x", inp[0].detach().clone())) | |
| emu_tmp = n35.EmuLinear(mod0, mode="packed") # built before the library decompresses the module | |
| emu_noact = n35.EmuLinear(mod0, mode="packed", act_quant=False) | |
| ref_ids = [x[:512] for x in tok([n35.render("passage:", t) for t in zdocs[:8]], add_special_tokens=False)["input_ids"]] | |
| Lm = max(len(x) for x in ref_ids) | |
| X = torch.full((8, Lm), 11, dtype=torch.long); M = torch.zeros((8, Lm), dtype=torch.long) | |
| for r, x in enumerate(ref_ids): | |
| X[r, :len(x)] = torch.tensor(x); M[r, :len(x)] = 1 | |
| with torch.inference_mode(): | |
| lib(input_ids=X.cuda(), attention_mask=M.cuda()) # first forward: library decompresses + runs its QDQ forward | |
| h.remove() | |
| x = cap["x"] | |
| with torch.inference_mode(): | |
| y_lib = mod0(x); y_emu = emu_tmp(x); y_w = emu_noact(x) | |
| from compressed_tensors.quantization.lifecycle.forward import forward_quantize | |
| xq_lib = forward_quantize(mod0, x, "input", mod0.quantization_scheme.input_activations) | |
| rel = lambda a, b: float((a.float() - b.float()).norm() / b.float().norm()) | |
| rep("layer_check", {"layer": name0, "lib_status_after_forward": str(mod0.quantization_status), | |
| "rel_emu_vs_lib": rel(y_emu, y_lib), "equal": bool(torch.equal(y_emu, y_lib)), | |
| "rel_weightonly_vs_lib": rel(y_w, y_lib), "rel_xq_vs_x": rel(xq_lib, x), | |
| "frac_x_changed_by_qdq": float((xq_lib != x).float().mean()), "xq_equal_emu_internal": bool(torch.equal(forward_quantize(mod0, x, "input", mod0.quantization_scheme.input_activations), xq_lib))}) | |
| del emu_tmp, emu_noact | |
| # 4c. whole model: library reference (decompressed + library QDQ forward) on card examples + 500 Zalo docs | |
| def lib_encode(model, texts, prefix, bs=16): | |
| ids = [x[:512] for x in tok([n35.render(prefix, t) for t in texts], add_special_tokens=False)["input_ids"]] | |
| out = [] | |
| for i in range(0, len(ids), bs): | |
| b = ids[i:i + bs]; L = max(len(x) for x in b) | |
| X = torch.full((len(b), L), 11, dtype=torch.long); M = torch.zeros((len(b), L), dtype=torch.long) | |
| for r, x in enumerate(b): | |
| X[r, :len(x)] = torch.tensor(x); M[r, :len(x)] = 1 | |
| with torch.inference_mode(): | |
| hh = model(input_ids=X.cuda(), attention_mask=M.cuda()).last_hidden_state | |
| mk = M.cuda().unsqueeze(-1).to(hh.dtype) | |
| out.append(F.normalize(((hh * mk).sum(1) / mk.sum(1)).float(), dim=-1).cpu().numpy()) | |
| return np.concatenate(out) | |
| lib_card = np.concatenate([lib_encode(lib, [Q], "query:"), lib_encode(lib, DOCS, "passage:")]) | |
| lib_z = lib_encode(lib, zdocs[:100], "passage:", bs=8) | |
| del lib, packed, mod0, ex, _pm, _ck, cap, x, y_lib, y_emu, y_w, xq_lib, h, p | |
| gc.collect(); torch.cuda.empty_cache(); print("mem after lib free GiB", torch.cuda.memory_allocated() / 2**30, flush=True) | |
| res = {} | |
| for mode in ("cache", "packed"): | |
| for act in (True, False): | |
| if mode == "packed" and not act: | |
| continue | |
| enc = n35.Nemo35(FP4, fp4=True, mode=mode, act_quant=act, tok_budget=8192) | |
| # same batching as lib_encode for the bit-level comparison | |
| e_card = np.concatenate([lib_encode(enc.m, [Q], "query:"), lib_encode(enc.m, DOCS, "passage:")]) | |
| e_z100 = lib_encode(enc.m, zdocs[:100], "passage:", bs=8) | |
| r = {"n_emulated": enc.m.n_emulated, | |
| "card_sims": (e_card[:1] @ e_card[1:].T)[0].round(6).tolist(), | |
| "maxrel_vs_lib_card": float(np.abs(e_card - lib_card).max() / np.abs(lib_card).max()), | |
| "maxrel_vs_lib_zalo100": float(np.abs(e_z100 - lib_z).max() / np.abs(lib_z).max()), | |
| "exact_vs_lib_zalo100": bool(np.array_equal(e_z100, lib_z)), | |
| "peak_alloc_gib": torch.cuda.max_memory_allocated() / 2**30} | |
| if act: | |
| t = time.time(); z = enc.encode(zdocs, "passage:"); zq2 = enc.encode([x["text"] for x in zq[:100]], "query:") | |
| r["zalo500_s"] = time.time() - t | |
| r["cos_vs_bf16_card_mean"] = float(cos(e_card, bf_card).mean()) | |
| r["cos_vs_bf16_card_min"] = float(cos(e_card, bf_card).min()) | |
| r["cos_vs_bf16_zalo500_mean"] = float(cos(z, bf_z).mean()) | |
| r["cos_vs_bf16_zalo500_min"] = float(cos(z, bf_z).min()) | |
| r["cos_vs_bf16_zaloq100_mean"] = float(cos(zq2, bf_zq).mean()) | |
| r["card_fp4"] = CARD_FP4 | |
| if mode == "cache": | |
| np.save(f"n35_emu_card_{size}.npy", e_card) | |
| else: | |
| r["cos_weightonly_vs_w4a4_card"] = float(cos(e_card, lib_card).mean()) | |
| r["maxabs_weightonly_vs_lib_zalo100"] = float(np.abs(e_z100 - lib_z).max()) | |
| res[f"{mode}{'' if act else '_weightonly'}"] = r | |
| print(mode, act, json.dumps(r), flush=True) | |
| del enc; gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats() | |
| rep("emulator", res) | |
| json.dump(R, open(OUT, "w"), indent=1) | |
| print("TEST_DONE", OUT) | |