${esc(JSON.stringify({shapes:s.shapes,dtypes:s.dtypes,invariants:s.invariants},null,2))}
`;specs.append(el)});(state.optimization.candidates||[]).forEach(c=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
From dc9eec4f3f14fd7a307670d0d91502981c042ab7 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:14:57 +0530
Subject: [PATCH 051/168] radeon forge: record measured kernel durations
---
extra/radeon_forge/runtime/events.py | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/runtime/events.py b/extra/radeon_forge/runtime/events.py
index d5d94ade2504f..71c75ede25e34 100644
--- a/extra/radeon_forge/runtime/events.py
+++ b/extra/radeon_forge/runtime/events.py
@@ -38,7 +38,15 @@ def __init__(self, trace_id: str | None = None):
self._lock = threading.RLock()
def point(self, kind: str, name: str, parent_id: str | None = None, **attributes: Any) -> TraceEvent:
- ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, name, now_ns(), now_ns(), parent_id, attributes)
+ ts = now_ns()
+ ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, name, ts, ts, parent_id, attributes)
+ with self._lock: self._events.append(ev)
+ return ev
+
+ def duration(self, kind: str, name: str, duration_ms: float, parent_id: str | None = None, **attributes: Any) -> TraceEvent:
+ end = now_ns()
+ start = end - max(0, int(float(duration_ms) * 1e6))
+ ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, name, start, end, parent_id, attributes)
with self._lock: self._events.append(ev)
return ev
From 069fbffed123a21e304e8f11cde11f75772486f5 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:15:41 +0530
Subject: [PATCH 052/168] radeon forge: attach measured kernel and prefill
spans
---
extra/radeon_forge/runtime/session.py | 18 ++++++++++++++----
1 file changed, 14 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index 02229b1e63696..45ee521969a26 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -69,6 +69,17 @@ def send(self, content: str, max_tokens: int = 512, temperature: float = 0.0) ->
self._emit("message", role="user", content=text)
return self._generate(max_tokens, temperature)
+ def _record_backend_event(self, event, parent_id: str) -> None:
+ metrics = dict(event.metrics)
+ self._emit(event.kind, **metrics)
+ if event.kind == "kernel":
+ name = str(metrics.pop("name", "kernel"))
+ duration_ms = float(metrics.pop("duration_ms", metrics.pop("duration_us", 0.0) / 1000.0))
+ self.trace.duration("kernel", name, duration_ms, parent_id, **metrics)
+ elif event.kind in {"prefill", "decode"} and float(metrics.get("wall_ms", 0.0)) > 0:
+ self.trace.duration("inference", event.kind, float(metrics["wall_ms"]), parent_id, **metrics)
+ else: self.trace.point("inference", event.kind, parent_id, **metrics)
+
def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent, ...]:
self.state = SessionState.GENERATING
started_at = len(self.events)
@@ -84,10 +95,9 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
if event.kind == "token":
pieces.append(event.text)
self._emit("token", text=event.text, metrics=dict(event.metrics))
- self.trace.point("inference", "token", parent.event_id, text=event.text, **dict(event.metrics))
- elif event.kind in {"prefill", "decode", "kernel", "metric"}:
- self._emit(event.kind, **dict(event.metrics))
- self.trace.point("inference", event.kind, parent.event_id, **dict(event.metrics))
+ self.trace.duration("inference", "token", float(event.metrics.get("wall_ms", 0.0)), parent.event_id,
+ text=event.text, **dict(event.metrics))
+ elif event.kind in {"prefill", "decode", "kernel", "metric"}: self._record_backend_event(event, parent.event_id)
elif event.kind == "tool_call" and event.tool_call is not None:
self.pending_tool_call = ToolCall(str(event.tool_call.get("id") or uuid.uuid4().hex), str(event.tool_call["name"]), event.tool_call.get("arguments", {}))
elif event.kind == "done": self._emit("generation_done", finish_reason=event.finish_reason, metrics=dict(event.metrics))
From 7c77b6c979c4760ae5c390b05239e3e89dfa665e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:19:27 +0530
Subject: [PATCH 053/168] radeon forge: add portable single-file optimization
recipes
---
extra/radeon_forge/synthesis/recipe.py | 281 +++++++++++++++++++++++++
1 file changed, 281 insertions(+)
create mode 100644 extra/radeon_forge/synthesis/recipe.py
diff --git a/extra/radeon_forge/synthesis/recipe.py b/extra/radeon_forge/synthesis/recipe.py
new file mode 100644
index 0000000000000..cd69659e554ef
--- /dev/null
+++ b/extra/radeon_forge/synthesis/recipe.py
@@ -0,0 +1,281 @@
+from __future__ import annotations
+
+import base64, hashlib, json, shutil, tomllib
+from dataclasses import asdict, dataclass, field
+from pathlib import Path, PurePosixPath
+from typing import Any, Mapping, Sequence
+
+from .workspace import CandidateRecord, CandidateWorkspace, KernelSpec
+
+
+FORMAT_VERSION = 1
+MAX_RECIPE_BYTES = 8_000_000
+MAX_ARTIFACT_BYTES = 4_000_000
+_ALLOWED_ROLES = {"oracle", "benchmark", "heldout", "knowledge", "reference", "seed", "implementation_cache", "support"}
+
+
+def _canonical_hash(payload: Any) -> str:
+ return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode()).hexdigest()
+
+
+def _string_list(value: Any, field_name: str) -> tuple[str, ...]:
+ if value is None: return ()
+ if not isinstance(value, list) or not all(isinstance(x, str) for x in value): raise ValueError(f"{field_name} must be an array of strings")
+ return tuple(value)
+
+
+def _safe_relative_path(value: str) -> str:
+ path = PurePosixPath(value)
+ if not value or path.is_absolute() or ".." in path.parts or "." in path.parts or "\x00" in value:
+ raise ValueError(f"unsafe recipe artifact path: {value!r}")
+ return path.as_posix()
+
+
+def _command(value: Any, field_name: str) -> tuple[str, ...]:
+ command = _string_list(value, field_name)
+ if any("\x00" in part for part in command): raise ValueError(f"{field_name} contains NUL")
+ return command
+
+
+@dataclass(frozen=True)
+class RecipeArtifact:
+ path: str
+ role: str
+ content: str
+ executable: bool = False
+ description: str = ""
+
+ @property
+ def sha256(self) -> str: return hashlib.sha256(self.content.encode()).hexdigest()
+
+
+@dataclass(frozen=True)
+class ForgeRecipe:
+ """Portable optimization knowledge.
+
+ A recipe deliberately captures intent, invariants, oracles and optional seed
+ material without defining a kernel DSL. An intelligent executor is expected
+ to fill implementation gaps and the independent oracles decide what survives.
+ """
+ name: str
+ description: str
+ operation: str
+ target: str
+ objective: str
+ agent_brief: str
+ invariants: tuple[str, ...]
+ unknowns: tuple[str, ...] = ()
+ compatibility: Mapping[str, Any] = field(default_factory=dict)
+ acceptance: Mapping[str, Any] = field(default_factory=dict)
+ shapes: Mapping[str, int | str] = field(default_factory=dict)
+ dtypes: Mapping[str, str] = field(default_factory=dict)
+ language: str = "python"
+ extension: str = ".py"
+ entrypoint: str = "build_kernel"
+ mockgpu_command: tuple[str, ...] = ()
+ hardware_command: tuple[str, ...] = ()
+ heldout_command: tuple[str, ...] = ()
+ artifacts: tuple[RecipeArtifact, ...] = ()
+ seed_artifact: str | None = None
+ seed_hypothesis: str = "Imported implementation cache; revalidate and specialize locally."
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+ source_text: str = field(default="", repr=False, compare=False)
+
+ @property
+ def recipe_id(self) -> str:
+ payload = asdict(self)
+ payload.pop("source_text", None)
+ return f"{self.name}-{_canonical_hash(payload)[:16]}"
+
+ @classmethod
+ def load(cls, path: str | Path) -> ForgeRecipe:
+ source_path = Path(path)
+ raw = source_path.read_bytes()
+ if len(raw) > MAX_RECIPE_BYTES: raise ValueError(f"recipe exceeds {MAX_RECIPE_BYTES} bytes")
+ payload = tomllib.loads(raw.decode("utf-8"))
+ if int(payload.get("format_version", 0)) != FORMAT_VERSION: raise ValueError(f"unsupported recipe format_version; expected {FORMAT_VERSION}")
+
+ required = ("name", "description", "operation", "target", "objective", "agent_brief", "invariants")
+ missing = [key for key in required if key not in payload]
+ if missing: raise ValueError(f"recipe missing required fields: {missing}")
+
+ artifacts: list[RecipeArtifact] = []
+ seen_paths: set[str] = set()
+ for item in payload.get("artifact", []):
+ if not isinstance(item, dict): raise ValueError("each [[artifact]] entry must be a table")
+ artifact_path = _safe_relative_path(str(item.get("path", "")))
+ if artifact_path in seen_paths: raise ValueError(f"duplicate artifact path: {artifact_path}")
+ seen_paths.add(artifact_path)
+ role = str(item.get("role", "support"))
+ if role not in _ALLOWED_ROLES: raise ValueError(f"unsupported artifact role {role!r}")
+ has_text, has_b64 = "content" in item, "content_base64" in item
+ if has_text == has_b64: raise ValueError(f"artifact {artifact_path} must define exactly one of content or content_base64")
+ try: content = str(item["content"]) if has_text else base64.b64decode(str(item["content_base64"]), validate=True).decode("utf-8")
+ except Exception as exc: raise ValueError(f"artifact {artifact_path} has invalid UTF-8/base64 content") from exc
+ if len(content.encode()) > MAX_ARTIFACT_BYTES: raise ValueError(f"artifact {artifact_path} exceeds {MAX_ARTIFACT_BYTES} bytes")
+ expected_sha = item.get("sha256")
+ actual_sha = hashlib.sha256(content.encode()).hexdigest()
+ if expected_sha is not None and str(expected_sha) != actual_sha: raise ValueError(f"artifact {artifact_path} sha256 mismatch")
+ artifacts.append(RecipeArtifact(artifact_path, role, content, bool(item.get("executable", False)), str(item.get("description", ""))))
+
+ seed_artifact = payload.get("seed_artifact")
+ if seed_artifact is not None:
+ seed_artifact = _safe_relative_path(str(seed_artifact))
+ if seed_artifact not in seen_paths: raise ValueError("seed_artifact must reference an embedded artifact")
+
+ oracle = payload.get("oracle", {})
+ if not isinstance(oracle, dict): raise ValueError("[oracle] must be a table")
+ reserved = {"format_version", "name", "description", "operation", "target", "objective", "agent_brief", "invariants",
+ "unknowns", "compatibility", "acceptance", "shapes", "dtypes", "language", "extension", "entrypoint", "oracle",
+ "artifact", "seed_artifact", "seed_hypothesis", "metadata"}
+ extra = {key: value for key, value in payload.items() if key not in reserved}
+ metadata = dict(payload.get("metadata", {}))
+ if extra: metadata["unrecognized_recipe_fields"] = extra
+
+ recipe = cls(
+ name=str(payload["name"]).strip(), description=str(payload["description"]).strip(), operation=str(payload["operation"]).strip(),
+ target=str(payload["target"]).strip(), objective=str(payload["objective"]).strip(), agent_brief=str(payload["agent_brief"]).strip(),
+ invariants=_string_list(payload["invariants"], "invariants"), unknowns=_string_list(payload.get("unknowns", []), "unknowns"),
+ compatibility=dict(payload.get("compatibility", {})), acceptance=dict(payload.get("acceptance", {})),
+ shapes=dict(payload.get("shapes", {})), dtypes={str(k): str(v) for k, v in dict(payload.get("dtypes", {})).items()},
+ language=str(payload.get("language", "python")), extension=str(payload.get("extension", ".py")),
+ entrypoint=str(payload.get("entrypoint", "build_kernel")),
+ mockgpu_command=_command(oracle.get("mockgpu_command", []), "oracle.mockgpu_command"),
+ hardware_command=_command(oracle.get("hardware_command", []), "oracle.hardware_command"),
+ heldout_command=_command(oracle.get("heldout_command", []), "oracle.heldout_command"), artifacts=tuple(artifacts),
+ seed_artifact=seed_artifact, seed_hypothesis=str(payload.get("seed_hypothesis", "Imported implementation cache; revalidate and specialize locally.")),
+ metadata=metadata, source_text=raw.decode("utf-8"),
+ )
+ if not recipe.name or not recipe.agent_brief or not recipe.invariants: raise ValueError("name, agent_brief and at least one invariant are required")
+ if not recipe.extension.startswith(".") or "/" in recipe.extension: raise ValueError("extension must be a simple suffix such as .py or .cpp")
+ return recipe
+
+
+@dataclass(frozen=True)
+class InstalledRecipe:
+ recipe_id: str
+ bundle_root: str
+ spec_id: str
+ seed_candidate_id: str | None
+ artifact_hashes: Mapping[str, str]
+
+
+class RecipeLibrary:
+ def __init__(self, workspace: CandidateWorkspace):
+ self.workspace = workspace
+ self.root = workspace.root / "recipes"
+ self.root.mkdir(parents=True, exist_ok=True)
+
+ def install(self, recipe: ForgeRecipe) -> InstalledRecipe:
+ bundle = self.root / recipe.recipe_id
+ if bundle.exists(): shutil.rmtree(bundle)
+ bundle.mkdir(parents=True)
+ if recipe.source_text: (bundle / "recipe.forge.toml").write_text(recipe.source_text, encoding="utf-8")
+ artifact_hashes: dict[str, str] = {}
+ for artifact in recipe.artifacts:
+ path = (bundle / artifact.path).resolve()
+ if bundle.resolve() not in path.parents: raise ValueError(f"artifact escaped bundle: {artifact.path}")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(artifact.content, encoding="utf-8")
+ if artifact.executable: path.chmod(path.stat().st_mode | 0o100)
+ artifact_hashes[artifact.path] = artifact.sha256
+
+ metadata = {
+ **dict(recipe.metadata), "recipe_id": recipe.recipe_id, "recipe_bundle": str(bundle), "recipe_agent_brief": recipe.agent_brief,
+ "recipe_unknowns": list(recipe.unknowns), "recipe_compatibility": dict(recipe.compatibility), "recipe_acceptance": dict(recipe.acceptance),
+ "recipe_artifacts": [{"path": x.path, "role": x.role, "sha256": x.sha256, "description": x.description} for x in recipe.artifacts],
+ "heldout_command": list(recipe.heldout_command),
+ }
+ spec = KernelSpec(recipe.name, recipe.operation, recipe.target, recipe.language, recipe.extension, recipe.entrypoint,
+ recipe.shapes, recipe.dtypes, recipe.invariants, recipe.objective, recipe.mockgpu_command,
+ recipe.hardware_command, metadata)
+ self.workspace.save_spec(spec)
+
+ seed_candidate: CandidateRecord | None = None
+ if recipe.seed_artifact is not None:
+ source = (bundle / recipe.seed_artifact).read_text(encoding="utf-8")
+ seed_candidate = self.workspace.create_candidate(spec.spec_id, source, recipe.seed_hypothesis)
+ seed_candidate = self.workspace.update(seed_candidate.candidate_id, "imported_unverified", {
+ "recipe_id": recipe.recipe_id, "seed_artifact": recipe.seed_artifact, "portable_cache": True,
+ })
+
+ manifest = {"recipe_id": recipe.recipe_id, "spec_id": spec.spec_id, "bundle_root": str(bundle),
+ "seed_candidate_id": seed_candidate.candidate_id if seed_candidate else None, "artifact_hashes": artifact_hashes}
+ (bundle / "installed.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
+ return InstalledRecipe(**manifest)
+
+ def install_file(self, path: str | Path) -> InstalledRecipe: return self.install(ForgeRecipe.load(path))
+
+ def installed(self) -> list[InstalledRecipe]:
+ ret: list[InstalledRecipe] = []
+ for path in sorted(self.root.glob("*/installed.json")):
+ try: ret.append(InstalledRecipe(**json.loads(path.read_text(encoding="utf-8"))))
+ except Exception: continue
+ return ret
+
+ def inspect(self, recipe_id: str) -> dict[str, Any]:
+ path = self.root / recipe_id / "installed.json"
+ if not path.is_file(): raise KeyError(f"unknown recipe {recipe_id}")
+ installed = InstalledRecipe(**json.loads(path.read_text(encoding="utf-8")))
+ spec = self.workspace.load_spec(installed.spec_id)
+ return {"installed": asdict(installed), "spec": asdict(spec) | {"spec_id": spec.spec_id},
+ "recipe_source": str(self.root / recipe_id / "recipe.forge.toml")}
+
+
+def _toml_string(value: str) -> str: return json.dumps(value, ensure_ascii=False)
+def _toml_array(values: Sequence[str]) -> str: return "[" + ", ".join(_toml_string(x) for x in values) + "]"
+
+
+def export_recipe(workspace: CandidateWorkspace, spec_id: str, output: str | Path, candidate_id: str | None = None) -> Path:
+ """Export a spec and optional implementation cache as one portable TOML file.
+
+ Exact generated code is base64-encoded because it is a disposable cache. The
+ intent, invariants and agent brief stay human-readable and reviewable.
+ """
+ spec = workspace.load_spec(spec_id)
+ metadata = dict(spec.metadata)
+ agent_brief = str(metadata.get("recipe_agent_brief") or
+ "Use the supplied intent, invariants and oracle as the contract. Inspect the local hardware and workload, then freely regenerate or restructure the implementation. Do not trust the cached implementation without rerunning every oracle.")
+ lines = [f"format_version = {FORMAT_VERSION}", f"name = {_toml_string(spec.name)}",
+ f"description = {_toml_string(str(metadata.get('description', spec.operation)))}", f"operation = {_toml_string(spec.operation)}",
+ f"target = {_toml_string(spec.target)}", f"objective = {_toml_string(spec.objective)}", f"agent_brief = {_toml_string(agent_brief)}",
+ f"invariants = {_toml_array(spec.invariants)}", f"language = {_toml_string(spec.language)}",
+ f"extension = {_toml_string(spec.extension)}", f"entrypoint = {_toml_string(spec.entrypoint)}"]
+ unknowns = tuple(str(x) for x in metadata.get("recipe_unknowns", ()))
+ if unknowns: lines.append(f"unknowns = {_toml_array(unknowns)}")
+ if candidate_id is not None:
+ candidate = workspace.load_candidate(candidate_id)
+ if candidate.spec_id != spec_id: raise ValueError("candidate does not belong to spec")
+ source = Path(candidate.source_path).read_text(encoding="utf-8")
+ seed_name = f"implementation-cache{spec.extension}"
+ lines += [f"seed_artifact = {_toml_string(seed_name)}", f"seed_hypothesis = {_toml_string(candidate.hypothesis)}"]
+ else: candidate, source, seed_name = None, "", ""
+
+ if spec.shapes:
+ lines.append("\n[shapes]")
+ lines += [f"{json.dumps(str(k))} = {json.dumps(v)}" for k, v in spec.shapes.items()]
+ if spec.dtypes:
+ lines.append("\n[dtypes]")
+ lines += [f"{json.dumps(str(k))} = {_toml_string(str(v))}" for k, v in spec.dtypes.items()]
+ compatibility = dict(metadata.get("recipe_compatibility", {}))
+ if compatibility:
+ lines.append("\n[compatibility]")
+ lines += [f"{json.dumps(str(k))} = {json.dumps(v)}" for k, v in compatibility.items()]
+ acceptance = dict(metadata.get("recipe_acceptance", {}))
+ if acceptance:
+ lines.append("\n[acceptance]")
+ lines += [f"{json.dumps(str(k))} = {json.dumps(v)}" for k, v in acceptance.items()]
+ lines += ["\n[oracle]", f"mockgpu_command = {_toml_array(spec.mockgpu_command)}", f"hardware_command = {_toml_array(spec.hardware_command)}"]
+ heldout = tuple(str(x) for x in metadata.get("heldout_command", ()))
+ if heldout: lines.append(f"heldout_command = {_toml_array(heldout)}")
+
+ if candidate is not None:
+ encoded = base64.b64encode(source.encode()).decode()
+ lines += ["\n[[artifact]]", f"path = {_toml_string(seed_name)}", "role = \"implementation_cache\"",
+ f"description = {_toml_string('Disposable implementation cache exported from ' + candidate.candidate_id)}",
+ f"sha256 = {_toml_string(hashlib.sha256(source.encode()).hexdigest())}", f"content_base64 = {_toml_string(encoded)}"]
+
+ out = Path(output)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return out
From 4c4449d85dcdc1adc5d4294bd581b19cfa361193 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:19:52 +0530
Subject: [PATCH 054/168] radeon forge: support recipe bundle placeholders
---
extra/radeon_forge/synthesis/workspace.py | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/synthesis/workspace.py b/extra/radeon_forge/synthesis/workspace.py
index 71bd8473093a5..04b36a134f560 100644
--- a/extra/radeon_forge/synthesis/workspace.py
+++ b/extra/radeon_forge/synthesis/workspace.py
@@ -105,6 +105,12 @@ def update(self, candidate_id: str, status: str, evidence: Mapping[str, Any]) ->
@staticmethod
def render_command(command: Sequence[str], spec: KernelSpec, candidate: CandidateRecord, root: Path) -> tuple[str, ...]:
+ bundle = str(spec.metadata.get("recipe_bundle", root))
replacements = {"{candidate}": candidate.source_path, "{candidate_id}": candidate.candidate_id,
- "{spec_id}": spec.spec_id, "{root}": str(root)}
- return tuple(replacements.get(part, part) for part in command)
+ "{spec_id}": spec.spec_id, "{root}": str(root), "{bundle}": bundle}
+ rendered: list[str] = []
+ for original in command:
+ part = str(original)
+ for key, value in replacements.items(): part = part.replace(key, value)
+ rendered.append(part)
+ return tuple(rendered)
From 55f95f06740ac12abd5226020894c4ccfee300ab Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:20:08 +0530
Subject: [PATCH 055/168] radeon forge: export recipe library
---
extra/radeon_forge/synthesis/__init__.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/synthesis/__init__.py b/extra/radeon_forge/synthesis/__init__.py
index fd71b0641d61e..d1a1177a84a21 100644
--- a/extra/radeon_forge/synthesis/__init__.py
+++ b/extra/radeon_forge/synthesis/__init__.py
@@ -1,5 +1,7 @@
from .defaults import install_default_specs
+from .recipe import ForgeRecipe, InstalledRecipe, RecipeArtifact, RecipeLibrary, export_recipe
from .tools import OptimizationTools
from .workspace import CandidateRecord, CandidateWorkspace, KernelSpec
-__all__ = ["CandidateRecord", "CandidateWorkspace", "KernelSpec", "OptimizationTools", "install_default_specs"]
+__all__ = ["CandidateRecord", "CandidateWorkspace", "ForgeRecipe", "InstalledRecipe", "KernelSpec", "OptimizationTools",
+ "RecipeArtifact", "RecipeLibrary", "export_recipe", "install_default_specs"]
From 0fac222b3884ff3d4057e9d9ee74bfc4c937a5f1 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:20:48 +0530
Subject: [PATCH 056/168] radeon forge: expose recipe import export tools
---
extra/radeon_forge/synthesis/tools.py | 38 ++++++++++++++++++++++++---
1 file changed, 34 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/synthesis/tools.py b/extra/radeon_forge/synthesis/tools.py
index 2f1d98dc7d2d0..5b11b602b662e 100644
--- a/extra/radeon_forge/synthesis/tools.py
+++ b/extra/radeon_forge/synthesis/tools.py
@@ -8,6 +8,7 @@
from ..oracles.mockgpu import MockGPUOracle
from ..permissions import Action
from ..runtime.tools import ToolRegistry, ToolSpec
+from .recipe import RecipeLibrary, export_recipe
from .workspace import CandidateWorkspace
@@ -16,6 +17,13 @@ def __init__(self, workspace: CandidateWorkspace, project_root: str | Path):
self.workspace = workspace
self.project_root = Path(project_root).resolve()
self.mockgpu = MockGPUOracle(self.project_root)
+ self.recipes = RecipeLibrary(workspace)
+
+ def _project_path(self, value: str, *, must_exist: bool = False) -> Path:
+ path = (self.project_root / value).resolve() if not Path(value).is_absolute() else Path(value).resolve()
+ if path != self.project_root and self.project_root not in path.parents: raise ValueError("path must stay inside the private workspace")
+ if must_exist and not path.is_file(): raise FileNotFoundError(path)
+ return path
def list_specs(self, args: Mapping[str, Any]) -> Any:
return {"specs": [asdict(x) | {"spec_id": x.spec_id} for x in self.workspace.specs()]}
@@ -32,7 +40,8 @@ def validate_mockgpu(self, args: Mapping[str, Any]) -> Any:
spec = self.workspace.load_spec(candidate.spec_id)
if not spec.mockgpu_command: raise ValueError("spec has no MockGPU oracle command")
command = self.workspace.render_command(spec.mockgpu_command, spec, candidate, self.project_root)
- result = self.mockgpu.run(command, env={"RADEON_FORGE_CANDIDATE": candidate.source_path})
+ result = self.mockgpu.run(command, env={"RADEON_FORGE_CANDIDATE": candidate.source_path,
+ "RADEON_FORGE_RECIPE_BUNDLE": str(spec.metadata.get("recipe_bundle", ""))})
updated = self.workspace.update(candidate.candidate_id, "mockgpu_passed" if result.passed else "mockgpu_failed", {"mockgpu": result.to_dict()})
return asdict(updated)
@@ -43,17 +52,38 @@ def benchmark_hardware(self, args: Mapping[str, Any]) -> Any:
spec = self.workspace.load_spec(candidate.spec_id)
if not spec.hardware_command: raise ValueError("spec has no hardware benchmark command")
command = self.workspace.render_command(spec.hardware_command, spec, candidate, self.project_root)
- env = {**os.environ, "DEV": "AMD", "RADEON_FORGE_CANDIDATE": candidate.source_path, "PYTHONUNBUFFERED": "1"}
+ env = {**os.environ, "DEV": "AMD", "RADEON_FORGE_CANDIDATE": candidate.source_path,
+ "RADEON_FORGE_RECIPE_BUNDLE": str(spec.metadata.get("recipe_bundle", "")), "PYTHONUNBUFFERED": "1"}
started = time.perf_counter_ns()
- proc = subprocess.run(command, cwd=self.project_root, env=env, text=True, capture_output=True, timeout=int(args.get("timeout_seconds", 900)))
+ proc = subprocess.run(command, cwd=str(spec.metadata.get("recipe_bundle", self.project_root)), env=env, text=True, capture_output=True,
+ timeout=int(args.get("timeout_seconds", 900)))
evidence = {"command": command, "returncode": proc.returncode, "elapsed_ms": (time.perf_counter_ns()-started)/1e6,
- "stdout": proc.stdout[-50000:], "stderr": proc.stderr[-50000:], "target": "gfx1100"}
+ "stdout": proc.stdout[-50000:], "stderr": proc.stderr[-50000:], "target": spec.target}
updated = self.workspace.update(candidate.candidate_id, "hardware_passed" if proc.returncode == 0 else "hardware_failed", {"hardware": evidence})
return asdict(updated)
+ def list_recipes(self, args: Mapping[str, Any]) -> Any:
+ return {"recipes": [asdict(x) for x in self.recipes.installed()]}
+
+ def inspect_recipe(self, args: Mapping[str, Any]) -> Any:
+ return self.recipes.inspect(str(args["recipe_id"]))
+
+ def import_recipe(self, args: Mapping[str, Any]) -> Any:
+ path = self._project_path(str(args["path"]), must_exist=True)
+ return asdict(self.recipes.install_file(path))
+
+ def export_recipe_file(self, args: Mapping[str, Any]) -> Any:
+ output = self._project_path(str(args["output"]))
+ path = export_recipe(self.workspace, str(args["spec_id"]), output, str(args["candidate_id"]) if args.get("candidate_id") else None)
+ return {"path": str(path), "sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest(), "portable": True}
+
def install(self, registry: ToolRegistry) -> None:
registry.register(ToolSpec("list_kernel_specs", "List typed megakernel and fused-kernel contracts", {"type":"object","properties":{}}), self.list_specs)
registry.register(ToolSpec("list_kernel_candidates", "List staged generated implementations and their oracle status", {"type":"object","properties":{"spec_id":{"type":"string"}}}), self.list_candidates)
registry.register(ToolSpec("stage_kernel_candidate", "Write one disposable implementation for a typed kernel specification", {"type":"object","required":["spec_id","source","hypothesis"],"properties":{"spec_id":{"type":"string"},"source":{"type":"string"},"hypothesis":{"type":"string"},"parent_id":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.stage_candidate)
registry.register(ToolSpec("validate_candidate_mockgpu", "Execute a generated AMD candidate through tinygrad's RDNA3 MockGPU semantic oracle", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"}}}, Action.COMPILE), self.validate_mockgpu)
registry.register(ToolSpec("benchmark_candidate_w7900", "Benchmark a MockGPU-passing candidate on the real local W7900", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"},"timeout_seconds":{"type":"integer"},"allow_without_mockgpu":{"type":"boolean"}}}, Action.BENCHMARK), self.benchmark_hardware)
+ registry.register(ToolSpec("list_forge_recipes", "List portable installed optimization recipes", {"type":"object","properties":{}}), self.list_recipes)
+ registry.register(ToolSpec("inspect_forge_recipe", "Read the intent, invariants, oracle and artifact inventory of an installed optimization recipe", {"type":"object","required":["recipe_id"],"properties":{"recipe_id":{"type":"string"}}}), self.inspect_recipe)
+ registry.register(ToolSpec("import_forge_recipe", "Install one portable .forge.toml optimization recipe from the private workspace", {"type":"object","required":["path"],"properties":{"path":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.import_recipe)
+ registry.register(ToolSpec("export_forge_recipe", "Export a contract and optional implementation cache as one shareable .forge.toml file", {"type":"object","required":["spec_id","output"],"properties":{"spec_id":{"type":"string"},"candidate_id":{"type":"string"},"output":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.export_recipe_file)
From b57e2a8ec812b16aa569514222a8eef5a9a67462 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:21:55 +0530
Subject: [PATCH 057/168] radeon forge: add standalone recipe cli
---
extra/radeon_forge/recipe_cli.py | 49 ++++++++++++++++++++++++++++++++
1 file changed, 49 insertions(+)
create mode 100644 extra/radeon_forge/recipe_cli.py
diff --git a/extra/radeon_forge/recipe_cli.py b/extra/radeon_forge/recipe_cli.py
new file mode 100644
index 0000000000000..dacde5645759c
--- /dev/null
+++ b/extra/radeon_forge/recipe_cli.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import argparse, json
+from dataclasses import asdict
+from pathlib import Path
+
+from .synthesis import CandidateWorkspace, ForgeRecipe, RecipeLibrary, export_recipe
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Import, inspect and export portable Radeon Forge optimization recipes")
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ inspect_p = sub.add_parser("inspect", help="Validate and inspect one .forge.toml file without installing it")
+ inspect_p.add_argument("recipe", type=Path)
+
+ install_p = sub.add_parser("install", help="Install a recipe into a local Forge optimization library")
+ install_p.add_argument("recipe", type=Path)
+ install_p.add_argument("--workspace", type=Path, default=Path.home() / ".cache" / "radeon-forge")
+
+ list_p = sub.add_parser("list", help="List installed portable recipes")
+ list_p.add_argument("--workspace", type=Path, default=Path.home() / ".cache" / "radeon-forge")
+
+ export_p = sub.add_parser("export", help="Export a local contract and optional implementation cache as one file")
+ export_p.add_argument("--workspace", type=Path, default=Path.home() / ".cache" / "radeon-forge")
+ export_p.add_argument("--spec-id", required=True)
+ export_p.add_argument("--candidate-id")
+ export_p.add_argument("--output", type=Path, required=True)
+
+ args = parser.parse_args()
+ if args.command == "inspect":
+ recipe = ForgeRecipe.load(args.recipe)
+ payload = asdict(recipe)
+ payload.pop("source_text", None)
+ payload["recipe_id"] = recipe.recipe_id
+ payload["artifacts"] = [{**asdict(x), "content": f"<{len(x.content.encode())} bytes>", "sha256": x.sha256} for x in recipe.artifacts]
+ print(json.dumps(payload, indent=2, default=str))
+ return
+
+ workspace = CandidateWorkspace(args.workspace)
+ library = RecipeLibrary(workspace)
+ if args.command == "install": print(json.dumps(asdict(library.install_file(args.recipe)), indent=2))
+ elif args.command == "list": print(json.dumps([asdict(x) for x in library.installed()], indent=2))
+ elif args.command == "export":
+ path = export_recipe(workspace, args.spec_id, args.output, args.candidate_id)
+ print(json.dumps({"path": str(path.resolve()), "bytes": path.stat().st_size}, indent=2))
+
+
+if __name__ == "__main__": main()
From c889ab49c7d46a1ba8b5aeb171da33eba70a6ac0 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:22:26 +0530
Subject: [PATCH 058/168] radeon forge: add portable batch-one recipe example
---
.../recipes/batch1_decode_rdna3.forge.toml | 66 +++++++++++++++++++
1 file changed, 66 insertions(+)
create mode 100644 extra/radeon_forge/recipes/batch1_decode_rdna3.forge.toml
diff --git a/extra/radeon_forge/recipes/batch1_decode_rdna3.forge.toml b/extra/radeon_forge/recipes/batch1_decode_rdna3.forge.toml
new file mode 100644
index 0000000000000..098243619d877
--- /dev/null
+++ b/extra/radeon_forge/recipes/batch1_decode_rdna3.forge.toml
@@ -0,0 +1,66 @@
+format_version = 1
+name = "batch1-decode-rdna3"
+description = "Portable optimization contract for low-latency, batch-one transformer decode on gfx1100."
+operation = "Specialize one transformer decode block or high-impact decode subgraph for a fixed local private-agent workload."
+target = "gfx1100"
+objective = "Minimize P95 inter-token latency and launches per token without violating numerical, KV-cache, memory, or task-quality constraints."
+agent_brief = """
+Treat this file as intent and evidence, not as a kernel DSL. Inspect the local model, shapes, generated tinygrad schedule, ISA and profile before choosing an implementation. You may fuse, reorder, specialize, replace abstractions, or generate a direct persistent implementation. The optional implementation cache is only a starting point. Keep observations separate from inferences, predict measurable changes before each experiment, and let the independent oracles reject bad ideas.
+"""
+invariants = [
+ "Match the trusted tinygrad reference within the configured tolerance.",
+ "Preserve KV-cache indexing and visibility semantics across repeated decode steps.",
+ "Pass tinygrad DEV=MOCK+AMD before any real-hardware benchmark unless explicitly waived.",
+ "Never use MockGPU time as performance evidence.",
+ "Preserve the frozen agent workload task-success threshold.",
+ "Do not make outbound network calls during core inference, profiling, generation, or validation."
+]
+unknowns = [
+ "The best fusion boundary is workload- and model-specific.",
+ "The optimal register/LDS tradeoff must be measured on the recipient W7900.",
+ "A full megakernel may lose to a smaller fused subgraph; benchmark both."
+]
+language = "python"
+extension = ".py"
+entrypoint = "build_kernel"
+
+[shapes]
+batch = 1
+sequence = "single decode token"
+model = "bound by the recipient workload"
+
+[dtypes]
+activations = "bf16 or fp16"
+accumulation = "fp32 where the oracle requires it"
+kv_cache = "bound by the recipient model"
+
+[compatibility]
+arch = "gfx1100"
+device_class = "Radeon PRO W7900"
+same_hardware_recommended = true
+
+[acceptance]
+maximum_task_success_drop_percent = 1.0
+maximum_invalid_tool_calls = 0
+maximum_crashes = 0
+external_network_calls = 0
+primary_metric = "p95_inter_token_latency_ms"
+
+[oracle]
+mockgpu_command = ["python3", "{candidate}", "--forge-mode", "mockgpu"]
+hardware_command = ["python3", "{candidate}", "--forge-mode", "benchmark", "--json"]
+heldout_command = ["python3", "{candidate}", "--forge-mode", "heldout", "--json"]
+
+[[artifact]]
+path = "knowledge/optimization_notes.md"
+role = "knowledge"
+description = "Free-form domain knowledge for the intelligent executor; not executable code."
+content = """
+# Batch-one RDNA3 decode notes
+
+Prioritize end-to-end decode latency over isolated FLOP/s. Useful evidence includes launch count per token, per-layer and per-kernel time, VGPR/SGPR/LDS/scratch metadata, occupancy, memory traffic, wait/stall evidence, prefix/KV-cache behavior, and tool-resumption overhead.
+
+Candidate ideas are not requirements: direct model-shape specialization, residual plus RMSNorm fusion, dequantization plus GEMV, RoPE/layout fusion, attention-decode specialization, persistent transformer-block execution, and removal of small launch boundaries. An intelligent agent may discard all of these when the profile contradicts them.
+
+The implementation is disposable. Durable knowledge is the intent, invariants, reference behavior, numerical tolerance, frozen workload, hardware evidence, failed experiments, and acceptance criteria.
+"""
From 3c5df2493f388196b15c28bb324a8576ba8ea0bc Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:22:59 +0530
Subject: [PATCH 059/168] radeon forge: test portable recipe round trips
---
test/test_radeon_forge_recipe.py | 99 ++++++++++++++++++++++++++++++++
1 file changed, 99 insertions(+)
create mode 100644 test/test_radeon_forge_recipe.py
diff --git a/test/test_radeon_forge_recipe.py b/test/test_radeon_forge_recipe.py
new file mode 100644
index 0000000000000..a8798f5167b57
--- /dev/null
+++ b/test/test_radeon_forge_recipe.py
@@ -0,0 +1,99 @@
+import base64
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.synthesis import CandidateWorkspace, ForgeRecipe, KernelSpec, RecipeLibrary, export_recipe
+
+
+class TestForgeRecipe(unittest.TestCase):
+ def _recipe_text(self, seed: str = "print('seed')\n") -> str:
+ encoded = base64.b64encode(seed.encode()).decode()
+ return f'''format_version = 1
+name = "portable-vopd"
+description = "One-file optimization knowledge"
+operation = "Tune an RDNA3 instruction schedule"
+target = "gfx1100"
+objective = "minimize P95 latency"
+agent_brief = "Inspect evidence, freely regenerate the implementation, and trust only the oracle."
+invariants = ["match reference", "never use MockGPU timing"]
+unknowns = ["best schedule is hardware dependent"]
+seed_artifact = "seed.py"
+
+[compatibility]
+arch = "gfx1100"
+
+[acceptance]
+maximum_error = 0.000001
+
+[oracle]
+mockgpu_command = ["python3", "{{candidate}}", "--bundle", "{{bundle}}"]
+hardware_command = ["python3", "{{candidate}}", "--benchmark"]
+
+[[artifact]]
+path = "seed.py"
+role = "implementation_cache"
+sha256 = "{__import__('hashlib').sha256(seed.encode()).hexdigest()}"
+content_base64 = "{encoded}"
+
+[[artifact]]
+path = "knowledge/notes.md"
+role = "knowledge"
+content = "The implementation is disposable."
+'''
+
+ def test_install_is_content_addressed_and_seed_is_unverified(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source_a, source_b = root / "a.forge.toml", root / "b.forge.toml"
+ source_a.write_text(self._recipe_text(), encoding="utf-8")
+ source_b.write_text(self._recipe_text(), encoding="utf-8")
+ recipe_a, recipe_b = ForgeRecipe.load(source_a), ForgeRecipe.load(source_b)
+ self.assertEqual(recipe_a.recipe_id, recipe_b.recipe_id)
+
+ workspace = CandidateWorkspace(root / "library")
+ installed = RecipeLibrary(workspace).install(recipe_a)
+ self.assertTrue((Path(installed.bundle_root) / "knowledge/notes.md").is_file())
+ self.assertIsNotNone(installed.seed_candidate_id)
+ candidate = workspace.load_candidate(installed.seed_candidate_id)
+ self.assertEqual(candidate.status, "imported_unverified")
+ self.assertEqual(Path(candidate.source_path).read_text(encoding="utf-8"), "print('seed')\n")
+
+ spec = workspace.load_spec(installed.spec_id)
+ rendered = workspace.render_command(spec.mockgpu_command, spec, candidate, root)
+ self.assertEqual(rendered[1], candidate.source_path)
+ self.assertEqual(rendered[3], installed.bundle_root)
+
+ def test_rejects_path_traversal(self):
+ text = self._recipe_text().replace('path = "seed.py"', 'path = "../seed.py"', 1).replace('seed_artifact = "seed.py"', 'seed_artifact = "../seed.py"')
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "bad.forge.toml"
+ path.write_text(text, encoding="utf-8")
+ with self.assertRaises(ValueError): ForgeRecipe.load(path)
+
+ def test_export_import_round_trip_preserves_contract_and_cache(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source_workspace = CandidateWorkspace(root / "source")
+ spec = KernelSpec(
+ name="roundtrip", operation="specialize batch-one decode", target="gfx1100", language="python", extension=".py",
+ invariants=("match reference", "no remote API"), objective="minimize p95 token latency",
+ mockgpu_command=("python3", "{candidate}"), hardware_command=("python3", "{candidate}", "--benchmark"),
+ metadata={"recipe_agent_brief":"Use the oracle as the contract and freely rewrite the implementation.",
+ "recipe_compatibility":{"arch":"gfx1100"}, "recipe_acceptance":{"max_error":1e-6}},
+ )
+ source_workspace.save_spec(spec)
+ candidate = source_workspace.create_candidate(spec.spec_id, "print('candidate')\n", "measured VOPD schedule")
+ exported = export_recipe(source_workspace, spec.spec_id, root / "shared.forge.toml", candidate.candidate_id)
+
+ loaded = ForgeRecipe.load(exported)
+ self.assertEqual(loaded.target, "gfx1100")
+ self.assertEqual(loaded.invariants, spec.invariants)
+ destination = CandidateWorkspace(root / "destination")
+ installed = RecipeLibrary(destination).install(loaded)
+ imported = destination.load_candidate(installed.seed_candidate_id)
+ self.assertEqual(Path(imported.source_path).read_text(encoding="utf-8"), "print('candidate')\n")
+ self.assertEqual(imported.status, "imported_unverified")
+
+
+if __name__ == "__main__": unittest.main()
From bf5b90950f7d8da1280faa44543b11f39b22bdb3 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:23:26 +0530
Subject: [PATCH 060/168] radeon forge: expose portable recipes in engine state
---
extra/radeon_forge/runtime/engine.py | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index 2b1af922c167e..a68fbcca15098 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -14,7 +14,9 @@
DEFAULT_SYSTEM_PROMPT = """You are Radeon Forge, a private local software and inference performance engineer.
-Use evidence before making performance claims. Separate observations, inferences and unknowns. Prefer reversible changes and preserve correctness. You may inspect the private workspace, author disposable target-specific kernel candidates, validate them through tinygrad MockGPU, and request permission for real W7900 benchmarks. Never treat MockGPU timing as performance evidence."""
+Use evidence before making performance claims. Separate observations, inferences and unknowns. Prefer reversible changes and preserve correctness. You may inspect the private workspace, author disposable target-specific kernel candidates, import portable optimization recipes, validate implementations through tinygrad MockGPU, and request permission for real W7900 benchmarks. Never treat MockGPU timing as performance evidence.
+
+Optimization recipes are contracts, not programming languages. Read their free-form intent, invariants, oracle, knowledge and failed experiments; then use your judgment to regenerate or radically restructure implementations. Cached source is merely one prior compilation and must never outrank the oracle."""
class ForgeEngine:
@@ -25,7 +27,8 @@ def __init__(self, backend: InferenceBackend, workspace: str | Path, system_prom
WorkspaceTools(self.workspace).install(self.tools)
self.optimization_workspace = CandidateWorkspace(self.workspace / ".radeon_forge")
install_default_specs(self.optimization_workspace)
- OptimizationTools(self.optimization_workspace, self.workspace).install(self.tools)
+ self.optimization_tools = OptimizationTools(self.optimization_workspace, self.workspace)
+ self.optimization_tools.install(self.tools)
self._sessions: dict[str, AgentSession] = {}
self._lock = threading.RLock()
@@ -52,6 +55,7 @@ def profile(self, session_id: str) -> dict[str, Any]: return build_profile_repor
def optimization_state(self) -> dict[str, Any]:
return {"specs": [asdict(x) | {"spec_id": x.spec_id} for x in self.optimization_workspace.specs()],
- "candidates": [asdict(x) for x in self.optimization_workspace.candidates()]}
+ "candidates": [asdict(x) for x in self.optimization_workspace.candidates()],
+ "recipes": [asdict(x) for x in self.optimization_tools.recipes.installed()]}
def close(self) -> None: self.backend.close()
From ccb3c44c37e4d1fd42fe12659ae775fe25d926f5 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:24:33 +0530
Subject: [PATCH 061/168] radeon forge: add recipe ui endpoints
---
extra/radeon_forge/ui/server.py | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/ui/server.py b/extra/radeon_forge/ui/server.py
index 41ca6177fa909..c9513009a1113 100644
--- a/extra/radeon_forge/ui/server.py
+++ b/extra/radeon_forge/ui/server.py
@@ -69,10 +69,17 @@ def do_GET(self):
def do_POST(self):
path = urlparse(self.path).path
try:
+ body = self._body()
if path == "/api/sessions": return self._json(self.engine.create_session().snapshot(), HTTPStatus.CREATED)
+ if path == "/api/recipes/import":
+ result = self.engine.optimization_tools.import_recipe({"path": str(body.get("path", ""))})
+ return self._json(result, HTTPStatus.CREATED)
+ if path == "/api/recipes/export":
+ result = self.engine.optimization_tools.export_recipe_file({"spec_id": str(body.get("spec_id", "")),
+ "candidate_id": body.get("candidate_id"), "output": str(body.get("output", ""))})
+ return self._json(result, HTTPStatus.CREATED)
session, tail = self._session_route()
if session is None: return self.send_error(404)
- body = self._body()
if tail == "messages":
events = session.send(str(body.get("content", "")), int(body.get("max_tokens", 512)), float(body.get("temperature", 0.0)))
return self._json({"events": [asdict(x) for x in events], "session": session.snapshot()})
@@ -85,7 +92,7 @@ def do_POST(self):
event = session.reject_tool(str(body.get("reason", "Rejected by user")))
return self._json({"event": asdict(event), "session": session.snapshot()})
return self.send_error(404)
- except (ValueError, RuntimeError) as exc: return self._json({"error": str(exc), "type": type(exc).__name__}, 400)
+ except (ValueError, RuntimeError, FileNotFoundError) as exc: return self._json({"error": str(exc), "type": type(exc).__name__}, 400)
except Exception as exc: return self._json({"error": str(exc), "type": type(exc).__name__}, 500)
From a2cd1b295586bb27be805a8acd9583484a8f3e91 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:25:07 +0530
Subject: [PATCH 062/168] radeon forge: add portable recipe library ui
---
extra/radeon_forge/ui/static/index.html | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/extra/radeon_forge/ui/static/index.html b/extra/radeon_forge/ui/static/index.html
index f14cd9ab0c924..fc5d8f6de0ea6 100644
--- a/extra/radeon_forge/ui/static/index.html
+++ b/extra/radeon_forge/ui/static/index.html
@@ -63,6 +63,10 @@
Typed kernel contracts Intent and invariants are durable; generated implementations are disposable.
Refresh
Candidate pipeline Staged → MockGPU → W7900 → accepted / rejected
+
Portable optimization recipes Share intent, invariants, oracle, knowledge, and an optional disposable implementation cache in one file.
+
Import recipe
+
+
From 862ecd52968f833331f10652757524678e2ab531 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:25:21 +0530
Subject: [PATCH 063/168] radeon forge: style recipe library ui
---
extra/radeon_forge/ui/static/kernels.css | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/extra/radeon_forge/ui/static/kernels.css b/extra/radeon_forge/ui/static/kernels.css
index f2f4804df8c22..1b65cbfb42930 100644
--- a/extra/radeon_forge/ui/static/kernels.css
+++ b/extra/radeon_forge/ui/static/kernels.css
@@ -1 +1 @@
-.kernel-layout{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:22px 24px 24px;width:100%;min-height:0}.kernel-list{padding:12px;overflow:auto}.kernel-card{background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:10px}.kernel-card h4{margin:0 0 6px;font-size:14px}.kernel-card p{color:var(--muted);font-size:11px;line-height:1.5}.kernel-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.status{padding:4px 7px;border-radius:7px;background:#262d3a;border:1px solid var(--line);font-size:9px;text-transform:uppercase;letter-spacing:.07em}.status.mockgpu_passed,.status.hardware_passed{color:var(--good);border-color:rgba(61,220,151,.28);background:rgba(61,220,151,.08)}.status.mockgpu_failed,.status.hardware_failed{color:#ff8e98;border-color:rgba(255,95,109,.28);background:rgba(255,95,109,.08)}.contract{margin-top:10px;padding:9px;background:#0f1219;border:1px solid var(--line);border-radius:9px;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#aeb8c8;white-space:pre-wrap;max-height:150px;overflow:auto}@media(max-width:900px){.kernel-layout{grid-template-columns:1fr}}
\ No newline at end of file
+.kernel-layout{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:22px 24px 24px;width:100%;min-height:0;overflow:auto}.kernel-list{padding:12px;overflow:auto}.kernel-card{background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:10px}.kernel-card h4{margin:0 0 6px;font-size:14px}.kernel-card p{color:var(--muted);font-size:11px;line-height:1.5}.kernel-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.status{padding:4px 7px;border-radius:7px;background:#262d3a;border:1px solid var(--line);font-size:9px;text-transform:uppercase;letter-spacing:.07em}.status.mockgpu_passed,.status.hardware_passed{color:var(--good);border-color:rgba(61,220,151,.28);background:rgba(61,220,151,.08)}.status.mockgpu_failed,.status.hardware_failed{color:#ff8e98;border-color:rgba(255,95,109,.28);background:rgba(255,95,109,.08)}.status.imported_unverified{color:#ffd278;border-color:rgba(245,185,66,.28);background:rgba(245,185,66,.08)}.contract{margin-top:10px;padding:9px;background:#0f1219;border:1px solid var(--line);border-radius:9px;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#aeb8c8;white-space:pre-wrap;max-height:150px;overflow:auto}.recipe-panel{grid-column:1/-1}.recipe-import{display:flex;gap:10px;padding:14px 14px 0}.recipe-import input{flex:1;background:#0f1219;border:1px solid var(--line);border-radius:10px;color:var(--text);padding:10px 12px;outline:0}.recipe-import input:focus{border-color:rgba(255,92,53,.65)}.kernel-actions{display:flex;gap:8px;margin-top:10px}.kernel-actions button{font-size:10px}@media(max-width:900px){.kernel-layout{grid-template-columns:1fr}.recipe-panel{grid-column:auto}}
From 7b187c67930dbd6393bafcf07d5b3b6d515d3a5c Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:26:07 +0530
Subject: [PATCH 064/168] radeon forge: wire recipe import export ui
---
extra/radeon_forge/ui/static/app.js | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/extra/radeon_forge/ui/static/app.js b/extra/radeon_forge/ui/static/app.js
index 07bc1c9a25db6..3ddf28cf123a5 100644
--- a/extra/radeon_forge/ui/static/app.js
+++ b/extra/radeon_forge/ui/static/app.js
@@ -1,6 +1,6 @@
const state={session:null,sessions:[],health:null,optimization:null,tab:'console'};
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
-const toast=msg=>{const el=$('#toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),2200)};
+const toast=msg=>{const el=$('#toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),2600)};
async function api(path,opts={}){const res=await fetch(path,{headers:{'Content-Type':'application/json'},...opts});const data=await res.json();if(!res.ok)throw new Error(data.error||`HTTP ${res.status}`);return data}
function fmtMs(v){return v==null?'—':`${Number(v).toFixed(v<10?2:1)} ms`}
function esc(v){return String(v??'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))}
@@ -19,6 +19,8 @@ async function rejectTool(){const out=await api(`/api/sessions/${state.session.s
async function refreshProfile(){if(!state.session)return;const p=await api(`/api/sessions/${state.session.session_id}/profile`),s=p.summary||{};$('#p50-token').textContent=fmtMs(s.token_wall_ms_p50);$('#p95-token').textContent=fmtMs(s.token_wall_ms_p95);$('#launches-token').textContent=s.mean_kernel_count_per_token==null?'—':Number(s.mean_kernel_count_per_token).toFixed(1);$('#tool-time').textContent=fmtMs(s.tool_time_ms);const findings=$('#findings');findings.innerHTML='';(p.findings||[]).forEach(f=>{const el=document.createElement('div');el.className=`finding ${f.severity}`;el.innerHTML=`
${esc(f.status)} ${esc(f.title)}
${esc((f.evidence||[]).join(' · '))}
Next: ${esc(f.recommendation)}
`;findings.append(el)});if(!p.findings?.length)findings.innerHTML='
No diagnosis yet. Run an agent turn first.
';renderAttribution(s.durations_ms_by_kind||{})}
function renderAttribution(d){const box=$('#attribution');box.innerHTML='';const entries=Object.entries(d).sort((a,b)=>b[1]-a[1]),max=Math.max(1,...entries.map(x=>x[1]));entries.forEach(([k,v])=>{const el=document.createElement('div');el.className='bar-row';el.innerHTML=`
${esc(k)} ${fmtMs(v)}
`;box.append(el)});if(!entries.length)box.textContent='No trace data yet.'}
async function refreshTrace(){if(!state.session)return;const t=await api(`/api/sessions/${state.session.session_id}/trace`),box=$('#timeline');box.innerHTML='';(t.events||[]).forEach(e=>{const el=document.createElement('div');el.className='trace-row';const attrs=Object.entries(e.attributes||{}).slice(0,4).map(([k,v])=>`${k}=${v}`).join(' · ');el.innerHTML=`
${esc(e.kind)} ${esc(e.name)} ${esc(attrs)} ${fmtMs(e.duration_ms)} `;box.append(el)});if(!t.events?.length)box.innerHTML='
'}
-async function refreshKernels(){state.optimization=await api('/api/optimization');const specs=$('#kernel-specs'),candidates=$('#kernel-candidates');specs.innerHTML='';candidates.innerHTML='';(state.optimization.specs||[]).forEach(s=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(s.name)} ${esc(s.operation)}
${esc(s.target)} ${esc(s.language)} ${esc(s.objective)}
${esc(JSON.stringify({shapes:s.shapes,dtypes:s.dtypes,invariants:s.invariants},null,2))}
`;specs.append(el)});(state.optimization.candidates||[]).forEach(c=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(c.candidate_id)} ${esc(c.hypothesis||'No hypothesis recorded')}
${esc(c.status)} ${esc(c.spec_id)}
${esc(JSON.stringify(c.evidence||{},null,2))}
`;candidates.append(el)});if(!state.optimization.candidates?.length)candidates.innerHTML='
No candidate has been staged. Ask Forge to list kernel specs and generate one.
'}
+async function exportCandidate(candidate){const output=`exports/${candidate.candidate_id}.forge.toml`;const out=await api('/api/recipes/export',{method:'POST',body:JSON.stringify({spec_id:candidate.spec_id,candidate_id:candidate.candidate_id,output})});toast(`Exported ${out.path}`);await refreshKernels()}
+async function importRecipe(){const input=$('#recipe-path'),path=input.value.trim();if(!path)return;const out=await api('/api/recipes/import',{method:'POST',body:JSON.stringify({path})});input.value='';toast(`Installed ${out.recipe_id}`);await refreshKernels()}
+async function refreshKernels(){state.optimization=await api('/api/optimization');const specs=$('#kernel-specs'),candidates=$('#kernel-candidates'),recipes=$('#recipe-list');specs.innerHTML='';candidates.innerHTML='';recipes.innerHTML='';(state.optimization.specs||[]).forEach(s=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(s.name)} ${esc(s.operation)}
${esc(s.target)} ${esc(s.language)} ${esc(s.objective)}
${esc(JSON.stringify({shapes:s.shapes,dtypes:s.dtypes,invariants:s.invariants,agent_brief:s.metadata?.recipe_agent_brief},null,2))}
`;specs.append(el)});(state.optimization.candidates||[]).forEach(c=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(c.candidate_id)} ${esc(c.hypothesis||'No hypothesis recorded')}
${esc(c.status)} ${esc(c.spec_id)}
${esc(JSON.stringify(c.evidence||{},null,2))}
Export one-file recipe
`;el.querySelector('.export-candidate').onclick=()=>exportCandidate(c).catch(e=>toast(e.message));candidates.append(el)});(state.optimization.recipes||[]).forEach(r=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(r.recipe_id)} Installed portable contract. Cached code remains unverified until local oracles pass.
${esc(r.spec_id)} ${r.seed_candidate_id?'seed cache ':''}
${esc(JSON.stringify({bundle:r.bundle_root,artifacts:r.artifact_hashes},null,2))}
`;recipes.append(el)});if(!state.optimization.candidates?.length)candidates.innerHTML='
No candidate has been staged. Ask Forge to list kernel specs and generate one.
';if(!state.optimization.recipes?.length)recipes.innerHTML='
No portable recipe installed yet. Import a .forge.toml file from the workspace.
'}
function switchTab(tab){state.tab=tab;$$('.tab').forEach(x=>x.classList.remove('active'));$(`#${tab}-tab`).classList.add('active');$$('[data-tab]').forEach(x=>x.classList.toggle('active',x.dataset.tab===tab));if(tab==='profile')refreshProfile();if(tab==='trace')refreshTrace();if(tab==='kernels')refreshKernels()}
-$('#new-session').onclick=createSession;$('#composer').onsubmit=async e=>{e.preventDefault();const input=$('#prompt'),text=input.value.trim();if(!text)return;input.value='';try{await sendMessage(text)}catch(err){toast(err.message)}};$('#approve-tool').onclick=()=>approveTool().catch(e=>toast(e.message));$('#reject-tool').onclick=()=>rejectTool().catch(e=>toast(e.message));$('#refresh-profile').onclick=()=>refreshProfile().catch(e=>toast(e.message));$('#refresh-trace').onclick=()=>refreshTrace().catch(e=>toast(e.message));$('#refresh-kernels').onclick=()=>refreshKernels().catch(e=>toast(e.message));$$('[data-tab]').forEach(x=>x.onclick=()=>switchTab(x.dataset.tab));boot();
+$('#new-session').onclick=createSession;$('#composer').onsubmit=async e=>{e.preventDefault();const input=$('#prompt'),text=input.value.trim();if(!text)return;input.value='';try{await sendMessage(text)}catch(err){toast(err.message)}};$('#approve-tool').onclick=()=>approveTool().catch(e=>toast(e.message));$('#reject-tool').onclick=()=>rejectTool().catch(e=>toast(e.message));$('#refresh-profile').onclick=()=>refreshProfile().catch(e=>toast(e.message));$('#refresh-trace').onclick=()=>refreshTrace().catch(e=>toast(e.message));$('#refresh-kernels').onclick=()=>refreshKernels().catch(e=>toast(e.message));$('#import-recipe').onclick=()=>importRecipe().catch(e=>toast(e.message));$$('[data-tab]').forEach(x=>x.onclick=()=>switchTab(x.dataset.tab));boot();
From 57d4ee42ff448009c0be27b6808cbeaf6f1da53b Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:31:26 +0530
Subject: [PATCH 065/168] radeon forge: stream real tinygrad kernel profile
events
---
.../backends/tinygrad_llama_worker.py | 88 +++++++++++++++++--
1 file changed, 83 insertions(+), 5 deletions(-)
diff --git a/extra/radeon_forge/backends/tinygrad_llama_worker.py b/extra/radeon_forge/backends/tinygrad_llama_worker.py
index 92a042cef4869..19c659de7cfca 100644
--- a/extra/radeon_forge/backends/tinygrad_llama_worker.py
+++ b/extra/radeon_forge/backends/tinygrad_llama_worker.py
@@ -2,17 +2,80 @@
import argparse, json, sys, time
from pathlib import Path
+from typing import Any, Callable
-from tinygrad import Device, GlobalCounters, Tensor
+from tinygrad import Context, Device, GlobalCounters, Tensor
+from tinygrad.device import Compiled
from tinygrad.nn.state import get_parameters
from examples.llama3 import Tokenizer, build_transformer
+MAX_PROFILE_EVENTS_PER_PHASE = 8192
+
+
def send(payload):
sys.stdout.write(json.dumps(payload, default=str) + "\n")
sys.stdout.flush()
+def _name(value: Any) -> str:
+ return str(getattr(value, "display_name", value))
+
+
+def _collect_profile_events(start: int) -> list[dict[str, Any]]:
+ """Flatten tinygrad device profile ranges into portable kernel evidence.
+
+ Timestamps are device-local, so only durations and ordering are exported.
+ Forge wall-clock spans remain the cross-layer timeline authority.
+ """
+ raw = list(Compiled.profile_events[start:])
+ del Compiled.profile_events[start:]
+ ret: list[dict[str, Any]] = []
+ for event in raw:
+ if hasattr(event, "ents") and hasattr(event, "sigs"):
+ for entry in event.ents:
+ try:
+ st, en = event.sigs[entry.st_id], event.sigs[entry.en_id]
+ duration_us = float(en - st)
+ except Exception: continue
+ device = str(getattr(entry, "device", "UNKNOWN"))
+ if device in {"CPU", "TINY"} or duration_us < 0: continue
+ ret.append({"name": _name(getattr(entry, "name", "kernel")), "device": device,
+ "duration_ms": duration_us / 1000.0, "profile_event_type": type(event).__name__,
+ "source": "tinygrad.Compiled.profile_events"})
+ elif hasattr(event, "st") and hasattr(event, "en") and getattr(event, "en") is not None:
+ try: duration_us = float(event.en - event.st)
+ except Exception: continue
+ device = str(getattr(event, "device", "UNKNOWN"))
+ if device in {"CPU", "TINY"} or duration_us < 0: continue
+ ret.append({"name": _name(getattr(event, "name", "kernel")), "device": device,
+ "duration_ms": duration_us / 1000.0, "profile_event_type": type(event).__name__,
+ "source": "tinygrad.Compiled.profile_events"})
+ return ret
+
+
+def _profiled(fn: Callable[[], Any]) -> tuple[Any, list[dict[str, Any]]]:
+ start = len(Compiled.profile_events)
+ try:
+ with Context(PROFILE=1): result = fn()
+ except BaseException:
+ _collect_profile_events(start)
+ raise
+ return result, _collect_profile_events(start)
+
+
+def _emit_kernel_events(events: list[dict[str, Any]], *, stage: str, token_index: int | None = None,
+ prompt_position: int | None = None) -> tuple[int, bool]:
+ truncated = len(events) > MAX_PROFILE_EVENTS_PER_PHASE
+ emitted = events[:MAX_PROFILE_EVENTS_PER_PHASE]
+ for sequence, event in enumerate(emitted):
+ metrics = {**event, "stage": stage, "sequence": sequence}
+ if token_index is not None: metrics["token_index"] = token_index
+ if prompt_position is not None: metrics["prompt_position"] = prompt_position
+ send({"kind": "kernel", "metrics": metrics})
+ return len(emitted), truncated
+
+
def main() -> None:
parser = argparse.ArgumentParser(description="Persistent tinygrad Llama backend for Radeon Forge")
parser.add_argument("--model", type=Path, required=True)
@@ -71,9 +134,12 @@ def encode_message(message) -> list[int]:
active_session = session_id
prefill_start = time.perf_counter_ns()
prefill_gpu_s, prefill_kernels, prefill_mem, prefill_ops = 0.0, 0, 0, 0
+ prefill_profile: list[dict[str, Any]] = []
for position in range(common, len(prompt) - 1):
GlobalCounters.reset()
- model(Tensor([[prompt[position]]], device=device), position, 0.0, 0, 0.0, 0.0, 0.0).realize()
+ _, profile = _profiled(lambda position=position: model(Tensor([[prompt[position]]], device=device), position, 0.0, 0, 0.0, 0.0, 0.0).realize())
+ for event in profile: event["prompt_position"] = position
+ prefill_profile.extend(profile)
prefill_gpu_s += GlobalCounters.time_sum_s
prefill_kernels += GlobalCounters.kernel_count
prefill_mem += GlobalCounters.global_mem
@@ -82,14 +148,21 @@ def encode_message(message) -> list[int]:
active_tokens = list(prompt)
send({"kind": "prefill", "metrics": {"wall_ms": prefill_wall_ms, "gpu_ms": prefill_gpu_s * 1e3,
"prompt_tokens": len(prompt), "prefix_reused_tokens": common, "new_prompt_tokens": max(0, len(prompt) - 1 - common),
- "kernel_count": prefill_kernels, "global_mem_bytes": prefill_mem, "global_ops": prefill_ops}})
+ "kernel_count": prefill_kernels, "global_mem_bytes": prefill_mem, "global_ops": prefill_ops,
+ "profile_kernel_events": len(prefill_profile)}})
+ prefill_truncated = len(prefill_profile) > MAX_PROFILE_EVENTS_PER_PHASE
+ for sequence, event in enumerate(prefill_profile[:MAX_PROFILE_EVENTS_PER_PHASE]):
+ send({"kind": "kernel", "metrics": {**event, "stage": "prefill", "sequence": sequence}})
+ if prefill_truncated:
+ send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": "prefill",
+ "captured": MAX_PROFILE_EVENTS_PER_PHASE, "available": len(prefill_profile)}})
start_pos, last_tok = len(prompt) - 1, prompt[-1]
generated = 0
for index in range(max_tokens):
GlobalCounters.reset()
wall_start = time.perf_counter_ns()
- tok = model(Tensor([[last_tok]], device=device), start_pos, temperature, 0, 0.0, 0.0, 0.0).item()
+ tok, profile = _profiled(lambda: model(Tensor([[last_tok]], device=device), start_pos, temperature, 0, 0.0, 0.0, 0.0).item())
wall_ms = (time.perf_counter_ns() - wall_start) / 1e6
gpu_ms = GlobalCounters.time_sum_s * 1e3
start_pos += 1
@@ -101,7 +174,12 @@ def encode_message(message) -> list[int]:
generated += 1
send({"kind": "token", "text": tokenizer.decode([tok]), "metrics": {"index": index, "wall_ms": wall_ms,
"gpu_ms": gpu_ms, "kernel_count": GlobalCounters.kernel_count, "global_mem_bytes": GlobalCounters.global_mem,
- "global_ops": GlobalCounters.global_ops, "parameter_bandwidth_gbs": (param_bytes / max(GlobalCounters.time_sum_s, 1e-12)) / 1e9}})
+ "global_ops": GlobalCounters.global_ops, "profile_kernel_events": len(profile),
+ "parameter_bandwidth_gbs": (param_bytes / max(GlobalCounters.time_sum_s, 1e-12)) / 1e9}})
+ emitted, truncated = _emit_kernel_events(profile, stage="decode", token_index=index)
+ if truncated:
+ send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": "decode", "token_index": index,
+ "captured": emitted, "available": len(profile)}})
else: send({"kind": "done", "finish_reason": "length", "metrics": {"generated_tokens": generated}})
except Exception as exc:
send({"kind": "error", "error": str(exc), "error_type": type(exc).__name__})
From 1d2a48fa04fcab0a123369ab820fe3e9af40ab38 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:32:15 +0530
Subject: [PATCH 066/168] radeon forge: reason over actual kernel profile
ranges
---
extra/radeon_forge/profiling/report.py | 91 +++++++++++++++++++++-----
1 file changed, 75 insertions(+), 16 deletions(-)
diff --git a/extra/radeon_forge/profiling/report.py b/extra/radeon_forge/profiling/report.py
index 0156e4d1ce027..2a59474079ed6 100644
--- a/extra/radeon_forge/profiling/report.py
+++ b/extra/radeon_forge/profiling/report.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import math, statistics
+from collections import defaultdict
from dataclasses import asdict, dataclass
from typing import Any, Iterable
@@ -23,37 +24,92 @@ def _percentile(values: list[float], percentile: float) -> float | None:
return ordered[idx]
+def _number(value: Any, default: float = 0.0) -> float:
+ try: return float(value)
+ except (TypeError, ValueError): return default
+
+
+def _kernel_summary(events: list[TraceEvent]) -> tuple[list[dict[str, Any]], float, int, int]:
+ grouped: dict[str, list[float]] = defaultdict(list)
+ decode_count, prefill_count = 0, 0
+ for event in events:
+ if event.name != "kernel": continue
+ duration = _number(event.attributes.get("duration_ms"))
+ if duration <= 0: continue
+ name = str(event.attributes.get("name") or event.attributes.get("kernel_name") or "unknown_kernel")
+ grouped[name].append(duration)
+ stage = str(event.attributes.get("stage", "unknown"))
+ if stage == "decode": decode_count += 1
+ elif stage == "prefill": prefill_count += 1
+ total = sum(sum(values) for values in grouped.values())
+ rows = [{"name": name, "calls": len(values), "total_ms": sum(values), "mean_ms": statistics.mean(values),
+ "p95_ms": _percentile(values, 0.95), "share": sum(values) / max(total, 1e-12)} for name, values in grouped.items()]
+ rows.sort(key=lambda row: (-row["total_ms"], row["name"]))
+ return rows, total, decode_count, prefill_count
+
+
def build_profile_report(events: Iterable[TraceEvent]) -> dict[str, Any]:
evs = list(events)
durations = {kind: sum(x.duration_ms or 0.0 for x in evs if x.kind == kind) for kind in {x.kind for x in evs}}
token_events = [x for x in evs if x.name == "token"]
- token_wall = [float(x.attributes.get("wall_ms", 0.0)) for x in token_events if float(x.attributes.get("wall_ms", 0.0)) > 0]
- token_gpu = [float(x.attributes.get("gpu_ms", 0.0)) for x in token_events if float(x.attributes.get("gpu_ms", 0.0)) > 0]
- kernels = [int(x.attributes.get("kernel_count", 0)) for x in token_events]
+ token_wall = [_number(x.attributes.get("wall_ms")) for x in token_events if _number(x.attributes.get("wall_ms")) > 0]
+ token_gpu = [_number(x.attributes.get("gpu_ms")) for x in token_events if _number(x.attributes.get("gpu_ms")) > 0]
+ kernels_per_token = [int(_number(x.attributes.get("kernel_count"))) for x in token_events]
+ expected_decode_profile = sum(int(_number(x.attributes.get("profile_kernel_events"))) for x in token_events)
prefill = [x for x in evs if x.name == "prefill"]
- tools = [x for x in evs if x.kind == "tool" and x.duration_ms is not None]
+ prefill_wall = sum(_number(x.attributes.get("wall_ms")) for x in prefill)
+ expected_prefill_profile = sum(int(_number(x.attributes.get("profile_kernel_events"))) for x in prefill)
+ tools = [x for x in evs if x.kind == "tool" and x.duration_ms is not None and x.name != "tool_result"]
+ metric_events = [x for x in evs if x.name == "metric"]
+ truncated = [x for x in metric_events if x.attributes.get("name") == "profile_truncated"]
+ top_kernels, profiled_kernel_ms, decode_profile_count, prefill_profile_count = _kernel_summary(evs)
findings: list[Finding] = []
- if kernels and statistics.mean(kernels) >= 20:
+ if kernels_per_token and statistics.mean(kernels_per_token) >= 20:
findings.append(Finding("high", "observed", "High kernel-launch count per decoded token",
- (f"mean launches/token={statistics.mean(kernels):.1f}",),
- "Inspect launch gaps and fuse the dominant decode subgraph or generate a persistent megakernel candidate."))
+ (f"mean launches/token={statistics.mean(kernels_per_token):.1f}", f"profiled decode ranges={decode_profile_count}"),
+ "Inspect the dominant launch sequence and test a fused subgraph or persistent megakernel; do not assume arithmetic is the bottleneck."))
if token_wall and token_gpu and sum(token_gpu) / max(sum(token_wall), 1e-9) < 0.65:
findings.append(Finding("high", "inferred", "GPU execution explains only part of decode wall time",
(f"GPU/wall ratio={sum(token_gpu)/sum(token_wall):.2f}",),
- "Profile CPU submission, synchronization and launch bubbles before optimizing arithmetic throughput."))
- if prefill and sum(x.duration_ms or 0 for x in prefill) > sum(token_wall):
+ "Profile CPU submission, synchronization, sampling and launch bubbles before optimizing arithmetic throughput."))
+ if prefill and prefill_wall > sum(token_wall):
findings.append(Finding("medium", "observed", "Prefill dominates this agent turn",
- (f"prefill_ms={sum(x.duration_ms or 0 for x in prefill):.2f}", f"decode_ms={sum(token_wall):.2f}"),
- "Increase stable-prefix reuse and compact repeated tool schemas/repository context."))
+ (f"prefill_ms={prefill_wall:.2f}", f"decode_ms={sum(token_wall):.2f}"),
+ "Increase stable-prefix reuse and compact repeated tool schemas or repository context before generating lower-level kernels."))
if tools and sum(x.duration_ms or 0 for x in tools) > sum(token_wall):
findings.append(Finding("medium", "observed", "Tool execution dominates model decode",
(f"tool_ms={sum(x.duration_ms or 0 for x in tools):.2f}",),
- "Parallelize independent tools or reduce tool round trips; a faster kernel will not materially improve task latency."))
- if not any(x.name == "kernel" for x in evs):
+ "Parallelize independent tools or reduce tool round trips; a faster inference kernel alone will not materially improve task latency."))
+
+ if top_kernels:
+ dominant = top_kernels[0]
+ if dominant["share"] >= 0.25:
+ findings.append(Finding("high", "observed", "One kernel family dominates captured GPU time",
+ (f"kernel={dominant['name']}", f"share={dominant['share']*100:.1f}%", f"calls={dominant['calls']}",
+ f"total_ms={dominant['total_ms']:.2f}"),
+ "Map this kernel back to the model subgraph, inspect its shapes and resource metadata, then generate a bounded structural alternative and retune it."))
+ tiny = [row for row in top_kernels if row["mean_ms"] < 0.05]
+ tiny_calls = sum(row["calls"] for row in tiny)
+ if decode_profile_count and tiny_calls / max(decode_profile_count + prefill_profile_count, 1) >= 0.35:
+ findings.append(Finding("medium", "inferred", "Captured execution is fragmented across many very small kernels",
+ (f"sub-50us calls={tiny_calls}", f"captured kernel calls={decode_profile_count+prefill_profile_count}"),
+ "Inspect adjacency and data materialization boundaries. Fusion is promising only where the independent numerical oracle covers the combined subgraph."))
+ else:
findings.append(Finding("info", "unknown", "No kernel-level trace is attached",
("Only agent/model aggregate counters are available.",),
- "Capture tinygrad PROFILE events or ROCm/SQTT evidence before making a causal hardware diagnosis."))
+ "Enable the tinygrad PROFILE event adapter or capture ROCm/SQTT evidence before making a causal hardware diagnosis."))
+
+ expected_profile = expected_decode_profile + expected_prefill_profile
+ captured_profile = decode_profile_count + prefill_profile_count
+ if truncated:
+ findings.append(Finding("medium", "observed", "Kernel trace was truncated",
+ tuple(f"{x.attributes.get('stage')} captured={x.attributes.get('captured')} available={x.attributes.get('available')}" for x in truncated[:4]),
+ "Reduce the profiled workload or raise the capture budget before using kernel shares as complete attribution."))
+ elif expected_profile and captured_profile < expected_profile:
+ findings.append(Finding("info", "unknown", "Some backend profile ranges were not attached to the unified trace",
+ (f"backend reported={expected_profile}", f"trace captured={captured_profile}"),
+ "Treat per-kernel attribution as partial until the transport discrepancy is resolved."))
return {
"summary": {
@@ -61,8 +117,11 @@ def build_profile_report(events: Iterable[TraceEvent]) -> dict[str, Any]:
"token_wall_ms_p50": statistics.median(token_wall) if token_wall else None,
"token_wall_ms_p95": _percentile(token_wall, 0.95),
"token_gpu_ms_p50": statistics.median(token_gpu) if token_gpu else None,
- "mean_kernel_count_per_token": statistics.mean(kernels) if kernels else None,
- "tool_time_ms": sum(x.duration_ms or 0 for x in tools),
+ "mean_kernel_count_per_token": statistics.mean(kernels_per_token) if kernels_per_token else None,
+ "tool_time_ms": sum(x.duration_ms or 0 for x in tools), "prefill_wall_ms": prefill_wall,
+ "profiled_kernel_time_ms": profiled_kernel_ms, "profiled_decode_kernel_calls": decode_profile_count,
+ "profiled_prefill_kernel_calls": prefill_profile_count, "kernel_profile_complete": bool(captured_profile and not truncated and captured_profile >= expected_profile),
+ "top_kernels": top_kernels[:20],
},
"findings": [asdict(x) for x in findings],
}
From 6d928364d70fda8cd90668d8e3b08c24c750910f Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 12:34:02 +0530
Subject: [PATCH 067/168] radeon forge: harden backend trace field ingestion
---
extra/radeon_forge/runtime/session.py | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index 45ee521969a26..469c12c5661b8 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -73,12 +73,16 @@ def _record_backend_event(self, event, parent_id: str) -> None:
metrics = dict(event.metrics)
self._emit(event.kind, **metrics)
if event.kind == "kernel":
- name = str(metrics.pop("name", "kernel"))
+ name = str(metrics.pop("name", metrics.pop("kernel_name", "kernel")))
duration_ms = float(metrics.pop("duration_ms", metrics.pop("duration_us", 0.0) / 1000.0))
self.trace.duration("kernel", name, duration_ms, parent_id, **metrics)
elif event.kind in {"prefill", "decode"} and float(metrics.get("wall_ms", 0.0)) > 0:
self.trace.duration("inference", event.kind, float(metrics["wall_ms"]), parent_id, **metrics)
- else: self.trace.point("inference", event.kind, parent_id, **metrics)
+ else:
+ if "name" in metrics: metrics[f"{event.kind}_name"] = metrics.pop("name")
+ if "kind" in metrics: metrics["backend_kind"] = metrics.pop("kind")
+ if "parent_id" in metrics: metrics["backend_parent_id"] = metrics.pop("parent_id")
+ self.trace.point("inference", event.kind, parent_id, **metrics)
def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent, ...]:
self.state = SessionState.GENERATING
@@ -95,8 +99,10 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
if event.kind == "token":
pieces.append(event.text)
self._emit("token", text=event.text, metrics=dict(event.metrics))
- self.trace.duration("inference", "token", float(event.metrics.get("wall_ms", 0.0)), parent.event_id,
- text=event.text, **dict(event.metrics))
+ token_metrics = dict(event.metrics)
+ if "name" in token_metrics: token_metrics["token_name"] = token_metrics.pop("name")
+ self.trace.duration("inference", "token", float(token_metrics.get("wall_ms", 0.0)), parent.event_id,
+ text=event.text, **token_metrics)
elif event.kind in {"prefill", "decode", "kernel", "metric"}: self._record_backend_event(event, parent.event_id)
elif event.kind == "tool_call" and event.tool_call is not None:
self.pending_tool_call = ToolCall(str(event.tool_call.get("id") or uuid.uuid4().hex), str(event.tool_call["name"]), event.tool_call.get("arguments", {}))
From 56277d486be5907905e3895885cc02512164619c Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:11:24 +0530
Subject: [PATCH 068/168] radeon forge: allow named kernel evidence in traces
---
extra/radeon_forge/runtime/events.py | 29 ++++++++++++++--------------
1 file changed, 14 insertions(+), 15 deletions(-)
diff --git a/extra/radeon_forge/runtime/events.py b/extra/radeon_forge/runtime/events.py
index 71c75ede25e34..29f3bf3d2ea1c 100644
--- a/extra/radeon_forge/runtime/events.py
+++ b/extra/radeon_forge/runtime/events.py
@@ -37,33 +37,32 @@ def __init__(self, trace_id: str | None = None):
self._events: list[TraceEvent] = []
self._lock = threading.RLock()
- def point(self, kind: str, name: str, parent_id: str | None = None, **attributes: Any) -> TraceEvent:
- ts = now_ns()
- ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, name, ts, ts, parent_id, attributes)
- with self._lock: self._events.append(ev)
- return ev
-
- def duration(self, kind: str, name: str, duration_ms: float, parent_id: str | None = None, **attributes: Any) -> TraceEvent:
- end = now_ns()
- start = end - max(0, int(float(duration_ms) * 1e6))
- ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, name, start, end, parent_id, attributes)
+ def point(self, kind: str, event_name: str, parent_id: str | None = None, **attributes: Any) -> TraceEvent:
+ """Record an instantaneous event.
+
+ `event_name` is deliberately not called `name`: backend evidence commonly
+ carries a `name` attribute for the concrete GPU kernel. Keeping those two
+ namespaces separate lets an event be named `kernel` while retaining the
+ real kernel symbol in its attributes.
+ """
+ ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, event_name, now_ns(), now_ns(), parent_id, attributes)
with self._lock: self._events.append(ev)
return ev
@contextlib.contextmanager
- def span(self, kind: str, name: str, parent_id: str | None = None, **attributes: Any) -> Iterator[TraceEvent]:
+ def span(self, kind: str, event_name: str, parent_id: str | None = None, **attributes: Any) -> Iterator[TraceEvent]:
start = now_ns()
- provisional = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, name, start, None, parent_id, attributes)
+ provisional = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, event_name, start, None, parent_id, attributes)
try: yield provisional
except BaseException as exc:
attrs = dict(attributes)
attrs.update({"status": "error", "error_type": type(exc).__name__, "error": str(exc)})
- with self._lock: self._events.append(TraceEvent(provisional.event_id, self.trace_id, kind, name, start, now_ns(), parent_id, attrs))
+ with self._lock: self._events.append(TraceEvent(provisional.event_id, self.trace_id, kind, event_name, start, now_ns(), parent_id, attrs))
raise
else:
attrs = dict(attributes)
attrs.setdefault("status", "ok")
- with self._lock: self._events.append(TraceEvent(provisional.event_id, self.trace_id, kind, name, start, now_ns(), parent_id, attrs))
+ with self._lock: self._events.append(TraceEvent(provisional.event_id, self.trace_id, kind, event_name, start, now_ns(), parent_id, attrs))
def extend(self, events: list[TraceEvent]) -> None:
with self._lock: self._events.extend(events)
@@ -86,4 +85,4 @@ def chrome_trace(self) -> dict[str, Any]:
events.append({"name": ev.name, "cat": ev.kind, "ph": "X", "ts": ev.start_ns / 1000,
"dur": (ev.end_ns - ev.start_ns) / 1000, "pid": 1, "tid": ev.kind,
"args": dict(ev.attributes)})
- return {"traceEvents": events, "displayTimeUnit": "ms"}
+ return {"traceEvents": events, "displayTimeUnit": "ms"}
\ No newline at end of file
From 9ebc191e5ed1b4aabf3e71912f386b2c6aba27f8 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:11:52 +0530
Subject: [PATCH 069/168] radeon forge: add runtime integration tests
---
test/test_radeon_forge_runtime.py | 91 +++++++++++++++++++++++++++++++
1 file changed, 91 insertions(+)
create mode 100644 test/test_radeon_forge_runtime.py
diff --git a/test/test_radeon_forge_runtime.py b/test/test_radeon_forge_runtime.py
new file mode 100644
index 0000000000000..38a31c37d70c8
--- /dev/null
+++ b/test/test_radeon_forge_runtime.py
@@ -0,0 +1,91 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.backends.fake import ScriptedBackend
+from extra.radeon_forge.permissions import PermissionDenied
+from extra.radeon_forge.profiling.report import build_profile_report
+from extra.radeon_forge.runtime import ForgeEngine
+from extra.radeon_forge.runtime.backend import BackendCapabilities, GenerationEvent
+from extra.radeon_forge.runtime.session import SessionState
+from extra.radeon_forge.runtime.tools import WorkspaceTools
+from extra.radeon_forge.synthesis.workspace import CandidateWorkspace, KernelSpec
+
+
+class KernelEvidenceBackend:
+ @property
+ def name(self): return "kernel-evidence-local"
+
+ @property
+ def capabilities(self): return BackendCapabilities(prefix_cache=True, persistent_kv=True, kernel_metrics=True)
+
+ def stream(self, request):
+ yield GenerationEvent("prefill", metrics={"wall_ms": 8.0, "gpu_ms": 5.0, "prompt_tokens": 24,
+ "prefix_reused_tokens": 12, "profile_kernel_events": 1})
+ yield GenerationEvent("kernel", metrics={"name": "rmsnorm_fused", "duration_ms": 0.40, "stage": "prefill", "device": "AMD"})
+ yield GenerationEvent("token", "ok", metrics={"index": 0, "wall_ms": 2.0, "gpu_ms": 1.4,
+ "kernel_count": 24, "profile_kernel_events": 2})
+ yield GenerationEvent("kernel", metrics={"name": "decode_gemv", "duration_ms": 0.90, "stage": "decode", "device": "AMD"})
+ yield GenerationEvent("kernel", metrics={"name": "decode_gemv", "duration_ms": 0.70, "stage": "decode", "device": "AMD"})
+ yield GenerationEvent("done", finish_reason="stop", metrics={"generated_tokens": 1})
+
+ def close(self): pass
+
+
+class TestRadeonForgeRuntime(unittest.TestCase):
+ def test_kernel_evidence_survives_unified_trace_and_is_ranked(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(KernelEvidenceBackend(), directory)
+ session = engine.create_session()
+ session.send("profile one token")
+ report = build_profile_report(session.trace.events())
+ top = report["summary"]["top_kernels"]
+ self.assertEqual(top[0]["name"], "decode_gemv")
+ self.assertEqual(top[0]["calls"], 2)
+ self.assertAlmostEqual(top[0]["total_ms"], 1.6)
+ self.assertTrue(report["summary"]["kernel_profile_complete"])
+ self.assertTrue(any(x["title"] == "One kernel family dominates captured GPU time" for x in report["findings"]))
+ kernel_events = [event for event in session.trace.events() if event.name == "kernel"]
+ self.assertEqual([event.attributes["name"] for event in kernel_events], ["rmsnorm_fused", "decode_gemv", "decode_gemv"])
+ engine.close()
+
+ def test_permissioned_tool_round_trip(self):
+ responses = [
+ '
{"name":"read_file","arguments":{"path":"hello.txt"}} ',
+ "The private file was read successfully.",
+ ]
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory, "hello.txt").write_text("local only", encoding="utf-8")
+ engine = ForgeEngine(ScriptedBackend(responses), directory)
+ session = engine.create_session()
+ session.send("read hello.txt")
+ self.assertEqual(session.state, SessionState.AWAITING_TOOL_APPROVAL)
+ with self.assertRaises(PermissionDenied): session.approve_tool("not-a-real-grant")
+ token = engine.grant_for_pending_tool(session.session_id, "approve one local read")
+ session.approve_tool(token)
+ self.assertEqual(session.state, SessionState.COMPLETED)
+ self.assertEqual(session.messages[-1]["content"], "The private file was read successfully.")
+ self.assertTrue(any(event.kind == "tool_result" for event in session.events))
+ engine.close()
+
+ def test_workspace_paths_cannot_escape(self):
+ with tempfile.TemporaryDirectory() as directory:
+ tools = WorkspaceTools(directory)
+ with self.assertRaisesRegex(ValueError, "escapes workspace"):
+ tools.read_file({"path": "../outside.txt"})
+ with self.assertRaisesRegex(ValueError, "not allowlisted"):
+ tools.run_command({"command": "curl https://example.com"})
+
+ def test_generated_candidates_are_content_addressed(self):
+ with tempfile.TemporaryDirectory() as directory:
+ workspace = CandidateWorkspace(directory)
+ spec = workspace.save_spec(KernelSpec(name="decode-gemv", operation="gemv", shapes={"hidden": 4096},
+ invariants=("numerically_matches_reference",)))
+ first = workspace.create_candidate(spec.spec_id, "def build_kernel():\n return 1\n", "baseline schedule")
+ second = workspace.create_candidate(spec.spec_id, "def build_kernel():\n return 1\n", "same implementation, new explanation")
+ self.assertEqual(first.candidate_id, second.candidate_id)
+ self.assertEqual(first.source_sha256, second.source_sha256)
+ self.assertTrue(Path(second.source_path).is_file())
+
+
+if __name__ == "__main__": unittest.main()
From c34d6370084a5f1981a4ce27dbbb114d925804b5 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:13:29 +0530
Subject: [PATCH 070/168] radeon forge: add externally measured trace durations
---
extra/radeon_forge/runtime/events.py | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/extra/radeon_forge/runtime/events.py b/extra/radeon_forge/runtime/events.py
index 29f3bf3d2ea1c..3f75c03cdfca2 100644
--- a/extra/radeon_forge/runtime/events.py
+++ b/extra/radeon_forge/runtime/events.py
@@ -49,6 +49,21 @@ def point(self, kind: str, event_name: str, parent_id: str | None = None, **attr
with self._lock: self._events.append(ev)
return ev
+ def duration(self, kind: str, event_name: str, duration_ms: float, parent_id: str | None = None, **attributes: Any) -> TraceEvent:
+ """Record a duration measured by another clock domain.
+
+ GPU profile timestamps are device-local and cannot be placed exactly on the
+ CPU wall-clock axis without calibration. We preserve their measured duration
+ and causal parent while anchoring the range at ingestion time. The attributes
+ retain source/stage/order for later calibrated timeline adapters.
+ """
+ duration = max(0.0, float(duration_ms))
+ end = now_ns()
+ start = end - int(duration * 1e6)
+ ev = TraceEvent(uuid.uuid4().hex, self.trace_id, kind, event_name, start, end, parent_id, attributes)
+ with self._lock: self._events.append(ev)
+ return ev
+
@contextlib.contextmanager
def span(self, kind: str, event_name: str, parent_id: str | None = None, **attributes: Any) -> Iterator[TraceEvent]:
start = now_ns()
From 9e0b696e8bd4a5013f8cb1f136eb0360718deef5 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:14:07 +0530
Subject: [PATCH 071/168] radeon forge: recover pending tools after denied
grants
---
extra/radeon_forge/runtime/session.py | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index 469c12c5661b8..ec547ff0b22d5 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -130,10 +130,18 @@ def approve_tool(self, permission_token: str, max_tokens: int = 512) -> tuple[Se
call = self.pending_tool_call
started_at = len(self.events)
self.state = SessionState.RUNNING_TOOL
- with self.trace.span("tool", call.name, call_id=call.call_id) as span:
- self._emit("tool_started", call=asdict(call))
- result = self.tools.execute(call, permission_token)
- self.trace.point("tool", "tool_result", span.event_id, ok=result.ok, elapsed_ms=result.elapsed_ms)
+ try:
+ with self.trace.span("tool", call.name, call_id=call.call_id) as span:
+ self._emit("tool_started", call=asdict(call))
+ result = self.tools.execute(call, permission_token)
+ self.trace.point("tool", "tool_result", span.event_id, ok=result.ok, elapsed_ms=result.elapsed_ms)
+ except Exception as exc:
+ # Authorization happens before the tool body. A stale, exhausted or
+ # incorrectly scoped grant must leave the proposed call pending so the
+ # user can issue a fresh explicit grant and retry it safely.
+ self.state = SessionState.AWAITING_TOOL_APPROVAL
+ self._emit("tool_authorization_failed", call_id=call.call_id, error=str(exc), error_type=type(exc).__name__)
+ raise
self._emit("tool_result", result=asdict(result))
self.messages.append({"role": "assistant", "content": f"
{{\"name\":\"{call.name}\"}} "})
self.messages.append({"role": "tool", "name": call.name, "tool_call_id": call.call_id, "content": str(result.output)})
From 626b05005cecb8cef8379a82e413ca0799e4683e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:19:17 +0530
Subject: [PATCH 072/168] radeon forge: add compatibility-gated hook registry
---
extra/radeon_forge/synthesis/hooks.py | 234 ++++++++++++++++++++++++++
1 file changed, 234 insertions(+)
create mode 100644 extra/radeon_forge/synthesis/hooks.py
diff --git a/extra/radeon_forge/synthesis/hooks.py b/extra/radeon_forge/synthesis/hooks.py
new file mode 100644
index 0000000000000..8c094c6f296a2
--- /dev/null
+++ b/extra/radeon_forge/synthesis/hooks.py
@@ -0,0 +1,234 @@
+from __future__ import annotations
+
+import hashlib, json, threading, time, uuid
+from dataclasses import asdict, dataclass, field
+from enum import Enum
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+from .workspace import CandidateRecord, CandidateWorkspace, KernelSpec
+
+
+class HookLayer(str, Enum):
+ AGENT_LOOP = "agent_loop"
+ SCHEDULER = "scheduler"
+ MODEL = "model"
+ TRANSFORMER_BLOCK = "transformer_block"
+ SUBGRAPH = "subgraph"
+ KERNEL = "kernel"
+ KV_CACHE = "kv_cache"
+ SAMPLER = "sampler"
+
+
+class HookMode(str, Enum):
+ BEFORE = "before"
+ AFTER = "after"
+ REPLACE = "replace"
+ WRAP = "wrap"
+
+
+@dataclass(frozen=True)
+class HookDescriptor:
+ layer: HookLayer
+ target: str
+ mode: HookMode = HookMode.REPLACE
+ adapter: str = "request_metadata"
+ selector: Mapping[str, Any] = field(default_factory=dict)
+ priority: int = 0
+ exclusive_group: str = ""
+ description: str = ""
+
+ @classmethod
+ def from_spec(cls, spec: KernelSpec) -> HookDescriptor:
+ raw = spec.metadata.get("hook", {})
+ if not isinstance(raw, Mapping): raise ValueError("spec metadata hook must be a table")
+ layer = HookLayer(str(raw.get("layer", "kernel")))
+ target = str(raw.get("target", spec.operation)).strip()
+ if not target: raise ValueError("hook target must not be empty")
+ selector = raw.get("selector", {})
+ if not isinstance(selector, Mapping): raise ValueError("hook selector must be a table")
+ group = str(raw.get("exclusive_group", f"{layer.value}:{target}"))
+ return cls(layer, target, HookMode(str(raw.get("mode", "replace"))), str(raw.get("adapter", "request_metadata")),
+ dict(selector), int(raw.get("priority", 0)), group, str(raw.get("description", "")))
+
+
+@dataclass(frozen=True)
+class RuntimeFingerprint:
+ architecture: str = ""
+ gpu: str = ""
+ runtime: str = ""
+ runtime_revision: str = ""
+ model_family: str = ""
+ model_hash: str = ""
+ dtype: str = ""
+ shapes: Mapping[str, Any] = field(default_factory=dict)
+ extra: Mapping[str, Any] = field(default_factory=dict)
+
+ @classmethod
+ def from_mapping(cls, value: Mapping[str, Any] | None) -> RuntimeFingerprint:
+ raw = dict(value or {})
+ known = {key: raw.pop(key, "") for key in ("architecture", "gpu", "runtime", "runtime_revision", "model_family", "model_hash", "dtype")}
+ shapes = raw.pop("shapes", {})
+ return cls(**known, shapes=dict(shapes) if isinstance(shapes, Mapping) else {}, extra=raw)
+
+ def flattened(self) -> dict[str, Any]:
+ ret = {"architecture": self.architecture, "gpu": self.gpu, "runtime": self.runtime,
+ "runtime_revision": self.runtime_revision, "model_family": self.model_family,
+ "model_hash": self.model_hash, "dtype": self.dtype}
+ ret.update({f"shape.{key}": value for key, value in self.shapes.items()})
+ ret.update(self.extra)
+ return ret
+
+
+@dataclass(frozen=True)
+class CompatibilityReport:
+ compatible: bool
+ exact: tuple[str, ...]
+ unknown: tuple[str, ...]
+ mismatches: tuple[str, ...]
+
+
+def _matches(expected: Any, actual: Any) -> bool:
+ if expected in (None, "", "*"): return True
+ if isinstance(expected, Sequence) and not isinstance(expected, (str, bytes, bytearray)): return actual in expected
+ if isinstance(expected, str) and expected.endswith("*"): return str(actual).startswith(expected[:-1])
+ return expected == actual
+
+
+def check_compatibility(spec: KernelSpec, fingerprint: RuntimeFingerprint) -> CompatibilityReport:
+ expected = spec.metadata.get("recipe_compatibility", spec.metadata.get("compatibility", {}))
+ if not isinstance(expected, Mapping): raise ValueError("compatibility contract must be a table")
+ actual = fingerprint.flattened()
+ exact, unknown, mismatches = [], [], []
+ if spec.target:
+ arch = actual.get("architecture", "")
+ if not arch: unknown.append("architecture")
+ elif _matches(spec.target, arch): exact.append("architecture")
+ else: mismatches.append(f"architecture expected={spec.target!r} actual={arch!r}")
+ for key, value in expected.items():
+ key = str(key)
+ current = actual.get(key)
+ if current in (None, ""): unknown.append(key)
+ elif _matches(value, current): exact.append(key)
+ else: mismatches.append(f"{key} expected={value!r} actual={current!r}")
+ return CompatibilityReport(not mismatches, tuple(exact), tuple(unknown), tuple(mismatches))
+
+
+@dataclass(frozen=True)
+class ActiveHook:
+ activation_id: str
+ candidate_id: str
+ spec_id: str
+ source_path: str
+ source_sha256: str
+ descriptor: HookDescriptor
+ compatibility: CompatibilityReport
+ activated_at_s: float
+ reason: str
+ previous_activation_id: str | None = None
+
+
+class HookActivationError(RuntimeError): pass
+
+
+class HookRegistry:
+ """Persistent, rollback-safe deployment registry for validated optimizations.
+
+ The registry selects implementations; the isolated inference backend owns the
+ actual adapter. Unsupported adapters cannot be activated merely because a
+ candidate benchmarked successfully.
+ """
+ SUPPORTED_ADAPTERS = frozenset({"request_metadata", "python_transformer_block"})
+
+ def __init__(self, workspace: CandidateWorkspace):
+ self.workspace = workspace
+ self.root = workspace.root / "hooks"
+ self.root.mkdir(parents=True, exist_ok=True)
+ self.active_path, self.history_path = self.root / "active.json", self.root / "history.jsonl"
+ self._lock = threading.RLock()
+ if not self.active_path.exists(): self.active_path.write_text("[]\n", encoding="utf-8")
+
+ def _load_active(self) -> list[ActiveHook]:
+ try: payload = json.loads(self.active_path.read_text(encoding="utf-8"))
+ except Exception: payload = []
+ ret = []
+ for item in payload:
+ try:
+ desc = item["descriptor"]
+ comp = item["compatibility"]
+ ret.append(ActiveHook(item["activation_id"], item["candidate_id"], item["spec_id"], item["source_path"],
+ item["source_sha256"], HookDescriptor(HookLayer(desc["layer"]), desc["target"], HookMode(desc["mode"]),
+ desc["adapter"], desc.get("selector", {}), int(desc.get("priority", 0)), desc.get("exclusive_group", ""),
+ desc.get("description", "")), CompatibilityReport(bool(comp["compatible"]), tuple(comp.get("exact", ())),
+ tuple(comp.get("unknown", ())), tuple(comp.get("mismatches", ()))), float(item["activated_at_s"]),
+ item["reason"], item.get("previous_activation_id")))
+ except Exception: continue
+ return ret
+
+ def _save_active(self, hooks: Sequence[ActiveHook]) -> None:
+ temp = self.active_path.with_suffix(".tmp")
+ temp.write_text(json.dumps([asdict(x) for x in hooks], indent=2, default=str) + "\n", encoding="utf-8")
+ temp.replace(self.active_path)
+
+ def _history(self, event: str, **data: Any) -> None:
+ with self.history_path.open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps({"event": event, "timestamp_s": time.time(), **data}, default=str) + "\n")
+
+ def active(self) -> list[ActiveHook]:
+ with self._lock: return sorted(self._load_active(), key=lambda x: (-x.descriptor.priority, x.activated_at_s))
+
+ def _required_status(self, spec: KernelSpec) -> frozenset[str]:
+ heldout = spec.metadata.get("heldout_command", ())
+ return frozenset({"heldout_passed", "accepted"}) if heldout else frozenset({"hardware_passed", "heldout_passed", "accepted"})
+
+ def activate(self, candidate_id: str, fingerprint: RuntimeFingerprint, reason: str) -> ActiveHook:
+ if not reason.strip(): raise HookActivationError("activation requires a reason")
+ with self._lock:
+ candidate = self.workspace.load_candidate(candidate_id)
+ spec = self.workspace.load_spec(candidate.spec_id)
+ descriptor = HookDescriptor.from_spec(spec)
+ if descriptor.adapter not in self.SUPPORTED_ADAPTERS: raise HookActivationError(f"runtime adapter {descriptor.adapter!r} is not installed")
+ if candidate.status not in self._required_status(spec):
+ raise HookActivationError(f"candidate status {candidate.status!r} has not passed the required hardware/held-out oracle")
+ source_path = Path(candidate.source_path)
+ if not source_path.is_file(): raise HookActivationError("candidate source is missing")
+ source_sha = hashlib.sha256(source_path.read_bytes()).hexdigest()
+ if source_sha != candidate.source_sha256: raise HookActivationError("candidate source hash changed after validation")
+ compatibility = check_compatibility(spec, fingerprint)
+ if not compatibility.compatible: raise HookActivationError("incompatible runtime: " + "; ".join(compatibility.mismatches))
+ current = self._load_active()
+ previous = next((x for x in current if x.descriptor.exclusive_group == descriptor.exclusive_group), None)
+ current = [x for x in current if x.descriptor.exclusive_group != descriptor.exclusive_group]
+ active = ActiveHook(uuid.uuid4().hex, candidate.candidate_id, spec.spec_id, candidate.source_path, source_sha, descriptor,
+ compatibility, time.time(), reason.strip(), previous.activation_id if previous else None)
+ current.append(active)
+ self._save_active(current)
+ self._history("hook_activated", activation=asdict(active), replaced=asdict(previous) if previous else None)
+ return active
+
+ def deactivate(self, activation_id: str, reason: str) -> ActiveHook:
+ if not reason.strip(): raise HookActivationError("deactivation requires a reason")
+ with self._lock:
+ current = self._load_active()
+ target = next((x for x in current if x.activation_id == activation_id), None)
+ if target is None: raise KeyError(f"unknown active hook {activation_id}")
+ self._save_active([x for x in current if x.activation_id != activation_id])
+ self._history("hook_deactivated", activation=asdict(target), reason=reason.strip())
+ return target
+
+ def clear(self, reason: str) -> list[ActiveHook]:
+ with self._lock:
+ current = self._load_active()
+ self._save_active([])
+ self._history("hooks_cleared", activations=[asdict(x) for x in current], reason=reason.strip())
+ return current
+
+ def runtime_metadata(self) -> dict[str, Any]:
+ hooks = []
+ for active in self.active():
+ source = Path(active.source_path)
+ if not source.is_file() or hashlib.sha256(source.read_bytes()).hexdigest() != active.source_sha256: continue
+ hooks.append({"activation_id": active.activation_id, "candidate_id": active.candidate_id, "spec_id": active.spec_id,
+ "source_path": active.source_path, "source_sha256": active.source_sha256,
+ "descriptor": asdict(active.descriptor)})
+ return {"active_hooks": hooks}
From dd3fcaa41cebb8c74d3ddffb11388344e7cb779d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:19:32 +0530
Subject: [PATCH 073/168] radeon forge: export runtime hook contracts
---
extra/radeon_forge/synthesis/__init__.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/synthesis/__init__.py b/extra/radeon_forge/synthesis/__init__.py
index d1a1177a84a21..cd4d63a5f95a9 100644
--- a/extra/radeon_forge/synthesis/__init__.py
+++ b/extra/radeon_forge/synthesis/__init__.py
@@ -1,7 +1,9 @@
from .defaults import install_default_specs
+from .hooks import ActiveHook, CompatibilityReport, HookDescriptor, HookLayer, HookMode, HookRegistry, RuntimeFingerprint, check_compatibility
from .recipe import ForgeRecipe, InstalledRecipe, RecipeArtifact, RecipeLibrary, export_recipe
from .tools import OptimizationTools
from .workspace import CandidateRecord, CandidateWorkspace, KernelSpec
-__all__ = ["CandidateRecord", "CandidateWorkspace", "ForgeRecipe", "InstalledRecipe", "KernelSpec", "OptimizationTools",
- "RecipeArtifact", "RecipeLibrary", "export_recipe", "install_default_specs"]
+__all__ = ["ActiveHook", "CandidateRecord", "CandidateWorkspace", "CompatibilityReport", "ForgeRecipe", "HookDescriptor",
+ "HookLayer", "HookMode", "HookRegistry", "InstalledRecipe", "KernelSpec", "OptimizationTools", "RecipeArtifact",
+ "RecipeLibrary", "RuntimeFingerprint", "check_compatibility", "export_recipe", "install_default_specs"]
From 9957b1106e4bea45499e79489983caca45d32a23 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:19:52 +0530
Subject: [PATCH 074/168] radeon forge: preserve hook descriptors in portable
recipes
---
extra/radeon_forge/synthesis/portable.py | 49 ++++++++++++++++++++++++
1 file changed, 49 insertions(+)
create mode 100644 extra/radeon_forge/synthesis/portable.py
diff --git a/extra/radeon_forge/synthesis/portable.py b/extra/radeon_forge/synthesis/portable.py
new file mode 100644
index 0000000000000..00c4440ca0305
--- /dev/null
+++ b/extra/radeon_forge/synthesis/portable.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Mapping
+
+from .hooks import HookDescriptor
+from .recipe import export_recipe
+from .workspace import CandidateWorkspace
+
+
+def _toml_value(value: Any) -> str:
+ if isinstance(value, bool): return "true" if value else "false"
+ if isinstance(value, (int, float)): return str(value)
+ if isinstance(value, str): return json.dumps(value, ensure_ascii=False)
+ if isinstance(value, (list, tuple)): return "[" + ", ".join(_toml_value(x) for x in value) + "]"
+ raise TypeError(f"unsupported portable hook value: {type(value).__name__}")
+
+
+def _append_table(lines: list[str], name: str, values: Mapping[str, Any]) -> None:
+ if not values: return
+ lines.append(f"\n[{name}]")
+ for key, value in values.items():
+ if isinstance(value, Mapping): continue
+ lines.append(f"{json.dumps(str(key))} = {_toml_value(value)}")
+ for key, value in values.items():
+ if isinstance(value, Mapping): _append_table(lines, f"{name}.{key}", value)
+
+
+def export_recipe_with_hook(workspace: CandidateWorkspace, spec_id: str, output: str | Path,
+ candidate_id: str | None = None) -> Path:
+ """Export one recipe while preserving its concrete runtime interception point."""
+ path = export_recipe(workspace, spec_id, output, candidate_id)
+ spec = workspace.load_spec(spec_id)
+ descriptor = HookDescriptor.from_spec(spec)
+ hook = {
+ "layer": descriptor.layer.value,
+ "target": descriptor.target,
+ "mode": descriptor.mode.value,
+ "adapter": descriptor.adapter,
+ "priority": descriptor.priority,
+ "exclusive_group": descriptor.exclusive_group,
+ "description": descriptor.description,
+ "selector": dict(descriptor.selector),
+ }
+ lines = path.read_text(encoding="utf-8").rstrip().splitlines()
+ _append_table(lines, "metadata.hook", hook)
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return path
From 4f2d4ebc89c4780701c19e7648efc3e70ca4ff28 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:20:10 +0530
Subject: [PATCH 075/168] radeon forge: define concrete optimization hook
targets
---
extra/radeon_forge/synthesis/defaults.py | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/synthesis/defaults.py b/extra/radeon_forge/synthesis/defaults.py
index 41a92beca2aa8..139b14deeab86 100644
--- a/extra/radeon_forge/synthesis/defaults.py
+++ b/extra/radeon_forge/synthesis/defaults.py
@@ -15,7 +15,10 @@ def install_default_specs(workspace: CandidateWorkspace) -> list[KernelSpec]:
"No out-of-workspace file access", "MockGPU timing is never used as a speed metric"),
objective="minimize median and P95 W7900 latency without correctness loss",
mockgpu_command=("python3", "{candidate}"), hardware_command=("python3", "{candidate}"),
- metadata={"seed":"extra/gemm/amd_asm_matmul.py", "role":"infrastructure and schedule-synthesis gate"},
+ metadata={"seed":"extra/gemm/amd_asm_matmul.py", "role":"infrastructure and schedule-synthesis gate",
+ "hook":{"layer":"kernel", "target":"batch1_projection_gemm", "mode":"replace", "adapter":"request_metadata",
+ "selector":{"program_name":"generated_gemm"}, "exclusive_group":"projection_gemm",
+ "description":"Validated kernel selection forwarded to a backend-specific kernel adapter."}},
),
KernelSpec(
name="batch1-decode-megakernel",
@@ -26,7 +29,11 @@ def install_default_specs(workspace: CandidateWorkspace) -> list[KernelSpec]:
invariants=("Match the trusted tinygrad block reference", "Preserve KV-cache semantics", "No spills unless explicitly allowed",
"Generated code is disposable; specification and oracle are authoritative"),
objective="minimize inter-token latency and kernel launches/token",
- metadata={"status":"oracle command must be bound after selecting the model", "role":"final technical target"},
+ metadata={"status":"oracle command must be bound after selecting the model", "role":"final technical target",
+ "hook":{"layer":"transformer_block", "target":"llama.decode.block", "mode":"replace",
+ "adapter":"python_transformer_block", "selector":{"indices":"all", "phase":"decode"},
+ "exclusive_group":"decode_transformer_block",
+ "description":"Replace selected tinygrad Llama blocks inside the isolated model process."}},
),
]
existing = {x.spec_id for x in workspace.specs()}
From f4990519203ccd770663f28ec5efae87d5813bdb Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:22:34 +0530
Subject: [PATCH 076/168] radeon forge: make optimization hooks execution-stage
aware
---
extra/radeon_forge/synthesis/hooks.py | 173 ++++++++++++++++++++++----
1 file changed, 150 insertions(+), 23 deletions(-)
diff --git a/extra/radeon_forge/synthesis/hooks.py b/extra/radeon_forge/synthesis/hooks.py
index 8c094c6f296a2..f98253d83db7b 100644
--- a/extra/radeon_forge/synthesis/hooks.py
+++ b/extra/radeon_forge/synthesis/hooks.py
@@ -6,7 +6,7 @@
from pathlib import Path
from typing import Any, Mapping, Sequence
-from .workspace import CandidateRecord, CandidateWorkspace, KernelSpec
+from .workspace import CandidateWorkspace, KernelSpec
class HookLayer(str, Enum):
@@ -27,6 +27,114 @@ class HookMode(str, Enum):
WRAP = "wrap"
+class ExecutionStage(str, Enum):
+ """Coarse states in one agent/inference execution.
+
+ Stage is deliberately orthogonal to HookLayer. A kernel or block replacement
+ can be valid for decode but harmful for prefill; a scheduler optimization may
+ only apply while resuming after a tool call; a KV optimization may only apply
+ while appending to a warm cache.
+ """
+ ANY = "any"
+ SESSION_START = "session_start"
+ PREFILL = "prefill"
+ FIRST_TOKEN = "first_token"
+ DECODE = "decode"
+ TOOL_EXECUTION = "tool_execution"
+ TOOL_RESUME = "tool_resume"
+ KV_APPEND = "kv_append"
+ SAMPLING = "sampling"
+ SESSION_END = "session_end"
+
+
+@dataclass(frozen=True)
+class ExecutionContext:
+ stage: ExecutionStage
+ batch_size: int = 1
+ prompt_tokens: int = 0
+ context_tokens: int = 0
+ generated_token_index: int = -1
+ prefix_reused_tokens: int = 0
+ tool_round: int = 0
+ warm: bool = False
+ attributes: Mapping[str, Any] = field(default_factory=dict)
+
+ @classmethod
+ def from_mapping(cls, value: Mapping[str, Any]) -> ExecutionContext:
+ raw = dict(value)
+ stage = ExecutionStage(str(raw.pop("stage")))
+ known = {key: raw.pop(key, default) for key, default in (
+ ("batch_size", 1), ("prompt_tokens", 0), ("context_tokens", 0), ("generated_token_index", -1),
+ ("prefix_reused_tokens", 0), ("tool_round", 0), ("warm", False))}
+ return cls(stage, int(known["batch_size"]), int(known["prompt_tokens"]), int(known["context_tokens"]),
+ int(known["generated_token_index"]), int(known["prefix_reused_tokens"]), int(known["tool_round"]),
+ bool(known["warm"]), raw)
+
+ def flattened(self) -> dict[str, Any]:
+ return {"stage": self.stage.value, "batch_size": self.batch_size, "prompt_tokens": self.prompt_tokens,
+ "context_tokens": self.context_tokens, "generated_token_index": self.generated_token_index,
+ "prefix_reused_tokens": self.prefix_reused_tokens, "tool_round": self.tool_round, "warm": self.warm,
+ "prefix_cache": "hit" if self.prefix_reused_tokens > 0 else "miss", **dict(self.attributes)}
+
+
+@dataclass(frozen=True)
+class StagePredicate:
+ stages: tuple[ExecutionStage, ...] = (ExecutionStage.ANY,)
+ min_context_tokens: int | None = None
+ max_context_tokens: int | None = None
+ min_prompt_tokens: int | None = None
+ max_prompt_tokens: int | None = None
+ min_generated_token_index: int | None = None
+ max_generated_token_index: int | None = None
+ batch_sizes: tuple[int, ...] = ()
+ prefix_cache: str = "any" # any, hit, miss
+ warm: bool | None = None
+ conditions: Mapping[str, Any] = field(default_factory=dict)
+
+ @classmethod
+ def from_mapping(cls, value: Mapping[str, Any] | None) -> StagePredicate:
+ raw = dict(value or {})
+ stage_value = raw.pop("stages", raw.pop("stage", ["any"]))
+ if isinstance(stage_value, str): stage_value = [stage_value]
+ if not isinstance(stage_value, Sequence): raise ValueError("hook stages must be a string or array")
+ stages = tuple(ExecutionStage(str(x)) for x in stage_value)
+ batch_value = raw.pop("batch_sizes", raw.pop("batch_size", ()))
+ if isinstance(batch_value, int): batch_value = [batch_value]
+ if not isinstance(batch_value, Sequence): raise ValueError("hook batch_sizes must be an integer or array")
+ prefix_cache = str(raw.pop("prefix_cache", "any"))
+ if prefix_cache not in {"any", "hit", "miss"}: raise ValueError("prefix_cache must be any, hit, or miss")
+ warm = raw.pop("warm", None)
+ if warm is not None and not isinstance(warm, bool): raise ValueError("warm must be boolean")
+ fields = {}
+ for name in ("min_context_tokens", "max_context_tokens", "min_prompt_tokens", "max_prompt_tokens",
+ "min_generated_token_index", "max_generated_token_index"):
+ item = raw.pop(name, None)
+ fields[name] = None if item is None else int(item)
+ explicit_conditions = raw.pop("conditions", {})
+ if not isinstance(explicit_conditions, Mapping): raise ValueError("hook conditions must be a table")
+ conditions = {**raw, **dict(explicit_conditions)}
+ return cls(stages, **fields, batch_sizes=tuple(int(x) for x in batch_value), prefix_cache=prefix_cache, warm=warm,
+ conditions=conditions)
+
+ @property
+ def signature(self) -> str:
+ return hashlib.sha256(json.dumps(asdict(self), sort_keys=True, default=str).encode()).hexdigest()[:12]
+
+ def matches(self, context: ExecutionContext) -> bool:
+ if ExecutionStage.ANY not in self.stages and context.stage not in self.stages: return False
+ if self.min_context_tokens is not None and context.context_tokens < self.min_context_tokens: return False
+ if self.max_context_tokens is not None and context.context_tokens > self.max_context_tokens: return False
+ if self.min_prompt_tokens is not None and context.prompt_tokens < self.min_prompt_tokens: return False
+ if self.max_prompt_tokens is not None and context.prompt_tokens > self.max_prompt_tokens: return False
+ if self.min_generated_token_index is not None and context.generated_token_index < self.min_generated_token_index: return False
+ if self.max_generated_token_index is not None and context.generated_token_index > self.max_generated_token_index: return False
+ if self.batch_sizes and context.batch_size not in self.batch_sizes: return False
+ if self.prefix_cache != "any" and context.flattened()["prefix_cache"] != self.prefix_cache: return False
+ if self.warm is not None and context.warm is not self.warm: return False
+ flat = context.flattened()
+ return all(_matches(expected, flat.get(str(key))) for key, expected in self.conditions.items())
+
+
@dataclass(frozen=True)
class HookDescriptor:
layer: HookLayer
@@ -34,6 +142,7 @@ class HookDescriptor:
mode: HookMode = HookMode.REPLACE
adapter: str = "request_metadata"
selector: Mapping[str, Any] = field(default_factory=dict)
+ when: StagePredicate = field(default_factory=StagePredicate)
priority: int = 0
exclusive_group: str = ""
description: str = ""
@@ -47,9 +156,14 @@ def from_spec(cls, spec: KernelSpec) -> HookDescriptor:
if not target: raise ValueError("hook target must not be empty")
selector = raw.get("selector", {})
if not isinstance(selector, Mapping): raise ValueError("hook selector must be a table")
+ when_value = raw.get("when", {key: raw[key] for key in ("stage", "stages") if key in raw})
+ predicate = StagePredicate.from_mapping(when_value if isinstance(when_value, Mapping) else {"stages": when_value})
group = str(raw.get("exclusive_group", f"{layer.value}:{target}"))
return cls(layer, target, HookMode(str(raw.get("mode", "replace"))), str(raw.get("adapter", "request_metadata")),
- dict(selector), int(raw.get("priority", 0)), group, str(raw.get("description", "")))
+ dict(selector), predicate, int(raw.get("priority", 0)), group, str(raw.get("description", "")))
+
+ @property
+ def slot_key(self) -> str: return f"{self.exclusive_group}:{self.when.signature}"
@dataclass(frozen=True)
@@ -131,13 +245,15 @@ class ActiveHook:
class HookActivationError(RuntimeError): pass
-class HookRegistry:
- """Persistent, rollback-safe deployment registry for validated optimizations.
+def _descriptor_from_dict(desc: Mapping[str, Any]) -> HookDescriptor:
+ when = desc.get("when", {})
+ return HookDescriptor(HookLayer(desc["layer"]), str(desc["target"]), HookMode(desc["mode"]), str(desc["adapter"]),
+ dict(desc.get("selector", {})), StagePredicate.from_mapping(when), int(desc.get("priority", 0)),
+ str(desc.get("exclusive_group", "")), str(desc.get("description", "")))
- The registry selects implementations; the isolated inference backend owns the
- actual adapter. Unsupported adapters cannot be activated merely because a
- candidate benchmarked successfully.
- """
+
+class HookRegistry:
+ """Persistent, rollback-safe, execution-state-aware optimization registry."""
SUPPORTED_ADAPTERS = frozenset({"request_metadata", "python_transformer_block"})
def __init__(self, workspace: CandidateWorkspace):
@@ -154,12 +270,10 @@ def _load_active(self) -> list[ActiveHook]:
ret = []
for item in payload:
try:
- desc = item["descriptor"]
comp = item["compatibility"]
ret.append(ActiveHook(item["activation_id"], item["candidate_id"], item["spec_id"], item["source_path"],
- item["source_sha256"], HookDescriptor(HookLayer(desc["layer"]), desc["target"], HookMode(desc["mode"]),
- desc["adapter"], desc.get("selector", {}), int(desc.get("priority", 0)), desc.get("exclusive_group", ""),
- desc.get("description", "")), CompatibilityReport(bool(comp["compatible"]), tuple(comp.get("exact", ())),
+ item["source_sha256"], _descriptor_from_dict(item["descriptor"]),
+ CompatibilityReport(bool(comp["compatible"]), tuple(comp.get("exact", ())),
tuple(comp.get("unknown", ())), tuple(comp.get("mismatches", ()))), float(item["activated_at_s"]),
item["reason"], item.get("previous_activation_id")))
except Exception: continue
@@ -177,6 +291,16 @@ def _history(self, event: str, **data: Any) -> None:
def active(self) -> list[ActiveHook]:
with self._lock: return sorted(self._load_active(), key=lambda x: (-x.descriptor.priority, x.activated_at_s))
+ def resolve(self, context: ExecutionContext) -> list[ActiveHook]:
+ """Select the highest-priority matching implementation per logical hook group."""
+ selected: dict[str, ActiveHook] = {}
+ for hook in self.active():
+ if not hook.descriptor.when.matches(context): continue
+ group = hook.descriptor.exclusive_group
+ current = selected.get(group)
+ if current is None or hook.descriptor.priority > current.descriptor.priority: selected[group] = hook
+ return sorted(selected.values(), key=lambda x: (-x.descriptor.priority, x.activated_at_s))
+
def _required_status(self, spec: KernelSpec) -> frozenset[str]:
heldout = spec.metadata.get("heldout_command", ())
return frozenset({"heldout_passed", "accepted"}) if heldout else frozenset({"hardware_passed", "heldout_passed", "accepted"})
@@ -197,8 +321,8 @@ def activate(self, candidate_id: str, fingerprint: RuntimeFingerprint, reason: s
compatibility = check_compatibility(spec, fingerprint)
if not compatibility.compatible: raise HookActivationError("incompatible runtime: " + "; ".join(compatibility.mismatches))
current = self._load_active()
- previous = next((x for x in current if x.descriptor.exclusive_group == descriptor.exclusive_group), None)
- current = [x for x in current if x.descriptor.exclusive_group != descriptor.exclusive_group]
+ previous = next((x for x in current if x.descriptor.slot_key == descriptor.slot_key), None)
+ current = [x for x in current if x.descriptor.slot_key != descriptor.slot_key]
active = ActiveHook(uuid.uuid4().hex, candidate.candidate_id, spec.spec_id, candidate.source_path, source_sha, descriptor,
compatibility, time.time(), reason.strip(), previous.activation_id if previous else None)
current.append(active)
@@ -223,12 +347,15 @@ def clear(self, reason: str) -> list[ActiveHook]:
self._history("hooks_cleared", activations=[asdict(x) for x in current], reason=reason.strip())
return current
- def runtime_metadata(self) -> dict[str, Any]:
- hooks = []
- for active in self.active():
- source = Path(active.source_path)
- if not source.is_file() or hashlib.sha256(source.read_bytes()).hexdigest() != active.source_sha256: continue
- hooks.append({"activation_id": active.activation_id, "candidate_id": active.candidate_id, "spec_id": active.spec_id,
- "source_path": active.source_path, "source_sha256": active.source_sha256,
- "descriptor": asdict(active.descriptor)})
- return {"active_hooks": hooks}
+ @staticmethod
+ def _runtime_item(active: ActiveHook) -> dict[str, Any] | None:
+ source = Path(active.source_path)
+ if not source.is_file() or hashlib.sha256(source.read_bytes()).hexdigest() != active.source_sha256: return None
+ return {"activation_id": active.activation_id, "candidate_id": active.candidate_id, "spec_id": active.spec_id,
+ "source_path": active.source_path, "source_sha256": active.source_sha256,
+ "descriptor": asdict(active.descriptor)}
+
+ def runtime_metadata(self, context: ExecutionContext | None = None) -> dict[str, Any]:
+ source = self.resolve(context) if context is not None else self.active()
+ hooks = [item for active in source if (item := self._runtime_item(active)) is not None]
+ return {"active_hooks": hooks, "execution_context": asdict(context) if context is not None else None}
From 76b872fb4262de32c0e0238c4df15378f9bff59d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:23:05 +0530
Subject: [PATCH 077/168] radeon forge: export execution-stage hook contracts
---
extra/radeon_forge/synthesis/__init__.py | 11 +++++++----
1 file changed, 7 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/synthesis/__init__.py b/extra/radeon_forge/synthesis/__init__.py
index cd4d63a5f95a9..2cb1df40b17a6 100644
--- a/extra/radeon_forge/synthesis/__init__.py
+++ b/extra/radeon_forge/synthesis/__init__.py
@@ -1,9 +1,12 @@
from .defaults import install_default_specs
-from .hooks import ActiveHook, CompatibilityReport, HookDescriptor, HookLayer, HookMode, HookRegistry, RuntimeFingerprint, check_compatibility
+from .hooks import (ActiveHook, CompatibilityReport, ExecutionContext, ExecutionStage, HookDescriptor, HookLayer, HookMode,
+ HookRegistry, RuntimeFingerprint, StagePredicate, check_compatibility)
+from .portable import export_recipe_with_hook
from .recipe import ForgeRecipe, InstalledRecipe, RecipeArtifact, RecipeLibrary, export_recipe
from .tools import OptimizationTools
from .workspace import CandidateRecord, CandidateWorkspace, KernelSpec
-__all__ = ["ActiveHook", "CandidateRecord", "CandidateWorkspace", "CompatibilityReport", "ForgeRecipe", "HookDescriptor",
- "HookLayer", "HookMode", "HookRegistry", "InstalledRecipe", "KernelSpec", "OptimizationTools", "RecipeArtifact",
- "RecipeLibrary", "RuntimeFingerprint", "check_compatibility", "export_recipe", "install_default_specs"]
+__all__ = ["ActiveHook", "CandidateRecord", "CandidateWorkspace", "CompatibilityReport", "ExecutionContext", "ExecutionStage",
+ "ForgeRecipe", "HookDescriptor", "HookLayer", "HookMode", "HookRegistry", "InstalledRecipe", "KernelSpec",
+ "OptimizationTools", "RecipeArtifact", "RecipeLibrary", "RuntimeFingerprint", "StagePredicate", "check_compatibility",
+ "export_recipe", "export_recipe_with_hook", "install_default_specs"]
From 148765a2e84ff28ecfe498c8f07b1b3dbddeec54 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:23:23 +0530
Subject: [PATCH 078/168] radeon forge: scope default hooks to execution stages
---
extra/radeon_forge/synthesis/defaults.py | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/extra/radeon_forge/synthesis/defaults.py b/extra/radeon_forge/synthesis/defaults.py
index 139b14deeab86..0ff82351288c4 100644
--- a/extra/radeon_forge/synthesis/defaults.py
+++ b/extra/radeon_forge/synthesis/defaults.py
@@ -17,7 +17,9 @@ def install_default_specs(workspace: CandidateWorkspace) -> list[KernelSpec]:
mockgpu_command=("python3", "{candidate}"), hardware_command=("python3", "{candidate}"),
metadata={"seed":"extra/gemm/amd_asm_matmul.py", "role":"infrastructure and schedule-synthesis gate",
"hook":{"layer":"kernel", "target":"batch1_projection_gemm", "mode":"replace", "adapter":"request_metadata",
- "selector":{"program_name":"generated_gemm"}, "exclusive_group":"projection_gemm",
+ "selector":{"program_name":"generated_gemm"},
+ "when":{"stages":["prefill", "first_token", "decode"], "batch_sizes":[1]},
+ "exclusive_group":"projection_gemm",
"description":"Validated kernel selection forwarded to a backend-specific kernel adapter."}},
),
KernelSpec(
@@ -31,9 +33,10 @@ def install_default_specs(workspace: CandidateWorkspace) -> list[KernelSpec]:
objective="minimize inter-token latency and kernel launches/token",
metadata={"status":"oracle command must be bound after selecting the model", "role":"final technical target",
"hook":{"layer":"transformer_block", "target":"llama.decode.block", "mode":"replace",
- "adapter":"python_transformer_block", "selector":{"indices":"all", "phase":"decode"},
+ "adapter":"python_transformer_block", "selector":{"indices":"all"},
+ "when":{"stages":["decode"], "batch_sizes":[1], "min_generated_token_index":1},
"exclusive_group":"decode_transformer_block",
- "description":"Replace selected tinygrad Llama blocks inside the isolated model process."}},
+ "description":"Replace selected tinygrad Llama blocks only during steady batch-one decode."}},
),
]
existing = {x.spec_id for x in workspace.specs()}
From d88be92a8799e24f636a08363f417687a58c1874 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:23:51 +0530
Subject: [PATCH 079/168] radeon forge: export stage-aware hook predicates
---
extra/radeon_forge/synthesis/portable.py | 24 ++++++++++++++++++++----
1 file changed, 20 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/synthesis/portable.py b/extra/radeon_forge/synthesis/portable.py
index 00c4440ca0305..86b99d49bed5b 100644
--- a/extra/radeon_forge/synthesis/portable.py
+++ b/extra/radeon_forge/synthesis/portable.py
@@ -18,21 +18,36 @@ def _toml_value(value: Any) -> str:
def _append_table(lines: list[str], name: str, values: Mapping[str, Any]) -> None:
- if not values: return
+ filtered = {key: value for key, value in values.items() if value is not None and value != {}}
+ if not filtered: return
lines.append(f"\n[{name}]")
- for key, value in values.items():
+ for key, value in filtered.items():
if isinstance(value, Mapping): continue
lines.append(f"{json.dumps(str(key))} = {_toml_value(value)}")
- for key, value in values.items():
+ for key, value in filtered.items():
if isinstance(value, Mapping): _append_table(lines, f"{name}.{key}", value)
def export_recipe_with_hook(workspace: CandidateWorkspace, spec_id: str, output: str | Path,
candidate_id: str | None = None) -> Path:
- """Export one recipe while preserving its concrete runtime interception point."""
+ """Export one recipe while preserving both placement and execution-state applicability."""
path = export_recipe(workspace, spec_id, output, candidate_id)
spec = workspace.load_spec(spec_id)
descriptor = HookDescriptor.from_spec(spec)
+ predicate = descriptor.when
+ when = {
+ "stages": [stage.value for stage in predicate.stages],
+ "min_context_tokens": predicate.min_context_tokens,
+ "max_context_tokens": predicate.max_context_tokens,
+ "min_prompt_tokens": predicate.min_prompt_tokens,
+ "max_prompt_tokens": predicate.max_prompt_tokens,
+ "min_generated_token_index": predicate.min_generated_token_index,
+ "max_generated_token_index": predicate.max_generated_token_index,
+ "batch_sizes": list(predicate.batch_sizes),
+ "prefix_cache": predicate.prefix_cache,
+ "warm": predicate.warm,
+ "conditions": dict(predicate.conditions),
+ }
hook = {
"layer": descriptor.layer.value,
"target": descriptor.target,
@@ -42,6 +57,7 @@ def export_recipe_with_hook(workspace: CandidateWorkspace, spec_id: str, output:
"exclusive_group": descriptor.exclusive_group,
"description": descriptor.description,
"selector": dict(descriptor.selector),
+ "when": when,
}
lines = path.read_text(encoding="utf-8").rstrip().splitlines()
_append_table(lines, "metadata.hook", hook)
From bb3ee545f5f7e966e47c48059afc328bc6421c8c Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:24:22 +0530
Subject: [PATCH 080/168] radeon forge: retain local runtime fingerprint
metadata
---
extra/radeon_forge/runtime/backend.py | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/extra/radeon_forge/runtime/backend.py b/extra/radeon_forge/runtime/backend.py
index dafcd7fc7b21e..e81c165ab3397 100644
--- a/extra/radeon_forge/runtime/backend.py
+++ b/extra/radeon_forge/runtime/backend.py
@@ -40,6 +40,8 @@ class InferenceBackend(Protocol):
def name(self) -> str: ...
@property
def capabilities(self) -> BackendCapabilities: ...
+ @property
+ def runtime_metadata(self) -> Mapping[str, Any]: ...
def stream(self, request: GenerationRequest) -> Iterator[GenerationEvent]: ...
def close(self) -> None: ...
@@ -63,11 +65,14 @@ def __init__(self, command: Sequence[str], env: Mapping[str, str] | None = None)
if payload.get("kind") != "ready": raise RuntimeError(f"invalid backend handshake: {payload}")
self._name = str(payload.get("name", "jsonl-local-model"))
self._capabilities = BackendCapabilities(**payload.get("capabilities", {}))
+ self._runtime_metadata = {str(key): value for key, value in payload.items() if key not in {"kind", "name", "capabilities"}}
@property
def name(self) -> str: return self._name
@property
def capabilities(self) -> BackendCapabilities: return self._capabilities
+ @property
+ def runtime_metadata(self) -> Mapping[str, Any]: return dict(self._runtime_metadata)
def _drain_stderr(self) -> None:
for line in self._stderr:
From ee2332617798c32d2f96e7516423e9c024467b69 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:24:35 +0530
Subject: [PATCH 081/168] radeon forge: expose scripted runtime metadata
---
extra/radeon_forge/backends/fake.py | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/backends/fake.py b/extra/radeon_forge/backends/fake.py
index 50baf93a8471c..d16196f38631f 100644
--- a/extra/radeon_forge/backends/fake.py
+++ b/extra/radeon_forge/backends/fake.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Iterator
+from typing import Iterator, Mapping, Any
from ..runtime.backend import BackendCapabilities, GenerationEvent, GenerationRequest
@@ -11,6 +11,9 @@ def __init__(self, responses: list[str] | None = None): self.responses = respons
def name(self) -> str: return "scripted-local"
@property
def capabilities(self) -> BackendCapabilities: return BackendCapabilities(kernel_metrics=True)
+ @property
+ def runtime_metadata(self) -> Mapping[str, Any]:
+ return {"runtime": "scripted", "architecture": "", "gpu": "", "model_family": "test"}
def stream(self, request: GenerationRequest) -> Iterator[GenerationEvent]:
text = self.responses.pop(0) if self.responses else "Done."
yield GenerationEvent("prefill", metrics={"wall_ms": 4.0, "prompt_tokens": 32, "prefix_reused_tokens": 24})
From 5d945b56ee95503e537792a9b73a47acd04e31fd Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:25:22 +0530
Subject: [PATCH 082/168] radeon forge: apply stage-specific model hooks with
rollback
---
extra/radeon_forge/backends/stage_hooks.py | 105 +++++++++++++++++++++
1 file changed, 105 insertions(+)
create mode 100644 extra/radeon_forge/backends/stage_hooks.py
diff --git a/extra/radeon_forge/backends/stage_hooks.py b/extra/radeon_forge/backends/stage_hooks.py
new file mode 100644
index 0000000000000..ace5137e51c9c
--- /dev/null
+++ b/extra/radeon_forge/backends/stage_hooks.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+import hashlib, importlib.util
+from dataclasses import asdict
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+from tinygrad import TinyJit
+
+from ..synthesis.hooks import ExecutionContext, StagePredicate
+
+
+class StageHookError(RuntimeError): pass
+
+
+def _matching_hooks(hooks: Sequence[Mapping[str, Any]], context: ExecutionContext) -> list[Mapping[str, Any]]:
+ """Resolve the highest-priority matching hook in each exclusive group."""
+ selected: dict[str, Mapping[str, Any]] = {}
+ for hook in hooks:
+ descriptor = hook.get("descriptor", {})
+ if not isinstance(descriptor, Mapping): continue
+ try: predicate = StagePredicate.from_mapping(descriptor.get("when", {}))
+ except Exception: continue
+ if not predicate.matches(context): continue
+ group = str(descriptor.get("exclusive_group", f"{descriptor.get('layer')}:{descriptor.get('target')}"))
+ previous = selected.get(group)
+ if previous is None or int(descriptor.get("priority", 0)) > int(previous.get("descriptor", {}).get("priority", 0)):
+ selected[group] = hook
+ return sorted(selected.values(), key=lambda x: -int(x.get("descriptor", {}).get("priority", 0)))
+
+
+class ModelStageHookRuntime:
+ """Apply validated Python model hooks only in their declared execution states.
+
+ Candidate code runs inside the already-isolated local model subprocess. The
+ original model objects are retained and restored on every transition or
+ failure. This adapter never treats activation metadata as validation evidence.
+ """
+ def __init__(self, model: Any):
+ self.model = model
+ self._original_layers = tuple(getattr(model, "layers", ()))
+ self._active_signature: tuple[str, ...] = ()
+ self._loaded_modules: dict[tuple[str, str], Any] = {}
+
+ def _reset(self) -> None:
+ if self._original_layers and hasattr(self.model, "layers"): self.model.layers = list(self._original_layers)
+ if hasattr(self.model, "forward_jit") and self.model.forward_jit is not None: self.model.forward_jit = TinyJit(self.model.forward)
+ self._active_signature = ()
+
+ @staticmethod
+ def _indices(selector: Mapping[str, Any], count: int) -> list[int]:
+ value = selector.get("indices", "all")
+ if value == "all": return list(range(count))
+ if isinstance(value, int): values = [value]
+ elif isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): values = [int(x) for x in value]
+ else: raise StageHookError("transformer block selector indices must be 'all', an integer, or an array")
+ if any(index < 0 or index >= count for index in values): raise StageHookError("transformer block selector is out of range")
+ return values
+
+ def _module(self, hook: Mapping[str, Any]) -> Any:
+ path = Path(str(hook["source_path"]))
+ expected = str(hook["source_sha256"])
+ if not path.is_file(): raise StageHookError(f"hook source is missing: {path}")
+ actual = hashlib.sha256(path.read_bytes()).hexdigest()
+ if actual != expected: raise StageHookError("hook source changed after activation")
+ key = (str(path), expected)
+ if key in self._loaded_modules: return self._loaded_modules[key]
+ spec = importlib.util.spec_from_file_location(f"radeon_forge_hook_{expected[:16]}", path)
+ if spec is None or spec.loader is None: raise StageHookError(f"cannot import hook source {path}")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ self._loaded_modules[key] = module
+ return module
+
+ def apply(self, hooks: Sequence[Mapping[str, Any]], context: ExecutionContext) -> dict[str, Any]:
+ selected = [hook for hook in _matching_hooks(hooks, context)
+ if hook.get("descriptor", {}).get("adapter") == "python_transformer_block"]
+ signature = tuple(str(hook.get("activation_id")) for hook in selected)
+ if signature == self._active_signature:
+ return {"changed": False, "active": list(signature), "stage": context.stage.value}
+ self._reset()
+ if not selected: return {"changed": True, "active": [], "stage": context.stage.value, "baseline": True}
+ try:
+ layers = list(self._original_layers)
+ for hook in selected:
+ descriptor = hook["descriptor"]
+ if descriptor.get("mode", "replace") != "replace": raise StageHookError("python_transformer_block currently supports replace mode only")
+ module = self._module(hook)
+ factory = getattr(module, "build_replacement", None)
+ if not callable(factory): raise StageHookError("hook must define build_replacement(original, layer_index, model, context)")
+ selector = descriptor.get("selector", {})
+ for index in self._indices(selector if isinstance(selector, Mapping) else {}, len(layers)):
+ replacement = factory(layers[index], index, self.model, asdict(context))
+ if not callable(replacement): raise StageHookError(f"replacement for layer {index} is not callable")
+ layers[index] = replacement
+ self.model.layers = layers
+ if hasattr(self.model, "forward_jit") and self.model.forward_jit is not None: self.model.forward_jit = TinyJit(self.model.forward)
+ self._active_signature = signature
+ return {"changed": True, "active": list(signature), "stage": context.stage.value, "baseline": False}
+ except Exception as exc:
+ self._reset()
+ return {"changed": True, "active": [], "stage": context.stage.value, "baseline": True,
+ "rolled_back": True, "error": str(exc), "error_type": type(exc).__name__}
+
+ def close(self) -> None: self._reset()
From bf739f3dc963d130411f29c3049c5d3dc645424d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:26:07 +0530
Subject: [PATCH 083/168] radeon forge: inject active optimization state into
model turns
---
extra/radeon_forge/runtime/session.py | 21 +++++++++++++--------
1 file changed, 13 insertions(+), 8 deletions(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index ec547ff0b22d5..a4cf0b4227d26 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -3,7 +3,7 @@
import threading, time, uuid
from dataclasses import asdict, dataclass, field
from enum import Enum
-from typing import Any, Mapping
+from typing import Any, Callable, Mapping
from .backend import GenerationRequest, InferenceBackend
from .events import TraceRecorder
@@ -30,10 +30,11 @@ class SessionEvent:
class AgentSession:
"""Persistent private-agent session with explicit tool approval and full tracing."""
def __init__(self, backend: InferenceBackend, tools: ToolRegistry, system_prompt: str, session_id: str | None = None,
- max_agent_steps: int = 8, trace: TraceRecorder | None = None):
+ max_agent_steps: int = 8, trace: TraceRecorder | None = None,
+ metadata_provider: Callable[[AgentSession, int], Mapping[str, Any]] | None = None):
self.session_id = session_id or uuid.uuid4().hex
self.backend, self.tools, self.system_prompt = backend, tools, system_prompt
- self.max_agent_steps = max_agent_steps
+ self.max_agent_steps, self.metadata_provider = max_agent_steps, metadata_provider
self.trace = trace or TraceRecorder()
self.messages: list[dict[str, Any]] = [{"role": "system", "content": self._system_prompt()}]
self.events: list[SessionEvent] = []
@@ -84,6 +85,13 @@ def _record_backend_event(self, event, parent_id: str) -> None:
if "parent_id" in metrics: metrics["backend_parent_id"] = metrics.pop("parent_id")
self.trace.point("inference", event.kind, parent_id, **metrics)
+ def _request_metadata(self, step: int) -> dict[str, Any]:
+ metadata = {"trace_id": self.trace.trace_id, "step": step,
+ "tool_round": sum(1 for event in self.events if event.kind == "tool_result"),
+ "resume_after_tool": bool(self.messages and self.messages[-1].get("role") == "tool")}
+ if self.metadata_provider is not None: metadata.update(dict(self.metadata_provider(self, step)))
+ return metadata
+
def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent, ...]:
self.state = SessionState.GENERATING
started_at = len(self.events)
@@ -93,7 +101,7 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
with self.trace.span("agent", "model_turn", session_id=self.session_id, step=step) as parent:
self._emit("generation_started", backend=self.backend.name, step=step, capabilities=asdict(self.backend.capabilities))
request = GenerationRequest(self.session_id, tuple(self.messages), tuple(self.tools.schemas()), max_tokens, temperature,
- metadata={"trace_id": self.trace.trace_id, "step": step})
+ metadata=self._request_metadata(step))
try:
for event in self.backend.stream(request):
if event.kind == "token":
@@ -103,7 +111,7 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
if "name" in token_metrics: token_metrics["token_name"] = token_metrics.pop("name")
self.trace.duration("inference", "token", float(token_metrics.get("wall_ms", 0.0)), parent.event_id,
text=event.text, **token_metrics)
- elif event.kind in {"prefill", "decode", "kernel", "metric"}: self._record_backend_event(event, parent.event_id)
+ elif event.kind in {"prefill", "decode", "kernel", "metric", "hook"}: self._record_backend_event(event, parent.event_id)
elif event.kind == "tool_call" and event.tool_call is not None:
self.pending_tool_call = ToolCall(str(event.tool_call.get("id") or uuid.uuid4().hex), str(event.tool_call["name"]), event.tool_call.get("arguments", {}))
elif event.kind == "done": self._emit("generation_done", finish_reason=event.finish_reason, metrics=dict(event.metrics))
@@ -136,9 +144,6 @@ def approve_tool(self, permission_token: str, max_tokens: int = 512) -> tuple[Se
result = self.tools.execute(call, permission_token)
self.trace.point("tool", "tool_result", span.event_id, ok=result.ok, elapsed_ms=result.elapsed_ms)
except Exception as exc:
- # Authorization happens before the tool body. A stale, exhausted or
- # incorrectly scoped grant must leave the proposed call pending so the
- # user can issue a fresh explicit grant and retry it safely.
self.state = SessionState.AWAITING_TOOL_APPROVAL
self._emit("tool_authorization_failed", call_id=call.call_id, error=str(exc), error_type=type(exc).__name__)
raise
From e8c3e63e37f069ba18bd4d2249fc64e7a9798604 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:27:10 +0530
Subject: [PATCH 084/168] radeon forge: add permissioned stage-aware hook
deployment tools
---
extra/radeon_forge/synthesis/tools.py | 77 +++++++++++++++++++++------
1 file changed, 62 insertions(+), 15 deletions(-)
diff --git a/extra/radeon_forge/synthesis/tools.py b/extra/radeon_forge/synthesis/tools.py
index 5b11b602b662e..e58e7f27a24f3 100644
--- a/extra/radeon_forge/synthesis/tools.py
+++ b/extra/radeon_forge/synthesis/tools.py
@@ -3,21 +3,25 @@
import os, subprocess, time
from dataclasses import asdict
from pathlib import Path
-from typing import Any, Mapping
+from typing import Any, Callable, Mapping
from ..oracles.mockgpu import MockGPUOracle
from ..permissions import Action
from ..runtime.tools import ToolRegistry, ToolSpec
-from .recipe import RecipeLibrary, export_recipe
+from .hooks import HookRegistry, RuntimeFingerprint
+from .portable import export_recipe_with_hook
+from .recipe import RecipeLibrary
from .workspace import CandidateWorkspace
class OptimizationTools:
- def __init__(self, workspace: CandidateWorkspace, project_root: str | Path):
+ def __init__(self, workspace: CandidateWorkspace, project_root: str | Path, hooks: HookRegistry | None = None,
+ fingerprint_provider: Callable[[], RuntimeFingerprint] | None = None):
self.workspace = workspace
self.project_root = Path(project_root).resolve()
self.mockgpu = MockGPUOracle(self.project_root)
self.recipes = RecipeLibrary(workspace)
+ self.hooks, self.fingerprint_provider = hooks, fingerprint_provider
def _project_path(self, value: str, *, must_exist: bool = False) -> Path:
path = (self.project_root / value).resolve() if not Path(value).is_absolute() else Path(value).resolve()
@@ -25,6 +29,9 @@ def _project_path(self, value: str, *, must_exist: bool = False) -> Path:
if must_exist and not path.is_file(): raise FileNotFoundError(path)
return path
+ def _fingerprint(self) -> RuntimeFingerprint:
+ return self.fingerprint_provider() if self.fingerprint_provider is not None else RuntimeFingerprint()
+
def list_specs(self, args: Mapping[str, Any]) -> Any:
return {"specs": [asdict(x) | {"spec_id": x.spec_id} for x in self.workspace.specs()]}
@@ -45,23 +52,39 @@ def validate_mockgpu(self, args: Mapping[str, Any]) -> Any:
updated = self.workspace.update(candidate.candidate_id, "mockgpu_passed" if result.passed else "mockgpu_failed", {"mockgpu": result.to_dict()})
return asdict(updated)
- def benchmark_hardware(self, args: Mapping[str, Any]) -> Any:
- candidate = self.workspace.load_candidate(str(args["candidate_id"]))
- if candidate.status != "mockgpu_passed" and not bool(args.get("allow_without_mockgpu", False)):
- raise ValueError("candidate must pass MockGPU before W7900 benchmarking")
+ def _run_hardware_command(self, candidate_id: str, command_value, timeout_seconds: int, evidence_key: str,
+ pass_status: str, fail_status: str) -> Any:
+ candidate = self.workspace.load_candidate(candidate_id)
spec = self.workspace.load_spec(candidate.spec_id)
- if not spec.hardware_command: raise ValueError("spec has no hardware benchmark command")
- command = self.workspace.render_command(spec.hardware_command, spec, candidate, self.project_root)
+ command = self.workspace.render_command(command_value, spec, candidate, self.project_root)
env = {**os.environ, "DEV": "AMD", "RADEON_FORGE_CANDIDATE": candidate.source_path,
"RADEON_FORGE_RECIPE_BUNDLE": str(spec.metadata.get("recipe_bundle", "")), "PYTHONUNBUFFERED": "1"}
started = time.perf_counter_ns()
proc = subprocess.run(command, cwd=str(spec.metadata.get("recipe_bundle", self.project_root)), env=env, text=True, capture_output=True,
- timeout=int(args.get("timeout_seconds", 900)))
+ timeout=timeout_seconds)
evidence = {"command": command, "returncode": proc.returncode, "elapsed_ms": (time.perf_counter_ns()-started)/1e6,
"stdout": proc.stdout[-50000:], "stderr": proc.stderr[-50000:], "target": spec.target}
- updated = self.workspace.update(candidate.candidate_id, "hardware_passed" if proc.returncode == 0 else "hardware_failed", {"hardware": evidence})
+ updated = self.workspace.update(candidate.candidate_id, pass_status if proc.returncode == 0 else fail_status, {evidence_key: evidence})
return asdict(updated)
+ def benchmark_hardware(self, args: Mapping[str, Any]) -> Any:
+ candidate = self.workspace.load_candidate(str(args["candidate_id"]))
+ if candidate.status != "mockgpu_passed" and not bool(args.get("allow_without_mockgpu", False)):
+ raise ValueError("candidate must pass MockGPU before W7900 benchmarking")
+ spec = self.workspace.load_spec(candidate.spec_id)
+ if not spec.hardware_command: raise ValueError("spec has no hardware benchmark command")
+ return self._run_hardware_command(candidate.candidate_id, spec.hardware_command, int(args.get("timeout_seconds", 900)),
+ "hardware", "hardware_passed", "hardware_failed")
+
+ def validate_heldout(self, args: Mapping[str, Any]) -> Any:
+ candidate = self.workspace.load_candidate(str(args["candidate_id"]))
+ if candidate.status != "hardware_passed": raise ValueError("candidate must pass the real hardware benchmark first")
+ spec = self.workspace.load_spec(candidate.spec_id)
+ command = tuple(str(x) for x in spec.metadata.get("heldout_command", ()))
+ if not command: raise ValueError("spec has no held-out validation command")
+ return self._run_hardware_command(candidate.candidate_id, command, int(args.get("timeout_seconds", 900)),
+ "heldout", "heldout_passed", "heldout_failed")
+
def list_recipes(self, args: Mapping[str, Any]) -> Any:
return {"recipes": [asdict(x) for x in self.recipes.installed()]}
@@ -74,8 +97,28 @@ def import_recipe(self, args: Mapping[str, Any]) -> Any:
def export_recipe_file(self, args: Mapping[str, Any]) -> Any:
output = self._project_path(str(args["output"]))
- path = export_recipe(self.workspace, str(args["spec_id"]), output, str(args["candidate_id"]) if args.get("candidate_id") else None)
- return {"path": str(path), "sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest(), "portable": True}
+ path = export_recipe_with_hook(self.workspace, str(args["spec_id"]), output,
+ str(args["candidate_id"]) if args.get("candidate_id") else None)
+ return {"path": str(path), "sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest(), "portable": True,
+ "includes_execution_stage_hook": True}
+
+ def list_active_hooks(self, args: Mapping[str, Any]) -> Any:
+ if self.hooks is None: return {"hooks": [], "available": False}
+ return {"hooks": [asdict(x) for x in self.hooks.active()], "available": True,
+ "runtime_fingerprint": asdict(self._fingerprint())}
+
+ def activate_hook(self, args: Mapping[str, Any]) -> Any:
+ if self.hooks is None: raise RuntimeError("hook registry is unavailable")
+ fingerprint = self._fingerprint()
+ if not fingerprint.architecture and not bool(args.get("allow_unknown_runtime", False)):
+ raise ValueError("runtime architecture is unknown; start the real local model backend before deployment")
+ active = self.hooks.activate(str(args["candidate_id"]), fingerprint,
+ str(args.get("reason", "Approved stage-specific local deployment")))
+ return asdict(active)
+
+ def deactivate_hook(self, args: Mapping[str, Any]) -> Any:
+ if self.hooks is None: raise RuntimeError("hook registry is unavailable")
+ return asdict(self.hooks.deactivate(str(args["activation_id"]), str(args.get("reason", "User-requested rollback"))))
def install(self, registry: ToolRegistry) -> None:
registry.register(ToolSpec("list_kernel_specs", "List typed megakernel and fused-kernel contracts", {"type":"object","properties":{}}), self.list_specs)
@@ -83,7 +126,11 @@ def install(self, registry: ToolRegistry) -> None:
registry.register(ToolSpec("stage_kernel_candidate", "Write one disposable implementation for a typed kernel specification", {"type":"object","required":["spec_id","source","hypothesis"],"properties":{"spec_id":{"type":"string"},"source":{"type":"string"},"hypothesis":{"type":"string"},"parent_id":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.stage_candidate)
registry.register(ToolSpec("validate_candidate_mockgpu", "Execute a generated AMD candidate through tinygrad's RDNA3 MockGPU semantic oracle", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"}}}, Action.COMPILE), self.validate_mockgpu)
registry.register(ToolSpec("benchmark_candidate_w7900", "Benchmark a MockGPU-passing candidate on the real local W7900", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"},"timeout_seconds":{"type":"integer"},"allow_without_mockgpu":{"type":"boolean"}}}, Action.BENCHMARK), self.benchmark_hardware)
+ registry.register(ToolSpec("validate_candidate_heldout", "Run a hardware-passing candidate on its held-out correctness and task-quality suite", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"},"timeout_seconds":{"type":"integer"}}}, Action.BENCHMARK), self.validate_heldout)
registry.register(ToolSpec("list_forge_recipes", "List portable installed optimization recipes", {"type":"object","properties":{}}), self.list_recipes)
- registry.register(ToolSpec("inspect_forge_recipe", "Read the intent, invariants, oracle and artifact inventory of an installed optimization recipe", {"type":"object","required":["recipe_id"],"properties":{"recipe_id":{"type":"string"}}}), self.inspect_recipe)
+ registry.register(ToolSpec("inspect_forge_recipe", "Read the intent, invariants, execution-stage hook, oracle and artifact inventory of an installed optimization recipe", {"type":"object","required":["recipe_id"],"properties":{"recipe_id":{"type":"string"}}}), self.inspect_recipe)
registry.register(ToolSpec("import_forge_recipe", "Install one portable .forge.toml optimization recipe from the private workspace", {"type":"object","required":["path"],"properties":{"path":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.import_recipe)
- registry.register(ToolSpec("export_forge_recipe", "Export a contract and optional implementation cache as one shareable .forge.toml file", {"type":"object","required":["spec_id","output"],"properties":{"spec_id":{"type":"string"},"candidate_id":{"type":"string"},"output":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.export_recipe_file)
+ registry.register(ToolSpec("export_forge_recipe", "Export a contract, execution-stage hook and optional implementation cache as one shareable .forge.toml file", {"type":"object","required":["spec_id","output"],"properties":{"spec_id":{"type":"string"},"candidate_id":{"type":"string"},"output":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.export_recipe_file)
+ registry.register(ToolSpec("list_active_optimization_hooks", "List deployed optimizations and the execution states in which each can run", {"type":"object","properties":{}}), self.list_active_hooks)
+ registry.register(ToolSpec("activate_optimization_hook", "Deploy a validated optimization into its declared execution stages; activation is compatibility-gated and rollback-safe", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"},"reason":{"type":"string"},"allow_unknown_runtime":{"type":"boolean"}}}, Action.DEPLOY), self.activate_hook)
+ registry.register(ToolSpec("deactivate_optimization_hook", "Rollback one active optimization hook", {"type":"object","required":["activation_id"],"properties":{"activation_id":{"type":"string"},"reason":{"type":"string"}}}, Action.DEPLOY), self.deactivate_hook)
From 83739d7ca1f7890a612248158092697b8321cf06 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:27:40 +0530
Subject: [PATCH 085/168] radeon forge: connect stage-aware hooks to live
sessions
---
extra/radeon_forge/runtime/engine.py | 26 ++++++++++++++++++++------
1 file changed, 20 insertions(+), 6 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index a68fbcca15098..41281fb994d98 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -3,11 +3,11 @@
import threading
from dataclasses import asdict
from pathlib import Path
-from typing import Any
+from typing import Any, Mapping
from ..permissions import PermissionController
from ..profiling.report import build_profile_report
-from ..synthesis import CandidateWorkspace, OptimizationTools, install_default_specs
+from ..synthesis import CandidateWorkspace, HookRegistry, OptimizationTools, RuntimeFingerprint, install_default_specs
from .backend import InferenceBackend
from .session import AgentSession
from .tools import ToolRegistry, WorkspaceTools
@@ -16,7 +16,7 @@
DEFAULT_SYSTEM_PROMPT = """You are Radeon Forge, a private local software and inference performance engineer.
Use evidence before making performance claims. Separate observations, inferences and unknowns. Prefer reversible changes and preserve correctness. You may inspect the private workspace, author disposable target-specific kernel candidates, import portable optimization recipes, validate implementations through tinygrad MockGPU, and request permission for real W7900 benchmarks. Never treat MockGPU timing as performance evidence.
-Optimization recipes are contracts, not programming languages. Read their free-form intent, invariants, oracle, knowledge and failed experiments; then use your judgment to regenerate or radically restructure implementations. Cached source is merely one prior compilation and must never outrank the oracle."""
+Optimization recipes are contracts, not programming languages. A hook has two independent coordinates: where it intercepts the stack (scheduler, model block, subgraph, kernel, KV cache, sampler) and when it applies (prefill, first token, steady decode, tool resume, KV append, sampling, or a workload predicate). Read the free-form intent, invariants, oracle, stage predicate, knowledge and failed experiments; then use your judgment to regenerate or radically restructure implementations. Cached source is merely one prior compilation and must never outrank the oracle."""
class ForgeEngine:
@@ -27,14 +27,26 @@ def __init__(self, backend: InferenceBackend, workspace: str | Path, system_prom
WorkspaceTools(self.workspace).install(self.tools)
self.optimization_workspace = CandidateWorkspace(self.workspace / ".radeon_forge")
install_default_specs(self.optimization_workspace)
- self.optimization_tools = OptimizationTools(self.optimization_workspace, self.workspace)
+ self.hooks = HookRegistry(self.optimization_workspace)
+ self.optimization_tools = OptimizationTools(self.optimization_workspace, self.workspace, self.hooks, self.runtime_fingerprint)
self.optimization_tools.install(self.tools)
self._sessions: dict[str, AgentSession] = {}
self._lock = threading.RLock()
+ def runtime_fingerprint(self) -> RuntimeFingerprint:
+ metadata = getattr(self.backend, "runtime_metadata", {})
+ if callable(metadata): metadata = metadata()
+ return RuntimeFingerprint.from_mapping(metadata if isinstance(metadata, Mapping) else {})
+
+ def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, Any]:
+ # Send every validated active hook to the isolated backend. The backend
+ # resolves execution-state predicates at prefill/first-token/decode/tool
+ # resume boundaries using live context that the outer agent cannot fake.
+ return {**self.hooks.runtime_metadata(), "runtime_fingerprint": asdict(self.runtime_fingerprint())}
+
def create_session(self) -> AgentSession:
with self._lock:
- session = AgentSession(self.backend, self.tools, self.system_prompt)
+ session = AgentSession(self.backend, self.tools, self.system_prompt, metadata_provider=self._session_metadata)
self._sessions[session.session_id] = session
return session
@@ -56,6 +68,8 @@ def profile(self, session_id: str) -> dict[str, Any]: return build_profile_repor
def optimization_state(self) -> dict[str, Any]:
return {"specs": [asdict(x) | {"spec_id": x.spec_id} for x in self.optimization_workspace.specs()],
"candidates": [asdict(x) for x in self.optimization_workspace.candidates()],
- "recipes": [asdict(x) for x in self.optimization_tools.recipes.installed()]}
+ "recipes": [asdict(x) for x in self.optimization_tools.recipes.installed()],
+ "active_hooks": [asdict(x) for x in self.hooks.active()],
+ "runtime_fingerprint": asdict(self.runtime_fingerprint())}
def close(self) -> None: self.backend.close()
From e27d6451653ab584a2367f143871528484c116a2 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:28:52 +0530
Subject: [PATCH 086/168] radeon forge: resolve hooks at live inference stage
boundaries
---
.../backends/tinygrad_llama_worker.py | 62 +++++++++++++++----
1 file changed, 51 insertions(+), 11 deletions(-)
diff --git a/extra/radeon_forge/backends/tinygrad_llama_worker.py b/extra/radeon_forge/backends/tinygrad_llama_worker.py
index 19c659de7cfca..2bba48fbfbeb7 100644
--- a/extra/radeon_forge/backends/tinygrad_llama_worker.py
+++ b/extra/radeon_forge/backends/tinygrad_llama_worker.py
@@ -1,14 +1,17 @@
from __future__ import annotations
-import argparse, json, sys, time
+import argparse, hashlib, json, sys, time
from pathlib import Path
-from typing import Any, Callable
+from typing import Any, Callable, Mapping
from tinygrad import Context, Device, GlobalCounters, Tensor
from tinygrad.device import Compiled
from tinygrad.nn.state import get_parameters
from examples.llama3 import Tokenizer, build_transformer
+from ..synthesis.hooks import ExecutionContext, ExecutionStage
+from .stage_hooks import ModelStageHookRuntime
+
MAX_PROFILE_EVENTS_PER_PHASE = 8192
@@ -76,6 +79,20 @@ def _emit_kernel_events(events: list[dict[str, Any]], *, stage: str, token_index
return len(emitted), truncated
+def _model_identity(path: Path, size: str, quantize: str | None) -> str:
+ try:
+ stat = path.stat()
+ identity = f"{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}:{size}:{quantize}"
+ except OSError: identity = f"{path}:{size}:{quantize}"
+ return hashlib.sha256(identity.encode()).hexdigest()
+
+
+def _hook_event(runtime: ModelStageHookRuntime, hooks: list[Mapping[str, Any]], context: ExecutionContext) -> None:
+ result = runtime.apply(hooks, context)
+ if result.get("changed") or result.get("rolled_back"):
+ send({"kind": "hook", "metrics": {**result, "context": context.flattened()}})
+
+
def main() -> None:
parser = argparse.ArgumentParser(description="Persistent tinygrad Llama backend for Radeon Forge")
parser.add_argument("--model", type=Path, required=True)
@@ -95,6 +112,9 @@ def main() -> None:
device = Device.DEFAULT
model = build_transformer(args.model, model_size=args.size, quantize=args.quantize, device=device, max_context=args.max_context)
param_bytes = sum(x.nbytes() for x in get_parameters(model))
+ hook_runtime = ModelStageHookRuntime(model)
+ device_obj = Device[device]
+ architecture = str(getattr(device_obj, "arch", ""))
def encode_role(role: str) -> list[int]:
return [tokenizer.special_tokens["<|start_header_id|>"]] + tokenizer.encode(role) + [tokenizer.special_tokens["<|end_header_id|>"]] + tokenizer.encode("\n\n")
@@ -106,20 +126,30 @@ def encode_message(message) -> list[int]:
active_session: str | None = None
active_tokens: list[int] = []
- send({"kind": "ready", "name": f"tinygrad-llama-{args.size}", "device": str(device), "model": str(args.model),
+ send({"kind": "ready", "name": f"tinygrad-llama-{args.size}", "device": str(device), "gpu": str(device),
+ "architecture": architecture, "runtime": "tinygrad", "runtime_revision": "radeon-forge",
+ "model": str(args.model), "model_family": "llama", "model_hash": _model_identity(args.model, args.size, args.quantize),
+ "dtype": args.quantize or "model_default", "shapes": {"batch": 1, "max_context": args.max_context},
"parameter_bytes": param_bytes, "capabilities": {"streaming": True, "structured_tools": False,
"prefix_cache": True, "persistent_kv": True, "kernel_metrics": True, "cancellation": False}})
for line in sys.stdin:
try:
payload = json.loads(line)
- if payload.get("op") == "shutdown": return
+ if payload.get("op") == "shutdown":
+ hook_runtime.close()
+ return
if payload.get("op") != "generate": raise ValueError("unsupported operation")
request = payload["request"]
+ metadata = request.get("metadata", {})
+ hooks = metadata.get("active_hooks", [])
+ if not isinstance(hooks, list): hooks = []
session_id = str(request["session_id"])
messages = request["messages"]
max_tokens = max(1, min(int(request.get("max_tokens", 256)), args.max_context))
temperature = float(request.get("temperature", 0.0))
+ tool_round = int(metadata.get("tool_round", 0))
+ resume_after_tool = bool(metadata.get("resume_after_tool", False))
prompt = [tokenizer.bos_id]
for message in messages: prompt += encode_message(message)
@@ -132,6 +162,11 @@ def encode_message(message) -> list[int]:
if old != new: break
common += 1
active_session = session_id
+ prefill_context = ExecutionContext(ExecutionStage.PREFILL, batch_size=1, prompt_tokens=len(prompt),
+ context_tokens=max(0, len(prompt)-1), generated_token_index=-1, prefix_reused_tokens=common,
+ tool_round=tool_round, warm=bool(active_tokens), attributes={"resume_after_tool": resume_after_tool, "session_id": session_id})
+ _hook_event(hook_runtime, hooks, prefill_context)
+
prefill_start = time.perf_counter_ns()
prefill_gpu_s, prefill_kernels, prefill_mem, prefill_ops = 0.0, 0, 0, 0
prefill_profile: list[dict[str, Any]] = []
@@ -149,7 +184,7 @@ def encode_message(message) -> list[int]:
send({"kind": "prefill", "metrics": {"wall_ms": prefill_wall_ms, "gpu_ms": prefill_gpu_s * 1e3,
"prompt_tokens": len(prompt), "prefix_reused_tokens": common, "new_prompt_tokens": max(0, len(prompt) - 1 - common),
"kernel_count": prefill_kernels, "global_mem_bytes": prefill_mem, "global_ops": prefill_ops,
- "profile_kernel_events": len(prefill_profile)}})
+ "profile_kernel_events": len(prefill_profile), "resume_after_tool": resume_after_tool}})
prefill_truncated = len(prefill_profile) > MAX_PROFILE_EVENTS_PER_PHASE
for sequence, event in enumerate(prefill_profile[:MAX_PROFILE_EVENTS_PER_PHASE]):
send({"kind": "kernel", "metrics": {**event, "stage": "prefill", "sequence": sequence}})
@@ -160,6 +195,11 @@ def encode_message(message) -> list[int]:
start_pos, last_tok = len(prompt) - 1, prompt[-1]
generated = 0
for index in range(max_tokens):
+ stage = ExecutionStage.FIRST_TOKEN if index == 0 else ExecutionStage.DECODE
+ decode_context = ExecutionContext(stage, batch_size=1, prompt_tokens=len(prompt), context_tokens=start_pos,
+ generated_token_index=index, prefix_reused_tokens=common, tool_round=tool_round, warm=True,
+ attributes={"resume_after_tool": resume_after_tool, "session_id": session_id})
+ _hook_event(hook_runtime, hooks, decode_context)
GlobalCounters.reset()
wall_start = time.perf_counter_ns()
tok, profile = _profiled(lambda: model(Tensor([[last_tok]], device=device), start_pos, temperature, 0, 0.0, 0.0, 0.0).item())
@@ -172,13 +212,13 @@ def encode_message(message) -> list[int]:
break
active_tokens.append(tok)
generated += 1
- send({"kind": "token", "text": tokenizer.decode([tok]), "metrics": {"index": index, "wall_ms": wall_ms,
- "gpu_ms": gpu_ms, "kernel_count": GlobalCounters.kernel_count, "global_mem_bytes": GlobalCounters.global_mem,
- "global_ops": GlobalCounters.global_ops, "profile_kernel_events": len(profile),
- "parameter_bandwidth_gbs": (param_bytes / max(GlobalCounters.time_sum_s, 1e-12)) / 1e9}})
- emitted, truncated = _emit_kernel_events(profile, stage="decode", token_index=index)
+ send({"kind": "token", "text": tokenizer.decode([tok]), "metrics": {"index": index, "stage": stage.value,
+ "wall_ms": wall_ms, "gpu_ms": gpu_ms, "kernel_count": GlobalCounters.kernel_count,
+ "global_mem_bytes": GlobalCounters.global_mem, "global_ops": GlobalCounters.global_ops,
+ "profile_kernel_events": len(profile), "parameter_bandwidth_gbs": (param_bytes / max(GlobalCounters.time_sum_s, 1e-12)) / 1e9}})
+ emitted, truncated = _emit_kernel_events(profile, stage=stage.value, token_index=index)
if truncated:
- send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": "decode", "token_index": index,
+ send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": stage.value, "token_index": index,
"captured": emitted, "available": len(profile)}})
else: send({"kind": "done", "finish_reason": "length", "metrics": {"generated_tokens": generated}})
except Exception as exc:
From 5089b6c7e42cbd9b9b8126b4bd8e956107d2588d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:30:09 +0530
Subject: [PATCH 087/168] radeon forge: test stage-specific hook selection and
rollback
---
test/test_radeon_forge_hooks.py | 86 +++++++++++++++++++++++++++++++++
1 file changed, 86 insertions(+)
create mode 100644 test/test_radeon_forge_hooks.py
diff --git a/test/test_radeon_forge_hooks.py b/test/test_radeon_forge_hooks.py
new file mode 100644
index 0000000000000..426cc452d91ba
--- /dev/null
+++ b/test/test_radeon_forge_hooks.py
@@ -0,0 +1,86 @@
+import hashlib
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.backends.stage_hooks import ModelStageHookRuntime
+from extra.radeon_forge.synthesis.hooks import (ExecutionContext, ExecutionStage, HookRegistry, RuntimeFingerprint,
+ StagePredicate)
+from extra.radeon_forge.synthesis.workspace import CandidateWorkspace, KernelSpec
+
+
+class FakeModel:
+ def __init__(self):
+ self.layers = [lambda value: value + 1, lambda value: value + 2]
+ self.forward_jit = None
+
+
+class TestStageAwareHooks(unittest.TestCase):
+ def test_predicate_distinguishes_execution_state_and_workload(self):
+ predicate = StagePredicate.from_mapping({"stages": ["decode"], "batch_sizes": [1], "min_context_tokens": 1024,
+ "min_generated_token_index": 1, "prefix_cache": "hit",
+ "conditions": {"resume_after_tool": True}})
+ matching = ExecutionContext(ExecutionStage.DECODE, context_tokens=2048, generated_token_index=4,
+ prefix_reused_tokens=512, warm=True, attributes={"resume_after_tool": True})
+ self.assertTrue(predicate.matches(matching))
+ self.assertFalse(predicate.matches(ExecutionContext(ExecutionStage.PREFILL, context_tokens=2048,
+ prefix_reused_tokens=512, attributes={"resume_after_tool": True})))
+ self.assertFalse(predicate.matches(ExecutionContext(ExecutionStage.DECODE, context_tokens=512,
+ generated_token_index=4, prefix_reused_tokens=256,
+ attributes={"resume_after_tool": True})))
+ self.assertFalse(predicate.matches(ExecutionContext(ExecutionStage.DECODE, context_tokens=2048,
+ generated_token_index=0, prefix_reused_tokens=256,
+ attributes={"resume_after_tool": True})))
+
+ def test_prefill_and_decode_implementations_can_coexist(self):
+ with tempfile.TemporaryDirectory() as directory:
+ workspace = CandidateWorkspace(directory)
+ common = {"layer": "transformer_block", "target": "llama.block", "adapter": "python_transformer_block",
+ "exclusive_group": "llama-block"}
+ prefill_spec = workspace.save_spec(KernelSpec("prefill-block", "prefill block", target="gfx1100",
+ invariants=("match reference",), metadata={"hook": {**common, "when": {"stages": ["prefill"]}}}))
+ decode_spec = workspace.save_spec(KernelSpec("decode-block", "decode block", target="gfx1100",
+ invariants=("match reference",), metadata={"hook": {**common, "when": {"stages": ["decode"],
+ "min_generated_token_index": 1}}}))
+ prefill = workspace.create_candidate(prefill_spec.spec_id, "def build_replacement(*args): return args[0]\n", "prefill")
+ decode = workspace.create_candidate(decode_spec.spec_id, "def build_replacement(*args): return args[0]\n", "decode")
+ workspace.update(prefill.candidate_id, "hardware_passed", {})
+ workspace.update(decode.candidate_id, "hardware_passed", {})
+ registry = HookRegistry(workspace)
+ fingerprint = RuntimeFingerprint(architecture="gfx1100", runtime="tinygrad", model_family="llama")
+ registry.activate(prefill.candidate_id, fingerprint, "validated prefill path")
+ registry.activate(decode.candidate_id, fingerprint, "validated decode path")
+ self.assertEqual(len(registry.active()), 2)
+ self.assertEqual(registry.resolve(ExecutionContext(ExecutionStage.PREFILL))[0].candidate_id, prefill.candidate_id)
+ self.assertEqual(registry.resolve(ExecutionContext(ExecutionStage.FIRST_TOKEN, generated_token_index=0)), [])
+ self.assertEqual(registry.resolve(ExecutionContext(ExecutionStage.DECODE, generated_token_index=2))[0].candidate_id,
+ decode.candidate_id)
+
+ def test_model_adapter_rolls_back_bad_stage_hook(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ good = root / "good.py"
+ good.write_text("def build_replacement(original, layer_index, model, context):\n return lambda value: original(value) * 10\n",
+ encoding="utf-8")
+ bad = root / "bad.py"
+ bad.write_text("VALUE = 1\n", encoding="utf-8")
+ descriptor = {"layer": "transformer_block", "target": "llama.block", "mode": "replace",
+ "adapter": "python_transformer_block", "selector": {"indices": [0]},
+ "when": {"stages": ["decode"]}, "priority": 0, "exclusive_group": "block", "description": ""}
+ def hook(path, activation):
+ return {"activation_id": activation, "candidate_id": activation, "spec_id": activation,
+ "source_path": str(path), "source_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
+ "descriptor": descriptor}
+
+ model = FakeModel()
+ runtime = ModelStageHookRuntime(model)
+ baseline = model.layers[0](2)
+ applied = runtime.apply([hook(good, "good")], ExecutionContext(ExecutionStage.DECODE, generated_token_index=2))
+ self.assertEqual(applied["active"], ["good"])
+ self.assertEqual(model.layers[0](2), baseline * 10)
+ rolled_back = runtime.apply([hook(bad, "bad")], ExecutionContext(ExecutionStage.DECODE, generated_token_index=2))
+ self.assertTrue(rolled_back["rolled_back"])
+ self.assertEqual(model.layers[0](2), baseline)
+
+
+if __name__ == "__main__": unittest.main()
From 7fb9ffdcea7c43e784f1bdeb8c8ad28ebed01851 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:30:31 +0530
Subject: [PATCH 088/168] ci: validate Radeon Forge branch
---
.github/workflows/radeon-forge.yml | 35 ++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 .github/workflows/radeon-forge.yml
diff --git a/.github/workflows/radeon-forge.yml b/.github/workflows/radeon-forge.yml
new file mode 100644
index 0000000000000..127778ae41ff9
--- /dev/null
+++ b/.github/workflows/radeon-forge.yml
@@ -0,0 +1,35 @@
+name: Radeon Forge
+
+on:
+ push:
+ branches: [radeon-forge]
+ paths:
+ - "extra/radeon_forge/**"
+ - "test/test_radeon_forge*.py"
+ - ".github/workflows/radeon-forge.yml"
+ pull_request:
+ paths:
+ - "extra/radeon_forge/**"
+ - "test/test_radeon_forge*.py"
+
+permissions:
+ contents: read
+
+jobs:
+ forge:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - name: Compile Radeon Forge
+ run: python -m compileall -q extra/radeon_forge test/test_radeon_forge*.py
+ - name: Run isolated Forge tests
+ run: >-
+ python -m unittest -v
+ test.test_radeon_forge
+ test.test_radeon_forge_recipe
+ test.test_radeon_forge_runtime
+ test.test_radeon_forge_hooks
From 2488ea147e24212ae231c4ce9d93d04ce74c3ac1 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:32:27 +0530
Subject: [PATCH 089/168] radeon forge: attribute bottlenecks by execution
stage
---
extra/radeon_forge/profiling/report.py | 92 ++++++++++++++++++--------
1 file changed, 64 insertions(+), 28 deletions(-)
diff --git a/extra/radeon_forge/profiling/report.py b/extra/radeon_forge/profiling/report.py
index 2a59474079ed6..b77d32a6e9e76 100644
--- a/extra/radeon_forge/profiling/report.py
+++ b/extra/radeon_forge/profiling/report.py
@@ -29,23 +29,30 @@ def _number(value: Any, default: float = 0.0) -> float:
except (TypeError, ValueError): return default
-def _kernel_summary(events: list[TraceEvent]) -> tuple[list[dict[str, Any]], float, int, int]:
- grouped: dict[str, list[float]] = defaultdict(list)
- decode_count, prefill_count = 0, 0
- for event in events:
- if event.name != "kernel": continue
- duration = _number(event.attributes.get("duration_ms"))
- if duration <= 0: continue
- name = str(event.attributes.get("name") or event.attributes.get("kernel_name") or "unknown_kernel")
- grouped[name].append(duration)
- stage = str(event.attributes.get("stage", "unknown"))
- if stage == "decode": decode_count += 1
- elif stage == "prefill": prefill_count += 1
+def _rows(grouped: dict[str, list[float]]) -> tuple[list[dict[str, Any]], float]:
total = sum(sum(values) for values in grouped.values())
rows = [{"name": name, "calls": len(values), "total_ms": sum(values), "mean_ms": statistics.mean(values),
"p95_ms": _percentile(values, 0.95), "share": sum(values) / max(total, 1e-12)} for name, values in grouped.items()]
rows.sort(key=lambda row: (-row["total_ms"], row["name"]))
- return rows, total, decode_count, prefill_count
+ return rows, total
+
+
+def _kernel_summary(events: list[TraceEvent]) -> tuple[list[dict[str, Any]], float, dict[str, int], dict[str, list[dict[str, Any]]]]:
+ grouped: dict[str, list[float]] = defaultdict(list)
+ by_stage: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
+ stage_counts: dict[str, int] = defaultdict(int)
+ for event in events:
+ if event.kind != "kernel": continue
+ duration = _number(event.attributes.get("duration_ms"), event.duration_ms or 0.0)
+ if duration <= 0: continue
+ name = str(event.name or event.attributes.get("name") or event.attributes.get("kernel_name") or "unknown_kernel")
+ stage = str(event.attributes.get("stage", "unknown"))
+ grouped[name].append(duration)
+ by_stage[stage][name].append(duration)
+ stage_counts[stage] += 1
+ rows, total = _rows(grouped)
+ stage_rows = {stage: _rows(values)[0] for stage, values in by_stage.items()}
+ return rows, total, dict(stage_counts), stage_rows
def build_profile_report(events: Iterable[TraceEvent]) -> dict[str, Any]:
@@ -55,6 +62,10 @@ def build_profile_report(events: Iterable[TraceEvent]) -> dict[str, Any]:
token_wall = [_number(x.attributes.get("wall_ms")) for x in token_events if _number(x.attributes.get("wall_ms")) > 0]
token_gpu = [_number(x.attributes.get("gpu_ms")) for x in token_events if _number(x.attributes.get("gpu_ms")) > 0]
kernels_per_token = [int(_number(x.attributes.get("kernel_count"))) for x in token_events]
+ token_wall_by_stage: dict[str, list[float]] = defaultdict(list)
+ for event in token_events:
+ wall = _number(event.attributes.get("wall_ms"))
+ if wall > 0: token_wall_by_stage[str(event.attributes.get("stage", "decode"))].append(wall)
expected_decode_profile = sum(int(_number(x.attributes.get("profile_kernel_events"))) for x in token_events)
prefill = [x for x in evs if x.name == "prefill"]
prefill_wall = sum(_number(x.attributes.get("wall_ms")) for x in prefill)
@@ -62,46 +73,67 @@ def build_profile_report(events: Iterable[TraceEvent]) -> dict[str, Any]:
tools = [x for x in evs if x.kind == "tool" and x.duration_ms is not None and x.name != "tool_result"]
metric_events = [x for x in evs if x.name == "metric"]
truncated = [x for x in metric_events if x.attributes.get("name") == "profile_truncated"]
- top_kernels, profiled_kernel_ms, decode_profile_count, prefill_profile_count = _kernel_summary(evs)
+ hook_events = [x for x in evs if x.name == "hook"]
+ hook_rollbacks = [x for x in hook_events if x.attributes.get("rolled_back")]
+ top_kernels, profiled_kernel_ms, stage_kernel_counts, top_kernels_by_stage = _kernel_summary(evs)
+ captured_profile = sum(stage_kernel_counts.values())
findings: list[Finding] = []
if kernels_per_token and statistics.mean(kernels_per_token) >= 20:
findings.append(Finding("high", "observed", "High kernel-launch count per decoded token",
- (f"mean launches/token={statistics.mean(kernels_per_token):.1f}", f"profiled decode ranges={decode_profile_count}"),
- "Inspect the dominant launch sequence and test a fused subgraph or persistent megakernel; do not assume arithmetic is the bottleneck."))
+ (f"mean launches/token={statistics.mean(kernels_per_token):.1f}", f"profiled token-stage ranges={sum(v for k,v in stage_kernel_counts.items() if k != 'prefill')}"),
+ "Inspect the dominant launch sequence separately for first-token and steady decode, then test a fused subgraph or persistent megakernel."))
if token_wall and token_gpu and sum(token_gpu) / max(sum(token_wall), 1e-9) < 0.65:
findings.append(Finding("high", "inferred", "GPU execution explains only part of decode wall time",
(f"GPU/wall ratio={sum(token_gpu)/sum(token_wall):.2f}",),
"Profile CPU submission, synchronization, sampling and launch bubbles before optimizing arithmetic throughput."))
if prefill and prefill_wall > sum(token_wall):
findings.append(Finding("medium", "observed", "Prefill dominates this agent turn",
- (f"prefill_ms={prefill_wall:.2f}", f"decode_ms={sum(token_wall):.2f}"),
- "Increase stable-prefix reuse and compact repeated tool schemas or repository context before generating lower-level kernels."))
+ (f"prefill_ms={prefill_wall:.2f}", f"token_generation_ms={sum(token_wall):.2f}"),
+ "Use a prefill-specific recipe: increase stable-prefix reuse, compact repeated tool schemas, or tune prefill kernels independently of decode."))
if tools and sum(x.duration_ms or 0 for x in tools) > sum(token_wall):
findings.append(Finding("medium", "observed", "Tool execution dominates model decode",
(f"tool_ms={sum(x.duration_ms or 0 for x in tools):.2f}",),
- "Parallelize independent tools or reduce tool round trips; a faster inference kernel alone will not materially improve task latency."))
+ "Use an agent-loop or tool-execution-stage optimization; a faster model kernel alone will not materially improve task latency."))
+
+ first_token = token_wall_by_stage.get("first_token", [])
+ steady_decode = token_wall_by_stage.get("decode", [])
+ if first_token and steady_decode and statistics.median(first_token) > statistics.median(steady_decode) * 1.4:
+ findings.append(Finding("medium", "observed", "First-token and steady-decode latency are materially different",
+ (f"first_token_p50={statistics.median(first_token):.2f}ms", f"steady_decode_p50={statistics.median(steady_decode):.2f}ms"),
+ "Do not force one kernel schedule across both states. Keep separate first-token and steady-decode hook predicates and validate each independently."))
+
+ stage_dominants = {stage: rows[0] for stage, rows in top_kernels_by_stage.items() if rows}
+ distinct_dominants = {row["name"] for row in stage_dominants.values()}
+ if len(distinct_dominants) > 1:
+ findings.append(Finding("high", "observed", "Different execution stages have different dominant kernels",
+ tuple(f"{stage}: {row['name']} ({row['share']*100:.1f}% of captured {stage} GPU time)" for stage, row in sorted(stage_dominants.items())),
+ "Create separate stage-scoped optimization recipes rather than a single global replacement. Preserve a shared oracle but tune each state independently."))
if top_kernels:
dominant = top_kernels[0]
if dominant["share"] >= 0.25:
- findings.append(Finding("high", "observed", "One kernel family dominates captured GPU time",
+ findings.append(Finding("high", "observed", "One kernel family dominates captured GPU time overall",
(f"kernel={dominant['name']}", f"share={dominant['share']*100:.1f}%", f"calls={dominant['calls']}",
f"total_ms={dominant['total_ms']:.2f}"),
- "Map this kernel back to the model subgraph, inspect its shapes and resource metadata, then generate a bounded structural alternative and retune it."))
+ "Map this kernel to both its model subgraph and execution stage, then generate a bounded structural alternative and retune it."))
tiny = [row for row in top_kernels if row["mean_ms"] < 0.05]
tiny_calls = sum(row["calls"] for row in tiny)
- if decode_profile_count and tiny_calls / max(decode_profile_count + prefill_profile_count, 1) >= 0.35:
+ if captured_profile and tiny_calls / max(captured_profile, 1) >= 0.35:
findings.append(Finding("medium", "inferred", "Captured execution is fragmented across many very small kernels",
- (f"sub-50us calls={tiny_calls}", f"captured kernel calls={decode_profile_count+prefill_profile_count}"),
- "Inspect adjacency and data materialization boundaries. Fusion is promising only where the independent numerical oracle covers the combined subgraph."))
+ (f"sub-50us calls={tiny_calls}", f"captured kernel calls={captured_profile}"),
+ "Inspect adjacency and materialization boundaries within the same execution stage. Fusion is promising only where the numerical oracle covers the combined subgraph."))
else:
findings.append(Finding("info", "unknown", "No kernel-level trace is attached",
("Only agent/model aggregate counters are available.",),
"Enable the tinygrad PROFILE event adapter or capture ROCm/SQTT evidence before making a causal hardware diagnosis."))
+ if hook_rollbacks:
+ findings.append(Finding("high", "observed", "An execution-stage optimization was rolled back",
+ tuple(f"stage={x.attributes.get('stage')} error={x.attributes.get('error')}" for x in hook_rollbacks[-4:]),
+ "Keep the trusted baseline active, mark the candidate failed for this execution state, and regenerate from the preserved intent and oracle."))
+
expected_profile = expected_decode_profile + expected_prefill_profile
- captured_profile = decode_profile_count + prefill_profile_count
if truncated:
findings.append(Finding("medium", "observed", "Kernel trace was truncated",
tuple(f"{x.attributes.get('stage')} captured={x.attributes.get('captured')} available={x.attributes.get('available')}" for x in truncated[:4]),
@@ -111,17 +143,21 @@ def build_profile_report(events: Iterable[TraceEvent]) -> dict[str, Any]:
(f"backend reported={expected_profile}", f"trace captured={captured_profile}"),
"Treat per-kernel attribution as partial until the transport discrepancy is resolved."))
+ stage_latency = {stage: {"count": len(values), "p50_ms": statistics.median(values) if values else None,
+ "p95_ms": _percentile(values, 0.95)} for stage, values in token_wall_by_stage.items()}
return {
"summary": {
"event_count": len(evs), "durations_ms_by_kind": durations, "decode_tokens": len(token_events),
"token_wall_ms_p50": statistics.median(token_wall) if token_wall else None,
"token_wall_ms_p95": _percentile(token_wall, 0.95),
"token_gpu_ms_p50": statistics.median(token_gpu) if token_gpu else None,
+ "token_latency_by_stage": stage_latency,
"mean_kernel_count_per_token": statistics.mean(kernels_per_token) if kernels_per_token else None,
"tool_time_ms": sum(x.duration_ms or 0 for x in tools), "prefill_wall_ms": prefill_wall,
- "profiled_kernel_time_ms": profiled_kernel_ms, "profiled_decode_kernel_calls": decode_profile_count,
- "profiled_prefill_kernel_calls": prefill_profile_count, "kernel_profile_complete": bool(captured_profile and not truncated and captured_profile >= expected_profile),
- "top_kernels": top_kernels[:20],
+ "profiled_kernel_time_ms": profiled_kernel_ms, "profiled_kernel_calls_by_stage": stage_kernel_counts,
+ "kernel_profile_complete": bool(captured_profile and not truncated and captured_profile >= expected_profile),
+ "top_kernels": top_kernels[:20], "top_kernels_by_stage": {key: value[:10] for key, value in top_kernels_by_stage.items()},
+ "hook_transitions": len(hook_events), "hook_rollbacks": len(hook_rollbacks),
},
"findings": [asdict(x) for x in findings],
}
From f17ef42d34372c4fef58730e90ba4922d9eb95f4 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:33:06 +0530
Subject: [PATCH 090/168] radeon forge: unify direct UI actions with scoped
permissions
---
extra/radeon_forge/runtime/engine.py | 17 ++++++++++++-----
1 file changed, 12 insertions(+), 5 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index 41281fb994d98..928fea6d9b1b5 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-import threading
+import threading, uuid
from dataclasses import asdict
from pathlib import Path
from typing import Any, Mapping
@@ -10,7 +10,7 @@
from ..synthesis import CandidateWorkspace, HookRegistry, OptimizationTools, RuntimeFingerprint, install_default_specs
from .backend import InferenceBackend
from .session import AgentSession
-from .tools import ToolRegistry, WorkspaceTools
+from .tools import ToolCall, ToolRegistry, WorkspaceTools
DEFAULT_SYSTEM_PROMPT = """You are Radeon Forge, a private local software and inference performance engineer.
@@ -39,9 +39,6 @@ def runtime_fingerprint(self) -> RuntimeFingerprint:
return RuntimeFingerprint.from_mapping(metadata if isinstance(metadata, Mapping) else {})
def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, Any]:
- # Send every validated active hook to the isolated backend. The backend
- # resolves execution-state predicates at prefill/first-token/decode/tool
- # resume boundaries using live context that the outer agent cannot fake.
return {**self.hooks.runtime_metadata(), "runtime_fingerprint": asdict(self.runtime_fingerprint())}
def create_session(self) -> AgentSession:
@@ -63,6 +60,16 @@ def grant_for_pending_tool(self, session_id: str, reason: str, max_uses: int = 1
action = self.tools.spec(session.pending_tool_call.name).action
return self.permissions.issue([action], reason, max_uses=max_uses).token
+ def execute_explicit_ui_tool(self, name: str, arguments: Mapping[str, Any], reason: str) -> Any:
+ """Execute one direct UI mutation through the same scoped permission boundary as the agent."""
+ spec = self.tools.spec(name)
+ grant = self.permissions.issue([spec.action], reason.strip() or f"Explicit local UI action: {name}", max_uses=1)
+ result = self.tools.execute(ToolCall(uuid.uuid4().hex, name, dict(arguments)), grant.token)
+ if not result.ok:
+ if isinstance(result.output, Mapping) and result.output.get("error"): raise RuntimeError(str(result.output["error"]))
+ raise RuntimeError(f"{name} failed")
+ return result.output
+
def profile(self, session_id: str) -> dict[str, Any]: return build_profile_report(self.session(session_id).trace.events())
def optimization_state(self) -> dict[str, Any]:
From c7b1d745da38d181772451a83b1f09181211184d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:33:45 +0530
Subject: [PATCH 091/168] radeon forge: expose permissioned hook activation and
rollback UI API
---
extra/radeon_forge/ui/server.py | 21 +++++++++++++++++----
1 file changed, 17 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/ui/server.py b/extra/radeon_forge/ui/server.py
index c9513009a1113..3e16329a0d6c7 100644
--- a/extra/radeon_forge/ui/server.py
+++ b/extra/radeon_forge/ui/server.py
@@ -53,7 +53,7 @@ def do_GET(self):
if path == "/": return self._static("index.html")
if path in {"/app.js", "/style.css", "/kernels.css"}: return self._static(path[1:])
if path == "/api/health": return self._json({"ok": True, "backend": self.engine.backend.name,
- "capabilities": asdict(self.engine.backend.capabilities)})
+ "capabilities": asdict(self.engine.backend.capabilities), "runtime_fingerprint": asdict(self.engine.runtime_fingerprint())})
if path == "/api/sessions": return self._json(self.engine.sessions())
if path == "/api/optimization": return self._json(self.engine.optimization_state())
session, tail = self._session_route()
@@ -72,12 +72,25 @@ def do_POST(self):
body = self._body()
if path == "/api/sessions": return self._json(self.engine.create_session().snapshot(), HTTPStatus.CREATED)
if path == "/api/recipes/import":
- result = self.engine.optimization_tools.import_recipe({"path": str(body.get("path", ""))})
+ result = self.engine.execute_explicit_ui_tool("import_forge_recipe", {"path": str(body.get("path", ""))},
+ str(body.get("reason", "Import portable optimization recipe from local UI")))
return self._json(result, HTTPStatus.CREATED)
if path == "/api/recipes/export":
- result = self.engine.optimization_tools.export_recipe_file({"spec_id": str(body.get("spec_id", "")),
- "candidate_id": body.get("candidate_id"), "output": str(body.get("output", ""))})
+ result = self.engine.execute_explicit_ui_tool("export_forge_recipe", {"spec_id": str(body.get("spec_id", "")),
+ "candidate_id": body.get("candidate_id"), "output": str(body.get("output", ""))},
+ str(body.get("reason", "Export portable execution-stage optimization recipe")))
return self._json(result, HTTPStatus.CREATED)
+ if path == "/api/hooks/activate":
+ result = self.engine.execute_explicit_ui_tool("activate_optimization_hook", {
+ "candidate_id": str(body.get("candidate_id", "")), "reason": str(body.get("reason", "Deploy validated stage-specific optimization")),
+ "allow_unknown_runtime": bool(body.get("allow_unknown_runtime", False))},
+ str(body.get("reason", "Deploy validated stage-specific optimization")))
+ return self._json(result, HTTPStatus.CREATED)
+ if path == "/api/hooks/deactivate":
+ result = self.engine.execute_explicit_ui_tool("deactivate_optimization_hook", {
+ "activation_id": str(body.get("activation_id", "")), "reason": str(body.get("reason", "Rollback local optimization hook"))},
+ str(body.get("reason", "Rollback local optimization hook")))
+ return self._json(result)
session, tail = self._session_route()
if session is None: return self.send_error(404)
if tail == "messages":
From 82895d1dbb1deab41fe2d003984af9553e582ef3 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:34:25 +0530
Subject: [PATCH 092/168] radeon forge: visualize execution-stage optimization
hooks
---
extra/radeon_forge/ui/static/index.html | 29 +++++++++++++++----------
1 file changed, 18 insertions(+), 11 deletions(-)
diff --git a/extra/radeon_forge/ui/static/index.html b/extra/radeon_forge/ui/static/index.html
index fc5d8f6de0ea6..c81ef3102a988 100644
--- a/extra/radeon_forge/ui/static/index.html
+++ b/extra/radeon_forge/ui/static/index.html
@@ -24,46 +24,50 @@
Console
Profiler
Timeline
-
Kernels
+
Optimizations
-
Typed kernel contracts Intent and invariants are durable; generated implementations are disposable.
Refresh
-
Candidate pipeline Staged → MockGPU → W7900 → accepted / rejected
-
Portable optimization recipes Share intent, invariants, oracle, knowledge, and an optional disposable implementation cache in one file.
+
Active execution hooks Where the optimization intercepts × when it is allowed to run.
Refresh
+
Typed optimization contracts Intent and invariants are durable; generated implementations are disposable.
+
Candidate pipeline Staged → MockGPU → W7900 → held-out → active / rejected
+
Portable optimization recipes Share placement, execution-state predicate, intent, oracle, knowledge, and an optional implementation cache in one file.
Import recipe
@@ -75,11 +79,14 @@
Runtime Offline
+
Runtime fingerprint
+
Arch — Model — Dtype —
+
Current session
State — Trace — Events 0
Optimization flow
-
Observe Attribute Hypothesize Generate MockGPU gate W7900 benchmark Deploy / revert
+
Observe by execution state Attribute Hypothesize Generate MockGPU gate W7900 + held-out Activate scoped hook Rollback on failure
From e5c88921968fc26dcd2f34e94708b8116dfb5f56 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:35:28 +0530
Subject: [PATCH 093/168] radeon forge: render and control execution-stage
hooks
---
extra/radeon_forge/ui/static/app.js | 19 ++++++++++++-------
1 file changed, 12 insertions(+), 7 deletions(-)
diff --git a/extra/radeon_forge/ui/static/app.js b/extra/radeon_forge/ui/static/app.js
index 3ddf28cf123a5..43cf4639c22bc 100644
--- a/extra/radeon_forge/ui/static/app.js
+++ b/extra/radeon_forge/ui/static/app.js
@@ -1,11 +1,12 @@
const state={session:null,sessions:[],health:null,optimization:null,tab:'console'};
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
-const toast=msg=>{const el=$('#toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),2600)};
+const toast=msg=>{const el=$('#toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),3000)};
async function api(path,opts={}){const res=await fetch(path,{headers:{'Content-Type':'application/json'},...opts});const data=await res.json();if(!res.ok)throw new Error(data.error||`HTTP ${res.status}`);return data}
function fmtMs(v){return v==null?'—':`${Number(v).toFixed(v<10?2:1)} ms`}
function esc(v){return String(v??'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))}
+function hookWhen(h){const w=h?.when||{};const stages=(w.stages||['any']).map(String).join(', ');const detail=[];if(w.min_context_tokens!=null)detail.push(`ctx≥${w.min_context_tokens}`);if(w.max_context_tokens!=null)detail.push(`ctx≤${w.max_context_tokens}`);if(w.min_generated_token_index!=null)detail.push(`token≥${w.min_generated_token_index}`);if(w.max_generated_token_index!=null)detail.push(`token≤${w.max_generated_token_index}`);if(w.batch_sizes?.length)detail.push(`batch=${w.batch_sizes.join('/')}`);if(w.prefix_cache&&w.prefix_cache!=='any')detail.push(`cache=${w.prefix_cache}`);if(w.warm!=null)detail.push(w.warm?'warm':'cold');Object.entries(w.conditions||{}).forEach(([k,v])=>detail.push(`${k}=${v}`));return {stages,detail:detail.join(' · ')}}
async function boot(){try{state.health=await api('/api/health');renderHealth();await refreshSessions();if(!state.sessions.length)await createSession();else await selectSession(state.sessions[0].session_id)}catch(e){toast(e.message)}}
-function renderHealth(){const h=state.health;$('#runtime-name').textContent=h?.backend||'Offline';$('#backend-status').textContent=h?`${h.backend} · local loopback runtime`:'Backend unavailable';const caps=$('#capabilities');caps.innerHTML='';Object.entries(h?.capabilities||{}).forEach(([k,v])=>{const el=document.createElement('span');el.className=`cap ${v?'on':''}`;el.textContent=k.replaceAll('_',' ');caps.append(el)})}
+function renderHealth(){const h=state.health;$('#runtime-name').textContent=h?.backend||'Offline';const fp=h?.runtime_fingerprint||{};$('#backend-status').textContent=h?`${h.backend} · ${fp.architecture||'unbound architecture'} · local loopback runtime`:'Backend unavailable';$('#runtime-arch').textContent=fp.architecture||'unbound';$('#runtime-model').textContent=fp.model_family||'—';$('#runtime-dtype').textContent=fp.dtype||'—';const caps=$('#capabilities');caps.innerHTML='';Object.entries(h?.capabilities||{}).forEach(([k,v])=>{const el=document.createElement('span');el.className=`cap ${v?'on':''}`;el.textContent=k.replaceAll('_',' ');caps.append(el)})}
async function refreshSessions(){state.sessions=await api('/api/sessions');renderSessionList()}
function renderSessionList(){const list=$('#session-list');list.innerHTML='';state.sessions.forEach((s,i)=>{const el=document.createElement('div');el.className=`session-item ${state.session?.session_id===s.session_id?'active':''}`;el.innerHTML=`
${i===0?'Primary':'Session'} ${s.session_id.slice(0,6)} ${esc(s.state)} `;el.onclick=()=>selectSession(s.session_id);list.append(el)})}
async function createSession(){const s=await api('/api/sessions',{method:'POST',body:'{}'});await refreshSessions();await selectSession(s.session_id)}
@@ -16,11 +17,15 @@ function renderApproval(){const card=$('#approval-card'),call=state.session?.pen
async function sendMessage(text){if(!state.session)return;$('#send').disabled=true;$('#send').textContent='Running…';try{const out=await api(`/api/sessions/${state.session.session_id}/messages`,{method:'POST',body:JSON.stringify({content:text,max_tokens:512})});state.session=out.session;renderSession();await refreshSessions()}finally{$('#send').disabled=false;$('#send').textContent='Run'}}
async function approveTool(){const out=await api(`/api/sessions/${state.session.session_id}/tools/approve`,{method:'POST',body:JSON.stringify({reason:'Approved once from the local UI',max_tokens:512})});state.session=out.session;renderSession();await refreshSessions();if(state.tab==='kernels')await refreshKernels();toast('Tool executed locally')}
async function rejectTool(){const out=await api(`/api/sessions/${state.session.session_id}/tools/reject`,{method:'POST',body:JSON.stringify({reason:'Rejected in UI'})});state.session=out.session;renderSession();toast('Tool rejected')}
-async function refreshProfile(){if(!state.session)return;const p=await api(`/api/sessions/${state.session.session_id}/profile`),s=p.summary||{};$('#p50-token').textContent=fmtMs(s.token_wall_ms_p50);$('#p95-token').textContent=fmtMs(s.token_wall_ms_p95);$('#launches-token').textContent=s.mean_kernel_count_per_token==null?'—':Number(s.mean_kernel_count_per_token).toFixed(1);$('#tool-time').textContent=fmtMs(s.tool_time_ms);const findings=$('#findings');findings.innerHTML='';(p.findings||[]).forEach(f=>{const el=document.createElement('div');el.className=`finding ${f.severity}`;el.innerHTML=`
${esc(f.status)} ${esc(f.title)}
${esc((f.evidence||[]).join(' · '))}
Next: ${esc(f.recommendation)}
`;findings.append(el)});if(!p.findings?.length)findings.innerHTML='
No diagnosis yet. Run an agent turn first.
';renderAttribution(s.durations_ms_by_kind||{})}
+async function refreshProfile(){if(!state.session)return;const p=await api(`/api/sessions/${state.session.session_id}/profile`),s=p.summary||{},stages=s.token_latency_by_stage||{};$('#p50-token').textContent=fmtMs(s.token_wall_ms_p50);$('#p95-token').textContent=fmtMs(s.token_wall_ms_p95);$('#first-token').textContent=fmtMs(stages.first_token?.p50_ms);$('#steady-decode').textContent=fmtMs(stages.decode?.p50_ms);$('#launches-token').textContent=s.mean_kernel_count_per_token==null?'—':Number(s.mean_kernel_count_per_token).toFixed(1);$('#hook-transitions').textContent=`${s.hook_transitions||0}${s.hook_rollbacks?` / ${s.hook_rollbacks} rollback`:''}`;const findings=$('#findings');findings.innerHTML='';(p.findings||[]).forEach(f=>{const el=document.createElement('div');el.className=`finding ${f.severity}`;el.innerHTML=`
${esc(f.status)} ${esc(f.title)}
${esc((f.evidence||[]).join(' · '))}
Next: ${esc(f.recommendation)}
`;findings.append(el)});if(!p.findings?.length)findings.innerHTML='
No diagnosis yet. Run an agent turn first.
';renderAttribution(s.durations_ms_by_kind||{});renderStageKernels(s.top_kernels_by_stage||{})}
function renderAttribution(d){const box=$('#attribution');box.innerHTML='';const entries=Object.entries(d).sort((a,b)=>b[1]-a[1]),max=Math.max(1,...entries.map(x=>x[1]));entries.forEach(([k,v])=>{const el=document.createElement('div');el.className='bar-row';el.innerHTML=`
${esc(k)} ${fmtMs(v)}
`;box.append(el)});if(!entries.length)box.textContent='No trace data yet.'}
-async function refreshTrace(){if(!state.session)return;const t=await api(`/api/sessions/${state.session.session_id}/trace`),box=$('#timeline');box.innerHTML='';(t.events||[]).forEach(e=>{const el=document.createElement('div');el.className='trace-row';const attrs=Object.entries(e.attributes||{}).slice(0,4).map(([k,v])=>`${k}=${v}`).join(' · ');el.innerHTML=`
${esc(e.kind)} ${esc(e.name)} ${esc(attrs)} ${fmtMs(e.duration_ms)} `;box.append(el)});if(!t.events?.length)box.innerHTML='
'}
-async function exportCandidate(candidate){const output=`exports/${candidate.candidate_id}.forge.toml`;const out=await api('/api/recipes/export',{method:'POST',body:JSON.stringify({spec_id:candidate.spec_id,candidate_id:candidate.candidate_id,output})});toast(`Exported ${out.path}`);await refreshKernels()}
-async function importRecipe(){const input=$('#recipe-path'),path=input.value.trim();if(!path)return;const out=await api('/api/recipes/import',{method:'POST',body:JSON.stringify({path})});input.value='';toast(`Installed ${out.recipe_id}`);await refreshKernels()}
-async function refreshKernels(){state.optimization=await api('/api/optimization');const specs=$('#kernel-specs'),candidates=$('#kernel-candidates'),recipes=$('#recipe-list');specs.innerHTML='';candidates.innerHTML='';recipes.innerHTML='';(state.optimization.specs||[]).forEach(s=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(s.name)} ${esc(s.operation)}
${esc(s.target)} ${esc(s.language)} ${esc(s.objective)}
${esc(JSON.stringify({shapes:s.shapes,dtypes:s.dtypes,invariants:s.invariants,agent_brief:s.metadata?.recipe_agent_brief},null,2))}
`;specs.append(el)});(state.optimization.candidates||[]).forEach(c=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(c.candidate_id)} ${esc(c.hypothesis||'No hypothesis recorded')}
${esc(c.status)} ${esc(c.spec_id)}
${esc(JSON.stringify(c.evidence||{},null,2))}
Export one-file recipe
`;el.querySelector('.export-candidate').onclick=()=>exportCandidate(c).catch(e=>toast(e.message));candidates.append(el)});(state.optimization.recipes||[]).forEach(r=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(r.recipe_id)} Installed portable contract. Cached code remains unverified until local oracles pass.
${esc(r.spec_id)} ${r.seed_candidate_id?'seed cache ':''}
${esc(JSON.stringify({bundle:r.bundle_root,artifacts:r.artifact_hashes},null,2))}
`;recipes.append(el)});if(!state.optimization.candidates?.length)candidates.innerHTML='
No candidate has been staged. Ask Forge to list kernel specs and generate one.
';if(!state.optimization.recipes?.length)recipes.innerHTML='
No portable recipe installed yet. Import a .forge.toml file from the workspace.
'}
+function renderStageKernels(byStage){const box=$('#stage-kernels');box.innerHTML='';Object.entries(byStage).sort().forEach(([stage,rows])=>{const top=rows?.[0];if(!top)return;const el=document.createElement('div');el.className='kernel-card compact-card';el.innerHTML=`
${esc(stage)} ${esc(top.name)}
${top.calls} calls · ${fmtMs(top.total_ms)} · ${(100*top.share).toFixed(1)}% of captured stage time
`;box.append(el)});if(!box.children.length)box.innerHTML='
No stage-level kernel evidence yet.
'}
+async function refreshTrace(){if(!state.session)return;const t=await api(`/api/sessions/${state.session.session_id}/trace`),box=$('#timeline');box.innerHTML='';(t.events||[]).forEach(e=>{const el=document.createElement('div');el.className=`trace-row ${e.name==='hook'?'hook-row':''}`;const attrs=Object.entries(e.attributes||{}).slice(0,5).map(([k,v])=>`${k}=${Array.isArray(v)?v.join(','):v}`).join(' · ');el.innerHTML=`
${esc(e.kind)} ${esc(e.name)} ${esc(attrs)} ${fmtMs(e.duration_ms)} `;box.append(el)});if(!t.events?.length)box.innerHTML='
'}
+async function exportCandidate(candidate){const output=`exports/${candidate.candidate_id}.forge.toml`;const out=await api('/api/recipes/export',{method:'POST',body:JSON.stringify({spec_id:candidate.spec_id,candidate_id:candidate.candidate_id,output,reason:'Export shareable stage-aware optimization recipe'})});toast(`Exported ${out.path}`);await refreshKernels()}
+async function importRecipe(){const input=$('#recipe-path'),path=input.value.trim();if(!path)return;const out=await api('/api/recipes/import',{method:'POST',body:JSON.stringify({path,reason:'Import local portable optimization recipe'})});input.value='';toast(`Installed ${out.recipe_id}`);await refreshKernels()}
+async function activateCandidate(candidate){const reason=`Activate ${candidate.candidate_id} only in its validated execution states`;const out=await api('/api/hooks/activate',{method:'POST',body:JSON.stringify({candidate_id:candidate.candidate_id,reason})});toast(`Activated ${out.activation_id.slice(0,8)}`);await refreshKernels()}
+async function rollbackHook(hook){const out=await api('/api/hooks/deactivate',{method:'POST',body:JSON.stringify({activation_id:hook.activation_id,reason:`Rollback ${hook.candidate_id} from local UI`})});toast(`Rolled back ${out.candidate_id}`);await refreshKernels()}
+function renderActiveHooks(hooks){const box=$('#active-hooks');box.innerHTML='';(hooks||[]).forEach(h=>{const w=hookWhen(h.descriptor),el=document.createElement('div');el.className='kernel-card active-hook';el.innerHTML=`
active ${esc(h.descriptor.layer)} · ${esc(h.descriptor.target)}
${esc(h.candidate_id)}
${esc(w.stages)} ${esc(h.descriptor.mode)} priority ${h.descriptor.priority||0}
${w.detail?`
${esc(w.detail)}
`:''}
${esc(JSON.stringify({selector:h.descriptor.selector,compatibility:h.compatibility},null,2))}
Rollback
`;el.querySelector('.rollback-hook').onclick=()=>rollbackHook(h).catch(e=>toast(e.message));box.append(el)});if(!box.children.length)box.innerHTML='
No optimization is active. The trusted tinygrad baseline owns every execution stage.
'}
+async function refreshKernels(){state.optimization=await api('/api/optimization');const specs=$('#kernel-specs'),candidates=$('#kernel-candidates'),recipes=$('#recipe-list');specs.innerHTML='';candidates.innerHTML='';recipes.innerHTML='';renderActiveHooks(state.optimization.active_hooks||[]);const activeIds=new Set((state.optimization.active_hooks||[]).map(x=>x.candidate_id));(state.optimization.specs||[]).forEach(s=>{const h=s.metadata?.hook||{},w=hookWhen(h),el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(s.name)} ${esc(s.operation)}
${esc(s.target)} ${esc(h.layer||'kernel')} ${esc(w.stages)} ${esc(s.objective)}
${w.detail?`
${esc(w.detail)}
`:''}
${esc(JSON.stringify({where:{layer:h.layer,target:h.target,mode:h.mode,selector:h.selector},when:h.when,shapes:s.shapes,dtypes:s.dtypes,invariants:s.invariants,agent_brief:s.metadata?.recipe_agent_brief},null,2))}
`;specs.append(el)});(state.optimization.candidates||[]).forEach(c=>{const spec=(state.optimization.specs||[]).find(s=>s.spec_id===c.spec_id),h=spec?.metadata?.hook||{},w=hookWhen(h),eligible=['hardware_passed','heldout_passed','accepted'].includes(c.status),el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(c.candidate_id)} ${esc(c.hypothesis||'No hypothesis recorded')}
${esc(c.status)} ${esc(h.layer||'kernel')} ${esc(w.stages)}
${esc(JSON.stringify(c.evidence||{},null,2))}
Export recipe ${eligible&&!activeIds.has(c.candidate_id)?'Activate scoped hook ':''}${activeIds.has(c.candidate_id)?'currently active ':''}
`;el.querySelector('.export-candidate').onclick=()=>exportCandidate(c).catch(e=>toast(e.message));const activate=el.querySelector('.activate-candidate');if(activate)activate.onclick=()=>activateCandidate(c).catch(e=>toast(e.message));candidates.append(el)});(state.optimization.recipes||[]).forEach(r=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(r.recipe_id)} Installed portable contract. Placement and execution-state predicates are preserved; cached code remains unverified until local oracles pass.
${esc(r.spec_id)} ${r.seed_candidate_id?'seed cache ':''}
${esc(JSON.stringify({bundle:r.bundle_root,artifacts:r.artifact_hashes},null,2))}
`;recipes.append(el)});if(!state.optimization.candidates?.length)candidates.innerHTML='
No candidate has been staged. Ask Forge to list contracts and generate one for a specific execution state.
';if(!state.optimization.recipes?.length)recipes.innerHTML='
No portable recipe installed yet. Import a .forge.toml file from the workspace.
'}
function switchTab(tab){state.tab=tab;$$('.tab').forEach(x=>x.classList.remove('active'));$(`#${tab}-tab`).classList.add('active');$$('[data-tab]').forEach(x=>x.classList.toggle('active',x.dataset.tab===tab));if(tab==='profile')refreshProfile();if(tab==='trace')refreshTrace();if(tab==='kernels')refreshKernels()}
$('#new-session').onclick=createSession;$('#composer').onsubmit=async e=>{e.preventDefault();const input=$('#prompt'),text=input.value.trim();if(!text)return;input.value='';try{await sendMessage(text)}catch(err){toast(err.message)}};$('#approve-tool').onclick=()=>approveTool().catch(e=>toast(e.message));$('#reject-tool').onclick=()=>rejectTool().catch(e=>toast(e.message));$('#refresh-profile').onclick=()=>refreshProfile().catch(e=>toast(e.message));$('#refresh-trace').onclick=()=>refreshTrace().catch(e=>toast(e.message));$('#refresh-kernels').onclick=()=>refreshKernels().catch(e=>toast(e.message));$('#import-recipe').onclick=()=>importRecipe().catch(e=>toast(e.message));$$('[data-tab]').forEach(x=>x.onclick=()=>switchTab(x.dataset.tab));boot();
From 3f177c459cb410c7fe77bfa9fd7cf0717b304ba1 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:35:52 +0530
Subject: [PATCH 094/168] radeon forge: style stage-aware optimization controls
---
extra/radeon_forge/ui/static/kernels.css | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/extra/radeon_forge/ui/static/kernels.css b/extra/radeon_forge/ui/static/kernels.css
index 1b65cbfb42930..ab5f7cb4a8090 100644
--- a/extra/radeon_forge/ui/static/kernels.css
+++ b/extra/radeon_forge/ui/static/kernels.css
@@ -1 +1 @@
-.kernel-layout{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:22px 24px 24px;width:100%;min-height:0;overflow:auto}.kernel-list{padding:12px;overflow:auto}.kernel-card{background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:10px}.kernel-card h4{margin:0 0 6px;font-size:14px}.kernel-card p{color:var(--muted);font-size:11px;line-height:1.5}.kernel-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.status{padding:4px 7px;border-radius:7px;background:#262d3a;border:1px solid var(--line);font-size:9px;text-transform:uppercase;letter-spacing:.07em}.status.mockgpu_passed,.status.hardware_passed{color:var(--good);border-color:rgba(61,220,151,.28);background:rgba(61,220,151,.08)}.status.mockgpu_failed,.status.hardware_failed{color:#ff8e98;border-color:rgba(255,95,109,.28);background:rgba(255,95,109,.08)}.status.imported_unverified{color:#ffd278;border-color:rgba(245,185,66,.28);background:rgba(245,185,66,.08)}.contract{margin-top:10px;padding:9px;background:#0f1219;border:1px solid var(--line);border-radius:9px;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#aeb8c8;white-space:pre-wrap;max-height:150px;overflow:auto}.recipe-panel{grid-column:1/-1}.recipe-import{display:flex;gap:10px;padding:14px 14px 0}.recipe-import input{flex:1;background:#0f1219;border:1px solid var(--line);border-radius:10px;color:var(--text);padding:10px 12px;outline:0}.recipe-import input:focus{border-color:rgba(255,92,53,.65)}.kernel-actions{display:flex;gap:8px;margin-top:10px}.kernel-actions button{font-size:10px}@media(max-width:900px){.kernel-layout{grid-template-columns:1fr}.recipe-panel{grid-column:auto}}
+.kernel-layout{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:22px 24px 24px;width:100%;min-height:0;overflow:auto}.active-hooks-panel,.recipe-panel{grid-column:1/-1}.kernel-list{padding:12px;overflow:auto}.kernel-list.compact{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px}.kernel-card{background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:10px}.kernel-card h4{margin:0 0 6px;font-size:14px}.kernel-card p{color:var(--muted);font-size:11px;line-height:1.5}.kernel-card.active-hook{border-color:rgba(61,220,151,.32);box-shadow:inset 3px 0 0 rgba(61,220,151,.65)}.compact-card{margin:0}.stage-line{display:flex;align-items:center;gap:8px;margin-bottom:7px}.stage-line strong{font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.kernel-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.status{padding:4px 7px;border-radius:7px;background:#262d3a;border:1px solid var(--line);font-size:9px;text-transform:uppercase;letter-spacing:.07em}.status.stage{color:#cbb7ff;border-color:rgba(167,67,255,.3);background:rgba(167,67,255,.1)}.status.active{color:var(--good);border-color:rgba(61,220,151,.3);background:rgba(61,220,151,.1)}.status.mockgpu_passed,.status.hardware_passed,.status.heldout_passed,.status.accepted{color:var(--good);border-color:rgba(61,220,151,.28);background:rgba(61,220,151,.08)}.status.mockgpu_failed,.status.hardware_failed,.status.heldout_failed{color:#ff8e98;border-color:rgba(255,95,109,.28);background:rgba(255,95,109,.08)}.status.imported_unverified{color:#ffd278;border-color:rgba(245,185,66,.28);background:rgba(245,185,66,.08)}.contract{margin-top:10px;padding:9px;background:#0f1219;border:1px solid var(--line);border-radius:9px;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#aeb8c8;white-space:pre-wrap;max-height:170px;overflow:auto}.recipe-import{display:flex;gap:10px;padding:14px 14px 0}.recipe-import input{flex:1;background:#0f1219;border:1px solid var(--line);border-radius:10px;color:var(--text);padding:10px 12px;outline:0}.recipe-import input:focus{border-color:rgba(255,92,53,.65)}.kernel-actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin-top:10px}.kernel-actions button{font-size:10px}.hook-row{background:rgba(167,67,255,.06)}.stage-panel{grid-column:1/-1}@media(max-width:900px){.kernel-layout{grid-template-columns:1fr}.active-hooks-panel,.recipe-panel{grid-column:auto}}
From fc9655cc62c0d135feb6539cb3f97140ae062760 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:36:20 +0530
Subject: [PATCH 095/168] radeon forge: fit stage profiler and hook panels
---
extra/radeon_forge/ui/static/kernels.css | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/extra/radeon_forge/ui/static/kernels.css b/extra/radeon_forge/ui/static/kernels.css
index ab5f7cb4a8090..e7bba3e605a2c 100644
--- a/extra/radeon_forge/ui/static/kernels.css
+++ b/extra/radeon_forge/ui/static/kernels.css
@@ -1 +1 @@
-.kernel-layout{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:22px 24px 24px;width:100%;min-height:0;overflow:auto}.active-hooks-panel,.recipe-panel{grid-column:1/-1}.kernel-list{padding:12px;overflow:auto}.kernel-list.compact{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px}.kernel-card{background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:10px}.kernel-card h4{margin:0 0 6px;font-size:14px}.kernel-card p{color:var(--muted);font-size:11px;line-height:1.5}.kernel-card.active-hook{border-color:rgba(61,220,151,.32);box-shadow:inset 3px 0 0 rgba(61,220,151,.65)}.compact-card{margin:0}.stage-line{display:flex;align-items:center;gap:8px;margin-bottom:7px}.stage-line strong{font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.kernel-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.status{padding:4px 7px;border-radius:7px;background:#262d3a;border:1px solid var(--line);font-size:9px;text-transform:uppercase;letter-spacing:.07em}.status.stage{color:#cbb7ff;border-color:rgba(167,67,255,.3);background:rgba(167,67,255,.1)}.status.active{color:var(--good);border-color:rgba(61,220,151,.3);background:rgba(61,220,151,.1)}.status.mockgpu_passed,.status.hardware_passed,.status.heldout_passed,.status.accepted{color:var(--good);border-color:rgba(61,220,151,.28);background:rgba(61,220,151,.08)}.status.mockgpu_failed,.status.hardware_failed,.status.heldout_failed{color:#ff8e98;border-color:rgba(255,95,109,.28);background:rgba(255,95,109,.08)}.status.imported_unverified{color:#ffd278;border-color:rgba(245,185,66,.28);background:rgba(245,185,66,.08)}.contract{margin-top:10px;padding:9px;background:#0f1219;border:1px solid var(--line);border-radius:9px;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#aeb8c8;white-space:pre-wrap;max-height:170px;overflow:auto}.recipe-import{display:flex;gap:10px;padding:14px 14px 0}.recipe-import input{flex:1;background:#0f1219;border:1px solid var(--line);border-radius:10px;color:var(--text);padding:10px 12px;outline:0}.recipe-import input:focus{border-color:rgba(255,92,53,.65)}.kernel-actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin-top:10px}.kernel-actions button{font-size:10px}.hook-row{background:rgba(167,67,255,.06)}.stage-panel{grid-column:1/-1}@media(max-width:900px){.kernel-layout{grid-template-columns:1fr}.active-hooks-panel,.recipe-panel{grid-column:auto}}
+.metric-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.profile-layout{overflow:auto}.kernel-layout{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:22px 24px 24px;width:100%;min-height:0;overflow:auto}.active-hooks-panel,.recipe-panel{grid-column:1/-1}.kernel-list{padding:12px;overflow:auto}.kernel-list.compact{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px}.kernel-card{background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:14px;margin-bottom:10px}.kernel-card h4{margin:0 0 6px;font-size:14px}.kernel-card p{color:var(--muted);font-size:11px;line-height:1.5}.kernel-card.active-hook{border-color:rgba(61,220,151,.32);box-shadow:inset 3px 0 0 rgba(61,220,151,.65)}.compact-card{margin:0}.stage-line{display:flex;align-items:center;gap:8px;margin-bottom:7px}.stage-line strong{font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.kernel-meta{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.status{padding:4px 7px;border-radius:7px;background:#262d3a;border:1px solid var(--line);font-size:9px;text-transform:uppercase;letter-spacing:.07em}.status.stage{color:#cbb7ff;border-color:rgba(167,67,255,.3);background:rgba(167,67,255,.1)}.status.active{color:var(--good);border-color:rgba(61,220,151,.3);background:rgba(61,220,151,.1)}.status.mockgpu_passed,.status.hardware_passed,.status.heldout_passed,.status.accepted{color:var(--good);border-color:rgba(61,220,151,.28);background:rgba(61,220,151,.08)}.status.mockgpu_failed,.status.hardware_failed,.status.heldout_failed{color:#ff8e98;border-color:rgba(255,95,109,.28);background:rgba(255,95,109,.08)}.status.imported_unverified{color:#ffd278;border-color:rgba(245,185,66,.28);background:rgba(245,185,66,.08)}.contract{margin-top:10px;padding:9px;background:#0f1219;border:1px solid var(--line);border-radius:9px;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#aeb8c8;white-space:pre-wrap;max-height:170px;overflow:auto}.recipe-import{display:flex;gap:10px;padding:14px 14px 0}.recipe-import input{flex:1;background:#0f1219;border:1px solid var(--line);border-radius:10px;color:var(--text);padding:10px 12px;outline:0}.recipe-import input:focus{border-color:rgba(255,92,53,.65)}.kernel-actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin-top:10px}.kernel-actions button{font-size:10px}.hook-row{background:rgba(167,67,255,.06)}.stage-panel{grid-column:1/-1}@media(max-width:900px){.metric-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.kernel-layout{grid-template-columns:1fr}.active-hooks-panel,.recipe-panel{grid-column:auto}}
From f3b0973f16b12245ddedb76832b39f8e1d5eacf4 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:37:01 +0530
Subject: [PATCH 096/168] radeon forge: test stage-aware kernel profiling
---
test/test_radeon_forge_runtime.py | 28 +++++++++++++++++++++-------
1 file changed, 21 insertions(+), 7 deletions(-)
diff --git a/test/test_radeon_forge_runtime.py b/test/test_radeon_forge_runtime.py
index 38a31c37d70c8..6db089af44cbf 100644
--- a/test/test_radeon_forge_runtime.py
+++ b/test/test_radeon_forge_runtime.py
@@ -19,34 +19,47 @@ def name(self): return "kernel-evidence-local"
@property
def capabilities(self): return BackendCapabilities(prefix_cache=True, persistent_kv=True, kernel_metrics=True)
+ @property
+ def runtime_metadata(self): return {"runtime":"test", "architecture":"gfx1100", "model_family":"llama"}
+
def stream(self, request):
yield GenerationEvent("prefill", metrics={"wall_ms": 8.0, "gpu_ms": 5.0, "prompt_tokens": 24,
"prefix_reused_tokens": 12, "profile_kernel_events": 1})
yield GenerationEvent("kernel", metrics={"name": "rmsnorm_fused", "duration_ms": 0.40, "stage": "prefill", "device": "AMD"})
- yield GenerationEvent("token", "ok", metrics={"index": 0, "wall_ms": 2.0, "gpu_ms": 1.4,
+ yield GenerationEvent("token", "first", metrics={"index": 0, "stage": "first_token", "wall_ms": 4.0, "gpu_ms": 2.5,
+ "kernel_count": 24, "profile_kernel_events": 1})
+ yield GenerationEvent("kernel", metrics={"name": "first_token_projection", "duration_ms": 0.80,
+ "stage": "first_token", "device": "AMD"})
+ yield GenerationEvent("token", "ok", metrics={"index": 1, "stage": "decode", "wall_ms": 2.0, "gpu_ms": 1.4,
"kernel_count": 24, "profile_kernel_events": 2})
yield GenerationEvent("kernel", metrics={"name": "decode_gemv", "duration_ms": 0.90, "stage": "decode", "device": "AMD"})
yield GenerationEvent("kernel", metrics={"name": "decode_gemv", "duration_ms": 0.70, "stage": "decode", "device": "AMD"})
- yield GenerationEvent("done", finish_reason="stop", metrics={"generated_tokens": 1})
+ yield GenerationEvent("done", finish_reason="stop", metrics={"generated_tokens": 2})
def close(self): pass
class TestRadeonForgeRuntime(unittest.TestCase):
- def test_kernel_evidence_survives_unified_trace_and_is_ranked(self):
+ def test_kernel_evidence_survives_unified_trace_and_is_ranked_by_stage(self):
with tempfile.TemporaryDirectory() as directory:
engine = ForgeEngine(KernelEvidenceBackend(), directory)
session = engine.create_session()
- session.send("profile one token")
+ session.send("profile two execution states")
report = build_profile_report(session.trace.events())
top = report["summary"]["top_kernels"]
self.assertEqual(top[0]["name"], "decode_gemv")
self.assertEqual(top[0]["calls"], 2)
self.assertAlmostEqual(top[0]["total_ms"], 1.6)
+ self.assertEqual(report["summary"]["top_kernels_by_stage"]["prefill"][0]["name"], "rmsnorm_fused")
+ self.assertEqual(report["summary"]["top_kernels_by_stage"]["first_token"][0]["name"], "first_token_projection")
+ self.assertEqual(report["summary"]["top_kernels_by_stage"]["decode"][0]["name"], "decode_gemv")
self.assertTrue(report["summary"]["kernel_profile_complete"])
- self.assertTrue(any(x["title"] == "One kernel family dominates captured GPU time" for x in report["findings"]))
- kernel_events = [event for event in session.trace.events() if event.name == "kernel"]
- self.assertEqual([event.attributes["name"] for event in kernel_events], ["rmsnorm_fused", "decode_gemv", "decode_gemv"])
+ titles = {x["title"] for x in report["findings"]}
+ self.assertIn("One kernel family dominates captured GPU time overall", titles)
+ self.assertIn("Different execution stages have different dominant kernels", titles)
+ self.assertIn("First-token and steady-decode latency are materially different", titles)
+ kernel_events = [event for event in session.trace.events() if event.kind == "kernel"]
+ self.assertEqual([event.name for event in kernel_events], ["rmsnorm_fused", "first_token_projection", "decode_gemv", "decode_gemv"])
engine.close()
def test_permissioned_tool_round_trip(self):
@@ -61,6 +74,7 @@ def test_permissioned_tool_round_trip(self):
session.send("read hello.txt")
self.assertEqual(session.state, SessionState.AWAITING_TOOL_APPROVAL)
with self.assertRaises(PermissionDenied): session.approve_tool("not-a-real-grant")
+ self.assertEqual(session.state, SessionState.AWAITING_TOOL_APPROVAL)
token = engine.grant_for_pending_tool(session.session_id, "approve one local read")
session.approve_tool(token)
self.assertEqual(session.state, SessionState.COMPLETED)
From 2921d945ba9397ca0f49a5df8a0968a0b03e1575 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:37:52 +0530
Subject: [PATCH 097/168] radeon forge: test portable execution-stage hook
round trip
---
test/test_radeon_forge_recipe.py | 51 ++++++++++++++++++++++++++++----
1 file changed, 45 insertions(+), 6 deletions(-)
diff --git a/test/test_radeon_forge_recipe.py b/test/test_radeon_forge_recipe.py
index a8798f5167b57..00ac261ce9816 100644
--- a/test/test_radeon_forge_recipe.py
+++ b/test/test_radeon_forge_recipe.py
@@ -3,7 +3,8 @@
import unittest
from pathlib import Path
-from extra.radeon_forge.synthesis import CandidateWorkspace, ForgeRecipe, KernelSpec, RecipeLibrary, export_recipe
+from extra.radeon_forge.synthesis import (CandidateWorkspace, ForgeRecipe, HookDescriptor, KernelSpec, RecipeLibrary,
+ export_recipe, export_recipe_with_hook)
class TestForgeRecipe(unittest.TestCase):
@@ -21,11 +22,24 @@ def _recipe_text(self, seed: str = "print('seed')\n") -> str:
seed_artifact = "seed.py"
[compatibility]
-arch = "gfx1100"
+architecture = "gfx1100"
[acceptance]
maximum_error = 0.000001
+[metadata.hook]
+layer = "kernel"
+target = "projection_gemm"
+mode = "replace"
+adapter = "request_metadata"
+exclusive_group = "projection"
+
+[metadata.hook.when]
+stages = ["decode"]
+batch_sizes = [1]
+min_context_tokens = 1024
+prefix_cache = "hit"
+
[oracle]
mockgpu_command = ["python3", "{{candidate}}", "--bundle", "{{bundle}}"]
hardware_command = ["python3", "{{candidate}}", "--benchmark"]
@@ -60,6 +74,11 @@ def test_install_is_content_addressed_and_seed_is_unverified(self):
self.assertEqual(Path(candidate.source_path).read_text(encoding="utf-8"), "print('seed')\n")
spec = workspace.load_spec(installed.spec_id)
+ descriptor = HookDescriptor.from_spec(spec)
+ self.assertEqual(descriptor.layer.value, "kernel")
+ self.assertEqual([x.value for x in descriptor.when.stages], ["decode"])
+ self.assertEqual(descriptor.when.min_context_tokens, 1024)
+ self.assertEqual(descriptor.when.prefix_cache, "hit")
rendered = workspace.render_command(spec.mockgpu_command, spec, candidate, root)
self.assertEqual(rendered[1], candidate.source_path)
self.assertEqual(rendered[3], installed.bundle_root)
@@ -71,7 +90,7 @@ def test_rejects_path_traversal(self):
path.write_text(text, encoding="utf-8")
with self.assertRaises(ValueError): ForgeRecipe.load(path)
- def test_export_import_round_trip_preserves_contract_and_cache(self):
+ def test_export_import_round_trip_preserves_contract_cache_and_stage_hook(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source_workspace = CandidateWorkspace(root / "source")
@@ -80,20 +99,40 @@ def test_export_import_round_trip_preserves_contract_and_cache(self):
invariants=("match reference", "no remote API"), objective="minimize p95 token latency",
mockgpu_command=("python3", "{candidate}"), hardware_command=("python3", "{candidate}", "--benchmark"),
metadata={"recipe_agent_brief":"Use the oracle as the contract and freely rewrite the implementation.",
- "recipe_compatibility":{"arch":"gfx1100"}, "recipe_acceptance":{"max_error":1e-6}},
+ "recipe_compatibility":{"architecture":"gfx1100"}, "recipe_acceptance":{"max_error":1e-6},
+ "hook":{"layer":"transformer_block", "target":"llama.decode.block", "mode":"replace",
+ "adapter":"python_transformer_block", "selector":{"indices":[0,1]},
+ "when":{"stages":["decode"], "batch_sizes":[1], "min_generated_token_index":1,
+ "conditions":{"resume_after_tool":False}},
+ "exclusive_group":"decode-block"}},
)
source_workspace.save_spec(spec)
- candidate = source_workspace.create_candidate(spec.spec_id, "print('candidate')\n", "measured VOPD schedule")
- exported = export_recipe(source_workspace, spec.spec_id, root / "shared.forge.toml", candidate.candidate_id)
+ candidate = source_workspace.create_candidate(spec.spec_id, "print('candidate')\n", "measured decode implementation")
+ exported = export_recipe_with_hook(source_workspace, spec.spec_id, root / "shared.forge.toml", candidate.candidate_id)
loaded = ForgeRecipe.load(exported)
self.assertEqual(loaded.target, "gfx1100")
self.assertEqual(loaded.invariants, spec.invariants)
+ self.assertEqual(loaded.metadata["hook"]["when"]["stages"], ["decode"])
destination = CandidateWorkspace(root / "destination")
installed = RecipeLibrary(destination).install(loaded)
imported = destination.load_candidate(installed.seed_candidate_id)
self.assertEqual(Path(imported.source_path).read_text(encoding="utf-8"), "print('candidate')\n")
self.assertEqual(imported.status, "imported_unverified")
+ installed_spec = destination.load_spec(installed.spec_id)
+ descriptor = HookDescriptor.from_spec(installed_spec)
+ self.assertEqual(descriptor.target, "llama.decode.block")
+ self.assertEqual([x.value for x in descriptor.when.stages], ["decode"])
+ self.assertEqual(descriptor.when.min_generated_token_index, 1)
+ self.assertEqual(descriptor.when.conditions["resume_after_tool"], False)
+
+ def test_base_export_remains_valid_without_hook_extension(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ workspace = CandidateWorkspace(root / "source")
+ spec = workspace.save_spec(KernelSpec("plain", "plain operation", invariants=("correct",)))
+ path = export_recipe(workspace, spec.spec_id, root / "plain.forge.toml")
+ self.assertEqual(ForgeRecipe.load(path).name, "plain")
if __name__ == "__main__": unittest.main()
From 338808734a104054253562cddfdbf113711894c7 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:39:13 +0530
Subject: [PATCH 098/168] radeon forge: add asynchronous local agent jobs
---
extra/radeon_forge/runtime/jobs.py | 57 ++++++++++++++++++++++++++++++
1 file changed, 57 insertions(+)
create mode 100644 extra/radeon_forge/runtime/jobs.py
diff --git a/extra/radeon_forge/runtime/jobs.py b/extra/radeon_forge/runtime/jobs.py
new file mode 100644
index 0000000000000..6a76f9409a32b
--- /dev/null
+++ b/extra/radeon_forge/runtime/jobs.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+import threading, time, uuid
+from dataclasses import asdict, dataclass
+from typing import Any, Callable
+
+
+@dataclass(frozen=True)
+class JobSnapshot:
+ job_id: str
+ kind: str
+ state: str
+ session_id: str
+ created_at_s: float
+ started_at_s: float | None = None
+ completed_at_s: float | None = None
+ error: str | None = None
+ error_type: str | None = None
+
+
+class LocalJobManager:
+ """Small in-process job manager for non-blocking local UI operations."""
+ def __init__(self):
+ self._jobs: dict[str, JobSnapshot] = {}
+ self._lock = threading.RLock()
+
+ def _set(self, snapshot: JobSnapshot) -> None:
+ with self._lock: self._jobs[snapshot.job_id] = snapshot
+
+ def submit(self, kind: str, session_id: str, fn: Callable[[], Any]) -> JobSnapshot:
+ job_id, created = uuid.uuid4().hex, time.time()
+ initial = JobSnapshot(job_id, kind, "queued", session_id, created)
+ self._set(initial)
+
+ def run():
+ started = time.time()
+ self._set(JobSnapshot(job_id, kind, "running", session_id, created, started_at_s=started))
+ try:
+ fn()
+ except BaseException as exc:
+ self._set(JobSnapshot(job_id, kind, "failed", session_id, created, started, time.time(), str(exc), type(exc).__name__))
+ else:
+ self._set(JobSnapshot(job_id, kind, "completed", session_id, created, started, time.time()))
+
+ threading.Thread(target=run, name=f"radeon-forge-{kind}-{job_id[:8]}", daemon=True).start()
+ return initial
+
+ def snapshot(self, job_id: str) -> JobSnapshot:
+ with self._lock:
+ try: return self._jobs[job_id]
+ except KeyError as exc: raise KeyError(f"unknown job {job_id}") from exc
+
+ def snapshots(self, session_id: str | None = None) -> list[dict[str, Any]]:
+ with self._lock:
+ jobs = list(self._jobs.values())
+ if session_id is not None: jobs = [job for job in jobs if job.session_id == session_id]
+ return [asdict(job) for job in sorted(jobs, key=lambda x: x.created_at_s, reverse=True)]
From 35072323f5caf6cb1bece513e050c7c0f32ec0f1 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:40:10 +0530
Subject: [PATCH 099/168] radeon forge: expose live partial generation and
incremental events
---
extra/radeon_forge/runtime/session.py | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index a4cf0b4227d26..6a1ffcbeb8d63 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -39,6 +39,7 @@ def __init__(self, backend: InferenceBackend, tools: ToolRegistry, system_prompt
self.messages: list[dict[str, Any]] = [{"role": "system", "content": self._system_prompt()}]
self.events: list[SessionEvent] = []
self.pending_tool_call: ToolCall | None = None
+ self.partial_output = ""
self.state = SessionState.IDLE
self._sequence = 0
self._lock = threading.RLock()
@@ -94,6 +95,7 @@ def _request_metadata(self, step: int) -> dict[str, Any]:
def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent, ...]:
self.state = SessionState.GENERATING
+ self.partial_output = ""
started_at = len(self.events)
pieces: list[str] = []
step = sum(1 for event in self.events if event.kind == "generation_started") + 1
@@ -106,6 +108,7 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
for event in self.backend.stream(request):
if event.kind == "token":
pieces.append(event.text)
+ self.partial_output += event.text
self._emit("token", text=event.text, metrics=dict(event.metrics))
token_metrics = dict(event.metrics)
if "name" in token_metrics: token_metrics["token_name"] = token_metrics.pop("name")
@@ -124,10 +127,12 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
try: self.pending_tool_call = parse_tool_call(output)
except Exception as exc: self._emit("tool_parse_error", error=str(exc), raw=output)
if self.pending_tool_call is not None:
+ self.partial_output = ""
self.state = SessionState.AWAITING_TOOL_APPROVAL
self._emit("tool_approval_required", call=asdict(self.pending_tool_call), action=self.tools.spec(self.pending_tool_call.name).action.value)
else:
self.messages.append({"role": "assistant", "content": output})
+ self.partial_output = ""
self.state = SessionState.COMPLETED
self._emit("message", role="assistant", content=output)
return tuple(self.events[started_at:])
@@ -167,7 +172,10 @@ def reject_tool(self, reason: str) -> SessionEvent:
self.state = SessionState.IDLE
return self._emit("tool_rejected", call_id=call.call_id, reason=reason)
+ def events_after(self, sequence: int) -> list[dict[str, Any]]:
+ return [asdict(event) for event in self.events if event.sequence > sequence]
+
def snapshot(self) -> dict[str, Any]:
return {"session_id": self.session_id, "state": self.state.value, "messages": list(self.messages),
"events": [asdict(x) for x in self.events], "pending_tool_call": asdict(self.pending_tool_call) if self.pending_tool_call else None,
- "trace_id": self.trace.trace_id}
+ "partial_output": self.partial_output, "trace_id": self.trace.trace_id}
From e881ae0d9b3bb048bab513c00bfe943983bfd109 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:40:37 +0530
Subject: [PATCH 100/168] radeon forge: run local agent turns asynchronously
---
extra/radeon_forge/runtime/engine.py | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index 928fea6d9b1b5..c7bd043258ea0 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -9,6 +9,7 @@
from ..profiling.report import build_profile_report
from ..synthesis import CandidateWorkspace, HookRegistry, OptimizationTools, RuntimeFingerprint, install_default_specs
from .backend import InferenceBackend
+from .jobs import LocalJobManager
from .session import AgentSession
from .tools import ToolCall, ToolRegistry, WorkspaceTools
@@ -30,6 +31,7 @@ def __init__(self, backend: InferenceBackend, workspace: str | Path, system_prom
self.hooks = HookRegistry(self.optimization_workspace)
self.optimization_tools = OptimizationTools(self.optimization_workspace, self.workspace, self.hooks, self.runtime_fingerprint)
self.optimization_tools.install(self.tools)
+ self.jobs = LocalJobManager()
self._sessions: dict[str, AgentSession] = {}
self._lock = threading.RLock()
@@ -54,6 +56,17 @@ def session(self, session_id: str) -> AgentSession:
def sessions(self) -> list[dict[str, Any]]:
with self._lock: return [{"session_id": x.session_id, "state": x.state.value, "trace_id": x.trace.trace_id} for x in self._sessions.values()]
+ def submit_message(self, session_id: str, content: str, max_tokens: int = 512, temperature: float = 0.0) -> dict[str, Any]:
+ session = self.session(session_id)
+ job = self.jobs.submit("agent_turn", session_id, lambda: session.send(content, max_tokens, temperature))
+ return asdict(job)
+
+ def submit_tool_approval(self, session_id: str, reason: str, max_tokens: int = 512) -> dict[str, Any]:
+ session = self.session(session_id)
+ token = self.grant_for_pending_tool(session_id, reason)
+ job = self.jobs.submit("tool_and_resume", session_id, lambda: session.approve_tool(token, max_tokens))
+ return asdict(job)
+
def grant_for_pending_tool(self, session_id: str, reason: str, max_uses: int = 1) -> str:
session = self.session(session_id)
if session.pending_tool_call is None: raise RuntimeError("session has no pending tool")
From 6e0ac05cd9b89c0021e4949528b219bf40a39134 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:40:51 +0530
Subject: [PATCH 101/168] radeon forge: export asynchronous job runtime
---
extra/radeon_forge/runtime/__init__.py | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/runtime/__init__.py b/extra/radeon_forge/runtime/__init__.py
index edb8c53326723..682b5b0e81570 100644
--- a/extra/radeon_forge/runtime/__init__.py
+++ b/extra/radeon_forge/runtime/__init__.py
@@ -1,9 +1,10 @@
from .backend import BackendCapabilities, GenerationEvent, GenerationRequest, InferenceBackend, JsonlProcessBackend
from .engine import ForgeEngine
from .events import TraceEvent, TraceRecorder
+from .jobs import JobSnapshot, LocalJobManager
from .session import AgentSession, SessionState
from .tools import ToolCall, ToolRegistry, ToolResult, ToolSpec, WorkspaceTools
__all__ = ["AgentSession", "BackendCapabilities", "ForgeEngine", "GenerationEvent", "GenerationRequest", "InferenceBackend",
- "JsonlProcessBackend", "SessionState", "ToolCall", "ToolRegistry", "ToolResult", "ToolSpec", "TraceEvent",
- "TraceRecorder", "WorkspaceTools"]
+ "JobSnapshot", "JsonlProcessBackend", "LocalJobManager", "SessionState", "ToolCall", "ToolRegistry", "ToolResult",
+ "ToolSpec", "TraceEvent", "TraceRecorder", "WorkspaceTools"]
From e4799d49b8c987adaed861511cb4229082125603 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:41:32 +0530
Subject: [PATCH 102/168] radeon forge: stream local agent state through
asynchronous UI jobs
---
extra/radeon_forge/ui/server.py | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/ui/server.py b/extra/radeon_forge/ui/server.py
index 3e16329a0d6c7..e197a1ac89cec 100644
--- a/extra/radeon_forge/ui/server.py
+++ b/extra/radeon_forge/ui/server.py
@@ -6,7 +6,7 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
-from urllib.parse import urlparse
+from urllib.parse import parse_qs, urlparse
from ..backends.fake import ScriptedBackend
from ..runtime import ForgeEngine, JsonlProcessBackend
@@ -48,7 +48,7 @@ def _session_route(self):
return self.engine.session(match.group(1)), match.group(2) or ""
def do_GET(self):
- path = urlparse(self.path).path
+ parsed, path = urlparse(self.path), urlparse(self.path).path
try:
if path == "/": return self._static("index.html")
if path in {"/app.js", "/style.css", "/kernels.css"}: return self._static(path[1:])
@@ -56,9 +56,14 @@ def do_GET(self):
"capabilities": asdict(self.engine.backend.capabilities), "runtime_fingerprint": asdict(self.engine.runtime_fingerprint())})
if path == "/api/sessions": return self._json(self.engine.sessions())
if path == "/api/optimization": return self._json(self.engine.optimization_state())
+ job_match = re.fullmatch(r"/api/jobs/([a-f0-9]+)", path)
+ if job_match: return self._json(asdict(self.engine.jobs.snapshot(job_match.group(1))))
session, tail = self._session_route()
if session is None: return self.send_error(404)
if tail == "": return self._json(session.snapshot())
+ if tail == "events":
+ after = int(parse_qs(parsed.query).get("after", ["0"])[0])
+ return self._json({"events": session.events_after(after), "session": session.snapshot()})
if tail == "profile": return self._json(self.engine.profile(session.session_id))
if tail == "trace": return self._json(session.trace.to_dict())
if tail == "trace/chrome": return self._json(session.trace.chrome_trace())
@@ -96,11 +101,19 @@ def do_POST(self):
if tail == "messages":
events = session.send(str(body.get("content", "")), int(body.get("max_tokens", 512)), float(body.get("temperature", 0.0)))
return self._json({"events": [asdict(x) for x in events], "session": session.snapshot()})
+ if tail == "messages/async":
+ job = self.engine.submit_message(session.session_id, str(body.get("content", "")), int(body.get("max_tokens", 512)),
+ float(body.get("temperature", 0.0)))
+ return self._json({"job": job, "session": session.snapshot()}, HTTPStatus.ACCEPTED)
if tail == "tools/approve":
reason = str(body.get("reason", "Approved from Radeon Forge UI"))
token = self.engine.grant_for_pending_tool(session.session_id, reason)
events = session.approve_tool(token, int(body.get("max_tokens", 512)))
return self._json({"events": [asdict(x) for x in events], "session": session.snapshot()})
+ if tail == "tools/approve/async":
+ job = self.engine.submit_tool_approval(session.session_id, str(body.get("reason", "Approved from Radeon Forge UI")),
+ int(body.get("max_tokens", 512)))
+ return self._json({"job": job, "session": session.snapshot()}, HTTPStatus.ACCEPTED)
if tail == "tools/reject":
event = session.reject_tool(str(body.get("reason", "Rejected by user")))
return self._json({"event": asdict(event), "session": session.snapshot()})
From 3cc38f05ccb879d466f270570ee5812b5dcfaeb3 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:42:40 +0530
Subject: [PATCH 103/168] radeon forge: stream local agent turns in the UI
---
extra/radeon_forge/ui/static/app.js | 16 +++++++++-------
1 file changed, 9 insertions(+), 7 deletions(-)
diff --git a/extra/radeon_forge/ui/static/app.js b/extra/radeon_forge/ui/static/app.js
index 43cf4639c22bc..166fcf6feb609 100644
--- a/extra/radeon_forge/ui/static/app.js
+++ b/extra/radeon_forge/ui/static/app.js
@@ -1,5 +1,5 @@
-const state={session:null,sessions:[],health:null,optimization:null,tab:'console'};
-const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
+const state={session:null,sessions:[],health:null,optimization:null,tab:'console',activeJob:null};
+const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)], sleep=ms=>new Promise(r=>setTimeout(r,ms));
const toast=msg=>{const el=$('#toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),3000)};
async function api(path,opts={}){const res=await fetch(path,{headers:{'Content-Type':'application/json'},...opts});const data=await res.json();if(!res.ok)throw new Error(data.error||`HTTP ${res.status}`);return data}
function fmtMs(v){return v==null?'—':`${Number(v).toFixed(v<10?2:1)} ms`}
@@ -10,12 +10,14 @@ function renderHealth(){const h=state.health;$('#runtime-name').textContent=h?.b
async function refreshSessions(){state.sessions=await api('/api/sessions');renderSessionList()}
function renderSessionList(){const list=$('#session-list');list.innerHTML='';state.sessions.forEach((s,i)=>{const el=document.createElement('div');el.className=`session-item ${state.session?.session_id===s.session_id?'active':''}`;el.innerHTML=`
${i===0?'Primary':'Session'} ${s.session_id.slice(0,6)} ${esc(s.state)} `;el.onclick=()=>selectSession(s.session_id);list.append(el)})}
async function createSession(){const s=await api('/api/sessions',{method:'POST',body:'{}'});await refreshSessions();await selectSession(s.session_id)}
-async function selectSession(id){state.session=await api(`/api/sessions/${id}`);renderSession();renderSessionList();if(state.tab==='profile')refreshProfile();if(state.tab==='trace')refreshTrace()}
+async function selectSession(id){if(state.activeJob)throw new Error('A local turn is still running');state.session=await api(`/api/sessions/${id}`);renderSession();renderSessionList();if(state.tab==='profile')refreshProfile();if(state.tab==='trace')refreshTrace()}
function renderSession(){const s=state.session;if(!s)return;$('#session-title').textContent=`Agent Console · ${s.session_id.slice(0,6)}`;$('#session-state').textContent=s.state;$('#trace-id').textContent=s.trace_id.slice(0,10);$('#event-count').textContent=s.events.length;renderMessages();renderApproval()}
-function renderMessages(){const box=$('#messages');const messages=(state.session?.messages||[]).filter(x=>x.role!=='system'&&x.role!=='tool');if(!messages.length)return;box.innerHTML='';messages.forEach(m=>{const el=document.createElement('div');el.className=`message ${m.role}`;el.innerHTML=`
${m.role==='user'?'YOU':'RF'}
${esc(m.content)}
`;box.append(el)});box.scrollTop=box.scrollHeight}
+function renderMessages(){const box=$('#messages');const messages=(state.session?.messages||[]).filter(x=>x.role!=='system'&&x.role!=='tool');if(!messages.length&&!state.session?.partial_output)return;box.innerHTML='';messages.forEach(m=>{const el=document.createElement('div');el.className=`message ${m.role}`;el.innerHTML=`
${m.role==='user'?'YOU':'RF'}
${esc(m.content)}
`;box.append(el)});if(state.session?.partial_output){const el=document.createElement('div');el.className='message assistant streaming';el.innerHTML=`
RF
${esc(state.session.partial_output)}
`;box.append(el)}box.scrollTop=box.scrollHeight}
function renderApproval(){const card=$('#approval-card'),call=state.session?.pending_tool_call;if(!call){card.classList.add('hidden');return}card.classList.remove('hidden');$('#approval-name').textContent=call.name;$('#approval-args').textContent=JSON.stringify(call.arguments,null,2)}
-async function sendMessage(text){if(!state.session)return;$('#send').disabled=true;$('#send').textContent='Running…';try{const out=await api(`/api/sessions/${state.session.session_id}/messages`,{method:'POST',body:JSON.stringify({content:text,max_tokens:512})});state.session=out.session;renderSession();await refreshSessions()}finally{$('#send').disabled=false;$('#send').textContent='Run'}}
-async function approveTool(){const out=await api(`/api/sessions/${state.session.session_id}/tools/approve`,{method:'POST',body:JSON.stringify({reason:'Approved once from the local UI',max_tokens:512})});state.session=out.session;renderSession();await refreshSessions();if(state.tab==='kernels')await refreshKernels();toast('Tool executed locally')}
+function maxSequence(){return Math.max(0,...(state.session?.events||[]).map(x=>Number(x.sequence)||0))}
+async function watchJob(jobId){state.activeJob=jobId;let after=maxSequence(),profileTick=0;try{while(true){const [job,delta]=await Promise.all([api(`/api/jobs/${jobId}`),api(`/api/sessions/${state.session.session_id}/events?after=${after}`)]);state.session=delta.session;(delta.events||[]).forEach(e=>after=Math.max(after,Number(e.sequence)||0));renderSession();if(++profileTick%5===0&&state.tab==='trace')refreshTrace().catch(()=>{});if(job.state==='completed')break;if(job.state==='failed')throw new Error(`${job.error_type||'JobError'}: ${job.error||'local job failed'}`);await sleep(100)}}finally{state.activeJob=null;await refreshSessions();state.session=await api(`/api/sessions/${state.session.session_id}`);renderSession();if(state.tab==='profile')await refreshProfile();if(state.tab==='trace')await refreshTrace();if(state.tab==='kernels')await refreshKernels()}}
+async function sendMessage(text){if(!state.session||state.activeJob)return;$('#send').disabled=true;$('#send').textContent='Running…';try{const out=await api(`/api/sessions/${state.session.session_id}/messages/async`,{method:'POST',body:JSON.stringify({content:text,max_tokens:512})});state.session=out.session;renderSession();await watchJob(out.job.job_id)}finally{$('#send').disabled=false;$('#send').textContent='Run'}}
+async function approveTool(){if(state.activeJob)return;$('#approve-tool').disabled=true;try{const out=await api(`/api/sessions/${state.session.session_id}/tools/approve/async`,{method:'POST',body:JSON.stringify({reason:'Approved once from the local UI',max_tokens:512})});state.session=out.session;renderSession();await watchJob(out.job.job_id);toast('Tool executed locally')}finally{$('#approve-tool').disabled=false}}
async function rejectTool(){const out=await api(`/api/sessions/${state.session.session_id}/tools/reject`,{method:'POST',body:JSON.stringify({reason:'Rejected in UI'})});state.session=out.session;renderSession();toast('Tool rejected')}
async function refreshProfile(){if(!state.session)return;const p=await api(`/api/sessions/${state.session.session_id}/profile`),s=p.summary||{},stages=s.token_latency_by_stage||{};$('#p50-token').textContent=fmtMs(s.token_wall_ms_p50);$('#p95-token').textContent=fmtMs(s.token_wall_ms_p95);$('#first-token').textContent=fmtMs(stages.first_token?.p50_ms);$('#steady-decode').textContent=fmtMs(stages.decode?.p50_ms);$('#launches-token').textContent=s.mean_kernel_count_per_token==null?'—':Number(s.mean_kernel_count_per_token).toFixed(1);$('#hook-transitions').textContent=`${s.hook_transitions||0}${s.hook_rollbacks?` / ${s.hook_rollbacks} rollback`:''}`;const findings=$('#findings');findings.innerHTML='';(p.findings||[]).forEach(f=>{const el=document.createElement('div');el.className=`finding ${f.severity}`;el.innerHTML=`
${esc(f.status)} ${esc(f.title)}
${esc((f.evidence||[]).join(' · '))}
Next: ${esc(f.recommendation)}
`;findings.append(el)});if(!p.findings?.length)findings.innerHTML='
No diagnosis yet. Run an agent turn first.
';renderAttribution(s.durations_ms_by_kind||{});renderStageKernels(s.top_kernels_by_stage||{})}
function renderAttribution(d){const box=$('#attribution');box.innerHTML='';const entries=Object.entries(d).sort((a,b)=>b[1]-a[1]),max=Math.max(1,...entries.map(x=>x[1]));entries.forEach(([k,v])=>{const el=document.createElement('div');el.className='bar-row';el.innerHTML=`
${esc(k)} ${fmtMs(v)}
`;box.append(el)});if(!entries.length)box.textContent='No trace data yet.'}
@@ -28,4 +30,4 @@ async function rollbackHook(hook){const out=await api('/api/hooks/deactivate',{m
function renderActiveHooks(hooks){const box=$('#active-hooks');box.innerHTML='';(hooks||[]).forEach(h=>{const w=hookWhen(h.descriptor),el=document.createElement('div');el.className='kernel-card active-hook';el.innerHTML=`
active ${esc(h.descriptor.layer)} · ${esc(h.descriptor.target)}
${esc(h.candidate_id)}
${esc(w.stages)} ${esc(h.descriptor.mode)} priority ${h.descriptor.priority||0}
${w.detail?`
${esc(w.detail)}
`:''}
${esc(JSON.stringify({selector:h.descriptor.selector,compatibility:h.compatibility},null,2))}
Rollback
`;el.querySelector('.rollback-hook').onclick=()=>rollbackHook(h).catch(e=>toast(e.message));box.append(el)});if(!box.children.length)box.innerHTML='
No optimization is active. The trusted tinygrad baseline owns every execution stage.
'}
async function refreshKernels(){state.optimization=await api('/api/optimization');const specs=$('#kernel-specs'),candidates=$('#kernel-candidates'),recipes=$('#recipe-list');specs.innerHTML='';candidates.innerHTML='';recipes.innerHTML='';renderActiveHooks(state.optimization.active_hooks||[]);const activeIds=new Set((state.optimization.active_hooks||[]).map(x=>x.candidate_id));(state.optimization.specs||[]).forEach(s=>{const h=s.metadata?.hook||{},w=hookWhen(h),el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(s.name)} ${esc(s.operation)}
${esc(s.target)} ${esc(h.layer||'kernel')} ${esc(w.stages)} ${esc(s.objective)}
${w.detail?`
${esc(w.detail)}
`:''}
${esc(JSON.stringify({where:{layer:h.layer,target:h.target,mode:h.mode,selector:h.selector},when:h.when,shapes:s.shapes,dtypes:s.dtypes,invariants:s.invariants,agent_brief:s.metadata?.recipe_agent_brief},null,2))}
`;specs.append(el)});(state.optimization.candidates||[]).forEach(c=>{const spec=(state.optimization.specs||[]).find(s=>s.spec_id===c.spec_id),h=spec?.metadata?.hook||{},w=hookWhen(h),eligible=['hardware_passed','heldout_passed','accepted'].includes(c.status),el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(c.candidate_id)} ${esc(c.hypothesis||'No hypothesis recorded')}
${esc(c.status)} ${esc(h.layer||'kernel')} ${esc(w.stages)}
${esc(JSON.stringify(c.evidence||{},null,2))}
Export recipe ${eligible&&!activeIds.has(c.candidate_id)?'Activate scoped hook ':''}${activeIds.has(c.candidate_id)?'currently active ':''}
`;el.querySelector('.export-candidate').onclick=()=>exportCandidate(c).catch(e=>toast(e.message));const activate=el.querySelector('.activate-candidate');if(activate)activate.onclick=()=>activateCandidate(c).catch(e=>toast(e.message));candidates.append(el)});(state.optimization.recipes||[]).forEach(r=>{const el=document.createElement('div');el.className='kernel-card';el.innerHTML=`
${esc(r.recipe_id)} Installed portable contract. Placement and execution-state predicates are preserved; cached code remains unverified until local oracles pass.
${esc(r.spec_id)} ${r.seed_candidate_id?'seed cache ':''}
${esc(JSON.stringify({bundle:r.bundle_root,artifacts:r.artifact_hashes},null,2))}
`;recipes.append(el)});if(!state.optimization.candidates?.length)candidates.innerHTML='
No candidate has been staged. Ask Forge to list contracts and generate one for a specific execution state.
';if(!state.optimization.recipes?.length)recipes.innerHTML='
No portable recipe installed yet. Import a .forge.toml file from the workspace.
'}
function switchTab(tab){state.tab=tab;$$('.tab').forEach(x=>x.classList.remove('active'));$(`#${tab}-tab`).classList.add('active');$$('[data-tab]').forEach(x=>x.classList.toggle('active',x.dataset.tab===tab));if(tab==='profile')refreshProfile();if(tab==='trace')refreshTrace();if(tab==='kernels')refreshKernels()}
-$('#new-session').onclick=createSession;$('#composer').onsubmit=async e=>{e.preventDefault();const input=$('#prompt'),text=input.value.trim();if(!text)return;input.value='';try{await sendMessage(text)}catch(err){toast(err.message)}};$('#approve-tool').onclick=()=>approveTool().catch(e=>toast(e.message));$('#reject-tool').onclick=()=>rejectTool().catch(e=>toast(e.message));$('#refresh-profile').onclick=()=>refreshProfile().catch(e=>toast(e.message));$('#refresh-trace').onclick=()=>refreshTrace().catch(e=>toast(e.message));$('#refresh-kernels').onclick=()=>refreshKernels().catch(e=>toast(e.message));$('#import-recipe').onclick=()=>importRecipe().catch(e=>toast(e.message));$$('[data-tab]').forEach(x=>x.onclick=()=>switchTab(x.dataset.tab));boot();
+$('#new-session').onclick=()=>createSession().catch(e=>toast(e.message));$('#composer').onsubmit=async e=>{e.preventDefault();const input=$('#prompt'),text=input.value.trim();if(!text)return;input.value='';try{await sendMessage(text)}catch(err){toast(err.message)}};$('#approve-tool').onclick=()=>approveTool().catch(e=>toast(e.message));$('#reject-tool').onclick=()=>rejectTool().catch(e=>toast(e.message));$('#refresh-profile').onclick=()=>refreshProfile().catch(e=>toast(e.message));$('#refresh-trace').onclick=()=>refreshTrace().catch(e=>toast(e.message));$('#refresh-kernels').onclick=()=>refreshKernels().catch(e=>toast(e.message));$('#import-recipe').onclick=()=>importRecipe().catch(e=>toast(e.message));$$('[data-tab]').forEach(x=>x.onclick=()=>switchTab(x.dataset.tab));boot();
From 609fb3c4ff93c113a6b6051f91c449572dfd07f5 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:43:25 +0530
Subject: [PATCH 104/168] radeon forge: test live asynchronous agent generation
---
test/test_radeon_forge_runtime.py | 44 ++++++++++++++++++++++++++++---
1 file changed, 40 insertions(+), 4 deletions(-)
diff --git a/test/test_radeon_forge_runtime.py b/test/test_radeon_forge_runtime.py
index 6db089af44cbf..03ca8b87fa48c 100644
--- a/test/test_radeon_forge_runtime.py
+++ b/test/test_radeon_forge_runtime.py
@@ -1,4 +1,6 @@
import tempfile
+import threading
+import time
import unittest
from pathlib import Path
@@ -15,13 +17,10 @@
class KernelEvidenceBackend:
@property
def name(self): return "kernel-evidence-local"
-
@property
def capabilities(self): return BackendCapabilities(prefix_cache=True, persistent_kv=True, kernel_metrics=True)
-
@property
def runtime_metadata(self): return {"runtime":"test", "architecture":"gfx1100", "model_family":"llama"}
-
def stream(self, request):
yield GenerationEvent("prefill", metrics={"wall_ms": 8.0, "gpu_ms": 5.0, "prompt_tokens": 24,
"prefix_reused_tokens": 12, "profile_kernel_events": 1})
@@ -35,10 +34,27 @@ def stream(self, request):
yield GenerationEvent("kernel", metrics={"name": "decode_gemv", "duration_ms": 0.90, "stage": "decode", "device": "AMD"})
yield GenerationEvent("kernel", metrics={"name": "decode_gemv", "duration_ms": 0.70, "stage": "decode", "device": "AMD"})
yield GenerationEvent("done", finish_reason="stop", metrics={"generated_tokens": 2})
-
def close(self): pass
+class BlockingBackend:
+ def __init__(self): self.first_token = threading.Event(); self.release = threading.Event()
+ @property
+ def name(self): return "blocking-local"
+ @property
+ def capabilities(self): return BackendCapabilities(streaming=True)
+ @property
+ def runtime_metadata(self): return {"runtime":"test", "architecture":"gfx1100", "model_family":"llama"}
+ def stream(self, request):
+ yield GenerationEvent("prefill", metrics={"wall_ms": 1.0, "prompt_tokens": 8, "prefix_reused_tokens": 0})
+ yield GenerationEvent("token", "partial ", metrics={"index":0, "stage":"first_token", "wall_ms":1.0})
+ self.first_token.set()
+ if not self.release.wait(2): raise TimeoutError("test did not release backend")
+ yield GenerationEvent("token", "complete", metrics={"index":1, "stage":"decode", "wall_ms":1.0})
+ yield GenerationEvent("done", finish_reason="stop", metrics={"generated_tokens":2})
+ def close(self): self.release.set()
+
+
class TestRadeonForgeRuntime(unittest.TestCase):
def test_kernel_evidence_survives_unified_trace_and_is_ranked_by_stage(self):
with tempfile.TemporaryDirectory() as directory:
@@ -62,6 +78,26 @@ def test_kernel_evidence_survives_unified_trace_and_is_ranked_by_stage(self):
self.assertEqual([event.name for event in kernel_events], ["rmsnorm_fused", "first_token_projection", "decode_gemv", "decode_gemv"])
engine.close()
+ def test_async_job_exposes_partial_generation(self):
+ with tempfile.TemporaryDirectory() as directory:
+ backend = BlockingBackend()
+ engine = ForgeEngine(backend, directory)
+ session = engine.create_session()
+ job = engine.submit_message(session.session_id, "stream locally")
+ self.assertTrue(backend.first_token.wait(1))
+ self.assertEqual(engine.jobs.snapshot(job["job_id"]).state, "running")
+ self.assertEqual(session.state, SessionState.GENERATING)
+ self.assertEqual(session.partial_output, "partial ")
+ self.assertTrue(any(event["kind"] == "token" for event in session.events_after(0)))
+ backend.release.set()
+ deadline = time.time() + 2
+ while engine.jobs.snapshot(job["job_id"]).state not in {"completed", "failed"} and time.time() < deadline: time.sleep(0.01)
+ self.assertEqual(engine.jobs.snapshot(job["job_id"]).state, "completed")
+ self.assertEqual(session.state, SessionState.COMPLETED)
+ self.assertEqual(session.partial_output, "")
+ self.assertEqual(session.messages[-1]["content"], "partial complete")
+ engine.close()
+
def test_permissioned_tool_round_trip(self):
responses = [
'
{"name":"read_file","arguments":{"path":"hello.txt"}} ',
From 5f48f5ad01001a0c33bcdf68af7a59e3f715ddfc Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:44:45 +0530
Subject: [PATCH 105/168] radeon forge: require complete compatibility evidence
for deployment
---
extra/radeon_forge/synthesis/tools.py | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/synthesis/tools.py b/extra/radeon_forge/synthesis/tools.py
index e58e7f27a24f3..0878ea756dc6c 100644
--- a/extra/radeon_forge/synthesis/tools.py
+++ b/extra/radeon_forge/synthesis/tools.py
@@ -8,7 +8,7 @@
from ..oracles.mockgpu import MockGPUOracle
from ..permissions import Action
from ..runtime.tools import ToolRegistry, ToolSpec
-from .hooks import HookRegistry, RuntimeFingerprint
+from .hooks import HookRegistry, RuntimeFingerprint, check_compatibility
from .portable import export_recipe_with_hook
from .recipe import RecipeLibrary
from .workspace import CandidateWorkspace
@@ -109,10 +109,16 @@ def list_active_hooks(self, args: Mapping[str, Any]) -> Any:
def activate_hook(self, args: Mapping[str, Any]) -> Any:
if self.hooks is None: raise RuntimeError("hook registry is unavailable")
+ candidate = self.workspace.load_candidate(str(args["candidate_id"]))
+ spec = self.workspace.load_spec(candidate.spec_id)
fingerprint = self._fingerprint()
- if not fingerprint.architecture and not bool(args.get("allow_unknown_runtime", False)):
- raise ValueError("runtime architecture is unknown; start the real local model backend before deployment")
- active = self.hooks.activate(str(args["candidate_id"]), fingerprint,
+ allow_unknown = bool(args.get("allow_unknown_runtime", False))
+ report = check_compatibility(spec, fingerprint)
+ if report.mismatches: raise ValueError("runtime is incompatible: " + "; ".join(report.mismatches))
+ if report.unknown and not allow_unknown:
+ raise ValueError("runtime compatibility is incomplete: missing " + ", ".join(report.unknown) +
+ ". Regenerate locally or explicitly approve an unknown-runtime deployment.")
+ active = self.hooks.activate(candidate.candidate_id, fingerprint,
str(args.get("reason", "Approved stage-specific local deployment")))
return asdict(active)
From 4b94d4bb43d6b966271ea94858968dbc2a68b06e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:46:20 +0530
Subject: [PATCH 106/168] radeon forge: add stage-aware empirical autotuning
---
extra/radeon_forge/synthesis/autotune.py | 112 +++++++++++++++++++++++
1 file changed, 112 insertions(+)
create mode 100644 extra/radeon_forge/synthesis/autotune.py
diff --git a/extra/radeon_forge/synthesis/autotune.py b/extra/radeon_forge/synthesis/autotune.py
new file mode 100644
index 0000000000000..a0c979188fc3b
--- /dev/null
+++ b/extra/radeon_forge/synthesis/autotune.py
@@ -0,0 +1,112 @@
+from __future__ import annotations
+
+import hashlib, itertools, json, os
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+from ..command_backend import CommandHarness
+from ..contracts import Candidate, Objective, WorkloadContract
+from ..ledger import ExperimentLedger
+from ..tuner import TuningSummary, successive_halving
+from .hooks import HookDescriptor
+from .workspace import CandidateWorkspace
+
+
+@dataclass(frozen=True)
+class SearchPlan:
+ axes: Mapping[str, tuple[int | float | str | bool, ...]]
+ budgets: tuple[int, ...] = (3, 10, 30)
+ reduction: int = 3
+ max_candidates: int = 128
+ timeout_seconds: int = 900
+
+ @classmethod
+ def from_mapping(cls, value: Mapping[str, Any]) -> SearchPlan:
+ raw = dict(value)
+ axes_value = raw.get("axes", {})
+ if not isinstance(axes_value, Mapping) or not axes_value: raise ValueError("autotune search requires a non-empty axes table")
+ axes: dict[str, tuple[int | float | str | bool, ...]] = {}
+ for name, values in axes_value.items():
+ if not isinstance(values, Sequence) or isinstance(values, (str, bytes, bytearray)) or not values:
+ raise ValueError(f"search axis {name!r} must be a non-empty array")
+ converted = tuple(values)
+ if not all(isinstance(item, (int, float, str, bool)) for item in converted):
+ raise ValueError(f"search axis {name!r} contains an unsupported value")
+ axes[str(name)] = converted
+ budgets = tuple(int(x) for x in raw.get("budgets", (3, 10, 30)))
+ if not budgets or any(x <= 0 for x in budgets): raise ValueError("autotune budgets must be positive")
+ reduction = int(raw.get("reduction", 3))
+ max_candidates = int(raw.get("max_candidates", 128))
+ timeout_seconds = int(raw.get("timeout_seconds", 900))
+ if reduction < 2 or max_candidates < 1 or timeout_seconds < 1: raise ValueError("invalid autotune search limits")
+ plan = cls(axes, budgets, reduction, max_candidates, timeout_seconds)
+ if plan.cardinality > max_candidates: raise ValueError(f"search has {plan.cardinality} candidates, maximum is {max_candidates}")
+ return plan
+
+ @property
+ def cardinality(self) -> int:
+ total = 1
+ for values in self.axes.values(): total *= len(values)
+ return total
+
+ def parameters(self) -> list[dict[str, int | float | str | bool]]:
+ names = tuple(self.axes)
+ return [dict(zip(names, values)) for values in itertools.product(*(self.axes[name] for name in names))]
+
+
+def _candidate_id(base_id: str, parameters: Mapping[str, Any]) -> str:
+ digest = hashlib.sha256(json.dumps(parameters, sort_keys=True, default=str).encode()).hexdigest()[:12]
+ return f"{base_id}-tune-{digest}"
+
+
+def _contract(spec) -> WorkloadContract:
+ acceptance = spec.metadata.get("recipe_acceptance", spec.metadata.get("acceptance", {}))
+ if not isinstance(acceptance, Mapping): acceptance = {}
+ objective_text = str(spec.metadata.get("search_objective", "p95_latency_us"))
+ try: objective = Objective(objective_text)
+ except ValueError: objective = Objective.P95_LATENCY_US
+ return WorkloadContract(
+ name=f"{spec.name}:{HookDescriptor.from_spec(spec).when.signature}", target=spec.target, objective=objective,
+ max_abs_error=float(acceptance.get("max_abs_error", acceptance.get("maximum_error", 1e-3))),
+ max_rel_error=float(acceptance.get("max_rel_error", 1e-3)),
+ max_vram_bytes=int(acceptance["max_vram_bytes"]) if acceptance.get("max_vram_bytes") is not None else None,
+ max_vgprs=int(acceptance["max_vgprs"]) if acceptance.get("max_vgprs") is not None else None,
+ max_lds_bytes=int(acceptance["max_lds_bytes"]) if acceptance.get("max_lds_bytes") is not None else None,
+ forbid_spills=bool(acceptance.get("forbid_spills", True)),
+ metadata={"hook": asdict(HookDescriptor.from_spec(spec)), "objective_text": spec.objective},
+ )
+
+
+def run_autotune(workspace: CandidateWorkspace, candidate_id: str, project_root: str | Path,
+ plan: SearchPlan, ledger_path: str | Path | None = None) -> tuple[Any, TuningSummary]:
+ """Tune one structural implementation without allowing speed to bypass correctness."""
+ record = workspace.load_candidate(candidate_id)
+ if record.status != "mockgpu_passed": raise ValueError("candidate must pass MockGPU before stage-specific W7900 autotuning")
+ spec = workspace.load_spec(record.spec_id)
+ if not spec.hardware_command: raise ValueError("spec has no hardware command for autotuning")
+ root = Path(project_root).resolve()
+ command = workspace.render_command(spec.hardware_command, spec, record, root)
+ cwd = str(spec.metadata.get("recipe_bundle", root))
+ environment = {"DEV": "AMD", "RADEON_FORGE_CANDIDATE": record.source_path,
+ "RADEON_FORGE_RECIPE_BUNDLE": str(spec.metadata.get("recipe_bundle", "")),
+ "RADEON_FORGE_EXECUTION_STAGES": ",".join(x.value for x in HookDescriptor.from_spec(spec).when.stages),
+ "PYTHONUNBUFFERED": "1"}
+ harness = CommandHarness(command, cwd=cwd, env={**os.environ, **environment}, timeout_seconds=plan.timeout_seconds)
+ candidates = [Candidate(_candidate_id(record.candidate_id, parameters), spec.name, parameters,
+ source_path=record.source_path, hypothesis=record.hypothesis, parent_id=record.candidate_id)
+ for parameters in plan.parameters()]
+ ledger = ExperimentLedger(ledger_path or (workspace.root / "autotune" / f"{record.candidate_id}.jsonl"))
+ summary = successive_halving(candidates, harness, _contract(spec), plan.budgets, plan.reduction, ledger)
+ evidence = {"search_plan": asdict(plan), "rounds": summary.rounds, "evaluated_trials": len(summary.evaluated),
+ "ledger": str(ledger.path), "execution_hook": asdict(HookDescriptor.from_spec(spec)),
+ "winner": summary.winner.to_dict() if summary.winner is not None else None,
+ "rejections": [{"candidate_id": result.candidate.candidate_id, "parameters": dict(result.candidate.parameters),
+ "reason": result.rejected_reason or result.correctness.reason,
+ "feasible": result.is_feasible(_contract(spec))} for result in summary.evaluated]}
+ if summary.winner is None:
+ updated = workspace.update(record.candidate_id, "autotune_failed", {"autotune": evidence})
+ else:
+ updated = workspace.update(record.candidate_id, "hardware_passed", {"autotune": evidence,
+ "selected_parameters": dict(summary.winner.candidate.parameters), "hardware": summary.winner.to_dict()})
+ return updated, summary
From 20d1189b912f61dae1ae677f3fd0b6b15c46b5bc Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:46:45 +0530
Subject: [PATCH 107/168] radeon forge: export empirical search contracts
---
extra/radeon_forge/synthesis/__init__.py | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/synthesis/__init__.py b/extra/radeon_forge/synthesis/__init__.py
index 2cb1df40b17a6..22dd8ae77ccd8 100644
--- a/extra/radeon_forge/synthesis/__init__.py
+++ b/extra/radeon_forge/synthesis/__init__.py
@@ -1,3 +1,4 @@
+from .autotune import SearchPlan, run_autotune
from .defaults import install_default_specs
from .hooks import (ActiveHook, CompatibilityReport, ExecutionContext, ExecutionStage, HookDescriptor, HookLayer, HookMode,
HookRegistry, RuntimeFingerprint, StagePredicate, check_compatibility)
@@ -8,5 +9,5 @@
__all__ = ["ActiveHook", "CandidateRecord", "CandidateWorkspace", "CompatibilityReport", "ExecutionContext", "ExecutionStage",
"ForgeRecipe", "HookDescriptor", "HookLayer", "HookMode", "HookRegistry", "InstalledRecipe", "KernelSpec",
- "OptimizationTools", "RecipeArtifact", "RecipeLibrary", "RuntimeFingerprint", "StagePredicate", "check_compatibility",
- "export_recipe", "export_recipe_with_hook", "install_default_specs"]
+ "OptimizationTools", "RecipeArtifact", "RecipeLibrary", "RuntimeFingerprint", "SearchPlan", "StagePredicate",
+ "check_compatibility", "export_recipe", "export_recipe_with_hook", "install_default_specs", "run_autotune"]
From 26ad9ba4d52bbba747f55f42f6cbd0d2d00ed6b3 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:47:36 +0530
Subject: [PATCH 108/168] radeon forge: expose empirical W7900 autotuning to
agents
---
extra/radeon_forge/synthesis/tools.py | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/synthesis/tools.py b/extra/radeon_forge/synthesis/tools.py
index 0878ea756dc6c..4b4ee8359c626 100644
--- a/extra/radeon_forge/synthesis/tools.py
+++ b/extra/radeon_forge/synthesis/tools.py
@@ -8,6 +8,7 @@
from ..oracles.mockgpu import MockGPUOracle
from ..permissions import Action
from ..runtime.tools import ToolRegistry, ToolSpec
+from .autotune import SearchPlan, run_autotune
from .hooks import HookRegistry, RuntimeFingerprint, check_compatibility
from .portable import export_recipe_with_hook
from .recipe import RecipeLibrary
@@ -76,9 +77,20 @@ def benchmark_hardware(self, args: Mapping[str, Any]) -> Any:
return self._run_hardware_command(candidate.candidate_id, spec.hardware_command, int(args.get("timeout_seconds", 900)),
"hardware", "hardware_passed", "hardware_failed")
+ def autotune_hardware(self, args: Mapping[str, Any]) -> Any:
+ candidate = self.workspace.load_candidate(str(args["candidate_id"]))
+ spec = self.workspace.load_spec(candidate.spec_id)
+ stored = spec.metadata.get("search", {})
+ if not isinstance(stored, Mapping): stored = {}
+ override = {key: args[key] for key in ("axes", "budgets", "reduction", "max_candidates", "timeout_seconds") if key in args}
+ plan = SearchPlan.from_mapping({**dict(stored), **override})
+ updated, summary = run_autotune(self.workspace, candidate.candidate_id, self.project_root, plan)
+ return {"candidate": asdict(updated), "winner": summary.winner.to_dict() if summary.winner else None,
+ "rounds": summary.rounds, "evaluated_trials": len(summary.evaluated)}
+
def validate_heldout(self, args: Mapping[str, Any]) -> Any:
candidate = self.workspace.load_candidate(str(args["candidate_id"]))
- if candidate.status != "hardware_passed": raise ValueError("candidate must pass the real hardware benchmark first")
+ if candidate.status != "hardware_passed": raise ValueError("candidate must pass the real hardware benchmark or autotuner first")
spec = self.workspace.load_spec(candidate.spec_id)
command = tuple(str(x) for x in spec.metadata.get("heldout_command", ()))
if not command: raise ValueError("spec has no held-out validation command")
@@ -132,6 +144,7 @@ def install(self, registry: ToolRegistry) -> None:
registry.register(ToolSpec("stage_kernel_candidate", "Write one disposable implementation for a typed kernel specification", {"type":"object","required":["spec_id","source","hypothesis"],"properties":{"spec_id":{"type":"string"},"source":{"type":"string"},"hypothesis":{"type":"string"},"parent_id":{"type":"string"}}}, Action.WRITE_GENERATED_SOURCE), self.stage_candidate)
registry.register(ToolSpec("validate_candidate_mockgpu", "Execute a generated AMD candidate through tinygrad's RDNA3 MockGPU semantic oracle", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"}}}, Action.COMPILE), self.validate_mockgpu)
registry.register(ToolSpec("benchmark_candidate_w7900", "Benchmark a MockGPU-passing candidate on the real local W7900", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"},"timeout_seconds":{"type":"integer"},"allow_without_mockgpu":{"type":"boolean"}}}, Action.BENCHMARK), self.benchmark_hardware)
+ registry.register(ToolSpec("autotune_candidate_w7900", "Empirically search a bounded parameter space for one MockGPU-passing implementation in its declared execution stages", {"type":"object","required":["candidate_id","axes"],"properties":{"candidate_id":{"type":"string"},"axes":{"type":"object"},"budgets":{"type":"array"},"reduction":{"type":"integer"},"max_candidates":{"type":"integer"},"timeout_seconds":{"type":"integer"}}}, Action.BENCHMARK), self.autotune_hardware)
registry.register(ToolSpec("validate_candidate_heldout", "Run a hardware-passing candidate on its held-out correctness and task-quality suite", {"type":"object","required":["candidate_id"],"properties":{"candidate_id":{"type":"string"},"timeout_seconds":{"type":"integer"}}}, Action.BENCHMARK), self.validate_heldout)
registry.register(ToolSpec("list_forge_recipes", "List portable installed optimization recipes", {"type":"object","properties":{}}), self.list_recipes)
registry.register(ToolSpec("inspect_forge_recipe", "Read the intent, invariants, execution-stage hook, oracle and artifact inventory of an installed optimization recipe", {"type":"object","required":["recipe_id"],"properties":{"recipe_id":{"type":"string"}}}), self.inspect_recipe)
From 40c914c5bbe087e31750fa19d1bbb19e70c40f6c Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:48:13 +0530
Subject: [PATCH 109/168] radeon forge: carry tuned parameters into active
runtime hooks
---
extra/radeon_forge/runtime/engine.py | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index c7bd043258ea0..6c367b0867e76 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -41,7 +41,13 @@ def runtime_fingerprint(self) -> RuntimeFingerprint:
return RuntimeFingerprint.from_mapping(metadata if isinstance(metadata, Mapping) else {})
def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, Any]:
- return {**self.hooks.runtime_metadata(), "runtime_fingerprint": asdict(self.runtime_fingerprint())}
+ metadata = self.hooks.runtime_metadata()
+ for item in metadata.get("active_hooks", []):
+ try:
+ record = self.optimization_workspace.load_candidate(str(item["candidate_id"]))
+ item["parameters"] = dict(record.evidence.get("selected_parameters", {}))
+ except Exception: item["parameters"] = {}
+ return {**metadata, "runtime_fingerprint": asdict(self.runtime_fingerprint())}
def create_session(self) -> AgentSession:
with self._lock:
From 1541d95c838d5ff5cb3d36374018d044012ff4b2 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:48:46 +0530
Subject: [PATCH 110/168] radeon forge: apply tuned parameters inside stage
hooks
---
extra/radeon_forge/backends/stage_hooks.py | 25 ++++++++++++++++++----
1 file changed, 21 insertions(+), 4 deletions(-)
diff --git a/extra/radeon_forge/backends/stage_hooks.py b/extra/radeon_forge/backends/stage_hooks.py
index ace5137e51c9c..1cc9f1c3929ce 100644
--- a/extra/radeon_forge/backends/stage_hooks.py
+++ b/extra/radeon_forge/backends/stage_hooks.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-import hashlib, importlib.util
+import hashlib, importlib.util, json
from dataclasses import asdict
from pathlib import Path
from typing import Any, Mapping, Sequence
@@ -29,6 +29,12 @@ def _matching_hooks(hooks: Sequence[Mapping[str, Any]], context: ExecutionContex
return sorted(selected.values(), key=lambda x: -int(x.get("descriptor", {}).get("priority", 0)))
+def _signature(hook: Mapping[str, Any]) -> str:
+ parameters = hook.get("parameters", {})
+ digest = hashlib.sha256(json.dumps(parameters, sort_keys=True, default=str).encode()).hexdigest()[:10]
+ return f"{hook.get('activation_id')}:{digest}"
+
+
class ModelStageHookRuntime:
"""Apply validated Python model hooks only in their declared execution states.
@@ -75,17 +81,26 @@ def _module(self, hook: Mapping[str, Any]) -> Any:
def apply(self, hooks: Sequence[Mapping[str, Any]], context: ExecutionContext) -> dict[str, Any]:
selected = [hook for hook in _matching_hooks(hooks, context)
if hook.get("descriptor", {}).get("adapter") == "python_transformer_block"]
- signature = tuple(str(hook.get("activation_id")) for hook in selected)
+ signature = tuple(_signature(hook) for hook in selected)
if signature == self._active_signature:
- return {"changed": False, "active": list(signature), "stage": context.stage.value}
+ return {"changed": False, "active": [str(hook.get("activation_id")) for hook in selected], "stage": context.stage.value}
self._reset()
if not selected: return {"changed": True, "active": [], "stage": context.stage.value, "baseline": True}
try:
layers = list(self._original_layers)
+ selected_parameters: dict[str, Mapping[str, Any]] = {}
for hook in selected:
descriptor = hook["descriptor"]
if descriptor.get("mode", "replace") != "replace": raise StageHookError("python_transformer_block currently supports replace mode only")
module = self._module(hook)
+ parameters = hook.get("parameters", {})
+ if not isinstance(parameters, Mapping): raise StageHookError("hook parameters must be a table")
+ parameters = dict(parameters)
+ setattr(module, "RADEON_FORGE_PARAMETERS", parameters)
+ configure = getattr(module, "configure", None)
+ if configure is not None:
+ if not callable(configure): raise StageHookError("optional configure attribute must be callable")
+ configure(parameters)
factory = getattr(module, "build_replacement", None)
if not callable(factory): raise StageHookError("hook must define build_replacement(original, layer_index, model, context)")
selector = descriptor.get("selector", {})
@@ -93,10 +108,12 @@ def apply(self, hooks: Sequence[Mapping[str, Any]], context: ExecutionContext) -
replacement = factory(layers[index], index, self.model, asdict(context))
if not callable(replacement): raise StageHookError(f"replacement for layer {index} is not callable")
layers[index] = replacement
+ selected_parameters[str(hook.get("activation_id"))] = parameters
self.model.layers = layers
if hasattr(self.model, "forward_jit") and self.model.forward_jit is not None: self.model.forward_jit = TinyJit(self.model.forward)
self._active_signature = signature
- return {"changed": True, "active": list(signature), "stage": context.stage.value, "baseline": False}
+ return {"changed": True, "active": [str(hook.get("activation_id")) for hook in selected],
+ "parameters": selected_parameters, "stage": context.stage.value, "baseline": False}
except Exception as exc:
self._reset()
return {"changed": True, "active": [], "stage": context.stage.value, "baseline": True,
From 584a51911bc4b3d134e3c8975b5f1bcef066eff0 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:49:18 +0530
Subject: [PATCH 111/168] radeon forge: test hard-gated stage autotuning
---
test/test_radeon_forge_autotune.py | 54 ++++++++++++++++++++++++++++++
1 file changed, 54 insertions(+)
create mode 100644 test/test_radeon_forge_autotune.py
diff --git a/test/test_radeon_forge_autotune.py b/test/test_radeon_forge_autotune.py
new file mode 100644
index 0000000000000..06b021084820b
--- /dev/null
+++ b/test/test_radeon_forge_autotune.py
@@ -0,0 +1,54 @@
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.synthesis.autotune import SearchPlan, run_autotune
+from extra.radeon_forge.synthesis.workspace import CandidateWorkspace, KernelSpec
+
+
+class TestStageAutotune(unittest.TestCase):
+ def test_fast_invalid_configuration_cannot_win(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ runner = root / "runner.py"
+ runner.write_text('''import json, os
+candidate = json.loads(os.environ["RADEON_FORGE_CANDIDATE_JSON"])
+tile = candidate["parameters"]["TILE"]
+budget = int(os.environ["RADEON_FORGE_BUDGET"])
+payload = {
+ "samples_us": ([1.0] if tile == 1 else [2.0]) * budget,
+ "correctness": {"passed": True, "max_abs_error": 0.0, "max_rel_error": 0.0, "checked_values": 128},
+ "resources": {"vgprs": 128 if tile == 1 else 64, "lds_bytes": 4096, "spilled_vgprs": 0, "spilled_sgprs": 0},
+ "compile_ok": True,
+ "stable": True
+}
+print(json.dumps(payload))
+''', encoding="utf-8")
+ workspace = CandidateWorkspace(root / "forge")
+ spec = workspace.save_spec(KernelSpec(
+ name="decode-search", operation="batch-one decode subgraph", target="gfx1100", invariants=("match reference",),
+ hardware_command=(sys.executable, str(runner)),
+ metadata={"recipe_acceptance":{"max_vgprs":96, "forbid_spills":True},
+ "hook":{"layer":"subgraph", "target":"decode.projection", "adapter":"request_metadata",
+ "when":{"stages":["decode"], "batch_sizes":[1]}, "exclusive_group":"decode-projection"}},
+ ))
+ candidate = workspace.create_candidate(spec.spec_id, "# parameterized candidate\n", "search tile size")
+ workspace.update(candidate.candidate_id, "mockgpu_passed", {"mockgpu":{"passed":True}})
+ updated, summary = run_autotune(workspace, candidate.candidate_id, root,
+ SearchPlan.from_mapping({"axes":{"TILE":[1,2]}, "budgets":[1,2], "reduction":2}))
+ self.assertIsNotNone(summary.winner)
+ self.assertEqual(summary.winner.candidate.parameters["TILE"], 2)
+ self.assertEqual(updated.status, "hardware_passed")
+ self.assertEqual(updated.evidence["selected_parameters"], {"TILE":2})
+ persisted = workspace.load_candidate(candidate.candidate_id)
+ self.assertEqual(persisted.evidence["selected_parameters"], {"TILE":2})
+ self.assertTrue(Path(persisted.evidence["autotune"]["ledger"]).is_file())
+
+ def test_search_space_is_bounded(self):
+ with self.assertRaisesRegex(ValueError, "maximum"):
+ SearchPlan.from_mapping({"axes":{"A":list(range(20)), "B":list(range(20))}, "max_candidates":128})
+
+
+if __name__ == "__main__": unittest.main()
From b1a95a9773c8485b3c39fb19a087419a43bca631 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:49:36 +0530
Subject: [PATCH 112/168] ci: cover stage autotuning tests
---
.github/workflows/radeon-forge.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/workflows/radeon-forge.yml b/.github/workflows/radeon-forge.yml
index 127778ae41ff9..275a466f5a122 100644
--- a/.github/workflows/radeon-forge.yml
+++ b/.github/workflows/radeon-forge.yml
@@ -33,3 +33,4 @@ jobs:
test.test_radeon_forge_recipe
test.test_radeon_forge_runtime
test.test_radeon_forge_hooks
+ test.test_radeon_forge_autotune
From 78b83c33f6715aeeceb2aedb743933dc315695f2 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:51:18 +0530
Subject: [PATCH 113/168] radeon forge: share stage-specific autotuning spaces
---
extra/radeon_forge/synthesis/portable.py | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/extra/radeon_forge/synthesis/portable.py b/extra/radeon_forge/synthesis/portable.py
index 86b99d49bed5b..509eb49da4a4c 100644
--- a/extra/radeon_forge/synthesis/portable.py
+++ b/extra/radeon_forge/synthesis/portable.py
@@ -30,7 +30,7 @@ def _append_table(lines: list[str], name: str, values: Mapping[str, Any]) -> Non
def export_recipe_with_hook(workspace: CandidateWorkspace, spec_id: str, output: str | Path,
candidate_id: str | None = None) -> Path:
- """Export one recipe while preserving both placement and execution-state applicability."""
+ """Export placement, execution-state applicability and empirical search knowledge."""
path = export_recipe(workspace, spec_id, output, candidate_id)
spec = workspace.load_spec(spec_id)
descriptor = HookDescriptor.from_spec(spec)
@@ -61,5 +61,19 @@ def export_recipe_with_hook(workspace: CandidateWorkspace, spec_id: str, output:
}
lines = path.read_text(encoding="utf-8").rstrip().splitlines()
_append_table(lines, "metadata.hook", hook)
+
+ # The search space is portable knowledge, not a mandatory implementation
+ # abstraction. A receiving agent may reuse, shrink or replace it, but keeping
+ # it next to the stage predicate makes prior hardware exploration reproducible.
+ search = spec.metadata.get("search", {})
+ if isinstance(search, Mapping) and search: _append_table(lines, "metadata.search", search)
+
+ selected_parameters = {}
+ if candidate_id is not None:
+ candidate = workspace.load_candidate(candidate_id)
+ selected_parameters = candidate.evidence.get("selected_parameters", {})
+ if isinstance(selected_parameters, Mapping) and selected_parameters:
+ _append_table(lines, "metadata.exported_winner", dict(selected_parameters))
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return path
From 1538592a943183cb3c9a7fdc03d7e3ae9f23b2c8 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:51:57 +0530
Subject: [PATCH 114/168] radeon forge: test portable stage autotuning
knowledge
---
test/test_radeon_forge_recipe.py | 19 ++++++++++++++++++-
1 file changed, 18 insertions(+), 1 deletion(-)
diff --git a/test/test_radeon_forge_recipe.py b/test/test_radeon_forge_recipe.py
index 00ac261ce9816..cadebef21c5fd 100644
--- a/test/test_radeon_forge_recipe.py
+++ b/test/test_radeon_forge_recipe.py
@@ -40,6 +40,15 @@ def _recipe_text(self, seed: str = "print('seed')\n") -> str:
min_context_tokens = 1024
prefix_cache = "hit"
+[metadata.search]
+budgets = [3, 10]
+reduction = 2
+max_candidates = 16
+
+[metadata.search.axes]
+WAVES = [2, 4]
+STAGES = [1, 2]
+
[oracle]
mockgpu_command = ["python3", "{{candidate}}", "--bundle", "{{bundle}}"]
hardware_command = ["python3", "{{candidate}}", "--benchmark"]
@@ -79,6 +88,7 @@ def test_install_is_content_addressed_and_seed_is_unverified(self):
self.assertEqual([x.value for x in descriptor.when.stages], ["decode"])
self.assertEqual(descriptor.when.min_context_tokens, 1024)
self.assertEqual(descriptor.when.prefix_cache, "hit")
+ self.assertEqual(spec.metadata["search"]["axes"]["WAVES"], [2, 4])
rendered = workspace.render_command(spec.mockgpu_command, spec, candidate, root)
self.assertEqual(rendered[1], candidate.source_path)
self.assertEqual(rendered[3], installed.bundle_root)
@@ -90,7 +100,7 @@ def test_rejects_path_traversal(self):
path.write_text(text, encoding="utf-8")
with self.assertRaises(ValueError): ForgeRecipe.load(path)
- def test_export_import_round_trip_preserves_contract_cache_and_stage_hook(self):
+ def test_export_import_round_trip_preserves_contract_cache_stage_and_search(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source_workspace = CandidateWorkspace(root / "source")
@@ -100,6 +110,8 @@ def test_export_import_round_trip_preserves_contract_cache_and_stage_hook(self):
mockgpu_command=("python3", "{candidate}"), hardware_command=("python3", "{candidate}", "--benchmark"),
metadata={"recipe_agent_brief":"Use the oracle as the contract and freely rewrite the implementation.",
"recipe_compatibility":{"architecture":"gfx1100"}, "recipe_acceptance":{"max_error":1e-6},
+ "search":{"axes":{"WAVES":[2,4], "UNROLL":[1,2]}, "budgets":[3,10,30], "reduction":2,
+ "max_candidates":16},
"hook":{"layer":"transformer_block", "target":"llama.decode.block", "mode":"replace",
"adapter":"python_transformer_block", "selector":{"indices":[0,1]},
"when":{"stages":["decode"], "batch_sizes":[1], "min_generated_token_index":1,
@@ -108,12 +120,15 @@ def test_export_import_round_trip_preserves_contract_cache_and_stage_hook(self):
)
source_workspace.save_spec(spec)
candidate = source_workspace.create_candidate(spec.spec_id, "print('candidate')\n", "measured decode implementation")
+ source_workspace.update(candidate.candidate_id, "hardware_passed", {"selected_parameters":{"WAVES":4, "UNROLL":2}})
exported = export_recipe_with_hook(source_workspace, spec.spec_id, root / "shared.forge.toml", candidate.candidate_id)
loaded = ForgeRecipe.load(exported)
self.assertEqual(loaded.target, "gfx1100")
self.assertEqual(loaded.invariants, spec.invariants)
self.assertEqual(loaded.metadata["hook"]["when"]["stages"], ["decode"])
+ self.assertEqual(loaded.metadata["search"]["axes"]["WAVES"], [2, 4])
+ self.assertEqual(loaded.metadata["exported_winner"], {"WAVES":4, "UNROLL":2})
destination = CandidateWorkspace(root / "destination")
installed = RecipeLibrary(destination).install(loaded)
imported = destination.load_candidate(installed.seed_candidate_id)
@@ -125,6 +140,8 @@ def test_export_import_round_trip_preserves_contract_cache_and_stage_hook(self):
self.assertEqual([x.value for x in descriptor.when.stages], ["decode"])
self.assertEqual(descriptor.when.min_generated_token_index, 1)
self.assertEqual(descriptor.when.conditions["resume_after_tool"], False)
+ self.assertEqual(installed_spec.metadata["search"]["axes"]["UNROLL"], [1, 2])
+ self.assertEqual(installed_spec.metadata["exported_winner"]["WAVES"], 4)
def test_base_export_remains_valid_without_hook_extension(self):
with tempfile.TemporaryDirectory() as directory:
From a3dcf72985b02733ba015b5fcf060d521fd4bbe1 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:53:50 +0530
Subject: [PATCH 115/168] radeon forge: require transition oracles for stateful
hooks
---
extra/radeon_forge/synthesis/deployment.py | 43 ++++++++++++++++++++++
1 file changed, 43 insertions(+)
create mode 100644 extra/radeon_forge/synthesis/deployment.py
diff --git a/extra/radeon_forge/synthesis/deployment.py b/extra/radeon_forge/synthesis/deployment.py
new file mode 100644
index 0000000000000..c1b54da587463
--- /dev/null
+++ b/extra/radeon_forge/synthesis/deployment.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from .hooks import (ActiveHook, HookActivationError, HookDescriptor, HookLayer, HookRegistry, RuntimeFingerprint)
+from .workspace import CandidateWorkspace
+
+
+STATEFUL_LAYERS = frozenset({HookLayer.MODEL, HookLayer.TRANSFORMER_BLOCK, HookLayer.KV_CACHE})
+RUNTIME_ADAPTERS = frozenset({"python_transformer_block"})
+
+
+class SafeHookRegistry(HookRegistry):
+ """Deployment policy layered over the generic stage resolver.
+
+ The generic registry is useful for tests and future adapters. The engine uses
+ this stricter registry so metadata-only or unimplemented adapters cannot be
+ presented as active optimizations, and stateful phase changes cannot deploy
+ without a held-out transition oracle.
+ """
+ SUPPORTED_ADAPTERS = RUNTIME_ADAPTERS
+
+ def __init__(self, workspace: CandidateWorkspace): super().__init__(workspace)
+
+ def activate(self, candidate_id: str, fingerprint: RuntimeFingerprint, reason: str) -> ActiveHook:
+ candidate = self.workspace.load_candidate(candidate_id)
+ spec = self.workspace.load_spec(candidate.spec_id)
+ descriptor = HookDescriptor.from_spec(spec)
+ if descriptor.adapter not in self.SUPPORTED_ADAPTERS:
+ raise HookActivationError(
+ f"runtime adapter {descriptor.adapter!r} is not executable in this engine build; "
+ "the recipe remains usable as profiling/search knowledge"
+ )
+ if descriptor.layer in STATEFUL_LAYERS:
+ heldout = tuple(spec.metadata.get("heldout_command", ()))
+ if not heldout:
+ raise HookActivationError(
+ f"{descriptor.layer.value} hooks require a held-out phase-transition oracle before deployment "
+ "(for example prefill -> first_token -> decode and tool-resume continuity)"
+ )
+ if candidate.status not in {"heldout_passed", "accepted"}:
+ raise HookActivationError(
+ f"stateful hook candidate status {candidate.status!r} has not passed its phase-transition oracle"
+ )
+ return super().activate(candidate_id, fingerprint, reason)
From 744e0885158991f71a7aa20a77d986f895b27522 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:54:05 +0530
Subject: [PATCH 116/168] radeon forge: export safe deployment policy
---
extra/radeon_forge/synthesis/__init__.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/synthesis/__init__.py b/extra/radeon_forge/synthesis/__init__.py
index 22dd8ae77ccd8..314e1a20dc344 100644
--- a/extra/radeon_forge/synthesis/__init__.py
+++ b/extra/radeon_forge/synthesis/__init__.py
@@ -1,5 +1,6 @@
from .autotune import SearchPlan, run_autotune
from .defaults import install_default_specs
+from .deployment import RUNTIME_ADAPTERS, STATEFUL_LAYERS, SafeHookRegistry
from .hooks import (ActiveHook, CompatibilityReport, ExecutionContext, ExecutionStage, HookDescriptor, HookLayer, HookMode,
HookRegistry, RuntimeFingerprint, StagePredicate, check_compatibility)
from .portable import export_recipe_with_hook
@@ -9,5 +10,6 @@
__all__ = ["ActiveHook", "CandidateRecord", "CandidateWorkspace", "CompatibilityReport", "ExecutionContext", "ExecutionStage",
"ForgeRecipe", "HookDescriptor", "HookLayer", "HookMode", "HookRegistry", "InstalledRecipe", "KernelSpec",
- "OptimizationTools", "RecipeArtifact", "RecipeLibrary", "RuntimeFingerprint", "SearchPlan", "StagePredicate",
- "check_compatibility", "export_recipe", "export_recipe_with_hook", "install_default_specs", "run_autotune"]
+ "OptimizationTools", "RUNTIME_ADAPTERS", "RecipeArtifact", "RecipeLibrary", "RuntimeFingerprint", "STATEFUL_LAYERS",
+ "SafeHookRegistry", "SearchPlan", "StagePredicate", "check_compatibility", "export_recipe", "export_recipe_with_hook",
+ "install_default_specs", "run_autotune"]
From 1fc7d5911a7224b66cdc4b5db6ef94b73b06fd14 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:54:37 +0530
Subject: [PATCH 117/168] radeon forge: use transition-safe deployment registry
---
extra/radeon_forge/runtime/engine.py | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index 6c367b0867e76..f0af8af0dc04e 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -7,7 +7,7 @@
from ..permissions import PermissionController
from ..profiling.report import build_profile_report
-from ..synthesis import CandidateWorkspace, HookRegistry, OptimizationTools, RuntimeFingerprint, install_default_specs
+from ..synthesis import CandidateWorkspace, OptimizationTools, RuntimeFingerprint, SafeHookRegistry, install_default_specs
from .backend import InferenceBackend
from .jobs import LocalJobManager
from .session import AgentSession
@@ -28,7 +28,7 @@ def __init__(self, backend: InferenceBackend, workspace: str | Path, system_prom
WorkspaceTools(self.workspace).install(self.tools)
self.optimization_workspace = CandidateWorkspace(self.workspace / ".radeon_forge")
install_default_specs(self.optimization_workspace)
- self.hooks = HookRegistry(self.optimization_workspace)
+ self.hooks = SafeHookRegistry(self.optimization_workspace)
self.optimization_tools = OptimizationTools(self.optimization_workspace, self.workspace, self.hooks, self.runtime_fingerprint)
self.optimization_tools.install(self.tools)
self.jobs = LocalJobManager()
@@ -96,6 +96,7 @@ def optimization_state(self) -> dict[str, Any]:
"candidates": [asdict(x) for x in self.optimization_workspace.candidates()],
"recipes": [asdict(x) for x in self.optimization_tools.recipes.installed()],
"active_hooks": [asdict(x) for x in self.hooks.active()],
- "runtime_fingerprint": asdict(self.runtime_fingerprint())}
+ "runtime_fingerprint": asdict(self.runtime_fingerprint()),
+ "runtime_adapters": sorted(self.hooks.SUPPORTED_ADAPTERS)}
def close(self) -> None: self.backend.close()
From f482c610e917b8520b7ed919cd2f8644a7f8f11e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:55:22 +0530
Subject: [PATCH 118/168] radeon forge: test executable adapters and
transition-oracle deployment
---
test/test_radeon_forge_hooks.py | 44 ++++++++++++++++++++++++++++++---
1 file changed, 41 insertions(+), 3 deletions(-)
diff --git a/test/test_radeon_forge_hooks.py b/test/test_radeon_forge_hooks.py
index 426cc452d91ba..6d86c6cc3d3d2 100644
--- a/test/test_radeon_forge_hooks.py
+++ b/test/test_radeon_forge_hooks.py
@@ -4,8 +4,9 @@
from pathlib import Path
from extra.radeon_forge.backends.stage_hooks import ModelStageHookRuntime
-from extra.radeon_forge.synthesis.hooks import (ExecutionContext, ExecutionStage, HookRegistry, RuntimeFingerprint,
- StagePredicate)
+from extra.radeon_forge.synthesis import SafeHookRegistry
+from extra.radeon_forge.synthesis.hooks import (ExecutionContext, ExecutionStage, HookActivationError, HookRegistry,
+ RuntimeFingerprint, StagePredicate)
from extra.radeon_forge.synthesis.workspace import CandidateWorkspace, KernelSpec
@@ -32,7 +33,7 @@ def test_predicate_distinguishes_execution_state_and_workload(self):
generated_token_index=0, prefix_reused_tokens=256,
attributes={"resume_after_tool": True})))
- def test_prefill_and_decode_implementations_can_coexist(self):
+ def test_prefill_and_decode_implementations_can_coexist_in_generic_resolver(self):
with tempfile.TemporaryDirectory() as directory:
workspace = CandidateWorkspace(directory)
common = {"layer": "transformer_block", "target": "llama.block", "adapter": "python_transformer_block",
@@ -56,6 +57,43 @@ def test_prefill_and_decode_implementations_can_coexist(self):
self.assertEqual(registry.resolve(ExecutionContext(ExecutionStage.DECODE, generated_token_index=2))[0].candidate_id,
decode.candidate_id)
+ def test_engine_registry_rejects_unimplemented_metadata_adapter(self):
+ with tempfile.TemporaryDirectory() as directory:
+ workspace = CandidateWorkspace(directory)
+ spec = workspace.save_spec(KernelSpec("advisory-kernel", "kernel idea", target="gfx1100",
+ invariants=("match reference",), metadata={"hook":{"layer":"kernel", "target":"gemv",
+ "adapter":"request_metadata", "when":{"stages":["decode"]}}}))
+ candidate = workspace.create_candidate(spec.spec_id, "# advisory only\n", "prior kernel schedule")
+ workspace.update(candidate.candidate_id, "hardware_passed", {})
+ registry = SafeHookRegistry(workspace)
+ with self.assertRaisesRegex(HookActivationError, "not executable"):
+ registry.activate(candidate.candidate_id, RuntimeFingerprint(architecture="gfx1100"), "deploy")
+
+ def test_stateful_hook_requires_phase_transition_oracle(self):
+ with tempfile.TemporaryDirectory() as directory:
+ workspace = CandidateWorkspace(directory)
+ hook = {"layer":"transformer_block", "target":"llama.block", "adapter":"python_transformer_block",
+ "when":{"stages":["decode"]}}
+ no_transition = workspace.save_spec(KernelSpec("no-transition", "decode block", target="gfx1100",
+ invariants=("preserve KV state",), metadata={"hook":hook}))
+ first = workspace.create_candidate(no_transition.spec_id, "def build_replacement(*args): return args[0]\n", "decode")
+ workspace.update(first.candidate_id, "hardware_passed", {})
+ registry = SafeHookRegistry(workspace)
+ fingerprint = RuntimeFingerprint(architecture="gfx1100", runtime="tinygrad", model_family="llama")
+ with self.assertRaisesRegex(HookActivationError, "phase-transition oracle"):
+ registry.activate(first.candidate_id, fingerprint, "deploy")
+
+ with_transition = workspace.save_spec(KernelSpec("with-transition", "decode block", target="gfx1100",
+ invariants=("preserve KV state",), metadata={"hook":hook,
+ "heldout_command":["python3", "validate_prefill_decode_transition.py"]}))
+ second = workspace.create_candidate(with_transition.spec_id, "def build_replacement(*args): return args[0]\n", "decode")
+ workspace.update(second.candidate_id, "hardware_passed", {})
+ with self.assertRaisesRegex(HookActivationError, "has not passed"):
+ registry.activate(second.candidate_id, fingerprint, "deploy")
+ workspace.update(second.candidate_id, "heldout_passed", {"heldout":{"transition":"prefill->first_token->decode"}})
+ active = registry.activate(second.candidate_id, fingerprint, "transition oracle passed")
+ self.assertEqual(active.candidate_id, second.candidate_id)
+
def test_model_adapter_rolls_back_bad_stage_hook(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
From 79b58f1bec5f2304ee168bef861c08db5bf06fe6 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:57:46 +0530
Subject: [PATCH 119/168] radeon forge: add batched prefill and exact KV reuse
accounting
---
.../backends/tinygrad_llama_worker.py | 131 +++++++++++-------
1 file changed, 82 insertions(+), 49 deletions(-)
diff --git a/extra/radeon_forge/backends/tinygrad_llama_worker.py b/extra/radeon_forge/backends/tinygrad_llama_worker.py
index 2bba48fbfbeb7..c674471fb18ae 100644
--- a/extra/radeon_forge/backends/tinygrad_llama_worker.py
+++ b/extra/radeon_forge/backends/tinygrad_llama_worker.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-import argparse, hashlib, json, sys, time
+import argparse, hashlib, json, subprocess, sys, time
from pathlib import Path
from typing import Any, Callable, Mapping
@@ -21,25 +21,18 @@ def send(payload):
sys.stdout.flush()
-def _name(value: Any) -> str:
- return str(getattr(value, "display_name", value))
+def _name(value: Any) -> str: return str(getattr(value, "display_name", value))
def _collect_profile_events(start: int) -> list[dict[str, Any]]:
- """Flatten tinygrad device profile ranges into portable kernel evidence.
-
- Timestamps are device-local, so only durations and ordering are exported.
- Forge wall-clock spans remain the cross-layer timeline authority.
- """
+ """Flatten tinygrad device profile ranges into portable kernel evidence."""
raw = list(Compiled.profile_events[start:])
del Compiled.profile_events[start:]
ret: list[dict[str, Any]] = []
for event in raw:
if hasattr(event, "ents") and hasattr(event, "sigs"):
for entry in event.ents:
- try:
- st, en = event.sigs[entry.st_id], event.sigs[entry.en_id]
- duration_us = float(en - st)
+ try: duration_us = float(event.sigs[entry.en_id] - event.sigs[entry.st_id])
except Exception: continue
device = str(getattr(entry, "device", "UNKNOWN"))
if device in {"CPU", "TINY"} or duration_us < 0: continue
@@ -67,19 +60,17 @@ def _profiled(fn: Callable[[], Any]) -> tuple[Any, list[dict[str, Any]]]:
return result, _collect_profile_events(start)
-def _emit_kernel_events(events: list[dict[str, Any]], *, stage: str, token_index: int | None = None,
- prompt_position: int | None = None) -> tuple[int, bool]:
+def _emit_kernel_events(events: list[dict[str, Any]], *, stage: str, token_index: int | None = None) -> tuple[int, bool]:
truncated = len(events) > MAX_PROFILE_EVENTS_PER_PHASE
emitted = events[:MAX_PROFILE_EVENTS_PER_PHASE]
for sequence, event in enumerate(emitted):
metrics = {**event, "stage": stage, "sequence": sequence}
if token_index is not None: metrics["token_index"] = token_index
- if prompt_position is not None: metrics["prompt_position"] = prompt_position
send({"kind": "kernel", "metrics": metrics})
return len(emitted), truncated
-def _model_identity(path: Path, size: str, quantize: str | None) -> str:
+def _weight_identity(path: Path, size: str, quantize: str | None) -> str:
try:
stat = path.stat()
identity = f"{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}:{size}:{quantize}"
@@ -87,12 +78,53 @@ def _model_identity(path: Path, size: str, quantize: str | None) -> str:
return hashlib.sha256(identity.encode()).hexdigest()
+def _shape(value: Any) -> list[int | str]:
+ try: return [int(item) for item in value.shape]
+ except Exception: return [str(getattr(value, "shape", "unknown"))]
+
+
+def _architecture_identity(model: Any, size: str, quantize: str | None) -> tuple[dict[str, Any], str]:
+ first = model.layers[0] if getattr(model, "layers", None) else None
+ attention = getattr(first, "attention", None)
+ feed_forward = getattr(first, "feed_forward", None)
+ payload = {
+ "family": "llama", "size_label": size, "quantize": quantize or "model_default",
+ "layers": len(getattr(model, "layers", ())), "max_context": int(getattr(model, "max_context", 0)),
+ "n_heads": int(getattr(attention, "n_heads", 0)), "n_kv_heads": int(getattr(attention, "n_kv_heads", 0)),
+ "head_dim": int(getattr(attention, "head_dim", 0)),
+ "embedding_shape": _shape(getattr(getattr(model, "tok_embeddings", None), "weight", None)),
+ "output_shape": _shape(getattr(getattr(model, "output", None), "weight", None)),
+ "ffn_w1_shape": _shape(getattr(getattr(feed_forward, "w1", None), "weight", None)),
+ }
+ return payload, hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
+
+
+def _git_revision() -> str:
+ try:
+ root = Path(__file__).resolve().parents[3]
+ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True, stderr=subprocess.DEVNULL).strip()
+ except Exception: return "unknown"
+
+
def _hook_event(runtime: ModelStageHookRuntime, hooks: list[Mapping[str, Any]], context: ExecutionContext) -> None:
result = runtime.apply(hooks, context)
if result.get("changed") or result.get("rolled_back"):
send({"kind": "hook", "metrics": {**result, "context": context.flattened()}})
+def _prefill_without_output_head(model: Any, token_ids: list[int], start_pos: int, device: str) -> None:
+ """Populate KV state for a prompt chunk without projecting every prompt token to vocabulary logits."""
+ if not token_ids: return
+ tokens = Tensor([token_ids], device=device)
+ _, seqlen = tokens.shape
+ h = model.tok_embeddings(tokens).contiguous()
+ freqs_cis = model.freqs_cis.cast(h.dtype)[:, start_pos:start_pos+seqlen, :, :, :]
+ mask = (Tensor.full((1, 1, seqlen, start_pos+seqlen), float("-inf"), dtype=h.dtype, device=h.device).triu(start_pos+1)
+ if model.max_context != 0 and seqlen > 1 else None)
+ for layer in model.layers: h = layer(h, start_pos, freqs_cis, mask)
+ h.realize()
+
+
def main() -> None:
parser = argparse.ArgumentParser(description="Persistent tinygrad Llama backend for Radeon Forge")
parser.add_argument("--model", type=Path, required=True)
@@ -112,6 +144,7 @@ def main() -> None:
device = Device.DEFAULT
model = build_transformer(args.model, model_size=args.size, quantize=args.quantize, device=device, max_context=args.max_context)
param_bytes = sum(x.nbytes() for x in get_parameters(model))
+ architecture_data, architecture_hash = _architecture_identity(model, args.size, args.quantize)
hook_runtime = ModelStageHookRuntime(model)
device_obj = Device[device]
architecture = str(getattr(device_obj, "arch", ""))
@@ -125,10 +158,11 @@ def encode_message(message) -> list[int]:
return encode_role(str(message.get("role", "user"))) + tokenizer.encode(content.strip()) + [tokenizer.special_tokens["<|eot_id|>"]]
active_session: str | None = None
- active_tokens: list[int] = []
+ cached_tokens: list[int] = [] # only tokens whose KV entries are actually materialized
send({"kind": "ready", "name": f"tinygrad-llama-{args.size}", "device": str(device), "gpu": str(device),
- "architecture": architecture, "runtime": "tinygrad", "runtime_revision": "radeon-forge",
- "model": str(args.model), "model_family": "llama", "model_hash": _model_identity(args.model, args.size, args.quantize),
+ "architecture": architecture, "runtime": "tinygrad", "runtime_revision": _git_revision(),
+ "model": str(args.model), "model_family": "llama", "model_hash": _weight_identity(args.model, args.size, args.quantize),
+ "model_architecture_hash": architecture_hash, "model_architecture": architecture_data,
"dtype": args.quantize or "model_default", "shapes": {"batch": 1, "max_context": args.max_context},
"parameter_bytes": param_bytes, "capabilities": {"streaming": True, "structured_tools": False,
"prefix_cache": True, "persistent_kv": True, "kernel_metrics": True, "cancellation": False}})
@@ -156,41 +190,35 @@ def encode_message(message) -> list[int]:
if not messages or messages[-1].get("role") != "assistant": prompt += encode_role("assistant")
if len(prompt) >= args.max_context: raise ValueError(f"prompt has {len(prompt)} tokens, max context is {args.max_context}")
+ if active_session != session_id:
+ active_session, cached_tokens = session_id, []
common = 0
- if active_session == session_id:
- for old, new in zip(active_tokens, prompt):
- if old != new: break
- common += 1
- active_session = session_id
+ for old, new in zip(cached_tokens, prompt):
+ if old != new: break
+ common += 1
+
prefill_context = ExecutionContext(ExecutionStage.PREFILL, batch_size=1, prompt_tokens=len(prompt),
context_tokens=max(0, len(prompt)-1), generated_token_index=-1, prefix_reused_tokens=common,
- tool_round=tool_round, warm=bool(active_tokens), attributes={"resume_after_tool": resume_after_tool, "session_id": session_id})
+ tool_round=tool_round, warm=bool(cached_tokens), attributes={"resume_after_tool": resume_after_tool, "session_id": session_id})
_hook_event(hook_runtime, hooks, prefill_context)
+ prefill_ids = list(prompt[common:-1])
+ GlobalCounters.reset()
prefill_start = time.perf_counter_ns()
- prefill_gpu_s, prefill_kernels, prefill_mem, prefill_ops = 0.0, 0, 0, 0
- prefill_profile: list[dict[str, Any]] = []
- for position in range(common, len(prompt) - 1):
- GlobalCounters.reset()
- _, profile = _profiled(lambda position=position: model(Tensor([[prompt[position]]], device=device), position, 0.0, 0, 0.0, 0.0, 0.0).realize())
- for event in profile: event["prompt_position"] = position
- prefill_profile.extend(profile)
- prefill_gpu_s += GlobalCounters.time_sum_s
- prefill_kernels += GlobalCounters.kernel_count
- prefill_mem += GlobalCounters.global_mem
- prefill_ops += GlobalCounters.global_ops
+ _, prefill_profile = _profiled(lambda: _prefill_without_output_head(model, prefill_ids, common, device))
prefill_wall_ms = (time.perf_counter_ns() - prefill_start) / 1e6
- active_tokens = list(prompt)
- send({"kind": "prefill", "metrics": {"wall_ms": prefill_wall_ms, "gpu_ms": prefill_gpu_s * 1e3,
- "prompt_tokens": len(prompt), "prefix_reused_tokens": common, "new_prompt_tokens": max(0, len(prompt) - 1 - common),
- "kernel_count": prefill_kernels, "global_mem_bytes": prefill_mem, "global_ops": prefill_ops,
- "profile_kernel_events": len(prefill_profile), "resume_after_tool": resume_after_tool}})
- prefill_truncated = len(prefill_profile) > MAX_PROFILE_EVENTS_PER_PHASE
- for sequence, event in enumerate(prefill_profile[:MAX_PROFILE_EVENTS_PER_PHASE]):
- send({"kind": "kernel", "metrics": {**event, "stage": "prefill", "sequence": sequence}})
+ prefill_gpu_ms = GlobalCounters.time_sum_s * 1e3
+ cached_tokens = list(prompt[:-1])
+ send({"kind": "prefill", "metrics": {"wall_ms": prefill_wall_ms, "gpu_ms": prefill_gpu_ms,
+ "prompt_tokens": len(prompt), "prefix_reused_tokens": common, "new_prompt_tokens": len(prefill_ids),
+ "prefill_chunk_tokens": len(prefill_ids), "prefix_cache_hit_ratio": common / max(1, len(prompt)-1),
+ "kernel_count": GlobalCounters.kernel_count, "global_mem_bytes": GlobalCounters.global_mem,
+ "global_ops": GlobalCounters.global_ops, "profile_kernel_events": len(prefill_profile),
+ "resume_after_tool": resume_after_tool, "output_head_skipped": True}})
+ emitted, prefill_truncated = _emit_kernel_events(prefill_profile, stage="prefill")
if prefill_truncated:
send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": "prefill",
- "captured": MAX_PROFILE_EVENTS_PER_PHASE, "available": len(prefill_profile)}})
+ "captured": emitted, "available": len(prefill_profile)}})
start_pos, last_tok = len(prompt) - 1, prompt[-1]
generated = 0
@@ -202,25 +230,30 @@ def encode_message(message) -> list[int]:
_hook_event(hook_runtime, hooks, decode_context)
GlobalCounters.reset()
wall_start = time.perf_counter_ns()
- tok, profile = _profiled(lambda: model(Tensor([[last_tok]], device=device), start_pos, temperature, 0, 0.0, 0.0, 0.0).item())
+ input_tok = last_tok
+ tok, profile = _profiled(lambda: model(Tensor([[input_tok]], device=device), start_pos, temperature, 0, 0.0, 0.0, 0.0).item())
wall_ms = (time.perf_counter_ns() - wall_start) / 1e6
gpu_ms = GlobalCounters.time_sum_s * 1e3
+ cached_tokens.append(input_tok) # this model invocation materialized input_tok's KV entry
start_pos += 1
last_tok = tok
if tok in tokenizer.stop_tokens:
- send({"kind": "done", "finish_reason": "stop", "metrics": {"generated_tokens": generated}})
+ send({"kind": "done", "finish_reason": "stop", "metrics": {"generated_tokens": generated,
+ "materialized_kv_tokens": len(cached_tokens)}})
break
- active_tokens.append(tok)
generated += 1
send({"kind": "token", "text": tokenizer.decode([tok]), "metrics": {"index": index, "stage": stage.value,
"wall_ms": wall_ms, "gpu_ms": gpu_ms, "kernel_count": GlobalCounters.kernel_count,
"global_mem_bytes": GlobalCounters.global_mem, "global_ops": GlobalCounters.global_ops,
- "profile_kernel_events": len(profile), "parameter_bandwidth_gbs": (param_bytes / max(GlobalCounters.time_sum_s, 1e-12)) / 1e9}})
+ "profile_kernel_events": len(profile), "context_tokens": start_pos,
+ "parameter_bandwidth_gbs": (param_bytes / max(GlobalCounters.time_sum_s, 1e-12)) / 1e9}})
emitted, truncated = _emit_kernel_events(profile, stage=stage.value, token_index=index)
if truncated:
send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": stage.value, "token_index": index,
"captured": emitted, "available": len(profile)}})
- else: send({"kind": "done", "finish_reason": "length", "metrics": {"generated_tokens": generated}})
+ else:
+ send({"kind": "done", "finish_reason": "length", "metrics": {"generated_tokens": generated,
+ "materialized_kv_tokens": len(cached_tokens), "pending_uncached_output_token": True}})
except Exception as exc:
send({"kind": "error", "error": str(exc), "error_type": type(exc).__name__})
From 7b02494ac0ba685af67b72034a539baaf1a37261 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:58:08 +0530
Subject: [PATCH 120/168] radeon forge: add exact KV materialization ledger
---
extra/radeon_forge/backends/kv_state.py | 38 +++++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 extra/radeon_forge/backends/kv_state.py
diff --git a/extra/radeon_forge/backends/kv_state.py b/extra/radeon_forge/backends/kv_state.py
new file mode 100644
index 0000000000000..0b4a1a2adcc08
--- /dev/null
+++ b/extra/radeon_forge/backends/kv_state.py
@@ -0,0 +1,38 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Sequence
+
+
+@dataclass
+class KVReuseLedger:
+ """Tracks the only prefix that is safe to reuse from one resident KV cache.
+
+ Generated output is not reusable until it has been fed back through the model
+ as a decode input. This distinction matters at length stops and tool
+ boundaries: emitted text and materialized KV state are not always identical.
+ """
+ active_session: str | None = None
+ cached_tokens: list[int] = field(default_factory=list)
+
+ def begin(self, session_id: str, prompt: Sequence[int]) -> int:
+ if self.active_session != session_id:
+ self.active_session = session_id
+ self.cached_tokens.clear()
+ common = 0
+ for old, new in zip(self.cached_tokens, prompt):
+ if old != new: break
+ common += 1
+ return common
+
+ def commit_prefill(self, prompt_without_pending_decode_token: Sequence[int]) -> None:
+ self.cached_tokens = list(prompt_without_pending_decode_token)
+
+ def commit_decode_input(self, token: int, expected_position: int) -> None:
+ if len(self.cached_tokens) != expected_position:
+ raise RuntimeError(f"KV ledger position mismatch: cached={len(self.cached_tokens)} expected={expected_position}")
+ self.cached_tokens.append(int(token))
+
+ def reset(self) -> None:
+ self.active_session = None
+ self.cached_tokens.clear()
From dad36521ea0d6536b99c7a4fd3a86e8284692285 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:59:03 +0530
Subject: [PATCH 121/168] radeon forge: use tested KV reuse ledger in local
inference
---
.../backends/tinygrad_llama_worker.py | 23 ++++++++-----------
1 file changed, 9 insertions(+), 14 deletions(-)
diff --git a/extra/radeon_forge/backends/tinygrad_llama_worker.py b/extra/radeon_forge/backends/tinygrad_llama_worker.py
index c674471fb18ae..b98722ccb9d35 100644
--- a/extra/radeon_forge/backends/tinygrad_llama_worker.py
+++ b/extra/radeon_forge/backends/tinygrad_llama_worker.py
@@ -10,6 +10,7 @@
from examples.llama3 import Tokenizer, build_transformer
from ..synthesis.hooks import ExecutionContext, ExecutionStage
+from .kv_state import KVReuseLedger
from .stage_hooks import ModelStageHookRuntime
@@ -146,6 +147,7 @@ def main() -> None:
param_bytes = sum(x.nbytes() for x in get_parameters(model))
architecture_data, architecture_hash = _architecture_identity(model, args.size, args.quantize)
hook_runtime = ModelStageHookRuntime(model)
+ kv = KVReuseLedger()
device_obj = Device[device]
architecture = str(getattr(device_obj, "arch", ""))
@@ -157,8 +159,6 @@ def encode_message(message) -> list[int]:
if not isinstance(content, str): content = json.dumps(content, default=str)
return encode_role(str(message.get("role", "user"))) + tokenizer.encode(content.strip()) + [tokenizer.special_tokens["<|eot_id|>"]]
- active_session: str | None = None
- cached_tokens: list[int] = [] # only tokens whose KV entries are actually materialized
send({"kind": "ready", "name": f"tinygrad-llama-{args.size}", "device": str(device), "gpu": str(device),
"architecture": architecture, "runtime": "tinygrad", "runtime_revision": _git_revision(),
"model": str(args.model), "model_family": "llama", "model_hash": _weight_identity(args.model, args.size, args.quantize),
@@ -172,6 +172,7 @@ def encode_message(message) -> list[int]:
payload = json.loads(line)
if payload.get("op") == "shutdown":
hook_runtime.close()
+ kv.reset()
return
if payload.get("op") != "generate": raise ValueError("unsupported operation")
request = payload["request"]
@@ -190,16 +191,10 @@ def encode_message(message) -> list[int]:
if not messages or messages[-1].get("role") != "assistant": prompt += encode_role("assistant")
if len(prompt) >= args.max_context: raise ValueError(f"prompt has {len(prompt)} tokens, max context is {args.max_context}")
- if active_session != session_id:
- active_session, cached_tokens = session_id, []
- common = 0
- for old, new in zip(cached_tokens, prompt):
- if old != new: break
- common += 1
-
+ common = kv.begin(session_id, prompt)
prefill_context = ExecutionContext(ExecutionStage.PREFILL, batch_size=1, prompt_tokens=len(prompt),
context_tokens=max(0, len(prompt)-1), generated_token_index=-1, prefix_reused_tokens=common,
- tool_round=tool_round, warm=bool(cached_tokens), attributes={"resume_after_tool": resume_after_tool, "session_id": session_id})
+ tool_round=tool_round, warm=bool(kv.cached_tokens), attributes={"resume_after_tool": resume_after_tool, "session_id": session_id})
_hook_event(hook_runtime, hooks, prefill_context)
prefill_ids = list(prompt[common:-1])
@@ -208,7 +203,7 @@ def encode_message(message) -> list[int]:
_, prefill_profile = _profiled(lambda: _prefill_without_output_head(model, prefill_ids, common, device))
prefill_wall_ms = (time.perf_counter_ns() - prefill_start) / 1e6
prefill_gpu_ms = GlobalCounters.time_sum_s * 1e3
- cached_tokens = list(prompt[:-1])
+ kv.commit_prefill(prompt[:-1])
send({"kind": "prefill", "metrics": {"wall_ms": prefill_wall_ms, "gpu_ms": prefill_gpu_ms,
"prompt_tokens": len(prompt), "prefix_reused_tokens": common, "new_prompt_tokens": len(prefill_ids),
"prefill_chunk_tokens": len(prefill_ids), "prefix_cache_hit_ratio": common / max(1, len(prompt)-1),
@@ -234,12 +229,12 @@ def encode_message(message) -> list[int]:
tok, profile = _profiled(lambda: model(Tensor([[input_tok]], device=device), start_pos, temperature, 0, 0.0, 0.0, 0.0).item())
wall_ms = (time.perf_counter_ns() - wall_start) / 1e6
gpu_ms = GlobalCounters.time_sum_s * 1e3
- cached_tokens.append(input_tok) # this model invocation materialized input_tok's KV entry
+ kv.commit_decode_input(input_tok, start_pos)
start_pos += 1
last_tok = tok
if tok in tokenizer.stop_tokens:
send({"kind": "done", "finish_reason": "stop", "metrics": {"generated_tokens": generated,
- "materialized_kv_tokens": len(cached_tokens)}})
+ "materialized_kv_tokens": len(kv.cached_tokens)}})
break
generated += 1
send({"kind": "token", "text": tokenizer.decode([tok]), "metrics": {"index": index, "stage": stage.value,
@@ -253,7 +248,7 @@ def encode_message(message) -> list[int]:
"captured": emitted, "available": len(profile)}})
else:
send({"kind": "done", "finish_reason": "length", "metrics": {"generated_tokens": generated,
- "materialized_kv_tokens": len(cached_tokens), "pending_uncached_output_token": True}})
+ "materialized_kv_tokens": len(kv.cached_tokens), "pending_uncached_output_token": True}})
except Exception as exc:
send({"kind": "error", "error": str(exc), "error_type": type(exc).__name__})
From b1411f8231b4882c0bad16ffe5e9d2561109a133 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:59:22 +0530
Subject: [PATCH 122/168] radeon forge: test exact KV reuse accounting
---
test/test_radeon_forge_kv.py | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 test/test_radeon_forge_kv.py
diff --git a/test/test_radeon_forge_kv.py b/test/test_radeon_forge_kv.py
new file mode 100644
index 0000000000000..2883eafc12bde
--- /dev/null
+++ b/test/test_radeon_forge_kv.py
@@ -0,0 +1,35 @@
+import unittest
+
+from extra.radeon_forge.backends.kv_state import KVReuseLedger
+
+
+class TestKVReuseLedger(unittest.TestCase):
+ def test_emitted_but_unprocessed_token_is_not_reported_as_cache_hit(self):
+ ledger = KVReuseLedger()
+ prompt = [1, 2, 3]
+ self.assertEqual(ledger.begin("session-a", prompt), 0)
+ ledger.commit_prefill(prompt[:-1])
+ ledger.commit_decode_input(prompt[-1], expected_position=2)
+ self.assertEqual(ledger.cached_tokens, [1, 2, 3])
+
+ # Token 4 was emitted to the user but generation stopped before it became
+ # the input to another decode step. It is intentionally absent from KV.
+ next_prompt = [1, 2, 3, 4, 5]
+ self.assertEqual(ledger.begin("session-a", next_prompt), 3)
+ ledger.commit_prefill(next_prompt[:-1])
+ self.assertEqual(ledger.cached_tokens, [1, 2, 3, 4])
+
+ def test_session_switch_invalidates_single_resident_cache(self):
+ ledger = KVReuseLedger("session-a", [1, 2, 3])
+ self.assertEqual(ledger.begin("session-b", [1, 2, 3]), 0)
+ self.assertEqual(ledger.active_session, "session-b")
+ self.assertEqual(ledger.cached_tokens, [])
+
+ def test_decode_position_mismatch_fails_closed(self):
+ ledger = KVReuseLedger("session-a", [1, 2])
+ with self.assertRaisesRegex(RuntimeError, "position mismatch"):
+ ledger.commit_decode_input(3, expected_position=4)
+ self.assertEqual(ledger.cached_tokens, [1, 2])
+
+
+if __name__ == "__main__": unittest.main()
From 0fa91c57741d04ddc999369da806aa2655c47542 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 15:59:34 +0530
Subject: [PATCH 123/168] ci: cover exact KV accounting
---
.github/workflows/radeon-forge.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/workflows/radeon-forge.yml b/.github/workflows/radeon-forge.yml
index 275a466f5a122..0ec5b817635b5 100644
--- a/.github/workflows/radeon-forge.yml
+++ b/.github/workflows/radeon-forge.yml
@@ -34,3 +34,4 @@ jobs:
test.test_radeon_forge_runtime
test.test_radeon_forge_hooks
test.test_radeon_forge_autotune
+ test.test_radeon_forge_kv
From db346c30ffac0f52abaaabe73b47038d4cab347d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:00:25 +0530
Subject: [PATCH 124/168] radeon forge: advertise native inference-engine
capabilities
---
extra/radeon_forge/runtime/backend.py | 3 +++
1 file changed, 3 insertions(+)
diff --git a/extra/radeon_forge/runtime/backend.py b/extra/radeon_forge/runtime/backend.py
index e81c165ab3397..c515c5794b4f1 100644
--- a/extra/radeon_forge/runtime/backend.py
+++ b/extra/radeon_forge/runtime/backend.py
@@ -13,6 +13,9 @@ class BackendCapabilities:
persistent_kv: bool = False
kernel_metrics: bool = False
cancellation: bool = False
+ batched_prefill: bool = False
+ stage_hooks: bool = False
+ local_only: bool = True
@dataclass(frozen=True)
From 6609ba397c62629e7f42b579c74abb2019a2f304 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:00:58 +0530
Subject: [PATCH 125/168] radeon forge: add bounded native tool-call stream
parser
---
extra/radeon_forge/runtime/tool_stream.py | 60 +++++++++++++++++++++++
1 file changed, 60 insertions(+)
create mode 100644 extra/radeon_forge/runtime/tool_stream.py
diff --git a/extra/radeon_forge/runtime/tool_stream.py b/extra/radeon_forge/runtime/tool_stream.py
new file mode 100644
index 0000000000000..f90effef378c2
--- /dev/null
+++ b/extra/radeon_forge/runtime/tool_stream.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import json, re, uuid
+from dataclasses import dataclass
+from typing import Iterable, Mapping, Any
+
+
+_TOOL_CALL = re.compile(r"\s*
\s*(\{.*\})\s* \s*", re.S)
+
+
+class ToolProtocolError(ValueError): pass
+
+
+@dataclass(frozen=True)
+class ParsedToolCall:
+ call_id: str
+ name: str
+ arguments: Mapping[str, Any]
+ raw: str
+
+ def to_event(self) -> dict[str, Any]:
+ return {"id": self.call_id, "name": self.name, "arguments": dict(self.arguments), "raw": self.raw}
+
+
+class ToolStreamParser:
+ """Incrementally detects the exact local tool-call protocol.
+
+ It is not a grammar decoder yet; it is a bounded early-stop and validation
+ layer. Malformed or unknown tool calls fail closed rather than being executed
+ as best-effort text.
+ """
+ def __init__(self, allowed_names: Iterable[str], max_bytes: int = 65536):
+ self.allowed_names = frozenset(str(name) for name in allowed_names)
+ self.max_bytes = max_bytes
+ self.buffer = ""
+ self.completed = False
+
+ def feed(self, text: str) -> ParsedToolCall | None:
+ if self.completed: raise ToolProtocolError("tool stream is already complete")
+ self.buffer += text
+ if len(self.buffer.encode("utf-8")) > self.max_bytes: raise ToolProtocolError("tool-call stream exceeds size limit")
+ if "" not in self.buffer: return None
+ match = _TOOL_CALL.fullmatch(self.buffer)
+ if match is None: raise ToolProtocolError("malformed tool call: output must contain exactly one wrapped JSON object")
+ try: payload = json.loads(match.group(1))
+ except json.JSONDecodeError as exc: raise ToolProtocolError(f"tool call contains invalid JSON: {exc}") from exc
+ if not isinstance(payload, dict): raise ToolProtocolError("tool-call payload must be an object")
+ name, arguments = payload.get("name"), payload.get("arguments", {})
+ if not isinstance(name, str) or not name: raise ToolProtocolError("tool call requires a non-empty string name")
+ if name not in self.allowed_names: raise ToolProtocolError(f"unknown or unavailable local tool {name!r}")
+ if not isinstance(arguments, dict): raise ToolProtocolError("tool call arguments must be an object")
+ call_id = payload.get("id") or uuid.uuid4().hex
+ if not isinstance(call_id, str): raise ToolProtocolError("tool call id must be a string")
+ self.completed = True
+ return ParsedToolCall(call_id, name, arguments, self.buffer)
+
+ def finalize(self) -> None:
+ stripped = self.buffer.lstrip()
+ if stripped.startswith("
") and not self.completed:
+ raise ToolProtocolError("generation ended with an incomplete tool call")
From 0424b876773d030a22c1ca076dfafcf165bd59fc Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:01:14 +0530
Subject: [PATCH 126/168] radeon forge: test bounded structured tool parsing
---
test/test_radeon_forge_tool_stream.py | 35 +++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 test/test_radeon_forge_tool_stream.py
diff --git a/test/test_radeon_forge_tool_stream.py b/test/test_radeon_forge_tool_stream.py
new file mode 100644
index 0000000000000..850154e91ee69
--- /dev/null
+++ b/test/test_radeon_forge_tool_stream.py
@@ -0,0 +1,35 @@
+import unittest
+
+from extra.radeon_forge.runtime.tool_stream import ToolProtocolError, ToolStreamParser
+
+
+class TestToolStreamParser(unittest.TestCase):
+ def test_incremental_valid_tool_call(self):
+ parser = ToolStreamParser(["read_file", "search_text"])
+ self.assertIsNone(parser.feed('{"name":"read_'))
+ call = parser.feed('file","arguments":{"path":"README.md"}} ')
+ self.assertEqual(call.name, "read_file")
+ self.assertEqual(call.arguments, {"path":"README.md"})
+ self.assertEqual(call.raw, '{"name":"read_file","arguments":{"path":"README.md"}} ')
+
+ def test_unknown_tool_fails_closed(self):
+ parser = ToolStreamParser(["read_file"])
+ with self.assertRaisesRegex(ToolProtocolError, "unknown or unavailable"):
+ parser.feed('{"name":"curl","arguments":{}} ')
+
+ def test_malformed_or_incomplete_calls_fail_closed(self):
+ parser = ToolStreamParser(["read_file"])
+ with self.assertRaisesRegex(ToolProtocolError, "exactly one"):
+ parser.feed('Sure. {"name":"read_file","arguments":{}} ')
+ incomplete = ToolStreamParser(["read_file"])
+ incomplete.feed('{"name":"read_file"')
+ with self.assertRaisesRegex(ToolProtocolError, "incomplete"):
+ incomplete.finalize()
+
+ def test_stream_size_is_bounded(self):
+ parser = ToolStreamParser(["read_file"], max_bytes=8)
+ with self.assertRaisesRegex(ToolProtocolError, "size limit"):
+ parser.feed("123456789")
+
+
+if __name__ == "__main__": unittest.main()
From a02b04da14fc789e9ae600d5a7ec5eea180126fa Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:02:25 +0530
Subject: [PATCH 127/168] radeon forge: early-stop on native structured tool
calls
---
.../backends/tinygrad_llama_worker.py | 29 +++++++++++++++++--
1 file changed, 26 insertions(+), 3 deletions(-)
diff --git a/extra/radeon_forge/backends/tinygrad_llama_worker.py b/extra/radeon_forge/backends/tinygrad_llama_worker.py
index b98722ccb9d35..8a105e20ea15c 100644
--- a/extra/radeon_forge/backends/tinygrad_llama_worker.py
+++ b/extra/radeon_forge/backends/tinygrad_llama_worker.py
@@ -9,6 +9,7 @@
from tinygrad.nn.state import get_parameters
from examples.llama3 import Tokenizer, build_transformer
+from ..runtime.tool_stream import ToolStreamParser
from ..synthesis.hooks import ExecutionContext, ExecutionStage
from .kv_state import KVReuseLedger
from .stage_hooks import ModelStageHookRuntime
@@ -126,6 +127,16 @@ def _prefill_without_output_head(model: Any, token_ids: list[int], start_pos: in
h.realize()
+def _available_tool_names(tools: Any) -> list[str]:
+ names = []
+ if not isinstance(tools, list): return names
+ for item in tools:
+ if not isinstance(item, Mapping): continue
+ function = item.get("function", {})
+ if isinstance(function, Mapping) and isinstance(function.get("name"), str): names.append(str(function["name"]))
+ return names
+
+
def main() -> None:
parser = argparse.ArgumentParser(description="Persistent tinygrad Llama backend for Radeon Forge")
parser.add_argument("--model", type=Path, required=True)
@@ -164,8 +175,9 @@ def encode_message(message) -> list[int]:
"model": str(args.model), "model_family": "llama", "model_hash": _weight_identity(args.model, args.size, args.quantize),
"model_architecture_hash": architecture_hash, "model_architecture": architecture_data,
"dtype": args.quantize or "model_default", "shapes": {"batch": 1, "max_context": args.max_context},
- "parameter_bytes": param_bytes, "capabilities": {"streaming": True, "structured_tools": False,
- "prefix_cache": True, "persistent_kv": True, "kernel_metrics": True, "cancellation": False}})
+ "parameter_bytes": param_bytes, "capabilities": {"streaming": True, "structured_tools": True,
+ "prefix_cache": True, "persistent_kv": True, "kernel_metrics": True, "cancellation": False,
+ "batched_prefill": True, "stage_hooks": True, "local_only": True}})
for line in sys.stdin:
try:
@@ -185,6 +197,8 @@ def encode_message(message) -> list[int]:
temperature = float(request.get("temperature", 0.0))
tool_round = int(metadata.get("tool_round", 0))
resume_after_tool = bool(metadata.get("resume_after_tool", False))
+ tool_names = _available_tool_names(request.get("tools", []))
+ tool_parser = ToolStreamParser(tool_names) if tool_names else None
prompt = [tokenizer.bos_id]
for message in messages: prompt += encode_message(message)
@@ -233,11 +247,14 @@ def encode_message(message) -> list[int]:
start_pos += 1
last_tok = tok
if tok in tokenizer.stop_tokens:
+ if tool_parser is not None: tool_parser.finalize()
send({"kind": "done", "finish_reason": "stop", "metrics": {"generated_tokens": generated,
"materialized_kv_tokens": len(kv.cached_tokens)}})
break
generated += 1
- send({"kind": "token", "text": tokenizer.decode([tok]), "metrics": {"index": index, "stage": stage.value,
+ piece = tokenizer.decode([tok])
+ parsed_tool = tool_parser.feed(piece) if tool_parser is not None else None
+ send({"kind": "token", "text": piece, "metrics": {"index": index, "stage": stage.value,
"wall_ms": wall_ms, "gpu_ms": gpu_ms, "kernel_count": GlobalCounters.kernel_count,
"global_mem_bytes": GlobalCounters.global_mem, "global_ops": GlobalCounters.global_ops,
"profile_kernel_events": len(profile), "context_tokens": start_pos,
@@ -246,7 +263,13 @@ def encode_message(message) -> list[int]:
if truncated:
send({"kind": "metric", "metrics": {"name": "profile_truncated", "stage": stage.value, "token_index": index,
"captured": emitted, "available": len(profile)}})
+ if parsed_tool is not None:
+ send({"kind": "tool_call", "tool_call": parsed_tool.to_event()})
+ send({"kind": "done", "finish_reason": "tool_call", "metrics": {"generated_tokens": generated,
+ "materialized_kv_tokens": len(kv.cached_tokens), "tool_name": parsed_tool.name}})
+ break
else:
+ if tool_parser is not None: tool_parser.finalize()
send({"kind": "done", "finish_reason": "length", "metrics": {"generated_tokens": generated,
"materialized_kv_tokens": len(kv.cached_tokens), "pending_uncached_output_token": True}})
except Exception as exc:
From 2e6be35758ad2bb7e6f770f9c1289f4cbc4293ee Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:03:18 +0530
Subject: [PATCH 128/168] radeon forge: preserve exact structured tool
transcripts
---
extra/radeon_forge/runtime/session.py | 34 ++++++++++++++++++++++-----
1 file changed, 28 insertions(+), 6 deletions(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index 6a1ffcbeb8d63..d02c7661fdaa2 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-import threading, time, uuid
+import json, threading, time, uuid
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any, Callable, Mapping
@@ -39,6 +39,7 @@ def __init__(self, backend: InferenceBackend, tools: ToolRegistry, system_prompt
self.messages: list[dict[str, Any]] = [{"role": "system", "content": self._system_prompt()}]
self.events: list[SessionEvent] = []
self.pending_tool_call: ToolCall | None = None
+ self.pending_assistant_content = ""
self.partial_output = ""
self.state = SessionState.IDLE
self._sequence = 0
@@ -55,6 +56,11 @@ def _system_prompt(self) -> str:
claim a tool result before it is returned. All inference and tools are local.
"""
+ @staticmethod
+ def _tool_content(call: ToolCall) -> str:
+ payload = {"id": call.call_id, "name": call.name, "arguments": dict(call.arguments)}
+ return f"{json.dumps(payload, separators=(',', ':'))} "
+
def _emit(self, kind: str, **data: Any) -> SessionEvent:
self._sequence += 1
event = SessionEvent(self._sequence, kind, data)
@@ -96,6 +102,7 @@ def _request_metadata(self, step: int) -> dict[str, Any]:
def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent, ...]:
self.state = SessionState.GENERATING
self.partial_output = ""
+ self.pending_assistant_content = ""
started_at = len(self.events)
pieces: list[str] = []
step = sum(1 for event in self.events if event.kind == "generation_started") + 1
@@ -116,7 +123,13 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
text=event.text, **token_metrics)
elif event.kind in {"prefill", "decode", "kernel", "metric", "hook"}: self._record_backend_event(event, parent.event_id)
elif event.kind == "tool_call" and event.tool_call is not None:
- self.pending_tool_call = ToolCall(str(event.tool_call.get("id") or uuid.uuid4().hex), str(event.tool_call["name"]), event.tool_call.get("arguments", {}))
+ arguments = event.tool_call.get("arguments", {})
+ if not isinstance(arguments, Mapping): raise ValueError("backend tool-call arguments must be an object")
+ self.pending_tool_call = ToolCall(str(event.tool_call.get("id") or uuid.uuid4().hex),
+ str(event.tool_call["name"]), dict(arguments))
+ raw = event.tool_call.get("raw")
+ if isinstance(raw, str): self.pending_assistant_content = raw
+ self._emit("structured_tool_call", call=asdict(self.pending_tool_call), native=True)
elif event.kind == "done": self._emit("generation_done", finish_reason=event.finish_reason, metrics=dict(event.metrics))
except Exception as exc:
self.state = SessionState.FAILED
@@ -124,9 +137,12 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
raise
output = "".join(pieces)
if self.pending_tool_call is None:
- try: self.pending_tool_call = parse_tool_call(output)
+ try:
+ self.pending_tool_call = parse_tool_call(output)
+ if self.pending_tool_call is not None: self.pending_assistant_content = output
except Exception as exc: self._emit("tool_parse_error", error=str(exc), raw=output)
if self.pending_tool_call is not None:
+ if not self.pending_assistant_content: self.pending_assistant_content = self._tool_content(self.pending_tool_call)
self.partial_output = ""
self.state = SessionState.AWAITING_TOOL_APPROVAL
self._emit("tool_approval_required", call=asdict(self.pending_tool_call), action=self.tools.spec(self.pending_tool_call.name).action.value)
@@ -141,6 +157,7 @@ def approve_tool(self, permission_token: str, max_tokens: int = 512) -> tuple[Se
with self._lock:
if self.state is not SessionState.AWAITING_TOOL_APPROVAL or self.pending_tool_call is None: raise RuntimeError("no tool call awaits approval")
call = self.pending_tool_call
+ assistant_content = self.pending_assistant_content or self._tool_content(call)
started_at = len(self.events)
self.state = SessionState.RUNNING_TOOL
try:
@@ -153,9 +170,10 @@ def approve_tool(self, permission_token: str, max_tokens: int = 512) -> tuple[Se
self._emit("tool_authorization_failed", call_id=call.call_id, error=str(exc), error_type=type(exc).__name__)
raise
self._emit("tool_result", result=asdict(result))
- self.messages.append({"role": "assistant", "content": f"{{\"name\":\"{call.name}\"}} "})
+ self.messages.append({"role": "assistant", "content": assistant_content})
self.messages.append({"role": "tool", "name": call.name, "tool_call_id": call.call_id, "content": str(result.output)})
self.pending_tool_call = None
+ self.pending_assistant_content = ""
if not result.ok:
self.state = SessionState.FAILED
return tuple(self.events[started_at:])
@@ -167,8 +185,11 @@ def reject_tool(self, reason: str) -> SessionEvent:
with self._lock:
if self.pending_tool_call is None: raise RuntimeError("no pending tool call")
call = self.pending_tool_call
- self.pending_tool_call = None
+ assistant_content = self.pending_assistant_content or self._tool_content(call)
+ self.messages.append({"role": "assistant", "content": assistant_content})
self.messages.append({"role": "tool", "name": call.name, "tool_call_id": call.call_id, "content": f"User rejected tool call: {reason}"})
+ self.pending_tool_call = None
+ self.pending_assistant_content = ""
self.state = SessionState.IDLE
return self._emit("tool_rejected", call_id=call.call_id, reason=reason)
@@ -178,4 +199,5 @@ def events_after(self, sequence: int) -> list[dict[str, Any]]:
def snapshot(self) -> dict[str, Any]:
return {"session_id": self.session_id, "state": self.state.value, "messages": list(self.messages),
"events": [asdict(x) for x in self.events], "pending_tool_call": asdict(self.pending_tool_call) if self.pending_tool_call else None,
- "partial_output": self.partial_output, "trace_id": self.trace.trace_id}
+ "pending_assistant_content": self.pending_assistant_content, "partial_output": self.partial_output,
+ "trace_id": self.trace.trace_id}
From 370d5caeed6193ea2d0050e31434d156f379f7de Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:04:15 +0530
Subject: [PATCH 129/168] radeon forge: test lossless native tool transcripts
---
test/test_radeon_forge_runtime.py | 37 ++++++++++++++++++++++++++++++-
1 file changed, 36 insertions(+), 1 deletion(-)
diff --git a/test/test_radeon_forge_runtime.py b/test/test_radeon_forge_runtime.py
index 03ca8b87fa48c..ce1ed413ef422 100644
--- a/test/test_radeon_forge_runtime.py
+++ b/test/test_radeon_forge_runtime.py
@@ -55,6 +55,22 @@ def stream(self, request):
def close(self): self.release.set()
+class NativeToolBackend:
+ RAW = '{"id":"call-7","name":"read_file","arguments":{"path":"hello.txt","start_line":2}} '
+ @property
+ def name(self): return "native-tool-local"
+ @property
+ def capabilities(self): return BackendCapabilities(structured_tools=True)
+ @property
+ def runtime_metadata(self): return {"runtime":"test", "architecture":"gfx1100", "model_family":"llama"}
+ def stream(self, request):
+ yield GenerationEvent("token", self.RAW, metrics={"index":0, "stage":"first_token", "wall_ms":1.0})
+ yield GenerationEvent("tool_call", tool_call={"id":"call-7", "name":"read_file",
+ "arguments":{"path":"hello.txt", "start_line":2}, "raw":self.RAW})
+ yield GenerationEvent("done", finish_reason="tool_call", metrics={"generated_tokens":1})
+ def close(self): pass
+
+
class TestRadeonForgeRuntime(unittest.TestCase):
def test_kernel_evidence_survives_unified_trace_and_is_ranked_by_stage(self):
with tempfile.TemporaryDirectory() as directory:
@@ -98,7 +114,7 @@ def test_async_job_exposes_partial_generation(self):
self.assertEqual(session.messages[-1]["content"], "partial complete")
engine.close()
- def test_permissioned_tool_round_trip(self):
+ def test_permissioned_tool_round_trip_preserves_arguments(self):
responses = [
'{"name":"read_file","arguments":{"path":"hello.txt"}} ',
"The private file was read successfully.",
@@ -115,9 +131,28 @@ def test_permissioned_tool_round_trip(self):
session.approve_tool(token)
self.assertEqual(session.state, SessionState.COMPLETED)
self.assertEqual(session.messages[-1]["content"], "The private file was read successfully.")
+ assistant_tool = next(message for message in session.messages if message.get("role") == "assistant" and "" in message.get("content", ""))
+ self.assertIn('"path":"hello.txt"', assistant_tool["content"])
self.assertTrue(any(event.kind == "tool_result" for event in session.events))
engine.close()
+ def test_native_structured_tool_call_and_rejection_are_lossless(self):
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory, "hello.txt").write_text("line1\nline2\n", encoding="utf-8")
+ engine = ForgeEngine(NativeToolBackend(), directory)
+ session = engine.create_session()
+ session.send("read line two")
+ self.assertEqual(session.state, SessionState.AWAITING_TOOL_APPROVAL)
+ self.assertEqual(session.pending_tool_call.call_id, "call-7")
+ self.assertEqual(session.pending_tool_call.arguments["start_line"], 2)
+ self.assertEqual(session.pending_assistant_content, NativeToolBackend.RAW)
+ session.reject_tool("not now")
+ self.assertEqual(session.state, SessionState.IDLE)
+ self.assertEqual(session.messages[-2]["content"], NativeToolBackend.RAW)
+ self.assertEqual(session.messages[-1]["tool_call_id"], "call-7")
+ self.assertIn("not now", session.messages[-1]["content"])
+ engine.close()
+
def test_workspace_paths_cannot_escape(self):
with tempfile.TemporaryDirectory() as directory:
tools = WorkspaceTools(directory)
From 8c233076370a49d88179ff662f5cc77faa7167a0 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:05:02 +0530
Subject: [PATCH 130/168] radeon forge: expose native model-serving stream
---
extra/radeon_forge/runtime/engine.py | 16 +++++++++++++---
1 file changed, 13 insertions(+), 3 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index f0af8af0dc04e..a9f9890219553 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -3,12 +3,12 @@
import threading, uuid
from dataclasses import asdict
from pathlib import Path
-from typing import Any, Mapping
+from typing import Any, Iterator, Mapping, Sequence
from ..permissions import PermissionController
from ..profiling.report import build_profile_report
from ..synthesis import CandidateWorkspace, OptimizationTools, RuntimeFingerprint, SafeHookRegistry, install_default_specs
-from .backend import InferenceBackend
+from .backend import GenerationEvent, GenerationRequest, InferenceBackend
from .jobs import LocalJobManager
from .session import AgentSession
from .tools import ToolCall, ToolRegistry, WorkspaceTools
@@ -40,7 +40,7 @@ def runtime_fingerprint(self) -> RuntimeFingerprint:
if callable(metadata): metadata = metadata()
return RuntimeFingerprint.from_mapping(metadata if isinstance(metadata, Mapping) else {})
- def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, Any]:
+ def inference_metadata(self) -> dict[str, Any]:
metadata = self.hooks.runtime_metadata()
for item in metadata.get("active_hooks", []):
try:
@@ -49,6 +49,16 @@ def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, An
except Exception: item["parameters"] = {}
return {**metadata, "runtime_fingerprint": asdict(self.runtime_fingerprint())}
+ def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, Any]: return self.inference_metadata()
+
+ def stream_inference(self, messages: Sequence[Mapping[str, Any]], tools: Sequence[Mapping[str, Any]] = (),
+ max_tokens: int = 256, temperature: float = 0.0, session_id: str | None = None,
+ stop: Sequence[str] = ()) -> Iterator[GenerationEvent]:
+ """Serve the resident local model without losing Forge hooks or profiling events."""
+ request = GenerationRequest(session_id or uuid.uuid4().hex, tuple(messages), tuple(tools), max_tokens, temperature,
+ tuple(stop), metadata=self.inference_metadata())
+ return self.backend.stream(request)
+
def create_session(self) -> AgentSession:
with self._lock:
session = AgentSession(self.backend, self.tools, self.system_prompt, metadata_provider=self._session_metadata)
From 6d7e6beec9666220185c179488ea5e11c1753e21 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:05:54 +0530
Subject: [PATCH 131/168] radeon forge: add OpenAI-compatible local serving
adapter
---
extra/radeon_forge/ui/openai_api.py | 102 ++++++++++++++++++++++++++++
1 file changed, 102 insertions(+)
create mode 100644 extra/radeon_forge/ui/openai_api.py
diff --git a/extra/radeon_forge/ui/openai_api.py b/extra/radeon_forge/ui/openai_api.py
new file mode 100644
index 0000000000000..0bf51e74ecbc8
--- /dev/null
+++ b/extra/radeon_forge/ui/openai_api.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+import json, statistics, time, uuid
+from collections import defaultdict
+from typing import Any, Iterable, Mapping, Sequence
+
+from ..runtime import ForgeEngine, GenerationEvent
+
+
+class OpenAIRequestError(ValueError): pass
+
+
+def _request(payload: Mapping[str, Any]) -> tuple[list[Mapping[str, Any]], list[Mapping[str, Any]], int, float, str, tuple[str, ...]]:
+ messages = payload.get("messages")
+ if not isinstance(messages, list) or not messages or not all(isinstance(item, Mapping) for item in messages):
+ raise OpenAIRequestError("messages must be a non-empty array of objects")
+ tools = payload.get("tools", [])
+ if not isinstance(tools, list) or not all(isinstance(item, Mapping) for item in tools): raise OpenAIRequestError("tools must be an array")
+ max_tokens = int(payload.get("max_tokens", payload.get("max_completion_tokens", 256)))
+ if max_tokens <= 0: raise OpenAIRequestError("max_tokens must be positive")
+ temperature = float(payload.get("temperature", 0.0))
+ session_id = str(payload.get("session_id") or payload.get("user") or uuid.uuid4().hex)
+ stop = payload.get("stop", ())
+ if isinstance(stop, str): stop = (stop,)
+ elif isinstance(stop, list) and all(isinstance(item, str) for item in stop): stop = tuple(stop)
+ elif stop in (None, ()): stop = ()
+ else: raise OpenAIRequestError("stop must be a string or array of strings")
+ return list(messages), list(tools), max_tokens, temperature, session_id, tuple(stop)
+
+
+def _tool_call(value: Mapping[str, Any]) -> dict[str, Any]:
+ return {"id": str(value.get("id") or uuid.uuid4().hex), "type": "function",
+ "function": {"name": str(value["name"]), "arguments": json.dumps(value.get("arguments", {}), separators=(",", ":"))}}
+
+
+def _finish_reason(value: str | None) -> str | None:
+ return "tool_calls" if value == "tool_call" else value
+
+
+def _summarize(events: Sequence[GenerationEvent], session_id: str) -> dict[str, Any]:
+ prefill = next((dict(event.metrics) for event in events if event.kind == "prefill"), {})
+ tokens = [dict(event.metrics) for event in events if event.kind == "token"]
+ by_stage: dict[str, list[float]] = defaultdict(list)
+ kernel_calls: dict[str, int] = defaultdict(int)
+ hook_events = []
+ for event in events:
+ if event.kind == "token":
+ wall = event.metrics.get("wall_ms")
+ if wall is not None: by_stage[str(event.metrics.get("stage", "decode"))].append(float(wall))
+ elif event.kind == "kernel": kernel_calls[str(event.metrics.get("stage", "unknown"))] += 1
+ elif event.kind == "hook": hook_events.append(dict(event.metrics))
+ return {"session_id": session_id, "prefill": prefill,
+ "token_latency_ms": {stage: {"count": len(values), "p50": statistics.median(values), "max": max(values)}
+ for stage, values in by_stage.items() if values},
+ "kernel_calls_by_stage": dict(kernel_calls), "hook_transitions": hook_events,
+ "generated_tokens": len(tokens)}
+
+
+def collect_chat_completion(engine: ForgeEngine, payload: Mapping[str, Any]) -> dict[str, Any]:
+ messages, tools, max_tokens, temperature, session_id, stop = _request(payload)
+ events = list(engine.stream_inference(messages, tools, max_tokens, temperature, session_id, stop))
+ text = "".join(event.text for event in events if event.kind == "token")
+ tool = next((event.tool_call for event in events if event.kind == "tool_call" and event.tool_call is not None), None)
+ done = next((event for event in reversed(events) if event.kind == "done"), None)
+ prefill = next((event for event in events if event.kind == "prefill"), None)
+ completion_tokens = int(done.metrics.get("generated_tokens", 0)) if done is not None else sum(event.kind == "token" for event in events)
+ prompt_tokens = int(prefill.metrics.get("prompt_tokens", 0)) if prefill is not None else 0
+ message: dict[str, Any] = {"role": "assistant", "content": None if tool is not None else text}
+ if tool is not None: message["tool_calls"] = [_tool_call(tool)]
+ return {"id": f"chatcmpl-{uuid.uuid4().hex}", "object": "chat.completion", "created": int(time.time()),
+ "model": str(payload.get("model") or engine.backend.name),
+ "choices": [{"index": 0, "message": message, "finish_reason": _finish_reason(done.finish_reason if done else None)}],
+ "usage": {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens,
+ "total_tokens": prompt_tokens + completion_tokens},
+ "system_fingerprint": engine.runtime_fingerprint().architecture or None,
+ "forge": _summarize(events, session_id)}
+
+
+def stream_chat_completion(engine: ForgeEngine, payload: Mapping[str, Any]) -> Iterable[str]:
+ messages, tools, max_tokens, temperature, session_id, stop = _request(payload)
+ completion_id, created = f"chatcmpl-{uuid.uuid4().hex}", int(time.time())
+ model = str(payload.get("model") or engine.backend.name)
+ first = True
+ for event in engine.stream_inference(messages, tools, max_tokens, temperature, session_id, stop):
+ if event.kind == "token":
+ delta = {"content": event.text}
+ if first: delta = {"role": "assistant", **delta}; first = False
+ chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
+ yield f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"
+ elif event.kind == "tool_call" and event.tool_call is not None:
+ delta = {"tool_calls": [{"index": 0, **_tool_call(event.tool_call)}]}
+ if first: delta = {"role": "assistant", **delta}; first = False
+ chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
+ yield f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"
+ elif event.kind == "done":
+ chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
+ "choices": [{"index": 0, "delta": {}, "finish_reason": _finish_reason(event.finish_reason)}],
+ "forge_session_id": session_id}
+ yield f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"
+ yield "data: [DONE]\n\n"
From 6cd0466cacefd1971c5af7caf8f4a9dd992f784d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:06:54 +0530
Subject: [PATCH 132/168] radeon forge: hide raw tool protocol from standard
streams
---
extra/radeon_forge/ui/openai_api.py | 42 +++++++++++++++++++++++------
1 file changed, 34 insertions(+), 8 deletions(-)
diff --git a/extra/radeon_forge/ui/openai_api.py b/extra/radeon_forge/ui/openai_api.py
index 0bf51e74ecbc8..0ff666b56d17e 100644
--- a/extra/radeon_forge/ui/openai_api.py
+++ b/extra/radeon_forge/ui/openai_api.py
@@ -7,6 +7,9 @@
from ..runtime import ForgeEngine, GenerationEvent
+_TOOL_PREFIX = ""
+
+
class OpenAIRequestError(ValueError): pass
@@ -33,8 +36,7 @@ def _tool_call(value: Mapping[str, Any]) -> dict[str, Any]:
"function": {"name": str(value["name"]), "arguments": json.dumps(value.get("arguments", {}), separators=(",", ":"))}}
-def _finish_reason(value: str | None) -> str | None:
- return "tool_calls" if value == "tool_call" else value
+def _finish_reason(value: str | None) -> str | None: return "tool_calls" if value == "tool_call" else value
def _summarize(events: Sequence[GenerationEvent], session_id: str) -> dict[str, Any]:
@@ -76,25 +78,49 @@ def collect_chat_completion(engine: ForgeEngine, payload: Mapping[str, Any]) ->
"forge": _summarize(events, session_id)}
+def _content_chunk(completion_id: str, created: int, model: str, text: str, include_role: bool) -> str:
+ delta = {"content": text}
+ if include_role: delta = {"role": "assistant", **delta}
+ chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
+ return f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"
+
+
+def _could_be_tool_protocol(text: str) -> bool:
+ stripped = text.lstrip()
+ return _TOOL_PREFIX.startswith(stripped) or stripped.startswith(_TOOL_PREFIX)
+
+
def stream_chat_completion(engine: ForgeEngine, payload: Mapping[str, Any]) -> Iterable[str]:
messages, tools, max_tokens, temperature, session_id, stop = _request(payload)
completion_id, created = f"chatcmpl-{uuid.uuid4().hex}", int(time.time())
model = str(payload.get("model") or engine.backend.name)
- first = True
+ first, buffered, buffering_tool = True, "", False
for event in engine.stream_inference(messages, tools, max_tokens, temperature, session_id, stop):
if event.kind == "token":
- delta = {"content": event.text}
- if first: delta = {"role": "assistant", **delta}; first = False
- chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
- "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
- yield f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"
+ if first or buffering_tool:
+ buffered += event.text
+ if _could_be_tool_protocol(buffered):
+ buffering_tool = True
+ continue
+ if buffered:
+ yield _content_chunk(completion_id, created, model, buffered, first)
+ first, buffered, buffering_tool = False, "", False
+ else:
+ yield _content_chunk(completion_id, created, model, event.text, False)
elif event.kind == "tool_call" and event.tool_call is not None:
+ # The native worker already validated the buffered text. Standard clients
+ # receive only the structured delta, never Forge's internal text protocol.
+ buffered, buffering_tool = "", False
delta = {"tool_calls": [{"index": 0, **_tool_call(event.tool_call)}]}
if first: delta = {"role": "assistant", **delta}; first = False
chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
yield f"data: {json.dumps(chunk, separators=(',', ':'))}\n\n"
elif event.kind == "done":
+ if buffered:
+ yield _content_chunk(completion_id, created, model, buffered, first)
+ first, buffered = False, ""
chunk = {"id": completion_id, "object": "chat.completion.chunk", "created": created, "model": model,
"choices": [{"index": 0, "delta": {}, "finish_reason": _finish_reason(event.finish_reason)}],
"forge_session_id": session_id}
From 3125b974a12edf34840df32a3789507bba06656d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:07:48 +0530
Subject: [PATCH 133/168] radeon forge: expose OpenAI-compatible local API
---
extra/radeon_forge/ui/server.py | 39 ++++++++++++++++++++++++++++-----
1 file changed, 33 insertions(+), 6 deletions(-)
diff --git a/extra/radeon_forge/ui/server.py b/extra/radeon_forge/ui/server.py
index e197a1ac89cec..ccde88679dab2 100644
--- a/extra/radeon_forge/ui/server.py
+++ b/extra/radeon_forge/ui/server.py
@@ -1,15 +1,16 @@
from __future__ import annotations
-import argparse, json, mimetypes, re, sys
+import argparse, json, mimetypes, re, sys, time
from dataclasses import asdict
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
-from typing import Any
+from typing import Any, Iterable
from urllib.parse import parse_qs, urlparse
from ..backends.fake import ScriptedBackend
from ..runtime import ForgeEngine, JsonlProcessBackend
+from .openai_api import OpenAIRequestError, collect_chat_completion, stream_chat_completion
class ForgeRequestHandler(BaseHTTPRequestHandler):
@@ -27,9 +28,24 @@ def _json(self, payload: Any, status: int = 200):
self.end_headers()
self.wfile.write(body)
+ def _sse(self, chunks: Iterable[str]):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Cache-Control", "no-cache")
+ self.send_header("Connection", "close")
+ self.end_headers()
+ try:
+ for chunk in chunks:
+ self.wfile.write(chunk.encode())
+ self.wfile.flush()
+ except (BrokenPipeError, ConnectionResetError): pass
+ finally: self.close_connection = True
+
def _body(self) -> dict[str, Any]:
length = int(self.headers.get("Content-Length", "0"))
- return json.loads(self.rfile.read(length) or b"{}")
+ payload = json.loads(self.rfile.read(length) or b"{}")
+ if not isinstance(payload, dict): raise ValueError("request body must be a JSON object")
+ return payload
def _static(self, name: str):
path = (self.static_root / name).resolve()
@@ -52,6 +68,11 @@ def do_GET(self):
try:
if path == "/": return self._static("index.html")
if path in {"/app.js", "/style.css", "/kernels.css"}: return self._static(path[1:])
+ if path == "/v1/models":
+ return self._json({"object":"list", "data":[{"id":self.engine.backend.name, "object":"model",
+ "created":int(time.time()), "owned_by":"local-radeon-forge",
+ "forge": {"runtime_fingerprint":asdict(self.engine.runtime_fingerprint()),
+ "capabilities":asdict(self.engine.backend.capabilities)}}]})
if path == "/api/health": return self._json({"ok": True, "backend": self.engine.backend.name,
"capabilities": asdict(self.engine.backend.capabilities), "runtime_fingerprint": asdict(self.engine.runtime_fingerprint())})
if path == "/api/sessions": return self._json(self.engine.sessions())
@@ -75,6 +96,9 @@ def do_POST(self):
path = urlparse(self.path).path
try:
body = self._body()
+ if path == "/v1/chat/completions":
+ if bool(body.get("stream", False)): return self._sse(stream_chat_completion(self.engine, body))
+ return self._json(collect_chat_completion(self.engine, body))
if path == "/api/sessions": return self._json(self.engine.create_session().snapshot(), HTTPStatus.CREATED)
if path == "/api/recipes/import":
result = self.engine.execute_explicit_ui_tool("import_forge_recipe", {"path": str(body.get("path", ""))},
@@ -118,6 +142,8 @@ def do_POST(self):
event = session.reject_tool(str(body.get("reason", "Rejected by user")))
return self._json({"event": asdict(event), "session": session.snapshot()})
return self.send_error(404)
+ except OpenAIRequestError as exc:
+ return self._json({"error":{"message":str(exc), "type":"invalid_request_error", "param":None, "code":None}}, 400)
except (ValueError, RuntimeError, FileNotFoundError) as exc: return self._json({"error": str(exc), "type": type(exc).__name__}, 400)
except Exception as exc: return self._json({"error": str(exc), "type": type(exc).__name__}, 500)
@@ -133,7 +159,7 @@ def build_backend(args):
def main():
- parser = argparse.ArgumentParser(description="Radeon Forge local inference and profiling UI")
+ parser = argparse.ArgumentParser(description="Radeon Forge local inference, agent and profiling server")
parser.add_argument("--workspace", type=Path, default=Path.cwd())
parser.add_argument("--backend", choices=("scripted", "tinygrad-llama"), default="scripted")
parser.add_argument("--model", type=Path)
@@ -144,11 +170,12 @@ def main():
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=7790)
args = parser.parse_args()
- if args.host not in {"127.0.0.1", "localhost", "::1"}: raise SystemExit("Forge UI binds to loopback only")
+ if args.host not in {"127.0.0.1", "localhost", "::1"}: raise SystemExit("Forge binds to loopback only")
engine = ForgeEngine(build_backend(args), args.workspace)
ForgeRequestHandler.engine = engine
server = ThreadingHTTPServer((args.host, args.port), ForgeRequestHandler)
- print(f"Radeon Forge UI: http://{args.host}:{args.port} backend={engine.backend.name} workspace={args.workspace.resolve()}")
+ print(f"Radeon Forge: http://{args.host}:{args.port} backend={engine.backend.name} workspace={args.workspace.resolve()}")
+ print(f"OpenAI-compatible API: http://{args.host}:{args.port}/v1")
try: server.serve_forever()
finally: engine.close()
From 2af3b951d83d74e4012f5fd08c2f498b3be06704 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:08:21 +0530
Subject: [PATCH 134/168] radeon forge: test OpenAI-compatible local API
adapter
---
test/test_radeon_forge_openai.py | 74 ++++++++++++++++++++++++++++++++
1 file changed, 74 insertions(+)
create mode 100644 test/test_radeon_forge_openai.py
diff --git a/test/test_radeon_forge_openai.py b/test/test_radeon_forge_openai.py
new file mode 100644
index 0000000000000..f91ed09315afd
--- /dev/null
+++ b/test/test_radeon_forge_openai.py
@@ -0,0 +1,74 @@
+import json
+import tempfile
+import unittest
+
+from extra.radeon_forge.backends.fake import ScriptedBackend
+from extra.radeon_forge.runtime import BackendCapabilities, ForgeEngine, GenerationEvent
+from extra.radeon_forge.ui.openai_api import OpenAIRequestError, collect_chat_completion, stream_chat_completion
+
+
+class ToolBackend:
+ RAW = '{"id":"call-1","name":"read_file","arguments":{"path":"README.md"}} '
+ @property
+ def name(self): return "tool-model"
+ @property
+ def capabilities(self): return BackendCapabilities(structured_tools=True, local_only=True)
+ @property
+ def runtime_metadata(self): return {"architecture":"gfx1100", "runtime":"tinygrad", "model_family":"llama"}
+ def stream(self, request):
+ yield GenerationEvent("prefill", metrics={"prompt_tokens":12, "wall_ms":2.0})
+ yield GenerationEvent("token", self.RAW[:20], metrics={"stage":"first_token", "wall_ms":1.0})
+ yield GenerationEvent("token", self.RAW[20:], metrics={"stage":"decode", "wall_ms":1.0})
+ yield GenerationEvent("tool_call", tool_call={"id":"call-1", "name":"read_file",
+ "arguments":{"path":"README.md"}, "raw":self.RAW})
+ yield GenerationEvent("done", finish_reason="tool_call", metrics={"generated_tokens":2})
+ def close(self): pass
+
+
+class TestOpenAIAdapter(unittest.TestCase):
+ def test_regular_completion_has_standard_shape_and_forge_metrics(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(ScriptedBackend(["hello local world"]), directory)
+ result = collect_chat_completion(engine, {"model":"local", "messages":[{"role":"user", "content":"hello"}],
+ "user":"stable-session"})
+ self.assertEqual(result["object"], "chat.completion")
+ self.assertEqual(result["choices"][0]["message"]["content"], "hello local world")
+ self.assertEqual(result["choices"][0]["finish_reason"], "stop")
+ self.assertEqual(result["forge"]["session_id"], "stable-session")
+ self.assertGreater(result["usage"]["completion_tokens"], 0)
+ engine.close()
+
+ def test_tool_completion_is_structured_and_raw_protocol_is_not_content(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(ToolBackend(), directory)
+ payload = {"messages":[{"role":"user", "content":"read README"}], "tools":[{"type":"function",
+ "function":{"name":"read_file", "description":"read", "parameters":{"type":"object"}}}]}
+ result = collect_chat_completion(engine, payload)
+ message = result["choices"][0]["message"]
+ self.assertIsNone(message["content"])
+ self.assertEqual(message["tool_calls"][0]["function"]["name"], "read_file")
+ self.assertEqual(json.loads(message["tool_calls"][0]["function"]["arguments"]), {"path":"README.md"})
+ self.assertEqual(result["choices"][0]["finish_reason"], "tool_calls")
+ engine.close()
+
+ def test_stream_suppresses_internal_tool_markup(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(ToolBackend(), directory)
+ payload = {"stream":True, "messages":[{"role":"user", "content":"read README"}], "tools":[{"type":"function",
+ "function":{"name":"read_file", "description":"read", "parameters":{"type":"object"}}}]}
+ stream = list(stream_chat_completion(engine, payload))
+ joined = "".join(stream)
+ self.assertNotIn("", joined)
+ self.assertIn('"tool_calls"', joined)
+ self.assertIn('"finish_reason":"tool_calls"', joined)
+ self.assertEqual(stream[-1], "data: [DONE]\n\n")
+ engine.close()
+
+ def test_invalid_messages_fail_before_model_execution(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(ScriptedBackend(), directory)
+ with self.assertRaises(OpenAIRequestError): collect_chat_completion(engine, {"messages":[]})
+ engine.close()
+
+
+if __name__ == "__main__": unittest.main()
From fe23afa78a5dc0084abc8cc7b3e7e1e8a938fcd1 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:08:37 +0530
Subject: [PATCH 135/168] ci: cover structured tools and OpenAI API
---
.github/workflows/radeon-forge.yml | 2 ++
1 file changed, 2 insertions(+)
diff --git a/.github/workflows/radeon-forge.yml b/.github/workflows/radeon-forge.yml
index 0ec5b817635b5..d2d02453ad2ab 100644
--- a/.github/workflows/radeon-forge.yml
+++ b/.github/workflows/radeon-forge.yml
@@ -35,3 +35,5 @@ jobs:
test.test_radeon_forge_hooks
test.test_radeon_forge_autotune
test.test_radeon_forge_kv
+ test.test_radeon_forge_tool_stream
+ test.test_radeon_forge_openai
From bd4ff58ed7a2d2c17c51946dc65d8f0cc21112ca Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:10:50 +0530
Subject: [PATCH 136/168] radeon forge: render OpenAI tools into local model
prompts
---
extra/radeon_forge/runtime/tool_prompt.py | 35 +++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 extra/radeon_forge/runtime/tool_prompt.py
diff --git a/extra/radeon_forge/runtime/tool_prompt.py b/extra/radeon_forge/runtime/tool_prompt.py
new file mode 100644
index 0000000000000..59c0e762de695
--- /dev/null
+++ b/extra/radeon_forge/runtime/tool_prompt.py
@@ -0,0 +1,35 @@
+from __future__ import annotations
+
+import json
+from typing import Any, Mapping, Sequence
+
+
+TOOL_PROTOCOL_MARKER = "Radeon Forge local tool protocol"
+
+
+def render_tool_instruction(tools: Sequence[Mapping[str, Any]]) -> str:
+ rows = []
+ for item in tools:
+ function = item.get("function", {}) if isinstance(item, Mapping) else {}
+ if not isinstance(function, Mapping) or not isinstance(function.get("name"), str): continue
+ rows.append({"name": function["name"], "description": str(function.get("description", "")),
+ "parameters": function.get("parameters", {"type":"object","properties":{}})})
+ if not rows: return ""
+ return f"""{TOOL_PROTOCOL_MARKER}.
+You may call only one of the tools listed below. When a tool is necessary, output exactly one object and no surrounding prose:
+{{"name":"tool_name","arguments":{{...}}}}
+Do not invent a result. Tool execution requires user approval and the result will be returned in a later message.
+Available tools:
+{json.dumps(rows, indent=2, sort_keys=True)}"""
+
+
+def inject_tool_instruction(messages: Sequence[Mapping[str, Any]], tools: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ copied = [dict(message) for message in messages]
+ instruction = render_tool_instruction(tools)
+ if not instruction: return copied
+ if any(TOOL_PROTOCOL_MARKER in str(message.get("content", "")) for message in copied if message.get("role") == "system"):
+ return copied
+ index = next((i for i, message in enumerate(copied) if message.get("role") == "system"), None)
+ if index is None: copied.insert(0, {"role":"system", "content":instruction})
+ else: copied[index]["content"] = str(copied[index].get("content", "")).rstrip() + "\n\n" + instruction
+ return copied
From ba7829b6faa1dbf958e9f360d1a2dfabf5eafe48 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:11:26 +0530
Subject: [PATCH 137/168] radeon forge: inject tool contracts into generic
local inference
---
extra/radeon_forge/runtime/engine.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index a9f9890219553..59c132b8316b2 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -11,6 +11,7 @@
from .backend import GenerationEvent, GenerationRequest, InferenceBackend
from .jobs import LocalJobManager
from .session import AgentSession
+from .tool_prompt import inject_tool_instruction
from .tools import ToolCall, ToolRegistry, WorkspaceTools
@@ -54,8 +55,9 @@ def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, An
def stream_inference(self, messages: Sequence[Mapping[str, Any]], tools: Sequence[Mapping[str, Any]] = (),
max_tokens: int = 256, temperature: float = 0.0, session_id: str | None = None,
stop: Sequence[str] = ()) -> Iterator[GenerationEvent]:
- """Serve the resident local model without losing Forge hooks or profiling events."""
- request = GenerationRequest(session_id or uuid.uuid4().hex, tuple(messages), tuple(tools), max_tokens, temperature,
+ """Serve the resident local model without losing Forge hooks, tools or profiling events."""
+ rendered_messages = inject_tool_instruction(messages, tools)
+ request = GenerationRequest(session_id or uuid.uuid4().hex, tuple(rendered_messages), tuple(tools), max_tokens, temperature,
tuple(stop), metadata=self.inference_metadata())
return self.backend.stream(request)
From aa7fd3c5633a3aec546f7b46d22c67754920ab35 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:11:43 +0530
Subject: [PATCH 138/168] radeon forge: test local tool prompt injection
---
test/test_radeon_forge_tool_prompt.py | 33 +++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
create mode 100644 test/test_radeon_forge_tool_prompt.py
diff --git a/test/test_radeon_forge_tool_prompt.py b/test/test_radeon_forge_tool_prompt.py
new file mode 100644
index 0000000000000..b581bc911dd0f
--- /dev/null
+++ b/test/test_radeon_forge_tool_prompt.py
@@ -0,0 +1,33 @@
+import unittest
+
+from extra.radeon_forge.runtime.tool_prompt import TOOL_PROTOCOL_MARKER, inject_tool_instruction, render_tool_instruction
+
+
+class TestToolPrompt(unittest.TestCase):
+ def test_tool_schema_is_rendered_for_local_model(self):
+ tools = [{"type":"function", "function":{"name":"read_file", "description":"Read a file",
+ "parameters":{"type":"object", "properties":{"path":{"type":"string"}}, "required":["path"]}}}]
+ text = render_tool_instruction(tools)
+ self.assertIn(TOOL_PROTOCOL_MARKER, text)
+ self.assertIn('"name": "read_file"', text)
+ self.assertIn('', text)
+
+ def test_instruction_merges_into_existing_system_message_once(self):
+ tools = [{"type":"function", "function":{"name":"read_file", "parameters":{"type":"object"}}}]
+ original = [{"role":"system", "content":"Be precise."}, {"role":"user", "content":"Read it"}]
+ injected = inject_tool_instruction(original, tools)
+ self.assertEqual(len(injected), 2)
+ self.assertTrue(injected[0]["content"].startswith("Be precise."))
+ self.assertEqual(injected[0]["content"].count(TOOL_PROTOCOL_MARKER), 1)
+ reinjected = inject_tool_instruction(injected, tools)
+ self.assertEqual(reinjected[0]["content"].count(TOOL_PROTOCOL_MARKER), 1)
+ self.assertEqual(original[0]["content"], "Be precise.")
+
+ def test_instruction_is_prepended_when_no_system_message_exists(self):
+ tools = [{"type":"function", "function":{"name":"search_text", "parameters":{"type":"object"}}}]
+ injected = inject_tool_instruction([{"role":"user", "content":"Search"}], tools)
+ self.assertEqual(injected[0]["role"], "system")
+ self.assertIn(TOOL_PROTOCOL_MARKER, injected[0]["content"])
+
+
+if __name__ == "__main__": unittest.main()
From 32aa6bd62317fd25f200a859cd59da3eb7b39b1e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:13:12 +0530
Subject: [PATCH 139/168] radeon forge: add signal-backed cancellation token
---
extra/radeon_forge/backends/cancellation.py | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
create mode 100644 extra/radeon_forge/backends/cancellation.py
diff --git a/extra/radeon_forge/backends/cancellation.py b/extra/radeon_forge/backends/cancellation.py
new file mode 100644
index 0000000000000..06686ffde3f29
--- /dev/null
+++ b/extra/radeon_forge/backends/cancellation.py
@@ -0,0 +1,21 @@
+from __future__ import annotations
+
+import signal, threading
+
+
+class SignalCancellation:
+ """Process-local cooperative cancellation set by SIGUSR1."""
+ def __init__(self):
+ self._event = threading.Event()
+ self.installed = False
+
+ def install(self) -> bool:
+ if not hasattr(signal, "SIGUSR1"): return False
+ signal.signal(signal.SIGUSR1, lambda _signum, _frame: self._event.set())
+ self.installed = True
+ return True
+
+ def reset(self) -> None: self._event.clear()
+ def request(self) -> None: self._event.set()
+ @property
+ def requested(self) -> bool: return self._event.is_set()
From c79f8c5f693fdb308feec279f990dd3616f50127 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:16:36 +0530
Subject: [PATCH 140/168] radeon forge: preserve resumable state after
cancellation
---
extra/radeon_forge/runtime/session.py | 30 +++++++++++++++++++++++++--
1 file changed, 28 insertions(+), 2 deletions(-)
diff --git a/extra/radeon_forge/runtime/session.py b/extra/radeon_forge/runtime/session.py
index d02c7661fdaa2..7de3e59efc2e1 100644
--- a/extra/radeon_forge/runtime/session.py
+++ b/extra/radeon_forge/runtime/session.py
@@ -16,6 +16,7 @@ class SessionState(str, Enum):
AWAITING_TOOL_APPROVAL = "awaiting_tool_approval"
RUNNING_TOOL = "running_tool"
COMPLETED = "completed"
+ CANCELLED = "cancelled"
FAILED = "failed"
@@ -41,6 +42,7 @@ def __init__(self, backend: InferenceBackend, tools: ToolRegistry, system_prompt
self.pending_tool_call: ToolCall | None = None
self.pending_assistant_content = ""
self.partial_output = ""
+ self.last_finish_reason: str | None = None
self.state = SessionState.IDLE
self._sequence = 0
self._lock = threading.RLock()
@@ -61,6 +63,12 @@ def _tool_content(call: ToolCall) -> str:
payload = {"id": call.call_id, "name": call.name, "arguments": dict(call.arguments)}
return f"{json.dumps(payload, separators=(',', ':'))} "
+ @staticmethod
+ def _looks_like_partial_tool_protocol(output: str) -> bool:
+ stripped = output.lstrip()
+ marker = ""
+ return bool(stripped) and (marker.startswith(stripped) or stripped.startswith(marker))
+
def _emit(self, kind: str, **data: Any) -> SessionEvent:
self._sequence += 1
event = SessionEvent(self._sequence, kind, data)
@@ -103,8 +111,10 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
self.state = SessionState.GENERATING
self.partial_output = ""
self.pending_assistant_content = ""
+ self.last_finish_reason = None
started_at = len(self.events)
pieces: list[str] = []
+ done_metrics: dict[str, Any] = {}
step = sum(1 for event in self.events if event.kind == "generation_started") + 1
if step > self.max_agent_steps: raise RuntimeError("agent step limit exceeded")
with self.trace.span("agent", "model_turn", session_id=self.session_id, step=step) as parent:
@@ -130,12 +140,28 @@ def _generate(self, max_tokens: int, temperature: float) -> tuple[SessionEvent,
raw = event.tool_call.get("raw")
if isinstance(raw, str): self.pending_assistant_content = raw
self._emit("structured_tool_call", call=asdict(self.pending_tool_call), native=True)
- elif event.kind == "done": self._emit("generation_done", finish_reason=event.finish_reason, metrics=dict(event.metrics))
+ elif event.kind == "done":
+ self.last_finish_reason = event.finish_reason
+ done_metrics = dict(event.metrics)
+ self._emit("generation_done", finish_reason=event.finish_reason, metrics=done_metrics)
except Exception as exc:
self.state = SessionState.FAILED
self._emit("error", error=str(exc), error_type=type(exc).__name__)
raise
output = "".join(pieces)
+
+ if self.last_finish_reason == "cancelled":
+ discarded_tool_prefix = self._looks_like_partial_tool_protocol(output)
+ if output and not discarded_tool_prefix: self.messages.append({"role": "assistant", "content": output})
+ self.pending_tool_call = None
+ self.pending_assistant_content = ""
+ self.partial_output = ""
+ self.state = SessionState.CANCELLED
+ self._emit("generation_cancelled", preserved_output=bool(output and not discarded_tool_prefix),
+ discarded_incomplete_tool_protocol=discarded_tool_prefix, generated_characters=len(output),
+ materialized_kv_tokens=done_metrics.get("materialized_kv_tokens"), cancel_stage=done_metrics.get("cancel_stage"))
+ return tuple(self.events[started_at:])
+
if self.pending_tool_call is None:
try:
self.pending_tool_call = parse_tool_call(output)
@@ -200,4 +226,4 @@ def snapshot(self) -> dict[str, Any]:
return {"session_id": self.session_id, "state": self.state.value, "messages": list(self.messages),
"events": [asdict(x) for x in self.events], "pending_tool_call": asdict(self.pending_tool_call) if self.pending_tool_call else None,
"pending_assistant_content": self.pending_assistant_content, "partial_output": self.partial_output,
- "trace_id": self.trace.trace_id}
+ "last_finish_reason": self.last_finish_reason, "trace_id": self.trace.trace_id}
From a29dc1819f720deb05ea762be20a8e0e3ad142a2 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:17:51 +0530
Subject: [PATCH 141/168] radeon forge: serialize and cancel resident model
execution safely
---
extra/radeon_forge/runtime/engine.py | 61 +++++++++++++++++++++++-----
1 file changed, 51 insertions(+), 10 deletions(-)
diff --git a/extra/radeon_forge/runtime/engine.py b/extra/radeon_forge/runtime/engine.py
index 59c132b8316b2..0dde5a45ec2f1 100644
--- a/extra/radeon_forge/runtime/engine.py
+++ b/extra/radeon_forge/runtime/engine.py
@@ -1,20 +1,22 @@
from __future__ import annotations
-import threading, uuid
+import contextlib, threading, uuid
from dataclasses import asdict
from pathlib import Path
-from typing import Any, Iterator, Mapping, Sequence
+from typing import Any, Callable, Iterator, Mapping, Sequence, TypeVar
from ..permissions import PermissionController
from ..profiling.report import build_profile_report
from ..synthesis import CandidateWorkspace, OptimizationTools, RuntimeFingerprint, SafeHookRegistry, install_default_specs
from .backend import GenerationEvent, GenerationRequest, InferenceBackend
from .jobs import LocalJobManager
-from .session import AgentSession
+from .session import AgentSession, SessionState
from .tool_prompt import inject_tool_instruction
from .tools import ToolCall, ToolRegistry, WorkspaceTools
+T = TypeVar("T")
+
DEFAULT_SYSTEM_PROMPT = """You are Radeon Forge, a private local software and inference performance engineer.
Use evidence before making performance claims. Separate observations, inferences and unknowns. Prefer reversible changes and preserve correctness. You may inspect the private workspace, author disposable target-specific kernel candidates, import portable optimization recipes, validate implementations through tinygrad MockGPU, and request permission for real W7900 benchmarks. Never treat MockGPU timing as performance evidence.
@@ -35,6 +37,9 @@ def __init__(self, backend: InferenceBackend, workspace: str | Path, system_prom
self.jobs = LocalJobManager()
self._sessions: dict[str, AgentSession] = {}
self._lock = threading.RLock()
+ self._generation_gate = threading.Lock()
+ self._generation_state_lock = threading.RLock()
+ self._active_generation_id: str | None = None
def runtime_fingerprint(self) -> RuntimeFingerprint:
metadata = getattr(self.backend, "runtime_metadata", {})
@@ -52,14 +57,33 @@ def inference_metadata(self) -> dict[str, Any]:
def _session_metadata(self, session: AgentSession, step: int) -> Mapping[str, Any]: return self.inference_metadata()
+ @contextlib.contextmanager
+ def _generation_slot(self, generation_id: str):
+ with self._generation_gate:
+ with self._generation_state_lock: self._active_generation_id = generation_id
+ try: yield
+ finally:
+ with self._generation_state_lock:
+ if self._active_generation_id == generation_id: self._active_generation_id = None
+
+ def _run_generation(self, generation_id: str, fn: Callable[[], T]) -> T:
+ with self._generation_slot(generation_id): return fn()
+
+ @property
+ def active_generation_id(self) -> str | None:
+ with self._generation_state_lock: return self._active_generation_id
+
def stream_inference(self, messages: Sequence[Mapping[str, Any]], tools: Sequence[Mapping[str, Any]] = (),
max_tokens: int = 256, temperature: float = 0.0, session_id: str | None = None,
stop: Sequence[str] = ()) -> Iterator[GenerationEvent]:
"""Serve the resident local model without losing Forge hooks, tools or profiling events."""
+ generation_id = session_id or uuid.uuid4().hex
rendered_messages = inject_tool_instruction(messages, tools)
- request = GenerationRequest(session_id or uuid.uuid4().hex, tuple(rendered_messages), tuple(tools), max_tokens, temperature,
+ request = GenerationRequest(generation_id, tuple(rendered_messages), tuple(tools), max_tokens, temperature,
tuple(stop), metadata=self.inference_metadata())
- return self.backend.stream(request)
+ def iterator():
+ with self._generation_slot(generation_id): yield from self.backend.stream(request)
+ return iterator()
def create_session(self) -> AgentSession:
with self._lock:
@@ -74,17 +98,33 @@ def session(self, session_id: str) -> AgentSession:
def sessions(self) -> list[dict[str, Any]]:
with self._lock: return [{"session_id": x.session_id, "state": x.state.value, "trace_id": x.trace.trace_id} for x in self._sessions.values()]
- def submit_message(self, session_id: str, content: str, max_tokens: int = 512, temperature: float = 0.0) -> dict[str, Any]:
+ def run_message(self, session_id: str, content: str, max_tokens: int = 512, temperature: float = 0.0):
session = self.session(session_id)
- job = self.jobs.submit("agent_turn", session_id, lambda: session.send(content, max_tokens, temperature))
+ return self._run_generation(session_id, lambda: session.send(content, max_tokens, temperature))
+
+ def submit_message(self, session_id: str, content: str, max_tokens: int = 512, temperature: float = 0.0) -> dict[str, Any]:
+ job = self.jobs.submit("agent_turn", session_id, lambda: self.run_message(session_id, content, max_tokens, temperature))
return asdict(job)
- def submit_tool_approval(self, session_id: str, reason: str, max_tokens: int = 512) -> dict[str, Any]:
+ def run_tool_approval(self, session_id: str, reason: str, max_tokens: int = 512):
session = self.session(session_id)
token = self.grant_for_pending_tool(session_id, reason)
- job = self.jobs.submit("tool_and_resume", session_id, lambda: session.approve_tool(token, max_tokens))
+ return self._run_generation(session_id, lambda: session.approve_tool(token, max_tokens))
+
+ def submit_tool_approval(self, session_id: str, reason: str, max_tokens: int = 512) -> dict[str, Any]:
+ job = self.jobs.submit("tool_and_resume", session_id, lambda: self.run_tool_approval(session_id, reason, max_tokens))
return asdict(job)
+ def cancel_generation(self, session_id: str) -> dict[str, Any]:
+ session = self.session(session_id)
+ if not self.backend.capabilities.cancellation: raise RuntimeError("resident model backend does not support cooperative cancellation")
+ active = self.active_generation_id
+ if active != session_id or session.state is not SessionState.GENERATING:
+ raise RuntimeError(f"session {session_id} is not the active model generation")
+ self.backend.cancel()
+ return {"requested": True, "session_id": session_id, "active_generation_id": active,
+ "state": session.state.value, "model_remains_resident": True, "kv_state_preserved": True}
+
def grant_for_pending_tool(self, session_id: str, reason: str, max_uses: int = 1) -> str:
session = self.session(session_id)
if session.pending_tool_call is None: raise RuntimeError("session has no pending tool")
@@ -109,6 +149,7 @@ def optimization_state(self) -> dict[str, Any]:
"recipes": [asdict(x) for x in self.optimization_tools.recipes.installed()],
"active_hooks": [asdict(x) for x in self.hooks.active()],
"runtime_fingerprint": asdict(self.runtime_fingerprint()),
- "runtime_adapters": sorted(self.hooks.SUPPORTED_ADAPTERS)}
+ "runtime_adapters": sorted(self.hooks.SUPPORTED_ADAPTERS),
+ "active_generation_id": self.active_generation_id}
def close(self) -> None: self.backend.close()
From cd2896446ff9db7df753cec11df035caddee476f Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:22:36 +0530
Subject: [PATCH 142/168] radeon forge: add cross-token stop sequence matcher
---
extra/radeon_forge/runtime/stop_sequences.py | 54 ++++++++++++++++++++
1 file changed, 54 insertions(+)
create mode 100644 extra/radeon_forge/runtime/stop_sequences.py
diff --git a/extra/radeon_forge/runtime/stop_sequences.py b/extra/radeon_forge/runtime/stop_sequences.py
new file mode 100644
index 0000000000000..41f6d26f234d9
--- /dev/null
+++ b/extra/radeon_forge/runtime/stop_sequences.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Iterable
+
+
+@dataclass(frozen=True)
+class StopMatch:
+ text: str
+ matched: str | None = None
+
+
+class StopSequenceMatcher:
+ """Incrementally hides stop strings even when they cross token boundaries."""
+ def __init__(self, stops: Iterable[str]):
+ values = tuple(dict.fromkeys(str(stop) for stop in stops))
+ if any(not stop for stop in values): raise ValueError("stop sequences must not be empty")
+ self.stops = values
+ self.buffer = ""
+ self.done = False
+
+ def feed(self, text: str) -> StopMatch:
+ if self.done: raise RuntimeError("stop matcher is already complete")
+ self.buffer += text
+ earliest: tuple[int, str] | None = None
+ for stop in self.stops:
+ index = self.buffer.find(stop)
+ if index >= 0 and (earliest is None or index < earliest[0] or (index == earliest[0] and len(stop) > len(earliest[1]))):
+ earliest = (index, stop)
+ if earliest is not None:
+ index, stop = earliest
+ output = self.buffer[:index]
+ self.buffer = ""
+ self.done = True
+ return StopMatch(output, stop)
+
+ keep = 0
+ for stop in self.stops:
+ limit = min(len(stop) - 1, len(self.buffer))
+ for length in range(limit, 0, -1):
+ if self.buffer.endswith(stop[:length]):
+ keep = max(keep, length)
+ break
+ if keep:
+ output, self.buffer = self.buffer[:-keep], self.buffer[-keep:]
+ else:
+ output, self.buffer = self.buffer, ""
+ return StopMatch(output)
+
+ def finalize(self) -> str:
+ if self.done: return ""
+ output, self.buffer = self.buffer, ""
+ self.done = True
+ return output
From 9c42981f3885631659f7f391c4f58237f84fdd71 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:22:49 +0530
Subject: [PATCH 143/168] radeon forge: test cross-token stop handling
---
test/test_radeon_forge_stop_sequences.py | 36 ++++++++++++++++++++++++
1 file changed, 36 insertions(+)
create mode 100644 test/test_radeon_forge_stop_sequences.py
diff --git a/test/test_radeon_forge_stop_sequences.py b/test/test_radeon_forge_stop_sequences.py
new file mode 100644
index 0000000000000..9b27f2e70c7fc
--- /dev/null
+++ b/test/test_radeon_forge_stop_sequences.py
@@ -0,0 +1,36 @@
+import unittest
+
+from extra.radeon_forge.runtime.stop_sequences import StopSequenceMatcher
+
+
+class TestStopSequenceMatcher(unittest.TestCase):
+ def test_stop_split_across_tokens_is_not_emitted(self):
+ matcher = StopSequenceMatcher([""])
+ self.assertEqual(matcher.feed("answerignored")
+ self.assertEqual(matched.text, "")
+ self.assertEqual(matched.matched, "")
+ self.assertEqual(matcher.finalize(), "")
+
+ def test_ambiguous_prefix_is_released_when_it_stops_matching(self):
+ matcher = StopSequenceMatcher(["STOP"])
+ self.assertEqual(matcher.feed("hello ST").text, "hello ")
+ self.assertEqual(matcher.feed("AR").text, "STAR")
+ self.assertEqual(matcher.finalize(), "")
+
+ def test_earliest_stop_wins(self):
+ matcher = StopSequenceMatcher(["END", "STOP"])
+ result = matcher.feed("one STOP two END")
+ self.assertEqual(result.text, "one ")
+ self.assertEqual(result.matched, "STOP")
+
+ def test_finalize_releases_safe_suffix(self):
+ matcher = StopSequenceMatcher(["STOP"])
+ self.assertEqual(matcher.feed("value ST").text, "value ")
+ self.assertEqual(matcher.finalize(), "ST")
+
+ def test_empty_stop_is_rejected(self):
+ with self.assertRaises(ValueError): StopSequenceMatcher([""])
+
+
+if __name__ == "__main__": unittest.main()
From 0996d8266f148e159063b4af91e54328a9c2502b Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:30:18 +0530
Subject: [PATCH 144/168] radeon forge: test stop-buffered text transport
---
test/test_radeon_forge_text_events.py | 57 +++++++++++++++++++++++++++
1 file changed, 57 insertions(+)
create mode 100644 test/test_radeon_forge_text_events.py
diff --git a/test/test_radeon_forge_text_events.py b/test/test_radeon_forge_text_events.py
new file mode 100644
index 0000000000000..d74fcd71bb469
--- /dev/null
+++ b/test/test_radeon_forge_text_events.py
@@ -0,0 +1,57 @@
+import tempfile
+import unittest
+
+from extra.radeon_forge.profiling.report import build_profile_report
+from extra.radeon_forge.runtime import BackendCapabilities, ForgeEngine, GenerationEvent
+from extra.radeon_forge.ui.openai_api import collect_chat_completion, stream_chat_completion
+
+
+class BufferedTextBackend:
+ @property
+ def name(self): return "buffered-text-local"
+
+ @property
+ def capabilities(self): return BackendCapabilities(streaming=True, local_only=True)
+
+ @property
+ def runtime_metadata(self): return {"architecture":"gfx1100", "runtime":"tinygrad", "model_family":"llama"}
+
+ def stream(self, request):
+ yield GenerationEvent("prefill", metrics={"prompt_tokens":8, "wall_ms":1.0})
+ # A real model token was generated, but its characters were withheld while
+ # Forge determined whether they were the prefix of a cross-token stop.
+ yield GenerationEvent("token", "", metrics={"index":0, "stage":"first_token", "wall_ms":2.0,
+ "gpu_ms":1.5, "kernel_count":20})
+ yield GenerationEvent("text", "visible answer", metrics={"stage":"first_token", "buffered_for_stop_sequence":True})
+ yield GenerationEvent("done", finish_reason="stop", metrics={"generated_tokens":1, "stop_sequence":""})
+
+ def close(self): pass
+
+
+class TestBufferedTextTransport(unittest.TestCase):
+ def test_agent_session_preserves_text_without_fake_token(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(BufferedTextBackend(), directory)
+ session = engine.create_session()
+ engine.run_message(session.session_id, "answer until the stop marker")
+ self.assertEqual(session.messages[-1]["content"], "visible answer")
+ report = build_profile_report(session.trace.events())
+ self.assertEqual(report["summary"]["decode_tokens"], 1)
+ self.assertEqual(report["summary"]["token_wall_ms_p50"], 2.0)
+ self.assertEqual(len([event for event in session.events if event.kind == "text"]), 1)
+ engine.close()
+
+ def test_openai_completion_and_stream_include_visible_text(self):
+ payload = {"messages":[{"role":"user", "content":"answer"}], "stop":[""]}
+ with tempfile.TemporaryDirectory() as directory:
+ engine = ForgeEngine(BufferedTextBackend(), directory)
+ result = collect_chat_completion(engine, payload)
+ self.assertEqual(result["choices"][0]["message"]["content"], "visible answer")
+ self.assertEqual(result["usage"]["completion_tokens"], 1)
+ stream = "".join(stream_chat_completion(engine, {**payload, "session_id":"stream-session"}))
+ self.assertIn("visible answer", stream)
+ self.assertIn('"finish_reason":"stop"', stream)
+ engine.close()
+
+
+if __name__ == "__main__": unittest.main()
From 8b227551cbc74506f95dc6c2c8cd064f76e8b217 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:31:37 +0530
Subject: [PATCH 145/168] radeon forge: add tool execution provenance context
---
extra/radeon_forge/runtime/tool_context.py | 37 ++++++++++++++++++++++
1 file changed, 37 insertions(+)
create mode 100644 extra/radeon_forge/runtime/tool_context.py
diff --git a/extra/radeon_forge/runtime/tool_context.py b/extra/radeon_forge/runtime/tool_context.py
new file mode 100644
index 0000000000000..dd9b98ea496c1
--- /dev/null
+++ b/extra/radeon_forge/runtime/tool_context.py
@@ -0,0 +1,37 @@
+from __future__ import annotations
+
+import contextlib
+from contextvars import ContextVar
+from dataclasses import asdict, dataclass
+from typing import Any, Iterator, Mapping
+
+
+@dataclass(frozen=True)
+class ToolExecutionContext:
+ session_id: str
+ trace_id: str
+ agent_step: int
+ tool_call_id: str
+ tool_name: str
+ attributes: Mapping[str, Any]
+
+
+_CURRENT: ContextVar[ToolExecutionContext | None] = ContextVar("RADEON_FORGE_TOOL_CONTEXT", default=None)
+
+
+@contextlib.contextmanager
+def bind_tool_context(context: ToolExecutionContext) -> Iterator[None]:
+ token = _CURRENT.set(context)
+ try: yield
+ finally: _CURRENT.reset(token)
+
+
+def current_tool_context(required: bool = False) -> ToolExecutionContext | None:
+ context = _CURRENT.get()
+ if required and context is None: raise RuntimeError("tool execution provenance is unavailable")
+ return context
+
+
+def current_tool_context_dict() -> dict[str, Any]:
+ context = current_tool_context()
+ return asdict(context) if context is not None else {}
From ccd495fb622f93c3ae61614e383c193552d8f2eb Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:32:18 +0530
Subject: [PATCH 146/168] radeon forge: add ROCm counter and ATT capture
adapter
---
extra/radeon_forge/profiling/capture.py | 177 ++++++++++++++++++++++++
1 file changed, 177 insertions(+)
create mode 100644 extra/radeon_forge/profiling/capture.py
diff --git a/extra/radeon_forge/profiling/capture.py b/extra/radeon_forge/profiling/capture.py
new file mode 100644
index 0000000000000..887f4dc4608b0
--- /dev/null
+++ b/extra/radeon_forge/profiling/capture.py
@@ -0,0 +1,177 @@
+from __future__ import annotations
+
+import csv, hashlib, json, os, shutil, subprocess, time, uuid
+from dataclasses import asdict, dataclass, field
+from enum import Enum
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+
+class CaptureKind(str, Enum):
+ COUNTERS = "counters"
+ ATT = "att"
+
+
+@dataclass(frozen=True)
+class CaptureRequest:
+ kind: CaptureKind
+ command: tuple[str, ...]
+ stage: str
+ session_id: str = ""
+ trace_id: str = ""
+ agent_step: int = 0
+ kernel_regex: str = ""
+ counters: tuple[str, ...] = ()
+ timeout_seconds: int = 900
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class CaptureArtifact:
+ path: str
+ size_bytes: int
+ sha256: str
+ suffix: str
+
+
+@dataclass(frozen=True)
+class CaptureResult:
+ capture_id: str
+ kind: str
+ passed: bool
+ output_directory: str
+ profiler_command: tuple[str, ...]
+ target_command: tuple[str, ...]
+ returncode: int | None
+ elapsed_ms: float
+ stdout_tail: str
+ stderr_tail: str
+ artifacts: tuple[CaptureArtifact, ...]
+ summary: Mapping[str, Any]
+ error: str = ""
+
+ def to_dict(self) -> dict[str, Any]: return asdict(self)
+
+
+class Rocprofv3Adapter:
+ """Evidence-preserving rocprofv3 adapter for counters and ATT/SQTT.
+
+ CLI options are detected from the installed profiler help rather than assumed
+ from a particular ROCm release. Performance is always measured by the target
+ hardware; this adapter only captures and normalizes evidence.
+ """
+ def __init__(self, project_root: str | Path, evidence_root: str | Path):
+ self.project_root = Path(project_root).resolve()
+ self.evidence_root = Path(evidence_root).resolve()
+ self.evidence_root.mkdir(parents=True, exist_ok=True)
+
+ @staticmethod
+ def executable() -> str | None: return shutil.which("rocprofv3")
+
+ def probe(self) -> dict[str, Any]:
+ executable = self.executable()
+ if executable is None: return {"available":False, "reason":"rocprofv3 is not on PATH"}
+ version = subprocess.run([executable, "--version"], text=True, capture_output=True, timeout=20)
+ help_run = subprocess.run([executable, "--help"], text=True, capture_output=True, timeout=20)
+ help_text = help_run.stdout + "\n" + help_run.stderr
+ avail_exe = shutil.which("rocprofv3-avail")
+ available = None
+ if avail_exe:
+ proc = subprocess.run([avail_exe, "list"], text=True, capture_output=True, timeout=60)
+ available = {"returncode":proc.returncode, "stdout":proc.stdout[-50000:], "stderr":proc.stderr[-10000:]}
+ return {"available":True, "executable":executable, "version_returncode":version.returncode,
+ "version":(version.stdout+version.stderr).strip(), "supports_att":"--att" in help_text,
+ "supports_kernel_regex":"--kernel-include-regex" in help_text, "supports_pmc":"--pmc" in help_text,
+ "supports_output_directory":"--output-directory" in help_text or " -d" in help_text,
+ "available_components":available}
+
+ def _validate_target(self, command: Sequence[str]) -> tuple[str, ...]:
+ argv = tuple(str(x) for x in command)
+ if not argv: raise ValueError("profile target command must not be empty")
+ executable = Path(argv[0]).name
+ allowed = {"python", "python3", "pytest", "tinygrad", "radeon-forge"}
+ if executable not in allowed: raise ValueError(f"profile target executable {executable!r} is not allowlisted")
+ if any("\x00" in part for part in argv): raise ValueError("profile command contains NUL")
+ return argv
+
+ def _profiler_command(self, request: CaptureRequest, output: Path, help_text: str) -> tuple[str, ...]:
+ executable = self.executable()
+ if executable is None: raise RuntimeError("rocprofv3 is not installed")
+ args: list[str] = [executable]
+ if request.kind is CaptureKind.ATT:
+ if "--att" not in help_text: raise RuntimeError("installed rocprofv3 does not advertise ATT support")
+ args.append("--att")
+ if "--att-simd-select" in help_text: args += ["--att-simd-select", "0x0"]
+ if request.kernel_regex:
+ if "--kernel-include-regex" not in help_text: raise RuntimeError("installed rocprofv3 cannot filter ATT by kernel regex")
+ args += ["--kernel-include-regex", request.kernel_regex]
+ elif request.kind is CaptureKind.COUNTERS:
+ if not request.counters: raise ValueError("counter capture requires at least one counter")
+ if "--pmc" not in help_text: raise RuntimeError("installed rocprofv3 does not advertise --pmc counter collection")
+ args += ["--pmc", ",".join(request.counters)]
+ else: raise ValueError(request.kind)
+ if "--output-directory" in help_text: args += ["--output-directory", str(output)]
+ else: args += ["-d", str(output)]
+ return tuple(args + ["--"] + list(request.command))
+
+ @staticmethod
+ def _artifacts(root: Path) -> tuple[CaptureArtifact, ...]:
+ ret = []
+ for path in sorted(root.rglob("*")):
+ if not path.is_file(): continue
+ data = path.read_bytes()
+ ret.append(CaptureArtifact(str(path), len(data), hashlib.sha256(data).hexdigest(), path.suffix.lower()))
+ return tuple(ret)
+
+ @staticmethod
+ def _csv_summary(root: Path) -> dict[str, Any]:
+ files, rows, columns = 0, 0, set()
+ numeric: dict[str, list[float]] = {}
+ for path in root.rglob("*.csv"):
+ files += 1
+ try:
+ with path.open(newline="", encoding="utf-8", errors="replace") as handle:
+ reader = csv.DictReader(handle)
+ columns.update(reader.fieldnames or ())
+ for row in reader:
+ rows += 1
+ for key, value in row.items():
+ try: numeric.setdefault(str(key), []).append(float(value))
+ except (TypeError, ValueError): pass
+ except OSError: continue
+ aggregate = {key:{"count":len(values), "min":min(values), "max":max(values), "mean":sum(values)/len(values)}
+ for key, values in numeric.items() if values}
+ return {"csv_files":files, "csv_rows":rows, "columns":sorted(columns), "numeric_columns":aggregate}
+
+ def capture(self, request: CaptureRequest) -> CaptureResult:
+ target = self._validate_target(request.command)
+ capture_id = f"{request.kind.value}-{time.strftime('%Y%m%dT%H%M%S')}-{uuid.uuid4().hex[:10]}"
+ output = self.evidence_root / capture_id
+ output.mkdir(parents=True, exist_ok=False)
+ manifest_path = output / "forge_capture_manifest.json"
+ started = time.perf_counter_ns()
+ returncode: int | None = None
+ stdout = stderr = error = ""
+ profiler_command: tuple[str, ...] = ()
+ try:
+ executable = self.executable()
+ if executable is None: raise RuntimeError("rocprofv3 is not installed")
+ help_run = subprocess.run([executable, "--help"], text=True, capture_output=True, timeout=20)
+ help_text = help_run.stdout + "\n" + help_run.stderr
+ profiler_command = self._profiler_command(request, output, help_text)
+ env = {**os.environ, "PYTHONUNBUFFERED":"1", "RADEON_FORGE_CAPTURE_ID":capture_id,
+ "RADEON_FORGE_EXECUTION_STAGE":request.stage, "RADEON_FORGE_TRACE_ID":request.trace_id}
+ proc = subprocess.run(profiler_command, cwd=self.project_root, env=env, text=True, capture_output=True,
+ timeout=max(1, min(request.timeout_seconds, 3600)))
+ returncode, stdout, stderr = proc.returncode, proc.stdout, proc.stderr
+ except Exception as exc: error = f"{type(exc).__name__}: {exc}"
+ elapsed_ms = (time.perf_counter_ns() - started) / 1e6
+ artifacts = tuple(x for x in self._artifacts(output) if Path(x.path) != manifest_path)
+ summary = {"stage":request.stage, "session_id":request.session_id, "trace_id":request.trace_id,
+ "agent_step":request.agent_step, "kernel_regex":request.kernel_regex, "counters":list(request.counters),
+ "capture_metadata":dict(request.metadata), "parsed_csv":self._csv_summary(output)}
+ passed = returncode == 0 and not error and bool(artifacts)
+ result = CaptureResult(capture_id, request.kind.value, passed, str(output), profiler_command, target, returncode,
+ elapsed_ms, stdout[-50000:], stderr[-50000:], artifacts, summary, error)
+ manifest_path.write_text(json.dumps(result.to_dict(), indent=2, default=str), encoding="utf-8")
+ return result
From d7d7240349e2030028a37045accc5fdab8e2b7fa Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:32:49 +0530
Subject: [PATCH 147/168] radeon forge: expose stage-scoped ROCm profiler tools
---
extra/radeon_forge/profiling/tools.py | 86 +++++++++++++++++++++++++++
1 file changed, 86 insertions(+)
create mode 100644 extra/radeon_forge/profiling/tools.py
diff --git a/extra/radeon_forge/profiling/tools.py b/extra/radeon_forge/profiling/tools.py
new file mode 100644
index 0000000000000..e81bd30a4ba94
--- /dev/null
+++ b/extra/radeon_forge/profiling/tools.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import json
+from dataclasses import asdict
+from pathlib import Path
+from typing import Any, Mapping
+
+from ..permissions import Action
+from ..runtime.tool_context import current_tool_context
+from ..runtime.tools import ToolRegistry, ToolSpec
+from .capture import CaptureKind, CaptureRequest, Rocprofv3Adapter
+
+
+class ProfilingTools:
+ def __init__(self, project_root: str | Path, evidence_root: str | Path):
+ self.adapter = Rocprofv3Adapter(project_root, evidence_root)
+
+ @staticmethod
+ def _context() -> dict[str, Any]:
+ context = current_tool_context()
+ return asdict(context) if context is not None else {}
+
+ @staticmethod
+ def _command(value: Any) -> tuple[str, ...]:
+ if not isinstance(value, list) or not value or not all(isinstance(x, str) for x in value):
+ raise ValueError("command must be a non-empty string array")
+ return tuple(value)
+
+ def probe(self, args: Mapping[str, Any]) -> Any: return self.adapter.probe()
+
+ def _capture(self, kind: CaptureKind, args: Mapping[str, Any]) -> Any:
+ context = self._context()
+ request = CaptureRequest(
+ kind=kind,
+ command=self._command(args.get("command")),
+ stage=str(args.get("stage", "unknown")),
+ session_id=str(context.get("session_id", args.get("session_id", ""))),
+ trace_id=str(context.get("trace_id", args.get("trace_id", ""))),
+ agent_step=int(context.get("agent_step", args.get("agent_step", 0))),
+ kernel_regex=str(args.get("kernel_regex", "")),
+ counters=tuple(str(x) for x in args.get("counters", ())),
+ timeout_seconds=int(args.get("timeout_seconds", 900)),
+ metadata={"tool_call_id":context.get("tool_call_id", ""), "tool_name":context.get("tool_name", ""),
+ **dict(args.get("metadata", {}))},
+ )
+ return self.adapter.capture(request).to_dict()
+
+ def capture_counters(self, args: Mapping[str, Any]) -> Any: return self._capture(CaptureKind.COUNTERS, args)
+ def capture_att(self, args: Mapping[str, Any]) -> Any: return self._capture(CaptureKind.ATT, args)
+
+ def list_captures(self, args: Mapping[str, Any]) -> Any:
+ captures = []
+ for path in sorted(self.adapter.evidence_root.glob("*/forge_capture_manifest.json"), reverse=True):
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ captures.append({"capture_id":payload.get("capture_id", path.parent.name), "kind":payload.get("kind"),
+ "passed":payload.get("passed"), "elapsed_ms":payload.get("elapsed_ms"), "output_directory":str(path.parent),
+ "summary":payload.get("summary", {}), "artifact_count":len(payload.get("artifacts", [])),
+ "error":payload.get("error", "")})
+ except Exception: continue
+ return {"captures":captures[:max(1, min(int(args.get("limit", 50)), 500))]}
+
+ def inspect_capture(self, args: Mapping[str, Any]) -> Any:
+ capture_id = str(args["capture_id"])
+ if "/" in capture_id or ".." in capture_id: raise ValueError("invalid capture id")
+ path = self.adapter.evidence_root / capture_id / "forge_capture_manifest.json"
+ if not path.is_file(): raise KeyError(f"unknown capture {capture_id}")
+ return json.loads(path.read_text(encoding="utf-8"))
+
+ def install(self, registry: ToolRegistry) -> None:
+ registry.register(ToolSpec("probe_rocm_profiler", "Inspect the installed local rocprofv3/ATT capabilities without running a workload",
+ {"type":"object","properties":{}}), self.probe)
+ registry.register(ToolSpec("capture_rocm_counters", "Capture selected hardware performance counters for one local command and execution state",
+ {"type":"object","required":["command","stage","counters"],"properties":{
+ "command":{"type":"array","items":{"type":"string"}}, "stage":{"type":"string"},
+ "counters":{"type":"array","items":{"type":"string"}}, "kernel_regex":{"type":"string"},
+ "timeout_seconds":{"type":"integer"}, "metadata":{"type":"object"}}}, Action.BENCHMARK), self.capture_counters)
+ registry.register(ToolSpec("capture_rocm_att", "Capture AMD Advanced Thread Trace/SQTT evidence for one local command and execution state",
+ {"type":"object","required":["command","stage"],"properties":{
+ "command":{"type":"array","items":{"type":"string"}}, "stage":{"type":"string"},
+ "kernel_regex":{"type":"string"}, "timeout_seconds":{"type":"integer"},
+ "metadata":{"type":"object"}}}, Action.BENCHMARK), self.capture_att)
+ registry.register(ToolSpec("list_profile_captures", "List immutable local ROCm counter and ATT capture manifests",
+ {"type":"object","properties":{"limit":{"type":"integer"}}}), self.list_captures)
+ registry.register(ToolSpec("inspect_profile_capture", "Inspect one profile manifest, artifact hashes and normalized evidence summary",
+ {"type":"object","required":["capture_id"],"properties":{"capture_id":{"type":"string"}}}), self.inspect_capture)
From 08ccc7e409269c326a07a719b274df8ba406fc00 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:34:10 +0530
Subject: [PATCH 148/168] radeon forge: test evidence-preserving ROCm captures
---
test/test_radeon_forge_capture.py | 89 +++++++++++++++++++++++++++++++
1 file changed, 89 insertions(+)
create mode 100644 test/test_radeon_forge_capture.py
diff --git a/test/test_radeon_forge_capture.py b/test/test_radeon_forge_capture.py
new file mode 100644
index 0000000000000..eeb55ddcfba2b
--- /dev/null
+++ b/test/test_radeon_forge_capture.py
@@ -0,0 +1,89 @@
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from extra.radeon_forge.profiling.capture import CaptureKind, CaptureRequest, Rocprofv3Adapter
+from extra.radeon_forge.profiling.tools import ProfilingTools
+from extra.radeon_forge.runtime.tool_context import ToolExecutionContext, bind_tool_context
+
+
+FAKE_ROCPROF = '''#!/usr/bin/env python3
+import csv, pathlib, sys
+if "--version" in sys.argv:
+ print("rocprofv3 fake 1.0")
+ raise SystemExit(0)
+if "--help" in sys.argv:
+ print("--att --att-simd-select --kernel-include-regex --pmc --output-directory -d")
+ raise SystemExit(0)
+args=sys.argv[1:]
+flag="--output-directory" if "--output-directory" in args else "-d"
+out=pathlib.Path(args[args.index(flag)+1])
+out.mkdir(parents=True, exist_ok=True)
+if "--att" in args:
+ (out/"thread_trace.att").write_bytes(b"ATT-EVIDENCE")
+else:
+ with (out/"counters.csv").open("w", newline="") as f:
+ writer=csv.DictWriter(f, fieldnames=["Kernel_Name","SQ_WAVES","DurationNs"])
+ writer.writeheader()
+ writer.writerow({"Kernel_Name":"decode_gemv","SQ_WAVES":"64","DurationNs":"900"})
+print("capture complete")
+'''
+
+
+class TestRocprofCapture(unittest.TestCase):
+ def _adapter(self, root: Path):
+ binary=root/"bin"/"rocprofv3"
+ binary.parent.mkdir()
+ binary.write_text(FAKE_ROCPROF, encoding="utf-8")
+ binary.chmod(0o755)
+ environment={**os.environ, "PATH":str(binary.parent)+os.pathsep+os.environ.get("PATH","")}
+ return Rocprofv3Adapter(root, root/"evidence"), environment
+
+ def test_counter_capture_writes_manifest_hashes_and_summary(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)
+ adapter, environment=self._adapter(root)
+ with patch.dict(os.environ, environment, clear=True):
+ probe=adapter.probe()
+ self.assertTrue(probe["available"])
+ self.assertTrue(probe["supports_pmc"])
+ result=adapter.capture(CaptureRequest(CaptureKind.COUNTERS, ("python3","-c","print('x')"), "decode",
+ session_id="s1", trace_id="t1", agent_step=2, counters=("SQ_WAVES","DurationNs")))
+ self.assertTrue(result.passed)
+ self.assertEqual(result.summary["stage"], "decode")
+ self.assertEqual(result.summary["session_id"], "s1")
+ self.assertEqual(result.summary["parsed_csv"]["csv_rows"], 1)
+ self.assertEqual(result.summary["parsed_csv"]["numeric_columns"]["SQ_WAVES"]["mean"], 64.0)
+ self.assertTrue(all(len(artifact.sha256)==64 for artifact in result.artifacts))
+ self.assertTrue((Path(result.output_directory)/"forge_capture_manifest.json").is_file())
+
+ def test_att_capture_is_separate_and_provenance_is_bound(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)
+ adapter, environment=self._adapter(root)
+ tools=ProfilingTools(root, root/"evidence")
+ context=ToolExecutionContext("session-7","trace-9",3,"call-2","capture_rocm_att",{"purpose":"decode diagnosis"})
+ with patch.dict(os.environ, environment, clear=True), bind_tool_context(context):
+ result=tools.capture_att({"command":["python3","-c","print('decode')"], "stage":"first_token",
+ "kernel_regex":"decode_.*", "timeout_seconds":30})
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["summary"]["session_id"], "session-7")
+ self.assertEqual(result["summary"]["trace_id"], "trace-9")
+ self.assertEqual(result["summary"]["agent_step"], 3)
+ self.assertEqual(result["summary"]["kernel_regex"], "decode_.*")
+ self.assertTrue(any(item["suffix"]==".att" for item in result["artifacts"]))
+ listed=tools.list_captures({"limit":10})
+ self.assertEqual(listed["captures"][0]["capture_id"], result["capture_id"])
+
+ def test_profile_target_is_allowlisted_and_shell_free(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)
+ adapter, environment=self._adapter(root)
+ with patch.dict(os.environ, environment, clear=True):
+ with self.assertRaisesRegex(ValueError, "not allowlisted"):
+ adapter.capture(CaptureRequest(CaptureKind.ATT, ("bash","-lc","rm -rf /"), "decode"))
+
+
+if __name__ == "__main__": unittest.main()
From fb538f5ad47264f6587998e7e0af00b375336602 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:36:52 +0530
Subject: [PATCH 149/168] radeon forge: test hardware-grounded profiler
findings
---
test/test_radeon_forge_profile_evidence.py | 39 ++++++++++++++++++++++
1 file changed, 39 insertions(+)
create mode 100644 test/test_radeon_forge_profile_evidence.py
diff --git a/test/test_radeon_forge_profile_evidence.py b/test/test_radeon_forge_profile_evidence.py
new file mode 100644
index 0000000000000..85711716e9dcb
--- /dev/null
+++ b/test/test_radeon_forge_profile_evidence.py
@@ -0,0 +1,39 @@
+import unittest
+
+from extra.radeon_forge.profiling.report import build_profile_report
+from extra.radeon_forge.runtime.events import TraceRecorder
+
+
+class TestHardwareProfileEvidence(unittest.TestCase):
+ def test_att_and_counter_captures_are_observed_evidence(self):
+ trace=TraceRecorder("trace-1")
+ trace.point("profile","hardware_capture",capture_id="att-1",capture_kind="att",passed=True,stage="decode",
+ artifact_count=3,output_directory="/tmp/att",parsed_csv={},error="")
+ trace.point("profile","hardware_capture",capture_id="counter-1",capture_kind="counters",passed=True,stage="first_token",
+ artifact_count=2,output_directory="/tmp/counters",parsed_csv={"csv_rows":8},error="")
+ report=build_profile_report(trace.events())
+ self.assertEqual(report["summary"]["hardware_capture_count"],2)
+ self.assertEqual(report["summary"]["att_capture_count"],1)
+ self.assertEqual(report["summary"]["counter_capture_count"],1)
+ titles={finding["title"] for finding in report["findings"]}
+ self.assertIn("AMD ATT/SQTT evidence is attached",titles)
+ self.assertIn("ROCm hardware counter evidence is attached",titles)
+ self.assertNotIn("No ROCm counter or ATT capture is attached to this trace",titles)
+
+ def test_failed_capture_is_visible(self):
+ trace=TraceRecorder("trace-2")
+ trace.point("profile","hardware_capture",capture_id="att-bad",capture_kind="att",passed=False,stage="decode",
+ artifact_count=0,output_directory="/tmp/att-bad",parsed_csv={},error="rocprofv3 missing ATT support")
+ report=build_profile_report(trace.events())
+ self.assertEqual(report["summary"]["failed_capture_count"],1)
+ finding=next(item for item in report["findings"] if item["title"]=="One or more hardware profiling captures failed")
+ self.assertEqual(finding["status"],"observed")
+ self.assertIn("missing ATT support",finding["evidence"][0])
+
+ def test_absence_remains_unknown(self):
+ report=build_profile_report(())
+ finding=next(item for item in report["findings"] if item["title"]=="No ROCm counter or ATT capture is attached to this trace")
+ self.assertEqual(finding["status"],"unknown")
+
+
+if __name__=="__main__": unittest.main()
From c1b8a6104275af360b5110f4659e284d74342ca8 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:41:14 +0530
Subject: [PATCH 150/168] radeon forge: compare compatible hardware profile
captures
---
extra/radeon_forge/profiling/compare.py | 173 ++++++++++++++++++++++++
1 file changed, 173 insertions(+)
create mode 100644 extra/radeon_forge/profiling/compare.py
diff --git a/extra/radeon_forge/profiling/compare.py b/extra/radeon_forge/profiling/compare.py
new file mode 100644
index 0000000000000..8b271baa25e34
--- /dev/null
+++ b/extra/radeon_forge/profiling/compare.py
@@ -0,0 +1,173 @@
+from __future__ import annotations
+
+import csv, json, math
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Iterable, Mapping
+
+
+@dataclass(frozen=True)
+class NumericDelta:
+ baseline: float
+ candidate: float
+ absolute: float
+ relative: float | None
+
+
+@dataclass(frozen=True)
+class KernelDelta:
+ kernel: str
+ metric: str
+ baseline_count: int
+ candidate_count: int
+ baseline_mean: float
+ candidate_mean: float
+ absolute: float
+ relative: float | None
+
+
+class IncomparableCaptures(ValueError): pass
+
+
+def _manifest(value: str | Path | Mapping[str, Any]) -> tuple[dict[str, Any], Path | None]:
+ if isinstance(value, Mapping): return dict(value), None
+ path = Path(value)
+ if path.is_dir(): path = path / "forge_capture_manifest.json"
+ if not path.is_file(): raise FileNotFoundError(path)
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict): raise ValueError(f"capture manifest {path} is not an object")
+ return payload, path.parent
+
+
+def _normalized_command(value: Any) -> tuple[str, ...]:
+ if not isinstance(value, list): return ()
+ return tuple(str(x) for x in value)
+
+
+def _counter_set(manifest: Mapping[str, Any]) -> tuple[str, ...]:
+ summary = manifest.get("summary", {})
+ if not isinstance(summary, Mapping): return ()
+ counters = summary.get("counters", ())
+ return tuple(sorted(str(x) for x in counters)) if isinstance(counters, list) else ()
+
+
+def _workload_identity(manifest: Mapping[str, Any]) -> str:
+ summary = manifest.get("summary", {})
+ metadata = summary.get("capture_metadata", {}) if isinstance(summary, Mapping) else {}
+ if isinstance(metadata, Mapping):
+ for key in ("workload_hash", "task_suite_hash", "input_hash", "workload_id"):
+ if metadata.get(key): return f"{key}:{metadata[key]}"
+ command = _normalized_command(manifest.get("target_command"))
+ return "command:" + json.dumps(command)
+
+
+def compatibility_report(baseline: Mapping[str, Any], candidate: Mapping[str, Any]) -> dict[str, Any]:
+ reasons: list[str] = []
+ base_summary = baseline.get("summary", {}) if isinstance(baseline.get("summary", {}), Mapping) else {}
+ cand_summary = candidate.get("summary", {}) if isinstance(candidate.get("summary", {}), Mapping) else {}
+ checks = {
+ "kind": (baseline.get("kind"), candidate.get("kind")),
+ "stage": (base_summary.get("stage"), cand_summary.get("stage")),
+ "target_command": (_normalized_command(baseline.get("target_command")), _normalized_command(candidate.get("target_command"))),
+ "workload_identity": (_workload_identity(baseline), _workload_identity(candidate)),
+ }
+ if baseline.get("kind") == "counters" or candidate.get("kind") == "counters":
+ checks["counters"] = (_counter_set(baseline), _counter_set(candidate))
+ for name, (left, right) in checks.items():
+ if left != right: reasons.append(f"{name} differs: baseline={left!r} candidate={right!r}")
+ if not baseline.get("passed"): reasons.append("baseline capture did not pass")
+ if not candidate.get("passed"): reasons.append("candidate capture did not pass")
+ return {"comparable": not reasons, "reasons": reasons, "checks": checks}
+
+
+def _relative(base: float, candidate: float) -> float | None:
+ if base == 0: return None
+ return (candidate - base) / base
+
+
+def _numeric_summary(manifest: Mapping[str, Any]) -> Mapping[str, Any]:
+ summary = manifest.get("summary", {})
+ parsed = summary.get("parsed_csv", {}) if isinstance(summary, Mapping) else {}
+ numeric = parsed.get("numeric_columns", {}) if isinstance(parsed, Mapping) else {}
+ return numeric if isinstance(numeric, Mapping) else {}
+
+
+def _numeric_deltas(baseline: Mapping[str, Any], candidate: Mapping[str, Any]) -> dict[str, dict[str, Any]]:
+ left, right = _numeric_summary(baseline), _numeric_summary(candidate)
+ ret: dict[str, dict[str, Any]] = {}
+ for key in sorted(set(left) & set(right)):
+ if not isinstance(left[key], Mapping) or not isinstance(right[key], Mapping): continue
+ if "mean" not in left[key] or "mean" not in right[key]: continue
+ base, cand = float(left[key]["mean"]), float(right[key]["mean"])
+ ret[str(key)] = asdict(NumericDelta(base, cand, cand-base, _relative(base, cand)))
+ return ret
+
+
+def _artifact_paths(manifest: Mapping[str, Any], root: Path | None, suffix: str) -> list[Path]:
+ paths = []
+ for item in manifest.get("artifacts", []):
+ if not isinstance(item, Mapping) or str(item.get("suffix", "")).lower() != suffix: continue
+ path = Path(str(item.get("path", "")))
+ if not path.is_absolute() and root is not None: path = root / path
+ if path.is_file(): paths.append(path)
+ return paths
+
+
+def _kernel_column(fieldnames: Iterable[str]) -> str | None:
+ names = list(fieldnames)
+ preferred = ("Kernel_Name", "KernelName", "Kernel", "Name", "kernel_name", "kernel")
+ return next((name for name in preferred if name in names), None)
+
+
+def _kernel_metrics(manifest: Mapping[str, Any], root: Path | None) -> dict[tuple[str, str], list[float]]:
+ grouped: dict[tuple[str, str], list[float]] = {}
+ for path in _artifact_paths(manifest, root, ".csv"):
+ try:
+ with path.open(newline="", encoding="utf-8", errors="replace") as handle:
+ reader = csv.DictReader(handle)
+ key_column = _kernel_column(reader.fieldnames or ())
+ if key_column is None: continue
+ for row in reader:
+ kernel = str(row.get(key_column, "")).strip()
+ if not kernel: continue
+ for key, value in row.items():
+ if key == key_column: continue
+ try: number = float(value)
+ except (TypeError, ValueError): continue
+ if math.isfinite(number): grouped.setdefault((kernel, str(key)), []).append(number)
+ except OSError: continue
+ return grouped
+
+
+def _kernel_deltas(baseline: Mapping[str, Any], base_root: Path | None,
+ candidate: Mapping[str, Any], cand_root: Path | None) -> list[dict[str, Any]]:
+ left, right = _kernel_metrics(baseline, base_root), _kernel_metrics(candidate, cand_root)
+ ret = []
+ for kernel, metric in sorted(set(left) & set(right)):
+ base_values, cand_values = left[(kernel, metric)], right[(kernel, metric)]
+ base_mean, cand_mean = sum(base_values)/len(base_values), sum(cand_values)/len(cand_values)
+ ret.append(asdict(KernelDelta(kernel, metric, len(base_values), len(cand_values), base_mean, cand_mean,
+ cand_mean-base_mean, _relative(base_mean, cand_mean))))
+ return ret
+
+
+def compare_captures(baseline_value: str | Path | Mapping[str, Any],
+ candidate_value: str | Path | Mapping[str, Any]) -> dict[str, Any]:
+ baseline, base_root = _manifest(baseline_value)
+ candidate, cand_root = _manifest(candidate_value)
+ compatibility = compatibility_report(baseline, candidate)
+ if not compatibility["comparable"]: raise IncomparableCaptures("; ".join(compatibility["reasons"]))
+ return {
+ "baseline_capture_id": baseline.get("capture_id"),
+ "candidate_capture_id": candidate.get("capture_id"),
+ "kind": baseline.get("kind"),
+ "stage": (baseline.get("summary", {}) or {}).get("stage"),
+ "compatibility": compatibility,
+ "numeric_column_deltas": _numeric_deltas(baseline, candidate),
+ "per_kernel_deltas": _kernel_deltas(baseline, base_root, candidate, cand_root),
+ "interpretation_contract": {
+ "lower_is_better_metrics": [],
+ "higher_is_better_metrics": [],
+ "note": "Deltas are descriptive only. Metric direction and causal meaning must come from the profiler schema or domain knowledge, not guessed from column names."
+ }
+ }
From 014175380592ac53b922c59e7fcbe79c1afec216 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:42:01 +0530
Subject: [PATCH 151/168] radeon forge: test comparable hardware profile deltas
---
test/test_radeon_forge_profile_compare.py | 81 +++++++++++++++++++++++
1 file changed, 81 insertions(+)
create mode 100644 test/test_radeon_forge_profile_compare.py
diff --git a/test/test_radeon_forge_profile_compare.py b/test/test_radeon_forge_profile_compare.py
new file mode 100644
index 0000000000000..ea936b374ec1c
--- /dev/null
+++ b/test/test_radeon_forge_profile_compare.py
@@ -0,0 +1,81 @@
+import csv
+import hashlib
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.profiling.compare import IncomparableCaptures, compare_captures
+
+
+class TestProfileCaptureComparison(unittest.TestCase):
+ def _capture(self, root: Path, capture_id: str, stage: str, rows: list[dict[str, str]], *, command=None,
+ counters=("SQ_WAVES", "DurationNs"), passed=True, workload_hash="suite-1") -> Path:
+ directory = root / capture_id
+ directory.mkdir()
+ csv_path = directory / "counters.csv"
+ with csv_path.open("w", newline="", encoding="utf-8") as handle:
+ writer = csv.DictWriter(handle, fieldnames=["Kernel_Name", "SQ_WAVES", "DurationNs"])
+ writer.writeheader(); writer.writerows(rows)
+ data = csv_path.read_bytes()
+ numeric = {}
+ for key in ("SQ_WAVES", "DurationNs"):
+ values = [float(row[key]) for row in rows]
+ numeric[key] = {"count":len(values), "min":min(values), "max":max(values), "mean":sum(values)/len(values)}
+ payload = {
+ "capture_id":capture_id, "kind":"counters", "passed":passed,
+ "target_command":command or ["python3", "workload.py", "--case", "decode"],
+ "artifacts":[{"path":str(csv_path), "size_bytes":len(data), "sha256":hashlib.sha256(data).hexdigest(), "suffix":".csv"}],
+ "summary":{"stage":stage, "counters":list(counters), "capture_metadata":{"workload_hash":workload_hash},
+ "parsed_csv":{"csv_files":1, "csv_rows":len(rows), "numeric_columns":numeric}}
+ }
+ manifest = directory / "forge_capture_manifest.json"
+ manifest.write_text(json.dumps(payload), encoding="utf-8")
+ return manifest
+
+ def test_compatible_captures_produce_global_and_per_kernel_deltas(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)
+ baseline=self._capture(root,"base","decode",[
+ {"Kernel_Name":"decode_gemv","SQ_WAVES":"64","DurationNs":"1000"},
+ {"Kernel_Name":"decode_gemv","SQ_WAVES":"64","DurationNs":"1200"},
+ ])
+ candidate=self._capture(root,"candidate","decode",[
+ {"Kernel_Name":"decode_gemv","SQ_WAVES":"72","DurationNs":"800"},
+ {"Kernel_Name":"decode_gemv","SQ_WAVES":"72","DurationNs":"900"},
+ ])
+ result=compare_captures(baseline,candidate)
+ self.assertTrue(result["compatibility"]["comparable"])
+ self.assertEqual(result["numeric_column_deltas"]["DurationNs"]["baseline"],1100.0)
+ self.assertEqual(result["numeric_column_deltas"]["DurationNs"]["candidate"],850.0)
+ row=next(item for item in result["per_kernel_deltas"] if item["kernel"]=="decode_gemv" and item["metric"]=="DurationNs")
+ self.assertEqual(row["absolute"],-250.0)
+ self.assertAlmostEqual(row["relative"],-250/1100)
+ self.assertEqual(result["interpretation_contract"]["lower_is_better_metrics"],[])
+
+ def test_stage_or_workload_mismatch_is_rejected(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)
+ rows=[{"Kernel_Name":"k","SQ_WAVES":"1","DurationNs":"1"}]
+ baseline=self._capture(root,"base","prefill",rows)
+ candidate=self._capture(root,"candidate","decode",rows)
+ with self.assertRaisesRegex(IncomparableCaptures,"stage differs"):
+ compare_captures(baseline,candidate)
+ other=self._capture(root,"other","prefill",rows,workload_hash="suite-2")
+ with self.assertRaisesRegex(IncomparableCaptures,"workload_identity differs"):
+ compare_captures(baseline,other)
+
+ def test_counter_set_or_failed_capture_is_rejected(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)
+ rows=[{"Kernel_Name":"k","SQ_WAVES":"1","DurationNs":"1"}]
+ baseline=self._capture(root,"base","decode",rows)
+ different=self._capture(root,"different","decode",rows,counters=("SQ_WAVES",))
+ with self.assertRaisesRegex(IncomparableCaptures,"counters differs"):
+ compare_captures(baseline,different)
+ failed=self._capture(root,"failed","decode",rows,passed=False)
+ with self.assertRaisesRegex(IncomparableCaptures,"candidate capture did not pass"):
+ compare_captures(baseline,failed)
+
+
+if __name__=="__main__": unittest.main()
From d3f3632b75b7b2cf834e25e90a7390b6a5690ea8 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:44:49 +0530
Subject: [PATCH 152/168] radeon forge: add transformer-block transition oracle
---
.../workloads/block_hook_harness.py | 192 ++++++++++++++++++
1 file changed, 192 insertions(+)
create mode 100644 extra/radeon_forge/workloads/block_hook_harness.py
diff --git a/extra/radeon_forge/workloads/block_hook_harness.py b/extra/radeon_forge/workloads/block_hook_harness.py
new file mode 100644
index 0000000000000..343a2642dce55
--- /dev/null
+++ b/extra/radeon_forge/workloads/block_hook_harness.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+import argparse, hashlib, importlib.util, json, os, time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Mapping
+
+import numpy as np
+
+from tinygrad import Device, GlobalCounters, Tensor, dtypes
+from extra.models.llama import TransformerBlock, precompute_freqs_cis
+
+
+@dataclass(frozen=True)
+class HarnessConfig:
+ dim: int = 128
+ hidden_dim: int = 256
+ n_heads: int = 4
+ n_kv_heads: int = 4
+ max_context: int = 128
+ prompt_tokens: int = 8
+ dtype: str = "float32"
+ max_abs_error: float = 2e-4
+ max_rel_error: float = 2e-3
+
+
+class ModelShell:
+ def __init__(self, layer: Any, config: HarnessConfig):
+ self.layers = [layer]
+ self.max_context = config.max_context
+ self.forward_jit = None
+
+
+def _candidate_path(argument: str | None) -> Path:
+ value = argument or os.environ.get("RADEON_FORGE_CANDIDATE")
+ if not value: raise ValueError("candidate path is required")
+ path = Path(value).resolve()
+ if not path.is_file(): raise FileNotFoundError(path)
+ return path
+
+
+def _parameters() -> dict[str, Any]:
+ raw = os.environ.get("RADEON_FORGE_CANDIDATE_JSON", "")
+ if not raw: return {}
+ payload = json.loads(raw)
+ values = payload.get("parameters", {}) if isinstance(payload, Mapping) else {}
+ if not isinstance(values, Mapping): raise ValueError("candidate parameters must be an object")
+ return dict(values)
+
+
+def _load_candidate(path: Path, parameters: Mapping[str, Any]):
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
+ spec = importlib.util.spec_from_file_location(f"radeon_forge_candidate_{digest[:16]}", path)
+ if spec is None or spec.loader is None: raise RuntimeError(f"cannot import candidate {path}")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ setattr(module, "RADEON_FORGE_PARAMETERS", dict(parameters))
+ configure = getattr(module, "configure", None)
+ if configure is not None:
+ if not callable(configure): raise TypeError("optional configure must be callable")
+ configure(dict(parameters))
+ factory = getattr(module, "build_replacement", None)
+ if not callable(factory): raise TypeError("candidate must define build_replacement(original, layer_index, model, context)")
+ return factory
+
+
+def _block(config: HarnessConfig) -> TransformerBlock:
+ return TransformerBlock(config.dim, config.hidden_dim, config.n_heads, config.n_kv_heads,
+ norm_eps=1e-5, max_context=config.max_context)
+
+
+def _reset_cache(block: TransformerBlock) -> None:
+ attention = getattr(block, "attention", None)
+ if attention is not None and hasattr(attention, "cache_kv"): delattr(attention, "cache_kv")
+
+
+def _dtype(name: str):
+ return {"float32":dtypes.float32, "float16":dtypes.float16, "bfloat16":dtypes.bfloat16}[name]
+
+
+def _inputs(config: HarnessConfig, prompt_tokens: int, seed: int):
+ Tensor.manual_seed(seed)
+ dtype = _dtype(config.dtype)
+ prompt = Tensor.randn(1, prompt_tokens, config.dim).cast(dtype).contiguous().realize()
+ first = Tensor.randn(1, 1, config.dim).cast(dtype).contiguous().realize()
+ decode = Tensor.randn(1, 1, config.dim).cast(dtype).contiguous().realize()
+ freqs = precompute_freqs_cis(config.dim // config.n_heads, config.max_context * 2).cast(dtype).contiguous().realize()
+ mask = Tensor.full((1, 1, prompt_tokens, prompt_tokens), float("-inf"), dtype=dtype).triu(1)
+ return prompt, first, decode, freqs, mask
+
+
+def _run_transition(callable_block, config: HarnessConfig, prompt_tokens: int, seed: int) -> list[np.ndarray]:
+ prompt, first, decode, freqs, mask = _inputs(config, prompt_tokens, seed)
+ outputs = [
+ callable_block(prompt, 0, freqs[:, :prompt_tokens], mask).realize().numpy(),
+ callable_block(first, prompt_tokens, freqs[:, prompt_tokens:prompt_tokens+1], None).realize().numpy(),
+ callable_block(decode, prompt_tokens+1, freqs[:, prompt_tokens+1:prompt_tokens+2], None).realize().numpy(),
+ ]
+ return outputs
+
+
+def _error(reference: list[np.ndarray], candidate: list[np.ndarray]) -> dict[str, Any]:
+ max_abs = max(float(np.max(np.abs(left.astype(np.float64)-right.astype(np.float64)))) for left, right in zip(reference, candidate))
+ max_rel = 0.0
+ checked = 0
+ for left, right in zip(reference, candidate):
+ left64, right64 = left.astype(np.float64), right.astype(np.float64)
+ denominator = np.maximum(np.abs(left64), 1e-8)
+ max_rel = max(max_rel, float(np.max(np.abs(left64-right64)/denominator)))
+ checked += left.size
+ return {"max_abs_error":max_abs, "max_rel_error":max_rel, "checked_values":checked}
+
+
+def validate(candidate_path: Path, config: HarnessConfig, prompt_lengths: tuple[int, ...], parameters: Mapping[str, Any]) -> dict[str, Any]:
+ block = _block(config)
+ model = ModelShell(block, config)
+ factory = _load_candidate(candidate_path, parameters)
+ max_abs = max_rel = 0.0
+ checked = 0
+ cases = []
+ for case_index, prompt_tokens in enumerate(prompt_lengths):
+ _reset_cache(block)
+ reference = _run_transition(block, config, prompt_tokens, seed=1000+case_index)
+ _reset_cache(block)
+ context = {"stage":"transition_oracle", "prompt_tokens":prompt_tokens, "batch_size":1,
+ "parameters":dict(parameters), "device":Device.DEFAULT}
+ replacement = factory(block, 0, model, context)
+ if not callable(replacement): raise TypeError("build_replacement must return a callable block")
+ candidate = _run_transition(replacement, config, prompt_tokens, seed=1000+case_index)
+ result = _error(reference, candidate)
+ max_abs, max_rel = max(max_abs, result["max_abs_error"]), max(max_rel, result["max_rel_error"])
+ checked += result["checked_values"]
+ cases.append({"prompt_tokens":prompt_tokens, **result})
+ passed = max_abs <= config.max_abs_error and max_rel <= config.max_rel_error
+ return {"passed":passed, "max_abs_error":max_abs, "max_rel_error":max_rel, "checked_values":checked,
+ "reason":"" if passed else "candidate diverged from transformer-block transition reference", "cases":cases}
+
+
+def benchmark(candidate_path: Path, config: HarnessConfig, budget: int, parameters: Mapping[str, Any]) -> tuple[list[float], dict[str, Any]]:
+ block = _block(config)
+ model = ModelShell(block, config)
+ factory = _load_candidate(candidate_path, parameters)
+ replacement = factory(block, 0, model, {"stage":"decode_benchmark", "parameters":dict(parameters), "device":Device.DEFAULT})
+ if not callable(replacement): raise TypeError("build_replacement must return a callable block")
+ _reset_cache(block)
+ prompt, _, _, freqs, mask = _inputs(config, config.prompt_tokens, seed=2026)
+ replacement(prompt, 0, freqs[:, :config.prompt_tokens], mask).realize()
+ samples = []
+ kernel_counts = []
+ for index in range(budget):
+ position = config.prompt_tokens + index
+ Tensor.manual_seed(3000+index)
+ value = Tensor.randn(1, 1, config.dim).cast(_dtype(config.dtype)).contiguous().realize()
+ GlobalCounters.reset()
+ started = time.perf_counter_ns()
+ replacement(value, position, freqs[:, position:position+1], None).realize()
+ samples.append((time.perf_counter_ns()-started)/1000.0)
+ kernel_counts.append(GlobalCounters.kernel_count)
+ return samples, {"kernel_count_mean":sum(kernel_counts)/len(kernel_counts), "device":Device.DEFAULT,
+ "prompt_tokens":config.prompt_tokens, "stage":"decode", "parameters":dict(parameters)}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Radeon Forge transformer-block oracle and benchmark")
+ parser.add_argument("--candidate")
+ parser.add_argument("--mode", choices=("correctness", "benchmark", "transition"), default="correctness")
+ parser.add_argument("--dtype", choices=("float32", "float16", "bfloat16"), default="float32")
+ parser.add_argument("--dim", type=int, default=128)
+ parser.add_argument("--hidden-dim", type=int, default=256)
+ parser.add_argument("--prompt-tokens", type=int, default=8)
+ args = parser.parse_args()
+ config = HarnessConfig(dim=args.dim, hidden_dim=args.hidden_dim, prompt_tokens=args.prompt_tokens, dtype=args.dtype)
+ candidate_path, parameters = _candidate_path(args.candidate), _parameters()
+ prompt_lengths = (1, 4, args.prompt_tokens, min(24, config.max_context-2)) if args.mode == "transition" else (args.prompt_tokens,)
+ correctness = validate(candidate_path, config, tuple(dict.fromkeys(prompt_lengths)), parameters)
+ budget = max(1, int(os.environ.get("RADEON_FORGE_BUDGET", "5")))
+ samples, metrics = (benchmark(candidate_path, config, budget, parameters) if args.mode == "benchmark" and correctness["passed"] else ([], {}))
+ payload = {
+ "samples_us":samples,
+ "correctness":correctness,
+ "resources":{},
+ "compile_ok":True,
+ "stable":bool(correctness["passed"]),
+ "metrics":metrics,
+ "mode":args.mode,
+ "candidate_sha256":hashlib.sha256(candidate_path.read_bytes()).hexdigest(),
+ }
+ print(json.dumps(payload, default=str))
+ raise SystemExit(0 if correctness["passed"] else 2)
+
+
+if __name__ == "__main__": main()
From c6a66654099ce2f1b1d237a048724d64c8b0b82b Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:45:38 +0530
Subject: [PATCH 153/168] radeon forge: test transformer-block oracle harness
---
test/test_radeon_forge_block_harness.py | 55 +++++++++++++++++++++++++
1 file changed, 55 insertions(+)
create mode 100644 test/test_radeon_forge_block_harness.py
diff --git a/test/test_radeon_forge_block_harness.py b/test/test_radeon_forge_block_harness.py
new file mode 100644
index 0000000000000..ae4ac277bacf4
--- /dev/null
+++ b/test/test_radeon_forge_block_harness.py
@@ -0,0 +1,55 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.workloads.block_hook_harness import HarnessConfig, benchmark, validate
+
+
+IDENTITY = '''
+PARAMETERS = {}
+def configure(parameters):
+ global PARAMETERS
+ PARAMETERS = dict(parameters)
+def build_replacement(original, layer_index, model, context):
+ assert context["parameters"] == PARAMETERS
+ return original
+'''
+
+BAD = '''
+def build_replacement(original, layer_index, model, context):
+ def replacement(x, start_pos, freqs_cis, mask):
+ return x * 0
+ return replacement
+'''
+
+
+class TestBlockHookHarness(unittest.TestCase):
+ def test_identity_replacement_passes_transition_and_benchmark(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path=Path(directory)/"identity.py"
+ path.write_text(IDENTITY,encoding="utf-8")
+ config=HarnessConfig(dim=32,hidden_dim=64,n_heads=4,n_kv_heads=4,max_context=32,prompt_tokens=2,
+ max_abs_error=1e-5,max_rel_error=1e-4)
+ result=validate(path,config,(1,2,4),{"WAVES":2})
+ self.assertTrue(result["passed"],result)
+ self.assertEqual(len(result["cases"]),3)
+ self.assertGreater(result["checked_values"],0)
+ samples,metrics=benchmark(path,config,2,{"WAVES":2})
+ self.assertEqual(len(samples),2)
+ self.assertTrue(all(value>0 for value in samples))
+ self.assertEqual(metrics["stage"],"decode")
+ self.assertEqual(metrics["parameters"],{"WAVES":2})
+
+ def test_incorrect_replacement_fails_reference_oracle(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path=Path(directory)/"bad.py"
+ path.write_text(BAD,encoding="utf-8")
+ config=HarnessConfig(dim=32,hidden_dim=64,n_heads=4,n_kv_heads=4,max_context=16,prompt_tokens=2,
+ max_abs_error=1e-5,max_rel_error=1e-4)
+ result=validate(path,config,(2,),{})
+ self.assertFalse(result["passed"])
+ self.assertGreater(result["max_abs_error"],config.max_abs_error)
+ self.assertIn("diverged",result["reason"])
+
+
+if __name__=="__main__": unittest.main()
From 25ac1acbf61d71cd94f6e3356d8cf67c8f95e39c Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:46:22 +0530
Subject: [PATCH 154/168] radeon forge: generate agent-facing candidate
scaffolds
---
extra/radeon_forge/synthesis/scaffold.py | 77 ++++++++++++++++++++++++
1 file changed, 77 insertions(+)
create mode 100644 extra/radeon_forge/synthesis/scaffold.py
diff --git a/extra/radeon_forge/synthesis/scaffold.py b/extra/radeon_forge/synthesis/scaffold.py
new file mode 100644
index 0000000000000..1dc7da04e7011
--- /dev/null
+++ b/extra/radeon_forge/synthesis/scaffold.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from .hooks import HookDescriptor, HookLayer
+from .workspace import KernelSpec
+
+
+def _doc(value: Any) -> str: return json.dumps(value, indent=2, sort_keys=True, default=str)
+
+
+def render_candidate_scaffold(spec: KernelSpec) -> str:
+ """Render the minimum executable contract, not a performance abstraction.
+
+ The scaffold intentionally contains no tile DSL or scheduling framework. It
+ gives an agent the exact runtime boundary, invariants, stage predicate and
+ parameter handoff, while leaving the implementation structure disposable.
+ """
+ hook = HookDescriptor.from_spec(spec)
+ header = f'''"""Disposable Radeon Forge candidate.
+
+Spec: {spec.name}
+Operation: {spec.operation}
+Target: {spec.target}
+Objective: {spec.objective}
+Placement: {hook.layer.value}:{hook.target} ({hook.mode.value})
+Execution states: {hook.when.signature}
+
+Invariants:
+{chr(10).join(f"- {item}" for item in spec.invariants)}
+
+This file is not trusted merely because it imports or compiles. It must pass
+MockGPU/reference, real hardware, and any held-out phase-transition oracle.
+"""
+
+from __future__ import annotations
+from typing import Any, Mapping
+
+RADEON_FORGE_PARAMETERS: dict[str, Any] = {{}}
+
+
+def configure(parameters: Mapping[str, Any]) -> None:
+ """Receive the locally autotuned schedule selected for this machine/state."""
+ global RADEON_FORGE_PARAMETERS
+ RADEON_FORGE_PARAMETERS = dict(parameters)
+
+'''
+ if hook.layer is HookLayer.TRANSFORMER_BLOCK:
+ body = '''def build_replacement(original, layer_index: int, model, context: Mapping[str, Any]):
+ """Return a callable with signature (x, start_pos, freqs_cis, mask).
+
+ `context` describes the activation/validation state. Runtime execution-state
+ selection is enforced outside this module by the signed hook manifest.
+ Replace this identity implementation with direct tinygrad/custom-kernel code.
+ """
+ assert context.get("stage") in {"transition_oracle", "decode_benchmark", "first_token", "decode"}
+
+ def replacement(x, start_pos, freqs_cis, mask):
+ # TODO(agent): implement the model- and gfx1100-specific block/subgraph.
+ # Keep `original` as the correctness fallback while iterating.
+ return original(x, start_pos, freqs_cis, mask)
+
+ return replacement
+'''
+ else:
+ body = '''def build_kernel(*args, **kwargs):
+ """Build the direct target-specific implementation for this hook contract."""
+ raise NotImplementedError("agent must generate a direct implementation")
+'''
+ footer = f'''\n\n# Machine-readable context copied from the durable spec for code-review tools.\nFORGE_SPEC_CONTEXT = {_doc({
+ "shapes":dict(spec.shapes), "dtypes":dict(spec.dtypes), "invariants":list(spec.invariants),
+ "hook":{"layer":hook.layer.value, "target":hook.target, "mode":hook.mode.value,
+ "adapter":hook.adapter, "selector":dict(hook.selector), "when":hook.when.signature},
+ "search":spec.metadata.get("search", {}),
+ })}\n'''
+ return header + body + footer
From 0f71f582fd9c4143000d2cb4001ac83008bd035e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:46:37 +0530
Subject: [PATCH 155/168] radeon forge: test agent candidate scaffold contract
---
test/test_radeon_forge_scaffold.py | 38 ++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 test/test_radeon_forge_scaffold.py
diff --git a/test/test_radeon_forge_scaffold.py b/test/test_radeon_forge_scaffold.py
new file mode 100644
index 0000000000000..f5bcff2dfdc79
--- /dev/null
+++ b/test/test_radeon_forge_scaffold.py
@@ -0,0 +1,38 @@
+import ast
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.synthesis.scaffold import render_candidate_scaffold
+from extra.radeon_forge.synthesis.workspace import KernelSpec
+
+
+class TestCandidateScaffold(unittest.TestCase):
+ def test_transformer_block_scaffold_is_executable_and_preserves_contract(self):
+ spec=KernelSpec("decode-block","specialize decode",target="gfx1100",invariants=("match reference","preserve KV"),
+ metadata={"search":{"axes":{"WAVES":[1,2,4]}},"hook":{"layer":"transformer_block","target":"llama.decode.block",
+ "mode":"replace","adapter":"python_transformer_block","selector":{"indices":"all"},
+ "when":{"stages":["first_token","decode"],"batch_sizes":[1]}}})
+ source=render_candidate_scaffold(spec)
+ ast.parse(source)
+ namespace={}
+ exec(compile(source,"candidate.py","exec"),namespace)
+ namespace["configure"]({"WAVES":4})
+ self.assertEqual(namespace["RADEON_FORGE_PARAMETERS"],{"WAVES":4})
+ original=lambda x,start_pos,freqs,mask:x+1
+ replacement=namespace["build_replacement"](original,0,object(),{"stage":"decode"})
+ self.assertEqual(replacement(2,0,None,None),3)
+ self.assertIn("first_token|decode",source)
+ self.assertIn("preserve KV",source)
+ self.assertIn('"WAVES"',source)
+
+ def test_non_block_scaffold_does_not_invent_a_dsl(self):
+ spec=KernelSpec("gemv","direct gemv",invariants=("correct",),metadata={"hook":{"layer":"kernel","target":"gemv"}})
+ source=render_candidate_scaffold(spec)
+ ast.parse(source)
+ self.assertIn("def build_kernel",source)
+ self.assertIn("NotImplementedError",source)
+ self.assertNotIn("class Tile",source)
+
+
+if __name__=="__main__": unittest.main()
From d53a7af5bd5feb54f25e9461332d2f229da3d73e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:48:47 +0530
Subject: [PATCH 156/168] radeon forge: add crash-safe local session
persistence
---
extra/radeon_forge/runtime/store.py | 104 ++++++++++++++++++++++++++++
1 file changed, 104 insertions(+)
create mode 100644 extra/radeon_forge/runtime/store.py
diff --git a/extra/radeon_forge/runtime/store.py b/extra/radeon_forge/runtime/store.py
new file mode 100644
index 0000000000000..ceb6a6ec60f3c
--- /dev/null
+++ b/extra/radeon_forge/runtime/store.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+import json, os, tempfile, time
+from dataclasses import asdict
+from pathlib import Path
+from typing import Any, Callable, Mapping
+
+from .backend import InferenceBackend
+from .events import TraceEvent, TraceRecorder
+from .session import AgentSession, SessionEvent, SessionState
+from .tools import ToolCall, ToolRegistry
+
+
+class SessionStore:
+ """Atomic, local-only persistence for agent sessions and unified traces."""
+ FORMAT_VERSION = 1
+
+ def __init__(self, root: str | Path):
+ self.root = Path(root).resolve()
+ self.root.mkdir(parents=True, exist_ok=True)
+
+ def _path(self, session_id: str) -> Path:
+ if not session_id or any(ch not in "0123456789abcdef" for ch in session_id.lower()): raise ValueError("invalid session id")
+ return self.root / f"{session_id}.json"
+
+ @staticmethod
+ def _atomic_json(path: Path, payload: Mapping[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(prefix=path.name+".", suffix=".tmp", dir=path.parent)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, indent=2, default=str)
+ handle.write("\n")
+ handle.flush(); os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ finally:
+ try: os.unlink(temporary)
+ except FileNotFoundError: pass
+
+ def save(self, session: AgentSession) -> Path:
+ snapshot = session.snapshot()
+ payload = {"format_version":self.FORMAT_VERSION, "saved_at_s":time.time(), "session":snapshot,
+ "trace":session.trace.to_dict()}
+ path = self._path(session.session_id)
+ self._atomic_json(path, payload)
+ return path
+
+ def delete(self, session_id: str) -> None:
+ try: self._path(session_id).unlink()
+ except FileNotFoundError: pass
+
+ def list(self) -> list[dict[str, Any]]:
+ ret=[]
+ for path in sorted(self.root.glob("*.json"), key=lambda item:item.stat().st_mtime, reverse=True):
+ try:
+ payload=json.loads(path.read_text(encoding="utf-8")); session=payload["session"]
+ ret.append({"session_id":session["session_id"], "state":session.get("state","unknown"),
+ "saved_at_s":payload.get("saved_at_s"), "message_count":len(session.get("messages",[])),
+ "event_count":len(session.get("events",[])), "path":str(path)})
+ except Exception: continue
+ return ret
+
+ def load_payload(self, session_id: str) -> dict[str, Any]:
+ path=self._path(session_id)
+ payload=json.loads(path.read_text(encoding="utf-8"))
+ if int(payload.get("format_version",0)) != self.FORMAT_VERSION: raise ValueError("unsupported session checkpoint version")
+ return payload
+
+ def restore(self, session_id: str, backend: InferenceBackend, tools: ToolRegistry, system_prompt: str,
+ metadata_provider: Callable[[AgentSession, int], Mapping[str, Any]] | None = None) -> AgentSession:
+ payload=self.load_payload(session_id); saved=payload["session"]
+ trace_payload=payload.get("trace", {})
+ trace=TraceRecorder(str(trace_payload.get("trace_id") or saved.get("trace_id") or ""))
+ trace_events=[]
+ for item in trace_payload.get("events", []):
+ try:
+ trace_events.append(TraceEvent(str(item["event_id"]), str(item["trace_id"]), str(item["kind"]), str(item["name"]),
+ int(item["start_ns"]), int(item["end_ns"]) if item.get("end_ns") is not None else None,
+ str(item["parent_id"]) if item.get("parent_id") is not None else None, dict(item.get("attributes", {}))))
+ except Exception: continue
+ trace.extend(trace_events)
+ session=AgentSession(backend,tools,system_prompt,session_id=str(saved["session_id"]),trace=trace,metadata_provider=metadata_provider)
+ session.messages=[dict(item) for item in saved.get("messages", [])]
+ if not session.messages: session.messages=[{"role":"system","content":session._system_prompt()}]
+ session.events=[]
+ for item in saved.get("events", []):
+ try: session.events.append(SessionEvent(int(item["sequence"]),str(item["kind"]),dict(item.get("data",{})),float(item.get("timestamp_s",time.time()))))
+ except Exception: continue
+ session._sequence=max((item.sequence for item in session.events),default=0)
+ pending=saved.get("pending_tool_call")
+ session.pending_tool_call=(ToolCall(str(pending["call_id"]),str(pending["name"]),dict(pending.get("arguments",{})))
+ if isinstance(pending,Mapping) else None)
+ session.pending_assistant_content=str(saved.get("pending_assistant_content", ""))
+ session.partial_output=""
+ session.last_finish_reason=saved.get("last_finish_reason")
+ prior_state=SessionState(str(saved.get("state",SessionState.IDLE.value)))
+ if prior_state in {SessionState.GENERATING,SessionState.RUNNING_TOOL}:
+ session.state=SessionState.IDLE
+ session._emit("session_recovered", prior_state=prior_state.value, action="incomplete operation was not replayed")
+ elif prior_state is SessionState.AWAITING_TOOL_APPROVAL and session.pending_tool_call is None:
+ session.state=SessionState.IDLE
+ session._emit("session_recovered", prior_state=prior_state.value, action="missing pending tool was cleared")
+ else: session.state=prior_state
+ return session
From 18a622572b59ff2af82be9e53c1ad4399e7d28a4 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:50:33 +0530
Subject: [PATCH 157/168] radeon forge: test local session restart recovery
---
test/test_radeon_forge_persistence.py | 79 +++++++++++++++++++++++++++
1 file changed, 79 insertions(+)
create mode 100644 test/test_radeon_forge_persistence.py
diff --git a/test/test_radeon_forge_persistence.py b/test/test_radeon_forge_persistence.py
new file mode 100644
index 0000000000000..99020197d894b
--- /dev/null
+++ b/test/test_radeon_forge_persistence.py
@@ -0,0 +1,79 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.backends.fake import ScriptedBackend
+from extra.radeon_forge.runtime import ForgeEngine
+from extra.radeon_forge.runtime.session import AgentSession, SessionState
+from extra.radeon_forge.runtime.store import SessionStore
+from extra.radeon_forge.runtime.tools import ToolRegistry
+from extra.radeon_forge.permissions import PermissionController
+
+
+class TestSessionPersistence(unittest.TestCase):
+ def test_completed_session_restores_and_continues(self):
+ with tempfile.TemporaryDirectory() as directory:
+ first=ForgeEngine(ScriptedBackend(["first local answer"]),directory)
+ session=first.create_session(); session_id=session.session_id
+ first.run_message(session_id,"first question")
+ trace_id=session.trace.trace_id
+ first.close()
+
+ second=ForgeEngine(ScriptedBackend(["continued after restart"]),directory)
+ restored=second.session(session_id)
+ self.assertEqual(restored.state,SessionState.COMPLETED)
+ self.assertEqual(restored.trace.trace_id,trace_id)
+ self.assertEqual(restored.messages[-1]["content"],"first local answer")
+ second.run_message(session_id,"continue")
+ self.assertEqual(restored.messages[-1]["content"],"continued after restart")
+ self.assertGreater(len(restored.trace.events()),0)
+ second.close()
+
+ def test_pending_tool_approval_restores_without_execution(self):
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory,"hello.txt").write_text("private",encoding="utf-8")
+ first=ForgeEngine(ScriptedBackend(['{"name":"read_file","arguments":{"path":"hello.txt"}} ']),directory)
+ session=first.create_session(); session_id=session.session_id
+ first.run_message(session_id,"read the file")
+ self.assertEqual(session.state,SessionState.AWAITING_TOOL_APPROVAL)
+ first.close()
+
+ second=ForgeEngine(ScriptedBackend(["read completed after approval"]),directory)
+ restored=second.session(session_id)
+ self.assertEqual(restored.state,SessionState.AWAITING_TOOL_APPROVAL)
+ self.assertEqual(restored.pending_tool_call.name,"read_file")
+ self.assertFalse(any(event.kind=="tool_started" for event in restored.events))
+ second.run_tool_approval(session_id,"approve restored local read")
+ self.assertEqual(restored.state,SessionState.COMPLETED)
+ self.assertEqual(restored.messages[-1]["content"],"read completed after approval")
+ second.close()
+
+ def test_inflight_checkpoint_recovers_to_idle_without_replay(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root=Path(directory)/"sessions"
+ store=SessionStore(root)
+ backend=ScriptedBackend(["unused"])
+ session=AgentSession(backend,ToolRegistry(PermissionController()),"system")
+ session.messages.append({"role":"user","content":"incomplete turn"})
+ session.state=SessionState.GENERATING
+ session._emit("generation_started",backend="fake",step=1,capabilities={})
+ store.save(session)
+ restored=store.restore(session.session_id,backend,ToolRegistry(PermissionController()),"system")
+ self.assertEqual(restored.state,SessionState.IDLE)
+ recovery=next(event for event in restored.events if event.kind=="session_recovered")
+ self.assertEqual(recovery.data["prior_state"],"generating")
+ self.assertFalse(any(message.get("role")=="assistant" for message in restored.messages))
+
+ def test_checkpoint_path_and_format_are_local_and_atomic(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store=SessionStore(directory)
+ session=AgentSession(ScriptedBackend(),ToolRegistry(PermissionController()),"system")
+ path=store.save(session)
+ self.assertEqual(path.parent.resolve(),Path(directory).resolve())
+ self.assertTrue(path.name.endswith(".json"))
+ self.assertFalse(list(Path(directory).glob("*.tmp")))
+ payload=store.load_payload(session.session_id)
+ self.assertEqual(payload["format_version"],SessionStore.FORMAT_VERSION)
+
+
+if __name__=="__main__": unittest.main()
From e5fac9dfdb2c0a7cc36079be5555496a88447e1a Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:51:24 +0530
Subject: [PATCH 158/168] radeon forge: add local model worker plugin registry
---
extra/radeon_forge/backends/plugins.py | 68 ++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
create mode 100644 extra/radeon_forge/backends/plugins.py
diff --git a/extra/radeon_forge/backends/plugins.py b/extra/radeon_forge/backends/plugins.py
new file mode 100644
index 0000000000000..9bd9950cd0edf
--- /dev/null
+++ b/extra/radeon_forge/backends/plugins.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+
+@dataclass(frozen=True)
+class WorkerPlugin:
+ name: str
+ module: str
+ description: str
+ required: tuple[str, ...]
+ optional: tuple[str, ...] = ()
+ defaults: Mapping[str, Any] = field(default_factory=dict)
+
+ def command(self, values: Mapping[str, Any]) -> list[str]:
+ config={**dict(self.defaults),**{str(k):v for k,v in values.items() if v is not None}}
+ missing=[name for name in self.required if config.get(name) in (None,"")]
+ if missing: raise ValueError(f"worker plugin {self.name!r} is missing required fields: {missing}")
+ allowed=set(self.required)|set(self.optional)
+ unknown=sorted(set(config)-allowed)
+ if unknown: raise ValueError(f"worker plugin {self.name!r} received unsupported fields: {unknown}")
+ command=[sys.executable,"-m",self.module]
+ for name in self.required+self.optional:
+ if name not in config or config[name] is None: continue
+ value=config[name]
+ flag="--"+name.replace("_","-")
+ if isinstance(value,bool):
+ if value: command.append(flag)
+ elif isinstance(value,(str,int,float,Path)): command += [flag,str(value)]
+ elif isinstance(value,Sequence) and not isinstance(value,(str,bytes,bytearray)):
+ for item in value: command += [flag,str(item)]
+ else: raise TypeError(f"unsupported worker option {name}: {type(value).__name__}")
+ return command
+
+
+class WorkerPluginRegistry:
+ def __init__(self): self._plugins: dict[str,WorkerPlugin]={}
+
+ def register(self,plugin:WorkerPlugin) -> None:
+ if not plugin.name or plugin.name in self._plugins: raise ValueError(f"duplicate or empty worker plugin {plugin.name!r}")
+ if not plugin.module.startswith("extra.radeon_forge.backends."):
+ raise ValueError("worker plugins must resolve to an in-tree local Radeon Forge backend module")
+ self._plugins[plugin.name]=plugin
+
+ def get(self,name:str) -> WorkerPlugin:
+ try:return self._plugins[name]
+ except KeyError as exc:raise KeyError(f"unknown local worker plugin {name!r}; available={sorted(self._plugins)}") from exc
+
+ def list(self) -> list[dict[str,Any]]:
+ return [{"name":item.name,"module":item.module,"description":item.description,
+ "required":list(item.required),"optional":list(item.optional),"defaults":dict(item.defaults)}
+ for item in sorted(self._plugins.values(),key=lambda x:x.name)]
+
+
+def default_worker_plugins() -> WorkerPluginRegistry:
+ registry=WorkerPluginRegistry()
+ registry.register(WorkerPlugin(
+ name="legacy-llama",
+ module="extra.radeon_forge.backends.tinygrad_llama_worker",
+ description="Resident tinygrad Llama-family worker with exact KV accounting, stage hooks and kernel profiling.",
+ required=("model",),
+ optional=("tokenizer","size","quantize","max_context","seed"),
+ defaults={"size":"1B","max_context":8192,"seed":42},
+ ))
+ return registry
From d951dd59ba521d7db0bc70152235dfbb3a7a476d Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:52:03 +0530
Subject: [PATCH 159/168] radeon forge: test local model worker plugins
---
test/test_radeon_forge_plugins.py | 41 +++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
create mode 100644 test/test_radeon_forge_plugins.py
diff --git a/test/test_radeon_forge_plugins.py b/test/test_radeon_forge_plugins.py
new file mode 100644
index 0000000000000..3dadf34a0fe45
--- /dev/null
+++ b/test/test_radeon_forge_plugins.py
@@ -0,0 +1,41 @@
+import sys
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.backends.plugins import WorkerPlugin, WorkerPluginRegistry, default_worker_plugins
+
+
+class TestWorkerPlugins(unittest.TestCase):
+ def test_legacy_llama_command_is_local_and_explicit(self):
+ plugin=default_worker_plugins().get("legacy-llama")
+ command=plugin.command({"model":Path("/models/local.gguf"),"tokenizer":Path("/models/tokenizer.model"),
+ "size":"1B","max_context":4096,"seed":7})
+ self.assertEqual(command[:3],[sys.executable,"-m","extra.radeon_forge.backends.tinygrad_llama_worker"])
+ self.assertIn("/models/local.gguf",command)
+ self.assertIn("--max-context",command)
+ self.assertIn("4096",command)
+ self.assertNotIn("http", " ".join(command))
+
+ def test_required_and_unknown_fields_fail_closed(self):
+ plugin=default_worker_plugins().get("legacy-llama")
+ with self.assertRaisesRegex(ValueError,"missing required"):
+ plugin.command({})
+ with self.assertRaisesRegex(ValueError,"unsupported fields"):
+ plugin.command({"model":"x","remote_api":"https://example.com"})
+
+ def test_registry_rejects_external_modules_and_duplicates(self):
+ registry=WorkerPluginRegistry()
+ with self.assertRaisesRegex(ValueError,"in-tree local"):
+ registry.register(WorkerPlugin("remote","third_party.worker","bad",("model",)))
+ local=WorkerPlugin("local","extra.radeon_forge.backends.worker","ok",("model",))
+ registry.register(local)
+ with self.assertRaisesRegex(ValueError,"duplicate"):
+ registry.register(local)
+
+ def test_discovery_is_stable(self):
+ rows=default_worker_plugins().list()
+ self.assertEqual([row["name"] for row in rows],["legacy-llama"])
+ self.assertIn("stage hooks",rows[0]["description"])
+
+
+if __name__=="__main__": unittest.main()
From 52ed99f7a984db6e552be5ebcb02a69a5f00776e Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:52:26 +0530
Subject: [PATCH 160/168] radeon forge: add agent evaluation package
---
extra/radeon_forge/evaluation/__init__.py | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 extra/radeon_forge/evaluation/__init__.py
diff --git a/extra/radeon_forge/evaluation/__init__.py b/extra/radeon_forge/evaluation/__init__.py
new file mode 100644
index 0000000000000..1cdec57d7248a
--- /dev/null
+++ b/extra/radeon_forge/evaluation/__init__.py
@@ -0,0 +1,3 @@
+from .suite import AgentTask, AgentTaskSuite, SuiteResult, TaskResult, run_suite
+
+__all__=["AgentTask","AgentTaskSuite","SuiteResult","TaskResult","run_suite"]
From e0b663d7073546cbf0613cc47b690ec8b55c94b4 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:53:03 +0530
Subject: [PATCH 161/168] radeon forge: add frozen private-agent suite
evaluator
---
extra/radeon_forge/evaluation/suite.py | 170 +++++++++++++++++++++++++
1 file changed, 170 insertions(+)
create mode 100644 extra/radeon_forge/evaluation/suite.py
diff --git a/extra/radeon_forge/evaluation/suite.py b/extra/radeon_forge/evaluation/suite.py
new file mode 100644
index 0000000000000..f026fe2d61f35
--- /dev/null
+++ b/extra/radeon_forge/evaluation/suite.py
@@ -0,0 +1,170 @@
+from __future__ import annotations
+
+import hashlib, json, math, re, statistics, time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+from ..runtime import ForgeEngine
+from ..runtime.session import SessionState
+
+
+@dataclass(frozen=True)
+class AgentTask:
+ task_id: str
+ prompt: str
+ expected_tools: tuple[str, ...] = ()
+ allowed_tools: tuple[str, ...] = ()
+ required_output_regex: tuple[str, ...] = ()
+ forbidden_output_regex: tuple[str, ...] = ()
+ max_tokens: int = 256
+ max_agent_steps: int = 8
+ timeout_seconds: float = 120.0
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+
+ @classmethod
+ def from_mapping(cls, value: Mapping[str, Any]) -> AgentTask:
+ task_id, prompt = str(value.get("task_id", "")).strip(), str(value.get("prompt", "")).strip()
+ if not task_id or not prompt: raise ValueError("task_id and prompt are required")
+ def strings(name: str) -> tuple[str, ...]:
+ raw=value.get(name,())
+ if not isinstance(raw,list) or not all(isinstance(item,str) for item in raw): raise ValueError(f"{name} must be a string array")
+ return tuple(raw)
+ return cls(task_id,prompt,strings("expected_tools"),strings("allowed_tools"),strings("required_output_regex"),
+ strings("forbidden_output_regex"),int(value.get("max_tokens",256)),int(value.get("max_agent_steps",8)),
+ float(value.get("timeout_seconds",120.0)),dict(value.get("metadata",{})))
+
+
+@dataclass(frozen=True)
+class AgentTaskSuite:
+ name: str
+ tasks: tuple[AgentTask, ...]
+ description: str = ""
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+
+ @property
+ def suite_hash(self) -> str:
+ payload=asdict(self)
+ return hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(",",":"),default=str).encode()).hexdigest()
+
+ @classmethod
+ def load(cls,path: str|Path) -> AgentTaskSuite:
+ payload=json.loads(Path(path).read_text(encoding="utf-8"))
+ if int(payload.get("format_version",0)) != 1: raise ValueError("unsupported agent suite format")
+ tasks=tuple(AgentTask.from_mapping(item) for item in payload.get("tasks",()))
+ if not tasks: raise ValueError("suite requires at least one task")
+ identifiers=[task.task_id for task in tasks]
+ if len(identifiers)!=len(set(identifiers)): raise ValueError("task ids must be unique")
+ return cls(str(payload.get("name","")).strip() or Path(path).stem,tasks,str(payload.get("description","")),dict(payload.get("metadata",{})))
+
+
+@dataclass(frozen=True)
+class TaskResult:
+ task_id: str
+ passed: bool
+ latency_ms: float
+ final_output: str
+ observed_tools: tuple[str, ...]
+ expected_tools: tuple[str, ...]
+ tool_call_valid: bool
+ output_valid: bool
+ terminal_state: str
+ generated_tokens: int
+ prompt_tokens: int
+ failure_reasons: tuple[str, ...]
+ session_id: str
+ trace_id: str
+
+
+@dataclass(frozen=True)
+class SuiteResult:
+ suite_name: str
+ suite_hash: str
+ passed_tasks: int
+ total_tasks: int
+ task_success_rate: float
+ tool_call_validity_rate: float
+ p50_latency_ms: float
+ p95_latency_ms: float
+ mean_latency_ms: float
+ results: tuple[TaskResult, ...]
+
+ def to_dict(self) -> dict[str, Any]: return asdict(self)
+
+
+def _percentile(values: Sequence[float], fraction: float) -> float:
+ if not values:return 0.0
+ ordered=sorted(values); index=max(0,min(len(ordered)-1,math.ceil(len(ordered)*fraction)-1))
+ return ordered[index]
+
+
+def _last_assistant(messages: Sequence[Mapping[str, Any]]) -> str:
+ for message in reversed(messages):
+ if message.get("role")=="assistant" and "" not in str(message.get("content","")):
+ return str(message.get("content",""))
+ return ""
+
+
+def _tool_sequence(session) -> tuple[str, ...]:
+ names=[]
+ for event in session.events:
+ if event.kind=="tool_started":
+ call=event.data.get("call",{})
+ if isinstance(call,Mapping) and call.get("name"):names.append(str(call["name"]))
+ return tuple(names)
+
+
+def _token_usage(session) -> tuple[int,int]:
+ prompt=generated=0
+ for event in session.events:
+ if event.kind=="prefill":prompt=max(prompt,int(event.data.get("prompt_tokens",0)))
+ elif event.kind=="generation_done":generated+=int((event.data.get("metrics",{}) or {}).get("generated_tokens",0))
+ return prompt,generated
+
+
+def run_task(engine: ForgeEngine,task: AgentTask) -> TaskResult:
+ session=engine.create_session(); session.max_agent_steps=task.max_agent_steps
+ started=time.perf_counter_ns(); deadline=time.monotonic()+task.timeout_seconds
+ failures=[]
+ try: engine.run_message(session.session_id,task.prompt,task.max_tokens,0.0)
+ except Exception as exc: failures.append(f"initial generation failed: {type(exc).__name__}: {exc}")
+ while session.state is SessionState.AWAITING_TOOL_APPROVAL and not failures:
+ if time.monotonic()>=deadline:
+ failures.append("task timeout while awaiting tool execution");break
+ call=session.pending_tool_call
+ if call is None:
+ failures.append("session requested approval without a pending tool");break
+ if call.name not in task.allowed_tools:
+ failures.append(f"tool {call.name!r} is not allowed by the frozen task policy")
+ session.reject_tool("not allowed by frozen evaluation policy")
+ break
+ try:engine.run_tool_approval(session.session_id,f"Frozen suite permits local tool {call.name}",task.max_tokens)
+ except Exception as exc:
+ failures.append(f"tool/resume failed: {type(exc).__name__}: {exc}");break
+ latency_ms=(time.perf_counter_ns()-started)/1e6
+ observed=_tool_sequence(session)
+ tool_valid=observed==task.expected_tools and all(name in task.allowed_tools for name in observed)
+ if not tool_valid:failures.append(f"tool sequence expected={task.expected_tools!r} observed={observed!r}")
+ output=_last_assistant(session.messages)
+ output_valid=True
+ for pattern in task.required_output_regex:
+ if re.search(pattern,output,re.I|re.S) is None:
+ output_valid=False;failures.append(f"required output pattern did not match: {pattern!r}")
+ for pattern in task.forbidden_output_regex:
+ if re.search(pattern,output,re.I|re.S) is not None:
+ output_valid=False;failures.append(f"forbidden output pattern matched: {pattern!r}")
+ if session.state not in {SessionState.COMPLETED,SessionState.CANCELLED}:
+ failures.append(f"non-terminal-success session state: {session.state.value}")
+ if latency_ms>task.timeout_seconds*1000:failures.append("task exceeded latency timeout")
+ prompt_tokens,generated_tokens=_token_usage(session)
+ passed=not failures and tool_valid and output_valid and session.state is SessionState.COMPLETED
+ return TaskResult(task.task_id,passed,latency_ms,output,observed,task.expected_tools,tool_valid,output_valid,
+ session.state.value,generated_tokens,prompt_tokens,tuple(failures),session.session_id,session.trace.trace_id)
+
+
+def run_suite(engine: ForgeEngine,suite: AgentTaskSuite) -> SuiteResult:
+ results=tuple(run_task(engine,task) for task in suite.tasks)
+ latencies=[item.latency_ms for item in results]
+ return SuiteResult(suite.name,suite.suite_hash,sum(item.passed for item in results),len(results),
+ sum(item.passed for item in results)/len(results),sum(item.tool_call_valid for item in results)/len(results),
+ statistics.median(latencies),_percentile(latencies,0.95),statistics.mean(latencies),results)
From 498e5e574a0170d1ddfcaf912d64476538dcf204 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:53:43 +0530
Subject: [PATCH 162/168] radeon forge: add local agent-suite benchmark CLI
---
extra/radeon_forge/evaluation/cli.py | 38 ++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 extra/radeon_forge/evaluation/cli.py
diff --git a/extra/radeon_forge/evaluation/cli.py b/extra/radeon_forge/evaluation/cli.py
new file mode 100644
index 0000000000000..9c8eebc24c7d2
--- /dev/null
+++ b/extra/radeon_forge/evaluation/cli.py
@@ -0,0 +1,38 @@
+from __future__ import annotations
+
+import argparse, json, sys
+from pathlib import Path
+
+from ..backends.plugins import default_worker_plugins
+from ..runtime import ForgeEngine, JsonlProcessBackend
+from .suite import AgentTaskSuite, run_suite
+
+
+def main() -> None:
+ parser=argparse.ArgumentParser(description="Run a frozen private-agent suite on the local Radeon Forge engine")
+ parser.add_argument("--suite",type=Path,required=True)
+ parser.add_argument("--workspace",type=Path,default=Path.cwd())
+ parser.add_argument("--model-plugin",default="legacy-llama")
+ parser.add_argument("--model",type=Path,required=True)
+ parser.add_argument("--tokenizer",type=Path)
+ parser.add_argument("--size",default="1B")
+ parser.add_argument("--quantize")
+ parser.add_argument("--max-context",type=int,default=8192)
+ parser.add_argument("--seed",type=int,default=42)
+ parser.add_argument("--output",type=Path)
+ args=parser.parse_args()
+
+ plugin=default_worker_plugins().get(args.model_plugin)
+ command=plugin.command({"model":args.model,"tokenizer":args.tokenizer,"size":args.size,"quantize":args.quantize,
+ "max_context":args.max_context,"seed":args.seed})
+ engine=ForgeEngine(JsonlProcessBackend(command),args.workspace)
+ try:result=run_suite(engine,AgentTaskSuite.load(args.suite)).to_dict()
+ finally:engine.close()
+ text=json.dumps(result,indent=2,default=str)+"\n"
+ if args.output:
+ args.output.parent.mkdir(parents=True,exist_ok=True);args.output.write_text(text,encoding="utf-8")
+ sys.stdout.write(text)
+ raise SystemExit(0 if result["passed_tasks"]==result["total_tasks"] else 2)
+
+
+if __name__=="__main__":main()
From c8b2edbad38ab0da8c8d476799c991a670f5ea14 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:54:05 +0530
Subject: [PATCH 163/168] radeon forge: add frozen private coding-agent suite
---
.../workloads/private_code_agent_suite.json | 58 +++++++++++++++++++
1 file changed, 58 insertions(+)
create mode 100644 extra/radeon_forge/workloads/private_code_agent_suite.json
diff --git a/extra/radeon_forge/workloads/private_code_agent_suite.json b/extra/radeon_forge/workloads/private_code_agent_suite.json
new file mode 100644
index 0000000000000..2c14f3438bb0a
--- /dev/null
+++ b/extra/radeon_forge/workloads/private_code_agent_suite.json
@@ -0,0 +1,58 @@
+{
+ "format_version": 1,
+ "name": "private-code-agent-v1",
+ "description": "Deterministic local repository tasks covering inspection, retrieval, tool execution, and resumed generation.",
+ "metadata": {
+ "primary_metric": "p95_end_to_end_task_latency",
+ "constraints": {
+ "external_network_calls": 0,
+ "tool_call_validity": 1.0,
+ "task_success_drop_from_baseline": 0.0
+ }
+ },
+ "tasks": [
+ {
+ "task_id": "read-project-identity",
+ "prompt": "Read the first 80 lines of README.md and tell me the project name. Use the local file tool before answering.",
+ "expected_tools": ["read_file"],
+ "allowed_tools": ["read_file"],
+ "required_output_regex": ["tinygrad"],
+ "forbidden_output_regex": ["https?://"],
+ "max_tokens": 192,
+ "timeout_seconds": 120
+ },
+ {
+ "task_id": "locate-global-counters",
+ "prompt": "Find where GlobalCounters is defined in this private repository, then answer with the file path. Use local text search.",
+ "expected_tools": ["search_text"],
+ "allowed_tools": ["search_text"],
+ "required_output_regex": ["tinygrad/helpers\\.py"],
+ "forbidden_output_regex": ["https?://"],
+ "max_tokens": 192,
+ "timeout_seconds": 120
+ },
+ {
+ "task_id": "run-forge-unit-test",
+ "prompt": "Run only the Radeon Forge KV ledger unit test and report whether it passed. Do not run the full suite.",
+ "expected_tools": ["run_command"],
+ "allowed_tools": ["run_command"],
+ "required_output_regex": ["pass|ok"],
+ "forbidden_output_regex": ["https?://"],
+ "max_tokens": 192,
+ "timeout_seconds": 180,
+ "metadata": {
+ "expected_command": "python -m unittest test.test_radeon_forge_kv"
+ }
+ },
+ {
+ "task_id": "explain-local-profile-boundary",
+ "prompt": "Without calling a tool, explain in one sentence why MockGPU timing cannot be used as Radeon performance evidence.",
+ "expected_tools": [],
+ "allowed_tools": [],
+ "required_output_regex": ["hardware|W7900|real GPU"],
+ "forbidden_output_regex": ["https?://"],
+ "max_tokens": 96,
+ "timeout_seconds": 90
+ }
+ ]
+}
From 142c72e29663c191e4798b5a4729489455a86564 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:54:23 +0530
Subject: [PATCH 164/168] radeon forge: test frozen agent-loop evaluation
---
test/test_radeon_forge_evaluation.py | 59 ++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
create mode 100644 test/test_radeon_forge_evaluation.py
diff --git a/test/test_radeon_forge_evaluation.py b/test/test_radeon_forge_evaluation.py
new file mode 100644
index 0000000000000..f3af4c1b13b02
--- /dev/null
+++ b/test/test_radeon_forge_evaluation.py
@@ -0,0 +1,59 @@
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from extra.radeon_forge.backends.fake import ScriptedBackend
+from extra.radeon_forge.evaluation.suite import AgentTask, AgentTaskSuite, run_suite
+from extra.radeon_forge.runtime import ForgeEngine
+
+
+class TestAgentEvaluation(unittest.TestCase):
+ def test_suite_measures_complete_tool_loop(self):
+ responses=[
+ '{"name":"read_file","arguments":{"path":"marker.txt"}} ',
+ 'The marker is ALPHA.',
+ 'MockGPU is a semantic emulator; only real W7900 hardware provides performance evidence.',
+ ]
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory,"marker.txt").write_text("ALPHA",encoding="utf-8")
+ suite=AgentTaskSuite("unit",(
+ AgentTask("read","Read marker.txt and report the marker.",expected_tools=("read_file",),allowed_tools=("read_file",),
+ required_output_regex=("ALPHA",),timeout_seconds=10),
+ AgentTask("explain","Why not use MockGPU timing?",required_output_regex=("real W7900|real.*hardware",),timeout_seconds=10),
+ ))
+ engine=ForgeEngine(ScriptedBackend(responses),directory)
+ result=run_suite(engine,suite)
+ self.assertEqual(result.passed_tasks,2)
+ self.assertEqual(result.task_success_rate,1.0)
+ self.assertEqual(result.tool_call_validity_rate,1.0)
+ self.assertGreater(result.p50_latency_ms,0)
+ self.assertEqual(result.results[0].observed_tools,("read_file",))
+ self.assertTrue(result.results[0].trace_id)
+ engine.close()
+
+ def test_unexpected_tool_is_rejected_and_task_fails(self):
+ with tempfile.TemporaryDirectory() as directory:
+ suite=AgentTaskSuite("unit",(AgentTask("bad","Answer directly",expected_tools=(),allowed_tools=()),))
+ backend=ScriptedBackend(['{"name":"list_files","arguments":{}} '])
+ engine=ForgeEngine(backend,directory)
+ result=run_suite(engine,suite)
+ task=result.results[0]
+ self.assertFalse(task.passed)
+ self.assertFalse(task.tool_call_valid)
+ self.assertIn("not allowed",task.failure_reasons[0])
+ self.assertEqual(task.terminal_state,"idle")
+ engine.close()
+
+ def test_suite_hash_is_stable_and_file_load_validates_ids(self):
+ suite=AgentTaskSuite("stable",(AgentTask("a","prompt"),),metadata={"x":1})
+ self.assertEqual(suite.suite_hash,suite.suite_hash)
+ with tempfile.TemporaryDirectory() as directory:
+ path=Path(directory)/"suite.json"
+ payload={"format_version":1,"name":"x","tasks":[{"task_id":"a","prompt":"one"},{"task_id":"a","prompt":"two"}]}
+ path.write_text(json.dumps(payload),encoding="utf-8")
+ with self.assertRaisesRegex(ValueError,"unique"):
+ AgentTaskSuite.load(path)
+
+
+if __name__=="__main__":unittest.main()
From d01342c75ca791cc8e8306a3fa961a9f5b0bfffd Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:55:22 +0530
Subject: [PATCH 165/168] radeon forge: compare agent suites under quality
gates
---
extra/radeon_forge/evaluation/compare.py | 85 ++++++++++++++++++++++++
1 file changed, 85 insertions(+)
create mode 100644 extra/radeon_forge/evaluation/compare.py
diff --git a/extra/radeon_forge/evaluation/compare.py b/extra/radeon_forge/evaluation/compare.py
new file mode 100644
index 0000000000000..c6408d0be7ad2
--- /dev/null
+++ b/extra/radeon_forge/evaluation/compare.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass,asdict
+from pathlib import Path
+from typing import Any,Mapping
+
+
+class IncomparableSuites(ValueError):pass
+
+
+@dataclass(frozen=True)
+class MetricDelta:
+ baseline:float
+ candidate:float
+ absolute:float
+ relative:float|None
+
+
+@dataclass(frozen=True)
+class EvaluationGate:
+ passed:bool
+ task_success_preserved:bool
+ tool_validity_preserved:bool
+ all_baseline_passes_still_pass:bool
+ reasons:tuple[str,...]
+
+
+def _load(value:str|Path|Mapping[str,Any])->dict[str,Any]:
+ if isinstance(value,Mapping):return dict(value)
+ path=Path(value)
+ payload=json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(payload,dict):raise ValueError("evaluation result must be an object")
+ return payload
+
+
+def _delta(base:float,candidate:float)->dict[str,Any]:
+ return asdict(MetricDelta(base,candidate,candidate-base,None if base==0 else (candidate-base)/base))
+
+
+def _tasks(payload:Mapping[str,Any])->dict[str,Mapping[str,Any]]:
+ rows=payload.get("results",())
+ if not isinstance(rows,list):raise ValueError("evaluation results must be an array")
+ ret={}
+ for row in rows:
+ if not isinstance(row,Mapping) or not row.get("task_id"):continue
+ ret[str(row["task_id"])]=row
+ return ret
+
+
+def compare_evaluations(baseline_value:str|Path|Mapping[str,Any],candidate_value:str|Path|Mapping[str,Any],
+ *,max_task_success_drop:float=0.0,max_tool_validity_drop:float=0.0)->dict[str,Any]:
+ baseline,candidate=_load(baseline_value),_load(candidate_value)
+ if baseline.get("suite_hash")!=candidate.get("suite_hash"):
+ raise IncomparableSuites(f"suite_hash differs: baseline={baseline.get('suite_hash')} candidate={candidate.get('suite_hash')}")
+ base_tasks,cand_tasks=_tasks(baseline),_tasks(candidate)
+ if set(base_tasks)!=set(cand_tasks):
+ raise IncomparableSuites(f"task ids differ: baseline={sorted(base_tasks)} candidate={sorted(cand_tasks)}")
+
+ base_success=float(baseline.get("task_success_rate",0.0));cand_success=float(candidate.get("task_success_rate",0.0))
+ base_tools=float(baseline.get("tool_call_validity_rate",0.0));cand_tools=float(candidate.get("tool_call_validity_rate",0.0))
+ success_ok=cand_success+max_task_success_drop>=base_success
+ tools_ok=cand_tools+max_tool_validity_drop>=base_tools
+ regressed=[task_id for task_id,row in base_tasks.items() if bool(row.get("passed")) and not bool(cand_tasks[task_id].get("passed"))]
+ reasons=[]
+ if not success_ok:reasons.append(f"task success regressed {base_success:.4f}->{cand_success:.4f}")
+ if not tools_ok:reasons.append(f"tool validity regressed {base_tools:.4f}->{cand_tools:.4f}")
+ if regressed:reasons.append(f"baseline-passing tasks regressed: {regressed}")
+ gate=EvaluationGate(not reasons,success_ok,tools_ok,not regressed,tuple(reasons))
+
+ per_task=[]
+ for task_id in sorted(base_tasks):
+ left,right=base_tasks[task_id],cand_tasks[task_id]
+ per_task.append({"task_id":task_id,"baseline_passed":bool(left.get("passed")),"candidate_passed":bool(right.get("passed")),
+ "latency_ms":_delta(float(left.get("latency_ms",0.0)),float(right.get("latency_ms",0.0))),
+ "baseline_tools":left.get("observed_tools",[]),"candidate_tools":right.get("observed_tools",[]),
+ "candidate_failure_reasons":right.get("failure_reasons",[])})
+
+ latency={name:_delta(float(baseline.get(name,0.0)),float(candidate.get(name,0.0)))
+ for name in ("p50_latency_ms","p95_latency_ms","mean_latency_ms")}
+ return {"suite_name":baseline.get("suite_name"),"suite_hash":baseline.get("suite_hash"),"gate":asdict(gate),
+ "quality":{"task_success_rate":_delta(base_success,cand_success),"tool_call_validity_rate":_delta(base_tools,cand_tools)},
+ "latency":latency,"per_task":per_task,
+ "deployable_speedup":gate.passed and latency["p95_latency_ms"]["absolute"]<0,
+ "interpretation":"Latency improvement is deployable only when the frozen quality/tool gates pass."}
From 9b35ad504ae33468d520e0a7ece95977ecaba413 Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:55:42 +0530
Subject: [PATCH 166/168] radeon forge: test quality-gated agent latency
comparison
---
test/test_radeon_forge_evaluation_compare.py | 46 ++++++++++++++++++++
1 file changed, 46 insertions(+)
create mode 100644 test/test_radeon_forge_evaluation_compare.py
diff --git a/test/test_radeon_forge_evaluation_compare.py b/test/test_radeon_forge_evaluation_compare.py
new file mode 100644
index 0000000000000..7ca4714f4a6c2
--- /dev/null
+++ b/test/test_radeon_forge_evaluation_compare.py
@@ -0,0 +1,46 @@
+import unittest
+
+from extra.radeon_forge.evaluation.compare import IncomparableSuites,compare_evaluations
+
+
+def result(suite_hash="same",success=1.0,tools=1.0,p95=100.0,passed=(True,True),latencies=(80.0,120.0)):
+ return {"suite_name":"private","suite_hash":suite_hash,"task_success_rate":success,"tool_call_validity_rate":tools,
+ "p50_latency_ms":90.0,"p95_latency_ms":p95,"mean_latency_ms":100.0,
+ "results":[
+ {"task_id":"a","passed":passed[0],"latency_ms":latencies[0],"observed_tools":["read_file"],"failure_reasons":[]},
+ {"task_id":"b","passed":passed[1],"latency_ms":latencies[1],"observed_tools":[],"failure_reasons":[]},
+ ]}
+
+
+class TestEvaluationComparison(unittest.TestCase):
+ def test_faster_quality_preserving_candidate_is_deployable(self):
+ baseline=result(p95=120.0)
+ candidate=result(p95=80.0,latencies=(60.0,90.0))
+ comparison=compare_evaluations(baseline,candidate)
+ self.assertTrue(comparison["gate"]["passed"])
+ self.assertTrue(comparison["deployable_speedup"])
+ self.assertEqual(comparison["latency"]["p95_latency_ms"]["absolute"],-40.0)
+ self.assertEqual(len(comparison["per_task"]),2)
+
+ def test_speed_cannot_hide_task_or_tool_regression(self):
+ baseline=result(p95=120.0)
+ candidate=result(success=0.5,tools=0.5,p95=50.0,passed=(True,False),latencies=(30.0,40.0))
+ comparison=compare_evaluations(baseline,candidate)
+ self.assertFalse(comparison["gate"]["passed"])
+ self.assertFalse(comparison["deployable_speedup"])
+ self.assertIn("task success regressed",comparison["gate"]["reasons"][0])
+ self.assertTrue(any("baseline-passing tasks regressed" in reason for reason in comparison["gate"]["reasons"]))
+
+ def test_different_suite_or_task_ids_are_rejected(self):
+ with self.assertRaisesRegex(IncomparableSuites,"suite_hash differs"):
+ compare_evaluations(result("a"),result("b"))
+ candidate=result();candidate["results"]=candidate["results"][:1]
+ with self.assertRaisesRegex(IncomparableSuites,"task ids differ"):
+ compare_evaluations(result(),candidate)
+
+ def test_explicit_tolerance_is_visible_and_bounded(self):
+ comparison=compare_evaluations(result(success=1.0),result(success=0.99),max_task_success_drop=0.02)
+ self.assertTrue(comparison["gate"]["task_success_preserved"])
+
+
+if __name__=="__main__":unittest.main()
From 208493b68a2643313243349e313ee3ddd2d3f10a Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:57:11 +0530
Subject: [PATCH 167/168] radeon forge: test agent-metric deployment gate
---
test/test_radeon_forge_deployment_metrics.py | 52 ++++++++++++++++++++
1 file changed, 52 insertions(+)
create mode 100644 test/test_radeon_forge_deployment_metrics.py
diff --git a/test/test_radeon_forge_deployment_metrics.py b/test/test_radeon_forge_deployment_metrics.py
new file mode 100644
index 0000000000000..93921e2963e41
--- /dev/null
+++ b/test/test_radeon_forge_deployment_metrics.py
@@ -0,0 +1,52 @@
+import tempfile
+import unittest
+
+from extra.radeon_forge.synthesis.deployment import SafeHookRegistry
+from extra.radeon_forge.synthesis.hooks import HookActivationError,RuntimeFingerprint
+from extra.radeon_forge.synthesis.workspace import CandidateWorkspace,KernelSpec
+
+
+SOURCE='''
+def build_replacement(original, layer_index, model, context):
+ return original
+'''
+
+
+class TestDeploymentMetricGate(unittest.TestCase):
+ def test_stateful_candidate_requires_transition_and_agent_metric(self):
+ with tempfile.TemporaryDirectory() as directory:
+ workspace=CandidateWorkspace(directory)
+ spec=workspace.save_spec(KernelSpec("decode","block",target="gfx1100",invariants=("match",),
+ metadata={"heldout_command":["python3","transition.py"],"require_agent_evaluation":True,
+ "hook":{"layer":"transformer_block","target":"llama.block","adapter":"python_transformer_block",
+ "when":{"stages":["first_token","decode"]}}}))
+ candidate=workspace.create_candidate(spec.spec_id,SOURCE,"faster block")
+ workspace.update(candidate.candidate_id,"heldout_passed",{"heldout":{"passed":True}})
+ registry=SafeHookRegistry(workspace)
+ fingerprint=RuntimeFingerprint(architecture="gfx1100",runtime="tinygrad",model_family="llama")
+ with self.assertRaisesRegex(HookActivationError,"frozen agent-suite"):
+ registry.activate(candidate.candidate_id,fingerprint,"deploy")
+
+ workspace.update(candidate.candidate_id,"evaluation_failed",{"agent_evaluation_comparison":{"gate":{"passed":False}}})
+ with self.assertRaisesRegex(HookActivationError,"frozen agent-suite"):
+ registry.activate(candidate.candidate_id,fingerprint,"deploy")
+
+ workspace.update(candidate.candidate_id,"evaluation_passed",{"agent_evaluation_comparison":{"gate":{"passed":True}}})
+ active=registry.activate(candidate.candidate_id,fingerprint,"quality and latency gates passed")
+ self.assertEqual(active.candidate_id,candidate.candidate_id)
+
+ def test_stateless_non_final_hook_keeps_lighter_policy(self):
+ with tempfile.TemporaryDirectory() as directory:
+ workspace=CandidateWorkspace(directory)
+ spec=workspace.save_spec(KernelSpec("advisory","block",target="gfx1100",invariants=("match",),
+ metadata={"heldout_command":["python3","transition.py"],
+ "hook":{"layer":"transformer_block","target":"llama.block","adapter":"python_transformer_block",
+ "when":{"stages":["decode"]}}}))
+ candidate=workspace.create_candidate(spec.spec_id,SOURCE,"validated")
+ workspace.update(candidate.candidate_id,"heldout_passed",{})
+ active=SafeHookRegistry(workspace).activate(candidate.candidate_id,
+ RuntimeFingerprint(architecture="gfx1100"),"transition passed")
+ self.assertEqual(active.candidate_id,candidate.candidate_id)
+
+
+if __name__=="__main__":unittest.main()
From 5492257497b6f5ea0a0e04263ecf4715e52d921c Mon Sep 17 00:00:00 2001
From: Rishav Sanjay <83537945+rishavsanjay@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:58:28 +0530
Subject: [PATCH 168/168] radeon forge: normalize recognized ATT and SQTT
exports
---
.../radeon_forge/profiling/sqtt_normalize.py | 127 ++++++++++++++++++
1 file changed, 127 insertions(+)
create mode 100644 extra/radeon_forge/profiling/sqtt_normalize.py
diff --git a/extra/radeon_forge/profiling/sqtt_normalize.py b/extra/radeon_forge/profiling/sqtt_normalize.py
new file mode 100644
index 0000000000000..03eaf76a57040
--- /dev/null
+++ b/extra/radeon_forge/profiling/sqtt_normalize.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import csv, json, math
+from collections import Counter,defaultdict
+from dataclasses import asdict,dataclass
+from pathlib import Path
+from typing import Any,Iterable,Mapping
+
+
+@dataclass(frozen=True)
+class ParsedArtifact:
+ path:str
+ format:str
+ parsed:bool
+ event_count:int
+ duration_us:float
+ categories:Mapping[str,int]
+ names:Mapping[str,int]
+ wave_count:int|None=None
+ instruction_classes:Mapping[str,int]|None=None
+ reason:str=""
+
+
+class UnsupportedSQTTFormat(ValueError):pass
+
+
+def _manifest_path(value:str|Path)->Path:
+ path=Path(value)
+ if path.is_dir():path=path/"forge_capture_manifest.json"
+ if not path.is_file():raise FileNotFoundError(path)
+ return path
+
+
+def _artifact_paths(manifest:Mapping[str,Any],root:Path)->list[Path]:
+ paths=[]
+ for item in manifest.get("artifacts",()):
+ if not isinstance(item,Mapping):continue
+ path=Path(str(item.get("path","")))
+ if not path.is_absolute():path=root/path
+ if path.is_file():paths.append(path)
+ return paths
+
+
+def _perfetto(path:Path)->ParsedArtifact:
+ payload=json.loads(path.read_text(encoding="utf-8",errors="replace"))
+ events=payload.get("traceEvents") if isinstance(payload,Mapping) else None
+ if not isinstance(events,list):raise UnsupportedSQTTFormat("JSON does not contain traceEvents")
+ categories=Counter();names=Counter();duration=0.0;wave_ids=set();instructions=Counter()
+ for event in events:
+ if not isinstance(event,Mapping):continue
+ category=str(event.get("cat","uncategorized"));name=str(event.get("name","unnamed"))
+ categories[category]+=1;names[name]+=1
+ try:
+ value=float(event.get("dur",0.0))
+ if math.isfinite(value) and value>=0:duration+=value
+ except (TypeError,ValueError):pass
+ args=event.get("args",{})
+ if isinstance(args,Mapping):
+ for key in ("wave","wave_id","waveId"):
+ if key in args:wave_ids.add(str(args[key]))
+ for key in ("instruction_class","instruction_type","inst_class","opcode_class"):
+ if key in args:instructions[str(args[key])]+=1
+ return ParsedArtifact(str(path),"perfetto-json",True,len(events),duration,dict(categories),dict(names),
+ len(wave_ids) if wave_ids else None,dict(instructions) if instructions else None)
+
+
+def _column(fieldnames:Iterable[str],candidates:tuple[str,...])->str|None:
+ names=list(fieldnames)
+ lowered={name.lower():name for name in names}
+ for candidate in candidates:
+ if candidate.lower() in lowered:return lowered[candidate.lower()]
+ return None
+
+
+def _table(path:Path)->ParsedArtifact:
+ delimiter="\t" if path.suffix.lower() in {".tsv",".tab"} else ","
+ with path.open(newline="",encoding="utf-8",errors="replace") as handle:
+ reader=csv.DictReader(handle,delimiter=delimiter);fields=reader.fieldnames or []
+ if not fields:raise UnsupportedSQTTFormat("table has no header")
+ wave_col=_column(fields,("wave","wave_id","waveid"))
+ inst_col=_column(fields,("instruction_class","instruction_type","inst_class","opcode_class","instruction"))
+ name_col=_column(fields,("kernel_name","kernel","name","event"))
+ category_col=_column(fields,("category","cat","type","event_type"))
+ duration_col=_column(fields,("duration_us","duration","dur","elapsed_us"))
+ start_col=_column(fields,("start_us","start","begin"));end_col=_column(fields,("end_us","end","finish"))
+ rows=0;duration=0.0;waves=set();instructions=Counter();names=Counter();categories=Counter()
+ for row in reader:
+ rows+=1
+ if wave_col and row.get(wave_col):waves.add(str(row[wave_col]))
+ if inst_col and row.get(inst_col):instructions[str(row[inst_col])]+=1
+ if name_col and row.get(name_col):names[str(row[name_col])]+=1
+ if category_col and row.get(category_col):categories[str(row[category_col])]+=1
+ try:
+ if duration_col and row.get(duration_col) not in (None,""):value=float(row[duration_col])
+ elif start_col and end_col:value=float(row[end_col])-float(row[start_col])
+ else:value=0.0
+ if math.isfinite(value) and value>=0:duration+=value
+ except (TypeError,ValueError):pass
+ recognized=bool(wave_col or inst_col or duration_col or (start_col and end_col))
+ if not recognized:raise UnsupportedSQTTFormat("table lacks wave, instruction or timeline columns")
+ return ParsedArtifact(str(path),"sqtt-table",True,rows,duration,dict(categories),dict(names),
+ len(waves) if waves else None,dict(instructions) if instructions else None)
+
+
+def normalize_capture(value:str|Path)->dict[str,Any]:
+ manifest_path=_manifest_path(value);root=manifest_path.parent
+ manifest=json.loads(manifest_path.read_text(encoding="utf-8"))
+ parsed=[];unsupported=[]
+ for path in _artifact_paths(manifest,root):
+ if path==manifest_path:continue
+ try:
+ if path.suffix.lower()==".json":item=_perfetto(path)
+ elif path.suffix.lower() in {".csv",".tsv",".tab"}:item=_table(path)
+ else:raise UnsupportedSQTTFormat(f"no registered decoder for {path.suffix or 'binary'}")
+ parsed.append(item)
+ except (UnsupportedSQTTFormat,json.JSONDecodeError,csv.Error) as exc:
+ unsupported.append(ParsedArtifact(str(path),"unknown",False,0,0.0,{}, {},reason=str(exc)))
+ total_events=sum(item.event_count for item in parsed)
+ total_duration=sum(item.duration_us for item in parsed)
+ waves=sum(item.wave_count or 0 for item in parsed)
+ instructions=Counter()
+ for item in parsed:instructions.update(item.instruction_classes or {})
+ return {"capture_id":manifest.get("capture_id"),"kind":manifest.get("kind"),"parsed":bool(parsed),
+ "recognized_artifacts":[asdict(item) for item in parsed],"unsupported_artifacts":[asdict(item) for item in unsupported],
+ "summary":{"recognized_count":len(parsed),"unsupported_count":len(unsupported),"event_count":total_events,
+ "duration_us":total_duration,"wave_count":waves or None,"instruction_classes":dict(instructions)},
+ "contract":"Only recognized structured exports are normalized. Raw ATT/SQTT binaries remain immutable evidence until a matching decoder is installed."}