Merged
perf(pypto_pro): Reduce JIT host overhead #7707
yzfAdd on 6 days ago
perf(pypto_pro): Reduce JIT host overhead #7707
Merged
yzfAdd on 6 days ago
Total: 8 files changed+143-46
@@ -59,7 +59,8 @@
59 "debug": {59 "debug": {
60 "compile_debug_mode": 0,60 "compile_debug_mode": 0,
61 "runtime_debug_mode": 0,61 "runtime_debug_mode": 0,
62- "dump_pass_graph": []62+ "dump_pass_graph": [],
63+ "enable_exception_dump": false
63 },64 },
64 "operation": {65 "operation": {
65 "combine_axis" : true66 "combine_axis" : true
@@ -573,6 +573,13 @@
573 "minimum": 0,573 "minimum": 0,
574 "maximum": 4574 "maximum": 4
575 },575 },
576+ "enable_exception_dump": {
577+ "type": "boolean",
578+ "label": {
579+ "zh": "是否启用PyPTO Pro JIT异常转储信息采集,默认关闭;须在Kernel变体首次编译前设置。",
580+ "en": "Enable PyPTO Pro JIT exception-dump metadata collection, disabled by default; set before a Kernel variant is first compiled."
581+ }
582+ },
576 "dump_pass_graph": {583 "dump_pass_graph": {
577 "type": "array",584 "type": "array",
578 "items": {585 "items": {
@@ -554,6 +554,7 @@ def set_debug_options(
554 compile_debug_mode: Optional[int] = None,554 compile_debug_mode: Optional[int] = None,
555 runtime_debug_mode: Optional[int] = None,555 runtime_debug_mode: Optional[int] = None,
556 dump_pass_graph: Optional[List[str]] = None,556 dump_pass_graph: Optional[List[str]] = None,
557+ enable_exception_dump: Optional[bool] = None,
557) -> None:558) -> None:
558 """559 """
559 Set debug options.560 Set debug options.
@@ -584,6 +585,11 @@ def set_debug_options(
584 Pass identifiers to dump computation graph and print IR. Empty list disables it.585 Pass identifiers to dump computation graph and print IR. Empty list disables it.
585 Unmatched identifiers are ignored with a warning. If compile_debug_mode is 1,586 Unmatched identifiers are ignored with a warning. If compile_debug_mode is 1,
586 all passes dump graph and print IR regardless of dump_pass_graph.587 all passes dump graph and print IR regardless of dump_pass_graph.
588+ 
589+ enable_exception_dump : bool
590+ Enable PyPTO Pro JIT exception-dump metadata collection. Disabled by default.
591+ Set before the first compilation of a Kernel variant; cached variants retain
592+ the setting captured when they were compiled.
587 """593 """
588 options_dict = {k: v for k, v in locals().items() if v is not None}594 options_dict = {k: v for k, v in locals().items() if v is not None}
589 set_options(debug_options=options_dict)595 set_options(debug_options=options_dict)
@@ -171,6 +171,7 @@ class CompiledKernel:
171 has_vector: bool = True171 has_vector: bool = True
172 target: KernelTarget | None = None172 target: KernelTarget | None = None
173 needs_print_debug: bool = False173 needs_print_debug: bool = False
174+ enable_exception_dump: bool = False
174 # Lazily bound launch closure (see _build_launch_entry). It depends only on the175 # Lazily bound launch closure (see _build_launch_entry). It depends only on the
175 # fields above, so it is built once instead of on every launch.176 # fields above, so it is built once instead of on every launch.
176 entry: "Callable | None" = dataclasses.field(default=None, compare=False, repr=False)177 entry: "Callable | None" = dataclasses.field(default=None, compare=False, repr=False)
@@ -776,12 +777,11 @@ def _build_launch_entry(compiled: "CompiledKernel"):
776 # resource-query errors. int64_t preserves the error tag above its 32-bit detail.777 # resource-query errors. int64_t preserves the error tag above its 32-bit detail.
777 call_kernel.restype = ctypes.c_int64778 call_kernel.restype = ctypes.c_int64
778 logger = logging.getLogger()779 logger = logging.getLogger()
779- # Exception-dump bookkeeping. The addresses and shapes it caches are per-launch, so780+ _set_dump_info = None
780- # the call itself has to stay on the hot path -- but the import and the kernel's own781+ if compiled.enable_exception_dump:
781- # identity do not, and _load_lib used to redo both on every launch.782+ from pypto_pro.runtime.exception_dump import set_dump_info as _set_dump_info
782- from pypto_pro.runtime.exception_dump import set_dump_info as _set_dump_info
783 783 
784- def entry(args: tuple, block_dim: int, stream):784+ def entry(args: tuple, block_dim: int, stream, tensor_shapes: list | None = None):
785 if has_tiling:785 if has_tiling:
786 args = _pack_tiling_arg(args)786 args = _pack_tiling_arg(args)
787 if len(args) != n_params:787 if len(args) != n_params:
@@ -812,10 +812,12 @@ def _build_launch_entry(compiled: "CompiledKernel"):
812 raise InvalidType(812 raise InvalidType(
813 f"arg[{index}] '{name}': dtype mismatch — expected {expected_dtype}, got {arg.dtype}"813 f"arg[{index}] '{name}': dtype mismatch — expected {expected_dtype}, got {arg.dtype}"
814 )814 )
815- # One .shape per tensor: reused for the positivity check, the rank check,815+ # Reuse shapes read for variant selection during this same launch.
816- # the constant-dimension checks and this parameter's slice of the dynamic816+ # Keep packed storage shapes here; normalize only the local value below.
817- # ABI tail.817+ shape = arg.shape if tensor_shapes is None else tensor_shapes[index]
818- shape = arg.shape818+ if shape is None:
819+ shape = arg.shape
820+ tensor_shapes[index] = shape
819 if len(shape) != rank:821 if len(shape) != rank:
820 raise InvalidType(822 raise InvalidType(
821 f"arg[{index}] '{name}': rank mismatch — expected {rank}D, got {len(shape)}D"823 f"arg[{index}] '{name}': rank mismatch — expected {rank}D, got {len(shape)}D"
@@ -852,7 +854,8 @@ def _build_launch_entry(compiled: "CompiledKernel"):
852 if other is None:854 if other is None:
853 continue855 continue
854 # pack_mult is 1 unless this is a sub-byte parameter's packed axis.856 # pack_mult is 1 unless this is a sub-byte parameter's packed axis.
855- actual = other.shape[dim] * pack_mult857+ shape = other.shape if tensor_shapes is None else tensor_shapes[param_index]
858+ actual = shape[dim] * pack_mult
856 if first < 0:859 if first < 0:
857 first = actual860 first = actual
858 elif actual != first:861 elif actual != first:
@@ -869,7 +872,8 @@ def _build_launch_entry(compiled: "CompiledKernel"):
869 # native auto sentinel) and is rejected by the native limit check instead.872 # native auto sentinel) and is rejected by the native limit check instead.
870 if block_dim > 0xFFFFFFFF:873 if block_dim > 0xFFFFFFFF:
871 block_dim = 0xFFFFFFFF874 block_dim = 0xFFFFFFFF
872- _set_dump_info(compiled, args, block_dim)875+ if _set_dump_info is not None:
876+ _set_dump_info(compiled, args, block_dim)
873 # Resolve limits and launch in one C call, avoiding two torch_npu C-extension877 # Resolve limits and launch in one C call, avoiding two torch_npu C-extension
874 # calls and Python dict/loop work. Errors return before any device launch.878 # calls and Python dict/loop work. Errors return before any device launch.
875 actual_block_dim = call_kernel(block_dim, stream._as_parameter_, *abi_args)879 actual_block_dim = call_kernel(block_dim, stream._as_parameter_, *abi_args)
@@ -1768,7 +1772,7 @@ def _launch_error_message(error_code: int, requested_block_dim: int, compiled: "
1768 return f"{prefix} (kind={kind}, detail={detail:#x})"1772 return f"{prefix} (kind={kind}, detail={detail:#x})"
1769 1773 
1770 1774 
1771-def _launch(compiled: "CompiledKernel", args: tuple, block_dim: int, stream):1775+def _launch(compiled: "CompiledKernel", args: tuple, block_dim: int, stream, tensor_shapes: list | None = None):
1772 """Launch one compiled kernel, binding its entry closure on first use.1776 """Launch one compiled kernel, binding its entry closure on first use.
1773 1777 
1774 Kept as a module-level function rather than inlined into the launcher so test1778 Kept as a module-level function rather than inlined into the launcher so test
@@ -1779,7 +1783,7 @@ def _launch(compiled: "CompiledKernel", args: tuple, block_dim: int, stream):
1779 entry = compiled.entry1783 entry = compiled.entry
1780 if entry is None:1784 if entry is None:
1781 entry = compiled.entry = _build_launch_entry(compiled)1785 entry = compiled.entry = _build_launch_entry(compiled)
1782- entry(args, block_dim, stream)1786+ entry(args, block_dim, stream, tensor_shapes)
1783 1787 
1784 1788 
1785def _format_findings(findings) -> str:1789def _format_findings(findings) -> str:
@@ -1904,7 +1908,7 @@ def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
1904 """1908 """
1905 base_entry = _build_launch_entry(compiled)1909 base_entry = _build_launch_entry(compiled)
1906 1910 
1907- def entry(args: tuple, block_dim: int, stream):1911+ def entry(args: tuple, block_dim: int, stream, tensor_shapes: list | None = None):
1908 # The sentinel cannot size the buffer (the actual count is resolved1912 # The sentinel cannot size the buffer (the actual count is resolved
1909 # natively at launch); size by the device-level upper bound instead,1913 # natively at launch); size by the device-level upper bound instead,
1910 # while the launch itself still carries the sentinel.1914 # while the launch itself still carries the sentinel.
@@ -1918,7 +1922,7 @@ def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
1918 log_buffer.view(torch.int32)[::words_per_region] = 01922 log_buffer.view(torch.int32)[::words_per_region] = 0
1919 capacity_u32 = words_per_region - 11923 capacity_u32 = words_per_region - 1
1920 full_args = (*args, log_buffer, capacity_u32)1924 full_args = (*args, log_buffer, capacity_u32)
1921- base_entry(full_args, block_dim, stream)1925+ base_entry(full_args, block_dim, stream, tensor_shapes)
1922 _replay_sanitizer(log_buffer, capacity_u32, sized_dim, build_dir, compiled.kernel_name, compiled.source_file)1926 _replay_sanitizer(log_buffer, capacity_u32, sized_dim, build_dir, compiled.kernel_name, compiled.source_file)
1923 1927 
1924 return entry1928 return entry
@@ -2218,10 +2222,11 @@ class _TileJitKernel:
2218 # A complete positional call is already normalized; skip the bind entirely.2222 # A complete positional call is already normalized; skip the bind entirely.
2219 if kwargs or len(args) != arity:2223 if kwargs or len(args) != arity:
2220 args = self._normalize_launch_args(args, kwargs)2224 args = self._normalize_launch_args(args, kwargs)
2225+ tensor_shapes = [None] * len(args) if self._static_dim_slots() else None
2221 compiled = self._ensure_compiled(2226 compiled = self._ensure_compiled(
2222- args, concrete_key=tk_snapshot, dtype_key=dtype_snapshot, spec=spec2227+ args, concrete_key=tk_snapshot, dtype_key=dtype_snapshot, spec=spec, tensor_shapes=tensor_shapes
2223 )2228 )
2224- _launch(compiled, args, block_dim, stream)2229+ _launch(compiled, args, block_dim, stream, tensor_shapes)
2225 2230 
2226 return launcher2231 return launcher
2227 2232 
@@ -2235,8 +2240,9 @@ class _TileJitKernel:
2235 self._validate_launch_arch()2240 self._validate_launch_arch()
2236 if kwargs_ or len(args) != self._positional_arity:2241 if kwargs_ or len(args) != self._positional_arity:
2237 args = self._normalize_launch_args(args, kwargs_)2242 args = self._normalize_launch_args(args, kwargs_)
2238- compiled = self._ensure_compiled(args, spec=_NO_SPEC)2243+ tensor_shapes = [None] * len(args) if self._static_dim_slots() else None
2239- _launch(compiled, args, _AUTO_BLOCK_DIM, None)2244+ compiled = self._ensure_compiled(args, spec=_NO_SPEC, tensor_shapes=tensor_shapes)
2245+ _launch(compiled, args, _AUTO_BLOCK_DIM, None, tensor_shapes)
2240 2246 
2241 def _validate_launch_arch(self) -> None:2247 def _validate_launch_arch(self) -> None:
2242 from pypto_pro.runtime.platform import get_platform_info2248 from pypto_pro.runtime.platform import get_platform_info
@@ -2298,9 +2304,9 @@ class _TileJitKernel:
2298 def _bind_runtime_args(self, args: tuple):2304 def _bind_runtime_args(self, args: tuple):
2299 """Validate tensor arguments and derive the static specialization signature."""2305 """Validate tensor arguments and derive the static specialization signature."""
2300 bound_signature = self._shape_signature_spec.bind_runtime_args(args)2306 bound_signature = self._shape_signature_spec.bind_runtime_args(args)
2301- python_args = self._shape_signature_spec.python_signature.bind(*args)2307+ # Launch arguments are already in signature order, including defaults.
2302 for tensor_spec in self._shape_signature_spec.tensors:2308 for tensor_spec in self._shape_signature_spec.tensors:
2303- arg = python_args.arguments[tensor_spec.parameter_name]2309+ arg = args[tensor_spec.parameter_index]
2304 if arg is None:2310 if arg is None:
2305 continue2311 continue
2306 if not isinstance(arg, torch.Tensor):2312 if not isinstance(arg, torch.Tensor):
@@ -2320,17 +2326,62 @@ class _TileJitKernel:
2320 return self._shape_signature_spec.bind_static_shapes(static_shapes)2326 return self._shape_signature_spec.bind_static_shapes(static_shapes)
2321 2327 
2322 def _static_dim_slots(self):2328 def _static_dim_slots(self):
2323- """Parameters carrying a StaticDim/StaticTail, i.e. the only ones whose runtime2329+ """Cache (parameter index, minimum rank, STATIC axes, tail start) descriptors.
2324- shape can contribute to ``static_signature``. Computed once; empty for a kernel2330+ 
2325- declared entirely with ``pl.DYNAMIC`` and fixed dims, which lets _ensure_compiled2331+ Only STATIC/ellipsis dimensions contribute to the compiled-cache key. Fixed
2326- skip binding the signature altogether."""2332+ and dynamic dimensions are still checked by the launch entry on cache hits.
2333+ """
2327 slots = self._static_dim_slots_cache2334 slots = self._static_dim_slots_cache
2328 if slots is None:2335 if slots is None:
2329- slots = self._static_dim_slots_cache = tuple(2336+ from pypto_pro.runtime.shape_policy import StaticDim
2330- t.parameter_index for t in self._shape_signature_spec.tensors if t.requires_binding2337+ 
2331- )2338+ slots = []
2339+ for tensor in self._shape_signature_spec.tensors:
2340+ if not tensor.requires_binding:
2341+ continue
2342+ rank = len(tensor.dimensions) - int(tensor.has_ellipsis)
2343+ axes = tuple(axis for axis, dim in enumerate(tensor.dimensions) if isinstance(dim, StaticDim))
2344+ slots.append((tensor.parameter_index, rank, axes, rank if tensor.has_ellipsis else None))
2345+ slots = self._static_dim_slots_cache = tuple(slots)
2332 return slots2346 return slots
2333 2347 
2348+ def _runtime_static_signature(self, args: tuple, tensor_shapes: list | None = None):
2349+ """Extract a cache key without binding; None requests the original error path.
2350+ 
2351+ The caller has normalized positional arguments. Unusual signatures, missing
2352+ tensors, invalid ranks and non-integer static extents fall back to full binding.
2353+ Positivity is checked by full binding on misses and entry on hits.
2354+ tensor_shapes, when provided, carries storage shapes to entry for this call
2355+ only. No tensor addresses or shapes are retained across launches.
2356+ """
2357+ slots = self._static_dim_slots()
2358+ if not slots:
2359+ return ()
2360+ if len(args) != self._positional_arity:
2361+ return None
2362+ signature = []
2363+ for index, rank, axes, tail in slots:
2364+ arg = args[index]
2365+ if not isinstance(arg, torch.Tensor):
2366+ return None
2367+ shape = arg.shape
2368+ if tensor_shapes is not None:
2369+ tensor_shapes[index] = shape
2370+ if (tail is None and len(shape) != rank) or (tail is not None and len(shape) < rank):
2371+ return None
2372+ for axis in axes:
2373+ value = shape[axis]
2374+ if type(value) is not int:
2375+ return None
2376+ signature.append((index, axis, value))
2377+ if tail is not None:
2378+ for axis in range(tail, len(shape)):
2379+ value = shape[axis]
2380+ if type(value) is not int:
2381+ return None
2382+ signature.append((index, axis, value))
2383+ return tuple(signature)
2384+ 
2334 def _resolve_spec_identity(self, concrete_key, dtype_key):2385 def _resolve_spec_identity(self, concrete_key, dtype_key):
2335 """Pack the specialization half of the cache key.2386 """Pack the specialization half of the cache key.
2336 2387 
@@ -2346,7 +2397,7 @@ class _TileJitKernel:
2346 2397 
2347 def _ensure_compiled(2398 def _ensure_compiled(
2348 self, args: tuple, concrete_key: dict | None = None, dtype_key: dict | None = None,2399 self, args: tuple, concrete_key: dict | None = None, dtype_key: dict | None = None,
2349- spec: tuple | None = None,2400+ spec: tuple | None = None, tensor_shapes: list | None = None,
2350 ):2401 ):
2351 """Return the compiled variant for one launch, compiling it on first use.2402 """Return the compiled variant for one launch, compiling it on first use.
2352 2403 
@@ -2362,15 +2413,11 @@ class _TileJitKernel:
2362 spec = self._resolve_spec_identity(concrete_key, dtype_key)2413 spec = self._resolve_spec_identity(concrete_key, dtype_key)
2363 tilingkey_packed, _, _, dtype_hash = spec2414 tilingkey_packed, _, _, dtype_hash = spec
2364 2415 
2365- # A cache hit needs only the key, so binding the full signature -- two2416+ # Hits need only STATIC values, not Signature.bind or BoundDimension objects.
2366- # inspect.Signature.bind calls plus a BoundDimension per declared dimension -- is2417+ # Full binding remains authoritative on misses and for malformed key inputs.
2367- # deferred to the miss path, where codegen actually consumes it.2418+ bound_signature = None
2368- if not self._static_dim_slots():2419+ static_signature = self._runtime_static_signature(args, tensor_shapes)
2369- # No parameter carries a StaticDim/StaticTail, so no dimension can ever be2420+ if static_signature is None:
2370- # marked static and the signature is provably empty for every launch.
2371- bound_signature = None
2372- static_signature = ()
2373- else:
2374 bound_signature = self._bind_runtime_args(args)2421 bound_signature = self._bind_runtime_args(args)
2375 static_signature = bound_signature.static_signature2422 static_signature = bound_signature.static_signature
2376 2423 
@@ -2383,6 +2430,7 @@ class _TileJitKernel:
2383 2430 
2384 if bound_signature is None:2431 if bound_signature is None:
2385 bound_signature = self._bind_runtime_args(args)2432 bound_signature = self._bind_runtime_args(args)
2433+ static_signature = bound_signature.static_signature
2386 return self._compile_variant(concrete_key, spec, bound_signature, static_signature)2434 return self._compile_variant(concrete_key, spec, bound_signature, static_signature)
2387 2435 
2388 def _compile_for_key(self, concrete_key: dict | None = None, dtype_key: dict | None = None):2436 def _compile_for_key(self, concrete_key: dict | None = None, dtype_key: dict | None = None):
@@ -2436,10 +2484,12 @@ class _TileJitKernel:
2436 target = get_jit_compile_config().resolve_kernel_target(2484 target = get_jit_compile_config().resolve_kernel_target(
2437 arch, has_cube=cg.has_cube, has_vector=cg.has_vector,2485 arch, has_cube=cg.has_cube, has_vector=cg.has_vector,
2438 )2486 )
2487+ from pypto import pypto_impl
2488+ 
2489+ config = pypto_impl.CurrentScope().GetAllConfig()
2439 compile_timeout = self._compile_timeout2490 compile_timeout = self._compile_timeout
2440 if compile_timeout is None:2491 if compile_timeout is None:
2441- from pypto import pypto_impl2492+ compile_timeout = config.get("host.compile_timeout", 600)
2442- compile_timeout = pypto_impl.CurrentScope().GetAllConfig().get("host.compile_timeout", 600)
2443 lib_path = _build_jit_so(2493 lib_path = _build_jit_so(
2444 cg,2494 cg,
2445 arch,2495 arch,
@@ -2459,6 +2509,7 @@ class _TileJitKernel:
2459 has_cube=cg.has_cube, has_vector=cg.has_vector,2509 has_cube=cg.has_cube, has_vector=cg.has_vector,
2460 target=target, source_file=cg.source_file,2510 target=target, source_file=cg.source_file,
2461 needs_print_debug=cg.needs_print_debug,2511 needs_print_debug=cg.needs_print_debug,
2512+ enable_exception_dump=config.get("debug.enable_exception_dump", False),
2462 )2513 )
2463 if self._sanitizer:2514 if self._sanitizer:
2464 # Pre-bind the sanitizer wrapper as the launch entry: it allocates2515 # Pre-bind the sanitizer wrapper as the launch entry: it allocates
@@ -145,8 +145,11 @@ _OOB_LOAD_TRIGGER = """\
145from __future__ import annotations145from __future__ import annotations
146import os, sys, logging146import os, sys, logging
147import torch147import torch
148+import pypto
148import pypto_pro.language as pl149import pypto_pro.language as pl
149 150 
151+pypto.set_debug_options(enable_exception_dump=True)
152+ 
150logging.basicConfig(level=logging.INFO, format="%(message)s")153logging.basicConfig(level=logging.INFO, format="%(message)s")
151 154 
152 155 
@@ -237,7 +240,10 @@ from __future__ import annotations
237import os, sys, logging240import os, sys, logging
238from dataclasses import dataclass241from dataclasses import dataclass
239import torch242import torch
243+import pypto
240import pypto_pro.language as pl244import pypto_pro.language as pl
245+ 
246+pypto.set_debug_options(enable_exception_dump=True)
241from pypto_pro.runtime.tilingkey import TilingKeyField247from pypto_pro.runtime.tilingkey import TilingKeyField
242 248 
243logging.basicConfig(level=logging.INFO, format="%(message)s")249logging.basicConfig(level=logging.INFO, format="%(message)s")
@@ -373,8 +379,11 @@ _CUBE_OOB_TRIGGER = """\
373from __future__ import annotations379from __future__ import annotations
374import os, sys, logging380import os, sys, logging
375import torch381import torch
382+import pypto
376import pypto_pro.language as pl383import pypto_pro.language as pl
377 384 
385+pypto.set_debug_options(enable_exception_dump=True)
386+ 
378logging.basicConfig(level=logging.INFO, format="%(message)s")387logging.basicConfig(level=logging.INFO, format="%(message)s")
379 388 
380 389 
@@ -458,8 +467,11 @@ _PTR_SCALAR_OOB_TRIGGER = """\
458from __future__ import annotations467from __future__ import annotations
459import os, sys, logging468import os, sys, logging
460import torch469import torch
470+import pypto
461import pypto_pro.language as pl471import pypto_pro.language as pl
462 472 
473+pypto.set_debug_options(enable_exception_dump=True)
474+ 
463logging.basicConfig(level=logging.INFO, format="%(message)s")475logging.basicConfig(level=logging.INFO, format="%(message)s")
464 476 
465 477 
@@ -74,6 +74,11 @@ def assert_option_type_error(setter, pattern):
74 "CHECK FAILED: ErrCode: F00001! Enum: ExternalError::INVALID_TYPE\n"74 "CHECK FAILED: ErrCode: F00001! Enum: ExternalError::INVALID_TYPE\n"
75 "Option 'debug.runtime_debug_mode' has invalid type. Expected int64, but got string",75 "Option 'debug.runtime_debug_mode' has invalid type. Expected int64, but got string",
76 ),76 ),
77+ (
78+ lambda:pypto.set_debug_options(enable_exception_dump="true"),
79+ "CHECK FAILED: ErrCode: F00001! Enum: ExternalError::INVALID_TYPE\n"
80+ "Option 'debug.enable_exception_dump' has invalid type. Expected bool, but got string",
81+ ),
77 (82 (
78 lambda:pypto.set_debug_options(dump_pass_graph=1),83 lambda:pypto.set_debug_options(dump_pass_graph=1),
79 "CHECK FAILED: ErrCode: F00001! Enum: ExternalError::INVALID_TYPE\n"84 "CHECK FAILED: ErrCode: F00001! Enum: ExternalError::INVALID_TYPE\n"
@@ -602,7 +602,8 @@ def test_packed_dyn_dim_mismatch_with_unpacked_param(launch):
602 launch(specs, args)602 launch(specs, args)
603 603 
604 604 
605-def test_cached_launch_passes_actual_stream_without_python_query(monkeypatch):605+@pytest.mark.parametrize("enable_exception_dump", [False, True])
606+def test_cached_launch_passes_actual_stream_without_python_query(monkeypatch, enable_exception_dump):
606 """Binding and cached launches must use the native topology without consulting Python compile configuration."""607 """Binding and cached launches must use the native topology without consulting Python compile configuration."""
607 lib = _FakeLib()608 lib = _FakeLib()
608 monkeypatch.setattr(_jit, "ctypes", _CtypesProxy(lib))609 monkeypatch.setattr(_jit, "ctypes", _CtypesProxy(lib))
@@ -611,7 +612,9 @@ def test_cached_launch_passes_actual_stream_without_python_query(monkeypatch):
611 streams = [MagicMock(), MagicMock(), _FAKE_STREAM]612 streams = [MagicMock(), MagicMock(), _FAKE_STREAM]
612 _torch_mock.npu.current_stream.side_effect = streams[:2]613 _torch_mock.npu.current_stream.side_effect = streams[:2]
613 target = _jit.KernelTarget("test-compiled-target", 1, 1, True)614 target = _jit.KernelTarget("test-compiled-target", 1, 1, True)
614- compiled = CompiledKernel(lib_path="<fake>", param_specs=[], target=target)615+ compiled = CompiledKernel(
616+ lib_path="<fake>", param_specs=[], target=target, enable_exception_dump=enable_exception_dump,
617+ )
615 dump = importlib.import_module("pypto_pro.runtime.exception_dump")618 dump = importlib.import_module("pypto_pro.runtime.exception_dump")
616 set_dump_info = MagicMock()619 set_dump_info = MagicMock()
617 monkeypatch.setattr(dump, "set_dump_info", set_dump_info)620 monkeypatch.setattr(dump, "set_dump_info", set_dump_info)
@@ -625,7 +628,7 @@ def test_cached_launch_passes_actual_stream_without_python_query(monkeypatch):
625 assert [call[1] for call in lib.call_kernel.calls] == [s._as_parameter_ for s in streams]628 assert [call[1] for call in lib.call_kernel.calls] == [s._as_parameter_ for s in streams]
626 _torch_mock.npu.get_stream_limit.assert_not_called()629 _torch_mock.npu.get_stream_limit.assert_not_called()
627 config_lookup.assert_not_called()630 config_lookup.assert_not_called()
628- assert len(set_dump_info.call_args_list) == 3631+ assert len(set_dump_info.call_args_list) == (3 if enable_exception_dump else 0)
629 assert all(call.args[0] is compiled for call in set_dump_info.call_args_list)632 assert all(call.args[0] is compiled for call in set_dump_info.call_args_list)
630 finally:633 finally:
631 _torch_mock.npu.current_stream.side_effect = None634 _torch_mock.npu.current_stream.side_effect = None
@@ -713,7 +716,10 @@ def test_explicit_stream_validated_once_at_launcher_creation(monkeypatch):
713 monkeypatch.setattr(kernel, "_validate_launch_arch", lambda: None)716 monkeypatch.setattr(kernel, "_validate_launch_arch", lambda: None)
714 monkeypatch.setattr(kernel, "_ensure_compiled", lambda *_args, **_kwargs: None)717 monkeypatch.setattr(kernel, "_ensure_compiled", lambda *_args, **_kwargs: None)
715 launches = []718 launches = []
716- monkeypatch.setattr(_jit, "_launch", lambda _compiled, _args, blocks, target: launches.append((blocks, target)))719+ monkeypatch.setattr(
720+ _jit, "_launch",
721+ lambda _compiled, _args, blocks, target, _tensor_shapes=None: launches.append((blocks, target)),
722+ )
717 # Invalidating the type only after construction detects an accidental hot-path723 # Invalidating the type only after construction detects an accidental hot-path
718 # isinstance check without requiring an NPU to create the test's stream.724 # isinstance check without requiring an NPU to create the test's stream.
719 monkeypatch.setattr(_torch_mock.npu, "Stream", None)725 monkeypatch.setattr(_torch_mock.npu, "Stream", None)
@@ -167,7 +167,9 @@ def test_shared_library_and_caller_use_the_same_resolved_target(monkeypatch, tmp
167 assert "probe<<<blockDim, 16384, stream>>>" in caller167 assert "probe<<<blockDim, 16384, stream>>>" in caller
168 168 
169 169 
170-def test_compilation_preserves_target_for_cached_launch_and_debug(monkeypatch, tmp_path):170+@pytest.mark.parametrize("debug_options", [{}, {"debug.enable_exception_dump": False},
171+ {"debug.enable_exception_dump": True}])
172+def test_compilation_preserves_target_for_cached_launch_and_debug(monkeypatch, tmp_path, debug_options):
171 """The compiled object must retain the exact descriptor selected when its binary was built."""173 """The compiled object must retain the exact descriptor selected when its binary was built."""
172 config = get_jit_compile_config()174 config = get_jit_compile_config()
173 resolve = MagicMock(wraps=config.resolve_kernel_target)175 resolve = MagicMock(wraps=config.resolve_kernel_target)
@@ -183,12 +185,19 @@ def test_compilation_preserves_target_for_cached_launch_and_debug(monkeypatch, t
183 monkeypatch.setattr(jit, "_codegen", lambda *_args, **_kwargs: cg)185 monkeypatch.setattr(jit, "_codegen", lambda *_args, **_kwargs: cg)
184 build = MagicMock(return_value="/tmp/test-kernel.so")186 build = MagicMock(return_value="/tmp/test-kernel.so")
185 monkeypatch.setattr(jit, "_build_jit_so", build)187 monkeypatch.setattr(jit, "_build_jit_so", build)
188+ from pypto import pypto_impl
189+ 
190+ scope = MagicMock()
191+ scope.GetAllConfig.return_value = debug_options
192+ monkeypatch.setattr(pypto_impl, "CurrentScope", lambda: scope)
186 kernel = jit._TileJitKernel(lambda: None, arch=NpuArch.DAV_3510, compile_timeout=30)193 kernel = jit._TileJitKernel(lambda: None, arch=NpuArch.DAV_3510, compile_timeout=30)
187 monkeypatch.setattr(kernel, "to_kernel_def", lambda *_args, **_kwargs: None)194 monkeypatch.setattr(kernel, "to_kernel_def", lambda *_args, **_kwargs: None)
188 compiled = kernel._compile_variant(None, (None, None, None, None), None, ())195 compiled = kernel._compile_variant(None, (None, None, None, None), None, ())
189 resolve.assert_called_once_with(NpuArch.DAV_3510, has_cube=True, has_vector=True)196 resolve.assert_called_once_with(NpuArch.DAV_3510, has_cube=True, has_vector=True)
190 assert compiled.target is build.call_args.kwargs["target"]197 assert compiled.target is build.call_args.kwargs["target"]
191 assert compiled.target is config.kernel_targets[NpuArch.DAV_3510]["cube_vec"]198 assert compiled.target is config.kernel_targets[NpuArch.DAV_3510]["cube_vec"]
199+ assert compiled.enable_exception_dump is debug_options.get("debug.enable_exception_dump", False)
200+ scope.GetAllConfig.assert_called_once_with()
192 201 
193 202 
194def test_debug_command_reuses_compiled_target_without_resolving(monkeypatch, tmp_path):203def test_debug_command_reuses_compiled_target_without_resolving(monkeypatch, tmp_path):