Repository navigation
Expand file tree
/
Copy pathtorch2ms.py
More file actions
1597 lines (1360 loc) · 60.4 KB
/
Copy pathtorch2ms.py
File metadata and controls
1597 lines (1360 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
torch2ms 主脚本。
读取预置的 PyTorch→MindSpore API 对照表,借助 LibCST 对源码做抽象语法树级改写,
同时生成必要的提示注释、补全 MindSpore 统一导入前缀,并输出转换后的代码与 diff。
"""
from __future__ import annotations
import difflib
import json
import os
import sys
from collections import OrderedDict, defaultdict
from typing import Optional
import libcst as cst
from libcst import helpers as cst_helpers
from libcst import metadata
from tqdm import tqdm
with open("api_mapping_out_excel.json", "r", encoding="utf8") as f:
API_MAP = json.load(f)["apis"]
def _literal_to_expr(value):
"""
将 Python 字面量转成 LibCST 表达式节点,便于直接拼装到 AST。
"""
return cst.parse_expression(repr(value))
class _MindSporeImportCollector(cst.CSTVisitor):
"""
收集 MindSpore 导入别名,用于还原完整调用名。
"""
def __init__(self) -> None:
self.alias_by_module = {}
def _maybe_record(self, module: str, alias: str) -> None:
"""
符合 mindspore 前缀时记录模块别名。
"""
if not module:
return
if not module.startswith("mindspore"):
return
self.alias_by_module[module] = alias
def visit_Import(self, node: cst.Import) -> None:
"""
处理 `import` 语句收集 MindSpore 别名。
"""
for name in node.names:
module = cst_helpers.get_full_name_for_node(name.name)
alias = (
name.asname.name.value
if getattr(name, "asname", None)
else getattr(name, "evaluated_name", None)
) or module
self._maybe_record(module, alias)
def visit_ImportFrom(self, node: cst.ImportFrom) -> None:
"""
处理 `from ... import ...`,记录 MindSpore 模块别名。
"""
if node.module is None:
return
module_name = cst_helpers.get_full_name_for_node(node.module)
if not module_name or not module_name.startswith("mindspore"):
return
for name in node.names:
if isinstance(name, cst.ImportStar):
continue
alias = (
name.asname.name.value
if getattr(name, "asname", None)
else getattr(name, "evaluated_name", None)
) or name.name.value
full_module = f"{module_name}.{name.name.value}"
self._maybe_record(full_module, alias)
def collect_mindspore_aliases(module: cst.Module) -> dict:
"""
根据导入语句收集 MindSpore 模块前缀到别名的映射。
"""
collector = _MindSporeImportCollector()
module.visit(collector)
return collector.alias_by_module
class _TorchImportCollector(cst.CSTVisitor):
"""
收集 torch 模块别名,记录 alias -> module 完整路径。
示例:
>>> code = "import torch.nn as tn\\nfrom torch import optim"
>>> collector = _TorchImportCollector()
>>> cst.parse_module(code).visit(collector)
>>> collector.module_by_alias
{'tn': 'torch.nn', 'optim': 'torch.optim'}
输出:
完成遍历后 `module_by_alias` 保存 torch 别名映射。
"""
def __init__(self) -> None:
self.module_by_alias = {}
def _maybe_record(self, module: str, alias: str) -> None:
"""
判断模块是否 torch 前缀并记录别名。
示例:
>>> collector = _TorchImportCollector()
>>> collector._maybe_record("torch.nn", "tn")
>>> collector.module_by_alias
{'tn': 'torch.nn'}
输出:
当模块以 torch 开头时写入 `module_by_alias`。
"""
if not module or not module.startswith("torch"):
return
self.module_by_alias[alias] = module
def visit_Import(self, node: cst.Import) -> None:
"""
处理 `import` 语句,将 torch 导入记录到别名表。
示例:
>>> code = "import torch as T"
>>> collector = _TorchImportCollector()
>>> cst.parse_module(code).visit(collector)
>>> collector.module_by_alias
{'T': 'torch'}
输出:
别名映射中包含 import 语句的别名关系。
"""
for name in node.names:
module = cst_helpers.get_full_name_for_node(name.name)
alias = (
name.asname.name.value
if getattr(name, "asname", None)
else getattr(name, "evaluated_name", None)
) or module
self._maybe_record(module, alias)
def visit_ImportFrom(self, node: cst.ImportFrom) -> None:
"""
处理 `from ... import ...` 语句,将 torch 下的导入也映射成完整模块。
示例:
>>> code = "from torch import nn"
>>> collector = _TorchImportCollector()
>>> cst.parse_module(code).visit(collector)
>>> collector.module_by_alias
{'nn': 'torch.nn'}
输出:
将 from 导入的名称补全成 torch 的全路径后写入映射。
"""
if node.module is None:
return
module_name = cst_helpers.get_full_name_for_node(node.module)
if not module_name or not module_name.startswith("torch"):
return
for name in node.names:
if isinstance(name, cst.ImportStar):
continue
alias = (
name.asname.name.value
if getattr(name, "asname", None)
else getattr(name, "evaluated_name", None)
) or name.name.value
full_module = f"{module_name}.{name.name.value}"
self._maybe_record(full_module, alias)
def collect_torch_aliases(module: cst.Module) -> dict:
"""
根据导入语句收集 torch 模块别名,返回 alias -> 全路径 的映射。
示例:
>>> mod = cst.parse_module("import torch.nn as tn\\nfrom torch import optim")
>>> collect_torch_aliases(mod)
{'tn': 'torch.nn', 'optim': 'torch.optim'}
输出:
字典形式的别名映射,用于后续还原完整 PyTorch API 名称。
"""
collector = _TorchImportCollector()
module.visit(collector)
return collector.module_by_alias
class _TorchAliasAssignmentCollector(cst.CSTVisitor):
"""
记录简单赋值形成的别名映射,例如: `myconv = nn.Conv2d`。
示例:
>>> code = "import torch.nn as nn\\nConv = nn.Conv2d"
>>> collector = _TorchAliasAssignmentCollector(api_by_class={}, pt_aliases={"nn": "torch.nn"})
>>> cst.parse_module(code).visit(collector)
>>> collector.alias_to_pt
{'Conv': 'torch.nn.Conv2d'}
输出:
遍历赋值后,`alias_to_pt` 保存直接别名,`alias_to_pt_wrapped` 保存包装类对应的原始 PyTorch API。
"""
def __init__(self, api_by_class: dict, pt_aliases: dict) -> None:
"""
初始化赋值别名收集器,依赖已有的 API 配置与 torch 别名。
示例:
>>> _TorchAliasAssignmentCollector({"Conv2d": {"pytorch": "torch.nn.Conv2d"}}, {"nn": "torch.nn"})
<_TorchAliasAssignmentCollector ...>
输出:
内部别名映射被置空,等待遍历代码时填充。
"""
self.api_by_class = api_by_class
self.pt_aliases = pt_aliases
self.alias_to_pt = {}
self.alias_to_pt_wrapped = {}
def _resolve_pt_full_name(self, full_name: Optional[str]) -> Optional[str]:
"""
根据别名映射还原 PyTorch 调用的完整路径。
示例:
>>> collector = _TorchAliasAssignmentCollector({}, {"nn": "torch.nn"})
>>> collector._resolve_pt_full_name("nn.Linear")
'torch.nn.Linear'
输出:
如果能找到匹配的前缀则返回完整路径,否则返回 None。
"""
if not full_name:
return None
parts = full_name.split(".")
for i in range(len(parts), 0, -1):
prefix = ".".join(parts[:i])
module = self.pt_aliases.get(prefix)
if module:
suffix = parts[i:]
if suffix:
return ".".join([module, *suffix])
return module
if full_name.startswith("torch"):
return full_name
return None
def _maybe_record_alias(self, target: cst.CSTNode, value: cst.CSTNode) -> None:
"""
处理单个赋值节点,记录左侧别名对应的 PyTorch API。
示例:
>>> collector = _TorchAliasAssignmentCollector({"Conv2d": {"pytorch": "torch.nn.Conv2d"}}, {"nn": "torch.nn"})
>>> assign = cst.parse_statement("my_conv = nn.Conv2d").body[0]
>>> collector._maybe_record_alias(assign.targets[0].target, assign.value)
>>> collector.alias_to_pt
{'my_conv': 'torch.nn.Conv2d'}
输出:
更新 `alias_to_pt` 或 `alias_to_pt_wrapped`,便于后续替换调用。
"""
if not isinstance(target, cst.Name):
return
if value is None:
return
if isinstance(value, cst.Call):
return
alias_name = target.value
value_full = cst_helpers.get_full_name_for_node(value)
root = value_full.split(".")[0] if value_full else None
if root in {"self", "cls"}:
return
pt_full_name = self._resolve_pt_full_name(value_full)
if pt_full_name and pt_full_name.startswith("torch"):
self.alias_to_pt[alias_name] = pt_full_name
return
if value_full:
class_name = value_full.split(".")[-1]
api_conf = self.api_by_class.get(class_name)
if api_conf:
self.alias_to_pt_wrapped[alias_name] = api_conf["pytorch"]
def visit_Assign(self, node: cst.Assign) -> None:
"""
捕获简单赋值语句并委托记录别名。
示例:
>>> collector = _TorchAliasAssignmentCollector({"Linear": {"pytorch": "torch.nn.Linear"}}, {"nn": "torch.nn"})
>>> cst.parse_module("layer = nn.Linear").visit(collector)
>>> collector.alias_to_pt
{'layer': 'torch.nn.Linear'}
输出:
将赋值中发现的别名写入映射。
"""
if len(node.targets) != 1:
return
self._maybe_record_alias(node.targets[0].target, node.value)
def visit_AnnAssign(self, node: cst.AnnAssign) -> None:
"""
捕获带类型标注的赋值并记录别名。
示例:
>>> collector = _TorchAliasAssignmentCollector({"Conv2d": {"pytorch": "torch.nn.Conv2d"}}, {"nn": "torch.nn"})
>>> cst.parse_module("conv: Any = nn.Conv2d").visit(collector)
>>> collector.alias_to_pt
{'conv': 'torch.nn.Conv2d'}
输出:
即使存在类型标注,也会保留别名映射信息。
"""
self._maybe_record_alias(node.target, node.value)
def collect_torch_assignment_aliases(module: cst.Module, api_by_class: dict, pt_aliases: dict) -> dict:
"""
收集代码中通过赋值形成的别名,返回直接别名和包装别名的双重映射。
示例:
>>> mod = cst.parse_module("import torch.nn as nn\\nConv = nn.Conv2d")
>>> collect_torch_assignment_aliases(mod, {"Conv2d": {"pytorch": "torch.nn.Conv2d"}}, {"nn": "torch.nn"})
({'Conv': 'torch.nn.Conv2d'}, {})
输出:
一个二元组: (alias_to_pt, alias_to_pt_wrapped)。
"""
collector = _TorchAliasAssignmentCollector(api_by_class, pt_aliases)
module.visit(collector)
return collector.alias_to_pt, collector.alias_to_pt_wrapped
class TorchToMindSporeTransformer(cst.CSTTransformer):
"""
使用 LibCST 将 PyTorch API 调用改写为 MindSpore 调用。
示例:
>>> code = "import torch.nn as nn\\nx = nn.ReLU()(input)"
>>> mod = cst.parse_module(code)
>>> wrapper = metadata.MetadataWrapper(mod)
>>> new_mod = wrapper.visit(TorchToMindSporeTransformer(API_MAP, pt_aliases={'nn': 'torch.nn'}))
>>> "mindspore" in new_mod.code
True
输出:
生成的新 AST 在 `code` 属性中包含 MindSpore API 调用及必要的注释。
"""
METHOD_ATTR_REMAP = {
# PyTorch Module 注册子模块 -> MindSpore Cell 注册子 Cell
"add_module": ("insert_child_to_cell", "torch.nn.Module.add_module"),
"register_module": ("insert_child_to_cell", "torch.nn.Module.register_module"),
}
METADATA_DEPENDENCIES = (metadata.ParentNodeProvider,)
def __init__(
self,
api_map,
ms_aliases: Optional[dict] = None,
pt_aliases: Optional[dict] = None,
pt_assignment_aliases: Optional[dict] = None,
pt_assignment_wrapped: Optional[dict] = None,
use_mint: bool = False,
) -> None:
"""
保存 PyTorch->MindSpore 的映射及收集到的别名信息。
示例:
>>> transformer = TorchToMindSporeTransformer(API_MAP, ms_aliases={'mindspore.nn': 'ms.nn'}, pt_aliases={'nn': 'torch.nn'})
>>> transformer.ms_aliases
{'mindspore.nn': 'ms.nn'}
输出:
Transformer 持有转换所需的别名和参数配置,准备在遍历时使用。
"""
super().__init__()
self.api_map = api_map
default_ms_aliases = {
"mindspore": "ms",
"mindspore.nn": "msnn",
"mindspore.ops": "msops",
"mindspore.mint": "mint",
"mindspore.mint.nn": "nn",
"mindspore.mint.ops": "ops",
}
self.ms_aliases = default_ms_aliases
if ms_aliases:
self.ms_aliases.update(ms_aliases)
self.pt_aliases = pt_aliases or {}
self.pt_assignment_aliases = pt_assignment_aliases or {}
self.pt_assignment_wrapped = pt_assignment_wrapped or {}
self.use_mint = use_mint
self.notes_by_stmt = defaultdict(list)
self.notes_by_func = defaultdict(list)
self.cell_class_stack = []
self.api_by_class = {
conf["pytorch"].split(".")[-1]: conf for conf in api_map.values()
}
self.api_by_pt_full = {
conf["pytorch"]: conf for conf in api_map.values()
}
def _find_enclosing_stmt(self, node: cst.CSTNode) -> Optional[cst.CSTNode]:
"""
获取包裹当前节点的最外层简单语句节点,方便追加注释。
示例:
>>> wrapper = metadata.MetadataWrapper(cst.parse_module("x = fn()"))
>>> transformer = TorchToMindSporeTransformer(API_MAP)
>>> wrapper.visit(transformer) # 让 transformer 拥有父节点元数据
>>> expr_node = wrapper.tree.body[0].body[0].value
>>> isinstance(transformer._find_enclosing_stmt(expr_node), cst.SimpleStatementLine)
True
输出:
返回 `cst.SimpleStatementLine` 或 None(未找到父节点时)。
"""
parent = self.get_metadata(metadata.ParentNodeProvider, node, None)
while parent is not None and not isinstance(parent, cst.SimpleStatementLine):
parent = self.get_metadata(metadata.ParentNodeProvider, parent, None)
return parent
def _record_note(self, node: cst.CSTNode, notes) -> None:
"""
将参数差异等提示绑定到最近的语句或语句块,方便人工确认。
"""
stmt = self._find_enclosing_stmt(node)
if stmt is None:
parent = self.get_metadata(metadata.ParentNodeProvider, node, None)
while parent and not isinstance(
parent, (cst.If, cst.For, cst.While, cst.With, cst.SimpleStatementLine)
):
parent = self.get_metadata(metadata.ParentNodeProvider, parent, None)
stmt = parent
if stmt is not None:
self.notes_by_stmt[stmt].extend(notes)
return
# 再退一步记录到最近的函数
func = self._find_enclosing_func(node)
if func is not None:
for note in notes:
self._record_func_note(func, note)
def _find_enclosing_func(self, node: cst.CSTNode) -> Optional[cst.FunctionDef]:
"""
向上寻找最近的函数定义节点,便于在函数签名附近添加注释。
用于收集需要展示在函数声明周围的提示信息,避免行尾注释分散难以查阅。
"""
parent = self.get_metadata(metadata.ParentNodeProvider, node, None)
while parent is not None and not isinstance(parent, cst.FunctionDef):
parent = self.get_metadata(metadata.ParentNodeProvider, parent, None)
return parent
def _record_func_note(self, node: cst.CSTNode, note: str) -> None:
"""
将提示绑定到最近的函数定义,便于批量添加到函数上方。
适合放置函数级别的提醒(如类型标注缺失映射),在 leave_FunctionDef 阶段统一落盘。
"""
if isinstance(node, cst.FunctionDef):
func = node
else:
func = self._find_enclosing_func(node)
if func:
self.notes_by_func[func].append(note)
def _is_ms_cell_base(self, base_name: Optional[str]) -> bool:
"""
判断基类名是否为 MindSpore Cell(包含常见别名)。
"""
if not base_name:
return False
prefixes = (
"mindspore.nn.",
"mindspore.mint.nn.",
"msnn.",
"ms.nn.",
"mint.nn.",
"nn.",
)
return base_name.endswith(".Cell") or base_name in {
"mindspore.nn.Cell",
"mindspore.mint.nn.Cell",
"msnn.Cell",
"ms.nn.Cell",
"mint.nn.Cell",
"nn.Cell",
"Cell",
} or any(base_name.startswith(p) and base_name[len(p):] == "Cell" for p in prefixes)
def _wrap_sequential_args(self, args):
"""
将 SequentialCell 的可变参数包装成列表,使调用符合 MindSpore 约定。
- 仅在纯位置参数且未显式提供 list/keyword 时包装;
- 已是关键字或单列表入参则直接返回;
- 以多行 list 形式输出以提升可读性。
"""
if not args:
return args
# 将 *[...]/*(...) 形式去星号,改为直接传入列表/元组
if len(args) == 1 and args[0].star:
return [args[0].with_changes(star=None)]
if not args:
return args
if any(arg.keyword is not None for arg in args):
return args
if len(args) == 1 and isinstance(args[0].value, cst.List):
return args
# 使用多行列表,尽量保留可读性
values_code = [
cst.Module([]).code_for_node(arg.value)
for arg in args
]
list_code = "[\n" + ",\n".join(f" {code}" for code in values_code) + "\n]"
list_expr = cst.parse_expression(list_code)
return [cst.Arg(keyword=None, value=list_expr)]
def visit_ClassDef(self, node: cst.ClassDef) -> bool:
"""
遍历类定义时记录“是否为 Cell”这一上下文。
- 若基类来自 torch.nn.Module 及其别名,则标记为需要后续重命名 forward。
- 若基类已是 MindSpore Cell,也视为需要保持 construct 语义。
结果会压栈到 `cell_class_stack`,在 leave_FunctionDef 中使用。
"""
base_names = [
cst_helpers.get_full_name_for_node(base.value) for base in node.bases
]
is_cell = False
for name in base_names:
pt_full_name = self._resolve_pt_full_name(name)
if pt_full_name and pt_full_name.endswith("Module"):
is_cell = True
break
if self._is_ms_cell_base(name):
is_cell = True
break
self.cell_class_stack.append(is_cell)
return True
def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef:
"""
处理函数定义收尾阶段:
1) 若处于 Cell 类中,自动将 forward 重命名为 construct;
2) 将此前记录的提示信息插入到函数前的空行注释中,避免丢失人工确认项。
"""
deco_notes: List[str] = []
new_decorators = []
for dec in updated_node.decorators:
converted = self._convert_decorator(dec, deco_notes)
if converted is not None:
new_decorators.append(converted)
if len(new_decorators) != len(updated_node.decorators):
updated_node = updated_node.with_changes(decorators=tuple(new_decorators))
for note in dict.fromkeys(deco_notes):
self._record_func_note(original_node, note)
if self.cell_class_stack and self.cell_class_stack[-1]:
if updated_node.name.value == "forward":
updated_node = updated_node.with_changes(name=cst.Name("construct"))
notes = self.notes_by_func.pop(original_node, [])
if notes:
leading = list(updated_node.leading_lines)
for note in dict.fromkeys(notes):
leading.append(cst.EmptyLine(comment=cst.Comment(f"# {note}")))
updated_node = updated_node.with_changes(leading_lines=leading)
return updated_node
def _resolve_ms_full_name(self, full_path: str) -> str:
"""
使用导入的别名还原 MindSpore API 全路径。
示例:
>>> transformer = TorchToMindSporeTransformer(API_MAP, ms_aliases={'mindspore.nn': 'ms.nn'})
>>> transformer._resolve_ms_full_name("mindspore.nn.ReLU")
'ms.nn.ReLU'
输出:
返回替换了别名后的完整 MindSpore 名称。
"""
parts = full_path.split(".")
for i in range(len(parts), 0, -1):
prefix = ".".join(parts[:i])
alias = self.ms_aliases.get(prefix)
if alias:
suffix = parts[i:]
if suffix:
return ".".join([alias, *suffix])
return alias
return full_path
def _resolve_pt_full_name(self, full_path: Optional[str]) -> Optional[str]:
"""
将调用名还原成完整的 PyTorch 路径,避免将同名自定义方法误判为 torch API。
示例:
>>> transformer = TorchToMindSporeTransformer(API_MAP, pt_aliases={'nn': 'torch.nn'})
>>> transformer._resolve_pt_full_name("nn.Linear")
'torch.nn.Linear'
输出:
成功匹配时返回以 torch 开头的完整路径,否则返回 None。
"""
if not full_path:
return None
if full_path in self.pt_assignment_aliases:
return self.pt_assignment_aliases[full_path]
parts = full_path.split(".")
for i in range(len(parts), 0, -1):
prefix = ".".join(parts[:i])
module = self.pt_aliases.get(prefix)
if module:
suffix = parts[i:]
if not suffix:
return module
result_parts = [module]
result_parts.extend(suffix)
return ".".join(result_parts)
if full_path.startswith("torch"):
return full_path
return None
def _reconstruct_args(self, call: cst.Call, api_conf):
"""
按 API 映射重排、重命名参数,返回新的实参列表与需要提示的备注。
示例:
>>> call = cst.parse_expression("fn(1, stride=2)")
>>> api_conf = {
... "pytorch": "torch.nn.Conv2d",
... "mindspore": "mindspore.nn.Conv2d",
... "params": [
... {"pytorch": {"name": "in_channels", "default": None}, "mindspore": {"name": "in_channels", "default": None}},
... {"pytorch": {"name": "stride", "default": 1}, "mindspore": {"name": "stride", "default": 1}},
... ],
... }
>>> new_args, notes = TorchToMindSporeTransformer(API_MAP)._reconstruct_args(call, api_conf)
>>> [a.keyword.value for a in new_args]
['in_channels', 'stride']
>>> notes
[]
输出:
元组 `(args, notes)`,其中 `args` 为适配 MindSpore 的参数列表,`notes` 为需要人工确认的提示。
"""
params = api_conf["params"]
if not params:
return call.args, []
positional_values = []
keyword_values = {}
for arg in call.args:
if arg.star:
# *args/**kwargs 保守不处理,并提示手动确认
return call.args, ["存在 *args/**kwargs,需手动确认参数映射;"]
if arg.keyword is None:
positional_values.append(arg.value)
else:
keyword_values[arg.keyword.value] = arg.value
ms_args = []
mismatch_notes = []
pos_idx = 0
force_keyword = False
used_keywords = set()
vararg_param_names = {"tensors", "inputs"}
if (
params
and params[0]["pytorch"].get("name") in vararg_param_names
and positional_values
and (len(positional_values) > 1 or len(positional_values) > len(params))
):
ms_args.extend(cst.Arg(keyword=None, value=val) for val in positional_values)
for idx, p in enumerate(params[1:], start=1):
pt = p["pytorch"]
ms = p["mindspore"]
pt_name = pt.get("name")
ms_name = ms.get("name")
pt_def = pt.get("default")
ms_def = ms.get("default")
if pt_name and pt_name in keyword_values:
kw_name = ms_name or pt_name
if pt_name != ms_name and ms_name is not None:
mismatch_notes.append(
f"'{api_conf['pytorch']}':默认参数名不一致(position {idx}): PyTorch={pt_name}, MindSpore={ms_name};"
)
ms_args.append(cst.Arg(keyword=cst.Name(kw_name), value=keyword_values[pt_name]))
elif (
pt_name is not None
and ms_name is not None
and pt_def is not None
and ms_def is not None
and pt_def != ms_def
):
mismatch_notes.append(
f"'{api_conf['pytorch']}'默认值不一致(position {idx}): PyTorch={pt_def}, MindSpore={ms_def};"
)
return ms_args, mismatch_notes
size_like_names = {"size", "shape", "dims"}
size_bundled = False
if (
params
and params[0]["pytorch"].get("name") in size_like_names
and params[0]["mindspore"].get("name") in size_like_names
and positional_values
and len(positional_values) > 1
and params[0]["pytorch"].get("name") not in keyword_values
):
size_elems = [cst.Element(value=v) for v in positional_values]
size_tuple = cst.Tuple(elements=size_elems)
ms_args.append(
cst.Arg(keyword=cst.Name(params[0]["mindspore"]["name"]), value=size_tuple)
)
size_bundled = True
pos_idx = len(positional_values)
for idx, p in enumerate(params):
pt = p["pytorch"]
ms = p["mindspore"]
pt_name = pt.get("name")
ms_name = ms.get("name")
pt_def = pt.get("default")
ms_def = ms.get("default")
if size_bundled and idx == 0:
continue
value = None
used_keyword = False
if pt_name and pt_name in keyword_values:
value = keyword_values[pt_name]
used_keyword = True
used_keywords.add(pt_name)
elif pos_idx < len(positional_values):
value = positional_values[pos_idx]
pos_idx += 1
if value is None:
if (
pt_name is not None
and ms_name is not None
and pt_def is not None
and ms_def is not None
and pt_def != ms_def
):
mismatch_notes.append(
f"'{api_conf['pytorch']}'默认值不一致(position {idx}): PyTorch={pt_def}, MindSpore={ms_def};"
)
continue
if ms_name is None:
mismatch_notes.append(
f"'{api_conf['pytorch']}':没有对应的mindspore参数 '{pt_name}' (position {idx});"
)
if pt_name:
used_keywords.add(pt_name)
force_keyword = True
continue
if pt_name and pt_name != ms_name:
mismatch_notes.append(
f"'{api_conf['pytorch']}':默认参数名不一致(position {idx}): PyTorch={pt_name}, MindSpore={ms_name};"
)
if used_keyword or force_keyword:
ms_args.append(cst.Arg(keyword=cst.Name(ms_name), value=value))
else:
ms_args.append(cst.Arg(keyword=None, value=value))
if force_keyword is False and used_keyword:
force_keyword = True
if pos_idx < len(positional_values):
mismatch_notes.append(
f"'{api_conf['pytorch']}':位置参数超过 MindSpore 参数数量,需手动确认;"
)
for extra_val in positional_values[pos_idx:]:
ms_args.append(cst.Arg(keyword=None, value=extra_val))
if any(arg.keyword is None for arg in ms_args) and any(arg.keyword is not None for arg in ms_args):
positional = [arg for arg in ms_args if arg.keyword is None]
keyword = [arg for arg in ms_args if arg.keyword is not None]
ms_args = positional + keyword
remaining_kwargs = set(keyword_values) - used_keywords
if remaining_kwargs:
names = ", ".join(sorted(remaining_kwargs))
mismatch_notes.append(
f"'{api_conf['pytorch']}':存在 MindSpore 未支持的参数 {names},需手动确认;"
)
return ms_args, mismatch_notes
def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.Call:
"""
在访问完函数/方法调用后,根据映射将 PyTorch 调用替换为 MindSpore 并调整参数。
示例:
>>> api_conf = {"pytorch": "torch.nn.ReLU", "mindspore": "mindspore.nn.ReLU", "params": []}
>>> transformer = TorchToMindSporeTransformer({"torch.nn.ReLU": api_conf}, pt_aliases={"nn": "torch.nn"})
>>> call = cst.parse_expression("nn.ReLU(x)")
>>> new_call = transformer.leave_Call(call, call)
>>> cst_helpers.get_full_name_for_node(new_call.func)
'mindspore.nn.ReLU'
True
输出:
如果匹配到映射则返回替换后的调用节点,并记录参数差异备注;否则原样返回。
"""
full_name = cst_helpers.get_full_name_for_node(updated_node.func)
pt_full_name = self._resolve_pt_full_name(full_name)
api_conf = None
def _apply_conf(conf, replace_func: bool = True):
new_args, notes = self._reconstruct_args(updated_node, conf)
if conf["mindspore"].endswith("SequentialCell"):
new_args = self._wrap_sequential_args(new_args)
new_call = updated_node.with_changes(
func=cst.parse_expression(self._resolve_ms_full_name(conf["mindspore"])) if replace_func else updated_node.func,
args=new_args,
)
if notes:
self._record_note(original_node, notes)
return new_call
if pt_full_name:
api_conf = self.api_by_pt_full.get(pt_full_name) or self.api_by_class.get(pt_full_name.split(".")[-1])
if api_conf:
return _apply_conf(api_conf)
wrapper_pt_full = self.pt_assignment_wrapped.get(full_name)
if wrapper_pt_full:
api_conf = self.api_by_pt_full.get(wrapper_pt_full) or self.api_by_class.get(wrapper_pt_full.split(".")[-1])
if api_conf:
return _apply_conf(api_conf, replace_func=False)
self._record_note(
original_node,
[f"'{wrapper_pt_full}' 未在映射表(api_mapping_out_excel.json)中找到,需手动确认;"],
)
# 实例方法兜底映射(如 self.features.add_module -> insert_child_to_cell)
if isinstance(updated_node.func, cst.Attribute):
attr_name = updated_node.func.attr.value
if attr_name in self.METHOD_ATTR_REMAP:
new_attr, pt_ref = self.METHOD_ATTR_REMAP[attr_name]
api_conf = self.api_by_pt_full.get(pt_ref) or self.api_by_class.get(pt_ref.split(".")[-1])
if api_conf:
new_args, notes = self._reconstruct_args(updated_node, api_conf)
else:
new_args, notes = updated_node.args, []
if notes:
self._record_note(original_node, notes)
if not api_conf:
self._record_note(
original_node,
[f"'{pt_ref}' 未在映射表(api_mapping_out_excel.json)中找到,需手动确认;"],
)
new_func = updated_node.func.with_changes(attr=cst.Name(new_attr))
return updated_node.with_changes(func=new_func, args=new_args)
if pt_full_name and not api_conf:
self._record_note(
original_node,
[f"'{pt_full_name}' 未在映射表(api_mapping_out_excel.json)中找到,需手动确认;"],
)
elif not pt_full_name and full_name and full_name.endswith("SequentialCell"):
# 直接调用 SequentialCell 时也包装参数列表,保持与 MindSpore 约定一致
if not any(arg.star for arg in updated_node.args):
new_args = self._wrap_sequential_args(list(updated_node.args))
if new_args != list(updated_node.args):
return updated_node.with_changes(args=new_args)
# 未命中映射但包含 *args/**kwargs,提醒人工确认
if any(arg.star for arg in updated_node.args):
self._record_note(original_node, ["存在 *args/**kwargs,未转换,需手动确认参数映射;"])
return updated_node
def leave_Attribute(self, original_node: cst.Attribute, updated_node: cst.Attribute) -> cst.BaseExpression:
"""
拦截属性访问,按映射表直接替换对应的 MindSpore 属性(含 dtype 常量等)。
"""
full_name = cst_helpers.get_full_name_for_node(updated_node)
if not full_name:
return updated_node
pt_full_name = self._resolve_pt_full_name(full_name)
if not pt_full_name or not pt_full_name.startswith("torch."):
return updated_node
api_conf = self.api_by_pt_full.get(pt_full_name) or self.api_by_class.get(
pt_full_name.split(".")[-1]
)
if api_conf:
ms_full_name = self._resolve_ms_full_name(api_conf["mindspore"])
return cst.parse_expression(ms_full_name)
return updated_node
def _convert_annotation_expr(
self, expr: cst.BaseExpression, missing_notes: List[str]
) -> cst.BaseExpression:
"""
递归转换类型标注中的表达式,支持 Optional/Union/Type 等嵌套结构。
"""
full_name = cst_helpers.get_full_name_for_node(expr)
if full_name:
pt_full_name = self._resolve_pt_full_name(full_name)
if pt_full_name:
api_conf = self.api_by_pt_full.get(pt_full_name) or self.api_by_class.get(
pt_full_name.split(".")[-1]
)
if api_conf:
ms_full_name = self._resolve_ms_full_name(api_conf["mindspore"])
return cst.parse_expression(ms_full_name)
missing_notes.append(
f"'{pt_full_name}' 未在映射表(api_mapping_out_excel.json)中找到,需手动确认;"
)
if isinstance(expr, cst.Subscript):
new_value = self._convert_annotation_expr(expr.value, missing_notes)
new_slices = []
for sl in expr.slice:
if isinstance(sl.slice, cst.Index):
inner = self._convert_annotation_expr(sl.slice.value, missing_notes)
new_slices.append(sl.with_changes(slice=sl.slice.with_changes(value=inner)))
else:
new_slices.append(sl)
return expr.with_changes(value=new_value, slice=tuple(new_slices))
if isinstance(expr, cst.Tuple):
new_elements = []
for elem in expr.elements:
if elem.value is None:
new_elements.append(elem)
else:
new_elements.append(
elem.with_changes(value=self._convert_annotation_expr(elem.value, missing_notes))
)
return expr.with_changes(elements=tuple(new_elements))
if isinstance(expr, cst.Attribute):
return expr.with_changes(value=self._convert_annotation_expr(expr.value, missing_notes))
return expr
def _convert_decorator(self, dec: cst.Decorator, notes: List[str]) -> Optional[cst.Decorator]:
"""
统一转换装饰器表达式,支持属性和调用形式;有映射则替换,无映射则保留并提示。
"""
expr = dec.decorator
target = expr.func if isinstance(expr, cst.Call) else expr
full_name = cst_helpers.get_full_name_for_node(target)
pt_full_name = self._resolve_pt_full_name(full_name)
if not pt_full_name:
if full_name and full_name.startswith("torch"):
notes.append(f"装饰器 '{full_name}' 未在映射表(api_mapping_out_excel.json)中找到,需手动确认;")
return dec
api_conf = self.api_by_pt_full.get(pt_full_name) or self.api_by_class.get(pt_full_name.split(".")[-1])
if api_conf:
ms_full_name = self._resolve_ms_full_name(api_conf["mindspore"])
if isinstance(expr, cst.Call):
new_args, arg_notes = self._reconstruct_args(expr, api_conf)
notes.extend(arg_notes)
new_call = expr.with_changes(func=cst.parse_expression(ms_full_name), args=new_args)
return dec.with_changes(decorator=new_call)
return dec.with_changes(decorator=cst.parse_expression(ms_full_name))
notes.append(f"装饰器 '{pt_full_name}' 未在映射表(api_mapping_out_excel.json)中找到,需手动确认;")
return dec