Skip to content

fix(config): preserve per-layer-type RoPE dictionaries - #3579

Merged
Qubitium merged 2 commits into
ModelCloud:mainfrom
tpurtell:upstream/01-nested-rope-20261108
Nov 8, 2026
Merged

Qubitium merged 2 commits into
ModelCloud:mainfrom
tpurtell:upstream/01-nested-rope-20261108

Conversation

@tpurtell

@tpurtell tpurtell commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Hybrid attention configurations already contain separate RoPE dictionaries per layer type. Preserve those dictionaries during compatibility normalization instead of inserting flat legacy scalar fields. Keep flat legacy defaults unchanged.

Stack

Layer 1/36 of a dependency-ordered fork extraction. Starts at upstream main 6bf8b0b1b. Review only this layer.

GitHub requires this cross-fork PR to target upstream main, so its Files changed tab includes earlier stack layers. After the predecessor lands, rebase this branch and retarget the next layer; do not merge later layers out of order. No predecessor is merged automatically.

Tests

CUDA_VISIBLE_DEVICES='' HIP_VISIBLE_DEVICES='' OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -q tests/test_nested_rope_config_compat.py

2 passed. Used Python 3.12, Torch 2.14.1, Transformers 5.19.0. No model quantization, GPU work, downloads, or heavyweight model validation. Unit fixtures are small and CPU execution is constrained to one math thread.

Review and remaining validation

This layer and its dependency diff were reviewed for scope, existing extension points, and compatibility with the resolved fork snapshot. New focused regression coverage is included. Kept as a draft for maintainer review; hardware paths and end-to-end model behavior have not been revalidated in this session. No speed claim. Original integration/history is preserved in tpurtell#3.

The guard keyed on `layer_types` alone, but Transformers resolves nested
`rope_parameters` through `_rope_type_labels` first
(`RotaryEmbeddingConfigMixin.nested_rope_parameter_keys`). DeepSeek V4
declares `_rope_type_labels = ("main", "compress")` while `layer_types`
names attention blocks, so the subset check failed and the flat backfill
appended scalar `rope_type`/`rope_theta` siblings next to the nested
dictionaries.

Factor the decision into `_rope_parameters_are_per_layer`, which mirrors
Transformers' label precedence and only inspects the keys that actually
resolve as nested. Flat legacy configs, empty dicts and configs without
labels still get the backfill.

Tests now cover the specific behaviours rather than a single happy path:
idempotency, no flat scalar siblings, `None` (NoPE) layer preservation,
`_rope_type_labels` priority, flat parameters that merely declare
`layer_types`, and missing/empty `rope_parameters`.

@Qubitium Qubitium left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review

The premise is correct and the new test is a genuine regression test: on main,
test_nested_attention_rope_parameters_are_preserved fails, and with this change
it passes. I reproduced both directions.

I pushed a follow-up commit (e2347892) to the PR branch with two changes; details
below.

What is correct

  • Real bug, real fix. Without the guard, a per-layer rope_parameters dict
    gains scalar rope_type/rope_theta siblings. This mirrors the workaround
    CohereCompassConfig.convert_rope_params_to_dict already carries on the Hub
    ("dangling entries were saved that fire on validation"), so the class of failure
    is real and precedented.
  • Flat legacy configs still work. rope_parameters=None + flat rope_theta
    still produces {"rope_type": "default", "rope_theta": ...}. The second test
    covers this.
  • validate_rope() passes afterwards, and the nested keys resolve correctly
    through RotaryEmbeddingConfigMixin.nested_rope_parameter_keys.
  • ruff check is clean; the diff does not touch unrelated behaviour.

Issue found and fixed

The guard resolves nested keys differently from Transformers. It keys on
config.layer_types, but Transformers prefers _rope_type_labels first:

# transformers/modeling_rope_utils.py:771
labels = getattr(self, "_rope_type_labels", None) or getattr(self, "layer_types", None) or ()

DeepseekV4Config is the counter-example: _rope_type_labels = ("main", "compress"),
while layer_types are heavily_compressed_attention. The subset check therefore
fails and the flat backfill runs anyway:

before: {'main': {...}, 'compress': {...}}
after : {'main': {...}, 'compress': {...}, 'rope_type': 'default', 'rope_theta': 10000.0,
         'partial_rotary_factor': 0.125}

V4 happens to survive because it overrides validate_rope(), so this is latent
rather than an active break — but it is the same pollution the PR sets out to
prevent, and any future config using _rope_type_labels would inherit it.

My commit factors the decision into _rope_parameters_are_per_layer, which
mirrors Transformers' label precedence and only inspects keys that actually
resolve as nested. It keeps the guard for pure nested dicts, still returns early
for None (NoPE) layers, and still backfills flat/empty/missing configs.

Test coverage

I extended the test from 2 to 9 cases, because the original only asserted the
happy path and would not have caught the above:

  • no flat scalar siblings added (rope_type/rope_theta absent from the nested top level);
  • idempotency across three normalize passes;
  • _rope_type_labels priority over layer_types — the V4 case above;
  • None (NoPE) layer preservation;
  • flat parameters that merely declare layer_types still get the backfill;
  • missing and empty rope_parameters still get the backfill.

One correction worth noting: I first asserted that pre-existing dangling scalars
should be removed. Transformers tolerates them (validate_rope and
standardize_rope_params both pass), so the correct invariant is only that no
new ones are added. The test reflects that.

Verification

On the PR head (e2347892), rebased onto main:

tests/test_nested_rope_config_compat.py  9 passed
tests/test_glm_nope_config.py            2 passed
tests/test_hunyuan_ocr_support.py       23 passed
                                        -----------
                                        34 passed

Broader sweep (-k "config_compat or rope_params or nope or hunyuan or normali",
12198 deselected): 198 passed, 60 skipped, 3 failed. All three failures are
pre-existing on main at 6bf8b0b1 and unrelated to this PR — I verified each
one by running it on a clean main checkout:

  • test_hf_config_compat.py::test_normalize_hf_config_compat_restores_legacy_cache_length_helpers
  • test_hf_config_compat.py::test_resolve_trust_remote_code_overrides_when_native_support_exists
  • test_awq_gemv_fast_jit.py::test_llm_awq_decode_normalizes_scaled_zeros_without_dynamic_attr_access

Notes (non-blocking)

  • The docstring says "Hybrid attention configs (including Dots3)". I checked the
    actual dots-studio/dots3-note-prev config: it ships rope_parameters: null
    with a flat rope_theta, so the guard does not fire on it and it takes the
    flat backfill path. The guard is still right, but "including Dots3" describes
    the intended shape rather than the currently published checkpoint — worth
    adjusting if a reviewer reads it as confirmed coverage.
  • The new test file lacks the SPDX-FileCopyrightText header that most files in
    tests/ carry. Not enforced by format/check.sh, but recent additions do
    include it.
  • ruff format wants to reformat the test file (and hf.py, though that drift is
    pre-existing on main). CI only runs ruff check, so neither fails the gate.

@Qubitium
Qubitium marked this pull request as ready for review November 8, 2026 04:43
@Qubitium
Qubitium merged commit 67cb384 into ModelCloud:main Nov 8, 2026
1 check passed
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.

2 participants