Repository navigation
Releases
spectral-trust 0.5.3: controls for numerical in-context learning
Controls and generators for follow-up studies of numerical in-context
learning. No result changes for existing calls.
spectral_trust.numeric.dynamics: seeded generators of the sequence
families of Bao et al. (2026),periodic(period p),logistic(the
logistic map at r, with burn-in) andlorenz(one chosen coordinate, RK4),
and of smooth families,sine(a chosen frequency),damped_oscillator
(closed form) andpendulum(Stormer-Verlet, symplectic; the energy drift
is reported). Each returns aTrajectorywith the raw values and the
integers of the000-999format;generate(name, ...)andFAMILIES
name them.numeric.token_preserving_shuffle(values, seed): the values in a random
order, with the exact multiset of tokens kept.numeric.inventory_covariates:
the number of distinct values, the share of values seen before, the
entropy of the value distribution and, with a tokenizer, the number of
distinct token ids, per sequence, ready as covariates of
st.confound_audit.numeric.rollout(model, tokenizer, values, n_steps, target=...):
multi-step extrapolation that feeds back the mode of
next_value_distribution(or its rounded mean) and reports the absolute
and cumulative error per step against the true continuation. The prompt
runs once and each step extends its key-value cache, so an edit of
st.edit_with_controlsreaches every step;numeric.RolloutReadout
makes a rollout that function's readout.- Value-weighted graphs in the numeric diagnostics:
profile_from_outputs(..., edge_weights="value" | "value_per_head", edges=...)builds the graph fromst.value_weighted_attention(the same
edges ascompute_spectraunderGSPConfig.edge_weights), and
numeric.profile(model, ids, edge_weights=...)runs the forward pass and
the value capture. λ2, HFER and SE matchcompute_spectraon the same
inputs;giniandsink_massstill read the attention. profile_from_outputs(..., center=True, center_positions=...): subtracts
each layer's mean hidden state (over the value tokens, or every node)
before the graph Fourier transform, removing the DC component; an ablation
of the authors' updated paper, to be aligned with their code once it is
public. Off by default.st.interventions.sink_bias(model, layers, b, hub=0)and
Intervention.sink_bias: add the logitbto every query's attention
score toward the hub key (default the first real token) at the chosen
layers, through eager attention, on the additive mask, so it holds under
cached generation and left padding;b = 0installs nothing. Undone on
exit like the other interventions.next_value_distribution: the hierarchical readout can start from an
existing key-value cache (internal; the same numbers).
Install: pip install -U spectral-trust==0.5.3
Library page: https://vcnoel.github.io/software/spectral-trust.html#numeric-053
spectral-trust 0.5.2: a fix for recent transformers
A fix for recent transformers releases. No result changes.
numerichierarchical next-value readout: the key-value cache is cropped
with a negative length, which everytransformersrelease accepts; recent
releases refused the positive length 0.5.1 passed.- Tests: across platforms, the 0.5.0 regression test skips the outputs that
depend on the eigenvector basis (Fiedler vector, spectral masses), and the
sparse Geometry of Reason case allows for ARPACK's platform differences.
Bit-identity is still asserted in the environment that wrote the fixtures.
Install: pip install -U spectral-trust==0.5.2
Library page: https://vcnoel.github.io/software/spectral-trust.html#graphs-051
spectral-trust 0.5.1: more graphs, and the measures others use
Directed and value-weighted attention graphs, measure-aware operator
spectra, Forman curvature and an LM-Polygraph bridge. No result changes for
existing calls: with the new options at their defaults, and without naming
the new opt-in metrics, every result is bit-identical to 0.5.0.
- Value-weighted edges (
spectral_trust.value_weighted): the attention
output at token i splits into one vector per key token plus the output
bias,c_ij = Σ_h a^h_ij W_O^h (g^h_i ⊙ v^h_j), and the edge from j to i
is‖c_ij‖(Kobayashi et al. 2020), or one norm per head. New names:
value_weighted_attention,capture_attention_values,AttentionValues
(contributions,edge_weights,reconstruct),ValueCapture,
value_weighted_edgesandattention_contributions. Grouped-query
attention, fused projections (GPT-2, Phi-3, GPT-NeoX), value and output
biases (the output bias is in no contribution) and the output gates of
Qwen3.5 and Qwen3-Next are covered; on hybrid models only the
full-attention layers have a graph. The contributions rebuild the
attention output to a float32 relative error below 1e-4 on ten layouts. - Directed graphs (
spectral_trust.directed):directed_operator
(P = D_out⁻¹ A),directed_total_variation(‖x − P x‖² / ‖x‖², per
column withper_column=True), the magnetic Laplacian
(magnetic_laplacian,magnetic_spectrum,magnetic_hfer,
magnetic_phase), flow-imbalance clustering (hermitian_clustering,
flow_imbalance,FlowClusters) andanalyze_directed_layer. The
magnetic HFER of a real signal is identical for a graph and its
transpose; the directed total variation is not. per_column_metrics(..., operator=P)adds adirected_tvcolumn.GSPConfiggainsedge_weights("attention","value",
"value_per_head"),graph_direction("symmetric","directed")
andmagnetic_q(default 0.25).GraphConstructorgains
layer_graph,directed_operatorandmagnetic_laplacian;EDGE_WEIGHTS,GRAPH_DIRECTIONSand
DIRECTED_GRAPH_METRIC_NAMESare exported.SpectralModel.run_with_spectraandcompute_spectra(new argument
edges=) build thegraphnamespace from the options. Directed graphs
are measured on the magnetic Laplacian and addgraph.directed_tvand
the arraygraph.phase.GSPDiagnosticsFramework, the graph filters
and frequency-resolved patching refuse the new options.- New page: Directed and value-weighted graphs.
- Operator spectra (
spectral_trust.operator_spectra): the attention as a
mapL²(μ) → L²(π)and its self-adjoint operatorD = Ω_μ⁻¹ Aᵀ Ω_π A,
under the pullback measure (πuniform,μ = Aᵀπ;λ₁ = 1on the
constant function) or the counting measure (AᵀA), or any pair of
measures. New names:attention_operator,operator_spectrum,
operator_measures,operator_metrics,participation_ratio(and its
centred variant),OperatorSpectrum,OPERATOR_METRIC_NAMES. A key no
query attends to has zero mass;Ω_μ⁻¹is then read as a pseudo-inverse,
which gives it the eigenvalue 0. Implemented from the equations of
Viganò, Melzi and Ovsjanikov (NeurIPS 2026); not checked against official
code, which is not released. - The opt-in
operatornamespace ofrun_with_spectraand
compute_spectra(computed only when named inmetrics=):
participation_ratio,participation_ratio_centered,contraction
(√λ₂) andeigenvalues, per head or per layer, on attention or on the
row-normalised value-weighted attention.GSPConfiggains
operator_measure,operator_headsandoperator_edges;
compute_spectragainsoperator_edges=. - Forman curvature (
spectral_trust.forman):forman_curvatureper edge,
directed or undirected, with negative-log, attention or unit edge
weights;forman_quantilesandforman_node_curvaturesummarise it over
tokens or spans. The opt-ingraph.forman_curvature_mean(with the array
graph.forman_quantiles) measures the layer graph of the graph options;
GSPConfiggainsforman_weights. Implemented from the equations of
Kim, Lutzeyer and Guo (2026); not checked against official code. - LM-Polygraph bridge (
spectral_trust.integrations.lm_polygraph,
optional extrapolygraph):SpectralTrustEstimatorscores any attention
metric as a sequence-level LM-Polygraph estimator. The core package never
imports lm-polygraph. Tested end to end with lm-polygraph 0.7.0 (its
manager, stat calculators and metrics) on GPT-2 and CoQA items. - Fixed: with value-weighted edges, the graph view and the animations
rebuilt the plain attention graph and mixed its eigenpairs with the value
graph's Fiedler vector. A symmetric value-weighted layer graph is now
stored asgraph.adjacencywhen the patterns are kept, and the views use
it; a directed layer graph raises a clear error there. - Fixed: headless Chrome, which the animations use for video, refuses to
start its sandbox as root (Colab, most containers). The launcher now
passes--no-sandboxwhen running as root, or as the environment
variableSPECTRAL_TRUST_BROWSER_NO_SANDBOX(1or0) says. GraphConstructor.construct_laplaciandocuments that negative weights are
set to zero (signed graphs are not supported yet).- New pages: Operator spectra in the attention geometry; LM-Polygraph
bridge. The directed-graphs page gains a Forman curvature section.
Numerical in-context learning, a confound audit and edits with matched
controls. No result changes for existing calls.
spectral_trust.numeric: the serialisation of Bao et al. (2026), value
token spans, the next-value distribution (restricted softmax or
hierarchical digit-wise) and the paper's layer diagnostics with its
non-graph controls (profile_from_outputs).st.confound_audit: raw and covariate-adjusted effects of spectral
readouts with bootstrap intervals.st.edit_with_controls: a graph filter or band patch next to
norm-matched permuted-graph, path-graph, random-subspace and scaling
controls.- Use case "Numerical ICL" and notebook
05_numerical_icl.ipynb.
Measures that answer the critiques of spectral attention diagnostics. No
result changes: every 0.5.0 call is bit-identical
(tests/test_regression_050.py).
GSPConfig.subgraph_renormalize: the nodes kept bysubgraph_indicesor
token_spanare renormalised per row before the graph is built (BOS drop
as in Bao et al.);graph.drop_and_renormalize.spectral_trust.features:sink_mass,value_norms,
value_weighted_sink,effective_rank,attention_covariates; the
asymmetryGand conductanceφ̂of Dahlem et al. (asymmetry,
capacity_phi,transport_sigma2,transport_operator; from their
equations, no released code);geometry_of_reason, the paper's features
on the symmetric normalised Laplacian by default;normalization="rw"
reproduces its first released run bit for bit.spectral_trust.pseudospectra:sigma_min,pseudospectrum,
pseudospectral_radius,pseudospectral_abscissa,kreiss_constant,
departure_from_normality,numerical_range,depth_propagator,
nonnormality.- Docs: "What a symmetrised spectrum cannot see" and "Baselines".
Install: pip install -U spectral-trust==0.5.1
Library page: https://vcnoel.github.io/software/spectral-trust.html#graphs-051
spectral-trust 0.5.0: interventions and use cases
Interventions: the TransformerLens basics (patching, ablation, steering)
on Hugging Face models, and interventions in the graph-spectral domain. No
result changes for existing calls.
- New subpackage
spectral_trust.interventionsand context manager
st.intervene(model): hook-based edits, all undone on exit (hooks
removed, weights restored bit for bit, the attention implementation and
any wrappedtransformersfunction put back). It takes aSpectralModel
or a plaintransformerscausal LM (GPT-2, Llama, Qwen, Mistral, Gemma,
GPT-NeoX and OPT layouts). Interventions on one model may be nested and
closed in any order. Positions are absolute, so position-dependent edits
agree between cached generation and recomputation. - Public names of
spectral_trust.interventions:- edits:
intervene(alsost.intervene),Intervention(resid,
attention,weights,hook,close),ResidSite(add,
graph_filter),AttentionSite(ablate,head_outputs,
edit_pattern,remove_edges),WeightSite(svd_scale,snr,
weight),Edit(remove) andremove_edges_from_pattern; - graph filters:
graph_filter(alsost.graph_filter),FilterSpec,
filter_coefficients,filter_response,ideal_response,
attention_adjacency,path_adjacency,laplacian,laplacian64,
compute_placement,FILTER_KINDS,GRAPH_NAMES,PRECISIONS; - patching:
patch,Patcher,PatchSpec,equal_count_bands(all
four also top-level),select_modes,haar_basis,BASES,SITES; - weights:
weight_snr,weight_svd_full(both also top-level),
matrix_snr,lowrank_snr,svd_scale_matrix; - warning thresholds:
KEEP_SINK_WARN_FACTOR(10) and
GRAPH_FILTER_WARN_RELATIVE_EDIT(0.5).
- edits:
- Graph-frequency steering:
iv.resid(layer).graph_filter(kind, cutoff= | band=, strength=, graph=, causal=)filters the residual stream along the
token axis on that layer's head-averaged attention graph (built as the
measurements build it), the chain graph, or a given graph:
X' = X + s (g(L) X − X). Low-pass, high-pass, band-pass and band-stop
responses use the Jackson-damped Chebyshev machinery ofband_energies
(no eigendecomposition), computed in float64 by default (on the CPU when
the model is on Apple MPS) or in float32 withprecision="float32",
faster on GPUs;method="dense"applies the ideal band indicator.causal=Truefilters each position on the graph
of its prefix, a lower-triangular operator, so generation with a KV cache
matches recomputation, beam search included; a cached step under the
symmetric filter raises. - Head ablation (
ablate("zero" | "mean" | "resample")on the per-head
outputs; mean and resample take a reference, and resample draws its items
once per input, shared by its beams), activation steering
(resid(l).add), custom hooks (iv.hook(site, layer, fn)) and
attention-pattern edits (edit_pattern; these need transformers 4.48 or
later and say so at run time, while the package keeps requiring 4.30). remove_edges(key_mask, keep_sink=True)removes attention edges and
renormalises each edited row over its remaining non-sink keys with the
first token's entry held fixed;keep_sink=Falserenormalises over every
remaining key, the first token included, andrenormalize=Falseonly
zeroes. None of the three is a pure edge ablation when the removed edges
carry most of a row: holding the sink fixed then multiplies the edges
left by a large factor (13 to 181 for the GPT-2 name movers in the IOI
use case).- Weight-spectrum steering:
iv.weights(layer, module).svd_scale(alpha, k=)
applies the spectral-steering rescaling
σ' = σ (1 + α (σ − mean) / std)and warns when a factor turns
non-positive. The rebuilt matrix equals spectral-steering's reference code
bit for bit; the two give the same model for bias-freenn.Linear
projections (the Llama-familymlp.down_proj), since the reference swaps
in a bias-free layer whilesvd_scaleedits the weight in place, keeps
the bias and also handles GPT-2'sConv1D. Edits of one matrix stack and
can be removed in any order. st.weight_snr(model, layer, module)isσ₁ / median(σ)over the full
spectrum (layer=None: every layer).st.weight_snr(W, k)on a tensor and
the newst.weight_svd_full(W)are the two functions of the unreleased
0.2.3 branch that spectral-steering's scripts import, so they run on this
release.- Activation patching:
st.patch(model, clean, corrupt, site=, layer=, head=, positions=)andst.Patcher, which runs the clean and corrupt
inputs once, captures activations as patches need them, batches many
patches, and raises if the model changed since the capture.
Frequency-resolved patching (band=,basis="clean_attention" | "corrupt_attention" | "path" | "random") takes one band of a token-axis
eigenbasis from the clean run; the full band equals plain patching.
st.equal_count_bandssplits the modes into equal-count bands. - Warnings:
remove_edgeswithkeep_sink=Truewarns, once per call,
when it multiplies the kept non-sink attention of any edited row by more
than 10;graph_filteron the residual stream warns, once per call, when
its edit exceeds half the residual norm of the edited positions
(‖X' − X‖ / ‖X‖ > 0.5).svd_scalewarns when a singular value's factor
turns non-positive. - New tutorial: Interventions.
- Use cases (
docs/use-cases/, with scripts and outputs in
examples/use_cases/): edge ablation and the attention sink on GPT-2 IOI,
graph-frequency steering against matched controls, frequency-resolved
patching on IOI, which words split Phi-3-mini's attention graph, the side
effects ofgraph_filteron GPT-2 and Phi-3-mini, and the design of a
band-stop injection defence, which has not been run.
Install: pip install -U spectral-trust==0.5.0
Release post: https://vcnoel.github.io/posts/steering-along-the-token-axis.html
The changelog also documents a known issue in releases before 0.2.2 (the random-walk Laplacian spectrum): https://github.com/vcnoel/spectral-trust/blob/main/CHANGELOG.md
spectral-trust 0.4.2: animated views
Animated views. One call writes a video, a GIF or an interactive page of a
SpectralCache. No computed value changes.
- New
SpectralCache.animate(kind, out, ...)and
st.viz.animate(cache, kind, out, ...). The file suffix picks the format:
.mp4(H.264),.webm(VP9),.gif, or.html(interactive). - Kinds:
flow: each token is a tube through depth, from layer 0 to the last.
Its position at each layer is the attention graph's Fiedler vector
(sign-matched from layer to layer) and third eigenvector, its colour is
the Fiedler side, and its thickness is the attention it receives.
other=outlines the tokens missing from a second prompt, for example an
injected instruction. Drawn with three.js; videos are captured frame by
frame from the same page in headless Chrome, with no new Python
dependency, and fall back to matplotlib when no browser is found.waterfall: the energy share of each graph-frequency mode as 3D
ridgelines through depth, with the HFER band marked.compare: two prompts on shared token positions, with the tokens present
in only one outlined, and the Fiedler value and HFER of both traced
through depth.graph_movie: the circular attention graph morphing through the layers.head_atlas: every head of a layer as small multiples sorted by a
per-head metric, sweeping over the layers.embedding3d: tokens in 3D by Laplacian eigenvectors 2 to 4.
- Okabe–Ito palette, light and dark themes, and deterministic output for a
fixedseed. Rendering runs on the CPU, and ffmpeg uses two threads by
default (threads=). - The
vizextra adds imageio and imageio-ffmpeg. Interactive plotly pages
embed plotly.js when theplotlypackage is installed, and load a pinned
CDN copy otherwise. Flow pages embed three.js r160 (MIT; its licence ships
with the package). - Docs: an animated gallery page.
spectral-trust 0.4.1
A new licence, a per-column metric, parallel layers for the per-head
functions, an explicit device for them, and a corrected tolerance
statement. No result changes for existing calls.
- (licence change) spectral-trust is released under the Apache License
2.0 from this version, instead of AGPL-3.0-or-later, so it can be used in
academic and commercial work, open or closed source. Versions up to 0.4.0
remain under AGPL-3.0-or-later. - New
per_column_metrics(signals, laplacian, config): energy, smoothness
index, spectral entropy and HFER of every column of a signal matrix (one
SAE feature, neuron or probe projection per column) from one
eigendecomposition. Columnjgets whatanalyze_layerreports for
signals[:, j:j+1]alone. Returns aColumnDiagnostics. per_head_metrics_all_layersandper_head_hybrid_metrics_all_layers
takenum_workers: layers are decomposed at once, each on one CPU
thread, with identical results in layer order. At 28 layers, 16 heads and
256 tokens on a 24-thread CPU, 8 workers took the attention metrics from
0.55 s to 0.15 s (3.7x) and the hybrid metrics from 1.30 s to 0.38 s
(3.4x).per_head_metricsandper_head_hybrid_metrics(and their_all_layers
versions) takedevice. The default stays the CPU, which is faster for
many small eigenproblems;"cuda"decomposes on the GPU. They never read
GSPConfig.device, and the docstrings now say so (it defaults to
"cuda"when one is available, which suggested otherwise).- Per-head calls change only their own thread's count. Each call runs its
eigendecomposition on one intra-op thread and restores the count after.
torch.set_num_threadsalso sets the count that threads created later
start with, so in 0.4.0 a thread created during a per-head call started
with one thread and kept it, and could leave one thread as the default
for the rest of the process. The calls now put that default back at once,
from a short-lived helper thread, so threads created meanwhile (including
thenum_workersworkers) start at the process default, and the default
is unchanged afterwards. The cost is about 0.4 ms per call. - The
per_head_hybrid_metricsdocstring said its values match
analyze_layeron each head. They agree to float32 rounding: energy and
smoothness index to about 1e-6 relative, HFER and spectral entropy, which
depend on eigenvectors computed by different float32 solvers (torch and
scipy), up to 8e-5 and 1.2e-3 absolute on Qwen3.5-2B attention with
one-column signals. Both are equally close to a float64 solve.