[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradients

未关闭 适合新手
#21,069 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 3 天内回复

@pierceluu10 已经在做这个了。

开始于 2026年11月29日。

  • #21086 来自 @pierceluu10 —— 未关闭

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
78/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python

调研方向

从 python/tvm/relax/transform/legalize_ops/grad.py 中的 _grad_take_backward 开始,检查属性 axis 如何用于计算融合输出梯度的维度。使用提供的 (3, 4) 示例复现,然后比较 axis=-1 与 axis=1 时的梯度。当两个梯度都与预期数组匹配,并且负轴在计算这些维度之前完成规范化时,即为完成。

由索引模型根据 Issue 内容生成。

描述

needs-triage type: bug
Expected behavior

R.take(x, idx, axis=-1) is a valid Relax operation (axis=-1 selects along the last dimension, equivalent to axis=1 for a 2D tensor). relax.transform.Gradient + LegalizeOps should produce the exact same gradient as axis=1.

For x of shape (3, 4), idx = [1, 3], w = full((3, 2), 2.0), L = sum(R.take(x, idx, axis=-1) * w), the exact gradient dL/dx must be [[0, 2, 0, 2], [0, 2, 0, 2], [0, 2, 0, 2]].

Actual behavior

In python/tvm/relax/transform/legalize_ops/grad.py (_grad_take_backward, lines 160–205):

axis = call.attrs.axis
if axis is not None:
    axis = int(axis)   # <-- missing negative axis normalization: if axis < 0: axis += len(x.shape)
...
for i in range(len(output_grad_ptr.shape)):
    if i < axis:
        fused_output_grad_shape_pre *= output_grad_ptr.shape[i]
    elif i > axis:
        fused_output_grad_shape_nxt *= output_grad_ptr.shape[i]

When axis = -1 (or any negative axis):

  • i < -1 is always False (fused_output_grad_shape_pre = 1).
  • i > -1 is always True for every dimension (including the gathered axis itself!), inflating fused_output_grad_shape_nxt to the entire size of output_grad (3 * 2 = 6 instead of 1).
  • The accumulation loop then writes to out_idx = idx[loop_l] * 6 + j. For idx[1] = 3 and j = 5, out_idx = 23, which writes 11 float64 elements (88 bytes) past the end of the 12-element out_buf on the heap, silently corrupting dL/dx (and crashing with SIGSEGV on larger shapes such as (64, 512)).
Environment
  • TVM version: apache-tvm==0.27.0.post1
  • OS: Linux (x86_64)
  • Python: 3.12.x
  • Target: llvm (backend-independent — the bug is in legalize_ops/grad.py)
Steps to reproduce
import numpy as np
import tvm
from tvm import relax
from tvm.script import ir as I, relax as R

# 1. Silent wrong gradient + heap OOB write on (3, 4)
@I.ir_module
class Module:
    @R.function
    def main(
        x: R.Tensor((3, 4), "float64"),
        idx: R.Tensor((2,), "int64"),
        w: R.Tensor((3, 2), "float64"),
    ) -> R.Tensor((), "float64"):
        with R.dataflow():
            t = R.take(x, idx, axis=-1)
            s = R.sum(R.multiply(t, w))
            R.output(s)
        return s

dev = tvm.cpu(0)
gmod = relax.transform.Gradient("main")(Module)
lgmod = relax.transform.LegalizeOps()(gmod)
vm = relax.VirtualMachine(tvm.compile(lgmod, target="llvm"), dev)

x = np.arange(12, dtype="float64").reshape(3, 4)
idx = np.array([1, 3], dtype="int64")
w = np.ones((3, 2), dtype="float64") * 2.0
_, (grad_x, _, _) = vm["main_adjoint"](
    tvm.runtime.tensor(x, dev), tvm.runtime.tensor(idx, dev), tvm.runtime.tensor(w, dev)
)
print("Expected grad_x:\n", np.array([[0., 2., 0., 2.]] * 3))
print("Actual TVM grad_x (axis=-1):\n", grad_x.numpy())

Observed output on apache-tvm==0.27.0.post1:

Expected grad_x:
 [[0. 2. 0. 2.]
 [0. 2. 0. 2.]
 [0. 2. 0. 2.]]
Actual TVM grad_x (axis=-1):
 [[0. 0. 0. 0.]
 [0. 0. 2. 2.]
 [2. 2. 2. 2.]]

Changing the shape to x: (64, 512), idx = [0, 511], w: (64, 2) immediately triggers a heap buffer overflow SIGSEGV (exit code -11).

Suggested Fix

In _grad_take_backward, normalize negative axis against len(x_ptr.shape) before computing fused_output_grad_shape_pre and fused_output_grad_shape_nxt:

if axis is not None:
    axis = int(axis)
    if axis < 0:
        axis += len(x_ptr.shape)
Triage
  • needs-triage
  • relax
主要语言
Python
星标
13.9k
派生
4.1k
平均合并
4 天 22 小时
30 天内合并 PR
22

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

apache/tvm 的其他 Issue

查看 apache/tvm 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。