-
Notifications
You must be signed in to change notification settings - Fork 73
Add pto.func helpers #952
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
and0d0
wants to merge
15
commits into
hw-native-sys:main
Choose a base branch
from
and0d0:946-func_extend
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add pto.func helpers #952
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
d35be55
Add reusable pto.func helpers
2e224b1
Add pto.func chain probe artifacts
b5afdbc
Refine pto.func docs and probe header
4b984ca
Fix pto.func license header
a2c4b95
Require explicit pto.func return types
822ecea
Fix mte cache ctl FileCheck labels
0f0698a
Reject early returns in rewritten control flow
25b8bf6
Preserve func helper surface templates
41a33a0
Support postponed annotations in pto.func
4a329e1
Relax pto.func partition metadata test
12ffb4b
Stabilize pto.func helper identity
e65c0ad
Preserve helper ABI cache key
5d1674c
Support older code object metadata
35d9040
Support const_expr pto.func parameters
856a819
Keep bare returns compatible in AST rewrite
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| # Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| # This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| # CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| # Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| # See LICENSE in the root of the software repository for the full text of the License. | ||
| """Shared cache-signature helpers for PTODSL tracing frontends.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
|
|
||
| def function_cache_signature(fn): | ||
| """Return one stable cache signature for a Python function body.""" | ||
| code = fn.__code__ | ||
| return ( | ||
| "python-function", | ||
| code.co_filename, | ||
| code.co_firstlineno, | ||
| getattr(code, "co_qualname", fn.__qualname__), | ||
| code.co_argcount, | ||
| code.co_posonlyargcount, | ||
| code.co_kwonlyargcount, | ||
| code.co_names, | ||
| code.co_consts, | ||
| code.co_code, | ||
| ) | ||
|
|
||
|
|
||
| def closure_cache_signature(fn): | ||
| """Return one stable cache signature for the closure state captured by *fn*.""" | ||
| try: | ||
| import inspect | ||
|
|
||
| closure_vars = inspect.getclosurevars(fn) | ||
| except TypeError: | ||
| return () | ||
| return tuple( | ||
| (name, cache_signature_atom(value)) | ||
| for name, value in sorted(closure_vars.nonlocals.items()) | ||
| ) | ||
|
|
||
|
|
||
| def cache_signature_atom(value): | ||
| """Return one hashable cache-signature atom for arbitrary captured values.""" | ||
| cache_signature = getattr(value, "__ptodsl_cache_signature__", None) | ||
| if callable(cache_signature): | ||
| return ("ptodsl-cache-signature", cache_signature_atom(cache_signature())) | ||
| try: | ||
| hash(value) | ||
| except TypeError: | ||
| if isinstance(value, dict): | ||
| items = ( | ||
| (cache_signature_atom(key), cache_signature_atom(item)) | ||
| for key, item in value.items() | ||
| ) | ||
| return ("dict", tuple(sorted(items, key=repr))) | ||
| if isinstance(value, (list, tuple)): | ||
| return ( | ||
| type(value).__name__, | ||
| tuple(cache_signature_atom(item) for item in value), | ||
| ) | ||
| if isinstance(value, set): | ||
| return ( | ||
| "set", | ||
| tuple(sorted((cache_signature_atom(item) for item in value), key=repr)), | ||
| ) | ||
| return (type(value).__name__, repr(value)) | ||
| return value | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "cache_signature_atom", | ||
| "closure_cache_signature", | ||
| "function_cache_signature", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| # Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| # This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| # CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| # Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| # See LICENSE in the root of the software repository for the full text of the License. | ||
| """``@pto.func`` decorator and reusable callable handle.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from functools import update_wrapper | ||
| import inspect | ||
| import typing | ||
|
|
||
| from ._ast_rewrite import rewrite_jit_function | ||
| from ._cache_signature import cache_signature_atom, closure_cache_signature, function_cache_signature | ||
| from ._tracing import current_runtime | ||
|
|
||
| _RETURNS_UNSET = object() | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class FuncSpec: | ||
| """Declarative metadata for a rewrite-capable reusable PTODSL callable.""" | ||
|
|
||
| symbol_name: str | ||
|
|
||
|
|
||
| class FuncTemplate: | ||
| """Callable decorated PTODSL helper surface.""" | ||
|
|
||
| def __init__(self, spec: FuncSpec, py_fn, *, ast_rewrite: bool = True, returns=_RETURNS_UNSET): | ||
| self.spec = spec | ||
| self.py_fn = py_fn | ||
| self._ast_rewrite = ast_rewrite | ||
| self.signature = inspect.signature(py_fn) | ||
| try: | ||
| self.type_hints = typing.get_type_hints(py_fn) | ||
| except Exception as exc: | ||
| if _has_annotations(self.signature): | ||
| raise TypeError( | ||
| f"failed to resolve @pto.func annotations for {py_fn.__qualname__!r}" | ||
| ) from exc | ||
| self.type_hints = {} | ||
| if returns is not _RETURNS_UNSET: | ||
| self.declared_returns = returns | ||
| elif "return" in self.type_hints: | ||
| self.declared_returns = self.type_hints["return"] | ||
| elif self.signature.return_annotation is not inspect.Signature.empty: | ||
| self.declared_returns = self.signature.return_annotation | ||
| else: | ||
| raise TypeError( | ||
| "@pto.func helpers must explicitly declare return types with " | ||
| "@pto.func(returns=...) or a Python return annotation; use " | ||
| "returns=None or -> None for helpers that do not return values" | ||
| ) | ||
| update_wrapper(self, py_fn) | ||
|
|
||
| def emit_body(self, *args, **kwargs): | ||
| """Emit this helper body into the currently active trace.""" | ||
| py_fn = ( | ||
| rewrite_jit_function(self.py_fn, reject_bare_returns=True) | ||
| if self._ast_rewrite | ||
| else self.py_fn | ||
| ) | ||
| return py_fn(*args, **kwargs) | ||
|
|
||
| def __call__(self, *args, **kwargs): | ||
| runtime = current_runtime() | ||
| if runtime is None: | ||
| raise RuntimeError( | ||
| "@pto.func helpers may only be called while tracing a compatible PTODSL kernel" | ||
| ) | ||
| return runtime.dispatch_ptodsl_func_call(self, *args, **kwargs) | ||
|
|
||
| def __ptodsl_cache_signature__(self): | ||
| return ( | ||
| type(self).__name__, | ||
| self.spec.symbol_name, | ||
| function_cache_signature(self.py_fn), | ||
| self._ast_rewrite, | ||
| cache_signature_atom(self.declared_returns), | ||
| closure_cache_signature(self.py_fn), | ||
| ) | ||
|
|
||
|
|
||
| def func(fn=None, *, name: str | None = None, ast_rewrite: bool = True, returns=_RETURNS_UNSET): | ||
| """Decorate a Python function as a reusable PTODSL callable helper.""" | ||
|
|
||
| def decorator(py_fn): | ||
| return FuncTemplate( | ||
| FuncSpec(symbol_name=name or py_fn.__name__), | ||
| py_fn, | ||
| ast_rewrite=ast_rewrite, | ||
| returns=returns, | ||
| ) | ||
|
|
||
| if fn is not None: | ||
| return decorator(fn) | ||
| return decorator | ||
|
|
||
|
|
||
| def _has_annotations(signature: inspect.Signature) -> bool: | ||
| if signature.return_annotation is not inspect.Signature.empty: | ||
| return True | ||
| return any( | ||
| param.annotation is not inspect.Parameter.empty | ||
| for param in signature.parameters.values() | ||
| ) | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "FuncSpec", | ||
| "FuncTemplate", | ||
| "func", | ||
| ] | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
当用户在定义
@pto.func的 Python 文件中启用了from __future__ import annotations时,inspect.signature(py_fn)返回的参数和返回值注解将是字符串(例如'pto.i32'),而不是实际的类型对象。这会导致后续的类型解析和缓存签名生成失败。\n\n建议使用标准库中的typing.get_type_hints来安全地解析和获取真实的类型注解,从而完美兼容from __future__ import annotations。