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.
phyelds/gpu/fields.py ADDED
@@ -0,0 +1,430 @@
1
+ """
2
+ The neighborhood field of a batch of devices: a value of each device's own, and one on each
3
+ edge into it, the value its sender sent.
4
+ """
5
+ import math
6
+ import operator
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ import torch
11
+
12
+ from phyelds.gpu.tensors import as_rows, as_tensor, common, where_rows
13
+ from phyelds.gpu.topology import BatchEdges
14
+
15
+ # The reductions a fold can run on a batch, told by the accumulator itself.
16
+ _FOLDS: dict[Any, str] = {
17
+ operator.add: "sum",
18
+ operator.mul: "prod",
19
+ max: "amax",
20
+ min: "amin",
21
+ operator.or_: "any",
22
+ operator.and_: "all",
23
+ }
24
+ _COMBINE: dict[str, Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = {
25
+ "sum": torch.add,
26
+ "prod": torch.mul,
27
+ "amax": torch.maximum,
28
+ "amin": torch.minimum,
29
+ }
30
+
31
+
32
+ class BatchField: # pylint: disable=too-many-public-methods # the API of a field
33
+ """
34
+ The ``NeighborhoodField`` of every device of a batch at once.
35
+
36
+ It runs the operations of ``NeighborhoodField`` for all the devices together. A callback,
37
+ given to ``map``, ``any`` or ``count_matching``, receives tensors with one row per entry,
38
+ so it must compute elementwise, as ``operator.eq`` or ``lambda value: value + 1`` do; the
39
+ values of the device go to ``map`` as its ``values``, not in a closure.
40
+
41
+ Args:
42
+ edges: The edges into the devices of the batch.
43
+ local: The value of each device (``[M, ...]``), or one for all.
44
+ values: The value on each edge (``[E, ...]``), or one for all.
45
+ present: Which edges carry a value (``bool [E]``); all of them by default.
46
+ local_present: Which devices hold a value of their own (``bool [M]``); all of them by
47
+ default.
48
+ default: The value of the field for the devices it does not hold: one per device, one
49
+ for all, or ``None``.
50
+ """
51
+
52
+ __slots__ = ("edges", "local_values", "values", "present", "local_present", "default")
53
+
54
+ def __init__( # pylint: disable=too-many-arguments
55
+ self,
56
+ edges: BatchEdges,
57
+ local: Any,
58
+ values: Any,
59
+ present: torch.Tensor | None = None,
60
+ *,
61
+ local_present: torch.Tensor | None = None,
62
+ default: Any = None,
63
+ ):
64
+ device = edges.devices.device
65
+ count = int(edges.senders.numel())
66
+ self.edges = edges
67
+ self.local_values = as_rows(local, edges.num_devices, device)
68
+ """The value of each device (``[M, ...]``), also where it holds none."""
69
+ self.values = as_rows(values, count, device)
70
+ """The value on each edge (``[E, ...]``), also where it carries none."""
71
+ self.present = (
72
+ torch.ones(count, dtype=torch.bool, device=device) if present is None else present
73
+ )
74
+ self.local_present = (
75
+ torch.ones(edges.num_devices, dtype=torch.bool, device=device)
76
+ if local_present is None else local_present
77
+ )
78
+ self.default = default
79
+
80
+ def __repr__(self) -> str:
81
+ return f"BatchField(local={self.local_values!r}, values={self.values!r})"
82
+
83
+ def __iter__(self):
84
+ raise TypeError("a field of a batch of devices cannot be iterated: reduce it")
85
+
86
+ def local(self) -> torch.Tensor:
87
+ """The value of each device, NaN for the devices that hold none."""
88
+ if bool(self.local_present.all()):
89
+ return self.local_values
90
+ nothing = as_rows(None, self._rows, self._device)
91
+ return where_rows(self.local_present, self.local_values, nothing)
92
+
93
+ def without_self(self) -> "BatchField":
94
+ """The field without the value of each device."""
95
+ return self._with(local_present=torch.zeros_like(self.local_present))
96
+
97
+ def with_local(self, value: Any) -> "BatchField":
98
+ """The field where each device holds ``value``, one per device or one for all."""
99
+ return self._with(
100
+ local=as_rows(value, self._rows, self._device),
101
+ local_present=torch.ones_like(self.local_present),
102
+ )
103
+
104
+ def where(self, mask: "BatchField") -> "BatchField":
105
+ """The field restricted to the entries whose value in ``mask`` holds."""
106
+ self.check_edges(mask)
107
+ return self._with(
108
+ present=self.present & mask.present & mask.values.to(torch.bool),
109
+ local_present=(
110
+ self.local_present & mask.local_present & mask.local_values.to(torch.bool)
111
+ ),
112
+ )
113
+
114
+ def map(self, func: Callable[..., Any], *values: Any) -> "BatchField":
115
+ """
116
+ Apply ``func`` to every value of the field, and to the default if any.
117
+
118
+ Args:
119
+ func: An elementwise function of a tensor of values and of ``values``.
120
+ *values: Values of the devices, each given to the edges into its device.
121
+
122
+ Returns:
123
+ The mapped field.
124
+ """
125
+ return BatchField(
126
+ self.edges,
127
+ func(self.local_values, *map(self._on_devices, values)),
128
+ func(self.values, *map(self._on_edges, values)),
129
+ self.present,
130
+ local_present=self.local_present,
131
+ default=None if self.default is None else func(
132
+ as_tensor(self.default, self._device), *values
133
+ ),
134
+ )
135
+
136
+ def coerce_in(self, lower: Any, upper: Any) -> "BatchField":
137
+ """
138
+ The field with every value clamped to ``[lower, upper]``.
139
+
140
+ Raises:
141
+ ValueError: If ``lower > upper``.
142
+ """
143
+ if lower > upper:
144
+ raise ValueError(f"lower bound ({lower}) must not exceed upper bound ({upper})")
145
+ return self.map(torch.clamp, lower, upper)
146
+
147
+ def sum(self, *, include_self: bool = True, start: Any = 0) -> torch.Tensor:
148
+ """The sum of the values of each device, from ``start``."""
149
+ return self.fold(start, operator.add, include_self=include_self)
150
+
151
+ def product(self, *, include_self: bool = True, start: Any = 1) -> torch.Tensor:
152
+ """The product of the values of each device, from ``start``."""
153
+ return self.fold(start, operator.mul, include_self=include_self)
154
+
155
+ def min(self, *, include_self: bool = True, default: Any = None, key: Any = None):
156
+ """The least value of each device, or ``default`` (NaN for ``None``) if it has none."""
157
+ return self._extreme("amin", include_self, default, key)
158
+
159
+ def max(self, *, include_self: bool = True, default: Any = None, key: Any = None):
160
+ """The greatest value of each device, or ``default`` (NaN for ``None``) if it has none."""
161
+ return self._extreme("amax", include_self, default, key)
162
+
163
+ def id_of_min(self, *, include_self: bool = True, key: Any = None) -> torch.Tensor:
164
+ """The id of the least value of each device, the least on ties; NaN if it has none."""
165
+ return self._id_of("amin", include_self, key)
166
+
167
+ def id_of_max(self, *, include_self: bool = True, key: Any = None) -> torch.Tensor:
168
+ """The id of the greatest value of each device, the least on ties; NaN if it has none."""
169
+ return self._id_of("amax", include_self, key)
170
+
171
+ def fold(
172
+ self, initial: Any, accumulator: Callable[[Any, Any], Any], *, include_self: bool = True
173
+ ) -> torch.Tensor:
174
+ """
175
+ Fold the values of each device into one, from ``initial``.
176
+
177
+ Args:
178
+ initial: The value to start from: one per device, or one for all.
179
+ accumulator: ``operator.add``, ``operator.mul``, ``max``, ``min``, or, on
180
+ booleans, ``operator.or_`` and ``operator.and_``.
181
+ include_self: Whether to include the value of each device.
182
+
183
+ Returns:
184
+ The folded value of each device.
185
+
186
+ Raises:
187
+ TypeError: If ``accumulator`` is another function: a batch engine cannot run it
188
+ on the entries one by one.
189
+ """
190
+ reduction = _FOLDS.get(accumulator)
191
+ if reduction is None:
192
+ raise TypeError(
193
+ "a batch engine folds with operator.add, operator.mul, max, min, "
194
+ f"operator.or_ and operator.and_, not {accumulator!r}"
195
+ )
196
+ start = as_rows(initial, self._rows, self._device)
197
+ if reduction == "any":
198
+ return start.to(torch.bool) | self.any(include_self=include_self)
199
+ if reduction == "all":
200
+ return start.to(torch.bool) & self.all(include_self=include_self)
201
+ reduced, _ = self._reduce(reduction, include_self)
202
+ start, reduced = common(start, reduced)
203
+ return _COMBINE[reduction](start, reduced)
204
+
205
+ def reduce(
206
+ self, reducer: Callable[[Any, Any], Any], *, include_self: bool = True,
207
+ default: Any = None,
208
+ ) -> torch.Tensor:
209
+ """The values of each device reduced with ``reducer``, or ``default`` if it has none."""
210
+ reduction = _FOLDS.get(reducer)
211
+ if reduction not in _COMBINE:
212
+ raise TypeError(f"a batch engine reduces with operator.add, operator.mul, max and "
213
+ f"min, not {reducer!r}")
214
+ reduced, found = self._reduce(reduction, include_self)
215
+ return where_rows(found, reduced, as_rows(default, self._rows, self._device))
216
+
217
+ def any(self, predicate: Callable[[Any], Any] | None = None, *, include_self: bool = True):
218
+ """Whether any value of each device satisfies ``predicate``, or is truthy."""
219
+ reduced, _ = self._reduce("amax", include_self, *self._truths(predicate))
220
+ return reduced > 0 # a device without entries keeps the identity of amax, negative
221
+
222
+ def all(self, predicate: Callable[[Any], Any] | None = None, *, include_self: bool = True):
223
+ """Whether every value of each device satisfies ``predicate``, or is truthy."""
224
+ reduced, _ = self._reduce("amin", include_self, *self._truths(predicate))
225
+ return reduced > 0 # a device without entries keeps the identity of amin, positive
226
+
227
+ def none(self, predicate: Callable[[Any], Any] | None = None, *, include_self: bool = True):
228
+ """Whether no value of each device satisfies ``predicate``, or is truthy."""
229
+ return ~self.any(predicate, include_self=include_self)
230
+
231
+ def count_matching(self, predicate: Callable[[Any], Any], *, include_self: bool = True):
232
+ """How many values of each device satisfy ``predicate``."""
233
+ counted, _ = self._reduce("sum", include_self, *self._truths(predicate))
234
+ return counted
235
+
236
+ # Elementwise operators, as those of NeighborhoodField; a value of each device goes to
237
+ # the edges into it.
238
+ def __add__(self, other: Any) -> "BatchField":
239
+ return self._binary(other, operator.add)
240
+
241
+ def __sub__(self, other: Any) -> "BatchField":
242
+ return self._binary(other, operator.sub)
243
+
244
+ def __mul__(self, other: Any) -> "BatchField":
245
+ return self._binary(other, operator.mul)
246
+
247
+ def __truediv__(self, other: Any) -> "BatchField":
248
+ return self._binary(other, operator.truediv)
249
+
250
+ def __floordiv__(self, other: Any) -> "BatchField":
251
+ return self._binary(other, operator.floordiv)
252
+
253
+ def __mod__(self, other: Any) -> "BatchField":
254
+ return self._binary(other, operator.mod)
255
+
256
+ def __pow__(self, other: Any) -> "BatchField":
257
+ return self._binary(other, operator.pow)
258
+
259
+ def __and__(self, other: Any) -> "BatchField":
260
+ return self._binary(other, operator.and_)
261
+
262
+ def __or__(self, other: Any) -> "BatchField":
263
+ return self._binary(other, operator.or_)
264
+
265
+ def __xor__(self, other: Any) -> "BatchField":
266
+ return self._binary(other, operator.xor)
267
+
268
+ def __lt__(self, other: Any) -> "BatchField":
269
+ return self._binary(other, operator.lt)
270
+
271
+ def __le__(self, other: Any) -> "BatchField":
272
+ return self._binary(other, operator.le)
273
+
274
+ def __gt__(self, other: Any) -> "BatchField":
275
+ return self._binary(other, operator.gt)
276
+
277
+ def __ge__(self, other: Any) -> "BatchField":
278
+ return self._binary(other, operator.ge)
279
+
280
+ def __invert__(self) -> "BatchField":
281
+ return self.map(operator.invert)
282
+
283
+ @staticmethod
284
+ def merged(mask: torch.Tensor, chosen: "BatchField", other: "BatchField") -> "BatchField":
285
+ """The field of ``chosen`` for the devices of ``mask``, of ``other`` for the rest."""
286
+ chosen.check_edges(other)
287
+ on_edges = mask[chosen.edges.receivers]
288
+ rows, device = chosen.edges.num_devices, mask.device
289
+ defaults = (chosen.default, other.default)
290
+ return BatchField(
291
+ chosen.edges,
292
+ where_rows(mask, chosen.local_values, other.local_values),
293
+ where_rows(on_edges, chosen.values, other.values),
294
+ torch.where(on_edges, chosen.present, other.present),
295
+ local_present=torch.where(mask, chosen.local_present, other.local_present),
296
+ default=None if None in defaults else where_rows(
297
+ mask, *(as_rows(value, rows, device) for value in defaults)
298
+ ),
299
+ )
300
+
301
+ @property
302
+ def _rows(self) -> int:
303
+ return self.edges.num_devices
304
+
305
+ @property
306
+ def _device(self) -> torch.device:
307
+ return self.edges.devices.device
308
+
309
+ def _with(self, **changes: Any) -> "BatchField":
310
+ """A copy of the field with ``changes`` to its local value or to its entries."""
311
+ return BatchField(
312
+ self.edges,
313
+ changes.get("local", self.local_values),
314
+ self.values,
315
+ changes.get("present", self.present),
316
+ local_present=changes.get("local_present", self.local_present),
317
+ default=self.default,
318
+ )
319
+
320
+ def check_edges(self, other: "BatchField") -> None:
321
+ """
322
+ Check that ``other`` belongs to the same batch of devices.
323
+
324
+ Raises:
325
+ ValueError: If it does not.
326
+ """
327
+ if other.edges is not self.edges:
328
+ raise ValueError("the fields belong to different batches of devices")
329
+
330
+ def _on_edges(self, value: Any) -> Any:
331
+ """A value of the devices as one on each edge into them: tensors are gathered."""
332
+ if isinstance(value, BatchField):
333
+ return value.values
334
+ if isinstance(value, torch.Tensor) and value.ndim > 0:
335
+ return value[self.edges.receivers]
336
+ return value
337
+
338
+ @staticmethod
339
+ def _on_devices(value: Any) -> Any:
340
+ """A value of the devices as one of each device: a field gives its local values."""
341
+ return value.local_values if isinstance(value, BatchField) else value
342
+
343
+ def _binary(self, other: Any, op: Callable[[Any, Any], Any]) -> "BatchField":
344
+ """``op`` of each entry and ``other``: a field, a value of each device, or one for all."""
345
+ if not isinstance(other, BatchField):
346
+ return self.map(op, other)
347
+ self.check_edges(other)
348
+ defaults = (self.default, other.default)
349
+ return BatchField(
350
+ self.edges,
351
+ op(self.local_values, other.local_values),
352
+ op(self.values, other.values),
353
+ self.present & other.present,
354
+ local_present=self.local_present & other.local_present,
355
+ default=None if None in defaults else op(*defaults),
356
+ )
357
+
358
+ def _truths(self, predicate: Callable[[Any], Any] | None) -> tuple[torch.Tensor, ...]:
359
+ """The truth of ``predicate``, or of the values, of each device and edge, as 0 or 1."""
360
+ mapped = self if predicate is None else self.map(predicate)
361
+ return tuple(
362
+ as_tensor(values, self._device).to(torch.bool).to(torch.int64)
363
+ for values in (mapped.local_values, mapped.values)
364
+ )
365
+
366
+ def _reduce(
367
+ self, reduction: str, include_self: bool,
368
+ local: torch.Tensor | None = None, values: torch.Tensor | None = None,
369
+ ) -> tuple[torch.Tensor, torch.Tensor]:
370
+ """
371
+ The ``reduction`` (``sum``, ``prod``, ``amax`` or ``amin``) of the entries of each
372
+ device, and whether it has any; of ``local`` and ``values`` instead of those of the
373
+ field, if given.
374
+ """
375
+ local, values = common(
376
+ self.local_values if local is None else local,
377
+ self.values if values is None else values,
378
+ )
379
+ if values.dtype == torch.bool:
380
+ local, values = local.to(torch.int64), values.to(torch.int64)
381
+ receivers = self.edges.receivers[self.present]
382
+ entries = values[self.present]
383
+ reduced = torch.full(
384
+ (self._rows, *values.shape[1:]), _identity(reduction, values.dtype),
385
+ dtype=values.dtype, device=self._device,
386
+ )
387
+ index = receivers.view(-1, *[1] * (entries.ndim - 1)).expand_as(entries)
388
+ reduced.scatter_reduce_(0, index, entries, reduce=reduction, include_self=True)
389
+ found = torch.zeros(self._rows, dtype=torch.bool, device=self._device)
390
+ found[receivers] = True
391
+ if include_self:
392
+ reduced = where_rows(
393
+ self.local_present, _COMBINE[reduction](reduced, local), reduced
394
+ )
395
+ found = found | self.local_present
396
+ return reduced, found
397
+
398
+ def _extreme(self, reduction: str, include_self: bool, default: Any, key: Any):
399
+ if key is not None:
400
+ raise TypeError("a batch engine compares the values themselves, without a key")
401
+ reduced, found = self._reduce(reduction, include_self)
402
+ return where_rows(found, reduced, as_rows(default, self._rows, self._device))
403
+
404
+ def _id_of(self, reduction: str, include_self: bool, key: Any) -> torch.Tensor:
405
+ best = self._extreme(reduction, include_self, None, key)
406
+ local, values = common(self.local_values, self.values)
407
+ receivers = self.edges.receivers
408
+ winners = self.present & (values == best[receivers])
409
+ unset = torch.iinfo(torch.int64).max
410
+ ids = torch.full((self._rows,), unset, dtype=torch.int64, device=self._device)
411
+ ids.scatter_reduce_(0, receivers[winners], self.edges.senders[winners],
412
+ reduce="amin", include_self=True)
413
+ if include_self:
414
+ own = self.local_present & (local == best)
415
+ ids = torch.where(own, torch.minimum(ids, self.edges.devices), ids)
416
+ if bool((ids != unset).all()):
417
+ return ids
418
+ return torch.where(ids != unset, ids.to(torch.float64), math.nan)
419
+
420
+
421
+ def _identity(reduction: str, dtype: torch.dtype) -> float | int:
422
+ """The value that ``reduction`` leaves unchanged: what a device without entries gets."""
423
+ if reduction == "sum":
424
+ return 0
425
+ if reduction == "prod":
426
+ return 1
427
+ if dtype.is_floating_point:
428
+ return math.inf if reduction == "amin" else -math.inf
429
+ limits = torch.iinfo(dtype)
430
+ return limits.max if reduction == "amin" else limits.min
phyelds/gpu/runtime.py ADDED
@@ -0,0 +1,58 @@
1
+ """
2
+ Synchronous rounds of every device at once, on a torch device: in a round each device reads
3
+ what its neighbors sent in the previous one, as ``phyelds.vm.synchronous.SynchronousRuntime``
4
+ does, with one row per device instead of one round per device.
5
+ """
6
+ from collections.abc import Callable, Mapping
7
+ from typing import Any
8
+
9
+ from phyelds.gpu.engine import BatchEngine, Rows, States, SynchronousMessages, _written
10
+ from phyelds.gpu.topology import GraphTopology
11
+
12
+
13
+ class BatchSynchronousRuntime:
14
+ """
15
+ Runs an aggregate program on every device of a graph at once, one synchronous round at a
16
+ time, on the torch device of the graph.
17
+
18
+ Args:
19
+ program: The ``@aggregate`` function to run; it runs once per round, for all the
20
+ devices, with a row per device in each value.
21
+ topology: Who hears whom.
22
+ """
23
+
24
+ def __init__(self, program: Callable[[], Any], topology: GraphTopology):
25
+ self.program = program
26
+ self.topology = topology
27
+ self.outputs: dict[str, Rows] = {}
28
+ """What the devices stored, by name: a value of each device and whether it stored one."""
29
+ self._edges = topology.batch()
30
+ self._states = States(topology.num_devices, topology.device)
31
+ self._messages = SynchronousMessages(topology.num_devices, topology.device)
32
+
33
+ def run_round(self, sensors: Mapping[str, Any]) -> Any:
34
+ """
35
+ Run the program once on every device.
36
+
37
+ Args:
38
+ sensors: The sensors of the devices, by name: a tensor with a row per device, or
39
+ one value for all.
40
+
41
+ Returns:
42
+ What the program returned: a tensor with a row per device for each value, or a
43
+ single value if it is the same for every device.
44
+ """
45
+ batch = BatchEngine(self._edges, self._states, self._messages, sensors)
46
+ result = batch.run(self.program)
47
+ devices = self._edges.devices
48
+ self._messages.publish(devices, batch.finish())
49
+ count = self.topology.num_devices
50
+ for name, (values, stored) in batch.node_context.stored.items():
51
+ self.outputs[name] = _written(None, count, devices, values, stored)
52
+ return result
53
+
54
+ def reset(self) -> None:
55
+ """Forget the state, the messages and the outputs of every device."""
56
+ self._states.clear()
57
+ self._messages.clear()
58
+ self.outputs = {}
phyelds/gpu/tensors.py ADDED
@@ -0,0 +1,78 @@
1
+ """
2
+ The values of a batch of devices as tensors, with one row per device.
3
+
4
+ On a batch engine ``None`` is NaN: the devices for which a branch returns nothing get NaN,
5
+ which, as ``None``, equals nothing.
6
+ """
7
+ import math
8
+ from typing import Any
9
+
10
+ import torch
11
+
12
+
13
+ def as_rows(value: Any, rows: int, device: torch.device) -> torch.Tensor:
14
+ """
15
+ ``value`` with one row per device.
16
+
17
+ Args:
18
+ value: A tensor with ``rows`` rows, kept as it is; or a value for every device: a
19
+ number, ``None``, a 0-dimensional tensor, or a tuple of numbers.
20
+ rows: How many devices the rows are for.
21
+ device: The torch device of the result.
22
+
23
+ Returns:
24
+ A tensor whose first dimension is ``rows``.
25
+
26
+ Raises:
27
+ TypeError: If ``value`` is not a number, ``None``, a tuple of numbers or a tensor.
28
+ ValueError: If ``value`` is a tensor with another number of rows.
29
+ """
30
+ if isinstance(value, torch.Tensor):
31
+ tensor = value.to(device)
32
+ if tensor.ndim == 0:
33
+ return tensor.expand(rows)
34
+ if tensor.shape[0] != rows:
35
+ raise ValueError(f"a value of {rows} devices needs {rows} rows, not {tensor.shape[0]}")
36
+ return tensor
37
+ if value is None:
38
+ return torch.full((rows,), math.nan, dtype=torch.float64, device=device)
39
+ try:
40
+ tensor = torch.as_tensor(value, dtype=_dtype(value), device=device)
41
+ except (TypeError, ValueError, RuntimeError) as error:
42
+ raise TypeError(
43
+ "a batch engine holds numbers, tuples of numbers and tensors, "
44
+ f"not {type(value).__name__}"
45
+ ) from error
46
+ return tensor.expand(rows, *tensor.shape)
47
+
48
+
49
+ def as_tensor(value: Any, device: torch.device) -> torch.Tensor:
50
+ """``value`` as a tensor, with 64 bits for Python numbers: a tensor stays as it is."""
51
+ if isinstance(value, torch.Tensor):
52
+ return value.to(device)
53
+ return torch.as_tensor(value, dtype=_dtype(value), device=device)
54
+
55
+
56
+ def where_rows(mask: torch.Tensor, chosen: torch.Tensor, other: torch.Tensor) -> torch.Tensor:
57
+ """The rows of ``chosen`` where ``mask`` holds, those of ``other`` elsewhere."""
58
+ chosen, other = common(chosen, other)
59
+ return torch.where(mask.view(-1, *[1] * (chosen.ndim - 1)), chosen, other)
60
+
61
+
62
+ def common(*tensors: torch.Tensor) -> tuple[torch.Tensor, ...]:
63
+ """``tensors`` converted to the type that holds the values of all of them."""
64
+ dtype = tensors[0].dtype
65
+ for tensor in tensors[1:]:
66
+ dtype = torch.promote_types(dtype, tensor.dtype)
67
+ return tuple(tensor.to(dtype) for tensor in tensors)
68
+
69
+
70
+ def _dtype(value: Any) -> torch.dtype | None:
71
+ """The type of a tensor holding ``value``: 64 bits for numbers, as Python has."""
72
+ if isinstance(value, bool):
73
+ return torch.bool
74
+ if isinstance(value, int):
75
+ return torch.int64
76
+ if isinstance(value, float):
77
+ return torch.float64
78
+ return torch.float64 if any(isinstance(item, float) for item in value) else None