minhluanquach's picture
download
raw
18.5 kB
"""
Lightweight UNet with Cross-Attention for Audio-Visual Fusion
=============================================================
This is the core trainable component. It takes:
- Masked face latents (lower half masked)
- Reference face latents (original frame)
- Binary mask
- Audio features from Whisper
And predicts the complete face latents with correct lip movements.
Architecture:
- Encoder: Conv blocks with downsampling
- Middle: ResBlocks + Cross-Attention (audio conditioning)
- Decoder: Conv blocks with upsampling + skip connections
- Cross-attention at multiple resolutions for fine-grained audio control
"""
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from torch.utils.checkpoint import checkpoint
class SinusoidalPositionEmbedding(nn.Module):
"""Timestep-style positional embedding (reused for feature conditioning)."""
def __init__(self, dim: int):
super().__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
device = x.device
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
emb = x[:, None] * emb[None, :]
emb = torch.cat([emb.sin(), emb.cos()], dim=-1)
return emb
class GroupNorm32(nn.GroupNorm):
"""GroupNorm that works with fp16."""
def forward(self, x):
return super().forward(x.float()).type(x.dtype)
class ResBlock(nn.Module):
"""Residual block with optional channel change."""
def __init__(
self,
in_channels: int,
out_channels: int,
dropout: float = 0.0,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.norm1 = GroupNorm32(32, in_channels)
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
self.norm2 = GroupNorm32(32, out_channels)
self.dropout = nn.Dropout(dropout)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
if in_channels != out_channels:
self.skip_connection = nn.Conv2d(in_channels, out_channels, 1)
else:
self.skip_connection = nn.Identity()
self.act = nn.SiLU()
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.norm1(x)
h = self.act(h)
h = self.conv1(h)
h = self.norm2(h)
h = self.act(h)
h = self.dropout(h)
h = self.conv2(h)
return h + self.skip_connection(x)
class CrossAttention(nn.Module):
"""Cross-attention layer for audio conditioning.
Spatial features (image) attend to sequential features (audio).
This is how the model learns which audio features correspond to
which spatial locations (i.e., lip movements).
"""
def __init__(
self,
query_dim: int,
context_dim: int,
heads: int = 8,
dim_head: int = 64,
dropout: float = 0.0,
):
super().__init__()
inner_dim = heads * dim_head
self.heads = heads
self.scale = dim_head ** -0.5
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
self.to_out = nn.Sequential(
nn.Linear(inner_dim, query_dim),
nn.Dropout(dropout),
)
def forward(
self,
x: torch.Tensor,
context: torch.Tensor,
) -> torch.Tensor:
"""
Args:
x: (B, N, C) spatial features flattened
context: (B, S, D) audio features
"""
h = self.heads
q = self.to_q(x)
k = self.to_k(context)
v = self.to_v(context)
q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q, k, v))
# Scaled dot-product attention (uses Flash Attention when available)
attn = F.scaled_dot_product_attention(q, k, v, scale=self.scale)
out = rearrange(attn, "b h n d -> b n (h d)")
return self.to_out(out)
class SpatialTransformerBlock(nn.Module):
"""Transformer block that applies cross-attention between spatial
features and audio context."""
def __init__(
self,
channels: int,
context_dim: int,
num_heads: int = 8,
dropout: float = 0.0,
):
super().__init__()
self.norm1 = nn.LayerNorm(channels)
self.attn1 = CrossAttention(
query_dim=channels,
context_dim=channels, # Self-attention
heads=num_heads,
dim_head=channels // num_heads,
dropout=dropout,
)
self.norm2 = nn.LayerNorm(channels)
self.attn2 = CrossAttention(
query_dim=channels,
context_dim=context_dim, # Cross-attention with audio
heads=num_heads,
dim_head=channels // num_heads,
dropout=dropout,
)
self.norm3 = nn.LayerNorm(channels)
self.ff = nn.Sequential(
nn.Linear(channels, channels * 4),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(channels * 4, channels),
nn.Dropout(dropout),
)
def forward(
self,
x: torch.Tensor,
context: torch.Tensor,
) -> torch.Tensor:
"""
Args:
x: (B, C, H, W)
context: (B, S, D) audio features
"""
B, C, H, W = x.shape
# Reshape to sequence
x_flat = rearrange(x, "b c h w -> b (h w) c")
# Self-attention
x_flat = x_flat + self.attn1(self.norm1(x_flat), self.norm1(x_flat))
# Cross-attention with audio
x_flat = x_flat + self.attn2(self.norm2(x_flat), context)
# Feed-forward
x_flat = x_flat + self.ff(self.norm3(x_flat))
# Reshape back
x = rearrange(x_flat, "b (h w) c -> b c h w", h=H, w=W)
return x
class DownBlock(nn.Module):
"""Downsampling block: ResBlocks + optional attention + downsample."""
def __init__(
self,
in_channels: int,
out_channels: int,
num_res_blocks: int = 2,
has_attention: bool = False,
context_dim: int = 384,
dropout: float = 0.0,
downsample: bool = True,
):
super().__init__()
self.res_blocks = nn.ModuleList()
self.attn_blocks = nn.ModuleList()
for i in range(num_res_blocks):
ch_in = in_channels if i == 0 else out_channels
self.res_blocks.append(ResBlock(ch_in, out_channels, dropout))
if has_attention:
self.attn_blocks.append(
SpatialTransformerBlock(out_channels, context_dim, dropout=dropout)
)
else:
self.attn_blocks.append(nn.Identity())
self.downsample = None
if downsample:
self.downsample = nn.Conv2d(out_channels, out_channels, 3, stride=2, padding=1)
def forward(
self,
x: torch.Tensor,
context: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, list[torch.Tensor]]:
skips = []
for res_block, attn_block in zip(self.res_blocks, self.attn_blocks):
x = res_block(x)
if isinstance(attn_block, SpatialTransformerBlock) and context is not None:
x = attn_block(x, context)
skips.append(x)
if self.downsample is not None:
x = self.downsample(x)
return x, skips
class UpBlock(nn.Module):
"""Upsampling block: ResBlocks + optional attention + upsample."""
def __init__(
self,
in_channels: int,
out_channels: int,
skip_channels: int,
num_res_blocks: int = 2,
has_attention: bool = False,
context_dim: int = 384,
dropout: float = 0.0,
upsample: bool = True,
):
super().__init__()
self.res_blocks = nn.ModuleList()
self.attn_blocks = nn.ModuleList()
for i in range(num_res_blocks):
ch_in = in_channels + skip_channels if i == 0 else out_channels + skip_channels
# Only first block gets skip connection concatenated
if i > 0:
ch_in = out_channels + skip_channels
self.res_blocks.append(ResBlock(ch_in, out_channels, dropout))
if has_attention:
self.attn_blocks.append(
SpatialTransformerBlock(out_channels, context_dim, dropout=dropout)
)
else:
self.attn_blocks.append(nn.Identity())
self.upsample = None
if upsample:
self.upsample = nn.Sequential(
nn.Upsample(scale_factor=2, mode="nearest"),
nn.Conv2d(out_channels, out_channels, 3, padding=1),
)
def forward(
self,
x: torch.Tensor,
skips: list[torch.Tensor],
context: Optional[torch.Tensor] = None,
) -> torch.Tensor:
for i, (res_block, attn_block) in enumerate(
zip(self.res_blocks, self.attn_blocks)
):
skip = skips[-(i + 1)]
x = torch.cat([x, skip], dim=1)
x = res_block(x)
if isinstance(attn_block, SpatialTransformerBlock) and context is not None:
x = attn_block(x, context)
if self.upsample is not None:
x = self.upsample(x)
return x
class AudioProjector(nn.Module):
"""Projects Whisper features to the cross-attention dimension.
Also handles temporal aggregation: maps variable-length audio
features to a fixed number of tokens for cross-attention.
"""
def __init__(
self,
whisper_dim: int = 384,
output_dim: int = 384,
num_tokens: int = 16,
):
super().__init__()
self.num_tokens = num_tokens
self.proj = nn.Sequential(
nn.Linear(whisper_dim, output_dim),
nn.SiLU(),
nn.Linear(output_dim, output_dim),
)
# Learnable query tokens for cross-attention pooling
self.queries = nn.Parameter(torch.randn(1, num_tokens, output_dim) * 0.02)
self.cross_attn = CrossAttention(
query_dim=output_dim,
context_dim=output_dim,
heads=4,
dim_head=output_dim // 4,
)
self.norm = nn.LayerNorm(output_dim)
def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
"""
Args:
audio_features: (B, T, D) from Whisper encoder
Returns:
(B, num_tokens, output_dim) compressed audio tokens
"""
B = audio_features.shape[0]
# Project to output dim
projected = self.proj(audio_features)
# Cross-attention pooling to fixed number of tokens
queries = self.queries.expand(B, -1, -1)
tokens = self.cross_attn(queries, self.norm(projected))
return tokens
class LipSyncUNet(nn.Module):
"""Lightweight UNet for single-step latent inpainting.
Takes masked latents + reference latents + mask + audio features
and predicts the complete face latents with lip movements.
Input channels:
4 (masked latent) + 4 (reference latent) + 1 (mask) = 9
Output channels:
4 (predicted latent)
"""
def __init__(
self,
in_channels: int = 9,
out_channels: int = 4,
base_channels: int = 128,
channel_mults: list[int] = [1, 2, 4],
num_res_blocks: int = 2,
attention_resolutions: list[int] = [8, 16],
audio_context_dim: int = 384,
dropout: float = 0.1,
use_checkpoint: bool = True,
):
super().__init__()
self.use_checkpoint = use_checkpoint
# Audio feature projector
self.audio_projector = AudioProjector(
whisper_dim=audio_context_dim,
output_dim=audio_context_dim,
num_tokens=16,
)
# Initial convolution
self.conv_in = nn.Conv2d(in_channels, base_channels, 3, padding=1)
# Determine channels at each level
channels = [base_channels * m for m in channel_mults]
# Build encoder
self.down_blocks = nn.ModuleList()
ch_in = base_channels
current_res = 32 # Latent resolution (256 / 8)
for i, ch_out in enumerate(channels):
has_attn = current_res in attention_resolutions
is_last = i == len(channels) - 1
self.down_blocks.append(
DownBlock(
in_channels=ch_in,
out_channels=ch_out,
num_res_blocks=num_res_blocks,
has_attention=has_attn,
context_dim=audio_context_dim,
dropout=dropout,
downsample=not is_last,
)
)
ch_in = ch_out
if not is_last:
current_res //= 2
# Middle block
self.mid_block1 = ResBlock(channels[-1], channels[-1], dropout)
self.mid_attn = SpatialTransformerBlock(
channels[-1], audio_context_dim, dropout=dropout
)
self.mid_block2 = ResBlock(channels[-1], channels[-1], dropout)
# Build decoder
self.up_blocks = nn.ModuleList()
reversed_channels = list(reversed(channels))
for i, ch_out in enumerate(reversed_channels):
ch_in = reversed_channels[i]
skip_ch = ch_out # Skip connections from encoder
has_attn = current_res in attention_resolutions
is_last = i == len(reversed_channels) - 1
next_ch = reversed_channels[i + 1] if not is_last else base_channels
self.up_blocks.append(
UpBlock(
in_channels=ch_in,
out_channels=next_ch,
skip_channels=skip_ch,
num_res_blocks=num_res_blocks,
has_attention=has_attn,
context_dim=audio_context_dim,
dropout=dropout,
upsample=not is_last,
)
)
if not is_last:
current_res *= 2
# Output convolution
self.norm_out = GroupNorm32(32, base_channels)
self.act_out = nn.SiLU()
self.conv_out = nn.Conv2d(base_channels, out_channels, 3, padding=1)
# Initialize weights
self._init_weights()
def _init_weights(self):
"""Initialize weights for stable training."""
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
# Zero-initialize the output conv for residual learning
nn.init.zeros_(self.conv_out.weight)
nn.init.zeros_(self.conv_out.bias)
def forward(
self,
masked_latent: torch.Tensor,
reference_latent: torch.Tensor,
mask: torch.Tensor,
audio_features: torch.Tensor,
) -> torch.Tensor:
"""
Args:
masked_latent: (B, 4, H, W) - face latent with lower half zeroed
reference_latent: (B, 4, H, W) - original face latent (provides identity)
mask: (B, 1, H, W) - binary mask (1 = region to inpaint)
audio_features: (B, T, D) - Whisper encoder features
Returns:
(B, 4, H, W) - predicted complete face latent
"""
# Concatenate inputs
x = torch.cat([masked_latent, reference_latent, mask], dim=1) # (B, 9, H, W)
# Project audio features
audio_ctx = self.audio_projector(audio_features) # (B, 16, D)
# Initial conv
x = self.conv_in(x)
# Encoder with skip connections
all_skips = []
for down_block in self.down_blocks:
if self.use_checkpoint and self.training:
x, skips = checkpoint(
down_block, x, audio_ctx, use_reentrant=False
)
else:
x, skips = down_block(x, audio_ctx)
all_skips.extend(skips)
# Middle
x = self.mid_block1(x)
x = self.mid_attn(x, audio_ctx)
x = self.mid_block2(x)
# Decoder
for up_block in self.up_blocks:
# Get skip connections for this level
n_skips = len(up_block.res_blocks)
skips = all_skips[-n_skips:]
all_skips = all_skips[:-n_skips]
if self.use_checkpoint and self.training:
x = checkpoint(
up_block, x, skips, audio_ctx, use_reentrant=False
)
else:
x = up_block(x, skips, audio_ctx)
# Output
x = self.norm_out(x)
x = self.act_out(x)
x = self.conv_out(x)
# Residual: predict the delta from masked latent
# This makes it easier to learn - just predict what's missing
output = masked_latent + x * mask
return output
def get_param_count(self) -> dict:
"""Return parameter counts."""
total = sum(p.numel() for p in self.parameters())
trainable = sum(p.numel() for p in self.parameters() if p.requires_grad)
return {
"total": total,
"trainable": trainable,
"total_M": total / 1e6,
"trainable_M": trainable / 1e6,
}

Xet Storage Details

Size:
18.5 kB
·
Xet hash:
43aab2fa2b48f0214c8220de235e8647a5dd639d5887ba7287108e222f352e31

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.