Skip to content

armgit / PS5LM

Public Imported from GitHub
0

llama.cpp on a jailbroken PS5: run any GGUF model natively on the console, starting with Qwen 3.8

Introspection: an endpoint for raw logits and layer activations, off by default (#28)

Bilawal Riaz6af22453ef97
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 672c112..d63159a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,22 @@ Versions follow [semver](https://semver.org). The app's version is set in
`v<version>` and ships `ps5lm-app-v<version>.zip` (see `scripts/release-app.sh`).
v0.1.x are the upstream payload releases by cobanov.
+## [Unreleased]
+
+### Added
+- **An opt-in endpoint for the model's own numbers**: `POST /v1/introspect` answers with the whole
+ logit row at the positions you name, the top candidates with their probabilities, the entropy, and
+ one row of a named graph tensor (`l_out`, `ffn_swiglu`, `ffn_out`, `attn_out`, `attn_norm`, `ffn_norm`,
+ `result_norm`, `result_output`) for a named layer. A request can also change one channel in place,
+ with zero, scale or add, at one position or at all of them. `messages` applies the chat template
+ first. It is off by default: Settings > Developer > "Logits and activations API" (a change
+ restarts the app with the loaded model), or `LLAMA_INTROSPECT=1`. `docs/INTROSPECTION.md` is the
+ reference, `scripts/ps5lm-introspect.py` is a client, and `examples/interpret/neuron_ablation.py`
+ zeroes the FFN neurons (`ffn_swiglu`) of one layer one at a time.
+- The patch reads the logits from the context's own output buffer and copies the tensors out of the
+ compute graph with the eval callback that llama.cpp already has, so no work is repeated and no
+ request pays for it unless it asks.
+
## [0.9.1] - 2026-10-20
### Fixed
diff --git a/README.md b/README.md
index dda0a96..820cfbc 100644
--- a/README.md
+++ b/README.md
@@ -127,6 +127,25 @@ opened the console's storage to it. On OnionHEN, add `PPSA99575` to `exact_title
| Settings | D-pad, Cross | choose a category and a row; flip it, or pick from its list |
| Settings, Diagnostics | Square, Triangle | app or server log; errors only |
+## Looking inside the model
+
+This fork adds an opt-in endpoint that returns the numbers the model computed.
+`POST /v1/introspect` answers with the whole logit row at the positions you name,
+the probabilities and the entropy, with one row of a named graph tensor for a
+named layer, and it can also change one channel in place before the rest of the
+model reads it.
+
+The endpoint is off by default. Turn it on in **Settings > Developer > Logits and
+activations API**.
+
+```sh
+python3 scripts/ps5lm-introspect.py --host <console> --prompt "Once upon a time" \
+ --positions last --top-k 10 --tensors l_out --layers 12
+```
+
+[Introspection](docs/INTROSPECTION.md) records the request fields, the tensor
+names, and the cost of each option.
+
## Want to tinker?
C++ on [ps5-homebrew-ui](https://github.com/blackbearreloaded/ps5-homebrew-ui), llama.cpp with
diff --git a/docs/INTROSPECTION.md b/docs/INTROSPECTION.md
new file mode 100644
index 0000000..0145ed6
--- /dev/null
+++ b/docs/INTROSPECTION.md
@@ -0,0 +1,261 @@
+# Introspection: raw logits and layer activations
+
+PS5LM's server normally answers like any chat server: text in, text out. For
+interpretability work that is not enough — you want the distribution the model
+actually computed, and the numbers inside the transformer while it ran.
+
+This fork adds one endpoint that returns both, for the positions and layers you
+name:
+
+```
+POST /v1/introspect
+```
+
+It is the same request as `/completion` (same tokenizer, same sampler, same
+context, same model) plus an `introspect` field that says what to capture. The
+answer is the normal completion object with an extra `introspection` member.
+The field also works on `/completion` itself, so an existing client only has to
+add one key.
+
+Implementation: `patches/0009-introspection-logits-and-activations.patch` over
+llama.cpp `04f7226`. Logits come from the context's own output buffer
+(`llama_get_logits_ith`), so no work is repeated; activations are copied out of
+the compute graph while it runs, through the graph-eval callback llama.cpp
+already exposes (`llama_context_params.cb_eval`). Nothing is captured unless a
+request asks, and nothing is recomputed.
+
+## Quick start
+
+```sh
+# the console must be running a model; then, from a computer on the same network
+python3 scripts/ps5lm-introspect.py --host <console-ip> \
+ --prompt "Once upon a time" --positions last --top-k 10 \
+ --tensors l_out --layers 12
+```
+
+```sh
+curl -s http://<console-ip>:8081/v1/introspect -H 'Content-Type: application/json' -d '{
+ "prompt": "Once upon a time",
+ "n_predict": 0,
+ "introspect": {
+ "logits": {"top_k": 10, "entropy": true},
+ "positions": "last",
+ "activations": {"tensors": ["l_out"], "layers": [12]}
+ }
+}'
+```
+
+## The request
+
+| Field | Meaning |
+|---|---|
+| `prompt` | Text, exactly as `/completion` takes it |
+| `messages` | Chat turns (`[{role, content}]`); the model's own chat template is applied first, so the probed prompt is the prompt the model would really be asked |
+| `n_predict` | Tokens to generate. `0` captures the prompt only (default) |
+| `temperature`, `top_k`, … | The usual sampling fields; `0` is greedy |
+| `introspect.logits` | `true`, or an object: `top_k` (candidates per position), `entropy`, `probs`, `full` (the whole vocabulary row), `max_full_rows` (cap, default 8) |
+| `introspect.positions` | `"last"` (the final prompt token, default), `"all"` (every prompt position), or a list of indices |
+| `introspect.activations.tensors` | Tensor names to capture; `l_out` alone is a typical choice |
+| `introspect.activations.layers` | `"all"` or a list of layer indices |
+| `introspect.generated` | Also capture the generated tokens (default `true`) |
+
+## The answer
+
+```json
+{
+ "content": ", there was a",
+ "introspection": {
+ "meta": {"model": "…", "n_layer": 42, "n_vocab": 130560, "n_ctx": 65536, "n_prompt": 5, "request": {…}},
+ "inputs": [{"index": 0, "id": 1, "piece": "<s>"}, …],
+ "positions": [
+ {
+ "index": 4, "id": 261, "piece": " time", "generated": false,
+ "logits": {
+ "n_vocab": 130560,
+ "argmax": {"id": 11, "piece": ",", "logit": 17.79, "prob": 0.99},
+ "top": [{"id": 11, "piece": ",", "logit": 17.79, "prob": 0.99}, …],
+ "entropy": 0.157,
+ "full": {"encoding": "base64", "dtype": "f32", "n_vocab": 130560, "data": "…"}
+ },
+ "activations": {
+ "l_out-12": {"shape": [2048, 1, 1, 1], "dtype": "f32", "encoding": "base64", "data": "…"}
+ }
+ }
+ ],
+ "truncated": false
+ }
+}
+```
+
+- `index` is the position in `inputs`; generated tokens continue after the
+ prompt, with `"generated": true` and `"step"` counting from 0. The final
+ generated token has no entry: no logits are computed for it.
+- `full.data` is `n_vocab` little-endian float32s, base64-encoded; `activations
+ .data` is one row of the tensor, i.e. that token's activations.
+- `truncated` says the activation budget cut tensors out of some positions.
+
+## Which activations
+
+Tensors are named by llama.cpp's graph; `-<layer>` is appended for per-layer
+ones. For the `llama` architecture (which is what MiniCPM5-2B, Qwen, Mistral,
+LFM2 and most GGUFs declare):
+
+| Tensor | What it is |
+|---|---|
+| `embd` | The token embedding row of each position (positions enter later, inside attention's RoPE) |
+| `attn_norm-<il>` | Residual stream after the block's input norm |
+| `kqv_out-<il>` | The fused Q/K/V projection output |
+| `attn_out-<il>` | Attention output, before the residual add |
+| `ffn_norm-<il>` | Residual stream after the post-attention norm |
+| `ffn_gate-<il>` | MLP gate pre-activation — one channel is one FFN neuron before SwiGLU |
+| `ffn_swiglu-<il>` | The gate x up activation, i.e. what the neuron actually emits |
+| `ffn_out-<il>` | MLP output, before the residual add (down-projection result) |
+| `l_out-<il>` | Residual stream after block `il`; `l_out-<il-1>` is the input of block `il` |
+| `result_norm` | Final hidden state, before the output projection |
+| `result_output` | The logits tensor of the graph itself |
+
+These are the names a `llama`-architecture GGUF (which is what MiniCPM5, Qwen,
+Mistral, LFM2 and most of the catalogue declare) delivers on both backends; the
+list is measured, not guessed, so a name outside it is not delivered rather than
+mis-addressed. Two that look like they should work do not in this revision:
+`inp_embd` (the graph names that node, but the scheduler never offers it to the
+callback here — use `embd`) and `inp_pos` (positions; the answer's `inputs` carry
+the token ids and pieces instead). Other architectures name their tensors in
+`src/models/<arch>.cpp` and may deliver different sets (`ffn_moe_*` for MoE
+models, for instance).
+
+A name that is not delivered simply does not appear in the answer; the request
+still succeeds. `docs/INSPECT.md`'s tool has its own capture path and lists its
+own names.
+
+Other architectures name their tensors in `src/models/<arch>.cpp`; a name that
+does not exist is simply not captured, and the answer then has no activations
+for it.
+
+One upstream detail the endpoint hides for you: llama.cpp computes the *last*
+layer's output, and `result_norm`/`result_output`, only for the rows that asked
+for logits, so those tensors do not exist for earlier rows of a normally batched
+prompt. A request that names positions (or intervenes at one) therefore marks
+every prompt row as an output row and renders one token at a time, which is what
+makes a per-position capture of those tensors possible at all.
+
+## Costs and limits
+
+- **`positions: "all"` evaluates the prompt one token at a time** so that every
+ position is the newest row of its own graph. A 1000-token prompt therefore
+ costs about 1000 decode steps (on the console, that is tens of seconds, not
+ milliseconds). `"last"` keeps the normal batched prefill.
+- **`entropy`/`probs` walk the whole vocabulary** for every captured position
+ (an exp over `n_vocab` values). Leave them off when capturing thousands of
+ positions.
+- **`full` rows are ~4 bytes × `n_vocab` each** (≈ 500 KB per position for a
+ 130k vocabulary) and are capped by `max_full_rows`.
+- **Activations are 4 bytes × `n_embd` per tensor per position** (8 KB for a
+ 2048-wide model). The response is base64, so a request for every layer and
+ every tensor over a long prompt can be very large; the server stops adding
+ them after `LLAMA_INTROSPECT_MAX_BYTES` (default 256 MiB) and sets
+ `"truncated": true`.
+- The request occupies the server's slot like any generation, and
+ `positions: "all"` or any intervention disables prompt caching for that request.
+
+## Interventions: change an activation, not just read it
+
+The same request can modify a tensor in place while the model runs — zero, scale
+or add a value to one channel (a single FFN neuron, one attention-head
+dimension) or a range of channels, at every position or at one position. That
+turns "this neuron is active when it says X" into "and with it zeroed, does it
+stop saying X?".
+
+```json
+{
+ "prompt": "Once upon a time",
+ "n_predict": 0,
+ "introspect": {
+ "logits": {"top_k": 10, "probs": true},
+ "positions": "last",
+ "interventions": [
+ {"tensor": "ffn_swiglu", "layers": [12], "channels": [3456], "op": "zero"}
+ ]
+ }
+}
+```
+
+| Field | Meaning |
+|---|---|
+| `tensor` | Base name (`ffn_swiglu`) or an exact node name (`ffn_swiglu-12`). One channel of `ffn_swiglu` is one FFN neuron; one channel of `ffn_out` is one of the `n_embd` residual features that the down projection writes |
+| `layers` | Which layers a base name expands to (default: all) |
+| `channels` | Channel indices to change; or `channel_start`/`channel_end` (end exclusive); neither means the whole row |
+| `position` | The token's sequence position, its `index` in `inputs` (generated tokens continue after the prompt); default `-1` = every position |
+| `op` | `zero`, `scale` (multiply by `value`) or `add` (`value`) |
+| `value` | Operand of `scale`/`add` |
+
+The answer repeats each intervention with `"modified"`, the number of elements
+actually changed — 0 means the name never matched a tensor in this graph, so
+check it rather than assuming the intervention happened.
+
+Notes that matter:
+
+- The change is applied inside the graph-eval callback, i.e. after llama.cpp has
+ finished computing that tensor and before anything consumes it, so it affects
+ exactly the forward pass that follows.
+- Any intervention evaluates the whole prompt in its own request: a prefix taken
+ from the prompt cache never runs the graph, so the intervention would reach
+ only the uncached rest. A baseline and an ablation of the same prompt therefore
+ see the same positions, and their `modified` counts compare.
+- A `position` intervention also evaluates the prompt one token at a time, and
+ *any* intervention that changed something makes the server drop the prompt
+ cache afterwards: the KV entries of an intervened pass are not the ones a later
+ request should reuse.
+- Interventions need the tensor to be `float32`/`float16`/`bfloat16` and at most
+ 64 MiB; anything else is left alone.
+- Compare against a baseline by sending the same request twice, once without
+ `interventions`.
+
+## Switches
+
+Set in `/data/PS5LM/env.txt` (one `NAME=value` per line; the app applies
+`LLAMA_*` names before the server starts). In the app, **Settings > Developer >
+Logits and activations API** is the switch:
+
+| Name | Default | Meaning |
+|---|---|---|
+| `LLAMA_INTROSPECT` | off | Set it to `1` to enable the endpoint. In the app, the Settings row "Logits and activations API" sets it and wins over `env.txt`; changing the row restarts the app with the loaded model, because the server reads the variable only when it starts |
+| `LLAMA_INTROSPECT_MAX_BYTES` | `268435456` | Cap on the activations one request may return |
+
+With the endpoint off, `/v1/introspect` answers 501 and every other request works as before.
+
+## What this does not give you
+
+- **A separate context per request.** This endpoint runs in the app's server, so it shares the
+ app's loaded model, its slot and its KV cache. The standalone
+ [`llama-inspect`](INSPECT.md) tool is the opposite trade: its own process, its own context, one
+ request at a time (so a capture is the whole batch, and `baseline: true` runs a prompt both ways in
+ one call) — CPU only, and a payload's memory limit.
+- **Weights.** They are in the GGUF file: read it directly from the host
+ (`gguf-py`, `gguf_dump.py`) or over FTP; the console does not need to serve
+ them.
+- **Attention matrices / per-head scores.** llama.cpp does not keep them; the
+ graph tensors above are what it computes.
+- **Embeddings for retrieval.** That is upstream's `/v1/embeddings` (start the
+ server with `--embeddings`), unchanged by this fork.
+- **Gradients.** llama.cpp is forward-only.
+
+## Status
+
+- [LOCALLY BUILT] The patch builds and is exercised on the host (macOS, CPU
+ backend) with a small test model: logits, full rows, entropy, all-positions
+ capture, the chat-template path, the budget, the disabled mode and
+ interventions were all run.
+- [LOCALLY BUILT] `argmax.prob` is the argmax's real probability: it was
+ hardcoded to 1.0 before this fix, which the console run exposed (the entropy
+ and the top-k probabilities were right all along, so the mismatch was visible
+ as an entropy of 1.176 nats next to `p=1.0000`). Verified against `softmax()`
+ of the full vocabulary row, to 1e-9.
+- [TESTED-ON-CONSOLE] Run on a 13.60 PS5 with MiniCPM5-2B Q8_0 on the GPU
+ (ggml-vulkan on RADV), release v0.10.0: logits, a full row of exactly
+ `n_vocab` floats, 13 activation tensors for four layers, every prompt
+ position, the chat-template path, and one intervention that changed 20,480
+ elements and moved the argmax with a top-10 KL of 0.915 nats. The same
+ token's nine tensors are byte-identical between batched and step-by-step
+ capture, which is what validates the graph-eval capture on the GPU backend.
+ Numbers: `docs/CONSOLE.md` (What the check returned).
diff --git a/examples/interpret/neuron_ablation.py b/examples/interpret/neuron_ablation.py
new file mode 100755
index 0000000..96fc52d
--- /dev/null
+++ b/examples/interpret/neuron_ablation.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3
+"""Which neuron in a layer moves the answer? Ask the running PS5LM.
+
+ python3 examples/interpret/neuron_ablation.py --host <console> \
+ --prompt "The capital of France is" --layer 20
+
+The loop this closes is the whole point of the endpoint:
+
+1. ask for the model's **logits** at the last prompt position, with the whole
+ vocabulary row, and the **ffn_swiglu** activation of one layer at that position:
+ gate x up, one channel per FFN neuron, the input of the down projection;
+2. rank that layer's neurons by how strongly they fire (the ones that are doing
+ something for this token);
+3. for each candidate, send the same request again with that one channel **zeroed**
+ in place, and measure what changed: the target token's probability, its rank,
+ and the exact KL divergence of the next-token distribution over the whole
+ vocabulary.
+
+Everything except the ranking comes from one request per candidate. A layer whose
+ablation barely moves anything is a layer that is not carrying this decision; the
+channels at the top of the last column are the ones worth looking at next.
+
+`--tensor ffn_out` asks a different question: its channels are the `n_embd`-wide
+residual features that the down projection writes, not neurons.
+
+The full vocabulary row is on by default because the KL is then exact (over all
+`n_vocab` values); pass `--top-only` to trade that for a tenth of the traffic.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import math
+import sys
+import time
+import urllib.error
+import urllib.request
+
+
+def post(host: str, path: str, body: dict, timeout: float = 300.0) -> dict:
+ data = json.dumps(body).encode()
+ req = urllib.request.Request(f"http://{host}:8081{path}", data=data, headers={"Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return json.loads(resp.read())
+ except urllib.error.HTTPError as e:
+ raise SystemExit(f"{e.code} from the console: {e.read().decode('utf-8', 'replace')[:800]}")
+
+
+def floats(b64: str):
+ import array
+
+ a = array.array("f")
+ a.frombytes(base64.b64decode(b64))
+ return a
+
+
+def softmax(row):
+ m = max(row)
+ exps = [math.exp(v - m) for v in row]
+ s = sum(exps)
+ return [e / s for e in exps]
+
+
+def request(host: str, args, interventions=None, want_activation=True):
+ spec: dict = {
+ "logits": {"top_k": args.top_k, "probs": True, "full": not args.top_only, "max_full_rows": 1},
+ "positions": "last",
+ "generated": False,
+ "capture_generated": False,
+ }
+ if want_activation:
+ spec["activations"] = {"tensors": [args.tensor], "layers": [args.layer]}
+ if interventions:
+ spec["interventions"] = interventions
+ body = {"prompt": args.prompt, "n_predict": 0, "temperature": 0.0, "introspect": spec}
+ t0 = time.time()
+ doc = post(host, "/v1/introspect", body)
+ return doc, time.time() - t0
+
+
+def intro(doc):
+ it = doc.get("introspection")
+ if not it:
+ raise SystemExit("no introspection in the answer: " + json.dumps(doc)[:400])
+ entry = it["positions"][-1]
+ return it, entry
+
+
+def main() -> int:
+ p = argparse.ArgumentParser()
+ p.add_argument("--host", required=True)
+ p.add_argument("--prompt", default="The capital of France is")
+ p.add_argument("--layer", type=int, default=20)
+ p.add_argument("--tensor", default="ffn_swiglu",
+ help="ffn_swiglu (one FFN neuron per channel), or ffn_out, l_out, attn_out (n_embd residual features)")
+ p.add_argument("--top", type=int, default=12, help="how many channels to rank and ablate")
+ p.add_argument("--top-k", type=int, default=20, help="candidates printed from the answer")
+ p.add_argument("--target", help="token piece to track (default: the baseline argmax)")
+ p.add_argument("--top-only", action="store_true", help="skip the full vocabulary row (approximate KL)")
+ args = p.parse_args()
+
+ print(f"{args.prompt!r} -> layer {args.layer}, tensor {args.tensor}")
+ t0 = time.time()
+ doc, dt = request(args.host, args)
+ it, entry = intro(doc)
+ acts = entry.get("activations") or {}
+ key = [k for k in acts if k.startswith(args.tensor)]
+ if not key:
+ raise SystemExit(f"the answer carried no {args.tensor}-<layer>: {sorted(acts)}")
+ key = key[0]
+ row = floats(acts[key]["data"])
+ logits = entry["logits"]
+ n_vocab = logits["n_vocab"]
+
+ # the target is tracked by its token id: a piece is found only while it is among
+ # the printed candidates, and an ablation can push it out of them
+ candidates = [logits["argmax"]] + (logits.get("top") or [])
+ if args.target is None:
+ target_id, target = logits["argmax"]["id"], logits["argmax"]["piece"]
+ else:
+ found = [t for t in candidates if t["piece"] == args.target]
+ if not found:
+ raise SystemExit(f"{args.target!r} is not among the baseline's top {args.top_k} candidates; raise --top-k")
+ target_id, target = found[0]["id"], args.target
+
+ print(f" {it['meta']['n_layer']} layers, vocab {n_vocab}, prompt {it['meta']['n_prompt']} tokens; answer in {dt:.2f} s")
+ print(f" next token: {logits['argmax']['piece']!r} (id {logits['argmax']['id']}, logit {logits['argmax']['logit']:.2f}, "
+ f"p {logits['argmax'].get('prob', float('nan')):.4f}), entropy {logits.get('entropy', float('nan')):.3f} nats")
+ print(f" {key}: {len(row)} channels, mean {sum(row)/len(row):.3f}, "
+ f"largest |activation| {max(abs(v) for v in row):.3f}")
+
+ def score(doc_logits):
+ """The target's logit, probability and rank. Exact from the full row; from the
+ printed candidates otherwise, and None there once the target drops out of them."""
+ if "full" in doc_logits:
+ row_i = floats(doc_logits["full"]["data"])
+ probs = softmax(row_i)
+ x = row_i[target_id]
+ return x, probs[target_id], sum(1 for v in row_i if v > x) + 1, probs
+ for t in [doc_logits["argmax"]] + (doc_logits.get("top") or []):
+ if t["id"] == target_id:
+ return t["logit"], t.get("prob"), None, None
+ return None, None, None, None
+
+ base_logit, base_p, base_rank, base_probs = score(logits)
+ print(f" tracking {target!r} (id {target_id}): baseline p={base_p:.6f}" + (f", rank {base_rank}" if base_rank else ""))
+
+ def num(v, spec):
+ return format(v, spec) if v is not None else format(float("nan"), spec)
+
+ # candidate neurons: the channels that fire hardest at this position
+ order = sorted(range(len(row)), key=lambda i: -abs(row[i]))[: args.top]
+ print(f"\n ablating the {len(order)} loudest channels one at a time (zeroing {args.tensor}-{args.layer} channel c):\n")
+ print(f" {'channel':>7} {'activation':>11} {'d logit':>8} {'p(target)':>12} {'rank':>7} {'KL(base||abl)':>13} argmax")
+ results = []
+ for c in order:
+ doc2, dt2 = request(args.host, args, interventions=[
+ {"tensor": args.tensor, "layers": [args.layer], "channels": [c], "op": "zero"},
+ ], want_activation=False)
+ it2, e2 = intro(doc2)
+ lg2 = e2["logits"]
+ mod = (it2.get("interventions") or [{}])[0].get("modified")
+ logit2, p2, rank2, probs2 = score(lg2)
+ dlogit = logit2 - base_logit if logit2 is not None else None
+ if base_probs is not None and probs2 is not None:
+ kl = sum(p * math.log(p / q) for p, q in zip(base_probs, probs2) if p > 0 and q > 0)
+ else:
+ kl = float("nan")
+ # a target that left the printed candidates moved more than any that stayed
+ effect = abs(dlogit) if dlogit is not None else math.inf
+ results.append((effect, c, row[c], dlogit, p2, rank2, kl, lg2["argmax"]["piece"], mod))
+ print(f" {c:>7} {row[c]:>11.4f} {num(dlogit, '>8.3f')} "
+ f"{num(p2, '>12.6f')} {rank2 if rank2 else '':>7} {kl:>13.5f} {lg2['argmax']['piece']!r}")
+
+ results.sort(key=lambda r: r[0], reverse=True)
+ if results:
+ _, c, a, dlogit, p2, rank2, kl, am, mod = results[0]
+ moved = f"logit {dlogit:+.3f}, p {p2:.6f}" if dlogit is not None else f"left the top {args.top_k}"
+ print(f"\n biggest single-neuron effect: {args.tensor}-{args.layer} channel {c} (activation {a:.3f}) "
+ f"-> {target!r} {moved}, argmax {am!r}, KL {kl:.5f} ({mod} elements changed)")
+ print(f" total {time.time() - t0:.1f} s for {1 + len(order)} requests")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/patches/0009-introspection-logits-and-activations.patch b/patches/0009-introspection-logits-and-activations.patch
new file mode 100644
index 0000000..6ffa8de
--- /dev/null
+++ b/patches/0009-introspection-logits-and-activations.patch
@@ -0,0 +1,1402 @@
+diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt
+index 70b8d7d..7da0f33 100644
+--- a/tools/server/CMakeLists.txt
++++ b/tools/server/CMakeLists.txt
+@@ -25,6 +25,8 @@ add_library(${TARGET} STATIC
+ server-mcp.h
+ server-schema.cpp
+ server-schema.h
++ server-introspect.cpp
++ server-introspect.h
+ )
+
+ if (BUILD_SHARED_LIBS)
+diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp
+index 60c5633..c785782 100644
+--- a/tools/server/server-context.cpp
++++ b/tools/server/server-context.cpp
+@@ -292,6 +292,13 @@ struct server_slot {
+
+ std::vector<completion_token_output> generated_token_probs;
+
++ // PS5LM fork: introspection results for the current task
++ server_introspect_result introspect;
++ int32_t introspect_n_full = 0;
++ int32_t introspect_n_gen = 0;
++ int64_t introspect_n_bytes = 0;
++ std::vector<int64_t> introspect_iv_modified;
++
+ bool has_next_token = true;
+ bool has_new_line = false;
+ bool truncated = false;
+@@ -397,6 +404,13 @@ struct server_slot {
+ generated_token_probs.clear();
+ json_schema = json();
+
++ // PS5LM fork: introspection state belongs to the task that just ended
++ introspect = {};
++ introspect_n_full = 0;
++ introspect_n_gen = 0;
++ introspect_n_bytes = 0;
++ introspect_iv_modified.clear();
++
+ task_prev = std::move(task);
+ task.reset();
+
+@@ -953,6 +967,9 @@ public:
+
+ server_decision_context decision;
+
++ // PS5LM fork: introspection (interpretability)
++ bool is_introspect_enabled() const { return introspect_enabled; }
++
+ server_queue queue_tasks;
+ server_response queue_results;
+
+@@ -1019,6 +1036,14 @@ private:
+ int slots_debug = 0; // env: LLAMA_SERVER_SLOTS_DEBUG
+ int slots_n_diff = 0; // env: LLAMA_SERVER_SLOTS_N_DIFF
+
++ // PS5LM fork: introspection (interpretability), env: LLAMA_INTROSPECT
++ // the capture engine is armed per request and consulted by the graph-eval
++ // callback; when nothing is armed it is a no-op on the decode path
++ bool introspect_enabled = false;
++ server_introspect_capture introspect_capture;
++ int32_t introspect_n_layer = 0;
++ int64_t introspect_max_bytes = 256ll << 20; // env: LLAMA_INTROSPECT_MAX_BYTES
++
+ int n_empty_consecutive = 0;
+
+ std::unique_ptr<server_prompt_cache> prompt_cache;
+@@ -1213,11 +1238,33 @@ private:
+ params_base.load_progress_callback_user_data = &load_progress_text;
+ }
+
++ // PS5LM fork: introspection (interpretability).
++ // Install the graph-eval callback that lets a request copy intermediate
++ // tensors out of the compute graph. It does nothing until a request arms
++ // it, so this does not change ordinary generation. The raw-logits half of
++ // the feature needs no callback at all: it reads the context's output
++ // buffer, which llama.cpp fills for every batch row that asks for it.
++ {
++ // Off unless asked for: LLAMA_INTROSPECT=1 in the environment, or
++ // the app's Developer setting, which sets it before the server starts.
++ const char * env = getenv("LLAMA_INTROSPECT");
++ introspect_enabled = env != nullptr && atoi(env) != 0;
++ const char * env_bytes = getenv("LLAMA_INTROSPECT_MAX_BYTES");
++ if (env_bytes != nullptr && atoll(env_bytes) > 0) {
++ introspect_max_bytes = atoll(env_bytes);
++ }
++ if (introspect_enabled) {
++ params_base.cb_eval = server_introspect_cb;
++ params_base.cb_eval_user_data = &introspect_capture;
++ }
++ SRV_INF("introspection: %s (activation budget %" PRId64 " MiB)\n", introspect_enabled ?
++ "enabled (POST /v1/introspect)" : "disabled (LLAMA_INTROSPECT=0)", introspect_max_bytes >> 20);
++ }
++
+ llama_init = common_init_from_params(params_base);
+
+ model_tgt = llama_init->model();
+ ctx_tgt = llama_init->context();
+-
+ if (model_tgt == nullptr) {
+ SRV_ERR("failed to load model, '%s'\n", params_base.model.path.c_str());
+ return false;
+@@ -1230,6 +1277,13 @@ private:
+
+ vocab = llama_model_get_vocab(model_tgt);
+
++ // PS5LM fork: number of layers, for building activation tensor names
++ introspect_n_layer = llama_model_n_layer(model_tgt);
++ if (introspect_enabled) {
++ SRV_INF("introspection: model has %d layers, vocab %d\n",
++ introspect_n_layer, llama_vocab_n_tokens(vocab));
++ }
++
+ try {
+ decision.init(model_tgt);
+ } catch (const std::exception & e) {
+@@ -2290,6 +2344,27 @@ private:
+
+ res->generation_params = slot.task->params; // copy the parameters
+
++ // PS5LM fork: the raw logits / activations this request asked for
++ if (!slot.task->params.introspect.interventions.empty()) {
++ json ivs = json::array();
++ int64_t total = 0;
++ for (size_t k = 0; k < slot.task->params.introspect.interventions.size(); ++k) {
++ const auto & iv = slot.task->params.introspect.interventions[k];
++ json e = iv.to_json();
++ const int64_t applied = k < slot.introspect_iv_modified.size() ? slot.introspect_iv_modified[k] : 0;
++ e["modified"] = applied;
++ total += applied;
++ ivs.push_back(e);
++ }
++ slot.introspect.interventions = ivs;
++ if (total > 0) {
++ // the KV cache now holds intervened activations: do not let a later
++ // request reuse this prefix
++ slot.prompt_clear();
++ }
++ }
++ res->introspect = slot.introspect.to_json();
++
+ queue_results.send(std::move(res));
+ }
+
+@@ -3231,13 +3306,35 @@ private:
+ int32_t off_next = 0;
+ int32_t n_batch = llama_n_batch(ctx_tgt);
+ for (int32_t off = 0; off < batch.size(); off = off_next) {
+- const int32_t n_tokens = std::min(n_batch, batch.size() - off);
++ // PS5LM fork: an all-positions introspection request renders one token at a
++ // time, so that every position is the newest row of its own graph
++ const int32_t introspect_step = introspect_prepare_step();
++ int32_t n_batch_use = n_batch;
++ if (introspect_step > 0) {
++ n_batch_use = std::min(n_batch, introspect_step);
++ }
++ const int32_t n_tokens = std::min(n_batch_use, batch.size() - off);
++ // PS5LM fork: the capture maps a tensor row back to the token's sequence
++ // position with this. The batch offset is not that position: a generated
++ // token decodes at offset 0, and a reused prefix shifts the prompt rows.
++ introspect_capture.row_pos.clear();
++ for (int32_t i = off; i < off + n_tokens; ++i) {
++ introspect_capture.row_pos.push_back(batch.tokens[i].pos[0]);
++ }
+ try {
+ scoped_timer t(t_decode, n_decode);
+ // TODO @ngxson : maybe handle n_batch == 1 here instead of inside decode()
+
+ batch.render(off, n_tokens);
+- bool ok = decode(n_batch, off);
++ bool ok = decode(n_batch_use, off);
++ if (n_batch_use != n_batch) {
++ // decode() can shrink its batch size on failure: keep this loop in step
++ n_batch = n_batch_use;
++ }
++ // PS5LM fork: harvest before post_decode(), which may release the slot
++ if (ok) {
++ introspect_harvest(off, n_tokens);
++ }
+ #ifdef DEBUG_TIMINGS
+ llama_synchronize(ctx_tgt);
+ #endif
+@@ -3978,13 +4075,21 @@ private:
+ break;
+ }
+
++ // PS5LM fork: an introspection request may want the logits and
++ // activations of every prompt position, and llama.cpp computes the
++ // last layer's output only for rows that ask for it - so a
++ // position-specific intervention needs the flag on every row too
++ const bool introspect_all =
++ slot.task->params.introspect.enabled &&
++ slot.task->params.introspect.step_tokens() > 0;
++
+ // embedding requires all tokens in the batch to be output;
+ // MTP also wants logits at every prompt position so the
+ // streaming hook can mirror t_h_nextn into ctx_dft.
+ add_ok &= batch.add(slot.id,
+ cur_tok,
+ /* pos = */ slot.prompt.tokens.pos_next(),
+- /* output = */ slot.need_embd(),
++ /* output = */ slot.need_embd() || introspect_all,
+ /* is_prompt = */ true);
+ if (!slot.task->decision.order.empty()) {
+ batch.set_decision_order(batch.size() - 1, slot.task->decision.order[slot.prompt.n_tokens()]);
+@@ -4286,6 +4391,159 @@ private:
+ return true;
+ }
+
++ // PS5LM fork: introspection (interpretability) -------------------------------
++
++ // Arms the graph-eval capture for the chunk that is about to be decoded and
++ // returns the render step: an all-positions request renders one token at a
++ // time, so that every position is the newest row of its own graph (and of the
++ // context's output buffer).
++ int32_t introspect_prepare_step() {
++ const server_slot * islot = nullptr;
++ if (introspect_enabled && batch.slot_batched != nullptr && batch.slot_batched->task != nullptr) {
++ const auto & p = batch.slot_batched->task->params.introspect;
++ if (p.enabled && p.any()) {
++ islot = batch.slot_batched;
++ }
++ }
++ if (islot == nullptr) {
++ introspect_capture.armed = false;
++ return 0;
++ }
++ introspect_capture.clear();
++ introspect_capture.row = -1; // the newest token of the chunk
++ introspect_capture.armed = islot->task->params.introspect.want_activations() ||
++ islot->task->params.introspect.want_interventions();
++ if (introspect_capture.armed) {
++ introspect_capture.build_names(islot->task->params.introspect, introspect_n_layer);
++ }
++ return islot->task->params.introspect.step_tokens();
++ }
++
++ // Collects the logits of the rows that just decoded and the activations the
++ // graph-eval callback copied out of the graph. Runs on the main loop thread,
++ // between decode() and post_decode(), so the slot is still alive.
++ void introspect_harvest(int32_t off, int32_t n_tokens) {
++ if (!introspect_enabled) {
++ return;
++ }
++ // the capture engine keeps the newest row, i.e. the one this position belongs to
++ const int32_t act_index = off + n_tokens - 1;
++
++ const int32_t n_vocab = llama_vocab_n_tokens(vocab);
++
++ for (auto & slot : slots) {
++ if (slot.task == nullptr || !slot.task->params.introspect.enabled) {
++ continue;
++ }
++ const auto & p = slot.task->params.introspect;
++
++ if (slot.introspect.positions.is_null()) {
++ slot.introspect.positions = json::array();
++ }
++
++ // meta and the request's own tokenization, once per task: positions
++ // index into this list
++ if (slot.introspect.meta.is_null()) {
++ json toks = json::array();
++ for (size_t i = 0; i < slot.task->tokens.size(); ++i) {
++ toks.push_back(json {
++ {"index", (int) i},
++ {"id", slot.task->tokens[i]},
++ {"piece", common_token_to_piece(vocab, slot.task->tokens[i], true)},
++ });
++ }
++ slot.introspect.inputs = toks;
++ slot.introspect.meta = json {
++ {"model", model_name},
++ {"build", llama_build_info()},
++ {"n_vocab", n_vocab},
++ {"n_layer", introspect_n_layer},
++ {"n_ctx", slot.n_ctx},
++ {"n_tokens", (int) slot.task->tokens.size()},
++ {"n_prompt", (int) slot.task->tokens.size()},
++ {"request", server_introspect_params_to_json(p)},
++ };
++ }
++
++ for (int32_t j = 0; j < n_tokens; ++j) {
++ const int32_t i = off + j;
++ const auto & bt = batch.tokens[i];
++ if (bt.id_slot != slot.id || !bt.output) {
++ continue; // another slot's row, or a row nobody asked for
++ }
++ const bool generated = !bt.is_prompt;
++ if (generated && !p.capture_generated) {
++ continue;
++ }
++ // the row's position is its index in the request's token list: prompt
++ // rows keep their prompt index even when a cached prefix is reused, and
++ // generated tokens continue past the prompt
++ const int32_t index = (int32_t) bt.pos[0];
++ if (!generated && !p.wants_position(index, (int32_t) slot.task->tokens.size())) {
++ continue;
++ }
++
++ json e = json::object();
++ e["index"] = index;
++ e["id"] = bt.token;
++ e["piece"] = common_token_to_piece(vocab, bt.token, true);
++ e["generated"] = generated;
++ if (generated) {
++ e["step"] = slot.introspect_n_gen;
++ }
++
++ if (p.want_logits) {
++ const float * logits = llama_get_logits_ith(ctx_tgt, j);
++ if (logits != nullptr) {
++ const bool allow_full = slot.introspect_n_full < p.max_full_rows;
++ json lj;
++ server_introspect_logits(logits, n_vocab, vocab, p, allow_full, lj);
++ if (p.full && allow_full) {
++ slot.introspect_n_full++;
++ }
++ e["logits"] = lj;
++ }
++ }
++
++ if (p.want_activations() && i == act_index && !introspect_capture.data.empty()) {
++ // bound the response: a wide activation request over a long prompt
++ // would otherwise be gigabytes of base64
++ size_t need = 0;
++ for (const auto & kv : introspect_capture.data) {
++ need += kv.second.data.size() * sizeof(float);
++ }
++ if (slot.introspect_n_bytes + (int64_t) need > introspect_max_bytes) {
++ slot.introspect.truncated = true;
++ } else {
++ json act = json::object();
++ for (const auto & kv : introspect_capture.data) {
++ act[kv.first] = kv.second.to_json();
++ }
++ e["activations"] = act;
++ slot.introspect_n_bytes += (int64_t) need;
++ }
++ }
++
++ slot.introspect.positions.push_back(e);
++ if (generated) {
++ slot.introspect_n_gen++;
++ }
++ }
++
++ // PS5LM fork: interventions are counted across the whole request
++ if (!introspect_capture.ivs.empty()) {
++ if (slot.introspect_iv_modified.size() != introspect_capture.ivs.size()) {
++ slot.introspect_iv_modified.assign(introspect_capture.ivs.size(), 0);
++ }
++ for (size_t k = 0; k < introspect_capture.ivs.size(); ++k) {
++ slot.introspect_iv_modified[k] += introspect_capture.ivs[k].modified;
++ }
++ }
++ }
++
++ introspect_capture.clear();
++ }
++
+ void post_decode(int32_t n_batch_tokens, int32_t off) {
+ // for checking if a given batch index is inside the current sub-batch
+ auto is_inside_view = [&](int32_t idx) {
+@@ -4842,6 +5100,34 @@ std::unique_ptr<server_res_generator> server_routes::handle_completions_impl(
+
+ task.apply_chat_session(chat_session);
+
++ // PS5LM fork: introspection (interpretability).
++ // A request may ask for the raw logits of the positions it names and/or
++ // for the activations of the layers it names.
++ if (!task.params.introspect_json.is_null()) {
++ task.params.introspect = server_introspect_params_from_json(task.params.introspect_json);
++ }
++ if (task.params.introspect.enabled) {
++ if (!ctx_server.is_introspect_enabled()) {
++ throw std::runtime_error("introspection is disabled on this server (start it without LLAMA_INTROSPECT=0)");
++ }
++ // one complete evaluation, no streaming: the caller wants the data, not a chat
++ task.params.stream = false;
++ task.params.verbose = true;
++ task.params.sampling.n_probs = 0;
++ // backend sampling records only the sampled candidates, which would
++ // hide the rest of the vocabulary from llama_get_logits_ith
++ task.params.sampling.backend_sampling = false;
++ if (task.params.introspect.all_positions) {
++ // every position has to be evaluated in this request
++ task.params.cache_prompt = false;
++ }
++ if (!task.params.introspect.interventions.empty()) {
++ // a reused prefix never runs the graph, so an intervention would
++ // touch only the uncached suffix: every position must be evaluated
++ task.params.cache_prompt = false;
++ }
++ }
++
+ task.id_slot = json_value(data, "id_slot", -1);
+ sse_ping_interval = task.params.sse_ping_interval;
+
+@@ -5690,6 +5976,49 @@ void server_routes::init_routes() {
+ return handle_embeddings_impl(req, TASK_RESPONSE_TYPE_OAI_EMBD);
+ };
+
++ // PS5LM fork: introspection (interpretability).
++ // Same task as /completion, but the request must carry an "introspect" field,
++ // the answer is never streamed, and the response gains an "introspection"
++ // object with the raw logits and/or the layer activations that were requested.
++ this->post_introspect = [this](const server_http_req & req) {
++ auto res = create_response();
++ if (!ctx_server.is_introspect_enabled()) {
++ res->error(format_error_response(
++ "introspection is disabled on this server (start it without LLAMA_INTROSPECT=0)",
++ ERROR_TYPE_NOT_SUPPORTED));
++ return res;
++ }
++
++ json body = json::parse(req.body);
++ if (!body.is_object() || body.count("introspect") == 0 || body.at("introspect").is_null()) {
++ res->error(format_error_response(
++ "this endpoint needs an \"introspect\" field; see docs/INTROSPECTION.md",
++ ERROR_TYPE_INVALID_REQUEST));
++ return res;
++ }
++
++ // "messages" is welcome too: render the model's own chat template through the
++ // same code path as /v1/chat/completions, so the prompt that gets probed is
++ // exactly the prompt the model would be asked
++ json data = body;
++ if (body.count("messages") > 0 && !body.at("messages").is_null()) {
++ const json introspect_field = body.at("introspect");
++ common_chat_session session;
++ std::vector<raw_buffer> files;
++ json parsed = oaicompat_chat_params_parse(ctx_server.vocab, body, meta->chat_params, files, session);
++ parsed["introspect"] = introspect_field;
++ data = std::move(parsed);
++ }
++
++ std::vector<raw_buffer> files; // dummy
++ return handle_completions_impl(
++ req,
++ SERVER_TASK_TYPE_COMPLETION,
++ data,
++ files,
++ TASK_RESPONSE_TYPE_NONE);
++ };
++
+ this->post_rerank = [this](const server_http_req & req) {
+ auto res = create_response();
+ if (!params.embedding || params.pooling_type != LLAMA_POOLING_TYPE_RANK) {
+diff --git a/tools/server/server-context.h b/tools/server/server-context.h
+index ed23f7d..d2ae01d 100644
+--- a/tools/server/server-context.h
++++ b/tools/server/server-context.h
+@@ -154,6 +154,8 @@ struct server_routes {
+ server_http_context::handler_t post_embeddings_oai;
+ server_http_context::handler_t post_rerank;
+ server_http_context::handler_t post_systemone;
++ // PS5LM fork: raw logits and per-layer activations
++ server_http_context::handler_t post_introspect;
+ server_http_context::handler_t get_lora_adapters;
+ server_http_context::handler_t post_lora_adapters;
+
+diff --git a/tools/server/server-introspect.cpp b/tools/server/server-introspect.cpp
+new file mode 100644
+index 0000000..af9c2ee
+--- /dev/null
++++ b/tools/server/server-introspect.cpp
+@@ -0,0 +1,624 @@
++#include "server-introspect.h"
++
++#include "common.h"
++#include "log.h"
++
++#include "base64.hpp"
++#include "ggml-backend.h"
++
++#include <algorithm>
++#include <cmath>
++#include <cstring>
++#include <stdexcept>
++
++const char * const server_introspect_default_tensors[] = {
++ "l_out",
++ "ffn_out",
++ "attn_out",
++ "result_norm",
++ nullptr,
++};
++
++//
++// params
++//
++
++static int32_t introspect_int_field(const json & j, const char * key, int32_t def, int32_t lo, int32_t hi) {
++ if (!j.contains(key) || j.at(key).is_null()) {
++ return def;
++ }
++ const int32_t v = j.at(key).get<int>();
++ if (v < lo || v > hi) {
++ throw std::runtime_error(std::string("introspect: '") + key + "' out of range");
++ }
++ return v;
++}
++
++static int64_t introspect_int_field64(const json & j, const char * key, int64_t def, int64_t lo, int64_t hi) {
++ if (!j.contains(key) || j.at(key).is_null()) {
++ return def;
++ }
++ const int64_t v = j.at(key).get<long long>();
++ if (v < lo || v > hi) {
++ throw std::runtime_error(std::string("introspect: '") + key + "' out of range");
++ }
++ return v;
++}
++
++server_introspect_params server_introspect_params_from_json(const json & j) {
++ server_introspect_params p;
++
++ if (j.is_null()) {
++ return p;
++ }
++ if (!j.is_object()) {
++ throw std::runtime_error("introspect: expected an object");
++ }
++
++ // "logits": true | {top_k, entropy, probs, full, max_full_rows}
++ if (j.contains("logits") && !j.at("logits").is_null()) {
++ const json & l = j.at("logits");
++ p.want_logits = true;
++ if (l.is_object()) {
++ p.top_k = introspect_int_field(l, "top_k", 20, 0, 65536);
++ p.max_full_rows = introspect_int_field(l, "max_full_rows", 8, 0, 4096);
++ p.want_entropy = l.value("entropy", true);
++ p.want_probs = l.value("probs", true);
++ p.full = l.value("full", false);
++ } else {
++ p.top_k = 20;
++ }
++ }
++
++ // "positions": "last" | "all" | [i, j, ...]
++ if (j.contains("positions") && !j.at("positions").is_null()) {
++ const json & pos = j.at("positions");
++ if (pos.is_string()) {
++ const std::string mode = pos.get<std::string>();
++ if (mode == "all") {
++ p.all_positions = true;
++ } else if (mode != "last") {
++ throw std::runtime_error("introspect: 'positions' must be \"last\", \"all\" or a list");
++ }
++ } else if (pos.is_array()) {
++ for (size_t i = 0; i < pos.size(); ++i) {
++ const int32_t v = pos.at(i).get<int>();
++ if (v < 0) {
++ throw std::runtime_error("introspect: 'positions' entries must be >= 0");
++ }
++ p.positions.push_back(v);
++ }
++ // every position has to be visible, so the batch is rendered one token at a time
++ p.all_positions = true;
++ } else {
++ throw std::runtime_error("introspect: 'positions' must be a string or a list");
++ }
++ }
++
++ // "activations": ["l_out", ...] | {"tensors": [...], "layers": "all" | [i, ...]}
++ if (j.contains("activations") && !j.at("activations").is_null()) {
++ const json & a = j.at("activations");
++ const json * t = nullptr;
++ const json * l = nullptr;
++
++ if (a.is_object()) {
++ if (a.contains("tensors")) {
++ t = &a.at("tensors");
++ }
++ if (a.contains("layers")) {
++ l = &a.at("layers");
++ }
++ } else if (a.is_array()) {
++ t = &a;
++ } else {
++ throw std::runtime_error("introspect: 'activations' must be a list or an object");
++ }
++
++ if (t != nullptr) {
++ if (!t->is_array()) {
++ throw std::runtime_error("introspect: 'activations' tensors must be a list");
++ }
++ for (size_t i = 0; i < t->size(); ++i) {
++ p.tensors.push_back(t->at(i).get<std::string>());
++ }
++ } else {
++ // bare {"layers": [...]} is a shorthand for the default tensors
++ for (size_t i = 0; server_introspect_default_tensors[i] != nullptr; ++i) {
++ p.tensors.push_back(server_introspect_default_tensors[i]);
++ }
++ }
++
++ if (l != nullptr && !l->is_null()) {
++ if (l->is_string()) {
++ if (l->get<std::string>() != "all") {
++ throw std::runtime_error("introspect: 'layers' must be \"all\" or a list");
++ }
++ } else if (l->is_array()) {
++ for (size_t i = 0; i < l->size(); ++i) {
++ const int32_t v = l->at(i).get<int>();
++ if (v < 0) {
++ throw std::runtime_error("introspect: 'layers' entries must be >= 0");
++ }
++ p.layers.push_back(v);
++ }
++ } else {
++ throw std::runtime_error("introspect: 'layers' must be a string or a list");
++ }
++ }
++ }
++
++ if (j.contains("generated") && !j.at("generated").is_null()) {
++ p.capture_generated = j.at("generated").get<bool>();
++ }
++
++ // "interventions": [{"tensor": "ffn_out", "layers": [12], "channels": [3456], "op": "zero"}]
++ if (j.contains("interventions") && !j.at("interventions").is_null()) {
++ const json & arr = j.at("interventions");
++ if (!arr.is_array()) {
++ throw std::runtime_error("introspect: 'interventions' must be a list");
++ }
++ for (size_t i = 0; i < arr.size(); ++i) {
++ const json & e = arr.at(i);
++ if (!e.is_object()) {
++ throw std::runtime_error("introspect: each intervention must be an object");
++ }
++ server_introspect_intervention iv;
++ if (e.contains("tensor") && !e.at("tensor").is_null()) {
++ iv.tensor = e.at("tensor").get<std::string>();
++ }
++ if (iv.tensor.empty()) {
++ throw std::runtime_error("introspect: an intervention needs a 'tensor'");
++ }
++ if (e.contains("layers") && e.at("layers").is_array()) {
++ for (size_t k = 0; k < e.at("layers").size(); ++k) {
++ iv.layers.push_back(e.at("layers").at(k).get<int>());
++ }
++ }
++ if (e.contains("channels") && e.at("channels").is_array()) {
++ for (size_t k = 0; k < e.at("channels").size(); ++k) {
++ iv.channels.push_back(e.at("channels").at(k).get<long long>());
++ }
++ }
++ iv.channel_start = introspect_int_field64(e, "channel_start", -1, -1, 1 << 30);
++ iv.channel_end = introspect_int_field64(e, "channel_end", -1, -1, 1 << 30);
++ iv.position = introspect_int_field64(e, "position", -1, -1, 1 << 30);
++ if (e.contains("op") && !e.at("op").is_null()) {
++ iv.op = e.at("op").get<std::string>();
++ }
++ if (e.contains("value") && !e.at("value").is_null()) {
++ iv.value = e.at("value").get<float>();
++ }
++ if (iv.op != "zero" && iv.op != "scale" && iv.op != "add") {
++ throw std::runtime_error("introspect: intervention op must be \"zero\", \"scale\" or \"add\"");
++ }
++ if (iv.channels.empty() && iv.channel_start < 0 && iv.channel_end < 0) {
++ // no channel named: the whole tensor row is the target
++ iv.channel_start = 0;
++ }
++ p.interventions.push_back(std::move(iv));
++ }
++ }
++
++ p.enabled = p.any();
++ return p;
++}
++
++json server_introspect_params_to_json(const server_introspect_params & p) {
++ json j = json::object();
++ if (p.want_logits) {
++ j["top_k"] = p.top_k;
++ j["entropy"] = p.want_entropy;
++ j["probs"] = p.want_probs;
++ j["full"] = p.full;
++ j["max_full_rows"] = p.max_full_rows;
++ }
++ if (p.all_positions) {
++ if (p.positions.empty()) {
++ j["positions"] = "all";
++ } else {
++ json pos = json::array();
++ for (const int32_t v : p.positions) {
++ pos.push_back(v);
++ }
++ j["positions"] = pos;
++ }
++ } else {
++ j["positions"] = "last";
++ }
++ if (!p.tensors.empty()) {
++ json tensors = json::array();
++ for (const auto & t : p.tensors) {
++ tensors.push_back(t);
++ }
++ j["activations"] = json {
++ {"tensors", tensors},
++ {"layers", p.layers.empty() ? json("all") : json(p.layers)},
++ };
++ }
++ if (!p.interventions.empty()) {
++ json arr = json::array();
++ for (const auto & iv : p.interventions) {
++ arr.push_back(iv.to_json());
++ }
++ j["interventions"] = arr;
++ }
++ j["generated"] = p.capture_generated;
++ return j;
++}
++
++//
++// capture
++//
++
++void server_introspect_intervention::build_names(int32_t n_layer) {
++ names.clear();
++ if (tensor.find('-') != std::string::npos) {
++ names.push_back(tensor); // an exact name, e.g. "ffn_out-12"
++ return;
++ }
++ if (layers.empty()) {
++ for (int32_t il = 0; il <= n_layer; ++il) {
++ names.push_back(tensor + "-" + std::to_string(il));
++ }
++ } else {
++ for (const int32_t il : layers) {
++ names.push_back(tensor + "-" + std::to_string(il));
++ }
++ }
++ names.push_back(tensor); // layer-less tensors (inp_embd, result_norm)
++}
++
++bool server_introspect_intervention::matches(const std::string & name) const {
++ for (const auto & n : names) {
++ if (n == name) {
++ return true;
++ }
++ }
++ return false;
++}
++
++json server_introspect_intervention::to_json() const {
++ json channels = json::array();
++ for (const int64_t c : this->channels) {
++ channels.push_back(c);
++ }
++ return json {
++ {"tensor", tensor},
++ {"layers", layers.empty() ? json("all") : json(layers)},
++ {"channels", channels},
++ {"channel_start", channel_start},
++ {"channel_end", channel_end},
++ {"position", position},
++ {"op", op},
++ {"value", value},
++ {"modified", modified},
++ };
++}
++
++void server_introspect_capture::build_names(const server_introspect_params & p, int32_t n_layer) {
++ names.clear();
++ for (const auto & base : p.tensors) {
++ // a name that already carries a layer suffix is matched as given
++ if (base.find('-') != std::string::npos) {
++ names.insert(base);
++ continue;
++ }
++ if (p.layers.empty()) {
++ for (int32_t il = 0; il <= n_layer; ++il) {
++ names.insert(base + "-" + std::to_string(il));
++ }
++ } else {
++ for (const int32_t il : p.layers) {
++ names.insert(base + "-" + std::to_string(il));
++ }
++ }
++ // layer-less tensors (inp_embd, result_norm, result_output) carry no suffix
++ names.insert(base);
++ }
++
++ ivs = p.interventions;
++ for (auto & iv : ivs) {
++ iv.build_names(n_layer);
++ }
++}
++
++bool server_introspect_capture::on_tensor(struct ggml_tensor * t, bool ask) {
++ if (!armed) {
++ return false;
++ }
++ const bool wanted = names.find(t->name) != names.end();
++
++ std::vector<server_introspect_intervention *> hits;
++ for (auto & iv : ivs) {
++ if (iv.matches(t->name)) {
++ hits.push_back(&iv);
++ }
++ }
++ if (!wanted && hits.empty()) {
++ return false;
++ }
++ if (ask) {
++ // tell the scheduler we want this node: for a device buffer that makes it
++ // the end of a split and copies the result back to the host. Everything
++ // below runs with the tensor complete and before its consumers run, which
++ // is what makes an in-place intervention safe.
++ return true;
++ }
++
++ // !ask: the node's buffer is complete and host-visible
++ const int64_t n_rows = t->ne[1];
++ if (n_rows <= 0 || t->ne[0] <= 0) {
++ return true;
++ }
++
++ const bool want_row = wanted && (row < 0 || row < n_rows) && n_bytes + ggml_row_size(t->type, t->ne[0]) <= max_bytes;
++ if (want_row) {
++ const int64_t r = row < 0 ? n_rows - 1 : row;
++ const size_t row_bytes = ggml_row_size(t->type, t->ne[0]);
++ std::vector<uint8_t> raw(row_bytes);
++ if (ggml_backend_buffer_is_host(t->buffer)) {
++ std::memcpy(raw.data(), (const uint8_t *) t->data + (size_t) r * t->nb[1], row_bytes);
++ } else {
++ ggml_backend_tensor_get(t, raw.data(), (size_t) r * t->nb[1], row_bytes);
++ }
++
++ server_introspect_tensor out;
++ out.name = t->name;
++ out.ne.assign(t->ne, t->ne + GGML_MAX_DIMS);
++ out.data.resize(t->ne[0]);
++
++ const int64_t n = t->ne[0];
++ bool ok = true;
++ switch (t->type) {
++ case GGML_TYPE_F32:
++ std::memcpy(out.data.data(), raw.data(), (size_t) n * sizeof(float));
++ break;
++ case GGML_TYPE_F16:
++ ggml_fp16_to_fp32_row((const ggml_fp16_t *) raw.data(), out.data.data(), n);
++ break;
++ case GGML_TYPE_BF16:
++ ggml_bf16_to_fp32_row((const ggml_bf16_t *) raw.data(), out.data.data(), n);
++ break;
++ default:
++ ok = false;
++ break;
++ }
++ if (ok) {
++ n_bytes += row_bytes;
++ data[t->name] = std::move(out); // the last write wins, i.e. the newest sub-batch
++ }
++ }
++
++ if (hits.empty()) {
++ return true;
++ }
++
++ // interventions: read the tensor (or the rows they touch), change it, write it back
++ const size_t nbytes = ggml_nbytes(t);
++ if (nbytes > (64u << 20)) {
++ return true; // refuse to buffer a tensor this large
++ }
++ const bool host = ggml_backend_buffer_is_host(t->buffer);
++ const int64_t ne0 = t->ne[0];
++ const int64_t ne1 = t->ne[1];
++ const int64_t ne2 = t->ne[2];
++ const bool direct = host && t->type == GGML_TYPE_F32 && t->nb[0] == sizeof(float) && t->nb[1] == (size_t) ne0 * sizeof(float);
++ if (!direct && t->type != GGML_TYPE_F32 && t->type != GGML_TYPE_F16 && t->type != GGML_TYPE_BF16) {
++ return true; // not a float activation
++ }
++
++ std::vector<uint8_t> raw(nbytes);
++ if (host) {
++ std::memcpy(raw.data(), t->data, nbytes);
++ } else {
++ ggml_backend_tensor_get(t, raw.data(), 0, nbytes);
++ }
++
++ // a layout with unit strides in dim 0/1 (how llama.cpp's graph tensors are laid out)
++ std::vector<float> v;
++ float * dense = nullptr; // mutable pointer into raw when the layout is already unit-stride
++ if (direct) {
++ dense = reinterpret_cast<float *>(raw.data());
++ } else {
++ v.resize((size_t) ne0 * ne1 * ne2);
++ if (t->type == GGML_TYPE_F32) {
++ std::memcpy(v.data(), raw.data(), (size_t) ne0 * ne1 * ne2 * sizeof(float));
++ } else if (t->type == GGML_TYPE_F16) {
++ ggml_fp16_to_fp32_row((const ggml_fp16_t *) raw.data(), v.data(), (int64_t) ne0 * ne1 * ne2);
++ } else {
++ ggml_bf16_to_fp32_row((const ggml_bf16_t *) raw.data(), v.data(), (int64_t) ne0 * ne1 * ne2);
++ }
++ dense = v.data();
++ }
++
++ bool changed = false;
++ for (auto * iv : hits) {
++ for (int64_t i1 = 0; i1 < ne1; ++i1) {
++ if (iv->position >= 0 && (i1 >= (int64_t) row_pos.size() || iv->position != row_pos[i1])) {
++ continue;
++ }
++ for (int64_t i0 = 0; i0 < ne0; ++i0) {
++ bool hit = false;
++ if (!iv->channels.empty()) {
++ for (const int64_t c : iv->channels) {
++ if (c == i0) {
++ hit = true;
++ break;
++ }
++ }
++ } else {
++ hit = i0 >= (iv->channel_start < 0 ? 0 : iv->channel_start) &&
++ (iv->channel_end < 0 || i0 < iv->channel_end);
++ }
++ if (!hit) {
++ continue;
++ }
++ const size_t idx = (size_t) i0 + (size_t) i1 * ne0;
++ float * slot_v = dense + idx;
++ if (iv->op == "zero") {
++ *slot_v = 0.0f;
++ } else if (iv->op == "scale") {
++ *slot_v *= iv->value;
++ } else {
++ *slot_v += iv->value;
++ }
++ iv->modified++;
++ changed = true;
++ }
++ }
++ }
++
++ if (changed) {
++ if (direct) {
++ // dense points into raw, write it back as-is
++ } else if (t->type == GGML_TYPE_F32) {
++ std::memcpy(raw.data(), v.data(), v.size() * sizeof(float));
++ } else if (t->type == GGML_TYPE_F16) {
++ for (size_t i = 0; i < v.size(); ++i) {
++ ((ggml_fp16_t *) raw.data())[i] = ggml_fp32_to_fp16(v[i]);
++ }
++ } else {
++ for (size_t i = 0; i < v.size(); ++i) {
++ ((ggml_bf16_t *) raw.data())[i] = ggml_fp32_to_bf16(v[i]);
++ }
++ }
++ if (ggml_backend_buffer_is_host(t->buffer)) {
++ std::memcpy(t->data, raw.data(), nbytes);
++ } else {
++ ggml_backend_tensor_set(t, raw.data(), 0, nbytes);
++ }
++ }
++
++ return true;
++}
++
++bool server_introspect_cb(struct ggml_tensor * t, bool ask, void * user_data) {
++ auto * capture = (server_introspect_capture *) user_data;
++ if (capture == nullptr) {
++ return false;
++ }
++ return capture->on_tensor(t, ask);
++}
++
++json server_introspect_tensor::to_json() const {
++ json ne = json::array();
++ for (const int64_t d : this->ne) {
++ ne.push_back(d);
++ }
++ return json {
++ {"shape", ne},
++ {"dtype", "f32"},
++ {"encoding", "base64"},
++ {"data", base64::encode((const char *) data.data(), data.size() * sizeof(float))},
++ };
++}
++
++//
++// logits
++//
++
++// bounded top-k selection, no allocation proportional to the vocabulary
++static std::vector<int32_t> introspect_top_k(const float * logits, int32_t n_vocab, int32_t k) {
++ std::vector<int32_t> best;
++ if (k <= 0) {
++ return best;
++ }
++ best.reserve(k);
++
++ auto worse = [&](int32_t a, int32_t b) { return logits[a] > logits[b]; }; // min-heap on the logit
++
++ for (int32_t i = 0; i < n_vocab; ++i) {
++ if ((int32_t) best.size() < k) {
++ best.push_back(i);
++ std::push_heap(best.begin(), best.end(), worse);
++ } else if (logits[i] > logits[best.front()]) {
++ std::pop_heap(best.begin(), best.end(), worse);
++ best.back() = i;
++ std::push_heap(best.begin(), best.end(), worse);
++ }
++ }
++ std::sort(best.begin(), best.end(), [&](int32_t a, int32_t b) { return logits[a] > logits[b]; });
++ return best;
++}
++
++static json introspect_token_json(const llama_vocab * vocab, int32_t id, float logit, float prob, bool with_prob) {
++ json j = json {
++ {"id", id},
++ {"piece", common_token_to_piece(vocab, id, true)},
++ {"logit", logit},
++ };
++ if (with_prob) {
++ j["prob"] = prob;
++ }
++ return j;
++}
++
++void server_introspect_logits(
++ const float * logits,
++ int32_t n_vocab,
++ const llama_vocab * vocab,
++ const server_introspect_params & p,
++ bool allow_full,
++ json & out) {
++ if (logits == nullptr || n_vocab <= 0) {
++ out = nullptr;
++ return;
++ }
++
++ int32_t best = 0;
++ for (int32_t i = 1; i < n_vocab; ++i) {
++ if (logits[i] > logits[best]) {
++ best = i;
++ }
++ }
++ const float best_logit = logits[best];
++
++ const bool need_norm = p.want_probs || p.want_entropy;
++ double log_sum = 0.0;
++ if (need_norm) {
++ double sum = 0.0;
++ for (int32_t i = 0; i < n_vocab; ++i) {
++ sum += std::exp((double) (logits[i] - best_logit));
++ }
++ log_sum = std::log(sum);
++ }
++ auto prob_of = [&](float logit) -> float {
++ return (float) std::exp((double) (logit - best_logit) - log_sum);
++ };
++
++ out = json::object();
++ out["n_vocab"] = n_vocab;
++ // the argmax's own probability is exp(0 - logsumexp), not 1.0
++ out["argmax"] = introspect_token_json(vocab, best, best_logit,
++ need_norm ? (float) std::exp(-log_sum) : 0.0f, p.want_probs);
++
++ if (p.top_k > 0) {
++ const std::vector<int32_t> top = introspect_top_k(logits, n_vocab, p.top_k);
++ json arr = json::array();
++ for (const int32_t id : top) {
++ arr.push_back(introspect_token_json(vocab, id, logits[id], p.want_probs ? prob_of(logits[id]) : 0.0f, p.want_probs));
++ }
++ out["top"] = arr;
++ }
++
++ if (p.want_entropy) {
++ double h = 0.0;
++ for (int32_t i = 0; i < n_vocab; ++i) {
++ const double lp = (double) (logits[i] - best_logit) - log_sum;
++ const double pr = std::exp(lp);
++ if (pr > 0.0) {
++ h -= pr * lp;
++ }
++ }
++ out["entropy"] = h;
++ }
++
++ if (p.full && allow_full) {
++ out["full"] = json {
++ {"encoding", "base64"},
++ {"dtype", "f32"},
++ {"n_vocab", n_vocab},
++ {"data", base64::encode((const char *) logits, (size_t) n_vocab * sizeof(float))},
++ };
++ }
++}
+diff --git a/tools/server/server-introspect.h b/tools/server/server-introspect.h
+new file mode 100644
+index 0000000..a80f7e1
+--- /dev/null
++++ b/tools/server/server-introspect.h
+@@ -0,0 +1,205 @@
++#pragma once
++
++// PS5LM fork: the introspection ("interpretability") API.
++//
++// llama.cpp computes, but never exposes, the two things an interpretability
++// experiment needs: the raw logit distribution over the whole vocabulary at a
++// chosen position, and the intermediate activations of the transformer blocks
++// (the residual stream before and after each block, and the MLP/attention
++// outputs inside it). This module supplies both, driven by a request field
++// ("introspect") rather than by a second model pass:
++//
++// - logits are read straight out of the context's output buffer with
++// llama_get_logits_ith() after the existing decode step;
++// - activations are copied out of the compute graph while it runs, through
++// llama_context_params.cb_eval (ggml_backend_sched_eval_callback), which
++// the scheduler calls for every node. The fetch is a no-op unless a
++// request armed it, so ordinary generation pays nothing.
++//
++// Everything here is request-scoped: the capture engine is armed for one
++// decode step at a time and cleared straight after, on the server's own
++// (main loop) thread.
++
++#include "server-common.h" // json alias, common_token_to_piece
++
++#include <cstdint>
++#include <map>
++#include <string>
++#include <unordered_set>
++#include <vector>
++
++struct ggml_tensor;
++
++// Default activation tensors, in the order a llama-architecture graph emits
++// them (see src/models/llama.cpp):
++// inp_embd token embedding + position, the residual stream at the input
++// attn_norm-<il> residual stream after the block's input norm
++// attn_out-<il> attention output (before the residual add)
++// ffn_norm-<il> residual stream after the post-attention norm
++// ffn_out-<il> MLP output (before the residual add)
++// l_out-<il> residual stream after block il (l_out-<il-1> is the block input)
++// result_norm final hidden state before the output projection
++// result_output logits tensor of the graph
++extern const char * const server_introspect_default_tensors[];
++
++// One in-place intervention on an activation tensor: zero, scale or add a value
++// to a channel (a single neuron, an attention head dimension, or a range), at one
++// position or at every position of the request. Applied inside the graph-eval
++// callback, i.e. after the tensor is computed and before its consumers run.
++struct server_introspect_intervention {
++ std::string tensor; // base name ("ffn_out") or exact name ("ffn_out-12")
++ std::vector<int32_t> layers; // layer filter for a base name, empty = all
++ std::vector<int64_t> channels; // explicit channel indices, empty = the range below
++ int64_t channel_start = -1; // inclusive, -1 = from 0
++ int64_t channel_end = -1; // exclusive, -1 = to the end
++ int64_t position = -1; // token index of the request, -1 = every position
++ std::string op = "zero"; // zero | scale | add
++ float value = 0.0f; // operand of scale/add
++
++ std::vector<std::string> names; // resolved ggml tensor names
++ int64_t modified = 0; // elements changed, summed over the request
++
++ void build_names(int32_t n_layer);
++ bool matches(const std::string & name) const;
++ json to_json() const;
++};
++
++struct server_introspect_params {
++ bool enabled = false;
++
++ // logits
++ bool want_logits = false;
++ int32_t top_k = 0; // entries in "top" (0 = no list)
++ bool want_entropy = false; // one extra pass over the vocabulary
++ bool want_probs = true; // probabilities for argmax/top (needs the same pass)
++ bool full = false; // include the whole float32 row (base64)
++ int32_t max_full_rows = 8; // cap on the number of full rows, bounds the response
++
++ // which positions of the request to look at
++ bool all_positions = false; // decode one token at a time so every position is visible
++ std::vector<int32_t> positions; // explicit positions (implies all_positions)
++
++ // activations
++ std::vector<std::string> tensors; // base names, e.g. {"l_out", "ffn_out"}
++ std::vector<int32_t> layers; // layer suffix filter, empty = all
++
++ bool capture_generated = true; // also capture the tokens the model produces
++
++ std::vector<server_introspect_intervention> interventions;
++
++ int32_t step_tokens() const {
++ if (all_positions) {
++ return 1;
++ }
++ // a position-specific intervention needs every position to be its own row
++ for (const auto & iv : interventions) {
++ if (iv.position >= 0) {
++ return 1;
++ }
++ }
++ return 0;
++ }
++
++ bool wants_position(int32_t idx, int32_t n_prompt) const {
++ if (!all_positions) {
++ return idx == n_prompt - 1; // "last" = the final prompt token
++ }
++ if (positions.empty()) {
++ return true;
++ }
++ for (const int32_t p : positions) {
++ if (p == idx) {
++ return true;
++ }
++ }
++ return false;
++ }
++
++ bool want_activations() const { return !tensors.empty(); }
++ bool want_interventions() const { return !interventions.empty(); }
++ bool any() const { return want_logits || want_activations() || want_interventions(); }
++};
++
++// Parses (and validates) the "introspect" request field. Throws json_error on a bad field.
++server_introspect_params server_introspect_params_from_json(const json & j);
++json server_introspect_params_to_json(const server_introspect_params & p);
++
++// One tensor row copied out of the graph: ne is the tensor's full shape, data has ne[0] floats.
++struct server_introspect_tensor {
++ std::string name;
++ std::vector<int64_t> ne;
++ std::vector<float> data;
++
++ json to_json() const;
++};
++
++// The graph-eval capture engine. Armed by the slot for one decode step; the
++// scheduler then offers it every node of the graph being computed.
++struct server_introspect_capture {
++ bool armed = false;
++
++ std::unordered_set<std::string> names; // exact ggml tensor names to match
++ int64_t row = -1; // row to keep within the tensor, -1 = the last row
++ std::vector<int64_t> row_pos; // sequence position (pos[0]) of each row of the chunk being decoded
++
++ std::vector<server_introspect_intervention> ivs; // applied when a tensor matches one
++
++ std::map<std::string, server_introspect_tensor> data; // by tensor name, last write wins
++
++ size_t max_bytes = 256u << 20; // hard bound on one captured step
++ size_t n_bytes = 0;
++
++ void clear() {
++ data.clear();
++ n_bytes = 0;
++ for (auto & iv : ivs) {
++ iv.modified = 0;
++ }
++ }
++
++ void build_names(const server_introspect_params & p, int32_t n_layer);
++ bool on_tensor(struct ggml_tensor * t, bool ask);
++};
++
++// the callback installed on the context (never null; a no-op until armed)
++bool server_introspect_cb(struct ggml_tensor * t, bool ask, void * user_data);
++
++// Formats the raw logits of one position: argmax, optional top-k / entropy / full row.
++// allow_full=false suppresses the full row (used when the per-request cap is reached).
++void server_introspect_logits(
++ const float * logits,
++ int32_t n_vocab,
++ const llama_vocab * vocab,
++ const server_introspect_params & p,
++ bool allow_full,
++ json & out);
++
++// Accumulated result of one introspection request, serialized as the response's
++// "introspection" object.
++struct server_introspect_result {
++ json meta = nullptr; // model / context facts, filled once by the caller
++ json inputs = nullptr; // the request's token ids and pieces
++ json positions = nullptr; // one entry per captured position
++ json interventions = nullptr; // what was changed, with the count of elements touched
++ bool truncated = false; // the byte budget cut some activations out
++
++ bool empty() const {
++ return (positions.is_null() || positions.size() == 0) && interventions.is_null();
++ }
++
++ json to_json() const {
++ if (empty()) {
++ return nullptr;
++ }
++ json out = json {
++ {"meta", meta},
++ {"inputs", inputs},
++ {"positions", positions.is_null() ? json::array() : positions},
++ {"truncated", truncated},
++ };
++ if (!interventions.is_null()) {
++ out["interventions"] = interventions;
++ }
++ return out;
++ }
++};
+diff --git a/tools/server/server-schema.cpp b/tools/server/server-schema.cpp
+index 54e126a..30efbbb 100644
+--- a/tools/server/server-schema.cpp
++++ b/tools/server/server-schema.cpp
+@@ -187,6 +187,17 @@ std::vector<std::unique_ptr<field>> make_llama_cmpl_schema(const common_params &
+ add((new field_bool("backend_sampling", params.sampling.backend_sampling))
+ ->set_desc("Use backend sampling instead of llama.cpp sampling"));
+
++ // PS5LM fork: interpretability. Keep the parsed value as json; the task
++ // parses it into task_params::introspect once the task is created.
++ add((new field_json("introspect"))
++ ->set_desc("Return raw logits and/or per-layer activations for this request. "
++ "Object with any of: logits (true or {top_k, entropy, probs, full, max_full_rows}), "
++ "positions (\"last\", \"all\" or a list of token indices), "
++ "activations (list of tensor names, or {tensors, layers}), generated (bool)")
++ ->set_handler([&](field_eval_context & ctx, const json & data) {
++ ctx.params.introspect_json = data.at("introspect");
++ }));
++
+ add((new field_bool("post_sampling_probs", params.post_sampling_probs))
+ ->set_desc("Return probabilities of top n_probs tokens after applying the sampling chain"));
+
+diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp
+index 3f30da2..542d559 100644
+--- a/tools/server/server-task.cpp
++++ b/tools/server/server-task.cpp
+@@ -351,6 +351,10 @@ json server_task_result_cmpl_final::to_json_non_oaicompat() {
+ if (!stream && !probs_output.empty()) {
+ res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
+ }
++ // PS5LM fork: raw logits and per-layer activations, when the request asked for them
++ if (!introspect.is_null()) {
++ res["introspection"] = introspect;
++ }
+ return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
+ }
+
+diff --git a/tools/server/server-task.h b/tools/server/server-task.h
+index 50926ec..93b29ec 100644
+--- a/tools/server/server-task.h
++++ b/tools/server/server-task.h
+@@ -10,6 +10,7 @@
+
+ // TODO: prevent including the whole server-common.h as we only use server_tokens
+ #include "server-common.h"
++#include "server-introspect.h" // PS5LM fork: introspection request/response types
+
+
+ enum server_task_type {
+@@ -99,6 +100,12 @@ struct task_params {
+ // Embeddings
+ int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm)
+
++ // PS5LM fork: interpretability ("introspect" request field).
++ // introspect_json is the raw request value; introspect is the parsed form,
++ // filled once the task is built (see server_introspect_params_from_json).
++ json introspect_json = nullptr;
++ struct server_introspect_params introspect;
++
+ json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const;
+ json to_json(bool only_metrics = false) const;
+ };
+@@ -384,6 +391,9 @@ struct server_task_result_cmpl_final : server_task_result {
+
+ task_params generation_params;
+
++ // PS5LM fork: the introspection payload of this request (null unless requested)
++ json introspect = nullptr;
++
+ // response formatting
+ bool verbose = false;
+ task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
+diff --git a/tools/server/server.cpp b/tools/server/server.cpp
+index 871e827..12dd9bd 100644
+--- a/tools/server/server.cpp
++++ b/tools/server/server.cpp
+@@ -241,6 +241,8 @@ int llama_server(common_params & params, int argc, char ** argv, server_child &
+ routes.post_systemone = models_routes->proxy_post;
+ routes.post_tokenize = models_routes->proxy_post;
+ routes.post_detokenize = models_routes->proxy_post;
++ // PS5LM fork
++ routes.post_introspect = models_routes->proxy_post;
+ routes.post_apply_template = models_routes->proxy_post;
+ routes.post_chat_completions_tok = models_routes->proxy_post;
+ routes.post_responses_tok_oai = models_routes->proxy_post;
+@@ -289,6 +291,9 @@ int llama_server(common_params & params, int argc, char ** argv, server_child &
+ ctx_http.post("/v1/systemone", ex_wrapper(routes.post_systemone));
+ ctx_http.post("/tokenize", ex_wrapper(routes.post_tokenize));
+ ctx_http.post("/detokenize", ex_wrapper(routes.post_detokenize));
++ // PS5LM fork: raw logits and per-layer activations (interpretability)
++ ctx_http.post("/introspect", ex_wrapper(routes.post_introspect));
++ ctx_http.post("/v1/introspect", ex_wrapper(routes.post_introspect));
+ ctx_http.post("/apply-template", ex_wrapper(routes.post_apply_template));
+ // token counting
+ ctx_http.post("/chat/completions/input_tokens", ex_wrapper(routes.post_chat_completions_tok));
diff --git a/ps5/app/activity.cpp b/ps5/app/activity.cpp
index f7ef71c..f7d1cdd 100644
--- a/ps5/app/activity.cpp
+++ b/ps5/app/activity.cpp
@@ -9,6 +9,7 @@
#include <nlohmann/json.hpp>
#include <cstdio>
+#include <cstring>
#include <map>
#include <mutex>
#include <string>
@@ -20,6 +21,7 @@ namespace {
std::mutex g_mutex;
std::map<int, std::string> g_partial; // an answer's stream, up to its last full line
+std::map<int, bool> g_ignored; // requests whose answer must not be accumulated
ps5lm::StatsCollector * g_sink = nullptr;
// One line, spaces collapsed, at most `cap` bytes, cut at a character's start.
@@ -203,6 +205,13 @@ void ps5lm_activity_begin(int id, const char * method, const char * path, const
if (!g_sink) {
return;
}
+ // an introspection answer can be tens of megabytes of logits and activations;
+ // the feed has nothing to show for it, so it is not accumulated at all
+ if (path != nullptr && strstr(path, "introspect") != nullptr) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ g_ignored[id] = true;
+ return;
+ }
const json j = json::parse(body, body + body_len, nullptr, false);
const int questions = j.is_object() && j.contains("questions") && j["questions"].is_object() ? (int) j["questions"].size() : 0;
g_sink->activity_begin(id, remote ? remote : "", path ? path : "", one_line(printable(asked_from(path ? path : "", j)), 400), questions);
@@ -212,6 +221,12 @@ void ps5lm_activity_data(int id, const char * data, size_t len) {
if (!g_sink) {
return;
}
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ if (g_ignored.count(id) != 0) {
+ return;
+ }
+ }
std::string out;
{
std::lock_guard<std::mutex> lock(g_mutex);
@@ -250,6 +265,9 @@ void ps5lm_activity_end(int id, int status) {
{
std::lock_guard<std::mutex> lock(g_mutex);
g_partial.erase(id);
+ if (g_ignored.erase(id) != 0) {
+ return;
+ }
}
if (g_sink) {
g_sink->activity_end(id, status);
diff --git a/ps5/app/dashboard.cpp b/ps5/app/dashboard.cpp
index 60aff91..96376d9 100644
--- a/ps5/app/dashboard.cpp
+++ b/ps5/app/dashboard.cpp
@@ -79,7 +79,7 @@ constexpr int kMarketChipCount = 7;
// ---- Settings -------------------------------------------------------------------
-enum class Setting : int { auto_load, default_model, ctx_cap, kv_type, sounds, tools, scratch_limit, clear_scratch, download_dir };
+enum class Setting : int { auto_load, default_model, ctx_cap, kv_type, sounds, tools, introspect, scratch_limit, clear_scratch, download_dir };
struct SettingRow {
Setting id;
@@ -111,10 +111,14 @@ constexpr SettingCategory kCategories[] = {
{ { Setting::sounds, "Sounds", "Interface sounds on the TV" },
{ Setting::download_dir, "Save downloads to", "Internal storage, or PS5LM/models on an M.2 or USB drive" } },
2 },
+ { "Developer",
+ { { Setting::introspect, "Logits and activations API",
+ "Off: /v1/introspect is closed. On: the raw numbers. A change restarts the model" } },
+ 1 },
{ "Diagnostics", {}, 0 },
};
-constexpr int kCategoryCount = 5;
-constexpr int kDiagnostics = 4;
+constexpr int kCategoryCount = 6;
+constexpr int kDiagnostics = 5;
constexpr uint32_t kCtxSteps[] = { 4096, 8192, 16384, 32768, 65536, 131072 };
constexpr const char * kKvSteps[] = { "auto", "f16", "q8_0", "q4_0" };
@@ -404,10 +408,16 @@ std::string setting_text(const Settings & s, Setting id, const std::vector<Model
}
}
-bool is_toggle(Setting id) { return id == Setting::auto_load || id == Setting::sounds || id == Setting::tools; }
+bool is_toggle(Setting id) { return id == Setting::auto_load || id == Setting::sounds || id == Setting::tools || id == Setting::introspect; }
bool toggle_value(const Settings & s, Setting id) {
- return id == Setting::auto_load ? s.auto_load : id == Setting::sounds ? s.sounds : s.tools;
+ switch (id) {
+ case Setting::auto_load: return s.auto_load;
+ case Setting::sounds: return s.sounds;
+ case Setting::tools: return s.tools;
+ case Setting::introspect: return s.introspect;
+ default: return false;
+ }
}
// A row's choices, for the list X opens under it: each with the settings it
@@ -967,7 +977,10 @@ void Dashboard::update_settings(const hui::InputFrame & input, ui::Feedback & fe
request_ = { Request::clear_scratch, "" };
feedback.play(Cue::select);
} else if (is_toggle(id)) {
- bool & on = id == Setting::auto_load ? settings_.auto_load : id == Setting::sounds ? settings_.sounds : settings_.tools;
+ bool & on = id == Setting::auto_load ? settings_.auto_load
+ : id == Setting::sounds ? settings_.sounds
+ : id == Setting::tools ? settings_.tools
+ : settings_.introspect;
on = !on;
request_ = { Request::settings, "" };
feedback.play(Cue::toggle);
diff --git a/ps5/app/main.cpp b/ps5/app/main.cpp
index d21fa0b..2b9ebc4 100644
--- a/ps5/app/main.cpp
+++ b/ps5/app/main.cpp
@@ -781,6 +781,10 @@ int main(int, char **) {
}
log_memory("before loading");
if (!args.empty()) {
+ // The introspection API is off unless the setting asks for it. The
+ // server reads LLAMA_INTROSPECT when its thread starts, below. The
+ // setting wins over env.txt, so the row always says what the server does.
+ setenv("LLAMA_INTROSPECT", models.settings.introspect ? "1" : "0", 1);
models.start(path, args, stats, model_part);
} else {
stats.set_state(ServerState::no_model);
@@ -981,6 +985,16 @@ int main(int, char **) {
models.rescan(stats);
}
std::printf("ps5lm-app: settings saved\n");
+ // The server reads LLAMA_INTROSPECT only when it starts: restart with the
+ // same model, so that the switch never says something the server does not do.
+ if (was.introspect != models.settings.introspect && !models.running.empty() && restart_at == 0) {
+ std::ofstream(kChoice) << models.running << "\n";
+ std::printf("ps5lm-app: restarting %s with the introspection API %s\n", models.running.c_str(),
+ models.settings.introspect ? "on" : "off");
+ dash.set_busy(std::string(models.settings.introspect ? "Opening" : "Closing") + " the logits and activations API",
+ "The app restarts with " + base_name(models.running));
+ restart_at = n + 3;
+ }
}
switch (req.kind) {
case Dashboard::Request::ask: ask_self(kPort, req.path, !live.decision.empty()); break;
diff --git a/ps5/app/settings.cpp b/ps5/app/settings.cpp
index f03ac36..4d14c8d 100644
--- a/ps5/app/settings.cpp
+++ b/ps5/app/settings.cpp
@@ -23,6 +23,7 @@ Settings load_settings(const char * path) {
s.kv_type = j.value("kv_type", s.kv_type);
s.sounds = j.value("sounds", s.sounds);
s.tools = j.value("tools", s.tools);
+ s.introspect = j.value("introspect", s.introspect);
s.scratch_limit_gib = j.value("scratch_limit_gib", s.scratch_limit_gib);
s.download_dir = j.value("download_dir", s.download_dir);
return s;
@@ -32,6 +33,7 @@ bool save_settings(const char * path, const Settings & s) {
const nlohmann::json j = {
{ "auto_load", s.auto_load }, { "default_model", s.default_model }, { "ctx_cap", s.ctx_cap },
{ "kv_type", s.kv_type }, { "sounds", s.sounds }, { "tools", s.tools },
+ { "introspect", s.introspect },
{ "scratch_limit_gib", s.scratch_limit_gib }, { "download_dir", s.download_dir },
};
std::ofstream out(path);
diff --git a/ps5/app/settings.hpp b/ps5/app/settings.hpp
index 3f9d4dc..2f7be58 100644
--- a/ps5/app/settings.hpp
+++ b/ps5/app/settings.hpp
@@ -17,6 +17,7 @@ struct Settings {
std::string kv_type = "auto"; // "auto", "f16", "q8_0" or "q4_0"
bool sounds = true;
bool tools = true; // file tools in the browser chat, inside the scratch folder
+ bool introspect = false; // POST /v1/introspect: raw logits and activations (off by default)
uint32_t scratch_limit_gib = 2; // warn when the scratch folder grows past this
std::string download_dir = "/data/PS5LM/models"; // where the market saves models
diff --git a/scripts/ps5lm-introspect.py b/scripts/ps5lm-introspect.py
new file mode 100755
index 0000000..dc21259
--- /dev/null
+++ b/scripts/ps5lm-introspect.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python3
+"""Talk to PS5LM's introspection endpoint and turn the answer into numbers.
+
+ # what does the model think the next token is, and what is layer 12's residual stream?
+ python3 tools/ps5lm-introspect.py --host 192.168.1.50 --prompt "Once upon a time" \
+ --positions last --top-k 10 --tensors l_out --layers 12
+
+ # every prompt position, logits + the residual stream of every layer, saved for poking at
+ python3 tools/ps5lm-introspect.py --host 192.168.1.50 --prompt "Once upon a time" \
+ --positions all --tensors l_out ffn_out --top-k 0 --save run1.npz
+
+ # where does the token "cat" rank, and what are the model's top candidates?
+ python3 tools/ps5lm-introspect.py --host 192.168.1.50 --prompt "The animal sat on the" \
+ --positions last --top-k 20 --rank-of cat
+
+ # chat: the prompt is rendered with the model's own chat template
+ python3 tools/ps5lm-introspect.py --host 192.168.1.50 --messages user=hello --positions last \
+ --n-predict 8 --tensors l_out --layers 20 --save chat.npz
+
+The endpoint is POST /v1/introspect on the console's llama-server (port 8081). Everything
+that arrives as base64 float32 is decoded here; --save writes one .npz with arrays named
+"logits_<index>", "act_<tensor>_<index>" plus the metadata as JSON under "meta".
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import sys
+import urllib.error
+import urllib.request
+
+try:
+ import numpy as np
+except ImportError: # numpy is only needed for --save and array prints
+ np = None
+
+
+def post(url: str, body: dict, timeout: float) -> dict:
+ data = json.dumps(body).encode()
+ req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return json.loads(resp.read())
+ except urllib.error.HTTPError as e:
+ detail = e.read().decode("utf-8", "replace")
+ raise SystemExit(f"{e.code} from the server: {detail[:2000]}")
+
+
+def floats(b64: str):
+ raw = base64.b64decode(b64)
+ if np is not None:
+ return np.frombuffer(raw, dtype="<f4")
+ import array
+
+ a = array.array("f")
+ a.frombytes(raw)
+ return a
+
+
+def build_request(args) -> dict:
+ spec: dict = {}
+ if args.top_k or args.full or args.entropy:
+ spec["logits"] = {
+ "top_k": args.top_k,
+ "entropy": args.entropy,
+ "probs": args.probs,
+ "full": args.full,
+ "max_full_rows": args.max_full_rows,
+ }
+ spec["positions"] = (
+ "all" if args.positions == "all" else "last" if args.positions == "last" else [int(x) for x in args.positions.split(",")]
+ )
+ if args.tensors:
+ layers = [int(x) for x in args.layers] if args.layers else "all"
+ spec["activations"] = {"tensors": args.tensors, "layers": layers}
+ spec["generated"] = not args.no_generated
+
+ if args.intervention:
+ ivs = []
+ for raw in args.intervention:
+ iv = json.loads(raw)
+ if "tensor" not in iv:
+ raise SystemExit(f"an --intervention needs a tensor: {raw!r}")
+ iv.setdefault("layers", [int(x) for x in args.layers] if args.layers else [])
+ if not iv["layers"]:
+ del iv["layers"]
+ ivs.append(iv)
+ spec["interventions"] = ivs
+
+ body: dict = {"n_predict": args.n_predict, "introspect": spec}
+ if args.messages:
+ msgs = []
+ for m in args.messages:
+ if "=" not in m:
+ raise SystemExit(f"--messages needs role=text, got {m!r}")
+ role, text = m.split("=", 1)
+ msgs.append({"role": role, "content": text})
+ body["messages"] = msgs
+ else:
+ body["prompt"] = args.prompt
+ if args.temperature is not None:
+ body["temperature"] = args.temperature
+ if args.raw_json:
+ body.update(json.loads(args.raw_json))
+ return body
+
+
+def show_logits(e: dict, args) -> None:
+ lg = e.get("logits")
+ if not lg:
+ return
+ am = lg["argmax"]
+ line = f" argmax {am['piece']!r} (id {am['id']}, logit {am['logit']:.3f}"
+ line += f", p={am['prob']:.3f})" if "prob" in am else ")"
+ if "entropy" in lg:
+ line += f" entropy {lg['entropy']:.3f} nats"
+ print(line)
+ top = lg.get("top") or []
+ if top:
+ shown = ", ".join(f"{t['piece']!r}:{t['logit']:.2f}" for t in top[: args.print_top])
+ print(f" top: {shown}")
+ if args.rank_of:
+ if "full" not in lg:
+ print(" --rank-of needs --full (the whole vocabulary row)")
+ else:
+ row = floats(lg["full"]["data"])
+ target = None
+ for t in lg.get("top") or []:
+ if t["piece"] == args.rank_of:
+ target = t["id"]
+ if target is None:
+ print(f" rank of {args.rank_of!r}: token not among the top; use --print-top to widen")
+ else:
+ rank = int((row > row[target]).sum()) + 1
+ print(f" rank of {args.rank_of!r}: {rank} of {len(row)} (logit {row[target]:.3f})")
+
+
+def save_npz(path: str, doc: dict) -> None:
+ if np is None:
+ raise SystemExit("--save needs numpy (pip install numpy)")
+ it = doc["introspection"]
+ out = {"meta": json.dumps(it["meta"]), "inputs": json.dumps(it["inputs"])}
+ for e in it["positions"]:
+ idx = e["index"]
+ lg = e.get("logits") or {}
+ if "full" in lg:
+ out[f"logits_{idx}"] = floats(lg["full"]["data"])
+ for name, t in (e.get("activations") or {}).items():
+ out[f"act_{name}_{idx}"] = floats(t["data"])
+ np.savez_compressed(path, **out)
+ print(f"saved {path}: {', '.join(sorted(out)[:6])}{' …' if len(out) > 6 else ''}")
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--host", default="127.0.0.1", help="console address (default 127.0.0.1)")
+ p.add_argument("--port", type=int, default=8081, help="llama-server port (default 8081)")
+ p.add_argument("--path", default="/v1/introspect")
+ src = p.add_mutually_exclusive_group(required=True)
+ src.add_argument("--prompt", help="raw prompt text")
+ src.add_argument("--messages", nargs="+", help="chat turns as role=text, rendered with the model's template")
+ p.add_argument("--n-predict", type=int, default=0, help="tokens to generate and capture (default 0)")
+ p.add_argument("--positions", default="last", help='"last", "all", or a comma-separated index list')
+ p.add_argument("--top-k", type=int, default=10, help="top candidates per position (0 = none)")
+ p.add_argument("--print-top", type=int, default=8, help="how many candidates to print")
+ p.add_argument("--entropy", action="store_true", help="include the entropy of the distribution")
+ p.add_argument("--probs", action="store_true", default=True, help="include probabilities (default)")
+ p.add_argument("--full", action="store_true", help="include the whole vocabulary row per position")
+ p.add_argument("--max-full-rows", type=int, default=8, help="cap on full rows in one answer")
+ p.add_argument("--rank-of", help="report the rank of this token piece when --full is used")
+ p.add_argument("--tensors", nargs="*", default=[], help="activation tensors, e.g. l_out ffn_out attn_out attn_norm result_norm")
+ p.add_argument("--layers", nargs="*", default=[], help="layer indices for the activations (default: all)")
+ p.add_argument("--no-generated", action="store_true", help="do not capture the generated tokens")
+ p.add_argument("--intervention", action="append", metavar="JSON",
+ help='change an activation in place, e.g. \'{"tensor":"ffn_out","channels":[3456],"op":"zero"}\'; '
+ 'repeatable, and --layers fills in the layer list when the object has none')
+ p.add_argument("--temperature", type=float, default=0.0, help="sampling temperature (0 = greedy)")
+ p.add_argument("--raw-json", help="extra request fields as JSON, merged last")
+ p.add_argument("--save", help="write the arrays to this .npz")
+ p.add_argument("--json", action="store_true", help="print the whole response as JSON")
+ p.add_argument("--timeout", type=float, default=600.0)
+ args = p.parse_args()
+
+ url = f"http://{args.host}:{args.port}{args.path}"
+ body = build_request(args)
+ doc = post(url, body, args.timeout)
+
+ if args.json:
+ json.dump(doc, sys.stdout, indent=2)
+ print()
+ return 0
+
+ it = doc.get("introspection")
+ if it is None:
+ print("no introspection in the answer; keys:", list(doc.keys()))
+ return 1
+
+ meta = it["meta"]
+ print(
+ f"{meta['model'].rsplit('/', 1)[-1]}: {meta['n_layer']} layers, vocab {meta['n_vocab']}, "
+ f"context {meta['n_ctx']}, prompt {meta['n_prompt']} tokens, build {meta['build']}"
+ )
+ for e in it["positions"]:
+ kind = "generated" if e["generated"] else "prompt"
+ acts = ", ".join(f"{n}{t['shape'][:1]}" for n, t in (e.get("activations") or {}).items())
+ print(f"position {e['index']} ({kind}) {e['piece']!r}" + (f" activations: {acts}" if acts else ""))
+ show_logits(e, args)
+ if it.get("truncated"):
+ print("note: the answer hit the server's activation budget and dropped some tensors")
+ for iv in (it.get("interventions") or []):
+ print(f"intervention {iv['op']} {iv['tensor']}"
+ + (f" layers {iv['layers']}" if iv.get("layers") not in (None, "all") else "")
+ + (f" channels {iv['channels']}" if iv.get("channels") else "")
+ + f": modified {iv['modified']}" + (" (nothing matched!)" if iv["modified"] == 0 else ""))
+ if "content" in doc and doc["content"]:
+ print(f"generated: {doc['content']!r}")
+ if args.save:
+ save_npz(args.save, doc)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())