Skip to content

Fix the cold unsloth.save import, the preview role map and the GPU memory cap - #11077

Merged
danielhanchen merged 17 commits into
mainfrom
pr/import-order-rolemap-memfraction
Sep 17, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
pr/import-order-rolemap-memfraction

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Three independent defects that share nothing but the fact that each one is a small, contained
correctness problem in a path nobody exercises on the machine it breaks on.

  1. A cold import unsloth.save raised ImportError on Apple Silicon, because the only thing
    that hid an import cycle in this repo was the GPU init path, which macOS never runs.
  2. Studio's dataset preview showed ShareGPT roles that the training run would not use, whenever
    the dataset spelled them Human, GPT, Assistant or with stray whitespace.
  3. A training run had no way to leave GPU memory for anything else on NVIDIA. The only cap was
    UNSLOTH_ROCM_MEM_FRACTION, read behind an IS_ROCM gate, so it was AMD only.

Each is a separate commit and can be reviewed on its own.

Root cause

1. The cold import cycle

unsloth/save.py imports .models.loader_utils, which executes unsloth/models/__init__.py.
Three modules under unsloth/models/ imported names back out of unsloth.save at module
scope, so that chain closed a cycle:

unsloth/save.py          -> from .models.loader_utils import ...
unsloth/models/__init__  -> from .llama import FastLlamaModel
unsloth/models/llama.py  -> from .vision import FastBaseModel
unsloth/models/vision.py -> from ..save import patch_saving_functions   # half built
ImportError: cannot import name 'patch_saving_functions' from partially initialized
module 'unsloth.save' (most likely due to a circular import)

unsloth/__init__.py hid this, but only on the GPU path, because _gpu_init.py imports
.models before .save, so by the time save.py runs the package it needs is already
complete. The MLX branch of unsloth/__init__.py never reaches _gpu_init, so on Apple
Silicon the cycle was live and importing unsloth first did not avoid it.

2. The dataset preview role map

unsloth_zoo.dataset_utils.standardize_data_formats matches its role aliases against
role.strip().lower(), because real datasets spell them Human, GPT, Assistant or
" user ". Studio's preview keeps its own copy of the same seven aliases in
studio/backend/hub/utils/dataset_format.py and looked the raw value up. Nine of ten
spellings previewed with the raw string as the role while the training run standardised them,
so the preview disagreed with the run it was previewing, and the preview is the thing the user
reads before starting the run.

3. The memory cap

set_per_process_memory_fraction was called in exactly one place in
studio/backend/core/training/worker.py, inside a block gated on _hw.IS_ROCM, driven by
UNSLOTH_ROCM_MEM_FRACTION. torch.cuda.set_per_process_memory_fraction serves both vendors,
so the gate, not the mechanism, was what kept NVIDIA uncapped.

Changes

unsloth/models/{vision,llama,sentence_transformer}.py and unsloth/save.py

Each of the three modules now defines a shim of the same name that imports the real function on
first call, instead of binding it at module scope. save.py then replaces those shims with the
real objects on the last line of its own module body, where .models is fully imported and this
module is finished.

So after import unsloth.save, which is the only way to reach the real function at all, the
module attributes are exactly the functions they were before this change: same identity, same
signature, same docstring, same behaviour under inspect. A tree that imports unsloth.models
and never unsloth.save keeps a working attribute through the shim, which is the only thing
that can work there. save.py only replaces a function carrying its own
_unsloth_deferred_shim marker, so it can never overwrite a function a caller put there.

No public name changes, no call site changes, no signature changes.

studio/backend/hub/utils/dataset_format.py

The alias lookup goes through a new _normalize_role_alias, the same strip() and lower()
the trainer uses. An alias nothing recognises is still shown exactly as written, which is what
this line always did; only the matching is normalised. A role that is missing, empty or nothing
but whitespace still falls back to user.

studio/backend/core/training/worker.py

_gpu_memory_fraction becomes the single policy entry point, in the shape the issue proposes.
With no override it answers 1.0 on every non-ROCm backend, which is what torch does with no
cap at all, and delegates the ROCm arm unchanged to the existing _rocm_memory_fraction so the
reserve policy, its floors and its denominator handling stay in one place with their own tests.

UNSLOTH_GPU_MEM_FRACTION is the new backend neutral name. On a ROCm host
UNSLOTH_ROCM_MEM_FRACTION is still read first, so a machine that already exports it keeps
exactly the cap it had; the neutral name is read after it, and is the only one NVIDIA reads. A
host that sets neither is byte for byte unchanged on either vendor, and nothing is logged.

The cap is applied to every visible CUDA device by index. set_per_process_memory_fraction
keeps the fraction per device and defaults device to current_device(), so calling it
without one would cap cuda:0 and leave every other shard of a multi GPU run allocating
freely while the log said otherwise. The fraction comes from an environment variable and
carries no device of its own, so the same value is the right one for each.

XPU, MPS and the inference paths are untouched.

Compatibility

Run through the version matrix on the five corners the change can reach. Every corner executes
the cold import tests, the cold import repro and the saving suites; the Studio corner
additionally executes the preview and memory cap tests and the simulated hardware matrix. Cells
marked skip are gated out because that corner does not carry the other half's dependencies, not
because anything failed.

corner python torch transformers trl peft cold import tests cold import repro saving suites preview roles memory cap hardware simulation
mA 3.10.19 2.6.0+cu124 4.57.6 0.22.2 0.18.0 pass pass pass skip skip skip
mC 3.13.12 2.11.0+cu130 5.5.0 1.0.0 0.20.0 pass pass pass skip skip skip
mD 3.13.12 2.14.0+cu130 5.17.0 1.13.0 0.20.0 pass pass pass skip skip skip
mX1b 3.13.12 2.14.0+cu130 5.17.0 1.13.0 0.18.0 pass pass pass skip skip skip
mStudio 3.13.12 2.10.0+cpu 5.4.0 0.29.1 0.18.1 skip skip skip pass pass pass

The memory cap was also simulated over Windows, Linux, WSL and macOS against NVIDIA, AMD and
CPU, by executing the shipped blocks with faked hardware. With no variable set, every cell is
identical to main on both vendors. With UNSLOTH_GPU_MEM_FRACTION=0.7 set, NVIDIA caps at 0.70
where it was previously uncapped, and AMD honours the neutral name where it previously ignored
it. With UNSLOTH_ROCM_MEM_FRACTION set, AMD is unchanged.

That the import change does not alter import behaviour is measured rather than argued. A script
snapshots the import surface (the names on each of the three modules, their callability and
signature, and the unsloth.save implementation each one resolves to) and the documents
produced on main and on this branch are byte identical on Linux. The same claim on macOS and
Windows rests on the source gates, which run on both, plus the fact that the change is pure
python with no platform branch in it; a GitHub runner cannot import unsloth.models at all, so
it cannot answer the behavioural half on any OS.

Tests

New, all failing on main and passing here.

  • tests/test_cold_import_order.py, 12 tests. Source gates over the module scope imports, the
    shims and the publish back, the original ordering reproduced in a child interpreter, and the
    post import attributes checked against unsloth.save itself. On main: 5 failed, 7 passed.
    Here: 12 passed. The 7 that pass on both are the ones that pin what must not change.
  • studio/backend/tests/test_dataset_preview_role_aliases.py, and
    studio/backend/tests/test_gpu_mem_fraction_env.py. Both fail to import on main, because
    the symbols they pin do not exist there.
  • studio/backend/tests/test_rocm_oom_guard.py: its two source pins are updated to the new
    wiring rather than loosened.

Existing suites, both arms, same versions, same machine.

unsloth tests/            main   42 failed, 24041 passed, 684 skipped, 9 errors
                        branch   44 failed, 24049 passed, 686 skipped, 9 errors
studio/backend tests/     main   15 failed, 46582 passed, 299 skipped, 17 errors
                        branch   17 failed, 46918 passed, 296 skipped, 15 errors

The failure sets differ only inside tests/version_compat/test_trl_padding_free_max_length.py,
tests/studio/... and two Studio files, and the differing names do not overlap between the two
arms, which is the signature of parallel execution rather than of a change. Run serially, those
same files give 151 passed on both arms, and
tests/test_account_tool_confinement.py plus tests/test_openai_auto_download.py give the same
three failures on both arms. The 28 failures shared by both arms of the unsloth run and the 30
shared by both arms of the Studio run are pre-existing on main and touch no file in this
change.

Gates:

python -m pytest --collect-only -q <the 16 files in consolidated-tests-ci.yml>   275 collected
python -m pytest tests/test_import_fixes_drift.py                                26 passed, 10 skipped

Cross platform, the four test files this PR adds or edits, with torch, transformers,
peft, trl, datasets, accelerate and unsloth_zoo installed on each runner:

ubuntu-latest     494 passed, 8 skipped
macos-15          493 passed, 9 skipped
windows-latest    494 passed, 8 skipped

The skips are named, not silent, and they are the honest part. No GitHub hosted runner
has an accelerator that unsloth_zoo.device_type recognises, so import unsloth.models
raises there and the eight cases that need it skip rather than run. They execute here, on
a machine with a GPU, where the file is 12 passed. On macos-15 the cross repo alias pin
skips for the same reason, which is the ninth skip. What every runner does execute is the
source gates, and those are what would catch a reintroduced module scope import on any
platform.

Two of those skips used to be failures, and finding that out is why this PR has two extra
commits. The gates were written against importlib.util.find_spec and
pytest.importorskip, both of which ask whether a package is installed. The real question
is whether it imports, and on a macOS runner with every dependency present it does not.
Both gates now probe the import and name the error in the skip reason.

Evidence

Reproduced on main and fixed here, one script per item, both arms logged:

  • cold import unsloth.save: main raises the ImportError above, branch imports and the
    deferred hand off resolves to the same objects.
  • dataset preview: 9 of 10 role spellings not normalised on main, 10 of 10 normalised here,
    driven through the real /api/datasets/check-format route on a mixed case ShareGPT upload.
  • memory cap: the simulated platform by vendor matrix described above, main shows only the
    ROCm block, branch shows both, and every unset cell matches.

Known limitations

  • The Apple Silicon arm is reproduced by import ordering, not by MLX. The repro and the tests
    put a bare unsloth package object in sys.modules, which is all unsloth.models ever
    needed from the parent, and import unsloth.save first, which is the same ordering the MLX
    branch leaves behind. Running the real MLX branch on a hosted macOS runner is not possible
    today: with mlx and mlx-lm installed, unsloth_zoo.device_type.get_device_type() still
    raises NotImplementedError: Unsloth currently only works on NVIDIA, AMD and Intel GPUs, so
    the import never gets that far. That is worth knowing on its own and is a separate matter.
  • There is no Settings control yet, which is the other half of [Feature] Unsloth Studio / Desktop: cap GPU memory for XPU and MPS training, and make image generation honour the VRAM Budget #8178. The issue itself says the
    product question is the work: set_per_process_memory_fraction bounds the torch allocator in
    the training worker and nothing else, so a control labelled "max VRAM" would overpromise
    against llama.cpp, the diffusion paths and a resident chat model. It also collides by name
    with the existing vram_budget_fraction setting, which is the llama.cpp context fit reserve,
    is clamped to [0.80, 1.00] and means something different. The env var half is useful on its
    own and does not constrain that decision.
  • XPU and MPS still have no cap. set_per_process_memory_fraction exists on those namespaces
    but neither the policy nor the reporting has been exercised on that hardware, so wiring it
    blind would be a claim rather than a fix.
  • studio/backend/utils/datasets/format_conversion.py keeps a second, five entry role map for
    the VLM image conversion writer. It already lowercases but does not strip, and it is a
    different function with a different job: it decides what a converted dataset contains, not
    what a preview shows. It is listed here rather than changed, because widening it is a
    behavioural change to stored data and deserves its own change and its own tests.

Part of #8178.


Review round: the memory cap covered one GPU

Codex raised that set_per_process_memory_fraction(fraction) with no device applies only to
torch.cuda.current_device(). Confirmed in torch's own source: the function defaults device to
current_device() and the allocator keeps the fraction per device. Studio shards a run across
every visible GPU through get_device_map, so cuda:1 and up allocated freely while the log
said a process-wide cap was in force.

It now iterates torch.cuda.device_count() and names each device explicitly, logging one line
per device with that device's own total. The fraction is an env override carrying no device of
its own, so the same value is correct for each.

Three tests, executed against the shipped block rather than asserted from its source: four
devices all capped, a process whose current device is 3 still capping 0, and the single-GPU
control unchanged at one call and one line. The two multi-device ones fail against the previous
commit. _FakeCuda now records a per-device map, because a single scalar could not tell a cap on
every GPU from a cap on cuda:0.

UI evidence

The dataset preview role map in this PR changes what Studio SHOWS, even though
git diff --stat studio/frontend is empty: the preview rows come from preview_samples on
POST /api/hub/datasets/check-format, which the "View dataset" dialog renders. Before/after
screenshots from two isolated installs are attached below.

Before / after

dataset preview roles, before and after

Two isolated installs built by the PR's own install.sh --local: BEFORE is the merge base
2ab07c9c4, AFTER is head 1fa00a3ed. One scene drives both: it writes a five-turn ShareGPT
JSONL whose from values are System, Human, GPT, " user " and moderator, uploads it
through the training section, and opens the "View dataset" dialog.

what the dialog shows BEFORE AFTER
"role":"System" present gone
"role":"Human" present gone
"role":"GPT" present gone
"role":" user " present gone
"role":"system" absent present
"role":"user" (once) twice, from Human and " user "
"role":"assistant" absent as a value present, from GPT
"role":"moderator" present present

moderator is the control. It is not an alias in either build, so it must read the same on both
halves; if it had changed too, the dialog would simply be lowercasing everything it renders and
the pair would prove nothing. It is identical, and the whitespace-padded " user " collapsing to
user shows the strip as well as the lower.

Two honest limits on this pair. The scene's own check-format API call returned 404 on BOTH
sides (the scene used the wrong route prefix), so the numeric half of the evidence is the dialog
text rather than a second reading of the response; the dialog text does come from the same
server that was photographed. And shows_assistant was True on both sides as a raw substring,
because the word appears in the dialog chrome as well as in the data, so the discriminating
facts are the "role":"..." values above rather than that flag.

unsloth/save.py imports .models.loader_utils, which runs unsloth/models/__init__.py.
vision.py, llama.py and sentence_transformer.py imported names back out of
unsloth.save at module scope, so the chain closed a cycle and a cold
`import unsloth.save` raised

  ImportError: cannot import name 'patch_saving_functions' from partially
  initialized module 'unsloth.save'

unsloth/__init__.py hid this on the GPU path, and only there, because _gpu_init
imports .models before .save. The MLX branch never reaches _gpu_init, so on Apple
Silicon the cycle was live and importing unsloth first did not avoid it.

Each of the three modules now defines a shim of the same name that imports the real
function on first call, and save.py replaces those shims with the real objects on
the last line of its own module body, where .models is fully imported and this
module is finished. So once unsloth.save has been imported at all, which is the
only way to reach the real function anyway, the module attributes are exactly the
functions they were before: same identity, same signature, same docstring. A tree
that imports unsloth.models and never unsloth.save keeps a working attribute
through the shim, which is the only thing that can work there. save.py only ever
replaces a function carrying its own _unsloth_deferred_shim marker, so it cannot
overwrite something a caller put there. No public name changes and no call site
changes.

Measured rather than argued: a script that snapshots the import surface (the names
on each module, their callability and signature, and the unsloth.save
implementation each one resolves to) produces byte identical documents on main and
here.

tests/test_cold_import_order.py holds the line with source gates over the module
scope imports, the shims and the publish back, plus the original ordering
reproduced in a child interpreter and the post import attributes checked against
unsloth.save itself.
…eview

unsloth_zoo.dataset_utils.standardize_data_formats matches its role aliases against
role.strip().lower() (unslothai/unsloth-zoo#1225). Studio's dataset preview keeps its
own copy of the same seven aliases in studio/backend/hub/utils/dataset_format.py and
looked the raw value up, so a dataset spelling its roles Human, GPT, Assistant or
" user " previewed with those raw strings as roles while the training run standardised
them. The preview disagreed with the run it was previewing.

The lookup now goes through _normalize_role_alias, the same strip and lower. An alias
nothing recognises is still shown as written; a role that is missing, empty or nothing
but whitespace still falls back to user.

Verified through the real /api/datasets/check-format route on a mixed-case ShareGPT
upload: 9 of 10 spellings previewed with the raw role before, all 10 normalise now.
The only cap on how much GPU memory a training run may take was
UNSLOTH_ROCM_MEM_FRACTION, read in one place behind _hw.IS_ROCM, so NVIDIA had no
cap at all. set_per_process_memory_fraction lives on torch.cuda for both vendors,
so one variable can serve both.

_gpu_memory_fraction is now the single policy entry point. With no override it
answers 1.0 on every non-ROCm backend, which is what torch does with no cap, and
delegates the ROCm arm unchanged to _rocm_memory_fraction. A host that sets nothing
is unchanged on either vendor, and nothing is logged. On a ROCm host
UNSLOTH_ROCM_MEM_FRACTION is still read first, so existing setups keep the cap they
had; the neutral name is read after it, and is the only one NVIDIA reads.

Simulated over Windows, Linux, WSL and Mac against NVIDIA, AMD and CPU by executing
the shipped blocks with faked hardware: every unset cell is identical to main.

XPU, MPS and the inference paths are untouched, and there is no Settings control
yet; unsloth#8178 asks for one and that half is a follow-up, since the label has to
settle what it bounds before a slider can mean anything.

tests/test_rocm_oom_guard.py's two source pins are updated to the new wiring rather
than loosened, and test_gpu_mem_fraction_env.py executes section 1h directly.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T11:00:16.569701Z 7fb5d8b Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
…list

The behavioural cases in tests/test_cold_import_order.py were gated on
importlib.util.find_spec for torch, transformers and peft. That is the wrong
question. A host can have all three installed and still be unable to import
unsloth.models, because unsloth_zoo.device_type raises

  NotImplementedError: Unsloth currently only works on NVIDIA, AMD and Intel GPUs.

when it recognises no accelerator. A GitHub macos-15 runner with torch installed is
exactly that host, and it was measured: the four cases and the parametrised one
turned red there, reporting an environment limit as a defect.

The gate now runs one child interpreter at collection, imports unsloth.models and
skips when that does not complete, naming both reasons. Confirmed both ways on this
machine: 12 passed with an accelerator, and 4 passed with 8 skipped when the
accelerator is hidden, where the old gate gave 8 failures.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
pre-commit-ci Bot and others added 2 commits September 16, 2026 06:26
…absent

test_the_alias_set_is_the_one_the_trainer_accepts reached unsloth_zoo through
pytest.importorskip, which only catches ImportError. unsloth_zoo raises
NotImplementedError from device_type at import time on a host with no accelerator it
recognises, so on a GitHub macOS runner the pin turned red instead of skipping.
Measured there, with unsloth_zoo and mlx both installed: it is the accelerator check,
not a missing package.

Catching Exception and naming the error in the skip reason keeps the pin meaningful
where the zoo is usable and honest where it is not.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen danielhanchen self-assigned this Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7fb5d8ba64

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/vision.py Outdated
Comment on lines +67 to +71
# The shim is short lived: `unsloth/save.py` replaces it with the real function on the last
# line of its own module body, so once `unsloth.save` has been imported at all, which is the
# only way to reach the real function anyway, this attribute is that function, identity and
# signature included. The shim answers only for a tree that imported `unsloth.models` and
# never `unsloth.save`. Pinned by tests/test_cold_import_order.py.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid loading GPU-only models during the MLX save import

On the Apple Silicon/MLX path this deferral still does not make import unsloth.save succeed: save.py imports .models.loader_utils, which executes models/__init__.py; that imports rl.py and then models/rl_replacements.py:39, whose module-scope unsloth_zoo.device_type import raises NotImplementedError when no CUDA/ROCm/XPU accelerator is present. Execution therefore never reaches the publish-back block, and the new behavioral tests skip precisely when unsloth.models is not importable, including the target macOS environment. The save utilities need to avoid executing models/__init__.py, or that import tree must be made MLX-safe.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checked this one against the installed unsloth_zoo and the premise does not hold. unsloth_zoo/device_type.py binds _IS_MLX = is_mlx_available() at module scope and get_device_type returns "mlx" as its FIRST branch, before any CUDA, ROCm or XPU probe, so on the Apple Silicon path this is about, the NotImplementedError you name is unreachable: the accelerator probes are never run. is_mlx_available is the same predicate unsloth/init.py uses to enter the MLX branch in the first place (Darwin, arm64, mlx importable, UNSLOTH_FORCE_GPU_PATH unset), so the two cannot disagree about which host they are on. The NotImplementedError does fire on a Mac with no MLX installed, but that host is not on the MLX path and is a pre-existing, separate matter rather than something this deferral introduced or claims to fix. The cycle this PR removes is real and the deferral removes it; the tests skip only where unsloth.models genuinely cannot import, which is not the MLX case.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 7fb5d8ba64

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

Performance, before against after, per part

This PR lands in three different places, so each was measured where it actually runs rather than
through one generic benchmark. B200 plus Xeon Platinum 8559C, torch 2.14.0+cu130, transformers
4.57.6, trl 0.24.0. Three arms selected by PYTHONPATH only: head f1cbd717f, base = the merge
base 2ab07c9c4, and a second independent checkout of 2ab07c9c4 as the negative control. Private
UNSLOTH_COMPILE_LOCATION per arm. GPU 0 for training, GPU 2 for imports, both verified idle first.

Part 1, the cold unsloth.save import: neutral

Fresh subprocess per measurement, one discarded warm-up plus 9 measured per arm, arm order rotated.

measurement head base control head - base control - base
import unsloth 11.345 s 11.765 s 11.544 s -0.420 -0.221
import unsloth; import unsloth.save 10.866 s 11.056 s 11.127 s -0.190 +0.071
-X importtime cumulative 9445.5 ms 9762.8 ms 9893.8 ms -317.3 +131.0
modules loaded 7679 7679 7679 0 unique 0 unique

The module-set comparison answers the "does it make something eager" question directly: identical
sets, zero modules present in one arm and not the other. Nothing becomes eager, nothing is dropped.
Every module that moved by 20 ms or more moved comparably in the control, which itself moved
unsloth_zoo by +303 ms, larger than any head-versus-base entry.

What changed is position, not cost. unsloth.save moves later, not earlier:

arm where it appears self cumulative
base nested inside unsloth.models.vision 2.108 ms 3.825 ms
head after unsloth.models completes, at the _gpu_init level 1.699 ms 3.572 ms

Runtime side of the shim: by the time import unsloth returns, unsloth/save.py's tail has already
replaced the shim with the real function, verified in the head arm
(patch_saving_functions.__module__ == "unsloth.save", no _unsloth_deferred_shim). Where the shim
does survive, a tree that imported unsloth.models and never unsloth.save, the extra frame plus
the sys.modules lookup measures 0.110 us per call, on a function called once per model load.

Part 2, the preview role map: a real regression, small and O(1)

Three paths per arm, one warm-up plus 9 reps per process, 3 processes per arm interleaved.
datasets.disable_caching() is asserted live in the harness; without it the second and later
conversion reps measure a fingerprint cache hit instead of the conversion.

path rows head base control head - base control - base
preview _standardize_sharegpt_row 10 000 6.530 ms 4.674 4.626 +1.856 -0.048
100 000 64.843 ms 49.296 46.844 +15.546 -2.453
conversion inner loop 10 000 6.943 ms 3.894 4.150 +3.050 +0.257
100 000 71.178 ms 38.648 38.780 +32.529 +0.131
standardize_chat_format end to end 100 000 321.660 ms 288.248 279.735 +33.412 -8.513

This one is real: at 10k and 100k rows the gap is 40x to 250x the control's, and it reproduces in
all three passes. Per-row cost is flat across a 1000x range, 0.643 / 0.653 / 0.648 us on preview and
0.655 / 0.694 / 0.712 us on conversion, so the change is strictly O(1) per row with no
algorithmic worsening. The extra work is one _normalize_role_alias call per message: a Python
frame plus str(role).strip().lower(), about +0.08 us per message, +0.16 us per row on preview and
+0.33 us on conversion
. In absolute terms +15.5 ms on a 100k-row preview and +33 ms on a 100k-row
conversion, paid once per dataset, or +11.6% end to end at 100k rows.

Part 3, the GPU memory cap: neutral

Shape first: on a non-ROCm host the block runs once at worker start, inside
run_training_process, before the ML imports, calling set_per_process_memory_fraction once per
visible device and never again, and it is a complete no-op unless UNSLOTH_GPU_MEM_FRACTION is set.
Nothing repeats per step, per batch or per allocation.

The cap is driven through the arm's own helpers, so base and control read a live fraction of 1.0
while head reads the cap, printed and asserted in all 18 runs. Llama-3.2-1B-Instruct 4bit, LoRA
r=16, 61 steps, batch 2 x grad accum 3, seed 3407, 3 reps per arm, rotated.

Cap 0.9, which never binds:

metric head base control head - base control - base
live memory fraction 0.900 1.000 1.000 cap is live
steps/s 1.528 1.525 1.544 +0.20% +1.25%
peak allocated 1534.24 MiB 1534.24 1534.24 +0.00 +0.00
peak reserved 2016.00 MiB 2016.00 2016.00 +0.00 +0.00

Cap 0.0125, chosen to genuinely bind: 2292 MiB against the measured 2016 MiB peak reserved, 1.14x
headroom.

metric head base control head - base control - base
steps/s 1.420 1.408 1.413 +0.85% +0.36%
peak allocated 1534.24 MiB 1534.24 1534.24 +0.00 +0.00
peak reserved 2016.00 MiB 2016.00 2016.00 +0.00 +0.00

Throughput deltas are the same order as the control and positive in sign, which is not a plausible
effect of a cap. Peak allocated and reserved are byte-identical across all 18 runs, including with a
cap only 14% above the reserved high-water mark, so the caching allocator's segment sizing did not
change.

Verdicts

Part 1 neutral, part 2 a measurable +0.16 to +0.33 us per row that is O(1) and paid once per
dataset, part 3 neutral.

Not measured, and why

The MLX branch this import fix actually repairs cannot be exercised here: on a CUDA host
unsloth/__init__.py takes the GPU path, which imports .models before .save and hides the
cycle, so a cold import unsloth.save succeeds on both arms (3 of 3 each). For that specific
failure the differential is void, not a pass. What can be said is that the fix costs nothing on
the path this host does take. Also unexercised: the ROCm arm of the cap, the unified-memory
classification and the WDDM branch, since there is no AMD hardware here; the multi-device cap loop,
since only one device was visible; and the real Studio worker end to end, since the cap was driven
through the arm's own helpers in-process rather than launching run_training_process with its
queues.

@danielhanchen
danielhanchen merged commit e15a75e into main Sep 17, 2026
57 of 66 checks passed
@danielhanchen
danielhanchen deleted the pr/import-order-rolemap-memfraction branch September 17, 2026 12:09
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…mory cap (unslothai#11077)

* Defer the unsloth.models imports of unsloth.save so a cold import works

unsloth/save.py imports .models.loader_utils, which runs unsloth/models/__init__.py.
vision.py, llama.py and sentence_transformer.py imported names back out of
unsloth.save at module scope, so the chain closed a cycle and a cold
`import unsloth.save` raised

  ImportError: cannot import name 'patch_saving_functions' from partially
  initialized module 'unsloth.save'

unsloth/__init__.py hid this on the GPU path, and only there, because _gpu_init
imports .models before .save. The MLX branch never reaches _gpu_init, so on Apple
Silicon the cycle was live and importing unsloth first did not avoid it.

Each of the three modules now defines a shim of the same name that imports the real
function on first call, and save.py replaces those shims with the real objects on
the last line of its own module body, where .models is fully imported and this
module is finished. So once unsloth.save has been imported at all, which is the
only way to reach the real function anyway, the module attributes are exactly the
functions they were before: same identity, same signature, same docstring. A tree
that imports unsloth.models and never unsloth.save keeps a working attribute
through the shim, which is the only thing that can work there. save.py only ever
replaces a function carrying its own _unsloth_deferred_shim marker, so it cannot
overwrite something a caller put there. No public name changes and no call site
changes.

Measured rather than argued: a script that snapshots the import surface (the names
on each module, their callability and signature, and the unsloth.save
implementation each one resolves to) produces byte identical documents on main and
here.

tests/test_cold_import_order.py holds the line with source gates over the module
scope imports, the shims and the publish back, plus the original ordering
reproduced in a child interpreter and the post import attributes checked against
unsloth.save itself.

* Studio: normalise ShareGPT role case and whitespace in the dataset preview

unsloth_zoo.dataset_utils.standardize_data_formats matches its role aliases against
role.strip().lower() (unslothai/unsloth-zoo#1225). Studio's dataset preview keeps its
own copy of the same seven aliases in studio/backend/hub/utils/dataset_format.py and
looked the raw value up, so a dataset spelling its roles Human, GPT, Assistant or
" user " previewed with those raw strings as roles while the training run standardised
them. The preview disagreed with the run it was previewing.

The lookup now goes through _normalize_role_alias, the same strip and lower. An alias
nothing recognises is still shown as written; a role that is missing, empty or nothing
but whitespace still falls back to user.

Verified through the real /api/datasets/check-format route on a mixed-case ShareGPT
upload: 9 of 10 spellings previewed with the raw role before, all 10 normalise now.

* Studio: honour UNSLOTH_GPU_MEM_FRACTION on NVIDIA training workers too

The only cap on how much GPU memory a training run may take was
UNSLOTH_ROCM_MEM_FRACTION, read in one place behind _hw.IS_ROCM, so NVIDIA had no
cap at all. set_per_process_memory_fraction lives on torch.cuda for both vendors,
so one variable can serve both.

_gpu_memory_fraction is now the single policy entry point. With no override it
answers 1.0 on every non-ROCm backend, which is what torch does with no cap, and
delegates the ROCm arm unchanged to _rocm_memory_fraction. A host that sets nothing
is unchanged on either vendor, and nothing is logged. On a ROCm host
UNSLOTH_ROCM_MEM_FRACTION is still read first, so existing setups keep the cap they
had; the neutral name is read after it, and is the only one NVIDIA reads.

Simulated over Windows, Linux, WSL and Mac against NVIDIA, AMD and CPU by executing
the shipped blocks with faked hardware: every unset cell is identical to main.

XPU, MPS and the inference paths are untouched, and there is no Settings control
yet; unsloth#8178 asks for one and that half is a follow-up, since the label has to
settle what it bounds before a slider can mean anything.

tests/test_rocm_oom_guard.py's two source pins are updated to the new wiring rather
than loosened, and test_gpu_mem_fraction_env.py executes section 1h directly.

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

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

* Skip the cold import cases by probing the import, not the dependency list

The behavioural cases in tests/test_cold_import_order.py were gated on
importlib.util.find_spec for torch, transformers and peft. That is the wrong
question. A host can have all three installed and still be unable to import
unsloth.models, because unsloth_zoo.device_type raises

  NotImplementedError: Unsloth currently only works on NVIDIA, AMD and Intel GPUs.

when it recognises no accelerator. A GitHub macos-15 runner with torch installed is
exactly that host, and it was measured: the four cases and the parametrised one
turned red there, reporting an environment limit as a defect.

The gate now runs one child interpreter at collection, imports unsloth.models and
skips when that does not complete, naming both reasons. Confirmed both ways on this
machine: 12 passed with an accelerator, and 4 passed with 8 skipped when the
accelerator is hidden, where the old gate gave 8 failures.

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

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

* Skip the cross-repo alias pin when unsloth_zoo is unusable, not just absent

test_the_alias_set_is_the_one_the_trainer_accepts reached unsloth_zoo through
pytest.importorskip, which only catches ImportError. unsloth_zoo raises
NotImplementedError from device_type at import time on a host with no accelerator it
recognises, so on a GitHub macOS runner the pin turned red instead of skipping.
Measured there, with unsloth_zoo and mlx both installed: it is the accelerator check,
not a missing package.

Catching Exception and naming the error in the skip reason keeps the pin meaningful
where the zoo is usable and honest where it is not.

* Apply the GPU memory cap to every visible CUDA device

* Cap every ROCm device, and standardize training roles the way the preview does

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

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

* Default a blank training role to user, as the preview does

* Make the ROCm guard drift assertions whitespace-insensitive

* Consult the fallback role key when the inferred one is blank

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

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

* Shorten the memory cap and role alias comments

* Trim comments across the import-order, role-map and memory-cap changes

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant