TrainStream
Zero-Dependency PyTorch Training Offload
Train and fine-tune models larger than your GPU's VRAM. TrainStream moves optimizer state, gradients, activations and, when necessary, the weights themselves into host RAM, streaming them back over PCIe exactly when the GPU needs them.
Core Technical Summary
TrainStream enables training and fine-tuning models larger than available GPU VRAM. It moves optimizer state, gradients, activations, and when necessary, weights themselves into system host RAM, streaming them back over PCIe precisely when required by the GPU. Frozen weights (such as a LoRA base) can be stored as int8, NF4, FP8, or NVFP4, with FP8 and NVFP4 multiplied directly by Blackwell Tensor Cores.
Implemented as a native C++/CUDA extension for PyTorch using exclusively the C++ standard library, CUDA runtime, and PyTorch ATen. It contains zero third-party framework dependencies (no DeepSpeed, no bitsandbytes). Weight updates match torch.optim.AdamW with a maximum parameter difference of about 3·10⁻⁷ after 20 steps, while activation and weight paging remain bit-exact.
Version 0.7.0 is faster on 4-bit bases: on Qwen2.5-14B LoRA, an NVFP4 base runs 1.30× faster than bitsandbytes QLoRA at 512 tokens and 1.74× faster than Unsloth at 2,048 tokens, and an NF4 base (the format bitsandbytes and Unsloth use) is now ahead of both outside a 12 GB VRAM cap, where it is level with Unsloth.
Benchmarks
Data sourced verbatim from the reproducible benchmark suite shipped with the package. TrainStream 0.7.0 full check of 11 November 2026. RTX 5090 Laptop GPU (24 GB) in WSL2 with a 49 GB VM; the same runs on Windows 11 (64 GB RAM) are in the package README. Step time is the median of 10 steps after warm-up; close comparisons ran 3 times and a win counts only beyond the runs' spread.
| Engine | Step Time | Peak VRAM | Against the Fastest |
|---|---|---|---|
| TrainStream, NVFP4 base (FP4 tensor cores) | 0.530 s | 16.8 GB | fastest |
| TrainStream, NF4 base | 0.609 s | 16.8 GB | 1.15x |
| bitsandbytes QLoRA (NF4) + PEFT | 0.687 s | 17.4 GB | 1.30x |
| Unsloth (4-bit) | 0.778 s | 11.5 GB | 1.47x |
| bitsandbytes QLoRA + Liger kernels | 0.909 s | 12.0 GB | 1.72x |
| bitsandbytes QLoRA + gradient checkpointing | 0.988 s | 12.7 GB | 1.86x |
| TrainStream (auto: exact bf16 base, 20 of 48 layers streamed) | 1.079 s | 21.6 GB | 2.04x |
With an NF4 base, the same format bitsandbytes and Unsloth use, TrainStream 0.7 is 1.13x faster than bitsandbytes here; in 0.6 it was 7% slower.
| Scenario | TrainStream NVFP4 | TrainStream NF4 | Fastest Rival |
|---|---|---|---|
| Batch 1 x 512 | 0.530 s | 0.609 s | bitsandbytes QLoRA + PEFT, 0.687 s |
| Batch 1 x 2,048 | 1.57 s | 2.17 s | Unsloth, 2.73 s |
| Batch 1 x 512, held to 12 GB VRAM | 0.869 s | 0.834 s | Unsloth, 0.819 s (within the spread) |
| Documents of 64-2,048 tokens packed into 2 x 2,048 | 4.15 s | 5.80 s | bitsandbytes QLoRA + Liger, 6.68 s |
Full fine-tune of Qwen2.5-1.5B (batch 4 x 512): TrainStream 1.23 s at 18.8 GB peak, against 1.85 s for stock PyTorch (32.4 GB, spilling past VRAM) and 2.12 s for DeepSpeed ZeRO-2 with optimizer offload. Under the 12 GB cap, bitsandbytes QLoRA with or without checkpointing ran out of memory.
| Format | Qwen2.5-14B | After 20 LoRA Steps | Qwen2.5-1.5B | After 40 LoRA Steps |
|---|---|---|---|---|
| int8 | −0.00% | +0.08% | +0.02% | +0.05% |
| FP8 (tensor cores) | +0.89% | +0.72% | +1.70% | +1.44% |
| NF4 | +3.10% | +2.88% | +5.94% | +5.04% |
| NF4, keep_precise="auto" | +2.89% | +2.70% | +5.27% | +4.29% |
| NF4, error_rank=16 (LoftQ) | +3.06% | +2.81% | +5.76% | +4.10% |
| NF4, double_quant=True | +2.79% | +2.72% | +5.96% | +4.97% |
| NVFP4 (tensor cores) | +5.19% | +5.01% | +10.86% | +9.84% |
| NVFP4, outliers=0.01 | +4.78% | +4.21% | +8.99% | +8.27% |
| NVFP4, error_rank=16 (LoftQ) | +5.14% | +4.91% | +10.85% | +8.71% |
Bytes per weight: bf16 2, int8 1.06, FP8 1.03, NF4 and NVFP4 0.56. Results after fine-tuning vary between runs (up to 0.2 points for NF4 formats and about 1 point for NVFP4), so smaller differences there are noise.
Capabilities
Fused Block Kernels & Fused LoRA (New in 0.7)
One CUDA kernel each for the operations every transformer block repeats:
- •
kernels=fuses RMSNorm (forward and backward, with a fixed-order weight gradient), rotary embedding and the gated MLP activation (SiLU / GELU-tanh). Hugging Face modules are patched only where a check against their own code agrees. - • The fused SwiGLU and RoPE round once instead of at every step, so they sit closer to an fp32 reference than PyTorch's own code; the fused RMSNorm matches PyTorch bit for bit.
- •
fused_lora=computes each adapter in two matmuls forward and three backward, with no fp32 round trip of the input and no extra copy kept for the adapter's gradient. - • On the FP8 / NVFP4 path, q / k / v (and gate / up) share one quantization of their common input.
Padding-Free Sequence Packing (New in 0.7)
trainstream.packing packs variable-length documents into full rows, best fit first. Position ids restart for every document, so attention stays inside each one and no padding is ever computed.
- • Enable it in the trainer with
TrainStreamTrainer(trainstream={"packing": N}), or usePackedCollatorandpack_sequences()directly. - • A packed batch gives the same loss and gradients as running its sequences one by one.
- • On packed 64–2,048-token documents, the NVFP4 base ran 1.61× faster than bitsandbytes QLoRA with Liger kernels.
Quantization Quality Options (New in 0.7)
Opt-in ways to recover the accuracy a 4-bit base gives up:
- •
keep_precise=keeps the matrices quantization hurts most in int8 (NF4 base) or FP8 (NVFP4 base) within a share of the bytes. - •
error_rank=(LoftQ) starts the LoRA adapters at a low-rank fit of the quantization error. - •
double_quant=stores block scales in one byte, about 0.37 bits less per weight (0.65 GB on a 14B model). - •
outliers=0.01multiplies the largest 1% of NVFP4 input channels in bf16: y = scaled_mm(nvfp4(x_regular), W) + x_outliers @ W_outliers.T.
8-Bit Moments & Disk Tier (New in 0.7)
Fits larger runs into the same host RAM:
- •
moment_dtype="int8"stores blockwise 8-bit optimizer moments with stochastic rounding: about 6 host bytes per trained parameter instead of 12."auto"picks it when bf16 moments won't fit. - •
disk_offload=moves frozen paged blocks that host RAM can't hold into memory-mapped files on a fast SSD, streamed from there. - • NVIDIA ModelOpt NVFP4 checkpoints load as stored, and
moe_paging=copies only the routed mixture-of-experts experts to the GPU (experimental).
Single-Model Direct Preference Optimization
Executes DPO without allocating a second full reference model in GPU memory or maintaining four simultaneous logit tensors:
- •
causal_lm_logprobs()andsequence_logprobs()compute per-sequence log-probabilities from hidden states in bounded chunks. - •
reference_logprobs()evaluates the reference using the same paged or quantized base with LoRA adapters switched off, once before training. - •
dpo_loss()combines them, returning the loss and the implicit rewards.
Paged KV Cache for In-Training Generation
Designed for online alignment loops (online DPO, GRPO, PPO) where model generation occurs within the training step:
- •
PagedKVCachekeeps as many layers' keys and values in VRAM as a budget allows and offloads the rest to pinned host pages. - • Offloaded pages stream back into device slots over TrainStream’s asynchronous H2D stream while preceding layers compute.
- •
TrainStreamCacheintegrates directly into Hugging Facemodel.generate().
Memory Planner, Recompute & Attention Selection
TrainStream measures the machine and decides for you, then tells you what it decided:
- • The planner measures VRAM, RAM, the page-lock budget and PCIe bandwidth, keeps as many layers resident as fit and streams the rest.
- •
recompute="auto"recomputes activations in backward where measured trials show it beats sending them over PCIe; activation paging always leaves 10% of physical RAM free. - •
attention="auto"times PyTorch's attention kernels on your model's shape and uses the fastest. - •
trainstream.memory_report(model)["events"]logs every decision.
Pinned Host Arena & Multi-GPU Peer Mapping
Engineered for maximum PCIe bus utilization and operating system stability:
- •
host_arena="auto"reserves page-locked memory in slabs atwrap(), so a training step never page-locks memory, which stalls on Windows (WDDM). - • Host threads poll the GPU briefly and then sleep instead of spinning, which in 0.7 freed 6–10 CPU cores per step.
- •
peer="auto"pools frozen blocks across GPUs' VRAM via CUDA IPC for data-parallel training on one machine.
Usage
pip install trainstream (or pip install "trainstream[hf]" for transformers, accelerate and peft). uv works too: uv pip install torch trainstream --torch-backend=auto. The first import compiles the CUDA extension (about 16–19 s) and caches it.Basic Integration
import torch, trainstream
model = MyModel().cuda()
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
model, optimizer = trainstream.wrap(model, optimizer) # wrap once, before the first forward
for x, y in loader: # an ordinary training loop
with torch.autocast("cuda", dtype=torch.bfloat16):
loss = model(x.cuda(), y.cuda())
loss.backward() # gradients stream to host RAM during backward
optimizer.step() # host AdamW; returns once the update is queued
optimizer.zero_grad()Quantization & Quality Options
# A frozen base on Blackwell FP4 tensor cores, with 0.7's quality options
model, optimizer = trainstream.wrap(
model, optimizer, device="cuda",
quantize="nvfp4", # frozen weights block-scaled to 4 bits
outliers=0.01, # largest 1% of input channels multiplied in bf16
keep_precise="auto", # the most-damaged matrices stay FP8
error_rank=16, # LoftQ: LoRA starts at the quantization error
kernels="auto", # fused RMSNorm / RoPE / SwiGLU (on for quantized bases)
fused_lora="auto", # two matmuls forward, three backward per adapter
moment_dtype="auto", # fp32 -> bf16 -> int8 moments as host RAM requires
)QLoRA-Style Hugging Face Trainer with Packing
import peft
from transformers import TrainingArguments
from trainstream.integrations.huggingface import TrainStreamTrainer, load_model
model = load_model("Qwen/Qwen2.5-14B", quantize="nf4") # quantizes while reading the checkpoint
model = peft.get_peft_model(model, peft.LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.0, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]))
trainer = TrainStreamTrainer(
model=model,
args=TrainingArguments(output_dir="out", bf16=True),
train_dataset=ds,
trainstream={"packing": 2048}, # padding-free: documents packed into 2,048-token rows
)
trainer.train()Single-Model DPO Workflow
import trainstream
from trainstream.integrations.huggingface import causal_lm_logprobs, load_model, reference_logprobs, wrap_hf
model = peft.get_peft_model(load_model("Qwen/Qwen2.5-7B", quantize="nf4"), lora_config)
model, optimizer = wrap_hf(model, torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=5e-6))
# Adapters off: the same base is the reference, computed once, up front
ref = reference_logprobs(model, [b for pair in pairs for b in pair]).split(batch_size)
for k, (chosen, rejected) in enumerate(pairs):
pc = causal_lm_logprobs(model, chosen["input_ids"], chosen["labels"])
pr = causal_lm_logprobs(model, rejected["input_ids"], rejected["labels"])
loss, chosen_reward, rejected_reward = trainstream.dpo_loss(pc, pr, ref[2 * k], ref[2 * k + 1], beta=0.1)
loss.backward(); optimizer.step(); optimizer.zero_grad()TrainStream: FAQ
What is TrainStream?
TrainStream is an open-source PyTorch library from InnvoSols that lets you train and fine-tune models larger than your GPU's VRAM. It moves optimizer state, gradients, activations and, when necessary, the weights themselves into host RAM and streams them back over PCIe exactly when the GPU needs them.
How do I install and use TrainStream?
Install a CUDA build of PyTorch, then install TrainStream from PyPI with pip install trainstream (or pip install "trainstream[hf]" for the Hugging Face integration; uv works too). Wrap your existing model and optimizer in one line: model, optimizer = trainstream.wrap(model, optimizer). The rest of the training loop stays unchanged. Hugging Face users can swap Trainer for TrainStreamTrainer instead.
Does TrainStream depend on DeepSpeed or bitsandbytes?
No. TrainStream is a native C++/CUDA extension that uses only the C++ standard library, the CUDA runtime and PyTorch ATen. It has no third-party framework dependencies. Its NF4 format is bit-identical to bitsandbytes' NF4 without depending on it.
How fast is TrainStream compared with bitsandbytes QLoRA and Unsloth?
In the TrainStream 0.7.0 benchmarks (Qwen2.5-14B LoRA r=16 on an RTX 5090 Laptop GPU), TrainStream with an NVFP4 base was 1.30x faster than bitsandbytes QLoRA at 512 tokens and 1.74x faster than Unsloth at 2,048 tokens. With an NF4 base, the format bitsandbytes and Unsloth use, it was 1.13x faster than bitsandbytes at 512 tokens and 1.26x faster than Unsloth at 2,048 tokens. Held to 12 GB of VRAM it was level with Unsloth.
Are TrainStream's weight updates numerically accurate?
Yes. Weight updates match torch.optim.AdamW with a maximum parameter difference of about 3x10⁻⁷ after 20 steps, and activation and weight paging are bit-exact. Quantized bases train on dequantized weights, as QLoRA does, so they are not bit-exact with a bf16 base.
Which quantization formats does TrainStream support?
Frozen weights, such as a LoRA base model, can be stored as int8, NF4, FP8 or NVFP4. FP8 and NVFP4 are multiplied directly by Blackwell Tensor Cores. Measured perplexity cost against bf16 on Qwen2.5-14B is about 0% for int8, +0.9% for FP8, +3.1% for NF4 and +5.2% for NVFP4. Opt-in quality options reduce that: outliers keeps the largest 1% of activation channels in bf16, keep_precise stores the most-damaged matrices one step more precise, error_rank starts LoRA adapters at a low-rank fit of the quantization error (LoftQ), and double_quant shrinks the block scales.
What is new in TrainStream 0.7?
Version 0.7 adds fused CUDA kernels for RMSNorm, rotary embedding and gated MLP activations, a fused LoRA path, padding-free sequence packing, 8-bit optimizer moments (about 6 host bytes per trained parameter instead of 12), a disk tier for frozen weights that do not fit in RAM, LoftQ initialisation, double quantization and loading of NVIDIA ModelOpt NVFP4 checkpoints. It also stops host threads spinning while they wait for the GPU and leaves host RAM a safety margin when paging activations.
Can TrainStream run DPO and online alignment training?
Yes. TrainStream runs Direct Preference Optimization without a second reference model in VRAM, by computing reference log-probabilities from the same base with LoRA adapters switched off. A paged KV cache also supports generation inside the training step for online DPO, GRPO and PPO, and plugs into Hugging Face model.generate().
Custom Optimization for Your Workloads
If your organization is training large architectures and encountering VRAM constraints, PCIe bottlenecks, or latency targets, our systems engineering team is available for consulting engagements and custom kernel authoring.