Skip to content

feat: add B09 partial arg and histogram ops - #2190

Open
hashiqiqixian wants to merge 14 commits into
hw-native-sys:mainfrom
hashiqiqixian:feat/ptoas-b09-partial-arg-histogram
Open

feat: add B09 partial arg and histogram ops#2190
hashiqiqixian wants to merge 14 commits into
hw-native-sys:mainfrom
hashiqiqixian:feat/ptoas-b09-partial-arg-histogram

Conversation

@hashiqiqixian

Copy link
Copy Markdown
Contributor

Summary

  • add tile.part_argmax and tile.part_argmin across C++ IR, Python IR/DSL, tuple codegen, tests, and docs
  • add A5-only tile.histogram with UINT16/UINT32 contracts, PTOAS lowering, runtime coverage, and docs
  • keep this batch independent from B02-B08 so it can merge directly in any batch order

Validation

  • remote serial build on /data/chenshenai/test2
  • 17 focused IR unit tests passed
  • Ruff check and format check passed
  • 965 header checks, 1081 English checks, and 81 docs parity checks passed
  • partial-arg PTOAS codegen: 4/4 passed and emitted pto.tpartargmax / pto.tpartargmin
  • partial-arg A2/A3 task-submit hardware validation: 4/4 passed (--precompile-workers 1, device 1)
  • histogram A5sim PTOAS compilation: 6/6 passed and emitted pto.thistogram

A5 simulator execution was attempted but is unavailable on this host because its libstdc++.so.6 lacks GLIBCXX_3.4.32; the status docs therefore describe compilation coverage and leave A5 execution 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: 23ee3622-6319-4f7f-be2d-71c9f9f5cb50

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 part_argmax, part_argmin, and histogram across the PyPTO IR, Python APIs, PTO-ISA lowering, runtime tests, and English/Chinese documentation.

Changes

Tile operation support

Layer / File(s) Summary
IR contracts and type deduction
src/ir/op/tile_ops/elementwise.cpp, tests/ut/ir/operators/test_partial_arg_histogram.py
Registers the three operations, validates operand layouts, dtypes, shapes, valid regions, and byte, and verifies result types and rejection cases.
Python operation APIs
python/pypto/ir/op/tile_ops.py, python/pypto/language/op/tile_ops.py, python/pypto/language/...
Adds IR emitters, tile wrappers returning selected values and indices, histogram byte forwarding, and public exports.
PTO instruction lowering
src/backend/common/pto_ops_elementwise.cpp
Lowers partial arg operations to pto.tpartargmax/pto.tpartargmin and histogram to pto.thistogram, including output allocation and byte configuration.
Runtime coverage and documentation
tests/st/runtime/ops/test_partial_arg.py, tests/st/runtime/ops/test_histogram.py, docs/{en,zh-cn}/dev/...
Adds A2/A3 partial-arg tests, A5 histogram tests, operation mappings, status entries, and aggregate statistics updates.

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

Sequence Diagram(s)

sequenceDiagram
  participant PyPTO
  participant TileIR
  participant PTOCodegen
  participant PTOISA
  PyPTO->>TileIR: Emit tile operation
  TileIR->>PTOCodegen: Pass validated operation and types
  PTOCodegen->>PTOISA: Generate corresponding PTO instruction
Loading

Possibly related PRs

Poem

A bunny hops through tiles so bright,
Argmax and argmin choose just right.
Histograms count each byte in line,
Three new ops make codegen shine.
“PTO!” I cheer, and twitch my nose.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.46% 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 clearly summarizes the main change: adding partial arg and histogram ops for B09.
Description check ✅ Passed The description directly matches the changeset, covering the new ops, validation, and docs.
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.

@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.

Actionable comments posted: 4

🧹 Nitpick comments (3)
tests/st/runtime/ops/test_partial_arg.py (1)

156-162: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Partial-shape coverage only varies rows, never columns.

valid_shape is parametrized as [(M, N), (11, N)] (Line 159), so v_cols is always N (full) in both cases. The column-partial masking branch in compute_expected (choose0[:, self._v_cols :] = True, Line 151) and the corresponding column-boundary behavior of part_argmax/part_argmin are never actually exercised.

Add a case that also shrinks v_cols (e.g. (M, 11) or (11, 11)) to cover the 2D partial-validity boundary.

🤖 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 `@tests/st/runtime/ops/test_partial_arg.py` around lines 156 - 162, Expand the
valid_shape parametrization in test_partial_arg to include a case with partial
columns, such as (M, 11) or (11, 11). Preserve the existing aligned and
row-partial cases while ensuring compute_expected and both
part_argmax/part_argmin exercise the column-boundary masking path.
tests/st/runtime/ops/test_histogram.py (1)

23-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Histogram filtering path is never actually exercised.

idx is always constructed to exactly equal the real higher-byte values already present in src (e.g. _idx16 == row index == the upper byte baked into _src16; _idx32 == the fixed 0x12/0x34/0x56 bytes baked into _src32). As a result, every filter predicate in compute_expected (Lines 141-143, 147-154) evaluates to "all elements pass" in every parametrized case. The test only proves "matching idx includes the element," never "mismatched idx excludes it" — the core selection behavior of the new tile.histogram op is untested.

Consider adding at least one case per dtype where some rows/columns have an idx value that does not match the corresponding higher byte, and asserting those elements are excluded from the cumulative counts.

Also applies to: 136-155

🤖 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 `@tests/st/runtime/ops/test_histogram.py` around lines 23 - 41, Update the
histogram test data helpers _idx16 and _idx32, or add dedicated parametrized
cases, so each supported dtype includes at least one idx value differing from
the corresponding higher byte in src. Ensure compute_expected’s filtering logic
and the cumulative-count assertions verify mismatched elements are excluded
while matching elements remain included.
src/ir/op/tile_ops/elementwise.cpp (1)

569-573: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the existing GetKwargOr helper instead of a manual loop for byte.

This file already uses GetKwargOr<bool>(kwargs, "high_precision", false) (line 337) for the same "extract an attribute with a default" pattern. The new byte extraction reimplements the linear-search loop manually instead of reusing that helper.

♻️ Proposed refactor
-  int byte = 1;
-  for (const auto& [key, value] : kwargs) {
-    if (key == "byte") byte = AnyCast<int>(value, "kwarg key: byte");
-  }
+  int byte = GetKwargOr<int>(kwargs, "byte", 1);
Based on learnings, kwargs should be looked up via the standard `GetKwarg` helper pattern rather than reimplemented per call site.
🤖 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/elementwise.cpp` around lines 569 - 573, Replace the
manual kwargs loop initializing byte with the existing GetKwargOr helper, using
the current default value of 1 and preserving the AnyCast<int> conversion and
subsequent byte range validation in the histogram operator.

Source: Learnings

🤖 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.

Inline comments:
In `@src/backend/common/pto_ops_elementwise.cpp`:
- Around line 353-412: Update MakePartArgCodegenPTO and MakeHistogramCodegenPTO
to omit operand type annotations when the corresponding GetExprTypeAnnotation
result is empty, using EmitInsOuts or the existing conditional annotation
pattern. Preserve annotations for non-empty types and keep the generated
ins/outs structure valid for all operands.
- Around line 360-365: Ensure both tuple outputs from ResolveTupleResultElements
remain materialized before MakePartArgCodegenPTO processes them, even when one
output is unused by the kernel. Preserve both TupleGetItemExpr consumer bindings
through DCE, or update the codegen path around GetCurrentResultVar and
ResolveTupleResultElements to support a single-output consumer without
triggering the two-element internal check.

In `@src/ir/op/tile_ops/elementwise.cpp`:
- Around line 453-476: Update DeduceTilePartArgType to validate the required
layouts for tile.part_argmax/tile.part_argmin operands: enforce the value layout
contract on src0 and src1 and the index layout contract on src0_idx and
src1_idx, matching the layouts used by pto.tpartargmax/pto.tpartargmin. Ensure
invalid layouts are rejected during IR type deduction before backend codegen.
- Around line 495-515: Update the result-type construction after the dominance
comparison to inherit each result tile’s layout from the dominating source
rather than always from src0. Select the value source corresponding to
result_valid (types[0] when src0_dominates, otherwise types[1]) and the matching
index source (types[2] or types[3]), then pass those sources to
InheritTileViewLayout while preserving the existing valid_shape and type
metadata.

---

Nitpick comments:
In `@src/ir/op/tile_ops/elementwise.cpp`:
- Around line 569-573: Replace the manual kwargs loop initializing byte with the
existing GetKwargOr helper, using the current default value of 1 and preserving
the AnyCast<int> conversion and subsequent byte range validation in the
histogram operator.

In `@tests/st/runtime/ops/test_histogram.py`:
- Around line 23-41: Update the histogram test data helpers _idx16 and _idx32,
or add dedicated parametrized cases, so each supported dtype includes at least
one idx value differing from the corresponding higher byte in src. Ensure
compute_expected’s filtering logic and the cumulative-count assertions verify
mismatched elements are excluded while matching elements remain included.

In `@tests/st/runtime/ops/test_partial_arg.py`:
- Around line 156-162: Expand the valid_shape parametrization in
test_partial_arg to include a case with partial columns, such as (M, 11) or (11,
11). Preserve the existing aligned and row-partial cases while ensuring
compute_expected and both part_argmax/part_argmin exercise the column-boundary
masking path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d5e61347-c1d1-4df4-b961-57de2f87a2f5

📥 Commits

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

📒 Files selected for processing (13)
  • docs/en/dev/codegen/00-pto_codegen.md
  • docs/en/dev/ptoas-op-status.md
  • docs/zh-cn/dev/codegen/00-pto_codegen.md
  • docs/zh-cn/dev/ptoas-op-status.md
  • 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/ir/op/tile_ops/elementwise.cpp
  • tests/st/runtime/ops/test_histogram.py
  • tests/st/runtime/ops/test_partial_arg.py
  • tests/ut/ir/operators/test_partial_arg_histogram.py

Comment thread src/backend/common/pto_ops_elementwise.cpp
Comment thread src/backend/common/pto_ops_elementwise.cpp
Comment thread src/ir/op/tile_ops/elementwise.cpp
Comment thread src/ir/op/tile_ops/elementwise.cpp
@hashiqiqixian
hashiqiqixian force-pushed the feat/ptoas-b09-partial-arg-histogram branch from 3ab0ce1 to e44e3bd Compare July 29, 2026 02:20
@hashiqiqixian

Copy link
Copy Markdown
Contributor Author

Review follow-up: e44e3bd expands partial-shape runtime coverage to rows, columns, and both axes; the UINT32 histogram fixture now contains deliberately mismatching high bytes so its filter path removes data; and the byte kwarg parsing now uses GetKwargOr.

@hashiqiqixian
hashiqiqixian force-pushed the feat/ptoas-b09-partial-arg-histogram branch from e44e3bd to 5730b88 Compare July 29, 2026 02:32
@hashiqiqixian
hashiqiqixian force-pushed the feat/ptoas-b09-partial-arg-histogram branch from 5730b88 to 3a6d8f6 Compare July 29, 2026 03:02
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