[Qwen3] `create_masks_for_generate` return type change after #41251
Author: hoshibara
Pull request: no
Labels: name: bug

### System Info

`transformers env` throw an error. I catch the system info with pytorch tools.
```
PyTorch version: 2.14.0.dev20260623+xpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 26.04 LTS (x86_64)
GCC version: (Ubuntu 15.2.0-16ubuntu1) 15.2.0
Clang version: 21.1.8 (6ubuntu1)
CMake version: version 4.2.3
Libc version: glibc-2.43

Python version: 3.12.13 | packaged by conda-forge | (main, Mar  5 2026, 16:50:00) [GCC 14.3.0] (64-bit runtime)
Python platform: Linux-7.0.0-22-generic-x86_64-with-glibc2.43
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
Is XPU available: True
XPU used to build PyTorch: 20260000
Intel GPU driver version:
* level-zero:   1.24.2
* libze1:       1.28.2-2
* intel-opencl-icd:     26.14.37833.4-1~25.10~ppa1
Intel GPU models onboard:
N/A
Intel GPU models detected:
* [0] _XpuDeviceProperties(name='Intel(R) Arc(TM) B580 Graphics', platform_name='Intel(R) oneAPI Unified Runtime over Level-Zero V2', type='gpu', device_id=0xE20B, uuid=86800be2-0000-0000-0400-000000000000, driver_version='1.15.37833+4', total_memory=12216MB, local_mem_size=128KB, last_level_cache_size=18432KB, max_compute_units=160, memory_clock_rate=2850MHz, memory_bus_width=64-bit, gpu_eu_count=160, gpu_subslice_count=20, max_work_group_size=1024, max_num_sub_groups=64, sub_group_sizes=[16 32], has_fp16=1, has_fp64=1, has_atomic64=1, is_integrated_gpu=0)
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: False
Caching allocator config: N/A

CPU:
Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Address sizes:                           46 bits physical, 48 bits virtual
Byte Order:                              Little Endian
CPU(s):                                  20
On-line CPU(s) list:                     0-19
Vendor ID:                               GenuineIntel
Model name:                              Intel(R) Core(TM) Ultra 7 265K
CPU family:                              6
Model:                                   198
Thread(s) per core:                      1
Core(s) per socket:                      20
Socket(s):                               1
Stepping:                                2
CPU(s) scaling MHz:                      42%
CPU max MHz:                             5600.0000
CPU min MHz:                             800.0000
BogoMIPS:                                7756.80
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni lam wbnoinvd dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid bus_lock_detect movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                          VT-x
L1d cache:                               704 KiB (18 instances)
L1i cache:                               1.1 MiB (18 instances)
L2 cache:                                36 MiB (11 instances)
L3 cache:                                30 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-19
Vulnerability Gather data sampling:      Not affected
Vulnerability Ghostwrite:                Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS Not affected; BHI BHI_DIS_S
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace

Versions of relevant libraries:
[pip3] dpcpp-cpp-rt==2026.0.0
[pip3] impi-rt==2021.18.0
[pip3] intel-cmplr-lib-rt==2026.0.0
[pip3] intel-cmplr-lib-ur==2026.0.0
[pip3] intel-cmplr-lic-rt==2026.0.0
[pip3] intel-opencl-rt==2026.0.0
[pip3] intel-openmp==2026.0.0
[pip3] intel-pti==0.17.0
[pip3] intel-sycl-rt==2026.0.0
[pip3] mkl==2026.0.0
[pip3] numpy==2.5.0
[pip3] oneccl==2022.0.0
[pip3] oneccl-devel==2022.0.0
[pip3] onemkl-license==2026.0.0
[pip3] onemkl-sycl-blas==2026.0.0
[pip3] onemkl-sycl-dft==2026.0.0
[pip3] onemkl-sycl-lapack==2026.0.0
[pip3] onemkl-sycl-rng==2026.0.0
[pip3] onemkl-sycl-sparse==2026.0.0
[pip3] tbb==2023.0.0
[pip3] tcmlib==1.5.0
[pip3] torch==2.14.0.dev20260623+xpu
[pip3] torchao==0.18.0.dev20260625+xpu
[pip3] torchaudio==2.11.0.dev20260624+xpu
[pip3] torchvision==0.29.0.dev20260624+xpu
[pip3] triton-xpu==3.7.2+git5fcc14d9
[pip3] umf==1.1.0
[conda] dpcpp-cpp-rt               2026.0.0                pypi_0                pypi
[conda] impi-rt                    2021.18.0               pypi_0                pypi
[conda] intel-cmplr-lib-rt         2026.0.0                pypi_0                pypi
[conda] intel-cmplr-lib-ur         2026.0.0                pypi_0                pypi
[conda] intel-cmplr-lic-rt         2026.0.0                pypi_0                pypi
[conda] intel-opencl-rt            2026.0.0                pypi_0                pypi
[conda] intel-openmp               2026.0.0                pypi_0                pypi
[conda] intel-pti                  0.17.0                  pypi_0                pypi
[conda] intel-sycl-rt              2026.0.0                pypi_0                pypi
[conda] mkl                        2026.0.0                pypi_0                pypi
[conda] numpy                      2.5.0                   pypi_0                pypi
[conda] oneccl                     2022.0.0                pypi_0                pypi
[conda] oneccl-devel               2022.0.0                pypi_0                pypi
[conda] onemkl-license             2026.0.0                pypi_0                pypi
[conda] onemkl-sycl-blas           2026.0.0                pypi_0                pypi
[conda] onemkl-sycl-dft            2026.0.0                pypi_0                pypi
[conda] onemkl-sycl-lapack         2026.0.0                pypi_0                pypi
[conda] onemkl-sycl-rng            2026.0.0                pypi_0                pypi
[conda] onemkl-sycl-sparse         2026.0.0                pypi_0                pypi
[conda] tbb                        2023.0.0                pypi_0                pypi
[conda] tcmlib                     1.5.0                   pypi_0                pypi
[conda] torch                      2.14.0.dev20260623+xpu  pypi_0                pypi
[conda] torchao                    0.18.0.dev20260625+xpu  pypi_0                pypi
[conda] torchaudio                 2.11.0.dev20260624+xpu  pypi_0                pypi
[conda] torchvision                0.29.0.dev20260624+xpu  pypi_0                pypi
[conda] triton-xpu                 3.7.2+git5fcc14d9       pypi_0                pypi
[conda] umf                        1.1.0                   pypi_0                pypi
```

### Who can help?

@vasqu @ArthurZucker @CyrilVallez

### Information

- [ ] The official example scripts
- [x] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [x] My own task or dataset (give details below)

### Reproduction

PR #41251 introduced early returns in `create_masks_for_generate` that change the return type from dict to a bare value when `effective_config.layer_types` has a single pattern or contains unknown types. This silently breaks model forward methods that rely on `isinstance(attention_mask, dict)` to detect whether the mask was already prepared by generate().

Before #41251

When effective_config.layer_types was present, create_masks_for_generate always returned a dict mapping layer type names to masks:

```python
# Line ~1530 before PR#41251
if hasattr(effective_config, "layer_types"):
    causal_masks = {}
    for layer_pattern in set(effective_config.layer_types):
        causal_masks[layer_pattern] = LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING[layer_pattern](**mask_kwargs)
    return causal_masks  # Always a dict
```

After #41251

The PR added two early-return paths that skip the dict wrapper:

```python
if any(layer_type not in LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING for layer_type in layer_patterns):
    return attention_mask  # Bare value — could be None, 2D tensor, etc.

if len(layer_patterns) == 1:
    return LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING[next(iter(layer_patterns))](**mask_kwargs)  # Bare value
```

Concrete impact: Qwen3

`Qwen3Model.forward` checks whether the mask was already prepared using isinstance:

```python
# src/transformers/models/qwen3/modeling_qwen3.py line ~404
if not isinstance(causal_mask_mapping := attention_mask, dict):
    # Mask not yet prepared — call create_causal_mask again
    causal_mask_mapping = {"full_attention": create_causal_mask(**mask_kwargs)}
```

Before PR#41251, `create_masks_for_generate` returned a dict like `{"full_attention": None}`. Qwen3Model.forward's isinstance(attention_mask, dict) check passed, and the model used the pre-computed mask (None) directly with is_causal=True.

After PR#41251, with the early return `if len(layer_patterns) == 1: return ...`, the function returns bare None instead of a dict. Qwen3Model.forward enters the non-dict branch, and calls `create_causal_mask(attention_mask=None)` a second time. In this second call, `attention_mask=None produces padding_mask=None`, which causes `_can_skip_causal_mask_xpu` to fall back to a conservative path that cannot determine the mask is purely causal, so it falls through to building a full 4D mask with `is_causal=False`. It cause a significant performance regression.


Script: 
[repro_contract.py](https://github.com/user-attachments/files/29470254/repro_contract.py)


### Expected behavior

Revert early return path or fix Qwen mask script.

Comments:
cc @arthurzucker since it's your PR!

@kaixuanliu 

Hey, thanks for the issue @hoshibara! Indeed, since xpu may return None for the mask during prefill, this is a new issue. However, all other models without `layer_types`, i.e. for which the mask is always a single Tensor or None, have this issue since a very long time... I'm investigating the best fix to detect such cases! 
I don't have xpu device available, but is the difference in speed so big for the prefill?

I'm very surprised here in general, as skipping the mask for the prefill will necessarily lead to recompilation on the first decode token, which in my experience would lead to worst perfs than having a full mask on the prefill as well.
Also, how is it even possible that the prefill is correct without a mask, given that for StaticCache, the k/v that will be returned are longer than the query tokens, meaning the attention outputs computed will NOT be equivalent (due to the softmax). Do you somehow rescale the output of QK^T to remove the effect of padding? @sywangyi @kaixuanliu 

> Hey, thanks for the issue [@hoshibara](https://github.com/hoshibara)! Indeed, since xpu may return None for the mask during prefill, this is a new issue. However, all other models without `layer_types`, i.e. for which the mask is always a single Tensor or None, have this issue since a very long time... I'm investigating the best fix to detect such cases! I don't have xpu device available, but is the difference in speed so big for the prefill?

In our tests, a tensor mask will take 30% performance regression in end-to-end prefill latency during `model.generate`.

Hi @Cyrilvallez , I summarize several points:

1. No matter on XPU or on CUDA with StaticCache, prefill and decode are normally compiled as two separate graphs. StaticCache makes the KV cache storage shape stable, but the prefill step still has query length > 1 while decode has query length = 1, and the attention-mask path may also differ. Therefore, if prefill skips the mask and decode uses a 4D mask, this does not stay in a single compiled graph; decode gets its own graph/compilation, so the recompilation is inevitable. 
2. With the default dynamic cache, transformers are expected to pass attention_mask=None in the common no-padding cases and rely on PyTorch SDPA’s is_causal=True. This lets XPU dispatch to the optimized/flash attention path. The update in https://github.com/huggingface/transformers/pull/41251 violated this expectation and lead to XPU dispatch attention to another path , which caused the performance regression
3. For prefill where q_len == kv_len, no matter dynamic cache or static cache, it follows point 2 as well
4. When using StaticCache, decode stage will correctly create a bool mask of shape (batch, 1, 1, max_cache_len), which will guarantee the correctness.
Hope this can answer your doubts. And I will submit a PR to fix the issue.


Hey! Yes sorry, we actually never compile the prefill so we don't have the problem of recompilation lol, I forgot for a second. 
However, the change here is only reflected for StaticCache anyway, not DynamicCache, as otherwise the mask is never prepared in advance by `generate`, so it would never have been a dict before and now not anymore. 

For StaticCache, during prefill we never have q_len == kv_len, because the k/v are padded to the max_len. Which is why I asked about the maths, because then the softmax will make the results different. However, with `is_causal=True`, it actually works because the padding is not reflected anymore, so a None mask is indeed correct. It will however work only and only if the Cache is fully empty, and will mathematically silently fail if the prefill is used with a non-empty Cache, as would be the case for example with some prefix caching or something (you call `generate` with an existing non-empty Cache and some new prefill tokens). This is because `is_causal` uses upper-left matrix, and not lower right by default. So this fast path is a bit brittle and should be restrained anyway

Ah yes, sorry my phrasing was not precise enough, what I meant with `q_len == kv_len` here was that the effective valid token range is the prompt length during prefill stage. So the issue here is mainly the contract change for Qwen3's prepared mask path: with StaticCache, `generate()` used to pass a dict like `{"full_attention": None}`. After the early return, it passes bare `None`, so `Qwen3Model.forward` treats the mask as not precomputed and calls `create_causal_mask()` again. That second call may materialize a full 4D mask, which preserves correctness but causes the XPU performance regression.

Fixed.
Thanks for you PR!!