Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

unity_pipeline.py 8.1 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
  1. # Copyright (c) Meta Platforms, Inc. and affiliates
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # MIT_LICENSE file in the root directory of this source tree.
  6. from __future__ import annotations
  7. import logging
  8. from argparse import ArgumentParser, Namespace
  9. from typing import Any, Dict, List, Optional, Union
  10. import torch
  11. from fairseq2.assets import asset_store
  12. from seamless_communication.inference.translator import Modality, Translator
  13. from seamless_communication.models.generator.loader import load_pretssel_vocoder_model
  14. from seamless_communication.models.generator.vocoder import PretsselVocoder
  15. from seamless_communication.models.monotonic_decoder import (
  16. load_monotonic_decoder_config,
  17. load_monotonic_decoder_model,
  18. )
  19. from seamless_communication.models.unity import (
  20. load_unity_config,
  21. load_unity_model,
  22. load_unity_text_tokenizer,
  23. load_unity_unit_tokenizer,
  24. )
  25. from seamless_communication.models.vocoder.loader import load_vocoder_model
  26. from seamless_communication.models.vocoder.vocoder import Vocoder
  27. from seamless_communication.streaming.agents.common import (
  28. AgentStates,
  29. EarlyStoppingMixin,
  30. )
  31. from simuleval.agents import AgentPipeline, TreeAgentPipeline
  32. from simuleval.agents.agent import GenericAgent
  33. from simuleval.data.segments import Segment
  34. logging.basicConfig(
  35. level=logging.INFO,
  36. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  37. )
  38. logger = logging.getLogger(__name__)
  39. def maybe_reset_states(states: Optional[List[Optional[AgentStates]]]) -> None:
  40. assert states is not None
  41. for s in states:
  42. if s is not None:
  43. if isinstance(s, EarlyStoppingMixin):
  44. s.reset_early()
  45. else:
  46. s.reset()
  47. class UnitYPipelineMixin:
  48. """
  49. Mixin for UnitY pipeline which works with both AgentPipeline
  50. and TreeAgentPipeline
  51. """
  52. @classmethod
  53. def add_args(cls, parser: ArgumentParser) -> None:
  54. super().add_args(parser) # type: ignore
  55. parser.add_argument("--task", type=str, help="Task type")
  56. parser.add_argument(
  57. "--unity-model-name",
  58. type=str,
  59. help="Unity model name.",
  60. default="seamless_streaming_unity",
  61. )
  62. parser.add_argument(
  63. "--monotonic-decoder-model-name",
  64. type=str,
  65. help="Monotonic decoder model name.",
  66. default="seamless_streaming_monotonic_decoder",
  67. )
  68. parser.add_argument(
  69. "--sample-rate",
  70. default=16000,
  71. type=float,
  72. )
  73. parser.add_argument(
  74. "--dtype",
  75. choices=["fp16", "fp32"],
  76. default="fp16",
  77. type=str,
  78. help=(
  79. "Choose between half-precision (fp16) and single precision (fp32) floating point formats."
  80. + " Prefer this over the fp16 flag."
  81. ),
  82. )
  83. @classmethod
  84. def load_model(cls, args: Namespace) -> Dict[str, Any]:
  85. if not torch.cuda.is_available() and "cuda" in args.device:
  86. raise ValueError("CUDA not available, use CPU.")
  87. args.device = torch.device(args.device)
  88. if (args.fp16 or args.dtype == "fp16") and args.device != torch.device("cpu"):
  89. args.dtype = torch.float16
  90. else:
  91. args.dtype = torch.float32
  92. input_modality, output_modality = Translator.get_modalities_from_task_str(
  93. args.task
  94. )
  95. if input_modality != Modality.SPEECH:
  96. raise ValueError("`UnitYAgentPipeline` only supports speech input.")
  97. unity_config = load_unity_config(args.unity_model_name)
  98. unity_config.use_text_decoder = False
  99. unity_config.use_text_encoder = False
  100. text_tokenizer = load_unity_text_tokenizer(args.unity_model_name)
  101. # Skip loading the T2U model.
  102. if output_modality == Modality.TEXT:
  103. unity_config.t2u_config = None
  104. unit_tokenizer = None
  105. else:
  106. unit_tokenizer = load_unity_unit_tokenizer(args.unity_model_name)
  107. asset_card = asset_store.retrieve_card(args.unity_model_name)
  108. asset_card.field("model_config").set(unity_config)
  109. logger.info(
  110. f"Loading the UnitY model: {args.unity_model_name} on device={args.device}, dtype={args.dtype}"
  111. )
  112. unity_model = load_unity_model(asset_card, device=args.device, dtype=args.dtype)
  113. unity_model.eval()
  114. monotonic_decoder_config = load_monotonic_decoder_config(
  115. args.monotonic_decoder_model_name
  116. )
  117. logger.info(
  118. f"Loading the Monotonic Decoder model: {args.monotonic_decoder_model_name} on device={args.device}, dtype={args.dtype}"
  119. )
  120. monotonic_decoder_model = load_monotonic_decoder_model(
  121. args.monotonic_decoder_model_name, device=args.device, dtype=args.dtype
  122. )
  123. monotonic_decoder_model.eval()
  124. return {
  125. "unity_model": unity_model,
  126. "unity_config": unity_config,
  127. "monotonic_decoder_model": monotonic_decoder_model,
  128. "monotonic_decoder_config": monotonic_decoder_config,
  129. "text_tokenizer": text_tokenizer,
  130. "unit_tokenizer": unit_tokenizer,
  131. }
  132. class UnitYAgentPipeline(UnitYPipelineMixin, AgentPipeline): # type: ignore
  133. pipeline: List[GenericAgent] = []
  134. def __init__(self, args: Namespace):
  135. models_and_configs = self.load_model(args)
  136. module_list = []
  137. for p in self.pipeline:
  138. module_list.append(
  139. p.from_args(
  140. args,
  141. **models_and_configs,
  142. )
  143. )
  144. super().__init__(module_list)
  145. def pop(self, states: Optional[List[Optional[AgentStates]]] = None) -> Segment:
  146. output_segment = super().pop(states)
  147. if states is None:
  148. # Not stateless
  149. first_states = self.module_list[0].states
  150. else:
  151. assert len(states) == len(self.module_list)
  152. first_states = states[0]
  153. if not first_states.source_finished and output_segment.finished:
  154. # An early stop.
  155. # The temporary solution is to start over
  156. if states is not None:
  157. maybe_reset_states(states)
  158. else:
  159. self.reset()
  160. output_segment.finished = False
  161. return output_segment
  162. @classmethod
  163. def from_args(cls, args: Any) -> UnitYAgentPipeline:
  164. return cls(args)
  165. class UnitYAgentTreePipeline(UnitYPipelineMixin, TreeAgentPipeline): # type: ignore
  166. pipeline: Any = {}
  167. def __init__(self, args: Namespace):
  168. models_and_configs = self.load_model(args)
  169. assert len(self.pipeline) > 0
  170. module_dict = {}
  171. for module_class, children in self.pipeline.items():
  172. module_dict[module_class.from_args(args, **models_and_configs)] = children
  173. super().__init__(module_dict, args)
  174. @classmethod
  175. def from_args(cls, args: Any) -> UnitYAgentPipeline:
  176. return cls(args)
  177. def pop(
  178. self, states: Optional[List[Optional[AgentStates]]] = None
  179. ) -> List[Segment]:
  180. output_segment = super().pop(states)
  181. if states is None:
  182. # Not stateless
  183. first_states = self.source_module.states
  184. else:
  185. assert len(states) == len(self.module_dict)
  186. first_states = states[self.source_module]
  187. if isinstance(output_segment, list):
  188. finished = any(segment.finished for segment in output_segment)
  189. else:
  190. # case when output_index is used
  191. finished = output_segment.finished
  192. if not first_states.source_finished and finished:
  193. # An early stop.
  194. # The temporary solution is to start over
  195. if states is not None:
  196. maybe_reset_states(states)
  197. else:
  198. self.reset()
  199. if isinstance(output_segment, list):
  200. for segment in output_segment:
  201. segment.finished = False
  202. else:
  203. output_segment.finished = False
  204. return output_segment # type: ignore[no-any-return]
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...