Merged
feat(frontend): Add LaunchKernel support in AST parser frontend #1015
feat(frontend): Add LaunchKernel support in AST parser frontend #1015
Merged
赵俊涵Add on Feb 10
Total: 8 files changed+216-239
@@ -18,11 +18,12 @@ including the parse function and JIT decorator.
18import inspect18import inspect
19import os19import os
20from typing import Any, Callable, Optional, Union20from typing import Any, Callable, Optional, Union
21+from enum import IntEnum
21 22 
22import pypto23import pypto
23import torch24import torch
24from pypto import pypto_impl25from pypto import pypto_impl
25-from pypto.converter import _torch_dtype_from26+from pypto.converter import _torch_dtype_from, _gen_pto_tensor
26from pypto.cost_model import _cost_model_run_once_data_from_host27from pypto.cost_model import _cost_model_run_once_data_from_host
27from pypto.frontend.parser.diagnostics import Source28from pypto.frontend.parser.diagnostics import Source
28from pypto.frontend.parser.parser import NestedFunctionMarker, Parser29from pypto.frontend.parser.parser import NestedFunctionMarker, Parser
@@ -155,29 +155,9 @@ class Parser(doc.NodeVisitor):
155 self._lowered_signature_cache = None155 self._lowered_signature_cache = None
156 self._bound_dim_values: Optional[dict[str, int]] = None156 self._bound_dim_values: Optional[dict[str, int]] = None
157 157 
158- @_catch_parser_errors
159- def parse(self) -> "Parser":
160- """The main parse method for parser (lazy mode).
161 158 
162- Prepares the AST but defers actual parsing until execute() is called.159+ @staticmethod
163- 
164- Returns
165- -------
166- res : Parser
167- Returns self for chaining.
168- """
169- node = self.diag.source.as_ast()
170- analyzer = LivenessAnalyzer()
171- exempt_vars = set(self._parsed_extra_vars.keys())
172- self.delete_after = analyzer.analyze(node, exempt_vars)
173- 
174- # Store for later execution (lazy mode)
175- self._parsed_node = node
176- return self
177- 
178- @_catch_parser_errors
179 def match_input_shapes(160 def match_input_shapes(
180- self,
181 input_shapes: list[list[int]],161 input_shapes: list[list[int]],
182 input_tensor_defs: Optional[list[pypto.Tensor]] = None,162 input_tensor_defs: Optional[list[pypto.Tensor]] = None,
183 ) -> dict[str, int]:163 ) -> dict[str, int]:
@@ -202,8 +182,6 @@ class Parser(doc.NodeVisitor):
202 dim_value_map = {}182 dim_value_map = {}
203 183 
204 # Get the signature to know which inputs have symbolic dimensions184 # Get the signature to know which inputs have symbolic dimensions
205- if input_tensor_defs is None:
206- input_tensor_defs, _ = self.get_signature()
207 185 
208 def _assign_dim_value(dim: pypto.SymbolicScalar, actual_value: int) -> None:186 def _assign_dim_value(dim: pypto.SymbolicScalar, actual_value: int) -> None:
209 if dim_value_map.get(str(dim), actual_value) != actual_value:187 if dim_value_map.get(str(dim), actual_value) != actual_value:
@@ -226,9 +204,30 @@ class Parser(doc.NodeVisitor):
226 raise TypeError(204 raise TypeError(
227 f"Invalid input shape type: {type(actual_input_shape)}, expected list"205 f"Invalid input shape type: {type(actual_input_shape)}, expected list"
228 )206 )
229- 
230 return dim_value_map207 return dim_value_map
231 208 
209+ 
210+ @_catch_parser_errors
211+ def parse(self) -> "Parser":
212+ """The main parse method for parser (lazy mode).
213+ 
214+ Prepares the AST but defers actual parsing until execute() is called.
215+ 
216+ Returns
217+ -------
218+ res : Parser
219+ Returns self for chaining.
220+ """
221+ node = self.diag.source.as_ast()
222+ analyzer = LivenessAnalyzer()
223+ exempt_vars = set(self._parsed_extra_vars.keys())
224+ self.delete_after = analyzer.analyze(node, exempt_vars)
225+ 
226+ # Store for later execution (lazy mode)
227+ self._parsed_node = node
228+ return self
229+ 
230+ 
232 @_catch_parser_errors231 @_catch_parser_errors
233 def bind_dynamic_dims_from_inputs(self, inputs: list[list[int]]) -> None:232 def bind_dynamic_dims_from_inputs(self, inputs: list[list[int]]) -> None:
234 """Bind symbolic dimensions to concrete values using sample inputs.233 """Bind symbolic dimensions to concrete values using sample inputs.
@@ -241,7 +240,9 @@ class Parser(doc.NodeVisitor):
241 240 
242 """241 """
243 242 
244- self._bound_dim_values = self.match_input_shapes(inputs)243+ input_tensor_defs, output_tensor_defs = self.get_signature()
244+ self._bound_dim_values = Parser.match_input_shapes(inputs, [*input_tensor_defs, *output_tensor_defs])
245+ 
245 246 
246 @_catch_parser_errors247 @_catch_parser_errors
247 def get_signature(248 def get_signature(
@@ -93,20 +93,20 @@ class _JIT:
93 pass_options=None, runtime_options=None, verify_options=None,93 pass_options=None, runtime_options=None, verify_options=None,
94 debug_options=None, infer_controlflow_shape=None):94 debug_options=None, infer_controlflow_shape=None):
95 self.dyn_func = dyn_func95 self.dyn_func = dyn_func
96- self.codegen_options = codegen_options96+ self._codegen_options = codegen_options
97- self.host_options = host_options97+ self._host_options = host_options
98- self.pass_options = pass_options98+ self._pass_options = pass_options
99- self.runtime_options = runtime_options or {}99+ self._runtime_options = runtime_options or {}
100- self.verify_options = verify_options or {}100+ self._verify_options = verify_options or {}
101- self.debug_options = debug_options101+ self._debug_options = debug_options
102- self.infer_controlflow_shape = infer_controlflow_shape102+ self._infer_controlflow_shape = infer_controlflow_shape
103- self.run_mode = self.init_run_mode()103+ self._run_mode = self.init_run_mode()
104 self.kwargs = None104 self.kwargs = None
105 105 
106 # if infer cache shape supported, also use full cache mode106 # if infer cache shape supported, also use full cache mode
107- if self.infer_controlflow_shape:107+ if self._infer_controlflow_shape:
108 # set to max cfgcache size 100000000108 # set to max cfgcache size 100000000
109- self.runtime_options['stitch_cfgcache_size'] = 100000000109+ self._runtime_options['stitch_cfgcache_size'] = 100000000
110 110 
111 self.kmodule = pypto_impl.KernelModule(self)111 self.kmodule = pypto_impl.KernelModule(self)
112 112 
@@ -114,7 +114,7 @@ class _JIT:
114 if len(args) < 1:114 if len(args) < 1:
115 raise ValueError("at least one tensor is required")115 raise ValueError("at least one tensor is required")
116 self.kwargs = kwargs116 self.kwargs = kwargs
117- if self.run_mode == RunMode.NPU:117+ if self._run_mode == RunMode.NPU:
118 pypto_impl.LaunchKernel(self, _current_stream(), *args)118 pypto_impl.LaunchKernel(self, _current_stream(), *args)
119 else:119 else:
120 self.run_cpu(*args)120 self.run_cpu(*args)
@@ -128,7 +128,7 @@ class _JIT:
128 return torch.empty(size, dtype=torch.int8, device='npu').data_ptr()128 return torch.empty(size, dtype=torch.int8, device='npu').data_ptr()
129 129 
130 def verify_begin(self, tensors):130 def verify_begin(self, tensors):
131- if isinstance(self.verify_options, dict) and self.verify_options.get("enable_pass_verify"):131+ if isinstance(self._verify_options, dict) and self._verify_options.get("enable_pass_verify"):
132 host_pto_tensors, _ = _gen_pto_tensor(tensors)132 host_pto_tensors, _ = _gen_pto_tensor(tensors)
133 host_pto_t_datas = _pto_to_tensor_data(host_pto_tensors)133 host_pto_t_datas = _pto_to_tensor_data(host_pto_tensors)
134 for i, dev_tensor in enumerate(_pto_to_tensor_data(tensors)):134 for i, dev_tensor in enumerate(_pto_to_tensor_data(tensors)):
@@ -155,14 +155,14 @@ class _JIT:
155 155 
156 def init_run_mode(self):156 def init_run_mode(self):
157 is_cann_enable = bool(os.environ.get("ASCEND_HOME_PATH"))157 is_cann_enable = bool(os.environ.get("ASCEND_HOME_PATH"))
158- if "run_mode" in self.runtime_options:158+ if "run_mode" in self._runtime_options:
159- run_mode = RunMode(self.runtime_options["run_mode"])159+ run_mode = RunMode(self._runtime_options["run_mode"])
160 else:160 else:
161 run_mode = RunMode.NPU if is_cann_enable else RunMode.SIM161 run_mode = RunMode.NPU if is_cann_enable else RunMode.SIM
162 if run_mode == RunMode.NPU and not is_cann_enable:162 if run_mode == RunMode.NPU and not is_cann_enable:
163 raise RuntimeError(163 raise RuntimeError(
164 "Please source cann environment while run mode is NPU.")164 "Please source cann environment while run mode is NPU.")
165- self.runtime_options["run_mode"] = int(run_mode)165+ self._runtime_options["run_mode"] = int(run_mode)
166 return RunMode(run_mode)166 return RunMode(run_mode)
167 167 
168 def run_cpu(self, *args):168 def run_cpu(self, *args):
@@ -176,23 +176,23 @@ class _JIT:
176 _cost_model_run_once_data_from_host(tensors, [])176 _cost_model_run_once_data_from_host(tensors, [])
177 177 
178 def _set_config_option(self):178 def _set_config_option(self):
179- if isinstance(self.codegen_options, dict):179+ if isinstance(self._codegen_options, dict):
180- pypto.set_codegen_options(**self.codegen_options)180+ pypto.set_codegen_options(**self._codegen_options)
181 181 
182- if isinstance(self.host_options, dict):182+ if isinstance(self._host_options, dict):
183- pypto.set_host_options(**self.host_options)183+ pypto.set_host_options(**self._host_options)
184 184 
185- if isinstance(self.pass_options, dict):185+ if isinstance(self._pass_options, dict):
186- pypto.set_pass_options(**self.pass_options)186+ pypto.set_pass_options(**self._pass_options)
187 187 
188- if isinstance(self.runtime_options, dict):188+ if isinstance(self._runtime_options, dict):
189- pypto.set_runtime_options(**self.runtime_options)189+ pypto.set_runtime_options(**self._runtime_options)
190 190 
191- if isinstance(self.verify_options, dict):191+ if isinstance(self._verify_options, dict):
192- pypto.set_verify_options(**self.verify_options)192+ pypto.set_verify_options(**self._verify_options)
193 193 
194- if isinstance(self.debug_options, dict):194+ if isinstance(self._debug_options, dict):
195- pypto.set_debug_options(**self.debug_options)195+ pypto.set_debug_options(**self._debug_options)
196 196 
197 197 
198@overload198@overload
@@ -604,20 +604,20 @@ private:
604 }604 }
605 605 
606 void InitConfigOptions(py::object &module) {606 void InitConfigOptions(py::object &module) {
607- auto options = module.attr("runtime_options").cast<py::dict>();607+ auto options = module.attr("_runtime_options").cast<py::dict>();
608 if (options.contains("triple_stream_sched")) {608 if (options.contains("triple_stream_sched")) {
609 tripleStream = options["triple_stream_sched"].cast<bool>();609 tripleStream = options["triple_stream_sched"].cast<bool>();
610 }610 }
611 if (options.contains("stitch_cfgcache_size")) {611 if (options.contains("stitch_cfgcache_size")) {
612 stitchCfgCacheSize = options["stitch_cfgcache_size"].cast<int64_t>();612 stitchCfgCacheSize = options["stitch_cfgcache_size"].cast<int64_t>();
613 }613 }
614- if (!module.attr("debug_options").is_none()) {614+ if (!module.attr("_debug_options").is_none()) {
615- auto debugOptions = module.attr("debug_options").cast<py::dict>();615+ auto debugOptions = module.attr("_debug_options").cast<py::dict>();
616 if (debugOptions.contains("runtime_debug_mode")) {616 if (debugOptions.contains("runtime_debug_mode")) {
617 isDebugMode = debugOptions["runtime_debug_mode"].cast<int64_t>() == CFG_DEBUG_ALL;617 isDebugMode = debugOptions["runtime_debug_mode"].cast<int64_t>() == CFG_DEBUG_ALL;
618 }618 }
619 }619 }
620- if (!module.attr("infer_controlflow_shape").is_none()) {620+ if (!module.attr("_infer_controlflow_shape").is_none()) {
621 inferCacheShape = true;621 inferCacheShape = true;
622 }622 }
623#if ENABALE_VERBOSE_LOG623#if ENABALE_VERBOSE_LOG
@@ -627,7 +627,7 @@ private:
627 }627 }
628 628 
629 void BuildDefaultCache(KernelBinary *kernel, py::object &module) {629 void BuildDefaultCache(KernelBinary *kernel, py::object &module) {
630- auto infershape = py::getattr(module, "infer_controlflow_shape");630+ auto infershape = py::getattr(module, "_infer_controlflow_shape");
631 auto cfshapes = infershape().cast<py::list>();631 auto cfshapes = infershape().cast<py::list>();
632 auto tensors = kernel->GetArgTypes();632 auto tensors = kernel->GetArgTypes();
633 for (auto &pyshape : cfshapes) {633 for (auto &pyshape : cfshapes) {
@@ -649,7 +649,7 @@ private:
649 }649 }
650 650 
651 bool InferCacheShape(py::object &module, py::args &args, std::vector<std::vector<int64_t>> &shapes) {651 bool InferCacheShape(py::object &module, py::args &args, std::vector<std::vector<int64_t>> &shapes) {
652- auto infershape = py::getattr(module, "infer_controlflow_shape", py::none());652+ auto infershape = py::getattr(module, "_infer_controlflow_shape", py::none());
653 if (infershape.is_none()) {653 if (infershape.is_none()) {
654 return false;654 return false;
655 }655 }
@@ -53,6 +53,7 @@ def test_hidden_loop_with_if_jit_function():
53 使用jit装饰器测试53 使用jit装饰器测试
54 """54 """
55 device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))55 device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
56+ torch.npu.set_device(device_id)
56 57 
57 tiling = 3258 tiling = 32
58 n, m = 1, 159 n, m = 1, 1
@@ -76,6 +77,7 @@ def test_hidden_loop_with_if_multiple_shapes():
76 测试不同形状77 测试不同形状
77 """78 """
78 device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))79 device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
80+ torch.npu.set_device(device_id)
79 81 
80 test_cases = [82 test_cases = [
81 {"tiling": 16, "n": 1, "m": 1, "s": 32},83 {"tiling": 16, "n": 1, "m": 1, "s": 32},
@@ -73,6 +73,7 @@ def test_verify_dyn():
73 device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0))73 device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0))
74 74 
75 device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu'75 device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu'
76+ torch.npu.set_device(device_id)
76 a = torch.rand(shape, dtype=torch.float16, device=device)77 a = torch.rand(shape, dtype=torch.float16, device=device)
77 b = torch.rand(shape, dtype=torch.float16, device=device)78 b = torch.rand(shape, dtype=torch.float16, device=device)
78 golden = ((a * (a + b)) - b) * b79 golden = ((a * (a + b)) - b) * b
@@ -27,7 +27,7 @@ D = 64
27def create_kernel(shape_out):27def create_kernel(shape_out):
28 @pypto.frontend.jit()28 @pypto.frontend.jit()
29 def kernel_func(29 def kernel_func(
30- in_tensor: pypto.Tensor((B, S, N1, D), pypto.DT_FP32), 30+ in_tensor: pypto.Tensor((B, S, N1, D), pypto.DT_FP32),
31 ) -> pypto.Tensor(shape_out, pypto.DT_FP32):31 ) -> pypto.Tensor(shape_out, pypto.DT_FP32):
32 pypto.set_vec_tile_shapes(1, 1, 64, 64)32 pypto.set_vec_tile_shapes(1, 1, 64, 64)
33 out_tensor = pypto.Tensor(shape_out, pypto.DT_FP32)33 out_tensor = pypto.Tensor(shape_out, pypto.DT_FP32)
@@ -44,10 +44,11 @@ def create_kernel(shape_out):
44 44 
45def test_clone():45def test_clone():
46 device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0))46 device_id = int(os.environ.get('TILE_FWK_DEVICE_ID', 0))
47+ torch.npu.set_device(device_id)
47 torch.manual_seed(42)48 torch.manual_seed(42)
48 # prepare data49 # prepare data
49 input_data = torch.rand((B, S, N1, D), dtype=torch.float32, device=f'npu:{device_id}')50 input_data = torch.rand((B, S, N1, D), dtype=torch.float32, device=f'npu:{device_id}')
50- 51+ 
51 output_shape = (B, S, N1 * D)52 output_shape = (B, S, N1 * D)
52 kernel_func = create_kernel(output_shape)53 kernel_func = create_kernel(output_shape)
53 # compute on npu54 # compute on npu
@@ -60,4 +61,3 @@ def test_clone():
60 golden = input_data.cpu().reshape((B, S, N1 * D)) + 161 golden = input_data.cpu().reshape((B, S, N1 * D)) + 1
61 62 
62 assert torch.allclose(output_cpu, golden, atol=1e-3, rtol=1e-3)63 assert torch.allclose(output_cpu, golden, atol=1e-3, rtol=1e-3)
63- 
@@ -9,7 +9,7 @@
9# See LICENSE in the root of the software repository for the full text of the License.9# See LICENSE in the root of the software repository for the full text of the License.
10# -----------------------------------------------------------------------------------------------------------10# -----------------------------------------------------------------------------------------------------------
11 11 
12-from pathlib import Path 12+from pathlib import Path
13 13 
14import os14import os
15import json15import json
@@ -17,6 +17,7 @@ import shutil
17import pypto17import pypto
18import torch18import torch
19import torch_npu19import torch_npu
20+import pytest
20 21 
21 22 
22def add_wrapper(shape, tiling=None):23def add_wrapper(shape, tiling=None):
@@ -68,6 +69,7 @@ def device_run(device_id):
68 check_output()69 check_output()
69 70 
70 71 
72+@pytest.mark.skip(reason="this feature is not ready")
71def test_debug_mode():73def test_debug_mode():
72 device_id = os.environ.get('TILE_FWK_DEVICE_ID', 0)74 device_id = os.environ.get('TILE_FWK_DEVICE_ID', 0)
73 output_name = "temp"75 output_name = "temp"