Repository navigation
Studio: don't pin transformers before the training worker activates the 5.x sidecar - #6968
Conversation
…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).
There was a problem hiding this comment.
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.
|
|
||
|
|
||
| def __getattr__(name: str) -> Any: | ||
| if name in _DEGRADED_ATTRS: | ||
| if _load_shared(): | ||
| return getattr(_shared, name) |
There was a problem hiding this comment.
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.
| 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()) |
There was a problem hiding this comment.
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.
| result = subprocess.run( | ||
| [sys.executable, "-c", _PREFLIGHT_SNIPPET], | ||
| cwd = str(_BACKEND_DIR), | ||
| capture_output = True, | ||
| text = True, | ||
| ) |
There was a problem hiding this comment.
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.
| 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, | |
| ) |
There was a problem hiding this comment.
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__.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…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).
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
What
Fixes the Studio training crash on Qwen3.5, GLM-4.7 and gemma-4 where the worker fails before training starts:
TokenizersBackend):ValueError: Tokenizer class TokenizersBackend does not exist or is not currently imported.... 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, importsutils/hf_xet_fallback.pyto decide the per-worker Xet env flip (core/training/worker.py, near the top ofrun_training_process). That shim importedunsloth_zooeagerly at module load, andunsloth_zoo/__init__importstransformers. So the defaulttransformers4.57.x was cached insys.modulesbeforeactivate_transformers_for_subprocessprepended the required 5.x sidecar (.venv_t5_530/.venv_t5_550/.venv_t5_510) tosys.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(andAutoConfig) then ran on 4.57.x, which does not knowTokenizersBackendor the 5.x architectures.This started after the startup-speedup change moved that preflight import ahead of activation and
unsloth_zoobegan pullingtransformerstransitively.Fix
Load the shared
unsloth_zoo.hf_xet_fallbackbackend lazily, only when a heavy download helper is first used, which happens after the sidecar is activated.child_should_disable_xetand theDEFAULT_*constants are defined locally so importing the shim stays light and does not drag intransformers. The download wrappers,DownloadStallError,start_watchdogandget_hf_download_stateresolve the shared backend on first use, and the existing degraded fallback (whenunsloth_zoois unavailable) is preserved unchanged.This targets the root cause: with the shim import kept light, the worker no longer pins
transformersbefore activation, so the sidecar prepend takes effect and the correct 5.x version loads cleanly. It touches onlyutils/hf_xet_fallback.py;worker.pyandtransformers_version.pyare 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/transformersgraph mid-process and fails atimport 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_processvia the training API), on B200: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 importingchild_should_disable_xetdoes not importtransformersorunsloth_zoo.test_training_worker_import_discipline.py(new): asserts, in a fresh interpreter, that the worker preflight imports leavetransformersunimported, so this whole class of regression cannot return silently. CPU only, no network, GPU, weights or sidecars, so it runs in the standardstudio-backend-cimatrix (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 realget_transformers_tierandactivate_transformers_for_subprocessfor a 5.x model (Qwen3.5, tier 530), then asserts the in-processtransformersactually switched to the 5.x sidecar. A stale pre-activation import leaves 4.57.x pinned and fails the assertion, which is exactly theTokenizersBackendcrash. It carries a self-containedtorch.cudaspoof (mirrorstests/_zoo_aggressive_cuda_spoof.py) sounsloth_zootakes its full,transformers-importing init path on a GPU-less runner; without that spoofunsloth_zoodegrades and never preloadstransformers, 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-ciworkflow on every change understudio/**(andunsloth/**), across Python 3.10 to 3.13 on CPU. So a future change that reintroduces a pre-activationtransformersimport, picks the wrong tier, or otherwise stops the sidecar from taking effect turns CI red without needing a GPU.