"""Static condensation for applying Dirichlet boundary conditions.
This module provides :class:`Condenser`, which splits a global FEM system
.. math::
K\\, u = f
into an *inner* (free-DOF) sub-system
.. math::
K_{ii}\\, u_i = f_i - K_{io}\\, u_o,
solves it, then re-assembles the full solution from the inner solution plus
the prescribed boundary values :math:`u_o`.
"""
import copy
from typing import Optional, Tuple
import torch
import torch.nn as nn
from ..sparse import SparseMatrix
[docs]
class Condenser(nn.Module):
"""Static-condensation operator for Dirichlet boundary conditions.
Partitions a global system :math:`K u = f` into inner (free) DOFs and
outer (Dirichlet) DOFs and condenses the prescribed values into the
right-hand side:
.. math::
K_{ii}\\, u_i = f_i - K_{io}\\, u_o.
Parameters
----------
dirichlet_mask : torch.Tensor
1D boolean tensor of shape :math:`[n_{\\text{dof}}]`. ``True`` marks
DOFs whose value is prescribed.
dirichlet_value : torch.Tensor, optional
1D tensor of shape :math:`[n_{\\text{dof}}]` (a full vector — only
the entries where ``dirichlet_mask`` is ``True`` are read) **or**
:math:`[n_{\\text{outer\\_dof}}]` (already restricted to the
boundary). Defaults to all zeros.
Attributes
----------
dirichlet_mask : torch.Tensor
Boolean mask of shape :math:`[n_{\\text{dof}}]`.
dirichlet_value : torch.Tensor
Prescribed values restricted to the boundary, shape
:math:`[n_{\\text{outer\\_dof}}]`. A tensor of this length given to
the constructor or to :meth:`update_dirichlet` is stored as it is,
not copied, so later calls see in-place updates of it; a
full-length vector is restricted with ``dirichlet_mask``, which
copies (also when every DOF is prescribed, so that the two lengths
coincide). The stored tensor keeps the dtype, device and autograd
graph it was given: ``__call__``, :meth:`condense_rhs` and
:meth:`recover` never reassign or modify it, each casts a local
copy to the dtype and device it needs. Only the constructor,
:meth:`update_dirichlet` and module casts such as
``condenser.to(...)`` or ``condenser.double()`` change it.
inner_row, inner_col : torch.Tensor or None
Row/column indices of the inner block :math:`K_{ii}` in *local*
inner-DOF numbering. Populated lazily on the first call.
ou2in_row, ou2in_col : torch.Tensor or None
Row/column indices of the coupling block :math:`K_{io}` in local
numbering. Populated lazily.
is_inner_edge, is_ou2in_edge : torch.Tensor or None
Boolean masks over the matrix's COO edge list selecting the
:math:`K_{ii}` / :math:`K_{io}` entries.
is_inner_dof, is_outer_dof : torch.Tensor or None
Boolean masks over the global DOFs.
inner_shape, ou2in_shape : tuple of int or None
Shapes of :math:`K_{ii}` and :math:`K_{io}`.
n_inner_dof, n_outer_dof, n_dof : int or None
DOF counts.
layout_signature : tuple or None
``layout_signature`` of the matrix the cached layout was computed
from (see ``tensormesh.sparse.mixin``): the addresses and version
counters of its row and column index tensors, its number of
entries and its shape. It identifies these index tensors, not the
sparsity pattern: a later matrix is accepted only with the same
signature (``matrix.has_same_layout``) and index tensors of the
same shapes and strides. ``None`` before the first call, on a copy
(``copy.copy``, ``copy.deepcopy``, ``pickle``) until its first
call, and after a failed layout computation. Also ``None`` after a
call with a ``DSparseMatrix``: that call releases the signature and
the held index tensors but keeps the masks and ``K_ou2in``, so
:meth:`condense_rhs` and :meth:`recover` still work.
K_ou2in : SparseMatrix or None
Cached :math:`K_{io}` block; reused by :meth:`condense_rhs`.
Notes
-----
:class:`Condenser` is a :class:`torch.nn.Module`. Its tensor state
(``dirichlet_mask``, ``dirichlet_value``, and the lazily computed index
buffers) is registered as PyTorch buffers, so
``condenser.to(device)`` / ``condenser.cuda()`` / ``condenser.cpu()``
move them together with the input system. The index tensors of the
layout matrix that the condenser keeps (see below) are not buffers.
The first call to ``__call__`` lazily computes the inner / outer edge
masks and caches them on the instance, together with the
``layout_signature`` of the matrix. Subsequent calls reuse the cached
layout as long as the input
:class:`~tensormesh.sparse.SparseMatrix` has the same signature
(checked via ``matrix.has_same_layout``) and index tensors of the same
shapes and strides. The lazy buffers are registered with
``persistent=False`` so they are not saved into ``state_dict``.
The signature identifies the row and column index tensors of the
matrix by address and version counter, which identifies a sparsity
pattern only while these tensors are alive: once they are freed, their
memory can go to the index tensors of another pattern with as many
entries, and that matrix then has the same signature. The condenser
therefore keeps the row and column index tensors of the matrix its
layout was computed from, as plain attributes (not in
``state_dict``). What stays alive, for the lifetime of the condenser,
is the storage behind these two tensors (:math:`2\\,\\text{nnz}`
integers, or all of the larger tensor they are views of), on the
device they were created on: moving the condenser with
``condenser.to(...)`` does not move it. For a matrix assembled by an
``ElementAssembler`` or a ``MixedElementAssembler`` this is storage
the assembler caches anyway; other sources, such as a
``FacetBilinearAssembler`` or a hand-built matrix, have no such cache.
The matrix itself and its values are not kept. A copy (``copy.copy``,
``copy.deepcopy``, ``pickle``) does not carry these references, since a
copied tensor at another address would protect nothing: it has no
``layout_signature`` and recomputes its layout from the matrix of its
next call instead of comparing signatures.
Examples
--------
.. code-block:: python
import torch
from tensormesh import Mesh, Condenser
from tensormesh.assemble import LaplaceElementAssembler
mesh = Mesh.gen_rectangle(chara_length=0.2)
K = LaplaceElementAssembler.from_mesh(mesh)()
f = torch.ones(mesh.n_points, dtype=mesh.dtype)
# Homogeneous Dirichlet on the whole boundary
condenser = Condenser(mesh.boundary_mask)
# Condense: returns (K_inner, f_inner) — note this is __call__,
# NOT a separate "condense_matrix" method.
K_inner, f_inner = condenser(K, f)
# Solve the inner system and recover the full solution
u_inner = K_inner.solve(f_inner)
u = condenser.recover(u_inner)
For time-dependent boundary data, update the prescribed values between
solves via :meth:`update_dirichlet`, then re-condense only the
right-hand side with :meth:`condense_rhs` (cheaper than rebuilding
``K_inner``).
"""
dirichlet_mask:torch.Tensor
dirichlet_value:torch.Tensor
inner_row:Optional[torch.Tensor]
inner_col:Optional[torch.Tensor]
ou2in_row:Optional[torch.Tensor]
ou2in_col:Optional[torch.Tensor]
is_inner_edge:Optional[torch.Tensor]
is_ou2in_edge:Optional[torch.Tensor]
is_inner_dof:Optional[torch.Tensor]
is_outer_dof:Optional[torch.Tensor]
inner_shape:Optional[Tuple[int, int]]
ou2in_shape:Optional[Tuple[int, int]]
n_inner_dof:Optional[int]
n_outer_dof:Optional[int]
n_dof:Optional[int]
layout_signature:Optional[Tuple]
K_ou2in:Optional[SparseMatrix]
_layout_row:Optional[torch.Tensor]
_layout_col:Optional[torch.Tensor]
_LAZY_BUFFERS = (
"inner_row", "inner_col", "ou2in_row", "ou2in_col",
"is_inner_edge", "is_ou2in_edge",
"is_inner_dof", "is_outer_dof",
)
# Plain attributes (never buffers) holding the row / column index
# tensors of the matrix the layout was computed from.
_LAYOUT_INDICES = ("_layout_row", "_layout_col")
[docs]
def __init__(self,
dirichlet_mask:torch.Tensor,
dirichlet_value:Optional[torch.Tensor] = None):
super().__init__()
assert dirichlet_mask.dtype == torch.bool, \
f"dirichlet_mask must be a bool tensor, got {dirichlet_mask.dtype}"
assert dirichlet_mask.ndim == 1, \
f"dirichlet_mask must be 1D, got shape {tuple(dirichlet_mask.shape)}"
self.register_buffer("dirichlet_mask", dirichlet_mask)
self.register_buffer("dirichlet_value", self._normalize_value(dirichlet_value))
for name in self._LAZY_BUFFERS:
self.register_buffer(name, None, persistent=False)
self.inner_shape = None
self.ou2in_shape = None
self.n_inner_dof = None
self.n_outer_dof = None
self.n_dof = None
self.layout_signature = None
self.K_ou2in = None
self._release_layout_indices()
def _normalize_value(self, value:Optional[torch.Tensor])->torch.Tensor:
"""Restrict a full or boundary-only prescribed-value vector to the boundary."""
mask = self.dirichlet_mask
n_outer = int(mask.sum())
if value is None:
return torch.zeros(n_outer, device=mask.device)
assert value.ndim == 1, \
f"dirichlet_value must be 1D, got shape {tuple(value.shape)}"
if value.shape[0] == mask.shape[0]:
return value[mask]
assert value.shape[0] == n_outer, \
f"dirichlet_value must have length n_dof ({mask.shape[0]}) " \
f"or n_outer_dof ({n_outer}), got {value.shape[0]}"
return value
def _compute_layout(self, matrix:SparseMatrix):
"""Precompute and cache inner / outer edge masks and local DOF indices.
Called lazily by :meth:`__call__` whenever the condenser has no
layout it can trust (see :meth:`_holds_layout`): on its first call,
and on the first call of a copy, which does not carry the index
tensors the layout was computed from.
Caches ``matrix.layout_signature`` and keeps the row and column
index tensors of ``matrix`` (see :meth:`_hold_layout_indices`):
while the condenser holds them their memory cannot be reused, so an
equal signature on a later call, with index tensors of the same
shapes and strides (see :meth:`_matches_held_indices`), means the
same index tensors, unmodified.
Parameters
----------
matrix : SparseMatrix
Reference matrix whose sparsity pattern determines the inner /
outer edge partition.
"""
# Trust nothing while the layout is being replaced: if this raises,
# the condenser holds no index tensors and shows no signature, and
# the next call recomputes instead of comparing signatures.
self._release_layout_indices()
edge_u, edge_v = matrix.row, matrix.col
n_dof = matrix.shape[0]
is_inner_dof, is_outer_dof = ~self.dirichlet_mask, self.dirichlet_mask
is_inner_u, is_inner_v = is_inner_dof[edge_u], is_inner_dof[edge_v]
is_outer_u, is_outer_v = is_outer_dof[edge_u], is_outer_dof[edge_v]
is_inner_edge, is_ou2in_edge = is_inner_u & is_inner_v, is_inner_u & is_outer_v
n_inner_dofs, n_outer_dofs = is_inner_dof.sum().item(), is_outer_dof.sum().item()
local_nids = torch.full((n_dof,), -1, dtype=torch.long, device=matrix.device)
local_nids[is_inner_dof] = torch.arange(n_inner_dofs, device=matrix.device)
local_nids[is_outer_dof] = torch.arange(n_outer_dofs, device=matrix.device)
self.inner_row = local_nids[edge_u[is_inner_edge]]
self.inner_col = local_nids[edge_v[is_inner_edge]]
self.ou2in_row = local_nids[edge_u[is_ou2in_edge]]
self.ou2in_col = local_nids[edge_v[is_ou2in_edge]]
self.is_inner_edge = is_inner_edge
self.is_ou2in_edge = is_ou2in_edge
self.is_inner_dof = is_inner_dof
self.is_outer_dof = is_outer_dof
self.inner_shape = (n_inner_dofs, n_inner_dofs)
self.ou2in_shape = (n_inner_dofs, n_outer_dofs)
self.n_inner_dof = n_inner_dofs
self.n_outer_dof = n_outer_dofs
self.n_dof = n_dof
self.layout_signature = matrix.layout_signature
self._hold_layout_indices(matrix)
def _hold_layout_indices(self, matrix:SparseMatrix):
"""Keep the row and column index tensors of ``matrix`` alive.
They are the tensor objects ``matrix.layout_signature`` reads. They
are written into ``__dict__`` directly: ``nn.Module.__setattr__``
would register an index tensor created as ``nn.Buffer`` (or
``nn.Parameter``) on the condenser, putting it in ``state_dict`` and
under ``_apply``. The matrix itself and its values are not kept.
"""
self.__dict__["_layout_row"] = matrix.row_indices
self.__dict__["_layout_col"] = matrix.col_indices
def _release_layout_indices(self):
"""Drop the index tensors held for the cached layout, and its signature.
The cached masks stay, but :meth:`__call__` no longer trusts them:
it recomputes the layout from the matrix of its next call. A
condenser that holds no index tensors shows no ``layout_signature``
either, since nothing protects it.
"""
for name in self._LAYOUT_INDICES:
self.__dict__[name] = None
self.__dict__["layout_signature"] = None
def _matches_held_indices(self, matrix:SparseMatrix)->bool:
"""Whether the index tensors of ``matrix`` have the shapes and strides of the held ones.
``layout_signature`` records addresses, version counters, the
element count and the matrix shape, not strides: two live views of
one storage that start at the same address with other strides
(``base[:n]`` and ``base[::2]``, or ``base[:1].expand(n)``) have
equal signatures and different entries. Together with an equal
signature, equal shapes and strides mean the very same elements.
"""
return all(
given.shape == held.shape and given.stride() == held.stride()
for given, held in ((matrix.row_indices, self.__dict__["_layout_row"]),
(matrix.col_indices, self.__dict__["_layout_col"]))
)
def _holds_layout(self)->bool:
"""Whether the cached layout can be checked by signature.
True when a layout is cached and the condenser holds the index
tensors it was computed from. Otherwise (a fresh condenser, a copy,
a condenser whose ``inner_row`` was reset) :meth:`__call__`
recomputes the layout instead of comparing signatures.
"""
return self.inner_row is not None and all(
self.__dict__.get(name) is not None for name in self._LAYOUT_INDICES
)
def __getstate__(self):
"""State used by ``copy.copy``, ``copy.deepcopy`` and ``pickle``.
Leaves out the index tensors held for the cached layout, and the
signature they protect, so that a copy recomputes its layout from
the matrix of its next call: a tensor copied to another address
protects nothing. The buffer dict and the set of non-persistent
buffer names are copied as well (``copy.copy`` keeps the type of a
dict subclass), so that a shallow copy that recomputes its layout,
updates its Dirichlet values, is cast or moved, or registers a
buffer leaves the original as it was.
"""
parent = getattr(super(), "__getstate__", None)
state = dict(parent() if parent is not None else self.__dict__)
for name in ("_buffers", "_non_persistent_buffers_set"):
if name in state:
state[name] = copy.copy(state[name])
for name in self._LAYOUT_INDICES:
state[name] = None
state["layout_signature"] = None
return state
def __setstate__(self, state):
"""Restore a copied or unpickled condenser without held index tensors or signature."""
super().__setstate__(state)
# Also covers states pickled before these attributes existed.
self._release_layout_indices()
def _condense_complex(self, K_ou2in:SparseMatrix, rhs:torch.Tensor):
"""Cast ``rhs`` and form :math:`K_{io}\\, u_o` when an operand is complex.
Shared by :meth:`__call__` and :meth:`condense_rhs` when
``K_ou2in``, ``rhs`` or the Dirichlet values are complex. The
target dtype is the complex dtype with the precision of
``K_ou2in``. :math:`u_o` is a local copy of the stored
``dirichlet_value``, moved to the device of ``K_ou2in`` and cast to
its precision without changing whether it is real or complex; the
stored tensor itself is neither reassigned nor modified. No sparse
product mixes real and complex operands: a real ``K_ou2in`` is
applied to the real and imaginary parts of complex :math:`u_o`
separately.
Parameters
----------
K_ou2in : SparseMatrix
Coupling block :math:`K_{io}`.
rhs : torch.Tensor
Global right-hand side of shape
:math:`[n_{\\text{dof}}, \\ldots]`.
Returns
-------
rhs : torch.Tensor
``rhs`` in the target dtype, on the device of ``K_ou2in``.
minus_term : torch.Tensor
:math:`K_{io}\\, u_o` of shape :math:`[n_{\\text{inner\\_dof}}]`,
in the target dtype, or real with the precision of ``K_ou2in``
when ``K_ou2in`` and :math:`u_o` are both real.
"""
values = K_ou2in.edata
dtype = torch.promote_types(values.dtype, torch.complex64) # float64 -> complex128
if self.dirichlet_value.is_complex():
u_o = self.dirichlet_value.type(dtype).to(values.device)
else:
# values.real.dtype: float64 for complex128 and for float64 values
u_o = self.dirichlet_value.type(values.real.dtype).to(values.device)
if values.is_complex():
minus_term = K_ou2in @ u_o.type(dtype)
elif u_o.is_complex():
minus_term = torch.complex(K_ou2in @ u_o.real, K_ou2in @ u_o.imag)
else:
minus_term = K_ou2in @ u_o
return rhs.type(dtype).to(values.device), minus_term
[docs]
def update_dirichlet(self, dirichlet_value:torch.Tensor):
"""Replace the cached prescribed boundary values.
Useful for time-dependent or parameter-swept problems where only
the right-hand side changes between solves; the cached
:math:`K_{io}` block (populated by ``__call__``) is preserved.
Parameters
----------
dirichlet_value : torch.Tensor
1D tensor of shape :math:`[n_{\\text{dof}}]` or
:math:`[n_{\\text{outer\\_dof}}]`, with the same conventions
as the ``dirichlet_value`` argument to :meth:`__init__`. The
values may be complex even if the matrix and the earlier data
were real; :meth:`condense_rhs` and :meth:`recover` then return
complex results.
"""
self.dirichlet_value = self._normalize_value(dirichlet_value)
def __call__(self,
matrix,
rhs:Optional[torch.Tensor] = None,
):
"""Condense both the matrix and the right-hand side.
Parameters
----------
matrix : SparseMatrix
Global stiffness/mass matrix of shape
:math:`[n_{\\text{dof}}, n_{\\text{dof}}]`.
rhs : torch.Tensor, optional
Global right-hand side of shape
:math:`[n_{\\text{dof}}, \\ldots]`. Trailing dimensions are
preserved (broadcasting is applied to the Dirichlet correction
term). Defaults to a zero vector.
Returns
-------
K_inner : SparseMatrix
Condensed matrix of shape
:math:`[n_{\\text{inner\\_dof}}, n_{\\text{inner\\_dof}}]`, with
the dtype of ``matrix``, on the device of ``matrix``.
f_inner : torch.Tensor
Condensed right-hand side of shape
:math:`[n_{\\text{inner\\_dof}}, \\ldots]`, on the device of
``matrix``. It has the dtype of ``matrix``, except that a real
``matrix`` with a complex ``rhs`` or complex Dirichlet values
gives the complex dtype of the same precision (``float32`` →
``complex64``, ``float64`` → ``complex128``).
Notes
-----
Caches the matrix sparsity layout on the first call and keeps the
index tensors of that matrix (see the class Notes). A later matrix
is accepted if it has the same ``layout_signature`` and index
tensors of the same shapes and strides, that is the same index
tensors, not modified in place since: the same matrix, ``K + B`` on
the same index tensors, or other values on ``K.row_indices`` and
``K.col_indices``. Any other matrix raises an ``AssertionError``,
also one with the same pattern on other index tensors. If you later
condense a matrix with a different sparsity pattern, instantiate a
new :class:`Condenser`. A copy of a condenser holds no index tensors
and computes its layout from the matrix of its first call. A
``DSparseMatrix`` is condensed through a global matrix built at
every call, and its layout is recomputed at every call.
Precision follows the matrix and complexness is the union of the
operands, so no imaginary part is discarded. A real matrix is
applied to the real and imaginary parts of complex Dirichlet
values separately. The Dirichlet values are read from
``dirichlet_value`` on every call: a local copy is moved to the
device of ``matrix`` and cast to its precision, staying complex if
it is complex and real if it is real. The stored
``dirichlet_value`` is neither reassigned nor modified, so it keeps
its dtype, device, values and autograd graph whatever ``matrix``
and ``rhs`` are, also under :func:`torch.no_grad`.
"""
# ---- DSparseMatrix dispatch ---------------------------------- #
# The single-device condensation logic indexes ``matrix.edata``
# by cached position-aware boolean masks (``is_inner_edge`` /
# ``is_ou2in_edge``). Adapting that to a row-sharded
# DSparseMatrix requires a from-scratch implementation (boundary
# mask broadcast + per-rank inner/outer partition + repartition
# of the condensed system). Until that lands, fall back through
# ``.to_single()`` so the API contract is honoured and meshes
# below the cluster threshold keep working.
from ..distributed import DSparseMatrix
if isinstance(matrix, DSparseMatrix):
return self._call_distributed(matrix, rhs)
if rhs is None:
rhs = torch.zeros(matrix.shape[0])
# A layout is checked by signature only while the condenser holds the
# index tensors it was computed from; otherwise (first call, copy)
# it is recomputed from this matrix.
if not self._holds_layout():
self._compute_layout(matrix)
assert matrix.shape[0] == self.n_dof, f"the shape of matrix must be [{self.n_dof}, {self.n_dof}], but got {matrix.shape}"
assert matrix.shape[1] == self.n_dof, f"the shape of matrix must be [{self.n_dof}, {self.n_dof}], but got {matrix.shape}"
assert matrix.has_same_layout(self.layout_signature) and self._matches_held_indices(matrix), \
"the layout of the matrix is changed, please recompute the condensed matrix"
assert rhs.shape[0] == self.n_dof, f"the shape of rhs must be [{self.n_dof}, ...], but got {rhs.shape}"
K_inner = SparseMatrix(
matrix.edata[self.is_inner_edge], self.inner_row, self.inner_col, self.inner_shape,
)
K_ou2in = SparseMatrix(
matrix.edata[self.is_ou2in_edge], self.ou2in_row, self.ou2in_col, self.ou2in_shape,
)
self.K_ou2in = K_ou2in
if any(t.is_complex() for t in (K_inner.edata, self.dirichlet_value, rhs)):
rhs, minus_term = self._condense_complex(K_ou2in, rhs)
else:
u_o = self.dirichlet_value.type(K_inner.edata.dtype).to(K_inner.edata.device)
rhs = rhs.type(K_inner.edata.dtype).to(K_inner.edata.device)
minus_term = K_ou2in @ u_o
for _ in range(rhs.dim() - 1):
minus_term = minus_term.unsqueeze(-1)
return K_inner, rhs[self.is_inner_dof] - minus_term
def _call_distributed(self, dmatrix, rhs):
"""Condense a :class:`DSparseMatrix` by round-tripping through
the single-device path (``.to_single()`` allgather, condense,
re-partition).
Correct but inefficient: cost is one global allgather of the
COO triples plus a re-partition. Intended as the interim
contract while the true per-rank Condenser is designed.
``to_single()`` builds the global matrix afresh at every call, on
new index tensors. Its layout is computed by :meth:`__call__`, and
the references to its index tensors (and the signature) are
released as soon as that call returns, also when it raises: nothing
of the throwaway matrix stays alive (it would pin 2 x global nnz
integers on every rank), and every call recomputes the layout, so
repeated calls with the same or another ``DSparseMatrix`` work.
:meth:`condense_rhs` and :meth:`recover` keep working on what the
last call cached.
TODO(future PR): native distributed condensation that keeps the
matrix sharded throughout (boundary mask broadcast + per-rank
inner/outer split + automatic owned/halo rewrite).
"""
import warnings
warnings.warn(
"Condenser on DSparseMatrix currently routes through .to_single() "
"(allgather + condense + re-partition). The per-rank distributed "
"Condenser is a follow-up PR; this path keeps the API working.",
stacklevel=2,
)
# Round-trip to single-device. Force CPU because the cached
# dirichlet_mask in this Condenser lives on the device chosen
# at construction time (typically CPU); avoid a cross-device
# index in _compute_layout. Result is moved back to dmatrix's
# device before re-partitioning below.
target_device = dmatrix.device
K_global = dmatrix.to_single().cpu()
if rhs is None:
f_global = None
else:
# rhs comes in as either DTensor (Shard(0)) or owned slice;
# for the round-trip we need the full vector. DTensor moved
# from torch.distributed._tensor (torch 2.0-2.1) to
# torch.distributed.tensor (torch >= 2.2); accept both.
DTensor = None
try:
from torch.distributed.tensor import DTensor as _DT
DTensor = _DT
except ImportError:
try:
from torch.distributed._tensor import DTensor as _DT
DTensor = _DT
except ImportError:
pass
if DTensor is not None and isinstance(rhs, DTensor):
f_global = rhs.full_tensor()
else:
f_global = rhs
if f_global is not None:
f_global = f_global.cpu()
try:
K_inner, f_inner = self.__call__(K_global, f_global)
finally:
# ``K_global`` is a throwaway matrix: keep none of it, so that
# the next call recomputes the layout from its own global matrix.
self._release_layout_indices()
K_inner = K_inner.to(target_device)
f_inner = f_inner.to(target_device)
# Re-partition the condensed result so downstream stays distributed.
# Use the same partition_method the caller's DSparseMatrix used.
from ..distributed import DSparseMatrix as _DM
from torch_sla.distributed import DSparseTensor
try:
from torch.distributed.device_mesh import init_device_mesh
except ImportError:
from torch.distributed._tensor.device_mesh import init_device_mesh
import torch.distributed as dist
if dist.is_available() and dist.is_initialized():
world = dist.get_world_size()
device = "cuda" if torch.cuda.is_available() else "cpu"
mesh = init_device_mesh(device, (world,))
K_inner_d_tensor = DSparseTensor.partition(
K_inner, mesh, partition_method="metis",
)
else:
K_inner_d_tensor = DSparseTensor.partition(K_inner, mesh=None,
partition_method="metis")
# Fresh UUID -- this is a new partition build that won't share
# caches with the input's partition.
K_inner_d = _DM(K_inner_d_tensor)
return K_inner_d, f_inner
[docs]
def condense_rhs(self, rhs:torch.Tensor)->torch.Tensor:
"""Condense the right-hand side only, reusing the cached matrix layout.
.. math::
f_i \\leftarrow f_i - K_{io}\\, u_o.
Use this after a first ``__call__`` to re-condense ``f`` when the
matrix is unchanged but the load vector changes (e.g. between
time steps).
Parameters
----------
rhs : torch.Tensor
Global right-hand side of shape
:math:`[n_{\\text{dof}}, \\ldots]`.
Returns
-------
torch.Tensor
Condensed right-hand side of shape
:math:`[n_{\\text{inner\\_dof}}, \\ldots]`, on the device of the
cached :math:`K_{io}` whatever the device of ``rhs``. It is
complex if the cached :math:`K_{io}`, ``rhs`` or the Dirichlet
values are complex, and then has the precision of
:math:`K_{io}` (``float32`` → ``complex64``, ``float64`` →
``complex128``). With real operands it has the dtype of
:math:`K_{io}`, or that of ``rhs`` if ``rhs`` has the higher
precision (a ``float64`` ``rhs`` with a ``float32``
:math:`K_{io}` gives ``float64``).
Raises
------
AssertionError
If ``__call__`` has not been invoked yet: the operator has no
cached :math:`K_{io}` block to apply.
Notes
-----
``rhs`` and a local copy of the stored ``dirichlet_value`` are
moved to the device of :math:`K_{io}`. With a complex operand, the
copy is cast to the precision of :math:`K_{io}`, staying complex if
it is complex and real if it is real, and a real :math:`K_{io}` is
applied to the real and imaginary parts of complex Dirichlet
values separately. With real operands, the copy takes the dtype of
``rhs`` or of :math:`K_{io}`, whichever has the higher precision,
so the values are never rounded to a lower precision than that of
:math:`K_{io}`. The stored ``dirichlet_value`` is neither
reassigned nor modified.
"""
assert self.K_ou2in is not None, \
"call the Condenser on a matrix first; condense_rhs reuses the cached K_io block"
values = self.K_ou2in.edata
if any(t.is_complex() for t in (values, self.dirichlet_value, rhs)):
rhs, minus_term = self._condense_complex(self.K_ou2in, rhs)
else:
u_o = self.dirichlet_value.type(torch.promote_types(rhs.dtype, values.dtype)).to(values.device)
rhs = rhs.type(values.dtype).to(values.device)
minus_term = self.K_ou2in @ u_o
for _ in range(rhs.dim() - 1):
minus_term = minus_term.unsqueeze(-1)
return rhs[self.is_inner_dof] - minus_term
[docs]
def recover(self, u:torch.Tensor)->torch.Tensor:
"""Recover the full-DOF solution from an inner-DOF solution.
Scatters the condensed solution ``u`` back into the free-DOF slots
and writes the prescribed boundary values into the constrained
slots.
Parameters
----------
u : torch.Tensor
Inner-system solution of shape
:math:`[n_{\\text{inner\\_dof}}, \\ldots]`.
Returns
-------
torch.Tensor
Full-system solution of shape
:math:`[n_{\\text{dof}}, \\ldots]`, on the device of ``u``, with
the dtype of ``u``, or the complex dtype of the same precision
if ``u`` is real and the Dirichlet values are complex.
Notes
-----
The boundary entries are a local copy of the stored
``dirichlet_value``, moved to the device of ``u`` and written in
the precision of the result. The stored tensor is neither
reassigned nor modified, so the values written here do not depend
on the precision or the device of the matrices condensed before.
The cached DOF masks are used on the device of ``u`` as well.
"""
assert u.shape[0] == self.n_inner_dof, f"the shape of u must be [{self.n_inner_dof}, ...], but got {u.shape}"
shape = list(u.shape)
shape[0] = self.n_dof
dtype = u.dtype
if self.dirichlet_value.is_complex() and not u.is_complex():
dtype = torch.promote_types(dtype, torch.complex64) # float64 -> complex128
is_inner = self.is_inner_dof.to(u.device)
is_outer = self.is_outer_dof.to(u.device)
u_full = torch.zeros(shape, dtype=dtype, device=u.device)
u_full[is_inner] += u
boundary_value = self.dirichlet_value.to(u.device)
for _ in range(u.dim() - 1):
boundary_value = boundary_value.unsqueeze(-1)
u_full[is_outer] += boundary_value
return u_full
[docs]
def restrict(self, f:torch.Tensor)->torch.Tensor:
"""Project a full-DOF vector down to inner DOFs.
Pure linear restriction :math:`f_i \\leftarrow f|_{\\text{inner}}`,
with **no** Dirichlet-value correction. Use this when the
right-hand side has no implicit Dirichlet contribution to
subtract — for example, the per-stage right-hand side of a
time-integration scheme such as
:class:`tensormesh.ode.ImplicitLinearRungeKutta`, where the
time-derivative at a Dirichlet DOF is zero by construction
and so the :math:`-K_{io}\\,u_o` term in :meth:`condense_rhs`
would over-apply the boundary correction.
Unlike ``Condenser.__call__`` / :meth:`condense_rhs`,
``restrict`` does not require the matrix layout to be cached
first: it only needs ``dirichlet_mask``.
Parameters
----------
f : torch.Tensor
Full-DOF vector of shape
:math:`[n_{\\text{dof}}, \\ldots]`.
Returns
-------
torch.Tensor
Inner-DOF vector of shape
:math:`[n_{\\text{inner\\_dof}}, \\ldots]`.
"""
assert f.shape[0] == self.dirichlet_mask.shape[0], \
f"the shape of f must be [{self.dirichlet_mask.shape[0]}, ...], but got {f.shape}"
return f[~self.dirichlet_mask]
[docs]
def prolong(self, f_inner:torch.Tensor)->torch.Tensor:
"""Lift an inner-DOF vector up to full DOF with zeros on the boundary.
Pure linear prolongation: inner entries are scattered into the
free-DOF slots, constrained slots are filled with **zero** —
not with ``dirichlet_value``. Use this when the quantity being
lifted should vanish on the boundary regardless of the
prescribed Dirichlet value, e.g. the per-stage slope of a
time integrator (since a fixed-value DOF has zero
time-derivative).
Like :meth:`restrict`, ``prolong`` only needs
``dirichlet_mask`` and does not require the matrix layout to
be cached first.
Parameters
----------
f_inner : torch.Tensor
Inner-DOF vector of shape
:math:`[n_{\\text{inner\\_dof}}, \\ldots]`.
Returns
-------
torch.Tensor
Full-DOF vector of shape
:math:`[n_{\\text{dof}}, \\ldots]` with zeros in the
constrained slots.
"""
n_inner = int((~self.dirichlet_mask).sum())
assert f_inner.shape[0] == n_inner, \
f"the shape of f_inner must be [{n_inner}, ...], but got {f_inner.shape}"
shape = list(f_inner.shape)
shape[0] = self.dirichlet_mask.shape[0]
f_full = torch.zeros(shape, dtype=f_inner.dtype, device=f_inner.device)
f_full[~self.dirichlet_mask] = f_inner
return f_full
Condenser.__autodoc__ = [
"__call__", "condense_rhs", "recover", "restrict", "prolong", "update_dirichlet",
]