# Architecture and shootouts

> Build multimodal ArchSpec DAGs, apply typed structural operators, check attention-geometry barriers, route certified shortcuts, and run matched-capacity shootouts.

Source: https://kucinglabs.com/docs/architecture
Markdown: https://kucinglabs.com/docs/architecture.md

## Multimodal ArchSpec DAGs and PyTorch builder

Changing model topology discards inherited weights in standard search loops. `arah.arch.spec` describes models as immutable, content-addressed DAGs (`ArchSpec`, `ModalitySpec`, `BlockSpec`) that compile into runnable PyTorch `DAGModule` instances via `build_module`.

- Supported `MODALITY_KINDS`: `vision`, `proprioception`, `sequence`, `latent`, `memory`, and `generic`.
- Supported `OP_KINDS`: `linear`, `mlp`, `glu`, `rmsnorm`, `layernorm`, `mha`, `mla`, `ridge_skip`, `exact_branch`, `pocs_circuit`, `retrieval_memory`, `concat`, and `add`.
- Each `ArchSpec` computes canonical JSON (`canonical_json()`), exact parameter count (`total_params()`), topological order, and a hardware memory plan (`to_dag_schedule(target=...)`).

## Typed architecture transforms and exact weight morphing

Use `arah.arch.ops` to change a model structure while preserving inherited weights. Exact weight morphs convert standard FFN blocks into SwiGLU (`ffn_to_glu`) and compress multi-head attention into latent KV projections (`mha_to_mla`, `kq_svd_compress`).

DAG operators attach ridge skip connections (`add_ridge_skip`), gated exact branches (`attach_exact_branch`), retrieval-memory tracks (`attach_retrieval_memory_track`), and POCS (Projection Onto Convex Sets) constraint layers (`insert_pocs_circuit`) that enforce geometric bounds by alternating projections. Compare any proposed edit against a parameter-matched random edit generated by `matched_random_arch_op`.

**Multimodal ArchSpec, exact FFN-to-GLU morph, and MLA conversion**

```python
import numpy as np
import torch

import arah
from arah.arch import (
    BlockSpec,
    ModalitySpec,
    add_ridge_skip,
    build_module,
    ffn_to_glu,
    kq_svd_compress,
    mha_to_mla,
)

# 1. Multimodal vision + proprioception DAG
spec = arah.ArchSpec(
    name="robot_manipulator_v1",
    modalities=(
        ModalitySpec("vision", input_dim=8, kind="vision"),
        ModalitySpec("proprio", input_dim=4, kind="proprioception"),
    ),
    nodes=(
        BlockSpec("vis_enc", "linear", ("vision",), 8, 6),
        BlockSpec("prop_enc", "linear", ("proprio",), 4, 6),
        BlockSpec("fused", "concat", ("vis_enc", "prop_enc"), 12, 12),
        BlockSpec("trunk", "glu", ("fused",), 12, 8, {"hidden_dim": 12}),
        BlockSpec("pose_head", "linear", ("trunk",), 8, 9),
    ),
    output_node="pose_head",
)
spec_with_skip = add_ridge_skip(spec, "trunk", new_node_id="trunk_skip")
dag_model = build_module(spec_with_skip, seed=0)
out = dag_model({"vision": torch.randn(2, 8), "proprio": torch.randn(2, 4)})
assert out.shape == (2, 9) and spec_with_skip.total_params() > spec.total_params()

# 2. Exact zero-error FFN -> SwiGLU morph and MHA -> MLA / KQ compression
rng = np.random.default_rng(0)
glu = ffn_to_glu(
    rng.normal(scale=0.3, size=(12, 8)),
    rng.normal(scale=0.3, size=(8, 12)),
    b_in=rng.normal(scale=0.1, size=(12,)),
    b_out=rng.normal(scale=0.1, size=(8,)),
    activation="silu",
    probe_inputs=rng.normal(size=(16, 8)),
)
mla = mha_to_mla(rng.normal(size=(16, 32)), rng.normal(size=(16, 32)), latent_dim_dc=8)
kq = kq_svd_compress(rng.normal(size=(16, 32)), rng.normal(size=(16, 32)), rank=8)
assert glu.exact_equivalent and glu.max_abs_err < 1e-10
assert mla.kv_cache_compression_ratio > 1.0 and kq.rank == 8
```

## Attention-geometry barrier diagnostics

Some attention designs hit mathematical limits before you run a benchmark. `arah.arch.diagnostics` checks five exact finite-dimensional bounds so you catch rank collapse, low-rank recall walls, and truncation error early.

| Diagnostic | Failure mode and exact bound |
| --- | --- |
| `dobrushin_rank_collapse_diagnostic` | Deep attention converging all tokens toward one vector (Dobrushin contraction coefficient and layer half-life) |
| `linear_attention_rank_wall` | Minimum recall error when compressing N by N exact attention to rank r (Eckart-Young Frobenius and spectral floors) |
| `sliding_window_truncation_bound` | Output drift from dropping distant tokens (exact tail mass `eps`, total-variation identity `TV(p, q) == eps`, and output error ceiling) |
| `lse_lipschitz_check` | Softmax stability and overflow margins (log-sum-exp sandwich bounds, shift invariance, and 1-Lipschitz infinity-norm check) |
| `multihead_pruning_bound` | Error from pruning attention heads (triangle and Pythagorean bounds alongside actual error and orthogonality defect) |

## Matched-capacity shootouts, Pareto archives, and certified shortcuts

Architecture comparisons mislead when a candidate wins by adding extra parameters. `run_architecture_shootout` caps `max_param_ratio` and tests the candidate against both the baseline and a `matched_random_arch_op` control using GRAPA e-processes (anytime-valid sequential tests that allow early stopping without inflating false positives).

`ParetoArchive` keeps separate frontiers per framework-computed `EquivalenceClass` (`exact-bit`, `exact-value`, `approximate-training-free`, `fitted`, `trained-short`) so a trained model cannot evict an exact construction. `CertifiedShortcutRouter` routes inputs to a fast model when the top-1 vs top-2 logit margin exceeds `2 * delta` (guaranteeing identical argmax whenever fast and reference logits stay within `delta`), and falls back to the reference model otherwise. Its report sets `certifies="reference_agreement_only"` to record that this check verifies agreement with `ref`, separate from ground-truth accuracy.

**Better-BERT shootout, equivalence-partitioned ParetoArchive, and CertifiedShortcutRouter**

```python
import hashlib
import torch
from torch import nn

import arah
from arah.arch import (
    LifecycleCostBreakdown,
    ParetoCandidate,
    dobrushin_rank_collapse_diagnostic,
    evaluate_certified_shortcut,
    linear_attention_rank_wall,
    make_bert_encoder_spec,
    matched_random_arch_op,
    propose_better_bert_spec,
)

# 1. Matched-capacity architecture shootout against baseline and random control
bert = make_bert_encoder_spec(d_model=32, n_layers=2, n_heads=4, d_ff=64)
better = propose_better_bert_spec(bert, latent_dim_dc=16, use_glu=True, use_rmsnorm=True)
rand_ctrl = matched_random_arch_op(bert, seed=7, target_params=better.total_params())
cand_id = hashlib.sha256(better.canonical_json().encode()).hexdigest()

def eval_arch(spec: arah.ArchSpec) -> list[float]:
    d = hashlib.sha256(spec.canonical_json().encode()).hexdigest()
    return [0.85] * 40 if d == cand_id else [0.68] * 40

shootout = arah.run_architecture_shootout(
    bert, better, eval_arch, random_control_spec=rand_ctrl, max_param_ratio=1.15, score_low=0.0, score_high=1.0
)
assert shootout.verdict == "candidate_wins"
assert linear_attention_rank_wall(seq_len_n=16, feature_dim_r=4).frobenius_sq_floor == 12.0
assert dobrushin_rank_collapse_diagnostic(torch.full((8, 8), 0.125).numpy()).rank_collapse_risk

# 2. Equivalence-stratified ParetoArchive: trained-short cannot evict exact-bit
archive = arah.ParetoArchive()
cost = LifecycleCostBreakdown(1.0, 1.0, 1.0, 0.01, 100)
archive.add(ParetoCandidate("exact_v1", 0.80, 4.0, 4096, cost, "authored", exact_bit_verified=True))
archive.add(ParetoCandidate("trained_v1", 0.95, 1.0, 1024, cost, "trained-short"))
parts = archive.partitions()
assert [c.candidate_id for c in parts["exact-bit"]] == ["exact_v1"]

# 3. Margin-certified fast path with exact ParameterAccounting
ref = nn.Linear(4, 2, bias=False)
fast = nn.Linear(4, 2, bias=False)
with torch.no_grad():
    ref.weight.copy_(torch.tensor([[2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0]]))
    fast.weight.copy_(ref.weight + 0.01)
router = arah.CertifiedShortcutRouter(fast, ref, delta_output_bound=0.10, k=1)
xs = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.50, 0.49, 0.0, 0.0]])
report = evaluate_certified_shortcut(router, xs)
assert report.fast_path_count == 1 and report.fallback_count == 1
assert report.reference_agreement_rate == 1.0 and report.certifies == "reference_agreement_only"
```
