Repository navigation
fix: replace deprecated transformers attention mask imports - #6880
Conversation
Add a local attention-mask compat module adapted from Transformers so Unsloth no longer imports modeling_attn_mask_utils directly. This keeps training working when the module is removed in Transformers v5.10 and eliminates FutureWarning spam during forward passes. Closes unslothai#6860 Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a local copy of attention-mask helper utilities in unsloth/models/_attn_mask_compat.py to replace the deprecated transformers.modeling_attn_mask_utils module, resolving deprecation warnings and ensuring compatibility with Transformers v5.10+. It updates imports across multiple model files and adds comprehensive equivalence tests. Feedback is provided to simplify a tensor subtraction operation to avoid potential device mismatch issues and unnecessary host-to-device copies.
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.
Replace torch.tensor(1.0) subtraction with 1.0 - expanded_mask to avoid CPU/GPU device mismatches and float16 sub_cpu errors on some platforms. Co-authored-by: Cursor <[email protected]>
|
Addressed the Gemini review feedback in 9711691 follow-up: Re-ran |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ec138df744
ℹ️ 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".
…acing The compat module imports `is_tracing` from `transformers.utils.import_utils`, but that symbol is only exported from transformers >= 4.52 (added when the upstream `_prepare_4d_attention_mask_for_sdpa` rewrite landed). Unsloth declares `transformers>=4.51.3` in pyproject.toml, so on the lower bound tested by CI (`__from_pyproject__` matrix cell) the new top-level import raises ImportError before any patched module can import the compat helpers. Mirror the conservative pre-`is_tracing` upstream behavior: when the symbol is missing, define a local `is_tracing(tensor=None)` that only consults `is_torchdynamo_compiling`. The `tensor` argument is accepted but ignored — the older release has no public API for fake-tensor / JAX-jit detection via `import_utils` either, and the previously-used upstream code path on transformers 4.51.x guarded the same checks by `is_torchdynamo_compiling` alone. Tests: - `test_import_falls_back_when_is_tracing_missing` reloads the compat module with `is_tracing` removed from `transformers.utils.import_utils` and asserts the local fallback is in use (returns False when dynamo is idle, accepts the optional tensor positional arg). - All 26 tests in `tests/utils/test_attn_mask_compat.py` pass. This addresses the Codex review feedback (P1) on PR unslothai#6880. Signed-off-by: Taranum Wasu <[email protected]> Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7dac6c8101
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Codex review follow-up on PR unslothai#6880 (P2). The previous fallback (``def is_tracing(tensor=None): return is_torchdynamo_compiling()``) was strictly less conservative than what upstream ``transformers==4.51.3`` did inline before ``is_tracing`` was added to ``transformers.utils.import_utils``. The pre-4.52 upstream expression was: is_tracing = torch.jit.is_tracing() or isinstance( inputs_embeds, torch.fx.Proxy ) or is_torchdynamo_compiling() The previous fallback only consulted Dynamo. That meant callers tracing or exporting under transformers 4.51.x would silently hit the data-dependent ``torch.all(attention_mask == 1)`` branch in ``_ignore_causal_mask_sdpa`` (and the equivalent in ``_prepare_4d_attention_mask_for_sdpa``) — failing on proxy control flow or baking the wrong SDPA causal-mask path. The local fallback now mirrors the legacy upstream expression: - ``torch.jit.is_tracing()`` for ``torch.jit.trace`` / ``torch.jit.script`` flows. - ``isinstance(tensor, torch.fx.Proxy)`` for ``symbolic_trace`` and ``torch.export`` paths that don't go through Dynamo. - ``is_torchdynamo_compiling()`` for ``torch.compile`` and ``torch._dynamo`` paths. The CUDA stream capture, FakeTensor, and JAX (torchax) checks the modern ``is_tracing`` does are out of scope: those need newer ``import_utils`` helpers, and the conservative dynamo fallback is the right choice when those helpers aren't available. This matches the behavior of the upstream ``is_tracing`` helpers that landed in 4.52 in the first place — those were new additions, not behaviour that pre-existed in 4.51.x. Tests: - ``test_import_falls_back_when_is_tracing_missing`` now exercises all three branches (dynamo idle → False; ``torch.fx.Proxy`` arg → True; patched ``torch.jit.is_tracing()`` → True). - All 26 tests in ``tests/utils/test_attn_mask_compat.py`` pass. - ``ruff check`` and ``ruff format`` clean on both files. Signed-off-by: Taranum Wasu <[email protected]> Co-authored-by: Cursor <[email protected]>
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…#6880 Upstream calls _unmask_unattended only when the caller supplied an attention_mask (modeling_attn_mask_utils.py:411 on 4.57.6, :427 on main). The vendored copy had it at function scope, so it also ran on the attention_mask is None -> to_causal_4d path. Values were never wrong there: a causal or sliding-window row always attends to its own diagonal, so no row is entirely -inf and the multiply is a no-op. But to_causal_4d returns a stride-0 expand view, and .mul() materialises it into a dense [bsz, 1, q, kv] tensor. Measured on a B200, bf16: bsz 32, q_len 1, kv 8192 1.34x slower, storage 0.50MB vs 0.02MB bsz 8, q_len 4096 7.06x slower, peak 544MB vs 128MB After this change both match upstream exactly (1.00-1.03x, identical storage). The existing equivalence test could not catch it: it builds inputs_embeds on CPU, where the device.type in ("cuda", "xpu") gate is False for both sides. Added a CUDA counterpart that asserts stride and storage as well as values. Also corrected the is_tracing version note. The symbol first appears in transformers 5.0.0, not 4.52, so the fallback is the live path for all of 4.x rather than an edge case at the 4.51.3 floor. Restored HuggingFace's copyright line alongside ours, and replaced the "v5.10+" claim in the module docstring with what is actually true today: the module still ships in 5.14.1, but transformers stopped importing it itself after 5.5.0 (135 internal references at 4.51.3, none from 5.5.0), so it can be dropped at any release. Verified: 34560 differential checks CPU+CUDA with 0 value mismatches and 0 layout divergences; 2880 checks in each of ten isolated venvs covering Python 3.9-3.14, transformers 4.51.3/4.57.6/5.5.0/5.14.1 and torch 2.6.0/2.7.1/2.8.0/2.9.1; bit-identical logits and generated token ids against main on Llama-3.2-1B and gemma-2-2b-it.
|
Thanks for this, the approach is right and the vendored copy is faithful. I pushed one commit (1b54d2f) with a fix plus a few doc corrections. The fix
Values were never wrong: a causal or sliding-window row always attends to its own diagonal, so no row is entirely
Reachable through the The existing equivalence test could not catch this: it builds Doc corrections
Verification
Two follow-ups, not blockers
Also |
unslothai#6880 _expand_mask was changed to a Python float literal (1.0 - expanded_mask), which reverts huggingface/transformers#38637. Upstream uses a 0-dim tensor from 4.53.0 onward so ExecuTorch edge-dialect lowering does not see an fp32 scalar against an fp16/bf16 mask. Both forms are bitwise equal on every supported torch, so this costs nothing and keeps the vendored copy matching upstream. Also switch the new test file to the AGPL-3.0 SPDX header used by the rest of tests/ instead of LGPL-3.0, which is not used anywhere in the repo.
|
@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". |
|
Pushed 9e49937, which reverts the The test file also carried an LGPL-3.0 header. Verification on the current head:
Cross-platform, running the PR's own tests as a real gate with torch and transformers installed:
The 4 skips are the CUDA-only regression test, which correctly skips on GPU-less runners. |
…nslothai#6880) _attn_mask_compat.py is a hand-copied subset of transformers' modeling_attn_mask_utils.py, and hand-copied code drifts silently. Both defects found while reviewing this PR were invisible in the diff and only surfaced under differential testing, so add a test that compares the two ASTs directly. Stylistic differences are normalised away first: docstrings, annotation text, the deprecation warnings the copy exists to drop, the 4.x inline is_tracing expression against the 5.x helper, single-use temporaries and a dead else after a return. Two deliberate forward-ports (the xpu device gate from 5.x, the 0-dim inversion tensor from 4.53.0) are relaxed only below the version that introduced them, so newer installs still compare them exactly. Verified 11/11 symbols match on transformers 4.51.3, 4.57.6, 5.5.0 and 5.14.1, that the test skips when the upstream module is absent, and that it fails on both defects this PR already fixed.
|
Added a drift test in 873baad, since the two defects fixed during this review were both invisible in the diff and only surfaced under differential testing. A vendored copy is only as good as the guarantee that it still matches what it vendors, and that guarantee was resting on review alone.
Normalised: docstrings, annotation text, the deprecation Two differences are deliberate, because the copy carries forward-ports that older Transformers lacks. Those are relaxed only below the release that introduced them, so newer installs still compare them exactly:
Results:
The skip on the last row is the point: once HuggingFace removes the module there is nothing left to compare, and that is the state this whole file is preparing for. I also checked the test can actually fail, since a green test that cannot go red is worse than none. Re-introducing each of the two defects already fixed here:
Both pass again once reverted. Full file is 32 passed across the two test modules. One note for whoever maintains this next: if the test fails after a Transformers upgrade, the default assumption should be that upstream changed and the copy needs re-syncing, not that the test is wrong. Relaxing a comparison is reasonable only for a deliberate divergence, and the version gate plus a reason should be written down at the same time. |
The import-hoist step diffed $MERGE_BASE against HEAD. On a pull_request event HEAD is refs/pull/N/merge, so that range spans every base commit since the branch point, and the step lints files the PR never touched. It fails PRs that change no Python at all. #7734 touches only TypeScript and CSS and was failed by 3 blockers from #6880; the run reported "checking 78 file(s)". Pin the AFTER end to the PR head SHA so the range is the PR's own commits. The head is fetched via refs/pull/N/head, which exists for fork PRs too, and the verifier reads revisions with git show, so the shallow clone stands. A failure here also short-circuits the rest of the job, so every later lint step (debugger calls, shell parse, YAML/JSON parse, codespell, shellcheck, ruff format) is skipped. Co-authored-by: danielhanchen <[email protected]>
Summary
unsloth/models/_attn_mask_compat.py, a local copy of the small attention-mask API Unsloth uses fromtransformers.modeling_attn_mask_utilsCloses #6860
Why
transformers.modeling_attn_mask_utilsis deprecated and scheduled for removal in Transformers v5.10. Unsloth currently imports it from 8 model files plus_utils.py, which triggers import-time failures once the module is removed and emitsFutureWarningnoise during training forward passes.Approach
The compat module preserves the existing
AttentionMaskConverter/_prepare_4d_*behavior Unsloth already relies on (adapted from HuggingFace Transformers, Apache 2.0). This avoids a risky signature migration tomasking_utilsin one shot while keeping mask output identical.Test plan
pytest tests/utils/test_attn_mask_compat.py -v— 25 passedto_causal_4dand_prepare_4d_causal_attention_mask_for_sdpamatchtransformers.modeling_attn_mask_utilson transformers 5.13.0 across multiple batch sizes / sequence lengths / sliding windowsFutureWarningaboutmodeling_attn_mask_utilstransformers.modeling_attn_mask_utilsimports remain underunsloth/models/masking_utilsif preferredMade with Cursor