Skip to content

feat(ops): add B03 tri and gather operators - #2184

Open
hashiqiqixian wants to merge 20 commits into
hw-native-sys:mainfrom
hashiqiqixian:feat/ptoas-b03-tri-gather
Open

feat(ops): add B03 tri and gather operators#2184
hashiqiqixian wants to merge 20 commits into
hw-native-sys:mainfrom
hashiqiqixian:feat/ptoas-b03-tri-gather

Conversation

@hashiqiqixian

Copy link
Copy Markdown
Contributor

Summary

  • complete B03 support for pto.ttri, pto.tgatherb, and canonical pto.mgather
  • add C++ IR/type contracts, PTO codegen, Python IR/DSL exports, bilingual docs, UT, and same-name ST
  • define tgatherb with the current 32-byte block-offset semantics and row/column valid-shape tails
  • support mgather row/elem coalesce, valid shapes, signed/unsigned payload dtypes, and printed-IR integer enum round trips
  • restore Tile/GlobalTensor wrapper operands after PTOAS lowers partition-view MGATHER to the legacy raw-pointer ABI
  • migrate the historical B03 assets (ee7b686a, 64c6b160, 711e45c7, 7ec0e5f2) and remove the stale pto.tmgather spelling

This branch is based directly on current main and contains no B02 changes, so B02 and B03 can be reviewed and squash-merged independently.

Validation

  • serial build and offline editable install on AArch64: passed
  • affected UT: 724 passed
  • Ruff check/format and clang-format checks: passed
  • A2/A3 hardware: 27/27 passed in one low-concurrency task-submit batch (task_20260728_073610_14453233363, device 1)
    • ttri: 10/10 pytest items, 9 unique device programs
    • tgatherb: 8/8 pytest items, 7 unique device programs
    • mgather: 9/9 pytest items, 8 unique device programs
  • saved PTO contains only pto.ttri, pto.tgatherb, and pto.mgather; legacy pto.tmgather is absent
  • PTOAS: v0.53; A5 hardware validation remains pending

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: aa372688-3f45-4b15-8908-a051d088b3e6

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds tile.tri, tile.gatherb, and tile.mgather through IR validation, Python APIs, PTO codegen, PTOAS preprocessing, runtime tests, and English/Chinese documentation.

Changes

Tile operation support

Layer / File(s) Summary
IR type contracts
src/ir/op/tile_ops/...
Registers the three operations with dtype, shape, valid-shape, offset, index, and coalesce validation.
Python APIs and exports
python/pypto/ir/op/tile_ops.py, python/pypto/language/...
Adds wrappers and public exports for tri, gatherb, and mgather.
PTO lowering and preprocessing
src/backend/common/..., python/pypto/backend/_ptoas_preprocess.py
Emits canonical PTO operations, adds mgather partition lowering, assigns layouts, and restores MGATHER wrapper operands.
Tests and documentation
tests/..., docs/...
Adds IR, codegen, preprocessing, and onboard runtime coverage, plus updated operation references and PTOAS status matrices.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PythonAPI
  participant TileIR
  participant PTOCodegen
  participant RuntimeTests
  PythonAPI->>TileIR: create tri, gatherb, or mgather
  TileIR->>PTOCodegen: validate and infer tile result
  PTOCodegen->>RuntimeTests: emit canonical PTO operation
  RuntimeTests->>RuntimeTests: execute and compare expected output
Loading

Poem

A rabbit hops through tiles so bright,
Triangular masks align just right.
Blocks gather, rows coalesce too,
PTO paths now carry them through.
Tests thump softly: all paths true!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.51% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main B03 tri and gather operator additions.
Description check ✅ Passed The description clearly matches the changeset and covers the new ops, backend work, docs, tests, and validation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d37d427536

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/ir/op/tile_ops/memory.cpp

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
python/pypto/language/op/tile_ops.py (1)

2689-2698: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

mem: Tensor type hint is narrower than the IR contract.

DeduceTileMgatherType accepts TensorType or DistributedTensorType (via AsTensorTypeLike), same as tile.load. Sibling op mscatter in this file already uses a generic _TensorT for this reason. Typing mem as plain Tensor here would make static type checkers flag legitimate DistributedTensor call sites even though the call itself works at runtime.

♻️ Proposed fix
-def mgather(mem: Tensor, idx: Tile, coalesce: str | int = "row") -> Tile:
+def mgather(mem: _TensorT, idx: Tile, coalesce: str | int = "row") -> Tile:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@python/pypto/language/op/tile_ops.py` around lines 2689 - 2698, Update the
mgather function’s mem parameter annotation from Tensor to the generic _TensorT
type used by mscatter, while preserving the existing unwrap and IR-call behavior
so both Tensor and DistributedTensor inputs are accepted by static type
checkers.
python/pypto/backend/_ptoas_preprocess.py (1)

33-50: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Skip the whole-file identifier/alias scan when no MGATHER call is present.

_restore_mgather_wrapper_operands unconditionally builds aliases/identifier_occurrences by scanning every line of every PTOAS output file, even though most generated kernels don't use tile.mgather at all. A cheap early-exit avoids this cost on the common path.

⚡ Proposed fix
 def _restore_mgather_wrapper_operands(content: str) -> str:
     """..."""
+    if "MGATHER" not in content:
+        return content
     lines = content.splitlines(keepends=True)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@python/pypto/backend/_ptoas_preprocess.py` around lines 33 - 50, Update
_restore_mgather_wrapper_operands to detect the absence of an MGATHER call and
return content before building aliases or identifier_occurrences. Perform this
lightweight check before the whole-file line scan, while preserving the existing
rewrite behavior when an MGATHER call is present.
src/ir/op/tile_ops/memory.cpp (1)

1053-1062: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Coalesce-mode 0/1 mapping is duplicated across IR and backend with no shared enum. Both sites independently encode "0=row, 1=elem" as raw literals; the codebase's own ir::AtomicType (shared between DeduceTileStoreType and its store codegen) is the established pattern for this exact situation.

  • src/ir/op/tile_ops/memory.cpp#L1053-L1062: move kMgatherCoalesceRow/kMgatherCoalesceElem out of the anonymous namespace into a small shared header enum (e.g. enum class CoalesceMode { kRow = 0, kElem = 1 }), mirroring AtomicType.
  • src/backend/common/pto_ops_memory.cpp#L350-L353: replace the raw op->GetKwarg<int>("coalesce", 0) + coalesce == 1 ? "elem" : "row" ternary with the shared enum from the header above, instead of re-hardcoding the mapping.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ir/op/tile_ops/memory.cpp` around lines 1053 - 1062, Replace the
duplicated coalesce-mode literals with a shared enum, following the existing
ir::AtomicType pattern. In src/ir/op/tile_ops/memory.cpp lines 1053-1062, move
the row/element constants from the anonymous namespace into a shared header enum
such as CoalesceMode; in src/backend/common/pto_ops_memory.cpp lines 350-353,
use that enum for the default and comparison instead of raw integer mapping.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@python/pypto/backend/_ptoas_preprocess.py`:
- Around line 33-50: Update _restore_mgather_wrapper_operands to detect the
absence of an MGATHER call and return content before building aliases or
identifier_occurrences. Perform this lightweight check before the whole-file
line scan, while preserving the existing rewrite behavior when an MGATHER call
is present.

In `@python/pypto/language/op/tile_ops.py`:
- Around line 2689-2698: Update the mgather function’s mem parameter annotation
from Tensor to the generic _TensorT type used by mscatter, while preserving the
existing unwrap and IR-call behavior so both Tensor and DistributedTensor inputs
are accepted by static type checkers.

In `@src/ir/op/tile_ops/memory.cpp`:
- Around line 1053-1062: Replace the duplicated coalesce-mode literals with a
shared enum, following the existing ir::AtomicType pattern. In
src/ir/op/tile_ops/memory.cpp lines 1053-1062, move the row/element constants
from the anonymous namespace into a shared header enum such as CoalesceMode; in
src/backend/common/pto_ops_memory.cpp lines 350-353, use that enum for the
default and comparison instead of raw integer mapping.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7022cf95-b628-4ead-8a32-d5087805f99e

📥 Commits

Reviewing files that changed from the base of the PR and between 478ddad and d37d427.

📒 Files selected for processing (19)
  • docs/en/dev/ir/05-operators.md
  • docs/en/dev/ptoas-op-status.md
  • docs/zh-cn/dev/ir/05-operators.md
  • docs/zh-cn/dev/ptoas-op-status.md
  • python/pypto/backend/_ptoas_preprocess.py
  • python/pypto/ir/op/tile_ops.py
  • python/pypto/language/__init__.py
  • python/pypto/language/op/__init__.py
  • python/pypto/language/op/tile_ops.py
  • src/backend/common/pto_ops_elementwise.cpp
  • src/backend/common/pto_ops_memory.cpp
  • src/ir/op/tile_ops/gather.cpp
  • src/ir/op/tile_ops/memory.cpp
  • tests/st/runtime/ops/test_gatherb.py
  • tests/st/runtime/ops/test_mgather.py
  • tests/st/runtime/ops/test_tri.py
  • tests/ut/codegen/test_pto_codegen.py
  • tests/ut/codegen/test_pto_codegen_ops.py
  • tests/ut/ir/operators/test_tile_ops.py

@hashiqiqixian

Copy link
Copy Markdown
Contributor Author

Review follow-up: 6137e4f adds the requested no-MGATHER preprocessing fast path. I did not change mgather(mem: Tensor, ...) to _TensorT: DistributedTensor is already a Tensor subclass and this API returns a Tile, so a TypeVar would not preserve any input/output type relationship. I also kept the internal integer coalesce encoding local; the public API remains the string contract, and introducing a cross-language enum/binding solely for this serialized attribute would expand this batch without changing safety.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

1 participant