Closed
[Bug-Report|缺陷反馈]: 【green light】elementwise_ops.py的add::test_add_basic样例跑动态模式报错 #463
renshuojianAdd on  Feb 12Closed at  Mar 3
renshuojian
renshuojian
Feb 12 Create

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

Describe the current behavior / 问题描述 (Mandatory / 必填)

elementwise_ops.py的add::test_add_basic样例跑动态模式报错

Environment / 环境信息 (Mandatory / 必填)

昇腾950

Steps to reproduce the issue / 重现步骤 (Mandatory / 必填)

python3 pypto_test.py add::test_add_basic

`
def create_add_op_kernel(a_shape: tuple, b_shape: tuple, run_mode: str = "npu", dynamic: bool = True):
if dynamic:
a_shape = pypto.frontend.dynamic("a_shape")
b_shape = pypto.frontend.dynamic("b_shape")
else:
a_shape = a_shape
b_shape = b_shape

if run_mode == "npu":
    mode = pypto.RunMode.NPU
elif run_mode == "sim":
    mode = pypto.RunMode.SIM
else:
    raise ValueError(f"Invalid run_mode: {run_mode}. Must be 'npu' or 'sim'")

@pypto.frontend.jit(runtime_options={"run_mode": mode})
def add_kernel(
    a: pypto.Tensor(a_shape, pypto.DT_FP32),
    b: pypto.Tensor(b_shape, pypto.DT_FP32),
) -> pypto.Tensor(a_shape, pypto.DT_FP32):
    pypto.set_vec_tile_shapes(2, 8)
    out = pypto.add(a, b)
    return out

return add_kernel

def test_add_basic(device_id: int = None, run_mode: str = "npu"):
"""Test basic usage of add function"""
print("=" * 60)
print("Test: Basic Usage of add Function")
print("=" * 60)

device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu'

dtype = torch.float32
a = torch.tensor([1, 2, 3], dtype=dtype, device=device)
b = torch.tensor([4, 5, 6], dtype=dtype, device=device)
expected = torch.tensor([5, 7, 9], dtype=dtype, device=device)

out = create_add_op_kernel(a.shape, b.shape, run_mode)(a, b)
if run_mode == "npu":
    assert_allclose(out.cpu().numpy(), expected.cpu().numpy(), rtol=1e-3, atol=1e-3)
print(f"Output: {out}")
print(f"Expected: {expected}")
print("✓ Basic usage of add function completed successfully")

`

Describe the expected behavior / 预期结果 (Mandatory / 必填)

能跑通动态模式

Error: 'SymbolicScalar' object is not iterable
Traceback (most recent call last):
File "/home/workspace/pypto/examples/pypto_test.py", line 275, in
main()
File "/home/workspace/pypto/examples/pypto_test.py", line 262, in main
ex_info['function'](device_id, args.run_mode)
File "/home/workspace/pypto/examples/pypto_test.py", line 157, in test_add_basic
out = create_add_op_kernel(a.shape, b.shape, run_mode)(a, b)
File "/home/workspace/pypto/examples/pypto_test.py", line 135, in create_add_op_kernel
a: pypto.Tensor(a_shape, pypto.DT_FP32),
File "/home/workspace/pypto/python/pypto/tensor.py", line 31, in init
elif all([isinstance(s, int) for s in shape]):
TypeError: 'SymbolicScalar' object is not iterable
[ERROR] 2026-02-12-16:48:50 (PID:860850, Device:0, RankID:-1) ERR99999 UNKNOWN applicaiton exception

Special notes for this issue/备注 (Optional / 选填)

likedislike
renshuojianrenshuojian
Feb 12 Modify description of issue
renshuojianrenshuojian
Feb 12 Modify description of issue
lidongshenglidongshengCollaborators
Feb 12 Assign shengxinchen as responsible person
lidongsheng
lidongshengCollaborators
Feb 12 Comments:

shape需要是一个tuple或者list

a_shape = pypto.frontend.dynamic("a_shape")
b_shape = pypto.frontend.dynamic("b_shape")
likedislike
袁野袁野Collaborators
Feb 13 Added label: Frontend
袁野袁野Collaborators
Feb 13 changed custom category from 任务 to 缺陷
shengxinchenshengxinchenCollaborators
Feb 27 Associated pull request
shengxinchen
shengxinchenCollaborators
Feb 27 Comments:

根因分析

pypto.frontend.dynamic() 返回的是一个单独的 SymbolicScalar 标量,而不是一个可迭代的 shape tuple。而kernel函数签名中的shape需要是tuple或list类型,因此抛出TypeError: 'SymbolicScalar' object is not iterable。

解决方案

如下述代码段所示,将create_add_op_kernel函数替换后可成功运行elementwise_ops.py中add::test_add_basic样例的动态模式:

def create_add_op_kernel(a_shape: tuple, b_shape: tuple, run_mode: str = "npu", dynamic: bool = True):
    ndim = len(a_shape)
    tile_dim0 = a_shape[0]
    concrete_tail = list(a_shape[1:])

    if dynamic:
        a_dim0 = pypto.frontend.dynamic("a_dim0")
        b_dim0 = pypto.frontend.dynamic("b_dim0")
        a_shape = (a_dim0,) + tuple(a_shape[1:])
        b_shape = (b_dim0,) + tuple(b_shape[1:])

    if run_mode == "npu":
        mode = pypto.RunMode.NPU
    elif run_mode == "sim":
        mode = pypto.RunMode.SIM
    else:
        raise ValueError(f"Invalid run_mode: {run_mode}. Must be 'npu' or 'sim'")

    @pypto.frontend.jit(runtime_options={"run_mode": mode})
    def add_kernel(
        a: pypto.Tensor(a_shape, pypto.DT_FP32),
        b: pypto.Tensor(b_shape, pypto.DT_FP32),
    ) -> pypto.Tensor(a_shape, pypto.DT_FP32):
        pypto.set_vec_tile_shapes(2, 8)

        if not dynamic:
            output = pypto.add(a, b)
        else:
            dim0 = a.shape[0]
            loop_count = (dim0 + tile_dim0 - 1) // tile_dim0
            output = pypto.Tensor(a_shape, pypto.DT_FP32)

            for idx in pypto.loop(loop_count):
                offset = idx * tile_dim0
                offset_end = pypto.min(offset + tile_dim0, dim0)
                valid_dim0 = offset_end - offset

                if ndim == 1:
                    tile_s = [tile_dim0]
                    start = [offset]
                    valid = [valid_dim0]
                else:
                    tile_s = [tile_dim0] + concrete_tail
                    start = [offset] + [0] * (ndim - 1)
                    valid = [valid_dim0] + concrete_tail

                a_view = pypto.view(a, tile_s, start, valid_shape=valid)
                b_view = pypto.view(b, tile_s, start, valid_shape=valid)
                result = pypto.add(a_view, b_view)
                pypto.assemble(result, start, output)

        return output

return add_kernel

修复方案

由于elementwise_ops.py旨在展示pypto元素级别的操作示例,因此将其中涉及动态相关的代码分支移除,相关的动态特性用法示例补充在examples/02_intermediate/controflow/others/dynamic.py中,详见PR:https://gitcode.com/cann/pypto/pull/1220

likedislike
shengxinchenshengxinchenCollaborators
Mar 3 changed custom state from 待办的 to 已完成
shengxinchenshengxinchenCollaborators
Mar 3 Close issue
杨旭杨旭Collaborators
Mar 9 associated Kanban: PyPTO
CANN-robotCANN-robotCollaborators
Mar 20 Added label: resolved