Skip to content

Keep the compiler on for native architectures loaded with trust_remote_code = True - #11516

Merged
danielhanchen merged 8 commits into
mainfrom
native-compile-trust-remote-code
Sep 22, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
native-compile-trust-remote-code

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

{
"message": "API rate limit exceeded for user ID 23090290. If you reach out to GitHub Support for help, please include the request ID E1F2:21C800:4387CCE:DE85A8B:6AB274E0 and timestamp 2026-09-22 12:30:25 UTC. For more on scraping GitHub and how it may affect your rights, please review our Terms of Service (https://docs.github.com/en/site-policy/github-terms/github-terms-of-service)",
"documentation_url": "https://docs.github.com/en/rest/using-the-rest-api/getting-started-with-the-rest-api#rate-limiting",
"status": "403"
}
{
"message": "API rate limit exceeded for user ID 23090290. If you reach out to GitHub Support for help, please include the request ID E224:2770ED:46DD97F:E94C3C8:6AB274E1 and timestamp 2026-09-22 12:30:26 UTC. For more on scraping GitHub and how it may affect your rights, please review our Terms of Service (https://docs.github.com/en/site-policy/github-terms/github-terms-of-service)",
"documentation_url": "https://docs.github.com/en/rest/using-the-rest-api/getting-started-with-the-rest-api#rate-limiting",
"status": "403"
}

What

trust_remote_code = True on a native transformers architecture no longer switches the Unsloth compiler pass off.

unsloth_compile_transformers returned early for any value of the flag, on the grounds that remote code cannot be traced. That is only true when the checkpoint ships its own modeling files. Loading gemma-4, Qwen3-MoE, Llama or any other native architecture with the flag set (a habit, and what most notebooks and scripts do) lost:

  • the fast LoRA forward: PEFT's own Linear4bit.forward ran instead, casting every activation to the fp32 adapter dtype and running both LoRA matmuls as fp32 SIMT GEMMs (1015 cutlass_80_simt_sgemm launches per step on gemma-4-26B-A4B);
  • the compiled norms: eager Gemma4RMSNorm with its fp32 round trip, 1728 residual-stream copies per step;
  • the fused linear cross entropy: the full 262k-vocab logits were materialised in fp32, plus 2.1 GB.

How

_config_uses_remote_code(config) in unsloth/models/loader.py decides whether the model code lives outside transformers, and only that answer is passed to the compiler:

  • a config class loaded from transformers_modules, on the root config or on a text_config, vision_config or audio_config sub-config;
  • an auto_map entry for a model or config class (AutoModel*, AutoConfig), on the root or a sub-config. A custom tokenizer, processor or feature extractor in auto_map is not code the compiler would trace and does not count;
  • no config at all keeps the old, conservative answer.

Real remote-code checkpoints (Phi-4-reasoning-vision, Nemotron-3-Nano-Omni, Step-3.7, Kimi-K2.7) still classify as remote and keep the compiler off, verified on their configs.

Measurements

gemma-4-26B-A4B-it, NF4, LoRA r=16 on every module including the experts, batch 2 x 1024, Unsloth gradient checkpointing, B200 (shared box, device time from torch.profiler):

arm device ms per step
trust_remote_code = True before this change 618.6
trust_remote_code = False (the best path available before) 571.3
trust_remote_code = True with this change 514.4 (together with the unsloth-zoo changes in unslothai/unsloth-zoo#1331)

Parity on tiny-random gemma-4 with real data, old path vs new, 10 steps: loss max delta 2.3e-4, grad norm max delta 3.4e-3. On the 26B the compiled bf16 LoRA arithmetic and the eager fp32 arithmetic diverge to 0.079 by step 10 at lr 2e-4, the same relationship every native model already has between trust_remote_code = False and True.

Tests

tests/test_trust_remote_code_native_compile.py: the predicate on native, auto_map, tokenizer-only auto_map, sub-config auto_map, transformers_modules root and sub-config classes, dict-shaped configs, and a GPU test that loads tiny-random gemma-4 in 4-bit with trust_remote_code = True and asserts Linear4bit.forward is Unsloth's and the compiled module was written. The GPU test fails on main and passes here; the check was run one process per arm from a neutral directory.

Compatibility

Pure Python over config attributes and the config class module; no torch, platform or transformers version dependence. transformers 4.57.6 and 5.x, TRL 0.22.2 and 1.x, PEFT 0.18 to 0.21, torch 2.6 and later. Linux, macOS, Windows and WSL unaffected beyond the compiler now running where it used to be skipped. Anyone who relied on trust_remote_code = True as a way to keep the compiler off should set UNSLOTH_COMPILE_DISABLE = 1, which is the supported switch.

Note for the notebooks

Every Unsloth notebook or script that passes trust_remote_code = True for a native architecture was running the slower path; no change is needed on their side, they pick the fast path up with this release.

Related: unslothai/unsloth-zoo#1336 (structural MoE experts dispatch, Llama-4 grouped path, Inkling), which fixes the three compiler items that running the compiler with trust_remote_code = True exposes on Inkling.

…e_code=True

The compiler pass was skipped whenever trust_remote_code was set, on the
grounds that remote code cannot be traced. That is only true when the
checkpoint ships its own modeling files. For an architecture transformers
itself ships, the flag changes nothing about where the code lives, yet it
dropped the fast LoRA forward, the fused linear cross entropy, the compiled
norms and the attention rewrites.

On gemma-4-26B-A4B (QLoRA, bsz 2 x 1024) that left PEFT's own Linear4bit
forward in place, which casts every activation to the float32 LoRA dtype
and runs both LoRA matmuls as fp32 SIMT GEMMs, and materialised the full
262144-vocab logits in float32 for the loss instead of the fused chunked
path.

Only a config with an auto_map (on it or a sub-config), or a config class
loaded out of transformers_modules, counts as remote code now. No config
keeps the previous conservative answer.
…onfigs too

A checkpoint can ship a custom tokenizer, processor or feature extractor
through auto_map while its model is a native architecture; that is not code
the compiler would have to trace, so it must not switch the optimizations
off. Only AutoModel* and AutoConfig entries count. The transformers_modules
class check now applies to text, vision and audio sub-configs the same way
it applies to the root, and dict-shaped configs are handled.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 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-22T13:58:00.351547Z 5d4cc64 New commits
🔒 Security Review ✅ Completed 2026-09-22T10:28:55.868549Z f3365f8 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.

@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: acd6b62b6c

ℹ️ 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/loader.py
Comment on lines +241 to +245
for sub in ("text_config", "vision_config", "audio_config"):
cfg = getattr(config, sub, None)
if cfg is None and isinstance(config, dict):
cfg = config.get(sub)
if cfg is not None and _remote(cfg):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Traverse every declared sub-config before compiling

For composite configs whose remote component is stored under another declared name such as llm_config, decoder_config, thinker_config, or a nested entry in sub_configs, this loop returns False even when that component has an AutoModel* mapping or comes from transformers_modules. These names are already supported by the composite-config traversal in unsloth/models/vision.py, so loading such a checkpoint with trust_remote_code=True now incorrectly enables compilation of model code that the previous safety gate treated as untraceable; recursively traverse the config's declared sub-configs before passing False to the compiler.

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 against transformers 5.17 and against the real checkpoints named, and the extra traversal would not catch anything loadable while widening an existing false positive, so leaving the three names as they are.

Remote code is dispatched from the root config only. configuration_auto.py:389 computes has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"] on the root dict, and auto_factory.py:208 and :355 compute it as hasattr(config, "auto_map") and cls.__name__ in config.auto_map on the root config. So a checkpoint that ships modeling files always resolves its root class out of transformers_modules, or carries a root auto_map, and _remote(config) already returns True at the root before the loop runs. A native root means no remote code was executed for that repo at all.

A native root also cannot construct a remote sub-config. Every composite config converts nested dicts through CONFIG_MAPPING / AutoConfig.for_model; get_class_from_dynamic_module appears in no configuration_*.py outside models/auto/. An unrecognised nested model_type raises KeyError, it does not fall back to remote code.

The three names in the comment check out that way on the actual configs:

repo root model_type root auto_map sub-config auto_map
OpenGVLab/InternVL2-2B internvl_chat AutoConfig, AutoModel, AutoModelForCausalLM llm_config: AutoConfig, AutoModel, AutoModelForCausalLM
Qwen/Qwen2.5-Omni-7B qwen2_5_omni none thinker_config, talker_config, token2wav_config: none

llm_config is the OpenGVLab remote-code convention and those roots always carry auto_map, so they are caught at the root. thinker_config and talker_config are native Qwen2_5OmniConfig sub-configs with no auto_map. decoder_config is not a sub-config name in 5.17. A scan of 4214 composite checkpoints (224 native composite model_types, top 40 by downloads each) turned up exactly one config with a remote auto_map under a non-triple name, ETH-CVG/lightglue_disk, and it raises KeyError: 'disk' in configuration_lightglue.py:83 before a config object exists.

Widening the loop would cost real models. Extra kwargs are set on native sub-config objects, so a fully native checkpoint can carry a stale auto_map it never uses: HuggingFaceM4/Idefics3-8B-Llama3 has a native root with text_config.auto_map = {AutoConfig, AutoModelForCausalLM} pointing at configuration_idefics3, and tiiuae/falcon-11B-vlm has a llava_next root with a six-entry auto_map on a plain FalconConfig. transformers ignores both and runs native LlamaForCausalLM / FalconForCausalLM. Extending the same auto_map test across every sub_configs key spreads that misclassification over 224 composite architectures to guard against zero loadable checkpoints.

On the reference to vision.py: _uses_flash_attention_for_generation answers a different question, which sub-model carries the attention implementation, and that genuinely is a per-branch attribute. Where the model code comes from is not.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: f3365f8f16

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

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: f3365f8f16

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
Every test in this file exercised _config_uses_remote_code directly, so
reverting the one line that uses it left 8 of 9 green; the only test that
reaches the call site needs a GPU and no CI lane runs tests/ on one. Add a
drift guard in the shape the repo already uses for import_fixes and callback
signatures: it fails on main and on a call-site-only revert.

@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: c3556df2b0

ℹ️ 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/loader.py
Comment on lines +225 to +227
def _remote(cfg):
if (getattr(type(cfg), "__module__", "") or "").startswith("transformers_modules"):
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the compile guard for locally registered models

When a caller registers an external config/model with AutoConfig.register and AutoModel.register, the resulting config class lives in the caller's module, has no auto_map, and is not under transformers_modules; this predicate therefore returns False. With trust_remote_code=True, the changed call site then enables the Transformers compiler before FastBaseModel.from_pretrained loads that external class through the supplied/registered auto model, removing the previous safety guard for custom implementations. Treat non-Transformers config classes (or the actual selected model class) conservatively as external too.

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.

Reproduced this both ways on a real load rather than reasoning about it, and the premise holds while the consequence does not, so leaving the predicate as it is.

The premise is correct. A class registered with AutoConfig.register / AutoModelForCausalLM.register does come back with __module__ = "__main__", no auto_map, and nothing under transformers_modules, and the predicate calls it native. Measured, not assumed.

What that costs is the question, and it splits into the only two cases a registered class can be in.

A custom model_type. Registered MyCustomConfig(model_type = "my_custom_arch") with MyCustomForCausalLM, saved a checkpoint, loaded it through FastModel.from_pretrained(trust_remote_code = True, auto_model = AutoModelForCausalLM):

arm compiler received load forward compiled modules written
main True (skipped) OK transformers.models.llama.modeling_llama.LlamaForCausalLM.forward none
this PR False (ran) OK transformers.models.llama.modeling_llama.LlamaForCausalLM.forward none for this architecture

The compiler rewrites transformers.models.<model_type>.modeling_<model_type>. For my_custom_arch there is no such module, so it emits nothing and the registered class keeps its own forward. The guard is preserved in the only sense that matters: there was never anything for the compiler to trace.

A native model_type. Registering a subclass under llama (exist_ok = True) is the case where the compiler does have a handle:

arm compiler received load forward compiled modules written
main True (skipped) OK LlamaForCausalLM.forward none
this PR False (ran) OK LlamaForCausalLM.forward unsloth_compiled_module_llama.py

It loads and runs; logits move by 1.6e-5 relative, the ordinary compiled-versus-eager margin. But that is not a custom implementation being traced, it is the native Llama module being compiled, which is exactly what the same subclass already gets today with trust_remote_code = False. The flag was never the thing making that safe.

So across both cases there is no crash, no failure to load, and no custom forward replaced. Widening the predicate to treat any non-transformers config class as external would switch the compiler off for a condition that does not produce a defect, which is the kind of defensive layer worth avoiding here. Anyone who does want the compiler off for a registered architecture has the supported switch, UNSLOTH_COMPILE_DISABLE = 1.

The skipif called __import__("torch") at module import time, so on a runner
without torch the whole module failed collection instead of skipping one test:
macos-15 and windows-latest both ended on ModuleNotFoundError, 0 tests
collected. Resolving it lazily collects 10 tests there instead.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
@danielhanchen
danielhanchen merged commit 7c28d74 into main Sep 22, 2026
5 of 50 checks passed
@danielhanchen
danielhanchen deleted the native-compile-trust-remote-code branch September 22, 2026 14:18
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…e_code = True (unslothai#11516)

* Keep the compiler on for native architectures loaded with trust_remote_code=True

The compiler pass was skipped whenever trust_remote_code was set, on the
grounds that remote code cannot be traced. That is only true when the
checkpoint ships its own modeling files. For an architecture transformers
itself ships, the flag changes nothing about where the code lives, yet it
dropped the fast LoRA forward, the fused linear cross entropy, the compiled
norms and the attention rewrites.

On gemma-4-26B-A4B (QLoRA, bsz 2 x 1024) that left PEFT's own Linear4bit
forward in place, which casts every activation to the float32 LoRA dtype
and runs both LoRA matmuls as fp32 SIMT GEMMs, and materialised the full
262144-vocab logits in float32 for the loss instead of the fused chunked
path.

Only a config with an auto_map (on it or a sub-config), or a config class
loaded out of transformers_modules, counts as remote code now. No config
keeps the previous conservative answer.

* Count only model and config auto_map entries as remote code, on sub-configs too

A checkpoint can ship a custom tokenizer, processor or feature extractor
through auto_map while its model is a native architecture; that is not code
the compiler would have to trace, so it must not switch the optimizations
off. Only AutoModel* and AutoConfig entries count. The transformers_modules
class check now applies to text, vision and audio sub-configs the same way
it applies to the root, and dict-shaped configs are handled.

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

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

* Cover the compiler call site, not just the predicate

Every test in this file exercised _config_uses_remote_code directly, so
reverting the one line that uses it left 8 of 9 green; the only test that
reaches the call site needs a GPU and no CI lane runs tests/ on one. Add a
drift guard in the shape the repo already uses for import_fixes and callback
signatures: it fails on main and on a call-site-only revert.

* Do not import torch while collecting the GPU test

The skipif called __import__("torch") at module import time, so on a runner
without torch the whole module failed collection instead of skipping one test:
macos-15 and windows-latest both ended on ModuleNotFoundError, 0 tests
collected. Resolving it lazily collects 10 tests there instead.

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

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

* Trim the predicate's comments to the facts the code does not state

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants