Skip to content

Parse the downloaded model mapper instead of exec'ing it - #9777

Merged
danielhanchen merged 30 commits into
mainfrom
harden-exec-sinks
Aug 30, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
harden-exec-sinks

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Summary

unslothai/unsloth-zoo#1083 closed one arbitrary-code-execution path: a model_type read straight out of a downloaded config.json was interpolated into a string that was then exec'd, so a hostile model repo got code execution with no trust_remote_code. This is the audit of the rest of this repo.

Most sites here are fine and are left alone. They execute source this package generated itself, from inspect.getsource of an installed transformers / TRL / PEFT class or from dir() of an installed module. Two are not.

The CI lint that stops the shape coming back was split out into #9827, so this PR is the two product fixes on their own.

1. The remote mapper was exec'd

unsloth/models/loader_utils.py:_get_new_mapper runs on any from_pretrained("org/name") where the name is not in the shipped tables. It fetched a slice of mapper.py over HTTPS and exec'd the response body. Anything that can answer that request, including anything that can intercept it, executed code in the user's process, for a download the user never asked for.

The three targets in that slice are plain dict literals, so it now ast.parses the text and ast.literal_evals the assignments instead of executing it. A body that does not carry them returns empty tables, which the caller already handles. The 3 second timeout, the offline check and the throwaway namespace are unchanged.

The module-level derivation loop in unsloth/models/mapper.py moved into build_mappers() to make that possible. The five generated tables were checked against main entry by entry: 448 / 1210 / 760 / 178 / 178, identical.

2. UNSLOTH_FORCE_CUSTOM_DTYPE was an arbitrary-expression channel

unsloth/models/vision.py read this environment variable and eval'd two of its fields, then exec'd two more. Six model families depend on it, so it stays, but an inherited environment should not be able to feed it.

  • the dtype fields resolve through a fixed alias table (unsloth/models/_custom_dtype.py) instead of eval
  • the six producers in loader.py go through register_custom_dtype rather than writing os.environ directly
  • vision.py only executes the code fields of a value this process registered
  • an inherited value is neutralised at import, because a zoo old enough to still eval that field can already be installed and a version floor cannot fix a resolved install

The wire format is deliberately unchanged: unsloth_zoo/compiler.py parses the same variable with the same split(";", 4) and the two packages release separately, so any layout change would break on skew. tests/security/test_custom_dtype_wire_format.py pins that by reading the zoo side rather than copying it.

Testing

  • tests/security on this branch: 493 passed, 6 skipped
  • GPU smoke, 3 runs before and 3 after: generation output, mapper tables, resolved dtypes and the saved adapter files are identical, and train_loss lands at 1.624200 to 1.624571, inside the baseline's own 1.623905 to 1.624643 spread
  • all 38 files in unsloth_compiled_cache/ are byte-identical before and after
  • version matrix: transformers 4.57.6 / 5.0.0 / 5.15.1, TRL 0.22.2 / 0.25.1 / 1.10.0, PEFT 0.18.0 / 0.19.1 / 0.20.0. 0 model types wrongly rejected out of 4,586 to 5,768 checked per cell, 0 architectures wrongly rejected, 0 gadgets allowed
  • the getattr walk was checked against the eval it replaces on a real LoRA model: 72 paths, 0 mismatches

Not in this PR

The lint and its allowlist are #9827. The quantize_gguf command injection and the create_locked_down_function builtins leak are covered by unsloth-zoo #1106 and #1105. The zoo-side half of this audit is unsloth-zoo #1108, merged.

@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 26, 2026 07:34
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

ℹ️ 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 scripts/lint_dynamic_exec.py Outdated
Comment on lines +103 to +104
reason = _is_interpolated(node.args[0])
if reason is not None:

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 Trace interpolation through inline conversions

When an interpolated payload is wrapped in a call before reaching the sink, such as exec(f"import {name}".encode()), _is_interpolated sees only the outer .encode() call and reports no finding, although exec accepts the resulting bytes and executes them. I verified this exact input executes successfully while lint_dynamic_exec.py --paths reports zero interpolated calls, so the new security gate can be bypassed without even assigning the payload to a local variable; inspect string-preserving/encoding wrappers recursively before deciding the argument is safe.

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 taking this one. The lint is a best-effort CI heuristic for the 'untrusted value spliced into source' shape, not a sound taint analysis, and chasing arbitrary inline conversions is unbounded. I checked all three repos and no such pattern exists today. The bounded cases with a real bypass, builtins. and compile's source keyword, are both fixed.

@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: 63a9121fab

ℹ️ 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 +98 to +101
value = os.environ.get(_ENV_KEY, "")
if value == "":
return "", False
return value, value in _REGISTERED

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 Sanitize untrusted dtype values before dependent readers run

When UNSLOTH_FORCE_CUSTOM_DTYPE is inherited, returning the raw value as untrusted only protects the new vision.py reader; it remains unchanged in os.environ, where the supported unsloth_zoo>=2026.8.15 dependency's compiler.fix_rotary_embedding_dtype still performs eval(_dtype) for generated sources containing cos.to or sin.to. I reproduced that reader executing a side effect from an inherited value such as all;(__import__(...).touch() or torch.float32);None;;, so compilation paths that reach the zoo helper retain the environment-code-execution vulnerability this change is intended to remove. Clear or sanitize unregistered values globally, or coordinate the trust check with the zoo reader.

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 taking this one. Scrubbing an inherited value out of os.environ would change behaviour for anyone deliberately setting it, and the zoo reader consumes only the dtype field through _get_dtype, with no exec anywhere: grep for exec(execute_code / exec(_custom_datatype / exec(custom_datatype in unsloth_zoo returns nothing. The eval(_dtype) on that line is real and is fixed in unslothai/unsloth-zoo#1108.

danielhanchen added a commit to unslothai/notebooks that referenced this pull request Aug 26, 2026
Same four corrections made on unslothai/unsloth#9777 and unslothai/unsloth-zoo#1108,
so the three copies of this lint do not drift:

  - allowlist identity is path::qualname::hash, not the hash alone, so an approved call
    copied into another location is not automatically approved there
  - a payload assigned to a local before the sink is tracked, since moving the
    interpolation up one line is a two-line refactor that leaves the shape unchanged
  - builtins.exec(f"...") is recognised as a sink
  - rebinding a tracked local to something that is not a built string clears it

This repo still has no interpolated dynamic-execution call, so the allowlist stays empty.
tests/security: 32 passed.
@danielhanchen

Copy link
Copy Markdown
Member Author

Ran reviewer.py over this PR (12 parallel reviewers). It found six real defects, four of them in the lint itself. Each was reproduced first and re-run after the fix, so none of these are speculative.

Fixed

Reviewers Finding
9/9 Allowlist identity was the call hash alone, despite storing path and qualname. Identical source at two locations shared one approval, so an allowlisted call copied into an attacker-controlled function inherited its justification. The committed allowlist already had a real instance: one hash spanned _utils.py:patch_gradient_accumulation_fix and llama.py:FastLlamaModel.from_pretrained. Key is now path::qualname::hash
5/9 Moving the interpolation onto the previous line defeated the lint completely. That is a two-line refactor that leaves the vulnerability shape untouched. Locals bound to a built string are now tracked per scope, and rebinding clears the name
2/9 builtins.exec(f"...") executes but was not a sink, because only ast.Name matched
3/9 unsloth-cli.py is a tracked entrypoint the adjacent compile and ruff steps cover, but the security lint never scanned it
2/9 test_probe_does_not_call_exec_or_eval could not fail. The fixture raised, _get_new_mapper's bare except swallowed it, and the assertion was only on the returned shape, which five empty tables satisfy. The pre-change vulnerable implementation passed this test. The fixture now records instead of raising, and the test asserts nothing was reached and that the probe still produced tables
2/9 A manual 16bit alias added on main through the established _add_with_lower(MAP_TO_UNSLOTH_16bit, ...) pattern was invisible to the probe, since only the source table was read. An older install would stop offering the upgrade notice for exactly the models main had just added. Those calls are now applied from literal arguments using the installed helpers, so the fetched text still supplies only data

The stronger lint then found two more interpolated sites, both the variable form and both safe: _utils.py builds a config class name from a hardcoded 9-name list, and save.py templates inspect.signature of the installed push_to_hub. Both recorded with a reason. Allowlist 35 to 37.

Not accepted

"The custom-dtype execution channel remains reachable through unsloth_zoo/compiler.py:814" (8/9). This was the single most-reported finding and it is a false positive. fix_rotary_embedding_dtype unpacks _custom_datatype and execute_code at line 805 and never uses either; grep -rn "exec(execute_code\|exec(_custom_datatype\|exec(custom_datatype" unsloth_zoo/ returns nothing. The reviewers inferred an exec from the parallel structure. The eval(_dtype) on that line is real, and it is fixed in unslothai/unsloth-zoo#1108, which is the companion to this PR.

Cross-PR note

This PR and unsloth-zoo#1108 are two halves of one audit. Landing this one alone leaves eval(_dtype) in the zoo reader, which is why the reviewers kept pointing at it.

Idempotency

Every changed path was run N times in one process and checked for accumulated state: build_mappers does not mutate its input and returns fresh dicts, repeated probes agree and leak nothing into module globals, N registrations of one dtype value add one entry, the lru_cached architecture registry returns the same frozenset, and both guards reject identically every time. 25 checks.

End to end, a model on the vision.py path loaded twice in one process: same generation, same dtypes, the code fields ran on both loads when registered and on neither when planted, and the registry did not grow.

tests/security plus both mapper suites: 496 passed.

@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: 619e05444b

ℹ️ 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 scripts/lint_dynamic_exec.py Outdated
not. Unparsing means reindenting, rewrapping or reflowing the call does not
invalidate a justification, while changing what is interpolated does.
"""
return hashlib.sha256(ast.unparse(node).encode("utf-8")).hexdigest()[:16]

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 Include taint producers in the allowlist hash

For an indirect sink such as the currently allowlisted exec(push_to_hub_text, globals()), this hashes only the unchanged call expression and not the assignment that made push_to_hub_text tainted. If that assignment is changed from interpolating trusted installed metadata to interpolating a user- or model-controlled value, the finding retains the same path, qualname, and hash, so the old justification silently approves the newly unsafe payload. Incorporate the normalized producer expression into the identity, or require indirect sinks to be reviewed again whenever their producer changes.

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 taking this one. Hashing the taint producers as well would invalidate every entry whenever an unrelated line above the call moved, which is the drift the ast.unparse hash exists to avoid. Location plus normalised call source is the identity that was actually reviewed.

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +137 to +138
if reason is None:
self.tainted[-1].pop(target.id, None)

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 Preserve taint across conditional rebinding

When a tainted payload is overwritten only on one branch, this removes its taint unconditionally in AST traversal order. For example, payload = f"import {user}"; if use_safe: payload = "import os"; exec(payload) is reported as having zero interpolated calls even though the unsafe value reaches exec whenever use_safe is false. Rebinding should clear taint only when it is guaranteed on every path reaching the sink, or branch states should be conservatively merged.

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 taking this one. Modelling taint across conditional rebinding is a dataflow analysis, and this is a heuristic gate. One level of local indirection is fixed because that is a two-line refactor of an existing shape; branch-sensitive tracking is not.

Comment thread unsloth/models/loader_utils.py Outdated
"FLOAT_TO_FP8_BLOCK_MAPPER" : tables[3],
"FLOAT_TO_FP8_ROW_MAPPER" : tables[4],
}
for node in ast.walk(tree):

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 Respect control flow when extracting fetched aliases

Because ast.walk(tree) visits every nested statement without considering whether it executes, a literal mapping assignment or _add_* call inside if False, a platform/version guard, or an uncalled helper function is applied to the returned tables anyway. If a future fetched mapper keeps an alias behind such a guard, the upgrade probe will claim that release supports the model and raise the upgrade notice even though executing that mapper would never install the mapping. Restrict extraction to statements that are unconditionally reached by the mapper's actual construction path, or represent these aliases in a dedicated literal data structure.

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 taking this one. The alias replay reads literal helper calls as data wherever they appear; respecting control flow would mean interpreting the fetched file, which is what this change removes. A guarded alias resolving is at worst a superset for a probe whose only job is to answer 'would a newer Unsloth know this name'.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 26, 2026
danielhanchen added a commit to unslothai/notebooks that referenced this pull request Aug 26, 2026
Keeps this copy of the lint identical to the ones on unslothai/unsloth#9777 and
unslothai/unsloth-zoo#1108 apart from DEFAULT_TARGETS:

  - compile's source is not positional-only, so compile(source = f"...") executed
    while node.args was empty. Scoped to compile; exec and eval raise TypeError for
    every keyword spelling on CPython 3.13.
  - a dangling symlink, a directory named *.py, or a symlink to one reached read_text
    and failed CI for a reason unrelated to dynamic execution.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Aug 26, 2026
Keeps this copy identical to the ones on unslothai/unsloth#9777 and
unslothai/notebooks#365 apart from DEFAULT_TARGETS:

  - compile's source is not positional-only, so compile(source = f"...") executed
    with node.args empty. Scoped to compile; exec and eval raise TypeError for every
    keyword spelling on CPython 3.13.
  - a dangling symlink, a directory named *.py, or a symlink to one reached read_text
    and failed CI for a reason unrelated to dynamic execution. Also a NUL byte in the
    source (ValueError from ast.parse, not SyntaxError) and a RecursionError in the
    walk.

@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: 3c320f53b8

ℹ️ 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 scripts/lint_dynamic_exec.py Outdated
justification without review. The location is half of what was reviewed, so it is
half of the key.
"""
return f"{finding['path']}::{finding['qualname']}::{finding['hash']}"

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 Distinguish duplicate calls within the same function

When an identical dynamic-execution call is added inside a function that already contains an allowlisted copy, this key is unchanged, so the new call inherits the old approval without review even if its local inputs are attacker-controlled. Fresh evidence beyond the earlier producer-hash concern is that the committed allowlist already contains duplicate keys for two calls at lines 3291 and 3334 of _utils.py (and another duplicate pair in rl.py), demonstrating that (path, qualname, hash) does not uniquely identify call sites; include a stable occurrence identity or reject ambiguous duplicate keys.

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.

Keeping the current behaviour, same as when this came up on 3861782333.

The factual claim checks out. scripts/dynamic_exec_allowlist.json has 37 entries and 35 distinct keys, with duplicate pairs in _utils.py::patch_gradient_accumulation_fix and rl.py::_patch_trl_rl_trainers_impl. That is the intended outcome rather than a defect: load_allowlist folds them into one entry and both call sites match it, so two textually identical calls in one function share one justification, which is accurate because they are the same construct reviewed for the same reason.

Making the key positional would mean the justification stops surviving a reformat, which is the property the hash keying exists to provide. New evidence for a conclusion already reached does not change it.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Aug 26, 2026
)

* Stop config-supplied values reaching exec, eval and getattr sinks

Follow-up to #1083, which stopped a config-supplied model_type reaching an exec'd
import by validating at the producer. This audits the rest of the exec/eval sites in
the package, closes the ones where an untrusted or user-level value can still reach
the executed string, and adds a lint so the shape cannot come back.

compiler.py re-checks model_type and the generated module name at the sink, so the
import path and the compiled-cache filename defend themselves rather than trusting the
caller, and resolves the UNSLOTH_FORCE_CUSTOM_DTYPE dtype field through _get_dtype
instead of eval.

empty_model.py gates config.architectures[0] on the names transformers registers in
its MODEL_*_MAPPING_NAMES tables before getattr and call.

peft_utils.py and tokenizer_utils.py drop three eval(f"...") lookups in favour of a
getattr walk, added next to the setter from #1083.

saving_utils.py turns an output-dtype assert into a ValueError, since asserts vanish
under python -O.

* Close the findings from the parallel review of this PR

Three runtime defects and the same four lint defects fixed on the unsloth side.

empty_model.py: a rejected architecture leaked global state

  create_empty_vision_model replaces SiglipVisionModel._init_weights with a no-op and
  restores it at the end of the function. The new guard raised in between, so a config
  with an unknown architecture left weight init disabled on a class shared by the whole
  process, and every SigLIP model built afterwards silently skipped initialisation.
  The guard now runs before the patch. Confirmed the leak was real by reproducing the
  old ordering, so the regression test is not vacuous.

empty_model.py: the getattr walk could not resolve bracket components

  peft_utils rewrites `.0.` to `[0].` before splitting. Its first call site skips paths
  containing brackets, but the second does not: when a module's forward calls
  `self.blocks[0](...)` directly, `final_where` includes the bracketed component and
  `getattr(obj, "blocks[0]")` fails where the removed eval indexed it happily. That is
  gradient checkpointing breaking on a real model shape. The walk now resolves digit
  subscripts, and only digits, so it is still a name-and-index walk rather than an
  expression.

vllm_utils.py: the architecture guard was asymmetric

  The vLLM vision path did the same getattr(transformers, config.architectures[0])
  followed by from_pretrained, gated only on model_type. model_type and architectures
  are independent fields of the same downloaded config.json, so that gate constrains
  neither. A config declaring a supported model_type and architectures ["AutoTokenizer"]
  resolved and invoked an unrelated class. Same check as create_empty_vision_model now.

  The comment in empty_model.py claimed this path already had the gate. It did not; the
  claim is removed rather than reworded.

scripts/lint_dynamic_exec.py

  Allowlist identity is path::qualname::hash rather than the hash alone, locals bound to
  a built string are tracked per scope, builtins.exec is a sink, and rebinding a tracked
  name clears it. The committed allowlist had 53 entries collapsing to 40 keys, so
  approvals were genuinely shared across unrelated locations.

  The stronger lint found four more interpolated sites, all the variable form and all
  self-generated from installed packages: the gguf reader partial class, the peft lora
  submodule scan, and the transformers quantizer patch. Recorded with reasons, 53 to 57.

tests/security plus tests/test_module_attribute_getter.py: 118 passed.

* Restore the SigLIP weight-init patch in a finally

create_empty_vision_model swaps SiglipVisionModel._init_weights for a no-op and puts
it back at the end. The restore sat after an `except Exception`, which does not catch
KeyboardInterrupt, so cancelling a cell partway through a load left weight init
disabled on a class shared by the whole process. Every SigLIP model built afterwards
then skipped initialisation, silently and nowhere near the cause.

Reproduced the old ordering under a simulated cancel to confirm it was real:

    PRE-FIX: _init_weights restored? False
    PRE-FIX: sentinel left behind?  True

The restore is now in a finally, and gated on `patched_here` so a nested or re-entrant
call that found the patch already installed cannot remove it from under the call that
owns it. The previous code would restore from the inner call.

This predates the PR, but the PR already moved the architecture guard above this block
for the same reason, so leaving the exception path leaking would be half a fix.

* Skip a non-canonical model_type instead of raising, and widen the walk

Three findings from independent verification passes over this PR.

compiler.py: the sink guard turned a skip into a hard failure

  38 of the model_type values transformers itself ships are hyphenated (`lfm2-vl`,
  `audio-spectrogram-transformer`, `data2vec-audio`, ...). The import below the guard
  raises ModuleNotFoundError for any name that is not a plain module name, and that
  happens BEFORE the compiled-cache filename is built, so such a value was always a
  silent skip and never reached the os.path.join. Raising made
  unsloth_compile_transformers(config.model_type) fail for real model types, and that
  function is exported. It returns now, which is the pre-change behaviour exactly, and
  the value still stops short of the filename. Verified the import fails first for
  `lfm2-vl`, `a/b` and `../../etc/passwd` alike.

empty_model.py: the indexed-component pattern was ASCII-only

  Python identifiers are not ASCII-only, and PyTorch registers a submodule under a
  Unicode name without complaint, so `self.层 = nn.ModuleList([...])` produced a path
  the walk could not resolve but the removed eval could. The name part is now anything
  without brackets; only the subscripts stay digit-constrained, which is what keeps
  this a name-and-index walk rather than an expression.

lint_dynamic_exec.py: the gate fell over on things that are not readable files

  A dangling symlink, a directory named `*.py`, or a symlink to one reaches scan_file
  through rglob and raised out of read_text, failing CI for a reason unrelated to
  dynamic execution. Now skipped, along with a NUL byte in the source (ValueError from
  ast.parse, not SyntaxError) and a RecursionError during the walk.

Tests cover all three. Allowlists unchanged: 37 unsloth, 57 zoo, 0 notebooks.

* State what the create_standalone_class justification actually covers

The entry justified `module` and said nothing about `model_location`, which is a
parameter. The function is not exported (absent from compiler.__all__) and all five
call sites are in the same file passing a path built from an already-validated
model_type, so the value is internal on every reachable path. The reason now says
that, and says that a caller outside this file would invalidate it.

* Carry the sink keyword resolution and unreadable-path skips

Keeps this copy identical to the ones on unslothai/unsloth#9777 and
unslothai/notebooks#365 apart from DEFAULT_TARGETS:

  - compile's source is not positional-only, so compile(source = f"...") executed
    with node.args empty. Scoped to compile; exec and eval raise TypeError for every
    keyword spelling on CPython 3.13.
  - a dangling symlink, a directory named *.py, or a symlink to one reached read_text
    and failed CI for a reason unrelated to dynamic execution. Also a NUL byte in the
    source (ValueError from ast.parse, not SyntaxError) and a RecursionError in the
    walk.

---------

Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 26, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3dc8729c1f

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

Four fixes from the latest review round.

The import-light guard stopped at a non-call statement that loaded a heavy
dependency, but let a call that was not a skip guard past unchecked, so a
dynamic import above a later importorskip kept the file on the light runner.
Its alias table was also built from one walk over the whole file, so a
binding inside one function decided how a call in an unrelated one was read;
it is now one table per lexical scope, each built on its enclosing one.

The mapper probe replayed mutations written above the selected builder call
onto its result, although that assignment replaces all five exported tables,
so an entry added between two rebuilds was reported as installed. It also
marked a class-bound name shadowed from the class body first line, dropping a
mutation written above the binding that really does reach the module global.
@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. Bravo.

Reviewed commit: ed38adc55b

ℹ️ 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 and others added 4 commits August 28, 2026 06:10
Against main's mapper.py today the probe returned empty tables, so the
"please update Unsloth" notice never fired for any model. That file has no
build_mappers: it writes the five exports as empty literals and fills them
from a module-scope loop, and the whole-name assignment rule read those
literals as the module clearing the tables.

An empty dict assigned to an exported table is now an initialiser rather than
a clear, but only where the fetched module has no build_mappers call, since
that is the shape whose exports are built by the loop this reproduces with the
installed builder. A non-empty rebind still replaces.

Checked against the live file: the probe and an exec of the same text now
agree on all five tables, 448/1210/760/178/178, for both mapper.py shapes.
Comment-only pass: 1106 added comment lines down to 403, no code tokens
changed (comment_tools.py check --strip-docstrings, 11/11 OK).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant