# Cross-model transfer and dark folding

> Audit attention sinks, align trajectories with auto-whitened Procrustes and CausalInterface bridges, imprint capabilities in null-space, and fold rank-1 gates with zero hooks.

Source: https://kucinglabs.com/docs/cross-model-transfer
Markdown: https://kucinglabs.com/docs/cross-model-transfer.md

## Geometry preflight, trajectory Procrustes, and CausalInterface

Activations from two models can score high on CKA while sitting in incompatible coordinate systems, or suffer from attention sinks where a few coordinates dominate activation norm and collapse effective rank near 1. That spike distorts orthogonal Procrustes alignment until you whiten the covariance. Run `audit_geometric_cleanliness` first to compute effective rank (participation ratio), flag sink collapse below 2.0, check superposition interference, and compare CKA against raw Euclidean MSE.

After preflight, align layers with `fit_procrustes_map` or `fit_trajectory_maps`, which adds spectral whitening on layers with sink collapse, and check multi-model consistency with `check_n_model_cycle_consistency`. A `CausalInterface` (exported under the alias `CausalABI`) is an invertible map between a recipient model hidden space and a shared canonical space so capabilities from multiple donors compose without pairwise alignments; build one with `fit_causal_interface` and combine modules with `compose_via_causal_interface`.

**Sink preflight, auto-whitened trajectory alignment, and CausalInterface composition**

```python
import numpy as np
import arah
from arah.xfer import (
    CausalCapabilityModule,
    apply_procrustes_map,
    audit_geometric_cleanliness,
    check_n_model_cycle_consistency,
    compose_via_causal_interface,
    fit_trajectory_maps,
)

rng = np.random.default_rng(0)
d, n = 8, 64
q_orth, _ = np.linalg.qr(rng.normal(size=(d, d)))

# Attention-sink needle triggers automatic spectral whitening during trajectory alignment
donor_l0 = rng.normal(scale=0.3, size=(n, d))
donor_l0[:, 0] *= 40.0
donor_l1 = rng.normal(size=(n, d))
recip_l0, recip_l1 = donor_l0 @ q_orth, donor_l1 @ q_orth

geo = audit_geometric_cleanliness(donor_l0, recip_l0, sink_pr_threshold=2.0)
traj = fit_trajectory_maps([donor_l0, donor_l1], [recip_l0, recip_l1], auto_whiten_on_sink=True)
cycle = check_n_model_cycle_consistency({"m_a": np.eye(d), "m_b": q_orth, "m_c": q_orth.T})
assert geo.sink_collapse_detected and traj.entries[0].auto_whitened and traj.mean_fit_r2 > 0.99
assert cycle.max_cycle_defect < 1e-10

# Fit reusable CausalInterface and compose two orthogonal capabilities
canon = rng.normal(size=(n, d))
recip = canon @ q_orth
readout_w = rng.normal(size=(d, 4))
iface = arah.fit_causal_interface(recip, canon, interface_id="demo-abi", recipient_readout=lambda h: h @ readout_w)

shift_a = np.array([1.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
shift_b = np.array([0.0, 0.0, 0.0, 0.0, -0.7, 0.9, 0.0, 0.0])
cap_a = CausalCapabilityModule("cap_a", d, lambda z: z + shift_a, donor_id="donor_a")
cap_b = CausalCapabilityModule("cap_b", d, lambda z: z + shift_b, donor_id="donor_b")
target_out = apply_procrustes_map(canon + shift_a + shift_b, iface.canonical_to_recipient) @ readout_w

comp = compose_via_causal_interface(
    iface, recip, [cap_a, cap_b], recipient_readout=lambda h: h @ readout_w, target_outputs=target_out
)
assert iface.roundtrip_r2 > 0.999 and comp.composition_beats_all_singles is True
```

## Null-space imprinting, strict-absence verification, and RMSNorm rotation

`imprint_trajectory_into_layers` writes aligned donor behavior into recipient layers one layer at a time. Woodbury null-space projection keeps background anchor outputs intact while recording remaining null-space capacity. Null-space imprinting functions expect column-vector matrices shaped `(d_in, n_samples)`, so transpose standard PyTorch `(batch, d_in)` tensors before calling.

Pair imprints with `preservation_plasticity_curve`, `run_shuffled_imprint_control`, and post-freeze checks (`generate_post_freeze_facts`, `verify_strict_absence_transfer`) that test facts invented after training cutoff with the donor unplugged to rule out memorization. For multi-donor edits, `imprint_multi_donor_joint_null_space` protects earlier donors alongside background anchors. Because RMSNorm depends only on vector L2 norm, orthogonal matrices preserve its output; `rotate_residual_block` applies exact orthogonal gauge rotations across RMSNorm blocks and rejects non-orthogonal matrices.

**Sequential and multi-donor null-space imprinting and exact RMSNorm rotation**

```python
import numpy as np
import torch
import arah
from arah.xfer import (
    DonorImprintSpec,
    imprint_multi_donor_joint_null_space,
    preservation_plasticity_curve,
)

rng = np.random.default_rng(1)
d_in, d_out = 12, 8
k_bg = np.vstack([np.eye(6), np.zeros((6, 6))])
k_edit = np.zeros((d_in, 4))
k_edit[6:10, :] = np.eye(4)
r_target = rng.normal(size=(d_out, 4))

imprint = arah.imprint_trajectory_into_layers(
    [torch.zeros(d_out, d_in, dtype=torch.float64)],
    lambda idx, cur: (k_edit, cur[idx].numpy() @ k_edit),
    [r_target],
    [k_bg],
    auto_loo=False,
    lam=1e-4,
    multi_phrasing_average=False,
)
assert imprint.total_preserve_drift_fro < 1e-10 and imprint.min_remaining_null_dim >= 2

# Preservation-plasticity curve across regularization strengths
curve = preservation_plasticity_curve(k_edit + 0.5 * k_bg[:, :4], r_target, k_bg, lam_values=(1e-4, 1.0, 1e3))
assert curve.points[0].new_fact_error < curve.points[-1].new_fact_error

# Multi-donor joint-null-space imprinting (donor 2 preserves donor 1 and background)
k_d1 = np.zeros((d_in, 2)); k_d1[6:8, :] = np.eye(2)
k_d2 = np.zeros((d_in, 2)); k_d2[8:10, :] = np.eye(2)
multi = imprint_multi_donor_joint_null_space(
    torch.zeros(d_out, d_in, dtype=torch.float64),
    [DonorImprintSpec("donor_a", k_d1, rng.normal(size=(d_out, 2))), DonorImprintSpec("donor_b", k_d2, rng.normal(size=(d_out, 2)))],
    k_bg,
    lam=1e-5,
)
assert not multi.conflict_detected and multi.max_earlier_donor_forgetting_fro < 1e-10

# Exact RMSNorm orthogonal gauge rotation: (W_in, W_out) -> (W_in Q^T, Q W_out)
q_orth, _ = np.linalg.qr(rng.normal(size=(8, 8)))
rot = arah.rotate_residual_block(
    rng.normal(size=(16, 8)),
    rng.normal(size=(8, 16)),
    q_orth,
    rmsnorm_weight=rng.uniform(0.5, 1.5, size=(8,)),
    verify_probes=rng.normal(size=(10, 8)),
)
assert rot.probes_verified is True and (rot.max_probe_abs_error or 0.0) < 1e-10
```

## Readout diagnosis and zero-hook dark folding

A model can encode the right answer in its hidden states while failing at the output head. `diagnose_readout_vs_reasoning` compares output AUROC against native and transferred linear probe AUROC so you know whether to repair readout weights or upstream reasoning layers.

Dark folding bakes a steering direction into static layer weights `W` and bias `b`, eliminating runtime forward hooks and donor access at inference. If diagnosis flags a recoverable readout bottleneck, map a donor probe with `transfer_linear_probe`, align its sign if probe AUROC sits below 0.5, and fold the rank-1 update with `fold_self_gated_amplification` (passing `preserve_keys` to protect anchor behavior).

**Diagnose readout bottleneck, transfer probe, and fold rank-1 gate with zero hooks**

```python
import numpy as np
import arah
from arah.xfer import ReadoutVerdict, compute_auroc, transfer_linear_probe

rng = np.random.default_rng(2)
d, n = 8, 80
labels = np.array([0] * (n // 2) + [1] * (n // 2), dtype=np.int64)
u_true = np.eye(d)[0]
q_orth, _ = np.linalg.qr(rng.normal(size=(d, d)))

h_recip = rng.normal(scale=0.35, size=(n, d))
h_recip[:, 0] += np.where(labels == 1, 2.0, -2.0)
pmap = arah.fit_procrustes_map(h_recip @ q_orth.T, h_recip)
xfer_probe = transfer_linear_probe(q_orth @ u_true, pmap)
u_fold = xfer_probe.unit_direction_u
if compute_auroc(h_recip @ u_fold, labels) < 0.5:
    u_fold = -u_fold

# Raw output reads noise dim 1 (AUROC ~ 0.5) while latent probe along dim 0 exceeds 0.95
diag = arah.diagnose_readout_vs_reasoning(
    output_scores=h_recip[:, 1],
    native_probe_scores=h_recip @ u_true,
    labels=labels,
    transferred_probe_scores=h_recip @ u_fold,
)
assert diag.verdict is ReadoutVerdict.READOUT_FAILURE_RECOVERABLE

# Fold into W, b while preserving orthogonal anchor subspace (dims 2..7)
bg_keys = np.vstack([np.zeros((2, 6)), np.eye(6)])
folded = arah.fold_self_gated_amplification(
    np.diag([0.15, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),
    u_fold,
    bias=np.zeros(d),
    gamma=15.0,
    param_name="mlp.w_down.weight",
    preserve_keys=bg_keys,
    lam=1e-4,
)
assert not folded.requires_runtime_hooks and not folded.requires_donor_at_inference
assert (folded.preserve_drift_fro or 0.0) < 1e-9
```

| `ReadoutVerdict` | Meaning and next action |
| --- | --- |
| `ALREADY_SOLVED` | Output AUROC meets `solved_threshold`; skip readout edits |
| `READOUT_FAILURE_RECOVERABLE` | Hidden states carry the signal while output fails; fold with `fold_self_gated_amplification` |
| `NATIVE_ONLY_REPRESENTATION` | Native probe passes while cross-model transferred probe does not align |
| `REASONING_ABSENCE` | Both output and hidden probes lack signal; repair upstream layers or imprint knowledge |
