Skip to content

Fix stale transformers sidecar imports - #6954

Closed
Imagineer99 wants to merge 5 commits into
unslothai:mainfrom
Imagineer99:fix/studio-transformers-sidecar-stale-import
Closed

Imagineer99 wants to merge 5 commits into
unslothai:mainfrom
Imagineer99:fix/studio-transformers-sidecar-stale-import

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

What

Fix Studio sidecar activation when the default ransformers package has already been imported before a 5.x sidecar is selected.

When a Qwen3.5 run selects the 5.3.0 sidecar, �ctivate_transformers_for_subprocess() previously only prepended .venv_t5_530 to sys.path. If ransformers==4.57.6 was already cached in sys.modules, later imports kept using the stale default package and Qwen3.5 failed with the unsupported-transformers error.

This change records whether ransformers was already loaded, activates the chosen sidecar path as before, then purges stale ransformers and dependent modules so the next import resolves from the sidecar.

Validation

  • PYTHONPATH=studio/backend ~/.unsloth/studio/unsloth_studio/bin/python -m pytest studio/backend/tests/test_transformers_version.py::TestActivateLoggingClarity -q
  • Direct A/B smoke test with real Studio venv and real .venv_t5_530:
    • no purge: preloaded 4.57.6, after activation still 4.57.6 from unsloth_studio/lib/python3.13/site-packages
    • with fix: preloaded 4.57.6, purged 65 stale modules, after activation 5.3.0 from /home/samle/.unsloth/studio/.venv_t5_530/transformers/init.py

Notes

This is intentionally limited to the subprocess sidecar activation path. Default-tier models still return without purging.

@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 introduces logic to purge stale in-memory transformers and related modules when activating a sidecar version of transformers for a subprocess, along with a unit test to verify this behavior. The feedback suggests unconditionally calling _purge_modules() instead of guarding it with stale_transformers is not None, as dependent modules (like huggingface_hub) might already be loaded even if transformers itself is not, which would otherwise prevent the stale modules from being purged.

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 +323 to +330
if stale_transformers is not None:
count = _purge_modules()
logger.warning(
"Purged %d stale module(s) after subprocess transformers sidecar activation "
"(previous transformers=%s)",
count,
stale_transformers,
)

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.

high

If transformers itself has not been imported yet, but other dependent/related modules (such as huggingface_hub) have already been imported (e.g., during preflight checks, security scanning, or config loading), stale_transformers will be None. Under the current implementation, the if stale_transformers is not None: guard will prevent _purge_modules() from being called. As a result, the stale huggingface_hub (and other dependent modules) will remain in sys.modules. When transformers is subsequently imported from the sidecar, it will import huggingface_hub, which will resolve to the stale version from the default environment instead of the sidecar's specific version (e.g., 1.8.0 or 1.21.0). This can lead to subtle bugs, import errors, or unexpected behavior due to version mismatches.

To prevent this, we should unconditionally call _purge_modules() when activating a sidecar, and use the returned count to determine whether to log the warning.

Suggested change
if stale_transformers is not None:
count = _purge_modules()
logger.warning(
"Purged %d stale module(s) after subprocess transformers sidecar activation "
"(previous transformers=%s)",
count,
stale_transformers,
)
count = _purge_modules()
if count > 0:
logger.warning(
"Purged %d stale module(s) after subprocess transformers sidecar activation "
"(previous transformers=%s)",
count,
stale_transformers or "not loaded",
)

@LeoBorcherding

LeoBorcherding commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Tested on Windows/AMD (gfx1200, ROCm 7.13, Py3.13), Qwen3.5-2B QLoRA.

Good news: the fix works. On a stock build the subprocess selected tier 530 but still loaded cached 4.57.6 (Subprocess loaded transformers 4.57.6 -> does not support Qwen3.5). On this branch the purge fires and that error is gone:

Purged 259 stale module(s) after subprocess transformers sidecar activation (previous transformers=4.57.6)

It then trades it for a new import failure a few steps later:

Failed to import ML libraries: Could not import module 'BloomPreTrainedModel'
RecursionError: maximum recursion depth exceeded
  .../unsloth_zoo/fused_losses/forward_install.py, line 358, in exec_module
    self._inner.exec_module(module)   [repeated 12x]

Root cause looks like: _purge_modules() drops unsloth_zoo from sys.modules, but its _ModelingFinder stays registered on sys.meta_path. Re-importing unsloth_zoo after the purge adds a second finder, so the next transformers.models.*.modeling_* import (bloom, pulled in by peft) gets its loader wrapped once per stale finder and _ModelingLoader.exec_module recurses until the stack blows.

Fix idea: when purging, also unregister unsloth_zoo's finders from sys.meta_path, or drop unsloth_zoo from _PURGE_PREFIXES so the hook is never re-stacked. This was upstream unsloth-zoo main @6c2225e, peft 0.19.1. Can retest whenever.

@Imagineer99

Copy link
Copy Markdown
Member Author

Tested on Windows/AMD (gfx1200, ROCm 7.13, Py3.13), Qwen3.5-2B QLoRA.

Good news: the fix works. On a stock build the subprocess selected tier 530 but still loaded cached 4.57.6 (Subprocess loaded transformers 4.57.6 -> does not support Qwen3.5). On this branch the purge fires and that error is gone:

Purged 259 stale module(s) after subprocess transformers sidecar activation (previous transformers=4.57.6)

It then trades it for a new import failure a few steps later:

Failed to import ML libraries: Could not import module 'BloomPreTrainedModel'
RecursionError: maximum recursion depth exceeded
  .../unsloth_zoo/fused_losses/forward_install.py, line 358, in exec_module
    self._inner.exec_module(module)   [repeated 12x]

Root cause looks like: _purge_modules() drops unsloth_zoo from sys.modules, but its _ModelingFinder stays registered on sys.meta_path. Re-importing unsloth_zoo after the purge adds a second finder, so the next transformers.models.*.modeling_* import (bloom, pulled in by peft) gets its loader wrapped once per stale finder and _ModelingLoader.exec_module recurses until the stack blows.

Fix idea: when purging, also unregister unsloth_zoo's finders from sys.meta_path, or drop unsloth_zoo from _PURGE_PREFIXES so the hook is never re-stacked. This was upstream unsloth-zoo main @6c2225e, peft 0.19.1. Can retest whenever.

Thanks, that diagnosis was right. The stale purge was removing unsloth_zoo from sys.modules but leaving its _ModelingFinder registered on sys.meta_path. When unsloth_zoo was imported again, a second finder was installed, so transformers modeling imports could get wrapped repeatedly and recurse.

I updated #6954 to remove stale meta_path hooks during the purge as well. Local repro now shows the old unsloth_zoo finder is gone before importing the trainer, then Unsloth installs exactly one fresh finder after import. The Qwen3.5 QLoRA Studio run now works on the Windows/AMD tester setup after reinstalling the branch.

That said, #6968 is the cleaner root-cause fix. It keeps the worker preflight import-light so unsloth_zoo/transformers are not imported before sidecar activation. That avoids relying on purge/re-import in the normal training path. I’d prefer #6968 as the main fix, with the purge/meta_path cleanup from #6954 only as a defensive fallback if we want to keep it.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for digging into this. The root cause fix for the stale sidecar import landed in #6968 (merged to main), so I am closing this as superseded.

For context on why the approaches differ: #6968 prevents the stale transformers import in the first place (it makes utils/hf_xet_fallback.py import unsloth_zoo lazily, so the worker preflight no longer pulls transformers 4.57.x into sys.modules before activate_transformers_for_subprocess prepends the 5.x sidecar). With nothing stale resident, the sys.path prepend takes effect and the correct transformers loads.

The purge-then-reimport path here is a no-op in that normal flow (there is nothing stale left to purge). When I tested it in the real training worker as a standalone fix, purging and re-importing the already-patched unsloth/transformers graph mid-process failed at import unsloth (Could not import module 'BloomPreTrainedModel' / RecursionError), so training still did not start. That is why #6968 targets the ordering instead.

#6968 also adds CPU-only regression guards to studio-backend-ci (they fail on the pre-fix code and pass after), so this class of bug is caught on every future studio PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants