nvalchemi.data.Batch#
- class nvalchemi.data.Batch(*, device, storage=None, keys=None)[source]#
Graph-aware batch built on
MultiLevelStorage.The three built-in attribute groups are:
"atoms"(SegmentedLevelStorage) – node-level tensors"edges"(SegmentedLevelStorage) – edge-level tensors"system"(UniformLevelStorage) – graph-level tensors
A
LevelSchemacan register additional uniform, segmented, and product levels.batch_idx,batch_ptr,num_nodes_list, andnum_edges_listremain aliases for the built-in atom and edge levels.- Parameters:
device (torch.device | str)
storage (MultiLevelStorage | None)
keys (dict[str, set[str]] | None)
- device#
Device of the underlying storage. When a storage is supplied it decides this value, and otherwise a bare
cudais resolved to the GPU the storage’s tensors reached, so batch-level allocations such asedge_ptrand the index tensor ofindex_select()never land on a different device than the data they are built for. Constructing a batch around a storage held on another indexed device raisesValueError.- Type:
- keys#
Level categorisation:
{"node": ..., "edge": ..., "system": ...}.- Type:
dict[str, set[str]] | None
- add_key(key, values, level='node', overwrite=False, *, dtype=None, payload_shape=None)[source]#
Add a new key-value pair to the batch.
Registered custom level names are accepted in addition to the built-in aliases. An unrecognized level retains the legacy behavior of assigning the key to the atom level. A batch carrying no system-level field gains its system group when level is
"system", since one row per graph needs no cardinality beyond the batch’s own. Empty zero-graph batches may materialize a field by supplying its dtype and payload_shape.- Parameters:
key (str) – Name of the new attribute.
values (list[Tensor]) – One value per graph.
level (str) – Built-in alias or registered custom level name.
overwrite (bool) – If
True, overwrite existing keys.dtype (torch.dtype, optional) – Expected field dtype. Required when values is empty; otherwise, when supplied, it must match every value.
payload_shape (tuple[int, ...], optional) – Shape after the dimensions owned by the level: the graph axis for uniform levels, one cardinality axis for segmented levels, or two parent-cardinality axes for product levels. Required when values is empty; otherwise, when supplied, it must match every value.
- Raises:
ValueError – If key exists and overwrite is
False, if the number of values does not match the batch size, shape, dtype, or level cardinality, if empty-field metadata is incomplete or invalid, or if the batch has no atom or edge group to add a field at that level to, or if key is"group_idx".TypeError – If level is not a string, a value is not a tensor, or an explicit dtype or payload shape has the wrong type.
- Return type:
None
- add_level(name, *, segmented)[source]#
Register an ordinary uniform or segmented level on this batch.
Registration changes schema metadata only. It does not allocate a storage group or create tensor fields.
add_levelis reserved for this public API during attribute-style access. A custom tensor field with the same name remains available asbatch["add_level"].- Parameters:
name (str) – Name of the level.
segmented (bool) – Whether the level has variable per-system cardinality.
- Return type:
None
- add_product_level(name, *, left, right)[source]#
Register an ordered product of two segmented levels on this batch.
Registration changes schema metadata only. It does not allocate a storage group or create tensor fields.
add_product_levelis reserved for this public API during attribute-style access. A custom tensor field with the same name remains available asbatch["add_product_level"].- Parameters:
name (str) – Name of the product level.
left (str) – Registered segmented level for the left entity axis.
right (str) – Registered segmented level for the right entity axis.
- Return type:
None
- append(other, *, missing_fields='drop', field_defaults=None)[source]#
Append another batch (in-place via concatenation).
If other is missing a group that this batch has (e.g. system-level data), this batch’s tensors in that group are extended with zeros so that the first dimension (num graphs) stays aligned.
With
missing_fields="fill", this batch keeps all of its fields: rows for appended graphs that lack a field are filled with zeros or supplied system-field defaults. Fields only other carries are dropped as with"drop". Zero-filled values are storage placeholders, not valid model outputs. Custom levels retain their strict schema compatibility requirements.Grouped batches may only be appended to other grouped batches. The appended batch’s local
group_idxvalues are rebased after the receiver’s existing groups. Appending a grouped and an ungrouped batch is rejected before either batch is modified.- Parameters:
other (Batch) – Batch to append. Must not share storage with self — use
batch.append(batch.clone())to double a batch.missing_fields ({"drop", "fill"}, optional) – Default
"drop"keeps shared fields within paired storage groups."fill"keeps every field of this batch without modifying other.field_defaults (mapping, optional) – System-field factories accepting
(num_graphs, device)and returning a tensor with one row per graph. Requires"fill". They fill this batch’s fields that other lacks; other missing fields use zeros. Fields this batch lacks are never added.
- Return type:
None
- append_data(data_list, exclude_keys=None)[source]#
Append individual
AtomicDataobjects to this batch.- Parameters:
data_list (list[AtomicData]) – Data objects to append.
exclude_keys (list[str], optional) – Keys to exclude.
- Raises:
ValueError – If data_list is empty or this batch has
group_idxmetadata.- Return type:
None
- property batch_size: int#
Alias for
num_graphs.
- clone(*, drop=())[source]#
Return a deep copy.
Overrides
DataMixin.clone()for performance.- Parameters:
drop (Iterable[str], optional) – Keys to leave out of the copy, at whichever level each is stored. A dropped key is never cloned, so a caller saves the clone of a field it would delete anyway. A key the batch does not carry is ignored. A level whose keys are all dropped keeps its cardinality. Default
()copies every key.- Return type:
- contiguous()[source]#
Ensure contiguous memory layout for all tensors.
- Returns:
For method chaining.
- Return type:
Self
- cuda(device=None, non_blocking=False)[source]#
Return a copy on CUDA.
- Parameters:
device (int | None)
non_blocking (bool)
- Return type:
- defrag(copied_mask=None)[source]#
Defrag this batch in-place by removing graphs that were put.
Drops graphs where
copied_mask[i]isTruefrom every materialized level, including fieldless segmented metadata. Payloads must use a buffer-kernel-supported dtype:bool,float32,float64,int32, orint64.- Parameters:
copied_mask (Tensor, optional) – (num_graphs,) bool; if None, uses stored value from last
put().- Returns:
For method chaining.
- Return type:
Self
- drop_level(name)[source]#
Remove a registered level’s storage group and every field it holds.
The level itself stays registered in the batch’s
LevelSchema; only its materialized storage goes away, which is the state a batch built without that level’s data is already in. Dropping a level that holds no storage is a no-op.- Parameters:
name (str) – Registered level name, for instance
"edges".- Raises:
KeyError – If name is not a registered level.
ValueError – If name is
"atoms"or"system", the two levels the batch derives its atom and graph counts from.
- Return type:
None
- property edge_ptr: Tensor#
Per-atom CSR pointer into the edge list (N+1,), int32.
Returns a tensor where
edge_ptr[i] : edge_ptr[i+1]is the slice of edge rows inneighbor_listthat belong to atomi(i.e. where atomiis the sender). Valid only after a COO-formatNeighborListHookhas populated the edges group.An all-zeros pointer of length
num_nodes + 1is returned when the edges group is absent or empty.
- classmethod empty(*, num_systems, num_nodes, num_edges, template=None, device='cpu', attr_map=None, level_capacities=None)[source]#
Construct an empty batch with pre-allocated capacity (zero graphs, fixed storage).
Storage tensors are allocated with the given capacities; no graphs are stored initially (
num_graphs == 0). Useput()to copy graphs into the buffer; each put appends after the graphs already stored.- Parameters:
num_systems (int) – Maximum number of systems (graphs) the buffer can hold.
num_nodes (int) – Total node (atom) capacity across all graphs.
num_edges (int) – Total edge capacity across all graphs.
template (AtomicData or Batch, optional) – Template for attribute keys and per-key shapes/dtypes. If
None, a minimalAtomicDatawithpositions,atomic_numbers, andenergyis used.device (torch.device or str, optional) – Device for allocated tensors.
attr_map (LevelSchema, optional) – Attribute registry; used when template is provided.
level_capacities (dict[str, int], optional) – Explicit capacities for payload-bearing custom segmented and product levels. Custom uniform levels use
num_systems; fieldless segmented levels need no entry.
- Returns:
Batch with
num_graphs == 0and capacity for the given sizes.- Return type:
- Raises:
TypeError – If a custom capacity is not an integer.
ValueError – If a capacity is negative, names an unknown or built-in level, or is missing for a payload-bearing custom segmented or product level in the template.
- classmethod empty_like(batch, *, device=None)[source]#
Create an empty batch with the schema and capacities of batch.
- Parameters:
batch (Batch) – Template batch for attribute keys and dtypes.
device (torch.device | str, optional) – Device for the new batch. Defaults to
batch.device.
- Returns:
A zero-graph batch preserving every materialized level and its graph-slot or payload capacity.
- Return type:
- extend_level_schema(schema)[source]#
Add schema declarations atomically without materializing storage.
Existing declarations must be compatible. New ordinary levels, product levels, field ownership, and declared dtypes are copied into one batch-owned schema only after the complete merge validates.
extend_level_schemais reserved for this public API during attribute-style access. A custom tensor field with the same name remains available asbatch["extend_level_schema"].- Parameters:
schema (LevelSchema) – Schema declarations to add.
- Raises:
TypeError – If schema is not a
LevelSchema.ValueError – If a declaration conflicts with the batch’s existing schema.
- Return type:
None
- classmethod from_data_list(data_list, device=None, skip_validation=False, attr_map=None, exclude_keys=None, field_levels=None)[source]#
Construct a batch from a list of
AtomicDataobjects.- Parameters:
data_list (list[AtomicData]) – Individual graphs to batch.
device (torch.device | str, optional) – Target device. Inferred from data_list if
None.skip_validation (bool) – If
True, skip shape validation for speed.attr_map (LevelSchema, optional) – Attribute registry. If omitted, reuse schema metadata carried by an input object or fall back to
LevelSchema().exclude_keys (list[str], optional) – Keys to exclude from batching.
field_levels (dict[str, str], optional) – Explicit per-field level map. Values may be built-in aliases such as
"atom","edge", and"system", or names registered in attr_map. Used to classify keys absent from the data class key sets.
- Return type:
- classmethod from_raw_dicts(data_list, device=None, attr_map=None, exclude_keys=None, field_levels=None)[source]#
Construct a batch directly from raw tensor dictionaries.
Bypasses
AtomicDataconstruction and Pydantic validation entirely, usingAtomicData._default_*_keysfor level classification. Keys not found in the default key sets are classified using field_levels (e.g. fromReader.field_levels). This is significantly faster when the data is already known to be well-formed (e.g. read from a validated Zarr store).- Parameters:
data_list (list[dict[str, Tensor]]) – Per-sample tensor dictionaries.
device (torch.device | str, optional) – Target device. Inferred from first dict if
None.attr_map (LevelSchema, optional) – Attribute registry. Defaults to
LevelSchema().exclude_keys (list[str], optional) – Keys to exclude from batching.
field_levels (dict[str, str], optional) – Explicit per-field level map. Values may be built-in aliases such as
"atom","edge", and"system", or names registered in attr_map. Used to classify keys absent from the default key sets.
- Return type:
- get_data(idx)[source]#
Reconstruct the
AtomicDataobject at position idx.Edge-index offsets applied during batching are automatically undone.
- Parameters:
idx (int) – Graph index (supports negative indexing).
- Return type:
- get_level_schema()[source]#
Return an independent copy of this batch’s level schema.
The returned schema may be inspected or modified without changing the batch. Use
extend_level_schema()to add declarations back to an existing batch.get_level_schemais reserved for this public API during attribute-style access. A custom tensor field with the same name remains available asbatch["get_level_schema"].- Returns:
Defensive copy of the batch-owned schema.
- Return type:
- property group_layout: GroupLayout#
Derived group-cardinality layout, built lazily from
group_idx.
- index_select(idx, *, drop=())[source]#
Select a subset of graphs by index.
Operates directly on concatenated tensors via segment selection – no per-graph
AtomicDatareconstruction.- Parameters:
idx (int, slice, Tensor, list[int], np.ndarray, or Sequence[int]) – Graph-level index specification.
drop (Iterable[str], optional) – Keys to leave out of the selection, at whichever level each is stored. A dropped key is never copied, so a caller saves the copy of a field it would delete anyway. A key the batch does not carry is ignored. A level whose keys are all dropped keeps its cardinality. Default
()copies every key.
- Return type:
- classmethod irecv(src, device, *, template=None, tag=0, group=None)[source]#
Non-blocking receive of a batch from src.
Posts non-blocking receives for the metadata header, then returns a
_BatchRecvHandlewhose.wait()blocks until all data arrives and reconstructs aBatchusing template.- Parameters:
src (int) – Source rank.
device (torch.device | str) – Device to receive tensors onto.
template (Batch, optional) – Template batch providing attribute keys, dtypes, group structure, and custom level definitions. Required when receiving custom levels and for the first structured receive. Its materialized levels, field order, dtypes, and trailing shapes must match the sender; callers may cache it for subsequent calls. No custom layout negotiation occurs on the wire.
tag (int) – Base message tag.
group (ProcessGroup, optional) – Process group.
- Returns:
Handle whose
.wait()returns the receivedBatch.- Return type:
_BatchRecvHandle
- isend(dst, *, tag=0, group=None)[source]#
Non-blocking send of this batch to dst.
Transmits the fixed metadata header and built-in level data first. Materialized custom level segment lengths and tensor payloads follow in schema order. A zero-graph batch sends only the metadata header. The wire format does not negotiate custom layouts; the receiver must provide a matching custom template as a caller precondition.
- Parameters:
dst (int) – Destination rank.
tag (int) – Base message tag. Incremented deterministically per group.
group (ProcessGroup, optional) – Process group.
Noneuses the default group.
- Returns:
Handle whose
.wait()blocks until all sends complete.- Return type:
_BatchSendHandle
- property level_keys: dict[str, set[str]]#
Return fields for every level whose cardinality is resolvable.
The mapping follows the effective
LevelSchemaorder. Empty sets represent registered uniform levels, fieldless built-in levels, or product levels whose segmented parents provide their cardinality. Unmaterialized custom segmented levels are omitted because their cardinality is unresolved.
- level_ptr(name)[source]#
Return the cumulative per-graph pointer for a registered level.
Materialized segmented and product levels expose their storage pointers. Uniform levels have one row per graph and therefore use
arange(B + 1). Missing built-inatomsandedgeslevels are treated as fieldless zero-cardinality levels. An unmaterialized product can be resolved from its two segmented parent pointers.- Parameters:
name (str) – Registered level name.
- Returns:
Cumulative element counts with length
num_graphs + 1andtorch.int32dtype.- Return type:
- Raises:
OverflowError – If the level’s graph count, per-graph product cardinality, or cumulative cardinality exceeds the signed int32 pointer range.
KeyError – If name is not registered or its segmented cardinality cannot be resolved from materialized data or resolved product parents.
- property max_num_nodes: int#
Maximum node count in any graph.
- model_dump(**kwargs)[source]#
Serialize the batch into a flat dictionary.
Collects all tensors from the underlying
MultiLevelStoragegroups, plus metadata fields (device,keys,batch_idx,batch_ptr,num_nodes_list,num_edges_list,num_graphs).- Return type:
dict[str, Any]
- Parameters:
kwargs (Any)
- property num_edges: int#
Total number of edges across all graphs.
- property num_edges_list: list[int]#
Per-graph edge counts as a Python list.
- property num_graphs: int#
Number of graphs in the batch.
- property num_nodes: int#
Total number of nodes across all graphs.
- property num_nodes_list: list[int]#
Per-graph node counts as a Python list.
- pin_memory()[source]#
Pin all tensors to page-locked memory.
- Returns:
For method chaining.
- Return type:
Self
- pop_level(name)[source]#
Detach a registered level’s storage group and return it.
The returned group is the live object, not a copy, so the fields it holds leave the batch with it and come back unchanged through
set_level().- Parameters:
name (str) – Registered level name, for instance
"edges".- Returns:
The detached group, or
Noneif the level held no storage.- Return type:
UniformLevelStorage or SegmentedLevelStorage or None
- Raises:
KeyError – If name is not a registered level.
ValueError – If name is
"atoms"or"system", the two levels the batch derives its atom and graph counts from.
Examples
>>> saved = batch.pop_level("edges") >>> batch.set_level("edges", saved)
- put(src_batch, mask, *, copied_mask=None, dest_mask=None)[source]#
Put graphs where mask[i] is True from src_batch into this batch (buffer).
Computes a fit mask for every materialized level and copies only graphs that fit in all levels. Built-in and custom uniform payloads may use
bool,float32,float64,int32, orint64. Materialized custom segmented and product payloads must usetorch.float32. If copied_mask is provided, it is updated with the combined copy mask fordefrag().- Parameters:
src_batch (Batch) – Source batch. Custom schemas and materialized custom groups must match the destination buffer.
mask (Tensor) – (num_graphs,) bool, True = consider copying this graph.
copied_mask (Tensor, optional) – (num_graphs,) bool; if provided, modified in place with the actual copy mask (fit in all levels). If None, stored on src_batch.
dest_mask (Tensor, optional) –
Deprecated and ignored; occupancy is derived from
num_graphs.Deprecated since version 0.3.0: Omit
dest_mask; it will be removed in the release after 0.3.0.
- Raises:
ValueError – If either batch has
group_idxmetadata (because graph-level insertion cannot preserve whole groups), or if src_batch is on another device than this batch, or if a mask’s length does not matchsrc_batch.num_graphs.- Warns:
DeprecationWarning – If dest_mask is passed. The argument is ignored.
- Return type:
None
Notes
Graphs are appended after the first
num_graphsslots at every level, so per-graph and per-atom data stay aligned. Each copied graph’sneighbor_listis re-offset to where its atoms land in this batch.The copy runs as a Warp kernel over both batches’ raw pointers, so a source on another device is rejected rather than moved: moving it would hide a per-step host-device transfer inside what callers use as an in-place buffer write.
- classmethod recv(src, device, *, template=None, tag=0, group=None)[source]#
Blocking receive from src.
Equivalent to
cls.irecv(src, device, ...).wait().- Parameters:
src (int) – Source rank.
device (torch.device | str) – Device to receive tensors onto.
template (Batch, optional) – Template batch providing attribute keys, dtypes, group structure, and custom level definitions. Required when receiving custom levels and must match the sender’s materialized layout. This matching template is a caller precondition; no custom layout negotiation occurs on the wire.
tag (int) – Base message tag.
group (ProcessGroup, optional) – Process group.
- Return type:
- send(dst, *, tag=0, group=None)[source]#
Blocking send to dst.
Equivalent to
self.isend(dst, tag=tag, group=group).wait(). When custom levels are present, the receiver must supply a matching template; the wire format performs no custom layout negotiation.- Parameters:
dst (int) – Destination rank.
tag (int) – Base message tag.
group (ProcessGroup, optional) – Process group.
- Return type:
None
- set_group_layout(group_idx)[source]#
Store graph grouping metadata and immediately rebuild its layout.
Arbitrary integer labels are normalized by order of appearance to dense local group indices. Graphs belonging to one group must be contiguous.
- Parameters:
group_idx (torch.Tensor) – Integer group label for every graph, shape
[B].- Return type:
None
- set_level(name, storage)[source]#
Attach storage as the batch’s group for a registered level.
The group’s fields are registered against the batch’s schema, which every group then shares, and the group takes its schema-defined position in the batch’s level order. Any group already materialized for name is replaced.
- Parameters:
name (str) – Registered level name, for instance
"edges".storage (UniformLevelStorage or SegmentedLevelStorage) – Group to attach. Its length must be the batch’s graph count and its device the batch’s device.
- Raises:
KeyError – If name is not a registered level.
TypeError – If storage is not the storage class the level’s kind calls for.
ValueError – If storage spans a different number of graphs, lives on another device, or carries a field another level already owns.
- Return type:
None
See also
pop_levelDetach a level and return its storage.
- property system_capacity: int#
Maximum number of systems (graphs) this buffer can hold (e.g. from
empty()).
- to(device, dtype=None, non_blocking=False)[source]#
Move all tensors to device.
Overrides
DataMixin.to()for performance: delegates toMultiLevelStorage.to_device()instead of themodel_dump/map_structure/model_validateround-trip.- Parameters:
device (torch.device | str) – Target device. A bare
"cuda"is recorded as the CUDA device current at the time of the move, which is where the tensors land.dtype (torch.dtype, optional) – Ignored (present for API compatibility).
non_blocking (bool) – Whether tensor copies may be asynchronous when supported.
- Return type:
- to_data_list()[source]#
Reconstruct all individual
AtomicDataobjects.- Return type:
list[AtomicData]
- trim(copied_mask=None)[source]#
Remove marked graphs and return a new
Batchwith tight storage.Unlike
defrag(), which compacts data to the front of pre-allocated buffers while preserving their capacity (ideal for fixed-size GPU buffers that will be reused withput()),trimproduces a brand-newBatchwhose underlying storage tensors are sized to exactly fit the remaining graphs — no padding, no unused trailing slots.Use
defrag()when you need to keep the buffer alive for furtherput()/defrag()cycles (e.g. communication buffers). Usetrimwhen the batch will be consumed directly by a model or integrator and must have self-consistent tensor shapes across all storage groups.- Parameters:
copied_mask (Tensor, optional) –
(num_graphs,)boolean tensor whereTruemarks graphs to remove. If None, uses the_copied_maskstored by the most recentput().- Returns:
A new
Batchcontaining only the kept graphs with all tensors sized to exactly fit, or None if every graph was removed.- Return type:
Batch or None
- Raises:
ValueError – If no copied_mask is provided and no prior
put()has stored one.
See also
defragIn-place compaction that preserves buffer capacity.
- without_keys(*keys)[source]#
Hide keys from the batch for the duration of a block.
Each of keys the batch carries is removed on entry and put back on exit, at the level it came from and as the same tensor. Every one of keys the batch carries when the block ends, whether written inside it or not, is removed first, so a model that writes
node_embeddingsonto the batch leaves no trace of the write, and a tensor read inside the block outlives it, autograd graph included. A key the batch does not carry is ignored on entry. The tracked key sets inkeysare hidden and restored alongside.- Parameters:
*keys (str) – Field names to hide.
- Yields:
None – Control while the batch carries none of keys.
- Return type:
Iterator[None]
Examples
>>> with batch.without_keys("node_embeddings", "graph_embeddings"): ... model.compute_embeddings(batch) ... embeddings = batch["node_embeddings"] >>> "node_embeddings" in batch False
Notes
A hidden key is written back into the level group it was read from rather than through
__setitem__(), becausedeldrops a key from every level, after which__setitem__would route it by the attribute registry rather than by where the tensor was stored.
- zero()[source]#
Reset this batch to an empty-but-allocated state.
Zeros all leaf data tensors while preserving the allocated storage capacity. After calling
zero(),num_graphsreturns 0 butsystem_capacityremains unchanged. Group-label storage is retained, whilegroup_layoutdescribes zero occupied graphs and groups.This method is used to reset pre-allocated communication buffers (created via
empty()) between pipeline steps without reallocating memory.Notes
Modeled after
GPUBuffer.zero()innvalchemi.dynamics.sinks. Resets bookkeeping for bothUniformLevelStorage(_num_kept) andSegmentedLevelStorage(segment_lengths,_batch_ptr).Examples
>>> batch = Batch.empty(num_systems=10, num_nodes=100, num_edges=200) >>> batch.zero() >>> batch.num_graphs 0 >>> batch.system_capacity 10
- Return type:
None