saearth 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- saearth/__init__.py +71 -0
- saearth/decompose/__init__.py +16 -0
- saearth/decompose/embeddings.py +23 -0
- saearth/decompose/encode.py +52 -0
- saearth/decompose/kmeans.py +46 -0
- saearth/decompose/sae.py +209 -0
- saearth/decompose/train.py +142 -0
- saearth/interpret/__init__.py +15 -0
- saearth/interpret/agent.py +272 -0
- saearth/interpret/assays.py +114 -0
- saearth/interpret/imagery.py +180 -0
- saearth/interpret/index.py +72 -0
- saearth/interpret/interpret.py +85 -0
- saearth/interpret/judge.py +47 -0
- saearth/interpret/label.py +65 -0
- saearth/interpret/llm.py +65 -0
- saearth/interpret/prompts.py +188 -0
- saearth/interpretations/alphaearth_dims.csv +65 -0
- saearth/interpretations/alphaearth_sae.csv +1791 -0
- saearth/interpretations/tessera_sae.csv +1720 -0
- saearth/models/alphaearth/kmeans.npz +0 -0
- saearth/models/alphaearth/sae.npz +0 -0
- saearth/models/tessera/kmeans.npz +0 -0
- saearth/models/tessera/sae.npz +0 -0
- saearth-0.1.0.dist-info/METADATA +248 -0
- saearth-0.1.0.dist-info/RECORD +29 -0
- saearth-0.1.0.dist-info/WHEEL +5 -0
- saearth-0.1.0.dist-info/licenses/LICENSE +33 -0
- saearth-0.1.0.dist-info/top_level.txt +1 -0
saearth/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""SAEarth: sparse, interpretable Earth embeddings.
|
|
2
|
+
|
|
3
|
+
Step 1, ``saearth.decompose``: a sparse autoencoder turns each Earth embedding into a
|
|
4
|
+
sparse code over 2,048 dimensions. Step 2, ``saearth.interpret``: an LLM agent describes
|
|
5
|
+
each dimension from satellite imagery and is scored on held-out locations.
|
|
6
|
+
|
|
7
|
+
The released models and interpretations can be used directly:
|
|
8
|
+
|
|
9
|
+
import saearth
|
|
10
|
+
sae = saearth.load_sae("alphaearth") # or "tessera"; saearth.load_kmeans(...) for k-means
|
|
11
|
+
codes = saearth.encode(sae, embeddings) # [n, 2048], about 4 nonzero per row
|
|
12
|
+
concepts = saearth.load_concepts("alphaearth") # label, interpretation, test F1, ...
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
PACKAGE = Path(__file__).resolve().parent # the released models and tables ship inside the package
|
|
18
|
+
EMBEDDINGS = ("alphaearth", "tessera")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _resource(name_or_path, filename: str) -> Path:
|
|
22
|
+
if str(name_or_path) in EMBEDDINGS:
|
|
23
|
+
return PACKAGE / "models" / str(name_or_path) / filename
|
|
24
|
+
return Path(name_or_path)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_sae(name_or_path, device: str = "cpu"):
|
|
28
|
+
"""A released SAE ("alphaearth" or "tessera") or an ``sae.npz`` you trained."""
|
|
29
|
+
from .decompose.sae import load_sae as load
|
|
30
|
+
return load(_resource(name_or_path, "sae.npz"), device)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def encode(model, embeddings, batch_size: int = 65_536):
|
|
34
|
+
"""Dense ``[n, M]`` sparse codes of ``[n, d]`` embeddings (TESSERA rows scaled to unit length first).
|
|
35
|
+
|
|
36
|
+
``model`` is an SAE from ``load_sae`` or k-means centers from ``load_kmeans`` (one active cluster per row,
|
|
37
|
+
activation = cosine to its center).
|
|
38
|
+
"""
|
|
39
|
+
import numpy as np
|
|
40
|
+
if isinstance(model, np.ndarray):
|
|
41
|
+
from .decompose.kmeans import assign
|
|
42
|
+
labels, activation = assign(embeddings, model)
|
|
43
|
+
codes = np.zeros((len(labels), len(model)), dtype=np.float32)
|
|
44
|
+
codes[np.arange(len(labels)), labels] = activation
|
|
45
|
+
return codes
|
|
46
|
+
from .decompose.sae import encode as run
|
|
47
|
+
return run(model, embeddings, batch_size)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def unit_length(embeddings):
|
|
51
|
+
"""Scale each row to unit length (TESSERA inputs)."""
|
|
52
|
+
from .decompose.embeddings import unit_length as scale
|
|
53
|
+
return scale(embeddings)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def dequantize_alphaearth(raw):
|
|
57
|
+
"""Signed int8 AlphaEarth GeoTIFF values to the float embeddings."""
|
|
58
|
+
from .decompose.embeddings import dequantize_alphaearth as dequantize
|
|
59
|
+
return dequantize(raw)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def load_kmeans(name_or_path):
|
|
63
|
+
"""Centers of a released k-means model ("alphaearth" or "tessera") or a ``kmeans.npz`` path."""
|
|
64
|
+
from .decompose.kmeans import load_kmeans as load
|
|
65
|
+
return load(_resource(name_or_path, "kmeans.npz"))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def load_concepts(embedding: str):
|
|
69
|
+
"""The interpreted SAE dimensions of "alphaearth" or "tessera" as a DataFrame indexed by dimension."""
|
|
70
|
+
import pandas as pd
|
|
71
|
+
return pd.read_csv(PACKAGE / "interpretations" / f"{embedding}_sae.csv").set_index("dimension")
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Step 1 of SAEarth: decompose dense Earth embeddings into sparse representations."""
|
|
2
|
+
|
|
3
|
+
from .embeddings import dequantize_alphaearth, unit_length
|
|
4
|
+
from .kmeans import assign, fit_kmeans, kmeans_codes, load_kmeans
|
|
5
|
+
from .sae import ARCHITECTURES, SparseAutoencoder, encode, load_sae
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def __getattr__(name):
|
|
9
|
+
# Imported on first use, so ``python -m saearth.decompose.train`` and ``.encode`` run without a runpy warning.
|
|
10
|
+
if name in ("train_sae", "train_kmeans"):
|
|
11
|
+
from . import train
|
|
12
|
+
return getattr(train, name)
|
|
13
|
+
if name == "encode_sparse":
|
|
14
|
+
from .encode import encode_sparse
|
|
15
|
+
return encode_sparse
|
|
16
|
+
raise AttributeError(name)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Input conventions for the two Earth embeddings.
|
|
2
|
+
|
|
3
|
+
AlphaEarth: 64-d annual embeddings. The Earth Engine collection
|
|
4
|
+
``GOOGLE/SATELLITE_EMBEDDING/V1/ANNUAL`` serves them as floats, ready to use. The
|
|
5
|
+
cloud-optimized GeoTIFF release stores signed 8-bit values; ``dequantize_alphaearth``
|
|
6
|
+
converts them to the same floats.
|
|
7
|
+
|
|
8
|
+
TESSERA: 128-d annual embeddings, scaled to unit length before encoding.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def dequantize_alphaearth(raw: np.ndarray) -> np.ndarray:
|
|
15
|
+
"""Signed int8 AlphaEarth values (GeoTIFF release) to float embeddings."""
|
|
16
|
+
values = raw.astype(np.float64)
|
|
17
|
+
return (np.sign(values) * np.square(np.abs(values) / 127.5)).astype(np.float32)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def unit_length(embeddings: np.ndarray) -> np.ndarray:
|
|
21
|
+
"""Scale each row to unit L2 norm (TESSERA inputs)."""
|
|
22
|
+
embeddings = np.asarray(embeddings, dtype=np.float32)
|
|
23
|
+
return embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Encode embeddings into sparse codes with an SAE (``sae.npz``) or k-means model (``kmeans.npz``).
|
|
2
|
+
|
|
3
|
+
python -m saearth.decompose.encode --model alphaearth --embeddings x.npy --output codes.npz
|
|
4
|
+
python -m saearth.decompose.encode --model my_kmeans.npz --embeddings x.npy --output codes.npz
|
|
5
|
+
|
|
6
|
+
``--model`` is a released SAE ("alphaearth" or "tessera") or a path to an ``sae.npz`` or ``kmeans.npz``.
|
|
7
|
+
|
|
8
|
+
Output: CSR arrays ``indptr``, ``indices`` (active dimensions) and ``values``
|
|
9
|
+
(activations); row ``i`` has its active dimensions in ``indices[indptr[i]:indptr[i+1]]``.
|
|
10
|
+
For k-means each row has one active cluster, whose activation is the cosine to its
|
|
11
|
+
center. Step 2 (``saearth.interpret``) reads either.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from .. import _resource
|
|
20
|
+
from .kmeans import kmeans_codes, load_kmeans
|
|
21
|
+
from .sae import encode, load_sae
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def encode_sparse(model, embeddings: np.ndarray, chunk: int = 262_144) -> dict:
|
|
25
|
+
"""Sparse codes of an SAE, or of k-means when ``model`` is its array of centers."""
|
|
26
|
+
if isinstance(model, np.ndarray):
|
|
27
|
+
return kmeans_codes(embeddings, model)
|
|
28
|
+
indptr, indices, values = [np.zeros(1, dtype=np.int64)], [], []
|
|
29
|
+
for start in range(0, len(embeddings), chunk):
|
|
30
|
+
codes = encode(model, embeddings[start:start + chunk])
|
|
31
|
+
rows, cols = np.nonzero(codes)
|
|
32
|
+
indices.append(cols.astype(np.int16))
|
|
33
|
+
values.append(codes[rows, cols])
|
|
34
|
+
indptr.append(indptr[-1][-1] + np.cumsum(np.bincount(rows, minlength=len(codes))))
|
|
35
|
+
return {"indptr": np.concatenate(indptr), "indices": np.concatenate(indices), "values": np.concatenate(values)}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main():
|
|
39
|
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
40
|
+
p.add_argument("--model", required=True)
|
|
41
|
+
p.add_argument("--embeddings", type=Path, required=True)
|
|
42
|
+
p.add_argument("--output", type=Path, required=True)
|
|
43
|
+
p.add_argument("--device", default="cpu")
|
|
44
|
+
a = p.parse_args()
|
|
45
|
+
embeddings = np.load(a.embeddings).astype(np.float32)
|
|
46
|
+
path = _resource(a.model, "sae.npz")
|
|
47
|
+
model = load_kmeans(path) if "centers" in np.load(path).files else load_sae(path, a.device)
|
|
48
|
+
np.savez(a.output, **encode_sparse(model, embeddings))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
if __name__ == "__main__":
|
|
52
|
+
main()
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""k-means decomposition: each embedding is assigned to its nearest center (2,048 in the released models).
|
|
2
|
+
|
|
3
|
+
A cluster's activation is the cosine between the embedding and the center, on the
|
|
4
|
+
embeddings assigned to that cluster, and zero elsewhere (one active cluster per row).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
SEED = 42
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def fit_kmeans(train: np.ndarray, k: int = 2048, max_iter: int = 3000) -> np.ndarray:
|
|
15
|
+
"""Lloyd k-means with k-means++ initialization on the training embeddings; returns float64 centers."""
|
|
16
|
+
from sklearn.cluster import KMeans
|
|
17
|
+
model = KMeans(n_clusters=k, init="k-means++", n_init=1, algorithm="lloyd",
|
|
18
|
+
random_state=SEED, max_iter=max_iter).fit(np.asarray(train, dtype=np.float32))
|
|
19
|
+
return model.cluster_centers_.astype(np.float64)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_kmeans(path: str | Path) -> np.ndarray:
|
|
23
|
+
"""Centers of a released k-means model (``models/<embedding>/kmeans.npz``)."""
|
|
24
|
+
return np.load(path)["centers"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def assign(embeddings: np.ndarray, centers: np.ndarray, chunk: int = 262_144) -> tuple[np.ndarray, np.ndarray]:
|
|
28
|
+
"""Nearest center of each row (float64 Euclidean) and the cosine activation of that center."""
|
|
29
|
+
half_norm = 0.5 * np.einsum("ij,ij->i", centers, centers)
|
|
30
|
+
center_norm = np.sqrt(2 * half_norm)
|
|
31
|
+
labels = np.empty(len(embeddings), dtype=np.int16)
|
|
32
|
+
activation = np.empty(len(embeddings), dtype=np.float32)
|
|
33
|
+
for start in range(0, len(embeddings), chunk):
|
|
34
|
+
block = np.asarray(embeddings[start:start + chunk], dtype=np.float64)
|
|
35
|
+
dots = block @ centers.T
|
|
36
|
+
nearest = (dots - half_norm).argmax(axis=1) # argmin of ||x - c||^2
|
|
37
|
+
labels[start:start + len(block)] = nearest
|
|
38
|
+
activation[start:start + len(block)] = (
|
|
39
|
+
dots[np.arange(len(block)), nearest] / (np.linalg.norm(block, axis=1) * center_norm[nearest]))
|
|
40
|
+
return labels, activation
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def kmeans_codes(embeddings: np.ndarray, centers: np.ndarray) -> dict:
|
|
44
|
+
"""k-means assignment as sparse codes (CSR ``indptr``/``indices``/``values``, one active cluster per row)."""
|
|
45
|
+
labels, activation = assign(embeddings, centers)
|
|
46
|
+
return {"indptr": np.arange(len(labels) + 1, dtype=np.int64), "indices": labels.astype(np.int16), "values": activation}
|
saearth/decompose/sae.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Sparse autoencoders: Matryoshka BatchTopK (the released models), BatchTopK and TopK.
|
|
2
|
+
|
|
3
|
+
- ``batchtopk``: training keeps the ``batch_size * k`` largest activations across the
|
|
4
|
+
whole batch. Inference uses a single frozen activation threshold, so the code of an
|
|
5
|
+
embedding does not depend on the other embeddings in its batch.
|
|
6
|
+
- ``matryoshka_batchtopk``: BatchTopK whose reconstruction loss is averaged over nested
|
|
7
|
+
dictionary prefixes (by default M/16, 3M/16, 7M/16 and M), which orders the dimensions
|
|
8
|
+
from coarse to fine.
|
|
9
|
+
- ``topk``: every row keeps exactly its own ``k`` largest activations, in training and
|
|
10
|
+
at inference.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Sequence
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import torch
|
|
21
|
+
from torch import Tensor, nn
|
|
22
|
+
from torch.nn import functional as F
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
ARCHITECTURES = ("matryoshka_batchtopk", "batchtopk", "topk")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def default_prefixes(dictionary_size: int, architecture: str) -> list[int]:
|
|
29
|
+
if architecture != "matryoshka_batchtopk":
|
|
30
|
+
return [dictionary_size]
|
|
31
|
+
if dictionary_size % 16:
|
|
32
|
+
raise ValueError("The default Matryoshka prefixes need a dictionary size divisible by 16.")
|
|
33
|
+
return [dictionary_size * n // 16 for n in (1, 3, 7, 16)]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class StepResult:
|
|
38
|
+
loss: Tensor
|
|
39
|
+
reconstruction_loss: Tensor
|
|
40
|
+
auxiliary_loss: Tensor
|
|
41
|
+
codes: Tensor
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SparseAutoencoder(nn.Module):
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
input_dim: int,
|
|
48
|
+
dictionary_size: int,
|
|
49
|
+
k: int,
|
|
50
|
+
architecture: str = "matryoshka_batchtopk",
|
|
51
|
+
prefixes: Sequence[int] | None = None,
|
|
52
|
+
*,
|
|
53
|
+
auxiliary_coefficient: float = 1.0 / 32.0,
|
|
54
|
+
dead_token_threshold: int = 10_000_000,
|
|
55
|
+
threshold_beta: float = 0.999,
|
|
56
|
+
threshold_start_step: int = 1_000,
|
|
57
|
+
) -> None:
|
|
58
|
+
super().__init__()
|
|
59
|
+
if architecture not in ARCHITECTURES:
|
|
60
|
+
raise ValueError(f"architecture must be one of {ARCHITECTURES}")
|
|
61
|
+
prefixes = tuple(int(p) for p in (prefixes or default_prefixes(dictionary_size, architecture)))
|
|
62
|
+
if prefixes[-1] != dictionary_size or tuple(sorted(set(prefixes))) != prefixes:
|
|
63
|
+
raise ValueError("Prefixes must increase strictly and end at dictionary_size.")
|
|
64
|
+
if architecture != "matryoshka_batchtopk" and len(prefixes) > 1:
|
|
65
|
+
raise ValueError("Only matryoshka_batchtopk uses nested prefixes.")
|
|
66
|
+
self.architecture = architecture
|
|
67
|
+
self.input_dim = int(input_dim)
|
|
68
|
+
self.dictionary_size = int(dictionary_size)
|
|
69
|
+
self.k = int(k)
|
|
70
|
+
self.prefixes = prefixes
|
|
71
|
+
self.auxiliary_coefficient = float(auxiliary_coefficient)
|
|
72
|
+
self.dead_token_threshold = int(dead_token_threshold)
|
|
73
|
+
self.threshold_beta = float(threshold_beta)
|
|
74
|
+
self.threshold_start_step = int(threshold_start_step)
|
|
75
|
+
self.top_k_auxiliary = self.input_dim // 2
|
|
76
|
+
|
|
77
|
+
self.W_dec = nn.Parameter(torch.empty(self.dictionary_size, self.input_dim))
|
|
78
|
+
nn.init.kaiming_uniform_(self.W_dec)
|
|
79
|
+
self.normalize_decoder_()
|
|
80
|
+
self.W_enc = nn.Parameter(self.W_dec.detach().clone().T)
|
|
81
|
+
self.b_enc = nn.Parameter(torch.zeros(self.dictionary_size))
|
|
82
|
+
self.b_dec = nn.Parameter(torch.zeros(self.input_dim))
|
|
83
|
+
self.register_buffer("threshold", torch.tensor(-1.0, dtype=torch.float32))
|
|
84
|
+
self.register_buffer("tokens_since_fired", torch.zeros(self.dictionary_size, dtype=torch.long))
|
|
85
|
+
|
|
86
|
+
# ----- encoding and decoding -----
|
|
87
|
+
|
|
88
|
+
def preactivations(self, inputs: Tensor) -> Tensor:
|
|
89
|
+
return F.relu((inputs - self.b_dec) @ self.W_enc + self.b_enc)
|
|
90
|
+
|
|
91
|
+
def encode(self, inputs: Tensor) -> Tensor:
|
|
92
|
+
"""Sparse code of each row (inference): activations above the frozen threshold, or the row's top k for TopK."""
|
|
93
|
+
if self.architecture == "topk":
|
|
94
|
+
return self.batch_topk(self.preactivations(inputs))
|
|
95
|
+
if float(self.threshold.item()) < 0:
|
|
96
|
+
raise RuntimeError("The inference threshold has not been calibrated.")
|
|
97
|
+
post_relu = self.preactivations(inputs)
|
|
98
|
+
return post_relu * (post_relu > self.threshold)
|
|
99
|
+
|
|
100
|
+
def decode(self, codes: Tensor, prefix: int | None = None) -> Tensor:
|
|
101
|
+
width = self.dictionary_size if prefix is None else int(prefix)
|
|
102
|
+
return codes[:, :width] @ self.W_dec[:width] + self.b_dec
|
|
103
|
+
|
|
104
|
+
# ----- training -----
|
|
105
|
+
|
|
106
|
+
def batch_topk(self, post_relu: Tensor) -> Tensor:
|
|
107
|
+
if self.architecture == "topk":
|
|
108
|
+
values, indices = post_relu.topk(self.k, dim=-1, sorted=False)
|
|
109
|
+
return torch.zeros_like(post_relu).scatter_(-1, indices, values)
|
|
110
|
+
keep = int(post_relu.shape[0]) * self.k
|
|
111
|
+
values, indices = post_relu.flatten().topk(keep, sorted=False)
|
|
112
|
+
return torch.zeros_like(post_relu.flatten()).scatter_(0, indices, values).reshape_as(post_relu)
|
|
113
|
+
|
|
114
|
+
def training_step(self, inputs: Tensor, step: int) -> StepResult:
|
|
115
|
+
post_relu = self.preactivations(inputs)
|
|
116
|
+
codes = self.batch_topk(post_relu)
|
|
117
|
+
prefix_losses = []
|
|
118
|
+
reconstruction = torch.zeros_like(inputs) + self.b_dec
|
|
119
|
+
cursor = 0
|
|
120
|
+
for prefix in self.prefixes:
|
|
121
|
+
reconstruction = reconstruction + codes[:, cursor:prefix] @ self.W_dec[cursor:prefix]
|
|
122
|
+
prefix_losses.append((inputs.float() - reconstruction.float()).pow(2).sum(dim=-1).mean())
|
|
123
|
+
cursor = prefix
|
|
124
|
+
reconstruction_loss = torch.stack(prefix_losses).mean()
|
|
125
|
+
|
|
126
|
+
fired = codes.sum(dim=0) > 0
|
|
127
|
+
self.tokens_since_fired.add_(int(inputs.shape[0]))
|
|
128
|
+
self.tokens_since_fired[fired] = 0
|
|
129
|
+
auxiliary_loss = self._auxiliary_loss((inputs - reconstruction).detach(), post_relu)
|
|
130
|
+
loss = reconstruction_loss + self.auxiliary_coefficient * auxiliary_loss
|
|
131
|
+
if int(step) > self.threshold_start_step:
|
|
132
|
+
self._update_threshold(codes)
|
|
133
|
+
return StepResult(loss, reconstruction_loss, auxiliary_loss, codes)
|
|
134
|
+
|
|
135
|
+
def _auxiliary_loss(self, residual: Tensor, post_relu: Tensor) -> Tensor:
|
|
136
|
+
"""AuxK loss: dead latents reconstruct the residual, which revives them."""
|
|
137
|
+
dead = self.tokens_since_fired >= self.dead_token_threshold
|
|
138
|
+
dead_count = int(dead.sum().item())
|
|
139
|
+
if dead_count == 0:
|
|
140
|
+
return torch.zeros((), dtype=residual.dtype, device=residual.device)
|
|
141
|
+
k_aux = min(self.top_k_auxiliary, dead_count)
|
|
142
|
+
candidates = torch.where(dead[None], post_relu, -torch.inf)
|
|
143
|
+
values, indices = candidates.topk(k_aux, dim=-1, sorted=False)
|
|
144
|
+
auxiliary_reconstruction = torch.zeros_like(post_relu).scatter_(1, indices, values) @ self.W_dec
|
|
145
|
+
numerator = (residual.float() - auxiliary_reconstruction.float()).pow(2).sum(dim=-1).mean()
|
|
146
|
+
centered = residual.float() - residual.float().mean(dim=0, keepdim=True)
|
|
147
|
+
return (numerator / centered.pow(2).sum(dim=-1).mean()).nan_to_num(0.0)
|
|
148
|
+
|
|
149
|
+
@torch.no_grad()
|
|
150
|
+
def _update_threshold(self, codes: Tensor) -> None:
|
|
151
|
+
"""Exponential moving average of the smallest kept activation in each batch."""
|
|
152
|
+
active = codes[codes > 0]
|
|
153
|
+
minimum = torch.zeros((), device=codes.device) if active.numel() == 0 else active.min().float()
|
|
154
|
+
if float(self.threshold.item()) < 0:
|
|
155
|
+
self.threshold.copy_(minimum)
|
|
156
|
+
else:
|
|
157
|
+
self.threshold.mul_(self.threshold_beta).add_(minimum, alpha=1.0 - self.threshold_beta)
|
|
158
|
+
|
|
159
|
+
@torch.no_grad()
|
|
160
|
+
def project_decoder_gradient_(self) -> None:
|
|
161
|
+
"""Remove the gradient component that would change the decoder row norms."""
|
|
162
|
+
if self.W_dec.grad is None:
|
|
163
|
+
return
|
|
164
|
+
normalized = F.normalize(self.W_dec, dim=-1)
|
|
165
|
+
self.W_dec.grad.sub_((self.W_dec.grad * normalized).sum(dim=-1, keepdim=True) * normalized)
|
|
166
|
+
|
|
167
|
+
@torch.no_grad()
|
|
168
|
+
def normalize_decoder_(self) -> None:
|
|
169
|
+
self.W_dec.copy_(F.normalize(self.W_dec, dim=-1))
|
|
170
|
+
|
|
171
|
+
# ----- saving and loading -----
|
|
172
|
+
|
|
173
|
+
def save(self, path: str | Path) -> None:
|
|
174
|
+
np.savez(
|
|
175
|
+
path,
|
|
176
|
+
W_enc=self.W_enc.detach().cpu().numpy(),
|
|
177
|
+
W_dec=self.W_dec.detach().cpu().numpy(),
|
|
178
|
+
b_enc=self.b_enc.detach().cpu().numpy(),
|
|
179
|
+
b_dec=self.b_dec.detach().cpu().numpy(),
|
|
180
|
+
threshold=self.threshold.cpu().numpy(),
|
|
181
|
+
k=np.int64(self.k),
|
|
182
|
+
prefixes=np.asarray(self.prefixes, dtype=np.int64),
|
|
183
|
+
architecture=np.str_(self.architecture),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def load_sae(path: str | Path, device: str = "cpu") -> SparseAutoencoder:
|
|
188
|
+
"""Load an SAE saved with ``save`` (the released models are Matryoshka BatchTopK) for inference."""
|
|
189
|
+
arrays = np.load(path)
|
|
190
|
+
dictionary_size, input_dim = arrays["W_dec"].shape
|
|
191
|
+
prefixes = arrays["prefixes"].tolist()
|
|
192
|
+
architecture = (str(arrays["architecture"]) if "architecture" in arrays.files
|
|
193
|
+
else "matryoshka_batchtopk" if len(prefixes) > 1 else "batchtopk")
|
|
194
|
+
model = SparseAutoencoder(input_dim, dictionary_size, int(arrays["k"]), architecture, prefixes)
|
|
195
|
+
with torch.no_grad():
|
|
196
|
+
for name in ("W_enc", "W_dec", "b_enc", "b_dec", "threshold"):
|
|
197
|
+
getattr(model, name).copy_(torch.from_numpy(arrays[name]))
|
|
198
|
+
return model.to(device).eval()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@torch.no_grad()
|
|
202
|
+
def encode(model: SparseAutoencoder, embeddings: np.ndarray, batch_size: int = 65_536) -> np.ndarray:
|
|
203
|
+
"""Dense ``[n, dictionary_size]`` float32 sparse codes of ``[n, input_dim]`` embeddings."""
|
|
204
|
+
device = next(model.parameters()).device
|
|
205
|
+
out = []
|
|
206
|
+
for start in range(0, len(embeddings), batch_size):
|
|
207
|
+
batch = torch.from_numpy(np.array(embeddings[start:start + batch_size], dtype=np.float32))
|
|
208
|
+
out.append(model.encode(batch.to(device)).cpu().numpy())
|
|
209
|
+
return np.concatenate(out, axis=0)
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Fit a decomposition of Earth embeddings: a sparse autoencoder or k-means.
|
|
2
|
+
|
|
3
|
+
SAE defaults reproduce the released models: Matryoshka BatchTopK, dictionary size
|
|
4
|
+
M = 2,048, K = 4 active dimensions per embedding on average, prefixes M/16, 3M/16, 7M/16
|
|
5
|
+
and M, learning rate 16 / (125 sqrt(M)), batch 4,096, Adam, 100,000 steps, seed 42.
|
|
6
|
+
``--method`` also takes ``batchtopk``, ``topk`` or ``kmeans`` (M clusters, one active
|
|
7
|
+
per embedding).
|
|
8
|
+
|
|
9
|
+
python -m saearth.decompose.train --train train.npy --validation validation.npy --output runs/my_sae
|
|
10
|
+
python -m saearth.decompose.train --method topk --dictionary-size 1024 --k 8 ...
|
|
11
|
+
python -m saearth.decompose.train --method kmeans --dictionary-size 512 ...
|
|
12
|
+
|
|
13
|
+
``train.npy`` and ``validation.npy`` hold float32 ``[n, d]`` embeddings (TESSERA rows
|
|
14
|
+
scaled to unit length, see ``embeddings.py``). Writes ``sae.npz`` (or ``kmeans.npz``)
|
|
15
|
+
and ``metrics.json`` with the validation reconstruction R^2 and mean L0.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import torch
|
|
25
|
+
|
|
26
|
+
from .kmeans import assign, fit_kmeans
|
|
27
|
+
from .sae import ARCHITECTURES, SparseAutoencoder
|
|
28
|
+
|
|
29
|
+
SEED = 42
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def geometric_median(points: torch.Tensor, max_iter: int = 100, tolerance: float = 1e-5) -> torch.Tensor:
|
|
33
|
+
guess = points.mean(dim=0)
|
|
34
|
+
for _ in range(max_iter):
|
|
35
|
+
weights = torch.linalg.vector_norm(points - guess, dim=1).clamp_min(1e-12).reciprocal()
|
|
36
|
+
updated = (weights[:, None] * points).sum(dim=0) / weights.sum()
|
|
37
|
+
if torch.linalg.vector_norm(updated - guess) < tolerance:
|
|
38
|
+
return updated
|
|
39
|
+
guess = updated
|
|
40
|
+
return guess
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def batches(rows: int, batch_size: int, steps: int, generator: torch.Generator):
|
|
44
|
+
"""Shuffled full batches, epoch after epoch, until ``steps`` batches are produced."""
|
|
45
|
+
produced = 0
|
|
46
|
+
while produced < steps:
|
|
47
|
+
order = torch.randperm(rows, generator=generator)
|
|
48
|
+
for start in range(0, rows - batch_size + 1, batch_size):
|
|
49
|
+
if produced == steps:
|
|
50
|
+
return
|
|
51
|
+
yield produced, order[start:start + batch_size]
|
|
52
|
+
produced += 1
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@torch.no_grad()
|
|
56
|
+
def evaluate(model: SparseAutoencoder, values: torch.Tensor, batch_size: int) -> dict:
|
|
57
|
+
"""Reconstruction R^2 (full dictionary) and mean number of active dimensions."""
|
|
58
|
+
mean = values.double().mean(dim=0)
|
|
59
|
+
sse = sst = active = 0.0
|
|
60
|
+
for start in range(0, len(values), batch_size):
|
|
61
|
+
batch = values[start:start + batch_size]
|
|
62
|
+
codes = model.encode(batch)
|
|
63
|
+
sse += float((batch.double() - model.decode(codes).double()).square().sum())
|
|
64
|
+
sst += float((batch.double() - mean).square().sum())
|
|
65
|
+
active += float((codes > 0).sum())
|
|
66
|
+
return {"r2": 1.0 - sse / sst, "l0": active / len(values)}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def train_sae(train: np.ndarray, validation: np.ndarray, dictionary_size: int = 2048, k: int = 4,
|
|
70
|
+
architecture: str = "matryoshka_batchtopk", prefixes: list[int] | None = None,
|
|
71
|
+
steps: int = 100_000, batch_size: int = 4096, device: str | None = None):
|
|
72
|
+
"""Train an SAE (``architecture`` in matryoshka_batchtopk, batchtopk, topk); returns it and its validation R^2 and mean L0."""
|
|
73
|
+
torch.manual_seed(SEED)
|
|
74
|
+
torch.cuda.manual_seed_all(SEED)
|
|
75
|
+
torch.use_deterministic_algorithms(True)
|
|
76
|
+
device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
|
77
|
+
train = torch.from_numpy(np.asarray(train, dtype=np.float32)).to(device)
|
|
78
|
+
validation = torch.from_numpy(np.asarray(validation, dtype=np.float32)).to(device)
|
|
79
|
+
m = dictionary_size
|
|
80
|
+
model = SparseAutoencoder(train.shape[1], m, k, architecture, prefixes).to(device)
|
|
81
|
+
optimizer = torch.optim.Adam(model.parameters(), lr=16.0 / (125.0 * math.sqrt(m)), betas=(0.9, 0.999))
|
|
82
|
+
generator = torch.Generator(device="cpu")
|
|
83
|
+
generator.manual_seed(SEED)
|
|
84
|
+
|
|
85
|
+
for step, indices in batches(len(train), batch_size, steps, generator):
|
|
86
|
+
batch = train.index_select(0, indices.to(device))
|
|
87
|
+
if step == 0:
|
|
88
|
+
with torch.no_grad():
|
|
89
|
+
model.b_dec.copy_(geometric_median(batch))
|
|
90
|
+
model.train()
|
|
91
|
+
result = model.training_step(batch, step)
|
|
92
|
+
optimizer.zero_grad(set_to_none=True)
|
|
93
|
+
result.loss.backward()
|
|
94
|
+
model.project_decoder_gradient_()
|
|
95
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
96
|
+
optimizer.step()
|
|
97
|
+
model.normalize_decoder_()
|
|
98
|
+
if (step + 1) % 10_000 == 0 or step + 1 == steps:
|
|
99
|
+
print(json.dumps({"step": step + 1, "loss": round(float(result.loss.detach()), 4)}), flush=True)
|
|
100
|
+
model.eval()
|
|
101
|
+
return model, evaluate(model, validation, batch_size)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def train_kmeans(train: np.ndarray, validation: np.ndarray, clusters: int = 2048, max_iter: int = 3000):
|
|
105
|
+
"""Fit k-means; returns the float64 centers and the validation R^2 of nearest-center reconstruction (L0 = 1)."""
|
|
106
|
+
centers = fit_kmeans(train, clusters, max_iter)
|
|
107
|
+
labels, _ = assign(validation, centers)
|
|
108
|
+
validation = np.asarray(validation, dtype=np.float64)
|
|
109
|
+
sse = float(np.square(validation - centers[labels]).sum())
|
|
110
|
+
sst = float(np.square(validation - validation.mean(axis=0)).sum())
|
|
111
|
+
return centers, {"r2": 1.0 - sse / sst, "l0": 1.0}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def main():
|
|
115
|
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
116
|
+
p.add_argument("--train", type=Path, required=True)
|
|
117
|
+
p.add_argument("--validation", type=Path, required=True)
|
|
118
|
+
p.add_argument("--output", type=Path, required=True)
|
|
119
|
+
p.add_argument("--method", default="matryoshka_batchtopk", choices=[*ARCHITECTURES, "kmeans"])
|
|
120
|
+
p.add_argument("--dictionary-size", type=int, default=2048, help="SAE dimensions, or k-means clusters")
|
|
121
|
+
p.add_argument("--k", type=int, default=4, help="active dimensions per embedding (SAE)")
|
|
122
|
+
p.add_argument("--prefixes", type=int, nargs="+", help="Matryoshka prefixes ending at the dictionary size")
|
|
123
|
+
p.add_argument("--steps", type=int, default=100_000)
|
|
124
|
+
p.add_argument("--batch-size", type=int, default=4096)
|
|
125
|
+
p.add_argument("--device", default=None)
|
|
126
|
+
a = p.parse_args()
|
|
127
|
+
train, validation = np.load(a.train), np.load(a.validation)
|
|
128
|
+
a.output.mkdir(parents=True, exist_ok=True)
|
|
129
|
+
if a.method == "kmeans":
|
|
130
|
+
centers, metrics = train_kmeans(train, validation, a.dictionary_size)
|
|
131
|
+
np.savez(a.output / "kmeans.npz", centers=centers)
|
|
132
|
+
else:
|
|
133
|
+
model, metrics = train_sae(train, validation, a.dictionary_size, a.k, a.method, a.prefixes, a.steps,
|
|
134
|
+
a.batch_size, a.device)
|
|
135
|
+
model.save(a.output / "sae.npz")
|
|
136
|
+
metrics["prefixes"] = list(model.prefixes)
|
|
137
|
+
(a.output / "metrics.json").write_text(json.dumps({"method": a.method, "validation": metrics}, indent=2))
|
|
138
|
+
print(json.dumps(metrics))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
if __name__ == "__main__":
|
|
142
|
+
main()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Step 2 of SAEarth: interpret each sparse dimension in natural language.
|
|
2
|
+
|
|
3
|
+
An image-only language-model agent explores satellite images of the locations where a
|
|
4
|
+
dimension is active or inactive, writes a description, and refines it against a
|
|
5
|
+
validation fidelity score; the final description is scored once on held-out locations
|
|
6
|
+
and given a short label.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def __getattr__(name):
|
|
11
|
+
# Imported on first use, so ``python -m saearth.interpret.interpret`` runs without a runpy warning.
|
|
12
|
+
if name == "interpret_dimensions":
|
|
13
|
+
from .interpret import interpret_dimensions
|
|
14
|
+
return interpret_dimensions
|
|
15
|
+
raise AttributeError(name)
|