Repository navigation
Survive transformers 5.x configs that refuse a global per-layer read - #8492
Conversation
Gemma4_(E2B)_Reinforcement_Learning_Sudoku_Game dies at model load on transformers 5.15.0, in the first cell, before anything trains: AmbiguousGlobalPerLayerAttributeError: 'head_dim' is a per-layer attribute and may vary across layers. _config_get does getattr(config, field, default). The default only covers AttributeError, and transformers 5.x heterogeneous configs raise this from __getattribute__ instead, so it escapes the Flash Attention head-dim probe and takes the whole load with it. Every caller of that helper is asking whether the config says X, so a refusal to answer globally is the same as not saying, and it returns the default. Reading the per-layer values matters as much as surviving. If a refusal only became a default, a heterogeneous model would report no head dim at all, and _get_flash_attention_disable_reason reads None as no reason to disable -- on exactly the models whose layers are allowed to differ. So _collect_attention_head_dims now reads config.per_layer_config first and falls back to the global value. Feature-detected throughout, with nothing named or imported: the exception class does not exist on transformers 4.57.6, per_layer_config does not either, and the object transformers hands back is a Sequence view rather than a list, so the per-layer walk guards the iteration instead of checking the type. Tests reconstruct the exception as a plain Exception rather than importing it; inheriting from AttributeError would make all of them pass unfixed. On this branch reverted, 11 of the 12 fail.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 806d3052d2
ℹ️ 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".
| them. | ||
| """ | ||
| try: | ||
| per_layer = getattr(config, "per_layer_config", None) |
There was a problem hiding this comment.
Read per-layer values from dictionary configs
When a heterogeneous config is dictionary-backed, getattr cannot see its per_layer_config key even though _config_get and the surrounding attention resolver explicitly support dictionaries. For example, {"per_layer_config": [{"head_dim": 512}]} produces no per-layer values, so _get_max_attention_head_dim can return None and leave Flash Attention enabled for an oversized layer. Read this field through the dictionary-aware accessor.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 45744cc, though not in the shape described, and the accessor swap alone would not
have done it.
The serialized form is not a list. HeterogeneousConfigMixin._update_heterogeneous_to_dict_output
writes a mapping of zero-padded layer index to that layer's overrides, so a saved Gemma 4
text config carries "per_layer_config": {"04": {"head_dim": 512}, "09": {"head_dim": 512}, ...}.
Reading that through _config_get and then iterating it walks the keys "04", "09", and
_config_get("04", "head_dim") is None, so the values are still lost.
There is also a third shape, and it is the one that actually reaches this code: Studio's
_load_config_for_gpu_estimate never builds a transformers config, it reads config.json and
wraps every dict in a SimpleNamespace, so the mapping arrives as an object whose attribute
names are the layer indices.
Measured on google/gemma-4-E2B-it under transformers 5.15.0, whose Gemma4TextConfig
synthesizes head_dim = 512 on every full-attention layer:
| form | max head dim | flash disabled |
|---|---|---|
| live config object | 512 | yes |
save_pretrained config.json |
256 (was), 512 (now) | no (was), yes (now) |
| Studio namespace | 256 (was), 512 (now) | no (was), yes (now) |
The fix reads per_layer_config through the dict-aware accessor and normalizes all three
shapes to the layer configs before iterating. Regression tests in
tests/test_heterogeneous_config_probes.py cover the mapping and the namespace.
| # transformers 4.x versions this still supports, and a config is | ||
| # third-party code that may raise anything. `_get_per_layer_values` | ||
| # below is where the per-layer answer actually gets read. | ||
| return default |
There was a problem hiding this comment.
Check per-layer dropout before enabling flex attention
When attention_dropout is itself a per-layer attribute, its global read raises the ambiguity exception and this fallback turns it into 0. _supports_flex_attention consequently misses nonzero dropout because _iter_attention_configs does not enumerate entries in the per-layer sequence, and may advertise/select flex attention despite its explicit nonzero-dropout guard. The per-layer dropout values need to participate in that check rather than being treated as absent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable. On transformers 5.15.0 an attribute only becomes per-layer when
per_layer_config overrides it, and _HeterogeneitySpec.per_layer_attributes is built
solely from the override keys. For the heterogeneous configs that exist,
Gemma4TextConfig.__post_init__ synthesizes per_layer_config with head_dim (and
num_key_value_heads when num_global_key_value_heads is set) and nothing else -- on
google/gemma-4-E2B-it, text_config.per_layer_attributes is exactly {'head_dim'} and
_config_get(text_config, "attention_dropout", 0) returns the real 0.0 with no exception
involved. No shipped checkpoint puts attention_dropout in per_layer_config, and every
released config has it at 0.0 globally, so the fallback never stands in for a nonzero
per-layer value. A config hand-built with per_layer_config={2: {"attention_dropout": 0.1}}
does behave as described, but that is a constructed input, not one flex attention selection
can receive.
| candidates = _get_per_layer_values(config, field_name) | ||
| candidates.append(_config_get(config, field_name, None)) |
There was a problem hiding this comment.
Derive missing head dimensions for each layer
When heterogeneous layers omit an explicit head_dim but expose per-layer hidden_size and num_attention_heads, this only collects the four explicit dimension fields. The later derivation still reads those size/count fields globally, where the new exception handling converts their ambiguity errors to None; consequently an oversized derived head dimension such as 1024 / 2 = 512 is never reported and Flash Attention can remain enabled. Apply the existing derivation to each per-layer config as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The derivation branch is unreachable on the configs this is about, and the premise does not
hold on the others.
_collect_attention_head_dims only falls through to hidden_size / num_attention_heads when
none of the four explicit head-dim fields produced a value. On the heterogeneous configs that
exist in transformers 5.15.0, head_dim is the per-layer attribute -- Gemma4TextConfig
synthesizes per_layer_config = {layer: {"head_dim": 512}} for the full-attention layers --
so the explicit path always fires first and returns 512. Confirmed on
google/gemma-4-E2B-it: sorted(set(_collect_attention_head_dims(text_config))) is
[256, 512] and _get_max_attention_head_dim(config) is 512.
And a config cannot generally be heterogeneous over hidden_size or num_attention_heads
to begin with: those are read globally by the config's own validator at construction, so
LlamaConfig(..., per_layer_config={2: {"hidden_size": 1024}}) raises
AmbiguousGlobalPerLayerAttributeError from validate_architecture before any consumer sees
it. The two heterogeneous checkpoint families the transformers docs name
(nvidia/Llama-3_3-Nemotron-Super-49B-v1_5, nvidia/gpt-oss-puzzle-88B) carry no
per_layer_config at all -- they use their own remote-code block_configs -- and neither
varies the head count per layer.
A live transformers 5.x heterogeneous config hands back a _PerLayerConfigView,
a Sequence of resolved layer configs, and the probe read it correctly. The same
checkpoint saved to config.json does not keep that shape: to_dict writes a
mapping of zero-padded layer index to that layer's overrides, {"04":
{"head_dim": 512}}, and Studio's VRAM estimator re-reads that JSON into
SimpleNamespaces rather than building a config at all.
Both mapping forms were walked as if they were the sequence, so iteration
yielded the layer indices and no head dim survived. Measured on
google/gemma-4-E2B-it under transformers 5.15.0, whose text config synthesizes
head_dim 512 on every full-attention layer: the object form reported 512 and
disabled Flash Attention, while the saved and namespace forms reported the
global 256 and left FA2 on for the 512-wide layers of the same model.
per_layer_config is now read through the dict-aware accessor, and the mapping
forms take their values, not their keys.
|
All three items answered, one fixed at The agreed one was live for a reason the comment did not name. The claimed shape, Measured on Worth knowing for anyone reading this later: a Gemma 4 checkpoint saved by transformers 5.15 does serialize Tests: 38 passed / exit 0 at the head, 40 passed / exit 0 after, and 42 passed / exit 0 with @codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Keep the externally-determined facts (the transformers 5.x exception name and versions, the serialized per-layer mapping shape, the 256 ceiling) and drop the restatements around them.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Confirmed this hits _config_get in unsloth/models/_utils.py, which still swallows only AttributeError, and the per-layer head dim never reaches the Flash Attention ceiling check. Will get this reviewed. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
I traced the configuration probe through the language, vision, and Studio attention resolver paths and reproduced the Transformers 5.15.0 failure with |
Gemma4_(E2B)_Reinforcement_Learning_Sudoku_Gamedies at model load ontransformers 5.15.0, in the first cell, before anything trains:
Found on a real L4 in a mainline notebook sweep (transformers 5.15.0, trl
1.9.2, peft 0.19.1, torch 2.11.0, unsloth 2026.8.15, unsloth_zoo 2026.8.10).
The traceback is
resolve_attention_implementation->_get_flash_attention_disable_reason->_get_max_attention_head_dim->_collect_attention_head_dims->_config_get.The bug
_config_getends ingetattr(config, field_name, default). That default onlyswallows
AttributeError. transformers 5.x heterogeneous configs -- Gemma 3n,Gemma 4, anything carrying
per_layer_config-- raiseAmbiguousGlobalPerLayerAttributeErrorout of__getattribute__, which is aplain
Exception. So it escapes a probe whose entire question is "does thisconfig mention a head dim", and takes the model load with it.
Two halves, and the second is the one that could go wrong quietly
Surviving is not enough. If a refusal simply became the default, a
heterogeneous model would report no head dim at all, and
_get_flash_attention_disable_reasonreadsNoneas "nothing here exceedsFlash Attention's 256 ceiling" -- on precisely the models whose layers are
allowed to differ. That trades a loud failure for a silent wrong answer.
So
_collect_attention_head_dimsnow readsconfig.per_layer_configfirst andfalls back to the global value.
_get_max_attention_head_dimon a config whoselayers are 128/512/128 returns 512, and FA2 still gets disabled with 512 named
in the reason.
Compatibility
Nothing new is named or imported.
AmbiguousGlobalPerLayerAttributeErrordoesnot exist on transformers 4.57.6 and neither does
per_layer_config, so bothare feature-detected: the read is guarded by behaviour, and the per-layer walk
guards the iteration rather than checking a type. That last part is load
bearing -- transformers hands back
_PerLayerConfigView, acollections.abc.Sequencesubclass, so anisinstance(..., (list, tuple))guard would skip it silently and take the per-layer path out of service without
failing anything. There is a test for exactly that.
A config with no
per_layer_config, an empty one, or a non-sequence in thatattribute all behave exactly as before.
Tests
tests/test_heterogeneous_config_probes.py, 12 tests. The fake exception isreconstructed as a plain
Exceptionrather than imported, because inheritingfrom
AttributeErrorwould make every one of them pass without the fix.With the source reverted on this branch, 11 of the 12 fail. The 28 tests in
test_attention_implementation.py,test_attn_impl_honor_explicit.pyandtest_flex_attention_needs_ampere.pypass unchanged.