Metadata-Version: 2.4
Name: dace-tactics
Version: 0.1.3
Summary: Reproducible transformation-based agents and a harness for DaCe: tactics applied as legal moves, replayed as recipes.
Author-email: Yakup Budanaz <ybudanaz@ethz.ch>
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/spcl/tactics
Project-URL: Repository, https://github.com/spcl/tactics
Project-URL: Changelog, https://github.com/spcl/tactics/blob/main/CHANGELOG.md
Keywords: dace,sdfg,loop-nest,code-generation,compilers,autotuning,hpc,llm-agents
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Compilers
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: pydantic>=2
Requires-Dist: pyyaml
Requires-Dist: sympy
Requires-Dist: opt-einsum>=3.0
Requires-Dist: dace-extended>=1.0.2
Requires-Dist: dace-relayout>=0.1.2
Requires-Dist: mcp>=2.3
Provides-Extra: fparena
Requires-Dist: fp-arena>=0.1.0; extra == "fparena"
Provides-Extra: bench
Requires-Dist: hpcagent-bench>=1.0.2; extra == "bench"
Dynamic: license-file

# Tactics

Tactics (formerly Tactics) lets an agent optimize a DaCe program only through legal, checked moves. A tactic is a
transformation rule (`tile-for`, `interchange-for`, `doall-fusion`, ...); a move applies one tactic to labeled rows
with its arguments; the ordered moves of an episode are its recipe, which replays the result. Install it with
`pip install dace-tactics` (PyPI refuses the name `tactics`) and import it as `tactics`.

Tactics optimizes whole DaCe programs on CPU and GPU. It canonicalizes a program, reshapes its loop nests with
legal moves, cuts it into kernels, places each kernel on a device, builds and sweeps each kernel, and reports what
to change next. Every kernel is checked against its Python oracle, the whole program against the benchmark's
reference.

Every stage has a deterministic default, so a run works with no agent, one agent or a human driving the same
`Session` API. Each call returns a typed record (`tactics/records.py`, frozen pydantic models).

| Stage | Decides | Default | Call |
|---|---|---|---|
| [1 Canonicalize](docs/stages.md#stage-1-canonicalize) | canonical parallel form (CPF) | DaCe canonicalization up to fusion | |
| [2 Moves](docs/stages.md#stage-2-moves) | fusion, fission, interchange, tiling, hoisting, layout, vectorization | canonicalization's fusion stage | `apply_move` |
| [3 Scopes](docs/stages.md#stage-3-scopes) | which regions become kernels | parallel maps; sequential and mixed loops whole; large maps split | `set_scope`, `unset_scope` |
| [4 Placement](docs/stages.md#stage-4-placement) | device per kernel | parallel on GPU, sequential on CPU | `place` |
| [5 Kernels](docs/stages.md#stage-5-kernels) | each kernel's code | CPF C++ (CPU) or CUDA (GPU) | `set_kernel_source` |
| [6 Variants](docs/stages.md#stage-6-variants) | compiler, FP mode, cost model | fastest variant that matches the oracle | `sweep` |
| [7 Feedback](docs/stages.md#stage-7-feedback) | what to try next | hints, whole-program and kernel times, offloading | `performance` |

## Agents: the HPCAgent-Bench plugin

[plugin/tactics](plugin/tactics) is an HPCAgent-Bench plugin. Point `HPCAGENT_BENCH_USER_PLUGIN_DIRS` at it and
run the `tactics` packet; it sets the library input mode itself (`finalize` hands the judge a library). The
`tactics` packet exposes the moves phase; scopes, placement and kernel builds run their defaults in
`get_performance` and `finalize`, on a copy, so a score leaves the moves open. The `tactics-full` packet (alias
`tactics-two-stage`) is structured, then unstructured: the agent settles moves and scopes, placement fixes the
kernels, and the agent then writes and tunes them one at a time.
`tactics-subagents` hands each kernel to a `kernel-optimizer` subagent. `tactics-requests` is `tactics` with
`request_transformation`, which records a transformation no move offers ([design](docs/design/transformation-requests.md)).
`tactics-llvm` and `tactics-mlir` are the baselines that choose compiler passes instead of moves: the same program,
entry and library, every kernel built through the agent's `opt -passes=` or `polygeist-opt --pass-pipeline=` pipeline.
`tactics-passes` is the pass-move agent: named MLIR, then LLVM, passes applied one at a time, with the loops after
each move ([design](docs/design/mlir-llvm-agent.md)).
The skill page ([skills/tactics](plugin/tactics/skills/tactics/SKILL.md)) explains the tree and the moves. Each
tool is listed with MCP annotations: reads are read-only, `write_kernel` and `unset_scope` overwrite earlier work.

| Phase | Tools | Packets |
|---|---|---|
| structured (stages 1-2) | `get_cpf`, `view_tree`, `list_move_kinds`, `list_moves`, `apply_move`, `run_defaults` | both |
| any | `get_performance`, `finalize` | both |
| scopes, kernels, codegen | `set_scope`, `unset_scope`, `list_kernels`, `focus_kernel`, `read_kernel`, `write_kernel`, `tune_kernel` | `tactics-full` (`tactics-two-stage`), `tactics-subagents` |

`write_kernel`, `tune_kernel` and `get_performance` answer with `Session.performance()`: the whole program's time and
correctness, each kernel's device and the bytes moved between memories, and each kernel's time and share. Stages not
reached yet run with their defaults on a copy, each kernel built in the first configuration of the sweep so that two
measurements compare. The answer is reused until the program changes, and a kernel's until it does. Reads and moves
(`apply_move`, `run_defaults`) answer at once without a time and take no device slot; `get_performance`, `write_kernel`,
`tune_kernel` and `finalize` hold one. `finalize` builds the program in the bench C ABI, each kernel linked from its own
build (the sweep's winner by default), into the shared folder. The packet's `score`, `submit` and `profile` replace the
bench's: they take no code, and each sends the judge the library `finalize` built with its `workspace_bytes`, which that
library's scratch needs.

Every library call has its implementation from the start, the fastest this host has for the target, shown in the tree;
`pure` loops come only from `inline-library` or `set-library-implementation`, or where a call has nothing else.

A call stops when its client leaves or after `TOOL_TIMEOUT_S`, and the session keeps what it built and measured, so
repeating the call goes on from there. The route journals every change, and a session that dies is rebuilt from it.

[docs/README.md](docs/README.md) maps the code and the phases, and says how to add a move, a tool, a phase or a packet.

## MCP server

`tactics-mcp KERNEL [--preset S] [--datatype float64] [--gpu]` serves the same tools over MCP (stdio) on one bench
kernel, for any MCP client. Each tool's input schema is its pydantic model's (`tactics/wire.py`), and its hints
(read-only, destructive) follow its effect. Inside the bench judge, the plugin serves the same tools as JSON-RPC at
`POST /tactics/mcp`, with the episode's identity in each call's `_meta`.

## Quick start

```bash
python examples/quickstart.py --device cpu --out quickstart_out
python examples/quickstart.py --device gpu --kernel jacobi_1d --out quickstart_jacobi
```

It runs every default on an HPCAgent-Bench kernel at preset S and saves each stage's SDFG and tree, the kernel DAG, each
kernel's unit and library, the program's code, the winning variant and the feedback. On `fuse_diamond`, canonicalization
turns four sequential loops into one parallel map. A benchmark's reference solution is replayed with `python -m
tactics.replay reference_solutions/<kernel>.py` ([reference solutions](reference_solutions/README.md)).

## The program as a tree

The agent reads the program as a tree of labeled rows and acts on it by label. For

```python
@dace.program
def blur_steps(A: dace.float64[N], B: dace.float64[N], W: dace.float64[N, N], y: dace.float64[N]):
    for t in range(T):
        B[1:-1] = (A[:-2] + A[1:-1] + A[2:]) / 3.0
        A[1:-1] = B[1:-1]
    y[:] = W @ A
```

`get_cpf` prints, every state closed:

```text
SDFG 'blur_steps'
|- for0  _loop_it_0=0:T  num_states=4
|  `- state3  doalls=4  reads=['A', 'B'] writes=['A', 'B']
`- state2  doalls=1  reads=['A', 'W'] writes=['y']
```

and `view_tree expand=[state3, doall3, doall4]` opens the time step's state and two of its doalls; `doall5` stays closed:

```text
SDFG 'blur_steps'
|- for0  _loop_it_0=0:T  num_states=4
|  `- state3  reads=['A', 'B'] writes=['A', 'B']
|     |- doall3  [_loop_it_1=0:N - 2]  reads=['A'] writes=['A_slice_plus_A_slice']  num_states=1
|     |  : A_slice_plus_A_slice[_loop_it_1] = A[_loop_it_1] + A[_loop_it_1 + 1]
|     |  `- state4  reads=['A'] writes=['A_slice_plus_A_slice']
|     |- doall4  [_loop_it_2=0:N - 2]  reads=['A', 'A_slice_plus_A_slice'] writes=['A_slice_A_slice_plus_A_slice']  num_states=1
|     |  : A_slice_A_slice_plus_A_slice[_loop_it_2] = A_slice_plus_A_slice[_loop_it_2] + A[_loop_it_2 + 2]
|     |  `- state5  reads=['A', 'A_slice_plus_A_slice'] writes=['A_slice_A_slice_plus_A_slice']
|     |- doall5  [_loop_it_3=0:N - 2]  reads=['A_slice_A_slice_plus_A_slice'] writes=['B']  num_states=1
|     `- lib_copy0  LIBNODE Copy [Auto]  reads=['B'] writes=['A']
`- state2  doalls=1  reads=['A', 'W'] writes=['y']
```

| row | is |
|---|---|
| `for<n>  i=lo:hi` | a sequential loop; `if<n>` a branch, its arms `when <cond>` / `else` |
| `state<n>` | a dataflow graph; leaving it is a barrier: everything in it finishes before the next state starts |
| `doall<n>  [i=lo:hi]` | a parallel loop (a map); `: ` lines are its body as Python, or as C after `view_tree c=[label]`; rows under it are the states of its body |
| `lib_<family><n>  LIBNODE <Kind> [<implementation>]` | a library call (BLAS, FFT, reduce, copy, ...), a black-box doall |

Rows carry what they read and write (a state leaves out its own temporaries), and `doalls=<k>` on a closed state;
`get_work_depth` gives a row's work and depth on request. `expand` opens a state (its doalls as rows) or a doall
(its statements and body states); `collapse` closes any open row. Labels stay on their rows until a move consumes them.
The [skill page](plugin/tactics/skills/tactics/SKILL.md) has the full vocabulary and the moves.

## Install and test

From PyPI (DaCe extended comes as `dace-extended`, imported as `dace`):

```bash
pip install dace-tactics
```

From a checkout of https://github.com/spcl/tactics:

```bash
sudo bash scripts/setup_apt.sh                                          # compilers, libomp, BLAS, binutils (Ubuntu)
export "$(bash scripts/setup_hptt.sh "$HOME/hptt" | tail -1)"          # HPTT for tensor transposes; sets HPTT_ROOT
uv sync --extra bench --group dev                                       # the bench, dev tools and FP-Arena
pre-commit install                                                      # ruff check, ruff format, headers
pytest -m "not integration and not cloudsc and not gpu and not vendor"  # unit set, as CI runs it
pytest -m integration                                                   # compiles and runs; bench OpenMP env (CI)
pytest -m cloudsc                                                       # every phase on cloudsc_monolith vs the bench (CI)
```

HPCAgent-Bench (`hpcagent-bench`), DaCe extended (`dace-extended`), dace-relayout and FP-Arena come from PyPI, in a
checkout as in a pip install. `python scripts/bump_deps.py [bench-branch]` points a checkout at the tip of a bench
branch instead (the nightly bench-tip CI job does this). Tactics is a user plugin of the bench (`plugin/tactics`, through
`HPCAGENT_BENCH_USER_PLUGIN_DIRS`); the bench never imports it. The plugin, its packets, optimizers, judge route
(`/tactics/<tool>`), `TACTICS_*` settings and record file (`tactics.json`) are all named `tactics`. Tactics assumes Linux.
A pip install of the bench does not ship the KernelBench submodule, so an ML kernel (`conv2d_*`) has no PyTorch
reference and its outputs go unchecked (`correct: null`). Point `HPCAGENT_BENCH_ML_KERNELBENCH_DIR` at an
initialized KernelBench checkout to check them.
Keep `HPTT_ROOT` set when building: on the CPU, DaCe lowers a top-level tensor transpose (8 of the 23 `conv2d_*`
kernels have one) only to HPTT, and without it the build stops with `SilentPureLowering`.

## Layout

```text
tactics/
  session.py   the one API over all stages
  replay.py    replay a benchmark's reference-solution script next to the default, timed and oracle-checked
  records.py   the typed answers and their status enums
  stages/      canonicalize, moves, scopes, placement, kernel, variants, feedback, performance
  ir/          extraction, the Python oracle, the kernel DAG, structure trees
  build/       compile and link, compilers on PATH, FP flags, validate-and-time, fork isolation
  corpus/      HPCAgent-Bench kernels and the oracle bridge
plugin/tactics/  the HPCAgent-Bench plugin: tools, judge route, method prompt
reference_solutions/  one reference-solution script per benchmark, replayed by tactics/replay.py
```

More: [the structure tree, Tactics' IR](docs/ir.md), [Python oracle](docs/oracle.md), [kernel DAG](docs/depends.md),
[build and runtime linking](docs/build.md), [FP modes and cost models](docs/fp-and-vectorization.md). Contributors
follow [AGENTS.md](AGENTS.md).

## References

- Stage 1 builds on *The Canonical Parallel Form as a Substrate for Parallelizing Compilers and Agentic
  Optimizers*, which defines CPF.
- The benchmark kernels and references come from *HPCAgent-Bench*.
