Views
No views yet
4.52.11import torch
2from transformers import CsmForConditionalGeneration, AutoProcessor
3
4model_id = "sesame/csm-1b"
5device = "cuda" if torch.cuda.is_available() else "cpu"
6
7# load the model and the processor
8processor = AutoProcessor.from_pretrained(model_id)
9model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=device)
10
11# prepare the inputs
12text = "[0]Hello from Sesame." # `[0]` for speaker id 0
13inputs = processor(text, add_special_tokens=True).to(device)
14
15# another equivalent way to prepare the inputs
16conversation = [
17 {"role": "0", "content": [{"type": "text", "text": "Hello from Sesame."}]},
18]
19inputs = processor.apply_chat_template(
20 conversation,
21 tokenize=True,
22 return_dict=True,
23).to(device)
24
25# infer the model
26audio = model.generate(**inputs, output_audio=True)
27processor.save_audio(audio, "example_without_context.wav")1import torch
2from transformers import CsmForConditionalGeneration, AutoProcessor
3from datasets import load_dataset, Audio
4
5model_id = "sesame/csm-1b"
6device = "cuda" if torch.cuda.is_available() else "cpu"
7
8# load the model and the processor
9processor = AutoProcessor.from_pretrained(model_id)
10model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=device)
11
12# prepare the inputs
13ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
14# ensure the audio is 24kHz
15ds = ds.cast_column("audio", Audio(sampling_rate=24000))
16conversation = []
17
18# 1. context
19for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
20 conversation.append(
21 {
22 "role": f"{speaker_id}",
23 "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
24 }
25 )
26
27# 2. text prompt
28conversation.append({"role": f"{ds[4]['speaker_id']}", "content": [{"type": "text", "text": ds[4]["text"]}]})
29
30inputs = processor.apply_chat_template(
31 conversation,
32 tokenize=True,
33 return_dict=True,
34).to(device)
35
36# infer the model
37audio = model.generate(**inputs, output_audio=True)
38processor.save_audio(audio, "example_with_context.wav")1import torch
2from transformers import CsmForConditionalGeneration, AutoProcessor
3from datasets import load_dataset, Audio
4
5model_id = "sesame/csm-1b"
6device = "cuda" if torch.cuda.is_available() else "cpu"
7
8# load the model and the processor
9processor = AutoProcessor.from_pretrained(model_id)
10model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=device)
11
12# prepare the inputs
13ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
14# ensure the audio is 24kHz
15ds = ds.cast_column("audio", Audio(sampling_rate=24000))
16# here a batch with two prompts
17conversation = [
18 [
19 {
20 "role": f"{ds[0]['speaker_id']}",
21 "content": [
22 {"type": "text", "text": ds[0]["text"]},
23 {"type": "audio", "path": ds[0]["audio"]["array"]},
24 ],
25 },
26 {
27 "role": f"{ds[1]['speaker_id']}",
28 "content": [
29 {"type": "text", "text": ds[1]["text"]},
30 ],
31 },
32 ],
33 [
34 {
35 "role": f"{ds[0]['speaker_id']}",
36 "content": [
37 {"type": "text", "text": ds[0]["text"]},
38 ],
39 }
40 ],
41]
42inputs = processor.apply_chat_template(
43 conversation,
44 tokenize=True,
45 return_dict=True,
46).to(device)
47
48audio = model.generate(**inputs, output_audio=True)
49processor.save_audio(audio, [f"speech_batch_idx_{i}.wav" for i in range(len(audio))])1import torch
2import copy
3from transformers import CsmForConditionalGeneration, AutoProcessor
4from datasets import load_dataset
5
6model_id = "sesame/csm-1b"
7device = "cuda"
8
9# set logs to ensure no recompilation and graph breaks
10torch._logging.set_logs(graph_breaks=True, recompiles=True, cudagraphs=True)
11
12# load the model and the processor
13processor = AutoProcessor.from_pretrained(model_id)
14model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=device)
15
16# use static cache, enabling automatically torch compile with fullgraph and reduce-overhead
17model.generation_config.max_length = 250 # big enough to avoid recompilation
18model.generation_config.max_new_tokens = None # would take precedence over max_length
19model.generation_config.cache_implementation = "static"
20model.depth_decoder.generation_config.cache_implementation = "static"
21
22# generation kwargs
23gen_kwargs = {
24 "do_sample": False,
25 "depth_decoder_do_sample": False,
26 "temperature": 1.0,
27 "depth_decoder_temperature": 1.0,
28}
29
30# Define a timing decorator
31class TimerContext:
32 def __init__(self, name="Execution"):
33 self.name = name
34 self.start_event = None
35 self.end_event = None
36
37 def __enter__(self):
38 # Use CUDA events for more accurate GPU timing
39 self.start_event = torch.cuda.Event(enable_timing=True)
40 self.end_event = torch.cuda.Event(enable_timing=True)
41 self.start_event.record()
42 return self
43
44 def __exit__(self, *args):
45 self.end_event.record()
46 torch.cuda.synchronize()
47 elapsed_time = self.start_event.elapsed_time(self.end_event) / 1000.0
48 print(f"{self.name} time: {elapsed_time:.4f} seconds")
49
50# prepare the inputs
51ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
52
53conversation = [
54 {
55 "role": f"{ds[0]['speaker_id']}",
56 "content": [
57 {"type": "text", "text": ds[0]["text"]},
58 {"type": "audio", "path": ds[0]["audio"]["array"]},
59 ],
60 },
61 {
62 "role": f"{ds[1]['speaker_id']}",
63 "content": [
64 {"type": "text", "text": ds[1]["text"]},
65 {"type": "audio", "path": ds[1]["audio"]["array"]},
66 ],
67 },
68 {
69 "role": f"{ds[2]['speaker_id']}",
70 "content": [
71 {"type": "text", "text": ds[2]["text"]},
72 ],
73 },
74]
75
76padded_inputs_1 = processor.apply_chat_template(
77 conversation,
78 tokenize=True,
79 return_dict=True,
80).to(device)
81
82print("\n" + "="*50)
83print("First generation - compiling and recording CUDA graphs...")
84with TimerContext("First generation"):
85 _ = model.generate(**padded_inputs_1, **gen_kwargs)
86print("="*50)
87
88print("\n" + "="*50)
89print("Second generation - fast !!!")
90with TimerContext("Second generation"):
91 _ = model.generate(**padded_inputs_1, **gen_kwargs)
92print("="*50)
93
94# now with different inputs
95conversation = [
96 {
97 "role": f"{ds[0]['speaker_id']}",
98 "content": [
99 {"type": "text", "text": ds[2]["text"]},
100 {"type": "audio", "path": ds[2]["audio"]["array"]},
101 ],
102 },
103 {
104 "role": f"{ds[1]['speaker_id']}",
105 "content": [
106 {"type": "text", "text": ds[3]["text"]},
107 {"type": "audio", "path": ds[3]["audio"]["array"]},
108 ],
109 },
110 {
111 "role": f"{ds[2]['speaker_id']}",
112 "content": [
113 {"type": "text", "text": ds[4]["text"]},
114 ],
115 },
116]
117padded_inputs_2 = processor.apply_chat_template(
118 conversation,
119 tokenize=True,
120 return_dict=True,
121).to(device)
122
123print("\n" + "="*50)
124print("Generation with other inputs!")
125with TimerContext("Generation with different inputs"):
126 _ = model.generate(**padded_inputs_2, **gen_kwargs)
127print("="*50)1from datasets import load_dataset, Audio
2from transformers import (
3 CsmForConditionalGeneration,
4 TrainingArguments,
5 CsmProcessor,
6 Trainer
7)
8
9processor = CsmProcessor.from_pretrained("sesame/csm-1b")
10model = CsmForConditionalGeneration.from_pretrained("sesame/csm-1b")
11model.train()
12model.codec_model.eval()
13
14ds = load_dataset("eustlb/dailytalk-conversations-grouped", split="train")
15ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
16
17def data_collator(samples):
18 conversations = []
19
20 for sample in samples:
21 concatenated_audio_array = sample["audio"]["array"]
22 audio = [concatenated_audio_array[s: e] for s, e in sample["audio_cut_idxs"]]
23
24 conversation = []
25 for speaker_id, text, audio in zip(sample["speaker_ids"], sample["texts"], audio):
26 conversation.append({
27 "role": f"{speaker_id}",
28 "content": [
29 {"type": "text", "text": text},
30 {"type": "audio", "audio": audio}
31 ]
32 })
33
34 conversations.append(conversation)
35
36 inputs = processor.apply_chat_template(
37 conversations,
38 tokenize=True,
39 return_dict=True,
40 output_labels=True,
41 )
42 return inputs
43
44training_args = TrainingArguments(
45 "test-trainer",
46 remove_unused_columns=False,
47 gradient_checkpointing=True,
48)
49
50trainer = Trainer(
51 model,
52 training_args,
53 train_dataset=ds,
54 data_collator=data_collator,
55)
56
57trainer.train()