offline_inference.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
  2. # SPDX-License-Identifier: Apache-2.0
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """ Example Usage
  16. CUDA_VISIBLE_DEVICES=0 \
  17. python3 offline_inference.py \
  18. --output-dir $output_dir \
  19. --llm-model-name-or-path $huggingface_model_local_dir \
  20. --token2wav-path $model_scope_model_local_dir \
  21. --backend $backend \
  22. --batch-size $batch_size --token2wav-batch-size $token2wav_batch_size \
  23. --engine-dir $trt_engines_dir \
  24. --split-name ${dataset} || exit 1
  25. """
  26. import argparse
  27. import json
  28. import os
  29. import sys
  30. import torch
  31. import torch.distributed as dist
  32. import torch.nn.functional as F
  33. import torchaudio
  34. from cosyvoice.utils.file_utils import load_wav
  35. from datasets import load_dataset
  36. from transformers import AutoTokenizer
  37. from torch.utils.data import DataLoader, Dataset
  38. from tqdm import tqdm
  39. import soundfile as sf
  40. import s3tokenizer
  41. from functools import partial
  42. import time
  43. import requests
  44. import asyncio
  45. import httpx
  46. sys.path.append("/workspace/CosyVoice/third_party/Matcha-TTS")
  47. try:
  48. torch.multiprocessing.set_start_method("spawn")
  49. except RuntimeError:
  50. pass
  51. async def send_request_async(client, url, payload):
  52. response = await client.post(url, json=payload, timeout=None)
  53. response.raise_for_status()
  54. response_json = response.json()
  55. return response_json['choices'][0]['message']['content']
  56. async def send_batch_requests_async(api_base, model_name, chats, temperature, top_p, top_k):
  57. async with httpx.AsyncClient() as client:
  58. tasks = []
  59. for chat in chats:
  60. payload = {
  61. "model": model_name,
  62. "messages": chat,
  63. "max_tokens": 2048,
  64. "temperature": temperature,
  65. "top_p": top_p,
  66. "top_k": top_k,
  67. "repetition_penalty": 1.1,
  68. "stop": ["<|eos1|>", "<|eos|>"],
  69. "stream": False,
  70. }
  71. tasks.append(send_request_async(client, api_base, payload))
  72. return await asyncio.gather(*tasks)
  73. def extract_speech_ids(speech_tokens_str):
  74. """Extract speech IDs from token strings like <|s_23456|>"""
  75. speech_ids = []
  76. for token_str in speech_tokens_str:
  77. if token_str.startswith('<|s_') and token_str.endswith('|>'):
  78. num_str = token_str[4:-2]
  79. num = int(num_str)
  80. speech_ids.append(num)
  81. else:
  82. print(f"Unexpected token: {token_str}")
  83. return speech_ids
  84. def convert_cosy2_tokens_to_speech_id_str(cosy2_tokens):
  85. """Convert CosyVoice2 tokens to speech IDs string like <|s_23456|>"""
  86. speech_id_str = ""
  87. for token in cosy2_tokens:
  88. speech_id_str += f"<|s_{token}|>"
  89. return speech_id_str
  90. def get_args():
  91. parser = argparse.ArgumentParser(description="Speech generation using LLM + CosyVoice2")
  92. parser.add_argument(
  93. "--split-name",
  94. type=str,
  95. default="wenetspeech4tts",
  96. help="huggingface dataset split name, see yuekai/CV3-Eval, yuekai/seed_tts_cosy2",
  97. )
  98. parser.add_argument(
  99. "--output-dir", required=True, type=str, help="dir to save result"
  100. )
  101. parser.add_argument(
  102. "--batch-size",
  103. default=1,
  104. type=int,
  105. help="batch size (per-device) for inference",
  106. )
  107. parser.add_argument(
  108. "--token2wav-batch-size",
  109. default=1,
  110. type=int,
  111. help="batch size (per-device) for inference",
  112. )
  113. parser.add_argument(
  114. "--num-workers", type=int, default=0, help="workers for dataloader"
  115. )
  116. parser.add_argument(
  117. "--prefetch", type=int, default=None, help="prefetch for dataloader"
  118. )
  119. parser.add_argument(
  120. "--llm-model-name-or-path",
  121. required=True,
  122. type=str,
  123. help="LLM model path (includes both model and tokenizer)",
  124. )
  125. parser.add_argument(
  126. "--token2wav-path",
  127. required=True,
  128. type=str,
  129. help="CosyVoice2 token2wav model path",
  130. )
  131. parser.add_argument(
  132. "--prompt-text",
  133. type=str,
  134. default=None,
  135. help="The prompt text for CosyVoice2",
  136. )
  137. parser.add_argument(
  138. "--prompt-speech-path",
  139. type=str,
  140. default=None,
  141. help="The path to the prompt speech for CosyVoice2",
  142. )
  143. parser.add_argument(
  144. "--top-p",
  145. type=float,
  146. default=0.95,
  147. help="top p for sampling",
  148. )
  149. parser.add_argument(
  150. "--temperature",
  151. type=float,
  152. default=0.8,
  153. help="temperature for sampling",
  154. )
  155. parser.add_argument(
  156. "--top-k",
  157. type=int,
  158. default=50,
  159. help="top k for sampling",
  160. )
  161. parser.add_argument(
  162. "--backend",
  163. type=str,
  164. default="hf",
  165. choices=["hf", "trtllm", "vllm", "trtllm-serve"],
  166. help="Backend to use for LLM inference: 'hf' for HuggingFace, 'trtllm' for TensorRT-LLM, 'vllm' for VLLM",
  167. )
  168. parser.add_argument(
  169. "--engine-dir",
  170. type=str,
  171. default=None,
  172. help="TensorRT-LLM engine directory (required when backend is 'trtllm')",
  173. )
  174. parser.add_argument(
  175. "--kv-cache-free-gpu-memory-fraction",
  176. type=float,
  177. default=0.6,
  178. help="Fraction of GPU memory to free for KV cache (TensorRT-LLM only)",
  179. )
  180. parser.add_argument(
  181. "--openai-api-base",
  182. type=str,
  183. default="http://localhost:8000/v1/chat/completions",
  184. help="OpenAI API base URL (for trtllm-serve backend)",
  185. )
  186. parser.add_argument(
  187. "--openai-model-name",
  188. type=str,
  189. default="trt_engines_bfloat16",
  190. help="Model name to use with OpenAI API (for trtllm-serve backend)",
  191. )
  192. args = parser.parse_args()
  193. return args
  194. def data_collator(batch, tokenizer, s3_tokenizer):
  195. """Simplified data collator for batch_size=1 processing"""
  196. collator_start_time = time.time()
  197. total_audio_processing_time = 0
  198. total_speech_tokenization_time = 0
  199. total_text_tokenization_time = 0
  200. target_sample_rate = 16000 # CosyVoice2 uses 16kHz for prompt audio
  201. device = s3_tokenizer.device if s3_tokenizer is not None else torch.device("cpu")
  202. input_ids_list, prompt_audio_list, prompt_text_list = [], [], []
  203. prompt_text_after_apply_template_list = []
  204. mels, prompt_audio_cosy2tokens_list, full_text_list = [], [], []
  205. chat_list = []
  206. for _, item in enumerate(batch):
  207. audio_processing_start_time = time.time()
  208. prompt_text, target_text = (
  209. item["prompt_text"],
  210. item["target_text"],
  211. )
  212. prompt_text_list.append(prompt_text)
  213. full_text = prompt_text + target_text
  214. full_text_list.append(full_text)
  215. # remove the unnecessary punctuation for cosyvoice3 zero_shot_zh dataset
  216. puncts = ['"', '(', ')', '“', '”', '‘', '(', ')', '\'']
  217. for p in puncts:
  218. if p in full_text:
  219. full_text = full_text.replace(p, '')
  220. print(f"removed {p} from {full_text}")
  221. # get prompt audio for CosyVoice2 (convert to 16kHz)
  222. ref_audio_org, ref_sr = (
  223. item["prompt_audio"]["array"],
  224. item["prompt_audio"]["sampling_rate"],
  225. )
  226. ref_audio_org = torch.from_numpy(ref_audio_org).float().unsqueeze(0)
  227. print(ref_audio_org.shape)
  228. if ref_sr != target_sample_rate:
  229. resampler = torchaudio.transforms.Resample(ref_sr, target_sample_rate)
  230. ref_audio = resampler(ref_audio_org)
  231. else:
  232. ref_audio = ref_audio_org
  233. prompt_audio_list.append(ref_audio)
  234. audio_processing_end_time = time.time()
  235. total_audio_processing_time += audio_processing_end_time - audio_processing_start_time
  236. speech_tokenization_start_time = time.time()
  237. if "prompt_audio_cosy2_tokens" in item:
  238. prompt_audio_cosy2tokens = item["prompt_audio_cosy2_tokens"]
  239. prompt_audio_cosy2tokens_list.append(prompt_audio_cosy2tokens)
  240. else:
  241. mels.append(s3tokenizer.log_mel_spectrogram(ref_audio.squeeze(0)))
  242. if len(mels) > 0:
  243. mels, mels_lens = s3tokenizer.padding(mels)
  244. codes, codes_lens = s3_tokenizer.quantize(mels.to(device), mels_lens.to(device))
  245. for i in range(len(codes)):
  246. prompt_audio_cosy2tokens_list.append(codes[i, :codes_lens[i].item()])
  247. speech_tokenization_end_time = time.time()
  248. total_speech_tokenization_time += speech_tokenization_end_time - speech_tokenization_start_time
  249. for i, prompt_audio_cosy2tokens in enumerate(prompt_audio_cosy2tokens_list):
  250. text_tokenization_start_time = time.time()
  251. prompt_audio_cosy2_id_str = convert_cosy2_tokens_to_speech_id_str(prompt_audio_cosy2tokens)
  252. # Create chat template for LLM generation
  253. chat = [
  254. {"role": "user", "content": full_text_list[i]},
  255. {"role": "assistant", "content": prompt_audio_cosy2_id_str}
  256. ]
  257. chat_list.append(chat)
  258. assert 'system' not in tokenizer.chat_template, "system is not allowed in the chat template"
  259. input_ids = tokenizer.apply_chat_template(
  260. chat,
  261. tokenize=True,
  262. return_tensors='pt',
  263. continue_final_message=True
  264. )
  265. input_ids_list.append(input_ids.squeeze(0))
  266. prompt_text_after_apply_template = f"<|sos|>{full_text_list[i]}<|task_id|>{prompt_audio_cosy2_id_str}"
  267. prompt_text_after_apply_template_list.append(prompt_text_after_apply_template)
  268. text_tokenization_end_time = time.time()
  269. total_text_tokenization_time += text_tokenization_end_time - text_tokenization_start_time
  270. ids = [item["id"] for item in batch]
  271. return {
  272. "input_ids": input_ids_list,
  273. "ids": ids,
  274. "prompt_text": prompt_text_list,
  275. "prompt_audio_list": prompt_audio_list,
  276. "prompt_text_after_apply_template": prompt_text_after_apply_template_list,
  277. "audio_processing_time": total_audio_processing_time,
  278. "speech_tokenization_time": total_speech_tokenization_time,
  279. "text_tokenization_time": total_text_tokenization_time,
  280. "chat_list": chat_list
  281. }
  282. def init_distributed():
  283. world_size = int(os.environ.get("WORLD_SIZE", 1))
  284. local_rank = int(os.environ.get("LOCAL_RANK", 0))
  285. rank = int(os.environ.get("RANK", 0))
  286. print(
  287. "Inference on multiple gpus, this gpu {}".format(local_rank)
  288. + ", rank {}, world_size {}".format(rank, world_size)
  289. )
  290. torch.cuda.set_device(local_rank)
  291. dist.init_process_group("nccl")
  292. return world_size, local_rank, rank
  293. def main(args):
  294. os.makedirs(args.output_dir, exist_ok=True)
  295. assert torch.cuda.is_available()
  296. local_rank, world_size, rank = 0, 1, 0
  297. device = torch.device(f"cuda:{local_rank}")
  298. tokenizer = AutoTokenizer.from_pretrained(args.llm_model_name_or_path)
  299. if args.backend == "hf":
  300. model = AutoModelForCausalLM.from_pretrained(args.llm_model_name_or_path)
  301. model.eval()
  302. model.to(device)
  303. runner = None
  304. elif args.backend == "trtllm":
  305. if args.engine_dir is None:
  306. raise ValueError("--engine-dir is required when backend is 'trtllm'")
  307. runtime_rank = tensorrt_llm.mpi_rank()
  308. model = None
  309. runner_kwargs = dict(
  310. engine_dir=args.engine_dir,
  311. rank=runtime_rank,
  312. max_output_len=2048,
  313. enable_context_fmha_fp32_acc=False,
  314. max_batch_size=args.batch_size,
  315. max_input_len=512,
  316. kv_cache_free_gpu_memory_fraction=args.kv_cache_free_gpu_memory_fraction,
  317. cuda_graph_mode=False,
  318. gather_generation_logits=False,
  319. )
  320. runner = ModelRunnerCpp.from_dir(**runner_kwargs)
  321. elif args.backend == "vllm":
  322. model = LLM(model=args.llm_model_name_or_path, gpu_memory_utilization=0.4)
  323. runner = None
  324. elif args.backend == "trtllm-serve":
  325. model = None
  326. runner = None
  327. else:
  328. raise ValueError(f"Unsupported backend: {args.backend}")
  329. if 'Step-Audio-2-mini' in args.token2wav_path:
  330. from token2wav_dit import CosyVoice2_Token2Wav
  331. else:
  332. assert 'CosyVoice2-0.5B' in args.token2wav_path
  333. from token2wav import CosyVoice2_Token2Wav
  334. token2wav_model = CosyVoice2_Token2Wav(
  335. model_dir=args.token2wav_path, enable_trt=True, device_id=local_rank
  336. )
  337. if args.prompt_speech_path:
  338. prompt_speech_16k = load_wav(args.prompt_speech_path, 16000)
  339. else:
  340. prompt_speech_16k = None
  341. s3_tokenizer = s3tokenizer.load_model(f"{args.token2wav_path}/speech_tokenizer_v2.onnx").to(device) if 'zero' in args.split_name else None
  342. dataset_name = "yuekai/CV3-Eval" if 'zero' in args.split_name else "yuekai/seed_tts_cosy2"
  343. dataset = load_dataset(
  344. dataset_name,
  345. split=args.split_name,
  346. trust_remote_code=True,
  347. )
  348. sampler = None
  349. dataloader = DataLoader(
  350. dataset,
  351. batch_size=args.batch_size,
  352. sampler=sampler,
  353. shuffle=False,
  354. num_workers=args.num_workers,
  355. prefetch_factor=args.prefetch,
  356. collate_fn=partial(data_collator, tokenizer=tokenizer, s3_tokenizer=s3_tokenizer),
  357. )
  358. for _ in range(3):
  359. print(f"Running {_} times")
  360. total_llm_time = 0
  361. total_token2wav_time = 0
  362. total_data_load_time = 0
  363. total_llm_post_processing_time = 0
  364. total_audio_save_time = 0
  365. total_audio_processing_time_in_collator = 0
  366. total_speech_tokenization_time_in_collator = 0
  367. total_text_tokenization_time_in_collator = 0
  368. total_audio_samples = 0
  369. start_time = time.time()
  370. total_steps = len(dataset)
  371. if rank == 0:
  372. progress_bar = tqdm(total=total_steps, desc="Processing", unit="wavs")
  373. last_batch_end_time = time.time()
  374. for batch in dataloader:
  375. data_loaded_time = time.time()
  376. total_data_load_time += data_loaded_time - last_batch_end_time
  377. total_audio_processing_time_in_collator += batch["audio_processing_time"]
  378. total_speech_tokenization_time_in_collator += batch["speech_tokenization_time"]
  379. total_text_tokenization_time_in_collator += batch["text_tokenization_time"]
  380. with torch.no_grad():
  381. llm_start_time = time.time()
  382. if args.backend == "hf":
  383. input_ids_list = batch["input_ids"]
  384. if len(input_ids_list) == 1:
  385. input_ids = input_ids_list[0].unsqueeze(0)
  386. attention_mask = torch.ones_like(input_ids)
  387. else:
  388. max_len = max([len(input_ids) for input_ids in input_ids_list])
  389. input_ids_list_new = [
  390. torch.cat([input_ids, torch.full((max_len - len(input_ids),), tokenizer.pad_token_id)])
  391. for input_ids in input_ids_list
  392. ]
  393. input_ids = torch.stack(input_ids_list_new)
  394. attention_mask = torch.zeros_like(input_ids)
  395. for i in range(len(input_ids_list)):
  396. attention_mask[i, :len(input_ids_list[i])] = 1
  397. input_ids = input_ids.to(device)
  398. outputs = model.generate(
  399. input_ids=input_ids.to(device),
  400. attention_mask=attention_mask.to(device),
  401. max_new_tokens=2048,
  402. do_sample=True,
  403. top_p=args.top_p,
  404. temperature=args.temperature,
  405. repetition_penalty=1.1,
  406. top_k=args.top_k,
  407. )
  408. torch.cuda.synchronize()
  409. elif args.backend == "trtllm":
  410. batch_input_ids = list(batch["input_ids"])
  411. input_lengths = [x.size(0) for x in batch_input_ids]
  412. end_id = tokenizer.convert_tokens_to_ids("<|eos1|>") if "<|eos1|>" in tokenizer.get_vocab() else tokenizer.eos_token_id
  413. print(f"end_id: {end_id}, tokenizer.eos_token_id: {tokenizer.eos_token_id} ========================")
  414. outputs = runner.generate(
  415. batch_input_ids=batch_input_ids,
  416. max_new_tokens=2048,
  417. end_id=end_id,
  418. pad_id=end_id,
  419. temperature=args.temperature,
  420. top_k=args.top_k,
  421. top_p=args.top_p,
  422. repetition_penalty=1.1,
  423. num_return_sequences=1,
  424. streaming=False,
  425. output_sequence_lengths=True,
  426. output_generation_logits=False,
  427. return_dict=True,
  428. return_all_generated_tokens=False
  429. )
  430. torch.cuda.synchronize()
  431. output_ids, sequence_lengths = outputs["output_ids"], outputs["sequence_lengths"]
  432. num_output_sents, num_beams, _ = output_ids.size()
  433. assert num_beams == 1
  434. beam = 0
  435. batch_size = len(batch["input_ids"])
  436. num_return_sequences = num_output_sents // batch_size
  437. assert num_return_sequences == 1
  438. outputs = []
  439. for i in range(batch_size * num_return_sequences):
  440. batch_idx = i // num_return_sequences
  441. seq_idx = i % num_return_sequences
  442. output_begin = input_lengths[batch_idx]
  443. output_end = sequence_lengths[i][beam]
  444. outputs_i = output_ids[i][beam][:output_end].tolist()
  445. outputs.append(outputs_i)
  446. elif args.backend == "vllm":
  447. input_ids_list = [ids.tolist() for ids in batch["input_ids"]]
  448. sampling_params = SamplingParams(
  449. temperature=args.temperature,
  450. top_p=args.top_p,
  451. top_k=args.top_k,
  452. repetition_penalty=1.1,
  453. max_tokens=2048,
  454. )
  455. outputs = model.generate(prompt_token_ids=input_ids_list, sampling_params=sampling_params)
  456. print(outputs)
  457. for j, output in enumerate(outputs):
  458. outputs[j] = input_ids_list[j] + output.outputs[0].token_ids
  459. elif args.backend == "trtllm-serve":
  460. if args.batch_size > 1:
  461. outputs = asyncio.run(send_batch_requests_async(
  462. args.openai_api_base,
  463. args.openai_model_name,
  464. batch["chat_list"],
  465. args.temperature,
  466. args.top_p,
  467. args.top_k,
  468. ))
  469. else:
  470. outputs = []
  471. for chat in batch["chat_list"]:
  472. payload = {
  473. "model": args.openai_model_name,
  474. "messages": chat,
  475. "max_tokens": 2048,
  476. "temperature": args.temperature,
  477. "top_p": args.top_p,
  478. "top_k": args.top_k,
  479. "repetition_penalty": 1.1,
  480. "stop": ["<|eos1|>", "<|eos|>"],
  481. "stream": False,
  482. }
  483. response = requests.post(args.openai_api_base, json=payload)
  484. response.raise_for_status()
  485. response_json = response.json()
  486. generated_content = response_json['choices'][0]['message']['content']
  487. outputs.append(generated_content)
  488. llm_end_time = time.time()
  489. total_llm_time += (llm_end_time - llm_start_time)
  490. items_for_token_2wav = []
  491. for i in range(len(batch["ids"])):
  492. llm_post_processing_start_time = time.time()
  493. if args.backend == "trtllm-serve":
  494. speech_tokens_str = outputs[i].strip().split('><')
  495. if len(speech_tokens_str) > 1:
  496. speech_tokens_str = [
  497. t if t.startswith('<') else '<' + t for t in speech_tokens_str
  498. ]
  499. speech_tokens_str = [
  500. t if t.endswith('>') else t + '>' for t in speech_tokens_str
  501. ]
  502. speech_ids = extract_speech_ids(speech_tokens_str)
  503. else:
  504. input_length = len(batch["input_ids"][i])
  505. generated_ids = outputs[i][input_length:]
  506. speech_tokens_str = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
  507. speech_ids = extract_speech_ids(speech_tokens_str)
  508. print(i, speech_ids)
  509. if len(speech_ids) == 0:
  510. print(f"Warning: No speech tokens generated for sample {batch['ids'][i]}, skipping")
  511. continue
  512. if args.prompt_text is not None:
  513. current_prompt_text = args.prompt_text
  514. current_prompt_audio = prompt_speech_16k
  515. else:
  516. current_prompt_text = batch["prompt_text"][i]
  517. current_prompt_audio = batch["prompt_audio_list"][i]
  518. llm_post_processing_end_time = time.time()
  519. total_llm_post_processing_time += llm_post_processing_end_time - llm_post_processing_start_time
  520. if current_prompt_audio is not None:
  521. items_for_token_2wav.append({
  522. "speech_ids": speech_ids,
  523. "prompt_audio": current_prompt_audio.squeeze(0),
  524. "id": batch["ids"][i]
  525. })
  526. else:
  527. print(f"Warning: No prompt audio available for sample {batch['ids'][i]}, skipping")
  528. for i in range(0, len(items_for_token_2wav), args.token2wav_batch_size):
  529. t2w_batch = items_for_token_2wav[i:i + args.token2wav_batch_size]
  530. if not t2w_batch:
  531. continue
  532. t2w_generated_speech_tokens_list = [item["speech_ids"] for item in t2w_batch]
  533. t2w_prompt_audios_list = [item["prompt_audio"] for item in t2w_batch]
  534. t2w_prompt_audios_sample_rate = [16000] * len(t2w_batch)
  535. t2w_ids = [item["id"] for item in t2w_batch]
  536. token2wav_start_time = time.time()
  537. generated_wavs = token2wav_model(
  538. t2w_generated_speech_tokens_list,
  539. t2w_prompt_audios_list,
  540. t2w_prompt_audios_sample_rate,
  541. )
  542. token2wav_end_time = time.time()
  543. total_token2wav_time += (token2wav_end_time - token2wav_start_time)
  544. audio_save_start_time = time.time()
  545. for j, audio_hat in enumerate(generated_wavs):
  546. generated_wave = audio_hat.squeeze().cpu().numpy()
  547. total_audio_samples += len(generated_wave)
  548. target_sample_rate = 24000
  549. utt = t2w_ids[j]
  550. sf.write(f"{args.output_dir}/{utt}.wav", generated_wave, target_sample_rate)
  551. print(f"Generated audio for sample {utt} with {len(t2w_generated_speech_tokens_list[j])} tokens")
  552. audio_save_end_time = time.time()
  553. total_audio_save_time += audio_save_end_time - audio_save_start_time
  554. if rank == 0:
  555. progress_bar.update(world_size * len(batch["ids"]))
  556. last_batch_end_time = time.time()
  557. if rank == 0:
  558. progress_bar.close()
  559. end_time = time.time()
  560. target_sample_rate = 24000
  561. total_audio_duration_seconds = total_audio_samples / target_sample_rate
  562. log_file_path = os.path.join(args.output_dir, "log.txt")
  563. with open(log_file_path, 'w') as f:
  564. args_dict = vars(args)
  565. log_data = {
  566. "args": args_dict,
  567. "data_load_time_seconds": total_data_load_time,
  568. "audio_processing_time_in_collator_seconds": total_audio_processing_time_in_collator,
  569. "speech_tokenization_time_in_collator_seconds": total_speech_tokenization_time_in_collator,
  570. "text_tokenization_time_in_collator_seconds": total_text_tokenization_time_in_collator,
  571. "llm_time_seconds": total_llm_time,
  572. "llm_post_processing_time_seconds": total_llm_post_processing_time,
  573. "token2wav_time_seconds": total_token2wav_time,
  574. "audio_save_time_seconds": total_audio_save_time,
  575. "total_audio_duration_seconds": total_audio_duration_seconds,
  576. "pipeline_time_seconds": end_time - start_time,
  577. }
  578. print(log_data)
  579. f.write(json.dumps(log_data, indent=4))
  580. print(f"Metrics logged to {log_file_path}")
  581. if __name__ == "__main__":
  582. args = get_args()
  583. if args.backend == "vllm":
  584. from vllm import LLM, SamplingParams
  585. elif args.backend == "trtllm":
  586. import tensorrt_llm
  587. from tensorrt_llm.runtime import ModelRunnerCpp
  588. elif args.backend == "hf":
  589. from transformers import AutoModelForCausalLM
  590. elif args.backend == "trtllm-serve":
  591. pass
  592. else:
  593. raise ValueError(f"Unsupported backend: {args.backend}")
  594. main(args)