Skip to content
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

【Hackathon 5th No.42】 为Paddle代码转换工具新增API转换规则 (第1组 编号1-20) -part #306

Merged
merged 19 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
first commit
  • Loading branch information
Li-fAngyU committed Sep 27, 2023
commit 18c4fcf16436550d0aa08aadbf41c892a188535a
126 changes: 118 additions & 8 deletions paconvert/api_mapping.json
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,36 @@
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.nonzero"
},
"torch.Tensor.as_strided": {},
"torch.as_strided": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.as_strided",
"min_input_args": 2,
"args_list": [
"input",
"size",
"stride",
"storage_offset"
],
"kwargs_change": {
"input": "x",
"size": "shape",
"storage_offset": "offset"
}
},
"torch.Tensor.as_strided": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.as_strided",
"min_input_args": 2,
"args_list": [
"size",
"stride",
"storage_offset"
],
"kwargs_change": {
"size": "shape",
"storage_offset": "offset"
}
},
"torch.Tensor.as_subclass": {},
"torch.Tensor.backward": {
"Matcher": "GenericMatcher",
Expand Down Expand Up @@ -730,8 +759,26 @@
"memory_format"
]
},
"torch.Tensor.cummax": {},
"torch.Tensor.cummin": {},
"torch.Tensor.cummax": {
"Matcher": "TupleAssignMatcher",
"paddle_api": "paddle.Tensor.cummax",
"args_list": [
"dim"
],
"kwargs_change": {
"dim": "axis"
}
},
"torch.Tensor.cummin": {
"Matcher": "TupleAssignMatcher",
"paddle_api": "paddle.Tensor.cummin",
"args_list": [
"dim"
],
"kwargs_change": {
"dim": "axis"
}
},
"torch.Tensor.cumprod": {
"Matcher": "UnchangeMatcher",
"min_input_args": 1,
Expand Down Expand Up @@ -1323,7 +1370,11 @@
]
},
"torch.Tensor.hypot_": {},
"torch.Tensor.i0": {},
"torch.Tensor.i0": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.i0",
"min_input_args": 0
},
"torch.Tensor.i0_": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.i0_",
Expand Down Expand Up @@ -1369,7 +1420,19 @@
},
"torch.Tensor.index_fill": {},
"torch.Tensor.index_fill_": {},
"torch.Tensor.index_put": {},
"torch.Tensor.index_put": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.index_put",
"min_input_args": 2,
"args_list": [
"indices",
"values",
"accumulate"
],
"kwargs_change": {
"values": "value"
}
},
"torch.Tensor.index_put_": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.index_put_",
Expand Down Expand Up @@ -3038,7 +3101,19 @@
"sizes": "shape"
}
},
"torch.Tensor.unfold": {},
"torch.Tensor.unfold": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.unfold",
"min_input_args": 2,
"args_list": [
"dimension",
"size",
"step"
],
"kwargs_change": {
"dimension": "axis"
}
},
"torch.Tensor.uniform_": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.Tensor.uniform_",
Expand Down Expand Up @@ -3134,8 +3209,16 @@
"other": "y"
}
},
"torch.Tensor.view": {},
"torch.Tensor.view_as": {},
"torch.Tensor.view": {
"Matcher": "TensorViewMatcher"
},
"torch.Tensor.view_as": {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

paddle有paddle.Tensor.view_as

"Matcher": "TensorView_asMatcher",
"min_input_args": 1,
"args_list": [
"other"
]
},
"torch.Tensor.vsplit": {},
"torch.Tensor.where": {
"Matcher": "GenericMatcher",
Expand Down Expand Up @@ -4089,6 +4172,19 @@
"input": "x"
}
},
"torch.clamp_max": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.clip",
"args_list": [
"input",
"max",
"*",
"out"
],
"kwargs_change": {
"input": "x"
}
},
"torch.clip": {
"Matcher": "GenericMatcher",
"paddle_api": "paddle.clip",
Expand Down Expand Up @@ -4511,6 +4607,20 @@
"device"
]
},
"torch.cummax": {
"Matcher": "TupleAssignMatcher",
"paddle_api": "paddle.cummax",
"args_list": [
"input",
"dim",
"*",
"out"
],
"kwargs_change": {
"input": "x",
"dim": "axis"
}
},
"torch.cummin": {
"Matcher": "TupleAssignMatcher",
"paddle_api": "paddle.cummin",
Expand Down
49 changes: 49 additions & 0 deletions paconvert/api_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2781,6 +2781,55 @@ def generate_code(self, kwargs):
return code


class TensorViewMatcher(BaseMatcher):
def generate_aux_code(self):
CODE_TEMPLATE = textwrap.dedent(
"""
def view(self, *args, **kwargs):
if args:
if len(args)==1 and isinstance(args[0], (tuple, list, str)):
return paddle.view(self, args[0])
else:
return paddle.view(self, list(args))
elif kwargs:
assert 'shape_or_dtype' in kwargs
return paddle.view(self, shape=kwargs['shape_or_dtype'])

setattr(paddle.Tensor, 'view', view)
"""
)
return CODE_TEMPLATE

def get_paddle_class_nodes(self, func, args, kwargs):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

辅助函数,以及判断什么情况下是 误识别,什么情况下 保持不变即可,什么情况下 保持不变+辅助函数,这里还需要细致梳理一遍代码

if kwargs:
if len(kwargs) == 1 and "shape_or_dtype" in kwargs:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

torch的代码,不可能有"shape_or_dtype" 吧,这个是转写torch代码,传入的func、args、kwargs都是torch的内容,而且需要先self.parse_func处理func

return "unchange"
else:
return "misidentify"

if args:
if len(args) > 1 and isinstance(args[0], (ast.Tuple, ast.List)):
Copy link
Collaborator

@zhwesky2010 zhwesky2010 Oct 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里判断逻辑不太对,应该是:

if len(args) == 1:
    if isinstance(args[0], (ast.Tuple, ast.List)):
           return "unchange"
    if isinstance(args[0], (ast.Constant) and isinstance(args[0].value, str):
           return "unchange"

对应list/tuple/dtype三种用法,都直接保持原样就行。

return "unchange"
else:
self.write_aux_code()
return "unchange"

return "misidentify"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个尽量不要模仿其他API,而是分析这个API的自身参数特性,如果输入了 指定关键字 ,例如x.view(dtype=torch.float32) 这个是误识别的吗?



class TensorView_asMatcher(BaseMatcher):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

paddle不是也有paddle.Tensor.view_as吗

def generate_code(self, kwargs):

API_TEMPLATE = textwrap.dedent(
"""
{}.view({}.shape)
"""
)
code = API_TEMPLATE.format(self.paddleClass, kwargs["other"])

return code


class TensorReshapeMatcher(BaseMatcher):
def generate_aux_code(self):
CODE_TEMPLATE = textwrap.dedent(
Expand Down
54 changes: 20 additions & 34 deletions tests/test_Tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,60 +16,58 @@

from apibase import APIBase

obj = APIBase("torch.Tensor")
obj = APIBase("torch.tensor")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

torch.Tensortorch.tensor 是两个API,这个不要改动



def test_case_1():
pytorch_code = textwrap.dedent(
"""
import torch
result = torch.Tensor(2, 3)
result = torch.tensor([2, 3])
"""
)
obj.run(pytorch_code, ["result"], check_value=False)
obj.run(pytorch_code, ["result"])


def test_case_2():
pytorch_code = textwrap.dedent(
"""
import torch
shape = [2, 3]
result = torch.Tensor(*shape)
data = [2, 3]
result = torch.tensor(data)
"""
)
obj.run(pytorch_code, ["result"], check_value=False)
obj.run(pytorch_code, ["result"])


def test_case_3():
pytorch_code = textwrap.dedent(
"""
import torch
dim1, dim2 = 2, 3
result = torch.Tensor(dim1, dim2)
data = [2, 3]
result = torch.tensor(data, dtype=torch.float)
"""
)
obj.run(pytorch_code, ["result"], check_value=False)
obj.run(pytorch_code, ["result"])


def test_case_4():
pytorch_code = textwrap.dedent(
"""
import torch
def fun(x: torch.Tensor):
return x * 2

a = torch.Tensor(3, 4)
result = fun(a)
data = [2, 3]
result = torch.tensor(data, dtype=torch.float, device=None)
"""
)
obj.run(pytorch_code, ["result"], check_value=False)
obj.run(pytorch_code, ["result"])


def test_case_5():
pytorch_code = textwrap.dedent(
"""
import torch
result = torch.Tensor([[3, 4], [5, 8]])
data = [2, 3]
result = torch.tensor(data, dtype=torch.float, device=None, requires_grad = False)
"""
)
obj.run(pytorch_code, ["result"])
Expand All @@ -79,8 +77,10 @@ def test_case_6():
pytorch_code = textwrap.dedent(
"""
import torch
a = torch.tensor([[3, 4], [5, 8]])
result = torch.Tensor(a)
data = [2, 3]
result = None
if torch.cuda.is_available():
result = torch.tensor(data, requires_grad = False, pin_memory=True)
"""
)
obj.run(pytorch_code, ["result"])
Expand All @@ -90,22 +90,8 @@ def test_case_7():
pytorch_code = textwrap.dedent(
"""
import torch
result = torch.Tensor((1, 2, 3))
data = [2, 3]
result = torch.tensor(data, requires_grad = False, pin_memory=False)
"""
)
obj.run(pytorch_code, ["result"])


def test_case_8():
pytorch_code = textwrap.dedent(
"""
import torch
result = torch.Tensor()
"""
)
obj.run(
pytorch_code,
["result"],
unsupport=True,
reason="paddle does not support 0-Size Tensor",
)
17 changes: 3 additions & 14 deletions tests/test_Tensor_T.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,20 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import textwrap

from apibase import APIBase

obj = APIBase("torch.Tensor.T")
obj = APIBase("torch.Tensor.t")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

torch.Tensor.Ttorch.tensor.t 是两个API,这个不要改动



def test_case_1():
pytorch_code = textwrap.dedent(
"""
import torch
x = torch.arange(16).reshape(4, 4)
result = x.T
"""
)
obj.run(pytorch_code, ["result"])


def test_case_2():
pytorch_code = textwrap.dedent(
"""
import torch
result = torch.arange(16).reshape(4, 4).T
a = torch.Tensor([[1.,2.], [3.,4.]])
result = a.t()
"""
)
obj.run(pytorch_code, ["result"])
Loading