Skip to content

A TTS that fits in your CPU (and pocket)

Python

Training speed: is_causal attention, one DDP all-reduce per accumulated step (#427)

manu-lm856a41d7e53c
diff --git a/pocket_tts/modules/attention.py b/pocket_tts/modules/attention.py
index 75aeebe..265d59a 100644
--- a/pocket_tts/modules/attention.py
+++ b/pocket_tts/modules/attention.py
@@ -198,8 +198,13 @@ class StreamingMultiheadAttention(StatefulModule):
if self.num_kv_heads != self.num_heads:
k_attn = k_attn.repeat_interleave(self.num_heads // self.num_kv_heads, dim=1)
v_attn = v_attn.repeat_interleave(self.num_heads // self.num_kv_heads, dim=1)
+ # Stateless and no context window: plain causal attention. is_causal with no explicit
+ # mask lets SDPA pick the flash kernel (a mask forces the slower mem-efficient one).
+ is_causal = False
if attn_mask is not None:
pass # precomputed by the caller (stateless path)
+ elif state is None and self.context is None:
+ is_causal = True
elif state is None:
attn_mask = _cached_causal_mask(t, self.context, q.device)
else:
@@ -207,7 +212,9 @@ class StreamingMultiheadAttention(StatefulModule):
1, -1
)
attn_mask = _build_attention_mask(pos_q, pos_k, self.context)
- x = F.scaled_dot_product_attention(q, k_attn, v_attn, attn_mask, dropout_p=0.0)
+ x = F.scaled_dot_product_attention(
+ q, k_attn, v_attn, attn_mask, dropout_p=0.0, is_causal=is_causal
+ )
x = x.transpose(1, 2)
# Reshape from (b, t, h, d) to (b, t, h*d)
b, t, h, d = x.shape
diff --git a/pocket_tts/modules/transformer.py b/pocket_tts/modules/transformer.py
index 0bc6106..ae8a67d 100644
--- a/pocket_tts/modules/transformer.py
+++ b/pocket_tts/modules/transformer.py
@@ -121,9 +121,9 @@ class StreamingTransformer(nn.Module):
def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
attn_mask = None
- if model_state is None:
+ if model_state is None and self.context is not None:
# Stateless (training) path: one shared mask for all layers, built
- # outside any compiled region.
+ # outside any compiled region. Without a context window the layers use is_causal.
attn_mask = _cached_causal_mask(x.shape[1], self.context, x.device)
for layer in self.layers:
x = layer(x, model_state, attn_mask=attn_mask)
diff --git a/tests/test_model_options.py b/tests/test_model_options.py
index fbf1ec3..2dbe053 100644
--- a/tests/test_model_options.py
+++ b/tests/test_model_options.py
@@ -3,6 +3,7 @@
from pathlib import Path
from typing import TypeVar
+import pytest
import safetensors.torch
import torch
@@ -11,6 +12,7 @@ from pocket_tts.models.mimi import build_mimi
from pocket_tts.modules.attention import StreamingMultiheadAttention
from pocket_tts.modules.rope import RotaryEmbedding
from pocket_tts.modules.stateful_module import StatefulModule, increment_steps, init_states
+from pocket_tts.modules.transformer import StreamingTransformer
from pocket_tts.utils.config import CONFIGS_DIR, FlowLMConfig, load_config
from pocket_tts.utils.weights_loading import get_mimi_state_dict
@@ -168,3 +170,31 @@ def test_pointwise_head_is_lsd_one_step_without_time_conditions():
v.zero_()
lsd.load_state_dict({**state, **pointwise.state_dict()}, strict=True)
assert torch.equal(sample_latents(pointwise), sample_latents(lsd))
+
+
[email protected]("device", ["cpu", "cuda"])
+def test_is_causal_matches_explicit_mask(device: str):
+ """Stateless forward without a context window (is_causal, flash-eligible) against the explicit
+ causal mask (a window covering the sequence): same outputs and gradients."""
+ if device == "cuda" and not torch.cuda.is_available():
+ pytest.skip("no GPU")
+ x = torch.randn(2, 40, 32, device=device)
+ for dtype, tol in [(torch.float32, 1e-5)] + [(torch.bfloat16, 0.05)] * (device == "cuda"):
+ results = []
+ for context in (None, 40):
+ torch.manual_seed(0)
+ m = StreamingTransformer(
+ d_model=32, num_heads=4, num_layers=2, dim_feedforward=64, context=context
+ ).to(device)
+ with torch.autocast(device, dtype=dtype, enabled=dtype != torch.float32):
+ if dtype == torch.bfloat16 and context is None: # raises unless flash runs it
+ with torch.nn.attention.sdpa_kernel(
+ torch.nn.attention.SDPBackend.FLASH_ATTENTION
+ ):
+ out = m(x, None)
+ else:
+ out = m(x, None)
+ out.float().square().mean().backward()
+ results.append([out.float()] + [p.grad for p in m.parameters()])
+ for a, b in zip(*results):
+ assert (a - b).abs().max() <= tol * b.abs().max(), (dtype, (a - b).abs().max())
diff --git a/training/train.py b/training/train.py
index 8c9481e..736eb4a 100644
--- a/training/train.py
+++ b/training/train.py
@@ -247,6 +247,10 @@ def main(config_path: str):
group["lr"] = lr * group.get("lr_scale", 1.0)
optimizer.zero_grad()
for micro in range(args.grad_accum_steps):
+ # Under DDP, all-reduce only on the last micro-batch. DDP decides at forward time
+ # whether the backward synchronizes, so the flag (what DDP.no_sync sets) goes first.
+ if isinstance(run.wrapped, DDP):
+ run.wrapped.require_backward_grad_sync = micro == args.grad_accum_steps - 1
if cache is not None:
(
latents,
@@ -286,14 +290,7 @@ def main(config_path: str):
metrics.update(refl_stats)
if reward_loss is not None:
loss = loss + reward_loss
- # Under DDP, allreduce only on the last micro-batch.
- last_micro = micro == args.grad_accum_steps - 1
- scaled = loss / args.grad_accum_steps
- if not last_micro and isinstance(run.wrapped, DDP):
- with run.wrapped.no_sync():
- scaled.backward()
- else:
- scaled.backward()
+ (loss / args.grad_accum_steps).backward()
if refl_rewards is not None and run.world_size > 1:
average_grads([p for p in model.parameters() if p.requires_grad])
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.optim.max_norm)