Okay, let's add the regularization term based on the distance to the pack of pretrained styles.
Here's the plan:
- Access the
pack of pretrained styles. This is likely stored as a class attribute (e.g., self.pack).
- Ensure the
pack tensor is on the same device as the styles tensor.
- Calculate the Mean Squared Error (MSE) between each generated style in the population (
styles) and every style in the pack. This will give a [P, V] tensor where P is population size and V is pack size.
- Average the MSE values along the
V dimension to get the mean distance for each generated style. This results in a [P] tensor.
- Add this
[P] tensor, scaled by a weight (which should be a hyperparameter, perhaps args.interp_weight), to the existing pop_loss.
- Handle the case where the
pack might be empty.
We need to make sure the pack tensor is available within the class context where this loss method is defined. Let's assume it's self.pack.
import torch
import math
# Assuming i2v, tts, mimi_loss, resemblyzer_loss, spectral_loss,
# args, phonemes, ref_wavs, ref_lens, venc, mimi, etc. are defined
# and self.pack is available (shape [V, 510, 1, 256])
# Assume this loss function is part of a class, e.g., a GA or optimizer class
# where 'self.pack' is accessible and is a torch.Tensor.
# @vectorized # Assuming this decorator handles multiprocessing/batching outside this function scope
class OptimizerWithPack: # Example class structure
def __init__(self, args, i2v, tts, mimi, venc, phonemes, ref_wavs, ref_lens, pack):
self.args = args
self.i2v = i2v
self.tts = tts
self.mimi = mimi
self.venc = venc
self.phonemes = phonemes
self.ref_wavs = ref_wavs
self.ref_lens = ref_lens
self.pack = pack # Assuming pack is loaded here [V, 510, 1, 256]
# ... other methods ...
# Applying the @vectorized decorator outside or defining it here
# If @vectorized manages populations, the input `pop` is the full population.
# If it manages batches within the population, this logic needs slight adjustment.
# Assuming @vectorized means `pop` is the full population [P, ...]
def loss(self, pop: torch.Tensor) -> torch.Tensor:
# pop: [P, individual_representation_dims]
# i2v(pop): [P, 510, 1, 256]
styles = self.i2v(pop.to(self.tts.device)) # => [P, 510, 1, 256]
pop_loss_list = [] # Use a list to collect losses for batches
N = max(1, self.args.batch // len(self.phonemes)) # max candidates per forward pass
# Loop over batches of styles for TTS inference
# Note: `styles` inside the loop is a *batch* of styles, not the full population
for styles_batch in [styles[i : i + N] for i in range(0, styles.shape[0], N)]:
n, _, _, _ = styles_batch.shape # n is the batch size (<= N)
# Repeat styles for each phoneme
styles_repeated = styles_batch.repeat_interleave(len(self.phonemes), 0) # => [n * len(phonemes), 510, 1, 256]
# Concatenate phonemes to match repeated styles
phonemes_repeated = self.phonemes * n # => [n * len(phonemes)]
with torch.autocast(self.tts.device.type):
syn_wavs, syn_lens = self.tts.forward_batch(styles_repeated, phonemes_repeated, speed=1)
# syn_wavs, syn_lens are for n*len(phonemes) items
# Reshape syn_wavs and syn_lens to process per-style loss
# They currently have shape [n * len(phonemes), ...]
# We need to compute loss per *original style*, not per style+phoneme combination
# Assuming mimi_loss and resemblyzer_loss compute loss per item and average/sum as needed.
# The current structure seems to imply that the loss is computed across all n*len(phonemes) pairs at once.
# Let's assume mimi_loss and resemblyzer_loss handle this internally and return [n] or a scalar that needs dividing by n
# Need to check the return shape of mimi_loss and resemblyzer_loss.
# If they return a scalar for the whole batch, we need to divide by n.
# If they return [n*len(phonemes)], we might need to average/sum per original style (n).
# The current `loss = pool + temp` suggests pool/temp are scalars or broadcastable.
# Let's assume they return a scalar sum of losses over the n*len(phonemes) items.
# Then we should divide by n to get the average loss per *original style* in the batch.
# Re-examining `pool, temp = mimi_loss(...)` and `loss = pool + temp`.
# The `n` argument passed suggests the loss functions *might* be designed to return a loss per original style (shape [n]).
# Let's assume `mimi_loss` and `resemblyzer_loss` return tensors of shape `[n]`.
# ref_wavs and ref_lens also need to be repeated to match syn_wavs
# Assuming ref_wavs/lens are scalars or single items currently. If they are [num_refs], need to repeat.
# Given the original code, it seems ref_wavs/lens are likely single items or handled internally by mimi_loss/venc.
# Let's assume the loss functions correctly handle the repeated syn_wavs/lens against ref_wavs/lens and return [n].
pool, temp = self.mimi_loss(self.mimi, self.ref_wavs, self.ref_lens, syn_wavs, syn_lens, n) # Assuming returns [n]
loss_batch = pool + temp # shape [n]
loss_batch += 1e-2 * self.resemblyzer_loss(self.venc, self.ref_wavs, self.ref_lens, syn_wavs, syn_lens, n) # Assuming returns [n]
if self.args.spectral:
# spectral_loss likely returns [n] or a scalar. Let's assume [n].
loss_batch += 1e-5 + self.spectral_loss(self.ref_wavs, syn_wavs, n) # Assuming returns [n]
# Store the loss for this batch *before* the final 1e2 scaling for the list
pop_loss_list.append(loss_batch)
# Concatenate losses from all batches. Now pop_loss is [P].
pop_loss_pre_reg = torch.cat(pop_loss_list) # Shape [P]
# Apply the final scaling (this matches the original code's last line in the loop)
pop_loss = 1e2 * pop_loss_pre_reg # Shape [P]
if self.args.interp:
# TODO: add a regularization term of distance to pack (for avoiding very OOD style tensor)
#
# the idea is to _prefer_ directions that are not OOD w.r.t. the available pretrained styles, but
# still permit some variation. so it shouldn't overwhelm the existing pop_loss
#
# pop_loss = [P]
# styles = [P, 510, 1, 256] # This is the original `styles` tensor from the start
# pack = [V, 510, 1, 256] # Assuming self.pack is this tensor
pack_on_device = self.pack.to(styles.device) # Ensure pack is on the right device
# Handle empty pack case
if pack_on_device.shape[0] > 0:
# Calculate the mean MSE between each style in 'styles' and all styles in 'pack'
# Reshape styles and pack for broadcasting
# styles: [P, 510, 1, 256] -> [P, 1, 510, 1, 256]
# pack: [V, 510, 1, 256] -> [1, V, 510, 1, 256]
styles_expanded = styles.unsqueeze(1)
pack_expanded = pack_on_device.unsqueeze(0)
# Compute squared difference: [P, V, 510, 1, 256]
squared_diff = (styles_expanded - pack_expanded)**2
# Compute MSE between each style and each pack vector by averaging over feature dims (510, 1, 256)
# Result shape: [P, V]
pairwise_mse = squared_diff.mean(dim=(2, 3, 4))
# Compute the mean MSE for each generated style across all pack vectors
# Result shape: [P]
regularization_term = pairwise_mse.mean(dim=1)
# Add regularization to the population loss.
# Use a weight hyperparameter, e.g., args.interp_weight
# Define args.interp_weight (e.g., 1e-3, needs tuning)
if hasattr(self.args, 'interp_weight'):
interp_weight = self.args.interp_weight
else:
# Default weight if not specified in args
interp_weight = 1e-3 # Choose a small default value
pop_loss = pop_loss + interp_weight * regularization_term
# else: if pack is empty, regularization_term is effectively 0, no change to pop_loss
# Return the final population loss, handling potential NaNs/Infs
return torch.nan_to_num(pop_loss, nan=math.inf)
# Example usage might look something like this (assuming OptimizerWithPack class):
# optimizer = OptimizerWithPack(...) # Initialize with args, models, pack, etc.
# population = ... # Your initial population tensor
# losses = optimizer.loss(population)