File size: 1,106 Bytes
7e2301f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""Semantic regularization: make VAE latents linearly predictive of frozen SSL features
(w2v-BERT 2.0 / WavLM). Keeps the latent space easy for the LM to model without quantization."""

from __future__ import annotations

import torch
import torch.nn as nn
import torch.nn.functional as F


class SemanticProjector(nn.Module):
    def __init__(self, latent_dim: int, semantic_dim: int, hidden: int = 512):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv1d(latent_dim, hidden, 3, padding=1), nn.GELU(), nn.Conv1d(hidden, semantic_dim, 1)
        )

    def forward(self, z: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """z: (B, D, F) latents. target: (B, S, Ft) SSL features at any frame rate.
        Returns 1 - mean cosine similarity after resampling the target to the latent rate."""
        if target.shape[-1] != z.shape[-1]:
            target = F.interpolate(target.float(), size=z.shape[-1], mode="linear", align_corners=False)
        pred = self.net(z)
        return 1.0 - F.cosine_similarity(pred, target.detach().to(pred.dtype), dim=1).mean()