reward_tts.py 7.5 KB

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