Co-authored-by: gcw_IDzXRVNw<15104808434@163.com> # message auto-generated for no-merge-commit merge: !39596 merge test/fx-graphmodule-api-master into master test(fx): add NPU test cases for torch.fx.GraphModule APIs [master] Created-by: gcw_IDzXRVNw Commit-by: gcw_IDzXRVNw Merged-by: ascend-robot Description: # 【合入来源】 > <font color="red">**https://gitcode.com/Ascend/pytorch/issues/1856**</font> \ > <font color="red">**https://gitcode.com/Ascend/pytorch/issues/2482**</font> - [x] issue/工单 Fork: gcw_IDzXRVNw/pytorch_npu 分支: `test/fx-graphmodule-api-master` → Ascend/pytorch:`master` 关联 Issue: https://gitcode.com/Ascend/pytorch/issues/1856 # 【修改方案】 本 PR 为用户提供的任务 issue #1856 的交付。社区用例情况: - 已在 PyTorch 官方社区 `pytorch/test/test_fx.py` 下逐一搜索 `GraphModule.code`、`GraphModule.graph` 等 API,确认上游不存在针对这些属性的独立测试用例(仅作为辅助断言在其他测试中引用),因此自行编写测试用例。 ### 一、API 功能说明 `torch.fx.GraphModule` 是 PyTorch FX 框架的核心输出类,将 `fx.Graph` 转化为可执行的 `nn.Module`,并通过 Python 代码生成实现 Python-to-Python 变换。本次验证的 10 个 API 均为纯 Python 图操作,与底层计算设备完全解耦: - `torch.fx.GraphModule`:nn.Module 子类,持有 fx.Graph 并自动生成 Python forward 代码,是 FX Python-to-Python 变换的基础 - `torch.fx.GraphModule.__init__`:从 Module/dict 根对象和 Graph 构造 GraphModule,自动拷贝图中引用的属性和子模块 - `torch.fx.GraphModule.add_submodule`:在指定路径添加子模块,自动创建中间占位 Module - `torch.fx.GraphModule.code`:只读 property,返回从 Graph 生成的 Python 源码字符串 - `torch.fx.GraphModule.delete_all_unused_submodules`:遍历 Graph 节点收集引用,删除未使用的子模块 - `torch.fx.GraphModule.delete_submodule`:删除指定路径的子模块,路径无效或为非 Module 时返回 False - `torch.fx.GraphModule.graph`:property (getter/setter),获取底层 Graph 或设置新 Graph(setter 自动触发 recompile) - `torch.fx.GraphModule.print_readable`:生成可读的模块源码打印输出 - `torch.fx.GraphModule.recompile`:从 Graph 重新编译`forward()`方法,返回 PythonCode 对象 - `torch.fx.GraphModule.to_folder`:将模块导出到文件夹(含 module.py、state_dict.pt、__init__.py) 上述 API 的实现特征:全部定义在 `torch.fx.graph_module.GraphModule` 上,torch_npu 未做任何覆盖/重写。所有 API 操作对象为 Python 对象(Graph、Node、Module 层级、字符串),不涉及 Tensor 计算或硬件算子。 ### 二、测试文件 `test_fx_graph_module_api.py` 用例完备性说明 | API 全路径 | 验证类型 | 核心测试用例 | 验证覆盖场景 | 验证完整性结论 | |-----------|---------|------------|------------|--------------| | `torch.fx.GraphModule` | 间接验证 | 通过 `test_init_from_module`、`test_init_from_dict` 验证 | 1. 类可正常导入和实例化 2. 作为 nn.Module 子类行为正确 | 通过 __init__ 测试隐式覆盖,验证完全完整 | | `torch.fx.GraphModule.__init__` | 直接验证 | `test_init_from_module`、`test_init_from_dict`、`test_init_sets_class_name`、`test_init_raises_on_bad_type` | 1. Module根对象拷贝子模块 2. Dict根对象赋值属性 3. 自定义class_name 4. 非法root类型抛异常 | 覆盖三种根对象类型+异常路径,验证完全完整 | | `torch.fx.GraphModule.add_submodule` | 直接验证 | `test_add_submodule_root_level`、`test_add_submodule_nested`、`test_add_submodule_overwrite_fails_on_non_module` | 1. 根级添加 2. 嵌套路径自动创建中间Module 3. 非Module属性阻塞路径返回False | 覆盖正常+异常路径,验证完全完整 | | `torch.fx.GraphModule.code` | 直接验证 | `test_code_returns_string`、`test_code_contains_forward`、`test_code_contains_op_names`、`test_code_consistent_after_recompile` | 1. 返回值类型 2. 包含forward函数 3. 包含算子名 4. 多次recompile一致性 | 覆盖类型/内容/一致性,验证完全完整 | | `torch.fx.GraphModule.delete_all_unused_submodules` | 直接验证 | `test_delete_all_unused_removes_orphans`、`test_delete_all_unused_preserves_used` | 1. 删除孤立模块 2. 保留图中引用的模块 | 覆盖删除+保留双向验证,验证完全完整 | | `torch.fx.GraphModule.delete_submodule` | 直接验证 | `test_delete_submodule_existing`、`test_delete_submodule_nested`、`test_delete_submodule_nonexistent`、`test_delete_submodule_non_module` | 1. 删除已存在模块 2. 删除嵌套模块 3. 路径不存在返回False 4. 路径指向非Module返回False | 覆盖2正常+2异常路径,验证完全完整 | | `torch.fx.GraphModule.graph` | 直接验证 | `test_graph_getter_returns_graph`、`test_graph_getter_has_nodes`、`test_graph_getter_is_consistent`、`test_graph_setter_reassigns_graph`、`test_graph_setter_triggers_recompile`、`test_graph_setter_forward_works`、`test_graph_setter_raises_on_non_graph`、`test_graph_setter_preserves_lint` | 1. getter返回Graph实例 2. graph含placeholder/output节点 3. 重复访问一致性 4. setter更新内部引用 5. setter触发recompile 6. setter后forward正确 7. 非法类型抛AssertionError 8. lint通过 | 覆盖getter(3)/setter(5)全部路径,验证完全完整 | | `torch.fx.GraphModule.print_readable` | 直接验证 | `test_print_readable_returns_string`、`test_print_readable_contains_child_code` | 1. 返回字符串含class/forward 2. 包含子GraphModule代码 | 覆盖输出格式+嵌套场景,验证完全完整 | | `torch.fx.GraphModule.recompile` | 直接验证 | `test_recompile_returns_python_code`、`test_recompile_preserves_forward` | 1. 返回PythonCode对象 2. recompile后forward计算结果不变 | 覆盖返回类型+功能正确性,验证完全完整 | | `torch.fx.GraphModule.to_folder` | 直接验证 | `test_to_folder_creates_files`、`test_to_folder_module_file_content` | 1. 创建module.py和__init__.py 2. 生成文件为合法Python | 覆盖文件生成+内容验证,验证完全完整 | 【结论】所有用例覆盖 API 的基础功能、异常行为、接口存在性、以及 NPU 设备场景,34 个测试用例完整覆盖昇腾 NPU 适配所需的最小功能集。 ### 三、昇腾 NPU 适配说明 本次 GraphModule 相关 API 在昇腾 NPU 上的验证采用如下方式,符合硬件适配要求: - 所有 10 个 API 均为纯 Python 框架层图操作(操作 Graph/Node/Module 层级对象和字符串),与底层 CPU/GPU/NPU 计算硬件完全解耦,无需任何 NPU 特定代码适配 - 测试文件包含专用 `TestFxGraphModuleOnNpu` 类(3 个测试用例),显式将模块和张量迁移到 NPU 设备(`npu:0`),验证在真实 NPU 环境下 `code`、`graph`、`recompile`、`forward` 全部正常工作 - `TestFxGraphModuleOnNpu.setUp` 包含设备检查,非 NPU 环境自动 skipTest,避免虚假通过 - torch_npu 未对任何 GraphModule API 进行覆盖/重写,所有 API 行为与 PyTorch 上游完全一致 【结论】本测试文件的设计合理,可充分保证 GraphModule 在昇腾 NPU 环境下的功能正确性与可用性。 # 【资料变更】 文档变更已在 v2.7.1 分支 PR 中合入,本 PR 仅提交测试文件。 # 【接口变更】 不涉及 # 【功能验证】 - 测试文件路径:`test/fx/test_fx_graph_module_api.py` - 测试环境:`torch 2.7.1+cpu` + `torch_npu 2.7.1.post4` + `NPU 910B3` + `CANN 8.5.0` - 本地验证结果(完整运行日志): ``` root@hostname:/tmp# python test/fx/test_fx_graph_module_api.py -v test_code_consistent_after_recompile ... ok test_code_contains_forward ... ok test_code_contains_op_names ... ok test_code_returns_string ... ok test_graph_getter_has_nodes ... ok test_graph_getter_is_consistent ... ok test_graph_getter_returns_graph ... ok test_graph_setter_forward_works ... ok test_graph_setter_preserves_lint ... ok test_graph_setter_raises_on_non_graph ... ok test_graph_setter_reassigns_graph ... ok test_graph_setter_triggers_recompile ... ok test_init_from_dict ... ok test_init_from_module ... ok test_init_raises_on_bad_type ... ok test_init_sets_class_name ... ok test_code_and_graph_on_npu ... ok test_forward_on_npu ... ok test_recompile_on_npu ... ok test_print_readable_contains_child_code ... ok test_print_readable_returns_string ... ok test_recompile_preserves_forward ... ok test_recompile_returns_python_code ... ok test_add_submodule_nested ... ok test_add_submodule_overwrite_fails_on_non_module ... ok test_add_submodule_root_level ... ok test_delete_all_unused_preserves_used ... ok test_delete_all_unused_removes_orphans ... ok test_delete_submodule_existing ... ok test_delete_submodule_nested ... ok test_delete_submodule_non_module ... ok test_delete_submodule_nonexistent ... ok test_to_folder_creates_files ... ok test_to_folder_module_file_content ... ok ---------------------------------------------------------------------- Ran 34 tests in 2.316s OK ``` 【结论】执行测试用例后,34 passed,所有测试用例在 NPU 环境下执行通过。GraphModule 核心 API 在 NPU 上验证正确。 # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR 标题正确使用类型标签:`test(fx)` - [x] PR 持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!39596
464 lines
16 KiB
Python
464 lines
16 KiB
Python
"""
|
|
Add validation cases for torch.fx.GraphModule APIs on NPU:
|
|
1. PyTorch community lacks direct and independent test cases for
|
|
torch.fx.GraphModule.code, torch.fx.GraphModule.graph, and
|
|
several submodule management APIs, so this file is added.
|
|
2. This file validates torch.fx.GraphModule.__init__,
|
|
torch.fx.GraphModule.code, torch.fx.GraphModule.graph,
|
|
torch.fx.GraphModule.add_submodule,
|
|
torch.fx.GraphModule.delete_submodule,
|
|
torch.fx.GraphModule.delete_all_unused_submodules,
|
|
torch.fx.GraphModule.print_readable,
|
|
torch.fx.GraphModule.recompile,
|
|
torch.fx.GraphModule.to_folder (extendable).
|
|
"""
|
|
|
|
import os
|
|
import tempfile
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
from torch.fx import symbolic_trace, GraphModule, Graph
|
|
from torch.fx.graph import PythonCode
|
|
from torch.testing._internal.common_utils import run_tests, TestCase
|
|
|
|
device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
|
|
|
|
|
|
class TestFxGraphModuleInit(TestCase):
|
|
|
|
def test_init_from_module(self):
|
|
"""GraphModule.__init__ with nn.Module root copies submodules."""
|
|
class TestMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
m = TestMod()
|
|
gm = symbolic_trace(m)
|
|
self.assertTrue(hasattr(gm, "lin"))
|
|
self.assertIsInstance(gm.lin, nn.Linear)
|
|
|
|
def test_init_from_dict(self):
|
|
"""GraphModule.__init__ with dict root assigns attributes."""
|
|
graph = Graph()
|
|
x = graph.placeholder("x")
|
|
lin = graph.call_module("lin", args=(x,))
|
|
graph.output(lin)
|
|
|
|
gm = GraphModule({"lin": nn.Linear(4, 3)}, graph)
|
|
x_in = torch.randn(2, 4)
|
|
out = gm(x_in)
|
|
self.assertEqual(out.shape, (2, 3))
|
|
|
|
def test_init_sets_class_name(self):
|
|
"""GraphModule.__init__ with custom class_name."""
|
|
graph = Graph()
|
|
x = graph.placeholder("x")
|
|
graph.output(x)
|
|
|
|
gm = GraphModule(torch.nn.Module(), graph, class_name="MyGM")
|
|
self.assertEqual(gm.__class__.__name__, "MyGM")
|
|
|
|
def test_init_raises_on_bad_type(self):
|
|
"""GraphModule.__init__ rejects non-Module/non-dict root."""
|
|
graph = Graph()
|
|
x = graph.placeholder("x")
|
|
graph.output(x)
|
|
|
|
with self.assertRaises(RuntimeError):
|
|
GraphModule("bad_root", graph)
|
|
|
|
|
|
class TestFxGraphModuleCode(TestCase):
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
|
|
class SimpleModule(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.linear = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return torch.relu(self.linear(x))
|
|
|
|
self.gm = symbolic_trace(SimpleModule())
|
|
|
|
def test_code_returns_string(self):
|
|
"""code property returns a non-empty string."""
|
|
code = self.gm.code
|
|
self.assertIsInstance(code, str)
|
|
self.assertGreater(len(code), 0)
|
|
|
|
def test_code_contains_forward(self):
|
|
"""code contains 'def forward'."""
|
|
self.assertIn("def forward", self.gm.code)
|
|
self.assertIn("self", self.gm.code)
|
|
|
|
def test_code_contains_op_names(self):
|
|
"""code contains operator names from traced model."""
|
|
code = self.gm.code
|
|
self.assertIn("relu", code)
|
|
self.assertIn("linear", code)
|
|
|
|
def test_code_consistent_after_recompile(self):
|
|
"""code is consistent after multiple recompiles."""
|
|
code1 = self.gm.code
|
|
self.gm.recompile()
|
|
code2 = self.gm.code
|
|
self.assertEqual(code1, code2)
|
|
|
|
|
|
class TestFxGraphModuleGraph(TestCase):
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
|
|
class SimpleModule(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.linear = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return torch.relu(self.linear(x))
|
|
|
|
self.module = SimpleModule()
|
|
self.gm = symbolic_trace(self.module)
|
|
|
|
def test_graph_getter_returns_graph(self):
|
|
"""graph getter returns a Graph instance."""
|
|
g = self.gm.graph
|
|
self.assertIsInstance(g, Graph)
|
|
|
|
def test_graph_getter_has_nodes(self):
|
|
"""graph getter returns graph with placeholder and output."""
|
|
g = self.gm.graph
|
|
nodes = list(g.nodes)
|
|
self.assertGreater(len(nodes), 0)
|
|
ops = {node.op for node in nodes}
|
|
self.assertIn("placeholder", ops)
|
|
self.assertIn("output", ops)
|
|
|
|
def test_graph_getter_is_consistent(self):
|
|
"""graph getter returns same object on repeated access."""
|
|
g1 = self.gm.graph
|
|
g2 = self.gm.graph
|
|
self.assertIs(g1, g2)
|
|
|
|
def test_graph_setter_reassigns_graph(self):
|
|
"""Setting graph reassigns internal reference."""
|
|
gm_new = symbolic_trace(self.module)
|
|
new_graph = gm_new.graph
|
|
self.gm.graph = new_graph
|
|
self.assertIs(self.gm.graph, new_graph)
|
|
|
|
def test_graph_setter_triggers_recompile(self):
|
|
"""Setting graph triggers recompile and produces valid code."""
|
|
gm_new = symbolic_trace(self.module)
|
|
self.gm.graph = gm_new.graph
|
|
code = self.gm.code
|
|
self.assertIsInstance(code, str)
|
|
self.assertGreater(len(code), 0)
|
|
|
|
def test_graph_setter_forward_works(self):
|
|
"""After graph set, forward produces correct output."""
|
|
gm_new = symbolic_trace(self.module)
|
|
self.gm.graph = gm_new.graph
|
|
x = torch.randn(2, 4)
|
|
expected = self.module(x)
|
|
actual = self.gm(x)
|
|
torch.testing.assert_close(actual, expected)
|
|
|
|
def test_graph_setter_raises_on_non_graph(self):
|
|
"""Setting graph to non-Graph raises AssertionError."""
|
|
with self.assertRaises(AssertionError):
|
|
self.gm.graph = "not_a_graph"
|
|
with self.assertRaises(AssertionError):
|
|
self.gm.graph = 42
|
|
|
|
def test_graph_setter_preserves_lint(self):
|
|
"""After setting a valid graph, lint() does not raise."""
|
|
gm_new = symbolic_trace(self.module)
|
|
self.gm.graph = gm_new.graph
|
|
self.gm.graph.lint()
|
|
|
|
|
|
class TestFxGraphModuleSubmodule(TestCase):
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
graph = Graph()
|
|
x = graph.placeholder("x")
|
|
lin = graph.call_module("lin", args=(x,))
|
|
graph.output(lin)
|
|
self.gm = GraphModule({"lin": nn.Linear(4, 3)}, graph)
|
|
|
|
def test_add_submodule_root_level(self):
|
|
"""add_submodule at root level adds the module."""
|
|
new_mod = nn.ReLU()
|
|
result = self.gm.add_submodule("relu", new_mod)
|
|
self.assertTrue(result)
|
|
self.assertIs(self.gm.relu, new_mod)
|
|
|
|
def test_add_submodule_nested(self):
|
|
"""add_submodule creates intermediate modules for nested path."""
|
|
new_mod = nn.ReLU()
|
|
result = self.gm.add_submodule("a.b.c", new_mod)
|
|
self.assertTrue(result)
|
|
self.assertIsInstance(self.gm.a, nn.Module)
|
|
self.assertIsInstance(self.gm.a.b, nn.Module)
|
|
self.assertIs(self.gm.a.b.c, new_mod)
|
|
|
|
def test_add_submodule_overwrite_fails_on_non_module(self):
|
|
"""add_submodule returns False when path blocked by non-Module."""
|
|
self.gm.add_submodule("blocker", nn.ReLU())
|
|
# Install a non-Module attribute to block the path
|
|
self.gm.blocker.some_attr = "not_a_module"
|
|
result = self.gm.add_submodule("blocker.some_attr.sub", nn.ReLU())
|
|
self.assertFalse(result)
|
|
|
|
def test_delete_submodule_existing(self):
|
|
"""delete_submodule removes an existing submodule."""
|
|
self.gm.add_submodule("temp", nn.ReLU())
|
|
self.assertTrue(hasattr(self.gm, "temp"))
|
|
result = self.gm.delete_submodule("temp")
|
|
self.assertTrue(result)
|
|
self.assertFalse(hasattr(self.gm, "temp"))
|
|
|
|
def test_delete_submodule_nested(self):
|
|
"""delete_submodule removes a nested submodule."""
|
|
self.gm.add_submodule("outer.inner", nn.ReLU())
|
|
self.assertTrue(hasattr(self.gm.outer, "inner"))
|
|
result = self.gm.delete_submodule("outer.inner")
|
|
self.assertTrue(result)
|
|
self.assertFalse(hasattr(self.gm.outer, "inner"))
|
|
|
|
def test_delete_submodule_nonexistent(self):
|
|
"""delete_submodule on nonexistent path returns False."""
|
|
result = self.gm.delete_submodule("nonexistent.path")
|
|
self.assertFalse(result)
|
|
|
|
def test_delete_submodule_non_module(self):
|
|
"""delete_submodule on non-Module attribute returns False."""
|
|
self.gm.some_param = nn.Parameter(torch.randn(2, 2))
|
|
result = self.gm.delete_submodule("some_param")
|
|
self.assertFalse(result)
|
|
|
|
def test_delete_all_unused_removes_orphans(self):
|
|
"""delete_all_unused_submodules removes modules not in graph."""
|
|
graph = Graph()
|
|
x = graph.placeholder("x")
|
|
lin = graph.call_module("lin", args=(x,))
|
|
graph.output(lin)
|
|
gm = GraphModule({"lin": nn.Linear(4, 3)}, graph)
|
|
gm.add_submodule("orphan", nn.ReLU())
|
|
self.assertTrue(hasattr(gm, "orphan"))
|
|
gm.delete_all_unused_submodules()
|
|
self.assertFalse(hasattr(gm, "orphan"))
|
|
self.assertTrue(hasattr(gm, "lin"))
|
|
|
|
def test_delete_all_unused_preserves_used(self):
|
|
"""delete_all_unused_submodules preserves modules in graph."""
|
|
graph = Graph()
|
|
x = graph.placeholder("x")
|
|
a = graph.call_module("a", args=(x,))
|
|
b = graph.call_module("b", args=(a,))
|
|
graph.output(b)
|
|
gm = GraphModule({
|
|
"a": nn.Linear(4, 4),
|
|
"b": nn.Linear(4, 3),
|
|
}, graph)
|
|
gm.add_submodule("orphan", nn.ReLU())
|
|
self.assertTrue(hasattr(gm, "orphan"))
|
|
gm.delete_all_unused_submodules()
|
|
self.assertFalse(hasattr(gm, "orphan"))
|
|
self.assertTrue(hasattr(gm, "a"))
|
|
self.assertTrue(hasattr(gm, "b"))
|
|
|
|
|
|
class TestFxGraphModulePrintReadable(TestCase):
|
|
|
|
def test_print_readable_returns_string(self):
|
|
"""print_readable returns a non-empty string."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return torch.relu(self.lin(x))
|
|
|
|
gm = symbolic_trace(SimpleMod())
|
|
output = gm.print_readable(print_output=False)
|
|
self.assertIsInstance(output, str)
|
|
self.assertGreater(len(output), 0)
|
|
self.assertIn("class", output)
|
|
self.assertIn("def forward", output)
|
|
|
|
def test_print_readable_contains_child_code(self):
|
|
"""print_readable includes code from child GraphModules."""
|
|
class ChildMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.w = nn.Parameter(torch.randn(3, 4))
|
|
|
|
def forward(self, x):
|
|
return x + self.w
|
|
|
|
class ParentMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.child = symbolic_trace(ChildMod())
|
|
|
|
def forward(self, x):
|
|
return self.child(x)
|
|
|
|
gm = symbolic_trace(ParentMod())
|
|
output = gm.print_readable(print_output=False)
|
|
self.assertIsInstance(output, str)
|
|
self.assertIn("class", output)
|
|
|
|
|
|
class TestFxGraphModuleRecompile(TestCase):
|
|
|
|
def test_recompile_returns_python_code(self):
|
|
"""recompile returns a PythonCode object."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
gm = symbolic_trace(SimpleMod())
|
|
pc = gm.recompile()
|
|
self.assertIsInstance(pc, PythonCode)
|
|
self.assertGreater(len(pc.src), 0)
|
|
|
|
def test_recompile_preserves_forward(self):
|
|
"""After recompile, forward still works correctly."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
m = SimpleMod()
|
|
gm = symbolic_trace(m)
|
|
x = torch.randn(2, 4)
|
|
expected = m(x)
|
|
gm.recompile()
|
|
actual = gm(x)
|
|
torch.testing.assert_close(actual, expected)
|
|
|
|
|
|
class TestFxGraphModuleToFolder(TestCase):
|
|
|
|
def test_to_folder_creates_files(self):
|
|
"""to_folder creates module.py and __init__.py in folder."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
gm = symbolic_trace(SimpleMod())
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
gm.to_folder(tmpdir, "TestMod")
|
|
self.assertTrue(os.path.isfile(os.path.join(tmpdir, "module.py")))
|
|
self.assertTrue(os.path.isfile(
|
|
os.path.join(tmpdir, "__init__.py")))
|
|
|
|
def test_to_folder_module_file_content(self):
|
|
"""to_folder output can be imported."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
gm = symbolic_trace(SimpleMod())
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
gm.to_folder(tmpdir, "TestMod")
|
|
# Verify the module file content is valid Python
|
|
with open(os.path.join(tmpdir, "module.py")) as f:
|
|
content = f.read()
|
|
self.assertIn("class TestMod(torch.nn.Module)", content)
|
|
self.assertIn("def forward", content)
|
|
|
|
|
|
class TestFxGraphModuleOnNpu(TestCase):
|
|
"""Verify GraphModule APIs work with tensors on NPU device."""
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
if device_type == "cpu":
|
|
self.skipTest("Test requires NPU device")
|
|
|
|
def test_code_and_graph_on_npu(self):
|
|
"""code and graph properties work after moving module to NPU."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return torch.relu(self.lin(x))
|
|
|
|
m = SimpleMod().to(device_type)
|
|
gm = symbolic_trace(m)
|
|
self.assertIsInstance(gm.code, str)
|
|
self.assertGreater(len(gm.code), 0)
|
|
self.assertIsInstance(gm.graph, Graph)
|
|
self.assertGreater(len(list(gm.graph.nodes)), 0)
|
|
|
|
def test_forward_on_npu(self):
|
|
"""Generated forward works with NPU tensors."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
m = SimpleMod().to(device_type)
|
|
gm = symbolic_trace(m)
|
|
x = torch.randn(2, 4).to(device_type)
|
|
expected = m(x)
|
|
actual = gm(x)
|
|
torch.testing.assert_close(actual, expected)
|
|
|
|
def test_recompile_on_npu(self):
|
|
"""recompile works after module is on NPU."""
|
|
class SimpleMod(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.lin = nn.Linear(4, 3)
|
|
|
|
def forward(self, x):
|
|
return self.lin(x)
|
|
|
|
m = SimpleMod().to(device_type)
|
|
gm = symbolic_trace(m)
|
|
x = torch.randn(2, 4).to(device_type)
|
|
gm.recompile()
|
|
actual = gm(x)
|
|
expected = m(x)
|
|
torch.testing.assert_close(actual, expected)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_tests()
|