Skip to content
84 changes: 83 additions & 1 deletion src/hyperloom/common/tests/test_tracelens_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@

import pytest

from hyperloom.common.tracelens_report import analysis_json_path, fusion_findings, member_name
from hyperloom.common.tracelens_report import (
analysis_json_path,
fusion_findings,
member_name,
system_finding_summary,
system_findings,
)

_ATTENTION_GEMM = "Cijk_Alik_Bljk_B_BS_BH_Bias_HA_S_SAV_UserArgs_MT256x128x32..."
_SOFTMAX = "void at::native::(anonymous namespace)::cunn_SoftMaxForwardReg<c10::BFloat1..."
Expand Down Expand Up @@ -71,3 +77,79 @@ def test_a_report_without_fusion_findings_reads_as_none(tmp_path):

assert fusion_findings(tmp_path / "analysis.json") == []
assert fusion_findings(tmp_path / "missing" / "analysis.md") == []


def test_system_findings_keep_tracelens_order_with_their_metric_rows(tmp_path):
report = {
"system_optimizations": [
{
"operation": "Exposed Collective Communication",
"node": None,
"members": [
{"metric": "Exposed Communication %", "value": 60.72, "unit": "%"},
{"metric": "Compute/Comm Overlap %", "value": None, "unit": "%"},
],
"impact": None,
"resolution": " Prefetch each all-gather off the critical path. ",
"priority": 1,
},
{
"operation": "High GPU Idle Time",
"node": "node-1",
"members": [{"metric": "Idle %", "value": 18.4, "unit": "%"}],
"impact": None,
"resolution": None,
"priority": 2,
},
]
}
(tmp_path / "analysis.json").write_text(json.dumps(report), encoding="utf-8")

assert system_findings(tmp_path / "analysis.md") == [
{
"operation": "Exposed Collective Communication",
"node": "",
"priority": 1,
"metrics": [
{"metric": "Exposed Communication %", "value": 60.72, "unit": "%"},
{"metric": "Compute/Comm Overlap %", "value": None, "unit": "%"},
],
},
{
"operation": "High GPU Idle Time",
"node": "node-1",
"priority": 2,
"metrics": [{"metric": "Idle %", "value": 18.4, "unit": "%"}],
},
]


def test_a_report_without_system_findings_reads_as_none(tmp_path):
(tmp_path / "analysis.json").write_text(json.dumps({"system_optimizations": []}), encoding="utf-8")

assert system_findings(tmp_path / "analysis.json") == []
assert system_findings(tmp_path / "missing" / "analysis.md") == []


def test_a_system_finding_summary_shows_the_share_tracelens_ranks_it_by():
comm = {
"operation": "Exposed Collective Communication",
"node": "",
"priority": 1,
"metrics": [
{"metric": "Exposed Communication Time", "value": 18913.274, "unit": "ms"},
{"metric": "Exposed Communication %", "value": 60.72, "unit": "%"},
],
}
unread = {
"operation": "D2H Memory Copy Overhead",
"node": "node-1",
"priority": 4,
"metrics": [
{"metric": "Copy Count", "value": 1250.0, "unit": "count"},
{"metric": "Copy %", "value": None, "unit": "%"},
],
}

assert system_finding_summary(comm) == "P1 Exposed Collective Communication Exposed Communication %: 60.72%"
assert system_finding_summary(unread) == "P4 D2H Memory Copy Overhead [node-1] Copy %: n/a"
49 changes: 48 additions & 1 deletion src/hyperloom/common/tracelens_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@
from pathlib import Path
from typing import Any

from hyperloom_common.coerce import first_str, to_float
from hyperloom_common.coerce import first_str, to_float, to_int
from hyperloom_common.jsonio import read_json

__all__ = [
"analysis_json_path",
"fusion_findings",
"member_kernel_names",
"member_name",
"system_finding_summary",
"system_findings",
"task_operation",
]

Expand Down Expand Up @@ -74,3 +76,48 @@ def fusion_findings(report_path: str | Path) -> list[dict[str, Any]]:
}
)
return findings


def system_finding_summary(finding: Mapping[str, Any]) -> str:
"""A system finding on one line: priority, title, node and its share, the first ``%`` row TraceLens ranks it by.

The report is parsed back from model-written markdown, so a block whose table is off-contract has no ``%`` row; its
share reads ``n/a`` like an unreadable value, and the finding stays listed.
"""
share = next((m for m in finding["metrics"] if m["unit"] == "%"), None)
label = share["metric"] if share else "share"
value = "n/a" if share is None or share["value"] is None else f"{share['value']:g}%"
node = f" [{finding['node']}]" if finding["node"] else ""
return f"P{finding['priority']} {finding['operation']}{node} {label}: {value}"


def system_findings(report_path: str | Path) -> list[dict[str, Any]]:
"""The report's ``system_optimizations[]`` in TraceLens' order (report priority, largest share of GPU time first).

Each finding keeps its fixed ``operation`` title, the ``node`` of a multi-node report (empty otherwise), the report
``priority`` and its metric rows (``value`` is None when unreadable). Its ``resolution`` is left in the report, where
the agents read it. A missing report or key reads as no findings.
"""
report = read_json(analysis_json_path(report_path), default={}, require_dict=True)
findings: list[dict[str, Any]] = []
for task in report.get("system_optimizations") or []:
if not isinstance(task, dict):
continue
metrics = [
{
"metric": first_str(row.get("metric")),
"value": to_float(row.get("value")),
"unit": first_str(row.get("unit")),
}
for row in task.get("members") or []
if isinstance(row, dict) and row.get("metric")
]
findings.append(
{
"operation": task_operation(task),
"node": first_str(task.get("node")),
"priority": to_int(task.get("priority")),
"metrics": metrics,
}
)
return findings
10 changes: 9 additions & 1 deletion src/hyperloom/inference_optimizer/roofline_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from hyperloom_common.coerce import dict_rows, first_str
from hyperloom_common.jsonio import read_json
from hyperloom.common.tracelens_report import member_name
from hyperloom.common.tracelens_report import member_name, system_finding_summary
from hyperloom.inference_optimizer import framework_registry
from hyperloom.inference_optimizer.roofline_ceiling import (
ComputeTarget,
Expand Down Expand Up @@ -645,6 +645,12 @@ def direction_saturation(snapshot: dict[str, Any] | None) -> dict[str, Any]:
}


def _system_findings_lines(trace_analyze: dict[str, Any]) -> list[str]:
"""The digest's ``system_findings`` block; empty when TraceLens reported none."""
rows = [f" {system_finding_summary(f)}" for f in trace_analyze.get("system_findings") or []]
return ["system_findings:", *rows] if rows else []


def build_profiler_digest(
snapshots: list[dict[str, Any]] | None,
trace_analyze: dict[str, Any] | None,
Expand Down Expand Up @@ -694,6 +700,8 @@ def build_profiler_digest(
if lever:
lines.append(f"suggested_lever (dominant={direction}): {lever[0]}")

lines.extend(_system_findings_lines(ta))

reusable = ta.get("reusable_native_kernel_ids")
if reusable:
lines.append(f"reusable_native_kernel_ids={[str(r) for r in reusable[:12]]}")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# SPDX-FileCopyrightText: 2026 Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT

"""Behavior-lock tests for ``SharedState.record_trace_analyze``: 15-key dict, snapshot_id wrap-on-clear, capped history
with anchor, and history failures that reach the caller.
"""Behavior-lock tests for ``SharedState.record_trace_analyze``: the canonical key set, snapshot_id wrap-on-clear, capped
history with anchor, and history failures that reach the caller.
"""

from __future__ import annotations
Expand All @@ -22,11 +22,11 @@ def _record(state: SharedState, trace: str) -> None:
)


def test_written_dict_has_sixteen_keys() -> None:
"""The canonical trace-analysis record includes the selected steady-state trace."""
def test_written_dict_has_seventeen_keys() -> None:
"""The canonical trace-analysis record includes the selected steady-state trace and TraceLens' findings."""
state = SharedState()
_record(state, "x")
assert len(state.last_trace_analyze) == 16
assert len(state.last_trace_analyze) == 17
assert set(state.last_trace_analyze) == {
"trace_input",
"steady_state_trace",
Expand All @@ -41,6 +41,7 @@ def test_written_dict_has_sixteen_keys() -> None:
"analysis_md_path",
"analysis_md_text",
"fusion_findings",
"system_findings",
"roofline_snapshot_id",
"roofline_baseline_gain_at_snapshot",
"ts",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from __future__ import annotations

import json
from dataclasses import replace
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -267,3 +268,43 @@ def test_build_specialist_prompts_inserts_section_between_kb_and_recipe():
roof_idx = user.index("## 4a. ROOFLINE EVIDENCE")
recipe_idx = user.index("## 5. WARM-START RECIPE SUMMARY")
assert kb_idx < roof_idx < recipe_idx


@pytest.mark.asyncio
async def test_recorded_system_findings_reach_the_coordinator_digest_and_the_specialist_section(tmp_path):
"""A finding whose table TraceLens could not read back has no share row; it is listed, not a crash."""
comm = {
"operation": "Exposed Collective Communication",
"node": None,
"members": [{"metric": "Exposed Communication %", "value": 60.72, "unit": "%"}],
"impact": None,
"resolution": "Overlap the all-gather with compute.",
"priority": 1,
}
off_contract = {"operation": "H2D memcpy hygiene check", "node": None, "members": [], "priority": 2}
analysis_md = tmp_path / "analysis.md"
analysis_md.write_text("# Executive Summary\n", encoding="utf-8")
(tmp_path / "analysis.json").write_text(
json.dumps({"system_optimizations": [comm, off_contract]}), encoding="utf-8"
)
state = SharedState()
state.record_trace_analyze(
{"trace_input": str(tmp_path / "trace.json")},
{"hot_kernels": [], "trace_report_path": str(analysis_md), "trace_health_warnings": []},
)
lines = [
"P1 Exposed Collective Communication Exposed Communication %: 60.72%",
"P2 H2D memcpy hygiene check share: n/a",
]

digest = state.to_prompt_summary()
assert all(f" {line}" in digest for line in lines)

params: dict[str, Any] = {"domain": "serving_specialist"}
await _make_coord(tmp_path, state=state).specialist_dispatch.warm_specialist_params(params)
section = roofline_evidence_section(_make_inp(params["roofline_evidence"]))
assert all(f"- {line}" in section for line in lines)

state.last_trace_analyze["system_findings"] = []
assert "system_findings:" not in state.to_prompt_summary()
assert not any("System bottlenecks" in row for row in roofline_evidence_section(_make_inp({"system_findings": []})))
12 changes: 9 additions & 3 deletions src/hyperloom/orchestrator/prompts/orchestration.md
Original file line number Diff line number Diff line change
Expand Up @@ -494,9 +494,15 @@ them**:
before `🟡`; fusion rows want a fused rewrite). You dispatch neither: the
rewrite controller selects its own operators and integrates its own patches,
and fusion queues its KEEPs for you to `integrate`.
* **`## System-Level Optimizations`** → `explore` variants; the text
names the flag (e.g. "graph capture stalls" → `--cuda-graph-max-bs`).
Prefer a `provenance='specialist:<domain>'` variant targeting it.
* **System bottlenecks** → an `explore` variant where the framework exposes
the lever as a server arg or env (e.g. "capture the decode step in a graph"
→ CUDA-graph settings), otherwise a specialist patch at the call site the
fix names (a host read such as `.item()`, a redundant `.contiguous()` or
clone); neither is a kernel rewrite. TraceLens lists them under
`system_findings` in `profiler_digest` (priority, title, share of GPU
time), and a dispatched specialist gets the same lines; each fix is under
`## System-Level Optimizations` in analysis.md. For a variant, prefer
`provenance='specialist:<domain>'` targeting it.

<!-- phase: FRAMEWORK_AGENT -->
### Choosing specialist domain by bottleneck
Expand Down
27 changes: 27 additions & 0 deletions src/hyperloom/orchestrator/prompts/roofline_evidence_section.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pathlib import Path
from typing import Any

from hyperloom.common.tracelens_report import system_finding_summary
from hyperloom.inference_optimizer import framework_registry

from ..specialists.prompt_inputs import SpecialistPromptInputs
Expand Down Expand Up @@ -119,6 +120,31 @@ def _fusion_findings_rows(findings: Any) -> list[str]:
return rows


_SYSTEM_FINDINGS_GUIDE = (
"Each one's fix, which names its lever, is under `## System-Level Optimizations` in the report below: read it "
"before acting on one. Idle points at CUDA-graph capture, batch size and async scheduling; exposed "
"communication at parallel layout and compute/communication overlap; memory copies at pinned memory, "
"non-blocking copies and keeping tensors on device. A lever the framework exposes as a server arg or env is an "
"`explore` variant; a fix naming a source change at a call site (a host read such as `.item()`, a redundant "
"`.contiguous()`) is a patch there; neither is a kernel rewrite. A family not listed is one TraceLens did not "
"flag on this trace."
)


def _system_findings_rows(findings: Any) -> list[str]:
"""List TraceLens' system bottlenecks one line each and point at their fixes; empty when the report has none."""
if not findings:
return []
return [
"**System bottlenecks (TraceLens, largest share of GPU time first):**",
"",
*(f"- {system_finding_summary(finding)}" for finding in findings),
"",
_SYSTEM_FINDINGS_GUIDE,
"",
]


def _no_snapshot(framework: str) -> str:
"""What the section says while it has no evidence: that a snapshot is on its way, or that none will come for a
framework that runs under no torch profiler, of which no roofline is enqueued."""
Expand Down Expand Up @@ -197,6 +223,7 @@ def roofline_evidence_section(inp: SpecialistPromptInputs) -> list[str]:
rows.append("")

rows.extend(_fusion_findings_rows(ev.get("fusion_findings")))
rows.extend(_system_findings_rows(ev.get("system_findings")))

analysis_path = ev.get("analysis_md_path")
if analysis_path:
Expand Down
13 changes: 10 additions & 3 deletions src/hyperloom/orchestrator/specialists/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@
#: Domains whose focus reads the target's ``config.json`` summary from ``model_info``.
_MODEL_INFO_DOMAINS: frozenset[str] = frozenset({"static_recon_specialist", "speculative_decoding_specialist"})

#: The ``last_trace_analyze`` lists a specialist's roofline evidence carries, and how many rows of each it is shown.
_ROOFLINE_EVIDENCE_LISTS: tuple[str, ...] = ("hot_kernels_top15", "fusion_findings", "system_findings")
_ROOFLINE_EVIDENCE_ROWS = 8


def _evidence_rows(last_trace_analyze: dict[str, Any], key: str) -> list[Any]:
return list(last_trace_analyze.get(key) or [])[:_ROOFLINE_EVIDENCE_ROWS]


#: ``(SharedState attribute, param key, conversion)`` for the values a specialist is warmed with. The converted value
#: decides: an empty string, an empty container and a zero are not exported, because an absent key is how the
#: specialist reads "this session has none".
Expand Down Expand Up @@ -246,13 +255,11 @@ async def warm_specialist_params(self, params: dict[str, Any]) -> None:
exc,
)
executive_summary = {}
hot_kernels = list(last_ta.get("hot_kernels_top15") or [])[:8]
params["roofline_evidence"] = {
"analysis_md_path": analysis_path,
"roofline_snapshot_id": last_ta.get("roofline_snapshot_id"),
"executive_summary": executive_summary,
"hot_kernels_top15": hot_kernels,
"fusion_findings": list(last_ta.get("fusion_findings") or [])[:8],
**{key: _evidence_rows(last_ta, key) for key in _ROOFLINE_EVIDENCE_LISTS},
}

measurement = getattr(state, "current_best_measurement", None)
Expand Down
Loading
Loading