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
¶
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 |
|
tokenizer |
its tokenizer. |
|
config |
the |
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
|
required | |
tokenizer
|
the tokenizer of an already-loaded model. |
None
|
|
config
|
Optional[GSPConfig]
|
graph-construction settings; default
|
None
|
device
|
Optional[Union[str, device]]
|
where to put a model loaded here ( |
None
|
dtype
|
Union[str, dtype, None]
|
weights dtype for a model loaded here (default float32). |
'float32'
|
**hf_kwargs
|
passed to |
{}
|
to_str_tokens
¶
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
( |
required |
metrics
|
which metrics to keep. None keeps all but the opt-in
|
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 |
None
|
token_span
|
|
None
|
|
hybrid
|
bool
|
compute the metrics that read the hidden states
( |
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
|
None
|
Returns:
| Type | Description |
|---|---|
SpectralCache
|
class: |
SpectralCache
|
|
SpectralCache
|
|
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
¶
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.
token_span
property
¶
The (start, end) span of each text that the metrics cover
(None for the whole sequence; per text for a batch).
metric
¶
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
¶
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
¶
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).
heatmap
¶
Layers x heads heatmap of one metric (see spectral_trust.viz.heatmap).
graph
¶
Attention graph of one layer or head (see spectral_trust.viz.graph).
spectrum
¶
Laplacian spectrum of one layer or head (see spectral_trust.viz.spectrum).
animate
¶
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
¶
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.
HeadSpectra
¶
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"].
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 |
required |
signals
|
Optional[Mapping[int, Tensor]]
|
true layer index -> the residual-stream states paired with
that layer, |
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 |
None
|
config
|
Optional[GSPConfig]
|
graph construction ( |
None
|
metrics, layers, heads, token_span, hybrid, keep_patterns
|
as in
|
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 |
None
|
operator_edges
|
Optional[Mapping[int, Tensor]]
|
the same for the |
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 |
required | |
model
|
the |
None
|
|
tokens
|
the tokens that were run: ids ( |
None
|
|
final_norm
|
bool
|
pair the last layer with |
True
|
attention_mask
|
|
None
|
|
config, metrics, layers, heads, token_span, keep_patterns
|
as in
|
required | |
hybrid
|
Optional[bool]
|
compute the hybrid metrics; None (default) does when the
cache holds |
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,
|
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
|
None
|
model
|
the nnsight |
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 |
None
|
final_norm
|
optional saved output of the final norm
( |
None
|
|
attention_mask
|
|
None
|
|
config, metrics, layers, heads, token_span, keep_patterns
|
as in
|
required | |
hybrid
|
Optional[bool]
|
compute the hybrid metrics; None (default) does when
|
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 |
required | |
model_config
|
the model config, which locates the attention layers
of hybrid models ( |
None
|
|
tokens
|
the input ids (or text, or token strings). |
None
|
|
tokenizer
|
decodes |
None
|
|
attention_mask
|
|
None
|
|
config, metrics, layers, heads, token_span, keep_patterns
|
as in
|
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
¶
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 |
None
|
Added in 0.5.0.
Intervention
¶
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 |
config |
graph construction for the graph filters (the
|
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
¶
The residual stream after block layer (site="post", the
library's pairing: hidden_states[layer + 1]) or before it
(site="pre").
attention
¶
Attention heads of block layer (one head, a list, or None for
all).
weights
¶
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
¶
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
¶
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
¶
The residual stream at one layer; see Intervention.resid.
add
¶
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'
|
strength
|
float
|
|
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 |
False
|
order
|
int
|
Chebyshev degree (no eigendecomposition). |
64
|
method
|
str
|
|
'chebyshev'
|
token_span
|
|
None
|
|
positions
|
Positions
|
edit only these absolute positions (the filter still
reads every position of the graph); non-negative with
|
None
|
precision
|
str
|
|
'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
¶
Attention heads at one layer; see Intervention.attention.
head_outputs
¶
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 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'
|
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 |
None
|
|
positions
|
Positions
|
ablate only at these absolute positions. |
None
|
edit_pattern
¶
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 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): |
required | |
keep_sink
|
bool
|
hold the sink entry fixed (see above). Removing the
sink itself then raises; pass |
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 |
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
¶
A weight matrix of one block; see Intervention.weights.
svd_scale
¶
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
¶
One registered intervention. remove undoes it (closing the
Intervention undoes all of them).
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
¶
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 |
|
|
|
|
|
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 |
required | |
clean, corrupt
|
text, texts or ids ( |
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 ( |
None
|
layers, sites
|
activations to cache up front ( |
required | |
forward_kwargs
|
Optional[dict]
|
extra keyword arguments of every forward call (for
example |
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
¶
Drop every cached activation and basis, and rerun the clean and corrupt inputs on the model as it is now.
activation
¶
A cached activation of the "clean" or "corrupt" run (or
site="pattern": attention weights [B, H, S, S]).
basis
¶
(eigenvalues [B, S] or None, U [B, S, S]), columns in ascending
eigenvalue order (float64).
patch_many
¶
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
¶
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
|
|
layer |
int
|
block index. |
head |
Union[None, int, Sequence[int]]
|
head or heads for |
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 |
basis |
Union[str, Tensor]
|
one of |
n_modes |
Optional[int]
|
keep the first |
seed |
int
|
seed of the random basis. |
equal_count_bands
¶
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
¶
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-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 |
required |
attention
|
Optional[Tensor]
|
attention weights |
None
|
kind
|
str
|
|
'lowpass'
|
cutoff
|
Optional[float]
|
eigenvalue cutoff for low-pass and high-pass filters (the
|
None
|
band
|
Optional[Tuple[float, float]]
|
|
None
|
strength
|
float
|
|
1.0
|
graph
|
GraphSpec
|
|
'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'
|
config
|
Optional[GSPConfig]
|
graph construction; default the library defaults. |
None
|
token_span
|
|
None
|
|
precision
|
str
|
|
'float64'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The filtered signal, same shape, dtype and device as |
filter_coefficients
¶
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
¶
The polynomial response g(lambda) the Chebyshev filter applies at
eigenvalues lam (what method="chebyshev" does to each mode).
ideal_response
¶
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
¶
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
¶
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
¶
GraphConstructor.construct_laplacian computed in float64 (or
dtype), with the same formulas and the same handling of self-loops
and isolated positions.
compute_placement
¶
(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
¶
Spectral SNR sigma_1 / median(sigma) of a weight matrix.
Two forms:
weight_snr(model, layer, module): the matrix atmodule(dotted path inside blocklayer;"mlp.down_proj"resolves to the MLP output projection of architectures that name it differently, such as GPT-2'smlp.c_proj), over the full spectrum.layer=Nonereturns one value per layer as a numpy array, a layer sweep.weight_snr(W)orweight_snr(W, k): a 2-D weight tensor. Withoutk, the full spectrum; withk, the fast top-k estimate of the 0.2.3 branch (lowrank_snr), which is what spectral-steering's layer search called asweight_snr(W, k=32).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
a |
required | |
layer
|
Optional[int]
|
block index for a model. For a tensor, a second positional
argument is taken as |
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
¶
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
¶
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.
lowrank_snr
¶
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 |
required | |
inputs
|
Sequence
|
token-id sequences, run one at a time. |
required |
readout
|
Readout
|
|
required |
layer
|
int
|
block index. |
required |
edit
|
str
|
|
'graph_filter'
|
kind, cutoff, band, causal, order
|
the filter ( |
required | |
strengths
|
Sequence[float]
|
|
(0.25, 0.5, 1.0)
|
controls
|
Sequence[str]
|
any of |
('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]
|
|
None
|
modes
|
Optional[Tuple[int, int]]
|
|
None
|
token_span
|
Optional[Tuple[Optional[int], Optional[int]]]
|
|
None
|
config
|
Optional[GSPConfig]
|
graph construction (default the SpectralModel's or the
library defaults; the band patch needs |
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]
|
|
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]]]
|
|
relative_edit |
Dict[float, List[float]]
|
|
skipped |
List[float]
|
strengths left out by |
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
¶
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
¶
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]]
|
|
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. |
quantize
¶
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
¶
Write non-negative integers as zero-padded digits-digit strings
joined by sep (and followed by it when trailing).
value_spans
¶
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
¶
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
¶
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
¶
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 |
required | |
input_ids
|
the prompt, |
required | |
tokenizer
|
default the SpectralModel's. |
None
|
|
digits
|
int
|
digits per value. |
3
|
method
|
str
|
|
'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
¶
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 |
required | |
hidden_states
|
|
None
|
|
layers
|
Optional[Sequence[int]]
|
layer indices (default all). |
None
|
pairing
|
str
|
|
'input'
|
drop
|
Sequence[int]
|
positions removed from the graph and the signal (default the
first, BOS); |
(0,)
|
renormalize
|
bool
|
renormalise attention rows after dropping. |
True
|
hfer_cutoff, n_low, basis
|
see |
required | |
groups
|
Optional[Sequence[Sequence[int]]]
|
optional node groups (positions in the original sequence)
merged by |
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 |
'attention'
|
edges
|
Optional[Mapping[int, object]]
|
with value edges, |
None
|
center
|
bool
|
subtract, in each layer, the mean hidden state over
|
False
|
center_positions
|
Optional[Sequence[int]]
|
positions (in the original sequence) whose mean is
subtracted, e.g. |
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
¶
pos_hfer, pos_spectral_entropy and pos_exp_se of a signal
[n, d] in the orthonormal DCT-II basis along positions.
attention_gini
¶
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
¶
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_from_outputs of one input, forward pass included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
a Hugging Face causal LM or a |
required | |
input_ids
|
|
required | |
edge_weights
|
str
|
|
'attention'
|
**kwargs
|
passed to |
{}
|
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
¶
One realisation of a family.
Attributes:
| Name | Type | Description |
|---|---|---|
values |
ndarray
|
|
ints |
ndarray
|
|
family |
str
|
the generator's name. |
params |
Dict[str, object]
|
its parameters, the seed included. |
periodic
¶
A period-p sequence: p values drawn uniformly in [0, 1)
(distinct for p >= 2) and repeated. p = 1 is a constant.
logistic
¶
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
¶
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
¶
FAMILIES[family](n=n, seed=seed, **params), e.g.
generate("logistic", 200, seed=3, r=3.9, burn_in=1000).
token_preserving_shuffle
¶
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 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 |
None
|
|
digits
|
int
|
digits per value of the serialisation. |
3
|
Returns:
| Type | Description |
|---|---|
Dict[str, object]
|
|
Dict[str, object]
|
per sequence, ready for |
Dict[str, object]
|
for several. |
Dict[str, object]
|
share of values seen before, which ignores order; |
Dict[str, object]
|
func: |
Dict[str, object]
|
contexts instead and changes under a shuffle. |
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
¶
A multi-step extrapolation.
Attributes:
| Name | Type | Description |
|---|---|---|
predicted |
ndarray
|
|
target |
Optional[ndarray]
|
|
entropy |
ndarray
|
|
std |
ndarray
|
|
method |
str
|
|
tol |
float
|
the error that ends |
summary
¶
Scalars for a readout: mean_entropy and, with a target,
mae, first_error, final_error, cum_error (the total)
and valid_steps.
RolloutReadout
¶
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 |
required |
n_steps
|
int
|
values to predict per item. |
required |
**kwargs
|
passed to |
{}
|
rollouts keeps every Rollout computed, in call order.
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 |
required | |
tokenizer
|
default the SpectralModel's. |
required | |
values
|
Optional[Sequence[int]]
|
the context, integers in |
required |
n_steps
|
int
|
values to predict. |
required |
target
|
Optional[Sequence[int]]
|
the true continuation (at least |
None
|
input_ids
|
the prompt as token ids ( |
None
|
|
digits, sep
|
the format. |
required | |
method, min_prob, chunk
|
as in |
required | |
predict
|
str
|
|
'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 |
50.0
|
Rollout
dataclass
¶
A multi-step extrapolation.
Attributes:
| Name | Type | Description |
|---|---|---|
predicted |
ndarray
|
|
target |
Optional[ndarray]
|
|
entropy |
ndarray
|
|
std |
ndarray
|
|
method |
str
|
|
tol |
float
|
the error that ends |
summary
¶
Scalars for a readout: mean_entropy and, with a target,
mae, first_error, final_error, cum_error (the total)
and valid_steps.
RolloutReadout
¶
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 |
required |
n_steps
|
int
|
values to predict per item. |
required |
**kwargs
|
passed to |
{}
|
rollouts keeps every Rollout computed, in call order.
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 |
None
|
|
kind
|
str
|
|
'auto'
|
n_folds
|
int
|
folds of the cross-validated logistic regression. |
5
|
n_boot, ci, seed
|
bootstrap over items ( |
required |
AuditResult
dataclass
¶
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
¶
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
¶
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 of a signal [n, d] (Roy and Vetterli 2007):
exp of the entropy of its normalised singular values.
bootstrap_ci
¶
(estimate, lo, hi): percentile bootstrap interval of stat
over items (or over groups of items, resampled whole).
paired_bootstrap
¶
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
¶
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 |
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
¶
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 |
required | |
metric
|
str
|
metric name, e.g. |
'fiedler_value'
|
text
|
int
|
which text of a batch (per-head metrics). |
0
|
backend
|
str
|
|
'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
¶
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
¶
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.
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 |
required | |
kind
|
str
|
one of |
'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'
|
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 ( |
0
|
wordmark
|
bool
|
draw a small "spectral-trust" wordmark in a corner. |
False
|
plotlyjs
|
str
|
for |
'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. |
{}
|
Examples:
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, |
required |
config
|
Optional[GSPConfig]
|
graph-construction settings (symmetrization, normalization,
self-loops). Defaults to |
None
|
token_span
|
Optional[Tuple[int, int]]
|
optional |
None
|
layer
|
int
|
layer index recorded in the result. |
-1
|
heads
|
HeadSelection
|
compute only these heads. One of: head indices for this layer
( |
None
|
keep_eigenvalues
|
bool
|
also return each head's spectrum in
|
False
|
device
|
Device
|
where the Laplacians are built and decomposed. The default
is the CPU whatever |
'cpu'
|
Returns:
| Type | Description |
|---|---|
PerHeadDiagnostics
|
class: |
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
|
required | |
config, token_span, device
|
as in |
required | |
heads
|
HeadSelection
|
as in |
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 |
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
|
|
required |
signals
|
Tensor
|
|
required |
config, token_span, layer, heads, device
|
as in
|
required |
Returns:
| Type | Description |
|---|---|
PerHeadDiagnostics
|
class: |
PerHeadDiagnostics
|
|
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.
heads_from_scores
¶
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
¶
Flatten per-layer diagnostics into one feature vector for a probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diagnostics
|
List[PerHeadDiagnostics]
|
output of |
required |
metrics
|
Optional[List[str]]
|
metric subset to keep, in order (default: all five). |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
1-D array of length |
ndarray
|
layer-major then head then metric. With head subsets ( |
ndarray
|
each layer contributes its selected heads, in ascending order. |
layer_delta_features
¶
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 |
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 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:
capture_attention_values
¶
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 |
required | |
inputs
|
a string, a list of strings, or token ids ( |
required | |
layers
|
Optional[Sequence[int]]
|
true layer indices (default every softmax-attention layer). |
None
|
tokenizer
|
for text input when |
None
|
|
keep_output
|
bool
|
also keep each attention module's output. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[int, 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
|
|
values |
Tensor
|
|
out_weight |
Tensor
|
|
out_bias |
Optional[Tensor]
|
|
gate |
Optional[Tensor]
|
|
gate_layout |
Optional[str]
|
|
output |
Optional[Tensor]
|
|
lengths |
Optional[List[int]]
|
real length of each batch item (right padding follows). |
contributions
¶
[B, Q, S, d_model] per-key contributions
(attention_contributions).
edge_weights
¶
Value-weighted edges, [B, S, S] or [B, H, S, S]
(value_weighted_edges).
reconstruct
¶
Σ_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
¶
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 |
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
¶
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
|
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
|
|
Tensor
|
input), float32, or float64 when an input is float64. Row i is the |
Tensor
|
query, as for attention. |
attention_contributions
¶
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
|
|
required | |
values
|
|
required | |
out_weight
|
|
required | |
gate
|
|
None
|
|
queries
|
Queries
|
query tokens (index, indices, slice); default all. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Tensor
|
float32, or float64 when an input is float64. |
directed_operator
¶
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
|
|
required | |
remove_self_loops
|
bool
|
zero the diagonal first
( |
False
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
directed_total_variation
¶
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
|
|
required | |
operator
|
|
required | |
per_column
|
bool
|
False (default) treats the |
False
|
Returns:
| Type | Description |
|---|---|
Tensor
|
float64 tensor |
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
|
|
required | |
q
|
float
|
the charge, |
DEFAULT_MAGNETIC_Q
|
normalized
|
bool
|
|
True
|
remove_self_loops
|
bool
|
zero the diagonal first. |
False
|
dtype
|
dtype
|
|
complex128
|
Returns:
| Type | Description |
|---|---|
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
|
|
required | |
adjacency
|
|
None
|
|
q, normalized, remove_self_loops
|
as in |
required | |
cutoff_ratio
|
float
|
as |
0.1
|
per_column
|
bool
|
one value per column ( |
False
|
eigenvectors
|
Optional[Tensor]
|
the |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
float64 tensor, a scalar or |
Tensor
|
1e-8 gets 0, as in |
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
|
|
None
|
|
q, normalized, remove_self_loops
|
as in |
required | |
mode
|
int
|
which eigenvector, in ascending order of eigenvalue (default 0, the lowest). |
0
|
eigenvectors
|
Optional[Tensor]
|
the eigenvectors of |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
float64 tensor |
hermitian_clustering
¶
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
|
|
required | |
k
|
int
|
number of clusters. |
required |
n_vectors
|
Optional[int]
|
eigenvectors kept, by decreasing |
None
|
normalized
|
bool
|
use |
False
|
seed
|
int
|
seeds k-means (best of |
0
|
Returns:
| Type | Description |
|---|---|
FlowClusters
|
class: |
FlowClusters
|
between clusters, the eigenvalues, the embedding. |
flow_imbalance
¶
The flow and imbalance matrices of FlowClusters for
any labelling of the nodes (adjacency[i, j]: row i reads column j).
FlowClusters
dataclass
¶
Result of hermitian_clustering.
Attributes:
| Name | Type | Description |
|---|---|---|
labels |
ndarray
|
|
flow |
ndarray
|
|
imbalance |
ndarray
|
|
eigenvalues |
ndarray
|
eigenvalues of the Hermitian matrix whose eigenvectors were clustered, by decreasing absolute value. |
embedding |
ndarray
|
|
analyze_directed_layer
¶
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
|
|
required | |
operator
|
|
required | |
config
|
Optional[GSPConfig]
|
graph settings; default |
None
|
layer
|
int
|
layer index stored in the diagnostics. |
0
|
Returns:
| Type | Description |
|---|---|
SpectralDiagnostics
|
|
Dict[str, object]
|
eigenvectors are complex) and ``{"directed_tv": float, "phase": |
Tuple[SpectralDiagnostics, Dict[str, object]]
|
[S] array} |
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
|
|
required | |
measure
|
Measure
|
|
'pullback'
|
normalize_rows
|
bool
|
divide each row of |
False
|
average_heads
|
bool
|
average |
False
|
return_difference
|
bool
|
also return |
False
|
row_tol
|
float
|
under the pullback measure without |
ROW_TOL
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
|
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: |
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
¶
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 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
|
|
required |
Returns:
| Type | Description |
|---|---|
|
|
OperatorSpectrum
dataclass
¶
Spectrum of the operator D of attention_operator.
Attributes:
| Name | Type | Description |
|---|---|---|
eigenvalues |
Tensor
|
|
eigenfunctions |
Optional[Tensor]
|
|
mu |
Tensor
|
|
pi |
Tensor
|
|
spectrum_metrics
¶
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 of every edge of a weighted graph (module notes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adjacency
|
|
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'
|
eps
|
float
|
floor of the negative-log weight. |
FORMAN_EPS
|
average_heads
|
bool
|
average over dimension -3 (heads) first. |
False
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Tensor
|
no edge (and on the diagonal). |
forman_quantiles
¶
Quantiles of the curvatures of the edges of a set of tokens, pooled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
curvature
|
|
required | |
tokens
|
Tokens
|
the tokens whose edges are pooled: None (all), one index, a
|
None
|
quantiles
|
Sequence[float]
|
levels in |
FORMAN_QUANTILES
|
direction
|
str
|
|
'out'
|
empty
|
float
|
the value of every quantile when the set has no edge. |
0.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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
¶
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
¶
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'
|
layers
|
Optional[Union[int, Sequence[int]]]
|
layer indices to measure (negative values count from the end); default every layer. |
None
|
layer_aggregation, head_aggregation
|
|
required | |
sign
|
float
|
the score is |
1.0
|
span
|
str
|
|
'all'
|
config
|
Optional[GSPConfig]
|
graph and operator options ( |
None
|
name
|
Optional[str]
|
the estimator's name in LM-Polygraph tables; default one built from the arguments. |
None
|
score
¶
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
¶
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
|
|
required | |
laplacian
|
|
required | |
config
|
Optional[GSPConfig]
|
supplies |
None
|
operator
|
optional |
None
|
Returns:
| Type | Description |
|---|---|
ColumnDiagnostics
|
class: |
ColumnDiagnostics
|
( |
ColumnDiagnostics
dataclass
¶
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.
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
¶
Constructs dynamic attention graphs from transformer attention patterns
layer_graph
¶
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
|
|
required |
attn_mask
|
Optional[Tensor]
|
as in |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
directed_operator
¶
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 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 matrix according to specified method Args: attention: [batch, heads, seq_len, seq_len] attention tensor Returns: Symmetrized attention tensor
aggregate_heads
¶
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 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
¶
Extract induced subgraph adjacency and build its Laplacian. full_adjacency: [B, N, N] target_indices: list of token indices to isolate
SpectralAnalyzer
¶
Performs spectral analysis and computes GSP diagnostics
project_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 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
¶
Mean Laplacian eigenvalue (trace / T). Attention-only.
compute_eig_spectral_entropy
staticmethod
¶
Entropy of the eigenvalue distribution, normalized to [0, 1] by log(#modes). Attention-only.
compute_eig_hfer
staticmethod
¶
Fraction of eigenvalue mass in the upper half of the spectrum. Attention-only.
compute_dirichlet_energy
¶
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 (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
¶
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 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 (natural log, unnormalised) of per-mode energies.
compute_hfer
¶
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 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
¶
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
¶
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
¶
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
¶
Main framework for GSP-based LLM diagnostics
analyze_text
¶
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 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 analysis results as a LaTeX-friendly .dat file (space-separated) Format suitable for pgfplots: ddplot table {file.dat};
save_comparison_latex_data
¶
Save comparison results as .dat file for PGFPlots
create_visualizations
¶
Create legacy symmetric diagnostic visualizations (2x2 grid)
visualize_multi_run
¶
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
¶
Compare two analysis results side-by-side with optional metric filtering. Output dynamically adjusts rows based on config.plot_metrics.
attention_layer_indices
¶
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-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 ofLare 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 / 2for a graph without isolated tokens, wherec_j = sum_i P_ijis a column sum ofP. The second term vanishes only whenPis 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, |
required | |
X
|
signals, |
required | |
rows
|
Rows
|
tokens to anchor on (indices, a slice, or a boolean mask of
length S). |
None
|
reduction
|
str
|
|
'sum'
|
dtype
|
dtype
|
computation dtype. The expansion
|
float64
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of shape |
row_value_spread
¶
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, |
required | |
V
|
value vectors, |
required | |
rows
|
Rows
|
queries to evaluate (as in |
None
|
reduction
|
str
|
|
'sum'
|
dtype
|
dtype
|
computation dtype (default float64; only the selected rows of
|
float64
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of shape |
top_band_hfer
¶
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 |
required | |
X
|
signals |
required | |
cutoff_ratio
|
float
|
fraction of modes counted as high frequency
( |
0.1
|
method
|
str
|
eigensolver, see |
'auto'
|
Returns:
| Type | Description |
|---|---|
float
|
HFER in [0, 1]; 0.0 when |
float
|
convention). |
num_high_modes
¶
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 |
gaussian_projection
¶
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
¶
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 |
required | |
X
|
signals |
required | |
edges
|
number of uniform bands on |
8
|
|
order
|
int
|
Chebyshev degree N ( |
64
|
lambda_max
|
Optional[float]
|
an upper bound on the spectrum. Pass |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
method
|
|
(project_dim, seed)
|
optional Johnson-Lindenstrauss projection of X. |
Returns:
| Type | Description |
|---|---|
|
|
band_entropy
¶
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
¶
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
¶
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
|
|
required | |
sink
|
int
|
index of the sink token (default the first). |
0
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
follows the sink. |
value_norms
¶
Norm of what each token writes through each head: ‖W_O^h v^h_j‖.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
|
required | |
out_weight
|
output projection as an |
required |
Returns:
| Type | Description |
|---|---|
|
|
|
|
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
¶
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
|
|
required | |
values, out_weight
|
as in |
required | |
sink
|
int
|
index of the sink token. |
0
|
Returns:
| Type | Description |
|---|---|
|
|
effective_rank
¶
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
|
|
required |
Returns:
| Type | Description |
|---|---|
|
|
|
|
for a zero matrix. |
attention_covariates
¶
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
|
|
required | |
values, out_weight
|
optional, as in |
required | |
sink
|
int
|
index of the sink token. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
Dict[str, object]
|
name -> |
|
Dict[str, object]
|
func: |
|
Dict[str, object]
|
|
|
Dict[str, object]
|
|
|
Dict[str, object]
|
|
|
Dict[str, object]
|
|
|
the |
Dict[str, object]
|
func: |
Dict[str, object]
|
|
|
Dict[str, object]
|
and |
transport_operator
¶
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).
asymmetryis their coefficientG = ‖M_asym‖_F / (‖M‖_F + ε)(eq. 7);capacity_phiis their spectral-sweep conductance estimateφ̂(Sections 3 and 5), andtransport_sigma2the second singular value ofMthat 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
¶
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 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
|
|
required | |
normalize
|
Optional[str]
|
|
'degree'
|
eps
|
float
|
the stabiliser |
0.0
|
Returns:
| Type | Description |
|---|---|
|
|
transport_sigma2
¶
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
¶
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
|
|
required | |
graph
|
str
|
|
'normalized'
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
and so |
capacity_phi
¶
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
|
|
required | |
graph
|
str
|
|
'normalized'
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
and so |
transport_sigma2
¶
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 |
required |
hidden_states
|
Sequence
|
the |
required |
normalization
|
str
|
the 0.1.2 |
'sym'
|
attention_mask
|
the tokenizer's |
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]
|
|
Dict[str, ndarray]
|
|
geometry_of_reason_text
¶
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
¶
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
|
|
required |
drop
|
index or indices of the tokens to remove (default the first
token). Ignored when |
0
|
|
keep
|
indices of the tokens to keep, in order. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
|
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
¶
σ_min(zI − A) on a grid of points z.
Attributes:
| Name | Type | Description |
|---|---|---|
z |
ndarray
|
complex grid ( |
sigma_min |
ndarray
|
same shape as |
eigenvalues |
ndarray
|
eigenvalues of |
eps |
tuple
|
the levels asked for, or |
NumericalRange
dataclass
¶
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 |
abscissa |
float
|
numerical abscissa |
sigma_min
¶
σ_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
|
|
required | |
z
|
complex points. |
required | |
method
|
str
|
|
'auto'
|
tol, max_iter
|
stopping rule of the inverse iteration (relative
change of the estimate). The estimate approaches |
required |
pseudospectrum
¶
σ_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
|
|
required | |
grid
|
complex points of any shape, or a pair |
None
|
|
eps
|
optional level or levels (kept in the result; see
|
None
|
|
method, tol, max_iter
|
as in |
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) = 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) = max{Re z : σ_min(zI − A) <= ε},
by the same inward march along n_lines horizontal lines. At least
max Re λ + ε.
kreiss_constant
¶
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
|
|
required | |
eps_grid
|
Optional[Sequence[float]]
|
levels for |
None
|
how
|
str
|
|
'radii'
|
n_angles, refine
|
rays and refinement rounds. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
float
|
is |
departure_from_normality
¶
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
|
|
required | |
relative
|
bool
|
divide by |
False
|
Returns:
| Type | Description |
|---|---|
|
|
numerical_range
¶
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
¶
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
|
|
nonnormality
¶
The non-normality summaries of one matrix, or of every depth product.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
|
required | |
eps
|
float
|
level of the pseudospectral radius and abscissa. |
0.01
|
depth, deflate, sink
|
as in |
required | |
kreiss
|
bool
|
include the Kreiss constant (the most expensive summary). |
True
|
kwargs
|
passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, object]
|
name -> value ( |
Dict[str, object]
|
|
Dict[str, object]
|
and |
Dict[str, object]
|
|
Dict[str, object]
|
|
Dict[str, object]
|
the propagator: |
Dict[str, object]
|
|
Dict[str, object]
|
compare with |