Metadata-Version: 2.4
Name: plato-maps
Version: 0.1.0
Summary: Clean, minimal closed-form Plato's Key maps for cross-model LLM representation transfer.
Author: Brendan Chatt
License-Expression: MIT
Project-URL: Homepage, https://github.com/brendanchatt/plato-maps
Project-URL: Repository, https://github.com/brendanchatt/plato-maps
Project-URL: Issues, https://github.com/brendanchatt/plato-maps/issues
Project-URL: Reference, https://hazyresearch.stanford.edu/blog/2026-11-25-platos-key
Keywords: platos-key,procrustes,representation-alignment,llm,interpretability,safetensors
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: safetensors>=0.4
Requires-Dist: torch>=2.1
Provides-Extra: transformers
Requires-Dist: transformers>=4.40; extra == "transformers"
Requires-Dist: huggingface_hub>=0.23; extra == "transformers"
Provides-Extra: hub
Requires-Dist: huggingface_hub>=0.23; extra == "hub"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Dynamic: license-file

# plato-maps

**Minimal, closed-form Plato's Key maps for cross-model LLM representation transfer — as easy to use and share as LoRAs.**

> **Note:** `plato-maps` is an independent, unofficial open-source implementation inspired by Hazy Research's blog post [**Plato's Key**](https://hazyresearch.stanford.edu/blog/2026-11-25-platos-key) (Vivien Cheng, Jerry Liu, Morris Yau, and Chris Ré, Nov 2026).

No training loops. No gradients. Just an orthogonal (or semi-orthogonal) Procrustes rotation and a single global scale factor stored in `.safetensors` with full provenance metadata.

---

## One-liner usage

```python
from plato_maps import Map

# Load a precomputed map from Hugging Face Hub and translate a donor key:
z_b = Map.from_hub("your-org/plato-map-qwen-to-llama")(z_a)
```

Or fit and apply in one line from paired hidden states:

```python
z_b = Map.fit(keys_a, keys_b)(z_a)
```

---

## Installation

Core library (minimal dependencies: `torch`, `safetensors`, `numpy`):

```bash
pip install plato-maps
```

With Hugging Face Transformers support (for `extract_keys` and the demo):

```bash
pip install "plato-maps[transformers]"
```

---

## Load a precomputed map

Maps are saved as standard `.safetensors` files with human-readable header metadata (`source_model`, `target_model`, `source_layer`, `target_layer`, `in_dim`, `out_dim`, `scale`, `r2`, `cosine_similarity`, etc.):

```python
from plato_maps import Map

# From Hugging Face Hub (auto-discovers map.safetensors or the unique .safetensors file)
key_map = Map.from_hub("your-org/plato-map-qwen2.5-to-llama3.1")
# Or specify a filename explicitly:
# key_map = Map.from_hub("your-org/plato-maps", filename="qwen7b_l14_to_llama8b_l16.safetensors")

# Or from a local file
key_map = Map.load("qwen_to_llama.safetensors")

print(key_map)
print(key_map.metadata)

# Translate any (..., in_dim) tensor or numpy array (no gradients)
z_recipient = key_map(z_donor)
```

---

## Fit your own map

Use `extract_keys` to pull paired hidden states from any two Hugging Face Transformers models, then fit in closed form via thin SVD:

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
from plato_maps import Map, extract_keys

prompts = [
    "The capital of Japan",
    "The capital of Italy",
    "The capital of Brazil",
    # ... ~100–1,000 diverse anchor prompts
]

donor_tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B")
donor = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B").eval()

recip_tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
recip = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B").eval()

keys_a = extract_keys(donor, donor_tok, prompts, layer=14, position="last")
keys_b = extract_keys(recip, recip_tok, prompts, layer=12, position="last")

key_map = Map.fit(
    keys_a,
    keys_b,
    source_model="Qwen/Qwen2.5-1.5B",
    target_model="Qwen/Qwen2.5-0.5B",
    source_layer=14,
    target_layer=12,
    extraction="hidden_states[layer], position=last",
)

key_map.save("qwen1.5b_to_qwen0.5b.safetensors")
```

---

## Chaining & PCA compression

### Chain maps across models (`A -> B -> C`)

Maps compose analytically in closed form without requiring paired data between `A` and `C`:

```python
map_ab = Map.load("a_to_b.safetensors")
map_bc = Map.load("b_to_c.safetensors")

map_ac = map_ab.compose(map_bc)  # Exact: map_ac(z) == map_bc(map_ab(z))
```

### Low-rank / PCA compression

Shrink map size and apply latency by compressing to rank `k` (`R_k = U @ Vh`, stored as compact `(d_b, k)` and `(k, d_a)` factors in `.safetensors`):

```python
# Option 1: Compress a fitted map to top-k cross-covariance components
small_map = key_map.compress(k=256)
small_map.save("qwen_to_llama_r256.safetensors")

# Option 2: Fit directly in k-dimensional per-model PCA subspaces
pca_map = Map.fit(keys_a, keys_b, pca_dim=256)
```

---

## Reproduce the Germany → Paris fact-swap demo

In the classic *Plato's Key* demonstration, prompting a recipient LLM with `"The capital of Germany is"` yields `"Berlin"`. Swapping in a rotated hidden state from a separate donor LLM at `"France"` flips the recipient's answer to `"Paris"`:

```python
import torch
from plato_maps import Map, extract_keys

# 1. Load a precomputed map (or fit one with Map.fit(keys_a, keys_b))
key_map = Map.load("qwen1.5b_to_qwen0.5b.safetensors")

# 2. Extract the donor's hidden state at "France" and translate it to the recipient's space
z_france = extract_keys(donor, donor_tok, ["The capital of France"], layer=14, position="last")[0]
z_swapped = key_map(z_france)

# 3. Inject z_swapped at the "Germany" token while running the recipient model
inputs = recip_tok("The capital of Germany is", return_tensors="pt").to(recip.device)
germany_idx = inputs["input_ids"][0].tolist().index(recip_tok.encode(" Germany", add_special_tokens=False)[-1])

def swap_hook(_module, _inp, output):
    h = output[0].clone() if isinstance(output, tuple) else output.clone()
    h[:, germany_idx, :] = z_swapped.to(device=h.device, dtype=h.dtype)
    return (h, *output[1:]) if isinstance(output, tuple) else h

handle = recip.model.layers[12 - 1].register_forward_hook(swap_hook)
try:
    with torch.no_grad():
        next_token = recip_tok.decode([recip(**inputs).logits[0, -1].argmax().item()])
finally:
    handle.remove()

print(next_token)  # -> " Paris"
```

Or run the full self-contained script in [`examples/germany_paris_demo.py`](examples/germany_paris_demo.py):

```bash
python examples/germany_paris_demo.py \
    --donor Qwen/Qwen2.5-1.5B \
    --recipient Qwen/Qwen2.5-0.5B \
    --save-map qwen1.5b_to_qwen0.5b.safetensors
```

To reuse an already-computed map without re-running calibration:

```bash
python examples/germany_paris_demo.py \
    --donor Qwen/Qwen2.5-1.5B \
    --recipient Qwen/Qwen2.5-0.5B \
    --map qwen1.5b_to_qwen0.5b.safetensors
```

---

## Mathematical formulation

Given paired donor keys $Z_A \in \mathbb{R}^{N \times d_A}$ and recipient keys $Z_B \in \mathbb{R}^{N \times d_B}$:

1. **Center by means:**
   $$\tilde{Z}_A = Z_A - \mu_A, \qquad \tilde{Z}_B = Z_B - \mu_B$$
2. **Orthogonal / semi-orthogonal Procrustes rotation** via thin SVD of $\tilde{Z}_B^\top \tilde{Z}_A = U \Sigma V^\top$:
   $$R = U V^\top \in \mathbb{R}^{d_B \times d_A}$$
   ($R^\top R = I_{d_A}$ when $d_B \ge d_A$; $R R^\top = I_{d_B}$ when $d_B \le d_A$.)
3. **Global Frobenius scale:**
   $$s = \frac{\|\tilde{Z}_B\|_F}{\|R \tilde{Z}_A^\top\|_F}$$
4. **Inference (zero gradients):**
   $$\hat{z}_B = \mu_B + s \, R (z_A - \mu_A)$$

---

## Reference

- Hazy Research — [**Plato's Key**](https://hazyresearch.stanford.edu/blog/2026-11-25-platos-key) (Vivien Cheng, Jerry Liu, Morris Yau, Chris Ré, Stanford University, November 25, 2026).

---

## License

MIT License — see [LICENSE](LICENSE).
