main
py 429 lines 15.6 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5 import numpy as np
6 import torch
7 import torch.nn as nn
8 import torchaudio.compliance.kaldi as kaldi
9 from torch.nn.utils.rnn import pad_sequence
10 from transformers import (
11 AutoFeatureExtractor,
12 BatchFeature,
13 )
14 from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
15 from transformers.processing_utils import ProcessorMixin
16 from transformers.utils import TensorType
17
18 from vllm.logger import init_logger
19
20 logger = init_logger(__name__)
21
22
23 def apply_cmvn(inputs, cmvn): # noqa
24 """Apply CMVN with mvn data."""
25 device = inputs.device
26 # dtype = inputs.dtype
27 frame, dim = inputs.shape
28
29 means = cmvn[0:1, :dim]
30 vars = cmvn[1:2, :dim]
31 inputs += means.to(device)
32 inputs *= vars.to(device)
33
34 return inputs.type(torch.float32)
35
36
37 def apply_lfr(inputs, lfr_m, lfr_n):
38 # LFR_inputs = []
39 T = inputs.shape[0]
40 T_lfr = int(np.ceil(T / lfr_n))
41 left_padding = inputs[0].repeat((lfr_m - 1) // 2, 1)
42 inputs = torch.vstack((left_padding, inputs))
43 T = T + (lfr_m - 1) // 2
44 feat_dim = inputs.shape[-1]
45 strides = (lfr_n * feat_dim, 1)
46 sizes = (T_lfr, lfr_m * feat_dim)
47 last_idx = (T - lfr_m) // lfr_n + 1
48 num_padding = lfr_m - (T - last_idx * lfr_n)
49 if num_padding > 0:
50 num_padding = (
51 (2 * lfr_m - 2 * T + (T_lfr - 1 + last_idx) * lfr_n)
52 / 2
53 * (T_lfr - last_idx)
54 )
55 inputs = torch.vstack([inputs] + [inputs[-1:]] * int(num_padding))
56 LFR_outputs = inputs.as_strided(sizes, strides)
57 return LFR_outputs.clone().type(torch.float32)
58
59
60 def load_cmvn(cmvn_file):
61 with open(cmvn_file, encoding="utf-8") as f:
62 lines = f.readlines()
63 means_list = []
64 vars_list = []
65 for i in range(len(lines)):
66 line_item = lines[i].split()
67 if line_item[0] == "<AddShift>":
68 line_item = lines[i + 1].split()
69 if line_item[0] == "<LearnRateCoef>":
70 add_shift_line = line_item[3 : (len(line_item) - 1)]
71 means_list = list(add_shift_line)
72 continue
73 elif line_item[0] == "<Rescale>":
74 line_item = lines[i + 1].split()
75 if line_item[0] == "<LearnRateCoef>":
76 rescale_line = line_item[3 : (len(line_item) - 1)]
77 vars_list = list(rescale_line)
78 continue
79 means = np.array(means_list).astype(np.float32)
80 vars = np.array(vars_list).astype(np.float32)
81 cmvn = np.array([means, vars])
82 cmvn = torch.as_tensor(cmvn, dtype=torch.float32)
83 return cmvn
84
85
86 class WavFrontend(nn.Module):
87 """Conventional frontend structure for ASR."""
88
89 def __init__(
90 self,
91 cmvn_file: str = "null",
92 fs: int = 16000,
93 window: str = "hamming",
94 n_mels: int = 80,
95 frame_length: int = 25,
96 frame_shift: int = 10,
97 filter_length_min: int = -1,
98 filter_length_max: int = -1,
99 lfr_m: int = 1,
100 lfr_n: int = 1,
101 dither: float = 1.0,
102 snip_edges: bool = True,
103 upsacle_samples: bool = True,
104 **kwargs,
105 ):
106 super().__init__()
107 self.fs = fs
108 self.window = window
109 self.n_mels = n_mels
110 self.frame_length = frame_length
111 self.frame_shift = frame_shift
112 self.filter_length_min = filter_length_min
113 self.filter_length_max = filter_length_max
114 self.lfr_m = lfr_m
115 self.lfr_n = lfr_n
116 self.cmvn_file = cmvn_file
117 self.dither = dither
118 self.snip_edges = snip_edges
119 self.upsacle_samples = upsacle_samples
120 self.cmvn = None if self.cmvn_file is None else load_cmvn(self.cmvn_file)
121
122 def output_size(self) -> int:
123 return self.n_mels * self.lfr_m
124
125 def forward(
126 self,
127 input: torch.Tensor,
128 input_lengths,
129 **kwargs,
130 ) -> tuple[torch.Tensor, torch.Tensor]:
131 batch_size = input.size(0)
132 feats = []
133 feats_lens = []
134 for i in range(batch_size):
135 waveform_length = input_lengths[i]
136 waveform = input[i][:waveform_length]
137 if self.upsacle_samples:
138 waveform = waveform * (1 << 15)
139 waveform = waveform.unsqueeze(0)
140 mat = kaldi.fbank(
141 waveform,
142 num_mel_bins=self.n_mels,
143 frame_length=min(self.frame_length, waveform_length / self.fs * 1000),
144 frame_shift=self.frame_shift,
145 dither=self.dither,
146 energy_floor=0.0,
147 window_type=self.window,
148 sample_frequency=self.fs,
149 snip_edges=self.snip_edges,
150 )
151
152 if self.lfr_m != 1 or self.lfr_n != 1:
153 mat = apply_lfr(mat, self.lfr_m, self.lfr_n)
154 if self.cmvn is not None:
155 mat = apply_cmvn(mat, self.cmvn)
156 feat_length = mat.size(0)
157 feats.append(mat)
158 feats_lens.append(feat_length)
159
160 feats_lens = torch.as_tensor(feats_lens)
161 if batch_size == 1:
162 feats_pad = feats[0][None, :, :]
163 else:
164 feats_pad = pad_sequence(feats, batch_first=True, padding_value=0.0)
165 return feats_pad, feats_lens
166
167
168 class FunASRFeatureExtractor(SequenceFeatureExtractor):
169 r"""Constructs a FunASR feature extractor.
170
171 This feature extractor inherits from [`~feature_extraction_sequence_
172 utils.SequenceFeatureExtractor`] which contains most of the main
173 methods. Users should refer to this superclass for more information
174 regarding those methods.
175
176 This class extracts mel-filter bank features from raw speech using a custom
177 numpy implementation of the `Short Time Fourier Transform` which should
178 match pytorch's `torch.stft` equivalent.
179
180 Args:
181 feature_size (`int`, *optional*, defaults to 80):
182 The feature dimension of the extracted features.
183 sampling_rate (`int`, *optional*, defaults to 16000):
184 The sampling rate at which the audio files should be digitalized
185 expressed in hertz (Hz).
186 hop_length (`int`, *optional*, defaults to 160):
187 Length of the overlapping windows for the STFT used to obtain the
188 Mel Frequency coefficients.
189 chunk_length (`int`, *optional*, defaults to 30):
190 The maximum number of chunks of `sampling_rate` samples used to
191 trim and pad longer or shorter audio sequences.
192 n_fft (`int`, *optional*, defaults to 400):
193 Size of the Fourier transform.
194 padding_value (`float`, *optional*, defaults to 0.0):
195 Padding value used to pad the audio. Should correspond to silences.
196 dither (`float`, *optional*, defaults to 0.0):
197 Adds dithering. In other words, adds a small Gaussian noise to each frame.
198 E.g. use 0.0001 to add dithering with a normal distribution centered
199 around 0.0 with standard deviation 0.0001 (assuming [-1,+1] range
200 of raw_speech). The value 0.0 means no dithering.
201 Dithering has similar effect as `spectrogram(mel_floor=...)`. It reduces
202 the high log_mel_fbank values for signals with hard-zero sections,
203 when VAD cutoff is present in the signal.
204
205 """
206
207 model_input_names = ["input_features"]
208
209 def __init__(
210 self,
211 feature_size=80,
212 sampling_rate=16000,
213 hop_length=160,
214 chunk_length=30,
215 n_fft=400,
216 padding_value=0.0,
217 dither=0.0,
218 max_length=1000,
219 return_attention_mask=False,
220 **kwargs,
221 ):
222 super().__init__(
223 feature_size=feature_size,
224 sampling_rate=sampling_rate,
225 padding_value=padding_value,
226 return_attention_mask=return_attention_mask,
227 **kwargs,
228 )
229 self.frontend_conf = kwargs.get("frontend_conf", {})
230 self.max_length = max_length
231 self.n_fft = n_fft
232 self.hop_length = hop_length
233 self.chunk_length = chunk_length
234 self.n_samples = chunk_length * sampling_rate
235 self.nb_max_frames = self.n_samples // hop_length
236 self.sampling_rate = sampling_rate
237 self.dither = dither
238
239 def extract_fbank(
240 self, data, data_len=None, data_type: str = "sound", frontend=None, **kwargs
241 ):
242 if isinstance(data, np.ndarray):
243 data = torch.from_numpy(data)
244 if len(data.shape) < 2:
245 data = data[None, :] # data: [batch, N]
246 data_len = [data.shape[1]] if data_len is None else data_len
247 elif isinstance(data, torch.Tensor):
248 if len(data.shape) < 2:
249 data = data[None, :] # data: [batch, N]
250 data_len = [data.shape[1]] if data_len is None else data_len
251 elif isinstance(data, (list, tuple)):
252 data_list, data_len = [], []
253 for data_i in data:
254 if isinstance(data_i, np.ndarray):
255 data_i = torch.from_numpy(data_i)
256 data_list.append(data_i)
257 data_len.append(data_i.shape[0])
258 data = pad_sequence(data_list, batch_first=True)
259
260 data, data_len = frontend(data, data_len, **kwargs)
261
262 if isinstance(data_len, (list, tuple)):
263 data_len = torch.tensor([data_len])
264 return data.to(torch.float32), data_len.to(torch.int32)
265
266 def __call__(
267 self,
268 raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
269 truncation: bool = True,
270 pad_to_multiple_of: int | None = None,
271 return_tensors: str | TensorType | None = None,
272 return_attention_mask: bool | None = None,
273 padding: str | None = "max_length",
274 max_length: int | None = None,
275 sampling_rate: int | None = None,
276 do_normalize: bool | None = None,
277 device: str | None = "cpu",
278 return_token_timestamps: bool | None = None,
279 **kwargs,
280 ) -> BatchFeature:
281 frontend = WavFrontend(**self.frontend_conf, dither=self.dither)
282
283 feats = []
284 speech_lengths = []
285 fake_token_lengths = []
286 for speech in raw_speech:
287 feature, length = self.extract_fbank(
288 speech,
289 data_type=kwargs.get("data_type", "sound"),
290 frontend=frontend,
291 is_final=True,
292 )
293 feats.append(feature)
294 speech_lengths.append(length)
295 olens = 1 + (length - 3 + 2 * 1) // 2
296 olens = 1 + (olens - 3 + 2 * 1) // 2
297 fake_token_len = (olens - 1) // 2 + 1
298 fake_token_len = torch.clamp(fake_token_len, min=1)
299 fake_token_lengths.append(fake_token_len)
300
301 feats = torch.concat(feats, dim=0)
302 batched_speech = self.pad(
303 BatchFeature({"input_features": feats}),
304 padding=padding,
305 max_length=max_length if max_length else self.max_length,
306 truncation=truncation,
307 pad_to_multiple_of=pad_to_multiple_of,
308 return_attention_mask=return_attention_mask or do_normalize,
309 )
310 if return_tensors is not None:
311 batched_speech = batched_speech.convert_to_tensors(return_tensors)
312
313 batched_speech["speech_lengths"] = torch.tensor(speech_lengths)
314 batched_speech["fake_token_lengths"] = torch.concat(fake_token_lengths)
315 return batched_speech
316
317
318 class FunASRProcessor(ProcessorMixin):
319 r"""Constructs a FunASR processor which wraps a FunASR feature extractor and
320 a FunASR tokenizer into a single processor.
321
322 [`FunASRProcessor`] offers all the functionalities of
323 [`FunASRFeatureExtractor`] and [`Qwen2Tokenizer`]. See the
324 [`~FunASRProcessor.__call__`] and [`~FunASRProcessor.decode`] for more
325 information.
326
327 Args:
328 feature_extractor (`FunASRFeatureExtractor`): An instance of
329 [`FunASRFeatureExtractor`].
330 The feature extractor is a required input.
331 tokenizer (`Qwen2Tokenizer`):
332 An instance of [`Qwen2Tokenizer`]. The tokenizer is a required
333 input.
334
335 """
336
337 feature_extractor_class = "FunASRFeatureExtractor"
338 tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
339
340 def __init__(
341 self,
342 feature_extractor,
343 tokenizer,
344 audio_token="<|AUDIO|>",
345 ):
346 super().__init__(feature_extractor, tokenizer)
347 self.current_processor = self.feature_extractor
348 self._in_target_context_manager = False
349 self.audio_token = (
350 tokenizer.audio_token if hasattr(tokenizer, "audio_token") else audio_token
351 )
352 self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
353
354 def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
355 return self.tokenizer.get_decoder_prompt_ids(
356 task=task, language=language, no_timestamps=no_timestamps
357 )
358
359 def __call__(self, *args, **kwargs):
360 """Forwards the `audio` argument to FunASRFeatureExtractor's
361 [`~FunASRFeatureExtractor.__call__`] and the `text` argument to
362 [`~Qwen2Tokenizer.__call__`]. Please refer to the docstring of the
363 above two methods for more information.
364 """
365 if self._in_target_context_manager:
366 return self.current_processor(*args, **kwargs)
367
368 audio = kwargs.pop("audio", None)
369 sampling_rate = kwargs.pop("sampling_rate", None)
370 text = kwargs.pop("text", None)
371 if len(args) > 0:
372 audio = args[0]
373 args = args[1:]
374
375 if text is None:
376 raise ValueError("You need to specify `text` input to process.")
377 elif isinstance(text, str):
378 text = [text]
379 elif not isinstance(text, list) and not isinstance(text[0], str):
380 raise ValueError(
381 "Invalid input text. Please provide a string, or a list of strings"
382 )
383
384 if audio is not None:
385 # ensure we have as much audios as audio tokens
386 num_audio_tokens = sum(sample.count(self.audio_token) for sample in text)
387 num_audios = 1 if type(audio) is np.ndarray else len(audio)
388 if num_audio_tokens != num_audios:
389 raise ValueError(
390 f"Found {num_audio_tokens} {self.audio_token} token{'s' if num_audio_tokens > 1 else ''} in provided text but received {num_audios} audio{'s' if num_audios > 1 else ''}" # noqa: E501
391 )
392 inputs = self.feature_extractor(
393 audio, *args, sampling_rate=sampling_rate, **kwargs
394 )
395
396 expanded_text = []
397 for sample in text:
398 replace_str = []
399 while self.audio_token in sample:
400 num_audio_tokens = inputs["fake_token_lengths"].item()
401
402 expanded_audio_token = self.audio_token * num_audio_tokens
403
404 replace_str.append(expanded_audio_token)
405 sample = sample.replace(self.audio_token, "<placeholder>", 1)
406
407 while "<placeholder>" in sample:
408 sample = sample.replace("<placeholder>", replace_str.pop(0), 1)
409 expanded_text.append(sample)
410 text = expanded_text
411
412 if text is not None:
413 encodings = self.tokenizer(text, **kwargs)
414
415 if text is None:
416 return inputs
417
418 elif audio is None:
419 return encodings
420 else:
421 inputs["labels"] = encodings["input_ids"]
422
423 return inputs
424
425 def get_prompt_ids(self, text: str, return_tensors="np"):
426 return self.tokenizer.get_prompt_ids(text, return_tensors=return_tensors)
427
428
429 AutoFeatureExtractor.register("FunASRFeatureExtractor", FunASRFeatureExtractor)