Metadata-Version: 2.5
Name: tensor-spectra
Version: 0.1.0
Summary: Reproducible spectral analysis of tensors from Transformer models
Project-URL: Repository, https://github.com/petitquentin/tensor-spectra
Project-URL: Issues, https://github.com/petitquentin/tensor-spectra/issues
Keywords: kv-cache,pytorch,spectral-analysis,transformers
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: accelerate>=1.0
Requires-Dist: dash>=2.18
Requires-Dist: datasets>=3.0
Requires-Dist: jsonschema>=4.23
Requires-Dist: matplotlib>=3.9
Requires-Dist: numpy>=1.26
Requires-Dist: plotly>=5.24
Requires-Dist: pydantic>=2.9
Requires-Dist: pyyaml>=6.0
Requires-Dist: torch>=2.2
Requires-Dist: transformers>=4.45
Description-Content-Type: text/markdown

# TensorSpectra

TensorSpectra is a reproducible Python framework for extracting user-selected tensor
populations from Hugging Face Transformer models and computing numerical and spectral
descriptors. The KV cache is the flagship target, accompanied by queries, hidden states, MLP
activations, attention maps, and decoder projection weights.

The project is under incremental development following [SPECS.md](SPECS.md). Steps 0–14 provide
the reproducible multi-target pipeline from typed configuration and benchmark generation through
extraction, spectral analysis, schema-versioned logging, and the end-to-end CLI.

## Installation

Install the PyPI package (Python 3.10 or newer):

```bash
python -m pip install tensor-spectra==0.1.0
python -m tensor_spectra --help
```

The distribution is named `tensor-spectra`; the Python import is `tensor_spectra`.

## Development setup with uv

Install [uv](https://docs.astral.sh/uv/), then create the project environment and install the
locked dependencies:

```bash
uv sync --dev
```

This creates `.venv` and uses the Python version in `.python-version`. Run commands inside the
environment without activating it:

```bash
uv run pytest
uv run ruff check .
uv run ruff format --check .
```

After changing dependencies, run `uv lock` and commit the updated `uv.lock`.

## Reproducibility core

```python
from tensor_spectra.repro import collect_environment, config_hash, set_global_seed

set_global_seed(7)
environment = collect_environment()
digest = config_hash({"seed": 7, "model": {"dtype": "float32"}})
```

`set_global_seed` seeds Python, NumPy, and PyTorch and enables deterministic PyTorch settings.
`collect_environment` records the key library, platform, accelerator, and repository versions.
`config_hash` produces a stable SHA-256 digest from a configuration-like object.

Bitwise determinism is only promised for the same configuration and pinned environment.
Different hardware, Python/library versions, or accelerator kernels can produce numerical drift;
the environment record exists to make those differences explicit.

## Configuration

A run is described by one YAML file matching section 8 of the specification. Configuration is
strictly typed: unknown fields and unsupported values are rejected instead of being silently
ignored. In particular, model and tokenizer revisions must be supplied explicitly.

```yaml
seed: 7
run_name: tiny-example
model:
  hf_id: hf-internal-testing/tiny-random-LlamaForCausalLM
  revision: 9fb191250dd56d0ba7ec9785a025ed29c03d5998
  dtype: float32
  device_map: cpu
targets:
  selected: [kv_cache.K, kv_cache.V]
data:
  benchmark: synthetic
  task: repeated-tokens
  sequence_lengths: [16]
  n_samples: 2
```

Load, serialize, and hash a configuration through the public API:

```python
from tensor_spectra.config import config_hash, dump_config, load_config

config = load_config(
    "config.yaml",
    overrides=["--model.dtype", "float32", "--targets.selected", "[kv_cache.K]"],
)
dump_config(config, "resolved-config.yaml")
digest = config_hash(config)
```

Override values use YAML syntax, so booleans, numbers, lists, and `null` retain their types. Both
`--data.n_samples 4` and `--data.n_samples=4` forms are accepted. A complete test configuration
is available in [`tests/configs/tiny.yaml`](tests/configs/tiny.yaml).

## Loading and inspecting models

Model and tokenizer loading uses the same required 40-character Hugging Face commit revision for
both artifacts. The configured runtime dtype, device map, attention implementation, and remote-code
policy are applied during loading; models are returned in evaluation mode.

```python
from tensor_spectra.config import load_config
from tensor_spectra.models import describe, load_model_and_tokenizer

config = load_config("config.yaml")
model, tokenizer = load_model_and_tokenizer(config)
architecture = describe(model)
```

`architecture` normalizes common Hugging Face configuration names into `n_layers`, `n_heads`,
`n_kv_heads`, `d_head`, `d_ff`, `hidden_size`, `rope`, and `gqa_factor`. CPU loading is supported
with `model.device_map: cpu`; Hugging Face sharding strategies such as `auto` are passed through.

## Extracting KV-cache matrices

Step 3 provides a target registry and a shared-forward extraction driver. The built-in
`kv_cache.K` and `kv_cache.V` targets read post-projection cache tensors from
`past_key_values` and normalize every layer/head to a detached float32 `[tokens, channels]`
matrix:

```python
import torch

from tensor_spectra.extraction import capture_targets

input_ids = torch.tensor([[1, 2, 3, 4]])
bundles = capture_targets(model, input_ids, config)
keys = bundles["kv_cache.K"]
```

Each `MatrixRecord` carries explicit axis semantics and RoPE flags. Each `TargetBundle` records
the layer/unit counts, matrix shape, original runtime dtype, and whether the attention kernel was
forced. GQA/MQA retains only distinct KV heads by default; set `targets.kv_cache.expand_gqa: true`
to duplicate each KV head across its query-head group for cross-model comparison.

### Additional built-in targets

Step 9 extends the same registry and normalized `TargetBundle` interface:

- `queries.Q` captures per-head pre- or post-RoPE query matrices through architecture-checked
  attention hooks.
- `hidden_states` uses `output_hidden_states=True`; embedding output is optional and recorded as
  layer 0 when included.
- `mlp_activations` captures `pre_activation`, `post_activation`, or `down_proj_in` matrices and
  records the selected hook point.
- `attention_probs` forces eager attention, enforces `max_sequence_length`, and supports
  deterministic randomized top-k spectra marked as `truncated@k`.
- `weights.q_proj`, `weights.k_proj`, `weights.v_proj`, `weights.o_proj`, `weights.up_proj`,
  `weights.gate_proj`, and `weights.down_proj` read static checkpoint weights. Attention
  projections can be split per head without losing exact reconstruction of the original matrix.

All selected activation targets share one model forward per sample. Static targets run without a
benchmark or model forward and serialize under `model_level`; mixed runs analyze static weights
once while activation targets remain per-sample.

### Llama 3.1 8B example

[`examples/llama31_8b_kv.py`](examples/llama31_8b_kv.py) loads the gated Llama 3.1 8B model,
runs a short prompt, and prints architecture metadata plus compact K/V extraction summaries. After
accepting the model license, authenticate once and run it:

```bash
hf auth login
uv run python examples/llama31_8b_kv.py
```

The example automatically resolves the current `main` revision to its immutable commit SHA and
prints that value. This keeps the run reproducible without making the first invocation awkward.
To repeat the exact checkpoint later, pass the printed value with `--revision <commit-sha>`.

The default bf16 checkpoint needs roughly 16 GB just for model weights; additional memory is
required for inference and the cache. `--device-map auto` allows Accelerate to shard or offload
when needed, though sufficient GPU memory is strongly recommended.

Smaller presets use the same report code and are friendlier for local experiments:

```bash
# Gated Meta model, approximately 2 GB in bf16
uv run python examples/llama32_1b_kv.py

# Open 1.1B model, approximately 2.2 GB in bf16
uv run python examples/tinyllama_1b_kv.py

# Open 135M model, approximately 270 MB in bf16
uv run python examples/smollm2_135m_kv.py
```

Every preset accepts the same options, including `--prompt`, `--max-length`, `--dtype`,
`--device-map`, `--revision`, and `--expand-gqa`.

Maximum-information Qwen2.5 Instruct examples are available as shell wrappers around the
end-to-end spectra runner:

```bash
bash examples/run_qwen25_3b_instruct_max_analysis.sh
bash examples/run_qwen25_7b_instruct_max_analysis.sh
```

They select KV cache, queries, hidden states, MLP activations, attention probabilities, static
weights, singular vectors, row/column value-statistic vectors, cross-layer analysis, and
approximation curves. These presets are intentionally heavy; use environment variables such as
`SEQUENCE_LENGTHS`, `N_SAMPLES`, `OUTPUT_VERBOSITY`, `TARGETS`, `NO_FIGURES=1`, or `DRY_RUN=1` to
scale them to available hardware.

Improved presets for every example model are in `examples/improved/`:

```bash
bash examples/improved/run_tinyllama_improved.sh
bash examples/improved/run_smollm2_135m_improved.sh
bash examples/improved/run_llama32_1b_improved.sh
bash examples/improved/run_llama31_8b_improved.sh
bash examples/improved/run_llama31_8b_instruct_improved.sh
bash examples/improved/run_qwen25_3b_improved.sh
bash examples/improved/run_qwen25_7b_improved.sh
bash examples/improved/run_qwen25_14b_improved.sh
```

All presets include `singular_values_depth` (largest/smallest values) and
`singular_value_ratio_depth` (their ratio) by default. They analyze Q/K/V and
hidden states over lengths 32–2048 and share `examples/improved/_run.sh`.
Each model has separate result and figure directories. The Qwen 14B preset saves length-scoped
results in `runs/improved/qwen25-14B/`, and renders combined PNG figures directly into
`figures/improved/qwen25-14B/`. Set `APPROXIMATION=1` to add compression figures or
`SKIP_EXISTING=1` to reuse saved analysis. Model weights alone take approximately 28 GB in bf16.
Keep the same model revision and analysis settings when combining saved sweeps; use a separate
`OUTPUT_DIR` and `FIGURE_DIR` for a different experiment.

Spectra-runner outputs are scoped by their sequence-length list, so separate invocations do not
overwrite one another. For example, `SEQUENCE_LENGTHS=128` writes under a `-s128` run and figure
directory, while longer sweeps use a compact range/count/hash suffix. The other shell wrappers enable
`AGGREGATE_EXISTING=1` by default: after each run, they also rebuild a `-combined` figure directory
from all preserved length runs sharing the same base `RUN_NAME`. Set `FLAT_OUTPUT=1` only when the
old overwrite-prone layout is intentionally wanted. `SKIP_EXISTING=1` now skips model analysis but
still regenerates the latest figures from the saved result.

## Benchmark data

Step 4 provides deterministic benchmark adapters that emit normalized `BenchmarkSample` records
containing `input_ids`, requested and actual lengths, task, source index, and metadata.

The synthetic adapter supports `natural`, `repeated`, and `random` modes. With
`force_exact_length: true`, every mode produces exactly the requested token count. Natural mode
without forcing stays within 10% below the requested length. Sample selection and random tokens are
derived from the configured seed and recorded `source_index`, making them reproducible regardless
of call order.

The real-data adapter uses the pinned
[`self-long/RULER-llama3-1M`](https://huggingface.co/datasets/self-long/RULER-llama3-1M)
dataset for the 13 RULER tasks and supported lengths from 4K through 1M. Its download test is
opt-in:

```bash
uv run pytest -m slow tests/test_data.py
```

Runs selecting only `weights.*` targets return no adapter and do not tokenize or load benchmark
data.

## Core spectral engine

Step 5 provides a pure matrix-to-dictionary engine using an fp32 economy SVD. It computes the
norms, stable/effective/numerical/energy ranks, condition number, power-law or exponential decay,
row/column norm summaries, per-column dynamic range and kurtosis, and optional coherence/top-k
singular vectors described in the specification.

```python
import torch

from tensor_spectra.spectral import SpectralOptions, analyze_matrix

matrix = torch.randn(128, 64)
metrics = analyze_matrix(
    matrix,
    SpectralOptions(compute_singular_vectors=False),
)
print(metrics["rank"]["stable"])
```

Externally computed top-k spectra can be passed to `analyze_spectrum`. Metrics that are not exact
without the missing tail carry explicit `partial_lower_bound`, `lower_bound`, or
`partial_top_k_normalization` statuses. NaN/Inf inputs return `valid: false` with an issue flag;
they do not enter the SVD or crash the analysis run.

## Analysis orchestration

Step 6 applies the spectral engine over every normalized `(target, layer, unit)` record without
target-specific assumptions:

```python
from tensor_spectra.analysis import run

result = run(bundles, config)
```

Per-layer and per-model summaries report the mean, p99, finite count, and non-finite count for each
scalar metric. Depth trends include stable rank, effective rank, and every configured energy-rank
threshold. Optional singular vectors enable cross-unit principal angles. Output granularity controls
whether unit, layer, or only model summaries are retained; `summary`, `spectra`, and `full`
verbosity respectively retain no spectra, singular values, or singular values plus vectors and raw
matrices.

Set `analysis.per_row_value_stats` or `analysis.per_col_value_stats` to retain optional per-row or
per-column vectors for value minima, maxima, sign counts, mean, median, variance, standard
deviation, and quartiles.

See [Model Analysis Output](docs/model-analysis-output.md) for the complete list of fields and
metrics currently calculated during analysis.

## Cross-layer similarity and clustering

Step 10 compares layer representations with linear CKA, principal-angle/Grassmann similarity,
spectral-profile divergence, and optional Procrustes or raw Frobenius measures. Activation units
are concatenated on their shared token axis; static weights use input/output singular subspaces,
where token-anchored CKA is explicitly disabled. Results include symmetric similarity matrices,
adjacent-layer trajectories, deterministic clustering labels/linkage, silhouette scores, and
cross-target adjusted Rand agreement.

`cross_layer.granularity: per_unit` enables identity or Hungarian unit matching. Set
`cross_layer.enabled: false` to skip this heavier analysis.

## Reconstruction approximation

Step 11 adds target-agnostic low-rank, quantization, and combined approximation curves under each
target's `approximation` block. The public pure-function API is also available directly:

```python
from tensor_spectra.approx import combined_pareto, low_rank_curve, quantization_curve

low_rank = low_rank_curve(matrix, [1, 2, 4, 8], whiten=False)
quantized = quantization_curve(matrix, [2, 4, 8], granularity="per_col")
pareto = combined_pareto(matrix, [1, 2, 4], [2, 4, 8], [1.0, 2.0, 4.0])
```

Absolute and fractional ranks are supported. Quantization implements affine or symmetric scales
per tensor, row, column, or flattened group, with optional percentile clipping. Combined analysis
quantizes the truncated-SVD factors and records factor bits, scale/zero-point overhead, bytes,
bits per original value, the complete surface, and budget-selected Pareto points. Weighted
(`low_rank.whiten`) mode minimizes an activation/covariance-weighted reconstruction norm.

## Attention-aware approximation and RoPE comparison

Step 12 measures how KV approximation changes attention logits and causal attention outputs.
Enable it with queries and keys selected; values add the attention-output metric:

```yaml
targets:
  selected: [queries.Q, kv_cache.K, kv_cache.V]
approximation:
  attention_aware:
    enabled: true
```

Low-rank and quantization functional curves are matched by `(layer, head)`, including automatic
GQA/MQA query-to-KV head mapping. Full rank and the explicit 32-bit quantization point are exact
zero-error baselines.

Pre- and post-RoPE keys can be captured through architecture-checked hooks and compared directly:

```python
from tensor_spectra.approx import compare_rope_spectra

config.targets.kv_cache.source = "hooks"
config.targets.kv_cache.rope = "pre"
pre = capture_targets(model, input_ids, config)["kv_cache.K"]
config.targets.kv_cache.rope = "post"
post = capture_targets(model, input_ids, config)["kv_cache.K"]
comparison = compare_rope_spectra(pre, post)
```

## Static figures

Step 13 renders schema-valid result files without loading models. The catalogue is designed around
scientific comparisons rather than individual matrix traces:

For generation commands, panel-by-panel definitions, interpretation guidance, and caveats, see
[`docs/figures-and-analysis.md`](docs/figures-and-analysis.md).

- normalized spectral envelopes for early/middle/late depth, with 10–90% bands and fitted-decay
  annotations;
- normalized effective/energy rank, stable rank, and condition-number profiles over depth and
  sequence length, including head/sample dispersion;
- condition-specific layer-by-unit maps for rank, conditioning, and decay diagnostics;
- row/column norm tails and outlier-channel fractions;
- CKA, principal-angle, and spectral-divergence matrices with adjacent-layer curves, a dendrogram,
  and depth-cluster labels;
- reconstruction, quantization, memory-Pareto, and attention-aware functional-error panels;
- one cross-target `target_comparison` figure for Q/K/V rank scaling and cluster agreement.

Plots that require a single matrix population select the longest requested model/length condition
and state it in the title; they never silently pool different sequence lengths. Use
`--sequence-lengths` or `figures.filters.sequence_lengths` to choose another condition.

```bash
uv run python -m tensor_spectra figures \
  --input runs/experiment/result.json \
  --format png \
  --out figures
```

Inputs may be individual JSON files or directories. Figures can be narrowed by catalogue entry and
by target, model, sequence length, layer, or unit:

```bash
uv run python -m tensor_spectra figures \
  --input runs/ \
  --format pgf \
  --out paper/figures \
  --only inter_layer,approximation,target_comparison \
  --targets queries.Q,kv_cache.K,kv_cache.V \
  --sequence-lengths 4096 16384
```

To plot the largest and smallest singular values against Layer ID, as in
`docs/image.png`, run:

```bash
uv run python -m tensor_spectra figures \
  --input runs/experiment/result.json \
  --out figures/per-layer-svd \
  --only singular_values_depth,singular_value_ratio_depth
```

This writes endpoint and largest-to-smallest ratio plots per target, model, and
sequence length, with median curves
and individual unit/sample points. It requires saved spectra (`spectra` or `full`
verbosity). Full spectra supply the true minimum, including zeros; truncated
top-k spectra supply only the largest value. See the
[figure guide](docs/figures-and-analysis.md) for details.

PNG output uses the headless Agg backend with fixed metadata and styling. PGF output is deterministic
and TeX-engine-independent, containing an inputable `pgfpicture`. Missing spectra or sidecars emit a
warning and skip only the affected figure; summary and aggregate figures continue rendering.

## Interactive web explorer

Step 14 provides a local Plotly Dash explorer backed by the same pure selectors as the static
figures. Launch it with an optional initial result:

```bash
uv run python -m tensor_spectra explore \
  --input runs/experiment/result.json \
  --port 8050
```

Open `http://127.0.0.1:8050` in a browser. A result can also be loaded later through the path field
or upload control. Loading by path allows the server to resolve adjacent NPZ sidecars; uploaded
summary-only JSON remains fully usable for aggregate views.

The explorer offers reactive target, view, metric, sequence-length, layer, unit, and visible-series
controls. It covers spectra, depth/length rank plots, heatmaps, norms, inter-layer structure, and
approximation curves. The current plot can be exported as PNG or SVG. Result and view state stay in
memory and do not depend on browser storage.

Use `--host 0.0.0.0` only when intentionally exposing the explorer beyond the local machine.

## JSON and NPZ result logging

Step 7 wraps an analysis tree in the schema-versioned reproducibility envelope and partitions
activation targets from static model-level targets:

```python
from tensor_spectra.logging import read, write

output_path = write(result, config, sample=sample)
reloaded = read(output_path)
```

Documents use schema version `2.0.0` and validate against the JSON Schema bundled with the package.
The logger records the resolved config and hash, environment, timestamp, selected targets, sample
identity, optional model metadata, aggregates, and failures. NumPy/PyTorch values are converted
safely; non-finite JSON numbers become `null` with a neighboring `*_non_finite` flag.

When `output.save_sidecar_npz` is enabled, singular values, singular vectors, and raw matrices are
written to `result.npz`. JSON keys become `*_ref` URIs with target-namespaced entries, which can be
loaded with `resolve_array(reference, output_path)`.

## End-to-end CLI

Run the complete model → data → extraction → analysis → logging pipeline with:

```bash
uv run python -m tensor_spectra run --config tests/configs/tiny.yaml
```

The canonical result is written to `<output.dir>/<run_name>/result.json`, with an optional
`result.npz` sidecar. Dotted overrides follow the same YAML parsing rules as the configuration API:

```bash
uv run python -m tensor_spectra run \
  --config tests/configs/tiny.yaml \
  --analysis.compute_singular_vectors true \
  --data.n_samples 4 \
  --output.dir ./my-runs
```

Validate the configuration, load and inspect the model, check target support, and print the full
target × task × sequence-length × sample plan without loading benchmark samples or running analysis:

```bash
uv run python -m tensor_spectra run --config tests/configs/tiny.yaml --dry-run
```

Use `--skip-existing` for idempotent jobs. It exits successfully without loading the model when the
canonical `result.json` already exists:

```bash
uv run python -m tensor_spectra run --config tests/configs/tiny.yaml --skip-existing
```

Failures during one sample are recorded once per selected target under `failures`; later samples
continue normally. `aggregates.run_summary` reports successful samples, failed samples, target
failures, and the total analyzed matrix count.
