You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生成PyTorch Sparse COO张量时出现值异常问题求助

稀疏张量coalesce后值异常的原因与解决方法

问题重现

尝试用以下代码创建稀疏张量(注:原代码存在语法错误,缺少闭合括号):

new_vertices_sparse = torch.sparse_coo_tensor(
    (new_vertices, torch.ones(len(new_vertices), dtype=int)), 
    size=(15,15,15)
)

打印张量时,values均为1,符合预期:

tensor(indices=tensor([[10, 10, 10,  ..., 12, 12, 11],
                       [ 5,  4,  3,  ...,  3,  2,  2],
                       [ 4,  5,  4,  ...,  6,  7,  8]]),
       values=tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                      ...
                      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
       size=(15, 15, 15), nnz=548, layout=torch.sparse_coo)

但调用print(new_vertices_sparse.coalesce().values())后,得到的values出现3、2、4等异常数值:

tensor([3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 4, 3, 2, 4, 4, 2, 3, 4, 2, 3, 3, 2, 3, 2,
        2, 3, 2, 3, 3, 3, 3, 2, 2, 4, 3, 2, 2, 3, 2, 4, 3, 2, 2, 3, 4, 2, 3, 2,
        ...
        3, 3])

原因分析

问题出在coalesce()方法的核心逻辑:该方法会自动合并重复的索引,并将相同索引位置的values进行累加。你的稀疏张量中存在大量重复的坐标索引(即多个相同的(维度1,维度2,维度3)组合),每个重复索引对应的value都是1,coalesce后这些1被相加,就得到了3、2、4等数值(比如某个索引重复3次,累加后就是3)。

解决方法

情况1:不需要重复索引,确保每个坐标唯一

先对new_vertices进行去重处理,保留唯一的索引组合,再创建稀疏张量:

# 对索引去重,dim=1表示按列去重(假设new_vertices是形状为(3, N)的张量)
unique_indices, _ = torch.unique(new_vertices, dim=1)
# 创建只包含唯一索引的稀疏张量,values全为1
new_vertices_sparse = torch.sparse_coo_tensor(
    unique_indices,
    torch.ones(unique_indices.shape[1], dtype=int),
    size=(15,15,15)
)
# 此时调用coalesce(),values仍保持为1
print(new_vertices_sparse.coalesce().values())

情况2:需要保留重复索引,但不想coalesce时累加

  • 若仅需查看原始values,直接调用new_vertices_sparse.values()即可,无需调用coalesce();
  • 若需要合并重复索引但自定义合并规则(比如取第一个值、最大值),可以手动处理:
    # 获取索引和原始values
    indices = new_vertices_sparse.indices()
    values = new_vertices_sparse.values()
    # 获取唯一索引及其对应的位置
    unique_indices, inverse_indices = torch.unique(indices, dim=1, return_inverse=True)
    # 按自定义规则合并,比如取第一个值
    merged_values = torch.zeros_like(unique_indices[0])
    for i in range(unique_indices.shape[1]):
        merged_values[i] = values[inverse_indices == i][0]
    # 创建合并后的稀疏张量
    coalesced_tensor = torch.sparse_coo_tensor(unique_indices, merged_values, size=(15,15,15))
    

内容的提问来源于stack exchange,提问作者Kat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:29:58