[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-111273":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":13,"stars7d":15,"stars30d":16,"stars90d":14,"forks30d":14,"starsTrendScore":17,"compositeScore":18,"rankGlobal":9,"rankLanguage":9,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":9,"pushedAt":38,"updatedAt":39,"readmeContent":40,"aiSummary":41,"trendingCount":14,"starSnapshotCount":14,"syncStatus":42,"lastSyncTime":43,"discoverSource":44},111273,"sm120-nvfp4-training","xl03-bit\u002Fsm120-nvfp4-training","xl03-bit","Faster, more memory-efficient NVFP4 training",null,"Python",117,13,1,0,15,54,8,58.34,"MIT License",false,"main",true,[24,25,26,27,28,29,30,31,32,33,34,35,36,37],"ai","ai-training","blackwell","cuda","deep-learning","fp4","gpu","graphics-card","low-precision-training","model-training","nvfp4","pytorch","sm120","triton","2026-11-13 04:26:48","2026-11-22 16:10:43","# SM120 NVFP4 Training\n\n**GeForce RTX 50-series cards and the RTX PRO 6000 Blackwell have native FP4 Tensor Cores, but NVIDIA Transformer Engine does not offer its full NVFP4 training recipe on these SM120 GPUs.** Its supported NVFP4 training path on this hardware requires disabling stochastic rounding and random Hadamard transforms. [NVIDIA hardware support matrix](https:\u002F\u002Fnvidia.github.io\u002FTransformerEngine\u002Fsupport_matrix.html)\n\nI built this open-source PyTorch package on [Infatoshi\u002Fnvfp4-sm120](https:\u002F\u002Fgithub.com\u002FInfatoshi\u002Fnvfp4-sm120) to make NVFP4 training accessible on these cards. It implements both operations in software and uses the FP4 Tensor Cores for forward and backward matrix multiplies. Six training profiles let you choose how much memory to spend on weights and AdamW state.\n\n## What does this mean?\n\nConsumer GPUs can put their FP4 compute to work during training. Workloads dominated by large matrix multiplies stand to benefit most. When GPU memory is the limit, storing weights and optimizer state more compactly can make room for a larger model on the same card.\n\nAs a rough illustration, the first three targets below compare NVFP4 on the smaller card with BF16 on the larger card, for the same model and batch shape. The fourth compares the size of model that fits in memory.\n\n- An **RTX 5060** could approach **RTX 5080** training throughput.\n- An **RTX 5080** could approach **RTX 5090** training throughput.\n- An **RTX 5090** could approach **RTX PRO 6000 Blackwell** training throughput.\n- **One RTX PRO 6000 Blackwell** using a compact NVFP4 profile could fit a model that would otherwise need **two such GPUs** for BF16 training.\n\nThese are illustrative hardware targets. The [measurements below](#406b-full-parameter-run) come from one RTX 5060 Ti and show model capacity, throughput and training progress.\n\n## Install and verify\n\nUse an existing Linux or WSL Python with the verified dependencies. The tested stack uses Python 3.10, PyTorch 2.11.0+cu130, TorchAO 0.17.0, Triton 3.6.0, NumPy, Ninja, a compatible NVIDIA driver, CUDA Toolkit 13.0 with nvcc and a C++ compiler. If CUDA discovery fails, set `CUDA_HOME` to the local toolkit directory before starting Python. The install command below adds the package while preserving the installed training dependencies.\n\n```bash\npython -m pip install --no-deps .\npython -m nvfp4_training list\npython -m nvfp4_training verify\npython -m nvfp4_training check\npython examples\u002Ftrain.py --profile balanced\n```\n\n`verify` compiles the CUDA extensions and checks quantization against a separately built reference, paired gradients, stochastic-rounding statistics and continuous updates. It records the accepted backward modes in the user's cache. Re-run after a fingerprint or device change. `check` exercises each profile with aligned\u002Fpadded shapes, eager\u002Fgraph execution, transpose recomputation and checkpoint recovery. No dataset is needed for these commands.\n\n## Use in a training loop\n\nFor frozen backbones used in inference or differentiable objectives, an opt-in\n[frozen-weight path](docs\u002Ffrozen.md) packs weights once, supports checked disk\ncaches and captures forward\u002Fbackward with replay-safe stochastic rounding.\nThe guide explains the problem, solution, supported workloads and integration steps.\nThe existing six profiles below remain the path for trainable base weights.\n\n```python\nimport torch\nfrom torch import nn\nfrom nvfp4_training import enable_nvfp4, train_step, check_finite\n\nmodel = enable_nvfp4(nn.Linear(257, 193), profile=\"balanced\")\nx = torch.randn(2, 64, 257, device=\"cuda\")\ny = torch.randn(2, 64, 193, device=\"cuda\")\n\ndef objective(model, x, y):\n    return (model(x).float() - y).square().mean()\n\nloss = train_step(model, objective, x, y)\ncheck_finite(model)\n```\n\nStart with a fresh trainable FP32 model with ordinary `nn.Linear` layers on one device. The converter attaches the matching AdamW as `model.nvfp4_optimizer`. For fixed shapes, use `with capture_step(model, objective, x, y, steps=N) as graph:` and call `graph.step(next_x, next_y)` once per real update. An eager step can precede capture. After closing the graph, use `save_checkpoint(path, model)` and restore with `load_checkpoint(path, fresh_converted_model)`. Save the sampler position separately. Global gradient clipping, cross-step accumulation, distributed training and custom Linear subclasses need their own integration. The FP8-master profile requires one deferred weight-gradient contribution per compressed projection per backward.\n\n## LoRA and unchanged-precision adaptation\n\n`prepare_lora` trains both low-rank matrices while freezing the base. Choose\n`mode=\"preserve\"` to retain the model's FP32, BF16 or FP16 weights unchanged, or\n`mode=\"nvfp4\"` to prepack frozen projections for native FP4 GEMMs with SR and RHT.\nBoth use FP32 adapters and ordinary AdamW. Optional block checkpointing reduces\nactivation memory, and CUDA Graph replay reduces launch overhead for fixed shapes.\n\nFor already quantized NVFP4 checkpoints, `mode=\"packed_nvfp4\"` preserves the source\nweight payload and offers GPU recomputation or caching of the backward layout.\nSee [packed NVFP4 LoRA](docs\u002FPACKED_NVFP4.md) for formats, tested compatibility and\nmemory choices. This new mode uses eager training; the existing modes keep their\nCUDA Graph support.\n\n```python\nfrom nvfp4_training import prepare_lora\nmodel, optimizer = prepare_lora(model, mode=\"preserve\", rank=16, alpha=16)\n# Use the normal loss.backward() \u002F optimizer.step() loop.\n```\n\nThe unchanged-precision implementation is also available independently as\n`precision_lora`, with only PyTorch as a dependency. See the [LoRA API guide](docs\u002FLORA.md)\nfor target selection, save\u002Fload, merging, independent packaging and examples.\nThe [LoRA measurements](results\u002Flora\u002FREADME.md) include three workload shapes and\n512 FineWeb updates of a real pretrained GPT-2, with matched data and loss curves.\n\n### Image-model LoRA on a 16 GB GPU\n\n**FLUX.2 Klein Base 4B completed 1,000 NVFP4 LoRA updates at 1024px.** In the matched\n40-update benchmark, native NVFP4 reduced full update time from **3.405 to 2.306 s**\nand peak allocated memory from **9.516 to 6.626 GiB**. The memory-saving recompute\noption took **2.360 s** and **4.669 GiB**—about half the BF16 training allocation.\nAll modes used the same data, rank, optimizer, checkpointing and attention backend.\n\n**Training reference — one of the four photographs used to learn this toy:**\n\n\u003Cimg src=\"results\u002Flora-image\u002Freference\u002Fmonster-toy-00.jpg\" alt=\"Original training photograph of the red monster toy, showing its raised eyes, yellow hair and belly, and four rope limbs\" width=\"280\">\n\nPhoto by Varun Jampani, Google DreamBooth, CC BY 4.0.\n[Original image, source and license](results\u002Flora-image\u002Freference\u002FREADME.md).\n\n**Generated beach scene after 100, 200, 300, 500 and 1000 updates:**\n\n![Subject learning after 100, 200, 300, 500 and 1000 updates](results\u002Flora-image\u002Fbeach-progress.png)\n\nSee the [image\u002FH3 experiment report](results\u002Flora-image\u002FREADME.md) for loss and memory\ncurves, numerical checks, optimization history and the scope of the H3 tests.\nThe [H3 single-frame example](examples\u002Fminimax_h3_single_frame\u002FREADME.md) includes\nthe scripts and recorded configuration of the completed 200-step LoRA experiment.\nThe [FLUX.2 example](examples\u002Fflux2_klein\u002FREADME.md) includes training, inference,\nadapter export and the matched benchmark. These additions leave the six\nfull-parameter profiles and the existing frozen-weight interfaces unchanged.\n\n## Measurements on one RTX 5060 Ti\n\nComplete forward, loss, backward and AdamW update, 12 warmup steps and five rounds of 30 synchronized steps. Peak memory is PyTorch allocated GiB, measured from initialization through training. The table uses the original, pre-fix implementation and disables transpose recomputation. Per-round timings and three recomputation variants are in [the results](results\u002Fbenchmarks.json).\n\n| Profile | Master \u002F moments | 453M, 2×64 ms \u002F GiB | FineWeb 354M, 2×512 ms \u002F GiB |\n|---|---|---:|---:|\n| `balanced` | FP16 \u002F 8+8 bits | 19.23 \u002F 2.049 | 40.08 \u002F 2.562 |\n| `short128` | FP16 \u002F 8+8 bits, 128-element blocks | 18.49 \u002F 2.069 | 39.78 \u002F 2.580 |\n| `conservative` | BF16 + signed residual \u002F 8+8 bits | 20.30 \u002F 2.487 | 41.82 \u002F 2.865 |\n| `same_as_v5` | FP32 \u002F INT8 + block-scaled FP16 | 28.81 \u002F 3.351 | 46.27 \u002F 3.447 |\n| `experimental_m4v4` | FP16 \u002F 4+4 bits | 19.20 \u002F 1.687 | 38.84 \u002F 2.266 |\n| `experimental_fp8_master` | scaled E4M3 \u002F 4+4 bits | 19.05 \u002F 1.265 | 39.89 \u002F 1.985 |\n\nOnly `experimental_fp8_master` uses adaptive blocks of 512 for master-weight storage. `balanced`, `short128` and `experimental_m4v4` store their compressed projection weights in FP16. `conservative` stores a BF16 value plus a signed residual, and `same_as_v5` keeps FP32 master weights. The block scales for AdamW moments and for the NVFP4 matrix operands are separate from the FP8 master-weight scale.\n\n`remat=True` re-encodes the transposed weight during backward. In the 453M workload the FP8-master profile with recomputation measured **18.01 ms and 1.031 GiB**. Tied embedding\u002Foutput weights stay FP32. Weight packing uses separate 1×16 scales along the two contraction directions. NVIDIA Transformer Engine's default 16×16 shared weight scaling is a different recipe.\n\n```bash\npython -m nvfp4_training bench --task 453m --profile short128\npython -m nvfp4_training bench --task 453m --profile short128 --precision bf16\n# For the language-model benchmark, set NVFP4_FINEWEB to the external shard.\npython -m nvfp4_training bench --task fineweb --profile experimental_m4v4 --remat\n```\n\nThe FineWeb benchmark expects [this GPT-2-tokenized shard](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fkjj0\u002Ffineweb10B-gpt2\u002Fblob\u002F889765ea1f903759787add96995d81171b632d0c\u002Ffineweb_train_000001.bin), SHA-256 `771fa4a99b9fe0946ffb6e848b4ba5c6a9b0fe87860ebf03bc2c1c7e45f8178e`. It verifies the digest before use.\n\n### Validation loss\n\nAt 8,192 steps and 8,388,608 training tokens, validation cross-entropy was **5.85269** for balanced NVFP4, **5.87184** for 4-bit moments and **5.89044** for FP8 master + 4-bit moments. Balanced BF16 reached **5.84488**. The FP8-master BF16 control produced nonfinite training loss after its last finite evaluation at step 6,144. The plot and [paired-window results](results\u002Fvalidation.json) retain that missing endpoint. These are single-seed runs on a 354M causal LM.\n\n![Six validation traces and their paired differences](results\u002Fvalidation.png)\n\n### Where the numbers come from\n\nThe table and curves come from the saved RTX 5060 Ti runs. The 453M task uses synthetic, GPU-resident inputs, bidirectional attention and MSE. FineWeb uses causal attention, a tied vocabulary head and token cross-entropy. At step 8,192 the balanced FP4–BF16 difference was +0.00781 CE on the same held-out windows. See the [validation and packaging record](results\u002FREADME.md) for the scope of the checks.\n\nOn a new machine, `verify` tests all three backward paths against the reference. It records `fast_pair` for both aligned and padded inputs after the tests pass. This preserves the weight-packing configuration used for the table and long runs.\n\n## 4.06B full-parameter run\n\n**On one GeForce RTX 5060 Ti 16GB, a 4.06B-parameter language model completed 2,048 full-parameter AdamW updates on FineWeb.** Training loss averaged **9.60 over the first 32 updates** and **6.78 over the last 32**. On the same 65,536 held-out tokens, validation loss fell from **11.40 at initialization** to **7.03 at update 1,024** and **6.68 at update 2,048**.\n\n![Per-update training loss, 32-update moving average and fixed-window validation loss](results\u002Ffineweb-4b-2048\u002Floss.png)\n\nPyTorch peak GPU memory was **12.75 GiB allocated** and **14.33 GiB reserved**. Weights, activations and AdamW state stayed on the card. With two 512-token sequences per batch, the model saw 2,097,152 training tokens at 297.98 ms per update (3,436 tokens\u002Fs). The run used `experimental_fp8_master`, block-by-block initialization and transpose recomputation.\n\n![GPU memory allocated and reserved during training, graph capture and validation](results\u002Ffineweb-4b-2048\u002Fmemory.png)\n\nAn earlier run exposed an overflow in the fixed-scale FP8 master weights. Version `0.1.0.dev1` lets each block of 512 weights grow its scale when an update exceeds its range. With the same seed and data, the rerun passed all 19 FP8 weight scans and the model and optimizer health check at step 2,048. [Per-update measurements, fix and reproduction instructions](results\u002Ffineweb-4b-2048\u002FREADME.md)\n\n## License and attribution\n\nThe project's original contributions are licensed under the [MIT License](LICENSE). The implementation builds on [Elliot Arledge's SM120 work](https:\u002F\u002Fgithub.com\u002FInfatoshi\u002Fnvfp4-sm120). The upstream MIT license and copyright notice are included. See [NOTICE](NOTICE.md) for component provenance.\n","这是一个面向NVIDIA Blackwell架构SM120 GPU（如RTX 50系列、RTX PRO 6000）的开源PyTorch训练库，支持全精度NVFP4训练。核心功能包括软件实现的随机舍入（stochastic rounding）与随机哈达玛变换（random Hadamard transform），并利用原生FP4张量核加速矩阵乘法；提供六种内存\u002F速度权衡的训练配置文件。适用于GPU显存受限但需训练大模型（如4B级）的场景，尤其适合以矩阵计算为主、追求更高吞吐或更大单卡模型容量的AI训练任务。",2,"2026-11-24 04:40:38","CREATED_QUERY"]