A TTS that fits in your CPU (and pocket)
Python
Drifting sampler head: training recipe and english_drifting_26-09 (#329)
manu-lma11539ee73ad
diff --git a/README.md b/README.mdindex 2ff6097..d22e666 100644--- a/README.md+++ b/README.md@@ -54,6 +54,7 @@ pocket-tts generate```Modify the voice with `--voice` and the text with `--text`. We provide a small catalog of voices.Choose a pretrained language model with `--language` when running `generate`, `export-voice`, or `serve` (default: `english`). Non-english languages have also biggers 24 layers variants that are higher quality but slower. You can select them by using for example `--language italian_24l`.+`--language english_drifting_26-09` selects an English model whose sampler head was trained with drifting instead of LSD (see [training/README.md](training/README.md) for the recipe).The `--config` option accepts a local YAML path, an `https://` URL, or an `hf://` path (e.g. `hf://<repo_id>/<path>[@revision]`) for custom weights.You can take a look at [this page](https://huggingface.co/kyutai/tts-voices) which details the licensesdiff --git a/docs/API Reference/python-api.md b/docs/API Reference/python-api.mdindex 782752c..6982e86 100644--- a/docs/API Reference/python-api.md+++ b/docs/API Reference/python-api.md@@ -42,7 +42,7 @@ The main class for text-to-speech generation.Load and return a TTSModel instance with pre-trained weights.**Parameters:**-- `language` (str | None): Name of built-in language config to load. Supported values: `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`. If both `language` and `config` are omitted, defaults to `"english"`, which is the same model as `"english_2026-09"`. The "24l" variants are larger models that are not distilled yet and are here only as a preview.+- `language` (str | None): Name of built-in language config to load. Supported values: `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english_drifting_26-09"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`. If both `language` and `config` are omitted, defaults to `"english"`, which is the same model as `"english_2026-09"`. The "24l" variants are larger models that are not distilled yet and are here only as a preview.- `config` (str | None): Path to model config YAML file. Incompatible with `language`.- `temp` (float | None): Sampling temperature for generation. `None` uses the model's recommended default from its config file (`default_temperature`, 0.3).- `sampler_decode_steps` (int): Number of generation steps (default: 1)diff --git a/docs/CLI Commands/export_voice.md b/docs/CLI Commands/export_voice.mdindex 0e5eeb0..be83d41 100644--- a/docs/CLI Commands/export_voice.md+++ b/docs/CLI Commands/export_voice.md@@ -24,7 +24,7 @@ Only the first 30 seconds of the audio file will be processed.### Options- `--quiet`: Do not print any output except errors.-- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.+- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_drifting_26-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.- `--config`: Model config yaml path — a local path, an `https://` URL, or an `hf://` path. Incompatible with `--language`.## Examplesdiff --git a/docs/CLI Commands/generate.md b/docs/CLI Commands/generate.mdindex 1aac8bc..aef03df 100644--- a/docs/CLI Commands/generate.md+++ b/docs/CLI Commands/generate.md@@ -19,7 +19,7 @@ This will generate a WAV file `./tts_output.wav` with the default text and voice- `--text TEXT`: Text to generate (default: "Hello world! I am Kyutai Pocket TTS. I'm fast enough to run on small CPUs. I hope you'll like me.")- `--voice VOICE`: Path to audio conditioning file (voice to clone). Defaults to a built-in voice chosen from the language: `giovanni` (it) for italian, `lola` (es) for spanish, `juergen` (de) for german, `rafael` (pt) for portuguese, `estelle` (fr) for french, `alba` (en) otherwise. With `--config` or `--checkpoint`, defaults to [alba's audio file](https://huggingface.co/kyutai/tts-voices/blob/main/alba-mackenna/casual.wav) instead of the voice name, since the pre-made voices only exist for the released language models. Urls and local paths are supported.- `--output-path OUTPUT_PATH`: Output path for generated audio (default: "./tts_output.wav")-- `--language LANGUAGE`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.+- `--language LANGUAGE`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_drifting_26-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.### Generation Parametersdiff --git a/docs/CLI Commands/serve.md b/docs/CLI Commands/serve.mdindex 3533ca7..7497936 100644--- a/docs/CLI Commands/serve.md+++ b/docs/CLI Commands/serve.md@@ -17,7 +17,7 @@ This starts a server on `http://localhost:8000` with the default voice model.- `--host HOST`: Host to bind to (default: "localhost")- `--port PORT`: Port to bind to (default: 8000)- `--reload`: Enable auto-reload for development-- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.+- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_drifting_26-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.- `--config`: Path to a custom config .yaml — a local path, an `https://` URL, or an `hf://` path. Incompatible with `--language`.- `--default-voice`: Voice used by the requests that don't ask for one (default: the built-in voice of the language). It accepts anything the `generate --voice` option accepts: a built-in voice name, a local path to an audio file or to a `.safetensors` voice, an `https://` URL, or an `hf://` path. It is loaded at startup, so a voice that cannot be read fails the server immediately instead of the first request.- `--quantize`: Use int8 quantization for the model (default: False). This can reduce memory usage and increase speed, with minimal impact on audio quality.diff --git a/pocket_tts/config/english_drifting_26-09.yaml b/pocket_tts/config/english_drifting_26-09.yamlnew file mode 100644index 0000000..d153476--- /dev/null+++ b/pocket_tts/config/english_drifting_26-09.yaml@@ -0,0 +1,63 @@+# English 6-layer model with a one-step drifting sampler head, CFG-distilled (guidance 2.0 baked in)+# from a 24-layer drifting teacher. training/configs/drifting*.yaml trains this kind of model.++weights_path: hf://kyutai/pocket-tts/languages/english_drifting_26-09/model.safetensors@75cfe24e3142233bb81887fed3482e9652bb4a6e+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_drifting_26-09/model.safetensors@a5ce31f3eba7a3b0cb9c24ba2015b098f278eaae+default_temperature: 0.3++flow_lm:+ insert_bos_before_voice: true+ dtype: float32+ flow:+ depth: 6+ dim: 512+ type: drifting+ transformer:+ d_model: 1024+ hidden_scale: 4+ max_period: 10000+ num_heads: 16+ num_layers: 6+ lookup_table:+ dim: 1024+ n_bins: 4000+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-09/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214+ #weights_path: final.safetensors++mimi:+ dtype: float32+ sample_rate: 24000+ inner_dim: 32+ outer_dim: 512+ channels: 1+ frame_rate: 12.5+ seanet:+ dimension: 512+ channels: 1+ n_filters: 64+ n_residual_layers: 1+ ratios:+ - 6+ - 5+ - 4+ kernel_size: 7+ residual_kernel_size: 3+ last_kernel_size: 3+ dilation_base: 2+ pad_mode: constant+ compress: 2+ transformer:+ d_model: 512+ num_heads: 8+ num_layers: 2+ layer_scale: 0.01+ context: 250+ dim_feedforward: 2048+ input_dimension: 512+ output_dimensions:+ - 512+ quantizer:+ dimension: 32+ output_dimension: 512+ #weights_path: codec.safetensorsdiff --git a/pocket_tts/main.py b/pocket_tts/main.pyindex c703c58..b0be6e0 100644--- a/pocket_tts/main.py+++ b/pocket_tts/main.py@@ -217,7 +217,7 @@ def serve(str | None,typer.Option(help="Language for the TTS model. "- "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."+ "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_drifting_26-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."" Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09'.",show_default=False,),@@ -283,7 +283,7 @@ def generate(typer.Option(help=("Language for the TTS model. "- "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."+ "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_drifting_26-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."" Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09'. ""The '24l' variants are bigger models, ""not distilled yet and here only as preview. They're not the final "@@ -403,7 +403,7 @@ def export_voice(typer.Option(help=("Language for the TTS model. "- "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."+ "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_drifting_26-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."" Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09'. ""The '24l' variants are bigger models, ""not distilled yet and here only as preview."diff --git a/pocket_tts/models/flow_lm.py b/pocket_tts/models/flow_lm.pyindex cc328cb..6560032 100644--- a/pocket_tts/models/flow_lm.py+++ b/pocket_tts/models/flow_lm.py@@ -41,6 +41,11 @@ def lsd_decode(v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tenreturn current+def drifting_decode(v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tensor:+ """One-step head without time conditions: the sample is the head's output for the noise."""+ return v_t(x_0)++def ot_decode(v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 16) -> torch.Tensor:"""Euler integration of an optimal-transport conditional flow.@@ -161,7 +166,14 @@ class FlowLMModel(nn.Module):else:torch.nn.init.trunc_normal_(noise, mean=0.0, std=std, a=-noise_clamp, b=noise_clamp)conditioned_flow = partial(self.flow_net, transformer_out)- decode = ot_decode if self.flow_type == "flow_matching" else lsd_decode+ if self.flow_type == "lsd":+ decode = lsd_decode+ elif self.flow_type == "flow_matching":+ decode = ot_decode+ elif self.flow_type == "drifting":+ decode = drifting_decode+ else:+ raise ValueError(f"Unknown flow type: {self.flow_type}")return decode(conditioned_flow, noise, sampler_decode_steps), out_eosdef backbone(diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.pyindex 7eb7c35..89ae8ba 100644--- a/pocket_tts/models/tts_model.py+++ b/pocket_tts/models/tts_model.py@@ -303,7 +303,7 @@ class TTSModel(nn.Module):Args:language: Optional language identifier to select a predefined config. Incompatible withthe `config` argument. Available options- are `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`.+ are `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english_drifting_26-09"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`.If neither `config` nor `language` is provided, defaults to `"english", which is the same model as 'english_2026-09'`.config: A path to a custom YAML config file: a local path (e.g., `"C://pocket_tts/pocket_tts_config.yaml"`),an `https://` URL, or an `hf://` path (e.g. `"hf://<repo_id>/<path>[@revision]"`).diff --git a/pocket_tts/modules/mlp.py b/pocket_tts/modules/mlp.pyindex 8853597..ac6a640 100644--- a/pocket_tts/modules/mlp.py+++ b/pocket_tts/modules/mlp.py@@ -181,7 +181,14 @@ class SimpleMLPAdaLN(nn.Module):flow_dim = config.dimflow_depth = config.depth- num_time_conds = 1 if config.type == "flow_matching" else 2+ if config.type == "lsd":+ num_time_conds = 2+ elif config.type == "flow_matching":+ num_time_conds = 1+ elif config.type == "drifting":+ num_time_conds = 0+ else:+ raise ValueError(f"Unknown flow type: {config.type}")return cls(latent_dim, flow_dim, latent_dim, cond_dim, flow_depth, num_time_conds=num_time_conds)diff --git a/pocket_tts/utils/config.py b/pocket_tts/utils/config.pyindex d539147..2068b49 100644--- a/pocket_tts/utils/config.py+++ b/pocket_tts/utils/config.py@@ -18,8 +18,9 @@ class StrictModel(BaseModel):class FlowConfig(StrictModel):dim: intdepth: int- # "lsd" (2 time conditions, 1-step decode) or "flow_matching" (1 time- # condition, Euler integration; needs >= 16 decode steps).+ # "lsd" (2 time conditions, 1-step decode), "flow_matching" (1 time+ # condition, Euler integration; needs >= 16 decode steps) or "drifting"+ # (no time condition, the head maps noise to a sample in one step).type: str = "lsd"diff --git a/swarm-config.yaml b/swarm-config.yamlindex 18c28e5..aece9f4 100644--- a/swarm-config.yaml+++ b/swarm-config.yaml@@ -50,6 +50,25 @@ services:- "traefik.http.services.server-english.loadbalancer.server.port=80"- "traefik.http.routers.server-english.priority=100"+ # Above english: PathPrefix(`/english`) also matches /english_drifting_26-09.+ backend-english-drifting:+ image: rg.fr-par.scw.cloud/namespace-unruffled-tereshkova/pocket-tts-server:${COMMIT_SHA}+ volumes:+ - hf-cache:/root/.cache/huggingface+ command: ["serve", "--port", "80", "--host", "0.0.0.0", "--language", "english_drifting_26-09", "--quantize"]+ deploy:+ labels:+ - "traefik.enable=true"+ - "traefik.http.routers.server-english-drifting.rule=Host(`pocket-tts-api.kyutai.org`) && PathPrefix(`/english_drifting_26-09`)"+ - "traefik.http.routers.server-english-drifting.middlewares=strip-api-english-drifting"+ - "traefik.http.middlewares.strip-api-english-drifting.replacepathregex.regex=^/english_drifting_26-09/(.*)"+ - "traefik.http.middlewares.strip-api-english-drifting.replacepathregex.replacement=/$$1"+ - "traefik.http.routers.server-english-drifting.entrypoints=websecure"+ - "traefik.http.routers.server-english-drifting.tls=true"+ - "traefik.http.routers.server-english-drifting.tls.certresolver=letsencrypt"+ - "traefik.http.services.server-english-drifting.loadbalancer.server.port=80"+ - "traefik.http.routers.server-english-drifting.priority=110"+backend-german:image: rg.fr-par.scw.cloud/namespace-unruffled-tereshkova/pocket-tts-server:${COMMIT_SHA}volumes:diff --git a/training/README.md b/training/README.mdindex 1074a8e..a1aa049 100644--- a/training/README.md+++ b/training/README.md@@ -157,6 +157,8 @@ If you want to finetune from the English teacher model, we provide two more confThe two configs above will give you a teacher that you can then distil down to 6 layers.Training the model in two steps like this works better than training a 6-layer model from scratch.+`drifting.yaml` trains a 24-layer teacher whose sampler head uses drifting instead of LSD, as in `english_drifting_26-09`. Distill it with `depth_distill.yaml` and `flow.type: drifting`.+### Reproducing our resultsIf you train on 2k hours of HiFiTTS-2 and batch size 64, this is the metrics progress you should expect to see:diff --git a/training/configs/drifting.yaml b/training/configs/drifting.yamlnew file mode 100644index 0000000..b77c2c8--- /dev/null+++ b/training/configs/drifting.yaml@@ -0,0 +1,52 @@+# Train a drifting teacher from scratch. The sampler head maps+# noise to a latent in one step and is trained with a kernel drift field+# instead of LSD (training/modules/samplers.py: Drifting). The kernel+# temperature is learned, from 10 down to ~0.05 within the first few thousand+# steps; the logged `temp` metric shows where it settles.+# Keep the learning rate constant. UTMOS on LibriSpeech goes from ~3.5 at 50k+# steps to ~4.25 at 400k, and in our runs annealing the learning rate before+# that jump stopped it.+model_config: pocket_tts/config/english.yaml+model_overrides:+ flow_lm.transformer.num_layers: 24+start_from_pretrained: false++data:+ # The quickstart's 200h subset; the reference numbers need --hours 2000.+ train_jsonl: data/hifitts2_200h/train_aligned.jsonl+ valid_jsonl: data/hifitts2_200h/valid_aligned.jsonl+ max_duration_sec: 60.0+ max_voice_prompt_sec: 5.0++flow:+ type: drifting+ kwargs:+ temp: 10.0+ temp_loss_weight: 1.0+ num_neg: 64++flow_batch_multiplier: 1 # the 64 generations per position already average the noise+eos_loss_weight: 0.1+text_dropout: 0.2+voice_dropout: 0.2++optim:+ lr: 2e-4+ schedule: constant+ warmup_steps: 4000+ betas: [0.9, 0.999]+ weight_decay: 0.0 # would also decay the learned temperature+ max_norm: 3.0++run_dir: runs/drifting+# Effective batch 128 (batch_size x GPUs x grad_accum_steps); on 8 GPUs use batch_size: 16.+batch_size: 128+grad_accum_steps: 1+max_steps: 400000+stats_ema_steps: 0+ema_decay: 0.999+log_freq: 50+valid_freq: 2500+ckpt_freq: 5000+num_ckpt_keep: 3+sample_cfg_coef: 2.0diff --git a/training/modules/model.py b/training/modules/model.pyindex cc0390e..97a1ca4 100644--- a/training/modules/model.py+++ b/training/modules/model.py@@ -116,7 +116,13 @@ class TrainableTTS(nn.Module):sel_z = z_flat[mask_flat]sel_target = target_flat[mask_flat]noise = torch.randn_like(sel_target)- flow_loss, metrics, _ = self.flow.loss(partial(fl.flow_net, sel_z), noise, sel_target)+ if getattr(self.flow, "fp32_loss", False):+ with torch.autocast(device_type=latents.device.type, enabled=False):+ flow_loss, metrics, _ = self.flow.loss(+ partial(fl.flow_net, sel_z.float()), noise.float(), sel_target.float()+ )+ else:+ flow_loss, metrics, _ = self.flow.loss(partial(fl.flow_net, sel_z), noise, sel_target)flow_loss = flow_loss.mean()loss = flow_loss + self.args.eos_loss_weight * eos_lossdiff --git a/training/modules/samplers.py b/training/modules/samplers.pyindex 7fa9820..70de6e8 100644--- a/training/modules/samplers.py+++ b/training/modules/samplers.py@@ -13,14 +13,17 @@ backbone output for one frame, `x_0` is noise and `x_1` the target latent.- LSD: Lagrangian Self Distillation (arXiv:2505.18825), 2 time conds (s, t),1-step (or few-step) decode. This is the objective of the releasedpocket-tts models.+- Drifting: one-step noise-to-data generator trained with a kernel drift+ field (arXiv:2602.04770), no time cond."""+import mathfrom typing import Literalimport torchfrom torch import nn-from pocket_tts.models.flow_lm import FlowNet, lsd_decode, ot_decode+from pocket_tts.models.flow_lm import FlowNet, drifting_decode, lsd_decode, ot_decodefrom .utils import MLP, f_grad_x_only, zero_init@@ -168,7 +171,117 @@ class LSD(FlowType):return lsd_decode(v_t, x_0, num_steps)-FLOW_TYPES: dict[str, type[FlowType]] = {"flow_matching": FlowMatching, "lsd": LSD}+def cdist(x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:+ """Pairwise Euclidean distances, [B, N, D] x [B, M, D] -> [B, N, M]."""+ sq = (+ x.square().sum(-1)[:, :, None]+ + y.square().sum(-1)[:, None, :]+ - 2 * torch.einsum("bnd,bmd->bnm", x, y)+ )+ return sq.clamp(min=eps).sqrt()+++class Drifting(FlowType):+ """Drifting generative model (https://arxiv.org/abs/2602.04770).++ A one-step noise-to-data generator. Each step draws `num_neg` generations per+ position (the negatives) and moves the generator output along a kernel drift+ field V: attraction to the data sample minus repulsion from the other+ generations, via the fixed-point loss ||x - stopgrad(x + V)||^2. The kernel is+ Laplacian, on distances normalized by their per-position mean.++ The kernel temperature starts at `temp` and, with temp_loss_weight > 0, is+ learned by maximizing the data sample's share of the kernel mass; with 0 it+ stays fixed (at `temp`, or at the learned value when resuming a run that+ learned it).+ """++ num_time_conds = 0+ # The backward through num_neg vmapped head draws per position overflows in+ # bf16; the head is small, so the loss runs in fp32.+ fp32_loss = True++ def __init__(+ self,+ temp: float = 10.0,+ temp_loss_weight: float = 1.0,+ num_neg: int = 64,+ normalize_force: bool | Literal["batch"] = "batch",+ min_scale: float = 1e-3,+ min_temp: float = 1e-3,+ ):+ super().__init__()+ assert normalize_force in (True, False, "batch"), normalize_force+ self.num_neg = num_neg+ self.normalize_force = normalize_force+ self.min_scale = min_scale+ self.min_temp = min_temp+ self.temp_loss_weight = temp_loss_weight+ self.temp = nn.Parameter(torch.full((1,), temp), requires_grad=temp_loss_weight > 0)++ def _drift(+ self,+ dists: torch.Tensor,+ x: torch.Tensor,+ y_pos: torch.Tensor,+ y_neg: torch.Tensor,+ temp: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ logit = -dists / temp # [N, num_neg, 1 + num_neg]: each generation vs data + generations+ # Log-mass of the data sample relative to a flat kernel (0 = chance).+ pos_log_mass = logit.log_softmax(dim=-1)[..., 0] + math.log(self.num_neg)+ A = (logit.softmax(dim=-1) * logit.softmax(dim=-2)).clamp(min=1e-6).sqrt().detach()+ A_pos, A_neg = A[..., :1], A[..., 1:]+ W_pos = A_pos * A_neg.sum(dim=-1, keepdim=True)+ W_neg = A_neg * A_pos.sum(dim=-1, keepdim=True)+ force = W_pos @ y_pos - W_neg @ y_neg+ force = force - (W_pos.sum(dim=-1, keepdim=True) - W_neg.sum(dim=-1, keepdim=True)) * x+ rms = force.square().mean((-1, -2), keepdim=True).clamp(min=1e-8).sqrt()+ if self.normalize_force == "batch":+ force = force / rms.mean(dim=0, keepdim=True)+ elif self.normalize_force:+ force = force / rms+ return force, pos_log_mass++ def loss(+ self, v_t: FlowNet, x_0: torch.Tensor, x_1: torch.Tensor+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor], torch.Tensor]:+ e = torch.randn(self.num_neg, *x_0.shape, device=x_0.device, dtype=x_0.dtype)+ x = torch.vmap(v_t, out_dims=1)(e) # [N, num_neg, D]+ y_neg = x.detach()+ y_pos = x_1[:, None] # [N, 1, D]+ with torch.no_grad():+ dists = torch.cat([cdist(y_neg, y_pos), cdist(y_neg, y_neg)], dim=-1)+ n = self.num_neg + 1+ scale = (dists * n / (n - 1)).mean(dim=(-1, -2), keepdim=True).clamp(min=self.min_scale)+ # A generation never attracts or repels itself.+ self_mask = torch.eye(self.num_neg, device=x.device) * 100.0+ dists = dists / scale + torch.cat(+ [torch.zeros_like(dists[..., :1]), self_mask.expand_as(dists[..., 1:])], dim=-1+ )+ scale_input = scale / x.shape[-1] ** 0.5+ x, y_pos, y_neg = (z / scale_input for z in (x, y_pos, y_neg))+ temp = self.temp.clamp(min=self.min_temp)+ V, pos_log_mass = self._drift(dists, x.detach(), y_pos, y_neg, temp)+ loss = (x - (x + V).detach()).square().mean(dim=(-1, -2))+ # Per position, the generation that puts the most mass on the data sample sets the temperature.+ temp_loss = -pos_log_mass.amax(dim=-1).mean()+ metrics = {+ "drifting_loss": loss.mean(),+ "temp": self.temp.detach().squeeze(),+ "std_mean": y_neg.std(dim=1).norm(dim=-1).mean(),+ }+ return loss + self.temp_loss_weight * temp_loss, metrics, torch.zeros_like(x_0[..., :1])++ def decode(self, v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tensor:+ return drifting_decode(v_t, x_0)+++FLOW_TYPES: dict[str, type[FlowType]] = {+ "flow_matching": FlowMatching,+ "lsd": LSD,+ "drifting": Drifting,+}def build_flow(name: str, **kwargs: object) -> FlowType:diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.pyindex ec62561..4c06165 100644--- a/training/tests/test_smoke.py+++ b/training/tests/test_smoke.py@@ -81,7 +81,7 @@ def make_batch(return latents, mask, text, voice[email protected]("flow_type", ["lsd", "flow_matching"])[email protected]("flow_type", ["lsd", "flow_matching", "drifting"])def test_train_step(flow_type: str):model = tiny_model(flow_type)model.train()@@ -94,7 +94,7 @@ def test_train_step(flow_type: str):assert "flow_loss" in metrics and "eos_loss" in metrics[email protected]("flow_type,cfg", [("lsd", 1.0), ("flow_matching", 1.0)])[email protected]("flow_type,cfg", [("lsd", 1.0), ("flow_matching", 1.0), ("drifting", 1.0)])def test_generate(flow_type: str, cfg: float):model = tiny_model(flow_type)tokens = torch.randint(0, 10, (5,))diff --git a/training/tests/test_units.py b/training/tests/test_units.pyindex 3aaf03a..74d6372 100644--- a/training/tests/test_units.py+++ b/training/tests/test_units.py@@ -8,7 +8,7 @@ from torch import nnfrom training.args import OptimArgs, TrainArgsfrom training.checkpointing import EMA-from training.modules.samplers import LSD+from training.modules.samplers import LSD, Driftingfrom training.scripts.shrink_checkpoint import select_layers, shrinkfrom training.train_utils import lr_at@@ -132,3 +132,28 @@ class TestDistillProb:for _ in range(30):_, met, _ = m.loss(self._v, torch.randn(2, 4), torch.randn(2, 4))assert "flow_distill" in met+++class TestDrifting:+ def _head(self) -> nn.Module:+ torch.manual_seed(0)+ return nn.Sequential(nn.Linear(4, 16), nn.GELU(), nn.Linear(16, 4))++ def test_learned_temperature_gets_a_gradient(self):+ m, head = Drifting(temp=1.0, num_neg=8), self._head()+ loss, _, _ = m.loss(head, torch.randn(6, 4), torch.randn(6, 4))+ loss.mean().backward()+ assert m.temp.grad is not None and m.temp.grad.abs().item() > 0++ def test_fixed_temperature_keeps_the_resumed_value(self):+ """temp_loss_weight 0 (the fine-tune) freezes the temperature but keeps the+ parameter, so a stage-1 checkpoint that learned it loads as-is."""+ learned = Drifting(temp=10.0).state_dict()+ learned["temp"] = torch.tensor([0.05])+ m = Drifting(temp_loss_weight=0.0)+ m.load_state_dict(learned)+ assert not m.temp.requires_grad and m.temp.item() == pytest.approx(0.05)++ def test_decode_is_the_head_output(self):+ head, x_0 = self._head(), torch.randn(3, 4)+ assert torch.equal(Drifting().decode(head, x_0), head(x_0))