Skip to content

feat(ir/codegen): add MX matmul_mx family and tget_scale_addr - #2237

Open
yanghaoran29 wants to merge 1 commit into
hw-native-sys:mainfrom
yanghaoran29:feat/mx-matmul-ops
Open

feat(ir/codegen): add MX matmul_mx family and tget_scale_addr#2237
yanghaoran29 wants to merge 1 commit into
hw-native-sys:mainfrom
yanghaoran29:feat/mx-matmul-ops

Conversation

@yanghaoran29

Copy link
Copy Markdown
Contributor

Summary

  • add tile.matmul_mx, tile.matmul_mx_acc, and tile.matmul_mx_bias with shared MX alignment and type validation
  • add tile.tget_scale_addr for scale-address binding and lower the MX operations to their PTO forms
  • extend memory-space inference, Python DSL/IR exports, operator documentation, and IR/codegen unit coverage

Testing

  • cmake --build build --parallel
  • ruff check 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 tests/ut/codegen/test_mx_ops_codegen.py tests/ut/ir/operators/test_mx_ops.py
  • python -m pytest tests/ut/codegen/test_mx_ops_codegen.py tests/ut/ir/operators/test_mx_ops.py tests/ut/ir/operators/test_op_registry.py -q (123 passed)

Dependency

@coderabbitai

coderabbitai Bot commented Jul 31, 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: 7627e47f-25bf-41d3-a6db-effe095b58d3

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

This PR adds MXFP8 block-scale matmul operations and scale-address binding to the IR, Python APIs, DSL exports, and PTO backend. It adds validation, accumulator and bias variants, code generation, unit tests, and English and Chinese documentation.

Changes

MXFP8 matmul implementation

Layer / File(s) Summary
IR contracts and registration
CMakeLists.txt, src/ir/op/tile_ops/matmul_mx.cpp, src/ir/transforms/..., docs/.../05-operators.md, docs/.../17-infer_tile_memory_space.md
Adds tile.matmul_mx, tile.matmul_mx_acc, tile.matmul_mx_bias, and tile.tget_scale_addr. The IR validates MXFP8 types, dimensions, scale groups, memory spaces, accumulator shapes, and bias shapes.
Python and DSL API exposure
python/pypto/ir/op/tile_ops.py, python/pypto/language/..., python/pypto/language/op/...
Adds IR helpers and tile wrappers, then exports all four operations through the public language modules.
PTO code generation and DPS handling
src/backend/common/pto_ops_datamove.cpp, src/backend/common/pto_ops_elementwise.cpp, src/codegen/pto/pto_codegen.cpp, docs/.../ptoas-op-status.md
Adds pto.tget_scale_addr emission, MX matmul accumulation code generation, accumulator input-output aliasing, and in-place DPS classification.
IR and codegen validation
tests/ut/ir/operators/test_mx_ops.py, tests/ut/codegen/test_mx_ops_codegen.py
Tests registry metadata, type deduction, alignment and shape validation, memory-space pairing, PTO emission, source ordering, and accumulator aliasing.

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

Possibly related issues

  • hw-native-sys/pypto#1975 — Adds the MXFP8 DSL operations, IR support, Python APIs, and backend code generation requested by the issue.

Suggested labels: enhancement

Poem

I’m a rabbit with scales in my pack,
MX matmuls now run on the track.
Tiles bind, fill, and align,
Accumulators keep their design,
While PTO hops neatly through code.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.16% 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 addition of the MX matmul operation family and the tget_scale_addr operation.
Description check ✅ Passed The description directly explains the new operations, code generation, exports, documentation, tests, and dependency.
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: 6ceccc0f0d

ℹ️ 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/matmul_mx.cpp Outdated

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/backend/common/pto_ops_elementwise.cpp (1)

727-742: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Enforce the all-or-none type-annotation invariant in make_acc_codegen.

ins_type_parts only pushes dst_type when it is non-empty, and only pushes each operand_type when it is non-empty. Operand SSA values are always emitted, so a partial type set desyncs the position of each entry in the emitted : type1, type2, ... clause from its actual operand.

The same file's MakeScatterCodegenPTO in pto_ops_datamove.cpp rejects this exact situation with an explicit INTERNAL_CHECK_SPAN that requires all type annotations to be present or all absent. Apply the same rule here, so a future operand whose type does not resolve fails loudly instead of emitting a misaligned type list.

🛡️ Proposed fix to enforce all-or-none type annotations
       std::ostringstream acc_inst;
       acc_inst << pto_op << " ins(" << dst;
-      std::vector<std::string> ins_type_parts;
-      if (!dst_type.empty()) ins_type_parts.push_back(dst_type);
-      for (size_t i = 1; i < op->args_.size(); ++i) {
-        acc_inst << ", " << codegen.GetExprAsCode(op->args_[i]);
-        std::string operand_type = codegen.GetExprTypeAnnotation(op->args_[i]);
-        if (!operand_type.empty()) ins_type_parts.push_back(operand_type);
-      }
+      std::vector<std::string> operand_types = {dst_type};
+      for (size_t i = 1; i < op->args_.size(); ++i) {
+        acc_inst << ", " << codegen.GetExprAsCode(op->args_[i]);
+        operand_types.push_back(codegen.GetExprTypeAnnotation(op->args_[i]));
+      }
+      bool any_type_present = std::any_of(operand_types.begin(), operand_types.end(),
+                                          [](const std::string& t) { return !t.empty(); });
+      bool all_types_present = std::all_of(operand_types.begin(), operand_types.end(),
+                                           [](const std::string& t) { return !t.empty(); });
+      INTERNAL_CHECK(!any_type_present || all_types_present)
+          << "Internal error: " << pto_op
+          << " operand type annotations must all be present or all absent, got a partial set";
+      std::vector<std::string> ins_type_parts = all_types_present ? operand_types
+                                                                  : std::vector<std::string>{};
🤖 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/backend/common/pto_ops_elementwise.cpp` around lines 727 - 742, Update
make_acc_codegen so type annotations are emitted only when dst_type and every
operand type are present; otherwise emit no type clause. Add an
INTERNAL_CHECK_SPAN matching MakeScatterCodegenPTO to reject partial annotations
before constructing acc_inst, while preserving the existing operand emission and
annotation ordering.
🧹 Nitpick comments (1)
python/pypto/language/op/tile_ops.py (1)

1220-1245: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Docstrings for the new MX ops omit Args/Returns sections.

matmul_mx, matmul_mx_acc, matmul_mx_bias, and tget_scale_addr each use a single-line docstring. The adjacent functions matmul, matmul_acc, and matmul_bias document each parameter with "Args:" and "Returns:" sections. Add the same sections to the new functions for consistency.

📝 Proposed docstring expansion (example for `matmul_mx`)
 def matmul_mx(lhs: Tile, lhs_scale: Tile, rhs: Tile, rhs_scale: Tile) -> Tile:
-    """MX block-scale matrix multiplication."""
+    """MX block-scale matrix multiplication.
+
+    Args:
+        lhs: Left-hand side data tile (FP8E4M3FN)
+        lhs_scale: Left-hand side scale tile (FP8E8M0)
+        rhs: Right-hand side data tile (FP8E4M3FN)
+        rhs_scale: Right-hand side scale tile (FP8E8M0)
+
+    Returns:
+        Tile wrapping the matmul_mx operation
+    """
     call_expr = _ir_ops.matmul_mx(lhs.unwrap(), lhs_scale.unwrap(), rhs.unwrap(), rhs_scale.unwrap())
     return Tile(expr=call_expr)
🤖 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 1220 - 1245, Expand the
docstrings for matmul_mx, matmul_mx_acc, matmul_mx_bias, and tget_scale_addr
with Args: entries describing every parameter and a Returns: entry describing
the returned Tile, matching the format and level of detail used by the adjacent
matmul, matmul_acc, and matmul_bias functions.
🤖 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.

Outside diff comments:
In `@src/backend/common/pto_ops_elementwise.cpp`:
- Around line 727-742: Update make_acc_codegen so type annotations are emitted
only when dst_type and every operand type are present; otherwise emit no type
clause. Add an INTERNAL_CHECK_SPAN matching MakeScatterCodegenPTO to reject
partial annotations before constructing acc_inst, while preserving the existing
operand emission and annotation ordering.

---

Nitpick comments:
In `@python/pypto/language/op/tile_ops.py`:
- Around line 1220-1245: Expand the docstrings for matmul_mx, matmul_mx_acc,
matmul_mx_bias, and tget_scale_addr with Args: entries describing every
parameter and a Returns: entry describing the returned Tile, matching the format
and level of detail used by the adjacent matmul, matmul_acc, and matmul_bias
functions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d9800fb-d8bf-418c-b153-d7f72126ecc9

📥 Commits

Reviewing files that changed from the base of the PR and between dc95be1 and 6ceccc0.

📒 Files selected for processing (18)
  • CMakeLists.txt
  • docs/en/dev/ir/05-operators.md
  • docs/en/dev/passes/17-infer_tile_memory_space.md
  • docs/en/dev/ptoas-op-status.md
  • docs/zh/dev/ir/05-operators.md
  • docs/zh/dev/passes/17-infer_tile_memory_space.md
  • docs/zh/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_datamove.cpp
  • src/backend/common/pto_ops_elementwise.cpp
  • src/codegen/pto/pto_codegen.cpp
  • src/ir/op/tile_ops/matmul_mx.cpp
  • src/ir/transforms/infer_tile_memory_space_pass.cpp
  • tests/ut/codegen/test_mx_ops_codegen.py
  • tests/ut/ir/operators/test_mx_ops.py
💤 Files with no reviewable changes (1)
  • src/ir/transforms/infer_tile_memory_space_pass.cpp

@yanghaoran29

Copy link
Copy Markdown
Contributor Author

Addressed AI review feedback in the amended commit:

  • Codex (tget_scale_addr L/R inference): fixed via local pair resolution in InferTileMemorySpace + regression test.
  • CodeRabbit (make_acc_codegen all-or-none type annotations): adopted; shared helper now rejects partial type lists.
  • CodeRabbit (MX DSL Args/Returns docstrings): adopted for matmul_mx / matmul_mx_acc / matmul_mx_bias / tget_scale_addr.

Also fixed clang-format failures that blocked CI pre-commit.

@yanghaoran29
yanghaoran29 force-pushed the feat/mx-matmul-ops branch 5 times, most recently from 1ccb315 to 0cff7de Compare August 1, 2026 04:05
@yanghaoran29
yanghaoran29 force-pushed the feat/mx-matmul-ops branch 7 times, most recently from 31fb37a to 1b33b35 Compare August 4, 2026 07:48
Add tile.matmul_mx / matmul_mx_acc / matmul_mx_bias with shared MX alignment and type checks, plus compiler-only tile.tget_scale_addr and PTO lowering for the MX path.

InferTileMemorySpace resolves Left/LeftScale and Right/RightScale and inserts tile.move. InsertMxScaleAddr then emits a fresh tget_scale_addr for every MX matmul consumer and rewrites scale operands to the bound SSA. It deliberately avoids cross-consumer CSE because SSA aliases, views, and bound results may share the same stateful physical scale buffer. Operands use AsVarLike so loop IterArgs are accepted.

Also validate constant rhs physical/valid K and scale geometry independently of lhs, streamline the MX regression tests, and document the new pass as pass 18 in en/zh with subsequent pass documents renumbered.
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