Download engine/tests/test_nvfp4_standalone.py from decisionmodels/REAX-1.4: direct link, hf CLI and curl.
- Browser
- Download file 4.16 kB
-
https://huggingface.co/decisionmodels/REAX-1.4/resolve/main/engine/tests/test_nvfp4_standalone.py
- Command line
-
hf download hf://decisionmodels/REAX-1.4/engine/tests/test_nvfp4_standalone.py
-
curl -L -o test_nvfp4_standalone.py https://huggingface.co/decisionmodels/REAX-1.4/resolve/main/engine/tests/test_nvfp4_standalone.py
4.16 kB
| # SPDX-License-Identifier: MIT | |
| """Standalone NVFP4 load (karpo_packed.load_text_cpu, REAX 1.4 release): a tiny random Gemma-4 saved (a) in the karpo BF16 layout and | |
| (b) in the compressed-tensors NVFP4 layout (model.language_model.* keys, projections only as weight_packed/...). The standalone | |
| load of (b) equals the load of (a) on every non-projection tensor and buffer; a missing non-projection tensor is refused.""" | |
| import json, tempfile | |
| from pathlib import Path | |
| import pytest | |
| torch = pytest.importorskip("torch") | |
| pytest.importorskip("transformers") | |
| pytest.importorskip("accelerate") | |
| from safetensors.torch import save_file | |
| def test_standalone_nvfp4_load_equals_bf16_layout(): | |
| from transformers import Gemma4Config | |
| from transformers.models.gemma4.modeling_gemma4 import Gemma4TextModel | |
| from engine.backends.karpo_packed import load_text_cpu | |
| torch.manual_seed(0) | |
| cfg = Gemma4Config(text_config=dict(vocab_size=512, hidden_size=64, intermediate_size=128, num_hidden_layers=4, num_attention_heads=2, | |
| num_key_value_heads=1, head_dim=32, global_head_dim=64, sliding_window=16, | |
| layer_types=["sliding_attention", "sliding_attention", "sliding_attention", "full_attention"], | |
| hidden_size_per_layer_input=0, num_kv_shared_layers=0)) | |
| tc = cfg.get_text_config() | |
| m = Gemma4TextModel(tc).to(torch.bfloat16) | |
| with torch.no_grad(): | |
| for p in m.parameters(): p.normal_() | |
| sd = {k: v.contiguous() for k, v in m.state_dict().items()} | |
| names = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj") | |
| isproj = lambda k: k.startswith("layers.") and k.split(".")[-2] in names and k.endswith(".weight") | |
| root = Path(tempfile.mkdtemp()) | |
| a, b = root / "bf16", root / "nv4"; a.mkdir(); b.mkdir() | |
| save_file({f"language_model.{k}": v for k, v in sd.items()}, str(a / "model.safetensors")) | |
| cj = cfg.to_dict(); json.dump(cj, open(a / "config.json", "w")) | |
| nvsd = {} | |
| for k, v in sd.items(): | |
| if isproj(k): | |
| base = f"model.language_model.{k[:-len('.weight')]}" | |
| n, kk = v.shape | |
| nvsd[base + ".weight_packed"] = torch.zeros(n, kk // 2, dtype=torch.uint8) | |
| nvsd[base + ".weight_scale"] = torch.zeros(n, kk // 16, dtype=torch.float8_e4m3fn) | |
| nvsd[base + ".weight_global_scale"] = torch.ones(1, dtype=torch.float32) | |
| nvsd[base + ".input_global_scale"] = torch.ones(1, dtype=torch.float32) | |
| else: | |
| nvsd[f"model.language_model.{k}"] = v | |
| nvsd["model.embed_vision.embedding_projection.weight"] = torch.zeros(64, 8, dtype=torch.bfloat16) | |
| save_file(nvsd, str(b / "model.safetensors")) | |
| cj2 = dict(cj); cj2["quantization_config"] = {"quant_method": "compressed-tensors", "format": "nvfp4-pack-quantized", | |
| "config_groups": {"group_0": {"targets": ["Linear"], "weights": {"num_bits": 4, "group_size": 16, "type": "float"}, | |
| "input_activations": {"num_bits": 4, "group_size": 16, "type": "float", "dynamic": "local"}}}, | |
| "ignore": ["lm_head"]} | |
| json.dump(cj2, open(b / "config.json", "w")) | |
| ma = load_text_cpu(a, torch.bfloat16, "sdpa", False, names) | |
| mb = load_text_cpu(b, torch.bfloat16, "sdpa", True, names) | |
| sa, sb = ma.state_dict(), mb.state_dict() | |
| assert set(sa) == set(sb), set(sa) ^ set(sb) | |
| neq = [k for k in sa if not isproj(k) and not torch.equal(sa[k], sb[k])] | |
| bufa = {k: v for k, v in ma.named_buffers()}; bufb = {k: v for k, v in mb.named_buffers()} | |
| assert bufa.keys() == bufb.keys() and all(torch.equal(bufa[k], bufb[k]) for k in bufa) | |
| assert not neq | |
| # the frozen path refuses a missing non-projection tensor; standalone too: | |
| bad = {k: v for k, v in nvsd.items() if not k.endswith("layers.1.input_layernorm.weight")} | |
| save_file(bad, str(b / "model.safetensors")) | |
| try: | |
| load_text_cpu(b, torch.bfloat16, "sdpa", True, names) | |
| raise AssertionError("missing norm accepted") | |
| except ValueError as e: | |
| assert "layers.1.input_layernorm.weight" in str(e) | |