Coverage for src/retrospeedlab/search/policy/prior.py: 100%
48 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-04 00:01 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-04 00:01 +0000
1import random
2from pathlib import Path
4import numpy as np
6from retrospeedlab.search.route.route_map import changed_at
8POLICY_FILE = "policy.npz"
9BYTE_SCALE = 255.0
11WEIGHT = "weight"
12BIAS = "bias"
14Layers = list[tuple[np.ndarray, np.ndarray]]
15Weights = dict[str, np.ndarray]
18def layers_of(weights: Weights) -> Layers:
19 count = sum(name.startswith(WEIGHT) for name in weights)
20 return [(weights[f"{WEIGHT}{index}"], weights[f"{BIAS}{index}"]) for index in range(count)]
23def load_weights(path: Path) -> Weights:
24 with np.load(path) as arrays:
25 return {name: arrays[name] for name in arrays.files}
28def observation(memory: np.ndarray) -> np.ndarray:
29 return memory.astype(np.float32) / BYTE_SCALE
32def hidden_of(layers: Layers, memory: np.ndarray) -> np.ndarray:
33 hidden = observation(memory)
34 for weight, bias in layers[:-1]:
35 hidden = np.tanh(weight @ hidden + bias)
36 return hidden
39def log_probabilities(layers: Layers, hidden: np.ndarray, actions: int) -> np.ndarray:
40 logits = (layers[-1][0] @ hidden + layers[-1][1])[:actions]
41 shifted = logits - logits.max()
42 return shifted - np.log(np.exp(shifted).sum())
45class PolicyPrior:
46 def __init__(self, path: Path) -> None:
47 self.path = path
48 self.layers: Layers = []
49 self.loaded: int | None = None
51 def current(self) -> Layers:
52 changed = changed_at(self.path)
53 if changed != self.loaded:
54 self.layers = [] if changed is None else layers_of(load_weights(self.path))
55 self.loaded = changed
56 return self.layers
58 def probabilities(self, memory: np.ndarray, actions: int) -> np.ndarray | None:
59 layers = self.current()
60 if not layers:
61 return None
62 return np.exp(log_probabilities(layers, hidden_of(layers, memory), actions))
64 def choose(self, memory: np.ndarray, actions: int, rng: random.Random) -> int | None:
65 probabilities = self.probabilities(memory, actions)
66 if probabilities is None:
67 return None
68 return rng.choices(range(actions), weights=probabilities.tolist())[0]