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
|
- # Copyright (c) Meta Platforms, Inc. and affiliates
- # All rights reserved.
- #
- # This source code is licensed under the license found in the
- # MIT_LICENSE file in the root directory of this source tree.
- from __future__ import annotations
- import logging
- from argparse import ArgumentParser, Namespace
- from typing import Any, Dict, List, Optional, Union
- import torch
- from fairseq2.assets import asset_store
- from seamless_communication.inference.translator import Modality, Translator
- from seamless_communication.models.generator.loader import load_pretssel_vocoder_model
- from seamless_communication.models.generator.vocoder import PretsselVocoder
- from seamless_communication.models.monotonic_decoder import (
- load_monotonic_decoder_config,
- load_monotonic_decoder_model,
- )
- from seamless_communication.models.unity import (
- load_unity_config,
- load_unity_model,
- load_unity_text_tokenizer,
- load_unity_unit_tokenizer,
- )
- from seamless_communication.models.vocoder.loader import load_vocoder_model
- from seamless_communication.models.vocoder.vocoder import Vocoder
- from seamless_communication.streaming.agents.common import (
- AgentStates,
- EarlyStoppingMixin,
- )
- from simuleval.agents import AgentPipeline, TreeAgentPipeline
- from simuleval.agents.agent import GenericAgent
- from simuleval.data.segments import Segment
- logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
- )
- logger = logging.getLogger(__name__)
- def maybe_reset_states(states: Optional[List[Optional[AgentStates]]]) -> None:
- assert states is not None
- for s in states:
- if s is not None:
- if isinstance(s, EarlyStoppingMixin):
- s.reset_early()
- else:
- s.reset()
- class UnitYPipelineMixin:
- """
- Mixin for UnitY pipeline which works with both AgentPipeline
- and TreeAgentPipeline
- """
- @classmethod
- def add_args(cls, parser: ArgumentParser) -> None:
- super().add_args(parser) # type: ignore
- parser.add_argument("--task", type=str, help="Task type")
- parser.add_argument(
- "--unity-model-name",
- type=str,
- help="Unity model name.",
- default="seamless_streaming_unity",
- )
- parser.add_argument(
- "--monotonic-decoder-model-name",
- type=str,
- help="Monotonic decoder model name.",
- default="seamless_streaming_monotonic_decoder",
- )
- parser.add_argument(
- "--sample-rate",
- default=16000,
- type=float,
- )
- parser.add_argument(
- "--dtype",
- choices=["fp16", "fp32"],
- default="fp16",
- type=str,
- help=(
- "Choose between half-precision (fp16) and single precision (fp32) floating point formats."
- + " Prefer this over the fp16 flag."
- ),
- )
- @classmethod
- def load_model(cls, args: Namespace) -> Dict[str, Any]:
- if not torch.cuda.is_available() and "cuda" in args.device:
- raise ValueError("CUDA not available, use CPU.")
- args.device = torch.device(args.device)
- if (args.fp16 or args.dtype == "fp16") and args.device != torch.device("cpu"):
- args.dtype = torch.float16
- else:
- args.dtype = torch.float32
- input_modality, output_modality = Translator.get_modalities_from_task_str(
- args.task
- )
- if input_modality != Modality.SPEECH:
- raise ValueError("`UnitYAgentPipeline` only supports speech input.")
- unity_config = load_unity_config(args.unity_model_name)
- unity_config.use_text_decoder = False
- unity_config.use_text_encoder = False
- text_tokenizer = load_unity_text_tokenizer(args.unity_model_name)
- # Skip loading the T2U model.
- if output_modality == Modality.TEXT:
- unity_config.t2u_config = None
- unit_tokenizer = None
- else:
- unit_tokenizer = load_unity_unit_tokenizer(args.unity_model_name)
- asset_card = asset_store.retrieve_card(args.unity_model_name)
- asset_card.field("model_config").set(unity_config)
- logger.info(
- f"Loading the UnitY model: {args.unity_model_name} on device={args.device}, dtype={args.dtype}"
- )
- unity_model = load_unity_model(asset_card, device=args.device, dtype=args.dtype)
- unity_model.eval()
- monotonic_decoder_config = load_monotonic_decoder_config(
- args.monotonic_decoder_model_name
- )
- logger.info(
- f"Loading the Monotonic Decoder model: {args.monotonic_decoder_model_name} on device={args.device}, dtype={args.dtype}"
- )
- monotonic_decoder_model = load_monotonic_decoder_model(
- args.monotonic_decoder_model_name, device=args.device, dtype=args.dtype
- )
- monotonic_decoder_model.eval()
- return {
- "unity_model": unity_model,
- "unity_config": unity_config,
- "monotonic_decoder_model": monotonic_decoder_model,
- "monotonic_decoder_config": monotonic_decoder_config,
- "text_tokenizer": text_tokenizer,
- "unit_tokenizer": unit_tokenizer,
- }
- class UnitYAgentPipeline(UnitYPipelineMixin, AgentPipeline): # type: ignore
- pipeline: List[GenericAgent] = []
- def __init__(self, args: Namespace):
- models_and_configs = self.load_model(args)
- module_list = []
- for p in self.pipeline:
- module_list.append(
- p.from_args(
- args,
- **models_and_configs,
- )
- )
- super().__init__(module_list)
- def pop(self, states: Optional[List[Optional[AgentStates]]] = None) -> Segment:
- output_segment = super().pop(states)
- if states is None:
- # Not stateless
- first_states = self.module_list[0].states
- else:
- assert len(states) == len(self.module_list)
- first_states = states[0]
- if not first_states.source_finished and output_segment.finished:
- # An early stop.
- # The temporary solution is to start over
- if states is not None:
- maybe_reset_states(states)
- else:
- self.reset()
- output_segment.finished = False
- return output_segment
- @classmethod
- def from_args(cls, args: Any) -> UnitYAgentPipeline:
- return cls(args)
- class UnitYAgentTreePipeline(UnitYPipelineMixin, TreeAgentPipeline): # type: ignore
- pipeline: Any = {}
- def __init__(self, args: Namespace):
- models_and_configs = self.load_model(args)
- assert len(self.pipeline) > 0
- module_dict = {}
- for module_class, children in self.pipeline.items():
- module_dict[module_class.from_args(args, **models_and_configs)] = children
- super().__init__(module_dict, args)
- @classmethod
- def from_args(cls, args: Any) -> UnitYAgentPipeline:
- return cls(args)
- def pop(
- self, states: Optional[List[Optional[AgentStates]]] = None
- ) -> List[Segment]:
- output_segment = super().pop(states)
- if states is None:
- # Not stateless
- first_states = self.source_module.states
- else:
- assert len(states) == len(self.module_dict)
- first_states = states[self.source_module]
- if isinstance(output_segment, list):
- finished = any(segment.finished for segment in output_segment)
- else:
- # case when output_index is used
- finished = output_segment.finished
- if not first_states.source_finished and finished:
- # An early stop.
- # The temporary solution is to start over
- if states is not None:
- maybe_reset_states(states)
- else:
- self.reset()
- if isinstance(output_segment, list):
- for segment in output_segment:
- segment.finished = False
- else:
- output_segment.finished = False
- return output_segment # type: ignore[no-any-return]
|