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.
- 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.stackand apply default placement.
- 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).
- 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.