test: add unit tests for torch.jit.ScriptModule.cuda and code_with_constants
Co-authored-by: sxj731533731<13791252840@163.com>
# message auto-generated for no-merge-commit merge:
!41627 merge fix_master into master
test: add unit tests for torch.jit.ScriptModule.cuda and code_with_constants
Created-by: sxj731533731
Commit-by: sxj731533731
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->
# 【合入来源】
> <font color="red">**https://gitcode.com/Ascend/pytorch/issues/2857**</font>\
> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font>
- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [ ] 重构优化
- [ ] 资料更新
# 【修改方案】
本次修改为在 test/ 目录下新增针对 torch.jit.ScriptModule 类中 cuda 和 code_with_constants 两个 API 的单元测试用例,具体实现如下:
测试用例文件新增:在 test/jit/ 目录下修改测试文件(如test_scriptmodule.py),继承 PyTorch 标准测试基类 TestCase。
cuda() API 测试:
注:当前在 NPU 环境下无法使用 cuda() 接口(因该接口强依赖 NVIDIA CUDA 运行时),该用例将被跳过;
code_with_constants API 测试:
构造包含常量(如 torch.tensor 常量、int 常量等)的 ScriptModule,并通过 torch.jit.script 转换。访问 code_with_constants 属性,断言返回值为包含两个元素的元组:第一个元素为 str 类型的计算图源码,第二个元素为 ConstMap 类型的常量映射。
# 【资料变更】
> “不涉及”
# 【接口变更】
>“不涉及”
# 【功能验证】
测试场景与测试方法:
code_with_constants 属性验证,构造含多种常量的 ScriptModule,断言 code_with_constants 返回值的结构和内容 返回 (str, ConstMap),且常量值匹配
具体demo如下:
```python
def test_script_module_code_with_constants(self):
"""Test code_with_constants API extraction and inference on NPU device."""
if not hasattr(torch, "npu") or not torch.npu.is_available():
self.skipTest("NPU device is unavailable, skip this test case")
# Define a model containing tensor constants and control flow
class ModelWithConstants(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv2d(1, 1, kernel_size=3, padding=1)
self.threshold = 0.5
# Register a tensor as a buffer to act as a constant in TorchScript
self.register_buffer('scale_factor', torch.tensor([2.0]))
def forward(self, x):
x = self.conv(x)
x = x * self.scale_factor
if x.mean() > self.threshold:
x = x + 1.0
return x
# Initialize model and convert to ScriptModule
model = ModelWithConstants()
scripted_model = torch.jit.script(model).npu()
# Move model to NPU and check device placement
self._check_model_device(scripted_model, "npu")
# Verify the functionality of code_with_constants API
result = scripted_model.code_with_constants
code_str, constants = result
# Verify the extracted code is a string and contains the forward function signature
self.assertIsInstance(code_str, str)
self.assertIn("def forward", code_str)
# Verify the constants object type
self.assertIsInstance(constants, torch.jit._script.ConstMap)
```
测试命令:python test_jit_scriptmodule.py
测试结果:

# 【CheckList】
> PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]
- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [x] PR持续集成流水线(CI)执行通过,代码检查无异常
See merge request: Ascend/pytorch!41627