Repository navigation
Model weights compression / effective 4-5 bit quant - #1630
Merged
Merged
Conversation
…()/evict() API
Replaces the per-model `{part}_to(device)` methods across all model classes,
plus scattered call sites in dataLoader/modelSetup/modelSampler/GenericTrainer,
with generic BaseModel methods driven by the existing ModelType.model_parts()
registry: materialize(*parts), evict(*parts), and materialize_only(*parts)
(evict everything else, then materialize the given parts - the swap-in/swap-out
pattern used throughout the Samplers and text-caching setup). eval() and
adapters() are likewise made concrete on BaseModel instead of hand-written per
model. Models whose component names diverge (Wuerstchen) or that have
components outside model_parts() (SD's depth_estimator, Anima's
text_conditioner) override the relevant methods directly.
Also fixes multi-TE samplers (Flux/SD3/SDXL/HiDream/HunyuanVideo) that
previously evicted all but the first text encoder and ran encode_text with
the rest still on temp_device.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…elper into BaseModelSetup
Squashed import of PR Nerogar#1623 (which contains Nerogar#1617), the dependency this feature is stacked on.
Quantized weights (fp8, W8A8, GGUF-A8) can be stored nvCOMP-compressed in VRAM and decoded on the fly during forward/backward, trading a small decode cost for lower resident VRAM. Compression is an opt-in per-component "Compress" toggle on the model tab, gated on ModelType.supports_compression() and wired generically through the centralized _setup_model_part call. quantize_layers stamps the flag onto the layers, guards against enabling it for a non-compressible dtype or without nvCOMP, and prints a per-model "% saved" line. Two decode backends are selected by import: a low-level batched-ANS path (via ctypes, sync-free decode; preferred) and a high-level nvCOMP Codec fallback. AutogradFunctionWrapper decodes the blob in both passes so backward re-derives the weight instead of holding it resident. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add nvidia-nvcomp-cu13 (and the cu12 legacy build) at 5.3.0.16; the feature silently no-ops without it. nvCOMP ships linux and win_amd64 wheels, so no platform marker. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
GGUF k-quants already normalize per 32-value block and bit-pack tightly, so the packed bytes sit at ~7.6-8.0 bits/byte entropy. Measured across all nvCOMP algorithms (ANS, Zstd, GDeflate, Deflate, Gzip, LZ4, Snappy, Bitcomp, Cascaded), real Q4_K_S and Q8_0 files top out at ~2-4% saved (ANS gives ~0% on Q4_K, ~3% on Q8_0) - not worth the decode cost. The int8 wins come from tensorwise scaling where outliers collapse most weights toward zero (low entropy); GGUF's per-block scale is the opposite by design. Revert LinearGGUFA8 to plain GGUFLinear (no CompressedWeightMixin/QuantizedModuleMixin) so its layers are never compressed. Toggling Compress on a GGUF dtype now raises in quantize_layers via the empty-compressible-layers guard. Drop GGUF from the UI tooltip. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Delegate locating the shared library to nvidia.libnvcomp's own load_library(), which resolves libnvcomp.so.5 on Linux and nvcomp64_5.dll on Windows, instead of the Linux-only lib64/libnvcomp.so* glob. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Works great! Training speed with Krea and BS2 on 5060ti is 2.x s/it vs. 3-4 s/it without it. Being able to turn off layer offload makes really a big difference especially for people with older PCIe like me. |
…eanup evictions `LayerOffloadConductor.to(device)` inferred the direction from the device argument. Splitting it into `materialize()` and `evict()` makes the direction explicit at the call site, and lets the offload config be passed in per call instead of being stored on the conductor. Cleanup calls that evicted a part only for the next step to materialize it again are removed; eviction now happens at save and teardown boundaries. `SampleWindowController` keeps an explicit eviction because nothing follows it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The dataloader debug hooks used materialize_only("vae"), which evicts every
other part. They run in the middle of caching, so the parts the caching loop
had just materialized were pulled back out from under it. They only need the
VAE present, so materialize() is enough.
_move_part dispatched the conductor on train_device and treated everything
else as an eviction, so an unexpected device silently evicted instead of
failing. It now dispatches on temp_device and asserts the remaining case is
train_device.
SampleWindowController evicts in a finally block, so a failed or cancelled
sample no longer leaves the model resident.
scripts/sample.py passed the train device as both train_device and
temp_device, so nothing could ever be evicted; it now sets a real temp device
and fills in train_device/temp_device on the TrainConfig it builds. It also
passes the quantization config to the loader, which it previously dropped.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
_setup_model_part took an attention_mask parameter whose None value meant "do not set an attention backend for this part", which conflated two unrelated things: mask is only a hint about whether the architecture uses masked attention, and its absence is not a sensible way to skip backend selection. Drop the parameter and call _set_attention_backend directly from each leaf setup_optimizations again, once per part that has a backend. The resulting set of calls is unchanged. Also condense the comments added when setup_optimizations was centralized. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
decompress_into() allocated five buffers on every decode (nvCOMP temp, the actual-size and status outputs it never reads, and the two pointer arrays). Their size depends only on the chunk count, so _decode_scratch() keeps one set per (num_chunks, device) and the pointer arrays are rebased in place. This is safe only because decodes are serialized on the compute stream; concurrent decodes on two streams would need one set per stream. LinearW8A8 goes back to a plain LinearW8A8Function taking (x, weight, scale, bias, compute_dtype) instead of the generic AutogradFunctionWrapper, which is removed. The weight is decompressed in forward() before the Function, so save_for_backward holds the decoded weight and backward does not decode again; with gradient checkpointing that tensor lives only inside the recomputed segment. CompressedWeightMixin.compression_sizes() becomes uncompressed_bytes(), since the stored size is plain weight.nbytes: the compressed blob is the weight tensor. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…into nvcomp-inject-squashed # Conflicts: # modules/dataLoader/AnimaBaseDataLoader.py # modules/dataLoader/ChromaBaseDataLoader.py # modules/dataLoader/ErnieBaseDataLoader.py # modules/dataLoader/Flux2BaseDataLoader.py # modules/dataLoader/FluxBaseDataLoader.py # modules/dataLoader/HiDreamBaseDataLoader.py # modules/dataLoader/HunyuanVideoBaseDataLoader.py # modules/dataLoader/IdeogramBaseDataLoader.py # modules/dataLoader/Krea2BaseDataLoader.py # modules/dataLoader/PixArtAlphaBaseDataLoader.py # modules/dataLoader/QwenBaseDataLoader.py # modules/dataLoader/SanaBaseDataLoader.py # modules/dataLoader/StableDiffusion3BaseDataLoader.py # modules/dataLoader/StableDiffusionBaseDataLoader.py # modules/dataLoader/StableDiffusionFineTuneVaeDataLoader.py # modules/dataLoader/StableDiffusionXLBaseDataLoader.py # modules/dataLoader/ZImageBaseDataLoader.py # modules/model/BaseModel.py # modules/modelSampler/AnimaSampler.py # modules/modelSampler/ChromaSampler.py # modules/modelSampler/ErnieSampler.py # modules/modelSampler/Flux2Sampler.py # modules/modelSampler/FluxSampler.py # modules/modelSampler/HiDreamSampler.py # modules/modelSampler/HunyuanVideoSampler.py # modules/modelSampler/IdeogramSampler.py # modules/modelSampler/Krea2Sampler.py # modules/modelSampler/PixArtAlphaSampler.py # modules/modelSampler/QwenSampler.py # modules/modelSampler/SanaSampler.py # modules/modelSampler/StableDiffusion3Sampler.py # modules/modelSampler/StableDiffusionSampler.py # modules/modelSampler/StableDiffusionVaeSampler.py # modules/modelSampler/StableDiffusionXLSampler.py # modules/modelSampler/WuerstchenSampler.py # modules/modelSampler/ZImageSampler.py # modules/modelSetup/BaseAnimaSetup.py # modules/modelSetup/BaseChromaSetup.py # modules/modelSetup/BaseErnieSetup.py # modules/modelSetup/BaseFlux2Setup.py # modules/modelSetup/BaseFluxSetup.py # modules/modelSetup/BaseHiDreamSetup.py # modules/modelSetup/BaseHunyuanVideoSetup.py # modules/modelSetup/BaseIdeogramSetup.py # modules/modelSetup/BaseKrea2Setup.py # modules/modelSetup/BaseModelSetup.py # modules/modelSetup/BasePixArtAlphaSetup.py # modules/modelSetup/BaseQwenSetup.py # modules/modelSetup/BaseSanaSetup.py # modules/modelSetup/BaseStableDiffusion3Setup.py # modules/modelSetup/BaseStableDiffusionSetup.py # modules/modelSetup/BaseStableDiffusionXLSetup.py # modules/modelSetup/BaseWuerstchenSetup.py # modules/modelSetup/BaseZImageSetup.py # modules/trainer/GenericTrainer.py # modules/ui/SampleWindowController.py
…shed # Conflicts: # modules/module/quantized/LinearFp8.py # modules/module/quantized/LinearW8A8.py
… flag Weight compression was a per-component bool sitting next to the weight data type, which allowed the two to contradict each other. It becomes two data types instead, FLOAT_W8A8_COMPRESSED and INT_W8A8_COMPRESSED, offered as their own entries in the Data Type dropdown next to the dtypes they compress. DataType gains uncompressed() and is_compressed(). Only is_quantized(), quantize_fpW8A8() and quantize_intW8A8() normalize through uncompressed(), since those are the ones with a compressed counterpart; a compressed data type picks the same quantized linear class and the same math as its base. LinearW8A8 is the only layer that compresses, so LinearFp8 no longer carries CompressedWeightMixin. The compressed entries stay in the dropdown when nvCOMP is not installed; selecting one then raises during setup rather than silently training uncompressed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Decompress a weight that is still on the CPU by copying it to the GPU, decoding it there and copying the result back, instead of raising. DoRA reads the unquantized weight during initialization, when the weight can still be on the CPU. Fall through to the next nvCOMP backend on any exception raised while importing one, not only on ImportError: a differing batched-ANS API raises AttributeError from ctypes, and the library loader raises OSError. Either would otherwise stop OneTrainer from starting, since this module is imported unconditionally. The message now names the exception type, so a fallback to the slower backend is visible. Launch the compression kernels on the stream of the tensor's own device instead of the stream of whichever device is currently selected, which is cuda:0 unless set_device was called. Give each thread its own decode scratch buffers. They are filled in on the host but read by the kernel when it runs, so a decode from a second thread could overwrite them in between, and the kernel would decode the wrong chunks into the wrong buffer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
needs_dynamic_parameter_shapes is a process global that only describes the current run, and was only ever set to True. torch._dynamo config overrides live in ContextVars since torch 2.12, so the force_parameter_static_shapes write in _compress_weight() dies with the training thread - but init_compile() re-applies it from the stale global in every later run's thread. In the long-lived UI process, one compressed run therefore kept parameter shape specialization relaxed for every subsequent run in the same session. reset_compile() clears the flag; GenericTrainer calls it just before init_compile(), so it runs before quantization can set the flag again for this run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # modules/modelSetup/BaseModelSetup.py # modules/modelSetup/BaseStableDiffusionSetup.py # modules/modelSetup/BaseStableDiffusionXLSetup.py # modules/modelSetup/BaseWuerstchenSetup.py
dxqb
added a commit
to dxqb/OneTrainer
that referenced
this pull request
Aug 13, 2026
Resolves the collisions with the materialize()/evict() API (Nerogar#1617), the centralized setup_optimizations (Nerogar#1623) and the weight-compression work (Nerogar#1630) that landed upstream while this branch was open. Conflicting files are resolved to the versions this feature has been developed and tested against.
states-spec
pushed a commit
to states-spec/OneTrainer-Plus
that referenced
this pull request
Oct 26, 2026
…preview-2) compress sat between dtype and *args, so a positional call LinearW8A8(dtype, in, out) bound in_features to compress. The fork's rocm_check "W8A8 linear layers" check builds its layers that way and failed with "Linear.__init__() missing 1 required positional argument: 'out_features'" since the compression change (Nerogar#1630). The quantizer passes compress by keyword and is unaffected. Upstream also adds a FIXME: bnb's Linear8bitLt takes input_features/output_features, but __create_linear_layer passes in_features/out_features, so the INT_8 weight dtype fails to construct (TypeError). Checked: broken in the fork and upstream since Nerogar#1034. Not fixed here, because more of that path has not run since then (e.g. get_unquantized_weight has no Linear8bitLt case, so DoRA would read raw int8 data). Tested on the CPU: LinearW8A8(torch.int8, 64, 32, bias=True) builds 64 -> 32 with compress off (TypeError before); INT_W8A8 and FLOAT_8 quantized layers still build through replace_linear_with_quantized_layers. (cherry picked from commit c2f3bff) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011z4fFGwikUdiKShtgwZP9C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR is the result of an experiment a while ago. After NVIDIA has fixed a roadblock in their API that I have reported (NVIDIA/CUDALibrarySamples#300) it turns out to be very useful:
It implements model weights compression. Transformer weights are compressed during quantization, and decompressed on each forward and backward. What's non-intuitive is how high the compression ratios are on int8 quantized weights, even using a very efficient compression codec:
This turns int8 effectively into a 4-5 bit quant without quality loss compared to int8.
Raw performance impact is between 5 and 7% of steptime on 512px batch size 2 for the decompression; less on higher batch sizes
However, the effective performance impact on a 16 GB card:
As to why this works so well on int8, even though model weights commonly have high entropy. It works much less on float8 (~ 15%). The quantization to int8 removes entropy due to its linear scale and rounding - outliers stretch the scale, pushing the many smaller weights toward 0:
diff looks larger than it is, because it includes #1623
diff of this PR only: 5ecdb24
Test plan
pre-commit run --all-filespassesAI assistance