Skip to content

Generalize transformers tier selection by probing AutoConfig - #6550

Merged
danielhanchen merged 20 commits into
mainfrom
feat/transformers-tier-autoconfig-probe
Jun 22, 2026
Merged

danielhanchen merged 20 commits into
mainfrom
feat/transformers-tier-autoconfig-probe

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

When loading a model whose tokenizer class only exists in transformers 5.x, Studio guessed the lowest 5.x sidecar (530). That misroutes any model whose built-in config parser actually needs a higher tier. Dense NemotronH is the motivating case: it ships a 5.x tokenizer, so the tokenizer check routed it to 530, but its hybrid_override_pattern mixes - (MLP) layers that only the transformers 5.10 parser understands, so 5.3/5.5 raise KeyError: '-' on a native (trust_remote_code=False) load such as export resolving a LoRA base.

The config.json transformers_version field cannot fix this either: it records the version that saved the model, not the minimum required to load it (this model was saved on 5.3.0.dev0 yet needs 5.10).

What this does

Replaces the weak "tokenizer says 5.x, so use 530" guess (both the local and remote paths) with an actual probe: parse config.json with the built-in parser (AutoConfig.from_pretrained(..., trust_remote_code=False)) inside each candidate sidecar, escalating 530 -> 550 -> 510, and select the first tier that parses. This is the real failure mode, so it generalizes to any architecture without maintaining hardcoded lists.

It is a hybrid: every strong signal (architecture/model_type, name substrings) stays a fast path with no subprocess. The probe runs only when the tier is otherwise ambiguous, and the result is cached by (model, commit sha) so it is a one-time cost per model revision.

Safety / fail-safe

  • The probe uses trust_remote_code=False, so it never executes repository code, and AutoConfig reads only config.json (no weights).
  • It mirrors the existing _is_vision_model_subprocess pattern (the sidecars are pip install --target dirs, so the child runs sys.executable with the target dir on sys.path); the token rides in the environment, never argv.
  • _probe_tier never raises. A transient failure (auth/network/offline) falls back to the legacy 530 guess uncached (retried next load); parse failures escalate; a missing sidecar is skipped. So it can only improve on prior behavior, never regress a load that worked before.
  • UNSLOTH_DISABLE_TIER_PROBE=1 restores the old guess.

Tests

Adds TestProbeTier (escalation order, first-success, middle-tier, nothing-parses -> highest, cache hit skips the subprocess, transient/timeout -> 530 uncached, all-sidecars-missing -> no spawn, disable flag, the remote tokenizer signal now routing through the probe, plus _stderr_is_transient and _local_dir_signature). Full suite: 68 passed.

When the only signal is a 5.x tokenizer class, get_transformers_tier guessed the
lowest 5.x sidecar (530). That misroutes models whose built-in config parser needs
a higher tier: dense NemotronH ships a 5.x tokenizer but its '-' (MLP) layer only
transformers 5.10 can parse, so 5.3/5.5 raise KeyError '-'. The config.json
transformers_version field records the saving version, not the minimum to load, so
it cannot drive routing either.

Replace the weak tokenizer->530 guesses (local and remote) with a probe: parse
config.json with the built-in parser (trust_remote_code=False) in each sidecar,
escalating 530->550->510, and pick the first that succeeds. This generalizes to any
architecture without hardcoded lists. Strong signals stay fast paths (no subprocess);
the probe runs only when the tier is otherwise ambiguous and is cached by (model,
commit sha). It never executes repo code, never downloads weights, never raises, and
falls back to the legacy 530 guess on a transient/auth/offline failure or when no
sidecar is available. UNSLOTH_DISABLE_TIER_PROBE restores the old behavior.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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 an AutoConfig-based probing mechanism to dynamically resolve the required transformers tier for ambiguous models by running a lightweight configuration parsing script in candidate sidecar virtual environments. The feedback identifies three robustness improvements for cross-platform compatibility, particularly on Windows: handling potential OSError exceptions when checking local path existence for remote repository IDs, avoiding UnicodeEncodeError in the probe script by writing UTF-8 encoded bytes to sys.stderr.buffer, and preventing UnicodeDecodeError in subprocess.run by specifying errors="replace".

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 +528 to +530

def _resolve_commit_sha(model_name: str, hf_token: str | None) -> str | None:
"""Immutable identity for the tier cache: a local dir signature or the HF commit sha.

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

On Windows, calling Path(model_name).exists() can raise an OSError (such as WinError 123 for invalid path syntax) if model_name is a remote repository ID or contains characters that are invalid in local paths. Since _resolve_commit_sha is called on any model name, this unhandled exception will crash the entire get_transformers_tier call.

Wrap the p.exists() check in a try...except OSError block to defensively handle invalid path strings, and log the exception at a debug level to aid in troubleshooting rather than silently ignoring it.

    p = Path(model_name)
    try:
        if p.exists():
            sha = _local_dir_signature(p)
    except OSError as e:
        logger.debug(f"Failed to check path existence for {model_name}: {e}")
References
  1. When handling exceptions, avoid broad or silent except clauses. Instead, catch specific exceptions and log them (at least at a debug level) to aid in troubleshooting.

Comment on lines +480 to +482
except Exception as exc:
sys.stderr.write(type(exc).__name__ + ": " + str(exc))
sys.exit(1)

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.

medium

If str(exc) contains non-ASCII characters, calling sys.stderr.write can raise a UnicodeEncodeError in the child process if sys.stderr.encoding is not UTF-8 (e.g., on Windows with CP1252).

To prevent this, write to sys.stderr.buffer directly by encoding the string to UTF-8 with replace error handling.

Suggested change
except Exception as exc:
sys.stderr.write(type(exc).__name__ + ": " + str(exc))
sys.exit(1)
except Exception as exc:
sys.stderr.buffer.write((type(exc).__name__ + ": " + str(exc)).encode("utf-8", "replace"))
sys.exit(1)

Comment on lines +554 to +561
"""
env = child_env_without_native_path_secret()
if hf_token:
env["HF_TOKEN"] = hf_token
if _env_offline():
env["HF_HUB_OFFLINE"] = "1"
env["TRANSFORMERS_OFFLINE"] = "1"
try:

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.

medium

If the subprocess outputs non-ASCII characters in its stderr (e.g., due to localized error messages or paths containing non-ASCII characters), calling subprocess.run with text=True can raise a UnicodeDecodeError on systems with non-UTF-8 default encodings (such as Windows with CP1252).

To prevent this, pass errors="replace" to subprocess.run to gracefully handle any decoding errors.

Suggested change
"""
env = child_env_without_native_path_secret()
if hf_token:
env["HF_TOKEN"] = hf_token
if _env_offline():
env["HF_HUB_OFFLINE"] = "1"
env["TRANSFORMERS_OFFLINE"] = "1"
try:
result = subprocess.run(
[sys.executable, "-c", _PROBE_CONFIG_SCRIPT, target_dir, model_name],
capture_output = True,
text = True,
errors = "replace",
timeout = _PROBE_TIMEOUT_SECS,
env = env,
**_windows_hidden_subprocess_kwargs(),
)

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

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

logger.info(
"Transformers tier %s selected for %s (AutoConfig probe; %s)", resolved, model_name, reason
)
_probe_tier_cache[key] = resolved

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 Do not cache 530 when no sidecar was probed

If all three ensure_fn() calls return False (for example a transient runtime-install/offline failure before the sidecars exist), probed_any stays false but this fallback still stores 530 in _probe_tier_cache. A later retry in the same backend process, after the sidecars become available, will hit this cached value and skip the AutoConfig probe, so ambiguous 5.x models that actually require 550/510 keep being routed to the 5.3 sidecar until restart. Return the legacy 530 fallback uncached when no sidecar was actually probed.

Useful? React with 👍 / 👎.

return "530"
else:
if probed_any:
resolved = "510"

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 Treat all-failed probes as inconclusive

When an ambiguous tokenizer-only model relies on remote code or a custom model_type, every sidecar probe uses trust_remote_code=False and fails with a non-transient built-in parser error rather than proving that a newer tier is required. This branch then caches/selects 510, changing the previous tokenizer-only route from 530 to 5.10 for models that may load successfully with trust_remote_code=True on the 5.3 stack. Treat the all-failed case as inconclusive/legacy 530 unless a probe actually parses at a higher tier.

Useful? React with 👍 / 👎.

sha = HfApi().model_info(model_name, token = hf_token).sha
except Exception as exc:
logger.debug("Could not resolve commit sha for '%s': %s", model_name, exc)
_probe_sha_cache[model_name] = sha

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 Retry SHA lookup before caching probe tiers

If the Hub model_info lookup fails transiently, this memoizes None as the model revision; when the subsequent AutoConfig probe succeeds, _probe_tier caches the selected tier under (model, None). Future calls in the same backend process never retry the SHA lookup, so an ambiguous model whose Hub revision changes can keep using a stale sidecar choice despite the cache being intended to be keyed by commit SHA. Avoid memoizing a missing SHA, or avoid storing successful probe tiers under an unknown revision.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

Codex:
- Never escalate to 510 on uncertainty. When every sidecar was probed and none
  parsed with the built-in parser, the model is a remote-code / custom model_type
  that loads via its own code; keep the legacy 530 route instead of jumping to
  510 (which would change the behavior of models that worked on the 5.3 stack).
- Only cache the 530 fallback when the result is conclusive (every tier actually
  probed). If a sidecar was missing/uninstallable the environment is incomplete,
  so return 530 uncached and retry on the next call.
- Do not pin the tier cache under an unknown revision: _resolve_commit_sha no
  longer memoizes a None sha (a transient Hub failure is retried), and _probe_tier
  only caches a tier when the commit sha is known.

Gemini:
- Wrap Path.exists() in the sha resolver in try/except OSError (a remote repo id
  can raise WinError 123 on Windows).
- Probe script writes the error to sys.stderr.buffer as UTF-8 bytes so a non-ASCII
  message cannot itself raise UnicodeEncodeError under cp1252.
- subprocess.run decodes stderr with errors="replace" to avoid UnicodeDecodeError
  on non-UTF-8 consoles.

Tests: 72 passed (added partial-sidecar uncached, sha-unresolved not cached,
all-failed stays 530 + cached, sha resolver retries None / handles OSError).
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

Addressed the review feedback:

  • The probe no longer escalates to 510 on uncertainty. When every sidecar was probed and none parsed with the built-in parser, the model loads via its own remote code, so the legacy 530 route is kept (a missing/skipped sidecar returns 530 uncached so it retries once the environment is complete).
  • The 530 fallback is only cached when conclusive (all tiers actually probed); a skipped sidecar stays uncached.
  • A tier is only cached under a known commit SHA. _resolve_commit_sha no longer memoizes a None SHA, so a transient Hub failure is retried instead of pinning the cache under an unknown revision.
  • Cross-platform: wrapped Path.exists() in the SHA resolver in try/except OSError (WinError 123 on Windows), the probe child writes its error to stderr.buffer as UTF-8, and subprocess.run decodes stderr with errors=replace.

Tests: 72 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@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: 8a61c97146

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

model_name,
)
return "530"
return _probe_tier(model_name, hf_token, "tokenizer needs 5.x")

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 Pass the HF token into the tokenizer gate

When callers use the new hf_token argument for a gated/private model whose only 5.x signal is tokenizer_config.json, this authenticated probe is never reached: the guard immediately above still calls _check_tokenizer_config_needs_v5(model_name), which performs an unauthenticated raw fetch and caches False. The probe then receives hf_token only after that gate succeeds, so these models fall through to the default 4.x tier instead of the required sidecar; thread the token through the config/tokenizer checks or make the probe reachable for authenticated lookups.

Useful? React with 👍 / 👎.

Comment on lines +557 to +558
if sha is not None:
_probe_sha_cache[model_name] = sha

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 Recompute local signatures before using the probe cache

For local model directories, the value returned by _local_dir_signature is a mutable content signature, but this stores it in _probe_sha_cache forever. If a long-running Studio process reuses or overwrites the same checkpoint directory with a different config.json/tokenizer_config.json, _resolve_commit_sha returns the old signature and _probe_tier_cache can keep selecting the previous tier even though the mtimes/sizes changed; only immutable remote SHAs should be memoized this way, or local signatures need to be recomputed each call.

Useful? React with 👍 / 👎.

…l sigs

Codex:
- Thread hf_token through _check_config_needs_510/550 and
  _check_tokenizer_config_needs_v5 (and the underlying raw fetches). Previously a
  gated/private model whose only 5.x signal is tokenizer_config.json never reached
  the authenticated probe: the unauthenticated raw fetch failed and cached False,
  so the model fell through to the default 4.x tier. The per-check caches are now
  keyed by (model, token) so an unauthenticated miss cannot poison a later authed
  read, mirroring _load_config_json.
- _resolve_commit_sha no longer memoizes a local directory signature. A local
  signature is mutable (size/mtime of config/tokenizer), so a reused/overwritten
  checkpoint path would otherwise keep selecting the previous tier; it is now
  recomputed every call. Only the immutable remote commit sha is memoized.

Tests: 75 passed (added token-cache isolation + auth header, local signature not
memoized, token threaded into all checks/probe).
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 2 addressed:

  • Threaded hf_token through _check_config_needs_510/550 and _check_tokenizer_config_needs_v5 (and the underlying raw fetches). A gated/private model whose only 5.x signal is tokenizer_config.json now reaches the authenticated probe instead of falling through to default 4.x. Each per-check cache is keyed by (model, token) so an unauthenticated miss cannot poison a later authenticated read.
  • _resolve_commit_sha no longer memoizes the mutable local-directory signature (recomputed every call); only the immutable remote commit SHA is memoized, so an overwritten checkpoint is not pinned to the old tier.

Tests: 75 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@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: 6a6ce3ce26

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

return _cache("530")


def get_transformers_tier(model_name: str, hf_token: str | None = None) -> str:

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 Thread request HF tokens into tier selection

The new token-aware tier detection is currently unreachable from the paths that actually activate a sidecar: activate_transformers_for_subprocess still calls get_transformers_tier(resolved) without an hf_token, while the inference/training/export workers only pass the model name to activation even though they carry request-scoped hf_tokens. For gated/private models whose 5.x signal is only in config.json or tokenizer_config.json, these checks still run unauthenticated, cache a miss under (model, None), and can select the default/wrong sidecar before the later model load uses the token.

Useful? React with 👍 / 👎.

sha: str | None = None
if not _env_offline():
try:
from huggingface_hub import HfApi

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 Avoid importing hub before sidecar activation

When an ambiguous 5.x model reaches the new probe from activate_transformers_for_subprocess, this import loads the default environment's huggingface_hub into sys.modules before the selected .venv_t5_* directory is prepended. That activation path only mutates sys.path and does not purge modules, so the later transformers-5 import can reuse the already-loaded default hub instead of the sidecar's pinned huggingface_hub==1.8.0, defeating the sidecar isolation and risking import/runtime mismatches for exactly the models that need probing.

Useful? React with 👍 / 👎.

model_name,
reason,
)
return _cache(tier)

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 Don't cache a tier after skipping lower probes

If an earlier sidecar is unavailable or its runtime install fails, this still caches the first higher tier that parses. In an environment where .venv_t5_530 is temporarily missing but .venv_t5_550 parses the model, the result is pinned under (model, sha) even though 530 may have been the lowest valid tier once installation succeeds; that contradicts the fail-safe behavior for incomplete probes and can keep routing the model to a higher sidecar until restart.

Useful? React with 👍 / 👎.

Comment on lines +571 to +572
if model_name in _probe_sha_cache:
return _probe_sha_cache[model_name]

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 Re-resolve mutable remote SHAs before reusing tier cache

This cache returns the first Hub SHA ever seen for a plain model id such as org/model, but those ids usually track a mutable default branch. If the repo later updates its config while the Studio process is still running, _probe_tier keeps looking up (model, old_sha) and reuses the stale tier instead of probing the new revision, so the advertised per-commit tier cache does not actually follow remote revisions until process restart.

Useful? React with 👍 / 👎.

…r cache

Codex round 3:
- Thread hf_token into the activation path that actually selects a sidecar. The
  token-aware tier checks added last round were unreachable:
  activate_transformers_for_subprocess called get_transformers_tier without a
  token, and the inference/training/export workers passed only the model name even
  though they hold a request-scoped hf_token. activate_transformers_for_subprocess
  now takes hf_token and the three workers forward config["hf_token"], so a
  gated/private model whose only 5.x signal is an authenticated config/tokenizer is
  routed to the right sidecar instead of falling to default 4.x.
- Stop importing huggingface_hub during tier detection. _probe_tier no longer
  resolves a commit sha, so it never pulls huggingface_hub into the worker before
  the sidecar venv is prepended to sys.path (activation only prepends, never
  purges), which would otherwise pin the default-env hub over the sidecar's
  pinned huggingface_hub==1.8.0.
- The tier cache is now keyed by model_name for the process lifetime (a model's
  required tier is a property of its architecture; cleared on restart). This drops
  the mutable-SHA memo that masked remote revision changes and the mutable
  local-signature memo, removing _resolve_commit_sha / _local_dir_signature /
  _probe_sha_cache entirely.
- Do not cache a probe success that depended on a skipped lower tier: if a lower
  sidecar was unavailable, the lowest valid tier may change once it installs, so
  the result is returned uncached and re-probed next call.

Tests: 73 passed (probe imports no hub; success uncached when a lower tier is
skipped; activation forwards the token).
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 3 addressed:

  • Threaded hf_token into the path that actually selects a sidecar. The token-aware checks added last round were unreachable: activate_transformers_for_subprocess called get_transformers_tier without a token, and the inference/training/export workers passed only the model name. activate_transformers_for_subprocess now takes hf_token and the three workers forward config["hf_token"], so a gated/private model whose only 5.x signal is an authenticated config/tokenizer reaches the right sidecar.
  • The probe no longer imports huggingface_hub in-process. _probe_tier dropped commit-SHA resolution, so it never pulls hub into the worker before the sidecar venv is on sys.path (activation only prepends, never purges), which would otherwise pin the default-env hub over the sidecar's pinned huggingface_hub==1.8.0.
  • The tier cache is now keyed by model_name for the process lifetime (a model's required tier is a property of its architecture; cleared on restart). This removes the mutable-SHA memo that masked remote revisions and the mutable local-signature memo (_resolve_commit_sha / _local_dir_signature / _probe_sha_cache are gone).
  • A probe success that depended on a skipped lower tier is no longer cached, so it re-probes once that sidecar installs.

Tests: 73 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@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: 806b0fee95

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

# Do not pin a result that depended on a skipped lower tier: once that sidecar is
# available the lowest valid tier may differ, so re-probe next call.
if not skipped:
_probe_tier_cache[model_name] = tier

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 Key probe cache by revision/content

When the same local checkpoint path is reused or overwritten (and similarly when a Hub repo advances under the same id), this stores the probed tier under only the path/repo string. A later ambiguous model at that same model_name with a different config.json will hit the cache at the top of _probe_tier and skip the AutoConfig probe, so Studio can activate a stale sidecar such as 530 for a config that now requires 510; include a local config signature or resolved Hub revision in the cache key, or avoid caching mutable local paths.

Useful? React with 👍 / 👎.

"""
env = child_env_without_native_path_secret()
if hf_token:
env["HF_TOKEN"] = hf_token

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 Enable implicit auth in the probe child

When the process inherits HF_HUB_DISABLE_IMPLICIT_TOKEN=1 (for example from a privacy-focused environment or another Hub subprocess env), setting only HF_TOKEN leaves AutoConfig.from_pretrained(..., token=None) unauthenticated because the token is still considered implicit. In that environment a gated/private ambiguous model hits a 401/GatedRepoError during the probe, _probe_tier falls back to 530, and the later authenticated load can use the wrong transformers sidecar; set HF_HUB_DISABLE_IMPLICIT_TOKEN=0 here or pass the token explicitly inside the probe script.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@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: 35c3895788

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

"""
try:
_activate_transformers_version(model_name)
_activate_transformers_version(model_name, hf_token)

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 one-arg activation call when token is absent

When hf_token is omitted, this now still passes a second positional argument (None) to _activate_transformers_version. Existing tests patch that helper with the previous one-argument callable; python -m pytest studio/backend/tests/test_mlx_training_worker_config.py::test_activate_transformers_version_or_warn_silent_on_success -q now fails because the resulting TypeError is swallowed as a warning instead of the success path staying silent. Either keep the old arity when no token is present or update the test double.

Useful? React with 👍 / 👎.

if local_tc.is_file() and _check_tokenizer_config_needs_v5(model_name):
logger.info(
"Transformers tier 530 selected for %s (local tokenizer_config.json check)",
if local_tc.is_file() and _check_tokenizer_config_needs_v5(model_name, hf_token):

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 Invalidate local misses when checkpoint files appear

When the same process inspects a local checkpoint directory before config.json/tokenizer_config.json has been written, the slow fallback caches None/False for that path. On a later call after tokenizer_config.json exists, this branch still delegates to _check_tokenizer_config_needs_v5, which returns the stale cached miss instead of reading the new local file, so a TokenizersBackend checkpoint can still fall through to default and never reach the 5.x probe. This affects in-progress/local checkpoints; avoid caching local misses or include a local file signature in the tokenizer/config caches.

Useful? React with 👍 / 👎.

…st double

- _load_config_json / _check_tokenizer_config_needs_v5: a local checkpoint dir whose
  config.json / tokenizer_config.json is not yet present was being fetched from the Hub
  as if the path were a repo id, and the 404 miss was cached. A later call after the
  file is written (in-progress checkpoint) then served the stale miss, so a
  TokenizersBackend checkpoint fell through to the default tier. Skip the Hub fetch for
  local dirs and do not cache the miss, so the file is read once it appears.
- test_activate_transformers_version_or_warn_*: the worker now threads hf_token into
  _activate_transformers_version (model_name, hf_token); update the one-arg test doubles
  to the real two-arg signature so the silent-success path stays silent.
@danielhanchen

Copy link
Copy Markdown
Member Author

Both fixed:

  • _load_config_json and _check_tokenizer_config_needs_v5 no longer fetch a local checkpoint dir from the Hub when its config.json/tokenizer_config.json is absent, and no longer cache that miss. A file written later in the same process (in-progress checkpoint) is read on the next call, so a TokenizersBackend checkpoint reaches the 5.x path instead of falling through to default.
  • The MLX activation test doubles were one-arg; the worker threads hf_token into _activate_transformers_version(model_name, hf_token). Updated the doubles to the real two-arg signature so test_activate_transformers_version_or_warn_silent_on_success passes again.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0051419054

ℹ️ 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 usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

…r-autoconfig-probe

# Conflicts:
#	studio/backend/tests/test_transformers_version.py
#	studio/backend/utils/transformers_version.py
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

…r-autoconfig-probe

# Conflicts:
#	studio/backend/core/inference/worker.py
#	studio/backend/utils/transformers_version.py
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b4caf9c714

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

Integrates PR #6396 (custom-folder-path tier detection) into the AutoConfig
probe design. Resolved studio/backend/utils/transformers_version.py:

- get_transformers_tier: keep #6396's positive local config.json signals
  (510/550/530 architecture/model_type + Qwen3.6 name override +
  unknown-arch resolve-base fallback) as the strong fast paths, then escalate
  the weak 5.x signals (tokenizer-needs-v5, config-saved-by-5.x) through the
  AutoConfig probe to resolve the exact tier. So a local Qwen3.5 with a
  standard tokenizer routes to 530 by config, not the default 4.57.x.
- Thread hf_token / probe through every path, including the unknown-arch
  recursion and the new 530 config check.
- _check_config_needs_530 made token-aware and cached by (model, token) only
  for a definitive read, consistent with 510/550 (no caching of transient
  misses). _config_needs_530_cache keyed by (model, token).
- activate/ensure: pre-resolve only LoRA adapters (#6396) while keeping the
  hf_token forwarding; fold _safe_is_file/_safe_is_dir over the remaining
  model_name-derived path probes for cross-platform robustness.
- Updated TestCheckConfigNeeds530.test_result_is_cached to the definitive-read
  caching contract (local config.json) used by the 510/550 tests.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@danielhanchen

Copy link
Copy Markdown
Member Author

Merged latest main and resolved the conflicts in studio/backend/utils/transformers_version.py. The only divergence was PR #6396 (custom-folder-path tier detection), now integrated into the AutoConfig probe design:

  • get_transformers_tier keeps Studio: fix tier detection for models loaded via custom folder path #6396's positive local config.json signals (510/550/530 architecture/model_type, the Qwen3.6 name override, and the unknown-arch resolve-base fallback) as the strong fast paths, then escalates the weak 5.x signals (5.x tokenizer class, config saved by transformers 5.x) through the AutoConfig probe to resolve the exact tier. A local Qwen3.5 with a standard tokenizer now routes to 530 by config instead of falling through to 4.57.x.
  • hf_token and probe are threaded through every path, including the unknown-arch recursion and the new 530 config check.
  • _check_config_needs_530 is token-aware and caches by (model, token) only on a definitive read, matching 510/550 (no caching of transient/auth misses).
  • activate/ensure pre-resolve only LoRA adapters (so a full checkpoint reaches its own config.json), and _safe_is_file/_safe_is_dir now guard the remaining model_name-derived path probes.

This also closes the open review items: the probe child writes stderr as UTF-8 bytes and subprocess.run uses errors="replace" (no Unicode crash); the child clears HF_HUB_DISABLE_IMPLICIT_TOKEN; the tokenizer gate is reached with hf_token; the probe cache is keyed by mode so a default-first result isn't reused for a known-5.x caller; needs_transformers_5 passes probe=False (no sidecar spawns on the log-only path) while still reporting version-field-only 5.x models as needing 5.x; local-checkpoint misses are not cached before the files exist; and the plain-Trainer/MLX activation path keeps working when no token is present.

Merged test suite passes (test_transformers_version.py, test_mlx_training_worker_config.py, and the other tier/worker tests) at 206 in the tier+worker group.

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@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 updates the transformers version detection and activation mechanism to support gated/private models by propagating the Hugging Face token (hf_token) to subprocesses and tier detection. It introduces an AutoConfig probe mechanism that executes config parsing inside candidate sidecar virtual environments to dynamically resolve the correct transformers tier for ambiguous models, and updates caching strategies to isolate authenticated and unauthenticated lookups. The review feedback suggests resolving local paths to their absolute real paths in _probe_cache_key to prevent cache collisions, and reusing the _token_cache_key helper function in _cached_config_json to avoid duplicating token hashing logic.

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 +924 to +933
def _probe_cache_key(model_name: str) -> str:
"""Cache key for the probe result. A local checkpoint can be overwritten in place, so
fold in a cheap config.json signature (size + mtime) and re-probe when it changes.
Remote ids key by name alone (resolving a Hub revision would need a pre-activation hub
import that pins the wrong env)."""
try:
st = (Path(model_name) / "config.json").stat()
except OSError:
return model_name
return f"{model_name}\0{st.st_size}:{st.st_mtime_ns}"

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.

medium

To prevent potential cache collisions or incorrect cache hits when using relative paths (e.g., if the current working directory changes or if different relative paths point to different local directories), resolve the config.json path to its absolute real path before generating the cache key.

Suggested change
def _probe_cache_key(model_name: str) -> str:
"""Cache key for the probe result. A local checkpoint can be overwritten in place, so
fold in a cheap config.json signature (size + mtime) and re-probe when it changes.
Remote ids key by name alone (resolving a Hub revision would need a pre-activation hub
import that pins the wrong env)."""
try:
st = (Path(model_name) / "config.json").stat()
except OSError:
return model_name
return f"{model_name}\0{st.st_size}:{st.st_mtime_ns}"
def _probe_cache_key(model_name: str) -> str:
"""Cache key for the probe result. A local checkpoint can be overwritten in place, so
fold in a cheap config.json signature (size + mtime) and re-probe when it changes.
Remote ids key by name alone (resolving a Hub revision would need a pre-activation hub
import that pins the wrong env)."""
try:
config_path = (Path(model_name) / "config.json").resolve()
st = config_path.stat()
return f"{config_path}\0{st.st_size}:{st.st_mtime_ns}"
except OSError:
return model_name

Comment on lines +816 to +822
def _cached_config_json(model_name: str, hf_token: str | None) -> dict | None:
"""Already-fetched config.json from the in-process cache (no new fetch); the tier checks
above populate it, and a miss just skips the version-field probe."""
import hashlib

tok = hashlib.sha256(hf_token.encode()).hexdigest()[:16] if hf_token else None
return _config_json_cache.get((model_name, tok))

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.

medium

Avoid duplicating the token hashing and cache key generation logic. Instead, reuse the existing _token_cache_key helper function to retrieve the cached configuration.

Suggested change
def _cached_config_json(model_name: str, hf_token: str | None) -> dict | None:
"""Already-fetched config.json from the in-process cache (no new fetch); the tier checks
above populate it, and a miss just skips the version-field probe."""
import hashlib
tok = hashlib.sha256(hf_token.encode()).hexdigest()[:16] if hf_token else None
return _config_json_cache.get((model_name, tok))
def _cached_config_json(model_name: str, hf_token: str | None) -> dict | None:
"""Already-fetched config.json from the in-process cache (no new fetch); the tier checks
above populate it, and a miss just skips the version-field probe."""
return _config_json_cache.get(_token_cache_key(model_name, hf_token))
References
  1. Centralize recurring or complex logical checks into a single helper function and reuse it across the codebase to ensure consistency and simplify maintenance.

- _probe_cache_key resolves config.json to its absolute realpath before
  keying, so a relative path or a changed cwd can't collide with or miss a
  prior probe result. Remote ids still fall back to the name (stat raises,
  caught).
- _cached_config_json reuses _token_cache_key instead of re-hashing the
  token inline, keeping the (model, token) key derivation in one place.
@danielhanchen

Copy link
Copy Markdown
Member Author

Both addressed in 1fee210:

  • _probe_cache_key now resolves config.json to its absolute realpath before keying, so a relative path or a changed cwd can't collide with or miss a prior probe result. Remote ids still fall back to the bare name (the stat() raises and is caught).
  • _cached_config_json reuses _token_cache_key instead of re-hashing the token inline, so the (model, token) key derivation lives in one place.

Tier suite still green (191 passed).

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1fee2106eb

ℹ️ 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 007a212 into main Jun 22, 2026
31 of 39 checks passed
@danielhanchen
danielhanchen deleted the feat/transformers-tier-autoconfig-probe branch June 22, 2026 15:20
danielhanchen added a commit that referenced this pull request Aug 17, 2026
…pgrade

Two tests in TestProbeGating fail standalone on main:

  assert get_transformers_tier("org/new") == "default"
  AssertionError: assert '530' == 'default'

Which PR introduced it, and which side is wrong:

  #6550 (2026-06-22) added these two tests, pinning model_type "brandnew"
  #7043 (2026-07-11) added the CONFIG_MAPPING_NAMES tier, three weeks later

#7043 is right, and is not reverted here. Routing by the real mapping beats the
hardcoded tables it replaced, and raising a model_type the ambient default does
not ship is the point of it. What #7043 missed is that it now answers BEFORE the
version-field probe, so the two tests written against that probe stopped reaching
it. "brandnew" is in no mapping, so the mapping check returns 530 and the probe
never runs. They were correct when written and became wrong under a later,
correct source change.

They kept passing because _config_mapping_cache is module-global and other tests
populate it, so in the suite's serial order the mapping check found a state that
skipped the upgrade. Alone, or on an xdist worker, it does not.

Fixed by pinning a model_type the ambient default does ship, which is the only
input domain where the probe is still reachable, so the assertions measure the
probe again rather than the branch above it.

setup_method also now clears _config_mapping_cache: it cleared five caches and
missed the sixth. That is not the fix; with it and the old model_type the class
goes from two failures to three, because a third test leaned on the same stale
mapping.

Robustification, and the real gap: NOTHING pinned the ordering #7043 introduced.
Had it been pinned, #7043 would have had to update these two tests instead of
silently changing what they measured. A new test asserts that a model_type the
default lacks is answered by the mapping and never reaches the probe. Both halves
were mutation-checked:

  mapping short-circuit disabled -> "a model_type the default lacks must be raised"
  probe moved above the mapping  -> "the mapping check must answer before any
                                     sidecar probe runs"

  before (standalone): 2 failed, 5 passed
  after  (standalone): 8 passed

Whole file: 5 failed -> 3 failed, the remaining 3 a pre-existing
TestDamagedLatestSidecarRepairHandoff group unrelated to this.
danielhanchen added a commit that referenced this pull request Aug 17, 2026
…pgrade (#9029)

* Stop TestProbeGating asserting a tier the mapping check is meant to upgrade

Two tests in TestProbeGating fail standalone on main:

  assert get_transformers_tier("org/new") == "default"
  AssertionError: assert '530' == 'default'

Which PR introduced it, and which side is wrong:

  #6550 (2026-06-22) added these two tests, pinning model_type "brandnew"
  #7043 (2026-07-11) added the CONFIG_MAPPING_NAMES tier, three weeks later

#7043 is right, and is not reverted here. Routing by the real mapping beats the
hardcoded tables it replaced, and raising a model_type the ambient default does
not ship is the point of it. What #7043 missed is that it now answers BEFORE the
version-field probe, so the two tests written against that probe stopped reaching
it. "brandnew" is in no mapping, so the mapping check returns 530 and the probe
never runs. They were correct when written and became wrong under a later,
correct source change.

They kept passing because _config_mapping_cache is module-global and other tests
populate it, so in the suite's serial order the mapping check found a state that
skipped the upgrade. Alone, or on an xdist worker, it does not.

Fixed by pinning a model_type the ambient default does ship, which is the only
input domain where the probe is still reachable, so the assertions measure the
probe again rather than the branch above it.

setup_method also now clears _config_mapping_cache: it cleared five caches and
missed the sixth. That is not the fix; with it and the old model_type the class
goes from two failures to three, because a third test leaned on the same stale
mapping.

Robustification, and the real gap: NOTHING pinned the ordering #7043 introduced.
Had it been pinned, #7043 would have had to update these two tests instead of
silently changing what they measured. A new test asserts that a model_type the
default lacks is answered by the mapping and never reaches the probe. Both halves
were mutation-checked:

  mapping short-circuit disabled -> "a model_type the default lacks must be raised"
  probe moved above the mapping  -> "the mapping check must answer before any
                                     sidecar probe runs"

  before (standalone): 2 failed, 5 passed
  after  (standalone): 8 passed

Whole file: 5 failed -> 3 failed, the remaining 3 a pre-existing
TestDamagedLatestSidecarRepairHandoff group unrelated to this.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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