> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sglang.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Activation monitors

> Compute native monitor scores or export activation features to a sidecar.

Activation monitors reduce selected residual activations on the serving GPU.
Choose how you compute and deliver scores:

| Mode | Configuration | Delivery |
| - | - | - |
| Native scoring | `--activation-monitors` | Scores accompany tokens in `/generate` and `Engine.generate` |
| Sidecar scoring | `--activation-monitor-sidecar-probes` and `--activation-monitor-sidecar-endpoint`, plus the score service | Scores arrive through `/v1/monitor_scores/{rid}`, separately from `/generate` |

Both modes share activation capture and checkpoint computation primitives. Each
is enabled independently; enabling export does not enable native scoring. The
caller owns thresholds and any action taken on a score.

> [!NOTE]
>
> Activation monitors are not yet in SGLang's main branch or a release. Use the `lmsysorg/sglang:project-iris` Docker image, or build from the [`iris` branch](https://github.com/sgl-project/sglang/tree/iris).

## Currently supported

### Capabilities

| Capability | Native scoring | Sidecar scoring |
| - | - | - |
| Stateless probes | ✅ | ✅ |
| Stateful probes | ❌ | ✅ |
| Eager execution and CUDA graphs | ✅ | ✅ |
| Aggregate serving and tensor parallelism | ✅ | ✅ |
| Speculative decoding | ✅ | ✅ |
| Disaggregation (PD) | ❌ | ✅ Mooncake and NIXL, matching attention-TP sizes |

Supported speculative algorithms are EAGLE, EAGLE3, STANDALONE and DFLASH.

## Configure a native monitor

```bash theme={null}
python -m sglang.launch_server \
  --model-path "$MODEL_ID" --revision "$MODEL_REVISION" --tp 1 \
  --activation-monitors '[{"name":"probe","factory":"sglang.srt.activation_monitors.linear:create_linear_monitor","config":{"checkpoint":"/models/probe"}}]'
```

Factories are trusted, operator-installed Python code loaded at startup. Requests
cannot select a factory or load weights. Names must be unique. Omitting
`--activation-monitors`, or passing `[]`, disables monitors.

Validate monitor scores for the served weights and precision; weight updates
require a restart. Scores can vary with batch and cache
shapes in reduced precision. Persistent buffers are reserved before KV-cache
sizing; leave temporary workspace headroom with `--mem-fraction-static`.

Set `base_model.id` to `null` to allow different model repositories. Omit
`base_model.revision` or set it to `null` to allow different revisions. Non-null
IDs and revisions are checked exactly. Validate score quality for each deployed
checkpoint and precision; matching tensor shapes is not sufficient.

A linear checkpoint contains `config.json` and its safetensors weights. Example
`config.json` (use the model identity, taps, and normalization from training):

```json theme={null}
{
  "format_version": 1,
  "architecture": "linear",
  "base_model": { "id": "MODEL_ID", "revision": "MODEL_COMMIT" },
  "weights": "model.safetensors",
  "weights_dtype": "float32",
  "tap_ids": ["layer.32.input"],
  "outputs": [{ "name": "risk", "score_type": "logit" }],
  "normalization": { "type": "per_tap_standardization" }
}
```

For a pointwise GELU MLP, use
`sglang.srt.activation_monitors.mlp:create_mlp_monitor` with this checkpoint format:

```json theme={null}
{
  "format_version": 1,
  "architecture": "mlp",
  "base_model": { "id": "MODEL_ID", "revision": "MODEL_COMMIT" },
  "weights": "model.safetensors",
  "tap_ids": ["layer.30.input"],
  "outputs": [{ "name": "risk", "score_type": "logit" }],
  "hidden_size": 4096,
  "feature_size": 128,
  "compute_dtype": "bfloat16",
  "normalization": {
    "type": "rms_norm", "epsilon": 1e-6,
    "input_dtype": "bfloat16", "output_dtype": "bfloat16"
  }
}
```

Its FP32 tensors are `input_norm.weight`, `feature.weight`, `feature.bias`,
`readout.weight`, and `readout.bias`. Omit `normalization` and `input_norm.weight`
for a checkpoint trained without normalization.

## Request native scores

Monitors run on every target forward; the request flag controls score delivery,
not computation.

```bash theme={null}
curl http://localhost:30000/generate \
  -H 'Content-Type: application/json' \
  -d '{"text":"Hello","sampling_params":{"temperature":0,"max_new_tokens":2},"return_activation_monitors":true}'
```

The native Python API accepts the same opt-in:

```python theme={null}
result = engine.generate(
    "Hello",
    {"temperature": 0, "max_new_tokens": 2},
    return_activation_monitors=True,
)
scores = result["meta_info"]["activation_monitors"]
```

A non-streaming response contains the following shape under
`meta_info.activation_monitors` (values here are illustrative):

```json theme={null}
{
  "probe": {
    "outputs": [{ "name": "risk", "score_type": "logit" }],
    "status": "ok",
    "scores": [[1.7], [2.1]]
  }
}
```

With `stream: true`, each chunk contains new rows and a zero-based `token_start`;
output descriptors appear in the first chunk (a later chunk is shown here):

```json theme={null}
{
  "probe": {
    "token_start": 1,
    "status": "ok",
    "scores": [[2.1]]
  }
}
```

Row `k` scores the position that predicts output token `k`, like output-token
logprobs; row zero scores the last prompt position. `Engine.async_generate` uses
the same format. Zero-token output has an empty score list.

Speculative decoding returns scores from the accepted target path, including its
bonus prediction. Rejected candidates and tokens clipped by stopping are omitted.

An unavailable or nonfinite row is `null`, never a fabricated score. `status` is
`ok`, `partial`, or `unavailable`; missing rows also carry a `reason`. Asking for
scores on a server without monitors is an error. Requests that omit the opt-in
retain their existing response format.

Invalid host-side score payloads are logged and discarded without aborting token
generation; missing rows remain unavailable. GPU execution and monitor-state errors
retain normal engine error handling.

## Sidecar feature export

Use a stateless `linear` / `mlp` or stateful `mingru` / `local_attention_mingru`
checkpoint at `/models/probe`:

```bash theme={null}
python -m sglang.launch_server \
  --model-path "$MODEL_ID" --revision "$MODEL_REVISION" --tp 1 \
  --activation-monitor-sidecar-probes '[{"name":"probe","checkpoint":"/models/probe"}]' \
  --activation-monitor-sidecar-endpoint tcp://127.0.0.1:5557
```

Stateless probes export completed scores from the serving GPU; stateful probes
export reduced features for the consumer to score. The endpoint is a ZeroMQ consumer address,
not an HTTP score API. The exporter
does not wait for scoring or gate token delivery. `return_activation_monitors`
only requests native scores; it does not retrieve results from the consumer.
Each engine exporter has a **512 MiB** queue limit
(`--activation-monitor-sidecar-queue-bytes`) and reports gaps and overflow to the consumer.

Cached tokens carry a 16-byte computation ID shared by all exported probes.
The ID follows full-token KV through moves, CPU backup, PD and HiCache; recomputing
the same tokens produces new IDs. This identifies the history used by each
forward without storing recurrent probe state on the engine. Export and service
must use the same wire-protocol version.

PD workers export to the same consumer. HiCache L2 and Mooncake L3 preserve these
IDs with cached KV; recurrent probe state stays in the consumer. LoRA with PD or
the Rust frontend remains unqualified.

With `--enable-unified-memory`, the IDs belong to the full-attention pages of the
unified KV arena and move with them. Unified HiCache L2 also carries IDs in
page envelopes used by DFLASH and MXFP8 KV. These combinations
remain unsupported with L3 storage; `page_unified` host layout is unsupported.

## Sidecar score service

For a single scorer, start the consumer before the engine, using the same probe
names and checkpoints. This example uses a caller-supplied ID and reads directly
from that scorer.

```bash theme={null}
CUDA_VISIBLE_DEVICES=0 \
python -m sglang_activation_monitor_sidecar \
  --monitor probe=/models/probe \
  --feature-endpoint tcp://127.0.0.1:5557 --host 127.0.0.1 --port 8001 \
  --device cuda:0
```

Generation and score delivery are independent; use a unique `rid` to join them
and omit `return_activation_monitors` for sidecar-only requests:

```bash theme={null}
curl http://localhost:30000/generate \
  -H 'Content-Type: application/json' \
  -d '{"rid":"probe-example-1","text":"Hello","sampling_params":{"max_new_tokens":2}}'
```

**Nonstreaming:** `GET /v1/monitor_scores/{rid}?since=0` returns a snapshot; poll
with its `cursor` as `since` until `complete` is true and `has_more` is false:

```json theme={null}
{
  "rid": "probe-example-1",
  "scorer_instance_id": "673d99b44d224ccba293a674097e589b",
  "status": "completed",
  "complete": true,
  "reason": null,
  "offset": 0,
  "cursor": "5da8d57397cb496a9f156216ea4101f6:2",
  "invalid_from": null,
  "output_length": 2,
  "has_more": false,
  "monitors": {
    "probe": {
      "outputs": [{"name": "risk", "score_type": "logit"}],
      "scores": [[1.7], [2.1]],
      "valid": [true, true]
    }
  }
}
```

**Streaming:** `GET /v1/monitor_scores/{rid}/stream?since=0` sends the same payload
in `scores` SSE events, followed by `[DONE]`; reconnect with the last `cursor`:

```text theme={null}
event: scores
data: {"rid":"probe-example-1","scorer_instance_id":"673d99b44d224ccba293a674097e589b","status":"completed","complete":true,"reason":null,"offset":0,"cursor":"5da8d57397cb496a9f156216ea4101f6:2","invalid_from":null,"output_length":2,"has_more":false,"monitors":{"probe":{"outputs":[{"name":"risk","score_type":"logit"}],"scores":[[1.7],[2.1]],"valid":[true,true]}}}

data: [DONE]
```

Rows use native output-token alignment. Check `valid`, `status`, `reason` and
`invalid_from`: completion can include unavailable scores. Unknown or expired IDs
return HTTP 404; use a client deadline. `--retain-seconds` controls result retention;
`--max-score-streams` and `--max-snapshot-operations` bound HTTP concurrency.

Token streaming uses `/generate` with `stream: true`. To withhold tokens until
scores arrive, buffer a contiguous scored prefix in your client and handle
unavailable scores and timeouts explicitly.

History and results live in the scorer process. KV computation IDs select the
matching history; missing or evicted history makes scores unavailable.
`scorer_instance_id`, also returned by `/health`, changes on restart: undelivered
scores from the old instance are lost.

#### Score lookups across serving replicas

When independent launchers each run `--sidecar sglang_activation_monitor_sidecar`,
omit `rid` from the generation request. Use the returned `meta_info.id` from
`/generate` to read scores through any replica. For a standard single-choice
OpenAI chat or completion response that preserves the generation ID, use its
top-level `id`. Caller-supplied IDs such as `probe-example-1`
and IDs from an engine with a separately started scorer resolve locally. Each
scorer must be able to reach its peers on their private HTTP ports. Replicas
that share a single scorer already read the same scores.

To enable forwarding, mount your deployment's scorer list read-only at
`/etc/sglang/monitor-replicas` before starting the launchers, or pass
`--replica-file PATH` in the sidecar arguments. List one scorer IP and HTTP
port per line, as in this three-replica example.

```text theme={null}
10.0.0.7:8001
10.0.0.8:8001
[fd00::9]:8001
```

Have the deployment update this file atomically as replicas join or leave.
The launcher derives the owner ID from the advertised IP and port. With a wildcard
listener the launcher detects the IP or uses `SGLANG_HOST_IP`. If the address
other replicas use differs from the listener (for example, a remapped port),
pass `--advertise-address 10.0.0.7:9001` in that launcher's sidecar arguments
and list that address in the file. The scorer warns at startup if it cannot
find its advertised address in the file. With forwarding enabled it listens
on all interfaces by default, so restrict the scorer port to the deployment's
private network.

When A generates a response, its request ID includes A's owner ID. A serves
its own score GETs locally. When B receives the GET, it looks up that owner in
its current scorer list and forwards one GET to the listed address. This also
works for paginated reads and live streams resumed with a cursor.

An unlisted owner gets the usual local lookup, which returns 404 for an
unknown request. If B cannot read the membership file or connect to a listed
owner, it returns 503. Scores remain available while the owner retains them.
Without a configured replica file, score reads use the local scorer.

#### Input-token scores

Input delivery is off by default. Add `--activation-monitor-sidecar-input-scores`
to the engine command (both roles for PD). Use the same `rid` supplied to
`/generate` above (`probe-example-1` in this example). Choose either:

```bash theme={null}
# Fetch a snapshot.
curl 'http://localhost:8001/v1/monitor_scores/probe-example-1?scope=input&since=0&limit=1024'

# Stream updates; -N disables curl's output buffering.
curl -N 'http://localhost:8001/v1/monitor_scores/probe-example-1/stream?scope=input&since=0&limit=1024'
```

#### Size the history store

The default **9 GiB** history budget (`--state-store-bytes`) includes 8 GiB for
recurrent history and 1 GiB for input scores. The scorer protects up to half of
recurrent history for likely restart points, including rows before the
originating engine's KV page boundaries and successfully reused history. The rest uses LRU; unused protected capacity remains available to other
rows. Set `--state-store-protected-fraction` (default `0.5`) to adjust the maximum,
or `0` for plain LRU. Engines without page-size metadata retain LRU insertion.
This changes retention priority, not score computation or engine KV eviction.

When you change the total budget, the scorer reserves up to 1 GiB of the
space above 8 GiB for input scores. Use `--input-score-cache-bytes` to override
that split, or set it to `0` to disable the archive. Only requests with
input scoring enabled write to the archive. The scorer archives
complete, aligned runs of 64 consecutive computation IDs within a scoring
batch. Each block stores the token IDs and all probes' FP32 score columns.
Partial blocks can still be served from recurrent history while it is retained.

Set `--engine-cacheable-tokens` to the engine's GPU KV capacity plus HiCache host
capacity, counting logical token slots once across TP ranks. The service logs the
remaining recurrent capacity in token records and warns if it is too small or
the engine capacity is unknown. Accounting includes every configured probe and
packed-record overhead. Update this flag when engine caches change.

Allow headroom: the two stores evict independently, so sufficient capacity does
not guarantee that all reused KV has scoring history. Alert on increases in
`store_evictions_total`; monitor `store_bytes` and `store_entries`. Eviction can
lose history without a restart. Request state has a separate **2 GiB** limit
(`--request-state-bytes`). Allow additional process memory for transport buffers
and runtime allocations.

#### Recover after history loss

Recovery supports one Python engine replica and tokenizer worker (TP and HiCache
L2 allowed). Close external ingress, including generation health checks, and
restart the scorer with the same configuration. Keep ingress closed while running:

```bash theme={null}
python -m sglang_activation_monitor_sidecar recover \
  --engine-url http://localhost:30000 \
  --scorer-url http://localhost:8001 \
  --previous-instance-id "$PREVIOUS_SCORER_INSTANCE_ID" \
  --ingress-paused --policy fail-closed --timeout 300
```

The helper aborts active requests, waits for a new scorer and for local caches to
flush, then runs cold and warm canaries. Both must produce identical tokens and
complete, valid, finite scores of the expected width for every configured probe,
from the same new scorer instance. The cold run must miss the cache and the warm
run must hit it; the warm-hit check is skipped and reported when radix caching is
disabled.

Cold/warm scores may differ. The result reports the maximum absolute difference
per probe; optionally set `--max-score-diff` to enforce a limit in logits. No score
difference limit applies by default. Use `--policy fail-open` to drain generation
before aborting. Reopen ingress only after success; on failure, keep it closed.
API keys use `SGLANG_API_KEY` and `SGLANG_ADMIN_API_KEY`. Pausing and resuming
generation require the admin key, so start the engine with `--admin-api-key` and
supply `SGLANG_ADMIN_API_KEY`; with HiCache enabled, the helper also uses it to
check that no L3 backend is attached.

PD and L3 serving are supported, but this helper cannot coordinate recovery across
workers: PD needs every participant paused and flushed, and L3 also needs its
shared KV/computation-ID namespace invalidated or rotated before resuming.
A local flush or engine restart does not clear L3. For eviction, fix history-store
capacity or cache reuse before resuming.

With bundled `--sidecar`, the default `terminate` policy exits the engine when
the scorer dies; restarting both clears their volatile caches. The `ignore`
policy does not restart the scorer.

## Implement another native monitor

Implement the `ActivationMonitor` protocol in
`sglang.srt.activation_monitors.base`. Declare named taps and outputs plus an
identity containing implementation version and weight/configuration SHA-256
digests. Allocate persistent buffers in `allocate`. `on_tap` receives borrowed,
read-only activations and must reduce them before returning; retaining or modifying
them is unsupported. `run` writes into the supplied score and validity buffers.
CUDA graph paths require capture-safe operations and stable buffer addresses.

Models opt in through
`ResidualCaptureModel` and dispatch full residuals before each layer and the final
norm through `AuxHiddenStateList`. The runtime derives tap descriptors and attaches
a consumer; speculative capture and monitors share the same model boundaries.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.