Closed
[Inductor][DVM] FlexAttention 组合 mask 在 bitwise_and lowering 阶段编译失败 #5293
hbhu_binAdd on Oct 8Closed at 8 days ago
Oct 8 Added label: bot-triaged
TorchNPU-Bot
Oct 8 Comments:
Oct 8 Comments:
检测到当前 issue 已关联 PR,自动添加标签:bot-triaged


10 days ago Added label: module: graph-mode
chenrayray
8 days ago Comments:
8 days ago Comments:
这条开发自提 issue 提出已超过一个月,先关闭。如仍需跟进,请重新打开。


8 days ago Close issue
8 days ago changed custom state from TODO to DONE
8 days ago Added label: resolved
问题描述
在 torch_npu master 的 DVM 后端下,使用
flex_attention,并通过and_masks组合 causal mask 和读取外部positions张量的 document mask 时,torch.compile(backend="inductor")编译失败。首先在 mask 子图的
aten.bitwise_and.Tensorlowering 处报错。单独处理该错误后,外部张量索引aten.index.Tensor还会进入不适用于模板子图的 fallback 路径。环境
TORCHINDUCTOR_NPU_BACKEND=dvm,Ascend NPU。2.13.0+cpu。2.13.0+gitd151d4b、triton-ascend3.2.0、CANN9.2.0。最小复现
import os os.environ["TORCHINDUCTOR_NPU_BACKEND"] = "dvm" os.environ["TORCH_COMPILE_DEBUG"] = "1" os.environ["TORCHINDUCTOR_FORCE_DISABLE_CACHES"] = "1" import torch import torch_npu from torch.nn.attention.flex_attention import ( flex_attention, create_block_mask, and_masks, ) def causal_mask(b, h, q_idx, kv_idx): return q_idx >= kv_idx def document_mask(positions): def mask(b, h, q_idx, kv_idx): return positions[b, q_idx] == positions[b, kv_idx] return mask B, H, S, D = 2, 4, 128, 64 q, k, v = [ torch.randn(B, H, S, D, device="npu:0", dtype=torch.float16) for _ in range(3) ] positions = torch.tensor( [[0, 0, 0, 0, 1, 1, 1, 1] * 16] * B, device="npu:0", dtype=torch.int32, ) combined_mask = and_masks(causal_mask, document_mask(positions)) block_mask = create_block_mask( combined_mask, B=B, H=H, Q_LEN=S, KV_LEN=S, device="npu:0" ) @torch.compile(backend="inductor") def forward(q, k, v, block_mask): return flex_attention(q, k, v, block_mask=block_mask) out = forward(q, k, v, block_mask) torch.npu.synchronize() print(out.shape)实际结果
编译 mask 子图失败,错误关键内容如下(省略对象地址):
and_masks内部的result & mask(...)触发该操作。错误发生在编译阶段。预期结果
成功编译并执行,输出形状为
torch.Size([2, 4, 128, 64]),前向结果及反向梯度与等价的稠密 attention 参考实现一致。根因与修复范围
FlexAttention 的
mask_mod/score_mod子图最终内联到 Triton 模板,只需要 pointwise IR。DVM 普通图的make_pointwise还会提取 traced graph,并通过fn_to_aten_fn[fn]查询 ATen 映射;FlexAttention 额外 lowering 直接传入的ops.bitwise_and未登记在这张表中,因此查表失败。索引产生的 pointwise 中间值及类型提升同样不能按普通 DVM traced graph 处理。此外,读取捕获张量
positions[b, q_idx]时,DVM 的全局索引 fallback 会尝试创建外部算子 buffer,而PointwiseSubgraphLowering不允许这种 buffer。修复方向:
PointwiseSubgraphLowering时,直接构造 pointwise IR,跳过普通 DVM traced-graph 提取和映射查询。aten.index.Tensor使用上游间接读取 lowering,避免外部 fallback。验证
and_masks、or_masks、取反及 remainder score modification 的前向和反向精度回归。torch.compile(options={"npu_backend": "dvm"})切换到 DVM 时的覆盖启用行为。本 issue 用于关联上述 DVM FlexAttention 修复 PR。