To perform text-conditioned audio synthesis (similar to VALL-E), use the SemanticTransformer and SemanticTransformerTrainer.
- Initialize
HubertWithKmeans: Load a pre-trained Hubert model and its corresponding K-means quantization file. - Configure
SemanticTransformer: Set has_condition = True. You can use cond_as_self_attn_prefix = True to condition via self-attention prefix instead of cross-attention. - Prepare Dataset: Extend
torch.utils.data.Dataset to return a tuple containing a string (the text caption) and an audio tensor. The framework automatically routes these to the transformer. - Train: Use
SemanticTransformerTrainer to manage the training loop. - Generate: Use
trainer.generate(text=[...]) to synthesize audio from text prompts.
import torch
from audiolm_pytorch import HubertWithKmeans, SemanticTransformer, SemanticTransformerTrainer
from torch.utils.data import Dataset
# 1. Setup Wav2Vec/Hubert
wav2vec = HubertWithKmeans(
checkpoint_path = './hubert/hubert_base_ls960.pt',
kmeans_path = './hubert/hubert_base_ls960_L9_km500.bin'
)
# 2. Setup Semantic Transformer
semantic_transformer = SemanticTransformer(
num_semantic_tokens = 500,
dim = 1024,
depth = 6,
has_condition = True,
cond_as_self_attn_prefix = True
).cuda()
# 3. Define Dataset (must return caption and audio)
class MockTextAudioDataset(Dataset):
def __init__(self, length = 100, audio_length = 320 * 32):
super().__init__()
self.audio_length = audio_length
self.len = length
def __len__(self):
return self.len
def __getitem__(self, idx):
mock_audio = torch.randn(self.audio_length)
mock_caption = 'audio caption'
return mock_caption, mock_audio
dataset = MockTextAudioDataset()
# 4. Train
trainer = SemanticTransformerTrainer(
transformer = semantic_transformer,
wav2vec = wav2vec,
dataset = dataset,
batch_size = 4,
grad_accum_every = 8,
data_max_length = 320 * 32,
num_train_steps = 1_000_000
)
trainer.train()
# 5. Generate
sample = trainer.generate(text = ['sound of rain drops on the rooftops'], batch_size = 1, max_length = 2)