Closed
[Inductor][DVM] FlexAttention 组合 mask 在 bitwise_and lowering 阶段编译失败 #5293
hbhu_binAdd on  Oct 8Closed at  8 days ago
hbhu_bin
hbhu_binCollaborators
Oct 8 Create

问题描述

在 torch_npu master 的 DVM 后端下,使用 flex_attention,并通过 and_masks 组合 causal mask 和读取外部 positions 张量的 document mask 时,torch.compile(backend="inductor") 编译失败。

首先在 mask 子图的 aten.bitwise_and.Tensor lowering 处报错。单独处理该错误后,外部张量索引 aten.index.Tensor 还会进入不适用于模板子图的 fallback 路径。

环境

  • 后端:TORCHINDUCTOR_NPU_BACKEND=dvm,Ascend NPU。
  • 分支:torch_npu master 的 FlexAttention DVM 接入路径,修复前可复现。
  • 首次排查确认的 PyTorch 版本:2.13.0+cpu。
  • 补充环境信息(2026-10-08 查询的当前安装版本,非精确引入版本):torch_npu 2.13.0+gitd151d4b、triton-ascend 3.2.0、CANN 9.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 子图失败,错误关键内容如下(省略对象地址):

RuntimeError: <bound method bitwise_and of <torch._inductor.virtualized.OpsWrapper object ...>>

While executing %bitwise_and = call_function[
    target=torch.ops.aten.bitwise_and.Tensor
](args = (%full_default, %ge), kwargs = {})

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。

修复方向:

  1. 仅当当前已加载的后端为 DVM,且正在处理 PointwiseSubgraphLowering 时,直接构造 pointwise IR,跳过普通 DVM traced-graph 提取和映射查询。
  2. 仅在 DVM 的 FlexAttention 子图内,为 aten.index.Tensor 使用上游间接读取 lowering,避免外部 fallback。
  3. 保留默认 Triton、MLIR 后端原有的索引分派和构图流程;普通主图索引不受该局部覆盖影响。

验证

  • 原始组合 mask 用例已在 Ascend 上通过修复验证。
  • 已覆盖 and_masks、or_masks、取反及 remainder score modification 的前向和反向精度回归。
  • 将修复收敛为仅 DVM 生效后,重新验证了原组合 mask 的前向/反向精度,以及默认后端通过 torch.compile(options={"npu_backend": "dvm"}) 切换到 DVM 时的覆盖启用行为。
  • 默认后端不注册新增的 FlexAttention 索引覆盖。

本 issue 用于关联上述 DVM FlexAttention 修复 PR。

likedislike
TorchNPU-BotTorchNPU-BotCollaborators
Oct 8 Added label: bot-triaged
TorchNPU-Bot
TorchNPU-BotCollaborators
Oct 8 Comments:

检测到当前 issue 已关联 PR,自动添加标签:bot-triaged

likedislike
chenrayraychenrayrayCollaborators
10 days ago Added label: module: graph-mode
chenrayray
chenrayrayCollaborators
8 days ago Comments:

这条开发自提 issue 提出已超过一个月,先关闭。如仍需跟进,请重新打开。

likedislike
chenrayraychenrayrayCollaborators
8 days ago Close issue
chenrayraychenrayrayCollaborators
8 days ago changed custom state from TODO to DONE
ascend-robotascend-robotCollaborators
8 days ago Added label: resolved