-
Notifications
You must be signed in to change notification settings - Fork 5.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[eager Tensor] Add __format__
for eager Tensor
#68677
[eager Tensor] Add __format__
for eager Tensor
#68677
Conversation
你的PR提交成功,感谢你对开源项目的贡献! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@@ -913,6 +913,12 @@ def __str__(self: Tensor) -> str: | |||
|
|||
return tensor_to_string(self) | |||
|
|||
def __format__(self, format_spec): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个下个 PR 加一下类型提示?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个下个 PR 加一下类型提示?
这类魔术方法应该不需要加类型提示吧,不是一个公开的能被直接调用的API
@@ -913,6 +913,12 @@ def __str__(self: Tensor) -> str: | |||
|
|||
return tensor_to_string(self) | |||
|
|||
def __format__(self, format_spec): | |||
if self.ndim == 0: | |||
return self.item().__format__(format_spec) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
为什么 0D 的是特殊的呢?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
为什么 0D 的是特殊的呢?
因为只有0D张量才被定义为标量,才能作为一个数被格式化,其它形状目前应该没有支持__format__,来自: https://github.com/pytorch/pytorch/pull/5785/files#diff-3fc4fad2faca4e14e4a1a731cb4a547ce495b67158ca95f8fd3a8d02e9d234b3R303-R306。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
嗯,我刚拿 torch 试了下,确实这样
numpy_scalar = paddle_scalar.numpy() | ||
format_spec = f".{width}f" | ||
self.assertEqual( | ||
paddle_scalar.__format__(format_spec), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
是否可以端到端测试下,比如 "{:.3f}".format(x)
,再比如 "{:.{}f}".format(x, 3)
这种复杂 case
目前只测试了 __format__
,这容易在端到端验证时(用户的用法)上出问题
PR Category
User Experience
PR Types
New features
Description
Pcard-75624
添加动态图Tensor的
__format__
功能,支持f"{tensor:.2f}"
这类格式化打印方法,省去手动调用Tensor.item()
的过程。预期的Tensor为只含有单个元素的0-D Tensor,否则会抛出对应的异常。参考:https://github.com/pytorch/pytorch/blob/main/torch/_tensor.py#L1091-L1096