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_unit_decoder.py 5.7 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
  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 typing import Any, List, Optional
  9. import torch
  10. from seamless_communication.models.unity.model import UnitYModel, UnitYNART2UModel
  11. from seamless_communication.models.unity.unit_tokenizer import UnitTokenizer
  12. from seamless_communication.streaming.agents.online_text_decoder import (
  13. UnitYTextDecoderOutput,
  14. )
  15. from seamless_communication.streaming.agents.common import AgentStates
  16. from simuleval.agents import GenericAgent
  17. from simuleval.agents.actions import Action, ReadAction, WriteAction
  18. from simuleval.data.segments import Segment, TextSegment
  19. class NARUnitDecoderAgentStates(AgentStates): # type: ignore
  20. def reset(self) -> None:
  21. self.source_token_list: List[str] = []
  22. self.source_indices: Optional[torch.Tensor] = None
  23. self.duration_start_index: int = 0
  24. self.tgt_lang = None
  25. super().reset()
  26. def update_source(self, segment: Segment) -> None:
  27. """
  28. Update states from input segment
  29. Additionlly update incremental states
  30. Args:
  31. segment (~simuleval.agents.segments.Segment): input segment
  32. """
  33. self.source_finished = segment.finished
  34. if self.tgt_lang is None and segment.tgt_lang is not None:
  35. self.tgt_lang = segment.tgt_lang
  36. if segment.is_empty:
  37. if segment.finished:
  38. self.target_finished = True
  39. return
  40. segment_content: UnitYTextDecoderOutput = segment.content
  41. content = segment_content.decoder_features
  42. token = segment_content.tokens
  43. self.source_indices = segment_content.target_indices
  44. self.source_token_list += token
  45. self.source = content
  46. class NARUnitYUnitDecoderAgent(GenericAgent): # type: ignore
  47. """Non-autoregressive unit decoder"""
  48. source_type = "text"
  49. target_type = "text"
  50. def __init__(
  51. self, model: UnitYNART2UModel, tokenizer: UnitTokenizer, args: Namespace
  52. ) -> None:
  53. self.model = model
  54. self.tokenizer = tokenizer
  55. self.min_unit_chunk_size = args.min_unit_chunk_size
  56. self.d_factor = args.d_factor
  57. self.device = args.device
  58. self.dtype = args.dtype
  59. self.token_decoder = self.tokenizer.create_decoder()
  60. super().__init__(args)
  61. def build_states(self) -> NARUnitDecoderAgentStates:
  62. return NARUnitDecoderAgentStates()
  63. @property
  64. def max_len(self) -> int:
  65. return 200
  66. @staticmethod
  67. def add_args(parser: ArgumentParser) -> None:
  68. parser.add_argument(
  69. "--min-unit-chunk-size",
  70. type=int,
  71. required=True,
  72. help="Minimal units to produce every chunk",
  73. )
  74. parser.add_argument(
  75. "--d-factor",
  76. type=float,
  77. default=1.0,
  78. help="scaling factor for duration prediction",
  79. )
  80. @torch.inference_mode()
  81. def policy(self, states: NARUnitDecoderAgentStates) -> Action:
  82. if states.target_finished:
  83. return WriteAction("", finished=True)
  84. if len(states.source_token_list) < 2:
  85. if not states.source_finished:
  86. return ReadAction()
  87. else:
  88. return WriteAction("", finished=True)
  89. model_output, _, durations = self.model(
  90. text_decoder_output=states.source,
  91. text_decoder_padding_mask=None,
  92. text_seqs=states.source_indices,
  93. duration_factor=self.d_factor,
  94. )
  95. durations = durations[0]
  96. if states.source_finished and states.duration_start_index > 0:
  97. # We have to consider one more word for EOS, because we append an EOS at the end.
  98. if sum(durations[states.duration_start_index :]) == 0:
  99. # If you reach here, it means that the last source token is a silence token (e.g. punctuations)
  100. # In that case no need to consider one more token.
  101. return WriteAction("", finished=True)
  102. else:
  103. states.duration_start_index = max(states.duration_start_index - 1, 0)
  104. current_duration = sum(durations[states.duration_start_index :])
  105. if current_duration < self.min_unit_chunk_size:
  106. if not states.source_finished:
  107. # if current untranslated source result less than self.min_unit_chunk_size units
  108. return ReadAction()
  109. else:
  110. if current_duration == 0:
  111. return WriteAction("", finished=True)
  112. unit_seqs = model_output.logits[0].argmax(dim=-1)
  113. index_start_offset = sum(durations[: states.duration_start_index])
  114. unit_seqs = unit_seqs[index_start_offset:].unsqueeze(0)
  115. units = self.token_decoder(unit_seqs)
  116. # minus one because we add a ending_token on each s2t output phrase
  117. states.duration_start_index = len(durations) - 1
  118. return WriteAction(
  119. TextSegment(
  120. content=units,
  121. finished=states.source_finished,
  122. tgt_lang=states.tgt_lang,
  123. ),
  124. finished=states.source_finished,
  125. )
  126. @classmethod
  127. def from_args(cls, args: Namespace, **kwargs: Any) -> NARUnitYUnitDecoderAgent:
  128. unity_model: UnitYModel = kwargs.get("unity_model", None)
  129. unit_tokenizer: UnitTokenizer = kwargs.get("unit_tokenizer", None)
  130. assert unity_model.t2u_model is not None and isinstance(
  131. unity_model.t2u_model, UnitYNART2UModel
  132. )
  133. return cls(model=unity_model.t2u_model, tokenizer=unit_tokenizer, args=args)
Tip!

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

Comments

Loading...