Metadata-Version: 2.4
Name: saearth
Version: 0.1.0
Summary: Sparse, interpretable Earth embeddings: sparse autoencoders and LLM-agent interpretations
License-Expression: MIT AND CC-BY-4.0 AND CC-BY-SA-4.0
Project-URL: Homepage, https://saearth.wenruixu.com
Project-URL: Source, https://github.com/ruaruaxu/saearth
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: pandas
Requires-Dist: pyarrow
Requires-Dist: torch
Requires-Dist: scikit-learn
Provides-Extra: interpret
Requires-Dist: scipy; extra == "interpret"
Requires-Dist: earthengine-api; extra == "interpret"
Requires-Dist: rasterio; extra == "interpret"
Requires-Dist: pillow; extra == "interpret"
Requires-Dist: matplotlib; extra == "interpret"
Requires-Dist: requests; extra == "interpret"
Provides-Extra: notebooks
Requires-Dist: jupyter; extra == "notebooks"
Requires-Dist: earthengine-api; extra == "notebooks"
Dynamic: license-file

# SAEarth: Interpreting Earth Embeddings with Sparse Representations and LLM Agents

**[Concept Explorer](https://saearth.wenruixu.com)** | **Paper** (arXiv, link coming soon) | [Released models and interpretations](#what-is-released)

SAEarth turns a dense Earth embedding into a sparse representation whose dimensions are
described in natural language and validated on held-out locations. We release this
representation for the AlphaEarth and TESSERA embeddings: the trained models, a
description of every interpreted dimension with its held-out fidelity, and the code to
apply the method to other embeddings.

<p align="center"><img src="https://raw.githubusercontent.com/ruaruaxu/saearth/main/assets/framework.png" width="560" alt="SAEarth in two steps: sparse decomposition and agentic interpretation"></p>

## Contents

- [What is released](#what-is-released)
- [Quickstart](#quickstart)
- [Method](#method)
- [Apply SAEarth to your own embeddings](#apply-saearth-to-your-own-embeddings)
- [FAQ](#faq)
- [Citation](#citation)
- [License](#license)

## What is released

| | AlphaEarth | TESSERA |
|---|---|---|
| Sparse autoencoder (2,048 dimensions, about 4 active) | `saearth/models/alphaearth/sae.npz` | `saearth/models/tessera/sae.npz` |
| k-means (2,048 clusters, one active) | `saearth/models/alphaearth/kmeans.npz` | `saearth/models/tessera/kmeans.npz` |
| Interpreted dimensions | 1,790 (`saearth/interpretations/alphaearth_sae.csv`) | 1,719 (`saearth/interpretations/tessera_sae.csv`) |
| Median held-out test F1 | 0.839 | 0.817 |
| Faithful (test F1 ≥ 0.69) | 96.4% | 92.7% |

The interpreted dimensions carry 99.9% of the activation mass of each SAE.
`saearth/interpretations/alphaearth_dims.csv` describes the 64 original AlphaEarth dimensions with
the same agent and test, for comparison.

Each interpretation table has one row per dimension:

| Column | Meaning |
|---|---|
| `dimension` | SAE dimension (0–2,047) |
| `level` | Matryoshka level, coarse to fine: L1 = 0–127, L2 = 128–383, L3 = 384–895, L4 = 896–2,047 |
| `theme` | One of eight themes shared by both embeddings, such as Agricultural fields or Built-up settlements |
| `label` | Short label |
| `interpretation` | Full description written by the agent |
| `test_f1` | Fidelity on 100 held-out locations: F1 of the LLM annotator's image-by-image predictions of whether the dimension is in the top third of its activations or inactive |
| `faithful` | `test_f1 >= 0.69` |
| `activation_share` | Share of all activation mass carried by the dimension |

## Quickstart

```bash
pip install git+https://github.com/ruaruaxu/saearth.git
```

The package includes the released models and interpretation tables. To change the code,
clone the repository and run `pip install -e .` instead.

```python
import numpy as np
import saearth

sae = saearth.load_sae("alphaearth")              # or "tessera"
concepts = saearth.load_concepts("alphaearth")    # the interpretation table, indexed by dimension

x = np.load("my_alphaearth_embeddings.npy")       # [n, 64] float32
codes = saearth.encode(sae, x)                    # [n, 2048], about 4 nonzero per row
for d in np.flatnonzero(codes[0]):
    if d in concepts.index:
        print(d, round(float(codes[0, d]), 3), concepts.label[d])
```

[`notebooks/quickstart.ipynb`](https://github.com/ruaruaxu/saearth/blob/main/notebooks/quickstart.ipynb) reads the AlphaEarth embedding of
any place from Earth Engine and lists its concepts.

**Inputs.** AlphaEarth embeddings as served by the Earth Engine collection
`GOOGLE/SATELLITE_EMBEDDING/V1/ANNUAL`, or dequantized from the GeoTIFF release with
`saearth.dequantize_alphaearth`. TESSERA v1.1 embeddings scaled to unit length with
`saearth.unit_length`. The code of each row is independent of the other rows, so any batch
size gives the same result.

## Method

**Step 1: Sparse decomposition** (`saearth.decompose`). A Matryoshka BatchTopK sparse
autoencoder maps each embedding to 2,048 dimensions, about 4 of which are active per
location-year. The Matryoshka prefixes order the dimensions from coarse (L1) to fine (L4).
We also release k-means models with the same number of units, which assign each embedding
to one cluster.

**Step 2: Agentic interpretation** (`saearth.interpret`). For each dimension, the
locations are split into three disjoint sets, each location contributing one year: a
validation set (50 top-third, 50 inactive), a test set of the same size, and the remaining
locations for exploration. An LLM agent sees only annual Sentinel-2 RGB composites (1.28 km
across at 10 m), statistics computed from these images, and their years, with no location
information. It can

- **query** samples from an activation quantile range, random inactive samples, or inactive
  samples whose embeddings are closest to strongly active ones,
- **view** up to 50 images per call,
- **score** a candidate description: an LLM annotator predicts, image by image, whether the
  description matches each validation location, and the agent receives the F1,
- **finish** when it is satisfied.

The description with the best validation F1 is kept and scored once on the test set,
which the agent never sees. A short label is then written from the description and a map
of where the dimension is active. The released interpretations use `gpt-6-luna` as agent,
LLM annotator and label model.

## Apply SAEarth to your own embeddings

[`notebooks/apply_to_new_embeddings.ipynb`](https://github.com/ruaruaxu/saearth/blob/main/notebooks/apply_to_new_embeddings.ipynb) runs
both steps end to end on a sample drawn from Earth Engine, with the method, M and K set in
one cell. Install the extra dependencies first:

```bash
pip install -e ".[interpret]"
earthengine authenticate
export OPENAI_API_KEY=...
```

**Step 1.** Fit a decomposition on float32 `[n, d]` embeddings. The defaults reproduce
the released models; every choice below can be changed.

| Option | Default | Choices |
|---|---|---|
| Method | `matryoshka_batchtopk` | `matryoshka_batchtopk`, `batchtopk`, `topk`, `kmeans` |
| M, dimensions (clusters for k-means) | 2,048 | any; the default Matryoshka prefixes need a multiple of 16 |
| K, active dimensions per embedding (SAE) | 4 | any; k-means has one active cluster |
| Matryoshka prefixes | M/16, 3M/16, 7M/16, M | any increasing list ending at M |
| Training steps and batch size (SAE) | 100,000 steps of 4,096 | any |

`batchtopk` keeps the `batch_size * K` largest activations of each training batch and
encodes with a frozen threshold; `matryoshka_batchtopk` adds the nested prefixes, which
order the dimensions from coarse to fine; `topk` keeps exactly K activations per row. With
`kmeans`, each embedding activates its nearest cluster with the cosine to its center.

```python
from saearth.decompose import train_sae, train_kmeans, encode_sparse

sae, metrics = train_sae(train_embeddings, validation_embeddings,
                         dictionary_size=1024, k=8, architecture="topk")   # metrics: R^2 and mean L0
sae.save("my_sae.npz")
codes = encode_sparse(sae, embeddings)            # CSR arrays, the input of step 2

centers, metrics = train_kmeans(train_embeddings, validation_embeddings, clusters=512)
codes = encode_sparse(centers, embeddings)        # one active cluster per row
```

or from the command line:

```bash
python -m saearth.decompose.train --method topk --dictionary-size 1024 --k 8 \
    --train train.npy --validation validation.npy --output runs/my_sae
python -m saearth.decompose.encode --model runs/my_sae/sae.npz --embeddings x.npy --output codes.npz
```

**Step 2.** Describe dimensions from imagery, for any of the methods above.
`rows.parquet` lists each location-year (`location_id`, `year`, `longitude`, `latitude`) in
the same order as the embeddings and codes.

```python
from saearth.interpret import interpret_dimensions
results = interpret_dimensions("rows.parquet", "x.npy", "codes.npz", dimensions=[12, 454],
                               output="out", ee_project="<your-earth-engine-project>")
```

or `python -m saearth.interpret.interpret` with the same arguments. Each
`out/<dimension>/` folder holds `result.json` (interpretation, label, validation and test
F1), the agent's full action log `transcript.jsonl`, and the map given to the label model.
Images are fetched from Earth Engine once and cached in `out/images/`.

**Cost.** Interpreting the 1,719 TESSERA dimensions with `gpt-6-luna` cost US$102, about
US$0.06 per dimension. Step 1 needs no API calls.

## FAQ

**Where and when do the released models apply?** Anywhere AlphaEarth or TESSERA
embeddings exist, for 2017 onward. The SAEs were trained on 6.7 million location-years from
the AlphaEarth training coordinates (2017–2023), which cover all major ecoregions.

**Do I need a GPU?** No for encoding and interpretation. Training an SAE with the default
100,000 steps takes minutes on a GPU and longer on a CPU.

**Why are some dimensions not interpreted?** A dimension is interpreted when the top third
of its activations covers at least 150 distinct locations, enough to build disjoint
validation and test sets. The 1,790 and 1,719 interpreted dimensions carry 99.9% of all
activation mass.

**What does a test F1 of 0.69 mean?** Two human annotators rated 100 descriptions against
the most strongly activating images of each dimension. At a test F1 of 0.69, the
probability that the two annotators give a mean rating of at least 4 ("agree") reaches 0.5.
For reference, an annotator answering at random scores an F1 of 0.5.

**Should I use the SAE or the k-means model?** The SAE describes each location with
about 4 concepts at once and reconstructs the embedding more closely. k-means assigns one
cluster per location, which is simpler when a single label per location is enough.

## Citation

```bibtex
@article{xu2026saearth,
  title  = {SAEarth: Interpreting Earth Embeddings with Sparse Representations and LLM Agents},
  author = {Xu, Wenrui and Agostini, Gabriel and Blumenstock, Joshua and Liang, Lu and Pierson, Emma},
  year   = {2026}
}
```

## License

Code: MIT. Models and interpretations: CC BY 4.0 for AlphaEarth and CC BY-SA 4.0 for
TESSERA (see `LICENSE`).

Attribution:

- The [AlphaEarth Foundations Satellite Embedding dataset](https://developers.google.com/earth-engine/datasets/catalog/GOOGLE_SATELLITE_EMBEDDING_V1_ANNUAL)
  is produced by Google and Google DeepMind and is licensed under
  [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). We trained sparse
  autoencoders and k-means models on these embeddings and interpreted their dimensions.
- The TESSERA models and interpretations are derived from TESSERA embeddings.
- The example images, including those in `assets/framework.png`, contain modified
  Copernicus Sentinel data 2017–2023.
