| """ |
| LiquidFlow Block β Hybrid CfC + Mamba-2 SSD architecture. |
| CORRECTED VERSION: proper dimensions, no sequential loops. |
| |
| Architecture per block: |
| Input β Mamba-2 SSD (bidirectional) β CfC adaptive gate β Output |
| |
| The CfC provides adaptive gating that modulates the SSM output |
| based on input-dependent "liquid" time constants. |
| """ |
|
|
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| import math |
|
|
| from .cfc_cell import CfCCell, CfCBlock |
| from .mamba2_ssd import Mamba2SSD, Mamba2Block |
|
|
|
|
| class LiquidMambaBlock(nn.Module): |
| """ |
| LiquidMamba: CfC-gated Mamba-2 SSD block. |
| |
| Flow: |
| 1. Input β LayerNorm β Mamba-2 SSD (bidirectional scan) |
| 2. SSM output β CfC adaptive gate (parallel over all positions) |
| 3. Gated output β residual + feed-forward |
| |
| The CfC gate learns WHEN to trust the SSM output vs the raw input, |
| creating content-aware adaptive processing. |
| """ |
| |
| def __init__(self, dim, d_state=16, d_conv=4, expand=2, dropout=0.0): |
| super().__init__() |
| self.dim = dim |
| |
| |
| self.norm_ssm = nn.LayerNorm(dim) |
| self.norm_gate = nn.LayerNorm(dim) |
| self.norm_ff = nn.LayerNorm(dim) |
| |
| |
| self.ssd_fwd = Mamba2SSD(dim=dim, d_state=d_state, d_conv=d_conv, expand=expand) |
| self.ssd_bwd = Mamba2SSD(dim=dim, d_state=d_state, d_conv=d_conv, expand=expand) |
| self.merge = nn.Linear(dim * 2, dim, bias=False) |
| |
| |
| self.cfc_gate = CfCCell(dim=dim, dropout=dropout) |
| |
| |
| self.gate_proj = nn.Linear(dim, dim) |
| |
| |
| ff_dim = dim * expand |
| self.ff = nn.Sequential( |
| nn.Linear(dim, ff_dim), |
| nn.GELU(), |
| nn.Dropout(dropout), |
| nn.Linear(ff_dim, dim), |
| nn.Dropout(dropout), |
| ) |
| |
| def forward(self, x): |
| """ |
| Args: |
| x: [B, C, H, W] or [B, L, C] |
| Returns: |
| Same shape as input |
| """ |
| is_2d = x.dim() == 4 |
| if is_2d: |
| B, C, H, W = x.shape |
| x = x.flatten(2).transpose(1, 2) |
| |
| |
| residual = x |
| x_norm = self.norm_ssm(x) |
| |
| |
| fwd_out = self.ssd_fwd(x_norm) |
| bwd_out = torch.flip(self.ssd_bwd(torch.flip(x_norm, [1])), [1]) |
| ssm_out = self.merge(torch.cat([fwd_out, bwd_out], dim=-1)) |
| |
| |
| |
| gate_input = self.norm_gate(ssm_out) |
| cfc_out = self.cfc_gate(gate_input) |
| |
| |
| gate = torch.sigmoid(self.gate_proj(cfc_out)) |
| |
| |
| x = residual + gate * ssm_out |
| |
| |
| x = x + self.ff(self.norm_ff(x)) |
| |
| if is_2d: |
| x = x.transpose(1, 2).reshape(B, C, H, W) |
| return x |
|
|
|
|
| class LiquidFlowStage(nn.Module): |
| """Stack of LiquidMamba blocks at the same resolution.""" |
| |
| def __init__(self, dim, num_blocks=4, d_state=16, expand=2, dropout=0.0): |
| super().__init__() |
| self.blocks = nn.ModuleList([ |
| LiquidMambaBlock(dim=dim, d_state=d_state, expand=expand, dropout=dropout) |
| for _ in range(num_blocks) |
| ]) |
| |
| def forward(self, x): |
| for block in self.blocks: |
| x = block(x) |
| return x |
|
|
|
|
| class LiquidFlowBackbone(nn.Module): |
| """ |
| Complete LiquidFlow backbone β DiT-style noise predictor. |
| |
| FIXED: Output shape == Input shape (no patch_size confusion). |
| |
| Architecture: |
| Input [B, in_ch, H, W] |
| β Conv2d projection to hidden_dim |
| β + sinusoidal timestep embedding (AdaLN-style) |
| β + learnable positional encoding |
| β N Γ LiquidMamba Stages |
| β Conv2d projection back to in_ch |
| β Output [B, in_ch, H, W] |
| """ |
| |
| def __init__( |
| self, |
| in_channels=4, |
| hidden_dim=256, |
| num_stages=4, |
| blocks_per_stage=4, |
| d_state=16, |
| expand=2, |
| dropout=0.0, |
| ): |
| super().__init__() |
| self.in_channels = in_channels |
| self.hidden_dim = hidden_dim |
| |
| |
| self.in_proj = nn.Conv2d(in_channels, hidden_dim, kernel_size=1) |
| |
| |
| self.time_embed = nn.Sequential( |
| nn.Linear(hidden_dim, hidden_dim * 4), |
| nn.SiLU(), |
| nn.Linear(hidden_dim * 4, hidden_dim), |
| ) |
| |
| |
| self.t_cond = nn.Sequential( |
| nn.SiLU(), |
| nn.Linear(hidden_dim, hidden_dim * 2), |
| ) |
| |
| |
| self.pos_embed = nn.Parameter(torch.randn(1, 4096, hidden_dim) * 0.02) |
| |
| |
| self.stages = nn.ModuleList([ |
| LiquidFlowStage( |
| dim=hidden_dim, |
| num_blocks=blocks_per_stage, |
| d_state=d_state, |
| expand=expand, |
| dropout=dropout, |
| ) |
| for _ in range(num_stages) |
| ]) |
| |
| |
| self.out_norm = nn.LayerNorm(hidden_dim) |
| self.out_proj = nn.Linear(hidden_dim, in_channels) |
| |
| self._init_weights() |
| |
| def _init_weights(self): |
| |
| nn.init.zeros_(self.out_proj.weight) |
| nn.init.zeros_(self.out_proj.bias) |
| |
| def _sinusoidal_embedding(self, timesteps, dim): |
| """Sinusoidal positional embedding for diffusion timesteps.""" |
| half = dim // 2 |
| freqs = torch.exp( |
| -math.log(10000.0) * torch.arange(half, device=timesteps.device).float() / half |
| ) |
| args = timesteps.float().unsqueeze(-1) * freqs.unsqueeze(0) |
| emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) |
| if dim % 2: |
| emb = F.pad(emb, (0, 1)) |
| return emb |
| |
| def forward(self, x, t): |
| """ |
| Args: |
| x: [B, in_channels, H, W] β noisy latent |
| t: [B] β diffusion timesteps (integers 0..T-1) |
| Returns: |
| [B, in_channels, H, W] β predicted noise (same shape as input!) |
| """ |
| B, C, H, W = x.shape |
| L = H * W |
| |
| |
| x = self.in_proj(x) |
| x = x.flatten(2).transpose(1, 2) |
| |
| |
| t_emb = self._sinusoidal_embedding(t, self.hidden_dim) |
| t_emb = self.time_embed(t_emb) |
| t_cond = self.t_cond(t_emb) |
| scale, shift = t_cond.chunk(2, dim=-1) |
| |
| |
| x = x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) |
| x = x + self.pos_embed[:, :L, :] |
| |
| |
| x = x.transpose(1, 2).reshape(B, self.hidden_dim, H, W) |
| |
| |
| for stage in self.stages: |
| x = stage(x) |
| |
| |
| x = x.flatten(2).transpose(1, 2) |
| x = self.out_norm(x) |
| x = self.out_proj(x) |
| |
| |
| x = x.transpose(1, 2).reshape(B, self.in_channels, H, W) |
| |
| return x |
|
|