# U-MoLT on BlaGPT A minimal U-shaped Mixture-of-Loops Transformer (U-MoLT) implementation ported incrementally onto an official BlaGPT clone. All upstream BlaGPT files remain untouched; the new model is automatically registered through BlaGPT's built-in `@register_model` decorator and selected at training time via `--model_name umolt`. The MoLA kernel is included in this repository. Upstream repository: `https://github.com/erogol/BlaGPT.git` Pinned base commit: `f89d38c5dba3938a048ef0f5a4dd09d18216f96d`, recorded in [UMOLT_UPSTREAM.json](UMOLT_UPSTREAM.json). This directory preserves the cloned `.git` metadata. ## Added Files | File | Purpose | | --- | --- | | [bla_gpt/u_molt.py](bla_gpt/u_molt.py) | All model computation, config, BlaGPT registration, unrolled and recurrent inference | | [libs/mola_triton](../../libs/mola_triton) | FlashAttention and Triton implementation of the MoLA joint softmax | | [configs/umolt_s.json](configs/umolt_s.json) | Paper Table 2 (26): 6+6 layers, 768 hidden, 12/3 GQA, sparse Loop KV & MoLA (`[0, 2, 4]`), full current-loop depth history, 1:1 loop loss, Muon (3B tokens) | | [tests/test_mola_triton.py](tests/test_mola_triton.py) | CUDA forward/backward and dispatch unit tests for `libs/mola_triton` | | [requirements-umolt.txt](requirements-umolt.txt) | Minimal dependencies required by this model and the binary-shard training entry point | | [UMOLT_UPSTREAM.json](UMOLT_UPSTREAM.json) | Upstream repository URL and pinned base commit | | `README_UMOLT.md` | Algorithmic conventions, usage instructions, and port scope | ## Mapping Between Model and Paper The code is extracted from the eager path of the existing research implementation and distilled to the components required for U-MoLT. Class and configuration names follow the paper terminology, with no legacy aliases from earlier experiments. | Paper Concept | Code | Preserved Semantics | | --- | --- | --- | | U-MoLT | `UMoLT`, `UMoLTConfig` | Distinct parameters across layers; the same parameter set is shared across loops | | MoLT Encoder | `MoLTEncoder` | Each loop restarts from the same token embeddings and clears the current-loop depth bank | | Loop KV | `loop_kv_layers`, `project_memory` | The previous loop's normalized encoder source is projected through each reader's dedicated memory KV projection to replace sequence KV, allowing only `j < t` | | MoLA | `MoLA`, `flash_mola` | Uses a single shared softmax over sequence KV and same-token, current-loop depth KV | | Local depth source | `depth_sources` | Writers store the local KV computed from the layer input—never memory KV and never the block output | | MoLT Decoder | `MoLTDecoder` | Initialized from the raw encoder residual; the normalized encoder source provides cross KV, allowing `j <= t` | | QK normalization | `RMSNorm`, `_rope` | Head-wise RMSNorm applied before RoPE; writer depth keys are not normalized a second time | By default, all encoder layers act as Loop KV and MoLA readers. In the first loop, Loop KV layers attend to **strict-prefix local KV** (`j < t`); in subsequent loops, they attend to **strict-prefix previous-loop memory KV** (`j < t`). The first loop uses neither zero memory nor inclusive self-attention. The current token's input is preserved through the residual path and depth slots. If an attention source set is empty, the attention output is zero. `depth_sources="full"` includes all earlier encoder writers plus the strict reader's own local slot; if an ordinary inclusive reader is selected, its own slot (already present on the sequence diagonal) is not added a second time. `depth_sources="first"` has every reader read writer 0 once, deduplicating the first/own alias at layer 0. `loop_kv_layers=null` selects all encoder layers, and `mola_layers=null` follows `loop_kv_layers`. In `configs/umolt_s.json` (paper Table 2, method (26)), both are set to `[0, 2, 4]` for sparse alternating placement, while layers `[1, 3, 5]` perform ordinary causal self-attention. Setting `mola_layers=[]` disables depth retrieval. The decoder contains only causal cross-attention and an FFN—there is no decoder self-attention, decoder depth bank, or decoder-to-encoder feedback. Every decoder layer has its own KV projections; sharing the encoder source does not mean sharing projected KV. Pre-norm is used by default, while `norm_placement="post"` preserves the post-norm block and non-affine embedding norm. ## Training Run from the root of this directory. Install the dependencies on the target training machine: ```bash python -m pip install -r requirements-umolt.txt torchrun --standalone --nproc_per_node=1 bla_gpt/train.py \ --model_name umolt \ --config configs/umolt_s.json \ --run_name umolt_s ``` BlaGPT's native `train.py` requires CUDA/NCCL. For multi-GPU runs, adjust `--nproc_per_node` and ensure that `batch_size` is divisible by `device_batch_size * num_gpus`, and `val_tokens` is divisible by `device_batch_size * sequence_length * num_gpus`. The `input_bin` and `input_val_bin` fields in the configs point to tokenized binary shards in BlaGPT format; update them to match your actual data paths. No training data is included in this directory. To download or prepare data, refer to the upstream [README.md](README.md) and the `data/` scripts, which may require additional packages from the upstream `requirements.txt`. `UMoLTConfig` defaults to two loops, detached cross-loop feedback gradients, and normalized `1:2` loop loss weights: `loss = (CE_loop1 + 2 * CE_loop2) / 3`. `configs/umolt_s.json` matches paper Table 2 (26): `detach_loop_memory=false`, equal `1:1` loop loss weights (`[1.0, 1.0]`), sparse `[0, 2, 4]` Loop KV and MoLA placement, Muon (`lr=1e-3`, `batch_size=512`, `5,722` iterations = 3B tokens, `seed=11`), and `compile_model=true`. Detaching (when enabled) only cuts cross-loop memory and does not detach the current loop's decoder source. The training entry point returns the weighted scalar loss, whereas `model.eval()` returns the final-loop cross-entropy. Per-loop cross-entropy values can be inspected via `forward_unrolled(...).loop_losses`. Targets follow the BlaGPT loader convention: next-token labels already shifted right by one position, with `-1` as the ignore index (no second shift is applied). `mola_backend="auto"` (the default) uses PyTorch FlashAttention plus Triton for MoLA in parallel encoder passes on supported NVIDIA GPUs with BF16/FP16 inputs. Strict readers use only depth slots at the first position. CPU, FP32, unsupported shapes, and token-ordered cached inference use the eager PyTorch implementation. Set `mola_backend="eager"` to use that implementation everywhere. If your single GPU has limited VRAM, reduce `device_batch_size` (keeping `batch_size` divisible by `device_batch_size * num_gpus`) or set `compile_model` to `false`. ## Direct Invocation In an environment with the required dependencies installed, run from the root of this directory: ```python import torch from bla_gpt.u_molt import UMoLT, UMoLTConfig config = UMoLTConfig( vocab_size=128, hidden_size=64, num_heads=4, num_kv_heads=2, num_encoder_layers=2, num_decoder_layers=2, intermediate_size=128, block_size=64, sequence_length=64, ) model = UMoLT(config) tokens = torch.randint(0, config.vocab_size, (2, 17)) inputs, targets = tokens[:, :-1], tokens[:, 1:] logits, loss = model(inputs, targets) loss.backward() model.eval() with torch.no_grad(): # Fixed two-loop unrolling: each encoder loop runs in parallel over the full prefix. full = model.forward_unrolled(inputs, num_loops=2) # The BlaGPT contract returns only the last-position logits when targets is None. last_logits, _ = model(inputs) generated = model.generate(inputs[:1], 8, temperature=0, schedule="unrolled") # Token-ordered recurrence: one encoder pass and one decoder pass per token. recurrent_logits, state = model.forward_recurrent(inputs) next_token = torch.randint(0, config.vocab_size, (2, 1)) next_logits, state = model.recurrent_step(next_token, state) ``` During generation, `schedule="unrolled"` recomputes the fixed-N loops over the full prefix, prioritizing a minimal, readable implementation. When `targets` is `None`, intermediate decoder passes are skipped and only the last query is computed in the final decoder; the encoder source and every decoder layer's KV still cover the entire prefix. `schedule="recurrent"` builds and reuses caches in token order. Feedback layers cache projected boundary memory, ordinary encoder layers cache local sequence KV, and each decoder layer caches its own projected encoder cross KV. The current token's boundary memory is written only after the full encoder pass finishes, preventing same-position cross-loop feedback reads. The depth bank lives only while processing the current token and is not retained across tokens or loops. Each cache state belongs to a single request and is updated in place; start a fresh state for a new request, and keep total length within `block_size`. **Token-ordered recurrence evaluates the stabilized recurrence and generally does not equal fixed two-loop unrolling.** Do not use element-wise equality between these two interfaces as a correctness criterion, and do not treat fixed-loop prefill outputs as a recurrent cache. This minimal version excludes hybrid handoff, legacy checkpoint conversion, MoE, other backbones, and ablation frameworks. Parameter names follow the paper terminology, so legacy research checkpoints cannot be loaded directly via `load_state_dict`. ## Using on Another Official Clone For core integration, copy `bla_gpt/u_molt.py` and keep `libs/mola_triton` in the same position relative to it as in this repository. The registry automatically discovers `@register_model def register_umolt()` without editing `model_registers.py`, `utils.py`, or `train.py`. Keep `.git` intact: the official registry uses `.git` to locate the project root. Prefer basing on the pinned commit recorded above. Run `python -m pytest tests/test_mola_triton.py` on a supported CUDA machine to check the fused forward and gradients against eager PyTorch, and to verify default and cached dispatch.