[
  {
    "path": ".gitignore",
    "content": "# Python\n__pycache__/\n*.py[cod]\n*$py.class\n*.so\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# Virtual Environment\n.env\n.venv\nenv/\nvenv/\nENV/\n\n# IDE\n.idea/\n.vscode/\n*.swp\n*.swo\n\n# Project specific\n.python-version\n*.wav\noutput_*/\nbasic_audio.wav\nfull_conversation.wav\ncontext_audio.wav\n\n# Model files\n*.pt\n*.ckpt"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# CSM\n\n**2025/05/20** - CSM is availabile natively in [Hugging Face Transformers](https://huggingface.co/docs/transformers/main/en/model_doc/csm) 🤗 as of version `4.52.1`, more info available [in our model repo](https://huggingface.co/sesame/csm-1b)\n\n**2025/03/13** - We are releasing the 1B CSM variant. The checkpoint is [hosted on Hugging Face](https://huggingface.co/sesame/csm_1b).\n\n---\n\nCSM (Conversational Speech Model) is a speech generation model from [Sesame](https://www.sesame.com) that generates RVQ audio codes from text and audio inputs. The model architecture employs a [Llama](https://www.llama.com/) backbone and a smaller audio decoder that produces [Mimi](https://huggingface.co/kyutai/mimi) audio codes.\n\nA fine-tuned variant of CSM powers the [interactive voice demo](https://www.sesame.com/voicedemo) shown in our [blog post](https://www.sesame.com/research/crossing_the_uncanny_valley_of_voice).\n\nA hosted [Hugging Face space](https://huggingface.co/spaces/sesame/csm-1b) is also available for testing audio generation.\n\n## Requirements\n\n* A CUDA-compatible GPU\n* The code has been tested on CUDA 12.4 and 12.6, but it may also work on other versions\n* Similarly, Python 3.10 is recommended, but newer versions may be fine\n* For some audio operations, `ffmpeg` may be required\n* Access to the following Hugging Face models:\n  * [Llama-3.2-1B](https://huggingface.co/meta-llama/Llama-3.2-1B)\n  * [CSM-1B](https://huggingface.co/sesame/csm-1b)\n\n### Setup\n\n```bash\ngit clone git@github.com:SesameAILabs/csm.git\ncd csm\npython3.10 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\n# Disable lazy compilation in Mimi\nexport NO_TORCH_COMPILE=1\n\n# You will need access to CSM-1B and Llama-3.2-1B\nhuggingface-cli login\n```\n\n### Windows Setup\n\nThe `triton` package cannot be installed in Windows. Instead use `pip install triton-windows`.\n\n## Quickstart\n\nThis script will generate a conversation between 2 characters, using a prompt for each character.\n\n```bash\npython run_csm.py\n```\n\n## Usage\n\nIf you want to write your own applications with CSM, the following examples show basic usage.\n\n#### Generate a sentence\n\nThis will use a random speaker identity, as no prompt or context is provided.\n\n```python\nfrom generator import load_csm_1b\nimport torchaudio\nimport torch\n\nif torch.backends.mps.is_available():\n    device = \"mps\"\nelif torch.cuda.is_available():\n    device = \"cuda\"\nelse:\n    device = \"cpu\"\n\ngenerator = load_csm_1b(device=device)\n\naudio = generator.generate(\n    text=\"Hello from Sesame.\",\n    speaker=0,\n    context=[],\n    max_audio_length_ms=10_000,\n)\n\ntorchaudio.save(\"audio.wav\", audio.unsqueeze(0).cpu(), generator.sample_rate)\n```\n\n#### Generate with context\n\nCSM sounds best when provided with context. You can prompt or provide context to the model using a `Segment` for each speaker's utterance.\n\nNOTE: The following example is instructional and the audio files do not exist. It is intended as an example for using context with CSM.\n\n```python\nfrom generator import Segment\n\nspeakers = [0, 1, 0, 0]\ntranscripts = [\n    \"Hey how are you doing.\",\n    \"Pretty good, pretty good.\",\n    \"I'm great.\",\n    \"So happy to be speaking to you.\",\n]\naudio_paths = [\n    \"utterance_0.wav\",\n    \"utterance_1.wav\",\n    \"utterance_2.wav\",\n    \"utterance_3.wav\",\n]\n\ndef load_audio(audio_path):\n    audio_tensor, sample_rate = torchaudio.load(audio_path)\n    audio_tensor = torchaudio.functional.resample(\n        audio_tensor.squeeze(0), orig_freq=sample_rate, new_freq=generator.sample_rate\n    )\n    return audio_tensor\n\nsegments = [\n    Segment(text=transcript, speaker=speaker, audio=load_audio(audio_path))\n    for transcript, speaker, audio_path in zip(transcripts, speakers, audio_paths)\n]\naudio = generator.generate(\n    text=\"Me too, this is some cool stuff huh?\",\n    speaker=1,\n    context=segments,\n    max_audio_length_ms=10_000,\n)\n\ntorchaudio.save(\"audio.wav\", audio.unsqueeze(0).cpu(), generator.sample_rate)\n```\n\n## FAQ\n\n**Does this model come with any voices?**\n\nThe model open-sourced here is a base generation model. It is capable of producing a variety of voices, but it has not been fine-tuned on any specific voice.\n\n**Can I converse with the model?**\n\nCSM is trained to be an audio generation model and not a general-purpose multimodal LLM. It cannot generate text. We suggest using a separate LLM for text generation.\n\n**Does it support other languages?**\n\nThe model has some capacity for non-English languages due to data contamination in the training data, but it likely won't do well.\n\n## Misuse and abuse ⚠️\n\nThis project provides a high-quality speech generation model for research and educational purposes. While we encourage responsible and ethical use, we **explicitly prohibit** the following:\n\n- **Impersonation or Fraud**: Do not use this model to generate speech that mimics real individuals without their explicit consent.\n- **Misinformation or Deception**: Do not use this model to create deceptive or misleading content, such as fake news or fraudulent calls.\n- **Illegal or Harmful Activities**: Do not use this model for any illegal, harmful, or malicious purposes.\n\nBy using this model, you agree to comply with all applicable laws and ethical guidelines. We are **not responsible** for any misuse, and we strongly condemn unethical applications of this technology.\n\n---\n\n## Authors\nJohan Schalkwyk, Ankit Kumar, Dan Lyth, Sefik Emre Eskimez, Zack Hodari, Cinjon Resnick, Ramon Sanabria, Raven Jiang, and the Sesame team.\n"
  },
  {
    "path": "generator.py",
    "content": "from dataclasses import dataclass\nfrom typing import List, Tuple\n\nimport torch\nimport torchaudio\nfrom huggingface_hub import hf_hub_download\nfrom models import Model\nfrom moshi.models import loaders\nfrom tokenizers.processors import TemplateProcessing\nfrom transformers import AutoTokenizer\nfrom watermarking import CSM_1B_GH_WATERMARK, load_watermarker, watermark\n\n\n@dataclass\nclass Segment:\n    speaker: int\n    text: str\n    # (num_samples,), sample_rate = 24_000\n    audio: torch.Tensor\n\n\ndef load_llama3_tokenizer():\n    \"\"\"\n    https://github.com/huggingface/transformers/issues/22794#issuecomment-2092623992\n    \"\"\"\n    tokenizer_name = \"meta-llama/Llama-3.2-1B\"\n    tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)\n    bos = tokenizer.bos_token\n    eos = tokenizer.eos_token\n    tokenizer._tokenizer.post_processor = TemplateProcessing(\n        single=f\"{bos}:0 $A:0 {eos}:0\",\n        pair=f\"{bos}:0 $A:0 {eos}:0 {bos}:1 $B:1 {eos}:1\",\n        special_tokens=[(f\"{bos}\", tokenizer.bos_token_id), (f\"{eos}\", tokenizer.eos_token_id)],\n    )\n\n    return tokenizer\n\n\nclass Generator:\n    def __init__(\n        self,\n        model: Model,\n    ):\n        self._model = model\n        self._model.setup_caches(1)\n\n        self._text_tokenizer = load_llama3_tokenizer()\n\n        device = next(model.parameters()).device\n        mimi_weight = hf_hub_download(loaders.DEFAULT_REPO, loaders.MIMI_NAME)\n        mimi = loaders.get_mimi(mimi_weight, device=device)\n        mimi.set_num_codebooks(32)\n        self._audio_tokenizer = mimi\n\n        self._watermarker = load_watermarker(device=device)\n\n        self.sample_rate = mimi.sample_rate\n        self.device = device\n\n    def _tokenize_text_segment(self, text: str, speaker: int) -> Tuple[torch.Tensor, torch.Tensor]:\n        frame_tokens = []\n        frame_masks = []\n\n        text_tokens = self._text_tokenizer.encode(f\"[{speaker}]{text}\")\n        text_frame = torch.zeros(len(text_tokens), 33).long()\n        text_frame_mask = torch.zeros(len(text_tokens), 33).bool()\n        text_frame[:, -1] = torch.tensor(text_tokens)\n        text_frame_mask[:, -1] = True\n\n        frame_tokens.append(text_frame.to(self.device))\n        frame_masks.append(text_frame_mask.to(self.device))\n\n        return torch.cat(frame_tokens, dim=0), torch.cat(frame_masks, dim=0)\n\n    def _tokenize_audio(self, audio: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n        assert audio.ndim == 1, \"Audio must be single channel\"\n\n        frame_tokens = []\n        frame_masks = []\n\n        # (K, T)\n        audio = audio.to(self.device)\n        audio_tokens = self._audio_tokenizer.encode(audio.unsqueeze(0).unsqueeze(0))[0]\n        # add EOS frame\n        eos_frame = torch.zeros(audio_tokens.size(0), 1).to(self.device)\n        audio_tokens = torch.cat([audio_tokens, eos_frame], dim=1)\n\n        audio_frame = torch.zeros(audio_tokens.size(1), 33).long().to(self.device)\n        audio_frame_mask = torch.zeros(audio_tokens.size(1), 33).bool().to(self.device)\n        audio_frame[:, :-1] = audio_tokens.transpose(0, 1)\n        audio_frame_mask[:, :-1] = True\n\n        frame_tokens.append(audio_frame)\n        frame_masks.append(audio_frame_mask)\n\n        return torch.cat(frame_tokens, dim=0), torch.cat(frame_masks, dim=0)\n\n    def _tokenize_segment(self, segment: Segment) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Returns:\n            (seq_len, 33), (seq_len, 33)\n        \"\"\"\n        text_tokens, text_masks = self._tokenize_text_segment(segment.text, segment.speaker)\n        audio_tokens, audio_masks = self._tokenize_audio(segment.audio)\n\n        return torch.cat([text_tokens, audio_tokens], dim=0), torch.cat([text_masks, audio_masks], dim=0)\n\n    @torch.inference_mode()\n    def generate(\n        self,\n        text: str,\n        speaker: int,\n        context: List[Segment],\n        max_audio_length_ms: float = 90_000,\n        temperature: float = 0.9,\n        topk: int = 50,\n    ) -> torch.Tensor:\n        self._model.reset_caches()\n\n        max_generation_len = int(max_audio_length_ms / 80)\n        tokens, tokens_mask = [], []\n        for segment in context:\n            segment_tokens, segment_tokens_mask = self._tokenize_segment(segment)\n            tokens.append(segment_tokens)\n            tokens_mask.append(segment_tokens_mask)\n\n        gen_segment_tokens, gen_segment_tokens_mask = self._tokenize_text_segment(text, speaker)\n        tokens.append(gen_segment_tokens)\n        tokens_mask.append(gen_segment_tokens_mask)\n\n        prompt_tokens = torch.cat(tokens, dim=0).long().to(self.device)\n        prompt_tokens_mask = torch.cat(tokens_mask, dim=0).bool().to(self.device)\n\n        samples = []\n        curr_tokens = prompt_tokens.unsqueeze(0)\n        curr_tokens_mask = prompt_tokens_mask.unsqueeze(0)\n        curr_pos = torch.arange(0, prompt_tokens.size(0)).unsqueeze(0).long().to(self.device)\n\n        max_seq_len = 2048\n        max_context_len = max_seq_len - max_generation_len\n        if curr_tokens.size(1) >= max_context_len:\n            raise ValueError(\n                f\"Inputs too long, must be below max_seq_len - max_generation_len: {max_context_len}\"\n            )\n\n        for _ in range(max_generation_len):\n            sample = self._model.generate_frame(curr_tokens, curr_tokens_mask, curr_pos, temperature, topk)\n            if torch.all(sample == 0):\n                break  # eos\n\n            samples.append(sample)\n\n            curr_tokens = torch.cat([sample, torch.zeros(1, 1).long().to(self.device)], dim=1).unsqueeze(1)\n            curr_tokens_mask = torch.cat(\n                [torch.ones_like(sample).bool(), torch.zeros(1, 1).bool().to(self.device)], dim=1\n            ).unsqueeze(1)\n            curr_pos = curr_pos[:, -1:] + 1\n\n        audio = self._audio_tokenizer.decode(torch.stack(samples).permute(1, 2, 0)).squeeze(0).squeeze(0)\n\n        # This applies an imperceptible watermark to identify audio as AI-generated.\n        # Watermarking ensures transparency, dissuades misuse, and enables traceability.\n        # Please be a responsible AI citizen and keep the watermarking in place.\n        # If using CSM 1B in another application, use your own private key and keep it secret.\n        audio, wm_sample_rate = watermark(self._watermarker, audio, self.sample_rate, CSM_1B_GH_WATERMARK)\n        audio = torchaudio.functional.resample(audio, orig_freq=wm_sample_rate, new_freq=self.sample_rate)\n\n        return audio\n\n\ndef load_csm_1b(device: str = \"cuda\") -> Generator:\n    model = Model.from_pretrained(\"sesame/csm-1b\")\n    model.to(device=device, dtype=torch.bfloat16)\n\n    generator = Generator(model)\n    return generator"
  },
  {
    "path": "models.py",
    "content": "from dataclasses import dataclass\n\nimport torch\nimport torch.nn as nn\nimport torchtune\nfrom huggingface_hub import PyTorchModelHubMixin\nfrom torchtune.models import llama3_2\n\n\ndef llama3_2_1B() -> torchtune.modules.transformer.TransformerDecoder:\n    return llama3_2.llama3_2(\n        vocab_size=128_256,\n        num_layers=16,\n        num_heads=32,\n        num_kv_heads=8,\n        embed_dim=2048,\n        max_seq_len=2048,\n        intermediate_dim=8192,\n        attn_dropout=0.0,\n        norm_eps=1e-5,\n        rope_base=500_000,\n        scale_factor=32,\n    )\n\n\ndef llama3_2_100M() -> torchtune.modules.transformer.TransformerDecoder:\n    return llama3_2.llama3_2(\n        vocab_size=128_256,\n        num_layers=4,\n        num_heads=8,\n        num_kv_heads=2,\n        embed_dim=1024,\n        max_seq_len=2048,\n        intermediate_dim=8192,\n        attn_dropout=0.0,\n        norm_eps=1e-5,\n        rope_base=500_000,\n        scale_factor=32,\n    )\n\n\nFLAVORS = {\n    \"llama-1B\": llama3_2_1B,\n    \"llama-100M\": llama3_2_100M,\n}\n\n\ndef _prepare_transformer(model):\n    embed_dim = model.tok_embeddings.embedding_dim\n    model.tok_embeddings = nn.Identity()\n    model.output = nn.Identity()\n    return model, embed_dim\n\n\ndef _create_causal_mask(seq_len: int, device: torch.device):\n    return torch.tril(torch.ones(seq_len, seq_len, dtype=torch.bool, device=device))\n\n\ndef _index_causal_mask(mask: torch.Tensor, input_pos: torch.Tensor):\n    \"\"\"\n    Args:\n        mask: (max_seq_len, max_seq_len)\n        input_pos: (batch_size, seq_len)\n\n    Returns:\n        (batch_size, seq_len, max_seq_len)\n    \"\"\"\n    r = mask[input_pos, :]\n    return r\n\n\ndef _multinomial_sample_one_no_sync(probs):  # Does multinomial sampling without a cuda synchronization\n    q = torch.empty_like(probs).exponential_(1)\n    return torch.argmax(probs / q, dim=-1, keepdim=True).to(dtype=torch.int)\n\n\ndef sample_topk(logits: torch.Tensor, topk: int, temperature: float):\n    logits = logits / temperature\n\n    filter_value: float = -float(\"Inf\")\n    indices_to_remove = logits < torch.topk(logits, topk)[0][..., -1, None]\n    scores_processed = logits.masked_fill(indices_to_remove, filter_value)\n    scores_processed = torch.nn.functional.log_softmax(scores_processed, dim=-1)\n    probs = torch.nn.functional.softmax(scores_processed, dim=-1)\n\n    sample_token = _multinomial_sample_one_no_sync(probs)\n    return sample_token\n\n\n@dataclass\nclass ModelArgs:\n    backbone_flavor: str\n    decoder_flavor: str\n    text_vocab_size: int\n    audio_vocab_size: int\n    audio_num_codebooks: int\n\n\nclass Model(\n    nn.Module,\n    PyTorchModelHubMixin,\n    repo_url=\"https://github.com/SesameAILabs/csm\",\n    pipeline_tag=\"text-to-speech\",\n    license=\"apache-2.0\",\n):\n    def __init__(self, config: ModelArgs):\n        super().__init__()\n        self.config = config\n\n        self.backbone, backbone_dim = _prepare_transformer(FLAVORS[config.backbone_flavor]())\n        self.decoder, decoder_dim = _prepare_transformer(FLAVORS[config.decoder_flavor]())\n\n        self.text_embeddings = nn.Embedding(config.text_vocab_size, backbone_dim)\n        self.audio_embeddings = nn.Embedding(config.audio_vocab_size * config.audio_num_codebooks, backbone_dim)\n\n        self.projection = nn.Linear(backbone_dim, decoder_dim, bias=False)\n        self.codebook0_head = nn.Linear(backbone_dim, config.audio_vocab_size, bias=False)\n        self.audio_head = nn.Parameter(torch.empty(config.audio_num_codebooks - 1, decoder_dim, config.audio_vocab_size))\n\n    def setup_caches(self, max_batch_size: int) -> torch.Tensor:\n        \"\"\"Setup KV caches and return a causal mask.\"\"\"\n        dtype = next(self.parameters()).dtype\n        device = next(self.parameters()).device\n\n        with device:\n            self.backbone.setup_caches(max_batch_size, dtype)\n            self.decoder.setup_caches(max_batch_size, dtype, decoder_max_seq_len=self.config.audio_num_codebooks)\n\n        self.register_buffer(\"backbone_causal_mask\", _create_causal_mask(self.backbone.max_seq_len, device))\n        self.register_buffer(\"decoder_causal_mask\", _create_causal_mask(self.config.audio_num_codebooks, device))\n\n    def generate_frame(\n        self,\n        tokens: torch.Tensor,\n        tokens_mask: torch.Tensor,\n        input_pos: torch.Tensor,\n        temperature: float,\n        topk: int,\n    ) -> torch.Tensor:\n        \"\"\"\n        Args:\n            tokens: (batch_size, seq_len, audio_num_codebooks+1)\n            tokens_mask: (batch_size, seq_len, audio_num_codebooks+1)\n            input_pos: (batch_size, seq_len) positions for each token\n            mask: (batch_size, seq_len, max_seq_len\n\n        Returns:\n            (batch_size, audio_num_codebooks) sampled tokens\n        \"\"\"\n        dtype = next(self.parameters()).dtype\n        b, s, _ = tokens.size()\n\n        assert self.backbone.caches_are_enabled(), \"backbone caches are not enabled\"\n        curr_backbone_mask = _index_causal_mask(self.backbone_causal_mask, input_pos)\n        embeds = self._embed_tokens(tokens)\n        masked_embeds = embeds * tokens_mask.unsqueeze(-1)\n        h = masked_embeds.sum(dim=2)\n        h = self.backbone(h, input_pos=input_pos, mask=curr_backbone_mask).to(dtype=dtype)\n\n        last_h = h[:, -1, :]\n        c0_logits = self.codebook0_head(last_h)\n        c0_sample = sample_topk(c0_logits, topk, temperature)\n        c0_embed = self._embed_audio(0, c0_sample)\n\n        curr_h = torch.cat([last_h.unsqueeze(1), c0_embed], dim=1)\n        curr_sample = c0_sample.clone()\n        curr_pos = torch.arange(0, curr_h.size(1), device=curr_h.device).unsqueeze(0).repeat(curr_h.size(0), 1)\n\n        # Decoder caches must be reset every frame.\n        self.decoder.reset_caches()\n        for i in range(1, self.config.audio_num_codebooks):\n            curr_decoder_mask = _index_causal_mask(self.decoder_causal_mask, curr_pos)\n            decoder_h = self.decoder(self.projection(curr_h), input_pos=curr_pos, mask=curr_decoder_mask).to(\n                dtype=dtype\n            )\n            ci_logits = torch.mm(decoder_h[:, -1, :], self.audio_head[i - 1])\n            ci_sample = sample_topk(ci_logits, topk, temperature)\n            ci_embed = self._embed_audio(i, ci_sample)\n\n            curr_h = ci_embed\n            curr_sample = torch.cat([curr_sample, ci_sample], dim=1)\n            curr_pos = curr_pos[:, -1:] + 1\n\n        return curr_sample\n\n    def reset_caches(self):\n        self.backbone.reset_caches()\n        self.decoder.reset_caches()\n\n    def _embed_audio(self, codebook: int, tokens: torch.Tensor) -> torch.Tensor:\n        return self.audio_embeddings(tokens + codebook * self.config.audio_vocab_size)\n\n    def _embed_tokens(self, tokens: torch.Tensor) -> torch.Tensor:\n        text_embeds = self.text_embeddings(tokens[:, :, -1]).unsqueeze(-2)\n\n        audio_tokens = tokens[:, :, :-1] + (\n            self.config.audio_vocab_size * torch.arange(self.config.audio_num_codebooks, device=tokens.device)\n        )\n        audio_embeds = self.audio_embeddings(audio_tokens.view(-1)).reshape(\n            tokens.size(0), tokens.size(1), self.config.audio_num_codebooks, -1\n        )\n\n        return torch.cat([audio_embeds, text_embeds], dim=-2)\n"
  },
  {
    "path": "requirements.txt",
    "content": "torch==2.4.0\ntorchaudio==2.4.0\ntokenizers==0.21.0\ntransformers==4.49.0\nhuggingface_hub==0.28.1\nmoshi==0.2.2\ntorchtune==0.4.0\ntorchao==0.9.0\nsilentcipher @ git+https://github.com/SesameAILabs/silentcipher@master"
  },
  {
    "path": "run_csm.py",
    "content": "import os\nimport torch\nimport torchaudio\nfrom huggingface_hub import hf_hub_download\nfrom generator import load_csm_1b, Segment\nfrom dataclasses import dataclass\n\n# Disable Triton compilation\nos.environ[\"NO_TORCH_COMPILE\"] = \"1\"\n\n# Default prompts are available at https://hf.co/sesame/csm-1b\nprompt_filepath_conversational_a = hf_hub_download(\n    repo_id=\"sesame/csm-1b\",\n    filename=\"prompts/conversational_a.wav\"\n)\nprompt_filepath_conversational_b = hf_hub_download(\n    repo_id=\"sesame/csm-1b\",\n    filename=\"prompts/conversational_b.wav\"\n)\n\nSPEAKER_PROMPTS = {\n    \"conversational_a\": {\n        \"text\": (\n            \"like revising for an exam I'd have to try and like keep up the momentum because I'd \"\n            \"start really early I'd be like okay I'm gonna start revising now and then like \"\n            \"you're revising for ages and then I just like start losing steam I didn't do that \"\n            \"for the exam we had recently to be fair that was a more of a last minute scenario \"\n            \"but like yeah I'm trying to like yeah I noticed this yesterday that like Mondays I \"\n            \"sort of start the day with this not like a panic but like a\"\n        ),\n        \"audio\": prompt_filepath_conversational_a\n    },\n    \"conversational_b\": {\n        \"text\": (\n            \"like a super Mario level. Like it's very like high detail. And like, once you get \"\n            \"into the park, it just like, everything looks like a computer game and they have all \"\n            \"these, like, you know, if, if there's like a, you know, like in a Mario game, they \"\n            \"will have like a question block. And if you like, you know, punch it, a coin will \"\n            \"come out. So like everyone, when they come into the park, they get like this little \"\n            \"bracelet and then you can go punching question blocks around.\"\n        ),\n        \"audio\": prompt_filepath_conversational_b\n    }\n}\n\ndef load_prompt_audio(audio_path: str, target_sample_rate: int) -> torch.Tensor:\n    audio_tensor, sample_rate = torchaudio.load(audio_path)\n    audio_tensor = audio_tensor.squeeze(0)\n    # Resample is lazy so we can always call it\n    audio_tensor = torchaudio.functional.resample(\n        audio_tensor, orig_freq=sample_rate, new_freq=target_sample_rate\n    )\n    return audio_tensor\n\ndef prepare_prompt(text: str, speaker: int, audio_path: str, sample_rate: int) -> Segment:\n    audio_tensor = load_prompt_audio(audio_path, sample_rate)\n    return Segment(text=text, speaker=speaker, audio=audio_tensor)\n\ndef main():\n    # Select the best available device, skipping MPS due to float64 limitations\n    if torch.cuda.is_available():\n        device = \"cuda\"\n    else:\n        device = \"cpu\"\n    print(f\"Using device: {device}\")\n\n    # Load model\n    generator = load_csm_1b(device)\n\n    # Prepare prompts\n    prompt_a = prepare_prompt(\n        SPEAKER_PROMPTS[\"conversational_a\"][\"text\"],\n        0,\n        SPEAKER_PROMPTS[\"conversational_a\"][\"audio\"],\n        generator.sample_rate\n    )\n\n    prompt_b = prepare_prompt(\n        SPEAKER_PROMPTS[\"conversational_b\"][\"text\"],\n        1,\n        SPEAKER_PROMPTS[\"conversational_b\"][\"audio\"],\n        generator.sample_rate\n    )\n\n    # Generate conversation\n    conversation = [\n        {\"text\": \"Hey how are you doing?\", \"speaker_id\": 0},\n        {\"text\": \"Pretty good, pretty good. How about you?\", \"speaker_id\": 1},\n        {\"text\": \"I'm great! So happy to be speaking with you today.\", \"speaker_id\": 0},\n        {\"text\": \"Me too! This is some cool stuff, isn't it?\", \"speaker_id\": 1}\n    ]\n\n    # Generate each utterance\n    generated_segments = []\n    prompt_segments = [prompt_a, prompt_b]\n\n    for utterance in conversation:\n        print(f\"Generating: {utterance['text']}\")\n        audio_tensor = generator.generate(\n            text=utterance['text'],\n            speaker=utterance['speaker_id'],\n            context=prompt_segments + generated_segments,\n            max_audio_length_ms=10_000,\n        )\n        generated_segments.append(Segment(text=utterance['text'], speaker=utterance['speaker_id'], audio=audio_tensor))\n\n    # Concatenate all generations\n    all_audio = torch.cat([seg.audio for seg in generated_segments], dim=0)\n    torchaudio.save(\n        \"full_conversation.wav\",\n        all_audio.unsqueeze(0).cpu(),\n        generator.sample_rate\n    )\n    print(\"Successfully generated full_conversation.wav\")\n\nif __name__ == \"__main__\":\n    main() "
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup, find_packages\nimport os\n\n# Read requirements from requirements.txt\nwith open('requirements.txt') as f:\n    requirements = [line.strip() for line in f if line.strip() and not line.startswith('#')]\n\nsetup(\n    name='csm',\n    version='0.1.0',\n    packages=find_packages(),\n    install_requires=requirements,\n)\n"
  },
  {
    "path": "watermarking.py",
    "content": "import argparse\n\nimport silentcipher\nimport torch\nimport torchaudio\n\n# This watermark key is public, it is not secure.\n# If using CSM 1B in another application, use a new private key and keep it secret.\nCSM_1B_GH_WATERMARK = [212, 211, 146, 56, 201]\n\n\ndef cli_check_audio() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--audio_path\", type=str, required=True)\n    args = parser.parse_args()\n\n    check_audio_from_file(args.audio_path)\n\n\ndef load_watermarker(device: str = \"cuda\") -> silentcipher.server.Model:\n    model = silentcipher.get_model(\n        model_type=\"44.1k\",\n        device=device,\n    )\n    return model\n\n\n@torch.inference_mode()\ndef watermark(\n    watermarker: silentcipher.server.Model,\n    audio_array: torch.Tensor,\n    sample_rate: int,\n    watermark_key: list[int],\n) -> tuple[torch.Tensor, int]:\n    audio_array_44khz = torchaudio.functional.resample(audio_array, orig_freq=sample_rate, new_freq=44100)\n    encoded, _ = watermarker.encode_wav(audio_array_44khz, 44100, watermark_key, calc_sdr=False, message_sdr=36)\n\n    output_sample_rate = min(44100, sample_rate)\n    encoded = torchaudio.functional.resample(encoded, orig_freq=44100, new_freq=output_sample_rate)\n    return encoded, output_sample_rate\n\n\n@torch.inference_mode()\ndef verify(\n    watermarker: silentcipher.server.Model,\n    watermarked_audio: torch.Tensor,\n    sample_rate: int,\n    watermark_key: list[int],\n) -> bool:\n    watermarked_audio_44khz = torchaudio.functional.resample(watermarked_audio, orig_freq=sample_rate, new_freq=44100)\n    result = watermarker.decode_wav(watermarked_audio_44khz, 44100, phase_shift_decoding=True)\n\n    is_watermarked = result[\"status\"]\n    if is_watermarked:\n        is_csm_watermarked = result[\"messages\"][0] == watermark_key\n    else:\n        is_csm_watermarked = False\n\n    return is_watermarked and is_csm_watermarked\n\n\ndef check_audio_from_file(audio_path: str) -> None:\n    watermarker = load_watermarker(device=\"cuda\")\n\n    audio_array, sample_rate = load_audio(audio_path)\n    is_watermarked = verify(watermarker, audio_array, sample_rate, CSM_1B_GH_WATERMARK)\n\n    outcome = \"Watermarked\" if is_watermarked else \"Not watermarked\"\n    print(f\"{outcome}: {audio_path}\")\n\n\ndef load_audio(audio_path: str) -> tuple[torch.Tensor, int]:\n    audio_array, sample_rate = torchaudio.load(audio_path)\n    audio_array = audio_array.mean(dim=0)\n    return audio_array, int(sample_rate)\n\n\nif __name__ == \"__main__\":\n    cli_check_audio()\n"
  }
]