action-atlas-groot / loader.py
bag100's picture
Add files using upload-large-folder tool
3e6b99a verified
Raw
History Blame Contribute Delete
3.02 kB
#!/usr/bin/env python3
'''
Reference loader for the OpenVLA-OFT SAE release.
Loads a released SAE safetensors file into a TopK sparse autoencoder and applies it to OpenVLA-OFT
activations. The released SAEs were trained on z-scored activations, so the stored mean and std are
applied inside encode() and removed inside the reconstruction; callers pass raw activations.
Example:
import torch
from loader import load_sae, load_activation_episode
sae = load_sae("saes/per_token/sae_layer16.safetensors")
acts = load_activation_episode("libero_goal/.../task2_trial0_activations.pt")["layer_16"] # [n,1,595,4096]
x = acts.squeeze(1)[:, -7:, :].reshape(-1, 4096).float() # 7 action tokens, per-token
codes = sae.encode(x) # [N, d_sae], TopK-sparse
recon = sae.decode(codes) # [N, d_in]
'''
import json
from pathlib import Path
import torch
import torch.nn as nn
from safetensors import safe_open
class TopKSAE(nn.Module):
'''
TopK sparse autoencoder matching the training recipe (Gao et al. 2024): the encoder selects
the k largest pre-activations per token, the decoder reconstructs from that sparse code, and
z-scoring is folded in via the stored mean and std.
'''
def __init__(self, d_in, d_sae, k, mean, std):
super().__init__()
self.k = k
self.encoder = nn.Linear(d_in, d_sae)
self.decoder = nn.Linear(d_sae, d_in)
self.register_buffer("mean", mean)
self.register_buffer("std", std)
def encode(self, x):
x_norm = (x - self.mean) / self.std
pre = self.encoder(x_norm)
topv, topi = pre.topk(self.k, dim=-1)
z = torch.zeros_like(pre)
return z.scatter(-1, topi, topv)
def decode(self, z):
# decoder reconstructs in z-scored space; undo the normalization to return raw activations
return self.decoder(z) * self.std + self.mean
def forward(self, x):
return self.decode(self.encode(x))
def load_sae(path, device="cpu"):
path = Path(path)
with safe_open(path, framework="pt") as f:
meta = dict(f.metadata())
tensors = {k: f.get_tensor(k) for k in f.keys()}
d_in, d_sae, k = int(meta["d_in"]), int(meta["d_sae"]), int(meta["k"])
sae = TopKSAE(d_in, d_sae, k, tensors["mean"], tensors["std"])
sae.encoder.weight.data = tensors["encoder.weight"]
sae.encoder.bias.data = tensors["encoder.bias"]
sae.decoder.weight.data = tensors["decoder.weight"]
sae.decoder.bias.data = tensors["decoder.bias"]
sae.metadata = meta
return sae.to(device).eval()
def load_activation_episode(path):
# returns a dict layer_0..layer_31 -> bfloat16 tensor [n_activations, 1, 595, 4096]
return torch.load(path, map_location="cpu", weights_only=True)
def load_concepts(concepts_json):
'''
Load the concept -> SAE-feature-index map. Returns a nested dict
{layer_key: {category: {concept: {..., feature_indices: [int]}}}}.
'''
return json.load(open(concepts_json))