Skip to content

fix: replace deprecated transformers attention mask imports - #6880

Merged
danielhanchen merged 13 commits into
unslothai:mainfrom
Taranum01:fix/6860-attn-mask-compat
Jul 31, 2026
Merged

danielhanchen merged 13 commits into
unslothai:mainfrom
Taranum01:fix/6860-attn-mask-compat

Conversation

@Taranum01

Copy link
Copy Markdown
Contributor

Summary

  • Add unsloth/models/_attn_mask_compat.py, a local copy of the small attention-mask API Unsloth uses from transformers.modeling_attn_mask_utils
  • Route all 9 Unsloth import sites through the compat module instead of the deprecated Transformers path
  • Add equivalence tests comparing compat output to the legacy Transformers implementation

Closes #6860

Why

transformers.modeling_attn_mask_utils is 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 emits FutureWarning noise 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 to masking_utils in one shot while keeping mask output identical.

Test plan

  • pytest tests/utils/test_attn_mask_compat.py -v — 25 passed
  • Verified to_causal_4d and _prepare_4d_causal_attention_mask_for_sdpa match transformers.modeling_attn_mask_utils on transformers 5.13.0 across multiple batch sizes / sequence lengths / sliding windows
  • Verified compat helpers emit no FutureWarning about modeling_attn_mask_utils
  • Verified no direct transformers.modeling_attn_mask_utils imports remain under unsloth/models/
  • Maintainer review: happy to migrate further to masking_utils if preferred

Made with Cursor

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

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

Comment thread unsloth/models/_attn_mask_compat.py Resolved
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]>
@Taranum01

Copy link
Copy Markdown
Contributor Author

Addressed the Gemini review feedback in 9711691 follow-up: _expand_mask now uses 1.0 - expanded_mask instead of torch.tensor(1.0, dtype=dtype) - expanded_mask to stay device-agnostic and avoid float16 CPU subtraction issues.

Re-ran pytest tests/utils/test_attn_mask_compat.py -v — 25/25 still passing.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

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

Comment thread unsloth/models/_attn_mask_compat.py Resolved
Taranum Wasu and others added 2 commits July 8, 2026 03:36
…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]>

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

Comment thread unsloth/models/_attn_mask_compat.py Resolved
Taranum Wasu and others added 3 commits July 8, 2026 03:59
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]>
@Etherll Etherll self-assigned this Jul 23, 2026
@Etherll

Etherll commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e16b9ac5f1

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

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

Copy link
Copy Markdown
Member

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

_unmask_unattended was at function scope, so it also ran on the attention_mask is None -> to_causal_4d path. Upstream only calls it when the caller supplied a mask (modeling_attn_mask_utils.py:411 on 4.57.6, :427 on main).

Values were never wrong: 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 in bf16:

shape before after
bsz 32, q_len 1, kv 8192 1.34x slower, 0.50 MB storage 1.00x, 0.02 MB (matches upstream)
bsz 8, q_len 4096 7.06x slower, 544 MB peak 1.01x, 128 MB (matches upstream)

Reachable through the bsz != 1 inference paths in gemma.py:190, gemma2.py:492/499, cohere.py:451, granite.py:441, falcon_h1.py:526, which guard on batch size but not on the mask.

The existing equivalence test could not catch this: it builds inputs_embeds on CPU at line 109, where the device.type in ("cuda", "xpu") gate is False for both implementations. I added a CUDA counterpart that asserts stride and storage as well as values.

Doc corrections

  • is_tracing first appears in transformers 5.0.0, not 4.52. I checked import_utils.py at v4.51.3, v4.52.4, v4.53.3, v4.55.4, v4.56.2, v4.57.6, v5.0.0, v5.2.0, v5.5.0. That makes the fallback the live path for all of 4.x rather than an edge case at the floor, which is worth stating since it is the branch most users hit.
  • Restored HuggingFace's copyright line next to ours, matching how unsloth/kernels/fp8.py and unsloth/optimizers/q_galore_adamw.py credit adapted sources.
  • Replaced "compatible with Transformers v5.10+" with what is true today. The module still ships in 5.14.1 and the deprecation text still says v5.10, but transformers stopped importing it itself after 5.5.0 (135 internal references at 4.51.3, 121 at 4.57.6, none from 5.5.0 on). It is an orphaned shim kept for external consumers, so it can go at any release. That is the real argument for this PR, and it is stronger than the one in the description.

Verification

  • 34560 differential checks against transformers.modeling_attn_mask_utils on CPU and CUDA across batch size, query length, past length, sliding window, dtype and mask kind: 0 value mismatches, and now 0 layout divergences.
  • 2880 checks in each of ten isolated venvs: Python 3.9 through 3.14, transformers 4.51.3 / 4.57.6 / 5.5.0 / 5.14.1, torch 2.6.0 / 2.7.1 / 2.8.0 / 2.9.1. All pass, both is_tracing branches exercised.
  • With modeling_attn_mask_utils.py deleted from a 5.14.1 install, all 10 pre-PR import statements fail and all 9 post-PR ones succeed, which is the scenario this PR exists for.
  • Bit-identical logits and generated token ids against main on Llama-3.2-1B-Instruct and gemma-2-2b-it, right and left padded, plus an identical result through Studio's safetensors chat path.
  • Instrumented counters: the helper runs 16 times per 16-token generation on Llama-3.2-1B and 33 on gemma-2-2b-it, and 0 times during training, since llama.py:1015 drops the mask when self.training. Worth noting the issue says the warnings fire during a QLoRA training run; on Unsloth's path they fire during inference and eval instead.
  • Warning counts on 5.5.0 and 5.14.1: 11 FutureWarnings from the legacy module for a 4-call sequence, 0 from the compat module.

Two follow-ups, not blockers

pyproject.toml:92 and :586 still pin transformers<=5.5.0, so nobody can install into the >=5.10 case this protects against. Worth bumping separately once 5.x is validated.

tests/utils/test_attn_mask_compat.py is not run by any workflow. pyproject.toml:1337 limits testpaths to tests/security, studio-backend-ci.yml:189-201 passes --ignore=tests/utils, and consolidated-tests-ci.yml lists tests/utils files individually. Adding it to the Bucket-A list at lines 267 and 358 would get it running.

Also tests/version_compat/test_transformers_pinned_symbols.py:319-334 still says the symbols are imported by llama.py and sentence_transformer.py, which is no longer true after this PR.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 29, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 29, 2026
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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 29, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9e49937425

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

Pushed 9e49937, which reverts the _expand_mask inversion back to upstream's form and fixes the license header on the new test file. Details on the first are in the inline thread; short version is that upstream moved to torch.tensor(1.0, dtype=dtype) at 4.53.0 in huggingface/transformers#38637 for ExecuTorch edge-dialect lowering, so ec138df was reverting a fix rather than applying one. My earlier confirmation on that thread was wrong and I have retracted it.

The test file also carried an LGPL-3.0 header. tests/ is 92:10 AGPL-3.0 and LGPL is not used anywhere in the repo, so it now uses the standard SPDX-License-Identifier: AGPL-3.0-only. unsloth/models/_attn_mask_compat.py keeps Apache-2.0, which is correct: it is adapted from Apache-2.0 Transformers code and matches its neighbours in that directory.

Verification on the current head:

  • 34560 differential checks against transformers.modeling_attn_mask_utils on CPU and CUDA, 0 value mismatches and 0 layout divergences.
  • 2880 checks in each of transformers 4.51.3 (Python 3.9, torch 2.5.1), 5.5.0, 5.14.1 and 4.57.6 (Python 3.14), all clean. 4.51.3 is the one that matters for the revert, since it sits on the float-literal side of the 4.53.0 boundary and confirms the vendored copy stays equivalent to both upstream forms.
  • FutureWarning counts: legacy emits 11 on 5.5.0 and 5.14.1, the vendored copy emits 0 on every version tested.
  • is_tracing resolves through the transformers export on 5.x and through the local fallback on 4.x, so both branches are exercised.

Cross-platform, running the PR's own tests as a real gate with torch and transformers installed:

runner result
ubuntu-latest, Python 3.12 x64 26 passed, 4 skipped
macos-14, Python 3.12 arm64 26 passed, 4 skipped
windows-latest, Python 3.12 x64 26 passed, 4 skipped

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

Copy link
Copy Markdown
Member

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.

tests/utils/test_attn_mask_upstream_drift.py parses both _attn_mask_compat.py and the installed transformers.modeling_attn_mask_utils, normalises away differences that are stylistic rather than semantic, and asserts the remainder is identical.

Normalised: docstrings, annotation text, the deprecation warnings.warn calls the copy exists to drop, the 4.x inline torch.jit.is_tracing() or ... or is_torchdynamo_compiling() against the 5.x is_tracing helper, single-use temporaries, and a dead else after a return.

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:

transformers outcome
4.51.3 (Python 3.9) 11/11 symbols match
4.57.6 11/11 symbols match
5.5.0 11/11 symbols match
5.14.1 11/11 symbols match
5.14.1, module deleted skipped

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:

  • reverting _expand_mask to 1.0 - expanded_mask fails the test, flagging _expand_mask
  • hoisting _unmask_unattended back to function scope fails it, flagging _prepare_4d_causal_attention_mask_for_sdpa

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.

@danielhanchen
danielhanchen merged commit 7367955 into unslothai:main Jul 31, 2026
1 check passed
danielhanchen added a commit that referenced this pull request Aug 2, 2026
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]>
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.

Deprecated modeling_attn_mask_utils imports break on transformers v5.10

4 participants