bridge.models.qwen.modeling_qwen4_exp.gated_residual#

Qwen4-Exp gated residual streams and learned output contraction.

Module Contents#

Classes#

GatedResidualHyperConnection

Gated Residual hyper-connection of Qwen4-Exp (Qwen3.8-Flash-Next).

GatedResidualOutputMixer

Block-level learned contraction of the Qwen4-Exp residual streams.

Functions#

gated_residual_group_rmsnorm

Zero-centered RMSNorm applied independently to each of the n residual streams.

API#

bridge.models.qwen.modeling_qwen4_exp.gated_residual.gated_residual_group_rmsnorm(
x: torch.Tensor,
weight: torch.Tensor,
n: int,
eps: float,
) → torch.Tensor#

Zero-centered RMSNorm applied independently to each of the n residual streams.

Parameters:
  • x – […, n*C] n-stream hidden states.

  • weight – [n*C] zero-centered gain (the effective scale is 1 + weight).

  • n – Number of residual streams.

  • eps – RMSNorm epsilon.

Returns:

[…, n*C] normalized streams in x.dtype (computed in fp32).

class bridge.models.qwen.modeling_qwen4_exp.gated_residual.GatedResidualHyperConnection(
config: megatron.core.transformer.transformer_config.TransformerConfig,
layer_number: int = 1,
use_combine: bool = True,
)#

Bases: megatron.core.transformer.module.MegatronModule

Gated Residual hyper-connection of Qwen4-Exp (Qwen3.8-Flash-Next).

Every sub-layer (attention / MLP) of a decoder layer is wrapped by one instance. With n residual streams of width C travelling between layers as [s, b, n*C]:

xn      = GroupRMSNorm(x)                                # per-stream, zero-centered gain
mix     = sigmoid(W_up silu(W_down xn / n))              # [.., n*C] element-wise read gate
block_in = mean_j(mix_j * xn_j)                          # [.., C]   sub-layer input
inject  = 2 * sigmoid(W_inject xn / n)                   # [.., n]   per-stream write gate
x_new   = x + inject_j * F(block_in)  for every stream j

The interface matches :class:HyperConnectionModule so that

Class:

~megatron.core.transformer.transformer_layer.HyperConnectionTransformerLayer drives both formulations: forward returns (block_input, h_res, h_post) where h_res is an empty tensor (the residual mixing is the identity) and h_post is inject, and

Meth:

fused_h_res_h_post_bda applies the write gate. With use_combine=False the module is the block-level output mixer: it only returns block_in (see

Class:

GatedResidualOutputMixer).

Parameters are replicated across tensor-parallel ranks and kept in params_dtype like the reference checkpoints; the norm statistics run in fp32; gates retain activation-dtype operation boundaries.

Initialization

classmethod estimate_flops(
config: megatron.core.transformer.transformer_config.TransformerConfig,
*,
total_real_tokens_in_batch: float,
seqlen_squared_sum_in_batch: float,
) → float#

Count the read mixer and residual-injection projections (forward only).

_mix(
hidden_states: torch.Tensor,
) → Tuple[torch.Tensor, Optional[torch.Tensor]]#
forward(
hidden_states: torch.Tensor,
mhc_recompute_manager: object | None = None,
return_residual: bool = False,
*,
checkpoint_fn: collections.abc.Callable[..., torch.Tensor] | None = None,
) → tuple[torch.Tensor, torch.Tensor, torch.Tensor | None] | tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, torch.Tensor]#

Read the streams.

Parameters:
  • hidden_states – [s, b, n*C] n-stream hidden states.

  • mhc_recompute_manager – Must be None; residual recomputation is unsupported.

  • return_residual – Also return the (unchanged) n-stream residual as a 4th element, like :class:HyperConnectionModule.

  • checkpoint_fn – Must be None; residual recomputation is unsupported.

Returns:

(block_input [s, b, C], h_res=empty tensor, h_post [s, b, n]). h_post is None for the output mixer (use_combine=False).

apply_h_res(
h_res: Optional[torch.Tensor],
residual: torch.Tensor,
) → torch.Tensor#

The gated residual keeps the streams untouched (identity residual mixing).

static _inject(
residual: torch.Tensor,
inject: torch.Tensor,
x: torch.Tensor,
bias: Optional[torch.Tensor],
n: int,
) → torch.Tensor#
fused_h_res_h_post_bda(
h_res: Optional[torch.Tensor],
original_residual: torch.Tensor,
h_post: torch.Tensor,
layer_output_with_bias: Tuple[torch.Tensor, Optional[torch.Tensor]],
dropout_prob: float,
training: bool,
fused: bool,
manager: object | None = None,
*,
checkpoint_fn: collections.abc.Callable[..., torch.Tensor] | None = None,
) → torch.Tensor#

Write the sub-layer output back to every stream: x + inject_j * (F(x) + bias).

Parameters:
  • h_res – Unused (identity residual mixing).

  • original_residual – [s, b, n*C] n-stream hidden states before the sub-layer.

  • h_post – [s, b, n] per-stream write gates returned by :meth:forward.

  • layer_output_with_bias – (x [s, b, C], bias [C] or None).

  • fused (dropout_prob / training /) – bias-dropout-add settings; dropout is applied to the broadcast update when non-zero.

  • manager – Must be None; residual recomputation is unsupported.

  • checkpoint_fn – Must be None; residual recomputation is unsupported.

Returns:

[s, b, n*C] updated streams.

class bridge.models.qwen.modeling_qwen4_exp.gated_residual.GatedResidualOutputMixer(
config: megatron.core.transformer.transformer_config.TransformerConfig,
hidden_size: Optional[int] = None,
eps: Optional[float] = None,
)#

Bases: bridge.models.qwen.modeling_qwen4_exp.gated_residual.GatedResidualHyperConnection

Block-level learned contraction of the Qwen4-Exp residual streams.

Replaces the final layer norm of a

Class:

~megatron.core.transformer.transformer_block.TransformerBlock built with the Bridge-local Qwen4-Exp layer spec: it consumes the [s, b, n*C] streams and returns the [s, b, C] gated mean of their normalized values (hyper_connection_mixer in the HF checkpoint). Core’s generic mHC path remains disabled; the local HybridModel expands streams before the decoder so the learned mixer receives every stream without Core’s unweighted mean contraction.

The (config, hidden_size, eps) signature matches the layer-norm builders used in block specs.

Initialization

classmethod estimate_flops(
config: megatron.core.transformer.transformer_config.TransformerConfig,
*,
total_real_tokens_in_batch: float,
seqlen_squared_sum_in_batch: float,
) → float#

Count the final read mixer; it has no residual-injection projection.

forward(hidden_states: torch.Tensor) → torch.Tensor#

[s, b, n*C] streams -> [s, b, C] mixed output.