Repository navigation
Fix the cold unsloth.save import, the preview role map and the GPU memory cap - #11077
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…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.
…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.
|
@codex security review |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| # 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. |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Performance, before against after, per partThis PR lands in three different places, so each was measured where it actually runs rather than Part 1, the cold
|
| 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.
…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]>
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.
import unsloth.saveraisedImportErroron Apple Silicon, because the only thingthat hid an import cycle in this repo was the GPU init path, which macOS never runs.
the dataset spelled them
Human,GPT,Assistantor with stray whitespace.UNSLOTH_ROCM_MEM_FRACTION, read behind anIS_ROCMgate, 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.pyimports.models.loader_utils, which executesunsloth/models/__init__.py.Three modules under
unsloth/models/imported names back out ofunsloth.saveat modulescope, so that chain closed a cycle:
unsloth/__init__.pyhid this, but only on the GPU path, because_gpu_init.pyimports.modelsbefore.save, so by the timesave.pyruns the package it needs is alreadycomplete. The MLX branch of
unsloth/__init__.pynever reaches_gpu_init, so on AppleSilicon the cycle was live and importing
unslothfirst did not avoid it.2. The dataset preview role map
unsloth_zoo.dataset_utils.standardize_data_formatsmatches its role aliases againstrole.strip().lower(), because real datasets spell themHuman,GPT,Assistantor" user ". Studio's preview keeps its own copy of the same seven aliases instudio/backend/hub/utils/dataset_format.pyand looked the raw value up. Nine of tenspellings 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_fractionwas called in exactly one place instudio/backend/core/training/worker.py, inside a block gated on_hw.IS_ROCM, driven byUNSLOTH_ROCM_MEM_FRACTION.torch.cuda.set_per_process_memory_fractionserves both vendors,so the gate, not the mechanism, was what kept NVIDIA uncapped.
Changes
unsloth/models/{vision,llama,sentence_transformer}.pyandunsloth/save.pyEach 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.pythen replaces those shims with thereal objects on the last line of its own module body, where
.modelsis fully imported and thismodule is finished.
So after
import unsloth.save, which is the only way to reach the real function at all, themodule attributes are exactly the functions they were before this change: same identity, same
signature, same docstring, same behaviour under
inspect. A tree that importsunsloth.modelsand never
unsloth.savekeeps a working attribute through the shim, which is the only thingthat can work there.
save.pyonly replaces a function carrying its own_unsloth_deferred_shimmarker, 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.pyThe alias lookup goes through a new
_normalize_role_alias, the samestrip()andlower()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_fractionbecomes the single policy entry point, in the shape the issue proposes.With no override it answers
1.0on every non-ROCm backend, which is what torch does with nocap at all, and delegates the ROCm arm unchanged to the existing
_rocm_memory_fractionso thereserve policy, its floors and its denominator handling stay in one place with their own tests.
UNSLOTH_GPU_MEM_FRACTIONis the new backend neutral name. On a ROCm hostUNSLOTH_ROCM_MEM_FRACTIONis still read first, so a machine that already exports it keepsexactly 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_fractionkeeps the fraction per device and defaults
devicetocurrent_device(), so calling itwithout one would cap
cuda:0and leave every other shard of a multi GPU run allocatingfreely 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.
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.7set, NVIDIA caps at 0.70where it was previously uncapped, and AMD honours the neutral name where it previously ignored
it. With
UNSLOTH_ROCM_MEM_FRACTIONset, 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.saveimplementation each one resolves to) and the documentsproduced on
mainand on this branch are byte identical on Linux. The same claim on macOS andWindows 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.modelsat all, soit cannot answer the behavioural half on any OS.
Tests
New, all failing on
mainand passing here.tests/test_cold_import_order.py, 12 tests. Source gates over the module scope imports, theshims and the publish back, the original ordering reproduced in a child interpreter, and the
post import attributes checked against
unsloth.saveitself. Onmain: 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, andstudio/backend/tests/test_gpu_mem_fraction_env.py. Both fail to import onmain, becausethe symbols they pin do not exist there.
studio/backend/tests/test_rocm_oom_guard.py: its two source pins are updated to the newwiring rather than loosened.
Existing suites, both arms, same versions, same machine.
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 twoarms, which is the signature of parallel execution rather than of a change. Run serially, those
same files give
151 passedon both arms, andtests/test_account_tool_confinement.pyplustests/test_openai_auto_download.pygive the samethree 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
mainand touch no file in thischange.
Gates:
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:
The skips are named, not silent, and they are the honest part. No GitHub hosted runner
has an accelerator that
unsloth_zoo.device_typerecognises, soimport unsloth.modelsraises 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_specandpytest.importorskip, both of which ask whether a package is installed. The real questionis 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
mainand fixed here, one script per item, both arms logged:import unsloth.save:mainraises theImportErrorabove, branch imports and thedeferred hand off resolves to the same objects.
main, 10 of 10 normalised here,driven through the real
/api/datasets/check-formatroute on a mixed case ShareGPT upload.mainshows only theROCm block, branch shows both, and every unset cell matches.
Known limitations
put a bare
unslothpackage object insys.modules, which is allunsloth.modelseverneeded from the parent, and import
unsloth.savefirst, which is the same ordering the MLXbranch 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()stillraises
NotImplementedError: Unsloth currently only works on NVIDIA, AMD and Intel GPUs, sothe import never gets that far. That is worth knowing on its own and is a separate matter.
product question is the work:
set_per_process_memory_fractionbounds the torch allocator inthe 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_fractionsetting, 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 itsown and does not constrain that decision.
set_per_process_memory_fractionexists on those namespacesbut 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.pykeeps a second, five entry role map forthe 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 nodeviceapplies only totorch.cuda.current_device(). Confirmed in torch's own source: the function defaultsdevicetocurrent_device()and the allocator keeps the fraction per device. Studio shards a run acrossevery visible GPU through
get_device_map, socuda:1and up allocated freely while the logsaid a process-wide cap was in force.
It now iterates
torch.cuda.device_count()and names each device explicitly, logging one lineper 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.
_FakeCudanow records a per-device map, because a single scalar could not tell a cap onevery 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/frontendis empty: the preview rows come frompreview_samplesonPOST /api/hub/datasets/check-format, which the "View dataset" dialog renders. Before/afterscreenshots from two isolated installs are attached below.
Before / after
Two isolated installs built by the PR's own
install.sh --local: BEFORE is the merge base2ab07c9c4, AFTER is head1fa00a3ed. One scene drives both: it writes a five-turn ShareGPTJSONL whose
fromvalues areSystem,Human,GPT," user "andmoderator, uploads itthrough the training section, and opens the "View dataset" dialog.
"role":"System""role":"Human""role":"GPT""role":" user ""role":"system""role":"user"Humanand" user ""role":"assistant"GPT"role":"moderator"moderatoris the control. It is not an alias in either build, so it must read the same on bothhalves; 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 tousershows the strip as well as the lower.Two honest limits on this pair. The scene's own
check-formatAPI call returned 404 on BOTHsides (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_assistantwas 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.