Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

feat(tts): add native CSM training support (#1769)

AmixDigital3da204fadbd2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 691068f2..00ae0013 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -558,6 +558,7 @@ jobs:
tests/test_bugfixes.py::TestDiffModelLoading
tests/test_issue636_torch_floor.py
tests/test_issue265_xcodec2_audio_contract.py
+ tests/test_native_csm.py
tests/test_cli_dependency_floors.py
tests/test_click_argument_help.py
tests/test_cli_startup_is_light.py
diff --git a/README.ar.md b/README.ar.md
index 57841588..e1939c25 100644
--- a/README.ar.md
+++ b/README.ar.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:7861d55b549aad1c5740d27f2fc72471270ed3011de8cbbf95ef23500e27fa99 -->
+<!-- synced-from: README.md sha256:44c28c06ff7d2445391cfcc7cd483b096453a302085ff8ac52cb48fa79ce4da5 -->
<p align="center">🌍 <a href="README.md">English</a> | <a href="README.tr.md">Türkçe</a> | <strong>العربية</strong> | <a href="README.ja.md">日本語</a> | <a href="README.zh.md">中文</a></p>
<p align="center">
@@ -297,7 +297,7 @@ Alpaca وShareGPT وChatML وأزواج التفضيلات (DPO / ORPO / SimPO /
العادي والتضمين (embedding) وRAFT وغيرها — كلها تُكتشف تلقائيًا من JSONL أو JSON أو CSV أو Parquet أو TXT،
ولذلك تكتفي في معظم الحالات بتوجيه `data.train` إلى ملف دون أن يتغير شيء آخر. وتوجد المخططات مع مثال
عملي لكل صيغة، إضافةً إلى خط أنابيب البيانات (معرّفات URI البعيدة، والبثّ، والتقسيم إلى شظايا (sharding)، والدمج المتناوب (interleaving)، وتوسيع
-المفردات، واستيعاب المستندات)، في [`docs/data.md`](docs/data.md#data-formats).
+المفردات، واستيعاب المستندات)، في [`docs/data.md`](docs/data.md#data-formats)، مع توثيق [تدريب الصوت الأصلي لـ Sesame CSM](docs/training.md#native-sesame-csm) بشكل منفصل.
## الأوامر الشائعة
diff --git a/README.ja.md b/README.ja.md
index 3d431653..cca573e3 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:7861d55b549aad1c5740d27f2fc72471270ed3011de8cbbf95ef23500e27fa99 -->
+<!-- synced-from: README.md sha256:44c28c06ff7d2445391cfcc7cd483b096453a302085ff8ac52cb48fa79ce4da5 -->
<p align="center">🌍 <a href="README.md">English</a> | <a href="README.tr.md">Türkçe</a> | <a href="README.ar.md">العربية</a> | <strong>日本語</strong> | <a href="README.zh.md">中文</a></p>
<p align="center">
@@ -295,7 +295,7 @@ Alpaca、ShareGPT、ChatML、選好ペア(DPO / ORPO / SimPO / IPO / KTO)、
埋め込み、RAFT など — すべて JSONL、JSON、CSV、Parquet、TXT から自動検出されるため、ほとんどの場合は
`data.train` をファイルに向けるだけで、他は何も変わりません。各形式の実例つきスキーマと、データパイプライン
(リモート URI、ストリーミング、シャーディング、インターリーブ、語彙拡張、ドキュメント取り込み)は、
-[`docs/data.md`](docs/data.md#data-formats) にあります。
+[`docs/data.md`](docs/data.md#data-formats) にあり、[Sesame CSM のネイティブ音声学習](docs/training.md#native-sesame-csm)は別途説明されています。
## よく使うコマンド
diff --git a/README.md b/README.md
index 634fa799..fe3243dd 100644
--- a/README.md
+++ b/README.md
@@ -297,7 +297,7 @@ ASR, plaintext, embedding, RAFT and more — all auto-detected from JSONL, JSON,
TXT, so in most cases you point `data.train` at a file and nothing else changes. Schemas with a
worked example per format, plus the data pipeline (remote URIs, streaming, sharding,
interleaving, vocab expansion, document ingestion), are in
-[`docs/data.md`](docs/data.md#data-formats).
+[`docs/data.md`](docs/data.md#data-formats), with [native Sesame CSM audio training](docs/training.md#native-sesame-csm) documented separately.
## Common Commands
diff --git a/README.tr.md b/README.tr.md
index 4198f017..02d8f578 100644
--- a/README.tr.md
+++ b/README.tr.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:7861d55b549aad1c5740d27f2fc72471270ed3011de8cbbf95ef23500e27fa99 -->
+<!-- synced-from: README.md sha256:44c28c06ff7d2445391cfcc7cd483b096453a302085ff8ac52cb48fa79ce4da5 -->
<p align="center">🌍 <a href="README.md">English</a> | <strong>Türkçe</strong> | <a href="README.ar.md">العربية</a> | <a href="README.ja.md">日本語</a> | <a href="README.zh.md">中文</a></p>
<p align="center">
@@ -300,7 +300,7 @@ metin, gömme (embedding), RAFT ve daha fazlası — hepsi JSONL, JSON, CSV, Par
otomatik algılanır; bu yüzden çoğu durumda `data.train`'i bir dosyaya yöneltirsiniz ve başka hiçbir
şey değişmez. Her biçim için adım adım çözümlü bir örnekle şemalar ve veri ardışık düzeni (uzak URI'ler,
akış, parçalama, iç içe geçirme, sözcük dağarcığı genişletme, belge içe aktarma)
-[`docs/data.md`](docs/data.md#data-formats) içinde.
+[`docs/data.md`](docs/data.md#data-formats) içinde; [yerel Sesame CSM ses eğitimi](docs/training.md#native-sesame-csm) ise ayrı belgelenmiştir.
## Yaygın Komutlar
diff --git a/README.zh.md b/README.zh.md
index eb7f72c1..22bab92d 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -1,4 +1,4 @@
-<!-- synced-from: README.md sha256:7861d55b549aad1c5740d27f2fc72471270ed3011de8cbbf95ef23500e27fa99 -->
+<!-- synced-from: README.md sha256:44c28c06ff7d2445391cfcc7cd483b096453a302085ff8ac52cb48fa79ce4da5 -->
<p align="center">🌍 <a href="README.md">English</a> | <a href="README.tr.md">Türkçe</a> | <a href="README.ar.md">العربية</a> | <a href="README.ja.md">日本語</a> | <strong>中文</strong></p>
<p align="center">
@@ -289,7 +289,7 @@ Alpaca、ShareGPT、ChatML、偏好对(DPO / ORPO / SimPO / IPO / KTO)、视
ASR、纯文本、embedding、RAFT 等等——全部从 JSONL、JSON、CSV、Parquet 或 TXT 自动检测,
所以多数情况下把 `data.train` 指向文件就行,其他什么都不用改。每种格式的 schema 和
完整示例,加上数据管线(远程 URI、流式、分片、交错、词表扩展、文档导入),都在
-[`docs/data.md`](docs/data.md#data-formats)。
+[`docs/data.md`](docs/data.md#data-formats),而 [Sesame CSM 原生音频训练](docs/training.md#native-sesame-csm) 则另有说明。
## 常用命令
diff --git a/changelog.d/0.76.0/1769.added.md b/changelog.d/0.76.0/1769.added.md
new file mode 100644
index 00000000..cf2b6019
--- /dev/null
+++ b/changelog.d/0.76.0/1769.added.md
@@ -0,0 +1,5 @@
+- Add native Sesame CSM training for raw-audio transcript rows through Transformers
+ CSM/Mimi, with backbone and depth-decoder losses, a frozen codec, standard LoRA or
+ full fine-tuning, validation, checkpoint resume and processor saving. Pre-encoded
+ CSM codec-string data and unsupported SFT options remain refused.
+ Spark/Oute raw-audio support remains outside this change. (#265 by @Amix29 in #1769)
diff --git a/docs/commands.md b/docs/commands.md
index d0525d5e..723b75fc 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -377,7 +377,7 @@ soup train # task='distill' + distill_mode=token|sequence Token logit-KL or se
soup train # task=classifier|reranker|cross_encoder + lora LoRA-adapter classifier (frozen encoder) — LIVE (v0.71.12)
soup train # use_mod | expand_layers Mixture-of-Depths / LLaMA Pro (Llama/Qwen/Mistral) — LIVE (v0.71.12)
soup train # use_longlora LongLoRA S² is refused at config load: the override leaked future tokens and applied no S² grouping; use rope_scaling_type with plain LoRA (#1240)
-soup train # task='tts' + tts_family + modality='audio_out' TTS pre-encoded codec-token SFT + emotion templating; Orpheus/Llasa live-codec; Spark/Oute raw-audio refused (upstream pins); Sesame CSM refused — LIVE (v0.71.20)
+soup train # task='tts' + tts_family + modality='audio_out' Codec-string SFT + emotion templating — LIVE (v0.71.20); native Sesame CSM with raw audio + 32 Mimi codebooks (#265); Spark/Oute raw-audio refused
soup train # task in {sft,tts} + moe_expert_quant=nf4|int8_rowwise [+moe_lora] bnb per-expert quant of fused-MoE experts (CUDA); refused on other tasks, which never applied it (#798) — LIVE (v0.71.20)
soup train # task in {sft,tts} + train_router_only=true [+moe_lora] Freeze MoE experts, train only the gating router; refused on other tasks (#798). moe_lora needs lora.dropout: 0.0 on fused-expert MoEs — LIVE (v0.71.20)
soup train # quantization='bitnet_1.58' BitNet 1.58 training is not implemented; config load refuses it
diff --git a/docs/config-reference.md b/docs/config-reference.md
index 4dbf8d24..f6fefba4 100644
--- a/docs/config-reference.md
+++ b/docs/config-reference.md
@@ -170,7 +170,7 @@ Sections:
| `training.off_policy_mask_threshold` | `float \| null` | `null` | `>= 0.0`, `<= 1.0` | Off-policy mask threshold for token/sequence gating (axolotl). Must be in \[0, 1]. None = disabled. |
| `training.vision_grpo` | `bool` | `false` | | Enable Vision RL / VLM RL — extends GRPO/PPO to vision modality (Qwen2-VL / Pixtral / InternVL). Requires modality='vision', task in {grpo, ppo}, backend in {transformers, unsloth}. Compatibility validation is available, but no trainer consumes this flag yet. |
| `training.hub` | `str` | `"hf"` | one of `"hf"`, `"modelscope"`, `"modelers"` | Training-time model-download hub. 'hf' (default), 'modelscope' (China-hosted; mirrors most Llama/Qwen/etc.), 'modelers' (Openmind hub). `soup push --hub` selects its upload destination independently of this field. |
-| `training.tts_family` | `str \| null` | `null` | one of `"orpheus"`, `"sesame_csm"`, `"llasa"`, `"spark"`, `"oute"` | TTS model family — required when task='tts'. Runnable choices are orpheus, llasa, spark, and oute. sesame_csm is retained only so legacy configs receive an explicit refusal until Soup has a native CSM multimodal trainer. |
+| `training.tts_family` | `str \| null` | `null` | one of `"orpheus"`, `"sesame_csm"`, `"llasa"`, `"spark"`, `"oute"` | TTS model family — required when task='tts'. orpheus, llasa, spark and oute use codec-string SFT; sesame_csm uses a native multimodal trainer with raw audio and 32 parallel Mimi codebooks. |
| `training.tts_emotion` | `str \| null` | `null` | | Optional emotion tag for emotion-conditioned families (Orpheus / Oute). Allowlisted per-family. (v0.52.0) |
| `training.num_labels` | `int \| null` | `null` | `>= 1`, `<= 1024` | Number of output labels for task in (classifier, reranker, cross_encoder). Required when task is one of those. (v0.52.0) |
| `training.classifier_kind` | `str \| null` | `null` | one of `"single_label"`, `"multi_label"` | Sequence-classification head kind: single_label (default for task='classifier') or multi_label. (v0.52.0) |
diff --git a/docs/training.md b/docs/training.md
index d2671696..6efcdf23 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1972,9 +1972,8 @@ cross-entropy over interleaved `[text][audio-codec-token]` chat sequences**,
so `TTSTrainerWrapper` reuses the SFT model/tokenizer/LoRA/CE machinery and
adds per-family emotion templating plus codec-token registration. `sesame_csm`
is different: current CSM training uses text plus 32 Mimi codebooks as parallel
-multimodal frames. Soup therefore refuses CSM on this text-SFT codec-string
-path rather than silently training the wrong objective; a dedicated CSM trainer
-is still required.
+multimodal frames. Soup routes it to a dedicated native trainer (see below),
+and continues to refuse pre-encoded CSM codec-string chat.
There are two workflows:
@@ -2025,16 +2024,78 @@ Spark-TTS has no installable `sparktts` package and its official environment pin
Torch/Transformers below Soup's supported stack; current `outetts` pins
Transformers 4.52.3 and Oute preparation also needs transcript/word alignment.
For those two families, pre-encode in the upstream environment and train the
-resulting codec-token chat with `data.format: chatml`. Sesame CSM fails earlier
-with an architecture-specific message because
-its 32 parallel Mimi codebooks require a native multimodal trainer, not a
-codec-string adapter.
+resulting codec-token chat with `data.format: chatml`. Sesame CSM uses the native
+multimodal path below, rather than this codec-string adapter.
Three ready-made codec-string recipes ship: `orpheus-tts-sft`, `llasa-tts`,
`oute-tts` — copy with `soup recipes use <name>`. Cross-validators
reject the `mlx` backend, `modality != audio_out`, and emotion tags outside the
per-family allowlist.
+### Native Sesame CSM
+
+`training.tts_family: sesame_csm` selects `CsmForConditionalGeneration` and
+`CsmProcessor` from Transformers, with no separate Moshi installation. The
+processor builds text conditioning and audio-frame labels; the model encodes
+audio with its frozen Mimi codec and optimizes the sum of the backbone loss
+(first codebook) and depth-decoder loss (the other 31 codebooks). Text and padding
+are excluded from the audio targets. Mimi stays in evaluation mode during training.
+This follows the [Transformers CSM training contract](https://huggingface.co/docs/transformers/model_doc/csm#training).
+
+Install `pip install 'soup-cli[train,audio]'`, then prepare one local clip and
+its exact transcript per JSONL row. `role` is the native speaker id `"0"` or `"1"`:
+
+```json
+{"audio": "hello.wav", "messages": [{"role": "0", "content": "Hello, how are you?"}]}
+```
+
+```yaml
+base: sesame/csm-1b
+backend: transformers
+task: tts
+modality: audio_out
+output: ./output/csm
+data:
+ train: ./data/speech.jsonl
+ format: audio
+ audio_dir: ./data/audio
+ max_length: 2048
+training:
+ tts_family: sesame_csm
+ quantization: none
+ epochs: 3
+ batch_size: 1
+ gradient_accumulation_steps: 4
+ lr: 0.00002
+ lora:
+ r: 16
+ alpha: 32
+```
+
+Run `soup train -c csm.yaml`. The checkpoint may require Hugging Face access;
+obtain that access and authenticate before running. Local Transformers-format
+CSM checkpoints are also accepted. Audio is loaded through Soup's local-file
+safety checks and resampled to mono 24 kHz. Sequences longer than `max_length`
+are refused rather than truncating audio markers and breaking codec alignment.
+
+The initial native path supports one device, single-clip rows, standard LoRA
+on the backbone and depth decoder (excluding Mimi), or full fine-tuning with
+`lora.r: 0` (Mimi remains frozen). `batch_size: auto` conservatively selects 1.
+Validation loss, boolean gradient checkpointing, seeds, checkpoint resume and
+processor saving are supported. Multi-turn rows, quantization, packing,
+distributed training and additional SFT optimization knobs are refused explicitly.
+The MLX backend remains unsupported for TTS. On Apple Silicon, contributor @Amix29
+ran `test_native_mps_training_step` with PyTorch/MPS, torch 2.13.0 and transformers
+5.16.1: one LoRA training step on a tiny randomly initialized CSM/Mimi model,
+with finite loss and a frozen codec. This is the evidence for the MPS bf16 opt-in.
+Full fine-tuning, gradient checkpointing, evaluation, resume and the pretrained
+`sesame/csm-1b` checkpoint were not run on MPS.
+
+Offline tests construct a tiny real CSM model with all 32 Mimi codebooks and
+exercise forward/backward, training, evaluation, save/reload and resume. These
+tests validate the integration; they do not establish speech quality or a full
+training run on the pretrained `sesame/csm-1b` checkpoint.
+
## Classifier / Reranker / Cross-Encoder Training (BETA, v0.52.0)
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 6d0f2047..1f58396f 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -245,6 +245,20 @@ def _validate_classification_dataset_if_applicable(cfg: Any, dataset: dict) -> N
raise typer.Exit(1) from exc
+def _validate_csm_dataset_if_applicable(cfg: Any, dataset: dict) -> None:
+ if cfg.task != "tts" or cfg.training.tts_family != "sesame_csm":
+ return
+ from rich.markup import escape
+
+ from soup_cli.utils.csm import validate_csm_dataset
+
+ try:
+ validate_csm_dataset(dataset)
+ except ValueError as exc:
+ console.print(f"[red]Error validating CSM dataset:[/] {escape(str(exc))}")
+ raise typer.Exit(1) from exc
+
+
def _refuse_empty_train(dcfg, dataset) -> None:
"""Stop a run whose data loaded zero training rows (#1217).
@@ -1731,6 +1745,7 @@ def train(
)
_refuse_empty_train(cfg.data, dataset)
_validate_classification_dataset_if_applicable(cfg, dataset)
+ _validate_csm_dataset_if_applicable(cfg, dataset)
console.print(
f"[green]Data OK:[/] {_train_sample_count(cfg.data, dataset)} train samples"
)
@@ -1749,6 +1764,7 @@ def train(
)
_refuse_empty_train(cfg.data, dataset)
_validate_classification_dataset_if_applicable(cfg, dataset)
+ _validate_csm_dataset_if_applicable(cfg, dataset)
console.print(
f"[green]Loaded:[/] {_train_sample_count(cfg.data, dataset)} train samples"
)
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 6029d66e..a2eab6ad 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -1851,10 +1851,9 @@ class TrainingConfig(BaseModel):
]] = Field(
default=None,
description=(
- "TTS model family — required when task='tts'. Runnable choices are "
- "orpheus, llasa, spark, and oute. sesame_csm is retained only so "
- "legacy configs receive an explicit refusal until Soup has a native "
- "CSM multimodal trainer."
+ "TTS model family — required when task='tts'. "
+ "orpheus, llasa, spark and oute use codec-string SFT; sesame_csm uses "
+ "a native multimodal trainer with raw audio and 32 parallel Mimi codebooks."
),
)
tts_emotion: Optional[str] = Field(
@@ -5834,17 +5833,12 @@ class SoupConfig(BaseModel):
if tcfg.tts_family is None:
raise ValueError(
"task='tts' requires a runnable training.tts_family in "
- "(orpheus, llasa, spark, oute); sesame_csm is currently refused"
+ "(orpheus, llasa, sesame_csm, spark, oute)"
)
if tcfg.tts_family == "sesame_csm":
- raise ValueError(
- "training.tts_family='sesame_csm' is not supported by Soup yet: "
- "CSM trains text plus 32 Mimi codebooks as parallel multimodal "
- "frames, so neither raw data.format='audio' nor pre-encoded "
- "data.format='chatml' is a valid text-SFT substitute. Use the "
- "model's native CSM/AutoProcessor training path until Soup has "
- "a dedicated CSM trainer."
- )
+ from soup_cli.utils.csm import validate_csm_config
+
+ validate_csm_config(self)
if self.data.format == "audio" and tcfg.tts_family in {"spark", "oute"}:
from soup_cli.utils.tts_codec import incompatible_live_codec_error
diff --git a/src/soup_cli/trainer/csm.py b/src/soup_cli/trainer/csm.py
new file mode 100644
index 00000000..e6a4e0b2
--- /dev/null
+++ b/src/soup_cli/trainer/csm.py
@@ -0,0 +1,226 @@
+"""Native Sesame CSM training: text conditioning and 32 parallel Mimi codebooks."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from soup_cli.trainer.sft import SFTTrainerWrapper, console
+from soup_cli.utils.csm import validate_csm_config, validate_csm_dataset, validate_csm_row
+from soup_cli.utils.eval_schedule import training_eval_kwargs
+from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
+
+
+class CSMDataCollator:
+ """Let CsmProcessor build native targets; never flatten codebooks into text."""
+
+ def __init__(self, processor: Any, max_length: int) -> None:
+ self.processor = processor
+ self.max_length = max_length
+
+ def __call__(self, examples: list[dict]) -> dict:
+ import numpy as np
+
+ from soup_cli.utils.tts_codec import load_audio_mono
+
+ texts, audios = [], []
+ for row in examples:
+ path, speaker, transcript = validate_csm_row(row)
+ if any(token in transcript for token in (
+ self.processor.audio_token, self.processor.audio_eos_token,
+ )):
+ raise ValueError("CSM transcript must not contain an audio control token")
+ audio = load_audio_mono(path, target_sr=24000)
+ if audio.size == 0 or not np.isfinite(audio).all():
+ raise ValueError("CSM audio must be non-empty and finite")
+ # Render without tokenize=True: only Soup's bounded local reader
+ # opens the file. The processor receives arrays, never paths/URLs.
+ texts.append(self.processor.apply_chat_template(
+ [{"role": speaker, "content": [
+ {"type": "text", "text": transcript}, {"type": "audio"},
+ ]}], tokenize=False, add_generation_prompt=False,
+ ))
+ audios.append(audio)
+ batch = self.processor(
+ text=texts, audio=audios, sampling_rate=24000, output_labels=True,
+ depth_decoder_labels_ratio=1.0, padding=True, truncation=False,
+ return_tensors="pt", add_special_tokens=False,
+ )
+ if batch["input_ids"].shape[-1] > self.max_length:
+ raise ValueError(
+ f"CSM sequence exceeds data.max_length={self.max_length}; split the clip "
+ "or increase max_length. Truncating audio markers would break Mimi alignment."
+ )
+ padding = batch["attention_mask"] == 0
+ batch["labels"][padding] = -100
+ # Some CSM tokenizers pad with the audio marker. The model merges audio
+ # based on input_ids rather than attention_mask; use a neutral text id
+ # on padding to avoid inventing frames or EOS targets in the model.
+ neutral_id = self.processor.tokenizer.bos_token_id
+ if neutral_id is None or neutral_id in {
+ self.processor.audio_token_id, self.processor.audio_eos_token_id,
+ }:
+ raise ValueError("CSM tokenizer needs a BOS text token distinct from audio markers")
+ batch["input_ids"][padding] = neutral_id
+ if not (batch["labels"] == self.processor.audio_token_id).any(dim=-1).all():
+ raise ValueError("CSM batch has an example without an audio-frame target")
+ return batch
+
+
+def freeze_csm_codec(model: Any) -> None:
+ """Mimi supplies fixed targets, and must never receive optimizer updates."""
+ model.codec_model.requires_grad_(False)
+ model.codec_model.eval()
+
+
+def _non_leaf_depth_embeddings(module: Any, inputs: Any, output: Any) -> Any:
+ """Allow CSM's in-place backbone-frame insertion with frozen LoRA embeddings.
+
+ Transformers' checkpointing input-grad hook makes frozen embeddings a leaf
+ requiring grad. CSM replaces their first frame in place, which autograd
+ refuses on that leaf. A differentiable clone preserves gradient flow and
+ the upstream forward, without changing any target or trainable parameter.
+ """
+ if output.requires_grad and output.is_leaf:
+ return output.clone()
+ return output
+
+
+def make_csm_trainer(**kwargs: Any) -> Any:
+ """Keep Mimi in eval even when Trainer toggles the whole model to train."""
+ from transformers import Trainer
+
+ class NativeCSMTrainer(Trainer):
+ def __init__(self, **trainer_kwargs: Any) -> None:
+ super().__init__(**trainer_kwargs)
+ # The model sums two losses with different target cardinalities.
+ # HF's count of 2-D processor labels is not their normalization.
+ self.model_accepts_loss_kwargs = False
+
+ def compute_loss(
+ self, model: Any, inputs: dict, return_outputs: bool = False, **loss_kwargs: Any,
+ ) -> Any:
+ model.codec_model.eval()
+ return super().compute_loss(
+ model, inputs, return_outputs=return_outputs, **loss_kwargs,
+ )
+
+ return NativeCSMTrainer(**kwargs)
+
+
+class CSMTrainerWrapper(SFTTrainerWrapper):
+ """Dedicated setup with Soup's common logging, resume and final-save lifecycle."""
+
+ def setup(self, dataset: dict) -> None:
+ validate_csm_config(self.config)
+ from soup_cli.trainer.stream_setup import _distributed_launch
+
+ if self.deepspeed_config or self.fsdp_config or _distributed_launch():
+ raise ValueError("Native Sesame CSM currently supports single-device training only")
+ if str(self.device).startswith("cuda"):
+ import torch
+
+ if torch.cuda.is_available() and torch.cuda.device_count() > 1:
+ raise ValueError(
+ "Native Sesame CSM supports single-device training only; "
+ "set CUDA_VISIBLE_DEVICES to one GPU to avoid Trainer DataParallel"
+ )
+ validate_csm_dataset(dataset)
+
+ try:
+ import soundfile # noqa: F401
+ except (ImportError, OSError) as exc:
+ raise RuntimeError(
+ "Native Sesame CSM needs soundfile to read audio. "
+ "Install it with: pip install 'soup-cli[train,audio]'."
+ ) from exc
+
+ try:
+ from transformers import CsmForConditionalGeneration, CsmProcessor, TrainingArguments
+ except ImportError as exc:
+ raise RuntimeError(
+ "Native Sesame CSM needs Transformers CsmForConditionalGeneration and "
+ "CsmProcessor. Install it with: pip install 'soup-cli[train,audio]'."
+ ) from exc
+ from soup_cli.utils.gpu import bf16_fp16_flags, resolve_base_load_dtype
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ cfg, tcfg = self.config, self.config.training
+ apply_training_seed(tcfg)
+ self.processor = CsmProcessor.from_pretrained(
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ )
+ # Saving the processor, rather than just its tokenizer, preserves the
+ # feature extractor + native chat template for reload/inference.
+ self.tokenizer = self.processor
+ self.model = CsmForConditionalGeneration.from_pretrained(
+ cfg.base,
+ torch_dtype=resolve_base_load_dtype(self.device, full_finetune=tcfg.lora.r == 0),
+ trust_remote_code=self._trust_remote_code,
+ )
+ if (self.model.config.num_codebooks != 32
+ or self.model.codec_model.config.num_quantizers != 32
+ or self.model.depth_decoder.config.num_codebooks != 32):
+ raise ValueError("Native Sesame CSM requires all 32 Mimi codebooks")
+ if self.model.codec_model.config.sampling_rate != 24000:
+ raise ValueError("Native Sesame CSM requires a 24 kHz Mimi codec")
+ if (self.model.config.audio_token_id != self.processor.audio_token_id
+ or self.model.config.audio_eos_token_id != self.processor.audio_eos_token_id):
+ raise ValueError("CSM model and processor audio token ids do not match")
+ freeze_csm_codec(self.model)
+ self.model.config.use_cache = False
+ self.model.depth_decoder.config.use_cache = False
+ self.model.to(self.device)
+ if tcfg.lora.r > 0:
+ from peft import get_peft_model
+
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ # Generic PEFT forwarding preserves audio kwargs. CAUSAL_LM's
+ # text-specific wrapper is not the contract of this multimodal LM.
+ self.model = get_peft_model(self.model, build_lora_config(
+ tcfg.lora, task_type=None,
+ target_modules=r"(?:backbone_model|depth_decoder\.model)\.layers\.\d+"
+ r"\.self_attn\.(?:q_proj|v_proj)",
+ ))
+ if tcfg.gradient_checkpointing:
+ # Install HF's input-grad hooks before our clone hook. Trainer can
+ # enable checkpointing again: later input-grad hooks then see the
+ # already differentiable non-leaf and leave it intact.
+ self.model.gradient_checkpointing_enable(
+ gradient_checkpointing_kwargs={"use_reentrant": False},
+ )
+ embeddings = self.model.depth_decoder.get_input_embeddings()
+ self._depth_embedding_hook = embeddings.register_forward_hook(
+ _non_leaf_depth_embeddings,
+ )
+ self._batch_size = 1 if tcfg.batch_size == "auto" else tcfg.batch_size
+ if tcfg.batch_size == "auto":
+ console.print("[dim]Native CSM: batch_size=auto uses a conservative batch of 1.[/]")
+ output = Path(cfg.output)
+ if cfg.experiment_name:
+ output /= cfg.experiment_name
+ self._output_dir = str(output)
+ # MPS evidence/limits: docs/training.md#native-sesame-csm (one tiny-model LoRA step).
+ bf16, fp16 = bf16_fp16_flags(self.device, allow_mps_bf16=True)
+ args = TrainingArguments(
+ output_dir=self._output_dir, num_train_epochs=tcfg.epochs,
+ per_device_train_batch_size=self._batch_size,
+ gradient_accumulation_steps=tcfg.gradient_accumulation_steps,
+ learning_rate=tcfg.lr, weight_decay=tcfg.weight_decay, max_grad_norm=tcfg.max_grad_norm,
+ warmup_steps=resolve_trainer_warmup_steps(tcfg.warmup_ratio),
+ optim=tcfg.optimizer, lr_scheduler_type=tcfg.scheduler,
+ logging_steps=tcfg.logging_steps, save_steps=tcfg.save_steps, save_total_limit=3,
+ bf16=bf16, fp16=fp16, use_cpu=self.device == "cpu", report_to=self.report_to,
+ gradient_checkpointing=tcfg.gradient_checkpointing,
+ gradient_checkpointing_kwargs={"use_reentrant": False},
+ remove_unused_columns=False, label_names=["labels"], prediction_loss_only=True,
+ **training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, dataset.get("val"), batch_size=self._batch_size),
+ )
+ self.trainer = make_csm_trainer(
+ model=self.model, args=args, processing_class=self.processor,
+ train_dataset=dataset["train"], eval_dataset=dataset.get("val") or None,
+ data_collator=CSMDataCollator(self.processor, cfg.data.max_length),
+ )
+ console.print("[green]Native Sesame CSM:[/] backbone + 31 depth codebooks; Mimi frozen")
diff --git a/src/soup_cli/trainer/dispatch.py b/src/soup_cli/trainer/dispatch.py
index f8252ed5..b75b74df 100644
--- a/src/soup_cli/trainer/dispatch.py
+++ b/src/soup_cli/trainer/dispatch.py
@@ -126,6 +126,10 @@ def build_trainer(cfg: Any, **trainer_kwargs: Any):
return MoleRoutingTrainerWrapper(cfg, **trainer_kwargs)
if task == "tts":
+ if getattr(getattr(cfg, "training", None), "tts_family", None) == "sesame_csm":
+ from soup_cli.trainer.csm import CSMTrainerWrapper
+
+ return CSMTrainerWrapper(cfg, **trainer_kwargs)
# v0.71.20 #131 — TTS fine-tuning (SFT-style next-token CE over text +
# audio-codec-token sequences; per-family templating).
from soup_cli.trainer.tts import TTSTrainerWrapper
diff --git a/src/soup_cli/utils/csm.py b/src/soup_cli/utils/csm.py
new file mode 100644
index 00000000..5613f96d
--- /dev/null
+++ b/src/soup_cli/utils/csm.py
@@ -0,0 +1,84 @@
+"""Import-light validation for the native Sesame CSM trainer (#265)."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from soup_cli.config.schema import SoupConfig
+
+
+def validate_csm_config(cfg: SoupConfig) -> None:
+ """Refuse text-SFT substitutes and knobs the native trainer cannot honour."""
+ if cfg.backend != "transformers":
+ raise ValueError("Sesame CSM requires backend='transformers'")
+ if cfg.data.format != "audio":
+ raise ValueError(
+ "Sesame CSM requires data.format='audio' with a transcript and a raw audio clip; "
+ "pre-encoded codec-string chat is not a native CSM training example."
+ )
+ tcfg = cfg.training
+ if tcfg.quantization != "none":
+ raise ValueError("Sesame CSM requires training.quantization='none'")
+ if not isinstance(tcfg.gradient_checkpointing, bool):
+ raise ValueError("Sesame CSM supports boolean training.gradient_checkpointing only")
+
+ # This is a separate Trainer path: accepting an SFT optimization without
+ # implementing it would silently ignore an operator's requested behaviour.
+ supported = {
+ "epochs", "lr", "batch_size", "gradient_accumulation_steps", "seed", "data_seed",
+ "warmup_ratio", "weight_decay", "max_grad_norm", "optimizer", "scheduler",
+ "save_steps", "logging_steps", "eval_steps", "lora", "quantization", "tts_family",
+ "gradient_checkpointing",
+ }
+ defaults = type(tcfg)().model_dump()
+ for name, value in tcfg.model_dump().items():
+ if name not in supported and value != defaults[name]:
+ raise ValueError(f"Sesame CSM does not support training.{name}")
+ lora_defaults = type(tcfg.lora)().model_dump()
+ for name, value in tcfg.lora.model_dump().items():
+ if name not in {"r", "alpha", "dropout"} and value != lora_defaults[name]:
+ raise ValueError(f"Sesame CSM does not support training.lora.{name}")
+ data_defaults = type(cfg.data)(train=cfg.data.train).model_dump()
+ for name, value in cfg.data.model_dump().items():
+ if name not in {"train", "format", "val_split", "max_length", "audio_dir"}:
+ if value != data_defaults[name]:
+ raise ValueError(f"Sesame CSM does not support data.{name}")
+
+
+def validate_csm_row(row: object) -> tuple[str, str, str]:
+ """One clip and its exact transcript, with a native speaker role (0 or 1).
+
+ Multiple messages paired with just one audio path are ambiguous: no
+ transcript/context concatenation or speaker inference is performed.
+ """
+ if not isinstance(row, dict):
+ raise ValueError("CSM row must be a dict")
+ path = row.get("audio")
+ if not isinstance(path, str) or not path.strip() or "\x00" in path:
+ raise ValueError("CSM row needs a non-empty local audio path")
+ messages = row.get("messages")
+ if not isinstance(messages, list) or len(messages) != 1:
+ raise ValueError("CSM row needs exactly one transcript message for its audio clip")
+ message = messages[0]
+ if not isinstance(message, dict) or set(message) != {"role", "content"}:
+ raise ValueError("CSM transcript message must contain only role and content")
+ speaker = message["role"]
+ if not isinstance(speaker, str) or speaker not in {"0", "1"}:
+ raise ValueError("CSM transcript role must be the speaker id '0' or '1'")
+ text = message["content"]
+ if not isinstance(text, str) or not text.strip() or "\x00" in text:
+ raise ValueError("CSM transcript content must be non-empty text")
+ return path, speaker, text
+
+
+def validate_csm_dataset(dataset: dict) -> None:
+ """Validate every paired transcript before downloading weights or taking a step."""
+ for split in ("train", "val"):
+ for index, row in enumerate(dataset.get(split) or []):
+ try:
+ validate_csm_row(row)
+ except ValueError as exc:
+ raise ValueError(f"CSM {split} row {index + 1}: {exc}") from exc
+ if not dataset.get("train"):
+ raise ValueError("CSM requires at least one training row")
diff --git a/src/soup_cli/utils/tts_codec.py b/src/soup_cli/utils/tts_codec.py
index 02ec8350..5fcc3c17 100644
--- a/src/soup_cli/utils/tts_codec.py
+++ b/src/soup_cli/utils/tts_codec.py
@@ -22,9 +22,10 @@ per-family encoder) is family-agnostic. It now has codec-string encoders for:
Spark and Oute raw-audio live encoding is deliberately refused on this path
because their current upstream stacks are incompatible with Soup. Sesame CSM
-is also refused: current CSM training uses 32 Mimi codebooks plus text as
+is refused on this codec-string path: its native trainer uses 32 Mimi codebooks plus text as
parallel multimodal frames, which cannot be represented faithfully by replacing
-a text assistant turn.
+a text assistant turn. Raw-audio transcript pairs use the dedicated native CSM
+trainer instead.
Security / robustness:
- Heavy imports (numpy / soundfile / torch / snac / transformers) are lazy — module import
@@ -386,9 +387,9 @@ def csm_live_codec_error() -> RuntimeError:
"TTS family 'sesame_csm' cannot use Soup's codec-string SFT "
"live-codec path: CSM trains 32 Mimi codebooks plus text as parallel "
"multimodal frames, not audio ids embedded in a text assistant turn. "
- "Use the model's native CSM/AutoProcessor training path; Soup needs a "
- "dedicated CSM trainer before either data.format=audio or pre-encoded "
- "data.format=chatml can be supported safely."
+ "Use Soup's dedicated CSM trainer with training.tts_family=sesame_csm, "
+ "data.format=audio and training.quantization=none. Pre-encoded "
+ "data.format=chatml is not a native CSM training example."
)
diff --git a/tests/test_issue1099_moe_lora_remaining_tasks.py b/tests/test_issue1099_moe_lora_remaining_tasks.py
index 7b69a5b4..d556c32a 100644
--- a/tests/test_issue1099_moe_lora_remaining_tasks.py
+++ b/tests/test_issue1099_moe_lora_remaining_tasks.py
@@ -400,7 +400,7 @@ class TestEveryAdapterBuildingTrainerReadsTheFlag:
declared here as one whose task refuses ``moe_lora`` at config load."""
#: Trainer modules whose task refuses the flag (schema ``_validate_moe_lora_task``).
- REFUSED_MODULES = frozenset({"asr.py"})
+ REFUSED_MODULES = frozenset({"asr.py", "csm.py"})
@staticmethod
def _calls(path):
@@ -436,6 +436,18 @@ class TestEveryAdapterBuildingTrainerReadsTheFlag:
"""The exemption list must not drift from the schema's refusal."""
with pytest.raises(ValueError, match="moe_lora.*task='asr'"):
_config("asr", moe_lora=True)
+ from soup_cli.config.schema import SoupConfig
+
+ assert self.REFUSED_MODULES == {"asr.py", "csm.py"}
+ values = dict(
+ base="sesame/csm-1b", task="tts", modality="audio_out",
+ data={"train": "speech.jsonl", "format": "audio"},
+ )
+ training = {"tts_family": "sesame_csm", "quantization": "none",
+ "lora": {"dropout": 0.0}}
+ SoupConfig(**values, training=training)
+ with pytest.raises(ValueError, match="moe_lora"):
+ SoupConfig(**values, training={**training, "moe_lora": True})
class TestThePathsThatNeverReadIt:
diff --git a/tests/test_issue265_llasa_csm_live_codec.py b/tests/test_issue265_llasa_csm_live_codec.py
index 782cd719..194babf0 100644
--- a/tests/test_issue265_llasa_csm_live_codec.py
+++ b/tests/test_issue265_llasa_csm_live_codec.py
@@ -181,8 +181,8 @@ class TestTrainerContract:
class TestCsmParseTimeRefusal:
- @pytest.mark.parametrize("data_format", ["audio", "chatml"])
- def test_csm_is_refused_at_config_parse_for_both_input_shapes(self, data_format):
+ @pytest.mark.parametrize("data_format", ["chatml"])
+ def test_csm_codec_string_shape_is_still_refused(self, data_format):
from soup_cli.config.loader import load_config_from_string
yaml = f"""base: sesame/csm-1b
@@ -193,8 +193,9 @@ data:
format: {data_format}
training:
tts_family: sesame_csm
+ quantization: none
"""
- with pytest.raises(ValueError, match="dedicated CSM trainer"):
+ with pytest.raises(ValueError, match="data.format='audio'"):
load_config_from_string(yaml)
def test_unrunnable_csm_recipe_is_not_advertised(self):
diff --git a/tests/test_issue359_deepspeed_guard_coverage.py b/tests/test_issue359_deepspeed_guard_coverage.py
index ccb4dec2..202557be 100644
--- a/tests/test_issue359_deepspeed_guard_coverage.py
+++ b/tests/test_issue359_deepspeed_guard_coverage.py
@@ -32,6 +32,8 @@ _BUILDS_TRAINER = re.compile(r"self\.trainer\s*=\s*(?!None\b)[A-Za-z_][\w.]*\s*\
_GUARD_CALL = re.compile(r"attach_empty_param_group_guard\s*\(")
#: DeepSpeed reachability: the wrapper takes a config it can be launched with.
_DEEPSPEED_CAPABLE = re.compile(r"\bdeepspeed_config\b")
+# Unlike forwarding exemptions, these trainers reject DeepSpeed before setup.
+_DEEPSPEED_REFUSING = {"csm.py"}
def _code_without_comments(text: str) -> str:
@@ -40,6 +42,8 @@ def _code_without_comments(text: str) -> str:
def _needs_guard(path: pathlib.Path) -> bool:
+ if path.name in _DEEPSPEED_REFUSING:
+ return False
code = _code_without_comments(path.read_text(encoding="utf-8"))
return bool(_DEEPSPEED_CAPABLE.search(code)) and bool(_BUILDS_TRAINER.search(code))
@@ -96,7 +100,7 @@ class TestGuardCoverage:
code = _code_without_comments(path.read_text(encoding="utf-8"))
if not _DEEPSPEED_CAPABLE.search(code):
continue
- if path.name in self._GUARD_EXEMPT:
+ if path.name in self._GUARD_EXEMPT or path.name in _DEEPSPEED_REFUSING:
continue
if not _GUARD_CALL.search(code):
offenders.append(path.name)
@@ -440,3 +444,19 @@ class TestUserSuppliedDeepspeedFileIsResolved:
ds, "resolve_user_deepspeed_file", lambda *a, **k: pytest.fail("not a file")
)
assert _resolve_deepspeed("zero2") == "preset:zero2"
+
+
+def test_deepspeed_refusing_exemption_is_earned():
+ from soup_cli.config.schema import SoupConfig
+ from soup_cli.trainer.csm import CSMTrainerWrapper
+
+ assert _DEEPSPEED_REFUSING == {"csm.py"}
+ config = SoupConfig(
+ base="sesame/csm-1b", task="tts", modality="audio_out",
+ data={"train": "speech.jsonl", "format": "audio"},
+ training={"tts_family": "sesame_csm", "quantization": "none"},
+ )
+ wrapper = CSMTrainerWrapper(config, device="cpu", deepspeed_config="ds.json")
+ with pytest.raises(ValueError, match="single-device"):
+ wrapper.setup({})
+ assert wrapper.model is None and wrapper.trainer is None
diff --git a/tests/test_issue563_mps_bf16_training.py b/tests/test_issue563_mps_bf16_training.py
index 187a38cb..a08193c5 100644
--- a/tests/test_issue563_mps_bf16_training.py
+++ b/tests/test_issue563_mps_bf16_training.py
@@ -109,11 +109,12 @@ class TestPrecisionPolicy:
) == (True, False)
assert calls == [("mps", True)]
- def test_only_hardware_validated_text_trainers_opt_in(self):
+ def test_only_hardware_validated_trainers_opt_in(self):
import soup_cli.trainer as trainer_package
root = Path(trainer_package.__file__).parent
- expected = {"sft.py", "dpo.py", "grpo.py", "reward_model.py", "prm.py"}
+ # CSM's real MPS training proof lives in test_native_csm.py.
+ expected = {"sft.py", "dpo.py", "grpo.py", "reward_model.py", "prm.py", "csm.py"}
opted_in = {
path.name
for path in root.glob("*.py")
diff --git a/tests/test_issue724_loraplus_wiring_coverage.py b/tests/test_issue724_loraplus_wiring_coverage.py
index 229643fc..4ae1ec93 100644
--- a/tests/test_issue724_loraplus_wiring_coverage.py
+++ b/tests/test_issue724_loraplus_wiring_coverage.py
@@ -85,6 +85,10 @@ _INJECT_CALL = re.compile(r"build_loraplus_optimizer\s*\(")
#: argued for rather than slipping through, and the "stays earned" test below
#: keeps each reason true.
_LORAPLUS_EXEMPT = {
+ "csm.py": (
+ "Native CSM accepts only standard LoRA; loraplus_lr_ratio is refused at "
+ "config parse (tests/test_native_csm.py)."
+ ),
"unlearn.py": (
"not a Trainer subclass — runs torch.optim.AdamW directly (unlearn.py), "
"so there is no trainer.optimizer to attach LoRA+ to. loraplus_lr_ratio "
diff --git a/tests/test_issue725_lorafa_wiring_coverage.py b/tests/test_issue725_lorafa_wiring_coverage.py
index 19d9d731..0a57b1ad 100644
--- a/tests/test_issue725_lorafa_wiring_coverage.py
+++ b/tests/test_issue725_lorafa_wiring_coverage.py
@@ -30,6 +30,7 @@ _LORAFA_NOT_IMPLEMENTED = {
"asr.py",
"bco.py",
"classifier.py",
+ "csm.py", # Native config refuses use_lorafa; test_native_csm.py pins it.
"distill.py",
"dpo.py",
"grpo.py",
diff --git a/tests/test_issue803_lora_patterns_all_trainers.py b/tests/test_issue803_lora_patterns_all_trainers.py
index d88ae1ce..70510540 100644
--- a/tests/test_issue803_lora_patterns_all_trainers.py
+++ b/tests/test_issue803_lora_patterns_all_trainers.py
@@ -24,6 +24,10 @@ _WRAPPERS = (
)
+# Native CSM limits its initial adapter contract and refuses patterns at parse.
+_PATTERN_REFUSING = {"csm"}
+
+
def _config(task: str):
from soup_cli.config.schema import SoupConfig
@@ -395,6 +399,7 @@ def test_every_build_lora_config_caller_is_covered_by_a_pattern_test() -> None:
{name for name, _ in _WRAPPERS}
| {name for name, _ in _SETUP_DRIVERS}
| {"online_dpo", "stream_setup"}
+ | _PATTERN_REFUSING
)
assert callers - covered == set(), f"no LoRA pattern test for: {sorted(callers - covered)}"
@@ -457,3 +462,19 @@ def test_trainers_cannot_construct_lora_config_outside_shared_builder() -> None:
"trainer modules must use soup_cli.utils.peft_wiring.build_lora_config; "
f"direct LoraConfig construction found in: {offenders}"
)
+
+
[email protected]("field", ["rank_pattern", "alpha_pattern"])
+def test_native_csm_pattern_refusal_is_earned(field):
+ from soup_cli.config.schema import SoupConfig
+
+ assert _PATTERN_REFUSING == {"csm"}
+ values = dict(
+ base="sesame/csm-1b", task="tts", modality="audio_out",
+ data={"train": "speech.jsonl", "format": "audio"},
+ )
+ # Control: the same native configuration parses without the pattern.
+ training = {"tts_family": "sesame_csm", "quantization": "none"}
+ SoupConfig(**values, training=training)
+ with pytest.raises(ValueError, match=field):
+ SoupConfig(**values, training={**training, "lora": {field: {"q_proj": 4}}})
diff --git a/tests/test_native_csm.py b/tests/test_native_csm.py
new file mode 100644
index 00000000..c33ca873
--- /dev/null
+++ b/tests/test_native_csm.py
@@ -0,0 +1,457 @@
+"""Native CSM: config/dispatch, safe audio collation and real multimodal loss."""
+
+from __future__ import annotations
+
+import copy
+import json
+import math
+import wave
+
+import pytest
+
+from tests.conftest import strip_ansi
+
+
+def csm_config(**training):
+ from soup_cli.config.schema import SoupConfig
+
+ return SoupConfig(
+ base="sesame/csm-1b", task="tts", modality="audio_out",
+ data={"train": "speech.jsonl", "format": "audio", "val_split": 0},
+ training={"tts_family": "sesame_csm", "quantization": "none", **training},
+ )
+
+
+def write_audio(path, frames=3840):
+ import numpy as np
+
+ samples = (2000 * np.sin(np.arange(frames) * 2 * math.pi * 220 / 24000)).astype("<i2")
+ with wave.open(str(path), "wb") as stream:
+ stream.setnchannels(1)
+ stream.setsampwidth(2)
+ stream.setframerate(24000)
+ stream.writeframes(samples.tobytes())
+
+
+def speech_row(path, text="Hello", speaker="0"):
+ return {"audio": str(path), "messages": [{"role": speaker, "content": text}]}
+
+
+def use_cpu_cli(monkeypatch):
+ import soup_cli.commands.train as train_command
+
+ monkeypatch.setattr(train_command, "detect_device", lambda **_: ("cpu", "CPU"))
+ monkeypatch.setattr(train_command, "get_gpu_info", lambda **_: {
+ "memory_total": "0 GB", "memory_total_bytes": 0, "gpu_count": 0,
+ })
+
+
+def test_native_audio_config_and_dispatch():
+ from soup_cli.trainer.csm import CSMTrainerWrapper
+ from soup_cli.trainer.dispatch import build_trainer
+
+ assert isinstance(build_trainer(csm_config(), device="cpu"), CSMTrainerWrapper)
+
+
[email protected]("fmt", ["chatml", "auto", "pre_tokenized"])
+def test_codec_string_configs_still_refused(fmt):
+ from soup_cli.config.schema import SoupConfig
+
+ values = csm_config().model_dump()
+ values["data"]["format"] = fmt
+ if fmt == "pre_tokenized":
+ values["data"]["tokenized_path"] = "cache"
+ reason = "pre_tokenized" if fmt == "pre_tokenized" else "data.format='audio'"
+ with pytest.raises(ValueError, match=reason):
+ SoupConfig(**values)
+
+
[email protected]("option, reason", [
+ ({"quantization": "4bit"}, "Sesame CSM requires training.quantization='none'"),
+ ({"packing": True}, "Sesame CSM does not support training.packing"),
+ ({"multipack": True}, "multipack=true is not supported for task='tts'"),
+ ({"use_liger": True}, "Sesame CSM does not support training.use_liger"),
+ ({"use_flash_attn": True}, "Sesame CSM does not support training.use_flash_attn"),
+ ({"freeze_ratio": 0.5}, "Sesame CSM does not support training.freeze_ratio"),
+ ({"auto_mixed_precision": True}, "Sesame CSM does not support training.auto_mixed_precision"),
+ ({"gradient_checkpointing": "selective"},
+ "Sesame CSM supports boolean training.gradient_checkpointing only"),
+ ({"neftune_alpha": 5}, "Sesame CSM does not support training.neftune_alpha"),
+ ({"lr_groups": {"default": 0.0001}}, "Sesame CSM does not support training.lr_groups"),
+])
+def test_unsupported_training_settings_fail_before_model_load(option, reason):
+ import re
+
+ with pytest.raises(ValueError, match=re.escape(reason)):
+ csm_config(**option)
+
+
[email protected]("option, field", [
+ ({"target_modules": ["q_proj"]}, "target_modules"),
+ ({"use_dora": True}, "use_dora"),
+ ({"target_parameters": "auto", "dropout": 0}, "target_parameters"),
+])
+def test_unsupported_lora_settings_are_explicit(option, field):
+ import re
+
+ with pytest.raises(ValueError, match=re.escape(
+ f"Sesame CSM does not support training.lora.{field}"
+ )):
+ csm_config(lora=option)
+
+
[email protected]("rank", [0, 2])
+def test_full_ft_and_lora_are_configurable(rank):
+ assert csm_config(lora={"r": rank}).training.lora.r == rank
+
+
[email protected]("speaker", ["0", "1"])
+def test_transcript_and_speaker_are_preserved(speaker):
+ from soup_cli.utils.csm import validate_csm_row
+
+ row = speech_row("clip.wav", "Exact transcript", speaker)
+ assert validate_csm_row(row) == ("clip.wav", speaker, "Exact transcript")
+
+
[email protected]("row, reason", [
+ ({}, "CSM row needs a non-empty local audio path"),
+ (speech_row(""), "CSM row needs a non-empty local audio path"),
+ (speech_row("a.wav", ""), "CSM transcript content must be non-empty text"),
+ (speech_row("a.wav", " "), "CSM transcript content must be non-empty text"),
+ (speech_row("a.wav", "Hello", "assistant"),
+ "CSM transcript role must be the speaker id '0' or '1'"),
+ (speech_row("a.wav", "Hello", True),
+ "CSM transcript role must be the speaker id '0' or '1'"),
+ ({"audio": "a.wav", "messages": []},
+ "CSM row needs exactly one transcript message for its audio clip"),
+ ({"audio": "a.wav", "messages": [{"role": "0", "content": []}]},
+ "CSM transcript content must be non-empty text"),
+ ({"audio": "a.wav", "messages": [{"role": "0", "content": "Hi", "train": False}]},
+ "CSM transcript message must contain only role and content"),
+ ({"audio": "a.wav", "messages": [{"role": "0", "content": "A"},
+ {"role": "1", "content": "B"}]},
+ "CSM row needs exactly one transcript message for its audio clip"),
+])
+def test_ambiguous_rows_fail_instead_of_training_wrong_transcript(row, reason):
+ import re
+
+ from soup_cli.utils.csm import validate_csm_row
+
+ with pytest.raises(ValueError, match=re.escape(reason)):
+ validate_csm_row(row)
+
+
+def tiny_csm_components():
+ """Real CSM + real 32-codebook Mimi, random tiny weights, no Hub access."""
+ pytest.importorskip("soundfile")
+ import torch
+ from tokenizers import Tokenizer
+ from tokenizers.models import WordLevel
+ from tokenizers.pre_tokenizers import Whitespace
+ from transformers import (
+ CsmConfig,
+ CsmForConditionalGeneration,
+ CsmProcessor,
+ EncodecFeatureExtractor,
+ PreTrainedTokenizerFast,
+ )
+
+ torch.manual_seed(42)
+ vocab = {"<pad>": 0, "<unk>": 1, "<bos>": 2, "<|AUDIO|>": 3,
+ "<|audio_eos|>": 4, "Hello": 5, "longer": 6, "[": 7,
+ "]": 8, "0": 9, "1": 10}
+ backend = Tokenizer(WordLevel(vocab, unk_token="<unk>"))
+ backend.pre_tokenizer = Whitespace()
+ tokenizer = PreTrainedTokenizerFast(
+ tokenizer_object=backend, pad_token="<pad>", unk_token="<unk>", bos_token="<bos>",
+ additional_special_tokens=["<|AUDIO|>", "<|audio_eos|>"],
+ )
+ template = ("{{ bos_token }}{% for message in messages %}[{{ message.role }}]"
+ "{% for part in message.content %}{% if part.type == 'text' %}{{ part.text }}"
+ "{% elif part.type == 'audio' %}<|AUDIO|><|audio_eos|>{% endif %}"
+ "{% endfor %}{% endfor %}")
+ processor = CsmProcessor(
+ EncodecFeatureExtractor(feature_size=1, sampling_rate=24000), tokenizer,
+ chat_template=template,
+ )
+ common = dict(hidden_size=16, intermediate_size=32, num_hidden_layers=1,
+ num_attention_heads=2, num_key_value_heads=2)
+ cfg = CsmConfig(
+ **common, vocab_size=9, text_vocab_size=len(vocab), num_codebooks=32,
+ audio_token_id=3, audio_eos_token_id=4, pad_token_id=0, bos_token_id=2,
+ codebook_pad_token_id=8,
+ depth_decoder_config={**common, "backbone_hidden_size": 16,
+ "vocab_size": 9, "num_codebooks": 32},
+ codec_config={"model_type": "mimi", **common, "num_filters": 2,
+ "codebook_size": 8, "codebook_dim": 8,
+ "vector_quantization_hidden_dimension": 8, "num_quantizers": 32,
+ "upsample_groups": 16},
+ )
+ model = CsmForConditionalGeneration(cfg)
+ return processor, model
+
+
+def test_real_processor_padding_and_both_decoder_gradients(tmp_path, tiny_csm_components):
+ import torch
+
+ from soup_cli.trainer.csm import CSMDataCollator, freeze_csm_codec
+
+ processor, model = tiny_csm_components
+ a, b = tmp_path / "a.wav", tmp_path / "b.wav"
+ write_audio(a)
+ write_audio(b, frames=5760)
+ rows = [speech_row(a), speech_row(b, "Hello longer", "1")]
+ original = copy.deepcopy(rows)
+ batch = CSMDataCollator(processor, max_length=128)(rows)
+ assert rows == original
+ assert (batch["labels"][batch["attention_mask"] == 0] == -100).all()
+ assert batch["input_values_cutoffs"].tolist() == [[3840], [5760]]
+ freeze_csm_codec(model)
+ model.train()
+ model.codec_model.eval()
+ out = model(**batch, use_cache=False)
+ assert torch.isfinite(out.loss)
+ assert torch.isfinite(out.backbone_loss) and torch.isfinite(out.depth_decoder_loss)
+ out.loss.backward()
+ for decoder in [model.backbone_model, model.depth_decoder]:
+ assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in decoder.parameters())
+ assert all(p.grad is None and not p.requires_grad for p in model.codec_model.parameters())
+
+
+def test_overlength_audio_frames_are_refused_without_truncation(tmp_path, tiny_csm_components):
+ from soup_cli.trainer.csm import CSMDataCollator
+
+ processor, _ = tiny_csm_components
+ path = tmp_path / "a.wav"
+ write_audio(path)
+ with pytest.raises(ValueError, match="max_length"):
+ CSMDataCollator(processor, max_length=2)([speech_row(path)])
+
+
+def test_reserved_audio_marker_in_transcript_refused(tmp_path, tiny_csm_components):
+ from soup_cli.trainer.csm import CSMDataCollator
+
+ processor, _ = tiny_csm_components
+ with pytest.raises(ValueError, match="control token"):
+ CSMDataCollator(processor, max_length=128)([speech_row(tmp_path / "a", "<|AUDIO|>")])
+
+
[email protected]("rank", [0, 2])
+def test_real_native_setup_train_save_reload_and_resume(tmp_path, tiny_csm_components, rank):
+ import torch
+ from transformers import CsmForConditionalGeneration, CsmProcessor
+
+ from soup_cli.config.schema import SoupConfig
+ from soup_cli.trainer.dispatch import build_trainer
+
+ processor, model = tiny_csm_components
+ base, output = tmp_path / "base", tmp_path / "trained"
+ model.save_pretrained(base)
+ processor.save_pretrained(base)
+ path = tmp_path / "clip.wav"
+ write_audio(path)
+ values = csm_config(
+ epochs=1, batch_size=1, gradient_accumulation_steps=1, lr=0.01,
+ logging_steps=1, save_steps=1, warmup_ratio=0, seed=42, lora={"r": rank},
+ gradient_checkpointing=rank > 0,
+ ).model_dump()
+ values.update(base=str(base), output=str(output))
+ cfg = SoupConfig(**values)
+ dataset = {"train": [speech_row(path), speech_row(path, speaker="1")],
+ "val": [speech_row(path)]}
+ wrapper = build_trainer(cfg, device="cpu")
+ wrapper.setup(dataset)
+ assert wrapper.trainer.model_accepts_loss_kwargs is False
+ if rank:
+ assert all("codec_model" not in name for name, p in wrapper.model.named_parameters()
+ if p.requires_grad)
+ assert any("depth_decoder" in name for name, p in wrapper.model.named_parameters()
+ if p.requires_grad)
+ result = wrapper.train()
+ assert wrapper.trainer.state.global_step == 2
+ assert math.isfinite(result["final_loss"])
+ assert any("eval_loss" in entry for entry in wrapper.trainer.state.log_history)
+ assert not wrapper.model.codec_model.training
+ assert all(p.grad is None for p in wrapper.model.codec_model.parameters())
+ reloaded_processor = CsmProcessor.from_pretrained(output)
+ assert reloaded_processor.chat_template == processor.chat_template
+ if rank:
+ from peft import PeftModel
+
+ reloaded = PeftModel.from_pretrained(
+ CsmForConditionalGeneration.from_pretrained(base), output,
+ )
+ assert any(p.detach().abs().sum() > 0 for name, p in reloaded.named_parameters()
+ if "lora_B" in name)
+ for decoder in ("backbone_model", "depth_decoder"):
+ assert any(p.detach().abs().sum() > 0 for name, p in reloaded.named_parameters()
+ if decoder in name and "lora_B" in name)
+ else:
+ reloaded = CsmForConditionalGeneration.from_pretrained(output)
+ assert any(not torch.equal(before, after)
+ for before, after in zip(model.backbone_model.parameters(),
+ reloaded.backbone_model.parameters()))
+ cfg.training.epochs = 2
+ resumed = build_trainer(cfg, device="cpu")
+ resumed.setup(dataset)
+ resumed.train(resume_from_checkpoint=str(output / "checkpoint-2"))
+ assert resumed.trainer.state.global_step == 4
+
+
+def test_padding_with_audio_token_does_not_invent_targets(tmp_path, tiny_csm_components):
+ import torch
+
+ from soup_cli.trainer.csm import CSMDataCollator, freeze_csm_codec
+
+ processor, model = tiny_csm_components
+ processor.tokenizer.pad_token = processor.audio_token
+ path = tmp_path / "clip.wav"
+ write_audio(path)
+ batch = CSMDataCollator(processor, 128)(
+ [speech_row(path), speech_row(path, "Hello longer longer longer")],
+ )
+ assert (batch["labels"][batch["attention_mask"] == 0] == -100).all()
+ freeze_csm_codec(model)
+ assert torch.isfinite(model(**batch).loss)
+
+
[email protected]("speaker,expected", [("0", 0), ("assistant", 1)])
+def test_cli_dry_run_validates_native_transcript_shape(tmp_path, monkeypatch, speaker, expected):
+ import yaml
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ use_cpu_cli(monkeypatch)
+ path = tmp_path / "clip.wav"
+ write_audio(path)
+ (tmp_path / "speech.jsonl").write_text(json.dumps(speech_row(path, speaker=speaker)) + "\n")
+ (tmp_path / "csm.yaml").write_text(yaml.safe_dump(csm_config().model_dump()))
+ result = CliRunner().invoke(app, ["train", "-c", "csm.yaml", "--dry-run"])
+ assert result.exit_code == expected, (result.output, repr(result.exception))
+ assert ("Ready to train" in strip_ansi(result.output)) == (expected == 0)
+ if expected:
+ assert "CSM train row 1" in strip_ansi(result.output)
+
+
+def test_full_cli_trains_local_native_model(tmp_path, monkeypatch, tiny_csm_components):
+ import yaml
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+ from soup_cli.config.schema import SoupConfig
+
+ monkeypatch.chdir(tmp_path)
+ processor, model = tiny_csm_components
+ base = tmp_path / "base"
+ model.save_pretrained(base)
+ processor.save_pretrained(base)
+ path = tmp_path / "clip.wav"
+ write_audio(path)
+ (tmp_path / "speech.jsonl").write_text(json.dumps(speech_row(path)) + "\n")
+ values = csm_config(
+ epochs=1, batch_size=1, gradient_accumulation_steps=1, logging_steps=1,
+ lora={"r": 2},
+ ).model_dump()
+ values.update(base=str(base), output=str(tmp_path / "trained"))
+ cfg = SoupConfig(**values)
+ (tmp_path / "csm.yaml").write_text(yaml.safe_dump(cfg.model_dump()))
+ # The CLI has no --device flag; isolate this portable test from the host's
+ # accelerator choice while leaving the data/model/trainer/save paths real.
+ use_cpu_cli(monkeypatch)
+ result = CliRunner().invoke(app, ["train", "-c", "csm.yaml", "--yes"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert (tmp_path / "trained" / "adapter_model.safetensors").is_file()
+ from transformers import CsmProcessor
+
+ saved_processor = CsmProcessor.from_pretrained(tmp_path / "trained")
+ assert saved_processor.feature_extractor.sampling_rate == 24000
+ assert saved_processor.chat_template == processor.chat_template
+
+
+def test_csm_imports_keep_heavy_dependencies_lazy():
+ import subprocess
+ import sys
+
+ command = (
+ "import sys; import soup_cli.utils.csm; import soup_cli.trainer.csm; "
+ "assert not {'torch','transformers','peft','trl','mlx'}.intersection(sys.modules)"
+ )
+ result = subprocess.run([sys.executable, "-c", command], capture_output=True, text=True)
+ assert result.returncode == 0, result.stderr
+
+
+def test_native_mps_training_step(tmp_path, tiny_csm_components):
+ import torch
+
+ from soup_cli.config.schema import SoupConfig
+ from soup_cli.trainer.dispatch import build_trainer
+
+ if not torch.backends.mps.is_available():
+ pytest.skip("needs Apple Silicon MPS")
+ processor, model = tiny_csm_components
+ base = tmp_path / "base"
+ model.save_pretrained(base)
+ processor.save_pretrained(base)
+ path = tmp_path / "clip.wav"
+ write_audio(path)
+ values = csm_config(
+ epochs=1, batch_size=1, gradient_accumulation_steps=1, logging_steps=1,
+ lora={"r": 2}, seed=42,
+ ).model_dump()
+ values.update(base=str(base), output=str(tmp_path / "trained"))
+ wrapper = build_trainer(SoupConfig(**values), device="mps")
+ wrapper.setup({"train": [speech_row(path)]})
+ from soup_cli.utils.gpu import mps_supports_bf16
+
+ assert wrapper.trainer.args.device.type == "mps"
+ assert wrapper.trainer.args.bf16 == mps_supports_bf16()
+ assert wrapper.trainer.args.fp16 is False
+ result = wrapper.train()
+ assert math.isfinite(result["final_loss"])
+ assert wrapper.trainer.state.global_step == 1
+ assert all(p.grad is None for p in wrapper.model.codec_model.parameters())
+
+
[email protected]("option", ["loraplus_lr_ratio", "use_lorafa"])
+def test_native_csm_refuses_unimplemented_lora_optimizers(option):
+ with pytest.raises(ValueError, match=option):
+ csm_config(**{option: 16.0 if option == "loraplus_lr_ratio" else True})
+
+
[email protected]("kwargs", [
+ {"deepspeed_config": "ds.json"}, {"fsdp_config": {"fsdp": "full_shard"}},
+])
+def test_native_csm_refuses_distributed_before_loading_any_model(kwargs):
+ from soup_cli.trainer.csm import CSMTrainerWrapper
+
+ wrapper = CSMTrainerWrapper(csm_config(), device="cpu", **kwargs)
+ with pytest.raises(ValueError, match="single-device"):
+ wrapper.setup({})
+ assert wrapper.model is None
+ assert wrapper.trainer is None
+
+
+def test_native_csm_refuses_automatic_cuda_data_parallel(monkeypatch):
+ import torch
+
+ from soup_cli.trainer.csm import CSMTrainerWrapper
+
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ wrapper = CSMTrainerWrapper(csm_config(), device="cuda")
+ with pytest.raises(ValueError, match="CUDA_VISIBLE_DEVICES"):
+ wrapper.setup({})
+ assert wrapper.model is None
+
+
+def test_native_csm_refuses_torchrun_before_loading(monkeypatch):
+ from soup_cli.trainer.csm import CSMTrainerWrapper
+
+ monkeypatch.setenv("WORLD_SIZE", "2")
+ wrapper = CSMTrainerWrapper(csm_config(), device="cpu")
+ with pytest.raises(ValueError, match="single-device"):
+ wrapper.setup({})
+ assert wrapper.model is None