Skip to content

High-Quality Voice Cloning TTS for 600+ Languages

Python

Support training with SDPA

Han Zhua65149e000fc
diff --git a/docs/training.md b/docs/training.md
index 0323171..417d1a3 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -19,9 +19,49 @@ Key fields in training config file:
| `steps` | Total training steps | 300,000 |
| `learning_rate` | Peak learning rate | 1e-4 |
| `batch_tokens` | Tokens per batch on each GPU | 8192 |
+| `attn_implementation` | Attention backend: `"flex_attention"` or `"sdpa"` | `"flex_attention"` |
`output_dir` and `data_config` are passed via command line (see below).
+## Attention Implementation
+
+By default, training uses `flex_attention`, which requires PyTorch ≥ 2.5 and a compatible GPU (e.g. NVIDIA Ampere or newer). If your environment does not support `flex_attention`, set `attn_implementation` to `"sdpa"` in your training config. See [examples/config/train_config_finetune_sdpa.json](../examples/config/train_config_finetune_sdpa.json) for a ready-to-use SDPA config:
+
+```json
+{
+ "attn_implementation": "sdpa",
+ "max_sample_tokens": 2000,
+ "min_sample_tokens": 50,
+ "max_batch_size": 64
+}
+```
+
+`"sdpa"` uses PyTorch's built-in scaled dot-product attention and works on a wider range of hardware.
+
+The following fields only apply when `attn_implementation != "flex_attention"`:
+
+| Field | Description | Default |
+|---|---|---|
+| `max_sample_tokens` | Maximum token length per sample; longer samples are dropped | 2000 |
+| `min_sample_tokens` | Minimum token length per sample; shorter samples are dropped | 50 |
+| `max_batch_size` | Cap on the number of samples per batch | 64 |
+
+`batch_tokens` remains the primary control for memory usage — it sets the total token budget per batch. `max_batch_size` is a safety guard to prevent a batch of many short samples from creating an unusually large batch dimension.
+
+### Batching strategy
+
+The two backends use **different batching strategies**, which are selected automatically:
+
+| Backend | Batching strategy | Batch shape | Notes |
+|---|---|---|---|
+| `flex_attention` | Sequence packing | `[1, C, batch_tokens]` | Multiple samples concatenated into one long sequence; document boundaries tracked via `document_ids` |
+| `sdpa` | Length-grouped padding | `[B, C, max_len]` | Samples with similar token lengths are grouped into the same batch and padded to the local maximum length |
+
+**Why different strategies?**
+
+- With `flex_attention`, sequence packing is memory-efficient because a compact `BlockMask` (not a dense matrix) describes which tokens can attend to each other across document boundaries.
+- With `sdpa`, length-grouped padding is used instead: samples of similar token lengths are batched together and padded to the local maximum, so a lightweight `[B, 1, max_len, max_len]` boolean attention mask suffices with low overhead and minimal wasted padding.
+
## Launching Training
```bash
diff --git a/examples/README.md b/examples/README.md
index ebdf6e8..0ec793f 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -96,6 +96,8 @@ Main difference between fine-tuning config ([config/train_config_finetune.json](
To use a different pretrained checkpoint, modify `init_from_checkpoint` in the config file.
+If you encounter issues with `flex_attention` on your GPU, use [config/train_config_finetune_sdpa.json](config/train_config_finetune_sdpa.json) instead, which uses SDPA attention for broader compatibility. See [docs/training.md](../docs/training.md#attention-implementation) for details.
+
---
## Evaluation
diff --git a/examples/config/train_config_finetune.json b/examples/config/train_config_finetune.json
index 23ce16a..f80f573 100644
--- a/examples/config/train_config_finetune.json
+++ b/examples/config/train_config_finetune.json
@@ -16,7 +16,7 @@
"resume_from_checkpoint": null,
"init_from_checkpoint": "k2-fsa/OmniVoice",
- "learning_rate": 5e-5,
+ "learning_rate": 1e-5,
"weight_decay": 0.01,
"max_grad_norm": 1.0,
"steps": 5000,
diff --git a/examples/config/train_config_finetune_sdpa.json b/examples/config/train_config_finetune_sdpa.json
new file mode 100644
index 0000000..4b0a543
--- /dev/null
+++ b/examples/config/train_config_finetune_sdpa.json
@@ -0,0 +1,43 @@
+{
+ "llm_name_or_path": "Qwen/Qwen3-0.6B",
+ "audio_vocab_size": 1025,
+ "audio_mask_id": 1024,
+ "num_audio_codebook": 8,
+
+ "audio_codebook_weights": [8, 8, 6, 6, 4, 4, 2, 2],
+ "drop_cond_ratio": 0.1,
+ "prompt_ratio_range": [0.0, 0.3],
+ "mask_ratio_range": [0.0, 1.0],
+ "language_ratio": 0.8,
+ "use_pinyin_ratio": 0.0,
+ "instruct_ratio": 0.0,
+ "only_instruct_ratio": 0.0,
+
+ "resume_from_checkpoint": null,
+ "init_from_checkpoint": "k2-fsa/OmniVoice",
+
+ "learning_rate": 1e-5,
+ "weight_decay": 0.01,
+ "max_grad_norm": 1.0,
+ "steps": 5000,
+ "seed": 42,
+ "warmup_type": "ratio",
+ "warmup_ratio": 0.01,
+ "warmup_steps": 0,
+
+ "batch_tokens": 8192,
+ "gradient_accumulation_steps": 1,
+ "num_workers": 2,
+
+ "mixed_precision": "bf16",
+ "allow_tf32": true,
+ "attn_implementation": "sdpa",
+ "max_sample_tokens": 2000,
+ "min_sample_tokens": 50,
+ "max_batch_size": 64,
+
+ "logging_steps": 50,
+ "eval_steps": 500,
+ "save_steps": 500,
+ "keep_last_n_checkpoints": -1
+}
diff --git a/examples/run_finetune.sh b/examples/run_finetune.sh
index db8ee2a..55f01d9 100755
--- a/examples/run_finetune.sh
+++ b/examples/run_finetune.sh
@@ -26,6 +26,8 @@ TOKEN_DIR="data/finetune/tokens"
TOKENIZER_PATH="eustlb/higgs-audio-v2-tokenizer"
# Training config file
+# If you encounter issues with flex_attention on your GPU, use the SDPA config instead:
+# TRAIN_CONFIG="config/train_config_finetune_sdpa.json"
TRAIN_CONFIG="config/train_config_finetune.json"
# Data config file
diff --git a/omnivoice/data/batching.py b/omnivoice/data/batching.py
index 40dddb9..6f78cbf 100644
--- a/omnivoice/data/batching.py
+++ b/omnivoice/data/batching.py
@@ -22,9 +22,10 @@ variable-length audio.
Key classes:
- ``PackingIterableDataset``: Packs multiple samples into fixed-length sequences
- for training. Used by ``omnivoice.training.builder``.
+ for training. Used by ``omnivoice.training.builder`` with flex_attention.
- ``StreamLengthGroupDataset``: Groups samples by length into buckets. Used by
- data processing scripts (e.g. ``omnivoice/scripts/``).
+ data processing scripts (e.g. ``omnivoice/scripts/``) and by
+ ``omnivoice.training.builder`` when ``attn_implementation != "flex_attention"``.
"""
import bisect
@@ -38,7 +39,17 @@ from omnivoice.data.dataset import IterableDataReader, WrappedIterableDataset
class StreamLengthGroupDataset(WrappedIterableDataset):
"""A streaming dataset that groups samples by their lengths into buckets.
- Only support audio data for now."""
+
+ By default, length is measured as audio duration in seconds from a raw
+ waveform field. Pass a custom ``length_fn`` to use a different measure —
+ e.g. ``lambda s: s["length"]`` for processed training data, in which case
+ ``batch_duration`` and ``min/max_length`` should use the same units.
+
+ If ``processor`` is provided, each raw sample is processed before length
+ measurement and bucketing, and the yielded batches contain **processed**
+ samples. This allows accurate bucketing by post-processing token length
+ (used in the SDPA training path).
+ """
def __init__(
self,
@@ -50,6 +61,8 @@ class StreamLengthGroupDataset(WrappedIterableDataset):
audio_key: str = "audio",
drop_last: bool = False,
max_sample: Optional[int] = None,
+ length_fn: Optional[Any] = None,
+ processor: Optional[Any] = None,
):
self.dataset = dataset
self.batch_duration = batch_duration
@@ -59,6 +72,8 @@ class StreamLengthGroupDataset(WrappedIterableDataset):
self.audio_key = audio_key
self.drop_last = drop_last
self.max_sample = max_sample if max_sample is not None else float("inf")
+ self.length_fn = length_fn
+ self.processor = processor
self.boundaries = np.linspace(min_length, max_length, num_buckets + 1)[1:]
@@ -77,8 +92,18 @@ class StreamLengthGroupDataset(WrappedIterableDataset):
bucket_max_len = [0.0] * self.num_buckets
for sample in self.dataset:
- audio = sample[self.audio_key]
- duration = audio.size(-1) / self.dataset.sample_rate
+ if self.processor is not None:
+ try:
+ sample = self.processor(sample)
+ except Exception as e:
+ logging.warning(f"Error processing sample: {e}")
+ continue
+
+ if self.length_fn is not None:
+ duration = self.length_fn(sample)
+ else:
+ audio = sample[self.audio_key]
+ duration = audio.size(-1) / self.dataset.sample_rate
if duration < self.min_length or duration > self.max_length:
# logging.warning(f"Skipping sample with duration {duration:.2f}s")
diff --git a/omnivoice/data/collator.py b/omnivoice/data/collator.py
index 8ce5583..c1cac27 100644
--- a/omnivoice/data/collator.py
+++ b/omnivoice/data/collator.py
@@ -15,11 +15,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Data collator with packing for efficient training.
+"""Data collators for OmniVoice training.
-Packs multiple samples into a single sequence of fixed length (``batch_tokens``)
-to maximize GPU utilization, instead of padding each sample individually.
-Used by ``omnivoice.training.builder`` to create the collate function.
+Two strategies are available:
+
+- ``PackingDataCollator``: Concatenates samples into a single long sequence
+ (sequence packing). Used with flex_attention. Batch shape is ``[1, C, L]``.
+- ``PaddingDataCollator``: Pads samples to the same length and stacks them.
+ Used with SDPA/eager attention. Batch shape is ``[B, C, max_len]``.
"""
from typing import Any, Dict, List
@@ -27,6 +30,76 @@ from typing import Any, Dict, List
import torch
+class PaddingDataCollator:
+ """Pads a list of processed samples to the same length and stacks them.
+
+ Produces a standard ``[B, C, max_len]`` batch suitable for SDPA/eager
+ attention, where B is the number of samples in the batch, C is the number
+ of audio codebook layers, and max_len is the longest sequence in the batch.
+
+ A 4D boolean attention mask of shape ``[B, 1, max_len, max_len]`` is included.
+ Each query position can attend to all non-padding key positions (bidirectional),
+ matching the masked-diffusion training objective. When passed as a 4D tensor,
+ HuggingFace models use it directly without adding an additional causal mask.
+
+ No ``document_ids`` are emitted — each sample occupies its own batch row.
+ """
+
+ def __init__(self, processor, batch_tokens: int):
+ self.batch_tokens = batch_tokens
+ self.processor = processor
+
+ def __call__(self, processed_samples: List[Dict[str, Any]]) -> Dict[str, Any]:
+ pad_id = self.processor.text_tokenizer.pad_token_id
+ max_len = max(s["length"] for s in processed_samples)
+ B = len(processed_samples)
+
+ padded_input_ids = []
+ padded_labels = []
+ padded_audio_mask = []
+ padded_position_ids = []
+ # valid[b, j] = True if position j is a real (non-padding) token for sample b
+ valid = torch.zeros(B, max_len, dtype=torch.bool)
+
+ for i, s in enumerate(processed_samples):
+ length = s["length"]
+ pad = max_len - length
+
+ padded_input_ids.append(
+ torch.nn.functional.pad(s["input_ids"], (0, pad), value=pad_id)
+ ) # [C, max_len]
+ padded_labels.append(
+ torch.nn.functional.pad(s["labels"], (0, pad), value=-100)
+ ) # [C, max_len]
+ padded_audio_mask.append(
+ torch.nn.functional.pad(s["audio_mask"], (0, pad), value=False)
+ ) # [max_len]
+ padded_position_ids.append(
+ torch.nn.functional.pad(
+ torch.arange(length, dtype=torch.long), (0, pad), value=0
+ )
+ ) # [max_len]
+ valid[i, :length] = True
+
+ # Stack into [B, C, max_len] / [B, max_len]
+ input_ids = torch.stack(padded_input_ids, dim=0) # [B, C, max_len]
+ labels = torch.stack(padded_labels, dim=0) # [B, C, max_len]
+ audio_mask = torch.stack(padded_audio_mask, dim=0) # [B, max_len]
+ position_ids = torch.stack(padded_position_ids, dim=0) # [B, max_len]
+
+ # 4D bidirectional attention mask: mask[b, 0, i, j] = valid[b, j]
+ # All query positions attend to all non-padding key positions.
+ attention_mask = valid[:, None, None, :].expand(B, 1, max_len, max_len).contiguous()
+
+ return {
+ "input_ids": input_ids, # [B, C, max_len]
+ "labels": labels, # [B, C, max_len]
+ "audio_mask": audio_mask, # [B, max_len]
+ "position_ids": position_ids, # [B, max_len]
+ "attention_mask": attention_mask, # [B, 1, max_len, max_len]
+ }
+
+
class PackingDataCollator:
def __init__(self, processor, batch_tokens: int):
self.batch_tokens = batch_tokens
diff --git a/omnivoice/models/omnivoice.py b/omnivoice/models/omnivoice.py
index 717e53b..96673eb 100644
--- a/omnivoice/models/omnivoice.py
+++ b/omnivoice/models/omnivoice.py
@@ -41,7 +41,13 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
-from torch.nn.attention.flex_attention import create_block_mask
+
+try:
+ from torch.nn.attention.flex_attention import create_block_mask
+
+ _flex_attention_available = True
+except ImportError:
+ _flex_attention_available = False
from transformers import (
AutoFeatureExtractor,
AutoModel,
@@ -193,6 +199,7 @@ def _resolve_model_path(name_or_path: str) -> str:
class OmniVoice(PreTrainedModel):
_supports_flex_attn = True
_supports_flash_attn_2 = True
+ _supports_sdpa = True
config_class = OmniVoiceConfig
def __init__(self, config: OmniVoiceConfig, llm: Optional[PreTrainedModel] = None):
@@ -385,6 +392,12 @@ class OmniVoice(PreTrainedModel):
inputs_embeds = self._prepare_embed_inputs(input_ids, audio_mask)
if attention_mask is None and document_ids is not None:
+ if not _flex_attention_available:
+ raise RuntimeError(
+ "flex_attention is not available in the current environment. "
+ "If you do not need flex_attention, set "
+ '"attn_implementation": "sdpa" in your training config.'
+ )
attention_mask = create_block_mask(
_get_packed_mask(
document_ids[0].to(inputs_embeds.device),
diff --git a/omnivoice/training/builder.py b/omnivoice/training/builder.py
index 848f4b7..4af2fc7 100644
--- a/omnivoice/training/builder.py
+++ b/omnivoice/training/builder.py
@@ -22,8 +22,14 @@ from a ``TrainingConfig``. Called by ``omnivoice.cli.train`` to set up training.
Key functions:
- ``build_model_and_tokenizer()``: Loads the model and text tokenizer.
-- ``build_dataloaders()``: Builds packed train/eval data loaders
- from a data config JSON.
+- ``build_dataloaders()``: Builds train/eval data loaders from a data config JSON.
+ The batching strategy is chosen based on ``TrainingConfig.attn_implementation``:
+
+ - ``"flex_attention"``: sequence packing via ``PackingIterableDataset`` +
+ ``PackingDataCollator``. Batch shape is ``[1, C, batch_tokens]``.
+ - other (e.g. ``"sdpa"``): length-grouped padding via
+ ``StreamLengthGroupDataset`` + ``PaddingDataCollator``. Batch shape
+ is ``[B, C, max_len]`` where B ≥ 1 and max_len ≤ batch_tokens.
"""
import logging
@@ -36,8 +42,8 @@ from transformers import AutoConfig, AutoModel, AutoTokenizer
from transformers import logging as hf_logging
from transformers.trainer_utils import seed_worker
-from omnivoice.data.batching import PackingIterableDataset
-from omnivoice.data.collator import PackingDataCollator
+from omnivoice.data.batching import PackingIterableDataset, StreamLengthGroupDataset
+from omnivoice.data.collator import PackingDataCollator, PaddingDataCollator
from omnivoice.data.dataset import WebDatasetReader, prepare_data_manifests_from_json
from omnivoice.data.processor import OmniVoiceSampleProcessor
from omnivoice.models.omnivoice import OmniVoice, OmniVoiceConfig, _resolve_model_path
@@ -81,7 +87,7 @@ def build_model_and_tokenizer(
logger.info(f"Loading weights from {config.init_from_checkpoint}")
model = OmniVoice.from_pretrained(
config.init_from_checkpoint,
- attn_implementation="flex_attention",
+ attn_implementation=config.attn_implementation,
dtype=torch.float32,
train=True,
)
@@ -102,7 +108,7 @@ def build_model_and_tokenizer(
llm = AutoModel.from_pretrained(
resolved_llm,
- attn_implementation="flex_attention",
+ attn_implementation=config.attn_implementation,
dtype=torch.float32,
)
@@ -125,7 +131,15 @@ def build_model_and_tokenizer(
def build_dataloaders(
config: TrainingConfig, tokenizer: AutoTokenizer
) -> Tuple[DataLoader, DataLoader]:
- """Setup Data Pipeline: Manifests -> WDS -> Packing -> Loaders."""
+ """Setup Data Pipeline: Manifests -> WDS -> Batching -> Loaders.
+
+ Batching strategy depends on ``config.attn_implementation``:
+ - ``"flex_attention"``: sequence packing (PackingIterableDataset +
+ PackingDataCollator). All samples are concatenated into one long sequence.
+ - other (e.g. ``"sdpa"``): length-grouped padding
+ (LengthGroupedIterableDataset + PaddingDataCollator). Samples with
+ similar token lengths are batched together and padded to the same length.
+ """
logger.info("Initializing Data Readers...")
processor = OmniVoiceSampleProcessor(
@@ -146,19 +160,44 @@ def build_dataloaders(
)
raw_train_ds = WebDatasetReader(manifests=train_manifests, evaluation=False)
- train_dataset = PackingIterableDataset(raw_train_ds, processor, config.batch_tokens)
+ use_packing = config.attn_implementation == "flex_attention"
- collate_fn = PackingDataCollator(processor, config.batch_tokens)
+ if use_packing:
+ train_dataset = PackingIterableDataset(
+ raw_train_ds, processor, config.batch_tokens
+ )
+ collate_fn = PackingDataCollator(processor, config.batch_tokens)
+ else:
+ train_dataset = StreamLengthGroupDataset(
+ raw_train_ds,
+ batch_duration=config.batch_tokens,
+ min_length=config.min_sample_tokens,
+ max_length=config.max_sample_tokens,
+ max_sample=config.max_batch_size,
+ processor=processor,
+ length_fn=lambda s: s["length"],
+ )
+ collate_fn = PaddingDataCollator(processor, config.batch_tokens)
+
+ logger.info(
+ "Using %s (attn_implementation=%s)",
+ "sequence packing" if use_packing else "length-grouped padding",
+ config.attn_implementation,
+ )
init_fn = partial(
seed_worker,
num_workers=config.num_workers,
- rank=torch.distributed.get_rank() if torch.distributed.is_initialized() else 0,
+ rank=(
+ torch.distributed.get_rank()
+ if torch.distributed.is_initialized()
+ else 0
+ ),
)
train_loader = DataLoader(
train_dataset,
- batch_size=None, # Each item is a batch packed to the target batch_tokens
+ batch_size=None,
num_workers=config.num_workers,
collate_fn=collate_fn,
worker_init_fn=init_fn,
@@ -168,11 +207,26 @@ def build_dataloaders(
eval_loader = None
if dev_manifests:
- raw_dev_ds = WebDatasetReader(manifests=dev_manifests, evaluation=True)
- dev_dataset = PackingIterableDataset(raw_dev_ds, processor, config.batch_tokens)
+ raw_dev_ds = WebDatasetReader(
+ manifests=dev_manifests, evaluation=True
+ )
+ if use_packing:
+ dev_dataset = PackingIterableDataset(
+ raw_dev_ds, processor, config.batch_tokens
+ )
+ else:
+ dev_dataset = StreamLengthGroupDataset(
+ raw_dev_ds,
+ batch_duration=config.batch_tokens,
+ min_length=config.min_sample_tokens,
+ max_length=config.max_sample_tokens,
+ max_sample=config.max_batch_size,
+ processor=processor,
+ length_fn=lambda s: s["length"],
+ )
eval_loader = DataLoader(
dev_dataset,
- batch_size=None, # Each item is a batch packed to the target batch_tokens
+ batch_size=None, # Each item is already a collated batch
num_workers=1,
collate_fn=collate_fn,
pin_memory=True,
diff --git a/omnivoice/training/config.py b/omnivoice/training/config.py
index ecae725..49cd880 100644
--- a/omnivoice/training/config.py
+++ b/omnivoice/training/config.py
@@ -76,6 +76,12 @@ class TrainingConfig:
allow_tf32: bool = True
use_deepspeed: bool = False
deepspeed_config: Optional[str] = None
+ attn_implementation: str = "flex_attention"
+
+ # Length-grouped batching (only used when attn_implementation != "flex_attention")
+ max_sample_tokens: int = 2000
+ min_sample_tokens: int = 50
+ max_batch_size: int = 64
# Logging
logging_steps: int = 100