Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions paddle/phi/kernels/cpu/top_k_kernel.cc
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,13 @@ void TopkKernel(const Context& dev_ctx,
indices->Resize(out_dims);
}
if (x.numel() == 0) {
Full<T, Context>(dev_ctx, out->dims(), NAN, out);
Full<int64_t, Context>(dev_ctx, indices->dims(), 0, indices);
return;
// Reaching here with a non-empty output implies the topk axis has size 0,
// which cannot supply the requested k (>=1) elements. Align with the
// "selected index k out of range" semantics instead of returning NaN.
PADDLE_THROW(errors::InvalidArgument(
"topk cannot select k = %d elements from an axis of size 0 "
"(selected index k out of range).",
static_cast<int>(k)));
Comment on lines +172 to +178

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2

本 PR 将「空规约轴(x.numel()==0 且输出非空)」从静默返回全 NaN 改为抛出 InvalidArgument,属于用户可见的行为变化,但未新增覆盖该异常路径的测试。

现有 test/legacy_test/test_top_k_v2_op.py 中 [0, 20]、axis=1 的用例,其规约轴长度为 20(非空),空的是 batch 维,走的是更早的 out->numel()==0 合法空输出分支,并不能触发本次改动的分支。

建议在 test/legacy_test/test_top_k_v2_op.py(及/或 test_top_k_op.py)补充异常路径断言,例如 x = paddle.empty([1024, 0]); paddle.topk(x, 10, axis=-1) 应抛 InvalidArgument,以固化 CPU/GPU/XPU 三端一致的新行为并防止回归。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

新提交 018d129 已在 test/legacy_test/test_top_k_v2_op.py::TestTopKAPI.test_errors 补充异常路径断言:paddle.empty([1024, 0]) 取 k=10, axis=-1 断言抛 ValueError,并新增 [0, 5] 合法空输出返回 [0, 3] 的回归断言。与相邻 k=0/k=-1 用例一致,覆盖了本次行为变化。该问题已解决。

}
PADDLE_ENFORCE_GE(
x.numel(),
Expand Down
25 changes: 14 additions & 11 deletions paddle/phi/kernels/gpu/top_k_kernel.cu
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@ void TopkKernel(const Context& dev_ctx,
indices->Resize(out_dims);
}
if (x.numel() == 0) {
Full<T, Context>(dev_ctx, out->dims(), NAN, out);
Full<int64_t, Context>(dev_ctx, indices->dims(), 0, indices);
return;
// Reaching here with a non-empty output implies the topk axis has size 0,
// which cannot supply the requested k (>=1) elements. Align with the
// "selected index k out of range" semantics instead of returning NaN.
PADDLE_THROW(errors::InvalidArgument(
"topk cannot select k = %d elements from an axis of size 0 "
"(selected index k out of range).",
static_cast<int>(k)));
}
PADDLE_ENFORCE_GE(
x.numel(),
Expand Down Expand Up @@ -431,15 +435,14 @@ void TopkKernelCuda(const Context& dev_ctx,
indices->Resize(out_dims);
}

// Handle empty input
if (x.numel() == 0) {
phi::Full<T, Context>(
dev_ctx, phi::vectorize(out->dims()), static_cast<T>(NAN), out);
phi::Full<int64_t, Context>(dev_ctx,
phi::vectorize(indices->dims()),
static_cast<int64_t>(0),
indices);
return;
// Reaching here with a non-empty output implies the topk axis has size 0,
// which cannot supply the requested k (>=1) elements. Align with the
// "selected index k out of range" semantics instead of returning NaN.
PADDLE_THROW(errors::InvalidArgument(
"topk cannot select k = %d elements from an axis of size 0 "
"(selected index k out of range).",
static_cast<int>(k)));
}

// Now safe to allocate output memory
Expand Down
10 changes: 7 additions & 3 deletions paddle/phi/kernels/xpu/top_k_kernel.cc
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,13 @@ void TopkKernel(const Context& dev_ctx,
indices->Resize(out_dims_);
}
if (x.numel() == 0) {
Full<T, Context>(dev_ctx, out->dims(), NAN, out);
Full<int64_t, Context>(dev_ctx, indices->dims(), 0, indices);
return;
// Reaching here with a non-empty output implies the topk axis has size 0,
// which cannot supply the requested k (>=1) elements. Align with the
// "selected index k out of range" semantics instead of returning NaN.
PADDLE_THROW(errors::InvalidArgument(
"topk cannot select k = %d elements from an axis of size 0 "
"(selected index k out of range).",
static_cast<int>(k)));
}
PADDLE_ENFORCE_GE(
x.numel(),
Expand Down
26 changes: 26 additions & 0 deletions test/legacy_test/test_top_k_v2_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,32 @@ def test_errors(self):
with self.assertRaises(ValueError):
paddle.topk(x, k=0)

# Cover the empty-reduction-axis path on every compiled backend. The
# per-backend kernel branch is only reached when running on that
# backend's place, so force CPU (always available) plus GPU/XPU when
# compiled instead of relying on the default place.
places = [paddle.CPUPlace()]
if core.is_compiled_with_cuda():
places.append(paddle.CUDAPlace(0))
if core.is_compiled_with_xpu():
places.append(paddle.XPUPlace(0))
for place in places:
with paddle.base.dygraph.guard(place):
# An empty reduction axis (size 0) cannot supply the requested
# k (>=1) elements, so topk must raise instead of silently
# returning all-NaN (aligns with the forward "index k out of
# range" semantics).
empty_axis = paddle.empty([1024, 0], dtype="float32")
with self.assertRaisesRegex(ValueError, "axis of size 0"):
paddle.topk(empty_axis, k=10, axis=-1)

# A legit empty output (empty batch, non-empty reduction axis)
# still returns an empty tensor of the expected shape and must
# not be blocked by the check above.
empty_batch = paddle.empty([0, 5], dtype="float32")
values, _ = paddle.topk(empty_batch, k=3, axis=-1)
self.assertEqual(list(values.shape), [0, 3])


if __name__ == "__main__":
paddle.enable_static()
Expand Down
Loading