Metadata-Version: 2.4
Name: saearth
Version: 0.1.2
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

[![Website](https://img.shields.io/badge/Website-Concept%20Explorer-blue)](https://saearth.wenruixu.com)
[![Python package](https://img.shields.io/pypi/v/saearth?label=Python%20package)](https://pypi.org/project/saearth/)
[![Paper](https://img.shields.io/badge/Paper-arXiv%20coming%20soon-lightgrey)](https://github.com/ruaruaxu/saearth#citation)

SAEarth makes Earth embeddings interpretable. It trains a sparse autoencoder on an embedding
such as AlphaEarth or TESSERA, so that each location activates only a few dimensions, and
then lets an LLM agent describe each dimension in natural language from satellite imagery
(for example, fields crossed by "dark, winding hedgerows"). We release the models and
descriptions for AlphaEarth and TESSERA, and the code to apply the method to other
embeddings.

Preprint: SAEarth: Interpreting Earth Embeddings with Sparse Representations and LLM Agents.
[Wenrui Xu](https://wenruixu.com), [Gabriel Agostini](https://gsagostini.github.io), [Joshua Blumenstock](https://www.jblumenstock.com),
[Lu Liang](https://ced.berkeley.edu/people/lu-liang) and [Emma Pierson](https://people.eecs.berkeley.edu/~emmapierson/). arXiv link coming soon.<br>
Website: [https://saearth.wenruixu.com](https://saearth.wenruixu.com), to browse every
interpreted dimension with example images and maps.

<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](https://github.com/ruaruaxu/saearth#what-is-released)
- [Quickstart](https://github.com/ruaruaxu/saearth#quickstart)
- [Method](https://github.com/ruaruaxu/saearth#method)
- [Apply SAEarth to your own embeddings](https://github.com/ruaruaxu/saearth#apply-saearth-to-your-own-embeddings)
- [FAQ](https://github.com/ruaruaxu/saearth#faq)
- [Citation](https://github.com/ruaruaxu/saearth#citation)
- [License](https://github.com/ruaruaxu/saearth#license)

## What is released

| | AlphaEarth | TESSERA |
|---|---|---|
| SAE (2,048 dimensions, ~4 active) | `saearth/models/alphaearth/sae.npz` | `saearth/models/tessera/sae.npz` |
| k-means (2,048 clusters) | `saearth/models/alphaearth/kmeans.npz` | `saearth/models/tessera/kmeans.npz` |
| Interpretations | `saearth/interpretations/alphaearth_sae.csv` (1,790 dimensions) | `saearth/interpretations/tessera_sae.csv` (1,719 dimensions) |

Each SAE interpretation table (`alphaearth_sae.csv`, `tessera_sae.csv`) has one row per
interpreted dimension with these columns:

| Column | Meaning |
|---|---|
| `dimension` | SAE dimension (0–2,047) |
| `level` | Matryoshka level 1–4, coarse to fine: L1 = dimensions 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 name of the dimension (at most 18 words), written from `interpretation` and a map of where the dimension is active. For AlphaEarth dimension 345: "Rectangular agricultural fields across broad Northern Hemisphere midlatitude belts" |
| `interpretation` | What the dimension responds to in satellite imagery, written by the agent, usually in two to four sentences. `test_f1` scores this text. For AlphaEarth dimension 345: "Aerial imagery of broad, flat agricultural fields divided by straight roads, levees, or drainage channels into large rectangular parcels. …" |
| `test_f1` | Fidelity on 100 held-out locations: F1 of the LLM annotator's image-by-image predictions of whether each location is among the dimension's top-third activations or inactive |
| `faithful` | `test_f1 >= 0.69`. The threshold comes from a human evaluation: above it, two human annotators are more likely than not to agree that the description matches the dimension's images ([FAQ](https://github.com/ruaruaxu/saearth#faq)) |
| `activation_share` | Share of all activation mass carried by the dimension |

For comparison, `saearth/interpretations/alphaearth_dims.csv` describes the 64 original
AlphaEarth dimensions with the same agent and test, in the columns `dimension` (0–63),
`interpretation`, `test_f1` and `faithful`.

## Quickstart

```bash
pip install saearth
```

The package needs Python 3.10 or later and includes the released models and interpretation
tables. To modify the code, install an editable copy from the repository instead, so your
changes take effect without reinstalling:

```bash
git clone https://github.com/ruaruaxu/saearth.git
cd saearth
pip install -e .
```

```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 from Earth Engine the
AlphaEarth embeddings of a few example places (farmland near Davis, Midtown Manhattan, the
Amazon river near Manaus), encodes them with the released SAE and prints, for each place,
its active dimensions with their activation, label and test F1. Change the coordinates to
look up any other place.

**Inputs.** The released models take these embeddings:

- **AlphaEarth**: embeddings read from the Earth Engine collection
  `GOOGLE/SATELLITE_EMBEDDING/V1/ANNUAL` can be encoded directly. Google also publishes
  the embeddings as GeoTIFF files that store each value as an 8-bit integer. Convert these
  values back to embeddings with `saearth.dequantize_alphaearth`. Pixels without data
  become rows of NaN, so remove them before encoding, for example with
  `x = x[~np.isnan(x).any(axis=1)]`.
- **TESSERA** (v1.1): scale the embeddings to unit length with `saearth.unit_length` first.

Each row is encoded independently of the others, 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, an LLM agent
views annual Sentinel-2 RGB images of locations where the dimension is active or inactive,
without any location information, and writes a description of what the dimension responds
to. It refines the description using its F1 on a validation set, where an LLM annotator
judges image by image whether the description matches. The best description is then scored
once on held-out test locations that the agent never sees (`test_f1`), and a short label is
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. The paper
describes the full method.

## Apply SAEarth to your own embeddings

The released models already encode AlphaEarth and TESSERA embeddings of any location (see
[Quickstart](https://github.com/ruaruaxu/saearth#quickstart)). This section is for training
a new decomposition, for example on another Earth embedding, on one region, or with other
settings, and letting the agent describe its dimensions.

[`notebooks/apply_to_new_embeddings.ipynb`](https://github.com/ruaruaxu/saearth/blob/main/notebooks/apply_to_new_embeddings.ipynb)
walks through both steps on an example: it samples 20,000 AlphaEarth pixels in northern
California for 2023, trains a new SAE with 128 dimensions, and interprets three of them.
Replace the sample with your own embeddings and choose the method, M (dimensions) and K
(active dimensions per embedding) in one cell. Step 2 needs Earth Engine for the images and
an OpenAI API key for the agent:

```bash
pip install "saearth[interpret,notebooks]"
earthengine authenticate
export OPENAI_API_KEY=...
```

**Step 1.** Fit a decomposition on float32 `[n, d]` embeddings scaled to unit length
(`saearth.unit_length`). 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; the inference threshold is estimated after the first 1,000 steps |

`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 AlphaEarth SAE was trained on 6.7 million
location-years from the AlphaEarth training coordinates (2017–2023), which cover all major
ecoregions. TESSERA embeddings exist for 98.3% of these location-years, and the TESSERA SAE
uses only those.

**Do I need a GPU?** Not for encoding or 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 v1.1 embeddings
  (Feng et al., "TESSERA: Temporal Embeddings of Surface Spectra for Earth Representation
  and Analysis", CVPR 2026), accessed with [geotessera](https://github.com/ucam-eo/geotessera).
- The sample locations are the [AlphaEarth Foundations Supplemental Training Coordinates](https://doi.org/10.5281/zenodo.16585910),
  published by Google DeepMind under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
- The example images, including those in `assets/framework.png`, contain modified
  Copernicus Sentinel data 2017–2023.
