Skip to content

Commit 7fa6bb3

Browse files
trissimclaude
andcommitted
0.5.2: counters keep declined routes, imports wait for the module lock, lists of arrays set the device
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6f69ea4 commit 7fa6bb3

8 files changed

Lines changed: 229 additions & 56 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,29 @@
11
# Changelog
22

3+
## 0.5.2
4+
5+
### Counters keep declined routes
6+
7+
`ConversionCounters` keyed its totals by source, target and mechanism, so two
8+
conversions that declined different routes were merged and `declined_mechanisms`
9+
was lost in `rows`, `merge`, `to_json`/`from_json` and `format_table`. The key is
10+
now derived in one place from every `ConversionRecord` field except `nbytes` and
11+
`seconds`, so a field added to the record cannot fall out of the counters. Rows
12+
gain `declined_mechanisms` (a list); `format_table` shows it in a last column.
13+
14+
### A library is not loaded while another thread is importing it
15+
16+
`ArrayLibrary.loaded_module()` answers `None` for a module whose
17+
`__spec__._initializing` is true, so `module` goes through
18+
`importlib.import_module`, which waits on the module lock. Two threads first
19+
using a library together no longer see `partially initialized module`.
20+
21+
### A list of accelerator arrays gets its stream and OOM retry
22+
23+
The device of a call is read from direct array arguments and from the items of
24+
list and tuple arguments (one level, no deeper). Arrays of one library on
25+
different devices in one call now raise `ValueError` naming the devices.
26+
327
## 0.5.1
428

529
### No library inherits an operation it cannot perform

‎docs/source/api_reference.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ plan, says what was done to that array.
204204

205205
``ConversionCounters``
206206
An observer that keeps count, bytes and seconds per source library and
207-
device, target library and device, and mechanism. ``rows()`` (also named
207+
device, target library and device, mechanism and declined mechanisms. ``rows()`` (also named
208208
``to_json()``) returns one row per kind, largest byte total first;
209209
``from_json(rows)`` rebuilds counters; ``merge(other)`` adds another
210210
process's totals; ``format_table()`` returns aligned text.

‎src/arraybridge/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
NumPy/numcodecs import cost.
1111
"""
1212

13-
__version__ = "0.5.1"
13+
__version__ = "0.5.2"
1414

1515
_LAZY_EXPORTS: dict[str, str] = {
1616
"MemoryType": ".types",

‎src/arraybridge/conversion.py‎

Lines changed: 44 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from collections.abc import Iterator, Mapping
2323
from contextlib import contextmanager
2424
from contextvars import ContextVar
25-
from dataclasses import asdict, dataclass, field
25+
from dataclasses import asdict, dataclass, field, fields
2626
from types import NotImplementedType
2727
from typing import TYPE_CHECKING, ClassVar, TypeGuard, TypeVar
2828

@@ -454,7 +454,17 @@ def record(self, record: ConversionRecord) -> None:
454454
"arraybridge conversion observer", default=IgnoreConversions()
455455
)
456456

457-
ConversionKey = tuple[str, str, str, str, str]
457+
# A conversion kind is identified by every field of the record except its measurements.
458+
_MEASUREMENTS = frozenset({"nbytes", "seconds"})
459+
_IDENTITY_FIELDS = tuple(
460+
each.name for each in fields(ConversionRecord) if each.name not in _MEASUREMENTS
461+
)
462+
ConversionKey = tuple[str | tuple[str, ...], ...]
463+
JsonRow = dict[str, str | int | float | list[str]]
464+
465+
466+
def _key_of(record: ConversionRecord) -> ConversionKey:
467+
return tuple(getattr(record, name) for name in _IDENTITY_FIELDS)
458468

459469

460470
@dataclass(slots=True)
@@ -468,27 +478,18 @@ class ConversionTotal:
468478

469479
@dataclass(slots=True)
470480
class ConversionCounters(ConversionObserver):
471-
"""Per-process totals keyed by source, target and mechanism.
481+
"""Per-process totals keyed by what identifies a conversion.
472482
473-
Counters from worker processes are plain data: pickle them or send
474-
``to_json()`` back, then ``merge`` them into the parent's.
483+
The key is every field of ``ConversionRecord`` but ``nbytes`` and
484+
``seconds``: the libraries and devices, the mechanism and the declined
485+
mechanisms. Counters from worker processes are plain data: pickle them or
486+
send ``to_json()`` back, then ``merge`` them into the parent's.
475487
"""
476488

477489
totals: dict[ConversionKey, ConversionTotal] = field(default_factory=dict)
478490

479491
def record(self, record: ConversionRecord) -> None:
480-
self._add(
481-
(
482-
record.source_library,
483-
record.source_device,
484-
record.target_library,
485-
record.target_device,
486-
record.mechanism,
487-
),
488-
1,
489-
record.nbytes,
490-
record.seconds,
491-
)
492+
self._add(_key_of(record), 1, record.nbytes, record.seconds)
492493

493494
def _add(self, key: ConversionKey, count: int, nbytes: int, seconds: float) -> None:
494495
total = self.totals.setdefault(key, ConversionTotal())
@@ -503,55 +504,56 @@ def merge(self, other: ConversionCounters) -> ConversionCounters:
503504
self._add(key, total.count, total.nbytes, total.seconds)
504505
return self
505506

506-
def rows(self) -> list[dict[str, str | int | float]]:
507+
def _largest_first(self) -> list[tuple[ConversionKey, ConversionTotal]]:
508+
return sorted(self.totals.items(), key=lambda item: (-item[1].nbytes, item[0]))
509+
510+
def rows(self) -> list[JsonRow]:
507511
"""One JSON-ready row per kind of conversion, largest byte total first."""
508512

509513
return [
510514
{
511-
"source_library": key[0],
512-
"source_device": key[1],
513-
"target_library": key[2],
514-
"target_device": key[3],
515-
"mechanism": key[4],
515+
**{
516+
name: list(part) if isinstance(part, tuple) else part
517+
for name, part in zip(_IDENTITY_FIELDS, key, strict=True)
518+
},
516519
"count": total.count,
517520
"nbytes": total.nbytes,
518521
"seconds": total.seconds,
519522
}
520-
for key, total in sorted(
521-
self.totals.items(), key=lambda item: (-item[1].nbytes, item[0])
522-
)
523+
for key, total in self._largest_first()
523524
]
524525

525526
to_json = rows
526527

527528
@classmethod
528-
def from_json(cls, rows: list[dict[str, str | int | float]]) -> ConversionCounters:
529+
def from_json(cls, rows: list[JsonRow]) -> ConversionCounters:
529530
counters = cls()
530531
for row in rows:
532+
key = tuple(
533+
tuple(map(str, part)) if isinstance(part, list) else str(part)
534+
for part in (row[name] for name in _IDENTITY_FIELDS)
535+
)
531536
counters._add(
532-
(
533-
str(row["source_library"]),
534-
str(row["source_device"]),
535-
str(row["target_library"]),
536-
str(row["target_device"]),
537-
str(row["mechanism"]),
538-
),
539-
int(row["count"]),
540-
int(row["nbytes"]),
541-
float(row["seconds"]),
537+
key, int(str(row["count"])), int(str(row["nbytes"])), float(str(row["seconds"]))
542538
)
543539
return counters
544540

545541
def format_table(self) -> str:
546542
"""The totals as aligned text, one line per kind of conversion."""
547543

548544
lines = [
549-
f"{'source':<28} {'target':<28} {'mechanism':<12} "
550-
f"{'count':>7} {'MB':>10} {'seconds':>9}"
545+
f"{'source':<28} {'target':<28} {'mechanism':<20} "
546+
f"{'count':>7} {'MB':>10} {'seconds':>9} declined"
551547
]
552-
for key, total in sorted(self.totals.items(), key=lambda item: (-item[1].nbytes, item[0])):
548+
for key, total in self._largest_first():
549+
row = dict(zip(_IDENTITY_FIELDS, key, strict=True))
550+
declined = row["declined_mechanisms"]
551+
assert isinstance(declined, tuple)
553552
lines.append(
554-
f"{key[0] + ' ' + key[1]:<28} {key[2] + ' ' + key[3]:<28} {key[4]:<12} "
555-
f"{total.count:>7} {total.nbytes / 1e6:>10.1f} {total.seconds:>9.3f}"
553+
f"{row['source_library']} {row['source_device']}".ljust(29)
554+
+ f"{row['target_library']} {row['target_device']}".ljust(29)
555+
+ f"{row['mechanism']!s:<20} "
556+
+ f"{total.count:>7} {total.nbytes / 1e6:>10.1f} {total.seconds:>9.3f} "
557+
+ ", ".join(declined)
556558
)
557559
return "\n".join(lines)

‎src/arraybridge/libraries.py‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -370,9 +370,17 @@ def prepare_import(self) -> None:
370370
os.environ.setdefault(name, value)
371371

372372
def loaded_module(self) -> ModuleType | None:
373-
"""The library's module if something already imported it."""
373+
"""The library's module if something has finished importing it.
374374
375-
return sys.modules.get(self.import_name)
375+
A module another thread is still executing is not loaded yet: it is
376+
answered ``None``, and ``import_module`` waits for it.
377+
"""
378+
379+
module = sys.modules.get(self.import_name)
380+
spec = getattr(module, "__spec__", None)
381+
if spec is not None and getattr(spec, "_initializing", False):
382+
return None
383+
return module
376384

377385
def import_module(self) -> ModuleType:
378386
"""Import the library's module."""
@@ -895,15 +903,28 @@ def _upload(self, data: np.ndarray, device: AcceleratorDevice) -> NativeT:
895903
"""Create a native array on ``device``; called inside that device's scope."""
896904

897905
def _argument_device(self, arguments: Sequence[object]) -> Device | None:
898-
"""The device of the first array of this library among a call's arguments."""
906+
"""The one device holding the arrays of this library among a call's arguments.
907+
908+
An array is an argument itself or an item of an argument that is a list
909+
or a tuple; nothing deeper is searched. Arrays on different devices in
910+
one call raise ``ValueError`` naming the devices.
911+
"""
899912

900913
if self.loaded_module() is None:
901914
return None
902-
for value in arguments:
903-
device = self._device_if_accepted(value)
904-
if device is not None:
905-
return device
906-
return None
915+
devices: dict[str, Device] = {}
916+
for argument in arguments:
917+
items = argument if isinstance(argument, (list, tuple)) else (argument,)
918+
for value in items:
919+
device = self._device_if_accepted(value)
920+
if device is not None:
921+
devices.setdefault(device.label, device)
922+
if len(devices) > 1:
923+
raise ValueError(
924+
f"The arrays of one {self.display_name} call are on different devices: "
925+
+ ", ".join(sorted(devices))
926+
)
927+
return next(iter(devices.values()), None)
907928

908929
@abstractmethod
909930
def _device_if_accepted(self, value: object) -> Device | None:

‎tests/test_conversion.py‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,7 @@ def test_totals_are_kept_per_kind_of_conversion(self):
757757
"target_library": "torch",
758758
"target_device": "accelerator:0",
759759
"mechanism": "host copy",
760+
"declined_mechanisms": [],
760761
"count": 2,
761762
"nbytes": 40,
762763
"seconds": 0.5,
@@ -767,6 +768,7 @@ def test_totals_are_kept_per_kind_of_conversion(self):
767768
"target_library": "torch",
768769
"target_device": "accelerator:0",
769770
"mechanism": "dlpack",
771+
"declined_mechanisms": [],
770772
"count": 1,
771773
"nbytes": 10,
772774
"seconds": 0.25,
@@ -809,7 +811,15 @@ def test_table_has_one_line_per_row(self):
809811

810812
header, *lines = counters.format_table().splitlines()
811813

812-
assert header.split() == ["source", "target", "mechanism", "count", "MB", "seconds"]
814+
assert header.split() == [
815+
"source",
816+
"target",
817+
"mechanism",
818+
"count",
819+
"MB",
820+
"seconds",
821+
"declined",
822+
]
813823
assert len(lines) == len(counters.rows())
814824
for line, row in zip(lines, counters.rows(), strict=True):
815825
for field in ("source_library", "source_device", "target_library", "target_device"):
@@ -818,3 +828,40 @@ def test_table_has_one_line_per_row(self):
818828
assert f"{row['count']:>7}" in line
819829
assert f"{row['nbytes'] / 1e6:.1f}" in line
820830
assert f"{row['seconds']:.3f}" in line
831+
832+
833+
class TestCounterKey:
834+
def test_every_field_but_the_measurements_identifies_a_kind(self):
835+
import dataclasses
836+
837+
base = ConversionRecord("numpy", "host", "torch", "accelerator:0", "host copy", 1, 1.0)
838+
values = {
839+
"source_library": "cupy",
840+
"source_device": "accelerator:1",
841+
"target_library": "jax",
842+
"target_device": "host",
843+
"mechanism": "dlpack",
844+
"declined_mechanisms": ("dlpack",),
845+
}
846+
for each in dataclasses.fields(ConversionRecord):
847+
if each.name in ("nbytes", "seconds"):
848+
continue
849+
other = dataclasses.replace(base, **{each.name: values[each.name]})
850+
counters = ConversionCounters()
851+
counters.record(base)
852+
counters.record(other)
853+
assert len(counters.totals) == 2, each.name
854+
assert ConversionCounters.from_json(counters.to_json()) == counters, each.name
855+
assert pickle.loads(pickle.dumps(counters)) == counters, each.name
856+
assert ConversionCounters().merge(counters) == counters, each.name
857+
858+
def test_declined_routes_are_shown_and_survive_json(self):
859+
counters = ConversionCounters()
860+
counters.record(
861+
ConversionRecord("numpy", "host", "torch", "host", "host copy", 5, 1.0, ("dlpack",))
862+
)
863+
rows = json.loads(json.dumps(counters.to_json()))
864+
865+
assert rows[0]["declined_mechanisms"] == ["dlpack"]
866+
assert ConversionCounters.from_json(rows) == counters
867+
assert "dlpack" in counters.format_table().splitlines()[1]

‎tests/test_devices.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from arraybridge.libraries import ArrayLibrary, HostDevices
1414
from tests.fakes import (
1515
FakeCupy,
16+
FakeCupyArray,
1617
FakePyclesperanto,
1718
FakePyclesperantoArray,
1819
FakeTorch,
@@ -262,3 +263,39 @@ def test_current_device_is_the_one_the_library_has_selected(self, monkeypatch):
262263

263264
assert ArrayLibrary.named("cupy").current_device() == AcceleratorDevice(1)
264265
assert TORCH.current_device() is None
266+
267+
268+
class TestArraysInLists:
269+
@staticmethod
270+
def seen_device(monkeypatch, *arguments):
271+
module = FakeCupy()
272+
monkeypatch.setitem(sys.modules, "cupy", module)
273+
cupy = ArrayLibrary.named("cupy")
274+
wrapped = cupy.execution_wrapper(lambda *_: None, oom_recovery=True)
275+
wrapped(*[argument(module) for argument in arguments])
276+
streams = [stream for event, stream in module.events if event == "stream enter"]
277+
return [stream.device_index for stream in streams]
278+
279+
def test_a_list_of_arrays_runs_on_their_device(self, monkeypatch):
280+
def arrays(module):
281+
return [FakeCupyArray(np.zeros(2), 1, module), FakeCupyArray(np.zeros(2), 1, module)]
282+
283+
assert self.seen_device(monkeypatch, arrays) == [1]
284+
285+
def test_a_tuple_of_arrays_runs_on_their_device(self, monkeypatch):
286+
assert self.seen_device(monkeypatch, lambda m: (FakeCupyArray(np.zeros(2), 1, m),)) == [1]
287+
288+
def test_only_one_level_is_searched(self, monkeypatch):
289+
module = FakeCupy()
290+
monkeypatch.setitem(sys.modules, "cupy", module)
291+
cupy = ArrayLibrary.named("cupy")
292+
nested = [[FakeCupyArray(np.zeros(2), 1, module)]]
293+
294+
assert cupy._argument_device((nested,)) is None
295+
296+
def test_arrays_on_different_devices_name_them(self, monkeypatch):
297+
def arrays(module):
298+
return [FakeCupyArray(np.zeros(2), 0, module), FakeCupyArray(np.zeros(2), 1, module)]
299+
300+
with pytest.raises(ValueError, match="accelerator:0.*accelerator:1"):
301+
self.seen_device(monkeypatch, arrays)

0 commit comments

Comments
 (0)