Skip to content

[Feature] Transformer Block Swap #3997

Closed

Description

@kabachuha

Hello!

Block swap - the offload of transformer layers sequentially to ram and back - is a common feature of training diffusion models, implemented in the frameworks such as https://github.com/tdrussell/diffusion-pipe, https://github.com/kohya-ss/musubi-tuner and https://github.com/bghira/SimpleTuner/ (diffusers's group offload).

Why is it overlooked for LLMs? When a LLM does inference, the tokens are generated rapidly, with the layers would have to be swapped back and forth with enormous frequency. It is impractical, if you do this in llama .cpp, it kills the speed. But many forget that it is for inference!

When LLM undergoes training, all of the tokens are predicted at the same time (with masked attention). It is no different than an image or a video model predicts the noise/velocity for a long tokens sequence, so the rapid transfer factor of LLM inference is not taken in the consideration anymore. The amount of time the transformer layers process the sequence nears the time the blocks are swapped through the PCI-E / RAM bandwidth and it gains practical use again. The main limiting speed becomes the CUDA cores throughput and not the swapping.

As shown in musubi-tuner, simple-tuner and diffusion-pipe, block swap can be enormously helpful and it also fully stacks with unsloth's gradient checkpointing algorithm and other optimizations.

Yes, it does slowdown the process. But if training a model is ~2x times longer, it's much better than not training the model at all!

If transformer block swap will be implemented in unsloth and if it will work, it will usher an entirely new era of hobbyist LLM fine-tuning!

Activity

  1. added
    feature request
    on Feb 7, 2026
  2. LeoBorcherding commented on Sep 24, 2026

    @LeoBorcherding
    Collaborator

    Worth narrowing this, because part of it already shipped, and then some numbers from a prototype.

    Two things already move to host RAM during training. use_gradient_checkpointing = "unsloth" offloads checkpoint-boundary activations to pinned CPU buffers with a double-buffered copy overlapped against compute, and it's the default in get_peft_model. offload_embedding keeps embed_tokens on the CPU and runs the lookup there, with forward hooks that move ids to the weight's device and the result back; it defaults to "auto" and fires when the embedding is at least 1 GiB and 5% of the card.

    So transformer block weights are the only item with no path, and offload_embedding is already a one-layer version of the same mechanism.

    The economics are better than the usual objection suggests, and they depend on the model.

    "Moving weights is too slow" comes from inference, where every token pays the round trip. Training amortizes one fetch across the whole sequence, so what matters is compute per layer against bytes per layer, and the layer's own size cancels out of the comparison:

    T  >=  (bytes/param * FLOP/s) / (2 * 3 * PCIe_bytes/s)
    

    for tokens per step T. At 4-bit on PCIe 4.0 that's on the order of 100 to 200 tokens per step, independent of model size. That's the property that makes this worth building.

    Sparse MoE breaks the cancellation. You move every expert but compute only with the active ones, so a sparsity factor params / active_params multiplies the right-hand side: about 27x for an 80B-A3B, putting break-even near 2700 tokens per step. Reachable, but a first implementation should be dense-only.

    Measured. I built a prototype to check the arithmetic. Llama-3.2-3B 4-bit, R9700 (ROCm 7.13, PCIe 4.0, 13.3 GB/s measured host-to-device), 24 of 28 layers swapped to pinned host RAM, 3 reps:

    tokens/step peak VRAM saved step time vs no swap
    512 1006 MiB +3.2%
    2048 1006 MiB -0.3%
    4096 1006 MiB -1.2%

    Losses bitwise identical over 60 steps. Smallest VRAM budget that still trains, by bisection: 5.00 GiB without, 4.06 GiB with. The saving is weights, so it's flat across sequence length; the overhead vanishes into run-to-run noise at 2048 and above.

    Two things that stack badly with gradient checkpointing, from building it. The checkpointer itself isn't the problem, it patches torch.utils.checkpoint process-wide and doesn't need to know swap exists. But:

    1. Its recompute sweep walks the layers in reverse. A prefetcher that only looks forward fetches layers that already finished, which then sit resident and save nothing. The direction has to flip with grad mode.
    2. Fetching into freshly allocated tensors saves almost nothing in practice. Average residency drops but the allocator's high-water mark doesn't, so the card you need is barely smaller (0.38 GiB instead of 0.94). Device slots have to come from a fixed pool.

    PR to follow.

  3. LeoBorcherding commented on Sep 24, 2026

    @LeoBorcherding
    Collaborator

    Both halves are up: the parameter and refusals in unslothai/unsloth#11832 · Block Swap: Stream frozen…, the mechanism in unslothai/unsloth-zoo#1378 · Add Block Swap zoo: stream…. Measured numbers, hardware fit and the test-coverage matrix are in the core PR body. Thank you @kabachuha for this idea! hope to get the teams thoughts and opinions on it soon.

  4. added a commit that references this issue on Oct 4, 2026
    7911672
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

feature request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions