Skip to content

Studio: don't pin transformers before the training worker activates the 5.x sidecar - #6968

Merged
danielhanchen merged 9 commits into
mainfrom
fix/studio-sidecar-preactivation-import
Jul 8, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
fix/studio-sidecar-preactivation-import

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

What

Fixes the Studio training crash on Qwen3.5, GLM-4.7 and gemma-4 where the worker fails before training starts:

  • Qwen3.5 / GLM-4.7 (tokenizer_class TokenizersBackend): ValueError: Tokenizer class TokenizersBackend does not exist or is not currently imported.
  • gemma-4: ... is not supported yet in transformers==4.57.6.

Closes #6951.

Root cause

The training worker runs in a fresh spawn subprocess (core/training/training.py) and, during preflight, imports utils/hf_xet_fallback.py to decide the per-worker Xet env flip (core/training/worker.py, near the top of run_training_process). That shim imported unsloth_zoo eagerly at module load, and unsloth_zoo/__init__ imports transformers. So the default transformers 4.57.x was cached in sys.modules before activate_transformers_for_subprocess prepended the required 5.x sidecar (.venv_t5_530 / .venv_t5_550 / .venv_t5_510) to sys.path.

Activation only edits sys.path, which is a no-op for an already imported module, so the stale 4.57.x won. AutoTokenizer.from_pretrained (and AutoConfig) then ran on 4.57.x, which does not know TokenizersBackend or the 5.x architectures.

This started after the startup-speedup change moved that preflight import ahead of activation and unsloth_zoo began pulling transformers transitively.

Fix

Load the shared unsloth_zoo.hf_xet_fallback backend lazily, only when a heavy download helper is first used, which happens after the sidecar is activated. child_should_disable_xet and the DEFAULT_* constants are defined locally so importing the shim stays light and does not drag in transformers. The download wrappers, DownloadStallError, start_watchdog and get_hf_download_state resolve the shared backend on first use, and the existing degraded fallback (when unsloth_zoo is unavailable) is preserved unchanged.

This targets the root cause: with the shim import kept light, the worker no longer pins transformers before activation, so the sidecar prepend takes effect and the correct 5.x version loads cleanly. It touches only utils/hf_xet_fallback.py; worker.py and transformers_version.py are unchanged.

Relationship to #6954: that PR clears the stale module by purging and re-importing after activation. In the worker that path re-imports an already patched unsloth/transformers graph mid-process and fails at import unsloth (Could not import module 'BloomPreTrainedModel' / RecursionError), so training still does not start. Preventing the stale import avoids that entirely. The purge can stay as a defensive backstop or be dropped; it becomes a no-op in the normal path because there is nothing stale to purge.

Validation

Real Studio training driven end to end (fresh run_training_process via the training API), on B200:

model tier / sidecar result
unsloth/Qwen3.5-2B 530 / 5.3.0 completed, loss 1.72
unsloth/gemma-4-E2B-it 550 / 5.5.0 completed, loss 7.00
unsloth/gemma-4-12b-it 510 / 5.10.2 tokenizer + model load OK
unsloth/GLM-4.7-Flash 530 / 5.3.0 tokenizer + model load OK
unsloth/Qwen3.5-9B-Base 530 / 5.3.0 tokenizer + model load OK
unsloth/Llama-3.2-1B-Instruct default / 4.57.x unchanged, OK

Each worker logs Subprocess loaded transformers <5.x> (the correct sidecar), no longer 4.57.6.

Tests

  • test_hf_xet_fallback.py: existing suite kept green via the restored _shared_* seam; the GPU-init retry test now triggers the lazy load explicitly; new guard asserts that importing child_should_disable_xet does not import transformers or unsloth_zoo.
  • test_training_worker_import_discipline.py (new): asserts, in a fresh interpreter, that the worker preflight imports leave transformers unimported, so this whole class of regression cannot return silently. CPU only, no network, GPU, weights or sidecars, so it runs in the standard studio-backend-ci matrix (3.10 to 3.13). It fails on the pre-fix code and passes after.
  • test_worker_activates_correct_transformers.py (new): the end to end "does it choose the correct transformers version" check the import guard implies. It runs the real preflight (from utils.hf_xet_fallback import child_should_disable_xet) plus the real get_transformers_tier and activate_transformers_for_subprocess for a 5.x model (Qwen3.5, tier 530), then asserts the in-process transformers actually switched to the 5.x sidecar. A stale pre-activation import leaves 4.57.x pinned and fails the assertion, which is exactly the TokenizersBackend crash. It carries a self-contained torch.cuda spoof (mirrors tests/_zoo_aggressive_cuda_spoof.py) so unsloth_zoo takes its full, transformers-importing init path on a GPU-less runner; without that spoof unsloth_zoo degrades and never preloads transformers, which would mask the bug. A one line stub sidecar stands in for the 5.x venv, so it stays CPU only with no GPU, network, weights or real sidecar. Fails on the pre-fix code (active=4.57.6), passes after (active=5.3.0).

All three guards run in the existing studio-backend-ci workflow on every change under studio/** (and unsloth/**), across Python 3.10 to 3.13 on CPU. So a future change that reintroduces a pre-activation transformers import, picks the wrong tier, or otherwise stops the sidecar from taking effect turns CI red without needing a GPU.

shimmyshimmer and others added 2 commits July 8, 2026 09:27
…ctivates the sidecar

The training worker (core/training/worker.py:run_training_process) decides the per-worker
Xet env flip during preflight by importing utils/hf_xet_fallback.py, which eagerly imported
unsloth_zoo at module load. unsloth_zoo's __init__ imports transformers, so the default
transformers 4.57.x was cached in sys.modules before activate_transformers_for_subprocess
prepended the 5.x sidecar to sys.path. Since activation only edits sys.path, the already
cached module won, and 5.x models failed to load their tokenizer or config:
  - Qwen3.5 / GLM-4.7 (tokenizer_class TokenizersBackend): "Tokenizer class TokenizersBackend
    does not exist or is not currently imported."
  - gemma-4: "... is not supported yet in transformers==4.57.6."

Fix: load the shared unsloth_zoo backend lazily (only when a heavy download helper is first
used, which is after activation). child_should_disable_xet and the DEFAULT_* constants are
defined locally so importing the shim stays light. The download wrappers, the DownloadStallError
class, start_watchdog and get_hf_download_state resolve the shared backend on first use, and the
degraded no-unsloth_zoo fallback is preserved.

Tests:
  - test_hf_xet_fallback.py: existing suite kept green via the restored _shared_* seam; the
    GPU-init retry test now triggers the lazy load explicitly; new guard asserts importing
    child_should_disable_xet does not import transformers/unsloth_zoo.
  - test_training_worker_import_discipline.py: new invariant test that the worker preflight
    imports leave transformers unimported, so this class of regression cannot return silently.
    Runs in studio-backend-ci (CPU only, no network/GPU/weights).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the hf_xet_fallback.py utility to lazily load the heavy unsloth_zoo backend on demand. This prevents eager imports of transformers during worker startup, ensuring that the correct sidecar version is activated before any default modules are cached. It also adds a regression test to enforce this import discipline. The feedback suggests two improvements: adding a module-level __dir__ function to hf_xet_fallback.py to improve IDE discoverability of dynamically resolved attributes, and explicitly passing PYTHONPATH to the test subprocess to make it robust against Python path isolation flags.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +220 to +225


def __getattr__(name: str) -> Any:
if name in _DEGRADED_ATTRS:
if _load_shared():
return getattr(_shared, name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To ensure that dynamically resolved attributes (like DownloadStallError, start_watchdog, and get_hf_download_state) are discoverable by IDEs, interactive shells, and inspection tools (e.g., dir()), consider defining a module-level __dir__ function as specified in PEP 562.

Suggested change
def __getattr__(name: str) -> Any:
if name in _DEGRADED_ATTRS:
if _load_shared():
return getattr(_shared, name)
def __getattr__(name: str) -> Any:
if name in _DEGRADED_ATTRS:
if _load_shared():
return getattr(_shared, name)
return _DEGRADED_ATTRS[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def __dir__() -> list[str]:
return sorted(globals().keys() | _DEGRADED_ATTRS.keys())

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.

Leaving this as is. DownloadStallError, start_watchdog and get_hf_download_state stay reachable both via attribute access and via 'from utils.hf_xet_fallback import *' (star-import reads all and drives the module getattr per name), so this only affects dir()/IDE listing, not reachable behavior. The three names are now declared at module level (annotation-only) to satisfy ruff F822, so I would rather not add a dir override purely for introspection.

Comment on lines +62 to +67
result = subprocess.run(
[sys.executable, "-c", _PREFLIGHT_SNIPPET],
cwd = str(_BACKEND_DIR),
capture_output = True,
text = True,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To make the subprocess execution completely robust against Python path isolation flags (such as PYTHONSAFEPATH or -P in Python 3.11+), explicitly pass PYTHONPATH in the environment instead of relying solely on cwd path-prepending behavior.

Suggested change
result = subprocess.run(
[sys.executable, "-c", _PREFLIGHT_SNIPPET],
cwd = str(_BACKEND_DIR),
capture_output = True,
text = True,
)
import os
env = os.environ.copy()
env["PYTHONPATH"] = str(_BACKEND_DIR)
result = subprocess.run(
[sys.executable, "-c", _PREFLIGHT_SNIPPET],
cwd = str(_BACKEND_DIR),
env = env,
capture_output = True,
text = True,
)

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.

Leaving this as is. This hardens against 'python -P' / PYTHONSAFEPATH (isolated mode), which is not set anywhere in studio-backend-ci.yml or tests/conftest.py. The job runs plain 'python -m pytest tests/', so cwd stays on sys.path and the subprocess import resolves (the suite passes). I would rather not carry a full env passthrough for a mode this CI never enables.

…odel's sidecar version

Adds test_worker_activates_correct_transformers.py: runs the real worker preflight
(from utils.hf_xet_fallback import child_should_disable_xet) plus the real tier
detection and activate_transformers_for_subprocess for a transformers-5.x model
(Qwen3.5, tier 530), then asserts the in-process transformers actually switched to
the 5.x sidecar. A stale pre-activation import leaves 4.57.x pinned and fails the
assertion, which is exactly the TokenizersBackend regression (#6951).

Self-contained CUDA spoof (mirrors tests/_zoo_aggressive_cuda_spoof.py) forces
unsloth_zoo down its full, transformers-importing init path on a GPU-less runner;
without it unsloth_zoo degrades and never preloads transformers, masking the bug.
A one-line stub sidecar stands in for the 5.x venv, so no GPU, network, weights, or
real sidecar are needed. Passes on this fix, fails on buggy main.
…uard

Load tests/_zoo_aggressive_cuda_spoof.py (the committed spoof the consolidated CI
already relies on) as the single source of truth so the guard matches CI and stays
robust on a CPU-only torch wheel, where a partial hand-rolled spoof could miss a
torch.cuda call and let the unsloth_zoo import raise (masking the bug). Falls back to
a minimal inline spoof for a standalone studio checkout. Verified: passes on this fix,
fails on buggy main, and the fallback path passes when the spoof file is absent.
DownloadStallError, start_watchdog and get_hf_download_state are provided via the
module __getattr__ (PEP 562), so ruff F822 flagged them as undefined names in __all__
and the Source-lint / pre-commit checks went red. Add annotation-only declarations
(no value bound, so __getattr__ still resolves them lazily to the shared unsloth_zoo
backend) to mark them defined for the linter while keeping F822 active for the rest
of __all__.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 8, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 939ef5bec2

ℹ️ 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".

shimmyshimmer and others added 3 commits July 8, 2026 10:53
…scipline guard

The worker preflight now also runs 'from core.training.training import
is_apple_silicon_training_platform, should_use_mlx_training_backend' before it
activates the transformers sidecar. Add that import (guarded) to the guard's
preflight snippet so the invariant test stays a faithful mirror: a future change
that makes core.training.training pull transformers/unsloth_zoo eagerly would then
be caught too. Verified clean on the current tree (no leak).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 915aac154f

ℹ️ 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
danielhanchen merged commit 41dd95e into main Jul 8, 2026
1 of 38 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-sidecar-preactivation-import branch July 8, 2026 12:33
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.

Unsloth studio - Transformers and hf_xet package issues.

3 participants