已关闭
[Bug-Report|缺陷反馈]: CANN 9.1.0 版本 使用 flat_idx = sub_score_reshape.topk(total, dim=-1).indices 算子,在相同输入下,多次执行算子有时返回结果相同,有时不相同,请定位,详见问题描述,谢谢 #2641
LetsAiGo创建于  23 天前关闭于  18 天前
LetsAiGo
23 天前 创建

Thanks for sending an issue! Please fill in the following template to help quickly solve your problem.

一、问题描述 (必填)
CANN 9.1.0 版本 使用 flat_idx = sub_score_reshape.topk(total, dim=-1).indices 算子,在相同输入下,多次执行算子,有时返回结果相同,有时不相同

flat_idx = sub_score_reshape.topk(total, dim=-1).indices

代码片段:
image.png

相同输入下不同批次,有的相同,有的不同,如下所示:
image.png

image.png

二、环境信息 (可选)

昇腾硬件型号: Ascend950PR

CNN版本信息:
node-10-31-200-119(@😃:opp# cat version.info
Version=9.1.0
version_dir=cann
required_package_runtime_version=">=8.5"
required_package_ge-executor_version=">=8.5"
required_package_metadef_version=">=8.5"
required_package_asc-devkit_version=">=8.5"
required_package_bisheng-compiler_version=">=8.5"
timestamp=20260730_231653901

操作系统: x86_64

三、重现步骤 (可选)

多次运行相同的代码,

四、预期结果 (可选)

相同的输入情况下,多次运行返回的结果相同

💡 备注(选填)

定位信息参考:
运行如下代码测试发现:TopK算子正常返回最大值的,但是存在未被选中的数值中存在比选中的还大的值,

import torch
import torch_npu

def has_rank_violation(x_cpu, k, loops=200):
x = x_cpu.npu()
for _ in range(loops):
_, idx = x.topk(k, dim=-1)
torch.npu.synchronize()

    mask = torch.zeros_like(x, dtype=torch.bool)
    mask.scatter_(1, idx, True)

    selected_min = torch.where(mask, x, torch.full_like(x, float("inf"))).min(dim=-1).values
    unselected_max = torch.where(~mask, x, torch.full_like(x, float("-inf"))).max(dim=-1).values
    if bool((unselected_max > selected_min).any().item()):
        print(f"selected_max = {torch.max(selected_min)} selected_min = {torch.min(selected_min)} unselected_max = {torch.max(unselected_max)} unselected_min = {torch.min(unselected_max)}")
        return selected_min.cpu(), unselected_max.cpu()
return None

def test_npu_topk_large_quantized_duplicate_values_break_rank():
h, n, k = 2, 156025, 3160
x = torch.randint( 0, 256, (h, n),generator=torch.Generator().manual_seed(123), dtype=torch.int32,).to(torch.float32) / 256.0
assert has_rank_violation(x, k, loops=200) is not None

def test_npu_topk_large_unique_values_not_repro():
n, k = 156025, 3160
x = torch.stack([
torch.randperm(n, generator=torch.Generator().manual_seed(1)).to(torch.float32),
torch.randperm(n, generator=torch.Generator().manual_seed(2)).to(torch.float32),
]) / float(n)

assert has_rank_violation(x, k, loops=100) is None

正常优选选中大者,但是存在未被选中的数值中存在比选中的还大的值,如下图所示:
image.png

likedislike
陈思
陈思成员
22 天前 评论:

收到反馈,正在联系算子责任人,请稍等

likedislike
zhanghedong成员
22 天前 评论:

已知晓,修复中。

likedislike
陈思陈思成员
22 天前 将 zhanghedong 设为负责人
陈思陈思成员
18 天前 issue状态由 进行中 改变为 已完成
陈思陈思成员
18 天前 关闭了 issue
cy_hw
cy_hw成员
14 天前 评论:

您好,问题已解决合入主线,待后续商分版本上线后即可解决。

likedislike
cy_hwcy_hw成员
14 天前 删除了关联的pull request:解决TopkV2算子偶现的精度问题
CANN-robotCANN-robot成员
14 天前 添加了label:resolved