reward_tts.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. """
  16. Reward calculation for CosyVoice2-0.5B.
  17. """
  18. from __future__ import annotations
  19. import re
  20. import json
  21. import time
  22. import argparse
  23. from typing import List
  24. import numpy as np
  25. import requests
  26. REWARD_SERVER_URL = "http://localhost:8000/v2/models/token2wav_asr/infer"
  27. def _parse_ids(token_str: str) -> List[int]:
  28. return [int(t) for t in re.findall(r"<\|s_(\d+)\|>", token_str)]
  29. def _remote_reward(tokens: List[int], ground_truth: str, timeout: float = 200.0) -> float:
  30. """Send token IDs and ground-truth text to the Triton server and get reward."""
  31. tokens_arr = np.array(tokens, dtype=np.int32).reshape(1, -1)
  32. lens_arr = np.array([[tokens_arr.shape[1]]], dtype=np.int32)
  33. gt_arr = np.array([ground_truth.encode("utf-8")], dtype=object)
  34. payload = {
  35. "inputs": [
  36. {
  37. "name": "TOKENS",
  38. "shape": list(tokens_arr.shape),
  39. "datatype": "INT32",
  40. "data": tokens_arr.tolist(),
  41. },
  42. {
  43. "name": "TOKEN_LENS",
  44. "shape": list(lens_arr.shape),
  45. "datatype": "INT32",
  46. "data": lens_arr.tolist(),
  47. },
  48. {
  49. "name": "GT_TEXT",
  50. "shape": [1, 1],
  51. "datatype": "BYTES",
  52. "data": [ground_truth],
  53. },
  54. ]
  55. }
  56. rsp = requests.post(
  57. REWARD_SERVER_URL,
  58. headers={"Content-Type": "application/json"},
  59. json=payload,
  60. timeout=timeout,
  61. verify=False,
  62. params={"request_id": "0"},
  63. )
  64. rsp.raise_for_status()
  65. result = rsp.json()
  66. try:
  67. # Reward is returned as the first output
  68. return float(result["outputs"][0]["data"][0])
  69. except (KeyError, IndexError, TypeError):
  70. return 0.0
  71. def compute_score(
  72. data_source: str,
  73. solution_str: str,
  74. ground_truth: str,
  75. extra_info: dict | None = None,
  76. *,
  77. debug_dump: bool = False,
  78. ) -> float:
  79. """Return reward in [0, 1] using the Triton ASR service.
  80. The reward is based on the pinyin-level WER between the ASR transcript
  81. produced from *solution_str* and the provided *ground_truth* text.
  82. """
  83. # Decode token IDs
  84. ids = _parse_ids(solution_str)
  85. # Query remote server for reward
  86. try:
  87. reward = _remote_reward(ids, ground_truth)
  88. except Exception as e:
  89. reward = 0.0
  90. if debug_dump:
  91. print(
  92. f"\033[92m[{data_source}] Remote reward: {reward:.4f}\033[0m"
  93. )
  94. return reward
  95. # CLI quick test
  96. if __name__ == "__main__":
  97. import sys
  98. def get_args():
  99. """Parse command line arguments."""
  100. parser = argparse.ArgumentParser(
  101. description="Test TTS CER scoring with data from JSONL file",
  102. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  103. )
  104. parser.add_argument(
  105. "--input", "-i",
  106. type=str,
  107. default="data/emilia_zh-cosy-tiny-test.jsonl",
  108. help="Path to input JSONL file"
  109. )
  110. parser.add_argument(
  111. "--max-samples", "-n",
  112. type=int,
  113. default=None,
  114. help="Maximum number of samples to process (default: all)"
  115. )
  116. parser.add_argument(
  117. "--no-interactive",
  118. action="store_true",
  119. help="Run in non-interactive mode (process all samples without prompts)"
  120. )
  121. parser.add_argument(
  122. "--debug",
  123. action="store_true",
  124. help="Enable debug mode"
  125. )
  126. return parser.parse_args()
  127. def load_jsonl(file_path: str):
  128. """Load data from jsonl file."""
  129. data = []
  130. with open(file_path, 'r', encoding='utf-8') as f:
  131. for line in f:
  132. data.append(json.loads(line.strip()))
  133. return data
  134. def code_to_solution_str(code_list: List[int]) -> str:
  135. """Convert code list to solution string format."""
  136. return ''.join([f"<|s_{code}|>" for code in code_list])
  137. # Parse command line arguments
  138. args = get_args()
  139. try:
  140. # Load data from jsonl file
  141. print(f"Loading data from: {args.input}")
  142. data_list = load_jsonl(args.input)
  143. print(f"Loaded {len(data_list)} samples")
  144. # Limit samples if specified
  145. if args.max_samples is not None:
  146. data_list = data_list[:args.max_samples]
  147. print(f"Processing first {len(data_list)} samples (limited by --max-samples)")
  148. # Process each sample
  149. begin_time = time.time()
  150. for i, sample in enumerate(data_list):
  151. print(f"\n--- Sample {i+1}/{len(data_list)} ---")
  152. print(f"Index: {sample.get('index', 'unknown')}")
  153. print(f"Text: {sample['text']}")
  154. # Extract required fields
  155. code_list = sample['code']
  156. ground_truth = sample['text']
  157. data_source = sample.get('index', f'sample_{i}') # Use index as data_source
  158. # Convert code list to solution string
  159. solution_str = code_to_solution_str(code_list)
  160. print(f"Solution tokens: {len(code_list)} tokens")
  161. if args.debug:
  162. print(f"Solution string: {solution_str}")
  163. else:
  164. print(f"Solution string preview: {solution_str[:100]}..." if len(solution_str) > 100 else f"Solution string: {solution_str}")
  165. # Call compute_score function
  166. try:
  167. score = compute_score(
  168. data_source=data_source,
  169. solution_str=solution_str,
  170. ground_truth=ground_truth,
  171. extra_info=None,
  172. debug_dump=args.debug
  173. )
  174. print(f"Final Score: {score:.4f}")
  175. except Exception as e:
  176. print(f"Error computing score: {e}")
  177. # Ask user if they want to continue (for interactive mode)
  178. if not args.no_interactive and i < len(data_list) - 1:
  179. try:
  180. response = input("\nPress Enter to continue or 'q' to quit: ").strip().lower()
  181. if response == 'q':
  182. break
  183. except KeyboardInterrupt:
  184. print("\nStopped by user")
  185. break
  186. print(f"\nProcessed {min(i+1, len(data_list))} samples")
  187. end_time = time.time()
  188. print(f"Time taken: {end_time - begin_time} seconds")
  189. except FileNotFoundError:
  190. print(f"Error: File not found - {args.input}")
  191. print("Please check the file path or use --input to specify correct path")
  192. print("Run with --help for usage information")
  193. except Exception as e:
  194. print(f"Error: {e}")