Modules

Layer stacks

class mammoth.modules.layer_stack.StackXcoder(task_wrappers: Dict[str, NativeTransformerWrapper], attention_layer_blocks: Dict[int, Dict[str, TransformerStack]], token_embs: Dict[str, Embedding], shared_stacks: ModuleDict, shared_token_embs: ModuleDict, shared_post_emb_norms: ModuleDict, shared_rotary_embs: ModuleDict, shared_to_logits: ModuleDict, shared_lang_post_emb_norms: ModuleDict | None = None)[source]

Bases: Module

Switches between different NativeTransformerWrappers depending on the task.

StackXcoder is the single registered owner of all shared parameters. NativeTransformerWrapper instances in task_wrappers hold plain Python references to the shared modules (not nn.Module children), so state_dict() contains exactly one copy of each shared parameter.

get_post_emb_norm_by_lang(lang: str) → Module | None[source]

The language’s own norm, or None when norms are per component.

class mammoth.modules.transformer.TransformerStack(blocks: ModuleList, final_norm: Module | None, dim: int, layer_stack_index: int, xcoder_id: str)[source]

Bases: Module

Stack of EncoderBlocks or DecoderBlocks for one (layer_stack_index, xcoder_id). Carries identity metadata so distributed/components.py can reference it by the same keys as before.

forward(x: Tensor, mask: Tensor | None = None, context: Tensor | None = None, context_mask: Tensor | None = None, rotary: tuple[Tensor, Tensor] | None = None, cache: KVCache | None = None, cache_offset: int = 0) → tuple[Tensor, KVCache | None][source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class mammoth.modules.transformer.NativeTransformerWrapper(token_emb: Embedding, post_emb_norm: Module, stacks: list[TransformerStack], rotary_emb: RotaryEmbedding | None, to_logits: Linear | None, emb_dropout: float = 0.0, return_only_embed: bool = False, embed_scale: float | None = None)[source]

Bases: Module

token_emb -> post_emb_norm -> TransformerStack(s) -> to_logits.

This wrapper is a lightweight routing view. All shared parameters (stacks, token_emb, post_emb_norm, rotary_emb, to_logits) are owned by StackXcoder.shared_* and stored here as plain Python references so PyTorch does not re-register them as children of this module. Only emb_dropout is per-task and registered normally.

forward(x: Tensor, mask: Tensor | None = None, context: Tensor | None = None, context_mask: Tensor | None = None, return_embeddings: bool = False, return_logits_and_embeddings: bool = False, return_attn: bool = False, return_intermediates: bool = False, cache: KVCache | None = None, seq_start_pos: int | None = None) → Tensor | tuple[Tensor, KVCache][source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

property num_layers: int

Total block count across all stacks; the size a KVCache needs.

Transformer blocks

class mammoth.modules.transformer.EncoderBlock(dim: int, heads: int, dim_head: int | None = None, ff_mult: float = 4.0, attn_dropout: float = 0.0, ff_dropout: float = 0.0, norm_bias: bool = False, norm_eps: float | None = None, activation: str = 'swiglu')[source]

Bases: Module

forward(x: Tensor, mask: Tensor | None = None, rotary: tuple[Tensor, Tensor] | None = None, cache: LayerCache | None = None) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class mammoth.modules.transformer.DecoderBlock(dim: int, heads: int, dim_head: int | None = None, ff_mult: float = 4.0, attn_dropout: float = 0.0, ff_dropout: float = 0.0, norm_bias: bool = False, norm_eps: float | None = None, activation: str = 'swiglu', kv_heads: int | None = None, qk_norm: bool = False, attn_scale: float | None = None, sandwich_norm: bool = False, sliding_window: int | None = None, rotary_emb: RotaryEmbedding | None = None, context_dim: int | None = None, use_cross_attn: bool = True)[source]

Bases: Module

Pre-norm decoder block: self-attn -> cross-attn -> ff, each with a residual connection.

Optional Gemma3-style extensions (see CLAUDE.md “Gemma3-270M -> Mammoth Conversion” for the architecture this mirrors, borrowed directly from transformers.models.gemma3.modeling_gemma3.Gemma3DecoderLayer):

  • sandwich_norm: adds a post-branch RMSNorm applied to the self-attn and ff outputs before the residual add (Gemma3’s post_attention_layernorm / post_feedforward_layernorm). Cross-attn is Mammoth-only scaffolding (Gemma3 has no cross-attention) and is never sandwich-normed.

  • sliding_window: builds a windowed-causal mask internally (causal AND query_pos - key_pos < window) and feeds it to self_attn, accounting for any cached prefix length.

  • rotary_emb: gives the block its own RotaryEmbedding (used for Gemma3’s dual RoPE, where local/sliding layers use a different theta than global/full-attention layers) instead of relying on the rotary tuple computed once per stack and shared across all blocks.

  • kv_heads / qk_norm / attn_scale: forwarded to the self-attn MultiHeadAttention (see attention.py).

  • context_dim: lets cross-attn’s K/V project from a different feature size than this block’s own dim (e.g. encoder dim != decoder dim), instead of requiring them to match.

  • use_cross_attn: when False, cross_attn/norm2 are never built at all (not just zero-initialized) and forward() never touches context – a TRUE decoder-only block, architecturally identical to a plain LM decoder layer (e.g. Gemma3DecoderLayer, which has no cross-attention). This is the “option 1” path from CLAUDE.md “Gemma3-270M -> Mammoth Conversion”, used by convert_gemma3_decoder_only.py, as opposed to the “fake encoder” path (convert_gemma3_native.py) which keeps use_cross_attn=True (the default) and zeros cross_attn.to_out instead.

  • norm_eps: RMSNorm epsilon for all norms in this block (including self-attn’s qk_norm). Gemma3 uses a fixed 1e-6 everywhere; the default None keeps torch’s dtype-based default for non-Gemma3 models. This matters more than it looks: activation rows can have near-zero variance, and torch’s default eps (~1.19e-7 for fp32) vs Gemma3’s 1e-6 differ enough to blow up the normalized output on those rows once multiplied by a large-magnitude norm weight.

forward(x: Tensor, context: Tensor | None = None, context_mask: Tensor | None = None, rotary: tuple[Tensor, Tensor] | None = None, cache: LayerCache | None = None) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Sublayers

class mammoth.modules.transformer.MultiHeadAttention(dim: int, heads: int, dim_head: int | None = None, attn_dropout: float = 0.0, causal: bool = False, is_cross_attn: bool = False, context_dim: int | None = None, kv_heads: int | None = None, qk_norm: bool = False, qk_norm_eps: float = 1e-06, attn_scale: float | None = None)[source]

Bases: Module

forward(x: Tensor, context: Tensor | None = None, mask: Tensor | None = None, rotary: tuple[Tensor, Tensor] | None = None, cache: LayerCache | None = None) → tuple[Tensor, LayerCache | None][source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class mammoth.modules.transformer.FeedForward(dim: int, ff_mult: float = 2.67, ff_dropout: float = 0.0, activation: Literal['swiglu', 'gelu', 'geglu'] = 'swiglu')[source]

Bases: Module

forward(x: Tensor) → Tensor[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class mammoth.modules.transformer.RotaryEmbedding(dim_head: int, base: int = 10000)[source]

Bases: Module

forward(seq_len: int, device: device, offset: int = 0) → tuple[Tensor, Tensor][source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

mammoth.modules.transformer.apply_rotary(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor) → tuple[Tensor, Tensor][source]

KV cache

class mammoth.modules.transformer.LayerCache(self_k: torch.Tensor | None = None, self_v: torch.Tensor | None = None, cross_k: torch.Tensor | None = None, cross_v: torch.Tensor | None = None)[source]

Bases: object

class mammoth.modules.transformer.KVCache(num_layers: int)[source]

Bases: object

Replaces x-transformers LayerIntermediates / Intermediates.

property batch_size: int | None

Number of rows (batch * beam) currently held, or None if empty.

reorder_beams(beam_indices: Tensor, reorder_cross: bool = True) → None[source]

Reorder cache tensors in-place. Called by decode_strategy.py.

Cross-attn K/V are identical across the beams of one sentence, so a pure within-sentence beam reshuffle can pass reorder_cross=False and skip copying them; they only need indexing when rows are dropped.