"""Tensor storage, split so the bookkeeping half can have a Rust backend.
``TensorBookkeeping`` holds the reference state -- refcounts, the persist flag,
whether the memory has been registered for remote reads -- keyed by integer
uuid, so the Rust graph runtime can adjust refcounts without a hop back to
Python.
``TensorStore`` holds the ``torch.Tensor`` objects and which request owns each.
Over the Python bookkeeper they are Python dicts. Over the Rust one they live in
the bookkeeper as well (``RustTensorStore``), so a release that takes a tensor
to zero can free it in the same Rust pass, with no per-uuid Python.
Uuids are globally unique now (see ``tensor_uuid``), so nothing here is keyed by
request. The one exception is the rid -> uuids ownership, which exists only so a
request teardown can find what to free.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterable
from dataclasses import dataclass, field
import torch
from mstar.graph.base import TensorPointerInfo
NameToTensorList = dict[str, list[torch.Tensor]]
# The worker interns request ids to integer handles; the api-server data and
# preprocess workers never did and still pass the string id. Both work: the id
# is an opaque dict key here, never arithmetic, and it reaches the bookkeeper --
# the half that is actually typed -- not at all.
Rid = int | str
[docs]
@dataclass
class ReferenceInfo:
ref_cnt: int = 0
persist: bool = False
mem_registered: bool = False
[docs]
@dataclass
class ColumnarTensorInfo:
"""One node's output batch, marshalled as columns of primitives.
The fields above the columns are constant for the whole batch, so they
cross into the bookkeeper once and intern once instead of per tensor.
``tp_size``/``tp_rank`` belong there too: the sharding group is a property
of the node and this rank, not of the request, so one batch -- one node,
one graph walk, one worker -- cannot be heterogeneous in them.
"""
source_session_id: str
source_entity: str
source_node_name: str
source_graph_walk: str
tp_size: int
tp_rank: int
uuids: list[int] = field(default_factory=list)
addresses: list[int] = field(default_factory=list)
nbytes: list[int] = field(default_factory=list)
ndims: list[int] = field(default_factory=list)
dims_flat: list[int] = field(default_factory=list)
stride_flat: list[int] = field(default_factory=list)
dtype_idx: list[int] = field(default_factory=list)
dtype_names: list[str] = field(default_factory=list)
def __post_init__(self):
self._seen_dtypes: dict[torch.dtype, int] = {}
[docs]
def dtype_index(self, dtype: torch.dtype) -> int:
"""The batch-local index of ``dtype``, registering it on first use."""
idx = self._seen_dtypes.get(dtype)
if idx is None:
idx = self._seen_dtypes[dtype] = len(self.dtype_names)
self.dtype_names.append(_dtype_name(dtype))
return idx
[docs]
def add_row(
self, uuid: int, address: int, nbytes: int, ndims: int,
dims, stride, dtype_idx: int,
) -> None:
"""One tensor whose layout is already known (a row of a template):
its entry in every column, in the layout's order."""
self.uuids.append(uuid)
self.addresses.append(address)
self.nbytes.append(nbytes)
self.ndims.append(ndims)
self.dims_flat.extend(dims)
self.stride_flat.extend(stride)
self.dtype_idx.append(dtype_idx)
[docs]
def add_tensors_canonical(
self, uuids: list[int],
canonicals: list[torch.Tensor],
):
self.uuids.extend(uuids)
for tensor in canonicals:
self.addresses.append(tensor.data_ptr())
self.nbytes.append(tensor.nbytes)
dims = tensor.shape
self.ndims.append(len(dims))
self.dims_flat.extend(dims)
self.stride_flat.extend(tensor.stride())
idx = self._seen_dtypes.get(tensor.dtype)
if idx is None:
idx = self._seen_dtypes[tensor.dtype] = len(self.dtype_names)
self.dtype_names.append(_dtype_name(tensor.dtype))
self.dtype_idx.append(idx)
[docs]
class TensorBookkeeping(ABC):
"""Per-uuid reference state. Never sees a tensor or a request id.
The defaults of the batched forms loop, so a backend only overrides where
batching buys something. They take two
parallel lists rather than a ParallelList because that is what crosses the
Rust boundary -- pyo3 converts a list of ints directly, where a NamedTuple
would need unpacking on every call.
"""
[docs]
@abstractmethod
def put_tensor(self, uuid: int, info: TensorPointerInfo):
pass
[docs]
def put_tensor_batch(
self, uuids: list[int], infos: list[TensorPointerInfo]
):
for uuid, info in zip(uuids, infos, strict=True):
self.put_tensor(uuid, info)
@property
def has_put_tensor_batch_columns(self):
return False
[docs]
def put_tensor_batch_columns(
self, infos: ColumnarTensorInfo,
):
"""Columnar put, for a backend that pays per tensor to marshal.
Returns whether it handled the batch. The default says no: a Python
bookkeeper stores the descriptor by reference and has nothing to
marshal, so flattening it into columns would only add work.
"""
raise NotImplementedError("Columnar put not implemented for this backend")
[docs]
@abstractmethod
def register_shm_segment(self, index: int, name: str):
"""Name one arena segment, once, as the arena grows into it.
Keeps the name off ``set_shm_placement``, which then crosses an index
the caller already had.
"""
pass
[docs]
@abstractmethod
def set_shm_placement(
self, uuids: list[int], segment_idxs: list[int],
offsets: list[int],
):
"""Stamp arena placement onto descriptors already held.
``register_for_send`` changes only these two fields, so only they
cross -- not a rebuilt descriptor. Segments cross as indices from
``register_shm_segment``: the caller reserved by index, and rendering
a name per tensor costs a string allocation on each side plus a hash,
to recover an integer it already had. ``-1`` is "no segment", the
producer having spilled that tensor to its own file.
"""
pass
[docs]
@abstractmethod
def get_info(self, uuid: int) -> TensorPointerInfo | None:
"""The descriptor a peer needs to read this tensor.
This is what lets an edge be rebuilt from uuids alone: ingestion and
routing carry uuids, and anything that has to put a descriptor back on
the wire (a disaggregated loop re-emitting its external inputs, say)
looks it up here.
"""
pass
[docs]
@abstractmethod
def forget_tensor(self, uuid: int):
"""Drop the record. The caller frees the tensor itself."""
pass
# -- refcounts ----------------------------------------------------------
[docs]
@abstractmethod
def increment_ref(self, uuid: int, n: int = 1):
pass
[docs]
def increment_ref_batch(self, uuids: list[int], counts: list[int]):
for uuid, n in zip(uuids, counts, strict=True):
self.increment_ref(uuid, n)
[docs]
@abstractmethod
def dereference(self, uuid: int, n: int = 1):
pass
[docs]
def dereference_batch(
self, uuids: list[int], counts: list[int], cleanup: bool = False,
) -> tuple[list[int], list[bool]]:
"""Drop ``counts[i]`` references from ``uuids[i]``, answering the gc
question in the same pass.
Returns the uuids that became collectable and whether each was
registered for remote reads -- the one flag a teardown still needs
after ``cleanup`` has dropped the record. Per uuid the caller would
otherwise pay a crossing each for the decrement, ``can_gc``,
``is_registered`` and ``forget_tensor``.
"""
return self._drop_refs(zip(uuids, counts, strict=True), cleanup)
def _drop_refs(
self, refs: Iterable[tuple[int, int]], cleanup: bool,
) -> tuple[list[int], list[bool]]:
collectable: list[int] = []
registered: list[bool] = []
for uuid, n in refs:
self.dereference(uuid, n)
if not self.can_gc(uuid):
continue
collectable.append(uuid)
registered.append(self.is_registered(uuid))
if cleanup:
for uuid in collectable:
self.forget_tensor(uuid)
return collectable, registered
# -- flags --------------------------------------------------------------
[docs]
@abstractmethod
def set_persist(self, uuid: int, persist: bool):
pass
[docs]
@abstractmethod
def set_mem_registered(self, uuid: int, mem_registered: bool):
pass
[docs]
@abstractmethod
def is_registered(self, uuid: int) -> bool:
pass
# -- gc -----------------------------------------------------------------
[docs]
@abstractmethod
def can_gc(self, uuid: int) -> bool:
"""No references left and not being persisted for the conductor."""
pass
[docs]
class PythonTensorBookkeeping(TensorBookkeeping):
"""The pure-Python bookkeeping the Rust one is tested against."""
def __init__(self):
self._ref_info: dict[int, ReferenceInfo] = {}
self._tensor_info: dict[int, TensorPointerInfo] = {}
# Arena segment index -> name; see register_shm_segment.
self._shm_segments: list[str | None] = []
[docs]
def put_tensor(self, uuid: int, info: TensorPointerInfo):
self._ref_info[uuid] = ReferenceInfo()
self._tensor_info[uuid] = info
[docs]
def register_shm_segment(self, index: int, name: str):
if index >= len(self._shm_segments):
self._shm_segments.extend(
[None] * (index + 1 - len(self._shm_segments))
)
self._shm_segments[index] = name
[docs]
def set_shm_placement(
self, uuids: list[int], segment_idxs: list[int],
offsets: list[int],
):
# The descriptor is held by reference, so stamping it in place is the
# whole update.
for uuid, idx, off in zip(uuids, segment_idxs, offsets, strict=True):
# Resolved BEFORE the uuid lookup, so a bad index is an error
# whether or not that tensor is still tracked -- the Rust
# bookkeeper checks in this order and the two must not disagree
# about which calls raise.
seg = None if idx < 0 else self._shm_segment_name(idx)
info = self._tensor_info.get(uuid)
if info is None:
continue
info.shm_segment = seg
info.shm_offset = off
def _shm_segment_name(self, idx: int) -> str:
name = self._shm_segments[idx] if idx < len(self._shm_segments) else None
if name is None:
# Shipping shm_segment=None would read as "spilled to a file" at
# the consumer, which then looks for a file nobody wrote -- far
# harder to trace than failing here.
raise ValueError(
f"set_shm_placement: segment {idx} was never "
f"registered via register_shm_segment"
)
return name
[docs]
def get_info(self, uuid: int) -> TensorPointerInfo | None:
return self._tensor_info.get(uuid)
[docs]
def forget_tensor(self, uuid: int):
self._ref_info.pop(uuid, None)
self._tensor_info.pop(uuid, None)
[docs]
def increment_ref(self, uuid: int, n: int = 1):
info = self._ref_info.get(uuid)
if info is None:
return
assert n >= 0, f"Tried to increment tensor {uuid} reference by {n}"
info.ref_cnt += n
[docs]
def dereference(self, uuid: int, n: int = 1):
info = self._ref_info.get(uuid)
if info is None:
return
info.ref_cnt -= n
def _drop_refs(
self, refs: Iterable[tuple[int, int]], cleanup: bool,
) -> tuple[list[int], list[bool]]:
"""One record lookup per uuid, where the generic version above pays
one per question it asks."""
collectable: list[int] = []
registered: list[bool] = []
for uuid, n in refs:
info = self._ref_info.get(uuid)
if info is None:
continue
info.ref_cnt -= n
if info.ref_cnt > 0 or info.persist:
continue
collectable.append(uuid)
registered.append(info.mem_registered)
if cleanup:
for uuid in collectable:
self._ref_info.pop(uuid, None)
self._tensor_info.pop(uuid, None)
return collectable, registered
[docs]
def set_persist(self, uuid: int, persist: bool):
info = self._ref_info.get(uuid)
if info is not None:
info.persist = persist
[docs]
def set_mem_registered(self, uuid: int, mem_registered: bool):
info = self._ref_info.get(uuid)
if info is not None:
info.mem_registered = mem_registered
[docs]
def is_registered(self, uuid: int) -> bool:
info = self._ref_info.get(uuid)
return info is not None and info.mem_registered
[docs]
def can_gc(self, uuid: int) -> bool:
info = self._ref_info.get(uuid)
return info is not None and info.ref_cnt <= 0 and not info.persist
def _dtype_name(dtype: torch.dtype) -> str:
"""Same short name the wire codec uses, so there is one mapping."""
return str(dtype).removeprefix("torch.")
def _dtype_from_name(name: str) -> torch.dtype:
return getattr(torch, name)
def _to_rust(info: TensorPointerInfo) -> dict:
return {
"dims": list(info.dims),
"dtype": _dtype_name(info.dtype),
"nbytes": info.nbytes,
"address": info.address,
"stride": list(info.stride),
"uuid": info.uuid,
"source_session_id": info.source_session_id,
"source_entity": info.source_entity,
"offset": info.offset,
"source_tp_size": info.source_tp_size,
"source_tp_rank": info.source_tp_rank,
"shm_segment": info.shm_segment,
"shm_offset": info.shm_offset,
"source_node_name": info._source_node_name,
"source_graph_walk": info._source_graph_walk,
}
def _from_rust(out) -> TensorPointerInfo:
return TensorPointerInfo(
# tuple(), like stride below: Rust hands back a list, but the Python
# bookkeeper stores what the producer built -- a torch.Size, which is
# a tuple subclass. A list never compares equal to either, so leaving
# it would make the same descriptor unequal across backends.
dims=tuple(out.dims),
dtype=_dtype_from_name(out.dtype),
nbytes=out.nbytes,
address=out.address,
stride=tuple(out.stride),
uuid=out.uuid,
source_session_id=out.source_session_id,
source_entity=out.source_entity,
offset=out.offset,
source_tp_size=out.source_tp_size,
source_tp_rank=out.source_tp_rank,
shm_segment=out.shm_segment,
shm_offset=out.shm_offset,
_source_node_name=out.source_node_name,
_source_graph_walk=out.source_graph_walk,
)
[docs]
class RustTensorBookkeeping(TensorBookkeeping):
"""Every method forwards; the batched ones go over in one call.
A descriptor handed in is COPIED into Rust, unlike the Python backend which
keeps the caller's object. Anything relying on seeing a later in-place edit
(``register_for_send`` stamping ``shm_segment``) has to write it back
(``set_shm_placement``).
"""
def __init__(self):
# Imported here, not at module scope: tensor_store is imported by
# effectively everything, and a top-level import would make the whole
# package unimportable wherever the extension is not built. Same
# pattern as arena.py.
from mstar_rust import TensorBookkeeping as _RustBookkeeping
self._rust = _RustBookkeeping()
# -- descriptors --------------------------------------------------------
[docs]
def put_tensor(self, uuid: int, info: TensorPointerInfo):
self._rust.put_tensor(uuid, _to_rust(info))
[docs]
def put_tensor_batch(
self, uuids: list[int], infos: list[TensorPointerInfo]
):
self._rust.put_tensor_batch(uuids, [_to_rust(i) for i in infos])
@property
def has_put_tensor_batch_columns(self):
return True
[docs]
def put_tensor_batch_columns(
self, infos: ColumnarTensorInfo
):
"""Store a batch already marshalled as columns of primitives.
``_to_rust`` builds a 15-key dict per tensor and pyo3 then allocates a
String per string field per tensor, which is where storing a batch
actually spends its time -- batching the *call* alone measured zero.
Here the caller has filled the columns as it minted, so no
``TensorPointerInfo`` is built to be torn apart again, and the fields
that are invariant across one node's output batch cross and intern
once rather than per tensor.
"""
self._rust.put_tensor_batch_columns(
infos.uuids, infos.addresses, infos.nbytes, infos.ndims,
infos.dims_flat, infos.stride_flat, infos.dtype_names,
infos.dtype_idx, infos.tp_size, infos.tp_rank,
infos.source_session_id, infos.source_entity,
infos.source_node_name, infos.source_graph_walk,
)
return True
[docs]
def register_shm_segment(self, index: int, name: str):
self._rust.register_shm_segment(index, name)
[docs]
def set_shm_placement(
self, uuids: list[int], segment_idxs: list[int],
offsets: list[int],
):
# One crossing, integers only -- no descriptor is rebuilt for Python,
# none is marshalled back, and no segment name is rendered per tensor
# for this side to intern straight back down to an id.
self._rust.set_shm_placement(uuids, segment_idxs, offsets)
[docs]
def get_info(self, uuid: int) -> TensorPointerInfo | None:
out = self._rust.get_info(uuid)
return None if out is None else _from_rust(out)
[docs]
def forget_tensor(self, uuid: int):
self._rust.forget_tensor(uuid)
# -- refcounts ----------------------------------------------------------
[docs]
def increment_ref(self, uuid: int, n: int = 1):
self._rust.increment_ref(uuid, n)
[docs]
def increment_ref_batch(self, uuids: list[int], counts: list[int]):
self._rust.increment_ref_batch(uuids, counts)
[docs]
def dereference(self, uuid: int, n: int = 1):
self._rust.dereference(uuid, n)
[docs]
def dereference_batch(
self, uuids: list[int], counts: list[int], cleanup: bool = False,
) -> tuple[list[int], list[bool]]:
return self._rust.dereference_batch(uuids, counts, cleanup)
# -- flags --------------------------------------------------------------
[docs]
def set_persist(self, uuid: int, persist: bool):
self._rust.set_persist(uuid, persist)
[docs]
def set_mem_registered(self, uuid: int, mem_registered: bool):
self._rust.set_mem_registered(uuid, mem_registered)
[docs]
def is_registered(self, uuid: int) -> bool:
return self._rust.is_registered(uuid)
# -- gc -----------------------------------------------------------------
[docs]
def can_gc(self, uuid: int) -> bool:
return self._rust.can_gc(uuid)
def _build_tensor_bookkeeping() -> TensorBookkeeping:
"""The Rust bookkeeper: the graph runtime holds a SHARE of this object, so
the two have to be the same implementation. ``PythonTensorBookkeeping`` is
the reference the tests check it against, not a fallback: serving needs the
extension.
Deliberately NOT gated on being in a worker, so the data worker takes the
Rust one too, and pays the copy of each descriptor into Rust with no graph
runtime behind it. Small next to its per-request work, and the api server
is a candidate for Rust itself; ``TensorStore(bookkeeping=...)`` is the
override if that stops being true.
"""
from mstar.graph.runtime.utils import require_rust_extension
require_rust_extension()
return RustTensorBookkeeping()
[docs]
class TensorStore:
"""The tensors themselves, plus which request owns each one.
Reference state lives in ``bookkeeping``; the delegating methods here exist
so callers have one object to talk to.
Constructing one with a Rust bookkeeper gives a ``RustTensorStore``, which
keeps the tensors in the bookkeeper too. That is decided here rather than
by the caller because the two must agree: the Rust graph runtime frees
tensors through the bookkeeper it shares, and can only do that for the
ones it holds.
"""
def __new__(cls, bookkeeping: TensorBookkeeping | None = None):
if bookkeeping is None:
bookkeeping = _build_tensor_bookkeeping()
impl = cls
if cls is TensorStore and isinstance(bookkeeping, RustTensorBookkeeping):
impl = RustTensorStore
self = object.__new__(impl)
# Resolved here because it picks the class; __init__ keeps it.
self.bookkeeping = bookkeeping
return self
def __init__(self, bookkeeping: TensorBookkeeping | None = None):
del bookkeeping # resolved by __new__
# {UUID -> tensor}
self._tensors: dict[int, torch.Tensor] = {}
# {UUID -> producer's host copy}, for a ``needs_cpu_tensor`` transport
# to send from. Optional and never the only copy; the producer reuses
# its memory after the send, so nothing but the send may read it, and
# the worker drops them once its step's sends are done.
self._tensors_cpu: dict[int, torch.Tensor] = {}
# Only for teardown: which uuids a request is responsible for, and the
# reverse so a single removal does not scan every request. A sliced
# tensor can outlive its producer's entry (_slice_existing_tensor mints
# a new uuid), so ownership is not derivable from the uuid alone.
self._rid_to_uuids: dict[Rid, set[int]] = {}
self._uuid_to_rid: dict[int, Rid] = {}
# Uuids a batched dereference already dropped from the bookkeeper. The
# caller still runs its own per-uuid teardown afterwards, and that ends
# in ``remove_tensor``; without this it would cross again to forget a
# record that is already gone.
self._forgotten: set[int] = set()
#: Whether a batched dereference with ``cleanup`` frees tensors itself and
#: reports only those that need the transport's teardown (``RustTensorStore``),
#: rather than reporting every one it took to zero.
frees_in_place: bool = False
# -- tensors ------------------------------------------------------------
[docs]
def get_tensor(self, uuid: int) -> torch.Tensor:
return self._tensors[uuid]
[docs]
def get_tensors(self, uuids: list[int]) -> list[torch.Tensor | None]:
"""``get_tensor`` over a column, None for a uuid not held."""
get = self._tensors.get
return [get(u) for u in uuids]
[docs]
def get_cpu_tensor(self, uuid: int) -> torch.Tensor | None:
"""The host copy stored alongside ``uuid``, if the producer gave one."""
return self._tensors_cpu.get(uuid)
[docs]
def drop_cpu_tensors(self) -> None:
"""Forget every host copy. A tensor sent after this is read from its
own memory."""
self._tensors_cpu.clear()
[docs]
def put_tensor(
self, request_id: Rid, uuid: int,
tensor: torch.Tensor,
info: TensorPointerInfo,
cpu_tensor: torch.Tensor | None = None,
):
self._tensors[uuid] = tensor
if cpu_tensor is not None:
self._tensors_cpu[uuid] = cpu_tensor
self._rid_to_uuids.setdefault(request_id, set()).add(uuid)
self._uuid_to_rid[uuid] = request_id
self.bookkeeping.put_tensor(uuid, info)
@property
def has_put_tensor_batch_columns(self) -> bool:
"""Whether the caller should marshal into ``ColumnarTensorInfo``.
The manager asks before it starts minting, because the two forms are
built differently -- columnar fills its columns as it goes, where the
other materialises a ``TensorPointerInfo`` per tensor.
"""
return self.bookkeeping.has_put_tensor_batch_columns
[docs]
def put_tensor_batch_multi(
self, request_ids: list[Rid], uuids: list[int],
tensors: list[torch.Tensor], infos: list[TensorPointerInfo],
cpu_tensors: list[torch.Tensor | None] | None = None,
):
"""``put_tensor_batch`` spanning requests: one bookkeeping call for a
whole output batch rather than one per request.
The maps below are plain dicts, so keeping them in a Python loop costs
nothing; it is ``bookkeeping.put_tensor_batch`` that is a Rust boundary
crossing, and taking every request at once collapses it to one.
"""
self._own(request_ids, uuids, tensors, cpu_tensors)
self.bookkeeping.put_tensor_batch(uuids, infos)
[docs]
def put_tensor_batch_columns(
self, request_ids: list[Rid], tensors: list[torch.Tensor],
columns: ColumnarTensorInfo,
cpu_tensors: list[torch.Tensor | None] | None = None,
):
"""``put_tensor_batch_multi`` for a backend that marshals per tensor.
Takes the columns the caller filled while minting instead of a
descriptor per tensor. ``columns.uuids`` is the same order as
``tensors``, which is what keeps the ownership maps aligned.
"""
self._own(request_ids, columns.uuids, tensors, cpu_tensors)
self.bookkeeping.put_tensor_batch_columns(columns)
def _own(
self, request_ids: list[Rid], uuids: list[int], tensors: list[torch.Tensor],
cpu_tensors: list[torch.Tensor | None] | None = None,
):
"""Record which request owns each tensor. Pure Python dicts, so this
stays a loop -- only the bookkeeping call crosses into Rust.
``cpu_tensors``, when given, is index-parallel to ``tensors``."""
if len(request_ids) != len(uuids) or len(uuids) != len(tensors):
raise ValueError("request_ids, uuids and tensors must be parallel")
# two of the three maps take the batch in one update each; only the
# per-request set stays a loop
self._tensors.update(zip(uuids, tensors, strict=True))
self._uuid_to_rid.update(zip(uuids, request_ids, strict=True))
owned = self._rid_to_uuids
for request_id, uuid in zip(request_ids, uuids, strict=True):
owned.setdefault(request_id, set()).add(uuid)
if cpu_tensors is not None:
for uuid, cpu_tensor in zip(uuids, cpu_tensors, strict=True):
if cpu_tensor is not None:
self._tensors_cpu[uuid] = cpu_tensor
[docs]
def check_uuid_presence(self, uuid: int) -> bool:
return uuid in self._tensors
[docs]
def remove_tensor(self, uuid: int):
forgotten = uuid in self._forgotten
self._forgotten.discard(uuid)
self._tensors_cpu.pop(uuid, None)
if self._tensors.pop(uuid, None) is None:
return
if not forgotten:
self.bookkeeping.forget_tensor(uuid)
request_id = self._uuid_to_rid.pop(uuid, None)
if request_id is not None:
owned = self._rid_to_uuids.get(request_id)
if owned is not None:
owned.discard(uuid)
if not owned:
del self._rid_to_uuids[request_id]
[docs]
def get_all_uuids(self, request_id: Rid) -> list[int]:
return list(self._rid_to_uuids.get(request_id, ()))
[docs]
def mark_teardown(self, uuids: list[int]):
"""The caller keeps per-uuid state for these that a release must reach
(see ``RustTensorStore``). Nothing to do here: every collectable uuid
is reported."""
# -- bookkeeping passthrough -------------------------------------------
[docs]
def can_gc(self, uuid: int) -> bool:
return self.bookkeeping.can_gc(uuid)
[docs]
def is_registered(self, uuid: int) -> bool:
return self.bookkeeping.is_registered(uuid)
[docs]
def get_info(self, uuid: int) -> TensorPointerInfo | None:
return self.bookkeeping.get_info(uuid)
[docs]
def increment_ref(self, uuid: int, n: int = 1):
self.bookkeeping.increment_ref(uuid, n)
[docs]
def register_shm_segment(self, index: int, name: str):
self.bookkeeping.register_shm_segment(index, name)
[docs]
def set_shm_placement(
self, uuids: list[int], segment_idxs: list[int],
offsets: list[int],
):
self.bookkeeping.set_shm_placement(uuids, segment_idxs, offsets)
[docs]
def increment_ref_batch(self, uuids: list[int], counts: list[int]):
self.bookkeeping.increment_ref_batch(uuids, counts)
[docs]
def dereference_batch(
self, uuids: list[int], counts: list[int], cleanup: bool = False,
) -> tuple[list[int], list[bool]]:
"""``dereference_batch_uniform`` where the count differs per uuid --
an ack that covers several reads of the same tensor, say."""
return self._collected(
self.bookkeeping.dereference_batch(uuids, counts, cleanup), cleanup
)
[docs]
def dereference(self, uuid: int, n: int = 1):
self.bookkeeping.dereference(uuid, n)
def _collected(
self, result: tuple[list[int], list[bool]], cleanup: bool,
) -> tuple[list[int], list[bool]]:
if cleanup:
self.mark_forgotten(result[0])
return result
[docs]
def mark_forgotten(self, uuids: list[int]):
"""These records are already gone from the bookkeeper, so the teardown
that follows must not cross again to drop them. For a caller that went
to the bookkeeper directly -- the Rust runtime releasing a node's
consumed inputs holds a share of it and never comes through here."""
self._forgotten.update(uuids)
[docs]
class RustTensorStore(TensorStore):
"""``TensorStore`` whose tensors and request ownership live in the Rust
bookkeeper, next to the refcounts.
That is what makes a release cost nothing per uuid on the Python side: a
batched dereference with ``cleanup`` -- or the Rust graph runtime freeing
a node's consumed inputs -- drops a tensor that needs nothing from the
transport in the same Rust pass that took it to zero, and reports only the
rest. "Needs something" is registered memory (``mem_registered``: an arena
slot, a per-uuid file, pinned RDMA memory) or per-uuid state the manager
keeps and flags with ``mark_teardown``. A reported tensor stays held until
the teardown's ``remove_tensor``, so the transport can still read it.
Built by ``TensorStore(bookkeeping)`` for a ``RustTensorBookkeeping``.
"""
frees_in_place = True
def __init__(self, bookkeeping: TensorBookkeeping | None = None):
del bookkeeping # resolved by __new__
self._rust = self.bookkeeping._rust
[docs]
def get_tensor(self, uuid: int) -> torch.Tensor:
"""KeyError when not held, as the dict lookup it replaces."""
return self._rust.get_tensor(uuid)
[docs]
def get_tensors(self, uuids: list[int]) -> list[torch.Tensor | None]:
return self._rust.get_tensors(uuids)
[docs]
def get_cpu_tensor(self, uuid: int) -> torch.Tensor | None:
return self._rust.get_cpu_tensor(uuid)
[docs]
def check_uuid_presence(self, uuid: int) -> bool:
return self._rust.has_tensor(uuid)
[docs]
def drop_cpu_tensors(self) -> None:
"""Forget every host copy stored since the last call; the copies live
in the Rust store with the tensors."""
self._rust.drop_cpu_tensors()
[docs]
def remove_tensor(self, uuid: int):
"""The object, its ownership and its record, in one crossing. A uuid
not held is left alone, record included."""
self._rust.remove_tensor(uuid)
[docs]
def put_tensor(
self, request_id: Rid, uuid: int,
tensor: torch.Tensor,
info: TensorPointerInfo,
cpu_tensor: torch.Tensor | None = None,
):
self._rust.put_stored(request_id, uuid, tensor, _to_rust(info), cpu_tensor)
@property
def has_put_tensor_batch_columns(self) -> bool:
return True
[docs]
def put_tensor_batch_multi(
self, request_ids: list[Rid], uuids: list[int],
tensors: list[torch.Tensor], infos: list[TensorPointerInfo],
cpu_tensors: list[torch.Tensor | None] | None = None,
):
self._rust.put_tensor_batch(
uuids, [_to_rust(i) for i in infos], request_ids, tensors, cpu_tensors,
)
[docs]
def put_tensor_batch_columns(
self, request_ids: list[Rid], tensors: list[torch.Tensor],
columns: ColumnarTensorInfo,
cpu_tensors: list[torch.Tensor | None] | None = None,
):
"""The objects cross with the columns, so a stored batch is one call
with no per-tensor Python."""
c = columns
self._rust.put_tensor_batch_columns(
c.uuids, c.addresses, c.nbytes, c.ndims, c.dims_flat,
c.stride_flat, c.dtype_names, c.dtype_idx, c.tp_size, c.tp_rank,
c.source_session_id, c.source_entity, c.source_node_name,
c.source_graph_walk, request_ids, tensors, cpu_tensors,
)
[docs]
def get_all_uuids(self, request_id: Rid) -> list[int]:
return self._rust.rid_uuids(request_id)
[docs]
def mark_teardown(self, uuids: list[int]):
if uuids:
self._rust.mark_teardown(uuids)
[docs]
def mark_forgotten(self, uuids: list[int]):
"""Nothing to track: ``remove_tensor`` drops the record with the
object in the same crossing, and dropping a missing one is a no-op."""
[docs]
def release_request(
self, request_id: Rid, force: bool,
) -> tuple[list[int], list[bool], list[int]]:
"""Request teardown in one crossing: every collectable uuid the request
owns (every one, under ``force``) is released as a batched dereference
releases it. Returns the uuids still needing the transport's teardown
with their ``mem_registered`` flags, and the deferred ones."""
return self._rust.release_request(request_id, force)
[docs]
def stored_counts(self) -> tuple[int, int]:
"""(tensors held, requests owning any) -- for tests."""
return self._rust.stored_counts()