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

online_text_decoder.py 15 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
  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. from argparse import ArgumentParser, Namespace
  8. from dataclasses import dataclass
  9. from typing import Any, Dict, List, Optional, Set, Tuple
  10. import torch
  11. from fairseq2.models.nllb.tokenizer import NllbTokenizer
  12. from fairseq2.nn.incremental_state import IncrementalStateBag
  13. from seamless_communication.models.monotonic_decoder import (
  14. MonotonicDecoderConfig,
  15. MonotonicDecoderModel,
  16. )
  17. from seamless_communication.streaming.agents.common import AgentStates
  18. from simuleval.agents import GenericAgent
  19. from simuleval.agents.actions import Action, ReadAction, WriteAction
  20. from simuleval.data.segments import Segment, TextSegment
  21. from torch import Tensor
  22. class DecoderAgentStates(AgentStates): # type: ignore
  23. def reset(self) -> None:
  24. self.source_len = 0
  25. self.target_indices: List[int] = []
  26. self.tgt_lang = None
  27. self.ngram_block_count = 0
  28. super().reset()
  29. def update_source(self, segment: Segment) -> None:
  30. """
  31. Update states from input segment
  32. Additionlly update incremental states
  33. Args:
  34. segment (~simuleval.agents.segments.Segment): input segment
  35. """
  36. self.source_finished = segment.finished
  37. if self.tgt_lang is None and segment.tgt_lang is not None:
  38. self.tgt_lang = segment.tgt_lang
  39. if not segment.is_empty:
  40. self.source = segment.content
  41. if len(self.source) == 0 and segment.finished:
  42. self.target_finished = True
  43. return
  44. self.source_len = self.source.size(1)
  45. class OnlineTextDecoderAgent(GenericAgent): # type: ignore
  46. """
  47. Online text decoder
  48. """
  49. target_type = "text"
  50. def __init__(
  51. self,
  52. model: MonotonicDecoderModel,
  53. config: MonotonicDecoderConfig,
  54. text_tokenizer: NllbTokenizer,
  55. args: Namespace,
  56. ) -> None:
  57. super().__init__(args)
  58. self.model = model
  59. self.config = config
  60. self.text_tokenizer = text_tokenizer
  61. self.max_len_a: int = args.max_len_a
  62. self.max_len_b: int = args.max_len_b
  63. self.max_consecutive_writes = self.args.max_consecutive_write
  64. self.min_starting_wait = args.min_starting_wait
  65. self.no_early_stop = args.no_early_stop
  66. self.device = args.device
  67. self.dtype = args.dtype
  68. self.eos_idx = text_tokenizer.vocab_info.eos_idx
  69. tgt_lang = getattr(args, "tgt_lang", None)
  70. assert tgt_lang is not None
  71. self.token_encoder = text_tokenizer.create_encoder(lang=tgt_lang, mode="target")
  72. prefix_indices = self.token_encoder.prefix_indices
  73. assert prefix_indices is not None
  74. self.prefix_indices: List[int] = prefix_indices.tolist()
  75. def build_states(self) -> DecoderAgentStates:
  76. return DecoderAgentStates()
  77. def max_len(self, states: DecoderAgentStates) -> int:
  78. return self.max_len_a * int(states.source.size(1)) + self.max_len_b
  79. @staticmethod
  80. def add_args(parser: ArgumentParser) -> None:
  81. parser.add_argument(
  82. "--max-len-a",
  83. type=int,
  84. default=1,
  85. help="Max length of predictions, a in ax + b",
  86. )
  87. parser.add_argument(
  88. "--max-len-b",
  89. type=int,
  90. default=200,
  91. help="Max length of predictions, b in ax + b",
  92. )
  93. parser.add_argument(
  94. "--max-consecutive-write",
  95. type=int,
  96. default=50,
  97. help="Max consecutive writes.",
  98. )
  99. parser.add_argument(
  100. "--min-starting-wait",
  101. type=int,
  102. default=1,
  103. help="Minimal starting waiting source steps",
  104. )
  105. parser.add_argument(
  106. "--no-early-stop",
  107. action="store_true",
  108. default=False,
  109. )
  110. parser.add_argument(
  111. "--tgt-lang",
  112. default="eng",
  113. type=str,
  114. )
  115. def policy(self, states: DecoderAgentStates) -> Action:
  116. raise NotImplementedError
  117. def enforce_tgt_lang_in_prefix(self, states: DecoderAgentStates) -> None:
  118. if states.tgt_lang:
  119. tgt_lang_tag = f"__{states.tgt_lang}__"
  120. tgt_lang_tag_idx = self.text_tokenizer.model.token_to_index(tgt_lang_tag)
  121. self.prefix_indices[-1] = tgt_lang_tag_idx
  122. class MMATextDecoderAgent(OnlineTextDecoderAgent): # type: ignore
  123. def __init__(
  124. self,
  125. model: MonotonicDecoderModel,
  126. config: MonotonicDecoderConfig,
  127. text_tokenizer: NllbTokenizer,
  128. args: Namespace,
  129. ) -> None:
  130. super().__init__(model, config, text_tokenizer, args=args)
  131. self.num_decoder_layers = self.config.num_decoder_layers
  132. self.decision_threshold = args.decision_threshold
  133. self.decision_method = args.decision_method
  134. self.block_ngrams = args.block_ngrams
  135. self.p_choose_start_layer = args.p_choose_start_layer
  136. @staticmethod
  137. def add_args(parser: ArgumentParser) -> None:
  138. OnlineTextDecoderAgent.add_args(parser)
  139. parser.add_argument(
  140. "--decision-threshold",
  141. type=float,
  142. default=0.5,
  143. help="The threshold to write an output, from 0 to 1. Small values give low latency.",
  144. )
  145. parser.add_argument(
  146. "--decision-method",
  147. type=str,
  148. default="min",
  149. choices=["mean", "min", "median"],
  150. help="The method to determine the decision. Either average all attention heads, or just pick the smallest one",
  151. )
  152. parser.add_argument(
  153. "--p-choose-start-layer",
  154. type=int,
  155. default=0,
  156. help="Encoder layer from which p_choose should be considered for selection.",
  157. )
  158. parser.add_argument(
  159. "--block-ngrams",
  160. action="store_true",
  161. )
  162. @classmethod
  163. def from_args(
  164. cls, args: Namespace, **kwargs: Dict[str, Any]
  165. ) -> MMATextDecoderAgent:
  166. model = kwargs.get("monotonic_decoder_model", None)
  167. config = kwargs.get("monotonic_decoder_config", None)
  168. text_tokenizer = kwargs.get("text_tokenizer", None)
  169. assert isinstance(model, MonotonicDecoderModel)
  170. assert isinstance(config, MonotonicDecoderConfig)
  171. assert isinstance(text_tokenizer, NllbTokenizer)
  172. return cls(
  173. model=model,
  174. config=config,
  175. text_tokenizer=text_tokenizer,
  176. args=args,
  177. )
  178. def run_decoder(
  179. self, states: DecoderAgentStates, pred_indices: List[int]
  180. ) -> Tuple[int, float, Tensor]:
  181. if len(pred_indices) == 0:
  182. self.enforce_tgt_lang_in_prefix(states)
  183. target_input = torch.tensor(
  184. self.prefix_indices + states.target_indices,
  185. device=self.device,
  186. dtype=torch.int64,
  187. ).unsqueeze(0)
  188. else:
  189. target_input = torch.tensor(
  190. pred_indices[-1:], device=self.device, dtype=torch.int64
  191. ).unsqueeze(0)
  192. encoder_output = states.source
  193. decoder_output, _, p_choose = self.model.decode(
  194. target_input, None, encoder_output, None, state_bag=self.state_bag
  195. )
  196. logits = self.model.project(decoder_output)
  197. if self.block_ngrams and states.source_finished:
  198. all_indices = states.target_indices + pred_indices
  199. blocked_indices = all_indices[-4:]
  200. logits[:, :, blocked_indices] = float("-inf")
  201. index = int(logits[0, -1].argmax().item())
  202. _, tgt_len, src_len = p_choose.size()
  203. p_choose = p_choose.view(self.num_decoder_layers, -1, tgt_len, src_len)
  204. if self.decision_method == "min":
  205. prob = p_choose[self.p_choose_start_layer :, :, -1, -1].min().item()
  206. elif self.decision_method == "mean":
  207. prob = p_choose[self.p_choose_start_layer :, :, -1, -1].mean().item()
  208. else:
  209. prob = p_choose[self.p_choose_start_layer :, :, -1, -1].median().item()
  210. return index, prob, decoder_output
  211. def postprocess(
  212. self,
  213. states: DecoderAgentStates,
  214. pred_indices: List[int],
  215. finished: bool,
  216. decoder_features_out: Optional[Tensor] = None,
  217. ) -> TextSegment:
  218. return TextSegment(
  219. content=" ".join(
  220. [self.text_tokenizer.model.index_to_token(idx) for idx in pred_indices]
  221. ),
  222. finished=finished,
  223. tgt_lang=states.tgt_lang,
  224. )
  225. def get_blocked_ngrams(self, target_indices: List[int]) -> Optional[Set[str]]:
  226. # TODO: make it configurable and use itertools
  227. if not self.block_ngrams:
  228. return None
  229. blocked_ngrams = set()
  230. if len(target_indices) >= 4:
  231. blocked_ngrams.add(str(target_indices[-4:]))
  232. blocked_ngrams.add(str(target_indices[-4:-2]))
  233. blocked_ngrams.add(str(target_indices[-4:-1]))
  234. if len(target_indices) >= 3:
  235. blocked_ngrams.add(str(target_indices[-3:]))
  236. blocked_ngrams.add(str(target_indices[-3:-1]))
  237. if len(target_indices) >= 2:
  238. blocked_ngrams.add(str(target_indices[-2:]))
  239. return blocked_ngrams
  240. def maybe_block_ngrams(
  241. self,
  242. states: DecoderAgentStates,
  243. pred_indices: List[int],
  244. decoder_features_out: Tensor,
  245. blocked_ngrams: Optional[Set[str]],
  246. index: int,
  247. ) -> Tuple[bool, Tensor]:
  248. """
  249. This check is used to force a READ decision when n-gram repeat
  250. happens before source_finished
  251. """
  252. if not self.block_ngrams or states.source_finished:
  253. return False, decoder_features_out
  254. assert blocked_ngrams is not None
  255. all_indices = states.target_indices + pred_indices + [index]
  256. for n in [3, 2]: # TODO: make it configurable
  257. if len(all_indices) >= n and states.ngram_block_count <= 4:
  258. if str(all_indices[-n:]) in blocked_ngrams:
  259. states.ngram_block_count += 1
  260. pred_indices[:] = pred_indices[: -(n - 1)]
  261. decoder_features_out = decoder_features_out[:, : -(n - 1)]
  262. return True, decoder_features_out
  263. blocked_ngrams.add(str(all_indices[-n:]))
  264. return False, decoder_features_out
  265. @torch.inference_mode()
  266. def policy(self, states: DecoderAgentStates) -> Action:
  267. if len(states.source) == 0:
  268. return ReadAction()
  269. if states.source_len < self.min_starting_wait and not states.source_finished:
  270. return ReadAction()
  271. if states.target_finished:
  272. return WriteAction("", finished=True)
  273. if len(states.source) == 0:
  274. return ReadAction()
  275. self.state_bag = IncrementalStateBag(4096)
  276. states.source_len = states.source.size(1)
  277. pred_indices: List[int] = []
  278. index = None
  279. prob = None
  280. finished = False
  281. blocked_ngrams = self.get_blocked_ngrams(states.target_indices)
  282. decoder_features_out = None
  283. while True:
  284. index, prob, decoder_features = self.run_decoder(states, pred_indices)
  285. if decoder_features_out is None:
  286. decoder_features_out = decoder_features.new(0)
  287. decoder_features_out = torch.cat(
  288. [decoder_features_out, decoder_features], dim=1
  289. )
  290. if (
  291. self.no_early_stop
  292. and not states.source_finished
  293. and (prob < self.decision_threshold or index == self.eos_idx)
  294. ):
  295. if prob == 1.0:
  296. pred_indices = []
  297. break
  298. block_ngram, decoder_features_out = self.maybe_block_ngrams(
  299. states, pred_indices, decoder_features_out, blocked_ngrams, index
  300. )
  301. if block_ngram:
  302. break
  303. if (
  304. finished
  305. or index == self.eos_idx
  306. or len(states.target_indices + pred_indices) > self.max_len(states)
  307. ):
  308. finished = True
  309. break
  310. if prob < self.decision_threshold and not states.source_finished:
  311. break
  312. if (
  313. len(states.target_indices + pred_indices) >= self.max_len(states)
  314. or len(pred_indices) >= self.max_consecutive_writes
  315. ):
  316. break
  317. pred_indices.append(index)
  318. if self.state_bag.step_nr == 0:
  319. self.state_bag.increment_step_nr(
  320. len(self.prefix_indices + states.target_indices)
  321. )
  322. else:
  323. self.state_bag.increment_step_nr()
  324. states.target_indices += pred_indices
  325. if len(pred_indices) > 0 or finished:
  326. finished = finished or len(
  327. states.target_indices + pred_indices
  328. ) > self.max_len(states)
  329. states.ngram_block_count = 0
  330. return WriteAction(
  331. self.postprocess(states, pred_indices, finished, decoder_features_out),
  332. finished=finished,
  333. )
  334. else:
  335. return ReadAction()
  336. class MMASpeechToTextDecoderAgent(MMATextDecoderAgent):
  337. source_type = "speech"
  338. @dataclass
  339. class UnitYTextDecoderOutput:
  340. decoder_features: Tensor
  341. tokens: List[str]
  342. target_indices: Optional[Tensor] = None
  343. class UnitYMMATextDecoderAgent(MMASpeechToTextDecoderAgent):
  344. """
  345. MMA UnitY text decoder agent which just prepares the decoder
  346. output for the downstream agent.
  347. """
  348. def postprocess(
  349. self,
  350. states: DecoderAgentStates,
  351. pred_indices: List[int],
  352. finished: bool,
  353. decoder_features_out: Optional[Tensor] = None,
  354. ) -> TextSegment:
  355. tokens: List[str] = [
  356. self.text_tokenizer.model.index_to_token(idx) for idx in pred_indices
  357. ]
  358. assert decoder_features_out is not None
  359. token_list = self.prefix_indices + states.target_indices
  360. if (
  361. len(pred_indices) > 0
  362. and pred_indices[-1] != self.text_tokenizer.vocab_info.eos_idx
  363. ):
  364. # Append "," to make speech smooth
  365. # TODO: a temporary solution.
  366. ending_token_index = self.text_tokenizer.model.token_to_index(",")
  367. token_list.append(ending_token_index)
  368. self.state_bag.increment_step_nr()
  369. _, _, decoder_features = self.run_decoder(states, [ending_token_index])
  370. decoder_features_out = torch.cat(
  371. [decoder_features_out, decoder_features], dim=1
  372. )
  373. target_input = torch.tensor(
  374. token_list,
  375. device=self.device,
  376. dtype=torch.int64,
  377. ).unsqueeze(0)
  378. return TextSegment(
  379. content=UnitYTextDecoderOutput(decoder_features_out, tokens, target_input),
  380. finished=finished,
  381. tgt_lang=states.tgt_lang,
  382. )
Tip!

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

Comments

Loading...