Files
TorchNPU/test/jit/test_jit_ScriptFunction.py
fengwu154 28f80b4f91 test(jit):add test for ScriptFunction,ScriptFunction.get_debug_state,ScriptFunction.save,and ScriptFunction.save_to_buffer
Co-authored-by: fengwu154<1067935138@qq.com>



# message auto-generated for no-merge-commit merge:
!35412 merge test-torch-jit-ScriptFunction-master into master

test(jit):add test for ScriptFunction,ScriptFunction.get_debug_state,ScriptFunction.save,and ScriptFunction.save_to_buffer

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

# 【合入来源】
https://gitcode.com/Ascend/pytorch/issues/1904

- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】
1. **`get_debug_state` 适配**  
   - 使用 PyTorch 内置的 `enable_profiling_mode_for_profiling_tests()` 上下文强制启用 profiling executor。  
   - 执行两次函数(一次 profile,一次 optimize),确保优化计划生成。  
   - 通过 `GRAPH_EXECUTOR` 常量判断执行器模式,非 profiling 模式自动跳过测试。
2. **`save` 适配**  
   - API 签名仅接受字符串路径,因此使用 `tempfile.TemporaryDirectory` 创建临时文件,避免对文件系统的污染。
3. **`save_to_buffer` 适配**  
   - 验证返回类型为 `bytes`,并通过 `io.BytesIO` 模拟文件流加载,与保存前输出一致。
   
   - **原测试缺口**:`test_jit.py` 虽大量使用 `ScriptFunction`,但缺少对其类型、`save_to_buffer` 及 `save` 直接路径的专门测试;`get_debug_state` 仅在特定测试中偶现调用,未系统验证。
- **新增覆盖**:
  - 类型断言:确保 `@torch.jit.script` 生成的函数为 `torch.jit.ScriptFunction` 实例。
  - 调试状态:验证在 profiling 模式下两次执行后可获得有效状态对象。
  - 序列化闭环:通过 `save_to_buffer` → `load` 和 `save(file)` → `load` 验证序列化后语义等价。
- **边界适配**:`get_debug_state` 通过 `@unittest.skipIf(GRAPH_EXECUTOR != ProfilingMode.PROFILING, ...)` 仅在有 profiling 执行器的环境中运行,避免内部断言错误。

- 新增测试文件 `test/jit/test_jit_ScriptFunction.py`。
- 实现 4 个测试用例,覆盖 `ScriptFunction` 类型、调试状态获取、内存序列化与文件序列化。
- 使用条件跳过(`@unittest.skipIf`)适配不同执行器模式(profiling / simple / legacy)。
- 不依赖外部文件,所有测试可在任意环境运行。


# 【资料变更】
不涉及
# 【接口变更】
不涉及

# 【功能验证】
```
root@devserver-fae-mirrors:/home/aicc/wf/api/2.7.1/pytorch/test# python test_jit_ScriptFunction.py
....
----------------------------------------------------------------------
Ran 4 tests in 10.120s

OK
```
覆盖版本:

v2.7.1
v2.9.0
v2.10.0
v2.11.0
v2.12.0 
master

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

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


See merge request: Ascend/pytorch!35412
2026-05-14 11:06:13 +08:00

75 lines
2.4 KiB
Python

# Owner(s): ["oncall: jit"]
"""
add validation cases for torch.jit.ScriptFunction APIs:
torch.jit.ScriptFunction
torch.jit.ScriptFunction.get_debug_state
torch.jit.ScriptFunction.save
torch.jit.ScriptFunction.save_to_buffer
"""
import io
import tempfile
import os
import torch
import unittest
from torch.testing._internal.common_utils import (
run_tests,
TestCase,
enable_profiling_mode_for_profiling_tests,
GRAPH_EXECUTOR,
ProfilingMode,
)
class TestScriptFunctionAPI(TestCase):
def setUp(self):
super().setUp()
@torch.jit.script
def test_fn(x: torch.Tensor) -> torch.Tensor:
return x * 2 + 1
self.script_fn = test_fn
self.dummy_input = torch.tensor([1.0, 2.0, 3.0]).npu()
def test_script_function_type(self):
"""Verify the object is a torch.jit.ScriptFunction."""
self.assertIsInstance(self.script_fn, torch.jit.ScriptFunction)
@unittest.skipIf(
GRAPH_EXECUTOR != ProfilingMode.PROFILING,
"get_debug_state requires profiling graph executor",
)
def test_get_debug_state(self):
"""Verify get_debug_state returns a valid object under profiling mode."""
with enable_profiling_mode_for_profiling_tests():
# Run twice: first to profile, second to generate optimized plan
self.script_fn(self.dummy_input)
self.script_fn(self.dummy_input)
state = self.script_fn.get_debug_state()
self.assertIsNotNone(state)
self.assertTrue(hasattr(state, "execution_plans"))
def test_save_to_buffer(self):
"""Test save_to_buffer returns bytes and can be loaded back."""
buf = self.script_fn.save_to_buffer()
self.assertIsInstance(buf, bytes)
loaded = torch.jit.load(io.BytesIO(buf))
expected = self.script_fn(self.dummy_input)
actual = loaded(self.dummy_input)
self.assertTrue(torch.equal(expected, actual))
def test_save_to_file(self):
"""Test save with a file path and reload."""
with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, "script_fn.pt")
self.script_fn.save(fname)
loaded = torch.jit.load(fname)
expected = self.script_fn(self.dummy_input)
actual = loaded(self.dummy_input)
self.assertTrue(torch.equal(expected, actual))
if __name__ == "__main__":
run_tests()