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,26 @@
1
+ """
2
+ PyTorch backend of phyelds: the devices of an aggregate system as tensors, on CPU or GPU.
3
+
4
+ ``BatchSynchronousRuntime`` runs an unmodified ``@aggregate`` program on every device at once,
5
+ one synchronous round at a time: ``BatchEngine`` implements the operations of the engine of
6
+ phyelds on tensors with a row per device, and ``BatchField`` the neighborhood field. The graph
7
+ comes from a radius search on a uniform grid (``radius_topology``) or from a mapping of
8
+ neighbors (``GraphTopology.from_neighbors``).
9
+ """
10
+ from phyelds.gpu.engine import BatchEngine
11
+ from phyelds.gpu.fields import BatchField
12
+ from phyelds.gpu.runtime import BatchSynchronousRuntime
13
+ from phyelds.gpu.topology import BatchEdges, GraphTopology, radius_topology
14
+ from phyelds.gpu.wavefront import BatchWavefrontRuntime, BatchWavefrontStep, select_batch
15
+
16
+ __all__ = [
17
+ "BatchEdges",
18
+ "BatchEngine",
19
+ "BatchField",
20
+ "BatchSynchronousRuntime",
21
+ "BatchWavefrontRuntime",
22
+ "BatchWavefrontStep",
23
+ "GraphTopology",
24
+ "radius_topology",
25
+ "select_batch",
26
+ ]
phyelds/gpu/engine.py ADDED
@@ -0,0 +1,405 @@
1
+ """
2
+ The engine of a batch of devices: the operations of ``phyelds.vm.Engine`` on tensors, with one
3
+ row per device, for the devices running the current code.
4
+
5
+ The calculus stays the one of the core: ``remember``, ``neighbors`` and ``exchange`` call the
6
+ operations of this engine, and ``@aggregate`` rewrites ``if`` statements and expressions into
7
+ its ``branch`` and ``choose``, which run each side for the devices taking it.
8
+ """
9
+ from collections.abc import Callable, Mapping
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Protocol
12
+
13
+ import torch
14
+
15
+ from phyelds import engine
16
+ from phyelds.gpu.fields import BatchField
17
+ from phyelds.gpu.tensors import as_rows, where_rows
18
+ from phyelds.gpu.topology import BatchEdges
19
+ from phyelds.vm import Engine, NodeContext
20
+ from phyelds.vm.internal import CompactPaths
21
+
22
+ _IDLE = object() # what a side of a branch that no device takes returns
23
+ _LOCAL = object() # the default of a neighbor field when none is given: the local value
24
+
25
+ # A value of each device of a batch, and which devices hold one.
26
+ Rows = tuple[torch.Tensor, torch.Tensor]
27
+
28
+
29
+ class States:
30
+ """
31
+ The state of every device: for each alignment key, a value of each device and whether
32
+ it holds one.
33
+
34
+ Args:
35
+ count: How many devices there are.
36
+ device: The torch device of the tensors.
37
+ """
38
+
39
+ def __init__(self, count: int, device: torch.device | str):
40
+ self.count = count
41
+ self.device = torch.device(device)
42
+ self._slots: dict[int, Rows] = {}
43
+
44
+ def read(self, key: int, devices: torch.Tensor) -> Rows | None:
45
+ """The values of ``devices`` at ``key`` and which of them hold one; none if no one does."""
46
+ slot = self._slots.get(key)
47
+ if slot is None:
48
+ return None
49
+ values, held = slot
50
+ return values[devices], held[devices]
51
+
52
+ def write(self, key: int, devices: torch.Tensor, values: torch.Tensor, mask: torch.Tensor):
53
+ """Store ``values`` at ``key`` for the ``devices`` of ``mask``."""
54
+ self._slots[key] = _written(self._slots.get(key), self.count, devices, values, mask)
55
+
56
+ def forget(self, key: int, devices: torch.Tensor, mask: torch.Tensor) -> None:
57
+ """Drop the values at ``key`` of the ``devices`` of ``mask``."""
58
+ slot = self._slots.get(key)
59
+ if slot is not None:
60
+ slot[1][devices[mask]] = False
61
+
62
+ def keep_read(self, devices: torch.Tensor, reads: Mapping[int, torch.Tensor]) -> None:
63
+ """Drop the values of ``devices`` they did not read, as a device drops its unused state."""
64
+ for key, (_, held) in self._slots.items():
65
+ read = reads.get(key)
66
+ held[devices if read is None else devices[~read]] = False
67
+
68
+ def clear(self) -> None:
69
+ """Forget the state of every device."""
70
+ self._slots.clear()
71
+
72
+
73
+ class Inbox(Protocol): # pylint: disable=too-few-public-methods
74
+ """Where a batch of devices reads what its neighbors sent."""
75
+
76
+ def read(self, key: int, edges: BatchEdges) -> Rows | None:
77
+ """What each edge into ``edges`` carries at ``key``, and which of them carry it."""
78
+
79
+
80
+ class SynchronousMessages:
81
+ """
82
+ The messages of synchronous rounds: in a round every device reads what its neighbors
83
+ sent in the previous one.
84
+
85
+ Args:
86
+ count: How many devices there are.
87
+ device: The torch device of the tensors.
88
+ """
89
+
90
+ def __init__(self, count: int, device: torch.device | str):
91
+ self.count = count
92
+ self.device = torch.device(device)
93
+ self._sent: dict[int, Rows] = {}
94
+
95
+ def read(self, key: int, edges: BatchEdges) -> Rows | None:
96
+ """What the sender of each edge sent at ``key`` in the previous round, if it did."""
97
+ slot = self._sent.get(key)
98
+ if slot is None:
99
+ return None
100
+ values, sent = slot
101
+ return values[edges.senders], sent[edges.senders]
102
+
103
+ def publish(self, devices: torch.Tensor, outbox: Mapping[int, Rows]) -> None:
104
+ """Replace the messages of ``devices`` with ``outbox``, for the next round."""
105
+ for key, (_, sent) in self._sent.items():
106
+ if key not in outbox:
107
+ sent[devices] = False
108
+ for key, (values, mask) in outbox.items():
109
+ slot = self._sent.get(key)
110
+ if slot is not None:
111
+ slot[1][devices] = False
112
+ self._sent[key] = _written(slot, self.count, devices, values, mask)
113
+
114
+ def clear(self) -> None:
115
+ """Forget every message."""
116
+ self._sent.clear()
117
+
118
+
119
+ class BatchContext(NodeContext):
120
+ """
121
+ The context of a batch of devices: their ids, their sensors and what they store.
122
+
123
+ Args:
124
+ devices: The ids of the devices of the batch (``int64 [M]``).
125
+ sensors: The sensors of every device, by name: a tensor with a row per device of the
126
+ whole system, or one value for all.
127
+ batch_engine: The engine running the batch: the devices that store are those running
128
+ the current code.
129
+ """
130
+
131
+ def __init__(
132
+ self, devices: torch.Tensor, sensors: Mapping[str, Any], batch_engine: "BatchEngine"
133
+ ):
134
+ super().__init__(devices, dict(sensors))
135
+ self._engine = batch_engine
136
+ self.stored: dict[str, Rows] = {}
137
+ """What the devices stored, by name: a value of each device and whether it stored one."""
138
+
139
+ def sense(self, sensor_name: str) -> Any:
140
+ value = self.sensors.get(sensor_name)
141
+ if isinstance(value, torch.Tensor) and value.ndim > 0:
142
+ return value[self.node_id]
143
+ return value
144
+
145
+ def store(self, output_name: str, value: Any) -> None:
146
+ running = self._engine.running
147
+ values = as_rows(value, running.numel(), running.device)
148
+ previous = self.stored.get(output_name)
149
+ if previous is None:
150
+ self.stored[output_name] = (values, running.clone())
151
+ else:
152
+ self.stored[output_name] = (
153
+ where_rows(running, values, previous[0]), previous[1] | running
154
+ )
155
+
156
+
157
+ @dataclass
158
+ class _Round:
159
+ """What the devices of a batch leave behind in a round: the values they read and sent."""
160
+
161
+ reads: dict[int, torch.Tensor] = field(default_factory=dict)
162
+ outbox: dict[int, Rows] = field(default_factory=dict)
163
+
164
+
165
+ class BatchEngine(Engine): # pylint: disable=too-many-instance-attributes
166
+ """
167
+ An engine that runs a batch of devices at once, each value holding a row per device.
168
+
169
+ Args:
170
+ edges: The devices of the batch and the edges into them.
171
+ states: The state of every device, kept from a round to the next.
172
+ inbox: What the neighbors sent.
173
+ sensors: The sensors of every device, by name (see ``BatchContext``).
174
+ """
175
+
176
+ vectorized = True
177
+
178
+ def __init__(
179
+ self, edges: BatchEdges, states: States, inbox: Inbox, sensors: Mapping[str, Any]
180
+ ):
181
+ super().__init__()
182
+ self.edges = edges
183
+ self.states = states
184
+ self.inbox = inbox
185
+ self.running = torch.ones(edges.num_devices, dtype=torch.bool, device=edges.devices.device)
186
+ """Which devices of the batch run the current code."""
187
+ self.node_context: BatchContext = BatchContext(edges.devices, sensors, self)
188
+ self._paths = CompactPaths()
189
+ self._stack: list[int] = []
190
+ self._counts = [0]
191
+ self._round = _Round()
192
+
193
+ def setup(self, node_context, messages, state=None):
194
+ raise NotImplementedError("a batch engine is built for each round of its devices")
195
+
196
+ def enter(self, name: str) -> None:
197
+ counter = self._counts[-1]
198
+ self._counts[-1] = counter + 1
199
+ parent = self._stack[-1] if self._stack else None
200
+ self._stack.append(self._paths.segment(parent, name, counter))
201
+ self._counts.append(0)
202
+
203
+ def exit(self) -> None:
204
+ if self._stack:
205
+ self._stack.pop()
206
+ self._counts.pop()
207
+
208
+ def current_path(self) -> list:
209
+ return self._stack.copy()
210
+
211
+ def read_state(self, stack: list | None = None) -> torch.Tensor:
212
+ key = self._key(stack)
213
+ self._mark_read(key)
214
+ slot = self.states.read(key, self.edges.devices)
215
+ nothing = self._rows(None)
216
+ return nothing if slot is None else where_rows(slot[1], slot[0], nothing)
217
+
218
+ def read_state_or(self, init: Any, stack: list | None = None) -> torch.Tensor:
219
+ key = self._key(stack)
220
+ self._mark_read(key)
221
+ value = self._rows(init)
222
+ slot = self.states.read(key, self.edges.devices)
223
+ if slot is not None:
224
+ value = where_rows(slot[1], slot[0], value)
225
+ self.states.write(key, self.edges.devices, value, self.running)
226
+ return value
227
+
228
+ def write_state(self, value: Any, stack: list | None = None) -> None:
229
+ self.states.write(self._key(stack), self.edges.devices, self._rows(value), self.running)
230
+
231
+ def forget(self, _self_path: list) -> None:
232
+ self.states.forget(self._key(_self_path), self.edges.devices, self.running)
233
+
234
+ def send(self, data: Any, stack: list | None = None) -> None:
235
+ if isinstance(data, BatchField):
236
+ raise TypeError("a batch engine sends a value of each device, not a field")
237
+ key = self._key(stack)
238
+ values = self._rows(data)
239
+ previous = self._round.outbox.get(key)
240
+ if previous is None:
241
+ self._round.outbox[key] = (values, self.running.clone())
242
+ else:
243
+ self._round.outbox[key] = (
244
+ where_rows(self.running, values, previous[0]), previous[1] | self.running
245
+ )
246
+
247
+ def neighbor_field(
248
+ self, local: Any, path: list | None = None, default: Any = _LOCAL, *,
249
+ addressed: bool = False,
250
+ ) -> BatchField:
251
+ del addressed # a batch engine sends no fields: no value is addressed to a device
252
+ local_rows = self._rows(local)
253
+ received = self.inbox.read(self._key(path), self.edges)
254
+ if received is None:
255
+ values = local_rows[self.edges.receivers]
256
+ present = torch.zeros_like(self.edges.receivers, dtype=torch.bool)
257
+ else:
258
+ values, present = received
259
+ return BatchField(
260
+ self.edges, local_rows, values, present,
261
+ default=local_rows if default is _LOCAL else default,
262
+ )
263
+
264
+ def branch(self, condition: Any, if_true: Callable[[], Any], if_false: Callable[[], Any]):
265
+ mask = self._mask(condition)
266
+ if mask is None:
267
+ return super().branch(condition, if_true, if_false)
268
+ return self._split(mask, if_true, if_false, aligned=True)
269
+
270
+ def choose(self, condition: Any, if_true: Callable[[], Any], if_false: Callable[[], Any]):
271
+ mask = self._mask(condition)
272
+ if mask is None:
273
+ return super().choose(condition, if_true, if_false)
274
+ return self._split(mask, if_true, if_false, aligned=False)
275
+
276
+ def run(self, program: Callable[[], Any]) -> Any:
277
+ """
278
+ Run ``program`` once for the devices of the batch, with this engine as the current one.
279
+
280
+ Returns:
281
+ What the program returned, with a row per device of the batch.
282
+ """
283
+ token = engine.set(self)
284
+ try:
285
+ return program()
286
+ finally:
287
+ engine.reset(token)
288
+
289
+ def finish(self) -> dict[int, Rows]:
290
+ """
291
+ End the round of the batch: drop the state its devices did not read.
292
+
293
+ Returns:
294
+ What the devices sent, by alignment key: a value of each and whether it sent one.
295
+ """
296
+ self.states.keep_read(self.edges.devices, self._round.reads)
297
+ return self._round.outbox
298
+
299
+ def _key(self, stack: list | None) -> int:
300
+ return self._paths.key(self._stack if stack is None else stack)
301
+
302
+ def _rows(self, value: Any) -> torch.Tensor:
303
+ return as_rows(value, self.edges.num_devices, self.edges.devices.device)
304
+
305
+ def _mark_read(self, key: int) -> None:
306
+ read = self._round.reads.get(key)
307
+ self._round.reads[key] = self.running.clone() if read is None else read | self.running
308
+
309
+ def _mask(self, condition: Any) -> torch.Tensor | None:
310
+ """The devices for which ``condition`` holds; none if it has a single truth value."""
311
+ if isinstance(condition, BatchField):
312
+ raise TypeError("a field has no truth value: reduce it first")
313
+ if not isinstance(condition, torch.Tensor) or condition.ndim == 0:
314
+ return None
315
+ return self._rows(condition).to(torch.bool)
316
+
317
+ def _split(self, mask: torch.Tensor, if_true, if_false, *, aligned: bool) -> Any:
318
+ """
319
+ Run each side for the running devices taking it, and merge what they return. Both
320
+ sides of a branch enter their alignment point with the same counter, as a device
321
+ enters only one of them: the paths are those of the devices on their own.
322
+ """
323
+ running, counter = self.running, self._counts[-1]
324
+ left, right = running & mask, running & ~mask
325
+ outcomes = []
326
+ for side_mask, side, name in ((left, if_true, "left"), (right, if_false, "right")):
327
+ if not bool(side_mask.any()):
328
+ outcomes.append(_IDLE)
329
+ continue
330
+ self.running = side_mask
331
+ if aligned:
332
+ self._counts[-1] = counter
333
+ self.enter(name)
334
+ try:
335
+ outcomes.append(side())
336
+ finally:
337
+ if aligned:
338
+ self.exit()
339
+ self.running = running
340
+ if outcomes[0] is _IDLE or outcomes[1] is _IDLE:
341
+ return outcomes[1] if outcomes[0] is _IDLE else outcomes[0]
342
+ return merge(left, outcomes[0], outcomes[1])
343
+
344
+
345
+ class Diverged:
346
+ """
347
+ A value that differs from device to device and has no rows: a function, or a field on
348
+ some devices only, that the branches of an ``if`` left in a variable. Using it fails.
349
+ """
350
+
351
+ def __getattr__(self, name: str) -> Any:
352
+ raise TypeError(_DIVERGED)
353
+
354
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
355
+ raise TypeError(_DIVERGED)
356
+
357
+ def __bool__(self) -> bool:
358
+ raise TypeError(_DIVERGED)
359
+
360
+
361
+ _DIVERGED = (
362
+ "the branches of an if left different functions or fields in this variable on different "
363
+ "devices: a batch engine cannot use it after the if"
364
+ )
365
+
366
+
367
+ def merge(mask: torch.Tensor, chosen: Any, other: Any) -> Any:
368
+ """
369
+ The values of ``chosen`` for the devices of ``mask``, those of ``other`` for the rest.
370
+
371
+ Tuples merge item by item, fields entry by entry, and numbers and tensors row by row,
372
+ with ``None`` as NaN; any other values become a ``Diverged``, which fails when used.
373
+ """
374
+ if chosen is other:
375
+ return chosen
376
+ if isinstance(chosen, tuple) and isinstance(other, tuple) and len(chosen) == len(other):
377
+ return tuple(merge(mask, *pair) for pair in zip(chosen, other))
378
+ if isinstance(chosen, BatchField) and isinstance(other, BatchField):
379
+ return BatchField.merged(mask, chosen, other)
380
+ if not (_has_rows(chosen) and _has_rows(other)):
381
+ return Diverged()
382
+ rows, device = mask.numel(), mask.device
383
+ return where_rows(mask, as_rows(chosen, rows, device), as_rows(other, rows, device))
384
+
385
+
386
+ def _has_rows(value: Any) -> bool:
387
+ """Whether ``value`` can be a row of each device: a number, ``None`` or a tensor."""
388
+ return value is None or isinstance(value, (bool, int, float, torch.Tensor))
389
+
390
+
391
+ def _written(
392
+ slot: Rows | None, count: int, devices: torch.Tensor, values: torch.Tensor, mask: torch.Tensor
393
+ ) -> Rows:
394
+ """``slot`` of ``count`` devices, with ``values`` written for the ``devices`` of ``mask``."""
395
+ if slot is None:
396
+ stored = torch.zeros((count, *values.shape[1:]), dtype=values.dtype, device=values.device)
397
+ held = torch.zeros(count, dtype=torch.bool, device=values.device)
398
+ else:
399
+ stored, held = slot
400
+ if stored.dtype != values.dtype:
401
+ common_type = torch.promote_types(stored.dtype, values.dtype)
402
+ stored, values = stored.to(common_type), values.to(common_type)
403
+ stored[devices[mask]] = values[mask].to(stored.dtype)
404
+ held[devices[mask]] = True
405
+ return stored, held