mstar.model.components#
Reusable transformer building blocks.
Components in this package are model-agnostic and meant to be shared
across model implementations. Anything model-specific (vision encoders,
audio codecs, multimodal preprocessing, etc.) stays in the per-model
components/ directory.
The TP-aware versions of these blocks (parallel linears, etc.) will land here too in a follow-up; the current shapes intentionally leave room for that.
- class mstar.model.components.AdaRMSNorm(hidden_size, cond_dim, eps=1e-6)[source]#
Bases:
ModuleRMSNorm with adaRMS conditioning.
A per-norm
nn.Linear(cond_dim, hidden_size*3)maps a shared condition vector to(scale, shift, gate). The normalization isrmsnorm(x) * (1 + scale) + shiftand the gate is returned for the enclosing decoder layer to apply at the residual.The
dense.weightanddense.biasare zero-initialized so the norm starts as the identity (matches HF Gemma / lerobot openpi).- forward(x, cond)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.Attention(*, hidden_size, num_heads, num_kv_heads, head_dim, qkv_bias=False, o_bias=False, qk_norm=False, rms_norm_eps=1e-6, rope_theta=10_000.0, rope_scale=1.0, rope_low_freq_factor=1.0, rope_high_freq_factor=1.0, rope_old_context_len=8192, input_hidden_size=None, attn_key='attn', kv_key='kv', pos_key='rope')[source]#
Bases:
Module- Parameters:
hidden_size (int)
num_heads (int)
num_kv_heads (int)
head_dim (int)
qkv_bias (bool)
o_bias (bool)
qk_norm (bool)
rms_norm_eps (float)
rope_theta (float)
rope_scale (float)
rope_low_freq_factor (float)
rope_high_freq_factor (float)
rope_old_context_len (int)
input_hidden_size (int | None)
attn_key (str)
kv_key (str)
pos_key (str | None)
- bind_resources(resources)[source]#
Resolve the resources this layer calls. See
NodeSubmodule.bind_node_resources..get: a layer may be bound on a node that owns only some of them.- Parameters:
resources (dict)
- Return type:
None
- class mstar.model.components.CrossAttention(*, hidden_size, num_heads, head_dim, q_bias=True, k_bias=False, v_bias=True, o_bias=True, source='default', cross_key=None, context_kv_key=None)[source]#
Bases:
ModuleMulti-head cross-attention over an engine-managed encoder-context KV.
For encoder-decoder models (Whisper, etc.): the decoder attends to a fixed encoder context whose K/V are computed once at prefill and written into a KV resource of their own, under the
context_labelthe model’sCrossAttentionConfignames (see issue #160). Q is projected per step; K/V projections are exposed viacompute_kvso the submodule can write them into that cache at encode time.Q/K/V/O are separate
nn.Linearmatching the HF layout. Subclasses override projection details (bias flags, acompute_kvthat reshapes for a model-specific pool layout) as needed; the default matches Whisper (q/v/o biased, k unbiased).TODO(#160): the projections are plain
nn.Linear— this module is not yet TP/SP-compatible (no column/row-parallel splits over heads). A tensor-parallel cross-attention variant is needed to serve the decoder under TP alongside the self-attention path.- Parameters:
- bind_resources(resources)[source]#
Resolve this source’s cross-attention resource and the cache holding its context. See
NodeSubmodule.bind_node_resources.- Parameters:
resources (dict)
- Return type:
None
- compute_kv(encoder_states)[source]#
Project the encoder context to K/V for the cross-attention pool.
(enc_len, hidden) -> (k, v), each(enc_len, num_heads, head_dim). Override to reshape for a model-specific pool layout.
- class mstar.model.components.DecoderLayer(self_attn, mlp, input_layernorm, post_attention_layernorm)[source]#
Bases:
ModuleStandard pre-norm transformer decoder layer.
- Computes:
residual = x x = input_layernorm(x); x = self_attn(x); x = residual + x residual = x x = post_attention_layernorm(x); x = mlp(x); x = residual + x
- Parameters:
self_attn (nn.Module) – attention module taking
(hidden_states, label=, layer_idx=)and returning a tensor.mlp (nn.Module) – feedforward module taking and returning a tensor.
input_layernorm (nn.Module) – pre-attention norm.
post_attention_layernorm (nn.Module) – pre-FFN norm.
- forward(hidden_states)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.FusedColumnLinear(input_size, shard_sizes, bias=False, dtype=None)[source]#
Bases:
ModuleLinear whose output is the concatenation of several shards along dim 0, fused into a single weight (and optional bias).
- Parameters:
input_size (int) – input feature dim.
shard_sizes (dict[str | int, int]) – maps a shard id to its output size. Shards are laid out along dim 0 in iteration order, so the order of this dict defines the layout (and the split used at forward time).
bias (bool) – whether to include a (fused) bias.
dtype (torch.dtype | None)
The fused
weight/biascarry aweight_loader(param, tensor, shard_id)method that copies one checkpoint shard into its slice of the fused parameter, dispatched byshard_id(a key ofshard_sizes). Wire the per-shard checkpoint keys to it with the loader’s stacked-param rules.- forward(x)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.FusedGatedMLP(hidden_size, intermediate_size, activation='silu', bias=False)[source]#
Bases:
ModuleSwiGLU-style gated MLP with the gate + up projections fused into a single
FusedColumnLinear(one GEMM instead of two):down(act(gate) * up). UnlikeGatedMLP(separate Linears + post-loadconsolidate_gate_up_weight), this fuses from construction and loads the separategate_proj/up_projcheckpoint tensors straight into the fused parameter via the loader’s stacked-param rules (gate is shard0, up is shard1). Use for models that fuse but don’t need TP. :param hidden_size: input/output feature dim. :param intermediate_size: gate/up output and down input feature dim. :param activation: activation applied to the gate path. Either an HFstring (
silu/gelu/gelu_tanh) or a callable.- Parameters:
- forward(x)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.GatedDecoderLayer(self_attn, mlp, input_layernorm, post_attention_layernorm)[source]#
Bases:
ModulePre-norm decoder layer with adaRMS gated residuals.
The norms must be
AdaRMSNorm-shaped:forward(x, cond)returns(normed, gate). The residual becomesx + gate * y.Used by pi05’s action expert;
adarms_condis the shared condition vector consumed by both norms.- Parameters:
self_attn (nn.Module)
mlp (nn.Module)
input_layernorm (nn.Module)
post_attention_layernorm (nn.Module)
- forward(hidden_states, adarms_cond)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.GatedMLP(hidden_size, intermediate_size, activation='silu', bias=False)[source]#
Bases:
ModuleSwiGLU-style gated MLP:
down(act(gate(x)) * up(x)).- Parameters:
- consolidate_gate_up_weight()[source]#
Fuse
gate_projandup_projweights into a singlegate_up_proj_weightbuffer and null out the originals. Idempotent; safe to call multiple times.- Return type:
None
- forward(x)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.MLP(input_size, intermediate_size, output_size=None, activation='silu', bias=True)[source]#
Bases:
ModulePlain two-layer MLP:
out(act(in(x))).Used for small projection MLPs that aren’t gated (Talker resize projection, bagel timestep embedder MLP, etc.). For SwiGLU-style transformer FFNs, use
GatedMLP.- Parameters:
- forward(x)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.ParallelSparseMoeBlock(hidden_size, num_experts, num_experts_per_tok, moe_intermediate_size, norm_topk_prob=True, router=None, comm_group=None)[source]#
Bases:
ModuleTP-aware Top-K sparse MoE.
When
tp_size == 1, the forward is identical toSparseMoeBlock(full fused kernel, no communication). Whentp_size > 1, expert weights are sharded along the intermediate dimension and an all-reduce is inserted between the down-projection GEMM and the top-k sum-reduce.- Parameters:
- forward(hidden_states, router_states=None, *, return_router_states=False)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Bases:
ModuleTP-aware Top-K sparse MoE with a shared expert + sigmoid gating.
The shared expert should be a
ParallelGatedMLPconstructed with the samecomm_groupso its all-reduce is handled internally.- Parameters:
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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.RMSNorm(hidden_size, eps=1e-6, gemma_mode=False)[source]#
Bases:
ModuleRMSNorm with optional Gemma-style
(1 + weight)scaling.- Parameters:
hidden_size (int) – feature dimension to normalize over.
eps (float) – variance epsilon.
gemma_mode (bool) – if True, use
(1 + weight)and a fp32 manual implementation (matches HF Gemma exactly; the loaded checkpoint weight is centered around zero, not one). If False, useweightand dispatch to FlashInfer’s fused kernel.
- extra_repr()[source]#
Return the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- Return type:
- forward(hidden_states)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.SparseMoeBlock(hidden_size, num_experts, num_experts_per_tok, moe_intermediate_size, norm_topk_prob=True, router=None)[source]#
Bases:
ModuleTop-K sparse MoE with fused expert weights, no shared expert.
- Expert weights match the HF fused checkpoint layout:
experts.gate_up_proj:(num_experts, 2 * moe_intermediate_size, hidden_size)experts.down_proj:(num_experts, hidden_size, moe_intermediate_size)
- Parameters:
- forward(hidden_states, router_states=None, *, return_router_states=False)[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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Bases:
ModuleTop-K sparse MoE with a shared expert + sigmoid gating.
Final output is:
out = routed(x) + sigmoid(shared_gate(x)) * shared_expert(x)
The shared expert is supplied by the caller (any
nn.Modulematching thehidden_size → hidden_sizeinterface). The routed path uses the same fused checkpoint layout asSparseMoeBlock.- Parameters:
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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class mstar.model.components.TopKRouter(hidden_size, num_experts, num_experts_per_tok, norm_topk_prob=True)[source]#
Bases:
ModuleSoftmax top-k router. This is the default router for all MoE blocks.
See the module docstring for the router contract. This router is stateless. It ignores
router_states. It returnsNoneforrouter_states_next.- Parameters:
- mstar.model.components.dispatch_experts_fused(hidden_states, gate_up_proj, down_proj, num_experts, selected_experts, routing_weights)[source]#
Naive per-expert dispatch using the fused HF checkpoint layout.
Used as a fallback when the Triton fused-MoE kernel isn’t available. Loops over the experts that received any tokens and runs SwiGLU per expert.
- Parameters:
hidden_states (Tensor) –
(tokens, hidden_size).gate_up_proj (Tensor) –
(num_experts, 2 * moe_intermediate_size, hidden_size).down_proj (Tensor) –
(num_experts, hidden_size, moe_intermediate_size).selected_experts (Tensor) –
(tokens, top_k)int64.routing_weights (Tensor) –
(tokens, top_k)float.num_experts (int)
- Return type:
Modules
Multi-head attention with GQA, optional QK-norm, and pluggable RoPE. |
|
Pre-norm transformer decoder layers. |
|
Tensor-parallel building blocks. |
|
Non-distributed fused linear projections. |
|
MLP and SwiGLU-style GatedMLP. |
|
Mixture-of-Experts blocks. |
|
RMSNorm and AdaRMSNorm. |