tensormesh.nn¶
BufferUtils¶
- class BufferDict(data: Dict[str, Tensor] | None = None)[source]¶
Bases:
ModuleModule-aware dict of tensors stored as buffers (non-trainable).
Use it whenever you need a dict of plain tensors attached to a
Module— for example integer connectivity[n_element, n_basis], vector point data[n_point, D], or precomputed quadrature tables — keyed by element type or field name. Tensors registered throughBufferDictfollow the parent module under.to(device)/.float()/.cuda(), appear instate_dict(), and do not require gradients.Two behaviours go beyond a plain
register_buffer():Keys that aren’t valid Python identifiers (anything not matching
^[a-zA-Z_][a-zA-Z0-9_]*$, e.g."123x"or names with dashes) are stored in an internalOrderedDict(_data) instead of being registered as buffers — Python’sregister_bufferrejects such names. Their tensors are still moved by_apply(), so.to(device)and friends still work; they just don’t appear instate_dict().Buffer ↔ parameter promotion:
as_parameter()turns a stored buffer into a trainableParameterin place, andas_buffer()reverses it. This lets the same container serve both pure-FEM workflows (everything as buffers) and ML workflows where some fields need gradients (e.g. learnable material parameters).
- Parameters:
data (Dict[str, Tensor], optional) – Initial key→tensor mapping. Keys matching
^[a-zA-Z_][a-zA-Z0-9_]*$are registered as buffers viaregister_buffer(); the rest are kept in the fallback_datadict. Default: empty.
Examples
>>> import torch >>> from tensormesh.nn import BufferDict >>> cells = BufferDict({ ... "triangle": torch.zeros(10, 3, dtype=torch.long), ... "quad": torch.zeros(5, 4, dtype=torch.long), ... }) >>> cells.to("cuda") # both tensors move to GPU >>> list(cells.keys()) ['triangle', 'quad'] >>> cells["triangle"].device.type 'cuda'
- __init__(data: Dict[str, Tensor] | None = None)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- as_parameter(key: str)[source]¶
Promote the buffer at
keyto a trainabletorch.nn.Parameterin place.After this call,
self[key]is a Parameter (gradient-tracking, will appear inparameters()); the same key must currently live in_buffersor this will raiseKeyError. Reverse withas_buffer().
- as_buffer(key: str)[source]¶
Demote the parameter at
keyback to a (non-trainable) buffer in place.Inverse of
as_parameter(). The same key must currently live in_parameters. The underlying storage is shared (viadetach()); the result no longer requires grad.
- keys() Iterable[str][source]¶
Iterate over keys across all three backing stores (buffers, parameters, fallback).
- items() Iterable[Tuple[str, Tensor]][source]¶
Iterate over
(key, tensor)pairs across all three backing stores.
- property dtype¶
torch.dtypeof the first registered buffer (representative).
- property device¶
torch.deviceof the first registered buffer (representative).
- to_dict() Mapping[str, Tensor | Module][source]¶
Return a plain
dictview of the contents (no module wiring).
- clone() BufferDict[source]¶
Return a deep copy: every stored tensor is cloned, then wrapped in a fresh
BufferDict.
- class BufferList(data: Iterable[Tensor] | None = None)[source]¶
Bases:
ModuleModule-aware list of tensors stored as buffers (non-trainable).
The list analogue of
BufferDict. Same motivation: PyTorch shipstorch.nn.ParameterListandtorch.nn.ModuleListbut no list of buffers.BufferListprovides one — tensors are stored under stringified indices viaregister_buffer(), so they follow.to(device)and appear instate_dict().Used inside
FacetAssemblerto hold the per-element-type boundary-facet masks — for mixed-facet elements like prisms and pyramids, each element type contributes more than one mask tensor (e.g. a triangle-facet mask and a quad-facet mask), so a list of buffers per key is the natural shape.Beyond standard list indexing (
int,slice),__getitem__()also accepts a 1Dtorch.Tensorof indices and returns a freshBufferList— convenient for gather-style operations.Like
BufferDict, individual entries can be promoted to trainable parameters viaas_parameter()(and demoted back viaas_buffer()).- Parameters:
data (Iterable[Tensor], optional) – Initial tensors. Default: empty.
Examples
>>> import torch >>> from tensormesh.nn import BufferList >>> bl = BufferList([torch.zeros(3), torch.zeros(4)]) >>> bl.append(torch.zeros(5)) >>> len(bl) 3 >>> bl.to("cuda") # all entries move to GPU >>> bl[0].device.type 'cuda'
- __init__(data: Iterable[Tensor] | None = None)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- as_parameter(key: int)[source]¶
Promote the buffer at index
keyto a trainabletorch.nn.Parameterin place.
- as_buffer(key: int)[source]¶
Demote the parameter at index
keyback to a (non-trainable) buffer in place.Storage is shared via
detach(); the result no longer requires grad.
- insert(index: int, value: Tensor)[source]¶
Insert
valueatindex, shifting subsequent entries (and their backing keys) right by one.
- pop(index: int = -1) Tensor[source]¶
Remove and return the tensor at
index(default: last), shifting subsequent entries left by one.
- property dtype¶
torch.dtypeof the first entry (representative).
- property device¶
torch.deviceof the first entry (representative).
- to_list() List[Tensor][source]¶
Return a plain Python list of the contained tensors (no module wiring).
- clone() BufferList[source]¶
Return a deep copy: every stored tensor is cloned, then wrapped in a fresh
BufferList.