Skip to content

Add MLX backend support for CLI unsloth train - #1

Closed
Lyxot wants to merge 6 commits into
mlx/trainer-apifrom
feat/cli-mlx-backend-aware
Closed

Lyxot wants to merge 6 commits into
mlx/trainer-apifrom
feat/cli-mlx-backend-aware

Conversation

@Lyxot

@Lyxot Lyxot commented Jun 26, 2026 •

Copy link
Copy Markdown
Owner

Closed because unslothai/unsloth#6462 has merged and unslothai/unsloth#6709 is now rebased directly onto latest main.

Copilot AI review requested due to automatic review settings June 26, 2026 20:13

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds MLX backend support to the unsloth train CLI by routing CLI training through the Studio backend-aware UnslothTrainer surface and reusing the existing Studio MLX worker subprocess path.

Changes:

  • CLI unsloth train now instantiates UnslothTrainer via a backend-aware factory path and activates the model-specific Transformers sidecar before importing trainer code when MLX is selected.
  • Studio training backend gains shared worker-config normalization utilities and an MLX adapter that preserves the legacy trainer API shape while delegating execution to the MLX worker subprocess.
  • MLX worker path is extended for CLI needs (CLI-relative local dataset paths, external output dirs, stop/cancel lifecycle, retry + stale event handling, and progress/output-dir reporting), with new focused tests.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
unsloth_cli/commands/train.py Adds MLX dispatch + Transformers sidecar activation ordering for CLI, and improves error-aware training loop handling.
studio/backend/tests/test_training_preflight.py Adds tests covering MLX dispatch, CLI activation order, adapter config/progress, retry/cancel semantics, and worker side effects.
studio/backend/core/training/worker.py Enhances MLX worker to support CLI path resolution, external output dirs, stop polling, xet-stall watchdog events, and shared entrypoint.
studio/backend/core/training/training.py Introduces shared MLX backend detection helpers, shared worker-config builder, and _MLXTrainerAdapter bridging legacy API to the worker subprocess.
studio/backend/core/training/trainer.py Makes UnslothTrainer backend-aware via __new__ dispatch to the MLX adapter and shares TrainingProgress with the orchestrator module.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +600 to +602
def _run_training_thread(
self, config: dict[str, Any], event_queue: queue.Queue, stop_queue: queue.Queue
):
Comment on lines +163 to +167
progress = trainer.get_training_progress()
if getattr(progress, "error", None):
trainer.training_thread.join(timeout = 5)
else:
trainer.training_thread.join()
Comment on lines +347 to +348
self._event_queue: queue.Queue | None = None
self._stop_queue: queue.Queue | None = None
@Lyxot
Lyxot force-pushed the feat/cli-mlx-backend-aware branch 3 times, most recently from acee331 to 79f2c12 Compare July 2, 2026 09:38
Lyxot and others added 6 commits July 2, 2026 23:02
* feat: add mlx public trainer api

* test: cover mlx public trainer api

* fix: preserve mlx epoch trainer configs

* fix: pass mlx warmup ratio through config

* fix: align mlx trainer dataset order

* fix: keep mlx chat templates import-light

* fix: infer mlx trainer context length

* fix: mirror cuda mlx context defaults

* fix: align mlx notebook trainer defaults

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: keep mlx public helpers import-light

* refactor: reuse mlx optimizer normalization

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: address mlx review feedback

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: tighten mlx training argument parity

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: align mlx trainer eos default

* Fix MLX trainer to accept DataCollatorForSeq2Seq and handle TokenizerWrapper in get_chat_template

* Trim redundant docstrings on internal MLX helpers

* MLX review fixes: Studio optimizer import-safe on non-MLX hosts, preserve explicit max_length, skip MLX tests before import

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* MLX review round 2: defer max_length to model context, optimizer alias fallback for older zoo, skip non-MLX test on missing GPU deps

* MLX review round 3: keep chat_templates importable without torch on MLX

* fix: preserve MLX trainer notebook shims

* fix: ignore CUDA tokenizer moves on MLX

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: harden MLX trainer shims

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: unwrap MLX scheduler enum args

* fix: coerce integral MLX epoch counts

* fix: spoof CUDA compatibility APIs on MLX

* fix: harden MLX notebook compatibility shims

* MLX: add torch.cuda.mem_get_info to the compatibility shim

Notebook memory cells call torch.cuda.mem_get_info()[0] directly (not gated by
is_available), so on MLX it raises without a shim. Return (free, total) bytes
from the MLX device stats, consistent with the other torch.cuda compat helpers,
and add a matching assertion to the compat-API test.

* MLX: use active memory for mem_get_info; fix BatchEncoding.to keyword device

Address review on the MLX compatibility shim:
- torch.cuda.mem_get_info() now derives free bytes from current active MLX
  memory instead of the peak high-water mark, so a capacity check stays
  accurate after a transient spike or a prior run.
- BatchEncoding.to(device=...) passed by keyword no longer forwards a positional
  None alongside the keyword (which raised "multiple values for 'device'"), so
  non-CUDA keyword moves like .to(device="cpu") delegate correctly.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* MLX: accept preserve_dataset_order; stub RL trainers with a clear error

Two fixes so unmigrated notebooks behave predictably on MLX (torch present):

- preserve_dataset_order is a real MLXTrainingConfig field but was missing from
  the extra-argument allowlist, so passing it (as a config or trainer kwarg)
  could be rejected as unknown on a zoo without the field. Add it to
  _MLX_IMPLEMENTED_EXTRA_ARGUMENTS so the documented no-shuffle path is reachable.

- GRPO/DPO/ORPO (and KTO/PPO/Reward) have no MLX trainer yet. Retarget the ones
  the installed trl exposes to a stub that raises a clear 'not supported on MLX'
  error instead of importing the real torch/CUDA trainer and crashing deep
  inside it. Only existing trainers are retargeted (no invented attributes),
  idempotent across re-imports.

* MLX: make RL-trainer stubbing import-safe; back current-memory APIs with active memory

Address review on the MLX shims:
- The RL-trainer stub loop probed trl with getattr(_trl, name), which triggers
  trl's lazy trainer import and pulls torch -- that can crash import unsloth on a
  torch-free MLX install just to check existence. Decide what to stub from
  trl.__all__ + already-materialized attrs (vars) instead; never resolve the real
  trainer. All trl trainer names are in __all__, so they are still stubbed (even
  torch-free), and the probe no longer imports torch.
- torch.cuda.memory_reserved / memory_allocated (the current, non-max APIs) were
  aliased to peak max_memory_reserved. Back them with current active MLX memory so
  cleanup / capacity checks see live usage; max_* keep the peak high-water mark.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* MLX: keep TRL's SFTConfig epoch default under the trl.SFTConfig alias

Unmigrated notebooks import SFTConfig from trl, which the MLX build aliases to
the public training-args class. TRL/HF SFTConfig defaults to num_train_epochs=3
(max_steps=-1); the native MLX config defaults to max_steps=60. So an SFTConfig
built without an explicit length silently ran 60 MLX steps instead of TRL's 3
epochs under the alias. Alias trl.SFTConfig to a thin subclass that seeds the
TRL epoch default only when neither max_steps nor num_train_epochs is given;
explicit lengths pass through untouched, and the native public args class keeps
its MLX default. Epoch mode is supported by the MLX trainer.

* MLX CI: keep the GGUF reload smoke under the job timeout

The RELOAD-GGUF-via-llama-cli step timed out at 300s. BF16 GGUF decode is
CPU-bound on the macOS runner (~10s+/token), so generating 24 tokens landed
right on the 300s cliff and killed the process. This step is a save/reload
integrity smoke (it only needs a few chars of output), so the token count is
incidental: generate 8 tokens with explicit threads and a small headroom on the
subprocess timeout, all env-tunable (UNSLOTH_GGUF_RELOAD_N / _THREADS /
_TIMEOUT). Cuts the reload well under the 25 minute job budget.

* MLX: broaden trainer stubs, real peak-memory reset, fix shim tests

Address review on the MLX public API:
- The SFTConfig identity tests asserted trl.SFTConfig is UnslothTrainingArguments,
  but the alias now points at the _MLXSFTConfig subclass that preserves TRL's
  epoch default, so the MLX suite failed before testing the shim. Assert
  issubclass instead.
- torch.cuda.reset_peak_memory_stats was a no-op, so max_memory_reserved kept
  earlier model-load peaks across a scoped run. Wire it to mx.reset_peak_memory
  with the same core/metal fallback used for the reads.
- The unsupported-trainer stubs were a fixed list, so trainers outside it (a
  newer RLOOTrainer) still routed to the real torch trainer. Derive the set from
  trl.__all__ (every non-SFT *Trainer) so all non-SFT surfaces fail with a clear
  MLX message; names come from __all__ so trl is never resolved.
- The non-MLX export smoke skipped only on missing bitsandbytes/triton; other
  absent GPU deps (numpy/torch/unsloth-zoo, or _gpu_init re-raising ImportError)
  made it fail on CPU hosts. Skip on any ImportError.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: keep MLX notebook compatibility minimal

* MLX CI: force CPU + small context for the GGUF reload smoke

The RELOAD-GGUF-via-llama-cli step timed out even at 8 tokens (>420s), so it is a
fixed hang, not per-token cost: on the paravirtual macOS runner GPU llama.cpp's
Metal backend stalls, and the gemma3 GGUF advertises a 32768 context that llama-cli
would otherwise fully allocate. Run llama-cli CPU-only (-ngl 0) with a small context
(-c 256); keep generation short. All env-tunable (UNSLOTH_GGUF_RELOAD_NGL / _CTX /
_N / _THREADS / _TIMEOUT). Also print llama.cpp's partial stdout/stderr on timeout so
a future hang is diagnosable instead of an opaque TimeoutExpired.

* MLX CI: export the reload-smoke GGUF as q8_0, not bf16

The GGUF reload via llama-cli timed out on the runner even CPU-only with a tiny
context and 8 tokens. Root cause is the format, not the flags: the smoke exported
quantization_method='not_quantized', which maps to a bf16 GGUF, and llama.cpp's
bf16 CPU decode is unusably slow on the paravirtual macOS runner. Export q8_0
(fast_quantized, the exporter default and what users deploy) instead -- llama.cpp
has optimized q8_0 CPU kernels, so the fresh-process reload loads and generates in
seconds. The reload stays CPU-only (-ngl 0) with a small context.

* test: clear TRL shim before availability check

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Lee Jackson <[email protected]>
Co-authored-by: imagineer99 <[email protected]>
* report a complete load once llama-server is healthy

load_progress() derived its fraction purely from the llama-server's VmRSS over the GGUF shard total. With layers offloaded to VRAM (-ngl) the process releases the mmap'd weight pages after upload, so VmRSS sinks back well below the shard total: the fraction climbs toward ~1.0 during mmap, then collapses to a small value (~8%) once the weights are on the GPU. A fraction-driven progress bar therefore restarts and sticks there indefinitely even though the model is loaded and serving, which reads as a hang at "Starting model...".

Once the server is healthy the load is complete by definition, so report
fraction 1.0 (and bytes_loaded == bytes_total) in the ready phase regardless of resident set size. The VmRSS read is factored into _read_rss_bytes() with its original semantics preserved (0 on a missing VmRSS line, None when /proc is unavailable) so it can be unit-tested off Linux.

Fixes unslothai#5740

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* stub heavy deps in the load-progress test and guard a valueless VmRSS

Two review fixes:

1. The new test imported core.inference.llama_cpp at module top, which pulls in
   loggers/structlog/httpx and fails collection with ModuleNotFoundError in the
   lightweight backend test env when the file is run on its own. Stub loggers,
   structlog and httpx via sys.modules.setdefault before the import, mirroring
   test_llama_cpp_load_progress_matrix.py; setdefault keeps the real modules when installed. Verified the file now collects and passes with only pytest present.

2. Catch IndexError in _read_rss_bytes: a "VmRSS:" line with no value column
   would make line.split()[1] raise and crash a load-progress poll. Return None
   instead, with a test for the valueless line.

* Hold load-progress high-water mark and explain a never-healthy load (unslothai#5740)

load_progress() now holds a per-process VmRSS high-water mark, so the bar
no longer regresses to ~8% when -ngl offloads the weights and frees the
mmap pages mid-load.

A live server that never returns 200 on /health now gets a specific error
(context/VRAM too large, or a local proxy/VPN intercepting the loopback
probe) instead of the generic invalid-GGUF/out-of-memory message.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Hakan Baysal <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Lee Jackson <[email protected]>
@Lyxot
Lyxot force-pushed the feat/cli-mlx-backend-aware branch from 79f2c12 to 2e50d99 Compare July 3, 2026 14:32
@Lyxot

Lyxot commented Jul 3, 2026

Copy link
Copy Markdown
Owner Author

Closing this copy because unslothai#6709 has been rebased onto latest main after unslothai#6462 merged.

@Lyxot Lyxot closed this Jul 3, 2026
NilayYadav pushed a commit that referenced this pull request Oct 21, 2026
…slothai#14551)

## Summary

unslothai#14541 runs a guided Z-Image step as two batch-1 calls, so turning CFG
on mid-session compiles nothing new and records no new CUDA graph. It
turned itself off under four modes. This PR turns it on under two of
them, static step skip and CFG-parallel. In both, the decline was never
actually needed. The other two keep the batched call, because there is a
real constraint.

| mode | before | after | why |
|---|---|---|---|
| static step skip (`transformer_cache="static"`) | batched | split |
With Studio's step-end callback, the skip keys calls by their order
within a step. Cond is `#0` and uncond is `#1`, so each branch is
skipped or computed on the same steps as the batched call. |
| CFG-parallel router | batched | split | The router pairs branches by
the identity of the first tensor argument. For Z-Image that is the
timestep, which is a fresh tensor on every call. So the router never
pairs Z-Image calls, batched or split, and every call runs on the
primary card either way. |
| step cache (FBCache) | batched | batched | FBCache keeps one residual
per `cache_context`, and two calls in one context would compare cond
against uncond. This case cannot happen today: no Z-Image pipeline
(`pipeline_z_image*.py`) opens a `cache_context`, so `apply_step_cache`
refuses Z-Image. |
| streamed / group / sequential offload | not armed | not armed | Two
calls would upload the streamed weights twice per step. That costs more
than a recompile, and `diffusion_cfg_batch` exists to avoid exactly
this. |

## What it does

- `_declined_now` declines under a static step skip only when the skip
has a plan and cannot key the two calls apart: no step signal, or a
`cache_context` name shared by both calls.
- The skip is found through its own `_unsloth_static_skip` slot as well
as the forward slot. A CFG-parallel router installed after the skip
takes over the forward slot and wraps the skip.
- The CFG-parallel decline is removed.
- The docstring now says which modes split and why.

## Results

Studio `DiffusionBackend`, same host, base = `origin/main`. Prompts 1-3
at guidance 0, then prompts 4-5 at guidance 2.0. Each cell is new dynamo
graphs / recompile log lines / Studio CUDA graph captures for that
render.

| setup | prompt 4 main | prompt 4 this PR | prompt 5 main | prompt 5
this PR |
|---|---|---|---|---|
| Z-Image-Turbo bf16, 1024x1024, 12 steps, static skip, default tier | 3
/ 6 / 1 | 0 / 0 / 0 | 1 / 2 / 0 | 0 / 0 / 0 |
| tiny Z-Image, 256x256, 12 steps, static skip | 3 / 6 / 1 | 0 / 0 / 0 |
1 / 2 / 0 | 0 / 0 / 0 |
| tiny Z-Image, 4 steps, CFG-parallel armed, CUDA graphs off | 3 / 6 / 0
| 0 / 0 / 0 | 1 / 2 / 0 | 0 / 0 / 0 |

- Static skip schedule: both arms skip 4 of 12 steps on each branch.
Main skips 4 of 12 batched calls; this PR skips 8 of 24 split calls.
Prompts 1-3 are bit-identical to main (same sha256).
- Real model, first guided render: 15.6 s on main (recompile plus
capture) vs 0.90 s on this PR. Second guided render: 5.7 s vs 0.77 s.
Each is a single render on a shared card, so these are latency
observations and not a throughput benchmark. Prompt 5 is bit-identical
to main (same sha256). Peak VRAM was 19.3 GB on main and 19.0 GB on this
PR.
- CFG-parallel: main and this PR both show `replica_calls 0` and
`steps_parallel 0`, which confirms the router never pairs Z-Image calls.
The guided images under the router are bit-identical to the split
without a router.

## Testing

- `tests/test_diffusion_zimage_cfg_split.py` has 4 new tests:
- Under the real `StaticStepSkip`, a guided render after guidance-off
renders adds 0 graphs.
- Split vs batched under the skip: the same steps are skipped (2x the
calls) and the predictions match within 1e-4.
- A skip with no step signal keeps the batched call, including when a
router is installed over the skip.
- Under the real `CfgParallelRouter`, the split adds 0 graphs, builds no
replica, and its output is bit-identical to the split without a router.
- The new tests fail on main (4 failed) and pass here.
- Related suites: `test_diffusion_cache`, `cfg_batch`, `multigpu`,
`multigpu_wiring`, `static_skip`, `step_skip_defaults`,
`zimage_cfg_split`, `zimage_fused`, `video_static_skip`, `cuda_graph`.
Main: 4 failed (the new tests only), 488 passed, 8 skipped. This PR: 492
passed, 8 skipped.

## Not verified

- CFG-parallel across two physical cards. The host queue leases one card
per job, so the router was armed with the primary card as its own
secondary. Since the router never pairs Z-Image calls, no replica is
built in either arm. Making CFG-parallel actually parallelise Z-Image is
a separate change and is not done here.
- On the default tier, CFG-parallel does not arm on Z-Image in either
arm: the CUDA graph wrapper owns the forward slot. The router case was
measured with CUDA graphs off, and with the eager tier (no compile, so
nothing to recompile).
- Steady-state s/step under the static skip on an exclusive card.
- A step cache on Z-Image, since no Z-Image pipeline can run one today.
- Streamed offload. It is unchanged and still not armed.
NilayYadav pushed a commit that referenced this pull request Nov 6, 2026
…n the DiT is offloaded (unslothai#16886)

## Summary

When a GPU is too small to hold the LTX-2.5 DiT, the int8 load offloads
it. Offload hooks cannot move torchao weights, so these loads skip the
hosted `LTX-2.5-INT8-ConvRot.safetensors` and quantize at load instead.
Concretely, an offloaded int8 load:
- stages the 36 GB of dense bf16 `transformer/` shards;
- quantizes 480 Linears into native (torchao-free) int8 at load;
- writes the 23.4 GiB result to the local prequant cache in the
background, while the first clip renders.

The hosted file already holds per-row int8 codes and float32 scales of
the same ConvRot-rotated weights. That is exactly what
`NativeWeightOnlyLinear` stores. This PR reads the hosted file directly
into native Linears whenever the plan offloads and the native W8A8
ConvRot build would run:
- no dense shards are staged;
- nothing is quantized at load;
- nothing is written to the cache.

## What / why / evidence

**What**
- **New `diffusion_native_hosted.py`:** reads the hosted int8 file into
native Linears. It refuses the file, and the load falls back to the
dense shards and the runtime build as before, unless all of the
following hold:
- the metadata (scheme, family, component, dtype, ConvRot kind and
group, min_features, excluded layers) matches the native build;
  - the quantized layer set equals the set the runtime build would swap;
  - the rotated layers are exactly those whose width the group divides;
  - zero points are all zero and there are no static activation scales;
- the recorded md5-canonical-v2 fingerprint verifies. This is the same
check the torchao load runs, through a plain-tensor `HostedInt8Parts`
view whose digests equal the `Int8Tensor`'s.
- **Planner (`video.py`):** when the artifact-sized plan still offloads
and the request resolves to int8 on a CUDA card with the W8A8 ConvRot
path, the planner stages the hosted file instead of the dense shards.
This applies to both the load's pre-download and the download panel's
plan.
- **Load (`video.py`):** after a native-cache miss, the load reads the
hosted file. A local native-cache hit still wins, so an existing user
replays the build they already have.
- **Scope:** opt-in per family (`native_offload_from_hosted_int8`, set
for LTX-2.5 only). `UNSLOTH_VIDEO_NATIVE_HOSTED=0` restores the old
path.

**Why.** The Nov 5 G4 16 GiB INT8 fresh first clip took 316.8 s. Its log
shows where the time went:
- `built 480 host linear(s) on cuda one at a time (25.8 GB in 100.8 s)`:
the dense shards were read from disk;
- a 94.8 s background cache write;
- a 99.7 s first encode alongside that write;
- a 58 s pin wait.

**Accuracy.** Frames are not bit-identical to base. The runtime build
quantizes the bf16 weights itself, while the hosted file was built by
the hosted-checkpoint builder. Both are per-row symmetric int8 of the
same ConvRot-rotated weights, but about 7-8% of codes differ by 1 and
the scales differ by about 0.6%. The codes this PR loads are the ones
Studio's resident int8 path (the default on cards that hold the DiT)
already uses. Measured against Studio's own bf16 render on the same VM:

| LPIPS (prompt v0 / v1) | vs Studio bf16 | vs Studio resident int8
(hosted file, torchao) |
|---|---|---|
| base (runtime native build) | 0.085 / 0.075 | 0.079 / 0.080 |
| head (hosted codes, native) | 0.097 / 0.047 | 0.086 / 0.054 |

Both arms of each tree are bit-identical to each other (A/A, PSNR 99
dB).

**Evidence. LTX-2.5 1280x704x121 two-stage distilled, INT8, held to a 16
GiB budget on a G4 (RTX PRO 6000 Blackwell), Colab.** Base = main
b75a4cd, head = this branch, one VM, one fresh process per arm.
- Page cache: every Studio arm first reads the pack, the hosted INT8
file AND the dense bf16 shards, so this table compares work, not disk.
- First clip = load + cold render.

| arm | load s | cold render s | first clip s | steady s / clip |
|---|---|---|---|---|
| base fresh #1 | 16.8 | 85.1 (denoise 62.7) | 101.8 | 10.51 |
| base fresh #2 | 15.7 | 52.3 (denoise 34.3) | 68.0 | 10.60 |
| head fresh #1 | 34.8 | 40.5 (denoise 29.3) | 75.3 | 10.49 |
| head fresh #2 | 34.2 | 40.0 (denoise 29.2) | 74.2 | 10.49 |
| base returning | 18.5 | 149.8 (pin wait 85.9, encode 48.4) | 168.3 |
10.51 |
| head returning | 13.1 | 28.0 | 41.1 | 10.63 |

- **Base fresh varies a lot** (68 to 102 s) because its 23.4 GiB
background write (81 s) overlaps the first render. Head has no write.
- **Head fresh load** includes the one-time fingerprint verification of
the 24 GB file (about 20 s). A returning load reads the file in 0.6 s.
- **Base returning** reads its native cache file back, and pinning it
took 87 s from disk.
- **Disk:** head keeps 24 GB of hosted file instead of 36 GB of dense
shards plus a 23.4 GiB cache entry. A fresh user downloads 12 GB less.

**Same row with the dense shards on disk but not in the page cache**,
the condition of the Nov 5 row: the pack and the hosted file are
prewarmed, and the 35.4 GiB of `transformer/` shards are evicted before
every Studio arm. Same kind of VM, second session:

| arm | load s | cold render s | first clip s |
|---|---|---|---|
| base fresh #1 | 34.5 | 143.8 (pin wait 50.5, denoise 77.1) | 178.3 |
| base fresh #2 | 92.9 | 54.8 | 147.8 |
| head fresh #1 | 32.2 | 39.5 | 71.7 |
| head fresh #2 | 29.6 | 40.0 | 69.7 |
| base returning | 15.6 | 120.3 (pin wait 98.5) | 136.0 |
| head returning | 10.6 | 21.5 | 32.1 |

Head fresh is 2.1-2.6x faster and head returning 4.2x faster. Each
tree's two fresh arms render bit-identical frames, and the frames match
the first session's.

## Tests

New `studio/backend/tests/test_video_native_hosted.py` (11 tests, CPU,
tiny LTX2VideoTransformer3DModel written in the hosted layout):
- **Native layout:** the hosted file reads into exactly the runtime
native build's layer set, with the same `rot_group` / `act_int8` /
shapes. Codes and scales come from the file, and every dense tensor is
bit-equal to the dense model's.
- **Refusals:** wrong rotation group, other family, unrotated file,
different excludes, a missing layer, a static activation scale, and
corrupted codes (fingerprint mismatch) each fall back. So do a
weight-only or fp8 native build.
- **Fingerprint:** `HostedInt8Parts` gives the same canonical digest as
a torchao `Int8Tensor`.
- **Gating:** only an opted-in family with an int8, CUDA, W8A8 build
takes the hosted file, and the env switch turns it off.

These tests fail on main (the module does not exist).
`test_video_ltx25_prequant.py`, `test_video_prequant.py`,
`test_diffusion_prequant.py`, `test_diffusion_native_stream_build.py`
and `test_diffusion_native_quant.py` pass, except one test that fails on
main as well with this host's torchao 0.17
(`test_unpinned_torchao_host_copy_is_a_distinct_wrapper_over_the_same_data`).

## Not proven

- **Frames:** not bit-identical to base (different quantization of the
same weights, see Accuracy). Two prompts are not enough to call the
LPIPS difference either way.
- **Other hosts:** only the G4 at 16 GiB was measured. L4 / A100 offload
rows and a host with less RAM than the 24 GB file read were not run.
- **Compile:** no new compiled code. The modules are the same
`NativeWeightOnlyLinear` class the runtime build makes, so no compile
check was rerun on GPU.
NilayYadav pushed a commit that referenced this pull request Nov 23, 2026
## Summary

On a native FSDP2 resume every rank calls `torch.load(optimizer.pt,
map_location="cpu")` on the whole, unsharded
optimizer state and then keeps only its own shards. An eager load gives
each rank its own anonymous copy of the full
file, so host RAM needs about (ranks per node) x (optimizer.pt size) at
the moment of the resume. For full fine-tuning
with AdamW that is 8 bytes per parameter per rank.

This loads `optimizer.pt` with `mmap=True`. The tensors are file-backed
and the ranks on one node share the pages
through the page cache, so the anonymous allocation goes away.
`set_optimizer_state_dict` still copies each rank's
shards to the device exactly as before.

- A file object, or a file torch cannot map (legacy non-zip
serialization), loads eagerly as before.
- Other load errors still propagate (the fallback only matches torch's
own "mmap can only be used" error).
- Only `native_load_optimizer` changes. The DCP directory path
(`UNSLOTH_FSDP2_DCP_OPTIM=1`), the scheduler load and
  the model weight reader are untouched.

## Measurements

Kaggle 2x T4, Qwen3-0.6B full fine-tuning, native FSDP2 sharded over 2
ranks, `adamw_torch` (optimizer.pt 4.77 GB),
torch 2.14.1, transformers 5.17.0. The window measured is the call to
`native_load_optimizer`, with RSS sampled every
20 ms. Arms alternate: eager, mmap, eager, mmap.

| arm | RssAnon peak increase per rank | host MemAvailable drop (both
ranks) | load time | resumed losses (steps 4, 5) |
|---|---|---|---|---|
| eager #1 | +4.57 GiB | 8.8 GiB | 23.5 s (cold cache) | 11.260438,
11.153262 |
| mmap #1 | +0.13 GiB | 0.3 GiB | 4.8 s | 11.260438, 11.153244 |
| eager #2 | +4.57 GiB | 8.8 GiB | 7.6 s | 11.260438, 11.153244 |
| mmap #2 | +0.13 GiB | 0.1 GiB | 4.8 s | 11.260438, 11.153270 |

- The anonymous memory a rank needs for the resume drops from 4.57 to
0.13 GiB (-97%). Repeated runs of each arm
  give the same number (spread 0.00 GiB).
- Device peak during the load is unchanged (5.571 GiB in every arm).
- Losses: step 4 is bitwise identical in all four arms. Step 5 varies by
up to 2.6e-5 between the two eager runs
  themselves, and the mmap runs fall inside that spread.

The same check on torch 2.15.0, this branch's tree against main with no
injection, alternating main / head / main /
head. On the head, `torch.load` received `mmap=True` for `optimizer.pt`
on both ranks:

| arm | RssAnon increase per rank | host MemAvailable drop | load time |
losses (steps 4, 5) |
|---|---|---|---|---|
| main | +4.57 GiB | 9.14 GiB | 23.5 s (cold) | 11.280999, 11.154003 |
| this branch | +0.13 GiB | 0.28 GiB | 5.0 s | 11.280999, 11.153976 |
| main | +4.57 GiB | 8.68 GiB | 7.8 s | 11.280999, 11.154009 |
| this branch | +0.13 GiB | 0.15 GiB | 4.9 s | 11.280999, 11.154009 |

## Tests

- `tests/test_fsdp2_native_optim_mmap_load.py` (new):
`native_load_optimizer` passes `mmap=True` for a path; the
mapped load equals the eager one; a legacy non-zip file and a file
object load eagerly; other errors propagate.
  4 of the 5 fail on main and all 5 pass here.
- `tests/test_native_resume_old_torch.py` still passes: torch < 2.6 is
refused before any load.
- The gloo resume tests (`test_fsdp2_native_resume_gloo.py`,
`test_fsdp2_native_dcp_resume_gloo.py`,
  `test_fsdp2_native_optim_unstepped_gloo.py`) pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants