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

1import random 

2from pathlib import Path 

3 

4import numpy as np 

5 

6from retrospeedlab.search.route.route_map import changed_at 

7 

8POLICY_FILE = "policy.npz" 

9BYTE_SCALE = 255.0 

10 

11WEIGHT = "weight" 

12BIAS = "bias" 

13 

14Layers = list[tuple[np.ndarray, np.ndarray]] 

15Weights = dict[str, np.ndarray] 

16 

17 

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)] 

21 

22 

23def load_weights(path: Path) -> Weights: 

24 with np.load(path) as arrays: 

25 return {name: arrays[name] for name in arrays.files} 

26 

27 

28def observation(memory: np.ndarray) -> np.ndarray: 

29 return memory.astype(np.float32) / BYTE_SCALE 

30 

31 

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 

37 

38 

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()) 

43 

44 

45class PolicyPrior: 

46 def __init__(self, path: Path) -> None: 

47 self.path = path 

48 self.layers: Layers = [] 

49 self.loaded: int | None = None 

50 

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 

57 

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)) 

63 

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]