[Bug] [Relax] nll_loss_backward skips negative ignore_index causing OOB read, wrong gradients, and SIGSEGV
メンテナーはふだん 3 日以内に返信
評価
- 難易度
- 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 の本文から書いたものです。
説明
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:
- Silent wrong gradient: Reading garbage/adjacent memory at
w[-100]corruptsweight_sum(all_weights_red) inreduction="mean". When memory atw[-100]holds500.0,dL/dlp[0, 1]becomes-2.0 / (2.0 + 500.0) = -0.00398406instead of-1.000000. - Heap out-of-bounds
SIGSEGV: Withignore_index=-10000000andtgt=[0, -10000000], the process immediately crashes withSIGSEGV(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 inlegalize_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 を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
apache/tvm のほかの issue
-
[Bug] [Relax] `relax.op.unique(return_inverse=True)` returns an input-shaped inverse for N-D input when `axis` is None対応中かも このイシューにリンクされたプルリクエストがオープン中、またはマージ済みです。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 3 日以内に返信
-
[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensorsオープンneeds-triage type: bug
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
メンテナーはふだん 3 日以内に返信
-
[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradients対応中かも @pierceluu10 が 4 日前に担当しました。 オープンneeds-triage type: bug
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 3 日以内に返信
-
[Bug][Relax][ONNX] NonZero returns the wrong output shape for scalar inputs対応中かも @tandede が 9 日前に担当しました。 オープンneeds-triage type: bug
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
メンテナーはふだん 3 日以内に返信
-
needs-triage type: bug
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
メンテナーはふだん 3 日以内に返信
似ている issue
-
難易度 1/5 1〜3時間 初心者へのやさしさ 78/100
web-push-libs/pywebpush#216 · コメント 1 件 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
AgriciDaniel/claude-seo#572 ·
メンテナーはふだん 5 日以内に返信
-
area:print-dispatch
難易度 2/5 1〜3時間 初心者へのやさしさ 92/100
メンテナーはふだん 1 日以内に返信
-
area: docs domain: technical-writing good first issue type: documentation
難易度 2/5 1〜3時間 初心者へのやさしさ 80/100
Deepak3699/Ai_Mentor#919 ·
メンテナーはふだん 2 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信