已合并
test(jit):add test for ScriptFunction,ScriptFunction.get_debug_state,ScriptFunction.save,and ScriptFunction.save_to_buffer #35369
test(jit):add test for ScriptFunction,ScriptFunction.get_debug_state,ScriptFunction.save,and ScriptFunction.save_to_buffer #35369
已合并
fengwu154创建于 5月12日
1 个文件变更+74-0
@@ -0,0 +1,74 @@
1+# Owner(s): ["oncall: jit"]
2+"""
3+add validation cases for torch.jit.ScriptFunction APIs:
4+torch.jit.ScriptFunction
5+torch.jit.ScriptFunction.get_debug_state
6+torch.jit.ScriptFunction.save
7+torch.jit.ScriptFunction.save_to_buffer
8+"""
9+ 
10+import io
11+import tempfile
12+import os
13+import torch
14+import unittest
15+from torch.testing._internal.common_utils import (
16+ run_tests,
17+ TestCase,
18+ enable_profiling_mode_for_profiling_tests,
19+ GRAPH_EXECUTOR,
20+ ProfilingMode,
21+)
22+ 
23+ 
24+class TestScriptFunctionAPI(TestCase):
25+ def setUp(self):
26+ super().setUp()
27+ 
28+ @torch.jit.script
29+ def test_fn(x: torch.Tensor) -> torch.Tensor:
30+ return x * 2 + 1
31+ 
32+ self.script_fn = test_fn
33+ self.dummy_input = torch.tensor([1.0, 2.0, 3.0]).npu()
34+ 
35+ def test_script_function_type(self):
36+ """Verify the object is a torch.jit.ScriptFunction."""
37+ self.assertIsInstance(self.script_fn, torch.jit.ScriptFunction)
38+ 
39+ @unittest.skipIf(
40+ GRAPH_EXECUTOR != ProfilingMode.PROFILING,
41+ "get_debug_state requires profiling graph executor",
42+ )
43+ def test_get_debug_state(self):
44+ """Verify get_debug_state returns a valid object under profiling mode."""
45+ with enable_profiling_mode_for_profiling_tests():
46+ # Run twice: first to profile, second to generate optimized plan
47+ self.script_fn(self.dummy_input)
48+ self.script_fn(self.dummy_input)
49+ state = self.script_fn.get_debug_state()
50+ self.assertIsNotNone(state)
51+ self.assertTrue(hasattr(state, "execution_plans"))
52+ 
53+ def test_save_to_buffer(self):
54+ """Test save_to_buffer returns bytes and can be loaded back."""
55+ buf = self.script_fn.save_to_buffer()
56+ self.assertIsInstance(buf, bytes)
57+ loaded = torch.jit.load(io.BytesIO(buf))
58+ expected = self.script_fn(self.dummy_input)
59+ actual = loaded(self.dummy_input)
60+ self.assertTrue(torch.equal(expected, actual))
61+ 
62+ def test_save_to_file(self):
63+ """Test save with a file path and reload."""
64+ with tempfile.TemporaryDirectory() as tmpdir:
65+ fname = os.path.join(tmpdir, "script_fn.pt")
66+ self.script_fn.save(fname)
67+ loaded = torch.jit.load(fname)
68+ expected = self.script_fn(self.dummy_input)
69+ actual = loaded(self.dummy_input)
70+ self.assertTrue(torch.equal(expected, actual))
71+ 
72+ 
73+if __name__ == "__main__":
74+ run_tests()