Files
TorchNPU/test/jit/test_jit_scriptmodule.py
T
bobebest 07770d39ce add test for add_module and apply api in torch.jit.ScriptModule
Co-authored-by: bobebest<773449114@qq.com>



# message auto-generated for no-merge-commit merge:
!40311 merge test-master into master

add test for add_module and apply api in torch.jit.ScriptModule

Created-by: bobebest
Commit-by: bobebest
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->

# 【合入来源】
> <font color="red">**如有社区issue,请关联issue链接**</font>\
> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font>

- [ ] 需求
- [ ] 问题单
- [x] issue/工单
https://gitcode.com/Ascend/pytorch/issues/1977
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】
> 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\
> 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容)

torch.jit.ScriptModule.add_module和torch.jit.ScriptModule.apply:已在 PyTorch 官方社区搜索 ,无针对该 API 的专门测试用例,因此自行编写测试用例。
Torch.jit.ScriptModule各属性介绍:把一个普通的 Python 模型(nn.Module)编译成 TorchScript 模型(ScriptModule),让它可以脱离 Python、在 NPU/C++/ 推理引擎上跑。

# API介绍
**torch.jit.ScriptModule.add_module**是 PyTorch TorchScript 中用于动态添加子模块的核心方法,该子模块可以使用给定的名称作为属性进行访问;
**语法:**add_module(name, module)
**参数:**
name(str):子模块的名称,可以是任意字符串
module(torch.nn.Module 或 None):要添加的子模块实例;传入 None 时相当于删除该名称对应的子模块
**返回值:**None
**核心特性:**
1、TorchScript 静态性约束:只有 add_module 能让 TorchScript 识别并追踪新加入的子模块、参数和缓冲区;
2、动态网络构建:适用于运行时才决定网络结构的场景(如循环添加多层、条件分支添加模块);
3、状态管理:加入的子模块会被纳入 parameters()、state_dict()、to(device)、train()/eval() 等管理体系。

**torch.jit.ScriptModule.apply**是 PyTorch TorchScript 静态图模块 的递归遍历函数,递归遍历模块自身 + 所有子模块,对每一个模块执行传入的函数。
**语法:**apply(fn)
**参数:**
fn(Callable[[torch.nn.Module], None]):一个函数,接受一个 Module 实例作为输入,返回 None。该函数会被递归地应用到模块自身和每一个子模块上
**返回值:**self(即调用 apply 的 ScriptModule 实例本身)
**核心特性如下:**
1、递归执行:深度优先遍历所有子模块
2、原地修改:直接修改模块,不返回新模型
3、顺序固定:先处理自身,再处理子模块
4、TorchScript 安全:可在静态图中正常使用
5、生命周期统一管理:参数、设备、模式全部生效
**具体测试内容如下:**
| 测试维度 | 具体内容 |
|---------|---------|
| 功能正确性 | `torch.jit.ScriptModule.add_module` 能否正确添加子模块;`torch.jit.ScriptModule.apply` 能否正确修改参数 |
| 递归行为 | `torch.jit.ScriptModule.apply` 是否递归访问所有嵌套子模块 |
| 类型一致性 | 添加的子模块是否被转换为 ScriptModule 类型 |
| 设备适配 | 所有参数和张量在 NPU 设备上的 device type 是否正确 |
| 前向推理 | 修改后的模型能否正常执行前向传播 |
| 返回值语义 | `torch.jit.ScriptModule.apply` 是否返回自身以支持链式调用 |


# 【资料变更】
> 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及”
不涉及
# 【接口变更】
> 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及”
不涉及

# 【功能验证】
> 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\
> 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图
![b6de5239a66a5bbba028c02fe3e625b2.png](https://raw.gitcode.com/user-images/assets/7404318/d146881f-1a0c-434d-833c-8ee1373450ad/b6de5239a66a5bbba028c02fe3e625b2.png 'b6de5239a66a5bbba028c02fe3e625b2.png')


# 【CheckList】
> PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]

- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [ ] PR持续集成流水线(CI)执行通过,代码检查无异常


See merge request: Ascend/pytorch!40311
2026-07-10 12:35:02 +08:00

342 lines
12 KiB
Python

"""
Add validation cases for torch.jit.ScriptModule APIs on NPU:
PyTorch community lacks sufficient and direct API validations for some APIs, so this file is added.
This file validates torch.jit.ScriptModule.bfloat16, torch.jit.ScriptModule.buffers,
torch.jit.ScriptModule.children, torch.jit.ScriptModule.code
torch.jit.ScriptModule.compile, torch.jit.ScriptModule.cpu
torch.jit.ScriptModule.add_module, torch.jit.ScriptModule.apply
"""
import os
import tempfile
import torch
from torch.testing._internal.common_utils import TestCase, run_tests
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
# Register buffer
self.register_buffer('register_buffer_out1', torch.randn(20))
self.register_buffer('register_buffer_out2', torch.randn(20, 1, 5, 5))
def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))
class TestJitScriptModuleBfloat16(TestCase):
def test_bfloat16(self):
model = Model()
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
self.assertIsInstance(model, nn.Module)
model_bf16 = model.bfloat16()
self.assertIsInstance(model_bf16, nn.Module)
# The validation parameters have been converted to bfloat16
for param in model_bf16.parameters():
self.assertEqual(param.dtype, torch.bfloat16)
def test_jit_bfloat16(self):
model = Model().bfloat16()
jit_model = torch.jit.script(model)
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
self.assertIsInstance(jit_model, torch.jit.ScriptModule)
# Verify the feasibility of JIT model execution
dummy_input = torch.randn(1, 1, 28, 28, dtype=torch.bfloat16, device="cpu")
output = jit_model(dummy_input)
self.assertEqual(output.dtype, torch.bfloat16)
class TestJitScriptModuleBuffers(TestCase):
def test_buffers(self):
model = Model()
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
buffers = list(model.buffers())
self.assertEqual(len(buffers), 2) # Two registered buffers
self.assertTrue(all(isinstance(b, torch.Tensor) for b in buffers))
def test_jit_buffers(self):
model = torch.jit.script(Model())
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
buffers = list(model.buffers())
self.assertEqual(len(buffers), 2)
self.assertTrue(all(isinstance(b, torch.Tensor) for b in buffers))
class TestJitScriptModuleChildren(TestCase):
def test_children(self):
model = Model()
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
children = list(model.children())
self.assertEqual(len(children), 2) # conv1, conv2
self.assertTrue(all(isinstance(c, nn.Module) for c in children))
def test_jit_children(self):
model = torch.jit.script(Model())
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
children = list(model.children())
self.assertEqual(len(children), 2)
self.assertTrue(all(isinstance(c, torch.nn.Module) for c in children))
class TestJitScriptModuleCode(TestCase):
def test_jit_code(self):
model = torch.jit.script(Model())
uninit_param = torch.nn.parameter.UninitializedParameter(device="npu")
self.assertEqual(uninit_param.device.type, "npu")
self.assertTrue(hasattr(model, 'code'))
self.assertIn('forward', str(model.code))
class TestJitScriptModuleCPU(TestCase):
def _check_model_device(self, model: torch.jit.ScriptModule, device_type: str):
"""Check whether all parameters and buffers of the model are on the specified device."""
for param in model.parameters():
self.assertEqual(param.device.type, device_type)
for buf in model.buffers():
self.assertEqual(buf.device.type, device_type)
def _run_infer(self, model: torch.jit.ScriptModule, device):
x = torch.randn(2, 1, 32, 32).to(device)
out = model(x)
self.assertEqual(out.dim(), 4)
def test_script_module_cpu_from_npu(self):
# Skip test if NPU is not available
if not hasattr(torch, "npu") or not torch.npu.is_available():
self.skipTest("NPU device unavailable, skip this test case")
# Instantiate model and convert to ScriptModule
model = Model()
script_model = torch.jit.script(model)
# Move ScriptModule to NPU and verify device
script_model = script_model.npu()
self._check_model_device(script_model, "npu")
# Transfer model from NPU back to CPU via cpu() method
cpu_script_model = script_model.cpu()
# Assert model type, device and normal inference execution
self.assertIsInstance(cpu_script_model, torch.jit.ScriptModule)
self._check_model_device(cpu_script_model, "cpu")
self._run_infer(cpu_script_model, torch.device("cpu"))
class TestJitScriptModuleCompile(TestCase):
def _check_model_device(self, model: torch.jit.ScriptModule, device_type: str):
"""Check whether all parameters and buffers of the model are on the specified device."""
for param in model.parameters():
self.assertEqual(param.device.type, device_type)
for buf in model.buffers():
self.assertEqual(buf.device.type, device_type)
def _run_infer(self, model, device):
"""Run model inference and verify output tensor shape validity."""
x = torch.randn(2, 1, 32, 32).to(device)
out = model(x)
self.assertEqual(out.dim(), 4)
def test_script_module_compile(self):
"""Test compilation and inference using torch.compile with NPU backend."""
if not hasattr(torch, "npu") or not torch.npu.is_available():
self.skipTest("NPU device is unavailable, skip this test case")
torch.npu.config.allow_internal_format = False
# Initialize model and convert to ScriptModule
model = Model()
scripted_model = torch.jit.script(model).npu()
# Move model to NPU and check device placement
self._check_model_device(scripted_model, "npu")
# Compile model with NPU backend
compiled_model = torch.compile(scripted_model, backend="npugraph_ex", fullgraph=True, dynamic=False)
# run inference validation
self._run_infer(compiled_model, torch.device("npu"))
class TestScriptModuleAddModule(TestCase):
class LinearLayer3to2(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.linear(x)
class LinearLayer5to3(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(5, 3)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.linear(x)
class ScriptedModelWithDynamicAdd(torch.jit.ScriptModule):
def __init__(self):
super().__init__()
main_mod = TestScriptModuleAddModule.LinearLayer5to3()
scripted_main = torch.jit.script(main_mod)
self.add_module("main", scripted_main)
sub_mod = TestScriptModuleAddModule.LinearLayer3to2()
scripted_sub = torch.jit.script(sub_mod)
self.add_module("sub_module", scripted_sub)
@torch.jit.script_method
def forward(self, x):
return self.main(x)
def test_add_module_on_scriptmodule_after_script(self):
module = self.ScriptedModelWithDynamicAdd()
# NPU
module.npu()
self.assertTrue(hasattr(module, "main"))
self.assertTrue(hasattr(module, "sub_module"))
self.assertIsInstance(module.main, torch.jit.ScriptModule)
self.assertIsInstance(module.sub_module, torch.jit.ScriptModule)
self.assertIn("main", module._modules)
self.assertIn("sub_module", module._modules)
main_params = list(module.main.parameters())
self.assertEqual(len(main_params), 2)
self.assertEqual(main_params[0].shape, (3, 5))
self.assertEqual(main_params[0].device.type, "npu")
sub_params = list(module.sub_module.parameters())
self.assertEqual(len(sub_params), 2)
self.assertEqual(sub_params[0].shape, (2, 3))
self.assertEqual(sub_params[0].device.type, "npu")
self.assertEqual(sub_params[1].device.type, "npu")
dummy_hidden = torch.randn(1, 3, device="npu")
sub_out = module.sub_module(dummy_hidden)
self.assertEqual(sub_out.shape, (1, 2))
self.assertEqual(sub_out.device.type, "npu")
dummy_input = torch.randn(1, 5, device="npu")
main_out = module(dummy_input)
self.assertEqual(main_out.shape, (1, 3))
self.assertEqual(main_out.device.type, "npu")
with tempfile.NamedTemporaryFile(suffix='.pt', delete=False) as f:
tmp_path = f.name
try:
module.save(tmp_path)
loaded = torch.jit.load(tmp_path)
loaded_npu = loaded.to("npu")
loaded_out = loaded_npu(dummy_input)
self.assertEqual(loaded_out.shape, (1, 3))
self.assertEqual(loaded_out.device.type, "npu")
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
class TestScriptModuleApply(TestCase):
def test_apply_modify_parameters(self):
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(1, 2, 3)
self.fc = nn.Linear(2 * 26 * 26, 5)
def forward(self, x):
x = self.conv(x)
x = x.view(x.size(0), -1)
return self.fc(x)
device = torch.device("npu")
model = SimpleModel().to(device)
scripted = torch.jit.script(model)
self.assertIsInstance(scripted, torch.jit.ScriptModule)
def zero_params(module):
if hasattr(module, 'weight') and module.weight is not None:
module.weight.data.fill_(0.0)
if hasattr(module, 'bias') and module.bias is not None:
module.bias.data.fill_(0.0)
scripted.apply(zero_params)
for param in scripted.parameters():
self.assertTrue(torch.all(param == 0))
self.assertEqual(param.device.type, "npu")
dummy = torch.randn(1, 1, 28, 28, device=device)
out = scripted(dummy)
self.assertTrue(torch.all(out == 0))
self.assertEqual(out.shape, (1, 5))
self.assertEqual(out.device.type, "npu")
def test_apply_recursively_visits_all_modules(self):
class Leaf(nn.Module):
def __init__(self):
super().__init__()
self.param = nn.Parameter(torch.randn(2, 2))
def forward(self, x):
return x
class Container(nn.Module):
def __init__(self):
super().__init__()
self.leaf1 = Leaf()
self.leaf2 = Leaf()
def forward(self, x):
return x
device = torch.device("npu")
model = Container().to(device)
scripted = torch.jit.script(model)
visited = set()
def record(module):
visited.add(id(module))
scripted.apply(record)
expected = {id(scripted), id(scripted.leaf1), id(scripted.leaf2)}
self.assertEqual(visited, expected)
def test_apply_returns_self(self):
class Dummy(nn.Module):
def forward(self, x):
return x
device = torch.device("npu")
model = Dummy().to(device)
scripted = torch.jit.script(model)
def noop(module):
pass
ret = scripted.apply(noop)
self.assertIs(ret, scripted)
if __name__ == "__main__":
run_tests()