diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e3d82b..9c799ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ remains unsupported. - Import manifests now report emitted adapters, stubs, and existing runtime bindings separately from catalog classifications. - Generated import conformance tests now execute emitted service handlers and verify unsupported stubs. +- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215). - Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`. - Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`. diff --git a/scripts/qa/__main__.py b/scripts/qa/__main__.py index 8e90182..8876930 100644 --- a/scripts/qa/__main__.py +++ b/scripts/qa/__main__.py @@ -112,7 +112,7 @@ def main(argv: list[str] | None = None) -> int: r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning") r.add_argument( "action", - choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"), + choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile", "rank"), ) r.add_argument("--limit", type=int, default=0) r.add_argument("--family", action="append", default=[], help="filter by encoding family") @@ -127,6 +127,7 @@ def main(argv: list[str] | None = None) -> int: r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)") r.add_argument("--before", default="", help="JSON inventory for diff") r.add_argument("--after", default="", help="JSON inventory for diff") + r.add_argument("--no-float", action="store_true", help="rank: exclude floating-point groups") cpu = sub.add_parser("cpu-coverage", help="legacy heuristic CPU/runtime coverage scan") cpu.add_argument("--blockers", action="store_true") @@ -168,6 +169,12 @@ def main(argv: list[str] | None = None) -> int: br.add_argument("--behind", type=int, required=True) args = p.parse_args(argv) + if args.command == "rdna2" and args.action == "rank": + from .rdna2_rank import run_rank + + return run_rank(_root(), args) + if args.command == "rdna2" and args.no_float: + r.error("--no-float requires the rank action") root = _root() if args.command == "orchestrate": diff --git a/scripts/qa/rdna2_rank.py b/scripts/qa/rdna2_rank.py new file mode 100644 index 0000000..8b3c560 --- /dev/null +++ b/scripts/qa/rdna2_rank.py @@ -0,0 +1,135 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Rank registry expansion by XML identity and operand shape.""" +from __future__ import annotations + +import json +import runpy +from argparse import Namespace +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Sequence + +from . import rdna2_plan + +# Relative planning weights, not measurements of implementation effort. +ENCODING_VARIANT_COST = 1 +OPERAND_RULE_COST = 2 +PRIMITIVE_COST = 4 + +FLOAT_FORMATS = {"FMT_NUM_F16", "FMT_NUM_F32", "FMT_NUM_F64"} +DIRECTIONS = {(False, False): "none", (True, False): "in", + (False, True): "out", (True, True): "inout"} + +FormKey = tuple[str, str] +Operand = tuple[str, str, str, int, bool, bool, bool, bool] +Signature = tuple[tuple[str, str, int, str], ...] + + +@dataclass +class RankGroup: + key: str + kind: str + family: str + signature: Signature + cost: int + forms: list[dict[str, str | int]] = field(default_factory=list) + float: bool = False + blocked_by_claims: int = 0 + + def payload(self) -> dict[str, Any]: + count = len(self.forms) + return {**asdict(self), "count": count, "score": count / self.cost} + + +def load_xml_operands(root: Path, identified: dict[FormKey, int]) -> dict[FormKey, list[Operand]]: + # Use the same base-row selection as the planner, including literal-only + # forms and relative moves with non-default conditions. + metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py")) + snapshot = (root / "crates/isa/data/rdna2.jsonl").read_text(encoding="utf-8") + _, _, forms = metadata["forms_from_snapshot"](snapshot) + return { + key: form["operands"] + for form in forms + if (key := (form["encoding"].upper(), form["name"])) in identified + } + + +def rank_groups( + data: dict[str, Any], + operands: dict[FormKey, list[Operand]], + *, + families: Sequence[str] = (), + claims: Sequence[rdna2_plan.ClaimScope] = (), + no_float: bool = False, + limit: int | None = None, +) -> list[dict[str, Any]]: + identified = data["identified"] + declared = set(data["declared"]) | { + (variant["family"], variant["of"]) + for variant in data["registry"].get("encoding_variant", []) + } + signatures = { + key: tuple((field, kind, size, DIRECTIONS[is_input, is_output]) + for field, _, kind, size, is_input, is_output, _, _ in rows) + for key, rows in operands.items() + } + formats = { + key: tuple((row[1], row[3]) for row in rows) + for key, rows in operands.items() + } + # The planner validates each form's rule. Its XML signature supplies the + # kinds, widths and directions that the registry's rule alone lacks. + declared_names = {name for _, name in declared} + rule_shapes = {(key[0], signatures[key]) for key in declared if key in identified} + declared_formats = {formats[key] for key in declared if key in identified} + + selected = {family.upper() for family in families} + claimed_families = {family for scope in claims for family in scope.families} + claimed_paths = {path for scope in claims if not scope.families for path in scope.paths} + groups: dict[str, RankGroup] = {} + for family, name in sorted(identified.keys() - declared): + if selected and family not in selected: + continue + form = (family, name) + signature = signatures[form] + if name in declared_names: + kind, cost = "encoding-variant", ENCODING_VARIANT_COST + elif (family, signature) not in rule_shapes and formats[form] in declared_formats: + kind, cost = "operand-rule", OPERAND_RULE_COST + else: + kind, cost = "primitive", PRIMITIVE_COST + shape = ",".join(f"{field}/{kind}/{size}/{direction}" for field, kind, size, direction in signature) + key = f"{kind}:{family}:{shape}" + if key not in groups: + groups[key] = RankGroup(key, kind, family, signature, cost) + group = groups[key] + group.float |= any(fmt in FLOAT_FORMATS for fmt, _ in formats[form]) + opcode = identified[form] + candidate = rdna2_plan.Candidate(family, name, opcode, None, None, None) + if family in claimed_families or rdna2_plan.claims_block_candidate(candidate, claimed_paths): + group.blocked_by_claims += 1 + else: + group.forms.append({"name": name, "opcode": opcode}) + + ranked = [group.payload() for group in groups.values() + if group.forms and not (no_float and group.float)] + ranked.sort(key=lambda group: (-group["score"], -group["count"], group["key"])) + return ranked[:limit] + + +def run_rank(root: Path, args: Namespace) -> int: + data = rdna2_plan.load_inventories(root) + operands = load_xml_operands(root, data["identified"]) + claims = rdna2_plan.load_claim_scopes(Path(args.claims)) if args.claims else [] + groups = rank_groups(data, operands, families=args.family, claims=claims, + no_float=args.no_float, limit=args.limit or None) + if args.out: + rdna2_plan.write_json(Path(args.out), groups) + if args.compact or args.out: + for group in groups: + print(f"{group['key']} count={group['count']} cost={group['cost']} " + f"score={group['score']:g} float={str(group['float']).lower()} " + f"blocked_by_claims={group['blocked_by_claims']}") + else: + print(json.dumps(groups, indent=2, sort_keys=True)) + return 0 diff --git a/tests/qa/test_rdna2_rank.py b/tests/qa/test_rdna2_rank.py new file mode 100644 index 0000000..080d2e7 --- /dev/null +++ b/tests/qa/test_rdna2_rank.py @@ -0,0 +1,111 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import io +import json +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest.mock import patch + +from qa.__main__ import main +from qa.rdna2_plan import load_claim_scopes +from qa.rdna2_rank import rank_groups + + +def operand(field, kind, fmt="FMT_NUM_U32", *, output=False): + return (field, fmt, kind, 32, not output, output, False, True) + + +class Rdna2Rank(unittest.TestCase): + def setUp(self): + self.base = ("VOP2", "SYNTHETIC_ADD") + self.variant = ("VOP3", "SYNTHETIC_ADD") + self.rule = ("SOP2", "SYNTHETIC_OTHER") + self.primitive = ("VOP2", "SYNTHETIC_NEW") + self.floating = ("VOP2", "SYNTHETIC_FLOAT") + self.data = { + "identified": {self.primitive: 5, self.variant: 17, self.base: 2, + self.floating: 4, self.rule: 11}, + "declared": {self.base}, + "registry": {}, + } + dst = operand("VDST", "OPR_VGPR", output=True) + src = operand("SRC0", "OPR_SRC") + self.operands = { + self.base: [dst, src], + self.variant: [dst, operand("SRC0", "OPR_SRC_NOLDS")], + self.rule: [operand("SDST", "OPR_SGPR", output=True), src], + self.primitive: [dst, src], + self.floating: [dst, operand("SRC0", "OPR_SRC", "FMT_NUM_F32")], + } + + def test_kinds_and_costs_determine_ranking(self): + groups = rank_groups(self.data, self.operands) + self.assertEqual( + [(group["kind"], group["cost"], group["score"]) for group in groups], + [("encoding-variant", 1, 1.0), ("primitive", 4, 0.5), ("operand-rule", 2, 0.5)], + ) + self.assertEqual(groups[0]["family"], "VOP3") + self.assertEqual(groups[0]["forms"], [{"name": "SYNTHETIC_ADD", "opcode": 17}]) + self.assertEqual(groups[0]["signature"], ( + ("VDST", "OPR_VGPR", 32, "out"), ("SRC0", "OPR_SRC_NOLDS", 32, "in"), + )) + + def test_declared_variant_is_not_ranked_and_supplies_a_rule_shape(self): + self.data["registry"]["encoding_variant"] = [ + {"of": self.base[1], "family": "VOP3", "opcode": 17, "operands": "synthetic_rule"}, + ] + other = ("VOP3", "SYNTHETIC_OTHER") + self.data["identified"][other] = 18 + self.operands[other] = self.operands[self.variant] + groups = rank_groups(self.data, self.operands, families=["vop3"]) + self.assertEqual(len(groups), 1) + self.assertEqual(groups[0]["kind"], "primitive") + self.assertEqual(groups[0]["forms"], [{"name": other[1], "opcode": 18}]) + + def test_claim_file_family_and_path_scopes(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "claims.json" + path.write_text(json.dumps({"claims": [ + {"families": ["vop3"], "paths": ["crates/isa/**"]}, + {"paths": ["unrelated/**"]}, + ]}), encoding="utf-8") + remaining = rank_groups(self.data, self.operands, claims=load_claim_scopes(path)) + self.assertEqual([group["family"] for group in remaining], ["VOP2", "SOP2"]) + path.write_text(json.dumps([{"paths": ["crates/isa/**"]}]), encoding="utf-8") + self.assertEqual(rank_groups(self.data, self.operands, claims=load_claim_scopes(path)), []) + + def test_partially_blocked_group_reports_dropped_form(self): + with patch("qa.rdna2_plan.claims_block_candidate", side_effect=lambda cand, _: cand.name == self.primitive[1]): + groups = rank_groups(self.data, self.operands, families=["VOP2"]) + self.assertEqual(groups[0]["blocked_by_claims"], 1) + self.assertEqual(groups[0]["count"], 1) + self.assertEqual(groups[0]["score"], 0.25) + self.assertEqual(groups[0]["forms"], [{"name": self.floating[1], "opcode": 4}]) + + def test_float_marker_and_cli_filter(self): + def invoke(*flags): + stdout = io.StringIO() + with redirect_stdout(stdout): + self.assertEqual(main(["rdna2", "rank", *flags]), 0) + return stdout.getvalue() + + with ( + patch("qa.rdna2_plan.load_inventories", return_value=self.data), + patch("qa.rdna2_rank.load_xml_operands", return_value=self.operands), + ): + groups = json.loads(invoke()) + self.assertEqual([group["float"] for group in groups], [False, True, False]) + self.assertEqual(json.loads(invoke("--no-float")), [groups[0], groups[2]]) + self.assertEqual(json.loads(invoke("--family", "sop2", "--limit", "1")), [groups[2]]) + self.assertEqual(len(invoke("--no-float", "--compact").splitlines()), 2) + + def test_deterministic_with_reordered_inventory_and_equal_scores(self): + additional_rule = ("SOP1", "SYNTHETIC_OTHER") + self.data["identified"][additional_rule] = 1 + self.operands[additional_rule] = self.operands[self.rule] + first = rank_groups(self.data, self.operands) + reordered = {**self.data, "identified": dict(reversed(list(self.data["identified"].items())))} + second = rank_groups(reordered, dict(reversed(list(self.operands.items())))) + self.assertEqual(first, second) + self.assertEqual([group["family"] for group in first], ["VOP3", "VOP2", "SOP1", "SOP2"])