<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lokaranjanpanda on Medium]]></title>
        <description><![CDATA[Stories by Lokaranjanpanda on Medium]]></description>
        <link>https://medium.com/@lokaranjanpanda?source=rss-531ebf6bde5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JYUVuOSPnXl607aV</url>
            <title>Stories by Lokaranjanpanda on Medium</title>
            <link>https://medium.com/@lokaranjanpanda?source=rss-531ebf6bde5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:03:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lokaranjanpanda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Decoding LatentVoiceGrad: The Math Behind Diffusion, Flow Matching, and Zero-Shot VC]]></title>
            <link>https://medium.com/@lokaranjanpanda/decoding-latentvoicegrad-the-math-behind-diffusion-flow-matching-and-zero-shot-vc-c739f7e0483e?source=rss-531ebf6bde5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c739f7e0483e</guid>
            <dc:creator><![CDATA[Lokaranjanpanda]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 21:42:04 GMT</pubDate>
            <atom:updated>2026-03-04T04:05:47.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgK6q13ggDCHug8TlJFVqQ.png" /></figure><h3>Decoding LatentVoiceGrad: The Math Behind Diffusion, Flow Matching, and Zero-Shot VC.</h3><p>Voice Conversion is one of the key takeaways which has both required understanding of linguistics and then convert it into some different speaker acoustics ,pitch,loudness.</p><p>Today I will Breakdown the famous paper LatenVoiceGRAD of converting one speaker voice to another.This is an art piece of engineering according to me.</p><p>Voice is not So similar like text it has a continuos smoothing you don’t know which part of the voice sound like p and which sound like b.Second thing the it’s not discrete like text tokens that you just cut them and provide them to the model.For suppose if you are listening to a speaker with 16khz sound .In 1 sec there is 16000 samples .So providing them to a transformer requires humangous VRAM.So Researchers use something call mel spectrogram it’s the compression if the voice that stores essential things the speaker acoustics,linguistic,pitch ,loudness and all.</p><p>The authors of this paper uses diffusion to convert the Speaker mel spectrogram to another speaker mel spectrogram.Then their is a vocoders which creates the actual raw audio from the mel spectrogram.For more Information read the vocoder paper .</p><p>So the First phase includes the compression of the high resolution(80 channels) mel spectrogram to low (32 channels) mel spectrogram.its like delete the details to delete the speaker details but not too much that you lose linguistics and phenomes.</p><h3>Phase 1: Adversarial Latent Autoencoder Training</h3><h3>Problem Formulation</h3><p>Given an input waveform <em>y</em>, we compute its mel-spectrogram <em>x</em> using STFT followed by a mel-filterbank projection, producing a matrix of shape <em>T × 80</em>, where <em>T</em> is the number of time frames and 80 is the number of mel-frequency channels.</p><p>x = \mathcal{M}(y) \in \mathbb{R}^{T \times 80}</p><h3>Objective: Undercomplete Autoencoder</h3><p>We build an encoder <em>g</em>_φ and decoder <em>f</em>_θ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/0*A2RxY5p4y-aye7ET" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/0*dySYbqiOQaTgdgou" /></figure><p>The reconstructed mel is x̂ = f_θ(g_φ(x)), and after passing through a pretrained vocoder <em>h</em>, the synthesized waveform ŷ = h(x̂) should be indistinguishable from real speech.</p><h3>Why 80 → 32 Compression?</h3><p>Modeling p(x) directly in 80 dimensions is expensive. By compressing to 32 dimensions, Phase 2&#39;s diffusion/flow model operates on p(z) with 60% less memory, lower noise instability, and fewer artifacts. The bottleneck enforces:</p><p>I(z; x) &lt; I(x; x)</p><p>meaning we retain semantic acoustic identity while discarding redundant spectral details.</p><h3>Encoder Architecture: BiLSTM-Based Compression</h3><p>Speech is temporally correlated — p(x_t | x_{&lt;t}) ≠ p(x_t) — so simple frame-wise compression loses context. A BiLSTM captures both past and future phoneme dependencies:</p><p>— so simple frame-wise compression loses context. A BiLSTM captures both past and future phoneme dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/95/0*pw9jU871JFyEOc6K" /></figure><p>The full encoder stack is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*rmqZ8v3drXmHQe1D" /></figure><p>The decoder mirrors this symmetrically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*YvvEKmQOnvLpD85n" /></figure><h3>Frozen HiFi-GAN Vocoder</h3><p>We use a pretrained HiFi-GAN generator <em>h</em> (from jik876/hifi-gan) with frozen weights (∇h = 0). This forces the autoencoder to produce mel representations that lie on the manifold the vocoder already understands, resulting in higher-quality waveform synthesis.</p><h3>Adversarial Discriminator: MPD + MSD</h3><p>We use HiFi-GAN’s original discriminator D_ψ = {D_MPD, D_MSD} operating at multiple temporal periods and scales. This preserves fine harmonic textures, pitch periodicity, and multi-resolution frequency realism.</p><h3>Loss Function</h3><p>The full training objective is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*EK2Vv9nZL9wu9E2T" /></figure><p>with λ = 45.</p><p><strong>1. Reconstruction Loss</strong> — direct mel-domain L1:The Most essential loss used in any autoencoders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/0*3nDuDFMSd5x9jqfn" /></figure><p><strong>2. Post-Vocoder Mel Loss</strong> — cycle consistency through waveform space. Let x̃ = M(ŷ):This loss is used because the model can cheat by predicting the mean .Suppose you are dealing with white and a black channel Your model will predict the mean of the white and black to reduce the loss but that doesn’t decide the true distribution.So the converted mel spectrogram must be of real distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/0*GRUbRGcCQgw0TT5a" /></figure><p><strong>3. LSGAN Adversarial Loss</strong> — improves gradient stability over BCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/0*GZHS3_geCnYsm-z3" /></figure><p><strong>4. Feature Matching Loss</strong> — aligns intermediate discriminator representations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*Av8nTK0owfrintc6" /></figure><p><strong>5. KL Divergence</strong> — the most critical term for Phase 2. We parameterize the latent as z = μ + σ ⊙ ε, where ε ~ N(0, I):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*eBLirPHTjwmpAGeP" /></figure><p>This enforces p(z) ≈ N(0, I), which is the prior assumed by the Phase 2 diffusion/flow model. Without this, the bottleneck memorizes exact mel patterns and breaks the generative modeling setup.</p><p>This is used cause we don’t want ki the compressed channels deviate from the original distribution.</p><h3>Final Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/0*wfxqSoabh3lOS34v" /></figure><h3>Quick Setup</h3><pre>git clone https://github.com/jik876/hifi-gan.git</pre><p>Mel extraction parameters: <strong>22,050 Hz</strong> sample rate · <strong>1024</strong> FFT size · <strong>256</strong> hop length · <strong>80</strong> mel bins.</p><pre>import os<br>import sys<br>import json<br>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>from torch.utils.data import Dataset, DataLoader<br>import librosa<br>import numpy as np<br><br># ─────────────────────────────────────────────────────────────────────────────<br># Import official HiFi-GAN models (clone repo first — see SETUP above)<br># ─────────────────────────────────────────────────────────────────────────────<br>HIFIGAN_REPO = os.path.join(os.path.dirname(__file__), &quot;hifi-gan&quot;)<br>if HIFIGAN_REPO not in sys.path:<br>    sys.path.insert(0, HIFIGAN_REPO)<br><br>try:<br>    from models import (<br>        Generator as HifiGANGenerator,<br>        MultiPeriodDiscriminator,      # MPD  ← official<br>        MultiScaleDiscriminator,       # MSD  ← official<br>    )<br>    from env import AttrDict<br>    print(&quot;✅ Official HiFi-GAN MPD + MSD loaded.&quot;)<br>except ImportError as e:<br>    raise ImportError(<br>        &quot;Could not import HiFi-GAN models.\n&quot;<br>        &quot;Run:  git clone https://github.com/jik876/hifi-gan.git\n&quot;<br>        &quot;and place it next to this script.\n&quot;<br>        f&quot;Original error: {e}&quot;<br>    )<br><br># ─────────────────────────────────────────────────────────────────────────────<br># Audio / Mel constants  (must match HiFi-GAN config.json)<br># ─────────────────────────────────────────────────────────────────────────────<br>SR          = 22050<br>N_MELS      = 80<br>HOP_LENGTH  = 256<br>WIN_LENGTH  = 1024<br>N_FFT       = 1024<br>FMIN        = 0<br>FMAX        = 8000          # HiFi-GAN UNIVERSAL_V1 uses 8000<br><br># ─────────────────────────────────────────────────────────────────────────────<br># Audio utilities<br># ─────────────────────────────────────────────────────────────────────────────<br>def load_mp3_to_mel(path):<br>    y, sr = librosa.load(path, sr=SR)<br>    mel = librosa.feature.melspectrogram(<br>        y=y, sr=sr, n_fft=N_FFT, hop_length=HOP_LENGTH,<br>        win_length=WIN_LENGTH, n_mels=N_MELS, fmin=FMIN, fmax=FMAX, power=1.0<br>    )<br>    mel_db   = librosa.power_to_db(mel, ref=1.0)<br>    mel_norm = (mel_db - mel_db.mean()) / (mel_db.std() + 1e-6)<br>    return mel_norm.T   # (frames, N_MELS)<br><br>def wav_to_mel_tensor(wav_np, device, T=None):<br>    &quot;&quot;&quot;Convert a numpy waveform → normalized mel tensor (T, N_MELS).&quot;&quot;&quot;<br>    m     = librosa.feature.melspectrogram(y=wav_np, sr=SR, n_fft=N_FFT,<br>                                           hop_length=HOP_LENGTH, n_mels=N_MELS,<br>                                           fmin=FMIN, fmax=FMAX, power=1.0)<br>    m_db  = librosa.power_to_db(m, ref=1.0)<br>    m_norm = (m_db - m_db.mean()) / (m_db.std() + 1e-6)  # (N_MELS, t)<br>    if T is not None:<br>        if m_norm.shape[1] &gt;= T:<br>            m_norm = m_norm[:, :T]<br>        else:<br>            pad    = np.zeros((N_MELS, T - m_norm.shape[1]), dtype=m_norm.dtype)<br>            m_norm = np.concatenate([m_norm, pad], axis=1)<br>    return torch.from_numpy(m_norm.T).float().to(device)   # (T, N_MELS)<br><br></pre><p>DataLoader</p><pre>class MP3MelDataset(Dataset):<br>    def __init__(self, file_list, frames=128):<br>        self.files  = file_list<br>        self.frames = frames<br><br>    def __len__(self):<br>        return len(self.files)<br><br>    def __getitem__(self, idx):<br>        mel = load_mp3_to_mel(self.files[idx])  # (T, 80)<br>        if mel.shape[0] &gt;= self.frames:<br>            start = np.random.randint(0, mel.shape[0] - self.frames + 1)<br>            mel   = mel[start:start + self.frames]<br>        else:<br>            pad = np.zeros((self.frames - mel.shape[0], mel.shape[1]), dtype=mel.dtype)<br>            mel = np.concatenate([mel, pad], axis=0)<br>        return torch.from_numpy(mel).float()    # (frames, 80)</pre><p>Encoder and Decoder,Vocoder</p><pre>class Encoder(nn.Module):<br>    def __init__(self, n_mels=80, hidden_fc=256, lstm_hidden=256, bottleneck=32):<br>        super().__init__()<br>        self.fc1       = nn.Linear(n_mels, hidden_fc)<br>        self.lrelu     = nn.LeakyReLU(0.2)<br>        self.bilstm    = nn.LSTM(hidden_fc, lstm_hidden, num_layers=2,<br>                                 bidirectional=True, batch_first=True)<br>        self.fc_out    = nn.Linear(2 * lstm_hidden, bottleneck)<br>        self.mu_head   = nn.Linear(bottleneck, bottleneck)<br>        self.logvar_head = nn.Linear(bottleneck, bottleneck)<br><br>    def forward(self, x):<br>        h         = self.lrelu(self.fc1(x))<br>        h, _      = self.bilstm(h)<br>        z         = self.fc_out(h)<br>        mu        = self.mu_head(z)<br>        logvar    = self.logvar_head(z)<br>        std       = torch.exp(0.5 * logvar)<br>        z_sample  = mu + std * torch.randn_like(std)<br>        return z_sample, mu, logvar<br><br><br>class Decoder(nn.Module):<br>    def __init__(self, bottleneck=32, hidden_fc=256, lstm_hidden=256, n_mels=80):<br>        super().__init__()<br>        self.fc1    = nn.Linear(bottleneck, hidden_fc)<br>        self.lrelu  = nn.LeakyReLU(0.2)<br>        self.bilstm = nn.LSTM(hidden_fc, lstm_hidden, num_layers=2,<br>                              bidirectional=True, batch_first=True)<br>        self.fc_out = nn.Linear(2 * lstm_hidden, n_mels)<br><br>    def forward(self, z):<br>        h       = self.lrelu(self.fc1(z))<br>        h, _    = self.bilstm(h)<br>        return self.fc_out(h)  # (B, T, n_mels)<br><br># ─────────────────────────────────────────────────────────────────────────────<br># Official HiFi-GAN vocoder loader<br># ─────────────────────────────────────────────────────────────────────────────<br>def load_hifigan_vocoder(checkpoint_dir=&quot;./hifigan_pretrained&quot;, device=&quot;cpu&quot;):<br>    &quot;&quot;&quot;<br>    Loads the pretrained HiFi-GAN Generator from official jik876 checkpoint.<br>    checkpoint_dir must contain:<br>        config.json                (from the official repo release)<br>        generator                  (checkpoint file, no extension, or rename to generator.pt)<br>    &quot;&quot;&quot;<br>    config_path = os.path.join(checkpoint_dir, &quot;config.json&quot;)<br>    ckpt_path   = os.path.join(checkpoint_dir, &quot;generator&quot;)       # official naming<br>    if not os.path.exists(ckpt_path):<br>        ckpt_path = os.path.join(checkpoint_dir, &quot;generator.pt&quot;)  # fallback<br><br>    with open(config_path) as f:<br>        h = AttrDict(json.load(f))<br><br>    generator = HifiGANGenerator(h).to(device)<br>    state = torch.load(ckpt_path, map_location=device)<br>    # Official checkpoints are saved as {&quot;generator&quot;: state_dict, ...}<br>    generator.load_state_dict(state[&quot;generator&quot;] if &quot;generator&quot; in state else state)<br>    generator.eval()<br>    generator.remove_weight_norm()<br>    print(f&quot;✅ HiFi-GAN Generator loaded from {ckpt_path}&quot;)<br>    return generator, h<br><br><br>def synthesize_waveform(generator, mel_batch):<br>    &quot;&quot;&quot;<br>    mel_batch : (B, T, n_mels)  — decoder output<br>    returns   : (B, T_wav)      — waveform<br>    HiFi-GAN Generator expects (B, n_mels, T).<br>    &quot;&quot;&quot;<br>    mel_t = mel_batch.permute(0, 2, 1)           # → (B, n_mels, T)<br>    with torch.no_grad():<br>        wav = generator(mel_t).squeeze(1)         # → (B, T_wav)<br>    return wav</pre><p>Losses</p><pre>def disc_loss_mpd_msd(mpd, msd, y_real, y_fake):<br>    &quot;&quot;&quot;<br>    LSGAN discriminator loss for both MPD and MSD.<br>    y_real / y_fake : (B, T_wav)<br>    Returns scalar L_D.<br>    Read Hi-Fi GAN Research Paper for More Infromation.<br>    &quot;&quot;&quot;<br>    y_real_u  = y_real.unsqueeze(1)   # (B, 1, T)<br>    y_fake_u  = y_fake.unsqueeze(1)<br><br>    # MPD<br>    real_outs_mpd, _ = mpd(y_real_u)<br>    fake_outs_mpd, _ = mpd(y_fake_u.detach())<br>    loss_d = sum(<br>        torch.mean((r - 1) ** 2) + torch.mean(f ** 2)<br>        for r, f in zip(real_outs_mpd, fake_outs_mpd)<br>    )<br>    # MSD<br>    real_outs_msd, _ = msd(y_real_u)<br>    fake_outs_msd, _ = msd(y_fake_u.detach())<br>    loss_d += sum(<br>        torch.mean((r - 1) ** 2) + torch.mean(f ** 2)<br>        for r, f in zip(real_outs_msd, fake_outs_msd)<br>    )<br>    return loss_d<br><br><br>def gen_loss_mpd_msd(mpd, msd, y_fake):<br>    &quot;&quot;&quot;<br>    Generator adversarial + feature-matching loss from both MPD and MSD.<br>    Returns (L_adv_gen, L_feat). Read Hi-Fi GAN Research Paper for More Infromation <br>    &quot;&quot;&quot;<br>    y_fake_u = y_fake.unsqueeze(1)<br><br>    # ── adversarial ────────────────────────────────────────────────────────<br>    fake_outs_mpd, _ = mpd(y_fake_u)<br>    fake_outs_msd, _ = msd(y_fake_u)<br>    L_adv = (<br>        sum(torch.mean((f - 1) ** 2) for f in fake_outs_mpd)<br>      + sum(torch.mean((f - 1) ** 2) for f in fake_outs_msd)<br>    )<br><br>    # ── feature matching  (uses stored real feats from disc_loss call) ──────<br>    # NOTE: call get_real_feats() below once per batch to avoid double forward<br>    return L_adv<br><br><br>def feature_matching_loss(mpd, msd, y_real, y_fake):<br>    &quot;&quot;&quot;<br>    L1 feature-matching loss between real and fake intermediate disc features.<br>    &quot;&quot;&quot;<br>    y_real_u = y_real.unsqueeze(1)<br>    y_fake_u = y_fake.unsqueeze(1)<br><br>    _, real_feats_mpd = mpd(y_real_u)<br>    _, fake_feats_mpd = mpd(y_fake_u)<br>    _, real_feats_msd = msd(y_real_u)<br>    _, fake_feats_msd = msd(y_fake_u)<br><br>    L_feat = 0.0<br>    for rf_list, ff_list in [(real_feats_mpd, fake_feats_mpd),<br>                              (real_feats_msd, fake_feats_msd)]:<br>        for rf_sub, ff_sub in zip(rf_list, ff_list):<br>            for rf, ff in zip(rf_sub, ff_sub):<br>                L_feat = L_feat + F.l1_loss(ff, rf.detach())<br><br>    return L_feat</pre><p>Training Loop</p><pre>def train_epoch(encoder, decoder, generator,<br>                mpd, msd,<br>                loader, optim_g, optim_d,<br>                device=&quot;cpu&quot;, lambda_reg=45.0):<br>    &quot;&quot;&quot;<br>    One epoch of training.<br><br>    generator : pretrained HiFi-GAN Generator (frozen / fine-tuned — your choice)<br>    mpd       : official MultiPeriodDiscriminator  (trained)<br>    msd       : official MultiScaleDiscriminator   (trained)<br>    &quot;&quot;&quot;<br>    encoder.train(); decoder.train()<br>    mpd.train();     msd.train()<br>    # Keep generator frozen (set to .train() only if fine-tuning)<br>    generator.eval()<br><br>    for batch_idx, mel in enumerate(loader):<br>        mel = mel.to(device)          # (B, T, 80)<br>        B, T, _ = mel.shape<br><br>        # ── Encoder → Decoder ────────────────────────────────────────────────<br>        z, mu, logvar = encoder(mel)       # (B, T, 32)<br>        mel_hat       = decoder(z)         # (B, T, 80)<br><br>        # ── Synthesize waveform via frozen HiFi-GAN generator ────────────────<br>        y_hat = synthesize_waveform(generator, mel_hat)    # (B, T_wav)  no grad tracked<br>        # Also synthesize from real mel to get &quot;real&quot; waveform target<br>        y_real = synthesize_waveform(generator, mel)       # (B, T_wav)<br>        # Trim / pad to same length<br>        min_len = min(y_hat.shape[-1], y_real.shape[-1])<br>        y_hat   = y_hat[..., :min_len]<br>        y_real  = y_real[..., :min_len]<br><br>        # ════════════════════════════════════════════════════════════════════<br>        # 1) UPDATE DISCRIMINATORS  (MPD + MSD)<br>        # ════════════════════════════════════════════════════════════════════<br>        optim_d.zero_grad()<br><br>        L_d = disc_loss_mpd_msd(mpd, msd, y_real, y_hat)<br>        L_d.backward()<br>        optim_d.step()<br><br>        # ════════════════════════════════════════════════════════════════════<br>        # 2) UPDATE GENERATOR  (Encoder + Decoder)<br>        # ════════════════════════════════════════════════════════════════════<br>        optim_g.zero_grad()<br><br>        # Re-synthesize with grad enabled for generator update<br>        mel_hat_g = decoder(encoder(mel)[0])         # fresh forward<br>        y_hat_g   = generator(mel_hat_g.permute(0, 2, 1)).squeeze(1)   # grad flows here<br>        y_hat_g   = y_hat_g[..., :min_len]<br><br>        # Reconstruction loss (mel space)<br>        L_rec = F.l1_loss(mel_hat_g, mel)<br><br>        # KL divergence<br>        L_kl = 0.5 * torch.mean(torch.exp(logvar) + mu ** 2 - 1 - logvar)<br><br>        # Mel loss from synthesized waveform<br>        mel_yhat_list = []<br>        for b in range(B):<br>            m_t = wav_to_mel_tensor(y_hat_g[b].detach().cpu().numpy(), device, T)<br>            mel_yhat_list.append(m_t)<br>        mel_yhat = torch.stack(mel_yhat_list, dim=0)     # (B, T, 80)<br>        L_mel    = F.l1_loss(mel_yhat, mel)<br><br>        # Adversarial loss  (MPD + MSD)<br>        L_adv  = gen_loss_mpd_msd(mpd, msd, y_hat_g)<br><br>        # Feature-matching loss  (MPD + MSD)<br>        L_feat = feature_matching_loss(mpd, msd, y_real.detach(), y_hat_g)<br><br>        # Total generator objective (λ=45 scales reconstruction terms per paper)<br>        J_ae = lambda_reg * (L_rec + L_mel + L_kl) + L_adv + L_feat<br>        J_ae.backward()<br>        optim_g.step()<br><br>        if batch_idx % 20 == 0:<br>            print(<br>                f&quot;  batch {batch_idx:4d} | &quot;<br>                f&quot;L_d={L_d.item():.4f}  L_rec={L_rec.item():.4f}  &quot;<br>                f&quot;L_kl={L_kl.item():.4f}  L_mel={L_mel.item():.4f}  &quot;<br>                f&quot;L_adv={L_adv.item():.4f}  L_feat={L_feat.item():.4f}&quot;<br>            )<br><br><br># ─────────────────────────────────────────────────────────────────────────────<br># Entry point<br># ─────────────────────────────────────────────────────────────────────────────<br>if __name__ == &quot;__main__&quot;:<br>    mp3_files = [&quot;./data/speaker1_001.mp3&quot;, &quot;./data/speaker1_002.mp3&quot;]<br>    ds = MP3MelDataset(mp3_files, frames=128)<br>    dl = DataLoader(ds, batch_size=4, shuffle=True, num_workers=2, drop_last=True)<br><br>    device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>    print(f&quot;Using device: {device}&quot;)<br><br>    # ── Latent Autoencoder ──────────────────────────────────────────────────<br>    enc  = Encoder().to(device)<br>    dec  = Decoder().to(device)<br><br>    # ── Official HiFi-GAN: Generator + MPD + MSD ───────────────────────────<br>    generator, h_cfg = load_hifigan_vocoder(&quot;./hifigan_pretrained&quot;, device=device)<br>    mpd = MultiPeriodDiscriminator().to(device)<br>    msd = MultiScaleDiscriminator().to(device)<br><br>    # ── Optimizers ──────────────────────────────────────────────────────────<br>    optim_g = torch.optim.AdamW(<br>        list(enc.parameters()) + list(dec.parameters()),<br>        lr=2e-4, betas=(0.8, 0.99)<br>    )<br>    optim_d = torch.optim.AdamW(<br>        list(mpd.parameters()) + list(msd.parameters()),<br>        lr=2e-4, betas=(0.8, 0.99)<br>    )<br><br>    # ── Training ────────────────────────────────────────────────────────────<br>    for epoch in range(10):<br>        print(f&quot;\n── Epoch {epoch} ──────────────────────────&quot;)<br>        train_epoch(enc, dec, generator, mpd, msd, dl,<br>                    optim_g, optim_d, device=device, lambda_reg=45.0)<br>        # save checkpoints<br>        torch.save({<br>            &quot;encoder&quot;:  enc.state_dict(),<br>            &quot;decoder&quot;:  dec.state_dict(),<br>            &quot;mpd&quot;:      mpd.state_dict(),<br>            &quot;msd&quot;:      msd.state_dict(),<br>            &quot;optim_g&quot;:  optim_g.state_dict(),<br>            &quot;optim_d&quot;:  optim_d.state_dict(),<br>        }, f&quot;checkpoint_epoch{epoch:03d}.pt&quot;)<br>        print(f&quot;  → checkpoint saved.&quot;)</pre><h3>Phase 2: Flow Matching in the Latent Space</h3><h3>The Core Objective</h3><p>Phase 2 trains a vector field network <em>v</em>_θ <strong>entirely inside the 32-dimensional latent space</strong> built in Phase 1. The Autoencoder and Vocoder are completely frozen and excluded from the training loop.</p><p>Why work in latent space? Mapping ODE trajectories over <em>T × 32</em> is exponentially cheaper — in memory, compute, and numerical stability — than doing it over <em>T × 80</em> mel frames.</p><h3>Architecture: Conditional 1D-CNN</h3><p><em>v</em>_θ is a <strong>WaveNet-style 1D-CNN</strong> adapted for the 32-channel bottleneck. At each step, it receives three inputs:</p><p><strong>1. Noisy Latent</strong> — the interpolated sample <em>z_t</em> at diffusion time <em>t</em></p><p><strong>2. Time Embedding</strong> — <em>t</em> is injected via sinusoidal positional encoding, so the network knows exactly where it sits along the ODE trajectory</p><p><strong>3. Speaker Identity</strong> (<em>s</em>) — extracted by a frozen, pretrained <strong>GE2E speaker encoder</strong>, projecting voice characteristics into a continuous vector space. This enables zero-shot conversion for unseen speakers</p><p><strong>4. Linguistic Content</strong> (<em>p</em>) — a sequence of discrete phonemes from a pretrained ASR model</p><h3>Why Phonemes Instead of HuBERT?</h3><p>This is the most consequential design choice in the paper. HuBERT and wav2vec 2.0 seem like the obvious choice — they are more powerful. But that is exactly the problem.</p><p><strong>HuBERT embeddings are not speaker-agnostic.</strong> Alongside the words, they encode the source speaker’s pitch, timbre, and vocal tract resonance. If you condition <em>v</em>_θ on a HuBERT embedding of Speaker A while injecting Speaker B’s GE2E vector as the target, you hand the network two conflicting instructions simultaneously — “keep Speaker A’s acoustic fingerprint” and “sound like Speaker B.” The output is an entangled, metallic voice.</p><p><strong>The phoneme bottleneck surgically solves this.</strong> A phoneme sequence (e.g., h-ɛ-l-oʊ) is a sterile, speaker-agnostic blueprint — it carries zero acoustic identity. By stripping content down to discrete phonetic units, the model is forced to derive all voice characteristics exclusively from the target GE2E embedding, guaranteeing a clean, disentangled conversion.</p><h3>Training: Self-Reconstruction via Straight-Line Paths</h3><p>During training, the model never performs voice conversion. It learns by <strong>self-reconstruction</strong>.</p><p>The Conditional Flow Matching framework defines a straight-line interpolation between pure Gaussian noise <em>z</em>₀ and the clean target latent <em>z</em>₁:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/0*LAJ7BL8MKU1a6eHU" /></figure><p>The ground-truth velocity along this path is simply the constant vector <em>(z₁ − z₀)</em>. The network is trained to regress this target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*O_VIR9Wn0BVNIM7r" /></figure><p>Note there is <strong>no vocoder in the training loop</strong>. Backpropagating through HiFi-GAN at every ODE timestep would be prohibitively slow. The L1 loss in 32-dimensional latent space keeps training lightweight and numerically stable.</p><h3>Inference: The Bait-and-Switch</h3><p>Once trained, the system performs voice conversion using <strong>Euler integration</strong> — but with a critical modification to the starting point.</p><h4>Step 1 — Partial Noise Injection (The 70% Rule)</h4><p>The source audio is encoded into <em>z_src</em> via the frozen encoder <em>g</em>_φ. Rather than starting from pure noise, the model initializes from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*fIWyuiRbNNQkeVQZ" /></figure><p>Starting from <em>r = 1.0</em> (pure source) skips conversion entirely. Starting from <em>r = 0.0</em> (pure noise) destroys the prosody, timing, and emotional pacing of the original. The <strong>30% noise residual</strong> acts as a scaffold — it anchors the trajectory to the source’s rhythmic structure while leaving the voice identity fully malleable.</p><h4>Step 2 — The Bait-and-Switch</h4><p>The network receives:</p><ul><li><strong>Content</strong> (<em>p</em>): phonemes extracted from the <strong>source</strong> audio</li><li><strong>Identity</strong> (<em>s</em>): the GE2E embedding of the <strong>target</strong> speaker <em>s_target</em></li></ul><p>Because the model learned to rigidly obey the speaker embedding during training, Euler’s method pulls <em>z_start</em> out of Speaker A’s acoustic region and deposits it precisely into Speaker B’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/0*LdWX0o_kaMp_9hdt" /></figure><h4>Step 3 — Decoding</h4><p>The converted latent <em>z_converted</em> is passed through the frozen decoder <em>f</em>_θ, then through the frozen HiFi-GAN vocoder <em>h</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/0*4yd3XRKhABa3Vquq" /></figure><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>import math<br><br># ==========================================<br># 1. Time Embedding (Sinusoidal)<br># ==========================================<br>class TimeEmbedding(nn.Module):<br>    &quot;&quot;&quot;Encodes the continuous time t (or discrete timestep l) into a vector.&quot;&quot;&quot;<br>    def __init__(self, dim):<br>        super().__init__()<br>        self.dim = dim<br><br>    def forward(self, t):<br>        # t shape: (B,)<br>        half_dim = self.dim // 2<br>        embeddings = math.log(10000) / (half_dim - 1)<br>        embeddings = torch.exp(torch.arange(half_dim, device=t.device) * -embeddings)<br>        embeddings = t.unsqueeze(1) * embeddings.unsqueeze(0)<br>        embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1)<br>        return embeddings<br><br># ==========================================<br># 2. Conditional WaveNet Block<br># ==========================================<br>class ConditionalResidualBlock(nn.Module):<br>    &quot;&quot;&quot;A 1D-CNN block that injects Time, Speaker, and Phoneme conditioning.&quot;&quot;&quot;<br>    def __init__(self, residual_channels, dilation, cond_dim):<br>        super().__init__()<br>        self.dilated_conv = nn.Conv1d(<br>            residual_channels, 2 * residual_channels, kernel_size=3, <br>            padding=dilation, dilation=dilation<br>        )<br>        # FiLM (Feature-wise Linear Modulation) projection for conditioning<br>        self.cond_proj = nn.Linear(cond_dim, 2 * residual_channels)<br>        self.output_proj = nn.Conv1d(residual_channels, residual_channels, kernel_size=1)<br><br>    def forward(self, x, cond):<br>        # x: (B, C, T), cond: (B, cond_dim, T) or (B, cond_dim, 1)<br>        residual = x<br>        <br>        # 1. Pass through dilated conv<br>        h = self.dilated_conv(x)<br>        <br>        # 2. Add conditioning (Time + Speaker + Phonemes)<br>        c = self.cond_proj(cond.transpose(1, 2)).transpose(1, 2)<br>        h = h + c<br>        <br>        # 3. Gated Activation (tanh * sigmoid)<br>        gate, filter_ = torch.chunk(h, 2, dim=1)<br>        h = torch.tanh(filter_) * torch.sigmoid(gate)<br>        <br>        # 4. Output projection and residual connection<br>        out = self.output_proj(h)<br>        return out + residual, out<br><br># ==========================================<br># 3. The Core Network (v_theta or epsilon_theta)<br># ==========================================<br>class LatentEstimator(nn.Module):<br>    &quot;&quot;&quot;The unified network for both Flow Matching and Diffusion in the 32-dim space.&quot;&quot;&quot;<br>    def __init__(self, latent_dim=32, speaker_dim=256, phoneme_dim=256, <br>                 residual_channels=256, num_blocks=8):<br>        super().__init__()<br>        self.time_emb = TimeEmbedding(residual_channels)<br>        <br>        # Initial projection of the 32-dim latent<br>        self.input_proj = nn.Conv1d(latent_dim, residual_channels, kernel_size=1)<br>        <br>        # Total conditioning dimension<br>        cond_dim = residual_channels + speaker_dim + phoneme_dim<br>        <br>        self.blocks = nn.ModuleList([<br>            ConditionalResidualBlock(residual_channels, dilation=2**i, cond_dim=cond_dim)<br>            for i in range(num_blocks)<br>        ])<br>        <br>        # Final projection back to 32-dim<br>        self.final_proj1 = nn.Conv1d(residual_channels, residual_channels, kernel_size=1)<br>        self.final_proj2 = nn.Conv1d(residual_channels, latent_dim, kernel_size=1)<br><br>    def forward(self, z, t, s, p):<br>        # z: (B, 32, T) - The noisy latent<br>        # t: (B,)       - The timestep<br>        # s: (B, 256)   - GE2E Target Speaker Embedding<br>        # p: (B, 256, T)- Phoneme feature sequence<br>        <br>        B, _, T = z.shape<br>        <br>        # 1. Embed Time<br>        t_emb = self.time_emb(t).unsqueeze(-1).expand(-1, -1, T) # (B, res_channels, T)<br>        <br>        # 2. Expand Speaker Embedding to match time sequence<br>        s_emb = s.unsqueeze(-1).expand(-1, -1, T)                # (B, speaker_dim, T)<br>        <br>        # 3. Concatenate all conditions<br>        cond = torch.cat([t_emb, s_emb, p], dim=1)               # (B, cond_dim, T)<br>        <br>        # 4. Pass through WaveNet blocks<br>        x = self.input_proj(z)<br>        skip_connection = 0<br>        for block in self.blocks:<br>            x, skip = block(x, cond)<br>            skip_connection += skip<br>            <br>        # 5. Final output<br>        out = F.relu(skip_connection)<br>        out = F.relu(self.final_proj1(out))<br>        return self.final_proj2(out) # Returns either vector field (FM) or noise (Diffusion)<br><br># ==========================================<br># 4. Training Objectives (Self-Reconstruction)<br># ==========================================<br><br>def compute_flow_matching_loss(model, z1, s, p):<br>    &quot;&quot;&quot;Phase 2 Training for Flow Matching (L_CFM).&quot;&quot;&quot;<br>    B = z1.shape[0]<br>    # 1. Sample pure noise<br>    z0 = torch.randn_like(z1)<br>    <br>    # 2. Sample random time t in [0, 1]<br>    t = torch.rand(B, device=z1.device)<br>    t_expand = t.view(B, 1, 1)<br>    <br>    # 3. Construct straight-line path<br>    zt = t_expand * z1 + (1 - t_expand) * z0<br>    <br>    # 4. The target vector field is simply the difference<br>    target_v = z1 - z0<br>    <br>    # 5. Predict the vector field using the model<br>    pred_v = model(zt, t, s, p)<br>    <br>    # 6. L1 Loss (Crucial for VoiceGrad stability)<br>    loss = F.l1_loss(pred_v, target_v)<br>    return loss<br><br>def compute_diffusion_loss(model, z0, s, p, alpha_bar_l):<br>    &quot;&quot;&quot;Phase 2 Training for Langevin Dynamics/Diffusion (L_VG1).&quot;&quot;&quot;<br>    # z0 here is the clean latent, alpha_bar_l is the noise schedule at step l<br>    B = z0.shape[0]<br>    eps = torch.randn_like(z0)<br>    <br>    # 1. Add noise according to diffusion schedule<br>    alpha_bar_expand = alpha_bar_l.view(B, 1, 1)<br>    zl = torch.sqrt(alpha_bar_expand) * z0 + torch.sqrt(1 - alpha_bar_expand) * eps<br>    <br>    # 2. Predict the injected noise<br>    # (In discrete diffusion, t is the integer step index)<br>    pred_eps = model(zl, t, s, p)<br>    <br>    # 3. L1 Loss<br>    loss = F.l1_loss(pred_eps, eps)<br>    return loss<br><br># ==========================================<br># 5. Inference Loops (The &quot;Bait-and-Switch&quot;)<br># ==========================================<br><br>@torch.no_grad()<br>def flow_matching_inference(model, z_source, s_target, p_source, L=10, r=0.7):<br>    &quot;&quot;&quot;<br>    Zero-Shot VC Inference using Flow Matching ODE (Euler Method).<br>    z_source: Clean 32-dim latent of Speaker A<br>    s_target: GE2E Embedding of Speaker B<br>    p_source: Phonemes extracted from Speaker A<br>    &quot;&quot;&quot;<br>    B, _, T = z_source.shape<br>    device = z_source.device<br>    <br>    # 1. The 70% Rule: Mix source with noise to destroy identity but keep pacing<br>    noise = torch.randn_like(z_source)<br>    z = (1 - r) * z_source + r * noise <br>    <br>    # 2. Euler ODE Solver Step<br>    # We start from t = (1-r) because we didn&#39;t start from 100% noise<br>    t_start = 1.0 - r <br>    dt = (1.0 - t_start) / L<br>    <br>    for i in range(L):<br>        # Current time<br>        t_val = t_start + i * dt<br>        t_tensor = torch.full((B,), t_val, device=device)<br>        <br>        # Predict Vector Field<br>        v_pred = model(z, t_tensor, s_target, p_source)<br>        <br>        # Take a discrete step forward<br>        z = z + v_pred * dt<br>        <br>    # z is now completely mapped to Speaker B&#39;s acoustic space<br>    return z<br><br><br><br>@torch.no_grad()<br>def diffusion_inference(model, z_source, s_target, p_source, alphas, alpha_bars, L_prime=50, r=0.7):<br>    &quot;&quot;&quot;<br>    Zero-Shot VC Inference using Annealed Langevin Dynamics (Reverse Diffusion).<br>    Requires a predefined variance schedule (alphas, alpha_bars).<br>    &quot;&quot;&quot;<br>    B, _, T = z_source.shape<br>    device = z_source.device<br>    <br>    # 1. Forward process to step L_prime (based on ratio r)<br>    noise = torch.randn_like(z_source)<br>    alpha_bar_L = alpha_bars[L_prime].view(1, 1, 1)<br>    z = torch.sqrt(alpha_bar_L) * z_source + torch.sqrt(1 - alpha_bar_L) * noise<br>    <br>    # 2. Reverse Diffusion (Langevin Dynamics)<br>    for l in reversed(range(1, L_prime + 1)):<br>        t_tensor = torch.full((B,), l, device=device)<br>        <br>        # Predict noise<br>        eps_pred = model(z, t_tensor, s_target, p_source)<br>        <br>        # Calculate reverse step math<br>        a_l = alphas[l].view(1, 1, 1)<br>        a_bar_l = alpha_bars[l].view(1, 1, 1)<br>        <br>        # Remove predicted noise<br>        z = (1 / torch.sqrt(a_l)) * (z - ((1 - a_l) / torch.sqrt(1 - a_bar_l)) * eps_pred)<br>        <br>        # Add Langevin noise variance (except for the last step)<br>        if l &gt; 1:<br>            z = z + torch.sqrt(1 - a_l) * torch.randn_like(z)<br>            <br>    return z</pre><p>GE2E For Speaker Embedding Extraction</p><pre>import torch<br>import numpy as np<br>from resemblyzer import VoiceEncoder, preprocess_wav<br>from pathlib import Path<br><br>def extract_target_speaker_embedding(audio_path, device=&quot;cpu&quot;):<br>    &quot;&quot;&quot;<br>    Extracts the 256-dimensional GE2E speaker embedding from a target audio file.<br>    &quot;&quot;&quot;<br>    # 1. Initialize the pre-trained GE2E Voice Encoder<br>    # This automatically downloads the pre-trained weights if not present<br>    encoder = VoiceEncoder(device=device)<br>    <br>    # 2. Preprocess the audio<br>    # GE2E expects a specific sample rate (16kHz), normalized volume, and trimmed silence.<br>    # preprocess_wav handles all of this automatically.<br>    fpath = Path(audio_path)<br>    wav = preprocess_wav(fpath)<br>    <br>    # 3. Extract the embedding<br>    # Passes the audio through the LSTM-based GE2E network<br>    # Output is a highly condensed (256,) numpy array representing the voice identity<br>    embed = encoder.embed_utterance(wav)<br>    <br>    # 4. Convert to PyTorch tensor to feed into our Flow Matching model<br>    embed_tensor = torch.tensor(embed, dtype=torch.float32).unsqueeze(0).to(device) # Shape: (1, 256)<br>    <br>    return embed_tensor<br><br># ==========================================<br># Example Usage in the Inference Pipeline<br># ==========================================<br>if __name__ == &quot;__main__&quot;:<br>    device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>    <br>    # Target speaker file (e.g., 5 seconds of Speaker B talking)<br>    target_audio_file = &quot;./data/target_speaker_B.wav&quot;<br>    <br>    print(&quot;Extracting GE2E Embedding...&quot;)<br>    s_target = extract_target_speaker_embedding(target_audio_file, device=device)<br>    <br>    print(f&quot;Extraction Complete! Target Embedding Shape: {s_target.shape}&quot;) <br>    # Output: torch.Size([1, 256])<br>    <br>    # Now, s_target is perfectly formatted to be passed into the Flow Matching inference function:<br>    # z_converted = flow_matching_inference(model, z_source, s_target, p_source)</pre><blockquote>With This I Conclude the Implementation of the Research Paper<br><a href="https://arxiv.org/pdf/2509.08379v1">LatentVoiceGrad: Nonparallel Voice Conversion with Latent Diffusion/Flow-Matching Models</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c739f7e0483e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Fused ResNet and EfficientNet to Break 83% on CIFAR-100 (With <2M Trainable Params)]]></title>
            <link>https://medium.com/@lokaranjanpanda/i-fused-resnet-and-efficientnet-to-break-83-on-cifar-100-with-2m-trainable-params-918b8260bb9d?source=rss-531ebf6bde5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/918b8260bb9d</guid>
            <dc:creator><![CDATA[Lokaranjanpanda]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 17:51:13 GMT</pubDate>
            <atom:updated>2025-12-18T17:51:13.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ox8foMmOJRAfWFeZEDYjvQ.png" /></figure><p><em>Why train one brain when you can make two different brains talk to each other? A deep dive into the “SideCar” Heterogeneous Mixture of Experts.</em></p><p>In modern Deep Learning, we usually pick a lane. You either choose a <strong>ResNet</strong> for its structural understanding, an <strong>EfficientNet</strong> for its texture bias and efficiency, or a <strong>Vision Transformer (ViT)</strong> if you have a massive compute budget. We pick one backbone, freeze it, add a classifier, and hope for the best.</p><p>But what if we didn’t have to choose?</p><p>What if we could take a <strong>ResNet50</strong> (the “Driver”) and strap an <strong>EfficientNet</strong> (the “Consultant”) to its side, forcing them to exchange information at every layer?</p><p>I spent the last week building exactly this: a <strong>Heterogeneous SideCar Architecture</strong>. My goal was simple but ambitious: <strong>Smash the 80% accuracy barrier on CIFAR-100 without training a massive model from scratch.</strong></p><p>Here is the story of how I built it, the three phases of experimentation, and how I eventually beat the baseline by reaching <strong>83% Test Accuracy</strong> in just 5 epochs.</p><h3>The Architecture: The “SideCar” Pattern</h3><p>The core concept is simple. Most ensemble models vote at the very end (Late Fusion). This is inefficient because the models can’t correct each other’s mistakes <em>during</em> the process. If ResNet gets confused by a texture in Layer 2, that error cascades all the way to the end.</p><p>My solution is <strong>Intermediate Fusion</strong>. I built a pipeline with three components:</p><ol><li><strong>The Driver (ResNet50):</strong> The primary backbone. It processes the image normally.</li><li><strong>The Consultant (EfficientNet-B0):</strong> A frozen feature extractor running in parallel.</li><li><strong>The SideCars (Adapters):</strong> Specialized neural bridges that sit between the layers. They take features from the Consultant, align them, and inject them into the Driver.</li></ol><p><em>The crucial detail:</em> The backbones are (mostly) frozen. We are only training the SideCars. This keeps the trainable parameter count under 2 million, allowing for lightning-fast training.</p><h3>Phase 1: The “Volume Mixer” (Squeeze-and-Excitation)</h3><p>My first attempt was the simplest possible interaction. I used a <strong>Squeeze-and-Excitation (SE)</strong> block inside the SideCar.</p><p>The Intuition:</p><p>Think of the SE-Block as a “Volume Knob.” The SideCar takes the Consultant’s features and the Driver’s features, mixes them, and then decides which channels are important. If EfficientNet sees a useful texture, the SE block turns up the volume on those channels before injecting them into ResNet.</p><p><strong>The Result:</strong></p><ul><li><strong>Top-1 Accuracy:</strong> 78.34%</li><li><strong>Top-5 Accuracy:</strong> 95.87%</li></ul><p>The Verdict:</p><p>It worked. For context, a standard ResNet50 trained from scratch usually plateaus around 75–76% on CIFAR-100 without heavy tuning. We beat the baseline immediately. However, the model was struggling with fine-grained distinctions (e.g., confusing an Otter with a Beaver), suggesting it needed a smarter way to communicate.</p><h3>Phase 2: The “Spotlight” (Cross-Attention)</h3><p>To break the plateau, I realized ResNet needed to ask specific questions. Instead of just “mixing” features, I implemented <strong>Multi-Head Cross-Attention</strong> in the deep layers.</p><p>The Intuition:</p><p>This turns the interaction into a Q&amp;A session:</p><ul><li><strong>Query (Q):</strong> ResNet asks, <em>“I see a shape at pixel (10,10). Do you have context for this?”</em></li><li><strong>Key (K) &amp; Value (V):</strong> EfficientNet replies, <em>“Yes, here is the texture map for that area.”</em></li></ul><p>This allows the Driver to “cherry-pick” exactly the information it needs from the Consultant.</p><p><strong>The Result:</strong></p><ul><li><strong>Top-1 Accuracy:</strong> 79.35% (+1.01%)</li><li><strong>Top-5 Accuracy:</strong> 96.11%</li></ul><p>We were inching closer to the 80% milestone. The model was smarter, but it was still “hesitating” on similar classes.</p><h3>Phase 3: The “Bootcamp” (Advanced Augmentation)</h3><p>At this point, I had a solid architecture (Hybrid SE + Cross-Attention), but I wanted to see how far I could push it. To stop the model from memorizing pixels and force it to learn robust concepts, I introduced a “Weighted Vest” to the training loop: <strong>Advanced Augmentation.</strong></p><p>I added two key techniques to the pipeline:</p><ol><li><strong>AutoAugment (CIFAR10 Policy):</strong> A learned policy of complex distortions (Shear, Solarize, Equalize) that prevents overfitting.</li><li><strong>Random Erasing:</strong> Randomly deleting rectangular patches of the image. This forces the ResNet to rely on the SideCar’s advice when its own features are occluded.</li></ol><p><strong>The Logic:</strong> If I delete the “Wheel” from a Car image, ResNet panics. It <em>must</em> ask EfficientNet via the SideCar: <em>“I can’t see the wheel, what else do you see?”</em> EfficientNet replies: <em>“I see metal texture and windows.”</em></p><p><strong>The Final Result (The Breakthrough):</strong></p><p>Plaintext</p><pre>Epoch 1: 74.28%<br>Epoch 2: 76.75%<br>Epoch 3: 79.95%<br>Epoch 4: 81.15% (Broke the 80% Barrier)<br>Epoch 5: 82.81%</pre><p>By Epoch 5, the model hit <strong>82.81% Test Accuracy</strong>. We didn’t just break the 80% barrier; we smashed it. We are now competing with significantly larger models while using a fraction of the compute.</p><h3>The Code: How to Build a SideCar</h3><p>Here is the PyTorch implementation of the <strong>Cross-Attention SideCar</strong>, the engine behind this performance.</p><p>Python</p><pre>class CrossAttention_SideCar(nn.Module):<br>    def __init__(self, driver_channels, consultant_channels, expansion=4, num_heads=8):<br>        super().__init__()<br>        self.mid_dim = driver_channels // expansion<br>        <br>        # Projections<br>        self.to_q = nn.Conv2d(driver_channels, self.mid_dim, 1)<br>        self.to_k = nn.Conv2d(consultant_channels, self.mid_dim, 1)<br>        self.to_v = nn.Conv2d(consultant_channels, self.mid_dim, 1)<br>        <br>        # The Brain: Multi-Head Attention<br>        self.mha = nn.MultiheadAttention(embed_dim=self.mid_dim, num_heads=num_heads, batch_first=True)<br>        <br>        # Zero-Init Injection (Safety Valve)<br>        self.inject = nn.Conv2d(self.mid_dim, driver_channels, 1)<br>        nn.init.zeros_(self.inject.weight)<br>        nn.init.zeros_(self.inject.bias)</pre><pre>    def forward(self, d_x, c_x):<br>        B, C, H, W = d_x.shape<br>        <br>        # 1. Align Consultant Spatial Dimensions<br>        if d_x.shape[-2:] != c_x.shape[-2:]:<br>            c_x = F.interpolate(c_x, size=(H, W), mode=&#39;bilinear&#39;, align_corners=False)<br>        <br>        # 2. Prepare Q, K, V<br>        q = self.to_q(d_x).flatten(2).transpose(1, 2)<br>        k = self.to_k(c_x).flatten(2).transpose(1, 2)<br>        v = self.to_v(c_x).flatten(2).transpose(1, 2)<br>        <br>        # 3. Cross-Attention<br>        attn, _ = self.mha(query=q, key=k, value=v)<br>        attn = attn.transpose(1, 2).view(B, self.mid_dim, H, W)<br>        <br>        # 4. Inject<br>        return d_x + self.inject(attn)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=918b8260bb9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing an RL-Guided Diffusion Pipeline for Drug Discovery.]]></title>
            <link>https://medium.com/@lokaranjanpanda/designing-an-rl-guided-diffusion-pipeline-for-drug-discovery-8fcafd9f7b7c?source=rss-531ebf6bde5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fcafd9f7b7c</guid>
            <category><![CDATA[drug-discovery]]></category>
            <dc:creator><![CDATA[Lokaranjanpanda]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 05:31:32 GMT</pubDate>
            <atom:updated>2025-12-11T05:31:32.848Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing an RL-Guided Diffusion Pipeline for Drug Discovery.</p><p>A policy(GNN) + MCTS controller guides a conditional equivariant diffusion generator to propose molecules.Candidates are evaluated cheaply by surrogate binding and ADMET predictors.Top candidates are validated with FDA pipeline(fold- Dock Affnity) and High Quality ADMET checks.FDA results are used to active learning to refine surrogates and to train the policy(via MCTS targets + RL),</p><p>Repeat until a pareto front of druglike candidates is obtained .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*8zLYvsMyqjmmEIJVmN4EtQ.png" /></figure><p><strong>3. Components — detailed description</strong></p><p><strong>3.1 Policy network (actor)</strong></p><p><strong>Type:</strong> Graph Neural Network (recommended: EGNN / GAT + global pooling)<br> <strong>Input:</strong> current molecule graph (nodes = atoms, edges = bonds), optional pocket embedding (vector)<br> <strong>Output(s):</strong></p><ul><li>P(a | s) — categorical distribution over <strong>actions</strong> (see action space below)</li><li>V(s) — scalar value estimate (critic head)<br> <strong>Architecture details:</strong></li><li>Atom features: one-hot atom type, formal charge, aromaticity, hybridization, H-count, ring flags (dim ≈ 40)</li><li>Bond features: bond type, conjugation, ring flag (dim ≈ 8)</li><li>3 GNN blocks (EGNN / GIN / GAT) each with 256 hidden units, layer-norm, SiLU activations</li><li>Global pooling (attention or sum) → MLP(256→128→action_logits) and MLP(256→64→value)<br> <strong>Regularization:</strong> dropout 0.1, entropy bonus in RL to maintain exploration.</li></ul><p><strong>3.2 Action space (discrete)</strong></p><p>Design to be small &amp; chemically meaningful:</p><ul><li>AddFragment(fragment_id, attach_atom) — fragment library size F (e.g. 200 common fragments).</li><li>RemoveSubgraph(atom_id) — remove small substituent.</li><li>MutateAtom(atom_id, new_atom) — change element/hybrid.</li><li>ChangeBond(atom_i, atom_j, bond_type)</li><li>RefineLatent(z_delta) — continuous action (optional) where policy outputs a small vector to perturb diffusion latent (requires mapping to diffusion).</li><li>Commit — stop generation, return molecule for evaluation.</li></ul><p><strong>Masking:</strong> invalid actions masked by chemistry rules (valence, explicit valence checks).</p><p><strong>3.3 Diffusion generator (EDM / equivariant 3D diffusion)</strong></p><p><strong>Role:</strong> conditional molecule generator that produces chemically valid 3D molecule (coordinates + atom types + bonding) given:</p><ul><li>policy action (conditioning signal)</li><li>optional pocket context (3D pocket grid or embedding)</li></ul><p><strong>Recommended model:</strong> GeoDiff / EDM with equivariance (E(n)-equivariant)<br> <strong>Inputs:</strong> noise tensor z, step t, conditioning vector (action embedding, pocket embedding)<br> <strong>Outputs:</strong> denoised 3D structure + atom types (or SMILES via paired decoder)<br> <strong>Architecture:</strong> U-Net style denoiser with message-passing equivariant layers; hidden dim 256; 10–20 diffusion steps for training (use DDPM or DDIM for sampling efficiency).<br> <strong>Conditioning methods:</strong> classifier-free guidance (concatenate or cross-attend action/pocket embeddings) and/or latent shifts.</p><p><strong>3.4 Surrogate binding predictor (fast)</strong></p><p><strong>Type:</strong> Graph + pocket encoder GNN (2D or 3D) → interaction module → scalar binding score<br> <strong>Input:</strong> candidate mol (graph or 3D), pocket embedding or pocket graph<br> <strong>Output:</strong> predicted docking score / pKd (real) and uncertainty (ensemble variance)<br> <strong>Model:</strong> 3-layer GNN + cross-attention; trained on PDBbind + docking labels (or pretrain on PDBbind then fine-tune on target docking).<br> <strong>Latency:</strong> target &lt; 0.05 s per molecule on GPU for batch.</p><p><strong>3.5 ADMET ensemble</strong></p><p><strong>Models:</strong> separate predictors for each property (hERG, Ames, Caco-2, logP, solubility, clearance)<br> <strong>Architecture:</strong> small GNN or fingerprint → MLP regressors/classifiers; ensemble of 3 models to estimate uncertainty.<br> <strong>Output:</strong> probabilities / predicted values + uncertainty.</p><p><strong>3.6 Expensive evaluator: FDA (Fold → Dock → Affinity)</strong></p><p><strong>Steps:</strong></p><ol><li><strong>Fold:</strong> ColabFold / AlphaFold2 (for novel proteins) or fetch AlphaFoldDB if available. Produces relaxed protein structure (OpenMM Amber relaxation).</li></ol><ul><li>Cost: ~500–1000 sec per protein (optimizations: use AlphaFold DB or reduced recycles).</li></ul><ol><li><strong>Dock:</strong> DiffDock (fast, ML docking) → sample 10 poses; optionally re-score top poses with AutoDock Vina / GNINA for classical scoring.</li></ol><ul><li>Cost: DiffDock ~1–10 sec/complex (GPU), Vina ~10–60 sec/complex (CPU).</li></ul><ol><li><strong>Affinity:</strong> high-accuracy GNN that takes the docked complex → predicted affinity (or run MD + MM-GBSA for top candidates if compute allows).</li><li><strong>High-quality ADMET:</strong> run more costly ADMET predictors or wet-lab plan.</li></ol><p><strong>Output:</strong> true binding score label (for training surrogates), pose(s), reliability metrics.</p><p><strong>4. Data &amp; datasets</strong></p><ul><li><strong>Pretrain generator:</strong> ZINC 250k or ZINC15; ChEMBL for known actives.</li><li><strong>Pretrain surrogates:</strong> PDBbind v2016 + PDB complexes; augment with docking labels (Vina / DiffDock) to train f_bind_fast.</li><li><strong>ADMET training:</strong> pkCSM / ADMET datasets; ChEMBL metadata for bioactivity.</li><li><strong>Active learning buffer:</strong> start empty; fill with FDA-evaluated (mol, pocket, docking_score, ADMET_labels) pairs.</li></ul><p><strong>5. Training &amp; online loop — full algorithm</strong></p><p><strong>5.1 Initialization (offline)</strong></p><ol><li>Pretrain diffusion generator G_diff on large molecule corpus for validity &amp; diversity.</li><li>Pretrain policy encoder to predict likelihood of fragment additions via behavioral cloning on known synthesis steps (optional).</li><li>Train f_bind_fast on PDBbind/docking labels; train ADMET ensemble.</li><li>Initialize replay buffer R = ∅.</li><li>Set MCTS params: k = 10 expansions per node, simulations = 200 per episode, c_puct = 1.25, topK_FDA = 10 per episode.</li></ol><p><strong>5.2 Per-episode loop (online)</strong></p><p>Repeat for N_episodes:</p><ol><li><strong>Start MCTS</strong> at root state s0 (empty or seed scaffold + pocket embedding).</li><li><strong>Run N_simulations MCTS simulations</strong>:</li></ol><ul><li>Selection (PUCT): use Q + P_policy prior from policy net.</li><li>Expansion: expand top-k actions from policy (k = 10).</li><li>Leaf evaluation: use f_bind_fast + ADMET ensemble to compute value V_surrogate and uncertainty.</li><li>Backpropagate V_surrogate (optionally combine with uncertainty penalty).</li></ul><ol><li>After simulations, compute π_MCTS (visit count distribution) at root.</li><li><strong>Train policy</strong>: minimize cross-entropy CE(P_policy, π_MCTS) + value loss MSE(V_policy, V_return) (where V_return uses surrogate or true returns).</li><li><strong>Select top candidate set</strong> from MCTS (by visit counts / Q scores) — choose K = topK_FDA molecules.</li><li><strong>Evaluate topK with FDA</strong> (expensive): run fold, dock, high-quality affinity, and high-quality ADMET.</li><li><strong>Add (mol, pocket, FDA_labels)</strong> to replay buffer R.</li><li><strong>Update surrogates</strong>: every R_retrain_interval episodes, fine-tune f_bind_fast and ADMET models on R.</li><li><strong>Policy RL fine-tune (optional):</strong> use PPO with returns from FDA (or corrected surrogate returns) for policy gradient updates.</li><li><strong>Logging &amp; archive</strong>: store Pareto front (binding vs ADMET), cache scores, and back up models.</li></ol><p>Stop when you have N_final candidates meeting thresholds.</p><p><strong>6. Losses &amp; reward design</strong></p><p><strong>6.1 Composite scalar reward (for RL)</strong></p><p>Let:</p><ul><li>S_bind = normalized binding score (higher better)</li><li>S_admet_j = normalized ADMET property (higher = better)</li><li>S_synth = synthesizability score (higher = easier)</li><li>Penalty = heavy constraint penalties for violating hard constraints</li></ul><p>Option A — weighted scalar:</p><p>Option B — constrained Lagrangian (recommended):</p><p>Use Lagrangian loss:</p><p>Update λ_j by dual ascent.</p><p><strong>6.2 Policy loss (MCTS supervision)</strong></p><ul><li>CE = cross-entropy to match MCTS visit distribution</li><li>V_return = surrogate or FDA return (bootstrap)</li><li>H = entropy regularizer</li></ul><p><strong>6.3 Surrogate loss</strong></p><p>MSE on predicted vs FDA labels plus aleatoric uncertainty term:</p><p><strong>7. MCTS details &amp; hyperparameters</strong></p><ul><li>k = 10 children per expansion (as you requested)</li><li>simulations = 200 (start), scale to 500 for more compute</li><li>c_puct = 1.25 (tune in [0.5, 2.0])</li><li>PUCT formula: argmax_a Q(s,a) + c_puct * P_policy(a) * sqrt(N_parent) / (1+N_child)</li><li>Virtual loss for parallel expansion if running multi-worker</li><li>Expansion policy: sample top-k actions by policy probability and include masked invalid actions.</li></ul><p><strong>8. Active learning &amp; surrogate retraining</strong></p><ul><li><strong>Selection heuristics for FDA labeling:</strong> choose candidates with high surrogate score <em>and</em> high surrogate uncertainty (UCB ranking) to maximize informativeness.</li><li><strong>Retrain frequency:</strong> retrain surrogate after every M = 100 FDA labels or when surrogate calibration degrades (R² &lt; 0.6 w.r.t new FDA labels).</li><li><strong>Caching:</strong> store canonical SMILES hash → surrogate &amp; FDA labels to avoid duplicate evaluation.</li></ul><p><strong>9. Evaluation metrics (what to monitor)</strong></p><ul><li><strong>Surrogate quality:</strong> R², Pearson r, RMSE vs FDA labels (target R² &gt; 0.6)</li><li><strong>Policy improvement:</strong> mean reward per episode, % candidates passing ADMET thresholds, average binding score (FDA) of topK</li><li><strong>Diversity / novelty:</strong> internal pairwise Tanimoto distance, novelty fraction vs training set (&lt; 0.4 similarity)</li><li><strong>Synthesizability:</strong> SCScore distribution (target &lt; 3)</li><li><strong>Compute &amp; cost:</strong> FDA calls per candidate, average time per episode, GPU hours.</li></ul><p><strong>10. Practical engineering &amp; compute estimates</strong></p><ul><li><strong>Minimum hardware:</strong> 1 GPU (NVIDIA A100 / 4090) for diffusion &amp; DiffDock; 8 CPU cores for Vina; 512 GB disk.</li><li><strong>Per-episode compute (ballpark):</strong></li><li>MCTS sims (surrogate evals): 200 sims × 1000 surrogate evals = cheap (minutes on GPU).</li><li>FDA evals: topK = 10 × (DiffDock 10s + (Vina 30s)) ≈ 400s ≈ 7 minutes (per episode).</li><li>AlphaFold folding (if required per protein): ~500s — do once per protein and cache.</li><li><strong>Storage:</strong> cache molecules &amp; results (100k candidates) → ~10–50 GB.</li></ul><p><strong>11. Reproducibility &amp; checkpoints</strong></p><ul><li>Save model checkpoints every epoch and the replay buffer snapshot.</li><li>Log with MLFlow/WandB: metrics, Pareto frontier, top candidates, surrogate calibration plots.</li><li>Provide random seeds and deterministic batching for debug runs.</li></ul><p><strong>12. Safety, limitations &amp; caveats</strong></p><ul><li>Surrogates have bias — active learning needed to correct drift.</li><li>FDA folding is expensive — avoid repeating for same protein.</li><li>This pipeline accelerates discovery <em>but does not replace</em> wet-lab validation: synthesis, in-vitro, in-vivo tests remain essential.</li></ul><p><strong>13. Example hyperparameter defaults (starting point)</strong></p><p>policy GNN: EGNN, hidden=256, layers=3</p><p>diffusion steps (train): 1000, sampling steps (inference): 50 (DDIM)</p><p>MCTS: k=10, sims=200, c_puct=1.25</p><p>topK_FDA per episode = 10</p><p>surrogate retrain interval = 100 FDA labels</p><p>batch sizes: policy train 256, surrogate fine-tune 1024</p><p>learning rates: policy 3e-4, value 1e-4, surrogates 1e-4</p><p>PPO (if used): clip=0.2, epochs=4, entropy_coef=0.01</p><p><strong>14. Minimal runnable pseudocode (skeleton)</strong></p><p># high-level skeleton (not full code)</p><p>for episode in range(N_episodes):</p><p>root = Node(state=seed_scaffold, pocket_embed)</p><p>for sim in range(N_simulations):</p><p>node, path = select(root, policy, c_puct)</p><p>actions = policy.topk_actions(node.state, k=10)</p><p>node.expand(actions)</p><p>leaf = node.random_unvisited_child()</p><p>mol = decode_partial_via_diffusion(leaf.state, policy_condition)</p><p>value = surrogate_eval(mol, pocket) # f_bind_fast + ADMET ensemble</p><p>leaf.backpropagate(value)</p><p>pi_mcts = compute_visit_distribution(root)</p><p>train_policy_on(root.state, pi_mcts, root.value)</p><p>candidates = select_top_k(root, K=topK_FDA)</p><p>fda_results = run_FDA_and_admet(candidates, pocket) # expensive</p><p>replay.append(candidates, fda_results)</p><p>if len(replay) &gt;= retrain_threshold: retrain_surrogates(replay)</p><p>if episode % ppo_interval == 0: ppo_update(policy, replay)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fcafd9f7b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>