You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "tqchen (via GitHub)" <gi...@apache.org> on 2026/02/28 22:47:28 UTC
[PR] [TVMScript] Fix PEP 563 closure variable resolution [tvm]
tqchen opened a new pull request, #18856:
URL: https://github.com/apache/tvm/pull/18856
With `from __future__ import annotations`, Python stores annotations as strings
and does not capture annotation-only variables in `__closure__`. This broke
TVMScript when buffer shapes/dtypes referenced closure variables.
Fix: wrap `extra_vars` in a `collections.ChainMap` with snapshots of all live
caller-frame locals (from `inspect.stack()`) as fallback layers in both
`tir/entry.py` (`prim_func`) and `ir/entry.py` (`ir_module`). The `ir_module`
function now also captures `outer_stack = inspect.stack()` at its entry point,
mirroring the existing pattern in `prim_func`. Lookup falls back to frame locals
only on cache miss, preserving existing behavior for non-PEP-563 code.
Add `tests/python/tvmscript/test_tvmscript_pep563_closure.py` (requires
`from __future__ import annotations` at the top) covering closure variables in
buffer shapes, dtypes, nested scopes, ir_module, and mixed annotation+body use.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [TVMScript] Fix PEP 563 closure variable resolution [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #18856:
URL: https://github.com/apache/tvm/pull/18856#discussion_r2867986588
##########
python/tvm/script/parser/ir/entry.py:
##########
@@ -18,6 +18,7 @@
"""The entry point of TVM parser for ir module."""
import inspect
+from collections import ChainMap
from collections.abc import Callable
Review Comment:

Per PEP 8, standard library imports should be sorted alphabetically. `collections` should come before `inspect`.
```suggestion
from collections import ChainMap
from collections.abc import Callable
import inspect
```
<details>
<summary>References</summary>
1. PEP 8 suggests sorting standard library imports alphabetically. <sup>([link](http://console.cloud.google.com/gemini-code-assist/agents-tools))</sup>
</details>
##########
tests/python/tvmscript/test_tvmscript_pep563_closure.py:
##########
@@ -0,0 +1,161 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Test TVMScript with PEP 563 (from __future__ import annotations).
+
+IMPORTANT: The `from __future__ import annotations` import below is the
+test condition itself, because we need to test compatibility with it.
+"""
+from __future__ import annotations
+
+import tvm
+import tvm.testing
+from tvm.script import ir as I
+from tvm.script import tir as T
+
+
+def _normalize(func):
+ """Strip the global_symbol so function names do not affect structural equality."""
+ return func.with_attr("global_symbol", "")
+
+
+def test_prim_func_closure_shape():
+ """Closure variable used in Buffer shape annotation."""
+
+ def f(M=16):
+ @T.prim_func
+ def func(A: T.Buffer((M,), "float32")):
+ T.evaluate(0)
+
+ return func
+
+ @T.prim_func
+ def expected_16(A: T.Buffer((16,), "float32")):
+ T.evaluate(0)
+
+ @T.prim_func
+ def expected_32(A: T.Buffer((32,), "float32")):
+ T.evaluate(0)
+
+ tvm.ir.assert_structural_equal(_normalize(f(16)), _normalize(expected_16))
+ tvm.ir.assert_structural_equal(_normalize(f(32)), _normalize(expected_32))
+
+
+def test_prim_func_closure_dtype():
+ """Closure variable used as Buffer dtype."""
+
+ def f(dtype="float32"):
+ @T.prim_func
+ def func(A: T.Buffer((16,), dtype)):
+ T.evaluate(0)
+
+ return func
+
+ @T.prim_func
+ def expected_f32(A: T.Buffer((16,), "float32")):
+ T.evaluate(0)
+
+ @T.prim_func
+ def expected_f16(A: T.Buffer((16,), "float16")):
+ T.evaluate(0)
+
+ tvm.ir.assert_structural_equal(_normalize(f("float32")), _normalize(expected_f32))
+ tvm.ir.assert_structural_equal(_normalize(f("float16")), _normalize(expected_f16))
+
+
+def test_prim_func_nested_closure():
+ """Variables from enclosing scope active on the call stack (grandparent frame fallback).
+
+ With PEP 563, closure-only variables are missing from __closure__ unless they
+ appear in the function body. The ChainMap fallback walks the live call stack,
+ so this works when the enclosing frames are still active (outer calls middle
+ which applies the decorator, keeping outer's frame alive on the stack).
+ """
+
+ def outer(M=16):
+ def middle(N=8):
+ @T.prim_func
+ def func(A: T.Buffer((M, N), "float32")):
+ T.evaluate(0)
+
+ return func
+
+ return middle()
+
+ @T.prim_func
+ def expected_16_8(A: T.Buffer((16, 8), "float32")):
+ T.evaluate(0)
+
+ @T.prim_func
+ def expected_32_8(A: T.Buffer((32, 8), "float32")):
+ T.evaluate(0)
+
+ tvm.ir.assert_structural_equal(_normalize(outer(16)), _normalize(expected_16_8))
+ tvm.ir.assert_structural_equal(_normalize(outer(32)), _normalize(expected_32_8))
+
+
+def test_ir_module_closure():
+ """Closure variable in @I.ir_module class method."""
+
+ def f(M=16):
+ @I.ir_module
+ class Mod:
+ @T.prim_func
+ def main(A: T.Buffer((M,), "float32")):
+ T.evaluate(0)
+
+ return Mod
+
+ @T.prim_func
+ def expected_16(A: T.Buffer((16,), "float32")):
+ T.evaluate(0)
+
+ @T.prim_func
+ def expected_32(A: T.Buffer((32,), "float32")):
+ T.evaluate(0)
+
+ tvm.ir.assert_structural_equal(
+ f(16)["main"], expected_16.with_attr("global_symbol", "main")
+ )
+ tvm.ir.assert_structural_equal(
+ f(32)["main"], expected_32.with_attr("global_symbol", "main")
+ )
Review Comment:

For consistency with the other tests in this file, consider using the `_normalize` helper function to strip the `global_symbol` attribute before comparison. This makes the test's intent clearer and aligns with the pattern used in other test cases here.
```python
tvm.ir.assert_structural_equal(_normalize(f(16)["main"]), _normalize(expected_16))
tvm.ir.assert_structural_equal(_normalize(f(32)["main"]), _normalize(expected_32))
```
##########
python/tvm/script/parser/tir/entry.py:
##########
@@ -17,6 +17,7 @@
"""The entry point of TVM parser for tir."""
import inspect
+from collections import ChainMap
from collections.abc import Callable
Review Comment:

Per PEP 8, standard library imports should be sorted alphabetically. `collections` should come before `inspect`.
```suggestion
from collections import ChainMap
from collections.abc import Callable
import inspect
```
<details>
<summary>References</summary>
1. PEP 8 suggests sorting standard library imports alphabetically. <sup>([link](http://console.cloud.google.com/gemini-code-assist/agents-tools))</sup>
</details>
##########
python/tvm/script/parser/ir/entry.py:
##########
@@ -46,14 +47,24 @@ def ir_module(mod: type | None = None, check_well_formed: bool = True) -> IRModu
The parsed ir module.
"""
+ # need to capture this var outside the wrapper because the wrapper
+ # adds to the stack
+ outer_stack = inspect.stack()
+
def decorator_wrapper(mod):
if not inspect.isclass(mod):
raise TypeError(f"Expect a class, but got: {mod}")
# Check BasePyModule inheritance
base_py_module_inherited = any(base.__name__ == "BasePyModule" for base in mod.__bases__)
- m = parse(mod, utils.inspect_class_capture(mod), check_well_formed=check_well_formed)
+ extra_vars = utils.inspect_class_capture(mod)
+ # Lazy fallback to caller frame locals for PEP 563 compatibility.
+ # With `from __future__ import annotations`, variables used only
+ # in annotations are not captured in __closure__. ChainMap defers
+ # lookup to caller locals only on cache miss.
+ extra_vars = ChainMap(extra_vars, *[f.frame.f_locals for f in outer_stack[1:]])
Review Comment:

This logic for creating a `ChainMap` with caller frame locals is duplicated in `python/tvm/script/parser/tir/entry.py`. To improve maintainability, consider extracting this logic into a common helper function in a shared utility module (e.g., `tvm.script.parser.utils`).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [TVMScript] Fix PEP 563 closure variable resolution [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #18856:
URL: https://github.com/apache/tvm/pull/18856#issuecomment-3978293302
## Summary of Changes
Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request resolves a critical compatibility issue with Python's PEP 563 (`from __future__ import annotations`) in TVMScript. The changes ensure that TVMScript can correctly parse and resolve variables used within type annotations, even when those variables are part of an outer scope's closure and not explicitly captured by Python's default closure mechanism. This significantly improves the robustness of TVMScript when used with modern Python features.
### Highlights
* **PEP 563 Closure Variable Resolution**: Addressed an issue where TVMScript failed to resolve closure variables used in annotations when `from __future__ import annotations` was enabled, as Python does not capture annotation-only variables in `__closure__` under this future import.
* **Enhanced Variable Capture Mechanism**: Implemented a fix by wrapping `extra_vars` in a `collections.ChainMap`. This `ChainMap` includes snapshots of all live caller-frame locals (obtained via `inspect.stack()`) as fallback layers, ensuring proper variable lookup for both `prim_func` and `ir_module`.
* **New Test Coverage**: Introduced a new test file, `test_tvmscript_pep563_closure.py`, to validate the fix across various scenarios, including closure variables in buffer shapes, dtypes, nested scopes, `ir_module` contexts, and mixed annotation/body usage.
🧠**New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
<details>
<summary><b>Changelog</b></summary>
* **python/tvm/script/parser/ir/entry.py**
* Imported `collections.ChainMap` for enhanced variable lookup.
* Captured the `inspect.stack()` at the entry point of the `ir_module` decorator.
* Modified `extra_vars` to use `ChainMap` for lazy fallback to caller frame locals, addressing PEP 563 compatibility.
* **python/tvm/script/parser/tir/entry.py**
* Imported `collections.ChainMap` for enhanced variable lookup.
* Modified `extra_vars` to use `ChainMap` for lazy fallback to caller frame locals, addressing PEP 563 compatibility.
* **tests/python/tvmscript/test_tvmscript_pep563_closure.py**
* Added a new test file to verify correct closure variable resolution with `from __future__ import annotations`.
* Included tests for `prim_func` with closure variables in buffer shapes and dtypes.
* Added tests for nested closures and `ir_module` closure variable usage.
* Included a regression test for mixed annotation and body usage of closure variables.
</details>
<details>
<summary><b>Using Gemini Code Assist</b></summary>
<br>
The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
<b>Invoking Gemini</b>
You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
Feature | Command | Description
--- | --- | ---
Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help | `/gemini help` | Displays a list of available commands.
<b>Customization</b>
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
<b>Limitations & Feedback</b>
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
<b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
</details>
[^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [TVMScript] Fix PEP 563 closure variable resolution [tvm]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen merged PR #18856:
URL: https://github.com/apache/tvm/pull/18856
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org