Upload 10 files
Browse files- speech_tokenizer/__init__.py +0 -0
- speech_tokenizer/__pycache__/__init__.cpython-310.pyc +0 -0
- speech_tokenizer/__pycache__/configuration_whisper.cpython-310.pyc +0 -0
- speech_tokenizer/__pycache__/generation_whisper.cpython-310.pyc +0 -0
- speech_tokenizer/__pycache__/modeling_whisper.cpython-310.pyc +0 -0
- speech_tokenizer/__pycache__/utils.cpython-310.pyc +0 -0
- speech_tokenizer/configuration_whisper.py +37 -0
- speech_tokenizer/generation_whisper.py +1828 -0
- speech_tokenizer/modeling_whisper.py +0 -0
- speech_tokenizer/utils.py +84 -0
speech_tokenizer/__init__.py
ADDED
File without changes
|
speech_tokenizer/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (139 Bytes). View file
|
|
speech_tokenizer/__pycache__/configuration_whisper.cpython-310.pyc
ADDED
Binary file (1.24 kB). View file
|
|
speech_tokenizer/__pycache__/generation_whisper.cpython-310.pyc
ADDED
Binary file (59.5 kB). View file
|
|
speech_tokenizer/__pycache__/modeling_whisper.cpython-310.pyc
ADDED
Binary file (81.1 kB). View file
|
|
speech_tokenizer/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (2.96 kB). View file
|
|
speech_tokenizer/configuration_whisper.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import WhisperConfig
|
2 |
+
|
3 |
+
|
4 |
+
class WhisperVQConfig(WhisperConfig):
|
5 |
+
def __init__(self,
|
6 |
+
pooling_kernel_size=None,
|
7 |
+
pooling_type="max",
|
8 |
+
pooling_position=0,
|
9 |
+
quantize_vocab_size=None,
|
10 |
+
quantize_position=16,
|
11 |
+
quantize_commit_coefficient=0.25,
|
12 |
+
quantize_loss_scale=1.0,
|
13 |
+
quantize_ema_decay=None,
|
14 |
+
quantize_restart_interval=None,
|
15 |
+
quantize_encoder_only=False,
|
16 |
+
quantize_causal_encoder=False,
|
17 |
+
quantize_causal_block_size=None,
|
18 |
+
skip_language_detection=False,
|
19 |
+
encoder_causal_attention=False,
|
20 |
+
encoder_causal_convolution=False,
|
21 |
+
**kwargs):
|
22 |
+
self.pooling_kernel_size = pooling_kernel_size
|
23 |
+
self.pooling_type = pooling_type
|
24 |
+
self.pooling_position = pooling_position
|
25 |
+
self.quantize_vocab_size = quantize_vocab_size
|
26 |
+
self.quantize_position = quantize_position
|
27 |
+
self.quantize_commit_coefficient = quantize_commit_coefficient
|
28 |
+
self.quantize_loss_scale = quantize_loss_scale
|
29 |
+
self.quantize_ema_decay = quantize_ema_decay
|
30 |
+
self.quantize_restart_interval = quantize_restart_interval
|
31 |
+
self.quantize_encoder_only = quantize_encoder_only
|
32 |
+
self.quantize_causal_encoder = quantize_causal_encoder
|
33 |
+
self.quantize_causal_block_size = quantize_causal_block_size
|
34 |
+
self.skip_language_detection = skip_language_detection
|
35 |
+
self.encoder_causal_attention = encoder_causal_attention
|
36 |
+
self.encoder_causal_convolution = encoder_causal_convolution
|
37 |
+
super().__init__(**kwargs)
|
speech_tokenizer/generation_whisper.py
ADDED
@@ -0,0 +1,1828 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
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 |
+
import copy
|
16 |
+
import math
|
17 |
+
import warnings
|
18 |
+
import zlib
|
19 |
+
from typing import Callable, Iterator, List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import numpy as np
|
22 |
+
import torch
|
23 |
+
import torch.nn.functional as F
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.cache_utils import EncoderDecoderCache
|
27 |
+
|
28 |
+
from transformers.generation.configuration_utils import GenerationConfig
|
29 |
+
from transformers.generation.logits_process import (
|
30 |
+
LogitsProcessorList,
|
31 |
+
SuppressTokensAtBeginLogitsProcessor,
|
32 |
+
SuppressTokensLogitsProcessor,
|
33 |
+
WhisperNoSpeechDetection,
|
34 |
+
WhisperTimeStampLogitsProcessor,
|
35 |
+
)
|
36 |
+
from transformers.generation.stopping_criteria import StoppingCriteriaList
|
37 |
+
from transformers.modeling_outputs import BaseModelOutput
|
38 |
+
from transformers.utils import logging
|
39 |
+
from transformers.models.whisper.tokenization_whisper import TASK_IDS, TO_LANGUAGE_CODE
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
|
45 |
+
def _median_filter(inputs: torch.Tensor, filter_width: int) -> torch.Tensor:
|
46 |
+
"""
|
47 |
+
Applies a median filter of width `filter_width` along the last dimension of the input.
|
48 |
+
|
49 |
+
The `inputs` tensor is assumed to be 3- or 4-dimensional.
|
50 |
+
"""
|
51 |
+
if filter_width <= 0 or filter_width % 2 != 1:
|
52 |
+
raise ValueError("`filter_width` should be an odd number")
|
53 |
+
|
54 |
+
pad_width = filter_width // 2
|
55 |
+
if inputs.shape[-1] <= pad_width:
|
56 |
+
return inputs
|
57 |
+
|
58 |
+
# Pad the left and right edges.
|
59 |
+
inputs = nn.functional.pad(inputs, (pad_width, pad_width, 0, 0), mode="reflect")
|
60 |
+
|
61 |
+
# sort() is faster than torch.median (https://github.com/pytorch/pytorch/issues/51450)
|
62 |
+
result = inputs.unfold(-1, filter_width, 1).sort()[0][..., pad_width]
|
63 |
+
return result
|
64 |
+
|
65 |
+
|
66 |
+
def _dynamic_time_warping(matrix: np.ndarray):
|
67 |
+
"""
|
68 |
+
Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate
|
69 |
+
token-level timestamps.
|
70 |
+
"""
|
71 |
+
output_length, input_length = matrix.shape
|
72 |
+
cost = np.ones((output_length + 1, input_length + 1), dtype=np.float32) * np.inf
|
73 |
+
trace = -np.ones((output_length + 1, input_length + 1), dtype=np.float32)
|
74 |
+
|
75 |
+
cost[0, 0] = 0
|
76 |
+
for j in range(1, input_length + 1):
|
77 |
+
for i in range(1, output_length + 1):
|
78 |
+
c0 = cost[i - 1, j - 1]
|
79 |
+
c1 = cost[i - 1, j]
|
80 |
+
c2 = cost[i, j - 1]
|
81 |
+
|
82 |
+
if c0 < c1 and c0 < c2:
|
83 |
+
c, t = c0, 0
|
84 |
+
elif c1 < c0 and c1 < c2:
|
85 |
+
c, t = c1, 1
|
86 |
+
else:
|
87 |
+
c, t = c2, 2
|
88 |
+
|
89 |
+
cost[i, j] = matrix[i - 1, j - 1] + c
|
90 |
+
trace[i, j] = t
|
91 |
+
|
92 |
+
# backtrace
|
93 |
+
i = trace.shape[0] - 1
|
94 |
+
j = trace.shape[1] - 1
|
95 |
+
trace[0, :] = 2
|
96 |
+
trace[:, 0] = 1
|
97 |
+
|
98 |
+
text_indices = []
|
99 |
+
time_indices = []
|
100 |
+
while i > 0 or j > 0:
|
101 |
+
text_indices.append(i - 1)
|
102 |
+
time_indices.append(j - 1)
|
103 |
+
if trace[i, j] == 0:
|
104 |
+
i -= 1
|
105 |
+
j -= 1
|
106 |
+
elif trace[i, j] == 1:
|
107 |
+
i -= 1
|
108 |
+
elif trace[i, j] == 2:
|
109 |
+
j -= 1
|
110 |
+
else:
|
111 |
+
raise RuntimeError(
|
112 |
+
f"Internal error in dynamic time warping. Unexpected trace[{i}, {j}]. Please file a bug report."
|
113 |
+
)
|
114 |
+
|
115 |
+
text_indices = np.array(text_indices)[::-1]
|
116 |
+
time_indices = np.array(time_indices)[::-1]
|
117 |
+
return text_indices, time_indices
|
118 |
+
|
119 |
+
|
120 |
+
def _get_attr_from_logit_processors(logits_processor, logit_processor_class, attribute_name):
|
121 |
+
if logits_processor is not None:
|
122 |
+
logit_processor = next((cls for cls in logits_processor if isinstance(cls, logit_processor_class)), None)
|
123 |
+
if logit_processor:
|
124 |
+
return getattr(logit_processor, attribute_name, None)
|
125 |
+
return None
|
126 |
+
|
127 |
+
|
128 |
+
def _pad_to_max_length(
|
129 |
+
current_segments,
|
130 |
+
pad_token_id,
|
131 |
+
device,
|
132 |
+
padding_side="right",
|
133 |
+
padding="longest",
|
134 |
+
bos_token_tensor=None,
|
135 |
+
cut_off_length=None,
|
136 |
+
):
|
137 |
+
max_total_length = 0
|
138 |
+
sequences = []
|
139 |
+
|
140 |
+
if padding_side not in ["right", "left"]:
|
141 |
+
raise ValueError(f"`padding_side` must be either 'right' or 'left', not {padding_side}")
|
142 |
+
|
143 |
+
if padding not in ["longest", "max_length"]:
|
144 |
+
raise ValueError(f"`padding` must be either 'longest' or 'max_length', not {padding}")
|
145 |
+
elif padding == "max_length" and cut_off_length is None:
|
146 |
+
raise ValueError("`cut_off_length` must be specified when `padding='max_length'`")
|
147 |
+
|
148 |
+
for current_segment_list in current_segments:
|
149 |
+
if current_segment_list is not None and len([d["tokens"] for d in current_segment_list]) > 0:
|
150 |
+
sequence = torch.cat([d["tokens"] for d in current_segment_list], dim=-1)
|
151 |
+
|
152 |
+
if cut_off_length is not None:
|
153 |
+
sequence = sequence[-cut_off_length:]
|
154 |
+
|
155 |
+
if bos_token_tensor is not None:
|
156 |
+
sequence = torch.cat([bos_token_tensor, sequence])
|
157 |
+
|
158 |
+
sequences.append(sequence)
|
159 |
+
max_total_length = max(max_total_length, len(sequences[-1]))
|
160 |
+
elif bos_token_tensor is not None:
|
161 |
+
sequences.append(bos_token_tensor)
|
162 |
+
else:
|
163 |
+
sequences.append(torch.tensor([], device=device))
|
164 |
+
|
165 |
+
max_total_length = cut_off_length + 1 if padding == "max_length" else max_total_length
|
166 |
+
for i in range(len(current_segments)):
|
167 |
+
pad_length = max_total_length - len(sequences[i])
|
168 |
+
pad = (0, pad_length) if padding_side == "right" else (pad_length, 0)
|
169 |
+
sequences[i] = F.pad(sequences[i], pad=pad, value=pad_token_id)
|
170 |
+
|
171 |
+
sequences = torch.stack(sequences, dim=0)
|
172 |
+
return sequences
|
173 |
+
|
174 |
+
|
175 |
+
class WhisperGenerationMixin:
|
176 |
+
def _extract_token_timestamps(self, generate_outputs, alignment_heads, time_precision=0.02, num_frames=None):
|
177 |
+
"""
|
178 |
+
Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to
|
179 |
+
map each output token to a position in the input audio. If `num_frames` is specified, the encoder-decoder
|
180 |
+
cross-attentions will be cropped before applying DTW.
|
181 |
+
|
182 |
+
Returns:
|
183 |
+
tensor containing the timestamps in seconds for each predicted token
|
184 |
+
"""
|
185 |
+
# Create a list with `decoder_layers` elements, each a tensor of shape
|
186 |
+
# (batch size, attention_heads, output length, input length).
|
187 |
+
cross_attentions = []
|
188 |
+
for i in range(self.config.decoder_layers):
|
189 |
+
cross_attentions.append(torch.cat([x[i] for x in generate_outputs.cross_attentions], dim=2))
|
190 |
+
|
191 |
+
# Select specific cross-attention layers and heads. This is a tensor
|
192 |
+
# of shape (batch size, num selected, output length, input length).
|
193 |
+
weights = torch.stack([cross_attentions[l][:, h] for l, h in alignment_heads])
|
194 |
+
weights = weights.permute([1, 0, 2, 3])
|
195 |
+
|
196 |
+
weight_length = None
|
197 |
+
|
198 |
+
if "beam_indices" in generate_outputs:
|
199 |
+
# If beam search has been used, the output sequences may have been generated for more timesteps than their sequence_lengths
|
200 |
+
# since the beam search strategy chooses the most probable sequences at the end of the search.
|
201 |
+
# In that case, the cross_attentions weights are too long and we have to make sure that they have the right output_length
|
202 |
+
weight_length = (generate_outputs.beam_indices != -1).sum(-1).max()
|
203 |
+
weights = weights[:, :, :weight_length]
|
204 |
+
|
205 |
+
# If beam index is still -1, it means that the associated token id is EOS
|
206 |
+
# We need to replace the index with 0 since index_select gives an error if any of the indexes is -1.
|
207 |
+
beam_indices = generate_outputs.beam_indices[:, :weight_length]
|
208 |
+
beam_indices = beam_indices.masked_fill(beam_indices == -1, 0)
|
209 |
+
|
210 |
+
# Select the cross attention from the right beam for each output sequences
|
211 |
+
weights = torch.stack(
|
212 |
+
[
|
213 |
+
torch.index_select(weights[:, :, i, :], dim=0, index=beam_indices[:, i])
|
214 |
+
for i in range(beam_indices.shape[1])
|
215 |
+
],
|
216 |
+
dim=2,
|
217 |
+
)
|
218 |
+
|
219 |
+
# make sure timestamps are as long as weights
|
220 |
+
input_length = weight_length or cross_attentions[0].shape[2]
|
221 |
+
timestamps = torch.zeros_like(generate_outputs.sequences, dtype=torch.float32)[:, : input_length + 1]
|
222 |
+
batch_size = timestamps.shape[0]
|
223 |
+
|
224 |
+
if num_frames is not None:
|
225 |
+
# two cases:
|
226 |
+
# 1. num_frames is the same for each sample -> compute the DTW matrix for each sample in parallel
|
227 |
+
# 2. num_frames is different, compute the DTW matrix for each sample sequentially
|
228 |
+
|
229 |
+
# we're using np.unique because num_frames can be int/list/tuple
|
230 |
+
if isinstance(num_frames, int):
|
231 |
+
weights = weights[..., : num_frames // 2]
|
232 |
+
|
233 |
+
elif isinstance(num_frames, (list, tuple, np.ndarray)) and len(np.unique(num_frames)) == 1:
|
234 |
+
weights = weights[..., : num_frames[0] // 2]
|
235 |
+
|
236 |
+
elif isinstance(num_frames, (torch.Tensor)) and len(torch.unique(num_frames)) == 1:
|
237 |
+
weights = weights[..., : num_frames[0] // 2]
|
238 |
+
|
239 |
+
else:
|
240 |
+
# num_frames is of shape (batch_size,) whereas batch_size is truely batch_size*num_return_sequences
|
241 |
+
repeat_time = batch_size if isinstance(num_frames, int) else batch_size // len(num_frames)
|
242 |
+
num_frames = np.repeat(num_frames, repeat_time)
|
243 |
+
|
244 |
+
if num_frames is None or isinstance(num_frames, int):
|
245 |
+
# Normalize and smoothen the weights.
|
246 |
+
std = torch.std(weights, dim=-2, keepdim=True, unbiased=False)
|
247 |
+
mean = torch.mean(weights, dim=-2, keepdim=True)
|
248 |
+
weights = (weights - mean) / std
|
249 |
+
weights = _median_filter(weights, self.config.median_filter_width)
|
250 |
+
|
251 |
+
# Average the different cross-attention heads.
|
252 |
+
weights = weights.mean(dim=1)
|
253 |
+
|
254 |
+
# Perform dynamic time warping on each element of the batch.
|
255 |
+
for batch_idx in range(batch_size):
|
256 |
+
if num_frames is not None and isinstance(num_frames, (tuple, list, np.ndarray, torch.Tensor)):
|
257 |
+
matrix = weights[batch_idx, ..., : num_frames[batch_idx] // 2]
|
258 |
+
|
259 |
+
# Normalize and smoothen the weights.
|
260 |
+
std = torch.std(matrix, dim=-2, keepdim=True, unbiased=False)
|
261 |
+
mean = torch.mean(matrix, dim=-2, keepdim=True)
|
262 |
+
matrix = (matrix - mean) / std
|
263 |
+
matrix = _median_filter(matrix, self.config.median_filter_width)
|
264 |
+
|
265 |
+
# Average the different cross-attention heads.
|
266 |
+
matrix = matrix.mean(dim=0)
|
267 |
+
else:
|
268 |
+
matrix = weights[batch_idx]
|
269 |
+
|
270 |
+
text_indices, time_indices = _dynamic_time_warping(-matrix.cpu().double().numpy())
|
271 |
+
jumps = np.pad(np.diff(text_indices), (1, 0), constant_values=1).astype(bool)
|
272 |
+
jump_times = time_indices[jumps] * time_precision
|
273 |
+
timestamps[batch_idx, 1:] = torch.tensor(jump_times)
|
274 |
+
|
275 |
+
return timestamps
|
276 |
+
|
277 |
+
def generate(
|
278 |
+
self,
|
279 |
+
input_features: Optional[torch.Tensor] = None,
|
280 |
+
generation_config: Optional[GenerationConfig] = None,
|
281 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
282 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
283 |
+
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
|
284 |
+
synced_gpus: bool = False,
|
285 |
+
return_timestamps: Optional[bool] = None,
|
286 |
+
task: Optional[str] = None,
|
287 |
+
language: Optional[Union[str, List[str]]] = None,
|
288 |
+
is_multilingual: Optional[bool] = None,
|
289 |
+
prompt_ids: Optional[torch.Tensor] = None,
|
290 |
+
prompt_condition_type: Optional[str] = None, # first-segment, all-segments
|
291 |
+
condition_on_prev_tokens: Optional[bool] = None,
|
292 |
+
temperature: Optional[Union[float, Tuple[float, ...]]] = None,
|
293 |
+
compression_ratio_threshold: Optional[float] = None,
|
294 |
+
logprob_threshold: Optional[float] = None,
|
295 |
+
no_speech_threshold: Optional[float] = None,
|
296 |
+
num_segment_frames: Optional[int] = None,
|
297 |
+
attention_mask: Optional[torch.Tensor] = None,
|
298 |
+
time_precision: float = 0.02,
|
299 |
+
return_token_timestamps: Optional[bool] = None,
|
300 |
+
return_segments: bool = False,
|
301 |
+
return_dict_in_generate: Optional[bool] = None,
|
302 |
+
**kwargs,
|
303 |
+
):
|
304 |
+
"""
|
305 |
+
Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.
|
306 |
+
|
307 |
+
<Tip warning={true}>
|
308 |
+
|
309 |
+
Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
|
310 |
+
model's default generation configuration. You can override any `generation_config` by passing the corresponding
|
311 |
+
parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
|
312 |
+
|
313 |
+
For an overview of generation strategies and code examples, check out the [following
|
314 |
+
guide](./generation_strategies).
|
315 |
+
|
316 |
+
</Tip>
|
317 |
+
|
318 |
+
Parameters:
|
319 |
+
input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):
|
320 |
+
Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by
|
321 |
+
loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
|
322 |
+
the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
|
323 |
+
[`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
|
324 |
+
tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] for details.
|
325 |
+
generation_config (`~generation.GenerationConfig`, *optional*):
|
326 |
+
The generation configuration to be used as base parametrization for the generation call. `**kwargs`
|
327 |
+
passed to generate matching the attributes of `generation_config` will override them. If
|
328 |
+
`generation_config` is not provided, the default will be used, which had the following loading
|
329 |
+
priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
|
330 |
+
configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
|
331 |
+
default values, whose documentation should be checked to parameterize generation.
|
332 |
+
logits_processor (`LogitsProcessorList`, *optional*):
|
333 |
+
Custom logits processors that complement the default logits processors built from arguments and
|
334 |
+
generation config. If a logit processor is passed that is already created with the arguments or a
|
335 |
+
generation config an error is thrown. This feature is intended for advanced users.
|
336 |
+
stopping_criteria (`StoppingCriteriaList`, *optional*):
|
337 |
+
Custom stopping criteria that complement the default stopping criteria built from arguments and a
|
338 |
+
generation config. If a stopping criteria is passed that is already created with the arguments or a
|
339 |
+
generation config an error is thrown. This feature is intended for advanced users.
|
340 |
+
prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
|
341 |
+
If provided, this function constraints the beam search to allowed tokens only at each step. If not
|
342 |
+
provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
|
343 |
+
`input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
|
344 |
+
on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
|
345 |
+
for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
|
346 |
+
Retrieval](https://arxiv.org/abs/2010.00904).
|
347 |
+
synced_gpus (`bool`, *optional*, defaults to `False`):
|
348 |
+
Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
|
349 |
+
return_timestamps (`bool`, *optional*):
|
350 |
+
Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
|
351 |
+
task (`str`, *optional*):
|
352 |
+
Task to use for generation, either "translate" or "transcribe". The `model.config.forced_decoder_ids`
|
353 |
+
will be updated accordingly.
|
354 |
+
language (`str` or list of `str`, *optional*):
|
355 |
+
Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. For
|
356 |
+
batched generation, a list of language tokens can be passed. You can find all the possible language
|
357 |
+
tokens in the `model.generation_config.lang_to_id` dictionary.
|
358 |
+
is_multilingual (`bool`, *optional*):
|
359 |
+
Whether or not the model is multilingual.
|
360 |
+
prompt_ids (`torch.Tensor`, *optional*):
|
361 |
+
Rank-1 tensor of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is
|
362 |
+
provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for
|
363 |
+
transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words
|
364 |
+
correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.
|
365 |
+
prompt_condition_type (`str`, *optional*):
|
366 |
+
Only relevant for long-form transcription. Condition type of `prompt_ids`. 'first-segment' means only the first segment is conditioned on `prompt_ids`. 'all-segments' means each segment is conditioned on `prompt_ids`. Make sure to enable `condition_on_prev_tokens` for 'all-segments'.
|
367 |
+
Defaults to 'first-segment'. For short-term transcription only 'first-segment' is possible.
|
368 |
+
condition_on_prev_tokens (`bool`, *optional*):
|
369 |
+
Only relevant for long-form transcription. Whether to condition each segment on the previous segment.
|
370 |
+
As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
|
371 |
+
performance.
|
372 |
+
temperature (`float` or list of `float`, *optional*):
|
373 |
+
The temperature to be used for generation. Passing a single `float` value and `do_sample=True` activates
|
374 |
+
generation using sampling. For long-form transcription, temperature fallback can be activated by passing
|
375 |
+
a list of float values such as (0.0, 0.2, 0.4, 0.6, 0.8, 1.0). As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
|
376 |
+
performance.
|
377 |
+
compression_ratio_threshold (`float`, *optional*):
|
378 |
+
Only relevant for long-form transcription. If defined, the zlib compression rate of each segment will be computed. If the compression rate of
|
379 |
+
a segment is higher than `compression_ratio_threshold`, temperature fallback is activated: the generated segment is discarded and the generation is
|
380 |
+
repeated using a higher temperature. The intuition behind this feature is that segments with very high compression rates
|
381 |
+
suffer from a lot of repetition. The unwanted repetition can be reduced by injecting more randomness by increasing the temperature. If `compression_ratio_threshold` is defined
|
382 |
+
make sure that `temperature` is a list of values. A common value for `compression_ratio_threshold` is 1.35.
|
383 |
+
As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
|
384 |
+
performance.
|
385 |
+
logprob_threshold (`float`, *optional*):
|
386 |
+
Only relevant for long-form transcription. If defined, the average log-probability of each segment will be computed. If the log-probability of
|
387 |
+
a given segment is lower than `logprob_threshold`, temperature fallback is activated: the generated segment is discarded and the generation is
|
388 |
+
repeated using a higher temperature. The intuition behind this feature is that segments of low log-probability
|
389 |
+
can be improved by injecting more randomness by increasing the temperature. If `logprob_threshold` is defined
|
390 |
+
make sure that `temperature` is a list of values. A common value for `logprob_threshold` is -1.0.
|
391 |
+
As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
|
392 |
+
performance.
|
393 |
+
no_speech_threshold (`float`, *optional*):
|
394 |
+
Only relevant for long-form transcription. If defined, the "no-speech" token combined with the `logprob_threshold`
|
395 |
+
is used to determine whether a segment contains only silence. In this case, the transcription for this segment
|
396 |
+
is skipped.
|
397 |
+
As shown in the [the Whisper paper](https://cdn.openai.com/papers/whisper.pdf), this can help to improve
|
398 |
+
performance.
|
399 |
+
num_segment_frames (`int`, *optional*):
|
400 |
+
The number of frames a single segment is made of. If not defined, `num_segment_frames` defaults to the model's stride
|
401 |
+
times the maximum input length.
|
402 |
+
attention_mask (`torch.Tensor`, *optional*):
|
403 |
+
`attention_mask` needs to be passed when doing long-form transcription using a batch size > 1.
|
404 |
+
time_precision (`int`, *optional*, defaults to 0.02):
|
405 |
+
The duration of output token in seconds. *E.g.* 0.02 means that a generated token on average accounts
|
406 |
+
for 20 ms.
|
407 |
+
return_token_timestamps (`bool`, *optional*):
|
408 |
+
Whether to return token-level timestamps with the text. This can be used with or without the
|
409 |
+
`return_timestamps` option. To get word-level timestamps, use the tokenizer to group the tokens into
|
410 |
+
words.
|
411 |
+
return_segments (`bool`, *optional*, defaults to `False`):
|
412 |
+
Whether to additionally return a list of all segments. Note that this option can only be enabled
|
413 |
+
when doing long-form transcription.
|
414 |
+
return_dict_in_generate (`bool`, *optional*, defaults to `False`):
|
415 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of just returning the generated tokens.
|
416 |
+
Note that when doing long-form transcription, `return_dict_in_generate` can only be enabled when
|
417 |
+
`return_segments` is set True. In this case the generation outputs of each segment is added to each
|
418 |
+
segment.
|
419 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
420 |
+
Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
|
421 |
+
forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
|
422 |
+
specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
|
423 |
+
|
424 |
+
Return:
|
425 |
+
[`~utils.ModelOutput`] or `torch.LongTensor` or `Dict[str, Any]`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
|
426 |
+
or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor` or a dict of segments when `return_segments=True`.
|
427 |
+
|
428 |
+
If the passed input is > 30 seconds / > 3000 mel input features and `return_segments=True` then a dictionary of generated sequence ids, called `sequences` and a list of each generated segment is returned.
|
429 |
+
|
430 |
+
else if the passed input is <= 30 seconds / >= 3000 mel input features, the possible [`~utils.ModelOutput`] types are:
|
431 |
+
|
432 |
+
- [`~generation.GenerateEncoderDecoderOutput`],
|
433 |
+
- [`~generation.GenerateBeamEncoderDecoderOutput`]
|
434 |
+
|
435 |
+
else only the generated output sequence ids are returned.
|
436 |
+
|
437 |
+
Example:
|
438 |
+
|
439 |
+
- *Longform transcription*: To transcribe or translate audios longer than 30 seconds, process the audio files without truncation and pass all mel features at once to generate.
|
440 |
+
|
441 |
+
```python
|
442 |
+
>>> import torch
|
443 |
+
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
|
444 |
+
>>> from datasets import load_dataset, Audio
|
445 |
+
|
446 |
+
>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
|
447 |
+
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
|
448 |
+
>>> model.cuda() # doctest: +IGNORE_RESULT
|
449 |
+
|
450 |
+
>>> # load audios > 30 seconds
|
451 |
+
>>> ds = load_dataset("distil-whisper/meanwhile", "default")["test"]
|
452 |
+
>>> # resample to 16kHz
|
453 |
+
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
|
454 |
+
>>> # take first 8 audios and retrieve array
|
455 |
+
>>> audio = ds[:8]["audio"]
|
456 |
+
>>> audio = [x["array"] for x in audio]
|
457 |
+
|
458 |
+
>>> # make sure to NOT truncate the input audio, to return the `attention_mask` and to pad to the longest audio
|
459 |
+
>>> inputs = processor(audio, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True, sampling_rate=16_000)
|
460 |
+
>>> inputs = inputs.to("cuda", torch.float32)
|
461 |
+
|
462 |
+
>>> # transcribe audio to ids
|
463 |
+
>>> generated_ids = model.generate(**inputs)
|
464 |
+
|
465 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
466 |
+
>>> transcription[0]
|
467 |
+
" Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile."
|
468 |
+
```
|
469 |
+
|
470 |
+
- *Shortform transcription*: If passed mel input features are < 30 seconds, the whole audio will be transcribed with a single call to generate.
|
471 |
+
|
472 |
+
```python
|
473 |
+
>>> import torch
|
474 |
+
>>> from transformers import AutoProcessor, WhisperForConditionalGeneration
|
475 |
+
>>> from datasets import load_dataset
|
476 |
+
|
477 |
+
>>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
|
478 |
+
>>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
|
479 |
+
|
480 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
481 |
+
|
482 |
+
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
|
483 |
+
>>> input_features = inputs.input_features
|
484 |
+
|
485 |
+
>>> generated_ids = model.generate(inputs=input_features)
|
486 |
+
|
487 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
488 |
+
>>> transcription
|
489 |
+
' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
490 |
+
```
|
491 |
+
|
492 |
+
"""
|
493 |
+
# 0. deprecate old inputs
|
494 |
+
if "inputs" in kwargs:
|
495 |
+
input_features = kwargs.pop("inputs")
|
496 |
+
warnings.warn(
|
497 |
+
"The input name `inputs` is deprecated. Please make sure to use `input_features` instead.",
|
498 |
+
FutureWarning,
|
499 |
+
)
|
500 |
+
|
501 |
+
# 1. prepare generation config
|
502 |
+
generation_config, kwargs = self._prepare_generation_config(generation_config, **kwargs)
|
503 |
+
|
504 |
+
# 2. set global generate variables
|
505 |
+
input_stride = self.model.encoder.conv1.stride[0] * self.model.encoder.conv2.stride[0]
|
506 |
+
num_segment_frames = input_stride * self.config.max_source_positions
|
507 |
+
batch_size, total_input_frames = self._retrieve_total_input_frames(
|
508 |
+
input_features=input_features, input_stride=input_stride, kwargs=kwargs
|
509 |
+
)
|
510 |
+
is_shortform = total_input_frames <= num_segment_frames
|
511 |
+
|
512 |
+
# 3. Make sure generation config is correctly set
|
513 |
+
# Make sure the generation config is correctly set depending on whether timestamps are to be returned or not
|
514 |
+
return_dict_in_generate = self._set_return_outputs(
|
515 |
+
return_dict_in_generate=return_dict_in_generate,
|
516 |
+
return_token_timestamps=return_token_timestamps,
|
517 |
+
logprob_threshold=logprob_threshold,
|
518 |
+
generation_config=generation_config,
|
519 |
+
)
|
520 |
+
timestamp_begin = self._set_return_timestamps(
|
521 |
+
return_timestamps=return_timestamps, is_shortform=is_shortform, generation_config=generation_config
|
522 |
+
)
|
523 |
+
self._set_language_and_task(
|
524 |
+
language=language, task=task, is_multilingual=is_multilingual, generation_config=generation_config
|
525 |
+
)
|
526 |
+
self._set_num_frames(
|
527 |
+
return_token_timestamps=return_token_timestamps, generation_config=generation_config, kwargs=kwargs
|
528 |
+
)
|
529 |
+
self._set_thresholds_and_condition(
|
530 |
+
generation_config=generation_config,
|
531 |
+
logprob_threshold=logprob_threshold,
|
532 |
+
compression_ratio_threshold=compression_ratio_threshold,
|
533 |
+
no_speech_threshold=no_speech_threshold,
|
534 |
+
condition_on_prev_tokens=condition_on_prev_tokens,
|
535 |
+
)
|
536 |
+
self._set_prompt_condition_type(
|
537 |
+
generation_config=generation_config,
|
538 |
+
prompt_condition_type=prompt_condition_type,
|
539 |
+
)
|
540 |
+
|
541 |
+
kwargs["attention_mask"] = attention_mask
|
542 |
+
# pass self.config for backward compatibility
|
543 |
+
init_tokens = self._retrieve_init_tokens(
|
544 |
+
input_features,
|
545 |
+
batch_size=batch_size,
|
546 |
+
generation_config=generation_config,
|
547 |
+
config=self.config,
|
548 |
+
num_segment_frames=num_segment_frames,
|
549 |
+
kwargs=kwargs,
|
550 |
+
)
|
551 |
+
# passing `decoder_input_ids` is deprecated - the only exception is for assisted generation
|
552 |
+
# where the input ids are handled explicitly by the generate method
|
553 |
+
self._check_decoder_input_ids(kwargs=kwargs)
|
554 |
+
|
555 |
+
# 3. Retrieve logits processors
|
556 |
+
device = kwargs["encoder_outputs"][0].device if "encoder_outputs" in kwargs else input_features.device
|
557 |
+
begin_index = init_tokens.shape[1]
|
558 |
+
logits_processor = self._retrieve_logit_processors(
|
559 |
+
generation_config=generation_config,
|
560 |
+
logits_processor=logits_processor,
|
561 |
+
begin_index=begin_index, # begin index is index of first generated decoder token
|
562 |
+
num_beams=kwargs.get("num_beams", 1),
|
563 |
+
device=device,
|
564 |
+
)
|
565 |
+
|
566 |
+
# 4 Set and retrieve global generation variables
|
567 |
+
self._set_condition_on_prev_tokens(
|
568 |
+
condition_on_prev_tokens=condition_on_prev_tokens, generation_config=generation_config
|
569 |
+
)
|
570 |
+
|
571 |
+
temperatures = [temperature] if not isinstance(temperature, (list, tuple)) else temperature
|
572 |
+
temperature = temperatures[0]
|
573 |
+
|
574 |
+
max_frames, seek = self._retrieve_max_frames_and_seek(
|
575 |
+
batch_size=batch_size,
|
576 |
+
attention_mask=attention_mask,
|
577 |
+
total_input_frames=total_input_frames,
|
578 |
+
is_shortform=is_shortform,
|
579 |
+
)
|
580 |
+
|
581 |
+
# 5 Prepare running variables, list for generation
|
582 |
+
num_return_sequences = generation_config.num_return_sequences
|
583 |
+
(
|
584 |
+
batch_idx_map,
|
585 |
+
cur_bsz,
|
586 |
+
input_features,
|
587 |
+
seek,
|
588 |
+
max_frames,
|
589 |
+
init_tokens,
|
590 |
+
do_condition_on_prev_tokens,
|
591 |
+
) = self._expand_variables_for_generation(
|
592 |
+
input_features=input_features,
|
593 |
+
seek=seek,
|
594 |
+
max_frames=max_frames,
|
595 |
+
init_tokens=init_tokens,
|
596 |
+
batch_size=batch_size,
|
597 |
+
condition_on_prev_tokens=condition_on_prev_tokens,
|
598 |
+
generation_config=generation_config,
|
599 |
+
)
|
600 |
+
|
601 |
+
current_segments = self._prepare_segments(
|
602 |
+
prompt_ids=prompt_ids,
|
603 |
+
batch_size=cur_bsz,
|
604 |
+
generation_config=generation_config,
|
605 |
+
)
|
606 |
+
|
607 |
+
# 6 Transcribe audio until we reach the end of all input audios
|
608 |
+
while (seek < max_frames).any():
|
609 |
+
# 6.1 NOTE: When in longform transcription mode and batch size > 1 we need to dynamically reduce the batch size during the loop
|
610 |
+
# in case one audio finished earlier than another one. Thus, we need to keep a table of "previous-index-2-current-index" in order
|
611 |
+
# to know which original audio is being decoded
|
612 |
+
# Set updated index map, duration of previously decoded chunks and number of max frames of current decoding chunk
|
613 |
+
input_features, cur_bsz, batch_idx_map = self._maybe_reduce_batch(
|
614 |
+
input_features=input_features,
|
615 |
+
seek=seek,
|
616 |
+
max_frames=max_frames,
|
617 |
+
cur_bsz=cur_bsz,
|
618 |
+
batch_idx_map=batch_idx_map,
|
619 |
+
)
|
620 |
+
time_offset = seek * time_precision / input_stride
|
621 |
+
seek_num_frames = (max_frames - seek).clamp(max=num_segment_frames)
|
622 |
+
|
623 |
+
# 6.2 cut out next 30s segment from input features
|
624 |
+
segment_input = self._get_input_segment(
|
625 |
+
input_features=input_features,
|
626 |
+
seek=seek,
|
627 |
+
seek_num_frames=seek_num_frames,
|
628 |
+
num_segment_frames=num_segment_frames,
|
629 |
+
cur_bsz=cur_bsz,
|
630 |
+
batch_idx_map=batch_idx_map,
|
631 |
+
)
|
632 |
+
|
633 |
+
# 6.3 prepare decoder input ids
|
634 |
+
suppress_tokens = _get_attr_from_logit_processors(
|
635 |
+
logits_processor, SuppressTokensLogitsProcessor, "suppress_tokens"
|
636 |
+
)
|
637 |
+
|
638 |
+
decoder_input_ids, kwargs = self._prepare_decoder_input_ids(
|
639 |
+
cur_bsz=cur_bsz,
|
640 |
+
init_tokens=init_tokens,
|
641 |
+
current_segments=current_segments,
|
642 |
+
batch_idx_map=batch_idx_map,
|
643 |
+
do_condition_on_prev_tokens=do_condition_on_prev_tokens,
|
644 |
+
prompt_ids=prompt_ids,
|
645 |
+
generation_config=generation_config,
|
646 |
+
config=self.config,
|
647 |
+
device=init_tokens.device,
|
648 |
+
suppress_tokens=suppress_tokens,
|
649 |
+
kwargs=kwargs,
|
650 |
+
)
|
651 |
+
|
652 |
+
# 6.4 set max new tokens or max length
|
653 |
+
self._set_max_new_tokens_and_length(
|
654 |
+
config=self.config,
|
655 |
+
decoder_input_ids=decoder_input_ids,
|
656 |
+
generation_config=generation_config,
|
657 |
+
)
|
658 |
+
|
659 |
+
# 6.5 Set current `begin_index` for all logit processors
|
660 |
+
if logits_processor is not None:
|
661 |
+
for proc in logits_processor:
|
662 |
+
if hasattr(proc, "set_begin_index"):
|
663 |
+
proc.set_begin_index(decoder_input_ids.shape[-1])
|
664 |
+
|
665 |
+
# 6.6 Run generate with fallback
|
666 |
+
(
|
667 |
+
seek_sequences,
|
668 |
+
seek_outputs,
|
669 |
+
should_skip,
|
670 |
+
do_condition_on_prev_tokens,
|
671 |
+
model_output_type,
|
672 |
+
) = self.generate_with_fallback(
|
673 |
+
segment_input=segment_input,
|
674 |
+
decoder_input_ids=decoder_input_ids,
|
675 |
+
cur_bsz=cur_bsz,
|
676 |
+
batch_idx_map=batch_idx_map,
|
677 |
+
seek=seek,
|
678 |
+
num_segment_frames=num_segment_frames,
|
679 |
+
max_frames=max_frames,
|
680 |
+
temperatures=temperatures,
|
681 |
+
generation_config=generation_config,
|
682 |
+
logits_processor=logits_processor,
|
683 |
+
stopping_criteria=stopping_criteria,
|
684 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
685 |
+
synced_gpus=synced_gpus,
|
686 |
+
return_token_timestamps=return_token_timestamps,
|
687 |
+
do_condition_on_prev_tokens=do_condition_on_prev_tokens,
|
688 |
+
is_shortform=is_shortform,
|
689 |
+
batch_size=batch_size,
|
690 |
+
kwargs=kwargs,
|
691 |
+
)
|
692 |
+
|
693 |
+
# 6.7 In every generated sequence, split by timestamp tokens and extract segments
|
694 |
+
for i, seek_sequence in enumerate(seek_sequences):
|
695 |
+
prev_i = batch_idx_map[i]
|
696 |
+
|
697 |
+
if should_skip[i]:
|
698 |
+
seek[prev_i] += seek_num_frames[prev_i]
|
699 |
+
continue
|
700 |
+
|
701 |
+
segments, segment_offset = self._retrieve_segment(
|
702 |
+
seek_sequence=seek_sequence,
|
703 |
+
seek_outputs=seek_outputs,
|
704 |
+
time_offset=time_offset,
|
705 |
+
timestamp_begin=timestamp_begin,
|
706 |
+
seek_num_frames=seek_num_frames,
|
707 |
+
time_precision=time_precision,
|
708 |
+
input_stride=input_stride,
|
709 |
+
prev_idx=prev_i,
|
710 |
+
idx=i,
|
711 |
+
return_token_timestamps=return_token_timestamps,
|
712 |
+
)
|
713 |
+
|
714 |
+
current_segments[prev_i] += segments
|
715 |
+
|
716 |
+
if is_shortform:
|
717 |
+
seek[prev_i] += max_frames[i]
|
718 |
+
else:
|
719 |
+
seek[prev_i] += segment_offset
|
720 |
+
|
721 |
+
# 7. Once all segments are added to the list of all segments, called `current_segments`, we extract the predicted
|
722 |
+
# output tokens from the list of dicts. If we use batch size > 1, we make sure to pad the output
|
723 |
+
final_segments = (
|
724 |
+
[x[1:] for x in current_segments]
|
725 |
+
if (prompt_ids is not None and generation_config.prompt_condition_type == "first-segment")
|
726 |
+
else current_segments
|
727 |
+
)
|
728 |
+
|
729 |
+
sequences = _pad_to_max_length(
|
730 |
+
final_segments, generation_config.pad_token_id, device=self.device, padding_side="right"
|
731 |
+
)
|
732 |
+
|
733 |
+
# 8. If we return all segments, the predicted output sequences are put under `"sequences"`.
|
734 |
+
if return_segments:
|
735 |
+
return {"sequences": sequences, "segments": final_segments}
|
736 |
+
|
737 |
+
if is_shortform:
|
738 |
+
# add eos token:
|
739 |
+
if generation_config.max_new_tokens is None and generation_config.max_length is None:
|
740 |
+
eos_tokens = torch.full((sequences.shape[0], 1), generation_config.eos_token_id)
|
741 |
+
sequences = torch.cat([sequences, eos_tokens], dim=-1)
|
742 |
+
|
743 |
+
if return_token_timestamps:
|
744 |
+
outputs = {}
|
745 |
+
outputs["sequences"] = sequences
|
746 |
+
outputs["token_timestamps"] = torch.stack([d["token_timestamps"] for d in seek_outputs], dim=0)
|
747 |
+
else:
|
748 |
+
outputs = sequences
|
749 |
+
|
750 |
+
if return_dict_in_generate and generation_config.return_dict_in_generate:
|
751 |
+
dict_outputs = self._stack_split_outputs(seek_outputs, model_output_type, sequences.device, kwargs)
|
752 |
+
|
753 |
+
if num_return_sequences > 1:
|
754 |
+
if hasattr(dict_outputs, "encoder_attentions") and dict_outputs.encoder_attentions is not None:
|
755 |
+
dict_outputs.encoder_attentions = tuple(
|
756 |
+
dict_outputs.encoder_attentions[i][::num_return_sequences]
|
757 |
+
for i in range(len(dict_outputs.encoder_attentions))
|
758 |
+
)
|
759 |
+
if (
|
760 |
+
hasattr(dict_outputs, "encoder_hidden_states")
|
761 |
+
and dict_outputs.encoder_hidden_states is not None
|
762 |
+
):
|
763 |
+
dict_outputs.encoder_hidden_states = tuple(
|
764 |
+
dict_outputs.encoder_hidden_states[i][::num_return_sequences]
|
765 |
+
for i in range(len(dict_outputs.encoder_hidden_states))
|
766 |
+
)
|
767 |
+
if return_token_timestamps:
|
768 |
+
dict_outputs["token_timestamps"] = outputs["token_timestamps"]
|
769 |
+
return dict_outputs
|
770 |
+
|
771 |
+
return outputs
|
772 |
+
|
773 |
+
return sequences
|
774 |
+
|
775 |
+
def generate_with_fallback(
|
776 |
+
self,
|
777 |
+
segment_input,
|
778 |
+
decoder_input_ids,
|
779 |
+
cur_bsz,
|
780 |
+
batch_idx_map,
|
781 |
+
seek,
|
782 |
+
num_segment_frames,
|
783 |
+
max_frames,
|
784 |
+
temperatures,
|
785 |
+
generation_config,
|
786 |
+
logits_processor,
|
787 |
+
stopping_criteria,
|
788 |
+
prefix_allowed_tokens_fn,
|
789 |
+
synced_gpus,
|
790 |
+
return_token_timestamps,
|
791 |
+
do_condition_on_prev_tokens,
|
792 |
+
is_shortform,
|
793 |
+
batch_size,
|
794 |
+
kwargs,
|
795 |
+
):
|
796 |
+
kwargs = copy.copy(kwargs)
|
797 |
+
|
798 |
+
# 6.6 Batch generate current chunk
|
799 |
+
seek_sequence_list = [None for _ in range(cur_bsz)]
|
800 |
+
seek_outputs_list = [None for _ in range(cur_bsz)]
|
801 |
+
needs_fallback = [False for _ in range(cur_bsz)]
|
802 |
+
should_skip = [False for _ in range(cur_bsz)]
|
803 |
+
fallback_index_map = list(range(cur_bsz))
|
804 |
+
if generation_config.no_speech_threshold is not None:
|
805 |
+
self._setup_no_speech_detection(logits_processor, segment_input, decoder_input_ids, kwargs)
|
806 |
+
|
807 |
+
for fallback_idx, temperature in enumerate(temperatures):
|
808 |
+
generation_config.do_sample = temperature is not None and temperature > 0.0
|
809 |
+
generation_config.temperature = temperature if generation_config.do_sample else 1.0
|
810 |
+
if generation_config.do_sample:
|
811 |
+
generation_config.num_beams = 1
|
812 |
+
|
813 |
+
generate_kwargs = copy.copy(kwargs)
|
814 |
+
for key in ["do_sample", "temperature", "num_beams"]:
|
815 |
+
if key in generate_kwargs:
|
816 |
+
del generate_kwargs[key]
|
817 |
+
|
818 |
+
cur_bsz = decoder_input_ids.shape[0]
|
819 |
+
if generation_config.cache_implementation == "static" and cur_bsz < batch_size:
|
820 |
+
segment_input = F.pad(segment_input, (0, 0, 0, 0, 0, batch_size - cur_bsz), value=0)
|
821 |
+
decoder_input_ids = F.pad(
|
822 |
+
decoder_input_ids, (0, 0, 0, batch_size - cur_bsz), value=generation_config.pad_token_id
|
823 |
+
)
|
824 |
+
if generate_kwargs.get("decoder_attention_mask") is not None:
|
825 |
+
generate_kwargs["decoder_attention_mask"] = F.pad(
|
826 |
+
generate_kwargs["decoder_attention_mask"], (0, 0, 0, batch_size - cur_bsz), value=True
|
827 |
+
)
|
828 |
+
if generate_kwargs.get("encoder_outputs") is not None:
|
829 |
+
generate_kwargs["encoder_outputs"] = F.pad(
|
830 |
+
generate_kwargs["encoder_outputs"], (0, 0, 0, 0, 0, batch_size - cur_bsz), value=0
|
831 |
+
)
|
832 |
+
|
833 |
+
seek_outputs = super().generate(
|
834 |
+
segment_input,
|
835 |
+
generation_config=generation_config,
|
836 |
+
logits_processor=logits_processor,
|
837 |
+
stopping_criteria=stopping_criteria,
|
838 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
839 |
+
synced_gpus=synced_gpus,
|
840 |
+
decoder_input_ids=decoder_input_ids,
|
841 |
+
**generate_kwargs,
|
842 |
+
)
|
843 |
+
|
844 |
+
model_output_type = type(seek_outputs)
|
845 |
+
|
846 |
+
# post-process sequence tokens and outputs to be in list form
|
847 |
+
seek_sequences, seek_outputs = self._postprocess_outputs(
|
848 |
+
seek_outputs=seek_outputs,
|
849 |
+
decoder_input_ids=decoder_input_ids,
|
850 |
+
return_token_timestamps=return_token_timestamps,
|
851 |
+
generation_config=generation_config,
|
852 |
+
is_shortform=is_shortform,
|
853 |
+
)
|
854 |
+
|
855 |
+
if cur_bsz < batch_size:
|
856 |
+
seek_sequences = seek_sequences[:cur_bsz]
|
857 |
+
seek_outputs = seek_outputs[:cur_bsz]
|
858 |
+
|
859 |
+
# 6.7 Extract cut sequences from every sequence and check if fallback should be applied
|
860 |
+
# Loop over each decoded audio individually as each decoding can be of a different length
|
861 |
+
new_fallback_index_map = []
|
862 |
+
new_segment_input = []
|
863 |
+
new_decoder_input_ids = []
|
864 |
+
new_decoder_attention_mask = []
|
865 |
+
|
866 |
+
for i, seek_sequence in enumerate(seek_sequences):
|
867 |
+
# make sure we cut a predicted EOS token if we are not finished with the generation yet
|
868 |
+
prev_i = batch_idx_map[fallback_index_map[i]]
|
869 |
+
is_not_final = (seek[prev_i] + num_segment_frames) < max_frames[prev_i]
|
870 |
+
|
871 |
+
# remove eos token id
|
872 |
+
if is_not_final and seek_sequence[-1] == generation_config.eos_token_id:
|
873 |
+
seek_sequence = seek_sequence[:-1]
|
874 |
+
if return_token_timestamps and not is_shortform:
|
875 |
+
seek_outputs[i]["token_timestamps"] = seek_outputs[i]["token_timestamps"][:-1]
|
876 |
+
|
877 |
+
# remove all padding tokens
|
878 |
+
if seek_sequence[-1] == generation_config.pad_token_id:
|
879 |
+
num_paddings = (seek_sequence == generation_config.pad_token_id).sum()
|
880 |
+
seek_sequence = seek_sequence[:-num_paddings]
|
881 |
+
if return_token_timestamps and not is_shortform:
|
882 |
+
seek_outputs[i]["token_timestamps"] = seek_outputs[i]["token_timestamps"][:-num_paddings]
|
883 |
+
|
884 |
+
# check which sequences in batch need fallback & which should be skipped
|
885 |
+
needs_fallback[i], should_skip[i] = self._need_fallback(
|
886 |
+
seek_sequence,
|
887 |
+
seek_outputs,
|
888 |
+
i,
|
889 |
+
logits_processor,
|
890 |
+
generation_config,
|
891 |
+
self.config.vocab_size,
|
892 |
+
temperature,
|
893 |
+
)
|
894 |
+
|
895 |
+
seek_sequence_list[fallback_index_map[i]] = seek_sequence
|
896 |
+
seek_outputs_list[fallback_index_map[i]] = seek_outputs[i]
|
897 |
+
is_low_temperature = temperature is None or temperature < 0.5
|
898 |
+
do_condition_on_prev_tokens[fallback_index_map[i]] = (
|
899 |
+
generation_config.condition_on_prev_tokens and is_low_temperature
|
900 |
+
)
|
901 |
+
|
902 |
+
if needs_fallback[i]:
|
903 |
+
new_fallback_index_map.append(fallback_index_map[i])
|
904 |
+
new_segment_input.append(segment_input[i])
|
905 |
+
new_decoder_input_ids.append(decoder_input_ids[i])
|
906 |
+
if "decoder_attention_mask" in kwargs:
|
907 |
+
new_decoder_attention_mask.append(kwargs["decoder_attention_mask"][i])
|
908 |
+
|
909 |
+
fallback_index_map = new_fallback_index_map
|
910 |
+
|
911 |
+
# if no sequence needs to be run with temperature fallback, we're finished
|
912 |
+
if len(fallback_index_map) == 0 or fallback_idx == len(temperatures) - 1:
|
913 |
+
seek_sequences = seek_sequence_list
|
914 |
+
seek_outputs = seek_outputs_list
|
915 |
+
break
|
916 |
+
|
917 |
+
# if we're still in the loop, make sure that decoder_input_ids and segment inputs are tensors
|
918 |
+
decoder_input_ids = torch.stack(new_decoder_input_ids)
|
919 |
+
segment_input = torch.stack(new_segment_input)
|
920 |
+
if "decoder_attention_mask" in kwargs:
|
921 |
+
kwargs["decoder_attention_mask"] = torch.stack(new_decoder_attention_mask)
|
922 |
+
|
923 |
+
return seek_sequences, seek_outputs, should_skip, do_condition_on_prev_tokens, model_output_type
|
924 |
+
|
925 |
+
@staticmethod
|
926 |
+
def _prepare_segments(prompt_ids, batch_size, generation_config):
|
927 |
+
if prompt_ids is not None and generation_config.prompt_condition_type == "first-segment":
|
928 |
+
prev_sot_token_id = getattr(generation_config, "prev_sot_token_id", None)
|
929 |
+
prompt_ids = prompt_ids[1:] if prompt_ids[0] == prev_sot_token_id else prompt_ids
|
930 |
+
current_segments = [[{"tokens": prompt_ids}] for _ in range(batch_size)]
|
931 |
+
else:
|
932 |
+
current_segments = [[] for _ in range(batch_size)]
|
933 |
+
|
934 |
+
return current_segments
|
935 |
+
|
936 |
+
def _postprocess_outputs(
|
937 |
+
self, seek_outputs, decoder_input_ids, return_token_timestamps, generation_config, is_shortform
|
938 |
+
):
|
939 |
+
# remove all previously passed decoder input ids
|
940 |
+
start_idx = decoder_input_ids.shape[-1] if not is_shortform else torch.tensor(0)
|
941 |
+
|
942 |
+
if isinstance(seek_outputs, torch.Tensor):
|
943 |
+
seek_outputs = seek_outputs[:, start_idx:]
|
944 |
+
return seek_outputs, seek_outputs
|
945 |
+
|
946 |
+
if return_token_timestamps and hasattr(generation_config, "alignment_heads"):
|
947 |
+
num_frames = getattr(generation_config, "num_frames", None)
|
948 |
+
seek_outputs["token_timestamps"] = self._extract_token_timestamps(
|
949 |
+
seek_outputs, generation_config.alignment_heads, num_frames=num_frames
|
950 |
+
)
|
951 |
+
seek_outputs["token_timestamps"] = seek_outputs["token_timestamps"][:, start_idx:]
|
952 |
+
|
953 |
+
seek_outputs["sequences"] = seek_outputs["sequences"][:, start_idx:]
|
954 |
+
|
955 |
+
def split_by_batch_index(values, key, batch_idx, is_shortform):
|
956 |
+
if key in ["scores", "encoder_attentions", "encoder_hidden_states", "logits"]:
|
957 |
+
return [v[batch_idx].cpu() for v in values]
|
958 |
+
if key in ["decoder_attentions", "decoder_hidden_states", "cross_attentions"]:
|
959 |
+
return tuple(tuple(w[batch_idx][None].cpu() for w in v) for v in values)
|
960 |
+
elif key == "past_key_values":
|
961 |
+
if not is_shortform:
|
962 |
+
# we don't save `past_key_values` as this is too costly for longform
|
963 |
+
return None
|
964 |
+
elif isinstance(values, EncoderDecoderCache):
|
965 |
+
all_past_key_values = []
|
966 |
+
for layer_idx in range(self.config.decoder_layers):
|
967 |
+
layer_past_key_values = []
|
968 |
+
for cache_cls in [values.self_attention_cache, values.cross_attention_cache]:
|
969 |
+
for v in [cache_cls.key_cache, cache_cls.value_cache]:
|
970 |
+
layer_past_key_values.append(v[layer_idx][batch_idx][None].cpu())
|
971 |
+
all_past_key_values.append(tuple(layer_past_key_values))
|
972 |
+
return tuple(all_past_key_values)
|
973 |
+
else:
|
974 |
+
all_past_key_values = []
|
975 |
+
for v in range(len(values)):
|
976 |
+
layer_past_key_values = []
|
977 |
+
for w in values[v]:
|
978 |
+
layer_past_key_values.append(w[batch_idx][None].cpu())
|
979 |
+
all_past_key_values.append(tuple(layer_past_key_values))
|
980 |
+
return tuple(all_past_key_values)
|
981 |
+
|
982 |
+
return values[batch_idx].cpu()
|
983 |
+
|
984 |
+
sequence_tokens = seek_outputs["sequences"]
|
985 |
+
seek_outputs = [
|
986 |
+
{k: split_by_batch_index(v, k, i, is_shortform) for k, v in seek_outputs.items()}
|
987 |
+
for i in range(sequence_tokens.shape[0])
|
988 |
+
]
|
989 |
+
|
990 |
+
return sequence_tokens, seek_outputs
|
991 |
+
|
992 |
+
def _stack_split_outputs(self, seek_outputs, model_output_type, device, kwargs):
|
993 |
+
# Stack back seek_outputs tensors after splitting them with the split_by_batch_index method
|
994 |
+
outputs = {}
|
995 |
+
for key in seek_outputs[0].keys():
|
996 |
+
if key == "sequences":
|
997 |
+
outputs[key] = torch.stack([v[key] for v in seek_outputs], dim=0).to(device)
|
998 |
+
if key in ["scores", "encoder_attentions", "encoder_hidden_states", "logits"]:
|
999 |
+
outputs[key] = tuple(
|
1000 |
+
torch.stack([v[key][i] for v in seek_outputs]).to(device) for i in range(len(seek_outputs[0][key]))
|
1001 |
+
)
|
1002 |
+
if key in ["decoder_attentions", "decoder_hidden_states", "cross_attentions"]:
|
1003 |
+
outputs[key] = tuple(
|
1004 |
+
tuple(
|
1005 |
+
torch.stack([v[key][i][j] for v in seek_outputs]).squeeze(1).to(device)
|
1006 |
+
for j in range(len(seek_outputs[0][key][0]))
|
1007 |
+
)
|
1008 |
+
for i in range(len(seek_outputs[0][key]))
|
1009 |
+
)
|
1010 |
+
if key == "past_key_values":
|
1011 |
+
past_key_value_type = kwargs.get("past_key_values")
|
1012 |
+
if seek_outputs[0][key] is not None:
|
1013 |
+
outputs[key] = tuple(
|
1014 |
+
tuple(
|
1015 |
+
torch.stack([v[key][i][j] for v in seek_outputs]).squeeze(1).to(device)
|
1016 |
+
for j in range(len(seek_outputs[0][key][0]))
|
1017 |
+
)
|
1018 |
+
for i in range(len(seek_outputs[0][key]))
|
1019 |
+
)
|
1020 |
+
if past_key_value_type is not None and isinstance(past_key_value_type, EncoderDecoderCache):
|
1021 |
+
outputs[key] = past_key_value_type.from_legacy_cache(outputs[key])
|
1022 |
+
else:
|
1023 |
+
outputs[key] = None
|
1024 |
+
|
1025 |
+
return model_output_type(**outputs)
|
1026 |
+
|
1027 |
+
def _need_fallback(
|
1028 |
+
self,
|
1029 |
+
seek_sequence,
|
1030 |
+
seek_outputs,
|
1031 |
+
index,
|
1032 |
+
logits_processor,
|
1033 |
+
generation_config,
|
1034 |
+
vocab_size,
|
1035 |
+
temperature,
|
1036 |
+
):
|
1037 |
+
needs_fallback = False
|
1038 |
+
should_skip = False
|
1039 |
+
if generation_config.compression_ratio_threshold is not None:
|
1040 |
+
compression_ratio = self._retrieve_compression_ratio(seek_sequence, vocab_size)
|
1041 |
+
|
1042 |
+
if compression_ratio > generation_config.compression_ratio_threshold:
|
1043 |
+
needs_fallback = True
|
1044 |
+
|
1045 |
+
if generation_config.logprob_threshold is not None:
|
1046 |
+
if hasattr(seek_outputs[0], "sequences_scores"):
|
1047 |
+
logprobs = [s["sequences_scores"] for s in seek_outputs][index]
|
1048 |
+
else:
|
1049 |
+
scores = seek_outputs[index]["scores"]
|
1050 |
+
logprobs = self._retrieve_avg_logprobs(
|
1051 |
+
scores, seek_sequence, generation_config.eos_token_id, temperature
|
1052 |
+
)
|
1053 |
+
|
1054 |
+
if logprobs < generation_config.logprob_threshold:
|
1055 |
+
needs_fallback = True
|
1056 |
+
|
1057 |
+
if generation_config.no_speech_threshold is not None:
|
1058 |
+
no_speech_prob = _get_attr_from_logit_processors(
|
1059 |
+
logits_processor, WhisperNoSpeechDetection, "no_speech_prob"
|
1060 |
+
)
|
1061 |
+
|
1062 |
+
if (
|
1063 |
+
logprobs < generation_config.logprob_threshold
|
1064 |
+
and no_speech_prob[index] > generation_config.no_speech_threshold
|
1065 |
+
):
|
1066 |
+
needs_fallback = False
|
1067 |
+
should_skip = True
|
1068 |
+
|
1069 |
+
return needs_fallback, should_skip
|
1070 |
+
|
1071 |
+
def _expand_variables_for_generation(
|
1072 |
+
self, input_features, seek, max_frames, init_tokens, batch_size, condition_on_prev_tokens, generation_config
|
1073 |
+
):
|
1074 |
+
if generation_config.num_return_sequences is not None and generation_config.num_return_sequences > 1:
|
1075 |
+
batch_idx_map = list(range(batch_size * generation_config.num_return_sequences))
|
1076 |
+
cur_bsz = len(batch_idx_map)
|
1077 |
+
do_condition_on_prev_tokens = [condition_on_prev_tokens for _ in range(len(batch_idx_map))]
|
1078 |
+
input_features = input_features.repeat_interleave(generation_config.num_return_sequences, dim=0)
|
1079 |
+
seek = seek.repeat_interleave(generation_config.num_return_sequences, dim=0)
|
1080 |
+
max_frames = max_frames.repeat_interleave(generation_config.num_return_sequences, dim=0)
|
1081 |
+
init_tokens = init_tokens.repeat_interleave(generation_config.num_return_sequences, dim=0)
|
1082 |
+
generation_config.num_return_sequences = 1
|
1083 |
+
else:
|
1084 |
+
cur_bsz = batch_size
|
1085 |
+
batch_idx_map = list(range(cur_bsz))
|
1086 |
+
do_condition_on_prev_tokens = [condition_on_prev_tokens for _ in range(cur_bsz)]
|
1087 |
+
|
1088 |
+
return (
|
1089 |
+
batch_idx_map,
|
1090 |
+
cur_bsz,
|
1091 |
+
input_features,
|
1092 |
+
seek,
|
1093 |
+
max_frames,
|
1094 |
+
init_tokens,
|
1095 |
+
do_condition_on_prev_tokens,
|
1096 |
+
)
|
1097 |
+
|
1098 |
+
@staticmethod
|
1099 |
+
def _setup_no_speech_detection(logits_processor, segment_input, decoder_input_ids, kwargs):
|
1100 |
+
set_inputs = _get_attr_from_logit_processors(logits_processor, WhisperNoSpeechDetection, "set_inputs")
|
1101 |
+
extra_kwargs = {k: v for k, v in kwargs.items() if torch.is_tensor(v)}
|
1102 |
+
set_inputs({"inputs": segment_input, "decoder_input_ids": decoder_input_ids, **extra_kwargs})
|
1103 |
+
|
1104 |
+
@staticmethod
|
1105 |
+
def _retrieve_total_input_frames(input_features, input_stride, kwargs):
|
1106 |
+
if input_features is not None:
|
1107 |
+
return input_features.shape[0], input_features.shape[-1]
|
1108 |
+
|
1109 |
+
if "encoder_outputs" in kwargs:
|
1110 |
+
encoder_outputs_shape = (
|
1111 |
+
kwargs["encoder_outputs"][0].shape
|
1112 |
+
if isinstance(kwargs["encoder_outputs"], BaseModelOutput)
|
1113 |
+
else kwargs["encoder_outputs"].shape
|
1114 |
+
)
|
1115 |
+
return encoder_outputs_shape[0], encoder_outputs_shape[1] * input_stride
|
1116 |
+
|
1117 |
+
raise ValueError("Make sure to provide either `input_features` or `encoder_outputs` to `generate`.")
|
1118 |
+
|
1119 |
+
@staticmethod
|
1120 |
+
def _maybe_warn_unused_inputs(
|
1121 |
+
condition_on_prev_tokens,
|
1122 |
+
temperature,
|
1123 |
+
compression_ratio_threshold,
|
1124 |
+
logprob_threshold,
|
1125 |
+
no_speech_threshold,
|
1126 |
+
total_input_frames,
|
1127 |
+
):
|
1128 |
+
warning_prefix = (
|
1129 |
+
f"Audio input consists of only {total_input_frames}. "
|
1130 |
+
"Short-form transcription is activated."
|
1131 |
+
"{}, but will be ignored."
|
1132 |
+
)
|
1133 |
+
if condition_on_prev_tokens is not None:
|
1134 |
+
logger.warning(warning_prefix.format(f"condition_on_prev_tokens is set to {condition_on_prev_tokens}"))
|
1135 |
+
|
1136 |
+
if compression_ratio_threshold is not None:
|
1137 |
+
logger.warning(
|
1138 |
+
warning_prefix.format(f"compression_ratio_threshold is set to {compression_ratio_threshold}")
|
1139 |
+
)
|
1140 |
+
|
1141 |
+
if logprob_threshold is not None:
|
1142 |
+
logger.warning(warning_prefix.format(f"logprob_threshold is set to {logprob_threshold}"))
|
1143 |
+
|
1144 |
+
if no_speech_threshold is not None:
|
1145 |
+
logger.warning(warning_prefix.format(f"no_speech_threshold is set to {no_speech_threshold}"))
|
1146 |
+
|
1147 |
+
# when passing temperature as a list it cannot just be ignored => throw error in this case
|
1148 |
+
if isinstance(temperature, (list, tuple)):
|
1149 |
+
raise ValueError(
|
1150 |
+
f"Audio input consists of only {total_input_frames}. Short-form transcription is activated."
|
1151 |
+
f"temperature cannot be set to {temperature} which can only be used for temperature fallback for long-form generation. Make sure to set `temperature` to a float value or `None` for short-form generation."
|
1152 |
+
)
|
1153 |
+
|
1154 |
+
@staticmethod
|
1155 |
+
def _set_return_outputs(return_dict_in_generate, return_token_timestamps, logprob_threshold, generation_config):
|
1156 |
+
if return_dict_in_generate is None:
|
1157 |
+
return_dict_in_generate = generation_config.return_dict_in_generate
|
1158 |
+
else:
|
1159 |
+
generation_config.return_dict_in_generate = return_dict_in_generate
|
1160 |
+
|
1161 |
+
generation_config.return_token_timestamps = return_token_timestamps
|
1162 |
+
if return_token_timestamps:
|
1163 |
+
generation_config.return_dict_in_generate = True
|
1164 |
+
generation_config.output_attentions = True
|
1165 |
+
generation_config.output_scores = True
|
1166 |
+
|
1167 |
+
if logprob_threshold is not None:
|
1168 |
+
generation_config.return_dict_in_generate = True
|
1169 |
+
generation_config.output_scores = True
|
1170 |
+
|
1171 |
+
return return_dict_in_generate
|
1172 |
+
|
1173 |
+
def _set_return_timestamps(self, return_timestamps, is_shortform, generation_config):
|
1174 |
+
if return_timestamps is None and hasattr(generation_config, "return_timestamps"):
|
1175 |
+
return_timestamps = generation_config.return_timestamps
|
1176 |
+
|
1177 |
+
if not is_shortform:
|
1178 |
+
if return_timestamps is False:
|
1179 |
+
raise ValueError(
|
1180 |
+
"You have passed more than 3000 mel input features (> 30 seconds) which automatically enables long-form generation which "
|
1181 |
+
"requires the model to predict timestamp tokens. Please either pass `return_timestamps=True` or make sure to pass no more than 3000 mel input features."
|
1182 |
+
)
|
1183 |
+
|
1184 |
+
logger.info("Setting `return_timestamps=True` for long-form generation.")
|
1185 |
+
return_timestamps = True
|
1186 |
+
|
1187 |
+
if return_timestamps and not hasattr(generation_config, "no_timestamps_token_id"):
|
1188 |
+
raise ValueError(
|
1189 |
+
"You are trying to return timestamps, but the generation config is not properly set. "
|
1190 |
+
"Make sure to initialize the generation config with the correct attributes that are needed such as `no_timestamps_token_id`. "
|
1191 |
+
"For more details on how to generate the approtiate config, refer to https://github.com/huggingface/transformers/issues/21878#issuecomment-1451902363"
|
1192 |
+
)
|
1193 |
+
|
1194 |
+
generation_config.return_timestamps = return_timestamps
|
1195 |
+
|
1196 |
+
if hasattr(generation_config, "no_timestamps_token_id"):
|
1197 |
+
timestamp_begin = generation_config.no_timestamps_token_id + 1
|
1198 |
+
else:
|
1199 |
+
# BC for models missing the `no_timestamps_token_id` in the generation config when generating short-form with no timestamps
|
1200 |
+
# We set the timestamp begin token larger than the vocab size, such that the timestamp condition is never met in the decoding loop
|
1201 |
+
timestamp_begin = self.config.vocab_size + 1
|
1202 |
+
|
1203 |
+
return timestamp_begin
|
1204 |
+
|
1205 |
+
@staticmethod
|
1206 |
+
def _set_language_and_task(language, task, is_multilingual, generation_config):
|
1207 |
+
if is_multilingual is not None:
|
1208 |
+
if not hasattr(generation_config, "is_multilingual"):
|
1209 |
+
raise ValueError(
|
1210 |
+
"The generation config is outdated and is thus not compatible with the `is_multilingual` argument "
|
1211 |
+
"to `generate`. Please update the generation config as per the instructions "
|
1212 |
+
"https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224"
|
1213 |
+
)
|
1214 |
+
generation_config.is_multilingual = is_multilingual
|
1215 |
+
|
1216 |
+
if hasattr(generation_config, "is_multilingual") and not generation_config.is_multilingual:
|
1217 |
+
if task is not None or language is not None:
|
1218 |
+
raise ValueError(
|
1219 |
+
"Cannot specify `task` or `language` for an English-only model. If the model is intended to be "
|
1220 |
+
"multilingual, pass `is_multilingual=True` to generate, or update the generation config."
|
1221 |
+
)
|
1222 |
+
|
1223 |
+
if language is not None:
|
1224 |
+
if not hasattr(generation_config, "lang_to_id"):
|
1225 |
+
raise ValueError(
|
1226 |
+
"The generation config is outdated and is thus not compatible with the `language` argument "
|
1227 |
+
"to `generate`. Either set the language using the `forced_decoder_ids` in the model config, "
|
1228 |
+
"or update the generation config as per the instructions https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224"
|
1229 |
+
)
|
1230 |
+
generation_config.language = language
|
1231 |
+
|
1232 |
+
if task is not None:
|
1233 |
+
if not hasattr(generation_config, "task_to_id"):
|
1234 |
+
raise ValueError(
|
1235 |
+
"The generation config is outdated and is thus not compatible with the `task` argument "
|
1236 |
+
"to `generate`. Either set the task using the `forced_decoder_ids` in the model config, "
|
1237 |
+
"or update the generation config as per the instructions https://github.com/huggingface/transformers/issues/25084#issuecomment-1664398224"
|
1238 |
+
)
|
1239 |
+
generation_config.task = task
|
1240 |
+
|
1241 |
+
def _retrieve_init_tokens(self, input_features, batch_size, generation_config, config, num_segment_frames, kwargs):
|
1242 |
+
def replace_or_add(lst: List[int], num: int, itr: Iterator[int]):
|
1243 |
+
"""short function to replace num with a itr in lst"""
|
1244 |
+
found = any(i in lst for i in itr)
|
1245 |
+
if found:
|
1246 |
+
lst = [num if i in itr else i for i in lst]
|
1247 |
+
else:
|
1248 |
+
lst.append(num)
|
1249 |
+
return lst
|
1250 |
+
|
1251 |
+
def language_to_id(language: str) -> int:
|
1252 |
+
language = language.lower()
|
1253 |
+
if language in generation_config.lang_to_id.keys():
|
1254 |
+
language_token = language
|
1255 |
+
elif language in TO_LANGUAGE_CODE.keys():
|
1256 |
+
language_token = f"<|{TO_LANGUAGE_CODE[language]}|>"
|
1257 |
+
elif language in TO_LANGUAGE_CODE.values():
|
1258 |
+
language_token = f"<|{language}|>"
|
1259 |
+
else:
|
1260 |
+
is_language_code = len(language) == 2
|
1261 |
+
raise ValueError(
|
1262 |
+
f"Unsupported language: {language}. Language should be one of:"
|
1263 |
+
f" {list(TO_LANGUAGE_CODE.values()) if is_language_code else list(TO_LANGUAGE_CODE.keys())}."
|
1264 |
+
)
|
1265 |
+
if language_token not in generation_config.lang_to_id:
|
1266 |
+
raise ValueError(
|
1267 |
+
f"{language_token} is not supported by this specific model as it is not in the `generation_config.lang_to_id`."
|
1268 |
+
"(You should just add it to the generation config)"
|
1269 |
+
)
|
1270 |
+
|
1271 |
+
return generation_config.lang_to_id[language_token]
|
1272 |
+
|
1273 |
+
task = getattr(generation_config, "task", None)
|
1274 |
+
language = getattr(generation_config, "language", None)
|
1275 |
+
|
1276 |
+
forced_decoder_ids = generation_config.forced_decoder_ids
|
1277 |
+
if forced_decoder_ids is not None:
|
1278 |
+
if language is None and task is None and forced_decoder_ids[0][1] is None:
|
1279 |
+
logger.warning_once(
|
1280 |
+
"Due to a bug fix in https://github.com/huggingface/transformers/pull/28687 transcription using a multilingual Whisper will default to language detection followed by transcription instead of translation to English."
|
1281 |
+
"This might be a breaking change for your use case. If you want to instead always translate your audio to English, make sure to pass `language='en'`."
|
1282 |
+
)
|
1283 |
+
elif hasattr(config, "forced_decoder_ids") and config.forced_decoder_ids is not None:
|
1284 |
+
forced_decoder_ids = config.forced_decoder_ids
|
1285 |
+
|
1286 |
+
if forced_decoder_ids is not None and task is not None:
|
1287 |
+
logger.warning_once(
|
1288 |
+
f"You have passed task={task}, but also have set `forced_decoder_ids` to {forced_decoder_ids} which creates a conflict. `forced_decoder_ids` will be ignored in favor of task={task}."
|
1289 |
+
)
|
1290 |
+
forced_decoder_ids = None
|
1291 |
+
elif forced_decoder_ids is not None and language is not None:
|
1292 |
+
logger.warning_once(
|
1293 |
+
f"You have passed language={language}, but also have set `forced_decoder_ids` to {forced_decoder_ids} which creates a conflict. `forced_decoder_ids` will be ignored in favor of language={language}."
|
1294 |
+
)
|
1295 |
+
forced_decoder_ids = None
|
1296 |
+
|
1297 |
+
init_tokens = [generation_config.decoder_start_token_id]
|
1298 |
+
if forced_decoder_ids is not None and forced_decoder_ids[0][0] == 1:
|
1299 |
+
i = 1
|
1300 |
+
while len(forced_decoder_ids) > 0 and forced_decoder_ids[0][0] == i:
|
1301 |
+
init_tokens += [forced_decoder_ids[0][1]]
|
1302 |
+
forced_decoder_ids = forced_decoder_ids[1:]
|
1303 |
+
i += 1
|
1304 |
+
|
1305 |
+
if len(forced_decoder_ids) > 0:
|
1306 |
+
raise ValueError(
|
1307 |
+
f"You are using token ids in `forced_decoder_ids` that do not seem to correctly follow the prompt pattern of Whisper. Make sure that {forced_decoder_ids} has an entry for all indices >= 1 and < {forced_decoder_ids[0][0]}.",
|
1308 |
+
)
|
1309 |
+
|
1310 |
+
# from v4.39 the forced decoder ids are always None in favour of decoder input ids
|
1311 |
+
generation_config.forced_decoder_ids = None
|
1312 |
+
|
1313 |
+
is_lang_id_undefined = len(init_tokens) <= 1 or (len(init_tokens) > 1 and init_tokens[1] is None)
|
1314 |
+
|
1315 |
+
# Make sure language is a list of strings of the correct length
|
1316 |
+
if isinstance(language, (list, tuple)):
|
1317 |
+
if any(l is None for l in language):
|
1318 |
+
raise TypeError(
|
1319 |
+
"Expected `language` to be `None`, a single string (e.g. `'en'`), or a list of strings with length equal to the batch size (e.g. `('en', 'fr')` for a batch size of 2). Got a list containing `None`."
|
1320 |
+
)
|
1321 |
+
if len(language) != batch_size:
|
1322 |
+
raise ValueError(
|
1323 |
+
"When passing a list of languages, the length of the list must match the batch size. "
|
1324 |
+
f"Expected length of {batch_size}, but got {len(language)} languages."
|
1325 |
+
)
|
1326 |
+
languages = language
|
1327 |
+
elif language is None:
|
1328 |
+
# Language will be detected for each item in batch
|
1329 |
+
languages = [None] * batch_size
|
1330 |
+
else:
|
1331 |
+
languages = [language] # Use a length-1 list now, broadcast later
|
1332 |
+
|
1333 |
+
# Separate init_tokens for each language
|
1334 |
+
init_tokens = [copy.copy(init_tokens) for _ in languages]
|
1335 |
+
|
1336 |
+
# Update init_tokens with languages
|
1337 |
+
lang_ids = None
|
1338 |
+
if language is not None:
|
1339 |
+
lang_ids = [language_to_id(l) for l in languages]
|
1340 |
+
elif hasattr(generation_config, "lang_to_id") and is_lang_id_undefined:
|
1341 |
+
# language is not defined or intentially set to `None` to trigger language detection
|
1342 |
+
lang_ids = self.detect_language(
|
1343 |
+
input_features=input_features,
|
1344 |
+
encoder_outputs=kwargs.get("encoder_outputs", None),
|
1345 |
+
attention_mask=kwargs.get("attention_mask", None),
|
1346 |
+
generation_config=generation_config,
|
1347 |
+
num_segment_frames=num_segment_frames,
|
1348 |
+
).tolist()
|
1349 |
+
if lang_ids is not None:
|
1350 |
+
# append or replace lang_ids to init_tokens
|
1351 |
+
for i in range(len(init_tokens)):
|
1352 |
+
if len(init_tokens[i]) > 1:
|
1353 |
+
init_tokens[i][1] = lang_ids[i]
|
1354 |
+
else:
|
1355 |
+
init_tokens[i].append(lang_ids[i])
|
1356 |
+
del languages
|
1357 |
+
|
1358 |
+
# Update init_tokens with task
|
1359 |
+
for i in range(len(init_tokens)):
|
1360 |
+
if task is not None:
|
1361 |
+
if task in TASK_IDS:
|
1362 |
+
init_tokens[i].append(generation_config.task_to_id[generation_config.task])
|
1363 |
+
task_id = generation_config.task_to_id[generation_config.task]
|
1364 |
+
|
1365 |
+
# if task is defined it'll overwrite task ids that might have already been defined via the generation_config
|
1366 |
+
replace_or_add(init_tokens[i], task_id, generation_config.task_to_id.values())
|
1367 |
+
else:
|
1368 |
+
raise ValueError(f"The `{task}`task is not supported. The task should be one of `{TASK_IDS}`")
|
1369 |
+
elif language is not None and hasattr(generation_config, "task_to_id"):
|
1370 |
+
# if language is defined, but no task id is in `init_tokens`, default to transcribe
|
1371 |
+
if not any(ti in init_tokens[i] for ti in generation_config.task_to_id.values()):
|
1372 |
+
init_tokens[i].append(generation_config.task_to_id["transcribe"])
|
1373 |
+
|
1374 |
+
if (
|
1375 |
+
not generation_config.return_timestamps
|
1376 |
+
and hasattr(generation_config, "no_timestamps_token_id")
|
1377 |
+
and init_tokens[i][-1] != generation_config.no_timestamps_token_id
|
1378 |
+
):
|
1379 |
+
init_tokens[i].append(generation_config.no_timestamps_token_id)
|
1380 |
+
elif (
|
1381 |
+
generation_config.return_timestamps and init_tokens[i][-1] == generation_config.no_timestamps_token_id
|
1382 |
+
):
|
1383 |
+
logger.info(
|
1384 |
+
"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `'True'`."
|
1385 |
+
)
|
1386 |
+
init_tokens[i] = init_tokens[i][:-1]
|
1387 |
+
|
1388 |
+
# let's make sure we don't pass `None` tokens as prompt tokens
|
1389 |
+
init_tokens[i] = [t for t in init_tokens[i] if t is not None]
|
1390 |
+
|
1391 |
+
return torch.as_tensor(init_tokens, dtype=torch.long, device=self.device).expand(batch_size, -1)
|
1392 |
+
|
1393 |
+
def detect_language(
|
1394 |
+
self,
|
1395 |
+
input_features: Optional[torch.FloatTensor] = None,
|
1396 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
1397 |
+
encoder_outputs: Optional[Union[torch.FloatTensor, BaseModelOutput]] = None,
|
1398 |
+
generation_config: Optional[GenerationConfig] = None,
|
1399 |
+
num_segment_frames: int = 3000,
|
1400 |
+
) -> torch.Tensor:
|
1401 |
+
"""
|
1402 |
+
Detects language from log-mel input features or encoder_outputs
|
1403 |
+
|
1404 |
+
Parameters:
|
1405 |
+
input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*):
|
1406 |
+
Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform can be obtained by
|
1407 |
+
loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
|
1408 |
+
the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
|
1409 |
+
[`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
|
1410 |
+
tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] for details.
|
1411 |
+
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
|
1412 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
1413 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
1414 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
1415 |
+
generation_config (`~generation.GenerationConfig`, *optional*):
|
1416 |
+
The generation configuration to be used as base parametrization for the generation call. `**kwargs`
|
1417 |
+
passed to generate matching the attributes of `generation_config` will override them. If
|
1418 |
+
`generation_config` is not provided, the default will be used, which had the following loading
|
1419 |
+
priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
|
1420 |
+
configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
|
1421 |
+
default values, whose documentation should be checked to parameterize generation.
|
1422 |
+
num_segment_frames (`int`, *optional*, defaults to 3000):
|
1423 |
+
The number of log-mel frames the model expects
|
1424 |
+
|
1425 |
+
Return:
|
1426 |
+
A `torch.LongTensor` representing the detected language ids.
|
1427 |
+
"""
|
1428 |
+
if input_features is None and encoder_outputs is None:
|
1429 |
+
raise ValueError("You have to specify either `input_features` or `encoder_outputs`")
|
1430 |
+
elif input_features is not None and encoder_outputs is not None:
|
1431 |
+
raise ValueError("Make sure to specificy only one of `input_features` or `encoder_outputs` - not both!")
|
1432 |
+
elif input_features is not None:
|
1433 |
+
inputs = {"input_features": input_features[:, :, :num_segment_frames]}
|
1434 |
+
batch_size = input_features.shape[0]
|
1435 |
+
elif encoder_outputs is not None:
|
1436 |
+
inputs = {"encoder_outputs": encoder_outputs}
|
1437 |
+
batch_size = (
|
1438 |
+
encoder_outputs[0].shape[0] if isinstance(encoder_outputs, BaseModelOutput) else encoder_outputs[0]
|
1439 |
+
)
|
1440 |
+
if attention_mask is not None:
|
1441 |
+
inputs["attention_mask"] = attention_mask
|
1442 |
+
|
1443 |
+
generation_config = generation_config or self.generation_config
|
1444 |
+
decoder_input_ids = (
|
1445 |
+
torch.ones((batch_size, 1), device=self.device, dtype=torch.long)
|
1446 |
+
* generation_config.decoder_start_token_id
|
1447 |
+
)
|
1448 |
+
|
1449 |
+
with torch.no_grad():
|
1450 |
+
logits = self(**inputs, decoder_input_ids=decoder_input_ids).logits[:, -1]
|
1451 |
+
|
1452 |
+
non_lang_mask = torch.ones_like(logits[0], dtype=torch.bool)
|
1453 |
+
non_lang_mask[list(generation_config.lang_to_id.values())] = False
|
1454 |
+
|
1455 |
+
logits[:, non_lang_mask] = -np.inf
|
1456 |
+
|
1457 |
+
lang_ids = logits.argmax(-1)
|
1458 |
+
|
1459 |
+
return lang_ids
|
1460 |
+
|
1461 |
+
@staticmethod
|
1462 |
+
def _check_decoder_input_ids(kwargs):
|
1463 |
+
decoder_input_ids = kwargs.get("decoder_input_ids", None)
|
1464 |
+
assistant_model = kwargs.get("assistant_model", None)
|
1465 |
+
if decoder_input_ids is not None and assistant_model is not None:
|
1466 |
+
raise ValueError(
|
1467 |
+
"Passing `decoder_input_ids` is deprecated. Consider passing `prompt_ids` instead.",
|
1468 |
+
)
|
1469 |
+
|
1470 |
+
@staticmethod
|
1471 |
+
def _set_num_frames(return_token_timestamps, generation_config, kwargs):
|
1472 |
+
if return_token_timestamps:
|
1473 |
+
if getattr(generation_config, "task", None) == "translate":
|
1474 |
+
logger.warning("Token-level timestamps may not be reliable for task 'translate'.")
|
1475 |
+
if not hasattr(generation_config, "alignment_heads"):
|
1476 |
+
raise ValueError(
|
1477 |
+
"Model generation config has no `alignment_heads`, token-level timestamps not available. "
|
1478 |
+
"See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config."
|
1479 |
+
)
|
1480 |
+
generation_config.num_frames = kwargs.pop("num_frames", None)
|
1481 |
+
|
1482 |
+
@staticmethod
|
1483 |
+
def _set_thresholds_and_condition(
|
1484 |
+
generation_config,
|
1485 |
+
logprob_threshold,
|
1486 |
+
compression_ratio_threshold,
|
1487 |
+
no_speech_threshold,
|
1488 |
+
condition_on_prev_tokens,
|
1489 |
+
):
|
1490 |
+
generation_config.logprob_threshold = (
|
1491 |
+
logprob_threshold
|
1492 |
+
if logprob_threshold is not None
|
1493 |
+
else getattr(generation_config, "logprob_threshold", None)
|
1494 |
+
)
|
1495 |
+
generation_config.compression_ratio_threshold = (
|
1496 |
+
compression_ratio_threshold
|
1497 |
+
if compression_ratio_threshold is not None
|
1498 |
+
else getattr(generation_config, "compression_ratio_threshold", None)
|
1499 |
+
)
|
1500 |
+
generation_config.no_speech_threshold = (
|
1501 |
+
no_speech_threshold
|
1502 |
+
if no_speech_threshold is not None
|
1503 |
+
else getattr(generation_config, "no_speech_threshold", None)
|
1504 |
+
)
|
1505 |
+
generation_config.condition_on_prev_tokens = (
|
1506 |
+
condition_on_prev_tokens
|
1507 |
+
if condition_on_prev_tokens is not None
|
1508 |
+
else getattr(generation_config, "condition_on_prev_tokens", None)
|
1509 |
+
)
|
1510 |
+
|
1511 |
+
@staticmethod
|
1512 |
+
def _set_prompt_condition_type(generation_config, prompt_condition_type):
|
1513 |
+
allowed_cond_types = ["first-segment", "all-segments"]
|
1514 |
+
|
1515 |
+
# default to "first-segment"
|
1516 |
+
prompt_condition_type = prompt_condition_type or allowed_cond_types[0]
|
1517 |
+
|
1518 |
+
if prompt_condition_type not in allowed_cond_types:
|
1519 |
+
raise ValueError(
|
1520 |
+
f"`prompt_condition_type={prompt_condition_type} does not exist. Make sure to set `prompt_condition_type` to one of {', '.join(allowed_cond_types)}"
|
1521 |
+
)
|
1522 |
+
|
1523 |
+
if generation_config.condition_on_prev_tokens is not True and prompt_condition_type == "all-segments":
|
1524 |
+
raise ValueError(
|
1525 |
+
"Make sure to set `condition_on_prev_tokens=True` when setting `prompt_condition_type='all-segments'`."
|
1526 |
+
)
|
1527 |
+
|
1528 |
+
generation_config.prompt_condition_type = prompt_condition_type
|
1529 |
+
|
1530 |
+
@staticmethod
|
1531 |
+
def _set_condition_on_prev_tokens(condition_on_prev_tokens, generation_config):
|
1532 |
+
condition_on_prev_tokens = (
|
1533 |
+
condition_on_prev_tokens
|
1534 |
+
if condition_on_prev_tokens is not None
|
1535 |
+
else getattr(generation_config, "condition_on_prev_tokens", False)
|
1536 |
+
)
|
1537 |
+
generation_config.condition_on_prev_tokens = condition_on_prev_tokens
|
1538 |
+
|
1539 |
+
@staticmethod
|
1540 |
+
def _retrieve_max_frames_and_seek(batch_size, attention_mask, total_input_frames, is_shortform):
|
1541 |
+
if batch_size > 1 and not is_shortform and attention_mask is None:
|
1542 |
+
raise ValueError(
|
1543 |
+
"When doing batched long-form audio transcription, make sure to pass an `attention_mask`. You can retrieve the `attention_mask` by doing `processor(audio, ..., return_attention_mask=True)` "
|
1544 |
+
)
|
1545 |
+
elif batch_size > 1 and not is_shortform:
|
1546 |
+
max_frames = attention_mask.sum(-1).cpu().to(torch.long)
|
1547 |
+
seek = torch.zeros((batch_size,), dtype=torch.long)
|
1548 |
+
else:
|
1549 |
+
max_frames = torch.ones((batch_size,), dtype=torch.long) * total_input_frames
|
1550 |
+
seek = torch.zeros((batch_size,), dtype=torch.long)
|
1551 |
+
|
1552 |
+
return max_frames, seek
|
1553 |
+
|
1554 |
+
def _retrieve_logit_processors(self, generation_config, logits_processor, begin_index, num_beams, device):
|
1555 |
+
if generation_config.return_timestamps is True:
|
1556 |
+
timestamp_processor = WhisperTimeStampLogitsProcessor(generation_config, begin_index=begin_index)
|
1557 |
+
logits_processor = (
|
1558 |
+
[timestamp_processor] if logits_processor is None else [timestamp_processor] + logits_processor
|
1559 |
+
)
|
1560 |
+
|
1561 |
+
if generation_config.suppress_tokens is not None:
|
1562 |
+
suppress_tokens_processor = SuppressTokensLogitsProcessor(generation_config.suppress_tokens, device=device)
|
1563 |
+
logits_processor = (
|
1564 |
+
[suppress_tokens_processor]
|
1565 |
+
if logits_processor is None
|
1566 |
+
else [suppress_tokens_processor] + logits_processor
|
1567 |
+
)
|
1568 |
+
generation_config.suppress_tokens = None
|
1569 |
+
|
1570 |
+
if generation_config.begin_suppress_tokens is not None:
|
1571 |
+
begin_suppress_processor = SuppressTokensAtBeginLogitsProcessor(
|
1572 |
+
generation_config.begin_suppress_tokens, begin_index=begin_index, device=device
|
1573 |
+
)
|
1574 |
+
logits_processor = (
|
1575 |
+
[begin_suppress_processor]
|
1576 |
+
if logits_processor is None
|
1577 |
+
else [begin_suppress_processor] + logits_processor
|
1578 |
+
)
|
1579 |
+
generation_config.begin_suppress_tokens = None
|
1580 |
+
|
1581 |
+
if generation_config.no_speech_threshold is not None:
|
1582 |
+
no_speech_detector = WhisperNoSpeechDetection(
|
1583 |
+
no_speech_token=generation_config.no_timestamps_token_id - 1,
|
1584 |
+
begin_index=begin_index,
|
1585 |
+
scores_is_logprobs=num_beams > 1,
|
1586 |
+
)
|
1587 |
+
logits_processor = (
|
1588 |
+
[no_speech_detector] if logits_processor is None else [no_speech_detector] + logits_processor
|
1589 |
+
)
|
1590 |
+
no_speech_detector.set_model(self)
|
1591 |
+
|
1592 |
+
return logits_processor
|
1593 |
+
|
1594 |
+
@staticmethod
|
1595 |
+
def _maybe_reduce_batch(input_features, seek, max_frames, cur_bsz, batch_idx_map):
|
1596 |
+
prev_bsz = cur_bsz
|
1597 |
+
new_batch_idx_map = []
|
1598 |
+
for i in range(prev_bsz):
|
1599 |
+
prev_i = batch_idx_map[i]
|
1600 |
+
if seek[prev_i] >= max_frames[prev_i]:
|
1601 |
+
cut_index = i + (cur_bsz - prev_bsz)
|
1602 |
+
cur_bsz -= 1
|
1603 |
+
input_features = torch.cat([input_features[:cut_index], input_features[cut_index + 1 :]], dim=0)
|
1604 |
+
else:
|
1605 |
+
# cut out index that goes away
|
1606 |
+
new_batch_idx_map.append(prev_i)
|
1607 |
+
|
1608 |
+
return input_features, cur_bsz, new_batch_idx_map
|
1609 |
+
|
1610 |
+
@staticmethod
|
1611 |
+
def _get_input_segment(input_features, seek, seek_num_frames, num_segment_frames, cur_bsz, batch_idx_map):
|
1612 |
+
if input_features is None:
|
1613 |
+
return None
|
1614 |
+
|
1615 |
+
segment_input = []
|
1616 |
+
for i in range(cur_bsz):
|
1617 |
+
prev_i = batch_idx_map[i]
|
1618 |
+
segment_input_slice = input_features[i : i + 1, :, seek[prev_i] : seek[prev_i] + seek_num_frames[prev_i]]
|
1619 |
+
|
1620 |
+
if segment_input_slice.shape[-1] < num_segment_frames:
|
1621 |
+
# pad to 3000 if necessary
|
1622 |
+
segment_input_slice = F.pad(
|
1623 |
+
segment_input_slice, pad=(0, num_segment_frames - segment_input_slice.shape[-1])
|
1624 |
+
)
|
1625 |
+
|
1626 |
+
segment_input.append(segment_input_slice)
|
1627 |
+
|
1628 |
+
segment_input = torch.cat(segment_input, dim=0)
|
1629 |
+
|
1630 |
+
return segment_input
|
1631 |
+
|
1632 |
+
@staticmethod
|
1633 |
+
def _prepare_decoder_input_ids(
|
1634 |
+
cur_bsz,
|
1635 |
+
init_tokens,
|
1636 |
+
current_segments,
|
1637 |
+
batch_idx_map,
|
1638 |
+
do_condition_on_prev_tokens,
|
1639 |
+
prompt_ids,
|
1640 |
+
generation_config,
|
1641 |
+
config,
|
1642 |
+
device,
|
1643 |
+
suppress_tokens,
|
1644 |
+
kwargs,
|
1645 |
+
):
|
1646 |
+
if "decoder_input_ids" in kwargs:
|
1647 |
+
decoder_input_ids = kwargs.pop("decoder_input_ids")
|
1648 |
+
|
1649 |
+
return decoder_input_ids, kwargs
|
1650 |
+
|
1651 |
+
cut_off_length = config.max_target_positions // 2 - 1
|
1652 |
+
|
1653 |
+
decoder_input_ids = init_tokens[batch_idx_map]
|
1654 |
+
|
1655 |
+
prev_start_of_text = getattr(generation_config, "prev_sot_token_id", None)
|
1656 |
+
if prev_start_of_text is None:
|
1657 |
+
prev_start_of_text = suppress_tokens[-2] if suppress_tokens is not None else None
|
1658 |
+
|
1659 |
+
if any(do_condition_on_prev_tokens) and len(current_segments[0]) > 0:
|
1660 |
+
# according to https://github.com/openai/whisper/blob/e58f28804528831904c3b6f2c0e473f346223433/whisper/decoding.py#L609
|
1661 |
+
active_segments = [current_segments[i] if do_condition_on_prev_tokens[i] else None for i in batch_idx_map]
|
1662 |
+
|
1663 |
+
if prompt_ids is not None and generation_config.prompt_condition_type == "all-segments":
|
1664 |
+
prev_ids = prompt_ids
|
1665 |
+
else:
|
1666 |
+
one_tensor = torch.ones((cur_bsz, 1), device=device, dtype=torch.long)
|
1667 |
+
prev_ids = prev_start_of_text * one_tensor[0] if prev_start_of_text is not None else None
|
1668 |
+
|
1669 |
+
padding = "max_length" if generation_config.cache_implementation == "static" else "longest"
|
1670 |
+
|
1671 |
+
prev_tokens = _pad_to_max_length(
|
1672 |
+
active_segments,
|
1673 |
+
generation_config.pad_token_id,
|
1674 |
+
device=device,
|
1675 |
+
padding_side="left",
|
1676 |
+
padding=padding,
|
1677 |
+
bos_token_tensor=prev_ids,
|
1678 |
+
cut_off_length=cut_off_length,
|
1679 |
+
)
|
1680 |
+
decoder_input_ids = torch.cat([prev_tokens, decoder_input_ids], dim=-1)
|
1681 |
+
|
1682 |
+
kwargs["decoder_attention_mask"] = decoder_input_ids != generation_config.pad_token_id
|
1683 |
+
elif prompt_ids is not None:
|
1684 |
+
prev_tokens = prompt_ids[None].repeat(decoder_input_ids.shape[0], 1)
|
1685 |
+
decoder_input_ids = torch.cat([prev_tokens, decoder_input_ids], dim=-1)
|
1686 |
+
# make sure `"decoder_attention_mask"` is not passed to forward
|
1687 |
+
kwargs.pop("decoder_attention_mask", None)
|
1688 |
+
else:
|
1689 |
+
# make sure `"decoder_attention_mask"` is not passed to forward
|
1690 |
+
kwargs.pop("decoder_attention_mask", None)
|
1691 |
+
|
1692 |
+
return decoder_input_ids, kwargs
|
1693 |
+
|
1694 |
+
def _set_max_new_tokens_and_length(self, config, decoder_input_ids, generation_config):
|
1695 |
+
max_new_tokens = generation_config.max_new_tokens if generation_config.max_new_tokens is not None else 0
|
1696 |
+
if max_new_tokens + decoder_input_ids.shape[-1] > self.config.max_target_positions:
|
1697 |
+
raise ValueError(
|
1698 |
+
f"The length of `decoder_input_ids` equal `prompt_ids` plus special start tokens is {decoder_input_ids.shape[-1]}, and the `max_new_tokens` "
|
1699 |
+
f"is {max_new_tokens}. Thus, the combined length of "
|
1700 |
+
f"`decoder_input_ids` and `max_new_tokens` is: {max_new_tokens + decoder_input_ids.shape[-1]}. This exceeds the "
|
1701 |
+
f"`max_target_positions` of the Whisper model: {self.config.max_target_positions}. "
|
1702 |
+
"You should either reduce the length of your prompt, or reduce the value of `max_new_tokens`, "
|
1703 |
+
f"so that their combined length is less than {self.config.max_target_positions}."
|
1704 |
+
)
|
1705 |
+
|
1706 |
+
num_initial_tokens = min(config.max_target_positions // 2 - 1, decoder_input_ids.shape[-1] - 1)
|
1707 |
+
|
1708 |
+
# Make sure we don't get larger than `max_length`
|
1709 |
+
if generation_config.max_length is not None and generation_config.max_new_tokens is None:
|
1710 |
+
max_length = min(generation_config.max_length + num_initial_tokens, config.max_target_positions)
|
1711 |
+
logger.info(
|
1712 |
+
f"Increase max_length from {generation_config.max_length} to {max_length} since input is conditioned on previous segment."
|
1713 |
+
)
|
1714 |
+
elif (
|
1715 |
+
generation_config.max_new_tokens is not None
|
1716 |
+
and generation_config.max_new_tokens + decoder_input_ids.shape[-1] > config.max_target_positions
|
1717 |
+
):
|
1718 |
+
max_new_tokens = config.max_target_positions - decoder_input_ids.shape[-1]
|
1719 |
+
generation_config.max_new_tokens = max_new_tokens
|
1720 |
+
|
1721 |
+
@staticmethod
|
1722 |
+
def _retrieve_compression_ratio(tokens, vocab_size):
|
1723 |
+
"""Compute byte length of zlib compressed token bytes vs. byte length of raw token bytes"""
|
1724 |
+
length = int(math.log2(vocab_size) / 8) + 1
|
1725 |
+
token_bytes = b"".join([t.to_bytes(length, "little") for t in tokens.tolist()])
|
1726 |
+
compression_ratio = len(token_bytes) / len(zlib.compress(token_bytes))
|
1727 |
+
|
1728 |
+
return compression_ratio
|
1729 |
+
|
1730 |
+
@staticmethod
|
1731 |
+
def _retrieve_avg_logprobs(scores, tokens, eos_token_id, temperature):
|
1732 |
+
rescale_temperature = temperature if temperature > 0.0 else 1
|
1733 |
+
scores = torch.stack(scores).to(tokens.device)
|
1734 |
+
|
1735 |
+
if scores.shape[0] > tokens.shape[0]:
|
1736 |
+
scores = scores[: tokens.shape[0]]
|
1737 |
+
else:
|
1738 |
+
tokens = tokens[-scores.shape[0] :]
|
1739 |
+
|
1740 |
+
logprobs = F.log_softmax((scores * rescale_temperature).float(), dim=-1).to(scores.dtype)
|
1741 |
+
|
1742 |
+
# retrieve logprob of selected tokens and sum
|
1743 |
+
sum_logprobs = sum((logprobs[i][tokens[i]] * (tokens[i] != eos_token_id)) for i in range(logprobs.shape[0]))
|
1744 |
+
length = (tokens != eos_token_id).sum(-1) if eos_token_id is not None else tokens.shape[0]
|
1745 |
+
|
1746 |
+
avg_logprobs = sum_logprobs / (length + 1)
|
1747 |
+
return avg_logprobs
|
1748 |
+
|
1749 |
+
@staticmethod
|
1750 |
+
def _retrieve_segment(
|
1751 |
+
seek_sequence,
|
1752 |
+
seek_outputs,
|
1753 |
+
time_offset,
|
1754 |
+
timestamp_begin,
|
1755 |
+
seek_num_frames,
|
1756 |
+
time_precision,
|
1757 |
+
input_stride,
|
1758 |
+
prev_idx,
|
1759 |
+
idx,
|
1760 |
+
return_token_timestamps,
|
1761 |
+
):
|
1762 |
+
# find the predicted "end of segment" predictions of Whisper
|
1763 |
+
# "end of segment" predictions occur whenever Whisper predicts a timestamp token
|
1764 |
+
timestamp_tokens: torch.Tensor = seek_sequence.ge(timestamp_begin)
|
1765 |
+
single_timestamp_ending = timestamp_tokens[-2:].tolist() == [False, True]
|
1766 |
+
timestamp_segment_indices = torch.where(timestamp_tokens[:-1] & timestamp_tokens[1:])[0]
|
1767 |
+
timestamp_segment_indices.add_(1)
|
1768 |
+
token_timestamps = seek_outputs[idx]["token_timestamps"] if return_token_timestamps else []
|
1769 |
+
|
1770 |
+
# If whisper predicted a "end of segment" via a timestep token, let's go ever each
|
1771 |
+
# "end of segment" prediction and slice the decoding into segments accordingly
|
1772 |
+
if len(timestamp_segment_indices) > 0:
|
1773 |
+
# if the output contains two consecutive timestamp tokens
|
1774 |
+
slices = timestamp_segment_indices.tolist()
|
1775 |
+
segments = []
|
1776 |
+
if single_timestamp_ending:
|
1777 |
+
slices.append(len(seek_sequence))
|
1778 |
+
|
1779 |
+
last_slice = 0
|
1780 |
+
# Add each segment to list of all segments
|
1781 |
+
for current_slice in slices:
|
1782 |
+
sliced_tokens = seek_sequence[last_slice:current_slice]
|
1783 |
+
start_timestamp_pos = sliced_tokens[0].item() - timestamp_begin
|
1784 |
+
end_timestamp_pos = sliced_tokens[-1].item() - timestamp_begin
|
1785 |
+
segments.append(
|
1786 |
+
{
|
1787 |
+
"start": time_offset[prev_idx] + start_timestamp_pos * time_precision,
|
1788 |
+
"end": time_offset[prev_idx] + end_timestamp_pos * time_precision,
|
1789 |
+
"tokens": sliced_tokens,
|
1790 |
+
"result": seek_outputs[idx],
|
1791 |
+
}
|
1792 |
+
)
|
1793 |
+
if return_token_timestamps:
|
1794 |
+
segments[-1]["token_timestamps"] = (
|
1795 |
+
token_timestamps[last_slice:current_slice] + time_offset[prev_idx]
|
1796 |
+
)
|
1797 |
+
last_slice = current_slice
|
1798 |
+
|
1799 |
+
if single_timestamp_ending:
|
1800 |
+
# single timestamp at the end means no speech after the last timestamp.
|
1801 |
+
segment_offset = seek_num_frames[prev_idx]
|
1802 |
+
else:
|
1803 |
+
# otherwise, ignore the unfinished segment and seek to the last timestamp
|
1804 |
+
# here we throw away all predictions after the last predicted "end of segment"
|
1805 |
+
# since we are cutting right in the middle of an audio
|
1806 |
+
last_timestamp_pos = seek_sequence[last_slice - 1].item() - timestamp_begin
|
1807 |
+
segment_offset = last_timestamp_pos * input_stride
|
1808 |
+
else:
|
1809 |
+
# If whisper does not predict any "end of segment" token, then
|
1810 |
+
# the whole decoding is considered a segment and we add it to the list of segments
|
1811 |
+
timestamps = seek_sequence[timestamp_tokens.nonzero().flatten()]
|
1812 |
+
last_timestamp_pos = seek_num_frames[prev_idx]
|
1813 |
+
if timestamps.numel() > 0 and timestamps[-1].item() != timestamp_begin:
|
1814 |
+
# no consecutive timestamps but it has a timestamp; use the last one.
|
1815 |
+
last_timestamp_pos = timestamps[-1].item() - timestamp_begin
|
1816 |
+
segments = [
|
1817 |
+
{
|
1818 |
+
"start": time_offset[prev_idx],
|
1819 |
+
"end": time_offset[prev_idx] + last_timestamp_pos * time_precision,
|
1820 |
+
"tokens": seek_sequence,
|
1821 |
+
"result": seek_outputs[idx],
|
1822 |
+
}
|
1823 |
+
]
|
1824 |
+
if return_token_timestamps:
|
1825 |
+
segments[-1]["token_timestamps"] = token_timestamps + time_offset[prev_idx]
|
1826 |
+
segment_offset = seek_num_frames[prev_idx]
|
1827 |
+
|
1828 |
+
return segments, segment_offset
|
speech_tokenizer/modeling_whisper.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
speech_tokenizer/utils.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import io
|
3 |
+
import glob
|
4 |
+
import math
|
5 |
+
import tarfile
|
6 |
+
import torch
|
7 |
+
import torchaudio
|
8 |
+
import safetensors
|
9 |
+
from .configuration_whisper import WhisperVQConfig
|
10 |
+
from .modeling_whisper import WhisperVQEncoder, WhisperVQForConditionalGeneration
|
11 |
+
from transformers import WhisperFeatureExtractor, WhisperTokenizerFast
|
12 |
+
|
13 |
+
|
14 |
+
def load_quantize_encoder(model_path):
|
15 |
+
config = WhisperVQConfig.from_pretrained(model_path)
|
16 |
+
config.quantize_encoder_only = True
|
17 |
+
model = WhisperVQEncoder(config)
|
18 |
+
state_dict = {}
|
19 |
+
for path in glob.glob(os.path.join(model_path, "model*.safetensors")):
|
20 |
+
with safetensors.safe_open(path, framework="pt", device="cpu") as f:
|
21 |
+
for key in f.keys():
|
22 |
+
if key.startswith("model.encoder."):
|
23 |
+
new_key = key[len("model.encoder."):]
|
24 |
+
if new_key.startswith("layer_norm"):
|
25 |
+
continue
|
26 |
+
if new_key.startswith("layers"):
|
27 |
+
layer_id = int(new_key.split(".")[1])
|
28 |
+
if layer_id >= config.quantize_position:
|
29 |
+
continue
|
30 |
+
state_dict[new_key] = f.get_tensor(key)
|
31 |
+
model.load_state_dict(state_dict)
|
32 |
+
model.eval()
|
33 |
+
model.cuda()
|
34 |
+
return model
|
35 |
+
|
36 |
+
|
37 |
+
_resample_buffer: dict[int, torchaudio.transforms.Resample] = {}
|
38 |
+
|
39 |
+
|
40 |
+
def extract_speech_token(model: WhisperVQEncoder, feature_extractor: WhisperFeatureExtractor, utts):
|
41 |
+
with torch.no_grad():
|
42 |
+
audios, indices = [], []
|
43 |
+
for idx, utt in enumerate(utts):
|
44 |
+
if isinstance(utt, tuple):
|
45 |
+
audio, sample_rate = utt
|
46 |
+
else:
|
47 |
+
audio, sample_rate = torchaudio.load(utt)
|
48 |
+
audio = audio.cuda()
|
49 |
+
if sample_rate != 16000:
|
50 |
+
if sample_rate not in _resample_buffer:
|
51 |
+
_resample_buffer[sample_rate] = torchaudio.transforms.Resample(
|
52 |
+
orig_freq=sample_rate,
|
53 |
+
new_freq=16000
|
54 |
+
).to('cuda')
|
55 |
+
audio = _resample_buffer[sample_rate](audio)
|
56 |
+
# if audio.shape[0] > 1:
|
57 |
+
# audio = audio[:1]
|
58 |
+
audio = audio[0]
|
59 |
+
audio = audio.cpu().numpy()
|
60 |
+
time_step = 0
|
61 |
+
while time_step * 16000 < audio.shape[0]:
|
62 |
+
audio_segment = audio[time_step * 16000: (time_step + 30) * 16000]
|
63 |
+
audios.append(audio_segment)
|
64 |
+
indices.append(idx)
|
65 |
+
time_step += 30
|
66 |
+
pooling_kernel_size = model.config.pooling_kernel_size or 1
|
67 |
+
stride = model.conv1.stride[0] * model.conv2.stride[0] * pooling_kernel_size * feature_extractor.hop_length
|
68 |
+
all_speech_tokens = [[] for _ in range(len(utts))]
|
69 |
+
batch_size = 128
|
70 |
+
for start in range(0, len(audios), batch_size):
|
71 |
+
features = feature_extractor(audios[start: start + batch_size], sampling_rate=16000,
|
72 |
+
return_attention_mask=True, return_tensors="pt", device='cuda',
|
73 |
+
padding="longest", pad_to_multiple_of=stride)
|
74 |
+
features = features.to(device="cuda")
|
75 |
+
outputs = model(**features)
|
76 |
+
speech_tokens = outputs.quantized_token_ids
|
77 |
+
attention_mask = features.attention_mask[:, ::model.conv1.stride[0] * model.conv2.stride[0]]
|
78 |
+
attention_mask = attention_mask[:, ::model.config.pooling_kernel_size]
|
79 |
+
assert attention_mask.shape == speech_tokens.shape
|
80 |
+
for i in range(len(speech_tokens)):
|
81 |
+
idx = indices[start + i]
|
82 |
+
speech_token = speech_tokens[i][attention_mask[i].bool()].tolist()
|
83 |
+
all_speech_tokens[idx].extend(speech_token)
|
84 |
+
return all_speech_tokens
|