Closed
[Bug-Report]: Tensor类缺少反向运算符实现(__rmul__, __rsub__, __rtruediv__) #617
wangzheng97Add on  Mar 9Closed at  Mar 13
wangzheng97
wangzheng97Collaborators
Mar 9 Create

问题描述 / Describe the current behavior

PyPTO的Tensor类缺少反向运算符(__rmul__, __rsub__, __rtruediv__)的实现,导致当标量(float/int)在左侧时,会抛出TypeError。

具体表现:

  • 2.0 * tensor → TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'
  • 1.0 - tensor → TypeError: unsupported operand type(s) for -: 'float' and 'Tensor'
  • 2.0 / tensor → TypeError: unsupported operand type(s) for /: 'float' and 'Tensor'

源码位置:python/pypto/tensor.py

  • 第252行:实现了 __mul__(支持 tensor * scalar)
  • 第236行:实现了 __radd__(支持 scalar + tensor)
  • 缺少:__rmul__, __rsub__, __rtruediv__ 的实现

对比:

  • 加法运算符完整:tensor + scalar ✅ 和 scalar + tensor ✅ 都支持
  • 乘法/减法/除法运算符不完整:只支持 tensor * scalar ✅,不支持 scalar * tensor ❌

环境信息 / Environment

  • 硬件:Ascend 910B(A3服务器)
  • CANN版本:8.5.0
  • PyPTO版本:当前master分支
  • Python版本:3.8+
  • 操作系统:Linux (Ubuntu 22.04)

重现步骤 / Steps to reproduce

import pypto

# 创建测试tensor
x = pypto.tensor((4,), pypto.DT_FP32)

# 测试1:tensor * scalar(成功)
print("测试1: tensor * scalar")
try:
    result = x * 2.0
    print("✅ x * 2.0 成功")
except Exception as e:
    print(f"❌ 失败: {e}")

# 测试2:scalar * tensor(失败)
print("\n测试2: scalar * tensor")
try:
    result = 2.0 * x
    print("✅ 2.0 * x 成功")
except TypeError as e:
    print(f"❌ 2.0 * x 失败: {e}")

# 测试3:tensor + scalar(成功)
print("\n测试3: tensor + scalar")
try:
    result = x + 1.0
    print("✅ x + 1.0 成功")
except Exception as e:
    print(f"❌ 失败: {e}")

# 测试4:scalar + tensor(成功,因为实现了__radd__)
print("\n测试4: scalar + tensor")
try:
    result = 1.0 + x
    print("✅ 1.0 + x 成功")
except Exception as e:
    print(f"❌ 失败: {e}")

运行结果:

测试1: tensor * scalar
✅ x * 2.0 成功

测试2: scalar * tensor
❌ 2.0 * x 失败: TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'

测试3: tensor + scalar
✅ x + 1.0 成功

测试4: scalar + tensor
✅ 1.0 + x 成功

预期结果 / Expected behavior

预期行为:

  • scalar * tensor 应该等价于 tensor * scalar
  • scalar - tensor 应该支持(返回 scalar + (-tensor))
  • scalar / tensor 应该支持

建议实现(参考 __radd__ 的实现方式):

# python/pypto/tensor.py

def __rmul__(self, other):
    """支持 scalar * tensor"""
    return self.mul(other)

def __rsub__(self, other):
    """支持 scalar - tensor"""
    # scalar - tensor = scalar + (-tensor)
    return pypto.add(other, pypto.neg(self))

def __rtruediv__(self, other):
    """支持 scalar / tensor"""
    return pypto.div(other, self)

日志/截图 / Log/Screenshot

错误堆栈

Traceback (most recent call last):
  File "test_operator_order.py", line XX, in <module>
    result = 2.0 * x
TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'

Python运算符查找机制说明

当执行 a * b 时,Python的查找顺序:

  1. 首先尝试 a.__mul__(b)
  2. 如果返回 NotImplemented,尝试 b.__rmul__(a)
  3. 如果都失败,抛出 TypeError

当前情况:

  • 2.0 * tensor:

    1. float.__mul__(2.0, tensor) → NotImplemented
    2. tensor.__rmul__(2.0) → 未实现 → TypeError
  • tensor * 2.0:

    1. tensor.__mul__(2.0) → 已实现 → 成功

备注 / Special notes

影响范围

  1. 用户体验:

    • 与NumPy/PyTorch的使用习惯不一致
    • 代码可读性降低(必须使用 tensor * scalar 而非自然的 scalar * tensor)
  2. 实际案例:

    • 在Derf算子开发中,多次遇到此问题
    • 必须统一使用 tensor * scalar 形式
    • 如果不注意运算符顺序,会导致难以理解的TypeError
  3. 一致性:

    • 加法已完整实现 __add__ 和 __radd__
    • 乘法/减法/除法应该保持一致

相关文档

  • 测试文件:test_operator_order.py(已构造完整测试用例)
  • 示例代码:examples/02_intermediate/operators/activation/activation.py L184 有相关注释
    # NOTE: '1.702 * x' leads to TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'
    

优先级建议

中等优先级

  • 不影响核心功能(用户可以通过调整运算符顺序解决)
  • 但影响用户体验和代码可读性
  • 建议在下个版本中实现

补充说明

如果这是设计决策而非bug,建议:

  1. 在官方文档中明确说明运算符使用规范
  2. 在API文档中标注限制
  3. 提供更友好的错误提示(而非直接TypeError)
likedislike
杨旭
杨旭Collaborators
Mar 10 Comments:

感谢反馈,我来看一下

likedislike
杨旭杨旭Collaborators
Mar 10 Assign wangzheng97 as responsible person
15 event messages are collapsed here。 See more
杨旭杨旭Collaborators
Mar 13 Associated milestone: 0.2.0.rc3
LiuChang
LiuChangCollaborators
Mar 13 Comments:

开发者你好,感谢提出的宝贵建议。
当前已合入相关改动

likedislike
LiuChangLiuChangCollaborators
Mar 13 changed custom state from 待办的 to 已完成
LiuChangLiuChangCollaborators
Mar 13 Close issue
杨旭杨旭Collaborators
Mar 19 Associated milestone: 0.2.0
CANN-robotCANN-robotCollaborators
Mar 20 Added label: resolved
KaranocaVeKaranocaVe
Sep 28 Associated pull request