QDpy
Loading...
Searching...
No Matches
_batch_rollout.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Evaluate different actor genomes without stepping completed lanes."""
6
7from copy import deepcopy
8
9import numpy as np
10import torch
11from torch import nn
12
13from .policy import CategoricalPolicy
14from .rollout import Episode
15
16
18 """Decode native flat genomes once and apply a different affine map per lane."""
19
20 def __init__(self, policy, genomes):
21 self.policy = policy
22 values = np.asarray(genomes, dtype=np.float32)
23 if not np.isfinite(values).all():
24 raise ValueError("Expected finite actor parameters.")
25 parameters = policy._tensor(values)
26 self.width = len(genomes)
27 self.layers = []
28 offset = 0
29 for layer in policy._network:
30 if isinstance(layer, nn.Linear):
31 size = layer.weight.numel()
32 weight = parameters[:, offset:offset + size].reshape(len(genomes), *layer.weight.shape)
33 offset += size
34 bias = parameters[:, offset:offset + layer.out_features]
35 offset += layer.out_features
36 self.layers.append((weight, bias))
37 else:
38 self.layers.append(layer)
39
40 @torch.no_grad()
41 def actions(self, lanes, observations):
42 indices = (None if len(lanes) == self.width
43 else torch.as_tensor(lanes, dtype=torch.long, device=self.policy.device))
44 outputs = self.policy._tensor(np.stack(observations))
45 for layer in self.layers:
46 if isinstance(layer, tuple):
47 weight, bias = layer
48 if indices is not None:
49 weight, bias = weight[indices], bias[indices]
50 outputs = torch.baddbmm(bias.unsqueeze(-1), weight, outputs.unsqueeze(-1)).squeeze(-1)
51 else:
52 outputs = layer(outputs)
53 if isinstance(self.policy, CategoricalPolicy):
54 indices = self.policy._greedy_indices(outputs).cpu().numpy()
55 return [self.policy._actions.decode(row) for row in indices]
56 return [self.policy._decode(row) for row in outputs.tanh().cpu().numpy()]
57
58
60 """Collect the same episode data as the single-lane rollout."""
61
62 def __init__(self, cursor, seed):
63 self.cursor = cursor
64 self.initial_info = deepcopy(cursor.reset(seed=seed))
65 self.observations = [cursor.observation]
66 self.actions = []
67 self.rewards = []
68
69 def step(self, action, budget, observation_shape):
70 self.actions.append(action.copy() if isinstance(action, np.ndarray) else action)
71 reward, terminated, truncated, info = self.cursor.step(action, budget, "evaluation_steps")
72 self.rewards.append(reward)
73 self.observations.append(self.cursor.observation)
74 if self.cursor.ended:
75 observations = np.stack(self.observations).reshape(len(self.observations), *observation_shape)
76 return Episode(observations, tuple(self.actions), tuple(self.rewards), self.initial_info,
77 deepcopy(dict(info)), terminated, truncated)
78 return None
79
80
81
82def _evaluate_batch(actor, cursors, genomes, budget, seeds, episode_count):
83 """Return completed episodes per candidate in proposal order.
84
85 Each repeat starts at most as many episodes as the remaining step
86 budget allows. Finished lanes wait for the next repeat. The last
87 round advances only the lanes with remaining step slots.
88 """
89 batch = _BatchActor(actor, genomes)
90 results = [[] for _ in cursors]
91 # Allocate resets in candidate order even though environment steps are interleaved.
92 assigned = seeds.integers(0, 2**32, size=(len(cursors), episode_count), dtype=np.uint64)
93 for repeat in range(episode_count):
94 if not budget.remaining:
95 break
96 active = {lane: _BatchEpisode(cursor, int(assigned[lane, repeat]))
97 for lane, cursor in enumerate(cursors[:budget.remaining])}
98 while active and budget.remaining:
99 lanes = list(active)[:budget.remaining]
100 actions = batch.actions(lanes, [cursors[lane].observation for lane in lanes])
101 for lane, action in zip(lanes, actions):
102 episode = active[lane].step(action, budget, actor._obs_shape)
103 if episode is not None:
104 results[lane].append(episode)
105 del active[lane]
106 return results
Measurements from a completed evaluation episode.
Definition rollout.py:20