phyelds-gpu 10.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ """
2
+ Who hears whom, as tensors: the communication graph of many devices, grouped by receiver, and
3
+ the radius search that builds it on a uniform grid, on CPU or GPU.
4
+ """
5
+ from collections.abc import Iterable, Mapping
6
+ from dataclasses import dataclass
7
+ import itertools
8
+ import math
9
+
10
+ import torch
11
+
12
+ # Cells a little wider than the radius, so that rounding never hides a neighbor in a farther
13
+ # cell, as in the uniform grid of the simulator.
14
+ _MARGIN = 1.0 + 1e-6
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class BatchEdges:
19
+ """The edges into a batch of devices: where what they hear comes from."""
20
+
21
+ devices: torch.Tensor
22
+ """The ids of the devices of the batch (``int64 [M]``)."""
23
+ edges: torch.Tensor
24
+ """The index of each edge into the batch among the edges of the topology (``int64 [E]``)."""
25
+ senders: torch.Tensor
26
+ """The id of the device each edge comes from (``int64 [E]``)."""
27
+ receivers: torch.Tensor
28
+ """The position in ``devices`` of the device each edge goes to (``int64 [E]``)."""
29
+
30
+ @property
31
+ def num_devices(self) -> int:
32
+ """How many devices the batch holds."""
33
+ return int(self.devices.numel())
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class GraphTopology:
38
+ """
39
+ A directed communication graph on a torch device: an edge goes from a sender to a
40
+ receiver that hears it. The edges are grouped by receiver, and sorted by sender in each
41
+ group, so that the edges into device ``i`` are ``offsets[i]:offsets[i + 1]``.
42
+ """
43
+
44
+ num_devices: int
45
+ """How many devices the graph links, with ids ``0`` to ``num_devices - 1``."""
46
+ senders: torch.Tensor
47
+ """The device each edge comes from (``int64 [E]``)."""
48
+ receivers: torch.Tensor
49
+ """The device each edge goes to (``int64 [E]``), in non-decreasing order."""
50
+ offsets: torch.Tensor
51
+ """Where the edges into each device start, and then end (``int64 [num_devices + 1]``)."""
52
+ distances: torch.Tensor | None = None
53
+ """The length of each edge (``float64 [E]``), if the positions of the devices are known."""
54
+
55
+ @property
56
+ def device(self) -> torch.device:
57
+ """The torch device holding the tensors of the graph."""
58
+ return self.offsets.device
59
+
60
+ @classmethod
61
+ def empty(cls, num_devices: int, device: torch.device | str = "cpu") -> "GraphTopology":
62
+ """
63
+ A graph of devices that hear nobody.
64
+
65
+ Args:
66
+ num_devices: How many devices the graph has.
67
+ device: The torch device holding its tensors.
68
+
69
+ Returns:
70
+ A ``GraphTopology`` without edges.
71
+ """
72
+ none = torch.zeros(0, dtype=torch.int64, device=device)
73
+ offsets = torch.zeros(num_devices + 1, dtype=torch.int64, device=device)
74
+ return cls(num_devices, none, none, offsets)
75
+
76
+ @classmethod
77
+ def from_neighbors(
78
+ cls,
79
+ neighbors: Mapping[int, Iterable[int]],
80
+ *,
81
+ num_devices: int | None = None,
82
+ positions: torch.Tensor | None = None,
83
+ device: torch.device | str = "cpu",
84
+ ) -> "GraphTopology":
85
+ """
86
+ The graph in which each device hears its neighbors.
87
+
88
+ Args:
89
+ neighbors: The ids of the neighbors of each device, by its id; a device hears
90
+ its neighbors, never itself.
91
+ num_devices: How many devices the graph has; ``len(neighbors)`` by default.
92
+ positions: The position of each device (``[num_devices, D]``), to measure the
93
+ edges; none by default.
94
+ device: The torch device holding the tensors of the graph.
95
+
96
+ Returns:
97
+ The ``GraphTopology`` of ``neighbors``.
98
+ """
99
+ count = len(neighbors) if num_devices is None else num_devices
100
+ senders: list[int] = []
101
+ receivers: list[int] = []
102
+ for receiver in range(count):
103
+ peers = sorted(peer for peer in neighbors.get(receiver, ()) if peer != receiver)
104
+ senders.extend(peers)
105
+ receivers.extend([receiver] * len(peers))
106
+ sender_ids = torch.tensor(senders, dtype=torch.int64, device=device)
107
+ receiver_ids = torch.tensor(receivers, dtype=torch.int64, device=device)
108
+ distances = None
109
+ if positions is not None:
110
+ located = positions.to(device=device, dtype=torch.float64)
111
+ distances = _lengths(located[sender_ids] - located[receiver_ids])
112
+ return cls(count, sender_ids, receiver_ids, _offsets(receiver_ids, count), distances)
113
+
114
+ def batch(self, devices: torch.Tensor | None = None) -> BatchEdges:
115
+ """
116
+ The edges into a batch of devices.
117
+
118
+ Args:
119
+ devices: The ids of the devices of the batch (``int64 [M]``); every device by
120
+ default, sharing the tensors of the graph.
121
+
122
+ Returns:
123
+ The ``BatchEdges`` of the batch, grouped by receiver in the order of ``devices``.
124
+ """
125
+ if devices is None:
126
+ every = torch.arange(self.num_devices, dtype=torch.int64, device=self.device)
127
+ all_edges = torch.arange(self.senders.numel(), dtype=torch.int64, device=self.device)
128
+ return BatchEdges(every, all_edges, self.senders, self.receivers)
129
+ devices = devices.to(device=self.device, dtype=torch.int64)
130
+ starts = self.offsets[devices]
131
+ lengths = self.offsets[devices + 1] - starts
132
+ receivers = torch.repeat_interleave(
133
+ torch.arange(devices.numel(), dtype=torch.int64, device=self.device), lengths
134
+ )
135
+ # The position of each edge in the group of its receiver.
136
+ firsts = torch.cumsum(lengths, dim=0) - lengths
137
+ rank = torch.arange(receivers.numel(), dtype=torch.int64, device=self.device)
138
+ edges = starts[receivers] + rank - firsts[receivers]
139
+ return BatchEdges(devices, edges, self.senders[edges], receivers)
140
+
141
+ def to_neighbors(self) -> dict[int, list[int]]:
142
+ """
143
+ The neighbors of each device, as plain Python values.
144
+
145
+ Returns:
146
+ The ids of the devices each device hears, in increasing order, by its id.
147
+ """
148
+ offsets = self.offsets.tolist()
149
+ senders = self.senders.tolist()
150
+ return {
151
+ device: senders[offsets[device]:offsets[device + 1]]
152
+ for device in range(self.num_devices)
153
+ }
154
+
155
+
156
+ def radius_topology(positions: torch.Tensor, radius: float) -> GraphTopology:
157
+ """
158
+ The graph in which each device hears the others within ``radius`` of it.
159
+
160
+ The search goes through a uniform grid of cells as wide as ``radius``, on the torch
161
+ device of ``positions``: each device is compared only with those in its cell and in the
162
+ cells around it. The neighbors are those of ``radius_neighborhood`` in the simulator.
163
+
164
+ Args:
165
+ positions: The position of each device (``[N, D]``).
166
+ radius: How far a device hears; with a negative one, nobody hears anybody.
167
+
168
+ Returns:
169
+ The ``GraphTopology`` of the devices, with the length of each edge.
170
+
171
+ Raises:
172
+ ValueError: If the devices are spread over too many cells to key them with ``int64``,
173
+ as hundreds of thousands of them in a space a million times wider than ``radius``.
174
+ """
175
+ count = int(positions.shape[0])
176
+ located = positions.to(dtype=torch.float64)
177
+ if count == 0 or radius < 0.0:
178
+ return GraphTopology.empty(count, positions.device)
179
+
180
+ grid = _Grid.build(located, radius * _MARGIN if radius > 0.0 else 1.0)
181
+ parts = [
182
+ found
183
+ for shift in itertools.product((-1, 0, 1), repeat=grid.dims)
184
+ if (found := grid.pairs_within(located, radius, shift)) is not None
185
+ ]
186
+ if not parts:
187
+ return GraphTopology.empty(count, positions.device)
188
+ senders = torch.cat([part[0] for part in parts])
189
+ receivers = torch.cat([part[1] for part in parts])
190
+ distances = torch.cat([part[2] for part in parts])
191
+ order = torch.argsort(receivers * count + senders)
192
+ receivers = receivers[order]
193
+ return GraphTopology(
194
+ count, senders[order], receivers, _offsets(receivers, count), distances[order]
195
+ )
196
+
197
+
198
+ def _lengths(vectors: torch.Tensor) -> torch.Tensor:
199
+ """The Euclidean length of each row of ``vectors``."""
200
+ # pylint cannot see into the C extension of torch, where vector_norm is a function.
201
+ return torch.linalg.vector_norm(vectors, dim=-1) # pylint: disable=not-callable
202
+
203
+
204
+ def _offsets(receivers: torch.Tensor, count: int) -> torch.Tensor:
205
+ """Where the edges into each of ``count`` devices start in sorted ``receivers``, then end."""
206
+ return torch.searchsorted(
207
+ receivers, torch.arange(count + 1, dtype=torch.int64, device=receivers.device)
208
+ )
209
+
210
+
211
+ @dataclass(frozen=True)
212
+ class _Grid:
213
+ """Devices sorted by cell, with the cells that hold at least one of them."""
214
+
215
+ sorted_devices: torch.Tensor
216
+ """The devices, ordered by the key of their cell."""
217
+ keys: torch.Tensor
218
+ """The keys of the cells holding devices, in increasing order."""
219
+ starts: torch.Tensor
220
+ """Where the devices of each cell start in ``sorted_devices``."""
221
+ counts: torch.Tensor
222
+ """How many devices each cell holds."""
223
+ strides: torch.Tensor
224
+ """How much the key of a cell grows with each coordinate of the cell."""
225
+ dims: int
226
+ """How many coordinates a position has."""
227
+
228
+ @classmethod
229
+ def build(cls, positions: torch.Tensor, side: float) -> "_Grid":
230
+ """
231
+ The grid of cells as wide as ``side`` holding ``positions``.
232
+
233
+ Raises:
234
+ ValueError: If the cells around the devices are too many to key with ``int64``.
235
+ """
236
+ cells = torch.floor(positions / side).to(torch.int64)
237
+ # Along each axis, only the coordinates of the cells with devices and of those next
238
+ # to them: a cell and the next keep consecutive ranks, so a shift by one cell is a
239
+ # shift by one rank, and the keys grow with the devices, not with the space.
240
+ ranks, sizes = [], []
241
+ for column in cells.T.contiguous():
242
+ around = torch.unique(torch.cat([column - 1, column, column + 1]))
243
+ ranks.append(torch.searchsorted(around, column))
244
+ sizes.append(int(around.numel()))
245
+ if math.prod(sizes) > torch.iinfo(torch.int64).max:
246
+ raise ValueError(
247
+ f"the {positions.shape[0]} devices span too many cells of side {side} to key"
248
+ " them: build the graph with GraphTopology.from_neighbors"
249
+ )
250
+ strides = [math.prod(sizes[axis + 1:]) for axis in range(len(sizes))]
251
+ stride_tensor = torch.tensor(strides, dtype=torch.int64, device=positions.device)
252
+ keys = (torch.stack(ranks, dim=1) * stride_tensor).sum(dim=-1)
253
+ order = torch.argsort(keys, stable=True)
254
+ unique_keys, counts = torch.unique_consecutive(keys[order], return_counts=True)
255
+ starts = torch.cumsum(counts, dim=0) - counts
256
+ return cls(order, unique_keys, starts, counts, stride_tensor, len(sizes))
257
+
258
+ def pairs_within(
259
+ self, positions: torch.Tensor, radius: float, shift: tuple[int, ...]
260
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None:
261
+ """
262
+ The pairs of devices within ``radius`` of each other, the receiver in a cell and the
263
+ sender in the cell ``shift`` away: their senders, receivers and distances.
264
+ """
265
+ targets = self.keys + (torch.tensor(shift, device=self.keys.device) * self.strides).sum()
266
+ found = torch.searchsorted(self.keys, targets)
267
+ safe = torch.clamp(found, max=self.keys.numel() - 1)
268
+ matched = (found < self.keys.numel()) & (self.keys[safe] == targets)
269
+ if not bool(matched.any()):
270
+ return None
271
+ receiver_cells = torch.nonzero(matched).squeeze(-1)
272
+ senders, receivers = self._cross(receiver_cells, safe[receiver_cells])
273
+ apart = senders != receivers
274
+ senders, receivers = senders[apart], receivers[apart]
275
+ distances = _lengths(positions[senders] - positions[receivers])
276
+ within = distances <= radius
277
+ if not bool(within.any()):
278
+ return None
279
+ return senders[within], receivers[within], distances[within]
280
+
281
+ def _cross(
282
+ self, receiver_cells: torch.Tensor, sender_cells: torch.Tensor
283
+ ) -> tuple[torch.Tensor, torch.Tensor]:
284
+ """Every pair of a device in a receiver cell and one in the matching sender cell."""
285
+ sender_counts = self.counts[sender_cells]
286
+ sizes = self.counts[receiver_cells] * sender_counts
287
+ pair = torch.repeat_interleave(
288
+ torch.arange(sizes.numel(), dtype=torch.int64, device=sizes.device), sizes
289
+ )
290
+ rank = torch.arange(int(sizes.sum()), dtype=torch.int64, device=sizes.device)
291
+ rank = rank - (torch.cumsum(sizes, dim=0) - sizes)[pair]
292
+ row = torch.div(rank, sender_counts[pair], rounding_mode="floor")
293
+ column = rank - row * sender_counts[pair]
294
+ receivers = self.sorted_devices[self.starts[receiver_cells][pair] + row]
295
+ senders = self.sorted_devices[self.starts[sender_cells][pair] + column]
296
+ return senders, receivers
@@ -0,0 +1,381 @@
1
+ """
2
+ Wavefronts of a batch of devices on a torch device: devices with their own clocks, talking
3
+ over a channel with delays and losses, running together when they do not depend on each other,
4
+ as ``phyelds.experimental.wavefront`` does, with one row per device.
5
+
6
+ The clocks and the channel are those of ``phyelds.experimental.wavefront``: they compute with
7
+ arithmetic only, so the same objects compute on tensors here.
8
+ """
9
+ from collections.abc import Callable, Mapping
10
+ from dataclasses import dataclass, field
11
+ import math
12
+ from typing import Any
13
+
14
+ import torch
15
+
16
+ from phyelds.experimental.wavefront import Channel, Clock, Draws, PeriodicClock
17
+ from phyelds.gpu.engine import BatchEngine, Rows, States, _written
18
+ from phyelds.gpu.tensors import as_rows
19
+ from phyelds.gpu.topology import BatchEdges, GraphTopology
20
+
21
+
22
+ def select_batch(
23
+ next_times: torch.Tensor,
24
+ topology: GraphTopology,
25
+ *,
26
+ lookahead: float,
27
+ delay: float,
28
+ until: float | None = None,
29
+ ) -> torch.Tensor:
30
+ """
31
+ Pick the devices that run their next round together, as ``select_wavefront`` does.
32
+
33
+ Args:
34
+ next_times: The time of the next round of each device (``float64 [N]``).
35
+ topology: Who hears whom: a device waits for the neighbors it hears.
36
+ lookahead: How far past the earliest pending round a wavefront reaches.
37
+ delay: How long a message takes, at the least, to reach a neighbor.
38
+ until: The time after which no round runs; none by default.
39
+
40
+ Returns:
41
+ The ids of the devices of the wavefront, in increasing order (``int64 [M]``).
42
+ """
43
+ none = torch.zeros(0, dtype=torch.int64, device=next_times.device)
44
+ if next_times.numel() == 0:
45
+ return none
46
+ earliest = float(next_times.min())
47
+ if until is not None and earliest > until:
48
+ return none
49
+ cap = earliest + lookahead if until is None else min(earliest + lookahead, until)
50
+ senders, receivers = topology.senders, topology.receivers
51
+ arrival = next_times[senders] + delay
52
+ due = next_times[receivers]
53
+ # A sender blocks a receiver if a message of its next round can arrive by the receiver's
54
+ # round; with no delay, of two devices due together the one with the lower id runs first.
55
+ blocking = (arrival < due) | ((arrival == due) & ((delay > 0.0) | (senders < receivers)))
56
+ blocked = torch.zeros_like(next_times, dtype=torch.bool)
57
+ blocked[receivers[blocking]] = True
58
+ return torch.nonzero((next_times <= cap) & ~blocked).squeeze(-1)
59
+
60
+
61
+ class Mailbox:
62
+ """
63
+ What each edge carries over a channel: the last message that arrived and the next one in
64
+ flight, with their arrival times, as the links of ``WavefrontRuntime`` keep them. A
65
+ message is the whole outbox of a round of the sender, by alignment key.
66
+
67
+ Args:
68
+ topology: The edges.
69
+ channel: How late messages arrive, which are lost, and for how long they are heard.
70
+ """
71
+
72
+ def __init__(self, topology: GraphTopology, channel: Channel):
73
+ count = int(topology.senders.numel())
74
+ self.topology = topology
75
+ self.channel = channel
76
+ self._arrived_at = torch.full((count,), -math.inf, dtype=torch.float64,
77
+ device=topology.device)
78
+ self._pending_at = torch.full((count,), math.inf, dtype=torch.float64,
79
+ device=topology.device)
80
+ self._arrived: dict[int, Rows] = {}
81
+ self._pending: dict[int, Rows] = {}
82
+
83
+ def read(self, key: int, edges: BatchEdges, times: torch.Tensor) -> Rows | None:
84
+ """
85
+ What each edge into ``edges`` carries at ``key`` when its receiver runs at ``times``.
86
+
87
+ Returns:
88
+ The values and which edges carry one heard at that time; none if no edge ever did.
89
+ """
90
+ if key not in self._arrived and key not in self._pending:
91
+ return None
92
+ index, now = edges.edges, times[edges.receivers]
93
+ arrived = self._pending_at[index] <= now
94
+ values, carried = _pick(arrived, self._slot(self._pending, key, index),
95
+ self._slot(self._arrived, key, index))
96
+ arrival = torch.where(arrived, self._pending_at[index], self._arrived_at[index])
97
+ return values, carried & self.channel.heard(now - arrival)
98
+
99
+ def transmit(
100
+ self, devices: torch.Tensor, times: torch.Tensor, outbox: Mapping[int, Rows],
101
+ uniform: Callable[[int], torch.Tensor],
102
+ ) -> None:
103
+ """
104
+ Send the outbox of ``devices``, which ran at ``times``, on every edge out of them.
105
+
106
+ Args:
107
+ devices: The ids of the senders (``int64 [M]``).
108
+ times: When each of them ran (``float64 [M]``).
109
+ outbox: What they sent, by alignment key: a value of each and whether it sent it.
110
+ uniform: Uniform draws in ``[0, 1)``, ``uniform(n)`` of them, for the channel.
111
+ """
112
+ senders = self.topology.senders
113
+ row = torch.full((self.topology.num_devices,), -1, dtype=torch.int64,
114
+ device=senders.device)
115
+ row[devices] = torch.arange(devices.numel(), device=senders.device)
116
+ sending = torch.nonzero(row[senders] >= 0).squeeze(-1)
117
+ sending = sending[~self.channel.lost(uniform(sending.numel()))]
118
+ rows = row[senders[sending]]
119
+ arrival = self.channel.arrival(times[rows], uniform(sending.numel()))
120
+ # The message in flight has arrived by the time the next one does: it is the last
121
+ # arrived now; one that would arrive later is overtaken, and lost.
122
+ arrived = sending[self._pending_at[sending] <= arrival]
123
+ for key in set(self._arrived) | set(self._pending):
124
+ pending = self._slot(self._pending, key, arrived)
125
+ self._arrived[key] = _put(self._arrived.get(key), self._edges, arrived, *pending)
126
+ self._arrived_at[arrived] = self._pending_at[arrived]
127
+ self._pending_at[sending] = arrival
128
+ for key in set(self._pending) | set(outbox):
129
+ values, sent = outbox.get(key, (None, None))
130
+ if values is None:
131
+ self._pending[key][1][sending] = False
132
+ continue
133
+ self._pending[key] = _put(self._pending.get(key), self._edges, sending,
134
+ values[rows], sent[rows])
135
+
136
+ def clear(self) -> None:
137
+ """Forget every message."""
138
+ self._arrived_at.fill_(-math.inf)
139
+ self._pending_at.fill_(math.inf)
140
+ self._arrived.clear()
141
+ self._pending.clear()
142
+
143
+ @property
144
+ def _edges(self) -> int:
145
+ return int(self.topology.senders.numel())
146
+
147
+ @staticmethod
148
+ def _slot(slots: Mapping[int, Rows], key: int, index: torch.Tensor) -> Rows | None:
149
+ slot = slots.get(key)
150
+ return None if slot is None else (slot[0][index], slot[1][index])
151
+
152
+
153
+ @dataclass(frozen=True)
154
+ class _Reading:
155
+ """The mailbox as the devices of a wavefront read it, each at the time of its round."""
156
+
157
+ mailbox: Mailbox
158
+ times: torch.Tensor
159
+
160
+ def read(self, key: int, edges: BatchEdges) -> Rows | None:
161
+ """What each edge into ``edges`` carries at ``key``, when its receiver runs."""
162
+ return self.mailbox.read(key, edges, self.times)
163
+
164
+
165
+ @dataclass
166
+ class _Run:
167
+ """What a run of a wavefront runtime keeps, from its start or its last reset."""
168
+
169
+ device_draws: torch.Tensor
170
+ next_times: torch.Tensor
171
+ last_times: torch.Tensor
172
+ results: Any = None
173
+ outputs: dict[str, Rows] = field(default_factory=dict)
174
+ now: float = 0.0
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class BatchWavefrontStep:
179
+ """What a wavefront ran."""
180
+
181
+ time: float
182
+ """The latest round of the wavefront."""
183
+ devices: torch.Tensor
184
+ """The ids of its devices (``int64 [M]``)."""
185
+ results: Any
186
+ """What the program returned for them, with a row per device of the wavefront."""
187
+
188
+
189
+ class BatchWavefrontRuntime: # pylint: disable=too-many-instance-attributes
190
+ """
191
+ Runs an aggregate program in wavefronts of devices that do not depend on each other, on
192
+ the torch device of the graph, as ``WavefrontRuntime`` of ``phyelds.experimental`` does.
193
+
194
+ Every device of the graph takes part from the start, with the clock and the channel of
195
+ ``phyelds.experimental.wavefront``; their randomness comes from a torch generator.
196
+
197
+ Args:
198
+ program: The ``@aggregate`` function to run.
199
+ topology: Who hears whom.
200
+ clock: When each device runs; ``PeriodicClock(1.0)`` by default.
201
+ channel: How messages travel; an ideal ``Channel()`` by default.
202
+ window: How close two rounds may be and still run together, besides the delay of
203
+ the channel; ``None`` for the delay alone.
204
+ seed: The seed of the randomness of the clocks and of the channel.
205
+
206
+ Raises:
207
+ ValueError: If ``window`` is negative.
208
+ """
209
+
210
+ def __init__( # pylint: disable=too-many-arguments
211
+ self,
212
+ program: Callable[[], Any],
213
+ topology: GraphTopology,
214
+ *,
215
+ clock: Clock | None = None,
216
+ channel: Channel | None = None,
217
+ window: float | None = None,
218
+ seed: int = 0,
219
+ ):
220
+ if window is not None and window < 0:
221
+ raise ValueError(f"window must be non-negative, not {window}")
222
+ self.program = program
223
+ self.topology = topology
224
+ self.clock: Clock = PeriodicClock(1.0) if clock is None else clock
225
+ self.channel = Channel() if channel is None else channel
226
+ self.window = window
227
+ self.seed = seed
228
+ self._states = States(topology.num_devices, topology.device)
229
+ self._mailbox = Mailbox(topology, self.channel)
230
+ self._generator = torch.Generator(device=topology.device)
231
+ self._run = self._start()
232
+
233
+ def reset(self) -> None:
234
+ """Forget the state, the messages, the outputs and the clocks of every device."""
235
+ self._states.clear()
236
+ self._mailbox.clear()
237
+ self._run = self._start()
238
+
239
+ @property
240
+ def time(self) -> float:
241
+ """The earliest round of the last wavefront, or the ``until`` of the last run."""
242
+ return self._run.now
243
+
244
+ @property
245
+ def last_times(self) -> torch.Tensor:
246
+ """When each device last ran; NaN if it has not yet."""
247
+ return self._run.last_times
248
+
249
+ @property
250
+ def results(self) -> Any:
251
+ """The latest result of each device: rows ``(values, held)`` for each value."""
252
+ return self._run.results
253
+
254
+ @property
255
+ def outputs(self) -> dict[str, Rows]:
256
+ """What each device stored in its latest round, by name: ``(values, stored)``."""
257
+ return self._run.outputs
258
+
259
+ def next_time(self) -> float:
260
+ """The time of the next round of any device."""
261
+ next_times = self._run.next_times
262
+ return float(next_times.min()) if next_times.numel() else math.inf
263
+
264
+ def step(self, sensors: Mapping[str, Any], *, until: float | None = None) -> BatchWavefrontStep:
265
+ """
266
+ Run the next wavefront.
267
+
268
+ Args:
269
+ sensors: The sensors of the devices, by name: a tensor with a row per device, or
270
+ one value for all; ``"time"`` is the time of each round, unless given.
271
+ until: The time after which no round runs; none by default.
272
+
273
+ Returns:
274
+ What the wavefront ran; no devices if no round is due by ``until``.
275
+ """
276
+ delay = max(self.channel.delay, 0.0 if self.window is None else self.window)
277
+ run = self._run
278
+ devices = select_batch(
279
+ run.next_times, self.topology, lookahead=self.clock.period, delay=delay, until=until
280
+ )
281
+ if devices.numel() == 0:
282
+ return BatchWavefrontStep(run.now, devices, None)
283
+ times = run.next_times[devices]
284
+ run.now = max(run.now, float(times.min()))
285
+ batch = BatchEngine(
286
+ self.topology.batch(devices), self._states, _Reading(self._mailbox, times),
287
+ {"time": run.next_times, **sensors},
288
+ )
289
+ result = batch.run(self.program)
290
+ self._mailbox.transmit(devices, times, batch.finish(), self._uniform)
291
+ self._keep(devices, result, batch.node_context.stored)
292
+ run.last_times[devices] = times
293
+ run.next_times[devices] = times + self.clock.interval(self._draws(devices))
294
+ return BatchWavefrontStep(float(times.max()), devices, result)
295
+
296
+ def run_until(self, until: float, sensors: Mapping[str, Any]) -> Any:
297
+ """
298
+ Run wavefronts until no round is due by ``until``.
299
+
300
+ Returns:
301
+ The latest result of each device, as ``results``.
302
+ """
303
+ while self.next_time() <= until:
304
+ if self.step(sensors, until=until).devices.numel() == 0:
305
+ break
306
+ self._run.now = max(self._run.now, until)
307
+ return self.results
308
+
309
+ def _start(self) -> _Run:
310
+ """A run from time zero: the seed drawn again, each device waiting for its first round."""
311
+ count, device = self.topology.num_devices, self.topology.device
312
+ self._generator.manual_seed(self.seed)
313
+ device_draws = self._uniform(count)
314
+ first = self.clock.first(Draws(device_draws, *self._fresh(count)))
315
+ return _Run(
316
+ device_draws=device_draws,
317
+ next_times=as_rows(first, count, device).to(torch.float64),
318
+ last_times=torch.full((count,), math.nan, dtype=torch.float64, device=device),
319
+ )
320
+
321
+ def _uniform(self, count: int) -> torch.Tensor:
322
+ return torch.rand(count, generator=self._generator, dtype=torch.float64,
323
+ device=self.topology.device)
324
+
325
+ def _fresh(self, count: int) -> tuple[torch.Tensor, torch.Tensor]:
326
+ """New uniform and exponential draws, ``count`` of each."""
327
+ return self._uniform(count), -torch.log1p(-self._uniform(count))
328
+
329
+ def _draws(self, devices: torch.Tensor) -> Draws:
330
+ uniform, exponential = self._fresh(devices.numel())
331
+ return Draws(self._run.device_draws[devices], uniform, exponential)
332
+
333
+ def _keep(self, devices: torch.Tensor, result: Any, stored: Mapping[str, Rows]) -> None:
334
+ """Keep the results and the outputs of the devices of a wavefront."""
335
+ run, count = self._run, self.topology.num_devices
336
+ run.results = _kept(run.results, result, count, devices)
337
+ for _, held in run.outputs.values():
338
+ held[devices] = False
339
+ for name, (values, mask) in stored.items():
340
+ run.outputs[name] = _written(run.outputs.get(name), count, devices, values, mask)
341
+
342
+
343
+ def _kept(previous: Any, result: Any, count: int, devices: torch.Tensor) -> Any:
344
+ """The rows of every device, ``previous``, with the ``result`` of ``devices`` written."""
345
+ if isinstance(result, tuple):
346
+ olds = previous if isinstance(previous, tuple) else (None,) * len(result)
347
+ return tuple(_kept(old, item, count, devices) for old, item in zip(olds, result))
348
+ rows = devices.numel()
349
+ every = torch.ones(rows, dtype=torch.bool, device=devices.device)
350
+ old = previous if isinstance(previous, tuple) and len(previous) == 2 else None
351
+ return _written(old, count, devices, as_rows(result, rows, devices.device), every)
352
+
353
+
354
+ def _pick(chosen: torch.Tensor, first: Rows | None, second: Rows | None) -> Rows:
355
+ """The rows of ``first`` where ``chosen`` holds, of ``second`` elsewhere; none is empty."""
356
+ sample = first if first is not None else second
357
+ empty = (torch.zeros_like(sample[0]), torch.zeros_like(sample[1]))
358
+ first, second = first or empty, second or empty
359
+ mask = chosen.view(-1, *[1] * (sample[0].ndim - 1))
360
+ values = torch.where(mask, *_common(first[0], second[0]))
361
+ return values, torch.where(chosen, first[1], second[1])
362
+
363
+
364
+ def _common(first: torch.Tensor, second: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
365
+ dtype = torch.promote_types(first.dtype, second.dtype)
366
+ return first.to(dtype), second.to(dtype)
367
+
368
+
369
+ def _put(slot: Rows | None, count: int, index: torch.Tensor, values: torch.Tensor,
370
+ carried: torch.Tensor) -> Rows:
371
+ """``slot`` of ``count`` edges with ``values`` and ``carried`` at ``index``."""
372
+ if slot is None:
373
+ slot = (torch.zeros((count, *values.shape[1:]), dtype=values.dtype, device=values.device),
374
+ torch.zeros(count, dtype=torch.bool, device=values.device))
375
+ stored, held = slot
376
+ if stored.dtype != values.dtype:
377
+ dtype = torch.promote_types(stored.dtype, values.dtype)
378
+ stored, values = stored.to(dtype), values.to(dtype)
379
+ stored[index] = values.to(stored.dtype)
380
+ held[index] = carried
381
+ return stored, held