Skip to content

feat(codegen): validate shift op family - #2189

Draft
hashiqiqixian wants to merge 4 commits into
hw-native-sys:mainfrom
hashiqiqixian:feat/ptoas-b08-shift
Draft

feat(codegen): validate shift op family#2189
hashiqiqixian wants to merge 4 commits into
hw-native-sys:mainfrom
hashiqiqixian:feat/ptoas-b08-shift

Conversation

@hashiqiqixian

Copy link
Copy Markdown
Contributor

Summary

  • align tile.shl, tile.shr, tile.shls, and tile.shrs with the current PTO-ISA dtype, valid-region, scalar, and row-major layout contracts
  • remove mixed-dtype promotion and shape broadcasting from exact tile shifts, preserve signed/unsigned 8/16/32-bit cross-architecture IR support, and reject unsigned scalar encodings that PTOAS cannot represent
  • add focused type coverage plus same-name runtime ST, and record A2/A3 hardware evidence in both status matrices

Validation

  • complete local diff review: passed
  • git diff --check: passed
  • Ruff check and format check for changed Python files: passed
  • serial CMake build and environment install on /data/chenshenai/test2: passed
  • focused shift contract UT: 32 passed
  • repository header, English-only, and docs parity checks: passed
  • A2/A3 codegen-only with latest PTOAS assembly: 8 passed; generated .pto files contain exact pto.tshl, pto.tshr, pto.tshls, and pto.tshrs operand types and order
  • A2/A3 task-submit hardware, one precompile worker and one 8-case batch: 8/8 passed on device 1

Runtime coverage includes left/right shifts, signed/unsigned 16-bit tile forms, zero/one/width-minus-one counts, scalar/tile forms, and narrowed valid_shape. A5 hardware validation remains pending and is documented in the status matrix.

@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: 28fbb248-d7fd-4559-b0fc-a49aabcf59c8

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

Shift operations now enforce matching tile contracts, bounded scalar counts, signed same-width scalar encoding, and row-major layouts. New unit and runtime tests cover supported dtypes, valid regions, platforms, code generation, and hardware-specific constraints. English and Chinese documentation reflect the updated mappings and status.

Changes

Tile shift contracts and runtime coverage

Layer / File(s) Summary
Shift IR contracts
src/ir/op/tile_ops/elementwise.cpp, src/backend/common/pto_ops_elementwise.cpp, tests/ut/ir/operators/test_tile_ops.py
Shift tiles require matching dtype and valid shape; scalar counts require signed same-width types and valid ranges; row-major registration and contract tests are updated.
Scalar shift normalization and codegen
python/pypto/ir/op/tile_ops.py, python/pypto/language/op/tile_ops.py, tests/ut/codegen/test_pto_codegen.py
Constant scalar counts use signed same-width encoding, with updated range documentation and MLIR assertions.
Runtime shift execution coverage
tests/st/runtime/ops/test_shift.py
Parameterized runtime programs test tile and scalar shifts across dtypes, valid regions, platforms, and hardware-specific constraints.
PTO mapping and status documentation
docs/en/dev/codegen/00-pto_codegen.md, docs/zh-cn/dev/codegen/00-pto_codegen.md, docs/en/dev/ptoas-op-status.md, docs/zh-cn/dev/ptoas-op-status.md
Shift mappings, layout and scalar rules, A2/A3 constraints, coverage notes, and status totals are updated.

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

Sequence Diagram(s)

sequenceDiagram
  participant ShiftCase
  participant PyPTOProgram
  participant TileShiftOps
  participant TestRunner
  ShiftCase->>PyPTOProgram: build shift program
  PyPTOProgram->>TileShiftOps: apply tile or scalar shift
  TileShiftOps->>TestRunner: write valid output region
  TestRunner->>ShiftCase: compare expected values
Loading

Possibly related PRs

  • hw-native-sys/pypto#2132: Introduces shared scalar operand dtype normalization helpers related to the shift-count normalization updated here.

Poem

A bunny hops where shift counts align,
With signed little widths in a tidy line.
Tiles match shapes, regions stay bright,
Leftward and rightward compile just right.
Tests thump softly: pass, pass, hooray! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.00% 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: validating the shift operation family.
Description check ✅ Passed The description matches the changeset and objectives, covering shift contracts, layout rules, tests, and hardware 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: d27d094fd1

ℹ️ 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/elementwise.cpp Outdated
Comment thread tests/st/runtime/ops/test_shift.py Outdated
@hashiqiqixian
hashiqiqixian force-pushed the feat/ptoas-b08-shift branch from a58f7f6 to 55158b2 Compare July 29, 2026 17:21

@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: 1

🤖 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 `@docs/en/dev/ptoas-op-status.md`:
- Around line 277-278: Update the same-name ST coverage breakdown from 48
regular ops to 50 in both docs/en/dev/ptoas-op-status.md (lines 277-278) and
docs/zh-cn/dev/ptoas-op-status.md (lines 263-264), preserving the distributed
count and totals.
🪄 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: 317a02d9-044b-48c8-a020-c5d01ce14e11

📥 Commits

Reviewing files that changed from the base of the PR and between a55399d and 55158b2.

📒 Files selected for processing (11)
  • 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/op/tile_ops.py
  • src/backend/common/pto_ops_elementwise.cpp
  • src/ir/op/tile_ops/elementwise.cpp
  • tests/st/runtime/ops/test_shift.py
  • tests/ut/codegen/test_pto_codegen.py
  • tests/ut/ir/operators/test_tile_ops.py

Comment on lines +277 to +278
112 have same-name ST coverage (108 regular STs and 4 distributed STs); 60 lack same-name ST coverage
(48 regular and 10 distributed); within these 204, another 32 ops are not suitable for standalone STs.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repo files mentioning ptoas-op-status:"
git ls-files | rg '(^|/)ptoas-op-status\.md$|ptoas-op-status'

echo
echo "English stats section around relevant lines:"
if [ -f docs/en/dev/ptoas-op-status.md ]; then
  nl -ba docs/en/dev/ptoas-op-status.md | sed -n '240,290p'
fi

echo
echo "Chinese stats section around relevant lines:"
if [ -f docs/zh-cn/dev/ptoas-op-status.md ]; then
  nl -ba docs/zh-cn/dev/ptoas-op-status.md | sed -n '230,280p'
fi

echo
echo "Diff stats around relevant hunks:"
git diff -- docs/en/dev/ptoas-op-status.md docs/zh-cn/dev/ptoas-op-status.md | sed -n '1,220p'

echo
echo "Other nearby totals/count mentions in English docs:"
rg -n "112|60|32|204|48|108|4|10" docs/en/dev/ptoas-op-status.md

python3 - <<'PY'
import re
from pathlib import Path
for path in ["docs/en/dev/ptoas-op-status.md", "docs/zh-cn/dev/ptoas-op-status.md"]:
    text = Path(path).read_text()
    # Extract the exact reported phrase if present.
    m = re.search(r"\(48 regular and 10 distributed\)", text)
    print(f"{path}: phrase found={bool(m)}")
    # Do not read files as executable; arithmetic check from reported numbers:
    stated = 60
    breakdown = 48 + 10
    print(f"{path}: stated_lacking={stated}, breakdown_sum={breakdown}, equal={stated==breakdown}, within_204_consistent={112+stated+32==204}")
PY

Repository: hw-native-sys/pypto

Length of output: 348


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files:"
git ls-files | rg '(^|/)ptoas-op-status\.md$|ptoas-op-status'

echo
echo "English section around relevant lines:"
sed -n '240,290p' docs/en/dev/ptoas-op-status.md

echo
echo "Chinese section around relevant lines:"
sed -n '230,280p' docs/zh-cn/dev/ptoas-op-status.md

echo
echo "Diff around relevant hunks:"
git diff -- docs/en/dev/ptoas-op-status.md docs/zh-cn/dev/ptoas-op-status.md | sed -n '1,220p'

echo
echo "Number mentions in affected file:"
rg -n "112|60|32|204|48|108|4|10" docs/en/dev/ptoas-op-status.md

python3 - <<'PY'
from pathlib import Path
for path in ["docs/en/dev/ptoas-op-status.md", "docs/zh-cn/dev/ptoas-op-status.md"]:
    text = Path(path).read_text()
    phrase = "(48 regular and 10 distributed)"
    print(f"{path}: phrase found={phrase in text}")
    print(f"{path}: stated_lacking=60, breakdown_sum=48+10={48+10}, equal={60==48+10}, within_204_consistent={112+60+32==204}")
PY

Repository: hw-native-sys/pypto

Length of output: 9708


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Find PTOAS/PTOOps source files:"
git ls-files | rg '(^|/)(PTOAS|PTOOps|ptoas|ptoas-op-status|ptoas_).*' || true

echo
echo "Search for same-name ST/distributed ST/PTOAS counts in tracked files:"
rg -n "same-name|same name|same-name ST|no same-name|缺少同名|未包含同名|same name PTO|same-name PTO|113|112|75|60|58|50|48|108|10|4|32|204" -S . \
  -g '!node_modules' -g '!build' -g '!dist' -g '!*.svg' -g '!*.png' \
  | head -n 200

echo
echo "Git diff stat:"
git diff --stat

Repository: hw-native-sys/pypto

Length of output: 20937


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re
from collections import Counter

# Read only the docs as data to classify same-name ST coverage flags without executing repo code.
def parse_status(table_text, defs):
    status_re = re.compile(r'<!--\s*def:\s*([^>]+)-->')
    rows = []
    ops = []
    for line in table_text.splitlines():
        m = status_re.search(line)
        if m:
            defs[m.group(1)] = line
        if line.startswith('|'):
            cells = re.split(r'\s*\|\s*', line.strip())
            ops.append(cells[1])
            rows.append([c.strip() for c in cells])
    return rows, ops

lang = 'en'  # English table should match; Chinese rows should have same op ordering.
text = Path('docs/en/dev/ptoas-op-status.md').read_text('utf-8')
# Extract table between first "|" and Stats paragraph.
start = text.index('|', text.index('/ ptoas-op-status.md', text.find('`')))
end = text.index('**Stats**')
table_text = text[start:end]
rows, ops = parse_status(table_text, {})

# Count per-category/section by counting non-header rows with an op name.
# Column definitions in comments are not numeric fields, but the status columns after section rows are simple ✅/❌/— markers.
def same_name_status(cell):
    # Column after op/type/category/status/status/status/status/status is first same-name status.
    # Use status def mapping; not easy here without definitions, so scan for ✅ marker in likely status columns.
    return cell in ('✅', '❌', '—')

# Instead, derive counts from the rendered commentary/status flags by simple line scan for missing same-name comment.
missing = []
for j, op in enumerate(ops):
    row = rows[j]
    # Use the full original line containing this op for parsing when available.
    line = ''
    # no-op
    pass

# Lightweight aggregate from same-name status columns using known comment pattern is too brittle.
# Use source data from rows if parsed; only available columns so far are limited by this function.
PY

echo "Manual row counts for same-name ST columns parsed from markdown:"
python3 - <<'PY'
import re
from pathlib import Path
lang = 'en'
text = Path('docs/en/dev/ptoas-op-status.md').read_text('utf-8')
table = text[text.index('<!-- markdownlint-disable'):text.index('**Stats**')]

def col_index(cell):
    for m in re.finditer(r'<!-- (?:header|def):\s*([^>]+)', table):
        pass
    # Actually extract header comment line count by scanning first rows with comment patterns.
    return None
PY

sed -n '150,285p' docs/en/dev/ptoas-op-status.md | awk -F'|' '{
  name=$2; gsub(/^ +| +$/,"",name);
  if (name !~ /^ *[|A-Za-z_-]+/) next
  if (NF < 9) next
  # Columns of interest after fixed columns: likely same-name status columns are consistent in rows containing ops.
  n++
  # Print row and first 9 cells for manual/verified tally.
  # print n, name, $4, $5
}'

Repository: hw-native-sys/pypto

Length of output: 263


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Exact lines:"
sed -n '272,282p' docs/en/dev/ptoas-op-status.md
sed -n '258,268p' docs/zh-cn/dev/ptoas-op-status.md

echo
echo "Parse exact same-name ST columns from English table:"
python3 --version
python3 - <<'PY'
from pathlib import Path
p = Path('docs/en/dev/ptoas-op-status.md')
text = p.read_text('utf-8')
# Use exact line numbers from previous scan to avoid substring assumptions.
lines = text.splitlines()
for lineno in range(276, 282):
    print(f"L{lineno}: {lines[lineno-1]}")

# Extract from the raw lines around the op rows through Stats, parsing only markdown cells.
table_start = lines.index('| pto.comm.tassign |') if any('pto.comm.tassign' in line for line in lines) else 0
table_end = next(i for i,l in enumerate(lines) if 'Stats' in l)
rows = []
header = None
for i,l in enumerate(lines[table_start:table_end], start=table_start):
    cells = [c.strip() for c in l.split('|', 73)[1:-1]]
    if not header:
        # Header is the first row without a real op name.
        if all(c and not c.startswith('pto.') and not c.startswith('PTO') for c in cells[:7]):
            header = cells
            rows.append(('header', cells))
            continue
    if not all(c and not c.startswith('pto.') and not c.startswith('PTO') for c in cells[:7]):
        continue
    rows.append((i, cells))
header = rows[0][1]
print('HEADER:')
print({idx: h for idx, h in header.items()})
counts = {'same_no': 0, 'same_yes': 0, 'dist': 0}
for idx, row in rows[1:]:
    name = row[1]
    # Find column names and values by header index.
    print(f"\n{idx}: {name}")
    for col in header:
        if 'same-name' in col.lower() or 'ST✅' in col or 'ST status' in col.lower():
            print(col, row[:73].get(col))
            val = row[:73].get(col)
            if val is not None and val.strip():
                counts['same_no'] += 1
    # The 8th cell is likely duplicate/stability evidence? Instead parse column names.
# Summarize only from cells with same-name-related columns if parsed, then print rows summary.
PY

Repository: hw-native-sys/pypto

Length of output: 1640


Fix the “lacking same-name ST” breakdown in both language versions. The paragraph states 60 ops lack same-name coverage, but the regular distributed breakdown is 48 + 10 = 58. Since the totals cross-check as 112 + 60 + 32 = 204, update the regular lacking count from 48 to 50 in both docs.

  • docs/en/dev/ptoas-op-status.md#L277-L278
  • docs/zh-cn/dev/ptoas-op-status.md#L263-L264
📍 Affects 2 files
  • docs/en/dev/ptoas-op-status.md#L277-L278 (this comment)
  • docs/zh-cn/dev/ptoas-op-status.md#L263-L264
🤖 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 `@docs/en/dev/ptoas-op-status.md` around lines 277 - 278, Update the same-name
ST coverage breakdown from 48 regular ops to 50 in both
docs/en/dev/ptoas-op-status.md (lines 277-278) and
docs/zh-cn/dev/ptoas-op-status.md (lines 263-264), preserving the distributed
count and totals.

@Little-oil

Copy link
Copy Markdown
Contributor

#2166 复核当前 head 55158b28:此前 unsigned tile scalar、负数/越界 shift count 和 valid-shape 的问题已经修复;现在剩下的是一个明确的验收 blocker。

  1. TSHL/TSHR 仍标为 ST ,但 PR 给出的真机证据只覆盖 16-bit signed/unsigned 共 8 个旧 case。当前新增的 8/16/32-bit、full/row/column/combined-shape 矩阵还没有当前 head 的真机结果。

#2166 的 G3/G5,请先把这两行改回 ;等当前完整矩阵在固定 toolchain 和真实硬件上通过后,再恢复 TSHLS/TSHRS 因 pinned valid-shape 问题保持 是正确的。

@hashiqiqixian
hashiqiqixian force-pushed the feat/ptoas-b08-shift branch from 55158b2 to 3cab369 Compare July 30, 2026 02:00
@hashiqiqixian

Copy link
Copy Markdown
Contributor Author

Closing this later PTOAS batch for now so work can proceed serially from B02 and B03. The branch is preserved for reopening when its turn arrives.

@hashiqiqixian hashiqiqixian reopened this Jul 30, 2026
@hashiqiqixian
hashiqiqixian marked this pull request as draft July 30, 2026 02:47
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.

2 participants