Skip to content

Survive transformers 5.x configs that refuse a global per-layer read - #8492

Merged
oobabooga merged 6 commits into
mainfrom
fix/hetero-config-head-dim
Aug 24, 2026
Merged

oobabooga merged 6 commits into
mainfrom
fix/hetero-config-head-dim

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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. Access it via the individual layer configs instead
(e.g. config.per_layer_config[i].head_dim).

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_get ends in getattr(config, field_name, default). That default only
swallows AttributeError. transformers 5.x heterogeneous configs -- Gemma 3n,
Gemma 4, anything carrying per_layer_config -- raise
AmbiguousGlobalPerLayerAttributeError out of __getattribute__, which is a
plain Exception. So it escapes a probe whose entire question is "does this
config 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_reason reads None as "nothing here exceeds
Flash 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_dims now reads config.per_layer_config first and
falls back to the global value. _get_max_attention_head_dim on a config whose
layers are 128/512/128 returns 512, and FA2 still gets disabled with 512 named
in the reason.

Compatibility

Nothing new is named or imported. AmbiguousGlobalPerLayerAttributeError does
not exist on transformers 4.57.6 and neither does per_layer_config, so both
are 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, a
collections.abc.Sequence subclass, so an isinstance(..., (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 that
attribute all behave exactly as before.

Tests

tests/test_heterogeneous_config_probes.py, 12 tests. The fake exception is
reconstructed as a plain Exception rather than imported, because inheriting
from AttributeError would 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.py and
test_flex_attention_needs_ampere.py pass unchanged.

danielhanchen and others added 2 commits August 11, 2026 19:36
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.

@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: 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".

Comment thread unsloth/models/_utils.py Outdated
them.
"""
try:
per_layer = getattr(config, "per_layer_config", 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.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 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.

Comment thread unsloth/models/_utils.py
# 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

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 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 👍 / 👎.

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 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.

Comment thread unsloth/models/_utils.py
Comment on lines +634 to +635
candidates = _get_per_layer_values(config, field_name)
candidates.append(_config_get(config, field_name, 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.

P2 Badge 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 👍 / 👎.

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.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

All three items answered, one fixed at 45744cc71 and two disproved in their threads.

The agreed one was live for a reason the comment did not name. The claimed shape, per_layer_config as a list, does not exist: to_dict writes a mapping keyed by zero-padded layer index ({"04": {"head_dim": 512}}), and the suggested remedy of reading the field through _config_get still yields nothing, because iterating that mapping walks the keys. The path that actually reaches this code is Studio's _load_config_for_gpu_estimate, which deliberately never builds a transformers config: it reads config.json and wraps every dict in SimpleNamespace.

Measured on google/gemma-4-E2B-it under a real transformers 5.15.0 install: the object form gave head_dim 512 with flex attention disabled, while the saved-config and namespace forms gave 256 and left flex attention on for the same model. All three agree at 512 now.

Worth knowing for anyone reading this later: a Gemma 4 checkpoint saved by transformers 5.15 does serialize per_layer_config (7 entries, head_dim 512), so this arrives the moment someone saves a fine-tune under the version this PR is about. The currently published unsloth/gemma-4-* configs were saved under 5.5.0 and predate the feature, which is why nothing had tripped over it yet.

Tests: 38 passed / exit 0 at the head, 40 passed / exit 0 after, and 42 passed / exit 0 with test_attention_implementation.py included. Both new tests fail at the head.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 45744cc711

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: fb0579065e

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

Copy link
Copy Markdown
Member Author

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.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e080507908

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

@oobabooga

Copy link
Copy Markdown
Member

I traced the configuration probe through the language, vision, and Studio attention resolver paths and reproduced the Transformers 5.15.0 failure with google/gemma-4-E2B-it: main raises AmbiguousGlobalPerLayerAttributeError, while this branch reads the 512 head dimension from live, serialized, and Studio namespace forms and falls back to SDPA. The focused attention suites passed under Transformers 5.15.0 and 4.57.6.

@oobabooga
oobabooga merged commit fdcb6d1 into main Aug 24, 2026
39 of 41 checks passed
@oobabooga
oobabooga deleted the fix/hetero-config-head-dim branch August 24, 2026 15:22
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.

2 participants