Expand description
Experimental training with named axes on a stream-ordered cuTile GPU backend.
Muon is adapted from Keller Jordan’s reference implementation. The pinned
source revision and MIT notice are packaged in
THIRD_PARTY.md.
Modules§
- architectures
- Reference architectures assembled only from public library modules: composition
witnesses as well as convenience constructors. One file per family under
src/architectures/. Equivalence to each architecture’s reference implementation is established by tests insrc/library/src/tests.rs, never asserted here. - prelude
Structs§
- Adam
- Device-resident Adam with bias correction and one state pair per ParamId.
- AdamW
- Adam with decoupled weight decay; moments and updates remain device-resident.
- Adaptive
AvgPool1d - Named-axis adaptive average pooling over one spatial axis: reduces it to a fixed target
extent using PyTorch’s own per-axis bin formula. See
Tensor::adaptive_avg_pool3dfor the exact bin math and its uneven-division behavior. - Adaptive
AvgPool2d - Named-axis adaptive average pooling over two spatial axes; see
AdaptiveAvgPool1dandTensor::adaptive_avg_pool3dfor the shared bin contract. - Adaptive
AvgPool3d - Named-axis adaptive average pooling over three spatial axes, wrapping
Tensor::adaptive_avg_pool3das a statelessModule; seeAdaptiveAvgPool1dfor the shared contract. - Adaptive
MaxPool1d - Named-axis adaptive max pooling over one spatial axis: reduces it to a fixed target extent
using the same bin formula as
AdaptiveAvgPool1d, taking each bin’s maximum instead of its mean. SeeTensor::adaptive_max_pool3dfor the exact composition and its tie-break. - Adaptive
MaxPool2d - Named-axis adaptive max pooling over two spatial axes; see
AdaptiveMaxPool1dandTensor::adaptive_max_pool3dfor the shared contract. - Adaptive
MaxPool3d - Named-axis adaptive max pooling over three spatial axes, wrapping
Tensor::adaptive_max_pool3das a statelessModule; seeAdaptiveMaxPool1dfor the shared contract. - Addition
Dataset - An inexhaustible deterministic stream of fresh addition problems. IDs are unique draw counters; values can still coincide after f32 projection.
- Addition
Sample - Alpha
Dropout - SELU-preserving alpha dropout: PyTorch’s
nn.AlphaDropout. Ordinary inverted dropout resets dropped units to zero, which is off-distribution for a SELU network whose self-normalizing property assumes zero mean and unit variance; alpha dropout instead resets dropped units to SELU’s own saturation value and applies an affine correction that keeps the first two moments fixed. Formula (bit-for-bit PyTorch’saten/src/ATen/native/Dropout.cpp_alpha_dropout_impl,alpha_dropout=true): withalpha = 1.7580993408473766(SELU’s-alpha_selu * scale_selu, negated) anda = 1 / sqrt((alpha^2 * p + 1) * (1 - p)), each element keeps with probability1 - p(maskkeep = draw >= p, the sameTensor::uniform_deviceconventionDropoutuses) and the output isa * input * keep + alpha * a * keep + alpha * a * (p - 1)– algebraicallya * (input + alpha)where kept, and the constantalpha * a * (p - 1)where dropped, with no dedicated “add a scalar constant” primitive needed: the three terms above compose frommul,scaleandaddalone, and the constant term is built withTensor::from_sliceexactly likenormalization::Affine’s own constant parameters.forward(evaluation) is the identity.forward_trainingconsumes exactly onepass.next_seed()draw regardless ofp;p == 0is the identity andp == 1is exact zeros with exactly zero gradient (PyTorch’s own_dropout_implspecial-casesp == 1toinput * 0before the affine constants – which are undefined atp == 1– are ever computed, for every dropout variant including this one). - AvgPool1d
- Named-channel 1D average pooling:
sum(window) / divisor, independently per channel, matching PyTorch’snn.AvgPool1dand all of its options. The divisor isdivisor_overridewhen set; otherwise, withcount_include_pad=True(the default), the window’s extent clipped to the padded input – the full kernel extent except for aceil_modewindow overhanging the right padding; withcount_include_pad=False, the count of real (non-padding) positions. The window count isfloor((L + 2p - k) / s) + 1, or withceil_mode=Trueceil((L + 2p - k) / s) + 1minus one when that last window would start at or pastL + p(PyTorch’s own rule: every window starts inside the input or its left padding). Stride defaults to the kernel extent and padding to0; padding must be at most half the kernel extent, the same constraintMaxPool1denforces. - AvgPool2d
- Named-channel 2D average pooling; see
AvgPool1dfor the sharedceil_mode,count_include_padanddivisor_overridecontract, applied per axis over two spatial axes asMaxPool2dis; a window’s divisor is the product of its per-axis counts. - AvgPool3d
- Named-channel 3D average pooling; see
AvgPool1dfor the shared contract, applied over three spatial axes asMaxPool3dis. - Axis
- Identity is independent of both the diagnostic name and tensor-local extent.
- Batch
- Batch
Norm - Batch normalization over one explicitly named feature axis, PyTorch’s
BatchNorm1d/BatchNorm2d/BatchNorm3din a single named-axis module: every OTHER axis present at call time – batch and any spatial axes – normalizes together, whatever it is named. Defaults to epsilon1e-5, momentumSome(0.1), a learnable per-feature affine scale and bias, andtrack_running_stats = true, matching PyTorch’s own defaults. - Bilinear
- Learned bilinear form over two named axes,
y = x1^T A x2 + b, PyTorch’snn.Bilinear. Composed from twoTensor::contractcalls –x1contracted againstweightoverin1, then that intermediate contracted againstx2overin2– the same contractionLinearalready uses, applied twice, so it needs no dedicated kernel. Any axisx1andx2share beyondin1/in2(such as a common batch axis) aligns automatically through that shared contraction, exactly likeLinear’s own unrelated axes; an axis unique to either input passes through untouched. - CELU
- Elementwise CELU with an explicit, finite, nonzero
alpha– PyTorch’s own documented domain, “valid for alpha != 0”, negativealphaincluded. SeeTensor::celufor the exact forward/backward split atx == 0and why the two-branch composition already matches PyTorch’smax(0, x) + min(0, ...)definition for any nonzeroalpha. - Categorical
Accuracy - Exact categorical classification counts. Counts compose across evaluation batches.
- Central
Difference - A centered finite-difference stencil evaluated at a positive coordinate step.
- Channel
Dropout - Channel (feature-map) dropout: PyTorch’s
nn.Dropout1d,nn.Dropout2dandnn.Dropout3dare one type here, since Axis names axes instead of positionally counting spatial dimensions – exactly howZeroPadalready collapses PyTorch’sZeroPad1d/2d/3dinto one axis-list constructor: the “1d”/“2d”/“3d” split is purely how many axes are namedspatial, never a different type or contract. Drops one mask value per combination ofchanneland every axis NOT namedspatial(so every batch-like axis varies independently too, matching PyTorch’smake_feature_noisemask shape[N, C, 1, 1, ...]), broadcasting that one decision over everyspatialaxis:Conv2d’s(batch, channel, height, width)output passed throughChannelDropout::new(p, channel, [height, width])zeroes whole feature maps together, the way dropping isolated pixels would not regularize a convolutional feature. Otherwise identical toDropout:forwardis the identity;forward_trainingconsumes exactly onepass.next_seed()draw regardless ofp, feeds it to oneTensor::uniform_devicecall over the non-spatial axes alone, keeps each (channel, batch, …) combination whose draw is>= p, and rescales kept elements by1 / (1 - p);p == 0is the identity andp == 1is exact zeros with exactly zero gradient, the same edge casesDropoutdocuments. - Channel
Shuffle torch.nn.ChannelShuffle(groups): splitchannel(extentC) into[group (groups), within (C / groups)]– PyTorch’s actual internal reshape order,(N, groups, C/groups, *), which is the reverse of its own prose (“divides … into g groups as (N, C/g, g, *)”), verified against a realchannel_shufflerun rather than trusted from the text – then merge back in swapped order[within, group], reproducing its documented transpose-and-flatten exactly ([ch0, ch1, ch2, ch3]atgroups=2becomes[ch0, ch2, ch1, ch3], matching the PyTorch docs’ own example; the two group/within orderings only coincide whengroups == C / groups, which is why that example alone cannot distinguish them). Every other axis is untouched, so this works on any(N, C, *)shape without naming the trailing axes. No dedicated kernel or backward rule:splitandmergeare both already differentiable.- Circular
Pad - Circular (wrap-around) padding, covering
CircularPad1d/2d/3d. Matches PyTorch’s own constraint that each side’s padding be at most the axis’s extent (a full wrap is allowed, unlike reflection’s strict<); seecircular_pad_axisfor the composition and its exact gradient. - Constant
Pad - Padding at an arbitrary constant value, covering
ConstantPad1d/2d/3d.ZeroPad’s own zero-padded tensor already has the correct interior (pad_zerosnever touches it) and exact zeros in the border; a second, independent zero-padding of a constant ones mask (Tensor::zeros(..).ge(0.0), which carries no gradient edge of its own) turns into an interior/border indicator, and itslogical_not– exactly zero inside, exactly one in the border – scaled byvalueand added supplies the constant. Backward is therefore identical toZeroPad’s: the border term is a detached constant and contributes no gradient. - Conv1d
- Named-channel 1D cross-correlation. Reuses
Conv2d’s exact geometry, weight layout, and xorshift initialization over a synthetic unit spatial axis appended for the call: a kernel of1, stride of1, and padding of0on that axis is an exact no-op (it always contracts a single, always-in-bounds position), andTensor::broadcast_to/Tensor::selectadd and remove an extent-1 axis with an exact identity gradient, so no separate rank-1 backend path exists. Stride and padding default to1and0; groups default to1, matchingConv2d. - Conv2d
- Named-channel 2D cross-correlation followed by bias addition.
- Conv3d
- Named-channel 3D cross-correlation followed by bias addition.
- Conv
Transpose1d - Named-channel 1D transposed convolution; see
ConvTranspose2dfor the shared contract. ReusesConvTranspose2d’s exact geometry and initialization over a synthetic unit spatial axis, exactly asConv1dreusesConv2d. - Conv
Transpose2d - Named-channel 2D transposed convolution (PyTorch’s
nn.ConvTranspose2d): stride, padding, output_padding and groups are supported; dilation is pinned at1, matchingConv2d. Stride defaults to[1, 1], padding and output_padding to[0, 0], and groups to1. - Conv
Transpose3d - Named-channel 3D transposed convolution; see
ConvTranspose2dfor the shared contract. The three spatial axes conventionally represent depth, height, and width, matchingConv3d. - Data
Loader - Device
- Dim
- Disjointness
- Exact separation across two or more declared populations.
- Disjointness
Receipt - Dropout
- Parameter-free inverted dropout (PyTorch’s
nn.Dropout).forward(evaluation) is the identity: it returns the same tensor unchanged, never a copy scaled by 1.forward_trainingconsumes exactly onepass.next_seed()draw per call, regardless ofp, so a downstream random consumer’s draw sequence does not shift whenpchanges; that seed only feeds an actualTensor::uniform_device(shape, seed, device)draw when0 < p < 1. The mask is generated entirely on the device – never a host-drawn tensor uploaded over PCIe every step – from a counter-based hash of(seed, element index)(seeTensor::uniform_device,backend::kernels::uniform_device); it keeps each element whose draw is>= p, zeroes the rest, and rescales the kept elements by1 / (1 - p)(PyTorch’s inverted dropout), so the output’s expectation matches the input.p == 0returns the input unchanged;p == 1returns exact zeros with exactly zero gradient (PyTorch’s ownp == 1behavior), since1 / (1 - p)is undefined there. Elsewhere the gradient ismask / (1 - p)by construction – a constant{0, 1}mask times a scalar – so no dedicated backward rule is needed. - ELU
- Elementwise ELU with an explicit, finite, nonzero
alpha(PyTorch’s own domain – negativealphaincluded). SeeTensor::elufor the exact forward/backward split atx == 0and the sign-algebra argument for why negativealphais safe here. - Embedding
- Look up one learned feature vector per vocabulary entry.
- Embedding
Bag - One learned feature vector per vocabulary entry, pooled per bag: PyTorch’s
nn.EmbeddingBag. UnlikeEmbedding’s dense one-hot contraction, the input is a host-side flat row-index array together withoffsets(bagbcovers positionsoffsets[b]..offsets[b + 1], or..index.len()for the last bag – exactlytorch.nn.EmbeddingBag.forward’s owninput/offsetspair), so it scales to a large table the same wayTensor::gatheritself does. Does not implementModule, which only threads a single tensor input: the index and offsets are host-side integer arrays, not tensors, exactly asTensor::gather’s ownindexandTensor::scatter_add’s ownindex/bucketalready are. - Empirical
Monotonicity - A sampled check, never a global proof about the represented function.
- Empirical
Monotonicity Receipt - Empirical
Residual - A sampled residual check, never a proof that the represented law holds.
- Empirical
Residual Receipt - ExactGELU
- Parameter-free erf-form GELU for checkpoints trained with exact GELU, which is
PyTorch’s default
nn.GELU(). - Feature
Alpha Dropout - Channel-wise alpha dropout: PyTorch’s
nn.FeatureAlphaDropout,AlphaDropout’s exact affine formula applied to aChannelDropout-shaped mask (one draw per (channel, batch, …) combination, broadcast over the namedspatialaxes) instead of one draw per element. SeeChannelDropoutfor the axis contract andAlphaDropoutfor the formula; this module is their composition, matching PyTorch’s own_feature_alpha_dropout(feature_dropout=true, alpha_dropout=truein the same_dropout_impl). - Finite
Passes - Exact accounting for a declared number of complete finite-corpus passes.
- Finite
Passes Loader - Batches a finite population for exactly N independently shuffled complete passes.
- Finite
Passes Receipt - Flatten
- Merge a run of named axes into one, PyTorch’s
nn.Flattenexpressed over identities instead of a positionalstart_dim/end_dimrange: the caller names the exact axes to fold, in the physical order they should flatten in, and the singleoutputaxis that replaces them. A thinModulewrapper overTensor::merge; see its own doc for the exact selected-axis-order and physical-layout contract this reuses verbatim, including which position the merged axis is inserted at. - Fold
- Named-axis
col2im(PyTorch’snn.Fold), the adjoint ofUnfold: combines an array of sliding local kernel-sized blocks (patchin place of a channel axis) by summing overlapping contributions intooutput_size-shapedspatialaxes, reconstructingchannels(inferred from the input’spatchextent divided by the kernel volume). Rejects an input whose extents are inconsistent withoutput_size/kernel/stride/paddingbefore any device call. Stride defaults to[1, 1]and padding to[0, 0]. - GELU
- Parameter-free tanh-form GELU. PyTorch’s default
nn.GELU()is the erf form,ExactGELU; a faithful port of an un-annotated PyTorch model uses that one. - GLU
- Gated Linear Unit over an explicit named
axis, halved by the gate. SeeTensor::glu. - Group
Norm - Group normalization over channel groups and explicitly named sample axes.
- Gru
- A stacked, optionally bidirectional, eager GRU over one named time axis.
See
Lstm’s doc comment for the eager-transition contract andRecurrentConfigfornum_layers/bidirectional/bias. The default configuration (one layer, unidirectional, bias on) is bit-exact with the single-layer GRU this type used to be. - GruCell
- One PyTorch-form GRU transition with explicit hidden state.
- GruRun
- Sequence output and the per-layer, per-direction terminal hidden states
from one
Grurun, ordered asLstmRun::statedocuments. - Hardshrink
- Parameter-free
Hardshrinkwith an explicitlambd. SeeTensor::hardshrinkfor the exact forward and gradient-at-the-band semantics. - Hardsigmoid
- Parameter-free
Hardsigmoid. SeeTensor::hardsigmoidfor the exact forward and gradient-at-the-kinks semantics. - Hardswish
- Parameter-free
Hardswish. SeeTensor::hardswishfor the exact forward and gradient-at-the-kinks semantics, including its asymmetric boundary convention. - Hardtanh
- Parameter-free
Hardtanhwith explicitmin_val/max_valbounds. SeeTensor::hardtanhfor the exact forward and gradient-at-the-kinks semantics. - Identity
- Parameter-free passthrough, PyTorch’s
nn.Identity: returns its input unchanged. - Identity
Scheme - Names the equivalence relation used to decide whether two observations are the same scientific unit.
- Idr
- Exact observed-ID accounting. Callers choose a stable ID whose equality means reuse.
- IdrLimits
- Declared operational limits for an infinite-data approximation.
- IdrReceipt
- InMemory
Dataset - Instance
Norm - Per-channel instance normalization over explicitly named sample axes.
- JitCache
Stats - Cumulative cuTile JIT disk-cache hit/miss counts for this process, zero for
both fields before any CUDA device has compiled a kernel, or when the cache
is disabled (
AXIS_JIT_CACHE=off) or could not be enabled. SeeDevice::cuda. - LPPool1d
- Named-channel 1D power-average pooling:
(sum(x^p))^(1/p)over each kernel window, independently per channel, matching PyTorch’snn.LPPool1d(f(X) = (sum_{x in X} x^p)^(1/p); atp = 1this is exactly sum pooling, and there is no division by the window size).p(PyTorch’snorm_type) is any finite positive real. An integerpuses repeated products; a realpusesexp(p ln x)with0^p = 0, so a negative input under a non-integerpis NaN, asx.pow(p)is in PyTorch. One deliberate difference remains: an odd integerpwhose window sum is negative returns the real signed rootsign(s) |s|^(1/p), where PyTorch’spow(1/p)returns NaN. Withceil_mode=True, windows are counted as inAvgPool1dand a window clipped at the input edge is(sum * k / clipped)^(1/p), exactly PyTorch’savg_pool(x^p) * kcomposition. PyTorch’sLPPoolhas nopaddingparameter, so none is exposed here either. Stride defaults to the kernel extent, matching every other pooling family in this file. - LPPool2d
- Named-channel 2D power-average pooling; see
LPPool1dfor the shared contract, applied over two spatial axes asMaxPool2dis. - LPPool3d
- Named-channel 3D power-average pooling; see
LPPool1dfor the shared contract, applied over three spatial axes asMaxPool3dis. - LawIdentity
- Stable identity for the scientific law whose residual is being evaluated.
- Layer
Norm - Population layer normalization over one or more declared named axes.
- Leaky
ReLU - Parameter-free leaky ReLU with an explicit negative-region slope. The derivative at exactly zero is the negative slope, matching PyTorch.
- Learning
Limits - Learning
Observation - Learning
Progress - Compares one declared metric on one declared population over an ordered budget.
- Learning
Progress Receipt - Linear
- Contract
input, introduceoutput, and preserve all unrelated axes. Cloning a built Linear explicitly ties its parameters. Carries a learned[output]bias by default;.bias(false)beforebuildomits it entirely, sonamed_parametersthen has onlyweightand no zero-filled bias tensor is ever allocated. - Linear
Cross Entropy Options - Options for
Tensor::linear_cross_entropy_with_logits, mirroringtorch.nn.functional.linear_cross_entropy(input, linear_weight, target, *, linear_bias=None, weight=None, reduction='mean', ignore_index=None, label_smoothing=0.0, options=None)(PyTorch 2.14, added to fuse a finalLinearprojection withcross_entropyso the full[*, n_classes]logits tensor is never materialized at large vocabularies). Onlylabel_smoothingis exposed here:reductionis left to the caller viaTensor::mean/Tensor::sumon the class-reduced result, matching every other loss in this file (multilabel_soft_margin_loss,binary_cross_entropy_with_logits); per-classweightandignore_indexare not implemented (this composition uses soft/one-hot probability targets, matchingcategorical_cross_entropy_with_logits, not sparse class-index targets with a sentinel to ignore); and PyTorch’soptions=chunked fast path has no analogue (seelinear_cross_entropy_with_logits’s own doc comment for why). - Local
Response Norm - Response normalization across a fixed-size sliding window of a named
channel axis, PyTorch’s
nn.LocalResponseNorm: each element divides by(k + alpha / size * sum(a_c'^2))^beta, where the sum runs over a window ofsizechannels aroundc, padded with implicit zeros at the channel-axis boundary (size / 2channels beforec,(size - 1) / 2after, PyTorch’s own asymmetric split for an evensize). No learned parameters, matching PyTorch’s own stateless module. - LogSigmoid
- Parameter-free numerically stable log-sigmoid. See
Tensor::log_sigmoid. - LogSoftmax
- Numerically stable log-softmax over an explicit named
axis. SeeTensor::log_softmax. - Lstm
- A stacked, optionally bidirectional, eager LSTM over one named time axis.
- Lstm
Cell - One standard IFGO LSTM transition with explicit hidden and cell state.
- LstmRun
- Sequence output and the per-layer, per-direction terminal recurrent
states from one
Lstmrun.state[layer * directions + direction](direction0 = forward, 1 = backward when bidirectional), matching PyTorch’s(num_layers * num_directions, batch, hidden)stacking order. - Lstm
State - Explicit recurrent state. Both tensors contain the same named stream axes and the LSTM’s hidden axis.
- MaxPool1d
- Named-channel 1D max pooling; see
MaxPool2dfor the shared contract, applied along one spatial axis. - MaxPool2d
- Named-channel 2D max pooling: reduce each kernel window to its maximum, independently per
channel. Stride defaults to the kernel extent and padding to
[0, 0], matching PyTorch’snn.MaxPool2d. Spatial arrays are ordered as the supplied named axes, preserved (at their new, pooled extent) in their original position; the channel axis is appended, exactly asConv2dappends its output-channel axis. Padding must be at most half the kernel extent in each dimension (PyTorch’s ownMaxPoolconstraint); a padded position can never win the maximum. Ties route the gradient to the first logical coordinate along each spatial axis, independently of physical layout, matchingTensor::min. - MaxPool3d
- Named-channel 3D max pooling; see
MaxPool2dfor the shared contract. The three spatial axes conventionally represent depth, height, and width, and its kernel/stride/padding arrays use that same supplied order, matchingConv3d. - MaxUnpool1d
- Named-axis 1D max unpooling, PyTorch’s
nn.MaxUnpool1d: the partial inverse ofMaxPool1d, scattering each input value to the position its index names in a zero output and leaving every other position zero.indicesareMaxPool1d::forward_with_indices’s, one per input element in its logical order; seeTensor::max_unpool3dfor duplicates and the gradient (a gather of the upstream gradient by the same indices). Stride defaults to the kernel extent and padding to0; the output extent defaults to(in - 1) * stride - 2 * padding + kernel, and an explicit one (to undo a pool whose floor division dropped a remainder) must lie strictly withinstrideof that default, as PyTorch requires. Not aModule: like PyTorch’s, its forward takes the indices as a second input. - MaxUnpool2d
- Named-axis 2D max unpooling, PyTorch’s
nn.MaxUnpool2d; seeMaxUnpool1dfor the shared contract. Its indices areMaxPool2d::forward_with_indices’s, row-major offsets into the output’s spatial plane in the supplied spatial order. - MaxUnpool3d
- Named-axis 3D max unpooling, PyTorch’s
nn.MaxUnpool3d; seeMaxUnpool1dfor the shared contract. Its indices areMaxPool3d::forward_with_indices’s. - Mish
- Parameter-free Mish,
x * tanh(softplus(x)). SeeTensor::mish. - Module
Dict - Named collection of modules with no forward of its own, insertion-ordered
like PyTorch’s
OrderedDict-backednn.ModuleDict. SeeModuleList’s own doc for the shared no-forward/aggregation contract; slots here are addressable as"{key}.{name}". Duplicate keys are rejected before any module is built. - Module
List - Ordered collection of modules with no forward of its own, PyTorch’s
nn.ModuleList: PyTorch’s ownnn.Module.forwardon it raisesNotImplementedError, since only a subclass that actually threads data through its children – such asSequential– has one, sooutput_shape/build/forwardbelow each return an explicit error instead of guessing an order. Build and run a held module directly throughModuleList::get/ModuleList::get_mut/ModuleList::iter.named_parametersstill aggregates every held module’s own parameters underSequential’s own slot-path convention,"{index}.{name}"(e.g."0.weight"), so they stay addressable throughmodel.parameter(path)even though nothing here threads a single input through them in order.ModuleDict,ParameterList, andParameterDictshare this exact contract, keyed or indexed differently. - Monotonicity
Limits - Multihead
Attention - Scaled dot-product multi-head attention,
torch.nn.MultiheadAttentionat its own defaultdropout=0.0:Attention(Q, K, V) = softmax(QK^T / sqrt(head_feature)) V, computed independently per head and concatenated before one output projection (PyTorch’sforward,batch_first-agnostic since Axis has no positional batch axis to begin with). - Muon
- Momentum updates orthogonalized by five Newton-Schulz iterations.
- Muon
Matrix - A parameter selected for Muon together with its matrix orientation.
- Muon
With AuxAdamW - Explicitly routes selected rank-2 parameters to Muon and the exact remainder to AdamW. No shape-based selection occurs.
- PReLU
- Parametric ReLU with a learnable weight, either shared across every element
(
PReLU::shared, PyTorch’s defaultnum_parameters=1) or one per entry of an explicit named channel axis (PReLU::channel, PyTorch’snum_parameters=C); both start at PyTorch’s default init,0.25. SeeTensor::prelu. - ParamId
- Parameter
- Cloning explicitly shares a parameter, including its accumulated gradient.
- Parameter
Dict - Named collection of standalone parameters, not owned by any module:
PyTorch’s
nn.ParameterDict. SeeModuleList’s own doc for the shared no-forward/aggregation contract; slots here are addressable by key. Duplicate keys are rejected immediately. - Parameter
List - Ordered collection of standalone parameters, not owned by any module:
PyTorch’s
nn.ParameterList. SeeModuleList’s own doc for the shared no-forward/aggregation contract; slots here are addressable by index,"{index}". - Pixel
Shuffle - Sub-pixel upscaling: rearrange
channel(extentC * factor^2) intofactorblocks along each of the two namedspatialaxes, expanding each byfactorand shrinkingchanneltoC. PyTorch’s ownpixel_shuffledecomposition – reshape the channel axis to(C, factor, factor), permute to interleave eachfactoraxis with its spatial axis, then flatten – is exactlyTensor::split(channel into[out_channel, row_factor, col_factor], outermost first) followed by twoTensor::mergecalls ([height, row_factor],[width, col_factor], spatial axis outermost so it varies slower than its own sub-pixel offset). No dedicated kernel or backward rule:split/mergeare both already differentiable. - Pixel
Unshuffle - The exact inverse of
PixelShuffle: shrinkchannel’s two namedspatialaxes byfactoreach and growchannelbyfactor^2. Composed asTensor::spliton each spatial axis ([outer, sub_pixel], spatial axis outermost, undoingPixelShuffle’s merge order exactly) followed by oneTensor::mergeof[channel, row_factor, col_factor]into the new channel axis (undoingPixelShuffle’s split order exactly). - Population
Linear - A family of independent linear maps sharing one explicit population axis. Inputs without the population axis are broadcast to every member; inputs already carrying it keep memberwise independence through later layers.
- Population
Receipt - Population
Spec - Position
Embedding - Add one learned vector per position: a
[position, feature]table whose extents are read from the input at build and broadcast over every other axis. The output shape equals the input shape. Entries start uniform in[-0.02, 0.02). - Prefix
Dropout - Prefix (nested) dropout (Axis issue #90; no PyTorch class –
docs/direction/next.md‘s tracked next implementation): truncates a tensor to its firstwpositions along one named orderedaxis, withwdrawn independently per training example, so one trained model yields a whole width sweep at evaluation time (the consumers’ own framing:learning/bae’s ordered sign code andvision/image-encode’s ordered latent/site lists, both cited on the issue). Every axis of the input other thanaxisitself is an “example” axis: each combination of their coordinates draws its own independent width, exactly likeChannelDropout’s non-spatial axes.forward(evaluation) is the identity – the full, untruncated tensor, matching “evaluation keeps everything.”forward_trainingconsumes exactly onepass.next_seed()draw, feeding oneTensor::uniform_devicecall over the example axes alone (so the draw is per example, not per element):w = draw * (extent(axis) + 1), a real value in[0, extent + 1), compared against a constant0 .. extentposition tensor alongaxis(Tensor::broadcast_tocombines the two disjoint axis sets – the per-example width and the per-position index – onto one shared shape first, exactly thetorch.cdist-style outer-combination idiombroadcast_to’s own doc comment describes). Positionisurvives exactly wheni < w: sincewis real-valued andiis an integer, this keepsfloor(w) + 1positions in the generic case (wessentially never lands exactly on an integer), so the kept prefix length is uniform over{1, ..., extent}(extentitself whenwlands in its last unit interval;0only at the zero-probability exact draww == 0) – the discrete-uniform-width contractnested.py’ssample_kandstage_a.py’sarange(width) < mboth draw, restated without a host round trip. No rescaling is applied: unlikeDropout’s inverted scaling, this is a hard truncation mask with expectation<= 1, not an expectation-preserving Bernoulli mask, matchingarange(K) < min both cited consumers exactly. The kept gradient passes through unchanged and the dropped gradient is exactly zero, the same constant-mask constructionDropoutalready uses. - RReLU
- PyTorch’s
nn.RReLU(randomized leaky ReLU, Xu et al. “Empirical Evaluation of Rectified Activations in Convolutional Network”). Defaultslower = 1 / 8,upper = 1 / 3, PyTorch’s own defaults.forward(evaluation) isTensor::leaky_reluat the fixed slope(lower + upper) / 2, PyTorch’s documented evaluation behavior.forward_trainingdraws a fresh independent slope per element, uniform in[lower, upper), from onepass.next_seed()draw fed to oneTensor::uniform_devicecall scaled into that range (lower + (upper - lower) * draw, the constantlowershift built withTensor::from_sliceexactly likeAlphaDropout’s constant term); every element keepsinputunchanged whereinput > 0and multiplies by its own per-element slope elsewhere –0itself takes the scaled branch, matching PyTorch’sx <= 0test. Both partition masks are built once (input.gt(0.0)and itslogical_not) and reused, so their probabilities are exactly complementary by construction rather than by two independent comparisons. - ReLU
- ReLU6
- Parameter-free
ReLU6:Hardtanhwith fixed bounds0and6. SeeTensor::relu6for the exact forward and (strictly-interior) backward semantics. - Recurrent
Config - Shared depth/direction/bias configuration for
Rnn,GruandLstm. PyTorch’sRNNBaseplays this role for its three subclasses, but it also owns shared weight storage and flattening behavior that Axis’s three families do not share (each keeps its own gate layout and init convention, matchingLstmCell’s existing precedent of not introducing a second parameter convention).RecurrentConfigis the honest analogue: the three fields every family’s constructor actually shares, reused verbatim byRnn::with_config,Gru::with_configandLstm::with_config, with no shared class behavior invented beyond that. - Reflection
Pad - Reflection padding, covering
ReflectionPad1d/2d/3d. Matches PyTorch’s own constraint that each side’s padding be strictly less than the axis’s extent (checked before launch, inreflect_source’s doc); seeedge_padfor the composition and its exact gradient. - Regime
Snapshot - Replication
Pad - Edge replication padding, covering
ReplicationPad1d/2d/3d. No pad-size constraint beyond the shared overflow check: seeedge_padfor the composition and its exact gradient. - Residual
Limits - Residual
Scope - Declares what residual was evaluated, where, and by which numerical method.
- RmsNorm
- Root-mean-square normalization over one or more declared named axes.
- Rnn
- A stacked, optionally bidirectional, eager Elman RNN over one named time
axis. See
Lstm’s doc comment for the eager-transition contract andRecurrentConfigfornum_layers/bidirectional/bias. The default configuration (one layer, unidirectional, bias on) is bit-exact with the single-layer RNN this type used to be. - RnnCell
- One Elman RNN transition,
h' = nonlinearity(W_ih x + b + W_hh h), with explicit hidden state.nonlinearitydefaults toTanh(PyTorch’sRNNCell(nonlinearity="tanh")default);.nonlinearity(Relu)matchesnonlinearity="relu". MirrorsLstmCell’s single combined bias (rather than PyTorch’s separatebias_ih/bias_hh) and its Xavier-uniform initialization (rather than PyTorch’suniform(-1/sqrt(hidden), 1/sqrt(hidden))); Axis’s ownLstmdoes not match PyTorch’s parameter layout or init either, soRnnCellfollowsLstmCell’s convention instead of introducing a second one.biasdefaults totrue(PyTorch’s default);.bias(false)matchesbias=False. - RnnRun
- Sequence output and the per-layer, per-direction terminal hidden states
from one
Rnnrun, ordered asLstmRun::statedocuments. - SELU
- Parameter-free SELU: PyTorch’s fixed-constant self-normalizing activation.
See
Tensor::selufor the exact constants. - SGD
- Sample
- Sequential
- Shape
- SiLU
- Parameter-free sigmoid linear unit,
x * sigmoid(x). - Sign
Straight Through - Parameter-free sign quantization to
{-1, +1}with a straight-through backward. SeeTensor::sign_straight_throughfor the exact forward and backward semantics this reproduces from bae’sbitae.quantize. - Single
Pass - A count-only invariant for a loader that promises unique examples within one pass. This proves the consumption budget, not the loader’s uniqueness promise.
- Softmax2d
- Softmax over an explicit named
channelaxis of a[channel, height, width]input (PyTorch’sSoftmax2d, which requires exactly that rank). Delegates to the existing named-axisTensor::softmax;height/widthexist to state and check the contract, sincesoftmaxalready treats every other axis independently. - Softmin
- Softmin over an explicit named
axis. SeeTensor::softmin. - Softplus
- Elementwise Softplus with explicit
beta/threshold, defaulting to PyTorch’s ownbeta = 1,threshold = 20. SeeTensor::softplusfor the exact branch seam. - Softshrink
- Parameter-free
Softshrinkwith an explicitlambd. SeeTensor::softshrinkfor the exact forward and gradient-at-the-band semantics. - Softsign
- Parameter-free
Softsign. SeeTensor::softsignfor the exact forward and backward semantics (smooth everywhere, no true kink). - Standardizer
- A train-fitted affine standardization transform.
- State
- A persistent non-parameter tensor a module owns across training steps –
BatchNorm-style running statistics, reported byModule::named_states. Cloning explicitly shares the same storage, likeParameter, but aStatecarries no gradient and is never touched by an optimizer: the only writer isTrainingPass::commit, which applies every update aforward_trainingcall queued withTrainingPass::stage. Nothing ever writes aStateoutside that commit, so a forward pass alone – training or not – is side-effect free, and a failed training step (a panicking or error-returning loss, a failed backward or optimizer step) leaves everyStateexactly as it was. - Tanh
- Parameter-free elementwise hyperbolic tangent module.
- Tanhshrink
- Parameter-free
Tanhshrink. SeeTensor::tanhshrinkfor the exact forward and backward semantics (smooth everywhere, no true kink). - Tensor
- Immutable values. Clones share a graph node;
detachstarts a new, untracked leaf. - Threshold
- Parameter-free
Thresholdwith an explicitthreshold/value. PyTorch requires both explicitly (no defaults); seeTensor::thresholdfor the exact forward and gradient-at-the-kink semantics. - Train
Step - Trainer
- Training
Pass - The explicit per-step training context threaded through
Module::forward_training.Trainer::step_trainingbuilds one from(run_seed, completed_steps); a caller drivingforward_trainingoutside theTrainer– a test, or a custom loop – builds one directly withTrainingPass::new. - Transformer
torch.nn.Transformer: oneTransformerEncoderbuilt fromnum_encoder_layerscopies of aTransformerEncoderLayerplus a finalLayerNorm, and oneTransformerDecoderbuilt the same way fromnum_decoder_layerscopies of aTransformerDecoderLayer, sharingfeature/time/embed_dim/num_heads/dim_feedforwardand every dropout/activation/epsilon/norm_first/bias setting.forwardencodessrcintomemorythen decodestgtagainst it, PyTorch’s own two-call composition. There is nocustom_encoder/custom_decoderoverride: Axis has noModule-shaped container that fits a differently-typed encoder/decoder pair interchangeably here, so a fully custom pair is built directly fromTransformerEncoder/TransformerDecoderinstead.- Transformer
Decoder torch.nn.TransformerDecoder: the decoder-layer analogue ofTransformerEncoder, sharing its independent-clone stacking convention and optional finalLayerNorm.- Transformer
Decoder Layer - One post-/pre-norm Transformer decoder block,
torch.nn.TransformerDecoderLayerat the same PyTorch 2.14 defaults asTransformerEncoderLayer. Masked self-attention overtgt, then cross-attention (multihead_attn) whose query istgtand whose key/value arememory, then the same feedforward block, with PyTorch’s own_sa_block/_mha_block/_ff_blockinlined: - Transformer
Encoder torch.nn.TransformerEncoder:num_layersindependently built copies of one configured, unbuiltTransformerEncoderLayer(cloned beforebuild, mirroring PyTorch’s own_get_clones), plus an optional finalLayerNorm. Each clone gets its own freshly seeded parameters atbuildtime rather than PyTorch’s literal deep-copy-of-already-initialized weights (PyTorch’s_get_clonesrunscopy.deepcopyon one already-built layer, so every layer starts from bit-identical initial weights) – deliberately following Axis’s own stacking convention instead (every index-seeded container in this crate, e.g.Sequential::build, gives each position a distinct seed) and the design doc’s “Repeatmust create independent blocks unless weight tying is explicit”.- Transformer
Encoder Layer - One post-/pre-norm Transformer encoder block,
torch.nn.TransformerEncoderLayerat PyTorch 2.14’s exact defaults (dim_feedforward=2048,dropout=0.1,activation="relu",layer_norm_eps=1e-5,norm_first=False,bias=True) and PyTorch’s own exact residual/dropout structure –_sa_block/_ff_blockinlined here as private helpers of the same name: - Unflatten
- Split one named axis into an ordered list of named axes whose extents
multiply back to it, PyTorch’s
nn.Unflattenover identities instead of a positional dim and an unnamed size tuple. A thinModulewrapper overTensor::split; see its own doc for the exact validation and physical layout it reuses verbatim. - Unfold
- Named-axis
im2col(PyTorch’snn.Unfold): extracts sliding local kernel-sized blocks, replacingchannelsin place withpatch(extentchannels * kernel volume) and shrinkingspatialto their windowed count. Out-of-bounds (padding) positions read0.0. Stride defaults to[1, 1]and padding to[0, 0]. Stateless:buildonly validates and infers the output shape. - Upsample
torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align_corners=None)over a fixed, ordered list of named spatial axes (PyTorch infers 1D/2D/3D from the input’s trailing dims; here the axes are named explicitly instead, so any rank works). Build withUpsample::size(a literal per-axis output extent, PyTorch’ssize=) orUpsample::scale_factor(a per-axis multiplier, PyTorch’sscale_factor=) – exactly one form, matching PyTorch’s own mutual exclusivity.- ZeroPad
- Exact zero padding, covering
ZeroPad1d/ZeroPad2d/ZeroPad3d(see the tuple-to-axis mapping abovevalidate_pad_list). Composed entirely from repeatedTensor::pad_zeros, one call per listed axis; backward ispad_zeros’s own exact crop, so a source element’s gradient is unaffected by padding.
Enums§
- Attention
Mask - An additive (
f32, added to pre-softmax scores;-infinityor a large negative forbids a query/key pair) or booleanattn_maskforMultiheadAttention. The boolean variant uses PyTorch’s own convention: a1.0entry forbids that query/key pair from attending,0.0allows it – the opposite sense fromTensor::masked_softmax’s own validity mask, whichMultiheadAttentioninverts internally before calling it. - Data
Regime Receipt - Disjointness
Evidence - The strength of the evidence recorded by a disjointness receipt.
- Embedding
BagMode - Pooling mode for
EmbeddingBag, matching PyTorch’smodeargument. - Kernel
Spec - Physical kernel shapes for
crate::Device::prepare_kernels. - Learning
Direction - Learning
Evidence - The strength of the claim made by a learning-progress receipt.
- Monotone
Direction - Muon
Matrix Orientation - The storage orientation of one explicitly selected Muon matrix.
- Population
Mode - Whether the ledger keeps identities after checking an observation.
- Residual
Claim - The claim made by this receipt. A guaranteed law requires a separate, construction-backed API and cannot be selected by a caller here.
- Residual
Evidence - RnnNonlinearity
- The pointwise nonlinearity applied at each
Rnn/RnnCelltransition. PyTorch’s default isTanh;Relumatchesnonlinearity="relu". - Transformer
Activation - Encoder/decoder feedforward nonlinearity,
torch.nn.TransformerEncoderLayer’sactivationargument restricted to its two string spellings ("relu"/"gelu"; a custom callable has no analogue here). PyTorch’s own_get_activation_fnmaps"gelu"toF.geluat its defaultapproximate="none"– the exact erf form,Tensor::gelu_exact/ExactGELUin this crate, not the tanh-formGELUmodule. - Upsample
Mode torch.nn.Upsample’s interpolation mode (mode=).
Traits§
- Data
Source - A source may be finite or generated.
Noneavailability means no finite corpus exists. - Into
Axes - Into
Layers - Module
- Optimizer
Functions§
- clip_
grad_ norm - PyTorch’s
clip_grad_norm_(https://docs.pytorch.org/docs/2.14/generated/torch.nn.utils.clip_grad_norm_.html): one global L2 norm over every listed parameter’s accumulated gradient together, not a per-tensor norm. Every gradient is rescaled by the SAME factormax_norm / (total_norm + 1e-6), and only whentotal_normexceedsmax_norm; below the threshold every gradient is left bit-exact, never renormalized to exactlymax_norm. Returns the pre-clip total norm either way, matching PyTorch’s own return value. - cosine_
annealing_ lr - Cosine-annealed learning rate at
step(0-indexed), matching PyTorch’sCosineAnnealingLRclosed form (https://docs.pytorch.org/docs/2.14/generated/torch.optim.lr_scheduler.CosineAnnealingLR.html): - jit_
cache_ stats - Snapshot of the cuTile JIT disk cache’s cumulative hit/miss counts for this process. Always zero in the docs.rs build, which has no CUDA runtime and never creates a device.
- one_
cycle_ lr - One-cycle learning rate at
step(0-indexed oftotal_steps), matching PyTorch’sOneCycleLRat its own defaults (https://docs.pytorch.org/docs/2.14/generated/torch.optim.lr_scheduler.OneCycleLR.html): a cosine warmup frommax_lr / div_factorup tomax_lrover the firstpct_startfraction oftotal_steps, then a cosine anneal down tomax_lr / div_factor / final_div_factor. PyTorch’s own closed form (torch/optim/lr_scheduler.py,_annealing_cosandOneCycleLR.get_lr):