generation_whisper.py 108 KB

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