Skip to content

Studio and Core: close remote-code gate gaps in Sentence Transformers, GGUF export, scans and tokenizer paths - #14437

Merged
danielhanchen merged 8 commits into
mainfrom
studio-remote-code-gate-gaps
Oct 21, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-remote-code-gate-gaps

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Hardening from a security review of the remote-code consent gate and its neighbours. Real models load, train and export as before; the cases that change are repos whose custom code previously ran without going through trust_remote_code or the consent dialog.

Changes

  • Sentence Transformers: the trust_remote_code gate follows what the loader loads (unsloth/models/sentence_transformer.py). Router routes are checked recursively (bounded depth) at the folder the loader actually reads, locally and on the Hub route; without trust, a whole-model class cannot be used as a module or route, and a WordEmbeddings tokenizer_class must be a word tokenizer. A module path starting with / is checked where it points instead of having the slash stripped. all-MiniLM, bge, e5, gte and nomic (with trust) load exactly as before.
  • RAG embedder: Dense and WordEmbeddings imports are restricted (core/rag/embeddings.py) the way the Router import already was: Dense activation_function only from torch., WordEmbeddings only from sentence_transformers.. A real Dense layer still saves and loads.
  • Studio GGUF export follows the load's trust decision (core/export/export.py, unsloth/models/decision_gguf.py). llama.cpp's convert_hf_to_gguf.py loads several architectures' tokenizers with trust_remote_code=True, so a checkpoint that loaded with built-in classes (and never reached the consent dialog) could still run its tokenizer auto_map code in the converter. When the load did not approve remote code, the converter child gets an HF_MODULES_CACHE that cannot be created, so transformers cannot import that code; folders without auto_map never touch the cache and convert identically. Set around the call and restored afterwards. Core save_pretrained_gguf (notebooks) is unchanged.
  • Managed accounts: trust_remote_code is downgraded, not refused (routes/export.py, routes/training.py). Export and training passed a managed account's trust_remote_code=True straight through; it now becomes False for them silently (the Export tab always sends true, so a 403 would break it). The owner is unchanged.
  • List-form tokenizer auto_map is seen by the scanner (utils/security/remote_code_scan.py). iter_auto_maps read only the dict form, so "auto_map": ["tokenization_x.Tok", null] scanned as "no remote code"; such repos now get the existing consent dialog.
  • Audio companion repos are scanned (core/inference/native_audio.py). The scanned targets include the codec named in MOSS audio_tokenizer_config.json and the base model of a companion repo that is only an adapter, so the consent gate sees the code that actually loads. Stock MOSS and Higgs targets are unchanged; built-in default codecs are skipped.
  • vocab_file paths in tokenizer_config.json (unsloth/import_fixes.py). Below transformers 5.17 a tokenizer_config.json could point vocab_file (and similar) at an absolute host path. A version-gated, install-once backport of the 5.17 rule makes the file inside the repo win over the config's path, while a path the caller passes explicitly still wins; it does not install on 5.17+ and skips (with a log line) on an unexpected signature. Nine real tokenizers load identically before and after on 4.57.6 and 5.5.0.

Tests. New tests/test_st_modules_json_trust_gate.py (7 of 9 new cases fail on main; the 2 real-model controls pass), studio/backend/tests/test_embedding_model_security_gate.py (3 fail on main), tests/saving/test_gguf_converter_remote_code.py, studio/backend/tests/test_remote_code_gate_gaps.py (8 fail on main, the 5 owner / override controls pass on both), studio/backend/tests/test_native_audio_companion_targets.py (6 of 9 fail on main), plus vocab cases in tests/test_transformers_security_fixes.py, which reproduce on 4.52.4, 4.57.6, 5.2.0 and 5.5.0 and leave 5.17.0 / 5.18.0 / 5.20.2 untouched. All pass here; the related Sentence Transformers, RAG, native audio, export / consent and import_fixes modules show the same failing IDs on both sides.

…e_code

Router routes are now checked recursively at the folder the loader reads,
a whole model class is no longer accepted as a module type or route,
a WordEmbeddings tokenizer_class must be a word tokenizer, and a rooted
module path is checked where it points rather than under the model folder.

The Studio RAG embedder wraps the Dense and WordEmbeddings dotted-path
imports the same way it already wraps Router, so below sentence-transformers
6.0 neither imports a name outside its expected namespace.
…cision

- GGUF export: llama.cpp's converter loads some tokenizers with
  trust_remote_code=True. When the model was not loaded with remote code,
  point HF_MODULES_CACHE at a path that cannot be created for the converter
  call only, so a tokenizer auto_map module is not imported. Applied in
  save_to_gguf (decision from _loaded_via_remote_code), Studio's GGUF save
  and push (consent-gated trust flag, also covers MLX) and the decision
  model converter. A converter that needed that code now fails with a
  message to reload with trust_remote_code=True. Folders without auto_map
  and models loaded with remote code convert as before.
- Export load and training start downgrade a managed account's
  trust_remote_code to False instead of forwarding it. Owners and the
  UNSLOTH_STUDIO_ALLOW_MANAGED_REMOTE_CODE override are unchanged.
- iter_auto_maps counts a legacy list-form tokenizer auto_map.
MOSS-TTS-Local processors also load the codec named in
audio_tokenizer_config.json, and a companion codec that only ships an
adapter_config.json is replaced by its base model at load time. List both
in native_audio_security_targets so the remote-code scan and consent gates
cover what actually loads. Curated default codecs are not probed, so stock
models keep the same target list.
Below transformers 5.17.0, PreTrainedTokenizerBase._from_pretrained lets a
vocab_file / merges_file / tokenizer_file entry in tokenizer_config.json
take precedence over the file resolved inside the repo, and the tokenizer
opens that path as given. save_pretrained never writes these keys.

Add fix_transformers_tokenizer_config_vocab_file_override, which passes the
repo-resolved files as keyword arguments so they apply after the config,
matching upstream 5.17.0. An explicit caller path still wins. It is a no-op
on 5.17.0 and later, applies once, and keeps __wrapped__. Wired next to the
other transformers back-ports in _gpu_init.py and on the MLX path.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-10-21T04:18:57.177332Z 4eb543a Manual request
🔒 Security Review ✅ Completed 2026-10-21T02:59:32.722931Z db1607d 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.

@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

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

Reviewed commit: db1607db11

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.

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

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

"adapter_base_pin": getattr(model_preflight, "adapter_base_pin", None),
"trust_remote_code": request.trust_remote_code,
# A managed account never forwards remote code to the worker.
"trust_remote_code": request.trust_remote_code and not managed_remote_code_refused(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep YAML trust disabled for managed accounts

When a managed caller selects a trusted-org model whose defaults contain training.trust_remote_code: true, this assignment initially downgrades trust to False, but the existing YAML fallback below then runs because the value is false and resets it to True. The training worker therefore receives remote-code permission even though the managed-account override is unset; the YAML fallback must also respect managed_remote_code_refused().

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.

Leaving this as is. The fallback only applies when the shipped YAML for the model sets trust_remote_code and is_trusted_org_repo confirms the repo is a first-party curated one, so the code it enables is ours, not the account's. Managed accounts training those curated models need it, and the downgrade above still covers every user-chosen repo.

Comment on lines +2162 to +2164
sub_folder = (
route if route.startswith("/") else (f"{folder}/{route}" if folder else route)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Recognize Windows-absolute nested router routes

On Windows, a nested Router route such as C:\payload or a UNC path is absolute to the upstream Path(subfolder, route) load, but this check recognizes only /-prefixed routes and instead validates a synthetic path beneath folder. A repository can therefore make the delegated gate inspect a different directory from the one Router actually opens, allowing class references in the absolute route's config to bypass this recursive check; use the same os.path.isabs() handling applied to the outer module path.

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.

Fixed in b882795: nested routes now use the same rooted test as the outer module path (startswith("/") or os.path.isabs(route)), so a drive or UNC route is checked where the loader reads it.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

3 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

ℹ️ 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 on lines +482 to +483
if base and base not in targets:
targets.append(base)

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 Validate the resolved codec rather than its adapter

When a Higgs TTS 2 checkpoint names an adapter-only codec, this retains the adapter in targets and appends its base. _preflight_speech_codec then iterates every entry returned after the model and requires each one to pass higgs_tts2_codec_local_complete; the adapter directory has no codec config.json or full weights by definition, so preflight rejects it as incomplete before the valid base can be loaded. The security scan can retain both repositories, but the completeness check must apply only to the effective base codec.

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.

Not a regression from this change: before it, the adapter was already the only companion and failed higgs_tts2_codec_local_complete the same way, so an adapter-only codec never loaded. This PR only adds its base to what the gates scan.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 4eb543a6d0

ℹ️ 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 on lines +360 to +362
audio_tokenizer_config = _read_audio_metadata(
model_name, "audio_tokenizer_config.json", hf_token, reject_oversized = 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.

P1 Badge Fail closed when companion metadata cannot be read

When this model is remote and fetching audio_tokenizer_config.json encounters a transient Hub error, _read_audio_metadata converts the failure to {}, causing this helper to return None and omit the configured codec from native_audio_security_targets. The processor performs its own metadata read later, so a retry that succeeds can load the codec without either the file-security or remote-code gate ever inspecting it; distinguish a definitive missing file from an unreadable response and propagate the latter so the existing caller fails closed.

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.

Leaving this. It needs the codec metadata read to fail transiently during the scan and then succeed moments later in the processor; outside that race the codec is scanned, and a definitive missing file already behaves as before.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4eb543a6d0

ℹ️ 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 0bc82e1 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-remote-code-gate-gaps branch October 21, 2026 08:22
danielhanchen added a commit that referenced this pull request Oct 21, 2026
## Problem

Five checks fail on main, so the `Repo tests (CPU, studio)`, `Repo tests
(CPU, rest)` and `workflow-trigger lint` shards are red on every open PR
(for example #14472, #14482, #14488, #14490 and #14494). All five
reproduce on main `4d7ebf5cea`.

| Test | Introduced by | Fault |
|---|---|---|
|
`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
| #14437 | Baseline. Two new dynamic-import sites: `import_module` in
`studio/backend/core/rag/embeddings.py`, and a third
`import_from_string` in `unsloth/models/sentence_transformer.py`
(`_require_word_tokenizer`). Both are safe, see below. |
|
`tests/studio/test_tauri_branding_contract.py::test_desktop_surfaces_do_not_restore_studio_branding`
| #14473 | Product. "Studio" became "Unsloth Studio" in the Markdown
import errors and the Tauri webview reject message. The desktop contract
allows "Unsloth" there, never "Unsloth Studio". "Unsloth" meets both
#14473's rule (no bare "Studio") and this one. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_auto_switch_section_sits_above_the_usage_examples`
| #14455 | Test. The redesign moved the usage examples above the monitor
link on purpose, and its own `api-settings-tab.test.ts` pins that. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_monitor_can_unload_the_loaded_model`
| #14455 | Test. Unloading moved from a standalone button on the page
into the model picker's eject (`ApiModelLoadControls`). The `/unload`
path itself is unchanged. |
|
`tests/studio/test_settings_compact_overflow_contract.py::test_api_monitor_entries_and_expanded_text_can_shrink`
| #14455 | Test. Entry rows are now rounded cards (no `border-b`), and
the prompt/reply box's `rounded-lg` became conditional, so the class
literals the test matched are gone. The overflow guards themselves are
still in the source. |

## Fix

- **Risky loaders:** two baseline entries with reasons.
- `embeddings.py` imports only the three `sentence_transformers.models`
paths written out in a literal tuple, to wrap their `import_from_string`
with the trust gate.
- `_require_word_tokenizer` imports only after its caller has refused
any `tokenizer_class` outside `sentence_transformers.*`, and only dotted
identifiers.
- **Branding:** "Unsloth Studio" to "Unsloth" in those seven Markdown
import errors and the Rust reject message.
`conversation-markdown-import.test.ts` now matches `/Unsloth Markdown/`.
- **#14455 contracts:** rewritten to guard what the redesign keeps:
- the auto-switch section still follows the monitor link, and the usage
examples come before both;
- the page passes `unloadActiveModel` to the load controls as
`onUnloadActive`, and eject is withheld while `busy` (`modelLoading ||
unloading`, #11223's rule);
  - the `/unload` call still reads the internal id from status;
  - entry rows keep `w-full min-w-0`;
  - the prompt/reply box keeps `max-h-72 overflow-auto break-words`;
  - the model id keeps `min-w-0 break-all`.

## Verification

- The four Python files: 78 passed (5 failed on main).
- `studio/frontend/tests/conversation-markdown-import.test.ts`: 20
passed.
- Sabotage, each run against the rewritten tests, each failing exactly
one test:
- removing `min-w-0` from the entry row, or `break-words` from the text
box: the overflow test fails;
- dropping `unloading` from `busy`, or passing `onEject` while busy: the
unload test fails;
- putting the auto-switch section above the monitor link: the order test
fails.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 10, 2026
…ode decision (unslothai#17397)

## Summary

Studio's GGUF export already keeps the GGUF converter to the load's
`trust_remote_code` decision (unslothai#14437), so a checkpoint loaded without
`trust_remote_code=True` cannot have its `auto_map` code run during
conversion. The notebook paths, `model.save_pretrained_gguf` and
`push_to_hub_gguf`, did not have the same guard: the converter
subprocess could import and run a repo's remote code even though the
user never opted in.

## Changes

- `unsloth/save.py`:
- `_gguf_remote_code_approved(model, tokenizer)` treats any of these as
consent:
    - the load's stamp (`_unsloth_trust_remote_code`);
    - a model class from `transformers_modules`;
    - a tokenizer or processor class from `transformers_modules`.
- `_gguf_converter_remote_code(approved)` mirrors Studio's
`_converter_remote_code`. When the load did not opt in, it points
`HF_MODULES_CACHE` at an unusable path for the length of the conversion,
then restores the previous value. The converter child copies the
environment, so it cannot import `auto_map` modules.
- The guard wraps the `save_to_gguf` call in
`unsloth_save_pretrained_gguf` (which `push_to_hub_gguf` uses) and
`save_to_gguf_generic`.
- `unsloth/models/llama.py`: `FastLlamaModel.from_pretrained` records
`_unsloth_trust_remote_code`, as `FastModel` already does, so a trusted
load keeps converting as before.
- `unsloth/models/sentence_transformer.py`: the GGUF export passes a
trusted stamp on to the inner model it converts.

## Impact

- **Unchanged:** architectures with no `auto_map` (Llama, Qwen, Gemma,
Mistral and the rest) never touch the module cache, so they convert
exactly as before. Loads with `trust_remote_code=True` are untouched.
- **Changed:** a model loaded without `trust_remote_code` whose saved
folder carries remote code the converter would need now fails to convert
instead of running that code, which matches Studio.

## Tests

New `tests/saving/test_gguf_notebook_remote_code_guard.py`: 3 of 5 fail
on main, and all 5 pass on this branch.
- Two tests drive the real `unsloth_save_pretrained_gguf` with the
converter stubbed.
- One runs a real subprocess. Its control step proves the `auto_map`
code runs when unguarded, and that it does not run under the guard.

169 related save and export tests pass on this branch.
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.

1 participant