[Bug] [Relax] nll_loss_backward skips negative ignore_index causing OOB read, wrong gradients, and SIGSEGV

オープン
#21,068 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 3 日以内に返信

@pierceluu10 がすでに取り組んでいます。

2026年11月29日 から。

  • #21087 @pierceluu10 による — オープン

評価

難易度
3/5
見積もり時間
1〜2日
初心者へのやさしさ
68/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python

調査の方向性

Start in python/tvm/relax/transform/legalize_ops/grad.py at _grad_nll_loss_backward and trace how all_weights is built and used in the mean reduction. Check the NLL loss backward tests and add coverage for negative and out-of-range ignore_index values. Done means ignored targets never cause an out-of-bounds weight read and contribute zero to the weight sum and prediction gradient.

索引モデルが issue の本文から書いたものです。

説明

needs-triage type: bug
Expected behavior

R.nn.nll_loss and R.grad.nll_loss_backward both document ignore_index: int = -100 as the default value (matching PyTorch). Any target entry equal to ignore_index (whether negative such as -100 or out-of-range non-negative such as 255) must be masked out before indexing weights, contributing 0 to weight_sum and 0 to pred_grad.

For lp of shape (2, 4), w = [1.0, 2.0, 3.0, 4.0], tgt = [1, -100], reduction="mean", ignore_index=-100, only sample 0 is active: L = (-lp[0, 1] * w[1]) / w[1] = -lp[0, 1], so dL/dlp[0, 1] must be -1.0.

Actual behavior

In python/tvm/relax/transform/legalize_ops/grad.py (_grad_nll_loss_backward, lines 56–63):

if ignore_index >= 0:
    weights = te.compute(
        weights.shape,
        lambda i: tirx.Select(i == ignore_index, tirx.const(0, weights.dtype), weights(i)),
        "weights_new",
    )

all_weights = te.compute(targets.shape, lambda *i: weights(targets(*i)), "all_weights")

Because of if ignore_index >= 0:, all negative ignore_index values (including the default -100) are completely skipped, and all_weights unconditionally emits an unguarded out-of-bounds memory load w[tgt[v_i0]] (e.g., w[-100]):

for i0 in range(T.int64(4)):
    with T.sblock("all_weights"):
        v_i0 = T.axis.spatial(T.int64(4), i0)
        all_weights[v_i0] = w[tgt[v_i0]]   # OOB heap read at w[-100]!

(Even for non-negative ignore_index >= num_classes, e.g., ignore_index=255 on a 4-class tensor, weights(targets(*i)) still reads out of bounds!)

Consequences:

  1. Silent wrong gradient: Reading garbage/adjacent memory at w[-100] corrupts weight_sum (all_weights_red) in reduction="mean". When memory at w[-100] holds 500.0, dL/dlp[0, 1] becomes -2.0 / (2.0 + 500.0) = -0.00398406 instead of -1.000000.
  2. Heap out-of-bounds SIGSEGV: With ignore_index=-10000000 and tgt=[0, -10000000], the process immediately crashes with SIGSEGV (exit code -11).
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

@I.ir_module
class Module:
    @R.function
    def main(
        lp: R.Tensor((2, 4), "float64"),
        w: R.Tensor((4,), "float64"),
        tgt: R.Tensor((2,), "int64"),
    ) -> R.Tensor((), "float64"):
        with R.dataflow():
            s = R.nn.nll_loss(lp, tgt, w, reduction="mean", ignore_index=-100)
            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)

lp = np.array([[-1.0, -2.0, -3.0, -4.0], [-0.5, -1.5, -2.5, -3.5]], dtype="float64")
# Construct a 64-byte aligned zero-copy slice whose [-100] element is deterministically 500.0
big = np.full((300,), 500.0, dtype="float64")
offset = 128
while (big.ctypes.data + offset * 8) % 64 != 0:
    offset += 1
big[offset : offset + 4] = np.array([1.0, 2.0, 3.0, 4.0], dtype="float64")
w_tvm = tvm.runtime.from_dlpack(big[offset : offset + 4])
tgt = np.array([1, -100], dtype="int64")

_, (grad_lp, _, _) = vm["main_adjoint"](tvm.runtime.tensor(lp, dev), w_tvm, tvm.runtime.tensor(tgt, dev))
print("Expected dL/dlp[0, 1]              : -1.000000")
print("Actual TVM nll_loss_backward [0, 1]:", float(grad_lp.numpy()[0, 1]))
print("OOB formula -2.0 / (2.0 + 500.0)   :", -2.0 / 502.0)

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

Expected dL/dlp[0, 1]              : -1.000000
Actual TVM nll_loss_backward [0, 1]: -0.00398406374501992
OOB formula -2.0 / (2.0 + 500.0)   : -0.00398406374501992

Replacing ignore_index=-100 / tgt=[1, -100] with ignore_index=-10000000 / tgt=[0, -10000000] triggers an immediate SIGSEGV (exit code -11).

Suggested Fix

In te_nll_loss_backward, guard the all_weights load directly with tirx.if_then_else(targets(*i) == ignore_index, tirx.const(0, weights.dtype), weights(targets(*i))) (avoiding eager OOB memory evaluation on ignored indices regardless of whether ignore_index is negative or >= num_classes).

Triage
  • needs-triage
  • relax
主要言語
Python
スター
13.9k
フォーク
4.1k
平均マージ
4日 22時間
マージ済み PR(30日)
22

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

apache/tvm のほかの issue

apache/tvm の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。