phyelds-gpu 10.2.0__tar.gz → 10.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phyelds-gpu
3
- Version: 10.2.0
3
+ Version: 10.3.0
4
4
  Summary: PyTorch backend for phyelds: aggregate programs on batches of devices, on CPU or GPU
5
5
  License: Apache-2.0
6
6
  Author: Gianluca Aguzzi
@@ -13,7 +13,7 @@ Classifier: Programming Language :: Python :: 3.12
13
13
  Classifier: Programming Language :: Python :: 3.13
14
14
  Classifier: Programming Language :: Python :: 3.14
15
15
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
- Requires-Dist: phyelds (>=10.2.0,<11.0.0)
16
+ Requires-Dist: phyelds (>=10.3.0,<11.0.0)
17
17
  Requires-Dist: torch (>=2.4.0)
18
18
  Project-URL: Homepage, https://github.com/phyelds/phyelds
19
19
  Project-URL: Repository, https://github.com/phyelds/phyelds
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "phyelds-gpu"
3
- version = "10.2.0"
3
+ version = "10.3.0"
4
4
  description = "PyTorch backend for phyelds: aggregate programs on batches of devices, on CPU or GPU"
5
5
  license = "Apache-2.0"
6
6
  authors = [
@@ -22,7 +22,7 @@ classifiers = [
22
22
 
23
23
  [tool.poetry.dependencies]
24
24
  python = ">=3.12,<3.15"
25
- phyelds = "^10.2.0"
25
+ phyelds = "^10.3.0"
26
26
  torch = ">=2.4.0"
27
27
 
28
28
  [tool.poetry.group.dev.dependencies]
@@ -8,12 +8,13 @@ its ``branch`` and ``choose``, which run each side for the devices taking it.
8
8
  """
9
9
  from collections.abc import Callable, Mapping
10
10
  from dataclasses import dataclass, field
11
- from typing import Any, Protocol
11
+ from typing import Any
12
12
 
13
13
  import torch
14
14
 
15
15
  from phyelds import engine
16
- from phyelds.gpu.fields import BatchField
16
+ from phyelds.gpu.fields import BatchField, as_field, default_rows
17
+ from phyelds.gpu.memory import Inbox, Outbox, Rows, States
17
18
  from phyelds.gpu.tensors import as_rows, where_rows
18
19
  from phyelds.gpu.topology import BatchEdges
19
20
  from phyelds.vm import Engine, NodeContext
@@ -22,99 +23,6 @@ from phyelds.vm.internal import CompactPaths
22
23
  _IDLE = object() # what a side of a branch that no device takes returns
23
24
  _LOCAL = object() # the default of a neighbor field when none is given: the local value
24
25
 
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
26
 
119
27
  class BatchContext(NodeContext):
120
28
  """
@@ -159,7 +67,7 @@ class _Round:
159
67
  """What the devices of a batch leave behind in a round: the values they read and sent."""
160
68
 
161
69
  reads: dict[int, torch.Tensor] = field(default_factory=dict)
162
- outbox: dict[int, Rows] = field(default_factory=dict)
70
+ outbox: Outbox = field(default_factory=Outbox)
163
71
 
164
72
 
165
73
  class BatchEngine(Engine): # pylint: disable=too-many-instance-attributes
@@ -208,47 +116,60 @@ class BatchEngine(Engine): # pylint: disable=too-many-instance-attributes
208
116
  def current_path(self) -> list:
209
117
  return self._stack.copy()
210
118
 
211
- def read_state(self, stack: list | None = None) -> torch.Tensor:
119
+ def read_state(self, stack: list | None = None) -> Any:
212
120
  key = self._key(stack)
213
121
  self._mark_read(key)
214
- slot = self.states.read(key, self.edges.devices)
122
+ slot = self.states.read(key, self.edges)
215
123
  nothing = self._rows(None)
216
- return nothing if slot is None else where_rows(slot[1], slot[0], nothing)
124
+ return nothing if slot is None else merge(slot[1], slot[0], nothing)
217
125
 
218
- def read_state_or(self, init: Any, stack: list | None = None) -> torch.Tensor:
126
+ def read_state_or(self, init: Any, stack: list | None = None) -> Any:
219
127
  key = self._key(stack)
220
128
  self._mark_read(key)
221
- value = self._rows(init)
222
- slot = self.states.read(key, self.edges.devices)
129
+ value = self._value(init)
130
+ slot = self.states.read(key, self.edges)
223
131
  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)
132
+ value = merge(slot[1], slot[0], value)
133
+ self.states.write(key, self.edges, value, self.running)
226
134
  return value
227
135
 
228
136
  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)
137
+ self.states.write(self._key(stack), self.edges, self._value(value), self.running)
230
138
 
231
139
  def forget(self, _self_path: list) -> None:
232
140
  self.states.forget(self._key(_self_path), self.edges.devices, self.running)
233
141
 
142
+ def own_value(self, value: Any) -> Any:
143
+ if not isinstance(value, BatchField):
144
+ return value
145
+ return where_rows(value.local_present, value.local_values, default_rows(value))
146
+
147
+ def default_value(self, value: Any) -> Any:
148
+ return value.default if isinstance(value, BatchField) else value
149
+
234
150
  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
151
  key = self._key(stack)
238
- values = self._rows(data)
239
- previous = self._round.outbox.get(key)
152
+ outbox = self._round.outbox
153
+ if isinstance(data, BatchField):
154
+ shared, addressed = default_rows(data), (data.values, data.present)
155
+ else:
156
+ shared, addressed = self._rows(data), None
157
+ previous = outbox.shared.get(key)
240
158
  if previous is None:
241
- self._round.outbox[key] = (values, self.running.clone())
159
+ outbox.shared[key] = (shared, self.running.clone())
242
160
  else:
243
- self._round.outbox[key] = (
244
- where_rows(self.running, values, previous[0]), previous[1] | self.running
161
+ outbox.shared[key] = (
162
+ where_rows(self.running, shared, previous[0]), previous[1] | self.running
245
163
  )
164
+ if addressed is not None or key in outbox.addressed:
165
+ outbox.addressed[key] = self._addressed(outbox.addressed.get(key), addressed)
246
166
 
247
167
  def neighbor_field(
248
168
  self, local: Any, path: list | None = None, default: Any = _LOCAL, *,
249
169
  addressed: bool = False,
250
170
  ) -> BatchField:
251
- del addressed # a batch engine sends no fields: no value is addressed to a device
171
+ # The messages already hold, on each edge, the value its sender addressed to it.
172
+ del addressed
252
173
  local_rows = self._rows(local)
253
174
  received = self.inbox.read(self._key(path), self.edges)
254
175
  if received is None:
@@ -286,12 +207,12 @@ class BatchEngine(Engine): # pylint: disable=too-many-instance-attributes
286
207
  finally:
287
208
  engine.reset(token)
288
209
 
289
- def finish(self) -> dict[int, Rows]:
210
+ def finish(self) -> Outbox:
290
211
  """
291
212
  End the round of the batch: drop the state its devices did not read.
292
213
 
293
214
  Returns:
294
- What the devices sent, by alignment key: a value of each and whether it sent one.
215
+ What the devices sent, by alignment key.
295
216
  """
296
217
  self.states.keep_read(self.edges.devices, self._round.reads)
297
218
  return self._round.outbox
@@ -302,6 +223,25 @@ class BatchEngine(Engine): # pylint: disable=too-many-instance-attributes
302
223
  def _rows(self, value: Any) -> torch.Tensor:
303
224
  return as_rows(value, self.edges.num_devices, self.edges.devices.device)
304
225
 
226
+ def _value(self, value: Any) -> Any:
227
+ """``value`` as the engine keeps it: a field as it is, anything else as rows."""
228
+ return value if isinstance(value, BatchField) else self._rows(value)
229
+
230
+ def _addressed(self, previous: Rows | None, addressed: Rows | None) -> Rows:
231
+ """
232
+ The values addressed on the edges into the running devices replaced with
233
+ ``addressed``, or dropped if it is none; those into the other devices kept.
234
+ """
235
+ on_edges = self.running[self.edges.receivers]
236
+ if addressed is None:
237
+ return previous[0], previous[1] & ~on_edges
238
+ values, present = addressed
239
+ if previous is None:
240
+ return values, present & on_edges
241
+ return (
242
+ where_rows(on_edges, values, previous[0]), torch.where(on_edges, present, previous[1])
243
+ )
244
+
305
245
  def _mark_read(self, key: int) -> None:
306
246
  read = self._round.reads.get(key)
307
247
  self._round.reads[key] = self.running.clone() if read is None else read | self.running
@@ -369,16 +309,19 @@ def merge(mask: torch.Tensor, chosen: Any, other: Any) -> Any:
369
309
  The values of ``chosen`` for the devices of ``mask``, those of ``other`` for the rest.
370
310
 
371
311
  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.
312
+ with ``None`` as NaN; a field and a number merge as fields, the number a field with no
313
+ entries whose default is the number. Any other values become a ``Diverged``, which fails
314
+ when used.
373
315
  """
374
316
  if chosen is other:
375
317
  return chosen
376
318
  if isinstance(chosen, tuple) and isinstance(other, tuple) and len(chosen) == len(other):
377
319
  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)):
320
+ if not all(isinstance(value, BatchField) or _has_rows(value) for value in (chosen, other)):
381
321
  return Diverged()
322
+ if isinstance(chosen, BatchField) or isinstance(other, BatchField):
323
+ edges = (chosen if isinstance(chosen, BatchField) else other).edges
324
+ return BatchField.merged(mask, as_field(edges, chosen), as_field(edges, other))
382
325
  rows, device = mask.numel(), mask.device
383
326
  return where_rows(mask, as_rows(chosen, rows, device), as_rows(other, rows, device))
384
327
 
@@ -386,20 +329,3 @@ def merge(mask: torch.Tensor, chosen: Any, other: Any) -> Any:
386
329
  def _has_rows(value: Any) -> bool:
387
330
  """Whether ``value`` can be a row of each device: a number, ``None`` or a tensor."""
388
331
  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
@@ -418,6 +418,20 @@ class BatchField: # pylint: disable=too-many-public-methods # the API of a fie
418
418
  return torch.where(ids != unset, ids.to(torch.float64), math.nan)
419
419
 
420
420
 
421
+ def as_field(edges: BatchEdges, value: Any) -> BatchField:
422
+ """``value`` as a field: a value of each device is a field with no entries, its default."""
423
+ if isinstance(value, BatchField):
424
+ return value
425
+ rows = as_rows(value, edges.num_devices, edges.devices.device)
426
+ absent = torch.zeros_like(edges.receivers, dtype=torch.bool)
427
+ return BatchField(edges, rows, rows[edges.receivers], absent, default=rows)
428
+
429
+
430
+ def default_rows(value: BatchField) -> torch.Tensor:
431
+ """The default of ``value`` for each device, NaN if it has none."""
432
+ return as_rows(value.default, value.edges.num_devices, value.edges.devices.device)
433
+
434
+
421
435
  def _identity(reduction: str, dtype: torch.dtype) -> float | int:
422
436
  """The value that ``reduction`` leaves unchanged: what a device without entries gets."""
423
437
  if reduction == "sum":
@@ -0,0 +1,251 @@
1
+ """
2
+ What the devices of a batch keep from a round to the next, as tensors with a row per device or
3
+ per edge: their state, and the messages of synchronous rounds.
4
+ """
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Protocol
8
+
9
+ import torch
10
+
11
+ from phyelds.gpu.fields import BatchField, as_field, default_rows
12
+ from phyelds.gpu.tensors import where_rows
13
+ from phyelds.gpu.topology import BatchEdges, GraphTopology
14
+
15
+ # A value of each device of a batch, and which devices hold one.
16
+ Rows = tuple[torch.Tensor, torch.Tensor]
17
+
18
+
19
+ @dataclass
20
+ class _FieldSlot: # pylint: disable=too-many-instance-attributes
21
+ """
22
+ A state kept as a field on some devices: of each device its value, whether it holds it,
23
+ and its default; of each edge into it, its value and whether it holds it. A value the
24
+ same for every neighbor is a field with no entries, whose default is that value.
25
+ """
26
+
27
+ local: torch.Tensor
28
+ local_present: torch.Tensor
29
+ default: torch.Tensor
30
+ held: torch.Tensor
31
+ values: torch.Tensor
32
+ present: torch.Tensor
33
+
34
+ @classmethod
35
+ def of_rows(cls, slot: Rows, num_edges: int) -> "_FieldSlot":
36
+ """The values of ``slot``, each the same for every neighbor, as fields."""
37
+ values, held = slot
38
+ return cls(values, torch.ones_like(held), values.clone(), held,
39
+ *_empty_rows(num_edges, values))
40
+
41
+ def read(self, edges: BatchEdges) -> tuple[BatchField, torch.Tensor]:
42
+ """The field of the devices of ``edges``, and which of them hold one."""
43
+ devices, index = edges.devices, edges.edges
44
+ stored = BatchField(
45
+ edges, self.local[devices], self.values[index], self.present[index],
46
+ local_present=self.local_present[devices], default=self.default[devices],
47
+ )
48
+ return stored, self.held[devices]
49
+
50
+ def write(self, edges: BatchEdges, value: BatchField, mask: torch.Tensor) -> None:
51
+ """Store ``value`` for the devices of ``edges`` in ``mask``, and for the edges into them."""
52
+ devices, on_edges = edges.devices[mask], mask[edges.receivers]
53
+ index = edges.edges[on_edges]
54
+ self.local = _assigned(self.local, devices, value.local_values[mask])
55
+ self.local_present[devices] = value.local_present[mask]
56
+ self.default = _assigned(self.default, devices, default_rows(value)[mask])
57
+ self.held[devices] = True
58
+ self.values = _assigned(self.values, index, value.values[on_edges])
59
+ self.present[index] = value.present[on_edges]
60
+
61
+
62
+ class States:
63
+ """
64
+ The state of every device: for each alignment key, a value of each device and whether
65
+ it holds one; a field, where some device keeps one.
66
+
67
+ Args:
68
+ topology: The devices and the edges between them.
69
+ """
70
+
71
+ def __init__(self, topology: GraphTopology):
72
+ self.count = topology.num_devices
73
+ self.num_edges = int(topology.senders.numel())
74
+ self.device = topology.device
75
+ self._slots: dict[int, Rows | _FieldSlot] = {}
76
+
77
+ def read(self, key: int, edges: BatchEdges) -> tuple[Any, torch.Tensor] | None:
78
+ """
79
+ The values of the devices of ``edges`` at ``key``, rows or a field, and which of them
80
+ hold one; none if no one does.
81
+ """
82
+ slot = self._slots.get(key)
83
+ if slot is None:
84
+ return None
85
+ if isinstance(slot, _FieldSlot):
86
+ return slot.read(edges)
87
+ values, held = slot
88
+ return values[edges.devices], held[edges.devices]
89
+
90
+ def write(self, key: int, edges: BatchEdges, value: Any, mask: torch.Tensor) -> None:
91
+ """Store ``value``, rows or a field, at ``key`` for the devices of ``edges`` in ``mask``."""
92
+ slot = self._slots.get(key)
93
+ if isinstance(value, BatchField) and not isinstance(slot, _FieldSlot):
94
+ rows = _empty_rows(self.count, value.local_values) if slot is None else slot
95
+ slot = _FieldSlot.of_rows(rows, self.num_edges)
96
+ if isinstance(slot, _FieldSlot):
97
+ slot.write(edges, as_field(edges, value), mask)
98
+ self._slots[key] = slot
99
+ else:
100
+ self._slots[key] = write_rows(slot, self.count, edges.devices, value, mask)
101
+
102
+ def forget(self, key: int, devices: torch.Tensor, mask: torch.Tensor) -> None:
103
+ """Drop the values at ``key`` of the ``devices`` of ``mask``."""
104
+ slot = self._slots.get(key)
105
+ if slot is not None:
106
+ _held(slot)[devices[mask]] = False
107
+
108
+ def keep_read(self, devices: torch.Tensor, reads: Mapping[int, torch.Tensor]) -> None:
109
+ """Drop the values of ``devices`` they did not read, as a device drops its unused state."""
110
+ for key, slot in self._slots.items():
111
+ read = reads.get(key)
112
+ _held(slot)[devices if read is None else devices[~read]] = False
113
+
114
+ def clear(self) -> None:
115
+ """Forget the state of every device."""
116
+ self._slots.clear()
117
+
118
+
119
+ class Inbox(Protocol): # pylint: disable=too-few-public-methods
120
+ """Where a batch of devices reads what its neighbors sent."""
121
+
122
+ def read(self, key: int, edges: BatchEdges) -> Rows | None:
123
+ """What each edge into ``edges`` carries at ``key``, and which of them carry it."""
124
+
125
+
126
+ @dataclass
127
+ class Outbox:
128
+ """What the devices of a batch sent in a round, by alignment key."""
129
+
130
+ shared: dict[int, Rows] = field(default_factory=dict)
131
+ """A value of each device for all its neighbors, and whether it sent one: for a field, its
132
+ default."""
133
+ addressed: dict[int, Rows] = field(default_factory=dict)
134
+ """For a field, its value on each edge into the batch, which the receiver addresses back to
135
+ the sender, and whether it holds one: the sender then reads it instead of the default."""
136
+
137
+
138
+ class SynchronousMessages:
139
+ """
140
+ The messages of synchronous rounds: in a round every device reads what its neighbors
141
+ sent in the previous one.
142
+
143
+ Args:
144
+ topology: The devices and the edges between them.
145
+ """
146
+
147
+ def __init__(self, topology: GraphTopology):
148
+ self.count = topology.num_devices
149
+ self.num_edges = int(topology.senders.numel())
150
+ self.device = topology.device
151
+ self._back = topology.reverse_edges()
152
+ self._sent: dict[int, Rows] = {}
153
+ self._addressed: dict[int, Rows] = {}
154
+ """The value addressed along each edge of the topology, and whether there is one."""
155
+
156
+ def read(self, key: int, edges: BatchEdges) -> Rows | None:
157
+ """What the sender of each edge sent at ``key`` in the previous round, if it did."""
158
+ slot = self._sent.get(key)
159
+ if slot is None:
160
+ return None
161
+ values, sent = slot[0][edges.senders], slot[1][edges.senders]
162
+ addressed = self._addressed.get(key)
163
+ if addressed is not None:
164
+ values = where_rows(addressed[1][edges.edges], addressed[0][edges.edges], values)
165
+ return values, sent
166
+
167
+ def publish(self, edges: BatchEdges, outbox: Outbox) -> None:
168
+ """Replace the messages of the devices of ``edges`` with ``outbox``, for the next round."""
169
+ devices = edges.devices
170
+ for key, (_, sent) in self._sent.items():
171
+ if key not in outbox.shared:
172
+ sent[devices] = False
173
+ for key, (values, mask) in outbox.shared.items():
174
+ slot = self._sent.get(key)
175
+ if slot is not None:
176
+ slot[1][devices] = False
177
+ self._sent[key] = write_rows(slot, self.count, devices, values, mask)
178
+ index, has_back = edges_back(self._back, edges)
179
+ for key in set(self._addressed) | set(outbox.addressed):
180
+ addressed = outbox.addressed.get(key)
181
+ if addressed is None:
182
+ self._addressed[key][1][index] = False
183
+ continue
184
+ values, present = addressed
185
+ self._addressed[key] = put_rows(
186
+ self._addressed.get(key), self.num_edges, index,
187
+ values[has_back], present[has_back],
188
+ )
189
+
190
+ def clear(self) -> None:
191
+ """Forget every message."""
192
+ self._sent.clear()
193
+ self._addressed.clear()
194
+
195
+
196
+ def edges_back(back: torch.Tensor, edges: BatchEdges) -> tuple[torch.Tensor, torch.Tensor]:
197
+ """
198
+ Where the values a batch addresses on the edges into it travel: on the edge back of each,
199
+ from the receiver to the sender.
200
+
201
+ Args:
202
+ back: The edge back of each edge of the topology, or ``-1`` (see
203
+ ``GraphTopology.reverse_edges``).
204
+ edges: The edges into the batch.
205
+
206
+ Returns:
207
+ The edges back, among those of the topology, and which edges into the batch have one.
208
+ """
209
+ targets = back[edges.edges]
210
+ has_back = targets >= 0
211
+ return targets[has_back], has_back
212
+
213
+
214
+ def _held(slot: Rows | _FieldSlot) -> torch.Tensor:
215
+ """Which devices hold a value in ``slot``."""
216
+ return slot.held if isinstance(slot, _FieldSlot) else slot[1]
217
+
218
+
219
+ def _assigned(stored: torch.Tensor, index: torch.Tensor, values: torch.Tensor) -> torch.Tensor:
220
+ """``stored`` with ``values`` at ``index``, in a type that holds both."""
221
+ if stored.dtype != values.dtype:
222
+ stored = stored.to(torch.promote_types(stored.dtype, values.dtype))
223
+ stored[index] = values.to(stored.dtype)
224
+ return stored
225
+
226
+
227
+ def put_rows(
228
+ slot: Rows | None, count: int, index: torch.Tensor, values: torch.Tensor,
229
+ carried: torch.Tensor,
230
+ ) -> Rows:
231
+ """``slot`` of ``count`` rows with ``values`` and ``carried`` at ``index``."""
232
+ stored, held = _empty_rows(count, values) if slot is None else slot
233
+ stored = _assigned(stored, index, values)
234
+ held[index] = carried
235
+ return stored, held
236
+
237
+
238
+ def write_rows(
239
+ slot: Rows | None, count: int, devices: torch.Tensor, values: torch.Tensor, mask: torch.Tensor
240
+ ) -> Rows:
241
+ """``slot`` of ``count`` devices, with ``values`` written for the ``devices`` of ``mask``."""
242
+ stored, held = _empty_rows(count, values) if slot is None else slot
243
+ stored = _assigned(stored, devices[mask], values[mask])
244
+ held[devices[mask]] = True
245
+ return stored, held
246
+
247
+
248
+ def _empty_rows(count: int, values: torch.Tensor) -> Rows:
249
+ """``count`` rows shaped as those of ``values``, none of them held."""
250
+ stored = torch.zeros((count, *values.shape[1:]), dtype=values.dtype, device=values.device)
251
+ return stored, torch.zeros(count, dtype=torch.bool, device=values.device)
@@ -6,7 +6,8 @@ does, with one row per device instead of one round per device.
6
6
  from collections.abc import Callable, Mapping
7
7
  from typing import Any
8
8
 
9
- from phyelds.gpu.engine import BatchEngine, Rows, States, SynchronousMessages, _written
9
+ from phyelds.gpu.engine import BatchEngine
10
+ from phyelds.gpu.memory import Rows, States, SynchronousMessages, write_rows
10
11
  from phyelds.gpu.topology import GraphTopology
11
12
 
12
13
 
@@ -27,8 +28,8 @@ class BatchSynchronousRuntime:
27
28
  self.outputs: dict[str, Rows] = {}
28
29
  """What the devices stored, by name: a value of each device and whether it stored one."""
29
30
  self._edges = topology.batch()
30
- self._states = States(topology.num_devices, topology.device)
31
- self._messages = SynchronousMessages(topology.num_devices, topology.device)
31
+ self._states = States(topology)
32
+ self._messages = SynchronousMessages(topology)
32
33
 
33
34
  def run_round(self, sensors: Mapping[str, Any]) -> Any:
34
35
  """
@@ -45,10 +46,10 @@ class BatchSynchronousRuntime:
45
46
  batch = BatchEngine(self._edges, self._states, self._messages, sensors)
46
47
  result = batch.run(self.program)
47
48
  devices = self._edges.devices
48
- self._messages.publish(devices, batch.finish())
49
+ self._messages.publish(self._edges, batch.finish())
49
50
  count = self.topology.num_devices
50
51
  for name, (values, stored) in batch.node_context.stored.items():
51
- self.outputs[name] = _written(None, count, devices, values, stored)
52
+ self.outputs[name] = write_rows(None, count, devices, values, stored)
52
53
  return result
53
54
 
54
55
  def reset(self) -> None:
@@ -138,6 +138,22 @@ class GraphTopology:
138
138
  edges = starts[receivers] + rank - firsts[receivers]
139
139
  return BatchEdges(devices, edges, self.senders[edges], receivers)
140
140
 
141
+ def reverse_edges(self) -> torch.Tensor:
142
+ """
143
+ The edge back of each edge: the one from its receiver to its sender.
144
+
145
+ Returns:
146
+ The index of the edge back of each edge (``int64 [E]``), or ``-1`` if the sender
147
+ does not hear the receiver.
148
+ """
149
+ count = self.senders.numel()
150
+ # Grouped by receiver and sorted by sender: the keys of the edges are sorted.
151
+ keys = self.receivers * self.num_devices + self.senders
152
+ wanted = self.senders * self.num_devices + self.receivers
153
+ found = torch.searchsorted(keys, wanted)
154
+ back = torch.clamp(found, max=max(count - 1, 0))
155
+ return torch.where((found < count) & (keys[back] == wanted), back, -1)
156
+
141
157
  def to_neighbors(self) -> dict[int, list[int]]:
142
158
  """
143
159
  The neighbors of each device, as plain Python values.
@@ -14,8 +14,9 @@ from typing import Any
14
14
  import torch
15
15
 
16
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
17
+ from phyelds.gpu.engine import BatchEngine
18
+ from phyelds.gpu.memory import Outbox, Rows, States, edges_back, put_rows, write_rows
19
+ from phyelds.gpu.tensors import as_rows, where_rows
19
20
  from phyelds.gpu.topology import BatchEdges, GraphTopology
20
21
 
21
22
 
@@ -73,6 +74,7 @@ class Mailbox:
73
74
  count = int(topology.senders.numel())
74
75
  self.topology = topology
75
76
  self.channel = channel
77
+ self._back = topology.reverse_edges()
76
78
  self._arrived_at = torch.full((count,), -math.inf, dtype=torch.float64,
77
79
  device=topology.device)
78
80
  self._pending_at = torch.full((count,), math.inf, dtype=torch.float64,
@@ -97,41 +99,28 @@ class Mailbox:
97
99
  return values, carried & self.channel.heard(now - arrival)
98
100
 
99
101
  def transmit(
100
- self, devices: torch.Tensor, times: torch.Tensor, outbox: Mapping[int, Rows],
102
+ self, edges: BatchEdges, times: torch.Tensor, outbox: Outbox,
101
103
  uniform: Callable[[int], torch.Tensor],
102
104
  ) -> None:
103
105
  """
104
- Send the outbox of ``devices``, which ran at ``times``, on every edge out of them.
106
+ Send the outbox of a batch of devices, which ran at ``times``, on every edge out of
107
+ them.
105
108
 
106
109
  Args:
107
- devices: The ids of the senders (``int64 [M]``).
110
+ edges: The devices of the batch, the senders, and the edges into them.
108
111
  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.
112
+ outbox: What they sent, by alignment key.
110
113
  uniform: Uniform draws in ``[0, 1)``, ``uniform(n)`` of them, for the channel.
111
114
  """
112
115
  senders = self.topology.senders
113
116
  row = torch.full((self.topology.num_devices,), -1, dtype=torch.int64,
114
117
  device=senders.device)
115
- row[devices] = torch.arange(devices.numel(), device=senders.device)
118
+ row[edges.devices] = torch.arange(edges.num_devices, device=senders.device)
116
119
  sending = torch.nonzero(row[senders] >= 0).squeeze(-1)
117
120
  sending = sending[~self.channel.lost(uniform(sending.numel()))]
118
121
  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])
122
+ self._land(sending, self.channel.arrival(times[rows], uniform(sending.numel())))
123
+ self._queue(sending, rows, outbox.shared, self._addressed(edges, outbox.addressed))
135
124
 
136
125
  def clear(self) -> None:
137
126
  """Forget every message."""
@@ -144,6 +133,48 @@ class Mailbox:
144
133
  def _edges(self) -> int:
145
134
  return int(self.topology.senders.numel())
146
135
 
136
+ def _land(self, sending: torch.Tensor, arrival: torch.Tensor) -> None:
137
+ """
138
+ Make way on the ``sending`` edges for messages arriving at ``arrival``: the message in
139
+ flight has arrived by then, and is the last arrived; one that would arrive later is
140
+ overtaken, and lost.
141
+ """
142
+ arrived = sending[self._pending_at[sending] <= arrival]
143
+ for key in set(self._arrived) | set(self._pending):
144
+ pending = self._slot(self._pending, key, arrived)
145
+ self._arrived[key] = put_rows(self._arrived.get(key), self._edges, arrived, *pending)
146
+ self._arrived_at[arrived] = self._pending_at[arrived]
147
+ self._pending_at[sending] = arrival
148
+
149
+ def _queue(
150
+ self, sending: torch.Tensor, rows: torch.Tensor, shared: Mapping[int, Rows],
151
+ addressed: Mapping[int, Rows],
152
+ ) -> None:
153
+ """
154
+ Put in flight on the ``sending`` edges what their senders, at ``rows`` of the batch,
155
+ sent: the value addressed along an edge, if any, or the one for every neighbor.
156
+ """
157
+ for key in set(self._pending) | set(shared):
158
+ values, sent = shared.get(key, (None, None))
159
+ if values is None:
160
+ self._pending[key][1][sending] = False
161
+ continue
162
+ carried = values[rows]
163
+ if key in addressed:
164
+ along, held = addressed[key]
165
+ carried = where_rows(held[sending], along[sending], carried)
166
+ self._pending[key] = put_rows(
167
+ self._pending.get(key), self._edges, sending, carried, sent[rows]
168
+ )
169
+
170
+ def _addressed(self, edges: BatchEdges, addressed: Mapping[int, Rows]) -> dict[int, Rows]:
171
+ """What a batch addressed, by key, on each edge of the topology, and where it did."""
172
+ index, has_back = edges_back(self._back, edges)
173
+ return {
174
+ key: put_rows(None, self._edges, index, values[has_back], present[has_back])
175
+ for key, (values, present) in addressed.items()
176
+ }
177
+
147
178
  @staticmethod
148
179
  def _slot(slots: Mapping[int, Rows], key: int, index: torch.Tensor) -> Rows | None:
149
180
  slot = slots.get(key)
@@ -225,7 +256,7 @@ class BatchWavefrontRuntime: # pylint: disable=too-many-instance-attributes
225
256
  self.channel = Channel() if channel is None else channel
226
257
  self.window = window
227
258
  self.seed = seed
228
- self._states = States(topology.num_devices, topology.device)
259
+ self._states = States(topology)
229
260
  self._mailbox = Mailbox(topology, self.channel)
230
261
  self._generator = torch.Generator(device=topology.device)
231
262
  self._run = self._start()
@@ -282,12 +313,13 @@ class BatchWavefrontRuntime: # pylint: disable=too-many-instance-attributes
282
313
  return BatchWavefrontStep(run.now, devices, None)
283
314
  times = run.next_times[devices]
284
315
  run.now = max(run.now, float(times.min()))
316
+ edges = self.topology.batch(devices)
285
317
  batch = BatchEngine(
286
- self.topology.batch(devices), self._states, _Reading(self._mailbox, times),
318
+ edges, self._states, _Reading(self._mailbox, times),
287
319
  {"time": run.next_times, **sensors},
288
320
  )
289
321
  result = batch.run(self.program)
290
- self._mailbox.transmit(devices, times, batch.finish(), self._uniform)
322
+ self._mailbox.transmit(edges, times, batch.finish(), self._uniform)
291
323
  self._keep(devices, result, batch.node_context.stored)
292
324
  run.last_times[devices] = times
293
325
  run.next_times[devices] = times + self.clock.interval(self._draws(devices))
@@ -337,7 +369,7 @@ class BatchWavefrontRuntime: # pylint: disable=too-many-instance-attributes
337
369
  for _, held in run.outputs.values():
338
370
  held[devices] = False
339
371
  for name, (values, mask) in stored.items():
340
- run.outputs[name] = _written(run.outputs.get(name), count, devices, values, mask)
372
+ run.outputs[name] = write_rows(run.outputs.get(name), count, devices, values, mask)
341
373
 
342
374
 
343
375
  def _kept(previous: Any, result: Any, count: int, devices: torch.Tensor) -> Any:
@@ -348,7 +380,7 @@ def _kept(previous: Any, result: Any, count: int, devices: torch.Tensor) -> Any:
348
380
  rows = devices.numel()
349
381
  every = torch.ones(rows, dtype=torch.bool, device=devices.device)
350
382
  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)
383
+ return write_rows(old, count, devices, as_rows(result, rows, devices.device), every)
352
384
 
353
385
 
354
386
  def _pick(chosen: torch.Tensor, first: Rows | None, second: Rows | None) -> Rows:
@@ -364,18 +396,3 @@ def _pick(chosen: torch.Tensor, first: Rows | None, second: Rows | None) -> Rows
364
396
  def _common(first: torch.Tensor, second: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
365
397
  dtype = torch.promote_types(first.dtype, second.dtype)
366
398
  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
File without changes