Skip to content
Valentin Noël

API reference

Every name below is importable from spectral_trust (import spectral_trust as st), except where a module path is shown.

High-level API

SpectralModel

SpectralModel(model, tokenizer=None, config=None, name=None)

A Hugging Face causal LM that returns spectral measurements of its attention graphs, in the style of TransformerLens' HookedTransformer.

Examples:

>>> model = SpectralModel.from_pretrained("Qwen/Qwen3-0.6B")
>>> cache = model.run_with_spectra("The cat sat on the mat because it was warm.")
>>> cache.layer(10).head(3)

The model is used as it is: no weights are changed and no hooks are added; it is put in eval mode. Its attention must be the eager implementation, the only one that returns attention weights; from_pretrained loads it that way and switches an already-loaded model to it.

Attributes:

Name Type Description
model

the wrapped PreTrainedModel.

tokenizer

its tokenizer.

config

the GSPConfig used for graph construction (symmetrisation, normalisation, HFER cutoff, ...).

n_layers property

n_layers

Number of decoder layers, from the model config.

n_heads property

n_heads

Attention heads per layer, from the model config.

from_pretrained classmethod

from_pretrained(name_or_model, tokenizer=None, config=None, device=None, dtype='float32', **hf_kwargs)

Load a Hugging Face causal LM with eager attention, or wrap one.

Parameters:

Name Type Description Default
name_or_model

a model id or local path, or an already-loaded PreTrainedModel (then pass its tokenizer; when it is omitted it is loaded from the model's name_or_path).

required
tokenizer

the tokenizer of an already-loaded model.

None
config Optional[GSPConfig]

graph-construction settings; default default_config.

None
device Optional[Union[str, device]]

where to put a model loaded here ("cpu", "cuda"); default: where from_pretrained leaves it.

None
dtype Union[str, dtype, None]

weights dtype for a model loaded here (default float32).

'float32'
**hf_kwargs

passed to AutoModelForCausalLM.from_pretrained (for example revision, local_files_only, trust_remote_code, device_map); the ones that apply to tokenizers are passed to AutoTokenizer as well.

{}

to_str_tokens

to_str_tokens(text)

The token strings of text, as SpectralCache.tokens holds them (each id decoded on its own).

run_with_spectra

run_with_spectra(text_or_list, metrics=None, layers=None, heads=None, token_span=None, hybrid=True, batch_size=8, keep_patterns=None)

Run the model once and return its spectral measurements.

Parameters:

Name Type Description Default
text_or_list TextInput

a string, a list of strings, or token ids ([seq] or [batch, seq] tensor, or a list of id lists). Strings are tokenised with the model's tokenizer as it is configured (special tokens included), with no truncation.

required
metrics

which metrics to keep. None keeps all but the opt-in operator namespace. Entries may be a namespace ("attn", "resid", "graph", "operator"), a namespaced name ("graph.hfer") or a bare name, which selects it in every namespace ("fiedler_value" gives attn.fiedler_value and graph.fiedler_value). A namespace that is not selected is not computed.

None
layers Optional[Sequence[int]]

true layer indices to measure (negative values count from the end); default every layer that returns attention.

None
heads HeadSelection

heads for the per-head namespaces attn and resid, as in per_head_metrics: indices, (layer, head) pairs, or a boolean [heads] or [layers, heads] mask (true layer indices). Heads not computed are NaN. The graph namespace always averages every head.

None
token_span

(start, end) tokens to measure, with slice semantics ((-5, None) is the last five tokens). The induced subgraph is taken before the Laplacian is built. With GSPConfig(subgraph_renormalize=True) each head's kept rows are renormalised first, so token_span=(1, None) drops the BOS sink and renormalises (spectral_trust.graph.drop_and_renormalize).

None
hybrid bool

compute the metrics that read the hidden states (resid.* and the hybrid graph.* metrics). With False only attention-only metrics are computed.

True
batch_size int

texts per forward pass. Batches are right-padded, which leaves every real token's attention and hidden states unchanged in a causal LM (the padding is cropped before any measurement); results equal one-text runs to float32 rounding. Use 1 to run texts one at a time.

8
keep_patterns Optional[bool]

keep the raw attention in the cache, for spectral_trust.viz.graph. None keeps it when it takes at most 64 MB.

None

Returns:

Type Description
SpectralCache

class:SpectralCache. Keys look like

SpectralCache

"blocks.10.attn.fiedler_value" (one value per head) and

SpectralCache

"blocks.10.graph.hfer" (head-averaged).

The graph namespace follows the graph options of config (edge_weights, graph_direction; see compute_spectra), and the operator namespace its operator options (operator_measure, operator_heads, operator_edges). For value-weighted edges the forward pass also records each layer's value states and output projection (ValueCapture), which leaves the model's outputs unchanged.

SpectralCache

SpectralCache(records, tokens, layers, n_heads, metric_names, config=None, meta=None)

Spectral measurements of one text or a batch of texts, keyed like a TransformerLens ActivationCache.

cache["blocks.10.attn.fiedler_value"] is a [n_heads] array, cache["blocks.10.graph.hfer"] a float. For a batch, values gain a leading text dimension (stacked when the shapes agree, a list otherwise), and cache[i] is the cache of text i. cache["attn.fiedler_value", 10] is the same as cache["blocks.10.attn.fiedler_value"].

Iteration and len follow the keys, as for a dict. to_dataframe gives one row per (text, layer, head, metric); save and load keep everything in one .npz file with its metadata as JSON.

n_texts property

n_texts

Number of texts in the cache.

is_batch property

is_batch

True when the cache was built from a list of texts.

tokens property

tokens

Token strings: a list for one text, a list of lists for a batch.

texts property

texts

The input strings (None where the input was token ids).

layers property

layers

True layer indices present in the cache, ascending.

metric_names property

metric_names

Namespaced scalar metrics present, e.g. "attn.fiedler_value".

families property

families

Tensor family of every metric in metric_names.

heads property

heads

Heads computed in each layer (every head when heads=None).

token_span property

token_span

The (start, end) span of each text that the metrics cover (None for the whole sequence; per text for a batch).

keys

keys()

Every key present, in layer then namespace order.

text

text(i)

The cache of text i of a batch, as a single-text cache.

layer

layer(layer)

Every measurement of one layer: cache.layer(10).head(3).

metric

metric(name, text=0)

One metric over every layer of one text: [layers, n_heads] for the per-head namespaces, [layers] for graph (operator: either, after GSPConfig.operator_heads). Rows follow layers. A bare per-head name means attn.

to_dataframe

to_dataframe(metrics=None)

Long-format table: one row per (layer, head, metric), with a text_id column first for a batch. head is missing (<NA>) for the head-averaged graph metrics, and heads that were not computed are left out. Columns: [text_id], layer, head, metric, family, value.

save

save(path)

Write the cache to one .npz file: every array, plus the metadata (tokens, layers, heads, config) as JSON. Loading needs no pickle. Returns the path written (.npz is appended if missing).

load classmethod

load(path)

Read a cache written by save.

heatmap

heatmap(metric='fiedler_value', **kwargs)

Layers x heads heatmap of one metric (see spectral_trust.viz.heatmap).

graph

graph(layer, head=None, **kwargs)

Attention graph of one layer or head (see spectral_trust.viz.graph).

spectrum

spectrum(layer, head=None, **kwargs)

Laplacian spectrum of one layer or head (see spectral_trust.viz.spectrum).

animate

animate(kind='embedding3d', out='spectral.mp4', **kwargs)

Write an animated (.mp4, .webm, .gif) or interactive (.html) view to out (see spectral_trust.viz.animate). Added in 0.4.2.

cache.animate("embedding3d", "hero.mp4") cache.animate("waterfall", "waterfall.gif", theme="dark")

LayerSpectra

LayerSpectra(cache, layer)

Measurements of one layer of a SpectralCache.

layer["hfer"] is the head-averaged (graph) metric; layer.attn["fiedler_value"] and layer.resid["hfer"] are [n_heads] arrays; layer["attn.fiedler_value"] names the namespace explicitly. layer.head(3) selects one head.

attn property

attn

Per-head attention-only metrics, name -> [n_heads].

resid property

resid

Per-head hybrid metrics, name -> [n_heads].

graph property

graph

Head-averaged graph metrics, name -> value.

operator property

operator

Operator-spectrum metrics, name -> [n_heads] or one value (GSPConfig.operator_heads); empty unless they were computed.

eigenvalues property

eigenvalues

Spectrum of the head-averaged graph.

fiedler_vector property

fiedler_vector

Fiedler vector of the head-averaged graph (largest entry positive).

HeadSpectra

HeadSpectra(layer, head)

Measurements of one head: cache.layer(10).head(3).

head["fiedler_value"] resolves a bare name in attn or resid when only one of them has it; hfer exists in both, so write head["attn.hfer"] or head["resid.hfer"].

operator property

operator

Per-head operator metrics (empty when they were computed per layer, GSPConfig.operator_heads="mean").

eigenvalues property

eigenvalues

This head's Laplacian spectrum, ascending.

compute_spectra

compute_spectra(attentions, signals=None, *, tokens, lengths=None, n_layers=None, config=None, metrics=None, layers=None, heads=None, token_span=None, hybrid=None, keep_patterns=None, meta=None, edges=None, operator_edges=None)

Spectral measurements from attention tensors (and optionally the signals paired with each layer), as a SpectralCache.

This is the computation behind SpectralModel.run_with_spectra and every adapter; call it directly for tensors from any other source.

Parameters:

Name Type Description Default
attentions Mapping[int, Tensor]

true layer index -> attention weights [batch, heads, seq, seq] (or [heads, seq, seq]), row i the query.

required
signals Optional[Mapping[int, Tensor]]

true layer index -> the residual-stream states paired with that layer, [batch, seq, d]. Needed for the hybrid metrics.

None
tokens Sequence[Sequence[str]]

one list of token strings per batch item.

required
lengths Optional[Sequence[int]]

real length of each batch item (right padding is cropped); default the full sequence.

None
n_layers Optional[int]

number of layers of the model, for negative layers.

None
config Optional[GSPConfig]

graph construction (GSPConfig); default default_config.

None
metrics, layers, heads, token_span, hybrid, keep_patterns

as in SpectralModel.run_with_spectra. hybrid=None computes the hybrid metrics when signals are given.

required
meta Optional[Dict[str, Any]]

extra metadata stored in the cache.

None
edges Optional[Mapping[int, Tensor]]

true layer index -> edge weights for the graph namespace when config.edge_weights is not "attention": [batch, seq, seq] (value-weighted, summed over heads) or [batch, heads, seq, seq] (per head), from value_weighted_edges. SpectralModel.run_with_spectra computes them.

None
operator_edges Optional[Mapping[int, Tensor]]

the same for the operator namespace when config.operator_edges is not "attention"; default edges when both options agree.

None

The operator namespace (computed only when metrics names it) reads each layer's attention as an operator L²(μ) → L²(π) (spectral_trust.operator_spectra), after config.operator_measure, operator_heads and operator_edges. The rows of A are divided by their sums first: the span's own edges under token_span, the value-weighted attention for value edges, and float rounding otherwise.

graph.forman_curvature_mean (computed only when named) is the mean Forman curvature of the edges of the layer graph that the graph options build (spectral_trust.forman, weights config.forman_weights): directed on a directed graph, undirected on a symmetric one, with the quantiles of its edge curvatures in graph.forman_quantiles. A value-weighted symmetric graph holds raw norms: under "neg_log" it is replaced by (P + Pᵀ)/2, P the row-normalised value-weighted attention.

The graph namespace follows config.edge_weights and config.graph_direction. With graph_direction="directed" its metrics come from the magnetic Laplacian of the row-normalised operator (analyze_directed_layer), it gains graph.directed_tv (hybrid), and graph.phase (the phase of the lowest magnetic eigenvector) is stored in place of graph.fiedler_vector. Under token_span the directed operator is built from the span's own edges. The attn and resid namespaces always measure each head's symmetrised attention.

Adapters

from_transformer_lens

from_transformer_lens(cache, model=None, tokens=None, *, final_norm=True, attention_mask=None, config=None, metrics=None, layers=None, heads=None, token_span=None, hybrid=None, keep_patterns=None)

Spectral measurements from a TransformerLens ActivationCache.

Reads blocks.{l}.attn.hook_pattern ([batch, heads, query, key]) for every layer, and blocks.{l}.hook_resid_post when present, which is the signal paired with layer l for the hybrid metrics.

Examples:

>>> logits, tl_cache = model.run_with_cache(tokens)
>>> cache = st.from_transformer_lens(tl_cache, model, tokens)

Parameters:

Name Type Description Default
cache

the ActivationCache of run_with_cache (any mapping with these keys works).

required
model

the HookedTransformer or TransformerBridge, used for the token strings (to_str_tokens), the model name and the number of layers. Defaults to cache.model when the cache has one.

None
tokens

the tokens that were run: ids ([batch, seq] or [seq]), text (tokenised with the model's tokenizer), or token strings. Without it, tokens are labelled by position.

None
final_norm bool

pair the last layer with ln_final.hook_out when the cache holds it (TransformerBridge caches do). That is the tensor Hugging Face returns as its last hidden state, so the hybrid metrics equal SpectralModel.run_with_spectra on every layer. With False, or when the hook is absent, the last layer is paired with its hook_resid_post, the residual stream before the final norm. cache.meta["signal_source"] records the choice.

True
attention_mask

[batch, seq] mask of a right-padded batch; each item is cropped to its real length. Without it every item is measured over the whole sequence.

None
config, metrics, layers, heads, token_span, keep_patterns

as in SpectralModel.run_with_spectra.

required
hybrid Optional[bool]

compute the hybrid metrics; None (default) does when the cache holds hook_resid_post.

None
Notes

Attention patterns do not depend on TransformerLens' weight processing, so the attention metrics match a Hugging Face run of the same model. The residual stream does: center_writing_weights (on by default in HookedTransformer.from_pretrained) removes its mean. For hybrid metrics equal to a Hugging Face run, load with HookedTransformer.from_pretrained_no_processing or use TransformerBridge without compatibility mode.

from_nnsight

from_nnsight(attentions, hidden_states=None, *, model=None, tokens=None, layer_indices=None, final_norm=None, attention_mask=None, config=None, metrics=None, layers=None, heads=None, token_span=None, hybrid=None, keep_patterns=None)

Spectral measurements from tensors saved in an nnsight trace.

The model must run eager attention, so that its attention modules return their weights. For GPT-2:

Examples:

>>> from nnsight import LanguageModel
>>> lm = LanguageModel("gpt2", attn_implementation="eager", dispatch=True)
>>> attn, resid = [], []
>>> with lm.trace(prompt):
...     for block in lm.transformer.h:
...         attn.append(block.attn.output[1].save())   # weights [1, H, S, S]
...         resid.append(block.output.save())          # block output [1, S, d]
>>> cache = st.from_nnsight(attn, resid, model=lm, tokens=prompt)

The module paths are the Hugging Face ones (model.layers[i].self_attn for Llama, Qwen and Mistral). Modules must be read in execution order inside the trace, hence one loop over the blocks. lm.output with output_attentions=True, output_hidden_states=True works as well: pass its .attentions and .hidden_states.

Parameters:

Name Type Description Default
attentions Union[Sequence[Any], Mapping[int, Any]]

one saved attention tensor per attention layer, [batch, heads, seq, seq], as a list (layer order) or a {layer: tensor} dict. Saved values of any nnsight version are accepted (tensors, or proxies with .value).

required
hidden_states Optional[Union[Sequence[Any], Mapping[int, Any]]]

optional signals for the hybrid metrics: one per attention layer (block outputs, paired with the same layer), or n_layers + 1 of them in the Hugging Face convention (embeddings first; layer l is paired with entry l + 1), or a {layer: tensor} dict. Tuples (module outputs) are reduced to their first element.

None
model

the nnsight LanguageModel (or the Hugging Face model): its config gives the layer layout and the name, its tokenizer the token strings.

None
tokens

the input that was traced (text, ids or token strings).

None
layer_indices Optional[Sequence[int]]

true layer index of each entry of attentions when they are a list; default from the model config, as in attention_layer_indices.

None
final_norm

optional saved output of the final norm (lm.transformer.ln_f.output), paired with the last layer in place of its block output. That is what Hugging Face returns as the last hidden state, so the hybrid metrics of the last layer then equal SpectralModel.run_with_spectra.

None
attention_mask

[batch, seq] mask of a right-padded batch; each item is cropped to its real length.

None
config, metrics, layers, heads, token_span, keep_patterns

as in SpectralModel.run_with_spectra.

required
hybrid Optional[bool]

compute the hybrid metrics; None (default) does when hidden_states are given.

None

from_hf_outputs

from_hf_outputs(outputs, model_config=None, tokens=None, *, tokenizer=None, attention_mask=None, config=None, metrics=None, layers=None, heads=None, token_span=None, hybrid=None, keep_patterns=None)

Spectral measurements from a Hugging Face model output.

Examples:

>>> out = model(**inputs, output_attentions=True, output_hidden_states=True)
>>> cache = st.from_hf_outputs(out, model.config, inputs["input_ids"], tokenizer=tok)

Parameters:

Name Type Description Default
outputs

a ModelOutput (or a dict) with attentions and, for the hybrid metrics, hidden_states.

required
model_config

the model config, which locates the attention layers of hybrid models (layer_types); see attention_layer_indices. config.attention_layer_map overrides it.

None
tokens

the input ids (or text, or token strings).

None
tokenizer

decodes tokens into token strings.

None
attention_mask

[batch, seq] mask of a right-padded batch; each item is cropped to its real length.

None
config, metrics, layers, heads, token_span, keep_patterns

as in SpectralModel.run_with_spectra.

required
hybrid Optional[bool]

compute the hybrid metrics; None (default) does when the output holds hidden states.

None

Interventions

Added in 0.5.0, in the subpackage spectral_trust.interventions. The context manager st.intervene and st.patch, st.Patcher, st.PatchSpec, st.equal_count_bands, st.graph_filter, st.weight_snr and st.weight_svd_full are also top-level names. See the interventions tutorial.

intervene

intervene(model, config=None, tokenizer=None)

Edit a model with hooks; every edit is undone on exit.

Works on a SpectralModel or a plain Hugging Face causal LM (GPT-2, Llama, Qwen, Mistral, Gemma, GPT-NeoX, OPT layouts). Interventions on one model may be nested and closed in any order.

Examples:

>>> with st.intervene(model) as iv:
...     iv.resid(6).graph_filter("lowpass", cutoff=0.5, strength=0.8, causal=True)
...     iv.attention(9, 6).ablate("zero")
...     iv.weights(7).svd_scale(-0.05)
...     out = model.generate(ids, max_new_tokens=20)

Parameters:

Name Type Description Default
model

the model to edit.

required
config Optional[GSPConfig]

graph construction for the graph filters (default: the SpectralModel's config, or the library defaults).

None
tokenizer

for text references in AttentionSite.ablate (default: the SpectralModel's tokenizer).

None

Added in 0.5.0.

Intervention

Intervention(model, config=None, tokenizer=None)

Edits of one model, undone on close (or on leaving the with block). Create it with intervene.

Interventions on the same model may be nested and closed in any order.

Attributes:

Name Type Description
model

the Hugging Face model being edited.

edits List[Edit]

the active Edit objects, in registration order.

config

graph construction for the graph filters (the SpectralModel's config, or the library defaults).

close

close()

Undo every edit: remove the hooks, restore the weights bit for bit (other open interventions' weight edits are re-applied), and release the shared changes (eager attention, the wrapped attention function, the generation hooks) once no intervention holds them.

resid

resid(layer, site='post')

The residual stream after block layer (site="post", the library's pairing: hidden_states[layer + 1]) or before it (site="pre").

attention

attention(layer, head=None)

Attention heads of block layer (one head, a list, or None for all).

weights

weights(layer, module='mlp.down_proj')

A weight matrix of block layer by dotted path. The default "mlp.down_proj" resolves to the MLP output projection of architectures that name it differently (GPT-2 mlp.c_proj).

hook

hook(site, layer, fn)

A custom edit, fn(x) -> new x (or None to keep x), at a site: "resid_pre", "resid_post", "attn_out", "mlp_out" or "z", the equivalent of a TransformerLens forward hook. x holds the tokens of the current call only; under cached generation that is the new token.

sink_bias

sink_bias(layers, b, hub=0)

Add the constant b to every query's attention score (logit, before the softmax) toward the key at position hub (counted from the first real token: left padding is skipped) at layers, in every head. b < 0 moves attention away from the hub (by default the first token, usually the attention sink), b > 0 toward it.

Works through eager attention (switched on while the edit is active) on the additive attention mask, whose last dimension is the key length, so it holds under cached generation. b = 0 installs nothing: the model is unchanged. New after 0.5.2 (unreleased).

ResidSite

ResidSite(iv, layer, site)

The residual stream at one layer; see Intervention.resid.

add

add(vector, scale=1.0, positions=None)

Activation steering: add scale * vector to the residual stream at positions (absolute; default every position). vector is [d], or [S, d] with one row per absolute position.

graph_filter

graph_filter(kind='lowpass', cutoff=None, band=None, strength=1.0, graph='attention', causal=False, order=64, method='chebyshev', token_span=None, positions=None, precision='float64')

Graph-frequency steering along the token axis: X' = X + s (g(L) X - X) on the residual stream after this block.

The graph is this layer's head-averaged attention from the same forward pass, symmetrised and normalised as in GraphConstructor (graph="attention"), the chain graph over positions ("path", a positional baseline), an adjacency tensor, or a callable (attention, x) -> adjacency. The filter is computed in float64.

Parameters:

Name Type Description Default
kind str

"lowpass" (keep eigenvalues below cutoff), "highpass", "bandpass" or "bandstop" (with band=(lo, hi)), in eigenvalue units (the "sym" Laplacian's spectrum lies in [0, 2]).

'lowpass'
strength float

s; 0 is the identity, 1 applies the filter, negative values push away from it.

1.0
causal bool

False filters each position on the symmetric graph of the whole sequence, so position i reads later positions; use it for single forward passes. True filters position i on the graph of its prefix 0..i only (a lower-triangular operator), so generation with a KV cache gives the same output as recomputing the sequence, also under beam search (the filter's state follows the cache's reordering); at the last position the two filters agree. A cached generation step with causal=False raises, as does a cache cropped or reordered by anything other than beam search (assisted decoding, for example).

False
order int

Chebyshev degree (no eigendecomposition).

64
method str

"dense" applies the ideal band indicator through an eigendecomposition, for checks.

'chebyshev'
token_span

(start, end) tokens that form the graph and are edited (slice semantics); others are neither edited nor read. For example (1, None) leaves the first token, whose residual norm is often far larger than the others', out of the graph. The graph is built from the attention sub-block of the span (see filters). With causal=True the bounds must be absolute (non-negative or None).

None
positions Positions

edit only these absolute positions (the filter still reads every position of the graph); non-negative with causal=True.

None
precision str

"float64" (default; computed on the CPU when the model is on Apple MPS, which has no float64) or "float32", much faster on GPUs but noisier when the first token's residual dwarfs the others', as in GPT-2 (cached and recomputed generation then drift apart by about 0.2 logits).

'float64'

Padded positions (from a 2-D attention_mask passed as a keyword) are left out of the graph. Attention is switched to the eager implementation for the duration of the intervention.

Size of the edit: a UserWarning is issued, once per graph_filter call, when the relative edit ||X' - X|| / ||X|| (Frobenius norms over the edited positions of one sequence) exceeds GRAPH_FILTER_WARN_RELATIVE_EDIT (0.5). In the side-effect measurements on GPT-2 small and Phi-3-mini (use case "Graph-filter side effects"), causal low-pass edits up to 0.29 of the residual left greedy generation as clean as the unedited model, while high-pass and band-pass edits at strength 1 (0.72 to 1.16 of the residual) raised the next-token KL to 2.0 to 12.9 nats and made up to 90% of greedy continuations degenerate; norm-matched controls did comparable damage.

AttentionSite

AttentionSite(iv, layer, head)

Attention heads at one layer; see Intervention.attention.

head_outputs

head_outputs(inputs)

Per-head outputs z of the selected heads on inputs (text, texts or ids), [B, S, len(heads), d_head], with this intervention's current edits active. Inputs of different lengths are run one at a time and returned as a list. The state of causal filters (and of the current call) is kept across this forward pass.

ablate

ablate(mode='zero', reference=None, positions=None, seed=0, per_position=False)

Ablate the selected heads' outputs (z, before the output projection, so a head's whole contribution is replaced).

Parameters:

Name Type Description Default
mode str

"zero"; "mean": the mean of the head's output over every token of reference (or per absolute position with per_position=True); "resample": the head's output on a reference item, at the same absolute position. The item is drawn once per input item and kept for the life of the edit (seeded); the beams of one input share it. Repeated calls, cached generation and beam search therefore agree with recomputation. The reference must be at least as long as the inputs.

'zero'
reference

text, texts or ids to compute the replacement on (run once, now, with the edits registered so far; texts of different lengths are run one at a time, so no padding enters the mean), or a tensor of head outputs [R, S, len(heads), d_head] (or [len(heads), d_head] for "mean"). Required by "mean" and "resample".

None
positions Positions

ablate only at these absolute positions.

None

edit_pattern

edit_pattern(fn)

Edit the attention probabilities of the selected heads before they meet the values: fn(weights [B, len(heads), q, k], query_positions [q]) -> weights (TransformerLens hook_pattern). The output is rebuilt as weights @ values; this is checked against the model's own output once per module. Needs transformers >= 4.48 (the module-level eager_attention_forward).

remove_edges

remove_edges(key_mask, keep_sink=True, queries=None, renormalize=True, sink=0)

Remove attention edges of the selected heads.

Removed entries are set to zero. With keep_sink=True (the default) each edited row is then renormalised over its remaining non-sink keys while the sink entry (the first token, sink=0) keeps its value, so the row's sink mass is held fixed and the removed mass goes back to the content keys only. With keep_sink=False the row is renormalised over every remaining key, and with renormalize=False the entries are only zeroed.

The three choices send the removed mass to different places, and none of them is a pure edge ablation when the removed edges carry much of the row. Plain renormalisation hands most of it to the sink, which in trained models already holds a large share of every row. Holding the sink fixed hands it to the content keys that are left: each is multiplied by the row's non-sink mass before the edit divided by the non-sink mass kept. When the removed edges held most of that mass, the factor is large and the edit amplifies the few edges left. In the GPT-2 small IOI use case (removing the name movers' END edges to the names, 0.77 of those rows), the median factor on the kept edges was 13 (head 10.0), 55 (9.9) and 181 (9.6), and plain renormalisation raised the first token's share of the rows from 0.20 to 0.87. A UserWarning is issued, once per remove_edges call, when the factor of any edited row exceeds KEEP_SINK_WARN_FACTOR (10). In that regime, report the removed mass and compare the three choices.

Parameters:

Name Type Description Default
key_mask

which edges to remove (True = remove): [k] keys removed for every query, [S, S] (query, key) or [B, S, S] over absolute positions, or a callable (query_positions [q], n_keys) -> mask [q, k] or [B, q, k].

required
keep_sink bool

hold the sink entry fixed (see above). Removing the sink itself then raises; pass keep_sink=False for that.

True
queries Positions

edit only these absolute query positions (default every query).

None
renormalize bool

False only zeroes the entries (rows then sum to less than one).

True
sink int

position of the sink, counted from the first real token (left padding, read from a 2-D attention_mask keyword, is skipped).

0

A row whose non-sink keys are all removed keeps its sink entry and sums to less than one. A row in which every entry to remove is already zero is returned bit for bit.

WeightSite

WeightSite(iv, layer, module)

A weight matrix of one block; see Intervention.weights.

weight property

weight

The weight in nn.Linear orientation [out, in] (a view).

snr

snr()

sigma_1 / median(sigma) of the current weight (weight_snr).

svd_scale

svd_scale(alpha, k=None)

Rescale the singular values, sigma' = sigma (1 + alpha (sigma - mean) / std) (svd_scale_matrix). k limits the edit to the top k singular values; the bias, if any, is kept.

Edits of one parameter stack, in any number of interventions: each applies to the weight as the edits before it left it. Removing one rebuilds the parameter from its original value with the others re-applied in order, and removing the last one restores the original bit for bit.

Edit

Edit(owner, description)

One registered intervention. remove undoes it (closing the Intervention undoes all of them).

remove

remove()

Undo the edit. Every hook is removed and every undo step runs even if one of them fails; the first error is raised afterwards.

remove_edges_from_pattern

remove_edges_from_pattern(w, remove, sink, keep_sink=True, renormalize=True, warn_factor=KEEP_SINK_WARN_FACTOR)

Remove edges from attention probabilities w [B, H, q, k].

remove is a boolean mask broadcastable to w; sink [B] the sink key of each item. See AttentionSite.remove_edges. Rows in which no nonzero entry is removed are returned bit for bit. With keep_sink=True, one UserWarning is issued when the kept non-sink entries of any edited row are multiplied by more than warn_factor (None: never).

sink_bias

sink_bias(model, layers, b, hub=0)

Bias every query's attention score toward the hub key by b.

A context manager: with sink_bias(model, [4, 5], -2.0): ... adds the logit b to the attention score toward position hub (default the first token, the usual attention sink) in every head of layers, and undoes it on exit. See Intervention.sink_bias; inside an intervene block, iv.sink_bias(layers, b) combines it with other edits. New after 0.5.2 (unreleased).

patch

patch(model, clean, corrupt, site='resid_pre', layer=0, head=None, positions=None, *, band=None, basis='clean_attention', n_modes=None, seed=0, metric=None, tokenizer=None, config=None, forward_kwargs=None)

Patch one clean activation into the corrupt run.

Plain patching (band=None) replaces the activation at positions (default all) by its clean value, as a TransformerLens patching hook does. With band, only that band of graph frequencies along the token axis is taken from the clean run (see spectral_trust.intervene.patching): band=(lo, hi) integer mode indices in ascending eigenvalue order, or float eigenvalues; basis one of "clean_attention", "corrupt_attention", "path", "random" or a tensor; n_modes caps the band's size.

Examples:

>>> st.patch(model, clean, corrupt, site="resid_pre", layer=8)
>>> st.patch(model, clean, corrupt, site="head", layer=9, head=6, positions=[-1])
>>> st.patch(model, clean, corrupt, site="resid_pre", layer=8, band=(0, 4))

Returns:

Type Description

Patched logits [B, ...] ([1, ...] for one input), or

metric(logits). For many patches, use Patcher, which

runs the clean and corrupt inputs once.

Added in 0.5.0.

Patcher

Patcher(model, clean, corrupt, *, tokenizer=None, config=None, layers=None, sites=None, forward_kwargs=None)

Runs a clean and a corrupt input once, caches their activations, and patches clean activations into the corrupt run.

Examples:

>>> p = st.Patcher(model, clean_ids, corrupt_ids)
>>> logits = p.patch(site="resid_pre", layer=6)                 # plain
>>> logits = p.patch(site="resid_pre", layer=6, band=(0, 3))    # lowest 3 modes
>>> ld = p.patch_many([st.PatchSpec("resid_pre", l, band=b)
...                    for l in range(12) for b in st.equal_count_bands(16, 8)],
...                   metric=logit_diff)

Parameters:

Name Type Description Default
model

a SpectralModel or a Hugging Face causal LM.

required
clean, corrupt

text, texts or ids ([S] or [B, S]) of the same shape. Batches must not be padded.

required
tokenizer

for text inputs (default: the SpectralModel's).

None
config Optional[GSPConfig]

graph construction for the attention bases (default: the SpectralModel's config, or the library defaults). Its normalisation must be symmetric ("sym" or "none").

None
layers, sites

activations to cache up front (sites from CAPTURE_SITES, "pattern" for attention weights [B, H, S, S]). By default nothing is cached up front: each call of patch_many captures what its patches need that is not cached yet, in one more pair of forward passes.

required
forward_kwargs Optional[dict]

extra keyword arguments of every forward call (for example {"logits_to_keep": 1}).

None

The cached activations belong to the model as it was when they were captured. Every call checks a token of the model's state (each parameter's storage and in-place version counter, the forward hooks and the attention implementation) and raises if it changed, for example under a weight edit or inside an intervene block that was opened or closed since; refresh recaptures. Writes through param.data bypass the version counter and are not detected.

Attributes:

Name Type Description
clean_logits, corrupt_logits

logits of the two unpatched runs.

Added in 0.5.0.

refresh

refresh()

Drop every cached activation and basis, and rerun the clean and corrupt inputs on the model as it is now.

activation

activation(run, site, layer)

A cached activation of the "clean" or "corrupt" run (or site="pattern": attention weights [B, H, S, S]).

basis

basis(basis, layer, seed=0)

(eigenvalues [B, S] or None, U [B, S, S]), columns in ascending eigenvalue order (float64).

projector

projector(spec)

U_b U_b^T per batch item, [B, S, S] (None for plain patching).

patch_many

patch_many(specs, metric=None, batch_size=32)

Run many patches in batched forward passes of the corrupt input.

Returns metric values [len(specs), B] when metric (a function of logits [B, ...] returning [B]) is given, else the patched logits [len(specs), B, ...].

patch

patch(spec=None, *, metric=None, **kwargs)

One patch (a PatchSpec, or its fields as keywords). Returns the patched logits [B, ...], or metric(logits).

PatchSpec dataclass

PatchSpec(site='resid_pre', layer=0, head=None, positions=None, band=None, basis='clean_attention', n_modes=None, seed=0)

One patch: where, and which part of the activation.

Attributes:

Name Type Description
site str

"resid_pre", "resid_post", "attn_out", "mlp_out", or "z"/"head" (per-head outputs).

layer int

block index.

head Union[None, int, Sequence[int]]

head or heads for site="z" (None: all heads).

positions Positions

positions to patch (default all). With a band, the band-projected difference is added at these positions only.

band Band

None for plain patching, or (lo, hi): integer mode indices (ascending eigenvalue, slice semantics) or float eigenvalues.

basis Union[str, Tensor]

one of BASES, or an orthonormal tensor.

n_modes Optional[int]

keep the first n_modes modes of the band (lowest eigenvalue first); with basis="random" and no band, the subspace size.

seed int

seed of the random basis.

equal_count_bands

equal_count_bands(n_modes, k)

Split n_modes modes (ascending eigenvalue) into k contiguous bands of equal count (the first n_modes % k bands hold one more), as (lo, hi) index pairs. Bands are empty when k > n_modes.

select_modes

select_modes(n, band, eigenvalues, n_modes)

Indices of the band's modes among n modes in ascending eigenvalue order. Integer bounds are mode indices with slice semantics; float bounds are eigenvalues (lo <= lambda < hi, the top mode included when hi is at or above it). n_modes keeps the first (lowest) n_modes of them.

haar_basis

haar_basis(n, seed, item=0)

Haar-random orthonormal [n, n] (QR of a Gaussian with the signs of R's diagonal fixed), seeded by (seed, item).

graph_filter

graph_filter(x, attention=None, *, kind='lowpass', cutoff=None, band=None, strength=1.0, graph='attention', causal=False, order=64, method='chebyshev', config=None, token_span=None, precision='float64')

Filter a signal along the token axis on a graph (functional form of ResidSite.graph_filter).

Parameters:

Name Type Description Default
x Tensor

signal [S, d] or [B, S, d].

required
attention Optional[Tensor]

attention weights [H, S, S] or [B, H, S, S] (row i the query), needed by graph="attention".

None
kind str

"lowpass", "highpass", "bandpass" or "bandstop".

'lowpass'
cutoff Optional[float]

eigenvalue cutoff for low-pass and high-pass filters (the "sym" Laplacian's spectrum lies in [0, 2]).

None
band Optional[Tuple[float, float]]

(lo, hi) in eigenvalue units for band-pass and band-stop.

None
strength float

s in X + s (g(L) X - X).

1.0
graph GraphSpec

"attention" (head-averaged attention, symmetrised and normalised as in GraphConstructor), "path" (chain graph over positions), an adjacency tensor [S, S] / [B, S, S], or a callable (attention, x) -> adjacency.

'attention'
causal bool

filter each position on the graph of its prefix (see the module notes).

False
order int

Chebyshev degree.

64
method str

"chebyshev" (no eigendecomposition) or "dense" (ideal band indicator from a full eigendecomposition).

'chebyshev'
config Optional[GSPConfig]

graph construction; default the library defaults.

None
token_span

(start, end) with slice semantics: only these tokens form the graph and are edited; the others are left unchanged and are not read. The graph is built from the attention sub-block of the span (see the module notes).

None
precision str

"float64" (default; on Apple MPS computed on the CPU) or "float32" (faster on GPUs, noisier when one token's norm dwarfs the others'); see the module notes.

'float64'

Returns:

Type Description
Tensor

The filtered signal, same shape, dtype and device as x.

filter_coefficients

filter_coefficients(kind, cutoff=None, band=None, order=64, lambda_max=2.0)

Chebyshev coefficients [order + 1] of a filter on [0, lambda_max] (Jackson-damped band indicators, as in band_chebyshev_coefficients).

  • "lowpass": the band [0, cutoff);
  • "highpass": [cutoff, lambda_max];
  • "bandpass": [lo, hi);
  • "bandstop": one minus the band-pass. An empty band (lo == hi) gives exactly the identity.

A band edge at or above lambda_max includes the top of the spectrum.

filter_response

filter_response(lam, kind, cutoff=None, band=None, order=64, lambda_max=2.0)

The polynomial response g(lambda) the Chebyshev filter applies at eigenvalues lam (what method="chebyshev" does to each mode).

ideal_response

ideal_response(lam, kind, cutoff=None, band=None, lambda_max=2.0)

The ideal band indicator at eigenvalues lam (method="dense").

Eigenvalues are clipped to [0, lambda_max] (float rounding of the null modes and of the top of the spectrum). Bands are half-open, [lo, hi), except that an upper edge at or above lambda_max includes the top, as in the Chebyshev filter and band_energies.

attention_adjacency

attention_adjacency(attention, config, dtype=torch.float32)

Head-aggregated, symmetrised adjacency [B, S, S] from attention [B, H, S, S], as the measurements build it (in dtype). Filters need a symmetric graph built from attention, so the config's edge_weights and graph_direction must be the defaults.

path_adjacency

path_adjacency(n, batch=1, device=None, dtype=torch.float32)

Chain graph over n positions (edges i -- i+1 of weight 1), [batch, n, n]. Its Laplacian eigenvectors are cosines along the sequence (exactly the DCT-II basis for the combinatorial Laplacian).

laplacian64

laplacian64(adjacency, config, dtype=_F64)

GraphConstructor.construct_laplacian computed in float64 (or dtype), with the same formulas and the same handling of self-loops and isolated positions.

compute_placement

compute_placement(device, precision, method='chebyshev')

(dtype, device) the filter computes in, for a signal on device. float64 runs where the signal is, except on Apple MPS, which has no float64: there it runs on the CPU. method="dense" (an eigendecomposition, for checks) always runs on the CPU.

weight_snr

weight_snr(model, layer=None, module='mlp.down_proj', k=None)

Spectral SNR sigma_1 / median(sigma) of a weight matrix.

Two forms:

  • weight_snr(model, layer, module): the matrix at module (dotted path inside block layer; "mlp.down_proj" resolves to the MLP output projection of architectures that name it differently, such as GPT-2's mlp.c_proj), over the full spectrum. layer=None returns one value per layer as a numpy array, a layer sweep.
  • weight_snr(W) or weight_snr(W, k): a 2-D weight tensor. Without k, the full spectrum; with k, the fast top-k estimate of the 0.2.3 branch (lowrank_snr), which is what spectral-steering's layer search called as weight_snr(W, k=32).

Parameters:

Name Type Description Default
model

a SpectralModel, a Hugging Face model, or a 2-D weight tensor.

required
layer Optional[int]

block index for a model. For a tensor, a second positional argument is taken as k.

None
module str

dotted path inside the block (model form).

'mlp.down_proj'
k Optional[int]

number of top singular values for the fast estimate (tensor form); None uses the full spectrum.

None

Added in 0.5.0.

weight_svd_full

weight_svd_full(W)

Full thin SVD (U, S, Vh) of a weight matrix in float32 (torch.linalg.svd(W.float(), full_matrices=False)), as in the 0.2.3 branch. Added in 0.5.0.

svd_scale_matrix

svd_scale_matrix(W, alpha, k=None)

Singular-value rescaling of a matrix [out, in] (see the module notes). k rescales only the top k singular values and leaves the others as they are (the mean and standard deviation are still those of the full spectrum); k=None rescales all of them. Returns a new tensor in W's dtype and on its device.

The factor 1 + alpha * z_i (z_i the singular value's z-score) must stay positive for the edit to compress (alpha < 0) or amplify (alpha > 0) the dominant directions. Past alpha = -1 / z_max the largest singular value changes sign and grows instead; a warning is issued. The formula is applied as written, as in the reference code.

matrix_snr

matrix_snr(W)

sigma_1 / median(sigma) of a matrix, float32, full spectrum.

lowrank_snr

lowrank_snr(W, k=1)

The 0.2.3 branch's fast estimate: S[0] / S[len(S) // 2] of the top max(k, 16) singular values from torch.svd_lowrank (niter = max(4, k // 4)). The median is that of the computed top values, not of the full spectrum, so it is larger than matrix_snr's and the estimate is smaller; torch.svd_lowrank is randomised (seed torch for a fixed value).

edit_with_controls

edit_with_controls(model, inputs, readout, *, layer, edit='graph_filter', kind='lowpass', cutoff=1.0, band=None, causal=True, order=64, strengths=(0.25, 0.5, 1.0), controls=('permuted', 'path', 'scaling'), positions=None, source=None, modes=None, token_span=None, config=None, seed=0, max_relative_edit=None, progress=False)

Run an edit and its norm-matched controls over inputs.

Parameters:

Name Type Description Default
model

a Hugging Face causal LM or a SpectralModel.

required
inputs Sequence

token-id sequences, run one at a time.

required
readout Readout

readout(model, ids [1, S]) -> {name: value}, called with the edit installed (for example the summary of next_value_distribution).

required
layer int

block index.

required
edit str

"graph_filter" or "band_patch".

'graph_filter'
kind, cutoff, band, causal, order

the filter (graph_filter), as in ResidSite.graph_filter.

required
strengths Sequence[float]

s values; 0 is the identity.

(0.25, 0.5, 1.0)
controls Sequence[str]

any of "permuted", "path", "random" (band patch only) and "scaling".

('permuted', 'path', 'scaling')
positions Union[None, Sequence[int], Callable[[int], Sequence[int]], Sequence[Sequence[int]]]

positions edited (others are read by the filter but left unchanged): one list for every item, a list per item, or a function of the item index. Default all positions.

None
source Optional[Sequence]

band_patch: the source (clean) sequences, each of the same length as its input.

None
modes Optional[Tuple[int, int]]

band_patch: (lo, hi) mode indices of the band, in ascending eigenvalue order.

None
token_span Optional[Tuple[Optional[int], Optional[int]]]

(start, end) (slice semantics, non-negative): only these tokens form the graph, and positions outside it are neither read nor edited. (1, None) leaves out the first token, whose residual norm is often orders of magnitude above the others' (an attention sink); without it a low-pass filter spreads that token into every position.

None
config Optional[GSPConfig]

graph construction (default the SpectralModel's or the library defaults; the band patch needs "sym" or "none").

None
seed int

seed of the permutation and the random subspace (the item index is added).

0
max_relative_edit Optional[float]

strengths whose mean relative edit exceeds this are skipped (for example 0.3, the side-effect guard of the graph-filter use cases).

None

EditControlResult dataclass

EditControlResult(conditions, strengths, baseline, edited=dict(), relative_edit=dict(), skipped=list())

Readouts of edit_with_controls.

Attributes:

Name Type Description
conditions List[str]

"target" and the controls, in order.

strengths List[float]

the strengths run.

baseline List[Dict[str, float]]

per-item readout of the unedited model.

edited Dict[Tuple[str, float], List[Dict[str, float]]]

(condition, strength) -> per-item readouts.

relative_edit Dict[float, List[float]]

strength -> per-item ||Delta|| / ||X|| over the edited positions (equal across conditions by construction).

skipped List[float]

strengths left out by max_relative_edit.

values

values(metric, condition=None, strength=None)

Per-item readout metric (baseline when condition is None).

summary

summary(metrics=None, n_boot=1000, ci=0.95, seed=0)

One row per (condition, strength, metric): mean change from the baseline with its interval, and for controls the paired difference target minus control with its interval.

Numerical in-context learning

spectral_trust.numeric: serialised number sequences, the next-value distribution and the layer diagnostics of Bao et al. (2026); see the use case.

quantize

quantize(values, low=50, high=950, bounds=None)

Rescale values linearly to [low, high] and round to integers.

The bounds are the minimum and maximum of values unless bounds gives them (pass the bounds of the full trajectory when serialising a prefix, so that the mapping does not depend on the context length). A constant input maps to the midpoint round((low + high) / 2).

serialize

Serialisation of numerical sequences for in-context learning, and the token spans of each value.

The default format is the one of Gruver et al. (2023), Liu et al. (2024) and Bao et al. (2026): values rescaled to [50, 950], rounded, written as zero-padded three-digit integers and followed by a comma (the last one included), e.g. "087,173,642,".

ValueSpans dataclass

ValueSpans(input_ids, values, separators, special, mixed=list())

Token positions of a serialised numerical sequence.

Attributes:

Name Type Description
input_ids List[int]

the token ids (special tokens included).

values List[Tuple[int, int]]

[start, end) token span of each value, in order.

separators List[int]

positions of the separator tokens.

special List[int]

positions of special tokens (BOS and the like).

mixed List[int]

positions of tokens that hold digits and the separator together (none for Llama 3 or Qwen 3 tokenizers); they are counted in the value they start.

numeric_positions property
numeric_positions

Every token position inside a value span.

content_positions property
content_positions

Every position that is not a special token.

quantize

quantize(values, low=50, high=950, bounds=None)

Rescale values linearly to [low, high] and round to integers.

The bounds are the minimum and maximum of values unless bounds gives them (pass the bounds of the full trajectory when serialising a prefix, so that the mapping does not depend on the context length). A constant input maps to the midpoint round((low + high) / 2).

serialize

serialize(values, digits=3, sep=',', trailing=True)

Write non-negative integers as zero-padded digits-digit strings joined by sep (and followed by it when trailing).

value_spans

value_spans(tokenizer, text, sep=',', add_special_tokens=True)

Tokenise text and locate each value's tokens and each separator.

Needs a fast tokenizer (offset mapping). Values are maximal runs of digits (with an optional leading minus sign or decimal point inside the run); every other non-space character is expected to be sep.

repeat_fraction

repeat_fraction(values, order=2)

Share of positions t >= order whose preceding order values, as a tuple, already occurred earlier followed by some value: the part of the sequence an induction (copy) mechanism can continue. 0 for sequences without repeated contexts, close to 1 for short periods.

value_spans

value_spans(tokenizer, text, sep=',', add_special_tokens=True)

Tokenise text and locate each value's tokens and each separator.

Needs a fast tokenizer (offset mapping). Values are maximal runs of digits (with an optional leading minus sign or decimal point inside the run); every other non-space character is expected to be sep.

repeat_fraction

repeat_fraction(values, order=2)

Share of positions t >= order whose preceding order values, as a tuple, already occurred earlier followed by some value: the part of the sequence an induction (copy) mechanism can continue. 0 for sequences without repeated contexts, close to 1 for short periods.

next_value_distribution

next_value_distribution(model, input_ids, tokenizer=None, *, digits=3, method='auto', min_prob=0.0, chunk=16)

Predictive distribution over the next digits-digit value.

Parameters:

Name Type Description Default
model

a Hugging Face causal LM or a SpectralModel.

required
input_ids

the prompt, [S] or [1, S], ending where the next value starts (after the separator).

required
tokenizer

default the SpectralModel's.

None
digits int

digits per value.

3
method str

"single" (one token per value), "hierarchical" (one token per digit) or "auto".

'auto'
min_prob float

hierarchical only: prefixes with probability below this are not expanded; their mass is spread uniformly over the values they start (0, the default, expands every prefix: exact).

0.0
chunk int

hierarchical only: prefixes scored per forward pass (bounds the memory of the repeated cache).

16

The hierarchical path needs a key-value cache that can be cropped and repeated (DynamicCache: Llama, Qwen 2/3, Gemma 2/3, Phi); models whose cache cannot are scored by re-running prompt and prefix.

ValueDistribution dataclass

ValueDistribution(probs, method)

A distribution over the integers 0 .. 10**digits - 1.

Attributes:

Name Type Description
probs ndarray

[10**digits] probabilities (sum 1).

method str

"single" or "hierarchical".

entropy property

entropy

Shannon entropy in nats.

summary

summary()

mean, std, var, entropy and mode.

profile_from_outputs

profile_from_outputs(attentions, hidden_states=None, *, layers=None, pairing='input', drop=(0,), renormalize=True, hfer_cutoff=0.5, n_low=10, basis='combinatorial', groups=None, positional=True, gini=True, keep_masses=False, item=0, edge_weights='attention', edges=None, center=False, center_positions=None)

Diagnostics of every layer of one forward pass.

Parameters:

Name Type Description Default
attentions

per-layer attention, a sequence of [B, H, S, S] (or [H, S, S]) tensors as Hugging Face returns them.

required
hidden_states

L + 1 hidden-state tensors [B, S, d]; None for the attention-only metrics.

None
layers Optional[Sequence[int]]

layer indices (default all).

None
pairing str

"input" pairs layer l with hidden_states[l], the states entering the block that produced the attention (Bao et al.); "output" with hidden_states[l + 1], as run_with_spectra does.

'input'
drop Sequence[int]

positions removed from the graph and the signal (default the first, BOS); () keeps every token.

(0,)
renormalize bool

renormalise attention rows after dropping.

True
hfer_cutoff, n_low, basis

see graph_signal_metrics.

required
groups Optional[Sequence[Sequence[int]]]

optional node groups (positions in the original sequence) merged by pool_nodes before the graph metrics, e.g. one group per value and one per separator.

None
positional, gini

compute the non-graph controls.

required
keep_masses bool

keep the per-mode energies of each layer.

False
item int

batch item to read.

0
edge_weights str

the graph's edges, as GSPConfig.edge_weights: "attention" (default, the paper's graph), "value" (the norm of what token j adds to token i's attention output, summed over heads inside the norm) or "value_per_head" (a^h_ij ||W_O^h v^h_j|| per head, then averaged like attention). Value-weighted edges give little weight to a sink whose value vectors are small (Kobayashi et al. 2020).

'attention'
edges Optional[Mapping[int, object]]

with value edges, {layer: tensor} as returned by value_weighted_attention ([B, S, S] for "value", [B, H, S, S] for "value_per_head", per_head=True), from the same input; profile computes them. Dropping and renormalising apply to them as to attention; gini and sink_mass always read the attention.

None
center bool

subtract, in each layer, the mean hidden state over center_positions from the signal of every node before the graph Fourier transform (and the positional DCT), which removes the shared (DC) component; an ablation of Bao et al.'s updated paper. Off by default (results unchanged). To be aligned with the authors' code once it is public.

False
center_positions Optional[Sequence[int]]

positions (in the original sequence) whose mean is subtracted, e.g. value_spans(...).numeric_positions for the value tokens; default every node of the graph (after drop).

None

graph_signal_metrics

graph_signal_metrics(adjacency, signal=None, *, hfer_cutoff=0.5, n_low=10, basis='combinatorial', return_masses=False)

Diagnostics of one graph [n, n] and an optional signal [n, d]: fiedler, low_eigenvalues (lambda_2 .. lambda_{n_low + 1} of the normalised Laplacian) and, with a signal, hfer, spectral_entropy, exp_se and signal_energy in the basis ("combinatorial" or "normalized") eigenbasis. return_masses adds the per-mode energies masses.

positional_metrics

positional_metrics(signal, hfer_cutoff=0.5)

pos_hfer, pos_spectral_entropy and pos_exp_se of a signal [n, d] in the orthonormal DCT-II basis along positions.

attention_gini

attention_gini(attention)

Normalised attention Gini of causal rows (Hurley and Rickard 2009, as in Bao et al. 2026, App. H): for head h and row i >= 2 (1-based), the Gini coefficient of A[h, i, :i] divided by its maximum 1 - 1/i, averaged over heads and rows. 0 is uniform attention, 1 one key.

pool_nodes

pool_nodes(adjacency, signal, groups)

Merge node groups into single nodes: edge weights are summed between groups, signals averaged within each group. Positions in no group are dropped. Returns (W [G, G], X [G, d] or None). Used to give a digit-level tokenizer one node per value, the aggregation Bao et al. (2026) leave to future work.

The diagnostics on value-weighted graphs (edge_weights="value" or "value_per_head"), forward pass included:

profile

profile(model, input_ids, *, edge_weights='attention', tokenizer=None, **kwargs)

profile_from_outputs of one input, forward pass included.

Parameters:

Name Type Description Default
model

a Hugging Face causal LM or a SpectralModel, loaded with attn_implementation="eager" (attention weights are needed).

required
input_ids

[S] or [1, S].

required
edge_weights str

"attention", "value" or "value_per_head"; value edges come from value_weighted_attention on the same input.

'attention'
**kwargs

passed to profile_from_outputs (drop, renormalize, basis, layers, ...).

{}

Sequence generators, token-inventory controls and multi-step extrapolation:

dynamics

Seeded generators of the sequence families of numerical in-context learning.

The families of Bao et al. (2026): periodic (a period-p pattern), logistic (the logistic map at r, periodic or chaotic) and lorenz (one coordinate of the Lorenz system). Smooth families, whose dynamics are simple but continuous: sine, damped_oscillator and pendulum (integrated with the symplectic Stormer-Verlet scheme, so its energy stays bounded over long runs).

Every generator returns a Trajectory: the raw values and the integers of the 000-999 format (rescaled to [50, 950] with the bounds of the whole run, as quantize does), so serialize(traj.ints[:n]) is a prompt and traj.ints[n:] its true continuation. The same seed gives the same trajectory; it draws the initial condition (or the phase), never the parameters.

Trajectory dataclass

Trajectory(values, ints, family, params=dict())

One realisation of a family.

Attributes:

Name Type Description
values ndarray

[n] raw values.

ints ndarray

[n] integers in [low, high] (default [50, 950]).

family str

the generator's name.

params Dict[str, object]

its parameters, the seed included.

text
text(n=None)

The first n values (all by default) in the "087,173," format.

split
split(n_context, n_steps=None)

(context, continuation): the first n_context integers and the n_steps that follow (all that follow by default).

periodic

periodic(p, n=1000, seed=0, *, low=50, high=950)

A period-p sequence: p values drawn uniformly in [0, 1) (distinct for p >= 2) and repeated. p = 1 is a constant.

logistic

logistic(r, n=1000, seed=0, *, burn_in=0, low=50, high=950)

The logistic map x <- r x (1 - x) from x0 uniform in [0.3, 0.7], after burn_in discarded steps (pass a few thousand to start on the attractor). After burn-in, r = 3.2, 3.5, 3.55 and 3.566 give periods 2, 4, 8 and 16; r = 3.9 and 4.0 are chaotic.

lorenz

lorenz(n=1000, seed=0, *, coord='x', dt=0.02, substeps=4, burn_in=500, sigma=10.0, rho=28.0, beta=8.0 / 3.0, low=50, high=950)

One coordinate ("x", "y", "z" or 0, 1, 2) of the Lorenz system, sampled every dt (RK4 with substeps steps per sample), from a seeded initial condition near the attractor after burn_in discarded samples.

sine

sine(n=1000, seed=0, *, frequency=1.0 / 32, amplitude=1.0, phase=None, low=50, high=950)

amplitude sin(2 pi frequency t + phase), frequency in cycles per value (1/32: one period every 32 values); the phase is drawn from seed unless given.

damped_oscillator

damped_oscillator(n=1000, seed=0, *, frequency=1.0 / 32, damping=0.01, phase=None, low=50, high=950)

The position of x'' + 2 zeta w x' + w^2 x = 0 (w = 2 pi frequency, zeta = damping < 1), in closed form: exp(-zeta w t) cos(w_d t + phase) with w_d = w sqrt(1 - zeta^2); one time unit per value.

pendulum

pendulum(n=1000, seed=0, *, theta0=None, omega=2 * np.pi / 32, dt=1.0, substeps=8, coord='theta', low=50, high=950)

A frictionless pendulum theta'' = -omega^2 sin(theta), a simple Hamiltonian system H = p^2 / 2 + omega^2 (1 - cos theta), integrated with the symplectic Stormer-Verlet (leapfrog) scheme, substeps steps per sample dt. Starts at rest at theta0 (radians; drawn uniformly in [0.5, 2.5] from seed unless given: large swings, so not a sine). coord: "theta" or "momentum". params["energy_drift"] is the largest relative energy error.

generate

generate(family, n=1000, seed=0, **params)

FAMILIES[family](n=n, seed=seed, **params), e.g. generate("logistic", 200, seed=3, r=3.9, burn_in=1000).

token_preserving_shuffle

token_preserving_shuffle(values, seed=0)

values in a random order (seed): every value, hence every token of its serialisation, is kept with its multiplicity; only the order changes. Pass the quantised integers (shuffling raw values and quantising afterwards gives the same integers, since the bounds are unchanged).

inventory_covariates

inventory_covariates(values, tokenizer=None, digits=3)

Inventory of one sequence, or of each of several.

Parameters:

Name Type Description Default
values

one sequence (1-D) or a list of sequences (lengths may differ).

required
tokenizer

if given, also n_unique_tokens, the distinct token ids of the serialised sequence (separators included, special tokens not): equal to n_unique + 1 with one token per value, at most 11 with one token per digit.

None
digits int

digits per value of the serialisation.

3

Returns:

Type Description
Dict[str, object]

{name: float} for one sequence; {name: np.ndarray} (one entry

Dict[str, object]

per sequence, ready for st.confound_audit(..., covariates=...))

Dict[str, object]

for several. repeat_fraction here is 1 - n_unique / n, the

Dict[str, object]

share of values seen before, which ignores order;

Dict[str, object]

func:~spectral_trust.numeric.repeat_fraction counts repeated

Dict[str, object]

contexts instead and changes under a shuffle. value_entropy is

Dict[str, object]

in nats.

rollout

Multi-step autoregressive extrapolation of a serialised sequence.

rollout predicts the next value with next_value_distribution (its mode by default, the greedy value), writes it back into the context in the same format and repeats, so each step conditions on the model's own predictions. Against the true continuation it reports the absolute error per step and its running sum. A one-step error can be small while the trajectory drifts away over many steps; this is what the per-step errors show.

With use_cache=True (the default) the prompt runs once and every step extends its key-value cache with the predicted value's tokens. The prompt's pass then has the prompt's length, so an edit installed by edit_with_controls (which edits the pass of the prompt's length) changes the prompt's keys and values, and every step of the rollout reads the edited prompt; the predicted tokens themselves are not edited. RolloutReadout packages a rollout as the readout of edit_with_controls, so an edit's effect on multi-step error is measured against its controls. With use_cache=False every step reruns the whole growing sequence through next_value_distribution (the same numbers up to float error, slower); an edit of the prompt's length then changes the first step only.

Rollout dataclass

Rollout(predicted, target, entropy, std, method, tol=50.0)

A multi-step extrapolation.

Attributes:

Name Type Description
predicted ndarray

[n_steps] predicted values.

target Optional[ndarray]

[n_steps] true continuation, or None.

entropy ndarray

[n_steps] entropy (nats) of each step's distribution.

std ndarray

[n_steps] standard deviation of each step's distribution.

method str

"single" or "hierarchical".

tol float

the error that ends valid_steps.

abs_error property
abs_error

|predicted - target| per step.

cum_error property
cum_error

Running sum of the absolute error.

valid_steps property
valid_steps

Steps before the first absolute error above tol.

summary
summary()

Scalars for a readout: mean_entropy and, with a target, mae, first_error, final_error, cum_error (the total) and valid_steps.

RolloutReadout

RolloutReadout(tokenizer, contexts, targets, n_steps, *, digits=3, sep=',', **kwargs)

A rollout as the readout of edit_with_controls.

Holds the prompts (inputs) and their true continuations; called as readout(model, ids), it finds the continuation of ids and returns Rollout.summary (mae, cum_error, final_error, ...)::

ro = RolloutReadout(tok, contexts, continuations, n_steps=20)
res = st.edit_with_controls(model, ro.inputs, ro, layer=8,
                            positions=ro.positions, token_span=(1, None))
res.summary(["mae", "cum_error"])

Parameters:

Name Type Description Default
tokenizer

the model's tokenizer.

required
contexts Sequence[Sequence[int]]

the integer contexts, one per item.

required
targets Sequence[Sequence[int]]

the true continuations (at least n_steps values each).

required
n_steps int

values to predict per item.

required
**kwargs

passed to rollout (predict, method, min_prob, tol, ...).

{}

rollouts keeps every Rollout computed, in call order.

positions
positions(i)

Token positions of the values of item i (for positions=).

rollout

rollout(model, tokenizer, values, n_steps, *, target=None, input_ids=None, digits=3, sep=',', method='auto', predict='mode', min_prob=0.0, chunk=16, use_cache=True, tol=50.0)

Extrapolate n_steps values, feeding back each prediction.

Parameters:

Name Type Description Default
model

a Hugging Face causal LM or a SpectralModel.

required
tokenizer

default the SpectralModel's.

required
values Optional[Sequence[int]]

the context, integers in [0, 10**digits) (for example traj.ints[:n]); serialised with serialize.

required
n_steps int

values to predict.

required
target Optional[Sequence[int]]

the true continuation (at least n_steps values); gives the errors.

None
input_ids

the prompt as token ids ([S] or [1, S], ending after a separator) instead of values.

None
digits, sep

the format.

required
method, min_prob, chunk

as in next_value_distribution.

required
predict str

"mode" (the most probable value: greedy decoding over values) or "mean" (the rounded expected value).

'mode'
use_cache bool

extend the prompt's key-value cache step by step (see the module docstring); False reruns the whole sequence each step.

True
tol float

absolute error that ends Rollout.valid_steps.

50.0

Rollout dataclass

Rollout(predicted, target, entropy, std, method, tol=50.0)

A multi-step extrapolation.

Attributes:

Name Type Description
predicted ndarray

[n_steps] predicted values.

target Optional[ndarray]

[n_steps] true continuation, or None.

entropy ndarray

[n_steps] entropy (nats) of each step's distribution.

std ndarray

[n_steps] standard deviation of each step's distribution.

method str

"single" or "hierarchical".

tol float

the error that ends valid_steps.

abs_error property

abs_error

|predicted - target| per step.

cum_error property

cum_error

Running sum of the absolute error.

valid_steps property

valid_steps

Steps before the first absolute error above tol.

summary

summary()

Scalars for a readout: mean_entropy and, with a target, mae, first_error, final_error, cum_error (the total) and valid_steps.

RolloutReadout

RolloutReadout(tokenizer, contexts, targets, n_steps, *, digits=3, sep=',', **kwargs)

A rollout as the readout of edit_with_controls.

Holds the prompts (inputs) and their true continuations; called as readout(model, ids), it finds the continuation of ids and returns Rollout.summary (mae, cum_error, final_error, ...)::

ro = RolloutReadout(tok, contexts, continuations, n_steps=20)
res = st.edit_with_controls(model, ro.inputs, ro, layer=8,
                            positions=ro.positions, token_span=(1, None))
res.summary(["mae", "cum_error"])

Parameters:

Name Type Description Default
tokenizer

the model's tokenizer.

required
contexts Sequence[Sequence[int]]

the integer contexts, one per item.

required
targets Sequence[Sequence[int]]

the true continuations (at least n_steps values each).

required
n_steps int

values to predict per item.

required
**kwargs

passed to rollout (predict, method, min_prob, tol, ...).

{}

rollouts keeps every Rollout computed, in call order.

positions

positions(i)

Token positions of the values of item i (for positions=).

Confound audit

confound_audit

confound_audit(readouts, target, covariates=None, *, cache=None, kind='auto', n_folds=5, n_boot=1000, ci=0.95, seed=0, groups=None)

Effect of each readout on target, raw and given the covariates.

Parameters:

Name Type Description Default
readouts Mapping[str, Sequence[float]]

name -> per-item values.

required
target Sequence[float]

per-item label (binary) or score (continuous).

required
covariates Optional[Mapping[str, Sequence[float]]]

name -> per-item values (length, sink mass, effective rank, mean position, any others). Constant covariates are ignored.

None
cache

a SpectralCache with one text per item; covariates_from_cache fills the standard covariates it can, without overriding covariates.

None
kind str

"binary", "continuous" or "auto" (binary when the target has two values).

'auto'
n_folds int

folds of the cross-validated logistic regression.

5
n_boot, ci, seed

bootstrap over items (groups: resample groups of items whole, e.g. realisations shared across conditions).

required

AuditResult dataclass

AuditResult(kind, covariates, rows=list(), covariate_rows=list())

Rows of confound_audit, one per readout.

Each row holds the readout name, n and, for a binary target, auroc, resid_auroc, partial_r, cv_auroc_covariates, cv_auroc_full and cv_gain; for a continuous target spearman and partial_spearman. Each statistic x comes with x_lo and x_hi. covariate_rows hold each covariate's own raw effect on the target (auroc or spearman), the baseline a readout has to beat.

confound_covariates

confound_covariates(attention=None, signal=None, *, positions=None, sink=0)

The standard covariates of one item: n_tokens, sink_mass (mean attention to position sink over heads and later queries, from attention [H, S, S]), effective_rank of signal [S, d] and mean_position of the analysed positions (default all).

covariates_from_cache

covariates_from_cache(cache, *, layers=None, sink=0)

Per-text covariates from a SpectralCache: n_tokens, mean_position and, when the attention patterns were kept, sink_mass averaged over layers (default all).

effective_rank

effective_rank(signal)

Effective rank of a signal [n, d] (Roy and Vetterli 2007): exp of the entropy of its normalised singular values.

bootstrap_ci

bootstrap_ci(values, stat=np.mean, n_boot=1000, ci=0.95, seed=0, groups=None)

(estimate, lo, hi): percentile bootstrap interval of stat over items (or over groups of items, resampled whole).

paired_bootstrap

paired_bootstrap(a, b, stat=np.mean, **kwargs)

Bootstrap interval of stat(a - b) over paired items.

Views

spectral_trust.viz; also SpectralCache.graph, .heatmap, .spectrum and .animate (see the animated gallery).

graph

graph(cache, layer, head=None, text=0, max_edges=400, min_weight=0.02, size=520)

The attention graph of one layer (head-averaged) or one head.

The layer graph is the one the graph namespace measured: with value-weighted edges it is the value-weighted graph (stored when the patterns are kept); a directed graph is not shown (ValueError; a head's graph still is).

Tokens are nodes on a circle, clockwise from the top. Edge opacity and width follow the symmetrised attention weight, relative to the largest weight off the diagonal; node colour is the graph's Fiedler vector (blue negative, orange positive), the eigenvector of lambda_2 that splits the graph along its weakest cut. Hover a node for its token, Fiedler entry and degree, and to highlight its edges; hover an edge for its weight.

Parameters:

Name Type Description Default
cache

a SpectralCache holding the attention patterns (keep_patterns).

required
layer int

true layer index.

required
head Optional[int]

one head, or None for the head-averaged graph.

None
text int

which text of a batch.

0
max_edges int

draw at most this many edges, the strongest.

400
min_weight float

skip edges below this fraction of the largest weight.

0.02
size int

width of the drawing in pixels.

520

heatmap

heatmap(cache, metric='fiedler_value', text=0, backend='svg', cell=None, robust=True)

One metric over layers x heads, one cell per (layer, head).

A bare per-head name means the attn namespace; pass "resid.hfer" for a hybrid one. A graph metric is drawn layers x texts. Heads that were not computed are left blank.

Parameters:

Name Type Description Default
cache

a SpectralCache.

required
metric str

metric name, e.g. "fiedler_value" or "resid.energy".

'fiedler_value'
text int

which text of a batch (per-head metrics).

0
backend str

"svg" (interactive View) or "matplotlib" (a matplotlib.figure.Figure).

'svg'
cell Optional[float]

cell size in pixels (default: fit about 620 px).

None
robust bool

colour scale from the 1st to the 99th percentile, so one extreme head does not wash out the rest.

True

spectrum

spectrum(cache, layer, head=None, text=0, width=560)

The Laplacian spectrum of one layer (head-averaged graph) or head.

Eigenvalues are drawn in ascending order, lambda_2 (the Fiedler value) in orange. The shaded band marks the top num_high_modes modes, whose share of the signal energy is the hybrid HFER. Hover a point for its value.

View

View(svg, title, kind)

An interactive figure: SVG plus a small inline script.

Displays itself in Jupyter, and save("view.html") writes a standalone page that opens offline. svg holds the bare SVG markup.

to_html

to_html()

A standalone HTML page holding the view.

save

save(path)

Write to_html to path (.html is appended if the name has no suffix) and return the path.

animate

animate(cache, kind='embedding3d', out='spectral.mp4', *, fps=None, duration=None, theme='light', size=None, dpi=100, seed=0, wordmark=False, plotlyjs='auto', threads=2, crf=None, font=None, progress=False, **options)

Write an animated (.mp4, .webm, .gif) or interactive (.html) view of cache to out and return its path.

Parameters:

Name Type Description Default
cache

a SpectralCache holding the attention patterns (keep_patterns, kept by default for short texts). waterfall also needs the hybrid metrics (hybrid=True, the default).

required
kind str

one of embedding3d, waterfall, compare, graph_movie, head_atlas.

'embedding3d'
out Union[str, Path]

output path; its suffix picks the format.

'spectral.mp4'
fps Optional[float]

frames per second (default 30 for video, 15 for GIF).

None
duration Optional[float]

length in seconds (default: set by the number of layers).

None
theme Union[str, Theme]

"light" or "dark".

'light'
size Optional[Tuple[int, int]]

frame size in pixels (default 1280 x 720 for video, 640 x 360 for GIF).

None
dpi int

resolution of the text and line widths (pixels per inch).

100
seed int

seed of the layouts that use one (graph_movie force layout); output is deterministic for a fixed seed.

0
wordmark bool

draw a small "spectral-trust" wordmark in a corner.

False
plotlyjs str

for .html: "auto" (embed when the plotly package is installed, else the CDN), "embed" (plotly.js copied into the page from the plotly package: one self-contained file that works offline, about 5 MB), "cdn" (a pinned plotly.js from cdn.plot.ly, a small page that needs the network), a URL, or the path of a local plotly.min.js.

'auto'
threads int

encoder threads (ffmpeg); the flow capture also pins the browser to this many CPUs when psutil is installed.

2
crf Optional[int]

video quality, lower is better and larger (default 18 for .mp4, 24 for flow's richer frames; 32 for .webm).

None
font

font family list (default Inter, Segoe UI, Helvetica, Arial).

None
progress bool

print frame progress.

False
**options

options of the kind, e.g. layers, text, title; other, highlight, engine ("auto", "browser" or "matplotlib"), bundle, axes and browser (flow); orbit (embedding3d); scale (waterfall); other and labels (compare); layout (graph_movie); layer and metric (head_atlas).

{}

Examples:

>>> pair.animate("flow", "flow.mp4", text=1, other=pair.text(0), theme="dark")
>>> cache.animate("embedding3d", "hero.mp4")
>>> st.viz.animate(cache, "waterfall", "waterfall.gif", theme="dark")
>>> st.viz.animate(clean, "compare", "compare.mp4", other=injected)

Per-head diagnostics

per_head_metrics

per_head_metrics(attention, config=None, token_span=None, layer=-1, heads=None, keep_eigenvalues=False, device='cpu')

Compute per-head spectral metrics for a single layer.

Parameters:

Name Type Description Default
attention Tensor

attention weights for one layer, [heads, seq, seq] (a leading batch dimension of size 1 is accepted and squeezed).

required
config Optional[GSPConfig]

graph-construction settings (symmetrization, normalization, self-loops). Defaults to GSPConfig(), i.e. the symmetric normalized Laplacian, whose spectrum lies in [0, 2] independent of sequence length. normalization="rw" reports the spectrum of the random-walk operator I - D^{-1} W itself, which equals that of the symmetric normalized Laplacian (the two are similar).

None
token_span Optional[Tuple[int, int]]

optional (start, end) half-open token range. The induced subgraph is taken before the Laplacian is built, which is what makes the diagnostic local to a span of interest (e.g. a generated tool call) rather than to the whole sequence.

None
layer int

layer index recorded in the result.

-1
heads HeadSelection

compute only these heads. One of: head indices for this layer ([0, 5, 7]); (layer, head) pairs, of which those with layer == layer are kept (requires layer >= 0); a boolean mask [heads] or [layers, heads] (row layer is used). Unselected heads are dropped before any conversion or decomposition. Rows of the result follow ascending head index and result.heads lists them.

None
keep_eigenvalues bool

also return each head's spectrum in result.eigenvalues ([heads, seq], ascending). The spectrum is computed anyway; this only keeps it.

False
device Device

where the Laplacians are built and decomposed. The default is the CPU whatever config.device says, because the batched symmetric eigensolver on CUDA is very slow for many small matrices (measured 1.9 s against 0.1 s for 32 heads x 16 layers at a 90-token span on one consumer GPU). Pass "cuda" to decompose on the GPU, which can pay off for long spans. config.device is not read here.

'cpu'

Returns:

Type Description
PerHeadDiagnostics

class:PerHeadDiagnostics with a [heads, 5] value matrix.

per_head_metrics_all_layers

per_head_metrics_all_layers(attentions, config=None, token_span=None, heads=None, device='cpu', num_workers=1)

Per-head metrics for every layer.

Parameters:

Name Type Description Default
attentions

sequence of per-layer attention tensors, each [heads, seq, seq] or [1, heads, seq, seq] — i.e. exactly what model(..., output_attentions=True).attentions returns.

required
config, token_span, device

as in per_head_metrics.

required
heads HeadSelection

as in per_head_metrics, resolved per layer: (layer, head) pairs (e.g. from heads_from_scores) or a [layers, heads] mask select different heads in each layer, plain indices or a [heads] mask the same heads everywhere.

None
num_workers int

layers decomposed at once, each on one CPU thread. The results are the same and in layer order for any value. Use this rather than calling per_head_metrics from your own threads.

1

per_head_hybrid_metrics

per_head_hybrid_metrics(attention, signals, config=None, token_span=None, layer=-1, heads=None, device='cpu')

Per-head hybrid metrics for one layer: the layer's residual-stream signals measured on each head's attention graph.

For each selected head h, the head's attention is symmetrized and turned into a Laplacian L_h exactly as in per_head_metrics; then energy = tr(X^T L_h X), smoothness_index = energy / ||X||_F^2, and spectral_entropy / hfer follow SpectralAnalyzer on the full eigenbasis of L_h (never truncated). config.project_dim applies the same Johnson-Lindenstrauss projection to X first.

Values agree with SpectralAnalyzer(eigen_solver="dense").analyze_layer run on each head's Laplacian to float32 rounding, which is not the same for every metric. Energy and smoothness index agree to about 1e-6 relative. HFER and spectral entropy depend on the eigenvectors, which the two paths compute with different float32 solvers (torch here, scipy there): for nearly degenerate modes the vectors are fixed only to float32 precision. Measured on Qwen3.5-2B attention (128 tokens, one-column SAE feature signals), HFER differed by up to 8e-5 and spectral entropy by up to 1.2e-3, absolute. Both are float32 roundings of the same quantity: on a sample of those graphs each path was as close to a float64 solve as to the other.

Parameters:

Name Type Description Default
attention Tensor

[heads, seq, seq] (or [1, heads, seq, seq]).

required
signals Tensor

[seq, d] (or [1, seq, d]), the residual-stream states paired with this layer (hidden_states[layer + 1] in the Hugging Face convention, as in the framework).

required
config, token_span, layer, heads, device

as in per_head_metrics. With normalization="rw" the general eigensolver runs on the CPU whatever device says.

required

Returns:

Type Description
PerHeadDiagnostics

class:PerHeadDiagnostics with family "hybrid" and a

PerHeadDiagnostics

[heads, 4] matrix over PER_HEAD_HYBRID_METRIC_NAMES.

per_head_hybrid_metrics_all_layers

per_head_hybrid_metrics_all_layers(attentions, hidden_states, config=None, token_span=None, heads=None, device='cpu', num_workers=1)

per_head_hybrid_metrics for every layer.

hidden_states may have one more entry than attentions (the Hugging Face convention, embeddings first): layer i is then paired with hidden_states[i + 1], as in the framework. With equal lengths layer i is paired with hidden_states[i]. num_workers is as in per_head_metrics_all_layers.

PerHeadDiagnostics dataclass

PerHeadDiagnostics(layer, values, metric_names, family=PER_HEAD_METRIC_FAMILY, heads=None, eigenvalues=None)

Per-head spectral metrics for one layer.

values is [num_heads, len(metric_names)]. When only a subset of heads was computed (heads=), heads lists their indices in row order; it is None when every head was computed. eigenvalues holds each head's ascending Laplacian spectrum, [num_heads, seq], when per_head_metrics was called with keep_eigenvalues=True.

metric

metric(name)

All heads' values for one metric, as a [num_heads] array.

heads_from_scores

heads_from_scores(scores, k)

The k highest-scoring heads of a [layers, heads] score matrix, as (layer, head) pairs sorted by layer then head, ready for heads=. NaN scores are never selected; ties keep row-major order.

The scores come from outside the library (an attribution method, a probe's weights, an ablation study); this only ranks them.

stack_feature_vector

stack_feature_vector(diagnostics, metrics=None)

Flatten per-layer diagnostics into one feature vector for a probe.

Parameters:

Name Type Description Default
diagnostics List[PerHeadDiagnostics]

output of per_head_metrics_all_layers.

required
metrics Optional[List[str]]

metric subset to keep, in order (default: all five).

None

Returns:

Type Description
ndarray

1-D array of length layers * heads * len(metrics), ordered

ndarray

layer-major then head then metric. With head subsets (heads=)

ndarray

each layer contributes its selected heads, in ascending order.

layer_delta_features

layer_delta_features(diagnostics, metric='spectral_radius')

Layer-to-layer differences of one per-head metric ("spectral dynamics").

Captures how each head's spectrum evolves with depth, which flat per-layer feature sets do not represent explicitly. Needs the same number of heads in every layer (all heads, or one head mask for all).

Returns:

Type Description
ndarray

1-D array of length (layers - 1) * heads.

Directed and value-weighted graphs

Added in 0.5.1. Graph options of GSPConfig (edge_weights, graph_direction, magnetic_q) and the functions behind them; see Directed and value-weighted graphs.

value_weighted_attention

value_weighted_attention(model, inputs, layers=None, per_head=False, tokenizer=None)

Value-weighted attention graphs of a model on some input.

{layer: edges} with edges [B, S, S] (per_head=False: the norm of what token j adds to token i's attention output, summed over heads inside the norm) or [B, H, S, S] (per_head=True). See value_weighted_edges and the module notes for the layouts covered.

Examples:

>>> model = st.SpectralModel.from_pretrained("gpt2")
>>> w = st.value_weighted_attention(model, "The cat sat on the mat.")
>>> w[5].shape        # [1, S, S]

capture_attention_values

capture_attention_values(model, inputs, layers=None, tokenizer=None, keep_output=False)

Run the model once and return, per layer, the tensors that split its attention output by key token (AttentionValues).

Parameters:

Name Type Description Default
model

a SpectralModel or a transformers causal LM.

required
inputs

a string, a list of strings, or token ids ([S], [B, S] or lists). Texts of different lengths are right-padded.

required
layers Optional[Sequence[int]]

true layer indices (default every softmax-attention layer).

None
tokenizer

for text input when model is not a SpectralModel.

None
keep_output bool

also keep each attention module's output.

False

Returns:

Type Description
Dict[int, AttentionValues]

{layer: AttentionValues}.

AttentionValues dataclass

AttentionValues(layer, weights, values, out_weight, out_bias=None, gate=None, gate_layout=None, output=None, lengths=None)

What one attention layer computed on one batch: enough to split its output into one vector per key token (see the module notes).

Attributes:

Name Type Description
layer int

true layer index.

weights Tensor

[B, H, S, S] attention weights (row i the query).

values Tensor

[B, H_kv, S, d_head] value states, as the attention read them.

out_weight Tensor

[d_model, H * d_head] output projection (torch.nn.Linear layout).

out_bias Optional[Tensor]

[d_model] output bias, or None. It is in no contribution.

gate Optional[Tensor]

[B, S, H * d_head] output gate after its sigmoid, or None.

gate_layout Optional[str]

"query_split", "gate_proj" or None.

output Optional[Tensor]

[B, S, d_model] the module's output, when kept.

lengths Optional[List[int]]

real length of each batch item (right padding follows).

contributions

contributions(queries=None)

[B, Q, S, d_model] per-key contributions (attention_contributions).

edge_weights

edge_weights(per_head=False, chunk_bytes=CHUNK_BYTES)

Value-weighted edges, [B, S, S] or [B, H, S, S] (value_weighted_edges).

reconstruct

reconstruct(chunk_bytes=CHUNK_BYTES)

Σ_j c_ij + b_O for every query, [B, S, d_model]: the attention output rebuilt from the per-key contributions (computed in chunks of queries).

ValueCapture

ValueCapture(model, layers=None, keep_output=False)

Context manager that records, during forward passes of a Hugging Face causal LM, what AttentionValues needs for each layer: the attention weights and value states (inside eager_attention_forward), the input of the output projection, the gate projection's output and, optionally, the module output. Nothing in the computation changes; the attention is switched to the eager implementation while the capture is open (and switched back on exit).

Examples:

>>> with ValueCapture(model, layers=[3, 7]) as cap:
...     model(input_ids)
>>> vals = cap.results()          # {3: AttentionValues, 7: ...}

Parameters:

Name Type Description Default
model

a SpectralModel or a transformers causal LM.

required
layers Optional[Sequence[int]]

true layer indices; default every layer with softmax attention (the full-attention layers of a hybrid model).

None
keep_output bool

also keep each attention module's output.

False

results

results(lengths=None)

AttentionValues of every captured layer, from the last forward pass. Checks, per layer, that the attention output is weights @ values and that the input of the output projection is that output (times the gate, when there is one); raises otherwise.

value_weighted_edges

value_weighted_edges(weights, values, out_weight, gate=None, per_head=False, chunk_bytes=CHUNK_BYTES)

Value-weighted edge weights of one attention layer.

per_head=False (default): w_ij = ‖Σ_h a^h_ij W_O^h (g^h_i ⊙ v^h_j)‖, the norm of what token j adds to token i's attention output (Kobayashi et al. 2020), [B, S, S]. per_head=True: w^h_ij = a^h_ij ‖W_O^h (g^h_i ⊙ v^h_j)‖, [B, H, S, S], which GraphConstructor aggregates over heads like attention. By the triangle inequality the sum over heads of the per-head weights bounds the summed weight from above; they differ where heads cancel. The output bias is in neither (it belongs to no token).

Without a gate the summed weights come from the Gram matrices of u^h_j = W_O^h v^h_j in float64 (O(S² H²)); with a gate they are computed over chunks of queries, each over the keys it attends to, within chunk_bytes of working memory. No [S, S, d_model] tensor is formed.

Parameters:

Name Type Description Default
weights, values, out_weight, gate

as in attention_contributions.

required
per_head bool

one graph per head instead of the norm of the sum.

False
chunk_bytes int

working memory of one chunk.

CHUNK_BYTES

Returns:

Type Description
Tensor

[B, S, S] or [B, H, S, S] (no batch dimension for unbatched

Tensor

input), float32, or float64 when an input is float64. Row i is the

Tensor

query, as for attention.

attention_contributions

attention_contributions(weights, values, out_weight, gate=None, queries=None)

What each key token adds to each query token's attention output.

c[b, i, j] = Σ_h a^h_ij W_O^h (g^h_i ⊙ v^h_j), so that c[b, i].sum(0) + b_O is the attention module's output at token i. The tensor is [B, Q, S, d_model]: pass queries for long sequences, or use value_weighted_edges for the norms alone.

Parameters:

Name Type Description Default
weights

[B, H, S, S] attention weights (or [H, S, S]).

required
values

[B, H_kv, S, d_head] value states as the attention read them (or [H_kv, S, d_head]).

required
out_weight

[d_model, H * d_head] output projection, as a torch.nn.Linear stores it (the transpose of a GPT-2 Conv1D weight).

required
gate

[B, S, H * d_head] output gate after its nonlinearity, or None.

None
queries Queries

query tokens (index, indices, slice); default all.

None

Returns:

Type Description
Tensor

[B, Q, S, d_model] ([Q, S, d_model] for unbatched input), in

Tensor

float32, or float64 when an input is float64.

directed_operator

directed_operator(adjacency, remove_self_loops=False)

The row-normalised operator P = D_out⁻¹ A of a directed graph.

Row i of P is row i of A divided by its sum, so (P x)_i is the A-weighted average of the signal over the tokens that i reads: one step of transport along the edges, from j to i. Negative weights are clipped to zero (as in GraphConstructor.construct_laplacian), and a row with no weight stays zero.

For attention, A is already row-stochastic and P equals it up to rounding. For value-weighted edges (raw norms, see spectral_trust.value_weighted) the division puts every row on the scale of attention.

Parameters:

Name Type Description Default
adjacency

[..., S, S] edge weights, row i reading column j.

required
remove_self_loops bool

zero the diagonal first (GSPConfig.remove_self_loops).

False

Returns:

Type Description
Tensor

P in the input's floating dtype (float32 for integer input).

directed_total_variation

directed_total_variation(signals, operator, per_column=False)

Directed total variation of a signal on a directed graph.

.. math:: \mathrm{TV}(x) = \frac{\lVert x - P x \rVert^2}{\lVert x \rVert^2}

with P the row-normalised operator (directed_operator). It measures how much one step of attention transport changes the signal: (P x)_i is what token i would receive by averaging the signal over the tokens it reads, and x_i − (P x)_i is how far its own value lies from that. It is zero for a signal that one step of transport leaves unchanged, a constant signal for instance (P 1 = 1), and it changes when the edges are reversed, unlike any quadratic Laplacian energy (see the module notes).

This is the quadratic form of Sandryhaila and Moura (2014) with P as the shift: their total variation is ‖x − A_norm x‖₁ with A_norm = A / |λ_max(A)|, and their 2-Dirichlet form is S₂(x) = ½ ‖x − A_norm x‖². A row-stochastic P has |λ_max| = 1, so P is its own normalised shift and TV(x) = 2 S₂(x) / ‖x‖². The division by ‖x‖² makes the value independent of the scale of x, as for the smoothness index.

Parameters:

Name Type Description Default
signals

[..., S, d] (or [S]), one column per feature; real or complex.

required
operator

[..., S, S] row-normalised operator P. It is not renormalised here.

required
per_column bool

False (default) treats the d columns as one signal, ‖X − P X‖_F² / ‖X‖_F², as the layer-level HFER does; True gives one value per column, [..., d], as per_column_metrics does.

False

Returns:

Type Description
Tensor

float64 tensor [...] or [..., d]. A signal (or column) whose

Tensor

squared norm is below 1e-8 gets 0, the threshold of the smoothness

Tensor

index.

magnetic_laplacian

magnetic_laplacian(adjacency, q=DEFAULT_MAGNETIC_Q, normalized=True, remove_self_loops=False, dtype=torch.complex128)

The magnetic Laplacian of a directed graph, a Hermitian matrix.

.. math:: A_s = \tfrac12 (A + A^\top), \qquad \Theta^{(q)}{ij} = 2\pi q \, (A), \qquad L^{(q)} = D_s - A_s \odot e^{i \Theta^{(q)}}} - A_{ji

with D_s the degrees of A_s, and the normalised form L_N = D_s^{-1/2} L^{(q)} D_s^{-1/2} = I − (D_s^{-1/2} A_s D_s^{-1/2}) ⊙ e^{iΘ} (Fanuel et al. 2017; Furutani et al. 2019; MagNet, Zhang et al. 2021). The magnitude of each entry is the symmetrised weight; the direction of the edge sits in its phase, and Θ is antisymmetric, so L is Hermitian. The eigenvalues are real and non-negative, and those of L_N lie in [0, 2]. At q = 0 the phases vanish and L is the symmetric Laplacian of A_s (GraphConstructor.construct_laplacian with "none" or "sym"). Isolated nodes (zero degree) get an identity row in the normalised form, as there.

The charge q: for weights in [0, 1] (the rows of a row-normalised operator), A_ij − A_ji lies in [−1, 1] and the phase in [−2πq, 2πq]. q = 1/4 (the default) is the largest charge for which the phase stays in [−π/2, π/2]: the real part A_s cos Θ of every entry stays non-negative, and the map from A_ij − A_ji to the phase stays one to one. At q = 1/4 a one-way edge of weight 1 gets the phase π/2 (+i against −i for its reverse), the setting MagNet uses as its directed extreme (it studies 0 <= q <= 1/4). At q = 1/2 such an edge would get the phase π, the same in both directions, and the direction would be lost. Attention weights are mostly far below 1, so their phases are small; the strong edges (to the attention sink, for instance) carry most of the phase.

Parameters:

Name Type Description Default
adjacency

[..., S, S] edge weights, row i reading column j; negative weights are clipped to zero. Use the row-normalised operator (directed_operator) for edges outside [0, 1].

required
q float

the charge, >= 0.

DEFAULT_MAGNETIC_Q
normalized bool

L_N (default) or the unnormalised L^{(q)}.

True
remove_self_loops bool

zero the diagonal first.

False
dtype dtype

torch.complex128 (default) or torch.complex64. The matrix is built in float64 and cast.

complex128

Returns:

Type Description
Tensor

[..., S, S] complex Hermitian tensor.

magnetic_spectrum

magnetic_spectrum(adjacency, q=DEFAULT_MAGNETIC_Q, normalized=True, remove_self_loops=False, dtype=torch.complex128)

Eigenvalues (ascending, real) and unit-norm complex eigenvectors (the columns) of magnetic_laplacian, from a Hermitian eigensolver (torch.linalg.eigh) in dtype. Arguments as there.

magnetic_hfer

magnetic_hfer(signals, adjacency=None, q=DEFAULT_MAGNETIC_Q, normalized=True, cutoff_ratio=0.1, per_column=False, remove_self_loops=False, eigenvectors=None)

High-frequency energy ratio of a signal on the magnetic Laplacian.

The energy of the signal in mode k is |u_kᴴ x|² (U unitary, from magnetic_spectrum), and the HFER is the share of the top num_high_modes modes, the rule of every other HFER in the library. At q = 0 it is the HFER on the symmetric Laplacian of (A + Aᵀ) / 2.

Orientation-blind for real signals. Reversing every edge (A → Aᵀ) conjugates the magnetic Laplacian, so its eigenvectors become conj(U) with the same eigenvalues, and for a real x |conj(u_k)ᴴ x| = |u_kᴴ x|. The magnetic HFER of a real signal is therefore identical for a graph and its transpose: the phases change which energies a real signal has (they depend on |A_ij − A_ji|) but not in a way that reveals which way the edges point. A complex signal can tell the two apart. Use directed_total_variation for a direction-aware measure of a real signal.

Parameters:

Name Type Description Default
signals

[S, d] or [S], real or complex.

required
adjacency

[S, S] edge weights (see magnetic_laplacian); not needed when eigenvectors are given.

None
q, normalized, remove_self_loops

as in magnetic_laplacian.

required
cutoff_ratio float

as GSPConfig.hfer_cutoff_ratio.

0.1
per_column bool

one value per column ([d]) instead of the columns taken together.

False
eigenvectors Optional[Tensor]

the [S, S] eigenvectors of magnetic_spectrum, ascending, to reuse them.

None

Returns:

Type Description
Tensor

float64 tensor, a scalar or [d]. A signal with total energy below

Tensor

1e-8 gets 0, as in SpectralAnalyzer.hfer_from_masses.

magnetic_phase

magnetic_phase(adjacency=None, q=DEFAULT_MAGNETIC_Q, normalized=True, mode=0, remove_self_loops=False, eigenvectors=None)

Phase of a magnetic eigenvector, as an ordering of the nodes.

At q = 0 the lowest eigenvector is the trivial mode (a constant phase). For q > 0 its phase is the first readout that is not trivial: a potential of the edge asymmetries. On a graph without cycles the magnetic Laplacian equals the symmetric one up to a diagonal unitary change of basis, and the lowest eigenvector has the phases φ with φ_i − φ_j = Θ_ij on every edge, so the phase grows along the direction of the edges, from the tokens that are read to the tokens that read them (a chain is ordered exactly). With cycles, as in attention, the lowest mode fits φ_i − φ_j ≈ Θ_ij with the weights A_s (an angular synchronisation of the asymmetries): the phase then ranks tokens by the net asymmetry of their strongest edges, not by position. On a layer dominated by its sink, it mostly follows how much each token reads from the sink.

The global phase is arbitrary; it is fixed so that the entry of largest modulus (on attention graphs usually the sink) has phase 0. Angles lie in (−π, π]; apply numpy.unwrap along an ordering if they wrap, which happens when q times the summed asymmetry along a path exceeds one half.

Parameters:

Name Type Description Default
adjacency

[S, S] edge weights (see magnetic_laplacian); not needed when eigenvectors are given.

None
q, normalized, remove_self_loops

as in magnetic_laplacian.

required
mode int

which eigenvector, in ascending order of eigenvalue (default 0, the lowest).

0
eigenvectors Optional[Tensor]

the eigenvectors of magnetic_spectrum, to reuse them.

None

Returns:

Type Description
Tensor

float64 tensor [S] of angles.

hermitian_clustering

hermitian_clustering(adjacency, k, n_vectors=None, normalized=False, seed=0, n_init=10)

Clusters of a directed graph that differ by the direction of the flow between them (Cucuringu, Li, Sun and Zanetti, AISTATS 2020).

The Hermitian adjacency H = i (A − Aᵀ) puts +i weight on an edge read one way and −i on the reverse, so a reciprocated edge cancels and only the net direction remains. Its eigenvalues are real and come in pairs ±λ. The rows of its n_vectors eigenvectors of largest |λ| (as real and imaginary parts) are clustered by k-means. Two nodes land together when they send and receive their net flow from the same clusters, even when the symmetrised graph has the same density everywhere. The k-means rows equal, up to a fixed rotation, the rows of the projection Σ g gᴴ onto those eigenvectors, so the clustering is that of the projection.

Parameters:

Name Type Description Default
adjacency

[n, n] edge weights, row i reading column j (attention orientation). Negative weights are clipped; the diagonal carries no direction and is ignored.

required
k int

number of clusters.

required
n_vectors Optional[int]

eigenvectors kept, by decreasing |λ|. Default 2, the leading pair ±λ: the strongest pattern of net flow, which separates the planted blocks of an ordered or cyclic flow between up to four clusters in the tests. A larger even number (up to 2 ⌊k / 2⌋, the largest rank of the k × k antisymmetric matrix of net flows between clusters) can add structure, or noise when the flow pattern has a lower rank.

None
normalized bool

use D^{-1/2} H D^{-1/2} with D the degrees of A + Aᵀ, which keeps high-degree nodes from dominating the leading eigenvectors.

False
seed int

seeds k-means (best of n_init k-means++ runs).

0

Returns:

Type Description
FlowClusters

class:FlowClusters: labels, the flow and imbalance matrices

FlowClusters

between clusters, the eigenvalues, the embedding.

flow_imbalance

flow_imbalance(adjacency, labels, k=None)

The flow and imbalance matrices of FlowClusters for any labelling of the nodes (adjacency[i, j]: row i reads column j).

FlowClusters dataclass

FlowClusters(labels, flow, imbalance, eigenvalues, embedding)

Result of hermitian_clustering.

Attributes:

Name Type Description
labels ndarray

[n] cluster of each node, 0 .. k-1, numbered in order of first appearance along the node index.

flow ndarray

[k, k], flow[a, b] = sum of A[i, j] over rows i in cluster a and columns j in cluster b: how much cluster a reads from cluster b (information flows from b to a).

imbalance ndarray

[k, k], flow[a, b] / (flow[a, b] + flow[b, a]) − 1/2 (0 when both are 0), in [−1/2, 1/2] and antisymmetric. Positive when a reads more from b than b reads from a. Its absolute value is the cut imbalance ratio of Cucuringu et al. (2020).

eigenvalues ndarray

eigenvalues of the Hermitian matrix whose eigenvectors were clustered, by decreasing absolute value.

embedding ndarray

[n, 2 l] real and imaginary parts of the l eigenvectors, the rows k-means clustered.

analyze_directed_layer

analyze_directed_layer(signals, operator, config=None, layer=0)

Layer diagnostics of a directed graph: the magnetic counterparts of SpectralAnalyzer.analyze_layer, plus the directed total variation.

The spectral metrics come from the magnetic Laplacian of operator (charge config.magnetic_q, normalised for normalization="sym", unnormalised for "none"), with the definitions of analyze_layer: energy is Σ_c x_cᴴ L x_c (real), spectral_masses are |U^H X|² summed over columns, hfer and spectral_entropy come from them, fiedler_value is the second-smallest eigenvalue and connectivity tests it against the zero tolerance. At q = 0 they equal the symmetric metrics of (P + Pᵀ) / 2. For q > 0 the smallest eigenvalue can be positive (it is zero only when the phases around every cycle cancel), and the energy fractions of the real hidden states do not depend on the direction of the edges (see magnetic_hfer).

Parameters:

Name Type Description Default
signals

[S, d] hidden states (config.project_dim applies, as in analyze_layer).

required
operator

[S, S] row-normalised operator (directed_operator).

required
config Optional[GSPConfig]

graph settings; default GSPConfig(device="cpu").

None
layer int

layer index stored in the diagnostics.

0

Returns:

Type Description
SpectralDiagnostics

(diagnostics, extras): a SpectralDiagnostics (its

Dict[str, object]

eigenvectors are complex) and ``{"directed_tv": float, "phase":

Tuple[SpectralDiagnostics, Dict[str, object]]

[S] array}` (:func:directed_total_variation, :func:magnetic_phase`).

Operator spectra

Added in 0.5.1. The attention as an operator between weighted function spaces (the operator namespace, options operator_measure, operator_heads, operator_edges); see Operator spectra in the attention geometry. Implemented from the equations of Viganò, Melzi and Ovsjanikov (NeurIPS 2026); not checked against official code, which is not released as of 15 Nov 2026.

attention_operator

attention_operator(A, measure='pullback', *, normalize_rows=False, average_heads=False, return_difference=False, row_tol=ROW_TOL)

The symmetric matrix S = Ω_μ^{-1/2} Aᵀ Ω_π A Ω_μ^{-1/2} of an attention map, similar to the self-adjoint operator D = Ω_μ⁻¹ Aᵀ Ω_π A on L²(μ) (see the module notes).

Parameters:

Name Type Description Default
A

[..., n, n] attention, row i the query (one head, a stack of heads, or any batch). It need not be causal.

required
measure Measure

"pullback" (π = 1/n, μ = Aᵀπ), "counting" (μ = π = 1, S = D = AᵀA) or a pair (mu, pi) of non-negative [..., n] measures on the keys and the queries, used as given (not normalised).

'pullback'
normalize_rows bool

divide each row of A by its sum first (a zero row stays zero), for weights that are not row-stochastic, such as value-weighted edges (value_weighted_edges).

False
average_heads bool

average A over its heads (dimension -3) first, for the operator of the head-averaged attention; the rows are normalised after the average.

False
return_difference bool

also return D.

False
row_tol float

under the pullback measure without normalize_rows, every row must sum to 0 or to 1 within this tolerance (the pullback construction assumes a row-stochastic A; rows that sum to 0 are queries that read nothing). Rows are not renormalised, so λ₁ = 1 holds up to the rounding of the row sums.

ROW_TOL

Returns:

Type Description

S ([..., n, n], float64, exactly symmetric), or (S, D).

Ω_μ⁻¹ is the pseudo-inverse on zero-mass keys.

Implemented from the equations of Viganò, Melzi and Ovsjanikov (NeurIPS 2026); not checked against official code, which is not released as of 15 Nov 2026.

operator_spectrum

operator_spectrum(A, measure='pullback', *, normalize_rows=False, average_heads=False, eigenfunctions=True, row_tol=ROW_TOL)

Eigenvalues and eigenfunctions of D = Ω_μ⁻¹ Aᵀ Ω_π A on L²(μ), from the symmetric matrix S of attention_operator (same arguments).

If S u = λ u, then φ = Ω_μ^{-1/2} u satisfies D φ = λ φ, and the φ are orthonormal in L²(μ). The eigenvalues are the squared gains ‖Aφ‖²_π / ‖φ‖²_μ: under the pullback measure the first is 1, with a constant eigenfunction; under the counting measure they are the squared singular values of A.

Returns:

Type Description
OperatorSpectrum

class:OperatorSpectrum, eigenvalues in decreasing order.

Implemented from the equations of Viganò, Melzi and Ovsjanikov (NeurIPS 2026); not checked against official code, which is not released as of 15 Nov 2026.

operator_measures

operator_measures(A, measure='pullback', *, normalize_rows=False, average_heads=False)

The measures (mu, pi) on the keys and the queries, [..., n] each, float64: π = 1/n and μ = Aᵀ π for "pullback", ones for "counting", or the given pair broadcast to A's batch shape. normalize_rows and average_heads as in attention_operator.

operator_metrics

operator_metrics(A, measure='pullback', *, normalize_rows=False, average_heads=False, row_tol=ROW_TOL, return_eigenvalues=False)

Participation ratio, centred participation ratio and contraction √λ₂ of the operator of A (arguments as in attention_operator), one value per matrix: [...] for A of shape [..., n, n]. For one value per head pass [heads, n, n]; for the operator of the head-averaged attention add average_heads=True. return_eigenvalues adds the spectrum ("eigenvalues", [..., n], decreasing).

Implemented from the equations of Viganò, Melzi and Ovsjanikov (NeurIPS 2026); not checked against official code, which is not released as of 15 Nov 2026.

participation_ratio

participation_ratio(eigenvalues, centered=False, normalized=True)

Participation ratio of a spectrum, (Σ λ)² / Σ λ², over the last dimension.

normalized=True divides by the number of eigenvalues n, which gives PR = (1/n) (Σλ)² / Σλ²: 1/n for one active mode, rank/n for a flat non-zero spectrum, invariant to a global rescaling. centered=True leaves out the largest eigenvalue (the constant mode under the pullback measure, where it equals 1) and normalises by n - 1: PR_cent = (1/(n-1)) (Σ_{k≥2} λ_k)² / Σ_{k≥2} λ_k². A spectrum whose (remaining) eigenvalues all vanish has ratio 0.

Parameters:

Name Type Description Default
eigenvalues

[..., n] (tensor, array or list), in any order.

required

Returns:

Type Description

[...], a tensor for a tensor input, a NumPy value otherwise.

OperatorSpectrum dataclass

OperatorSpectrum(eigenvalues, eigenfunctions, mu, pi)

Spectrum of the operator D of attention_operator.

Attributes:

Name Type Description
eigenvalues Tensor

[..., n] in decreasing order, float64, rounding below zero clipped to 0.

eigenfunctions Optional[Tensor]

[..., n, n], column k the eigenfunction of eigenvalues[..., k], orthonormal in L²(μ) on the keys of positive mass (None when not asked for). A zero-mass key has the indicator e_j (see the module notes).

mu Tensor

[..., n] measure on the keys.

pi Tensor

[..., n] measure on the queries.

spectrum_metrics

spectrum_metrics(eigenvalues)

The scalars of OPERATOR_METRIC_NAMES from a spectrum [..., n] in decreasing order: the participation ratio, its centred variant, and the contraction √λ₂ (the largest gain on signals of μ-mean zero under the pullback measure; 0 when n = 1).

Forman curvature

Added in 0.5.1. Per-edge curvature of attention graphs and its summaries (graph.forman_curvature_mean, option forman_weights); see Directed and value-weighted graphs. Implemented from the equations of Kim, Lutzeyer and Guo (2026); not checked against official code.

forman_curvature

forman_curvature(adjacency, directed=True, weights='neg_log', eps=FORMAN_EPS, average_heads=False)

Forman curvature of every edge of a weighted graph (module notes).

Parameters:

Name Type Description Default
adjacency

[..., S, S] non-negative edge weights, row i the query (source) and column j the key (target): an attention map, a head-averaged attention, value-weighted edges or any graph. Entries > 0 off the diagonal are the edges; the diagonal is ignored.

required
directed bool

the directed curvature (edges into the source, edges out of the target). With False the adjacency must be symmetric and the undirected curvature is returned (a symmetric matrix).

True
weights Weights

"neg_log" (w = max(-log a, eps), for weights in (0, 1] such as attention), "attention" (w = a), "unit" (w = 1, the combinatorial curvature) or a callable mapping the adjacency to positive weights.

'neg_log'
eps float

floor of the negative-log weight.

FORMAN_EPS
average_heads bool

average over dimension -3 (heads) first.

False

Returns:

Type Description
Tensor

[..., S, S] float64: F(i, j) on each edge, NaN where there is

Tensor

no edge (and on the diagonal).

forman_quantiles

forman_quantiles(curvature, tokens=None, quantiles=FORMAN_QUANTILES, direction='out', empty=0.0)

Quantiles of the curvatures of the edges of a set of tokens, pooled.

Parameters:

Name Type Description Default
curvature

[..., S, S] from forman_curvature.

required
tokens Tokens

the tokens whose edges are pooled: None (all), one index, a (start, end) span (slice semantics) or a list of indices.

None
quantiles Sequence[float]

levels in [0, 1]; linear interpolation between order statistics.

FORMAN_QUANTILES
direction str

"out" (edges leaving the tokens, the default), "in" or "all".

'out'
empty float

the value of every quantile when the set has no edge.

0.0

Returns:

Type Description
Tensor

[..., len(quantiles)].

For the curvature vector of a step, take the curvature of the graph of the prefix that ends with the step, forman_curvature(A[..., :T, :T]), and the step's tokens as a span (T_prev, T); one vector per layer, stacked over layers.

forman_node_curvature

forman_node_curvature(curvature, direction='out', reduce='mean', empty=0.0)

One value per token: reduce ("mean", "median", "min", "max" or "sum") of the curvatures of its edges ("out", "in" or "all"), and empty for a token with no such edge. [..., S, S] in, [..., S] out.

graph_curvature_summary

graph_curvature_summary(adjacency, directed, weights='neg_log', quantiles=FORMAN_QUANTILES)

The mean curvature over the edges of one graph [S, S] and the quantiles of all its edge curvatures (each undirected edge counted once); 0 and zeros for a graph without edges. The graph namespace's forman_curvature_mean and forman_quantiles.

Integrations

Added in 0.5.1. Each needs its optional extra; see LM-Polygraph bridge.

SpectralTrustEstimator

SpectralTrustEstimator(metric='operator.participation_ratio', *, layers=None, layer_aggregation='mean', head_aggregation='mean', sign=1.0, span='all', config=None, name=None)

Bases: Estimator

A spectral-trust metric as a sequence-level LM-Polygraph estimator.

Parameters:

Name Type Description Default
metric str

one attention metric, namespaced ("operator.participation_ratio", "graph.fiedler_value", "attn.hfer") or bare when only one namespace has it. Hybrid metrics (which read hidden states) are refused: the forward-pass statistic holds attention only.

'operator.participation_ratio'
layers Optional[Union[int, Sequence[int]]]

layer indices to measure (negative values count from the end); default every layer.

None
layer_aggregation, head_aggregation

"mean", "median", "max", "min" or "sum". Heads are reduced first, for the per-head metrics (attn, operator per head).

required
sign float

the score is sign times the aggregated metric (higher means more uncertain in LM-Polygraph).

1.0
span str

"all" (prompt and generation), "prompt" or "generated" (the greedy tokens): the induced subgraph, as token_span of compute_spectra.

'all'
config Optional[GSPConfig]

graph and operator options (GSPConfig); default the library defaults on CPU.

None
name Optional[str]

the estimator's name in LM-Polygraph tables; default one built from the arguments.

None

score

score(attention, n_generated=0)

The score of one item, from its [layers, heads, S, S] attention (NaN padding allowed) and the number of generated tokens at its end. Usable without LM-Polygraph's manager; NaN for an empty span.

Per-column diagnostics

per_column_metrics

per_column_metrics(signals, laplacian, config=None, operator=None)

Energy, smoothness index, spectral entropy and HFER of each column of signals on the graph of laplacian.

Column j gets exactly what SpectralAnalyzer(config).analyze_layer(signals[:, j:j+1], laplacian, layer) reports for it (the same eigenbasis, mode-count rule and thresholds: zero HFER and entropy below a total energy of 1e-8, zero smoothness below a squared norm of 1e-8), from one eigendecomposition for all columns. config.project_dim does not apply, since each column is its own one-dimensional signal.

Example, the attention-graph HFER of every SAE feature on a passage::

gc = st.GraphConstructor(cfg)
adj = gc.aggregate_heads(gc.symmetrize_attention(attn[None]))  # [1, S, S]
L = gc.construct_laplacian(adj)[0]
cols = st.per_column_metrics(feature_acts, L, cfg)  # [S, n_features]
cols.metric("hfer")                                  # [n_features]

Parameters:

Name Type Description Default
signals

[seq, d] (or [seq] for one column), a torch tensor or an array.

required
laplacian

[seq, seq] (a leading dimension of size 1 is accepted), e.g. from GraphConstructor.construct_laplacian.

required
config Optional[GSPConfig]

supplies eigen_solver and hfer_cutoff_ratio. Defaults to GSPConfig(device="cpu").

None
operator

optional [seq, seq] row-normalised directed operator P (directed_operator). When given, a fifth column "directed_tv" holds each column's directed total variation ‖x − P x‖² / ‖x‖² (directed_total_variation), how much one step of attention transport changes the feature.

None

Returns:

Type Description
ColumnDiagnostics

class:ColumnDiagnostics with a [d, 4] value matrix

ColumnDiagnostics

([d, 5] with operator).

ColumnDiagnostics dataclass

ColumnDiagnostics(values, metric_names, eigenvalues)

Per-column metrics of one signal matrix on one graph.

values is [d, 4] over COLUMN_METRIC_NAMES, one row per column of the signals. eigenvalues is the graph's spectrum, in ascending order.

metric

metric(name)

One metric for every column, as a [d] array.

Graphs and layer diagnostics

GSPConfig dataclass

GSPConfig(model_name='gpt2', max_length=512, device='cuda' if torch.cuda.is_available() else 'cpu', head_aggregation='uniform', symmetrization='symmetric', normalization='sym', hfer_cutoff_ratio=0.1, num_eigenvalues=50, eigen_solver='dense', lanczos_max_iter=1000, project_dim=None, project_seed=0, batch_size=1, num_layers_analyze=None, save_attention=True, save_activations=True, output_dir='./gsp_results', save_plots=True, display_plots=False, save_intermediate=True, verbose=True, trust_remote_code=False, torch_dtype='float32', device_map=None, local_files_only=False, runs=1, temperature=1.0, plot_metrics=None, latex_export=False, model_kwargs=dict(), remove_self_loops=False, directed=False, calc_velocity=False, subgraph_indices=None, subgraph_renormalize=False, attention_layer_map=None, edge_weights='attention', graph_direction='symmetric', magnetic_q=0.25, operator_measure='pullback', operator_heads='per_head', operator_edges='attention', forman_weights='neg_log')

Configuration for GSP diagnostics

GraphConstructor

GraphConstructor(config)

Constructs dynamic attention graphs from transformer attention patterns

layer_graph

layer_graph(edges, attn_mask=None)

The head-averaged graph of a layer, as config defines it.

With graph_direction="symmetric" (the default) it is aggregate_heads(symmetrize_attention(edges)), the adjacency every measurement of the library builds. With "directed" it is directed_operator(aggregate_heads(edges)): heads are aggregated without symmetrisation and each row is divided by its sum, which gives the causal row-normalised operator P (spectral_trust.directed.directed_operator; symmetrization does not apply).

Parameters:

Name Type Description Default
edges Tensor

[B, H, S, S] per-head edge weights (attention, or value_weighted_edges with per_head=True), or [B, S, S] for one edge matrix per item (value-weighted edges summed over heads), row i reading column j.

required
attn_mask Optional[Tensor]

as in aggregate_heads.

None

Returns:

Type Description
Tensor

[B, S, S].

directed_operator

directed_operator(adjacency)

Row-normalised operator P = D_out^-1 A of a directed adjacency (config.remove_self_loops applies); see spectral_trust.directed.directed_operator.

magnetic_laplacian

magnetic_laplacian(adjacency, q=None, dtype=torch.complex128)

Magnetic Laplacian of a directed adjacency, normalised for normalization="sym" and unnormalised for "none", with charge q (default config.magnetic_q); see spectral_trust.directed.magnetic_laplacian.

symmetrize_attention

symmetrize_attention(attention)

Symmetrize attention matrix according to specified method Args: attention: [batch, heads, seq_len, seq_len] attention tensor Returns: Symmetrized attention tensor

aggregate_heads

aggregate_heads(attention, attn_mask=None)

Aggregate multi-head attention into single adjacency matrix. attention: [B, H, Q, K] attn_mask: if provided, True for real tokens. Either [B,Q] or broadcastable to [B,1,Q,K]. Used only for weighting in 'attention_weighted'. returns: [B, Q, K]

construct_laplacian

construct_laplacian(adjacency)

Construct graph Laplacian from adjacency matrix. Negative weights are set to zero: signed graphs are not supported yet. Args: adjacency: [batch, seq_len, seq_len] adjacency matrix Returns: Graph Laplacian matrix

subgraph_laplacian

subgraph_laplacian(full_adjacency, target_indices)

Extract induced subgraph adjacency and build its Laplacian. full_adjacency: [B, N, N] target_indices: list of token indices to isolate

SpectralAnalyzer

SpectralAnalyzer(config)

Performs spectral analysis and computes GSP diagnostics

project_signals

project_signals(signals)

Apply the configured Johnson-Lindenstrauss projection (config.project_dim) to [seq_len, d] signals. Returns the signals unchanged when projection is off or project_dim >= d. The matrix is cached per (d, k, seed, dtype), so every layer of a model shares one projection.

compute_eigendecomposition

compute_eigendecomposition(laplacian)

Compute eigendecomposition of graph Laplacian.

Dispatches on the operator: symmetric Laplacians (normalization="sym" or "none") use a symmetric solver; non-symmetric ones (normalization="rw") use a general solver, since eigh/eigsh read only the lower triangle and would otherwise diagonalize a different, symmetrized matrix.

Parameters:

Name Type Description Default
laplacian ndarray

[seq_len, seq_len] Laplacian matrix

required

Returns: eigenvalues, eigenvectors (eigenvectors are orthonormal only for symmetric operators)

compute_eig_energy staticmethod

compute_eig_energy(eigenvalues)

Mean Laplacian eigenvalue (trace / T). Attention-only.

compute_eig_spectral_entropy staticmethod

compute_eig_spectral_entropy(eigenvalues)

Entropy of the eigenvalue distribution, normalized to [0, 1] by log(#modes). Attention-only.

compute_eig_hfer staticmethod

compute_eig_hfer(eigenvalues)

Fraction of eigenvalue mass in the upper half of the spectrum. Attention-only.

compute_dirichlet_energy

compute_dirichlet_energy(signals, laplacian)

Compute Dirichlet energy of signals on graph, tr(X^T L X).

Evaluated as sum(X * (L X)): one S x S by S x d product, O(S^2 d) time and O(S d) memory. The d x d matrix X^T L X is never formed (before 0.4.0 it was, at O(S d^2) cost). Accumulated in float64.

Parameters:

Name Type Description Default
signals ndarray

[seq_len, embedding_dim] signal matrix

required
laplacian ndarray

[seq_len, seq_len] Laplacian matrix

required

Returns: Total Dirichlet energy

compute_smoothness_index

compute_smoothness_index(signals, laplacian, energy=None)

Compute smoothness index (normalized energy), tr(X^T L X) / ||X||_F^2.

Parameters:

Name Type Description Default
signals ndarray

[seq_len, embedding_dim] signal matrix

required
laplacian ndarray

[seq_len, seq_len] Laplacian matrix

required
energy Optional[float]

the Dirichlet energy, if already computed (analyze_layer passes it so that it is evaluated once)

None

Returns: Smoothness index

compute_spectral_masses staticmethod

compute_spectral_masses(signals, eigenvectors)

Energy of the signals in each eigenmode, ||u_k^T X||^2: the one projection onto the eigenbasis that entropy, HFER and spectral masses share.

compute_spectral_entropy

compute_spectral_entropy(signals, eigenvectors)

Compute spectral entropy of signals Args: signals: [seq_len, embedding_dim] signal matrix eigenvectors: [seq_len, num_eigenvectors] eigenvector matrix Returns: Spectral entropy

spectral_entropy_from_masses staticmethod

spectral_entropy_from_masses(spectral_energies)

Spectral entropy (natural log, unnormalised) of per-mode energies.

compute_hfer

compute_hfer(signals, eigenvectors, eigenvalues, cutoff_ratio)

Compute High-Frequency Energy Ratio Args: signals: [seq_len, embedding_dim] signal matrix eigenvectors: [seq_len, num_eigenvectors] eigenvector matrix eigenvalues: [num_eigenvectors] eigenvalue array cutoff_ratio: Fraction of spectrum to consider as high-frequency Returns: HFER value

hfer_from_masses staticmethod

hfer_from_masses(spectral_energies, cutoff_ratio)

HFER of per-mode energies ordered by ascending eigenvalue: the share of the top num_high_modes(n, cutoff_ratio) modes, the library's single mode-count rule (see fast.num_high_modes).

analyze_layer

analyze_layer(signals, laplacian, layer_idx)

Perform complete spectral analysis for a single layer Args: signals: [seq_len, embedding_dim] activation tensor laplacian: [seq_len, seq_len] Laplacian tensor layer_idx: Layer index Returns: Complete spectral diagnostics

zero_eigenvalue_tolerance staticmethod

zero_eigenvalue_tolerance(eigenvalues, n)

Threshold below which a Laplacian eigenvalue counts as zero.

The tolerance is max(1e-6, 16 * sqrt(n) * eps * lambda_max), with eps of the eigenvalues' dtype. A fixed 1e-6 is crossed by floating-point noise: on unnormalised ("none") graphs, whose eigenvalues scale with the node degrees, and on float32 normalised attention graphs, where the zero mode of gpt2 layer 5 came out at 1.07e-6. The factor 16 leaves a margin of about 8 over the largest float32 error measured on real and synthetic attention graphs. Float64 input keeps the 1e-6 floor. For float32 normalised graphs the threshold is at most about 2e-4 at 2048 tokens, below the Fiedler values attention graphs show in practice.

is_connected classmethod

is_connected(eigenvalues, n)

True when the second-smallest Laplacian eigenvalue is numerically nonzero.

Every graph Laplacian (sym, rw and none) has a zero eigenvalue by construction, so a graph is connected exactly when its algebraic connectivity, the second-smallest eigenvalue, is above zero. Testing only that eigenvalue means noise on the zero mode cannot flip the answer. A single node counts as connected.

SpectralDiagnostics dataclass

SpectralDiagnostics(layer, energy, smoothness_index, spectral_entropy, hfer, eigenvalues, eigenvectors, spectral_masses, fiedler_value, connectivity, spectral_radius=None, max_imaginary=None, eig_energy=None, eig_spectral_entropy=None, eig_hfer=None, families=None)

Container for spectral diagnostics results.

Each metric belongs to a tensor family (see METRIC_FAMILIES / the families field): "attention" metrics are functions of attention weights alone; "hybrid" metrics project residual-stream states onto the attention eigenbasis and therefore require hidden-state access.

GSPDiagnosticsFramework

GSPDiagnosticsFramework(config)

Main framework for GSP-based LLM diagnostics

analyze_text

analyze_text(text, save_results=True, subgraph_indices=None)

Perform complete GSP analysis on input text Args: text: Input text to analyze save_results: Whether to save intermediate results subgraph_indices: Optional list of indices to isolate a specific subgraph Returns: Complete analysis results

analyze_dataset

analyze_dataset(texts, labels=None)

Analyze multiple texts and return results as DataFrame Args: texts: List of input texts labels: Optional labels for texts (e.g., 'hallucination', 'factual') Returns: DataFrame with aggregated results

save_latex_data

save_latex_data(results)

Save analysis results as a LaTeX-friendly .dat file (space-separated) Format suitable for pgfplots: ddplot table {file.dat};

save_comparison_latex_data

save_comparison_latex_data(res1, res2)

Save comparison results as .dat file for PGFPlots

create_visualizations

create_visualizations(results)

Create legacy symmetric diagnostic visualizations (2x2 grid)

visualize_multi_run

visualize_multi_run(run_results_list)

Visualize multiple runs with mean and individual traces. According to user request: If config.plot_metrics is ['all'] (or None): 2 subplots: Left: HFER, Entropy, Fiedler, Smoothness Right: Energy Else: Plot specific metrics.

visualize_comparison

visualize_comparison(result1, result2)

Compare two analysis results side-by-side with optional metric filtering. Output dynamically adjusts rows based on config.plot_metrics.

attention_layer_indices

attention_layer_indices(model_config, n_attentions, n_hidden_states, override=None)

Layer index of each attention tensor a model returns.

Most models return one attention tensor per layer, and tensor i belongs to layer i. Hybrid models (for example Qwen3.5, with linear-attention layers) return attention for their full-attention layers only. Their position in the model is then read from layer_types in the model config (or its text_config): every layer whose type does not name a linear, state-space, recurrent or convolutional mixer. override takes precedence. The hidden state paired with layer l is hidden_states[l + 1], the output of that layer.

Fast diagnostics

row_dirichlet_energy

row_dirichlet_energy(W, X, rows=None, reduction='sum', dtype=torch.float64)

Row-anchored Dirichlet energy, with no eigendecomposition.

.. math:: E_R(W, X) = \sum_{i \in R} \sum_j W_{ij} \, \lVert x_i - x_j \rVert^2

It measures how far each selected token's signal lies from the signals of the tokens it is connected to. With W a raw attention matrix (row i = query i), it is the attention-weighted distance between a query's state and the states it attends to.

Relation to the library's Laplacian normalisations (W symmetric, E taken over all rows, D = diag(W 1), L as built by GraphConstructor.construct_laplacian):

  • normalization="none" (L = D - W): tr(X^T L X) = E(W, X) / 2.
  • normalization="sym" (L = I - D^{-1/2} W D^{-1/2}): tr(X^T L X) = E(W, D^{-1/2} X) / 2 + sum of ||x_i||^2 over isolated tokens (d_i = 0), whose rows of L are the identity.
  • normalization="rw" (L = I - P, P = D^{-1} W): tr(X^T L X) = E(P, X) / 2 + sum_j (1 - c_j) ||x_j||^2 / 2 for a graph without isolated tokens, where c_j = sum_i P_ij is a column sum of P. The second term vanishes only when P is doubly stochastic.

So the row-anchored energy of a subset R is the share of (twice) the combinatorial Dirichlet energy carried by the edges leaving R.

Parameters:

Name Type Description Default
W

edge weights, [..., S, S] (e.g. [H, S, S] for one graph per head). Row i holds the weights of the edges leaving token i.

required
X

signals, [..., S, d], broadcastable against W's leading dimensions ([S, d] shared by every head, or [H, S, d]).

required
rows Rows

tokens to anchor on (indices, a slice, or a boolean mask of length S). None takes every row.

None
reduction str

"sum" (default) sums over the selected rows; "none" returns one value per selected row, [..., |R|].

'sum'
dtype dtype

computation dtype. The expansion d_i ||x_i||^2 - 2 x_i . (W X)_i + (W ||x||^2)_i is evaluated after centring X (the energy is translation invariant), and float64 keeps its cancellation error far below the float32 noise of the inputs. Only the selected rows of W are converted.

float64

Returns:

Type Description
Tensor

Tensor of shape [...] (reduction="sum") or [..., |R|].

row_value_spread

row_value_spread(A, V, rows=None, reduction='sum', dtype=torch.float64)

Attention-weighted spread of the values around each query's output.

.. math:: \mathrm{spread}i = \sum_j A \, \lVert v_j - o_i \rVert^2, \qquad o_i = \sum_j A_{ij} v_j

For a row-stochastic A (softmax attention) this is the variance of the value vectors under query i's attention distribution, sum_j A_ij ||v_j||^2 - ||o_i||^2: zero when the query attends to a single token (or to identical values), large when it averages values that disagree. No eigendecomposition is involved.

Parameters:

Name Type Description Default
A

attention weights, [..., S, S] (e.g. [H, S, S]); row i is query i. Rows need not sum to one; the formula above is used as written.

required
V

value vectors, [..., S, d] broadcastable against A ([H, S, d_head] for per-head values).

required
rows Rows

queries to evaluate (as in row_dirichlet_energy).

None
reduction str

"sum" over the selected rows, or "none".

'sum'
dtype dtype

computation dtype (default float64; only the selected rows of A are converted).

float64

Returns:

Type Description
Tensor

Tensor of shape [...] (reduction="sum") or [..., |R|].

top_band_hfer

top_band_hfer(L, X, cutoff_ratio=0.1, method='auto')

Exact high-frequency energy ratio from the top band of the spectrum.

For a symmetric Laplacian with full orthonormal eigenbasis U the spectral energies sum to the signal energy, sum_k ||u_k^T X||^2 = ||U^T X||_F^2 = ||X||_F^2, so

.. math:: \mathrm{HFER} = \frac{\lVert U_{\text{high}}^T X \rVert_F^2}

where U_high holds the eigenvectors of the top num_high_modes eigenvalues. Only those eigenpairs are computed. The result equals SpectralAnalyzer.compute_hfer with eigen_solver="dense" (to ~1e-8 in float32, ~1e-15 in float64).

How it differs from the truncated solver: eigen_solver="sparse" (the default before 0.4.0) with num_eigenvalues=50 keeps 25 bottom and 25 top modes once S > 50, and divides the energy of the top int(0.1 * 50) = 5 retained modes by the energy of the 50 retained modes. That is a different quantity (a fixed number of modes, normalised over a truncated basis); this function returns the full-basis ratio at any S, as the default eigen_solver="dense" does.

If the boundary eigenvalue is degenerate (lambda_{S-k} = lambda_{S-k-1}), the split by index is basis-dependent for every solver, dense included; attention graphs with continuous weights do not hit this in practice.

Parameters:

Name Type Description Default
L

symmetric Laplacian [S, S] (normalization="sym" or "none"), numpy or torch. The random-walk Laplacian is not symmetric, its eigenbasis is not orthonormal, and the identity above does not hold; it raises ValueError.

required
X

signals [S, d].

required
cutoff_ratio float

fraction of modes counted as high frequency (GSPConfig.hfer_cutoff_ratio, default 0.1).

0.1
method str

eigensolver, see top_band_eigenvectors.

'auto'

Returns:

Type Description
float

HFER in [0, 1]; 0.0 when ||X||_F^2 < 1e-8 (the dense path's

float

convention).

num_high_modes

num_high_modes(seq_len, cutoff_ratio)

The library's rule for how many modes HFER counts as high frequency: seq_len - int((1 - cutoff_ratio) * seq_len), i.e. the modes from index int((1 - cutoff_ratio) * seq_len) up, in ascending eigenvalue order. Every HFER path uses it: SpectralAnalyzer.compute_hfer (seq_len = number of modes in the basis, 50 under the truncated eigen_solver="sparse"), top_band_hfer and per_head_hybrid_metrics.

It equals ceil(cutoff_ratio * seq_len) except where floating-point rounding of (1 - cutoff_ratio) * seq_len lands just below an integer (cutoff_ratio=0.3, seq_len=90: 28 rather than 27). With the default 0.1 the two agree for every seq_len below 5000. The rule is kept as it is so that results do not change.

The eigenvalue-only eig_hfer and the per-head attention hfer are different metrics: eigenvalue mass in the upper half of the spectrum (index seq_len // 2 up), independent of cutoff_ratio.

Raises:

Type Description
ValueError

if cutoff_ratio is outside [0, 1].

gaussian_projection

gaussian_projection(dim, k, seed=0, dtype=np.float32)

Seeded Gaussian Johnson-Lindenstrauss matrix R of shape [dim, k] with i.i.d. N(0, 1/k) entries, so E[R R^T] = I.

For any PSD matrix A (here X^T L X, X^T X or X^T U_band U_band^T X) the estimate tr(R^T A R) is unbiased for tr(A) with relative standard deviation sqrt(2 ||A||_F^2 / k) / tr(A) <= sqrt(2 / k). Energy and spectral masses are therefore unbiased; smoothness, HFER and entropy are ratios or functions of such estimates and carry an O(1/sqrt(k)) error.

The matrix is drawn as standard_normal((k, dim)).T / sqrt(k) in float64, then cast: for one seed, the first k' columns of the k-column matrix times sqrt(k / k') are exactly the k'-column matrix.

jl_project

jl_project(X, k, seed=0)

Project signals X ([..., dim], numpy or torch) to [..., k] with gaussian_projection. Returns the input type, on the input's device, in float32 or float64 (half-precision inputs are widened to float32 first). If k >= dim the signals are returned unchanged.

band_energies

band_energies(L, X, edges=8, order=64, lambda_max=None, method='chebyshev', project_dim=None, seed=0)

Signal energy in eigenvalue bands of a symmetric Laplacian.

The exact band energy is E_b = sum_{k: lambda_k in band b} ||u_k^T X||^2 = tr(X^T 1_b(L) X). method="chebyshev" replaces the indicator 1_b by its Jackson-damped Chebyshev expansion of degree order on [0, lambda_max]:

.. math:: \hat E_b = \sum_{m=0}^{N} g_m c_m^{(b)} \, \mathrm{tr}\big(X^T T_m(\tilde L) X\big)

All bands share the moments (chebyshev_moments), so the cost is ceil(order / 2) products L @ Y (O(order S^2 d)) against O(S^3) for a dense eigendecomposition. It wins when order * d is small next to S; pass project_dim to shrink d first (energies stay unbiased, see gaussian_projection).

Properties of the estimate: each \hat E_b >= 0; when the bands partition [0, lambda_max] they sum to ||X||_F^2 exactly; and \hat E_b = sum_k p_b(lambda_k) ||u_k^T X||^2 with p_b given by band_filter_response. Modes within about pi * lambda_max / (2 * order) of an interior edge are shared between the two neighbouring bands, which is the whole approximation error.

Parameters:

Name Type Description Default
L

symmetric Laplacian [S, S] (numpy or torch, any device).

required
X

signals [S, d].

required
edges

number of uniform bands on [0, lambda_max] (default 8), or explicit increasing edges in eigenvalue units. Band b is [edges[b], edges[b+1]); the last band includes its right edge.

8
order int

Chebyshev degree N (method="chebyshev").

64
lambda_max Optional[float]

an upper bound on the spectrum. Pass 2.0 for normalization="sym" (its spectrum lies in [0, 2]) so that uniform bands mean the same thing for every input. Default: the Gershgorin bound of L, which depends on the input (1.0 if L is zero).

None

Raises:

Type Description
ValueError

if L is not symmetric (the rw operator), since both methods rely on an orthonormal eigenbasis.

method

"chebyshev" or "dense" (exact, torch.linalg.eigh).

(project_dim, seed)

optional Johnson-Lindenstrauss projection of X.

Returns:

Type Description

(energies, edges): numpy arrays [B] and [B + 1].

band_entropy

band_entropy(energies, normalize=False)

Entropy of the band-energy distribution, -sum_b p_b log p_b with p_b = E_b / sum E, natural log (the convention of SpectralAnalyzer.compute_spectral_entropy). normalize=True divides by log B.

This is not the hybrid spectral_entropy. That one is the entropy of the per-mode distribution over all S modes; this one coarse-grains the modes into B eigenvalue bands. With exact band energies the grouping inequality gives band_entropy <= spectral_entropy, with equality only when each band holds the mass of a single mode; the two are on different scales (at most log B against log S) and should not be compared or mixed across analyses. With Chebyshev energies the edge smoothing adds a further, small difference.

band_filter_response

band_filter_response(lam, edges, order, lambda_max)

The damped polynomial filters evaluated at eigenvalues lam: [B, len(lam)]. band_energies with method="chebyshev" returns exactly response @ spectral_masses, which is how its error against the true band indicators can be read off a dense spectrum.

Sink measures, orientation and reference features

Added in 0.5.1, in spectral_trust.features; see What a symmetrised spectrum cannot see and Baselines.

sink_mass

sink_mass(attention, sink=0)

Mean attention that the queries after the sink give to it.

mean_{i > sink} A[i, sink], per head and layer.

Parameters:

Name Type Description Default
attention

[..., S, S] attention weights, row i the query (for example [layers, heads, S, S]).

required
sink int

index of the sink token (default the first).

0

Returns:

Type Description

[...] (a float for one [S, S] map). Zero when no query

follows the sink.

value_norms

value_norms(values, out_weight)

Norm of what each token writes through each head: ‖W_O^h v^h_j‖.

Parameters:

Name Type Description Default
values

[..., heads, S, head_dim] value vectors per head (after the value projection and its bias). Grouped-query layouts with fewer value heads are repeated to the query heads.

required
out_weight

output projection as an nn.Linear weight, [d_model, heads * head_dim] (for GPT-2's Conv1D, pass c_proj.weight.T). Head h owns columns h * head_dim:(h + 1) * head_dim.

required

Returns:

Type Description

[..., heads, S]. A[h, i, j] times entry [h, j] is the norm

of token j's contribution to head h's output at token i (Kobayashi

et al. 2020); output gates, where a model has them, are not applied.

value_weighted_sink

value_weighted_sink(attention, values, out_weight, sink=0)

Sink score weighted by what the sink writes: ‖W_O^h v^h_sink‖ · sink_mass^h.

It is the mean, over the queries after the sink, of the norm of the sink's contribution to head h's output. A head can pour most of its attention into a sink whose value vector is near zero (a no-op); this score is small for such a head and large when the sink writes.

Parameters:

Name Type Description Default
attention

[..., heads, S, S].

required
values, out_weight

as in value_norms, with the same leading dimensions as attention.

required
sink int

index of the sink token.

0

Returns:

Type Description

[..., heads].

effective_rank

effective_rank(x)

Effective rank (Roy and Vetterli 2007): exp(-Σ p_k log p_k) with p = s / Σ s from the singular values s.

Parameters:

Name Type Description Default
x

[..., n, d]: hidden states [S, d], attention maps [heads, S, S], or any batch of matrices.

required

Returns:

Type Description

[...] (a float for one matrix), between 1 and min(n, d); 0

for a zero matrix.

attention_covariates

attention_covariates(attention, values=None, out_weight=None, sink=0)

Per-head attention-family covariates, to report next to (or regress out of) any spectral feature of the same heads.

Parameters:

Name Type Description Default
attention

[..., heads, S, S] (for example [layers, heads, S, S]).

required
values, out_weight

optional, as in value_weighted_sink; with them value_weighted_sink is included.

required
sink int

index of the sink token.

0

Returns:

Name Type Description
Dict[str, object]

name -> [..., heads] (n_tokens is an int). sink_mass is

Dict[str, object]

func:sink_mass, value_weighted_sink value_weighted_sink,

Dict[str, object]

diagonal_mass the mean of A[i, i] over queries,

Dict[str, object]

previous_token_mass the mean of A[i, i - 1] over queries

Dict[str, object]

i >= 1, row_entropy the mean over queries of

Dict[str, object]

-Σ_j A[i, j] log A[i, j] (nats), attention_effective_rank

the Dict[str, object]

func:effective_rank of each map, asymmetry the coefficient

Dict[str, object]

G of Dahlem et al. (spectral_trust.features.asymmetry)

Dict[str, object]

and n_tokens is S.

transport_operator

transport_operator(attention)

M = D_Q^{-1/2} B D_K^{-1/2} for each [..., S, S] map B (row and column sums as degrees; a zero degree gives a zero row or column). For a row-stochastic B its largest singular value is 1 (Dahlem et al., Theorem 3(i)). Returns a float64 tensor.

asymmetry

Orientation and capacity of an attention head, after Dahlem, Maniloff and Misiura, "Self-Attention as Transport: Orientation Blindness and the Limits of Symmetric Spectral Diagnostics" (arXiv 2605.04893, v3).

A head's row-stochastic attention B is read through the degree-normalised operator (their Definition 1, eq. 1)::

M = D_Q^{-1/2} B D_K^{-1/2},   D_Q = diag(B 1),  D_K = diag(Bᵀ 1).

Its Frobenius-orthogonal split M = M_sym + M_asym separates capacity (M_sym: every transpose-invariant spectral diagnostic lives there, so it cannot tell M from Mᵀ) from orientation (M_asym).

  • asymmetry is their coefficient G = ‖M_asym‖_F / (‖M‖_F + ε) (eq. 7);
  • capacity_phi is their spectral-sweep conductance estimate φ̂ (Sections 3 and 5), and transport_sigma2 the second singular value of M that the Cheeger inequality ties to it.

Implemented from the paper's equations: the authors have released no code (checked 15 Nov 2026), so these functions are not checked against theirs.

transport_operator

transport_operator(attention)

M = D_Q^{-1/2} B D_K^{-1/2} for each [..., S, S] map B (row and column sums as degrees; a zero degree gives a zero row or column). For a row-stochastic B its largest singular value is 1 (Dahlem et al., Theorem 3(i)). Returns a float64 tensor.

asymmetry

asymmetry(attention, normalize='degree', eps=0.0)

Asymmetry coefficient G = ‖M_asym‖_F / (‖M‖_F + ε), with M_asym = (M − Mᵀ) / 2 (Dahlem et al., eq. 7).

G lies in [0, 1]: 0 iff M is symmetric, 1 iff it is skew. A causal map has G <= 1/√2, reached by a strictly lower-triangular map; G near 0 in a decoder means the head attends to itself only (their "temporal isolation"). G(M) = G(Mᵀ): it measures how much orientation there is, not which way it points.

Parameters:

Name Type Description Default
attention

[..., S, S].

required
normalize Optional[str]

"degree" (default) measures the degree-normalised operator M of the paper; None measures the map itself, ‖A_asym‖_F / ‖A‖_F.

'degree'
eps float

the stabiliser ε of eq. 7 (the paper's G(M, 0) is eps=0). A zero map gives 0.

0.0

Returns:

Type Description

[...] (a float for one map).

transport_sigma2

transport_sigma2(attention)

Second singular value σ₂ of M per map ([...]); the spectral gap 1 − σ₂ bounds the conductance through the Cheeger inequality (1 − σ₂)/2 <= φ <= sqrt(2 (1 − σ₂)) (Dahlem et al., eq. 3).

capacity_phi

capacity_phi(attention, graph='normalized')

Spectral-sweep conductance estimate φ̂ of a head's bipartite transport graph (Dahlem et al., Sections 3 and 5).

The S queries and S keys are ranked by the second singular vectors of M (the vector (u₂; v₂), the second eigenvector of the dilation H(M)), and φ̂ is the smallest conductance w(S, S̄) / min(vol S, vol S̄) over the 2S − 1 threshold cuts of that ranking. Low φ̂: a bottleneck (concentrated routing); high: diffuse routing. An estimate: the exact conductance is NP-hard and can only be lower.

Parameters:

Name Type Description Default
attention

[..., S, S] row-stochastic maps.

required
graph str

"normalized" (default) measures the cuts on N_bip = H(M), the graph the paper's estimator sweeps; "raw" on A_bip = H(B), the raw attention weights.

'normalized'

Returns:

Type Description

[...] (a float for one map). When σ₂ is repeated the ranking,

and so φ̂, depends on the solver's choice of singular vectors.

capacity_phi

capacity_phi(attention, graph='normalized')

Spectral-sweep conductance estimate φ̂ of a head's bipartite transport graph (Dahlem et al., Sections 3 and 5).

The S queries and S keys are ranked by the second singular vectors of M (the vector (u₂; v₂), the second eigenvector of the dilation H(M)), and φ̂ is the smallest conductance w(S, S̄) / min(vol S, vol S̄) over the 2S − 1 threshold cuts of that ranking. Low φ̂: a bottleneck (concentrated routing); high: diffuse routing. An estimate: the exact conductance is NP-hard and can only be lower.

Parameters:

Name Type Description Default
attention

[..., S, S] row-stochastic maps.

required
graph str

"normalized" (default) measures the cuts on N_bip = H(M), the graph the paper's estimator sweeps; "raw" on A_bip = H(B), the raw attention weights.

'normalized'

Returns:

Type Description

[...] (a float for one map). When σ₂ is repeated the ranking,

and so φ̂, depends on the solver's choice of singular vectors.

transport_sigma2

transport_sigma2(attention)

Second singular value σ₂ of M per map ([...]); the spectral gap 1 − σ₂ bounds the conductance through the Cheeger inequality (1 − σ₂)/2 <= φ <= sqrt(2 (1 − σ₂)) (Dahlem et al., eq. 3).

geometry_of_reason

geometry_of_reason(attentions, hidden_states, *, normalization='sym', hfer_cutoff_ratio=0.1, eigen_solver='sparse', num_eigenvalues=50, lanczos_max_iter=1000, symmetrization='symmetric', head_aggregation='uniform', remove_self_loops=False, attention_mask=None, arpack_seed=None)

The Geometry of Reason features of one text, per layer, computed as the paper's released code computed them (spectral-trust 0.1.2, GSPDiagnosticsFramework.analyze_text with its default GSPConfig).

Parameters:

Name Type Description Default
attentions Sequence

one [1, heads, S, S] (or [heads, S, S]) tensor per layer, as a Hugging Face model returns with output_attentions=True. Their dtype is kept up to the Laplacian, as in 0.1.2.

required
hidden_states Sequence

the layers + 1 states [1, S, d] (or [S, d]) that output_hidden_states=True returns, embeddings first; layer l is measured on hidden_states[l + 1].

required
normalization str

the 0.1.2 GSPConfig field, at its value in the paper's run, as are hfer_cutoff_ratio, eigen_solver, num_eigenvalues, lanczos_max_iter, symmetrization, head_aggregation and remove_self_loops.

'sym'
attention_mask

the tokenizer's [1, S] mask; it only matters for head_aggregation="attention_weighted".

None
arpack_seed Optional[int]

None reproduces 0.1.2, whose ARPACK calls (sparse solver, more than 50 tokens) start from a random vector; an int fixes that start vector, so repeated runs agree.

None

Returns:

Type Description
Dict[str, ndarray]

fiedler_value, energy, smoothness, entropy and

Dict[str, ndarray]

hfer (GOR_FEATURES), one float64 array [layers] each.

geometry_of_reason_text

geometry_of_reason_text(model, tokenizer, text, max_length=512, **kwargs)

geometry_of_reason of text, tokenised and run as 0.1.2's LLMInstrumenter.process_text did (special tokens, truncation to max_length tokens). Load the model with attn_implementation="eager" so that it returns attention weights.

drop_and_renormalize

drop_and_renormalize(attention, drop=0, *, keep=None)

Attention with some tokens removed and every remaining row divided by its new sum, so each query again spreads unit mass over the kept keys.

This is the BOS-drop construction of Bao et al. (2026): drop the sink (drop=0) and renormalise the rows. GSPConfig.subgraph_indices and token_span drop nodes without renormalising; with GSPConfig.subgraph_renormalize=True they renormalise as here.

Parameters:

Name Type Description Default
attention Tensor

[..., S, S] attention weights, row i the query.

required
drop

index or indices of the tokens to remove (default the first token). Ignored when keep is given.

0
keep

indices of the tokens to keep, in order.

None

Returns:

Type Description
Tensor

[..., k, k] with the kept tokens. A row whose kept entries sum to

Tensor

zero stays zero.

Pseudospectra

Added in 0.5.1.

Pseudospectra and other measures of non-normality (Trefethen and Embree, "Spectra and Pseudospectra", Princeton 2005).

Causal attention is lower-triangular, hence non-normal: its eigenvalues are its diagonal and govern only the limit of its powers and products, while finite depth is governed by resolvent quantities (Li 2026, arXiv 2607.09279 and 2607.06621). For a matrix A and ε > 0:

  • the ε-pseudospectrum Λ_ε(A) = {z : σ_min(zI − A) < ε} (pseudospectrum, sigma_min);
  • its radius ρ_ε and abscissa α_ε (pseudospectral_radius, pseudospectral_abscissa);
  • the Kreiss constant K(A) = sup_{|z|>1} (|z| − 1) ‖(zI − A)⁻¹‖ = sup_ε (ρ_ε − 1)/ε, which brackets the transient, K <= sup_k ‖A^k‖ <= e n K (kreiss_constant);
  • Henrici's departure from normality (departure_from_normality);
  • the numerical range and radius (numerical_range);
  • all of them at once, for one matrix or for the products of a stack of layers, the depth propagator (nonnormality, depth_propagator).

σ_min(zI − A) is computed on a triangular form: the matrix itself when it is triangular (causal attention), otherwise its complex Schur form A = Q T Qᴴ (σ_min is unitarily invariant). Each point then costs O(n²) per inverse-iteration step, by two triangular solves, against O(n³) for a dense SVD. All computations are in complex128.

Pseudospectrum dataclass

Pseudospectrum(z, sigma_min, eigenvalues, eps=())

σ_min(zI − A) on a grid of points z.

Attributes:

Name Type Description
z ndarray

complex grid ([len(im), len(re)] for a (re, im) grid).

sigma_min ndarray

same shape as z.

eigenvalues ndarray

eigenvalues of A.

eps tuple

the levels asked for, or ().

inside

inside(eps)

Boolean mask of the grid points in the ε-pseudospectrum.

NumericalRange dataclass

NumericalRange(boundary, radius, abscissa)

Field of values W(A) = {xᴴAx : ‖x‖ = 1} (a convex set).

Attributes:

Name Type Description
boundary ndarray

points of its boundary, one per angle.

radius float

numerical radius w(A) = max |z| over W(A), with ‖A‖₂/2 <= w(A) <= ‖A‖₂.

abscissa float

numerical abscissa max Re z over W(A), the initial growth rate d/dt ‖e^{tA}‖ at t = 0.

sigma_min

sigma_min(A, z, *, method='auto', tol=1e-11, max_iter=300)

σ_min(zI − A) at the points z (any shape), the distance from A to the nearest matrix with z as an eigenvalue.

Parameters:

Name Type Description Default
A

[n, n] matrix (tensor or array).

required
z

complex points.

required
method str

"auto" (inverse iteration with triangular solves, O(n²) per step and point) or "svd" (a dense SVD per point, O(n³)).

'auto'
tol, max_iter

stopping rule of the inverse iteration (relative change of the estimate). The estimate approaches σ_min from above.

required

pseudospectrum

pseudospectrum(A, grid=None, eps=None, *, n_points=100, method='auto', tol=1e-11, max_iter=300)

σ_min(zI − A) on a complex grid; its level sets are the boundaries of the ε-pseudospectra Λ_ε(A) = {z : σ_min(zI − A) < ε}.

Parameters:

Name Type Description Default
A

[n, n] matrix. A triangular matrix (causal attention) is used as it is; any other is reduced to its complex Schur form first.

required
grid

complex points of any shape, or a pair (re, im) of 1-D arrays (a mesh with re along columns), or None for a square of n_points × n_points covering |z| <= ‖A‖₂ + max(eps).

None
eps

optional level or levels (kept in the result; see Pseudospectrum.inside).

None
method, tol, max_iter

as in sigma_min.

required

Values below about 1e-15 ‖A‖ are not resolved by float64 and are reported as they come (the triangular solves resolve them further than a dense SVD does).

pseudospectral_radius

pseudospectral_radius(A, eps, *, n_angles=180, refine=2, tol=None, method='auto')

ε-pseudospectral radius ρ_ε(A) = max{|z| : σ_min(zI − A) <= ε}.

Each of n_angles rays from the origin is marched inward from ‖A‖₂ + ε to its outermost crossing (never skipping one, since σ_min is 1-Lipschitz), then the best direction is refined refine times. The result is at least ρ(A) + ε, which always holds, and approaches ρ_ε from below as the rays refine.

pseudospectral_abscissa

pseudospectral_abscissa(A, eps, *, n_lines=181, refine=2, tol=None, method='auto')

ε-pseudospectral abscissa α_ε(A) = max{Re z : σ_min(zI − A) <= ε}, by the same inward march along n_lines horizontal lines. At least max Re λ + ε.

kreiss_constant

kreiss_constant(A, eps_grid=None, *, how='radii', n_angles=36, refine=1, method='auto')

Kreiss constant K(A) = sup_{ε>0} (ρ_ε(A) − 1)/ε = sup_{|z|>1} (|z| − 1) ‖(zI − A)⁻¹‖₂. It brackets the transient growth of the powers: K <= sup_k ‖A^k‖₂ <= e·n·K.

Parameters:

Name Type Description Default
A

[n, n] matrix.

required
eps_grid Optional[Sequence[float]]

levels for how="radii" (default logspace(-8, 8, 9)).

None
how str

"radii" (default) estimates it from pseudospectral_radius on eps_grid, refined by a golden-section search in log ε; "resolvent" maximises (|z| − 1)/σ_min(zI − A) over |z| = 1 + 10^s, s ∈ [-10, 8], on a polar grid refined around its best point. Both are lower bounds that converge as their grids refine.

'radii'
n_angles, refine

rays and refinement rounds.

required

Returns:

Type Description
float

inf when ρ(A) > 1. For a causal row-stochastic matrix K

float

is √n (Li 2026, Proposition 1), approached as ε → 0.

departure_from_normality

departure_from_normality(A, relative=False)

Henrici's departure from normality dep_F(A) = ‖N‖_F, where A = Q (D + N) Qᴴ is a Schur decomposition with N strictly triangular; equivalently sqrt(‖A‖_F² − Σ|λ_i|²), 0 iff A is normal. For a triangular matrix it is the norm of its off-diagonal part, with no factorisation.

Parameters:

Name Type Description Default
A

[..., n, n].

required
relative bool

divide by ‖A‖_F (a number in [0, 1]).

False

Returns:

Type Description

[...] (a float for one matrix).

numerical_range

numerical_range(A, n_angles=180, refine=2)

Numerical range of A from its rotated Hermitian parts H_θ = (e^{iθ}A + e^{-iθ}Aᴴ)/2 (Johnson's algorithm): the top eigenvector x_θ of H_θ gives the boundary point x_θᴴ A x_θ, and w(A) = max_θ λ_max(H_θ), refined refine times around the best angle.

depth_propagator

depth_propagator(layers, deflate=False, sink=0)

Products of a stack of layer operators over depth: Π_L = A_L ⋯ A_2 A_1 for L = 1..len(layers), with layer 1 applied first (for attention, one head-averaged map per layer).

With deflate=True each factor is A_l − P, P = 1 e_sinkᵀ. For causal row-stochastic maps, which all share that Perron projector, Π_L(A) − P = Π_L(A − P) (Li 2026, Proposition 2): the deflated products carry the deviation from the stationary (all-to-sink) state.

Returns:

Type Description
ndarray

[L, n, n].

nonnormality

nonnormality(A, eps=0.01, *, depth=False, deflate=False, sink=0, kreiss=True, **kwargs)

The non-normality summaries of one matrix, or of every depth product.

Parameters:

Name Type Description Default
A

[n, n]; with depth=True a stack [L, n, n] whose products (depth_propagator) are summarised.

required
eps float

level of the pseudospectral radius and abscissa.

0.01
depth, deflate, sink

as in depth_propagator.

required
kreiss bool

include the Kreiss constant (the most expensive summary).

True
kwargs

passed to kreiss_constant (how, n_angles).

{}

Returns:

Type Description
Dict[str, object]

name -> value ([L] arrays with depth=True): norm (2-norm),

Dict[str, object]

spectral_radius, spectral_abscissa, pseudospectral_radius

Dict[str, object]

and pseudospectral_abscissa at eps, kreiss_constant,

Dict[str, object]

henrici and henrici_relative, numerical_radius and

Dict[str, object]

numerical_abscissa. With depth=True also Li's references for

Dict[str, object]

the propagator: eigen_heuristic Π_l ρ(A_l) and norm_bound

Dict[str, object]

Π_l ‖A_l‖₂ (of the deflated factors with deflate=True), to

Dict[str, object]

compare with norm.