Closed
[Feature Request] 为 Tensor 类添加 Python 符号操作符支持(一元运算符及完整运算符重载) #631
wangzheng97Add on  Mar 11Closed at  Mar 13
wangzheng97
wangzheng97Collaborators
Mar 11 Create

功能描述

希望为 PyPTO 的 Tensor 类添加完整的 Python 符号操作符支持,重点包括:

  • 一元运算符:-(负号)、+(正号) - 本 Issue 重点
  • 反向二元运算符:__rmul__, __rsub__, __rtruediv__ - 详见关联 Issue #617
  • 其他运算符:__floordiv__, __mod__, __pow__
  • 比较运算符:__lt__, __le__, __ge__, __eq__, __ne__

使用场景

在开发 FastGELU 激活函数时,需要实现 tanh 函数:

# tanh(x) = (e^x - e^-x) / (e^x + e^-x)

当前必须使用的语法:

exp_pos = pypto.exp(tanh_input)
exp_neg = pypto.exp(pypto.neg(tanh_input))  # 必须使用 pypto.neg()
tanh_result = (exp_pos - exp_neg) / (exp_pos + exp_neg)

期望的自然语法:

exp_pos = pypto.exp(tanh_input)
exp_neg = pypto.exp(-tanh_input)  # 期望支持 - 操作符
tanh_result = (exp_pos - exp_neg) / (exp_pos + exp_neg)

期望的 API/用法

import pypto

x = pypto.tensor((128, 512), pypto.DT_FP32)

# 一元运算符(本 Issue 重点)
y1 = -x      # 等价于 pypto.neg(x)
y2 = +x      # 返回 x 自身

# 反向运算符(详见 #617)
scalar = 2.0
y3 = scalar * x   # 等价于 pypto.mul(scalar, x) - Issue #617
y4 = scalar - x   # 等价于 pypto.sub(scalar, x) - Issue #617
y5 = scalar / x   # 等价于 pypto.div(scalar, x) - Issue #617

# 其他运算符
y6 = x // 2       # 等价于 pypto.floor_div(x, 2)
y7 = x % 3        # 等价于 pypto.mod(x, 3)
y8 = x ** 2       # 等价于 pypto.pow(x, 2)

# 比较运算符
mask = x > 0.5    # 已支持
mask = x < 0.5    # 期望支持
mask = x == 0.5   # 期望支持

动机

1. 提升代码可读性

# 当前:冗长且不够直观
result = pypto.add(pypto.mul(x, 0.5), pypto.neg(y))

# 期望:简洁清晰
result = 0.5 * x - y

2. 降低学习成本

  • PyTorch 用户习惯使用符号操作符
  • 与 NumPy 语法保持一致
  • 减少记忆函数名的负担

3. API 一致性

  • SymbolicScalar 类已实现完整运算符支持(__neg__, __pos__, __eq__, __ne__, __lt__, __le__, __gt__, __ge__ 等)
  • Tensor 类目前只支持部分运算符(__add__, __sub__, __mul__, __truediv__, __gt__, __matmul__)
  • 两者的 API 不一致会让用户困惑

4. 实际开发中的问题
在开发 FastGELU 算子时,遇到了 TypeError: bad operand type for unary -: 'Tensor' 错误,必须改用 pypto.neg(),增加了代码复杂度。

参考实现

1. PyTorch

# torch.Tensor 完整支持所有运算符
class Tensor:
    def __neg__(self):
        return self.neg()
    
    def __pos__(self):
        return self
    
    def __add__(self, other):
        return self.add(other)
    # ... 其他运算符

2. TensorFlow

# tf.Tensor 支持运算符重载
x = tf.constant([1, 2, 3])
y = -x  # 等价于 tf.negative(x)
z = x + 1  # 等价于 tf.add(x, 1)

3. JAX

# jax.numpy 完全兼容 NumPy 运算符
import jax.numpy as jnp
x = jnp.array([1, 2, 3])
y = -x  # 自然语法

4. PyPTO 现状

Tensor 类 (python/pypto/tensor.py,232-279行):

  • ✅ 已实现:__add__, __radd__, __iadd__, __sub__, __isub__, __mul__, __imul__, __truediv__, __itruediv__, __gt__, __matmul__
  • ❌ 缺失(本 Issue):__neg__, __pos__
  • ❌ 缺失(Issue #617):__rsub__, __rmul__, __rtruediv__
  • ❌ 缺失:__floordiv__, __mod__, __pow__, __lt__, __le__, __ge__, __eq__, __ne__

SymbolicScalar 类 (python/pypto/symbolic_scalar.py,67-129行):

  • ✅ 已完整实现所有运算符

实现建议

基于现有代码模式,建议在 python/pypto/tensor.py 中添加:

# 在 Tensor 类中添加(约 265 行后)

# 一元运算符(本 Issue 重点)
def __neg__(self) -> 'Tensor':
    """Unary negation operator (-tensor)"""
    return pypto.neg(self)

def __pos__(self) -> 'Tensor':
    """Unary positive operator (+tensor)"""
    return self

# 反向运算符(详见 Issue #617)
def __rsub__(self, other: 'Tensor | int | float') -> 'Tensor':
    """Reverse subtraction operator (scalar - tensor)"""
    return pypto.sub(other, self)

def __rmul__(self, other: 'Tensor | int | float') -> 'Tensor':
    """Reverse multiplication operator (scalar * tensor)"""
    return pypto.mul(other, self)

def __rtruediv__(self, other: 'Tensor | int | float') -> 'Tensor':
    """Reverse division operator (scalar / tensor)"""
    return pypto.div(other, self)

# 其他运算符
def __floordiv__(self, other: 'Tensor | int | float') -> 'Tensor':
    """Floor division operator (tensor // scalar)"""
    return pypto.floor_div(self, other)

def __mod__(self, other: 'Tensor | int | float') -> 'Tensor':
    """Modulo operator (tensor % scalar)"""
    return pypto.mod(self, other)

def __pow__(self, other: 'Tensor | int | float') -> 'Tensor':
    """Power operator (tensor ** scalar)"""
    return pypto.pow(self, other)

# 比较运算符
def __lt__(self, other: 'Tensor | int | float') -> 'Tensor':
    return pypto.less(self, other)

def __le__(self, other: 'Tensor | int | float') -> 'Tensor':
    return pypto.less_equal(self, other)

def __ge__(self, other: 'Tensor | int | float') -> 'Tensor':
    return pypto.greater_equal(self, other)

def __eq__(self, other: 'Tensor | int | float') -> 'Tensor':
    return pypto.equal(self, other)

def __ne__(self, other: 'Tensor | int | float') -> 'Tensor':
    return pypto.not_equal(self, other)

补充信息

优先级建议:

  1. 高优先级:__neg__, __pos__ - 最常用的一元运算符(本 Issue 重点)
  2. 高优先级:__rsub__, __rmul__, __rtruediv__ - 反向运算符(Issue #617)
  3. 中优先级:比较运算符 - 提升易用性
  4. 低优先级:其他运算符 - 可逐步添加

测试建议:

  • 为每个运算符添加单元测试
  • 验证与 pypto.*() 函数的等价性
  • 测试与标量的交互
  • 测试广播行为

文档建议:

  • 更新 API 文档,说明支持的运算符
  • 提供使用示例
  • 说明与 NumPy 的兼容性

关联 Issue:

  • #617: [Bug-Report]: Tensor类缺少反向运算符实现(rmul, rsub, rtruediv)- 与本 Issue 互补,共同完善 Tensor 运算符支持

实际案例:

  • FastGELU 算子开发中遇到 TypeError: bad operand type for unary -: 'Tensor'
  • 代码仓库:custom/fast_gelu/fast_gelu.py
likedislike
lidongshenglidongshengCollaborators
Mar 12 changed custom category from 任务 to 需求
lidongshenglidongshengCollaborators
Mar 12 Assign seu_chang as responsible person
lidongshenglidongshengCollaborators
Mar 12 Added label: Frontend
lidongsheng
lidongshengCollaborators
Mar 12 Comments:

功能已在规划中,请耐心等待

likedislike
杨旭杨旭Collaborators
Mar 12 associated Kanban: PyPTO
12 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