Repository: huggingface/transformers
Pull request: Fix the issue that csm model cannot work with pipeline mode.

# What does this PR do?
Fix the csm model(text_to_audio) cannot work with pipeline mode.

example:
```
import torch
from transformers import pipeline

device = "hpu"
if torch.cuda.is_available():
    device="cuda"

print(f"device: {device}")
tts_pipeline = pipeline(
    "text-to-audio",
    model="sesame/csm-1b",
    device=device
)
generate_kwargs = {
    "output_audio": True,
}

text = "[0]Hello from Sesame."

audio_output = tts_pipeline(text, generate_kwargs=generate_kwargs)
print(f"audio_output: {audio_output}")
audio = audio_output["audio"] if isinstance(audio_output["audio"], torch.Tensor) and len(audio_output["audio"].shape) == 1 else audio_output["audio"][0]
import soundfile as sf
sf.write("example_with_pipeline.wav", audio, samplerate=audio_output["sampling_rate"])
```

Before patch:
<img width="980" height="194" alt="image" src="https://github.com/user-attachments/assets/fdfcebfe-1c9f-4d16-8a7e-d983d17e3b24" />
After patch:
<img width="1036" height="73" alt="image" src="https://github.com/user-attachments/assets/525c7bc1-fc2a-4168-8fb5-2fda3fe1d875" />


Batch inference with original example:

```
import torch
from transformers import CsmForConditionalGeneration, AutoProcessor
model_id = "sesame/csm-1b"

device="hpu"
if torch.cuda.is_available():
    device="cuda"


# load the model and the processor
processor = AutoProcessor.from_pretrained(model_id)
model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=device)

# prepare the inputs
text = ["[0]Hello from Sesame.", "[1]Open sesame."] # `[0]` for speaker id 0
inputs = processor(text, add_special_tokens=True).to(device)

audio = model.generate(**inputs, output_audio=True)
print(f"audio:{audio}")
processor.save_audio(audio, ["1.wav", "2.wav"])
```

Result:
<img width="760" height="59" alt="image" src="https://github.com/user-attachments/assets/b2cca836-ff96-4a0e-9e81-209a83bb6b24" />




<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @eustlb
- graph models: @clefourrier

Library:

- flax: @gante and @Rocketknight1
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @zach-huggingface, @SunMarc and @qgallouedec
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @SunMarc @zach-huggingface
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Changed files:
filename: src/transformers/models/auto/tokenization_auto.py
patch: @@ -167,6 +167,7 @@
             ),
         ),
         ("cpmant", ("CpmAntTokenizer", None)),
+        ("csm", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
         ("ctrl", ("CTRLTokenizer", None)),
         ("data2vec-audio", ("Wav2Vec2CTCTokenizer", None)),
         ("data2vec-text", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),

filename: src/transformers/pipelines/text_to_audio.py
patch: @@ -127,6 +127,10 @@ def __init__(self, *args, vocoder=None, sampling_rate=None, no_processor=True, *
                 sampling_rate = getattr(config, sampling_rate_name, None)
                 if sampling_rate is not None:
                     self.sampling_rate = sampling_rate
+                elif getattr(config, "codec_config", None) is not None:
+                    sampling_rate = getattr(config.codec_config, sampling_rate_name, None)
+                    if sampling_rate is not None:
+                        self.sampling_rate = sampling_rate
 
         # last fallback to get the sampling rate based on processor
         if self.sampling_rate is None and not self.no_processor and hasattr(self.processor, "feature_extractor"):
@@ -247,10 +251,15 @@ def _sanitize_parameters(
     def postprocess(self, audio):
         output_dict = {}
 
+        if self.model.config.model_type == "csm":
+            waveform_key = "audio"
+        else:
+            waveform_key = "waveform"
+
         # We directly get the waveform
         if self.no_processor:
             if isinstance(audio, dict):
-                waveform = audio["waveform"]
+                waveform = audio[waveform_key]
             elif isinstance(audio, tuple):
                 waveform = audio[0]
             else:
@@ -259,7 +268,10 @@ def postprocess(self, audio):
         else:
             waveform = self.processor.decode(audio)
 
-        output_dict["audio"] = waveform.to(device="cpu", dtype=torch.float).numpy()
+        if isinstance(audio, list):
+            output_dict["audio"] = [el.to(device="cpu", dtype=torch.float).numpy() for el in waveform]
+        else:
+            output_dict["audio"] = waveform.to(device="cpu", dtype=torch.float).numpy()
         output_dict["sampling_rate"] = self.sampling_rate
 
         return output_dict

filename: tests/pipelines/test_pipelines_text_to_audio.py
patch: @@ -247,6 +247,26 @@ def test_generative_model_kwargs(self):
         outputs = music_generator("This is a test", forward_params=forward_params, generate_kwargs=generate_kwargs)
         self.assertListEqual(outputs["audio"].tolist(), audio.tolist())
 
+    @slow
+    @require_torch
+    def test_csm_model_pt(self):
+        speech_generator = pipeline(task="text-to-audio", model="sesame/csm-1b", framework="pt")
+
+        outputs = speech_generator("[0]This is a test")
+        self.assertEqual(outputs["sampling_rate"], 24000)
+
+        audio = outputs["audio"]
+        self.assertEqual(ANY(np.ndarray), audio)
+
+        # test two examples side-by-side
+        outputs = speech_generator(["[0]This is a test", "[0]This is a second test"])
+        audio = [output["audio"] for output in outputs]
+        self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio)
+
+        # test batching
+        outputs = speech_generator(["[0]This is a test", "[0]This is a second test"], batch_size=2)
+        self.assertEqual(ANY(np.ndarray), outputs[0]["audio"])
+
     def get_test_pipeline(
         self,
         model,