mixle.engines.torch_engine module¶
Torch implementation of the ComputeEngine protocol.
The engine handles tensor placement, dtype policy, autograd support, optional compilation, and component sharding for resident scoring and estimation paths.
- class TorchEngine(device=None, dtype=None, compile=False, mesh=None, shard=None)[source]
Bases:
ComputeEngineTorch tensor engine for device placement, autograd, and optional DTensor sharding.
- property accumulator_dtype: Any
High-precision dtype for sufficient-statistic reductions (float64, or float32 on MPS).
Reductions that aggregate over observations accumulate in float64 even when scoring runs in reduced precision, so a float32 fit does not drift on large N. MPS has no float64, so there the accumulator falls back to float32 (its max precision) — fits on very large N may drift slightly.
- with_precision(precision)[source]
Return a Torch engine with the same placement and a new dtype policy.
- Parameters:
precision (Any)
- Return type:
TorchEngine
- asarray(x, dtype=None)[source]
Convert
xto a Torch tensor or DTensor on the configured device.Contract: float inputs are force-cast to the engine’s float dtype (e.g. a float32 numpy array becomes the engine’s float64) unless
dtypeis given; this differs from numpy’sasarray, which preserves the input dtype. Complex NumPy input is rejected whendtypeis not given explicitly: the dtype inference below has no complex-precision policy of its own, and letting it fall through to the generic non-floating/non-Boolean case would silently discard the imaginary component and collapse the real part to an integer. Pass an explicitdtype=torch.complex64/torch.complex128for a genuine complex tensor.
- zeros(shape, dtype=None)[source]
Allocate a zero tensor with this engine’s dtype/device/placement.
- empty(shape, dtype=None)[source]
Allocate an uninitialized tensor with this engine’s dtype/device/placement.
- arange(*args, **kwargs)[source]
Return
torch.arangeon the configured device.
- to_numpy(x)[source]
Gather/detach a Torch tensor or DTensor to a host NumPy array.
- stack(arrays, axis=0)[source]
Stack tensors with
torch.stackunder the engine’s dtype and device policy.Elements route through
asarray()first. Leaf scorers legitimately hand back float64 NumPy arrays; stacking them raw produced a float64 tensor that later met float32 engine tensors – invisible on CPU, but a hard “mat1 double, mat2 float” error inside the HMM forward pass on the first real CUDA execution (rented RTX 3060, 2026-08-04). The engine’s dtype policy has to apply at every ingestion point, not only the explicit asarray calls.
- concatenate(arrays, axis=0)[source]
Join tensors with
torch.catunder the same ingestion policy asstack().
- replicate(x)[source]
Return
xreplicated across the configured DeviceMesh.
- place_component_axis(x, axis=0)[source]
Place a stacked component parameter tensor on
Shard(axis).TorchEngine(mesh=..., shard='components')is the model-parallel configuration from the compute-engine design. Encoded data remains replicated, while homogeneous stacked-kernel parameter tensors are sharded along their component dimension. With no mesh, or with no component sharding requested, this is justasarray.
- requires_grad(x)[source]
Return whether
xis a Torch tensor/DTensor requiring gradients.
- compile(fn)[source]
Compile
fnwithtorch.compilewhen enabled and available.
- sum(x, *args, **kwargs)[source]
Return
torch.sumaccepting eitheraxisordim.Promotes a floating input to
accumulator_dtypewhen the caller doesn’t pass an explicitdtype=– mirroringNumpyEngine.sum(). Without this,torch.sumaccumulates in the input tensor’s own dtype by default, so a float32-precision fit on this engine would silently drift on large N (the exact catastrophic-cancellation riskaccumulator_dtypeexists to guard against) while the numpy engine, which already promotes, stayed accurate.
- static max(x, *args, **kwargs)[source]
Return
torch.maxaccepting eitheraxisordim(incl. a tuple of axes).
- matmul(x, y)[source]
Matrix-multiply under the engine’s dtype policy.
Both operands route through
asarray(). Mixed float32/float64 operands reached this point through paths that never crossed an explicit ingestion call, and torch.matmul promotes on CPU but hard-errors on CUDA (“mat1 double, mat2 float”) – found and probed on the first real CUDA execution of the HMM forward pass (rented RTX 3060, 2026-08-04: mat1 float64 [100, 2] against mat2 float32 [2, 2]). The engine’s declared dtype IS the policy for floating operands, so applying it here is a correctness boundary, not a cast of convenience.
- static cumsum(x, *args, **kwargs)[source]
Return
torch.cumsumacceptingaxis/dimand defaulting to a flattened scan.
- static logsumexp(x, *args, **kwargs)[source]
Return
torch.logsumexpaccepting eitheraxisordim.torch < 2.5 registers no DTensor sharding strategy for
logsumexp, so reducing over a sharded axis (the mixture E-step’s log-partition over component-sharded scores) raisesNotImplementedError. Fall back to redistributing the DTensor to replicated first – the reduction then runs locally and is correct on any torch version. torch >= 2.5 has the strategy and takes the fast native path unchanged; non-DTensor inputs re-raise the original error.
- hmm_forward_ll(log_emit, log_w, log_a, mask)[source]
Fused log-space forward: per-sequence emission log-likelihood (freeze-alpha padding).
- hmm_forward_backward(log_emit, log_w, log_a, mask, weights=None)[source]
Fused log-space Baum-Welch recurrences, exactly mirroring the generic engine-op version: alpha freezes across padded steps, beta carries, gamma is mask-SELECTED (NaN-safe for empty sequences), xi is computed for all transitions at once, and per-sequence
weightsscale gamma / xi / pi. Returns(ll, gamma, xi_sum, pi).
- index_add(out, index, values)[source]
Add
valuesintooutalong axis 0 using Torchindex_add.Contract: return-value-only –
torch.Tensor.index_add(no trailing underscore) does not mutateoutin place, unlike numpy’sadd.at; callers must use the returned tensor.