# LittleEngine Core LittleEngine is a general-purpose PyTorch library for building architectures tailored to your task and training new models from scratch. It provides expressive, size-efficient transformer layers, construction helpers, positional encodings, and optimizers designed and ablated to work well together—from embedding models and image encoders to super-resolution and experimental architectures. You choose the architecture; LittleEngine supplies compatible building blocks, including extensive infrastructure for ultra-long-context image encoders. A future, separate SDK will build on Core to provide application-domain-specific project templates and training workflows. The goal is to reduce the boilerplate and cognitive effort between an architectural idea and a working model. Components expose the choices that matter while sharing conventions for initialization, token geometry, parameter metadata, and optimization. Core focuses on model definition and optimization. The planned sibling SDK will provide training and experiment management, primarily targeting distributed training through PyTorch Lightning. ## What's included | Area | Functionality | |---|---| | **Attention** | Self- and cross-attention, grouped-query attention, Q/K normalization, output gating, rotary positions, and independently optional Q/K/V/O projections for externally projected inputs. | | **Attention construction** | Helpers for dense PyTorch SDPA and FlexAttention-backed Sliding Tile Attention, including shared masks and positional modules. | | **Feed-forward layers** | Configurable MLPs, ReLU² MLPs, and SwiGLU, with explicit expansion and output-initialization controls. | | **Convolution** | [Gated convolutional units](src/little_engine_core/conv/README.md) on pixel or latent token grids, with dense/grouped/depthwise mixers and linear/bilinear gates. | | **Normalization** | Parameter-free RMS normalization and experimental local mean subtraction over token grids. | | **Position embeddings** | Clifford absolute embeddings and multidimensional Golden Gate RoPE, adapted for dense and sparse attention with dynamic inference geometry. | | **Token geometry** | Explicit raster descriptions, coordinate generation, and reversible layout conversions with registered permutation modules. | | **Parameter management** | Inline parameter roles and hyperparameter hints, inspectable metadata tables, and optimizer parameter-group construction. | | **Optimizers** | Muon, NorMuon, role-aware AdamW, and `MuonAdam`, which routes parameters through a unified optimizer interface. | These are ordinary PyTorch modules and utilities. Use individual components or assemble a stack with the construction helpers. ## The glue is part of the library A model's behavior depends on more than its layer equations. Initialization, parameter grouping, learning-rate conventions, and weight decay all need to agree. LittleEngine carries this information alongside the model. Layers declare semantic parameter roles; optimizer policies use those roles and any explicit overrides to choose parameter treatment. The resulting decisions are inspectable, so you can see which optimizer, learning rate, and weight decay each parameter receives. `MuonAdam` brings this together by routing eligible matrix parameters to Muon and other parameters to AdamW. The metadata machinery also supports constructing parameter groups for other PyTorch optimizers. ## Dense and sparse attention LittleEngine supports both global dense attention and Sliding Tile Attention (STA), which organizes local attention around contiguous token tiles. Dense attention is a strong choice for smaller grids. PyTorch's SDPA is often fast and simple, and can remain competitive as token grids grow. The best attention configuration depends on your geometry and hardware. STA adds a useful locality bias and makes larger token grids practical. Together with our position schemes, it also supports changing inference geometry. Support for changing canvas size does not guarantee a trained model's extrapolation quality. Both approaches use the same attention primitives and parameter conventions, making mixed dense/local stacks straightforward to construct. `Attention.forward` requires an `attention_op` callable and accepts extrinsic `rope` (or independent `rope_q` / `rope_k`) and `block_mask` arguments. The caller owns backend options such as `enable_gqa`. The construction helpers provide these arguments and register their resources in one `AttentionLayers` module: ```python # In the owning module's __init__: self.attention = make_dense_attention( 6, canvas_shape_tokens=(14, 14, 1, 1, 1), d_model=384, n_heads=6, rope={"axes": "xy"}, ) # In forward, with normalization/residual policy chosen by the caller: y = self.attention.forward_layer(i, query, context) # Equivalently: y = self.attention.layers[i](query, context, **self.attention.attention_args(i)) ``` Import `make_dense_attention` or `make_sta_attention` from `little_engine_core.attn`. For multi-head self-attention, `n_heads` splits `d_model` into hardware-friendly heads; add `d_head` for other widths. Use `resolve_attention_dims` to preview how omitted head counts and widths resolve, including for GQA and cross-attention. Either helper also accepts explicit `layers=[...]` instead of common layer constructor options, allowing different head and projection configurations. Shared masks and positions are registered once per collection; parent `.to()` moves their state without rebinding callables. For standalone masks, register a `BlockMaskModule` and pass its current `.block_mask` to attention. Fixed layout transforms use `Rearrange(src, dst)` from `little_engine_core.canvas`, whose integer index buffer also follows `.to()`. GGRoPE binds its token canvas at construction and is called as `rope(tensor)`. Construct new geometry-bound components for a new canvas and retain/load the original frequency buffers to preserve positional scaling. Derived rotations are excluded from checkpoints and rebuilt after loading or device/dtype moves. Runtime mask and permutation caches are no longer part of the API. Clifford absolute embeddings and Golden Gate RoPE (GGRoPE) are our safe default choices for positional encoding. We adapted both for this library's dense and sparse attention layers, preserving STA's ability to choose dynamic inference geometry. Clifford embeddings add position to token features; GGRoPE applies position through query/key rotations, and the two can be used together. Their coordinate-based construction needs no position-table interpolation when the canvas changes. See the [position module docstrings](src/little_engine_core/position.py) for motivation, usage, and reference-window scaling, or the [ViT example](examples/vit.py) for a stack using both. ## Explicit geometry, flexible layouts The caller owns the residual tensor's layout. Before invoking a layer, arrange the tensor into its expected working dimensions, token order, and storage format. Layers assume that preparation is already done. The caller handles layout transitions, keeps positions and masks aligned with the tokens, and ensures residual branches have compatible layouts before combining them. Each layer's docstring describes its input/output layout contract. Layers that share a contract may refer to an exemplar layer's docstring and state their differences. This keeps layout concerns outside layers while making their assumptions explicit. Grid-aware components share an `(x, y, z, t, w)` geometry convention. Unused dimensions have extent one, so ordinary sequences and 2D images fit naturally. The `w` axis can represent co-located token groups. `Canvas` describes tensor dimensions and coordinate traversal; `TensorLayout` adds a storage preference. `pixel_grid`, `raster`, and `conv_grid` build common layouts, and `Rearrange` converts between them. Feature width is inferred from inputs and does not enter permutation buffers. See the [canvas guide](src/little_engine_core/canvas/README.md). ```python from little_engine_core.canvas import pixel_grid, raster, Rearrange pixels, patch = (224, 224, 1, 1, 1), (16, 16, 1, 1, 1) image = pixel_grid(pixels) packed, tokens = raster(pixels, patch) patchify = Rearrange(image, packed, mode="einops") unpatchify = Rearrange(packed, image, mode="einops") ``` The packed layout describes raw patch features; the token layout describes the learned projection's output. Pass the token layout to Clifford with `canvas=tokens` to generate coordinates for its configured axes, or supply custom, already selected coordinates with `coordinates=coords`. Attention helpers accept `canvas=`; STA additionally takes explicit `tile_shape_tokens`, windows, and stride geometry. Returned `to_attention[i]` and `from_attention[i]` modules are invoked by the caller, never by `forward_layer`. An optional `mask_canvas` controls mask interpretation independently of physical coordinate identities. Use the canvas API for geometry and layout conversion throughout the model. See [ViT](examples/vit.py) for an integrated example. Patch features flatten in `pt,pz,py,px,pw,c` order, with channels fastest. When importing a convolution kernel as a patch projection, reorder its input-channel and patch dimensions to match before flattening. At smaller dataset sizes, stacks with more convolution layers and a few interleaved attention layers tend to offer a better tradeoff between model quality and training cost. As dataset size grows, the Pareto-efficient balance tends to shift toward more attention and fewer convolution layers. This is whole-model training guidance; individual convolution layers are not necessarily faster than attention. ## Examples - **[CIFAR-10](examples/cifar10_minimal.py)** demonstrates the interaction between model layers, parameter metadata, and the shipped `MuonAdam` optimizer. It prints the optimizer's parameter treatment and runs a small training example. - **[ViT-style backbone](examples/vit.py)** demonstrates assembling attention, positional embeddings, feed-forward layers, and residual blocks into an image encoder. ## Getting started The current package requires Python 3.12 or later and targets PyTorch 2.13 with torchvision 0.28. Install from the repository root: ```bash python -m pip install -e . ``` Run the optimizer integration example: ```bash python examples/cifar10_minimal.py ```