Skip to content
76 changes: 48 additions & 28 deletions agents/forge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,21 @@ entering the ordinary performance search:
timing through the public baseline actions. Start from the workspace's
unimplemented template at the candidate entry; an empty file is created only
if the entry is missing.
2. Run `kernelforge.orchestrator.agent.make_agent_fn` with the target backend's
2. Run the engine's published implementer,
`kernelforge.workflows.forge_loop.api.make_agent_fn`, with the target backend's
expertise prompt, normal configured provider/model, real SDK session execution,
workspace guard and correctness-only in-session gate. README.md,
`_aka_eval/CANDIDATE.md` and the read-only baseline supply the contract.
Both the keyword interface and the grouped `ImplementerSetup` interface are
supported, preserving the same protected paths, correctness gate and session
limit. The grouped gate receives the validation limit for both stage and
Its `ImplementerSetup` carries the protected paths, the correctness gate and
the session limit; the gate receives the validation limit for both stage and
benchmark timeouts.
For grouped engines, new helper files are allowed inside declared trees in
directories present at session startup. That engine's nonrecursive new-file
allowlist rejects helpers in newly created directories; Arena does not widen
the allowlist outside the task's declared trees.
New helper files are allowed inside declared trees in directories present at
session startup. The engine's nonrecursive new-file allowlist rejects helpers
in newly created directories; Arena does not widen the allowlist outside the
task's declared trees. The loop that follows, and the loop of an
optimize-only run, are handed the same allowlist as `--commit-new-path`, so a
session that adds a module to a declared tree has it committed with its KEEP
rather than having the whole change rolled back.
After initialization, the loop receives the remaining campaign budget and,
when supported by its CLI, the same absolute deadline.
3. After each session, independently run candidate compile and complete
Expand Down Expand Up @@ -334,13 +337,23 @@ backfills a solution.
## Installed KernelForge runtime

The command line and the measurement driver are the whole interface to the
engine. The adapter patches no engine symbol and pins no engine module, so the
two release cadences are independent; [engine.py](engine.py) exists for the two
jobs that genuinely need the engine importable. `--arena-probe` reports what the
installed engine accepts, in the exact interpreter the campaign will use, and
checks that both commands still take the options the adapter builds.
engine for optimize and rewrite campaigns, and the adapter patches no engine
symbol. [engine.py](engine.py) exists for the two jobs that genuinely need the
engine importable, and refuses anything else.

`--arena-probe` reports what the installed engine accepts, in the exact
interpreter the campaign will use. It checks that both commands still take the
options the adapter builds, reads the capability handshake the rewrite command
prints (`forge-rewrite-by-flydsl --capabilities-json`), and imports the library
names initialization is built from.

`--arena-initialize` runs the correctness-only implementer the engine publishes
only as a library. It refuses anything else.
only as a library. It is built from `kernelforge.workflows.forge_loop.api`, the
interface the engine publishes for callers outside its loop, with
`kernelforge.config.Config` and the usage ledger in
`kernelforge.agent_backends.usage`. An engine without them, which is any
Hyperloom revision before `05e67da61`, fails the probe before campaign work
starts.

Upstream owns its GPU DSL/compiler support and SDKs. Install the `forge` extra in
the GPU runtime environment (it also pulls the agent SDK dependencies). Through
Expand Down Expand Up @@ -382,9 +395,9 @@ A dedicated interpreter can be selected with run-level `agent.python`.
Backend selection follows the run's target language. The operator name comes
from the task contract, and the engine's KB framework identity (`aiter`,
`sglang`, `vllm`, else `standalone`) from the baseline's recorded provenance
source. The probe reports the rewrite's accepted source languages from
`kernelforge.rewrite_by_flydsl.protocol`; an engine that does not publish them
cannot run a FlyDSL rewrite. TileLang is a baseline language only and never a
source. The probe reports the rewrite's accepted source languages from the
capability handshake the rewrite command prints; an engine that does not publish
them cannot run a FlyDSL rewrite. TileLang is a baseline language only and never a
Forge target.

New scratch repositories start on `codex/arena-forge`, independently of the
Expand All @@ -397,10 +410,18 @@ Search defaults live in [agent_config.yaml](agent_config.yaml); the run may
override `workflow`, `model`, `agent_backend`, `permission_mode`,
`timeout_seconds`, `session_timeout_seconds`, `max_port_attempts`,
`initialization_max_attempts`, `initialization_budget_fraction`,
`supervisor_backend`, and `python`. An empty supervisor follows the selected
backend. Lane count, task preparation, profiling, planning probes and knowledge
warm starts follow the engine defaults. Arena publishes the task and leaves the
search policy to Forge. Two consequences are load bearing. The public task
`supervisor_backend`, `lanes`, and `python`. An empty supervisor follows the
selected backend. `lanes` is the engine's implementer lane count per round:
empty follows the engine default, and the value is passed to `forge-loop` as
`--lanes`, so what a given count means is the engine's to say. A rewrite's
nested loop is not given it. Task preparation, profiling and
knowledge warm starts follow the engine defaults. One thing about scoring is
not left to the engine: Arena's speedup is the geometric mean of per-case
speedups, so an engine whose `forge-loop` accepts `--case-aggregate` is told
`geometric` and judges its own KEEPs by the mean that grades its result. An
engine without the option still runs and searches by its own aggregate; the
probe reports which under `case_aggregate`. Arena publishes the task and
leaves the rest of the search policy to Forge. Two consequences are load bearing. The public task
protocol exposes no profiler invocation, so the bridge answers `--profile-run`
with an explicit unsupported capability. A single-file upstream recipe cannot
describe a multi-file candidate, so a `solution/` tree with helper files may
Expand All @@ -425,13 +446,12 @@ Most tests drive the adapter with a replaced engine subprocess: they cover the
protocol, the delivery selection and the recovery paths, and their CPU timing
fixtures are not GPU measurements or actual optimization runs. The tests gated on
`AKA_FORGE_PROBE_PYTHON` use the installed engine for real — that a driver's
failure diagnostics are never read as a benchmark or a correctness pass, that the
scratch branch survives campaign preflight under a `main` or `master` Git
default, and that HIP/Triton initialization runs the real Forge implementer,
session execution, workspace guard and correctness gate. They cover rejected
attempts, an unedited workspace, harness tampering, session timeouts and a
failing loop. The provider is scripted throughout, so they prove neither model
quality nor GPU compiler compatibility. Real LLM/GPU qualification on
failure diagnostics are never read as a benchmark or a correctness pass, and
that HIP/Triton initialization runs the real Forge implementer, session
execution and correctness gate. They cover rejected attempts, an unedited
workspace, harness tampering, session timeouts and a failing loop. The provider
is scripted throughout and enters through the engine's provider registry, so
they prove neither model quality nor GPU compiler compatibility. Real LLM/GPU qualification on
schema-v3 tasks remains a required integration gate for every target language;
Gluon initialization and the v3 workflows have not yet run on a GPU.

Expand Down
26 changes: 24 additions & 2 deletions agents/forge/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
from agents.forge import bridge
from agents.forge.common import _read_forge_result, _resolve_gpu_arch, _resolve_gpu_type, run_forge_subprocess
from agents.forge.task_context import TaskContext
from agents.forge.bundles import allow_candidate_paths, candidate_files, committed_candidate, copy_workspace, install_candidate
from agents.forge.bundles import (allow_candidate_paths, candidate_files, committed_candidate, copy_workspace,
install_candidate, new_path_patterns)
from src.task_contract import BASELINE_DIR
from src.task_spec import resolve_task_path
from src.tools.agent_cost import report_agent_usage
Expand Down Expand Up @@ -128,7 +129,7 @@ def _config(eval_config: dict) -> dict:
raise ValueError("agent run configuration must be a mapping")
allowed = {"workflow", "model", "timeout_seconds", "permission_mode", "agent_backend",
"python", "max_port_attempts", "supervisor_backend", "session_timeout_seconds",
"initialization_max_attempts", "initialization_budget_fraction"}
"initialization_max_attempts", "initialization_budget_fraction", "lanes"}
config.update({key: value for key, value in overrides.items() if key in allowed})
if overrides.get("agent_backend") not in (None, "claude") and "model" not in overrides:
# A Claude default is not a model ID for another provider. Let upstream
Expand All @@ -140,6 +141,9 @@ def _config(eval_config: dict) -> dict:
for field in ("max_port_attempts", "session_timeout_seconds", "initialization_max_attempts"):
if type(config[field]) is not int or config[field] < 1:
raise ValueError(f"Forge {field} must be a positive integer")
# Empty leaves the lane count to the engine, which also owns its upper bound.
if config.get("lanes") is not None and (type(config["lanes"]) is not int or config["lanes"] < 1):
raise ValueError("Forge lanes must be a positive integer")
fraction = config["initialization_budget_fraction"]
if type(fraction) not in (int, float) or not 0 < fraction < 1:
raise ValueError("Forge initialization_budget_fraction must be between zero and one")
Expand Down Expand Up @@ -286,6 +290,10 @@ def recover_timeout_candidate(plan: dict, engine: Path, result, fallback: str =
return "", ""


#: How src.testcases.calculate_average_speedup combines per-case speedups, in the
#: engine's vocabulary.
ARENA_CASE_AGGREGATE = "geometric"

#: The engine dates its own budget from the moment its process is up, which
#: trails the moment this argv is built by interpreter start, the capability
#: probe and the engine import. Measured at 42s on MI355X; keep room to spare.
Expand Down Expand Up @@ -341,6 +349,19 @@ def build_command(plan: dict, context: TaskContext, config: dict, *, gpu_arch: s
"--baseline-json", plan["baseline"], "--program-md-file", plan["program"],
"--agent-backend", config["agent_backend"],
"--session-timeout-sec", str(config["session_timeout_seconds"])]
# The task lets a candidate add files to its solution tree, and the
# engine commits a created file only where it was told one may appear.
# Without this a session that splits the kernel into a new module has
# its whole change rolled back.
for pattern in new_path_patterns(context.spec, root):
command += ["--commit-new-path", pattern]
if config.get("lanes") is not None:
command += ["--lanes", str(config["lanes"])]
if plan.get("case_aggregate"):
# Arena's speedup is the geometric mean of per-case speedups. An
# engine searching by another mean keeps candidates Arena scores
# lower, so it is told which one grades its result.
command += ["--case-aggregate", ARENA_CASE_AGGREGATE]
else:
command += ["--source-kernel", plan["source"], "--flydsl-kernel-name", plan["anchor"],
"--logical-op-name", context.operator, "--no-prepare-driver",
Expand Down Expand Up @@ -434,6 +455,7 @@ def launch(eval_config: dict, task_config_dir: str, workspace: str) -> str:
capabilities = json.loads(probe.stdout)
status["engine"] = capabilities
plan["applyback_optional"] = bool(capabilities.get("applyback_optional"))
plan["case_aggregate"] = bool(capabilities.get("case_aggregate"))
require_supported_backend(context.spec, capabilities)
candidate = context.spec.candidate
initially_target = candidate.initial_state == "implemented" and candidate.initial_language == candidate.language
Expand Down
3 changes: 3 additions & 0 deletions agents/forge/agent_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ permission_mode: acceptEdits
# Shared wall-clock cap: setup, checks, PORT and nested OPTIMIZE together.
timeout_seconds: 87300
session_timeout_seconds: 3600
# Implementer lanes per round. Empty follows the engine's default; 1 runs one
# implementer session per round.
lanes:
max_port_attempts: 3
# HIP/Triton/Gluon initialization uses Forge's own correctness-only implementer.
# Reserve the remaining campaign budget for the ordinary optimization loop.
Expand Down
14 changes: 14 additions & 0 deletions agents/forge/bundles.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ def allow_candidate_paths(engine: Path, spec: TaskSpec, *, prefix: str = "") ->
stream.write("\n".join(lines) + "\n")


def new_path_patterns(spec: TaskSpec, root: Path) -> list[str]:
"""Authorize new files only in declared trees and existing directories."""
patterns = []
for scope in spec.candidate.editable:
if scope.scope != "tree":
continue
tree = resolve_task_path(root, scope.path, must_exist=True)
for directory in [tree, *sorted(path for path in tree.rglob("*") if path.is_dir())]:
relative = directory.relative_to(root).as_posix()
resolve_task_path(root, relative, must_exist=True)
patterns.append(relative + "/*")
return patterns


def copy_workspace(source: Path, destination: Path) -> None:
"""Copy, without hardlinks, and refuse external symlinks before copying."""
for path in source.rglob("*"):
Expand Down
34 changes: 24 additions & 10 deletions agents/forge/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
from __future__ import annotations

import asyncio
import contextlib
import importlib.metadata
import io
import json
import os
from pathlib import Path
Expand All @@ -28,18 +30,29 @@
ADAPTER_API = 1


def _rewrite_handshake(cli) -> dict:
"""What ``forge-rewrite-by-flydsl --capabilities-json`` prints for the rewrite's consumers."""
printed = io.StringIO()
with contextlib.redirect_stdout(printed):
cli.main(args=["forge-rewrite-by-flydsl", "--capabilities-json"], standalone_mode=False)
return json.loads(printed.getvalue())


def probe() -> dict:
"""Check the published command line the adapter builds, nothing deeper."""
"""Check the published command line the adapter builds and the library names initialization imports."""
from kernelforge import cli
from kernelforge.kernel_backends.constants import KERNEL_BACKENDS
from agents.forge.initialization import engine_library

# An engine that moved one of these fails here, before any campaign work.
engine_library()
try:
version = importlib.metadata.version("hyperloom-inference_optimizer")
except importlib.metadata.PackageNotFoundError:
version = "source-checkout"
required = {
"forge-loop": {"kernel", "driver", "workspace_dir", "max_hours",
"source_files", "target_functions", "baseline_json"},
"source_files", "target_functions", "baseline_json", "commit_new_paths"},
"forge-rewrite-by-flydsl": {"source_kernel", "driver", "workspace_dir", "max_hours",
"prepare_driver", "flydsl_kernel_name"},
}
Expand All @@ -54,20 +67,21 @@ def probe() -> dict:
# adapter asks for the standalone kernel only where the engine accepts that.
rewrite = cli.main.commands["forge-rewrite-by-flydsl"]
applyback_optional = "applyback" in {parameter.name for parameter in rewrite.params}
# Optional as well: an engine that cannot be told how Arena aggregates
# per-case speedups still runs, scoring its search by its own aggregate.
loop = cli.main.commands["forge-loop"]
case_aggregate = "case_aggregate" in {parameter.name for parameter in loop.params}
# The PORT states which source languages it ingests. An engine that does
# not publish them cannot be told the baseline's language, so the adapter
# refuses a FlyDSL rewrite there instead of letting the engine guess.
try:
from kernelforge.rewrite_by_flydsl.protocol import SUPPORTED_SOURCE_LANGUAGES
rewrite_sources = sorted(str(name) for name in SUPPORTED_SOURCE_LANGUAGES)
except ImportError:
rewrite_sources = None
languages = _rewrite_handshake(cli).get("source_languages")
rewrite_sources = sorted(map(str, languages)) if isinstance(languages, list) else None
from agents.forge.adapter import INITIALIZATION_LANGUAGES
return {"adapter_api": ADAPTER_API, "version": version,
"initialization_targets": sorted([*INITIALIZATION_LANGUAGES, "flydsl"]),
"backends": sorted(KERNEL_BACKENDS), "rewrite_target": "flydsl",
"rewrite_source_languages": rewrite_sources,
"applyback_optional": applyback_optional}
"applyback_optional": applyback_optional, "case_aggregate": case_aggregate}


def main(argv=None):
Expand All @@ -80,7 +94,7 @@ def main(argv=None):
plan = load_plan(Path(os.environ["ARENA_FORGE_PLAN"]))
probe() # Refuse an engine whose published command line moved.
from kernelforge.cli import main as cli
from agents.forge.initialization import initialize, prepare_loop
from agents.forge.initialization import engine_library, initialize, prepare_loop
from agents.forge.process_tree import managed_children
with managed_children():
initialization = asyncio.run(initialize(plan))
Expand All @@ -89,7 +103,7 @@ def main(argv=None):
# mode. Preserve a failed engine exit, even if it wrote partial JSON.
if isinstance(exit_code, int) and exit_code != 0:
raise SystemExit(exit_code)
from kernelforge.tracker.usage import combine_usage_totals
combine_usage_totals = engine_library().usage.combine_usage_totals
result_path = Path(plan["result"])
result = json.loads(result_path.read_text())
result["initialization"] = initialization
Expand Down
Loading
Loading