-
Notifications
You must be signed in to change notification settings - Fork 449
[Enhancement][Tool] Tree-style pretty ASTPrinter #1468
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,23 +1,102 @@ | ||
| from tvm import tir | ||
| from tvm.tir import PrimFunc | ||
| from tvm.tir import PyStmtExprVisitor, PrimFunc, Stmt | ||
|
|
||
| from tvm.tir.transform import prim_func_pass | ||
| from tvm.tir.stmt_functor import ir_transform | ||
|
|
||
|
|
||
| _child_fields = ["body", "block", "seq"] | ||
|
|
||
| _stmt_line_limit = 140 | ||
| _middle_connector = "├── " | ||
| _last_connector = "└── " | ||
|
|
||
| _normal_indent = " " * 4 | ||
| _seq_middle_indent = "|" + " " * 3 | ||
SiriusNEO marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| @tir.functor.visitor | ||
| class _ASTPrintVisitor(PyStmtExprVisitor): | ||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self.indent: list[str] = [] | ||
|
|
||
| def print_with_clip(self, s: str) -> None: | ||
| if len(s) > _stmt_line_limit: | ||
| s = s[:_stmt_line_limit] + "..." | ||
| print("".join(self.indent) + s) | ||
|
|
||
| def print_stmt_brief(self, stmt: Stmt, prefix: str) -> None: | ||
| stmt_script = repr(stmt).splitlines()[0].split(" ")[0].strip() | ||
| self.print_with_clip(prefix + f"{stmt.__class__.__name__}: " + stmt_script) | ||
|
|
||
| def visit_stmt(self, stmt: Stmt) -> None: | ||
| child_field_name: str = "" | ||
|
|
||
| field_keys = stmt.__class__.__dict__.keys() | ||
| # Filter out private/built-in fields. | ||
| field_keys = [key for key in field_keys if not key.startswith("_")] | ||
|
|
||
| for idx, key in enumerate(field_keys): | ||
| # For child fields, we'll handle them specially below instead of printing them in current line. | ||
| if key in _child_fields: | ||
| child_field_name = key | ||
SiriusNEO marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| continue | ||
|
|
||
| value = getattr(stmt, key, None) | ||
| if value is None: | ||
| continue | ||
| # Try to get its script representation. | ||
| value = repr(value) | ||
|
|
||
| is_last_child = idx == len(field_keys) - 1 and not child_field_name | ||
| # Add tree-like connector | ||
| connector = _last_connector if is_last_child else _middle_connector | ||
|
|
||
| # Every member | ||
| self.print_with_clip(connector + f"{key}: {value}") | ||
|
|
||
| # Handle child fields | ||
| if child_field_name and hasattr(stmt, child_field_name): | ||
| child = getattr(stmt, child_field_name) | ||
|
|
||
| if child_field_name != "seq": | ||
| prefix = _last_connector + f"{child_field_name}: " | ||
| self.print_stmt_brief(child, prefix) | ||
| self.indent.append(_normal_indent) | ||
| self.visit_stmt(child) | ||
| self.indent.pop() | ||
| else: | ||
| # Special output format for SeqStmt | ||
| for i, child_node in enumerate(child): | ||
| is_last_child = i == len(child) - 1 | ||
| prefix = (_last_connector if is_last_child else _middle_connector) + f"seq{i}: " | ||
| self.print_stmt_brief(child_node, prefix) | ||
| self.indent.append(_normal_indent if is_last_child else _seq_middle_indent) | ||
| self.visit_stmt(child_node) | ||
| self.indent.pop() | ||
|
|
||
|
|
||
| def ASTPrinter(): | ||
SiriusNEO marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """ | ||
| Print the AST of a given tilelang module for debugging. | ||
| """ | ||
| A visitor pass that renders the TileLang AST hierarchy in a visual tree format. | ||
|
|
||
| def pre_visit(statement: tir.Stmt) -> None: | ||
| """ | ||
| Pre-order visitor to print all visited statements. | ||
| """ | ||
| Comparing with TL script, this printer is more suitable for debugging | ||
| and understanding the internal structure of TensorIR, like the class structure of | ||
| each node and their connections. | ||
|
|
||
| print(f"Visiting statement: {type(statement)}, {statement}") | ||
| This printer generates a human-readable, tree-structured representation of the | ||
| Abstract Syntax Tree (AST). It uses ASCII/Unicode connectors to visualize | ||
| parent-child relationships, making it easier to inspect nested structures | ||
| (e.g., loops, blocks, scopes) and verify compiler transformations. | ||
| """ | ||
|
|
||
| def pass_fn(func: PrimFunc, mod, ctx) -> PrimFunc: | ||
| new_body = ir_transform(func.body, pre_visit, None) | ||
| return func.with_body(new_body) | ||
| print(f"PrimFunc(params={func.params}, ret_type={func.ret_type}, buffer_map={func.buffer_map}, attrs={func.attrs})") | ||
| func_body_prefix = _last_connector + "body=" | ||
| visitor = _ASTPrintVisitor() | ||
| visitor.print_stmt_brief(func.body, func_body_prefix) | ||
| visitor.visit_stmt(func.body) | ||
| visitor.indent.append(_normal_indent) | ||
SiriusNEO marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return func | ||
|
|
||
| return prim_func_pass(pass_fn, opt_level=0) | ||
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
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.
The new tree printer only recurses into fields listed in
_child_fields(currently justbody,block,seq). TIR statement nodes likeIfThenElseusethen_case/else_case, andBlockcan haveinit, which are statements but won’t be visited or expanded, so whole subtrees disappear from the tree output. This is a regression from the previousir_transformtraversal, and it can mislead debugging whenever kernels include conditionals or other statement children not namedbody/block/seq. Consider expanding the child field list or delegating traversal toPyStmtExprVisitorfor all statement children.Useful? React with 👍 / 👎.