File size: 3,874 Bytes
9d20fe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d3e0c7
9d20fe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d3e0c7
 
9d20fe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d3e0c7
9d20fe4
 
 
 
 
 
 
 
 
9d3e0c7
9d20fe4
 
 
9d3e0c7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Bounded, historical token trajectories in one shared, frozen PCA space."""
import torch
import torch.nn.functional as F

class RepresentationState:
    capacity = 128
    calibration_size = 8

    def __init__(self):
        self.pending = {}
        self.basis = self.center = self.scale = self.coords = None
        self.boundary = None
        self.queries = [-2] * self.capacity
        self.stages = 0
        self.fitted_samples = 0
        self.needs_full = False
        self.dimension_axes = None

    def add(self, query, hidden_states):
        if not hidden_states:
            raise ValueError("This model did not expose layer hidden states.")
        vectors = torch.stack([state[0, -1].detach().float() for state in hidden_states])
        vectors = F.normalize(vectors, dim=-1).cpu()
        if not torch.isfinite(vectors).all():
            raise ValueError("The model returned non-finite hidden states.")
        self.stages = len(vectors)
        if self.basis is None:
            self.pending[query] = vectors
            if sum(q >= 0 for q in self.pending) >= self.calibration_size:
                self.finalize()
        else:
            self._record(query, vectors)

    def finalize(self):
        samples = [vectors for query, vectors in self.pending.items() if query >= 0]
        if self.basis is not None or not samples:
            return
        sample = torch.cat(samples)
        self.center = sample.mean(0)
        centered = sample - self.center
        dimensions = min(3, *centered.shape)
        with torch.random.fork_rng(devices=[]):
            torch.manual_seed(42)
            _, _, basis = torch.pca_lowrank(centered, q=dimensions, center=False, niter=3)
        self.basis = F.pad(basis, (0, 3-dimensions))
        self.scale = torch.linalg.vector_norm(centered @ self.basis, dim=1).quantile(.95).clamp_min(.01)
        from projection_axes import projected_dimension_axes
        self.dimension_axes=projected_dimension_axes(self.basis,self.center,self.scale,"normalised_hidden_states")
        self.coords = torch.zeros((self.capacity, self.stages, 3), dtype=torch.float32)
        self.fitted_samples = len(samples)
        pending, self.pending = self.pending, {}
        for query, vectors in pending.items():
            self._record(query, vectors)
        self.needs_full = True

    def _record(self, query, vectors):
        coords = (vectors - self.center) @ self.basis / self.scale * 2.4
        if query == -1:
            self.boundary = coords
        else:
            slot = query % self.capacity
            self.coords[slot].copy_(coords)
            self.queries[slot] = query

    def snapshot(self, token_count, full=False):
        ready = self.basis is not None
        include_axes=ready and (full or self.needs_full)
        queries = sorted(q for q in self.queries if q >= max(0, token_count-self.capacity-1))
        if not (full or self.needs_full):
            queries = queries[-1:]
        def point(query, coords):
            return {"n": query, "layers": [[round(value,5) for value in row] for row in coords.tolist()]}
        points = [point(q, self.coords[q % self.capacity]) for q in queries] if ready else []
        if ready and self.boundary is not None:
            points.append(point(-1, self.boundary))
        self.needs_full = False
        result={"ready": ready, "stages": self.stages, "capacity": self.capacity,
                "calibrating": sum(q>=0 for q in self.pending), "calibration_target": self.calibration_size,
                "fitted_samples": self.fitted_samples, "points": points,
                "projection": "Shared PCA of unit-normalised hidden states; axes fixed for this stream"}
        if include_axes:result["dimension_axes"]=self.dimension_axes
        return result