modeling_clvp.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. # Copyright 2023 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """PyTorch CLVP model."""
  15. import copy
  16. import math
  17. from collections.abc import Callable
  18. from dataclasses import dataclass
  19. import torch
  20. from torch import nn
  21. from torch.nn import CrossEntropyLoss
  22. from ... import initialization as init
  23. from ...activations import ACT2FN, get_activation
  24. from ...cache_utils import Cache, DynamicCache
  25. from ...generation import GenerationConfig, GenerationMixin
  26. from ...masking_utils import create_bidirectional_mask, create_causal_mask
  27. from ...modeling_outputs import (
  28. BaseModelOutputWithPastAndCrossAttentions,
  29. BaseModelOutputWithPooling,
  30. CausalLMOutputWithCrossAttentions,
  31. )
  32. from ...modeling_utils import PreTrainedModel
  33. from ...processing_utils import Unpack
  34. from ...pytorch_utils import Conv1D
  35. from ...utils import (
  36. ModelOutput,
  37. TransformersKwargs,
  38. auto_docstring,
  39. can_return_tuple,
  40. logging,
  41. )
  42. from ...utils.generic import merge_with_config_defaults
  43. from ...utils.output_capturing import capture_outputs
  44. from .configuration_clvp import (
  45. ClvpConfig,
  46. ClvpDecoderConfig,
  47. ClvpEncoderConfig,
  48. )
  49. logger = logging.get_logger(__name__)
  50. # Copied from transformers.models.clip.modeling_clip.contrastive_loss
  51. def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
  52. return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
  53. # Copied from transformers.models.clip.modeling_clip.clip_loss with clip->clvp, image_loss->speech_loss
  54. def clvp_loss(similarity: torch.Tensor) -> torch.Tensor:
  55. caption_loss = contrastive_loss(similarity)
  56. speech_loss = contrastive_loss(similarity.t())
  57. return (caption_loss + speech_loss) / 2.0
  58. # Copied from transformers.models.llama.modeling_llama.rotate_half
  59. def rotate_half(x):
  60. """Rotates half the hidden dims of the input."""
  61. x1 = x[..., : x.shape[-1] // 2]
  62. x2 = x[..., x.shape[-1] // 2 :]
  63. return torch.cat((-x2, x1), dim=-1)
  64. def apply_rotary_pos_emb(q, k, v, cos, sin, position_ids, unsqueeze_dim=1):
  65. """Applies Rotary Position Embedding to the query and key tensors.
  66. Args:
  67. q (`torch.Tensor`): The query tensor.
  68. k (`torch.Tensor`): The key tensor.
  69. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  70. sin (`torch.Tensor`): The sine part of the rotary embedding.
  71. position_ids (`torch.Tensor`):
  72. The position indices of the tokens corresponding to the query and key tensors. For example, this can be
  73. used to pass offsetted position ids when working with a KV-cache.
  74. unsqueeze_dim (`int`, *optional*, defaults to 1):
  75. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  76. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  77. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  78. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  79. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  80. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  81. Returns:
  82. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  83. """
  84. cos = cos[position_ids].unsqueeze(unsqueeze_dim)
  85. sin = sin[position_ids].unsqueeze(unsqueeze_dim)
  86. q_embed = (q * cos) + (rotate_half(q) * sin)
  87. k_embed = (k * cos) + (rotate_half(k) * sin)
  88. v_embed = (v * cos) + (rotate_half(v) * sin)
  89. return q_embed, k_embed, v_embed
  90. def _pad_extra_bos_eos_tokens(
  91. input_ids,
  92. attention_mask=None,
  93. pad_token_id=0,
  94. bos_token_id=255,
  95. eos_token_id=0,
  96. add_bos_token=True,
  97. add_eos_token=True,
  98. ):
  99. """
  100. This method adds extra bos and eos tokens to input_ids and accordingly modifies the attention_mask which is used in
  101. `ClvpConditioningEncoder` and the generation loop of the `ClvpModelForConditionalGeneration`.
  102. """
  103. # add the bos token at the beginning
  104. if add_bos_token:
  105. input_ids = torch.nn.functional.pad(input_ids, (1, 0), value=bos_token_id)
  106. attention_mask = (
  107. torch.nn.functional.pad(attention_mask, (1, 0), value=1) if attention_mask is not None else attention_mask
  108. )
  109. modified_input_ids = input_ids
  110. if add_eos_token:
  111. modified_input_ids = torch.zeros(
  112. (input_ids.shape[0], input_ids.shape[1] + 1), dtype=input_ids.dtype, device=input_ids.device
  113. )
  114. for i, each_input_id in enumerate(input_ids):
  115. # locate where the valid tokens end and then add the eos token
  116. if torch.isin(each_input_id, pad_token_id).sum():
  117. pos = torch.where(each_input_id == pad_token_id)[0].min()
  118. modified_input_ids[i] = torch.concatenate(
  119. [each_input_id[:pos], torch.tensor([eos_token_id], device=input_ids.device), each_input_id[pos:]]
  120. )
  121. else:
  122. # if there are no pad tokens present, then add eos to the end
  123. modified_input_ids[i] = torch.nn.functional.pad(each_input_id, (0, 1), value=eos_token_id)
  124. attention_mask = (
  125. torch.nn.functional.pad(attention_mask, (1, 0), value=1) if attention_mask is not None else attention_mask
  126. )
  127. return modified_input_ids, attention_mask
  128. @dataclass
  129. @auto_docstring(
  130. custom_intro="""
  131. Base class for CLVP encoder's outputs that contains a pooling of the last hidden states as well as a projection
  132. output (a linear layer on top of the pooled output).
  133. """
  134. )
  135. class ClvpEncoderOutput(ModelOutput):
  136. r"""
  137. embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when model is initialized with `with_projection=True`):
  138. The embeddings obtained by applying the projection layer to the pooler_output.
  139. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  140. The hidden state of the last layer of the model.
  141. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
  142. Pooled output of the `last_hidden_state`.
  143. """
  144. embeds: torch.FloatTensor | None = None
  145. last_hidden_state: torch.FloatTensor | None = None
  146. pooler_output: torch.FloatTensor | None = None
  147. hidden_states: tuple[torch.FloatTensor] | None = None
  148. attentions: tuple[torch.FloatTensor] | None = None
  149. @dataclass
  150. @auto_docstring
  151. class ClvpOutput(ModelOutput):
  152. r"""
  153. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
  154. Contrastive loss for speech-text similarity.
  155. speech_ids (`torch.LongTensor`, *optional*):
  156. speech_ids (or speech candidates) generated by the `ClvpForCausalLM` model.
  157. logits_per_speech (`torch.FloatTensor` of shape `(speech_batch_size, text_batch_size)`):
  158. The scaled dot product scores between `speech_embeds` and `text_embeds`. This represents the speech-text
  159. similarity scores.
  160. logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, speech_batch_size)`):
  161. The scaled dot product scores between `text_embeds` and `speech_embeds`. This represents the text-speech
  162. similarity scores.
  163. text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
  164. The text embeddings obtained by applying the projection layer to the pooled output of the text encoder
  165. model.
  166. speech_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
  167. The speech embeddings obtained by applying the projection layer to the pooled output of the speech encoder
  168. model.
  169. text_model_output (`BaseModelOutputWithPooling`):
  170. The pooled output of the `last_hidden_state` of the text encoder Model.
  171. speech_model_output (`BaseModelOutputWithPooling`):
  172. The pooled output of the `last_hidden_state` of the speech encoder Model.
  173. decoder_hidden_states (`torch.FloatTensor`, *optional*):
  174. The hidden states of the decoder model.
  175. text_encoder_hidden_states (`torch.FloatTensor`, *optional*):
  176. The hidden states of the text encoder model.
  177. speech_encoder_hidden_states (`torch.FloatTensor`, *optional*):
  178. The hidden states of the speech encoder model.
  179. """
  180. loss: torch.FloatTensor | None = None
  181. speech_ids: torch.LongTensor | None = None
  182. logits_per_speech: torch.FloatTensor | None = None
  183. logits_per_text: torch.FloatTensor | None = None
  184. text_embeds: torch.FloatTensor | None = None
  185. speech_embeds: torch.FloatTensor | None = None
  186. text_model_output: BaseModelOutputWithPooling = None
  187. speech_model_output: BaseModelOutputWithPooling = None
  188. decoder_hidden_states: torch.FloatTensor | None = None
  189. text_encoder_hidden_states: torch.FloatTensor | None = None
  190. speech_encoder_hidden_states: torch.FloatTensor | None = None
  191. # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Clvp
  192. class ClvpRMSNorm(nn.Module):
  193. def __init__(self, hidden_size, eps: float = 1e-6) -> None:
  194. """
  195. ClvpRMSNorm is equivalent to T5LayerNorm
  196. """
  197. super().__init__()
  198. self.weight = nn.Parameter(torch.ones(hidden_size))
  199. self.variance_epsilon = eps
  200. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  201. input_dtype = hidden_states.dtype
  202. hidden_states = hidden_states.to(torch.float32)
  203. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  204. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  205. return self.weight * hidden_states.to(input_dtype)
  206. def extra_repr(self):
  207. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  208. class ClvpRotaryPositionalEmbedding(nn.Module):
  209. """
  210. Rotary Position Embedding Class for CLVP. It was proposed in the paper 'ROFORMER: ENHANCED TRANSFORMER WITH ROTARY
  211. POSITION EMBEDDING', Please see https://huggingface.co/papers/2104.09864.
  212. """
  213. def __init__(self, config):
  214. super().__init__()
  215. dim = max(config.projection_dim // (config.num_attention_heads * 2), 32)
  216. inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
  217. self.register_buffer("inv_freq", inv_freq)
  218. self.cached_sequence_length = None
  219. self.cached_rotary_positional_embedding = None
  220. def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  221. sequence_length = hidden_states.shape[1]
  222. if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:
  223. return self.cached_rotary_positional_embedding
  224. self.cached_sequence_length = sequence_length
  225. time_stamps = torch.arange(sequence_length, device=hidden_states.device).type_as(self.inv_freq)
  226. freqs = torch.einsum("i,j->ij", time_stamps, self.inv_freq)
  227. embeddings = torch.cat((freqs, freqs), dim=-1)
  228. self.cached_rotary_positional_embedding = embeddings.unsqueeze(0)
  229. return self.cached_rotary_positional_embedding
  230. class ClvpSelfAttention(nn.Module):
  231. """
  232. Multi-headed attention to combine Absolute and Rotary Positional Embeddings into a single Attention module.
  233. """
  234. def __init__(self, config, layer_idx=None):
  235. super().__init__()
  236. self.config = config
  237. self.embed_dim = config.hidden_size
  238. self.num_heads = config.num_attention_heads
  239. self.head_dim = self.embed_dim // self.num_heads
  240. if self.head_dim * self.num_heads != self.embed_dim:
  241. raise ValueError(
  242. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  243. f" {self.num_heads})."
  244. )
  245. self.scale = self.head_dim**-0.5
  246. self.dropout = config.attention_dropout
  247. self.layer_idx = layer_idx
  248. if hasattr(config, "max_position_embeddings"):
  249. max_positions = config.max_position_embeddings
  250. bias = torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool))
  251. bias = bias.view(1, 1, max_positions, max_positions)
  252. self.register_buffer("bias", bias, persistent=False)
  253. self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias)
  254. self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias)
  255. self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias)
  256. self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
  257. def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
  258. return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  259. def forward(
  260. self,
  261. hidden_states: torch.FloatTensor,
  262. rotary_pos_emb: torch.FloatTensor | None = None,
  263. attention_mask: torch.LongTensor | None = None,
  264. position_ids: torch.LongTensor | None = None,
  265. past_key_values: Cache | None = None,
  266. use_cache: bool | None = False,
  267. **kwargs: Unpack[TransformersKwargs],
  268. ) -> tuple[torch.FloatTensor, torch.FloatTensor | None]:
  269. # Raise error when position_ids is None but rotary_pos_emb is provided, because we need that when applying
  270. # rotary_pos_emb to query and key states.
  271. if rotary_pos_emb is not None and position_ids is None:
  272. raise ValueError("`position_ids` must be provided when `rotary_pos_emb` is not None.")
  273. bsz, _, embed_dim = hidden_states.size()
  274. # get query proj
  275. query_states = self._shape(self.q_proj(hidden_states), -1, bsz) * self.scale
  276. key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
  277. value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
  278. if past_key_values is not None:
  279. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  280. if rotary_pos_emb is not None:
  281. rotary_emb_dim = rotary_pos_emb.shape[-1]
  282. # Partial rotary embedding
  283. query_rot, query_pass = (
  284. query_states[..., :rotary_emb_dim],
  285. query_states[..., rotary_emb_dim:],
  286. )
  287. key_rot, key_pass = (
  288. key_states[..., :rotary_emb_dim],
  289. key_states[..., rotary_emb_dim:],
  290. )
  291. value_rot, value_pass = (
  292. value_states[..., :rotary_emb_dim],
  293. value_states[..., rotary_emb_dim:],
  294. )
  295. cos, sin = rotary_pos_emb.cos().squeeze(0), rotary_pos_emb.sin().squeeze(0)
  296. query_rot, key_rot, value_rot = apply_rotary_pos_emb(query_rot, key_rot, value_rot, cos, sin, position_ids)
  297. # [batch_size, num_heads, seq_length, head_dim]
  298. query_states = torch.cat((query_rot, query_pass), dim=-1)
  299. key_states = torch.cat((key_rot, key_pass), dim=-1)
  300. value_states = torch.cat((value_rot, value_pass), dim=-1)
  301. tgt_len = query_states.shape[2]
  302. src_len = key_states.shape[2]
  303. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
  304. if attention_mask is not None:
  305. if attention_mask.size() != (bsz, 1, tgt_len, src_len):
  306. raise ValueError(
  307. f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
  308. )
  309. attn_weights = attn_weights + attention_mask
  310. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  311. attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
  312. attn_output = torch.matmul(attn_probs, value_states)
  313. if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
  314. raise ValueError(
  315. f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
  316. f" {attn_output.size()}"
  317. )
  318. attn_output = attn_output.transpose(1, 2).contiguous()
  319. attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
  320. attn_output = self.out_proj(attn_output)
  321. return attn_output, attn_weights
  322. class ClvpGatedLinearUnit(nn.Module):
  323. """
  324. `ClvpGatedLinearUnit` uses the second half of the `hidden_states` to act as a gate for the first half of the
  325. `hidden_states` which controls the flow of data from the first of the tensor.
  326. """
  327. def __init__(self, config):
  328. super().__init__()
  329. self.activation_fn = ACT2FN[config.hidden_act]
  330. self.proj = nn.Linear(config.hidden_size, config.intermediate_size * 2)
  331. def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  332. hidden_states, gate = self.proj(hidden_states).chunk(2, dim=-1)
  333. return hidden_states * self.activation_fn(gate)
  334. class ClvpEncoderMLP(nn.Module):
  335. """
  336. This MLP is used in CLVP speech or text encoder models.
  337. """
  338. def __init__(self, config):
  339. super().__init__()
  340. self.config = config
  341. self.fc1 = ClvpGatedLinearUnit(config)
  342. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  343. self.dropout_layer = nn.Dropout(config.dropout)
  344. def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  345. hidden_states = self.fc1(hidden_states)
  346. hidden_states = self.dropout_layer(hidden_states)
  347. hidden_states = self.fc2(hidden_states)
  348. return hidden_states
  349. class ClvpEncoderLayer(nn.Module):
  350. def __init__(self, config: ClvpConfig):
  351. super().__init__()
  352. self.config = config
  353. self.embed_dim = config.hidden_size
  354. self.self_attn = ClvpSelfAttention(config)
  355. self.mlp = ClvpEncoderMLP(config)
  356. self.input_rmsnorm = ClvpRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
  357. self.post_attention_rmsnorm = ClvpRMSNorm(self.embed_dim, eps=config.layer_norm_eps)
  358. def forward(
  359. self,
  360. hidden_states: torch.FloatTensor,
  361. rotary_pos_emb: torch.FloatTensor,
  362. attention_mask: torch.LongTensor,
  363. position_ids: torch.LongTensor,
  364. **kwargs: Unpack[TransformersKwargs],
  365. ) -> torch.FloatTensor:
  366. residual = hidden_states
  367. hidden_states = self.input_rmsnorm(hidden_states)
  368. hidden_states, _ = self.self_attn(
  369. hidden_states,
  370. rotary_pos_emb=rotary_pos_emb,
  371. attention_mask=attention_mask,
  372. position_ids=position_ids,
  373. **kwargs,
  374. )
  375. hidden_states = residual + hidden_states
  376. residual = hidden_states
  377. hidden_states = self.post_attention_rmsnorm(hidden_states)
  378. hidden_states = self.mlp(hidden_states)
  379. hidden_states = residual + hidden_states
  380. return hidden_states
  381. # Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->Clvp
  382. class ClvpSequenceSummary(nn.Module):
  383. r"""
  384. Compute a single vector summary of a sequence hidden states.
  385. Args:
  386. config ([`ClvpConfig`]):
  387. The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
  388. config class of your model for the default values it uses):
  389. - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
  390. - `"last"` -- Take the last token hidden state (like XLNet)
  391. - `"first"` -- Take the first token hidden state (like Bert)
  392. - `"mean"` -- Take the mean of all tokens hidden states
  393. - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
  394. - `"attn"` -- Not implemented now, use multi-head attention
  395. - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
  396. - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
  397. (otherwise to `config.hidden_size`).
  398. - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
  399. another string or `None` will add no activation.
  400. - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
  401. - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
  402. """
  403. def __init__(self, config: ClvpConfig):
  404. super().__init__()
  405. self.summary_type = getattr(config, "summary_type", "last")
  406. if self.summary_type == "attn":
  407. # We should use a standard multi-head attention module with absolute positional embedding for that.
  408. # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
  409. # We can probably just use the multi-head attention module of PyTorch >=1.1.0
  410. raise NotImplementedError
  411. self.summary = nn.Identity()
  412. if hasattr(config, "summary_use_proj") and config.summary_use_proj:
  413. if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
  414. num_classes = config.num_labels
  415. else:
  416. num_classes = config.hidden_size
  417. self.summary = nn.Linear(config.hidden_size, num_classes)
  418. activation_string = getattr(config, "summary_activation", None)
  419. self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
  420. self.first_dropout = nn.Identity()
  421. if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
  422. self.first_dropout = nn.Dropout(config.summary_first_dropout)
  423. self.last_dropout = nn.Identity()
  424. if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
  425. self.last_dropout = nn.Dropout(config.summary_last_dropout)
  426. def forward(
  427. self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
  428. ) -> torch.FloatTensor:
  429. """
  430. Compute a single vector summary of a sequence hidden states.
  431. Args:
  432. hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
  433. The hidden states of the last layer.
  434. cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
  435. Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
  436. Returns:
  437. `torch.FloatTensor`: The summary of the sequence hidden states.
  438. """
  439. if self.summary_type == "last":
  440. output = hidden_states[:, -1]
  441. elif self.summary_type == "first":
  442. output = hidden_states[:, 0]
  443. elif self.summary_type == "mean":
  444. output = hidden_states.mean(dim=1)
  445. elif self.summary_type == "cls_index":
  446. if cls_index is None:
  447. cls_index = torch.full_like(
  448. hidden_states[..., :1, :],
  449. hidden_states.shape[-2] - 1,
  450. dtype=torch.long,
  451. )
  452. else:
  453. cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
  454. cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
  455. # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
  456. output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
  457. elif self.summary_type == "attn":
  458. raise NotImplementedError
  459. output = self.first_dropout(output)
  460. output = self.summary(output)
  461. output = self.activation(output)
  462. output = self.last_dropout(output)
  463. return output
  464. # Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP with GPT2->ClvpDecoderMLP
  465. class ClvpDecoderMLP(nn.Module):
  466. def __init__(self, intermediate_size, config):
  467. super().__init__()
  468. embed_dim = config.hidden_size
  469. self.c_fc = Conv1D(intermediate_size, embed_dim)
  470. self.c_proj = Conv1D(embed_dim, intermediate_size)
  471. self.act = ACT2FN[config.activation_function]
  472. self.dropout = nn.Dropout(config.resid_pdrop)
  473. def forward(self, hidden_states: tuple[torch.FloatTensor] | None) -> torch.FloatTensor:
  474. hidden_states = self.c_fc(hidden_states)
  475. hidden_states = self.act(hidden_states)
  476. hidden_states = self.c_proj(hidden_states)
  477. hidden_states = self.dropout(hidden_states)
  478. return hidden_states
  479. class ClvpDecoderLayer(nn.Module):
  480. def __init__(self, config, layer_idx=None):
  481. super().__init__()
  482. hidden_size = config.hidden_size
  483. inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
  484. self.input_layernorm = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  485. self.attn = ClvpSelfAttention(config, layer_idx=layer_idx)
  486. self.post_attention_layernorm = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  487. self.mlp = ClvpDecoderMLP(inner_dim, config)
  488. def forward(
  489. self,
  490. hidden_states: torch.FloatTensor,
  491. past_key_values: Cache | None = None,
  492. attention_mask: torch.LongTensor | None = None,
  493. position_ids: torch.LongTensor | None = None,
  494. use_cache: bool | None = False,
  495. **kwargs: Unpack[TransformersKwargs],
  496. ) -> torch.Tensor:
  497. residual = hidden_states
  498. hidden_states = self.input_layernorm(hidden_states)
  499. hidden_states, _ = self.attn(
  500. hidden_states,
  501. past_key_values=past_key_values,
  502. attention_mask=attention_mask,
  503. position_ids=position_ids,
  504. use_cache=use_cache,
  505. **kwargs,
  506. )
  507. # residual connection
  508. hidden_states = hidden_states + residual
  509. residual = hidden_states
  510. hidden_states = self.post_attention_layernorm(hidden_states)
  511. feed_forward_hidden_states = self.mlp(hidden_states)
  512. # residual connection
  513. hidden_states = residual + feed_forward_hidden_states
  514. return hidden_states
  515. class ClvpConditioningEncoder(nn.Module):
  516. """
  517. This class processes the log-mel spectrograms(extracted by the Feature Extractor) and text tokens(produced by the
  518. tokenizer) as inputs for the decoder model.
  519. First each log-mel spectrogram is processed into a single vector which captures valuable characteristics from each
  520. of them, then the text tokens are converted into token embeddings and position embeddings are added afterwards.
  521. Both of these vectors are concatenated and then passed to the decoder model.
  522. The text tokens helps to incorporate the "text information" and the log-mel spectrogram is used to specify the
  523. "voice characteristics" into the generated mel tokens.
  524. """
  525. def __init__(self, config: ClvpConfig):
  526. super().__init__()
  527. self.text_config = config.text_config
  528. self.decoder_config = config.decoder_config
  529. self.text_token_embedding = nn.Embedding(self.text_config.vocab_size, self.decoder_config.hidden_size)
  530. self.text_position_embedding = nn.Embedding(
  531. self.decoder_config.max_text_tokens, self.decoder_config.hidden_size
  532. )
  533. self.mel_conv = nn.Conv1d(self.decoder_config.feature_size, self.decoder_config.hidden_size, kernel_size=1)
  534. # define group norms to be used before each attention layer
  535. num_groups = self.compute_groupnorm_groups(self.decoder_config.hidden_size)
  536. self.group_norms = nn.ModuleList(
  537. [
  538. nn.GroupNorm(num_groups, self.decoder_config.hidden_size, eps=1e-5, affine=True)
  539. for _ in range(self.decoder_config.num_mel_attn_blocks)
  540. ]
  541. )
  542. # define the attention layers
  543. self.mel_attn_blocks = nn.ModuleList(
  544. [ClvpSelfAttention(self.decoder_config) for _ in range(self.decoder_config.num_mel_attn_blocks)]
  545. )
  546. self.gradient_checkpointing = False
  547. def compute_groupnorm_groups(self, channels: int, groups: int = 32):
  548. """
  549. Calculates the value of `num_groups` for nn.GroupNorm. This logic is taken from the official tortoise
  550. repository. link :
  551. https://github.com/neonbjb/tortoise-tts/blob/4003544b6ff4b68c09856e04d3eff9da26d023c2/tortoise/models/arch_util.py#L26
  552. """
  553. if channels <= 16:
  554. groups = 8
  555. elif channels <= 64:
  556. groups = 16
  557. while channels % groups != 0:
  558. groups = int(groups / 2)
  559. if groups <= 2:
  560. raise ValueError(
  561. f"Number of groups for the GroupNorm must be greater than 2, but it is {groups}."
  562. f"Please consider using a different `hidden_size`"
  563. )
  564. return groups
  565. def forward(
  566. self,
  567. input_features: torch.FloatTensor,
  568. input_ids: torch.LongTensor | None = None,
  569. inputs_embeds: torch.FloatTensor | None = None,
  570. attention_mask: torch.LongTensor | None = None,
  571. ):
  572. # process text
  573. if input_ids is not None and inputs_embeds is not None:
  574. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  575. elif input_ids is not None:
  576. batch_size, seq_length = input_ids.size()
  577. elif inputs_embeds is not None:
  578. batch_size, seq_length = inputs_embeds.size()[:-1]
  579. else:
  580. raise ValueError("You have to specify either input_ids or inputs_embeds")
  581. # construct attention mask if not given
  582. if attention_mask is None:
  583. attention_mask = torch.ones([batch_size, seq_length], dtype=torch.long, device=input_ids.device)
  584. # We add bos and eos input_ids in the modeling file instead of the tokenizer file to keep the logic simple
  585. # This logic is specific to ClvpConditioningEncoder and not used by other modules.
  586. input_ids, attention_mask = _pad_extra_bos_eos_tokens(
  587. input_ids,
  588. attention_mask,
  589. bos_token_id=self.text_config.bos_token_id,
  590. eos_token_id=self.text_config.eos_token_id,
  591. )
  592. inputs_embeds = self.text_token_embedding(input_ids)
  593. position_ids = attention_mask.cumsum(-1) - 1
  594. position_embeds = self.text_position_embedding(position_ids)
  595. text_embeds = inputs_embeds + position_embeds
  596. if self.gradient_checkpointing and self.training:
  597. # process each log-mel spectrogram into a single vector
  598. mel_spec = torch.utils.checkpoint.checkpoint(self.mel_conv, input_features)
  599. for i, mel_attn_block in enumerate(self.mel_attn_blocks):
  600. residual_mel_spec = mel_spec.transpose(1, 2)
  601. mel_spec = torch.utils.checkpoint.checkpoint(self.group_norms[i], mel_spec).transpose(1, 2)
  602. mel_spec = torch.utils.checkpoint.checkpoint(mel_attn_block, mel_spec)[0] + residual_mel_spec
  603. mel_spec = mel_spec.transpose(1, 2)
  604. else:
  605. # process each log-mel spectrogram into a single vector
  606. mel_spec = self.mel_conv(input_features)
  607. for i, mel_attn_block in enumerate(self.mel_attn_blocks):
  608. residual_mel_spec = mel_spec.transpose(1, 2)
  609. mel_spec = self.group_norms[i](mel_spec).transpose(1, 2)
  610. mel_spec = mel_attn_block(mel_spec)[0] + residual_mel_spec
  611. mel_spec = mel_spec.transpose(1, 2)
  612. mel_spec = mel_spec[:, :, 0]
  613. mel_spec = mel_spec.unsqueeze(1)
  614. # repeat if there is either (1 text vs N audios) or (N texts vs 1 audio)
  615. if text_embeds.shape[0] == 1 and mel_spec.shape[0] != 1:
  616. text_embeds = text_embeds.repeat(mel_spec.shape[0], 1, 1)
  617. elif text_embeds.shape[0] != 1 and mel_spec.shape[0] == 1:
  618. mel_spec = mel_spec.repeat(text_embeds.shape[0], 1, 1)
  619. # If there is N texts and M audios we will raise error since the number of text and audio must be same.
  620. elif text_embeds.shape[0] != mel_spec.shape[0]:
  621. raise ValueError(
  622. f"The number of texts and number of audios must be same. "
  623. f"Found {text_embeds.shape[0]} texts vs {mel_spec.shape[0]} audios"
  624. )
  625. return torch.concat([mel_spec, text_embeds], dim=1)
  626. @auto_docstring
  627. class ClvpPreTrainedModel(PreTrainedModel):
  628. config: ClvpConfig
  629. base_model_prefix = "model"
  630. supports_gradient_checkpointing = True
  631. _skip_keys_device_placement = "past_key_values"
  632. _can_record_outputs = {
  633. "hidden_states": (ClvpEncoderLayer, ClvpDecoderLayer),
  634. "attentions": ClvpSelfAttention,
  635. }
  636. @torch.no_grad()
  637. def _init_weights(self, module: nn.Module):
  638. """Initialize the weights"""
  639. factor = self.config.initializer_factor
  640. if isinstance(module, nn.Embedding):
  641. init.normal_(module.weight, mean=0.0, std=factor * 0.02)
  642. elif isinstance(module, (nn.Linear, Conv1D, nn.Conv1d)):
  643. init.normal_(module.weight, mean=0.0, std=factor * 0.02)
  644. if module.bias is not None:
  645. init.zeros_(module.bias)
  646. elif isinstance(module, ClvpRMSNorm):
  647. init.ones_(module.weight)
  648. elif isinstance(module, ClvpEncoderMLP):
  649. in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
  650. fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
  651. init.normal_(module.fc1.proj.weight if getattr(module.fc1, "proj") else module.fc1.weight, std=fc_std)
  652. init.normal_(module.fc2.weight, std=in_proj_std)
  653. elif isinstance(module, ClvpEncoder):
  654. config = self.config.get_text_config()
  655. factor = config.initializer_factor
  656. init.normal_(module.projection.weight, mean=0.0, std=factor * (config.hidden_size**-0.5))
  657. elif isinstance(module, ClvpConditioningEncoder):
  658. init.normal_(module.mel_conv.weight, mean=0.0, std=factor)
  659. init.zeros_(module.mel_conv.bias)
  660. elif isinstance(module, ClvpForCausalLM):
  661. for name, p in module.named_parameters():
  662. if name == "c_proj.weight":
  663. init.normal_(
  664. p, mean=0.0, std=self.config.initializer_range / math.sqrt(2 * self.config.num_hidden_layers)
  665. )
  666. elif isinstance(module, ClvpModelForConditionalGeneration):
  667. init.constant_(module.logit_scale, self.config.logit_scale_init_value)
  668. elif isinstance(module, ClvpSelfAttention):
  669. if hasattr(module.config, "max_position_embeddings"):
  670. max_positions = module.config.max_position_embeddings
  671. bias = torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool))
  672. bias = bias.view(1, 1, max_positions, max_positions)
  673. init.copy_(module.bias, bias)
  674. elif isinstance(module, ClvpRotaryPositionalEmbedding):
  675. dim = max(self.config.projection_dim // (self.config.num_attention_heads * 2), 32)
  676. inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
  677. init.copy_(module.inv_freq, inv_freq)
  678. if isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
  679. init.zeros_(module.bias)
  680. init.ones_(module.weight)
  681. class ClvpEncoder(ClvpPreTrainedModel):
  682. """
  683. Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
  684. [`ClvpEncoderLayer`].
  685. Args:
  686. config: ClvpConfig
  687. """
  688. config: ClvpEncoderConfig
  689. def __init__(self, config: ClvpConfig):
  690. super().__init__(config)
  691. self.config = config
  692. self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
  693. self.rotary_pos_emb = ClvpRotaryPositionalEmbedding(config) if config.use_rotary_embedding else None
  694. self.layers = nn.ModuleList([ClvpEncoderLayer(config) for _ in range(config.num_hidden_layers)])
  695. self.sequence_summary = ClvpSequenceSummary(config)
  696. self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  697. self.projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
  698. self.gradient_checkpointing = False
  699. self.post_init()
  700. def get_input_embeddings(self):
  701. return self.token_embedding
  702. def set_input_embeddings(self, value):
  703. self.token_embedding = value
  704. @merge_with_config_defaults
  705. @capture_outputs
  706. @auto_docstring
  707. def forward(
  708. self,
  709. input_ids: torch.LongTensor | None = None,
  710. inputs_embeds: torch.LongTensor | None = None,
  711. attention_mask: torch.LongTensor | None = None,
  712. position_ids: torch.LongTensor | None = None,
  713. **kwargs: Unpack[TransformersKwargs],
  714. ) -> ClvpEncoderOutput:
  715. if (input_ids is None) ^ (inputs_embeds is not None):
  716. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  717. if inputs_embeds is None:
  718. inputs_embeds = self.token_embedding(input_ids)
  719. # expand attention_mask and create position_ids if needed
  720. attention_mask = create_bidirectional_mask(
  721. config=self.config,
  722. inputs_embeds=inputs_embeds,
  723. attention_mask=attention_mask,
  724. )
  725. if position_ids is None:
  726. device = input_ids.device if input_ids is not None else inputs_embeds.device
  727. position_ids = torch.arange(inputs_embeds.shape[1], dtype=torch.long, device=device)
  728. position_ids = position_ids.unsqueeze(0)
  729. rotary_pos_emb = self.rotary_pos_emb(inputs_embeds) if self.rotary_pos_emb is not None else None
  730. hidden_states = inputs_embeds
  731. for encoder_layer in self.layers:
  732. hidden_states = encoder_layer(
  733. hidden_states,
  734. rotary_pos_emb,
  735. attention_mask,
  736. position_ids,
  737. **kwargs,
  738. )
  739. last_hidden_state = self.final_layer_norm(hidden_states)
  740. # take the mean over axis 1 and get pooled output
  741. pooled_output = self.sequence_summary(last_hidden_state)
  742. # apply the projection layer
  743. embeds = self.projection(pooled_output)
  744. return ClvpEncoderOutput(
  745. embeds=embeds,
  746. last_hidden_state=last_hidden_state,
  747. pooler_output=pooled_output,
  748. )
  749. class ClvpDecoder(ClvpPreTrainedModel):
  750. """
  751. Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ClvpDecoderLayer`]
  752. """
  753. config: ClvpDecoderConfig
  754. def __init__(self, config):
  755. super().__init__(config)
  756. self.config = config
  757. self.input_embeds_layer = nn.Embedding(self.config.vocab_size, self.config.hidden_size)
  758. self.position_embeds_layer = nn.Embedding(self.config.max_position_embeddings, self.config.hidden_size)
  759. self.drop = nn.Dropout(self.config.embd_pdrop)
  760. self.layers = nn.ModuleList(
  761. [ClvpDecoderLayer(self.config, layer_idx=i) for i in range(self.config.num_hidden_layers)]
  762. )
  763. self.layer_norm = nn.LayerNorm(self.config.hidden_size, eps=self.config.layer_norm_epsilon)
  764. self.gradient_checkpointing = False
  765. # Initialize weights and apply final processing
  766. self.post_init()
  767. def get_input_embeddings(self):
  768. return self.input_embeds_layer
  769. def set_input_embeddings(self, new_embeddings):
  770. self.input_embeds_layer = new_embeddings
  771. @merge_with_config_defaults
  772. @capture_outputs
  773. @auto_docstring
  774. def forward(
  775. self,
  776. input_ids: torch.LongTensor | None = None,
  777. attention_mask: torch.FloatTensor | None = None,
  778. token_type_ids: torch.LongTensor | None = None,
  779. position_ids: torch.LongTensor | None = None,
  780. past_key_values: Cache | None = None,
  781. inputs_embeds: torch.FloatTensor | None = None,
  782. use_cache: bool | None = None,
  783. **kwargs: Unpack[TransformersKwargs],
  784. ) -> BaseModelOutputWithPastAndCrossAttentions:
  785. if (input_ids is None) ^ (inputs_embeds is not None):
  786. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  787. if inputs_embeds is None:
  788. inputs_embeds = self.input_embeds_layer(input_ids)
  789. seq_len = inputs_embeds.shape[1]
  790. if token_type_ids is not None:
  791. token_type_ids = token_type_ids.view(-1, seq_len)
  792. if use_cache and past_key_values is None:
  793. past_key_values = DynamicCache(config=self.config)
  794. if position_ids is None:
  795. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  796. position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
  797. position_ids = position_ids.unsqueeze(0)
  798. position_embeds = self.position_embeds_layer(position_ids)
  799. inputs_embeds = inputs_embeds + position_embeds
  800. attention_mask = create_causal_mask(
  801. config=self.config,
  802. inputs_embeds=inputs_embeds,
  803. attention_mask=attention_mask,
  804. past_key_values=past_key_values,
  805. )
  806. hidden_states = inputs_embeds
  807. if token_type_ids is not None:
  808. token_type_embeds = self.input_embeds_layer(token_type_ids)
  809. hidden_states = hidden_states + token_type_embeds
  810. hidden_states = self.drop(hidden_states)
  811. output_shape = (
  812. -1,
  813. seq_len,
  814. ) + (hidden_states.size(-1),)
  815. for block in self.layers:
  816. hidden_states = block(
  817. hidden_states,
  818. past_key_values=past_key_values,
  819. attention_mask=attention_mask,
  820. position_ids=position_ids,
  821. use_cache=use_cache,
  822. **kwargs,
  823. )
  824. hidden_states = self.layer_norm(hidden_states)
  825. hidden_states = hidden_states.view(output_shape)
  826. return BaseModelOutputWithPastAndCrossAttentions(
  827. last_hidden_state=hidden_states,
  828. past_key_values=past_key_values,
  829. )
  830. @auto_docstring
  831. class ClvpModel(ClvpPreTrainedModel):
  832. config: ClvpDecoderConfig
  833. def __init__(self, config: ClvpDecoderConfig):
  834. super().__init__(config)
  835. self.config = config
  836. self.decoder = ClvpDecoder(self.config)
  837. # Initialize weights and apply final processing
  838. self.post_init()
  839. def get_input_embeddings(self):
  840. return self.decoder.input_embeds_layer
  841. def set_input_embeddings(self, value):
  842. self.decoder.input_embeds_layer = value
  843. @can_return_tuple
  844. @auto_docstring
  845. def forward(
  846. self,
  847. input_ids: torch.LongTensor | None = None,
  848. attention_mask: torch.FloatTensor | None = None,
  849. token_type_ids: torch.LongTensor | None = None,
  850. position_ids: torch.LongTensor | None = None,
  851. past_key_values: Cache | None = None,
  852. inputs_embeds: torch.FloatTensor | None = None,
  853. use_cache: bool | None = None,
  854. **kwargs: Unpack[TransformersKwargs],
  855. ) -> BaseModelOutputWithPastAndCrossAttentions:
  856. # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
  857. decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
  858. input_ids=input_ids,
  859. attention_mask=attention_mask,
  860. token_type_ids=token_type_ids,
  861. position_ids=position_ids,
  862. past_key_values=past_key_values,
  863. inputs_embeds=inputs_embeds,
  864. use_cache=use_cache,
  865. **kwargs,
  866. )
  867. return BaseModelOutputWithPastAndCrossAttentions(
  868. last_hidden_state=decoder_outputs.last_hidden_state,
  869. past_key_values=decoder_outputs.past_key_values,
  870. hidden_states=decoder_outputs.hidden_states,
  871. attentions=decoder_outputs.attentions,
  872. cross_attentions=decoder_outputs.cross_attentions,
  873. )
  874. @auto_docstring(
  875. custom_intro="""
  876. The CLVP decoder model with a language modelling head on top.
  877. """
  878. )
  879. class ClvpForCausalLM(ClvpPreTrainedModel, GenerationMixin):
  880. config: ClvpDecoderConfig
  881. def __init__(self, config):
  882. super().__init__(config)
  883. self.config = config
  884. self.model = ClvpModel(self.config)
  885. self.final_norm = nn.LayerNorm(self.config.hidden_size)
  886. self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=True)
  887. # Initialize weights and apply final processing
  888. self.post_init()
  889. def get_output_embeddings(self):
  890. return None
  891. def get_input_embeddings(self):
  892. return self.model.decoder.input_embeds_layer
  893. def set_input_embeddings(self, new_embeddings):
  894. self.model.decoder.input_embeds_layer = new_embeddings
  895. def _prepare_model_inputs(
  896. self,
  897. inputs: torch.Tensor | None,
  898. bos_token_id: int | None,
  899. model_kwargs: dict[str, torch.Tensor],
  900. ) -> tuple[torch.Tensor, str | None, dict[str, torch.Tensor]]:
  901. """
  902. This function extracts the model-specific `inputs` for generation.
  903. """
  904. input_name = self.main_input_name
  905. model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None}
  906. inputs_kwarg = model_kwargs.pop(input_name, None)
  907. if inputs_kwarg is not None and inputs is not None:
  908. raise ValueError(
  909. f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed."
  910. f"Make sure to either pass {inputs} or {input_name}=..."
  911. )
  912. elif inputs_kwarg is not None:
  913. inputs = inputs_kwarg
  914. if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
  915. model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
  916. inputs, bos_token_id, model_kwargs=model_kwargs
  917. )
  918. inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
  919. # Check if conditioning_embeds are provided or not, if yes then concatenate the bos_token_id at the end of the conditioning_embeds.
  920. # Then we must subtract the positional_ids because during the forward pass it will be added anyways, so we must cancel them out here.
  921. conditioning_embeds = model_kwargs.get("conditioning_embeds")
  922. if conditioning_embeds is not None:
  923. mel_start_token_embedding = self.model.decoder.input_embeds_layer(
  924. torch.full(
  925. (conditioning_embeds.shape[0], 1),
  926. fill_value=self.config.bos_token_id,
  927. device=conditioning_embeds.device,
  928. )
  929. )
  930. mel_start_token_embedding += self.model.decoder.position_embeds_layer(
  931. torch.full((conditioning_embeds.shape[0], 1), fill_value=0, device=conditioning_embeds.device)
  932. )
  933. conditioning_embeds = torch.concat([conditioning_embeds, mel_start_token_embedding], dim=1)
  934. # subtract the positional_ids here
  935. if hasattr(model_kwargs, "attention_mask"):
  936. position_ids = model_kwargs["attention_mask"].long().cumsum(-1) - 1
  937. else:
  938. position_ids = torch.arange(
  939. 0, conditioning_embeds.shape[1], dtype=torch.long, device=conditioning_embeds.device
  940. )
  941. position_ids = position_ids.unsqueeze(0).repeat(conditioning_embeds.shape[0], 1)
  942. model_kwargs["inputs_embeds"] = conditioning_embeds - self.model.decoder.position_embeds_layer(
  943. position_ids
  944. )
  945. model_kwargs["input_ids"] = (
  946. torch.ones((model_kwargs["inputs_embeds"].shape[0], 1), dtype=torch.long, device=self.device)
  947. * self.config.bos_token_id
  948. )
  949. return model_kwargs["inputs_embeds"], "inputs_embeds", model_kwargs
  950. inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
  951. return inputs, input_name, model_kwargs
  952. def prepare_inputs_for_generation(
  953. self,
  954. input_ids,
  955. past_key_values=None,
  956. inputs_embeds=None,
  957. conditioning_embeds=None,
  958. is_first_iteration=False,
  959. **kwargs,
  960. ):
  961. # Overwritten: has `conditioning_embeds`-related logic
  962. input_ids_length = input_ids.shape[-1]
  963. model_inputs = super().prepare_inputs_for_generation(
  964. input_ids,
  965. past_key_values=past_key_values,
  966. inputs_embeds=inputs_embeds,
  967. is_first_iteration=is_first_iteration,
  968. **kwargs,
  969. )
  970. if conditioning_embeds is not None and not is_first_iteration:
  971. model_inputs["position_ids"] = torch.tensor([input_ids_length], dtype=torch.long, device=input_ids.device)
  972. return model_inputs
  973. @can_return_tuple
  974. @auto_docstring
  975. def forward(
  976. self,
  977. input_ids: torch.LongTensor | None = None,
  978. past_key_values: Cache | None = None,
  979. attention_mask: torch.FloatTensor | None = None,
  980. token_type_ids: torch.LongTensor | None = None,
  981. position_ids: torch.LongTensor | None = None,
  982. inputs_embeds: torch.FloatTensor | None = None,
  983. labels: torch.LongTensor | None = None,
  984. use_cache: bool | None = None,
  985. **kwargs: Unpack[TransformersKwargs],
  986. ) -> tuple | CausalLMOutputWithCrossAttentions:
  987. r"""
  988. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  989. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  990. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  991. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  992. """
  993. outputs: BaseModelOutputWithPastAndCrossAttentions = self.model(
  994. input_ids=input_ids,
  995. past_key_values=past_key_values,
  996. attention_mask=attention_mask,
  997. token_type_ids=token_type_ids,
  998. position_ids=position_ids,
  999. inputs_embeds=inputs_embeds,
  1000. use_cache=use_cache,
  1001. **kwargs,
  1002. )
  1003. hidden_states = outputs.last_hidden_state
  1004. lm_logits = self.final_norm(hidden_states)
  1005. lm_logits = self.lm_head(lm_logits)
  1006. loss = None
  1007. if labels is not None:
  1008. labels = labels.to(lm_logits.device)
  1009. # Shift so that tokens < n predict n
  1010. shift_logits = lm_logits[..., :-1, :].contiguous()
  1011. shift_labels = labels[..., 1:].contiguous()
  1012. # Flatten the tokens
  1013. loss_fct = CrossEntropyLoss()
  1014. loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
  1015. return CausalLMOutputWithCrossAttentions(
  1016. loss=loss,
  1017. logits=lm_logits,
  1018. past_key_values=outputs.past_key_values,
  1019. hidden_states=outputs.hidden_states,
  1020. attentions=outputs.attentions,
  1021. cross_attentions=outputs.cross_attentions,
  1022. )
  1023. @auto_docstring(
  1024. custom_intro="""
  1025. The composite CLVP model with a text encoder, speech encoder and speech decoder model.
  1026. """
  1027. )
  1028. class ClvpModelForConditionalGeneration(ClvpPreTrainedModel, GenerationMixin):
  1029. def __init__(self, config: ClvpConfig):
  1030. super().__init__(config)
  1031. if not isinstance(config.text_config, ClvpEncoderConfig):
  1032. raise TypeError(
  1033. "config.text_config is expected to be of type `ClvpEncoderConfig` but is of type"
  1034. f" {type(config.text_config)}."
  1035. )
  1036. if not isinstance(config.speech_config, ClvpEncoderConfig):
  1037. raise TypeError(
  1038. "config.speech_config is expected to be of type `ClvpEncoderConfig` but is of type"
  1039. f" {type(config.speech_config)}."
  1040. )
  1041. if not isinstance(config.decoder_config, ClvpDecoderConfig):
  1042. raise TypeError(
  1043. "config.decoder_config is expected to be of type `ClvpDecoderConfig` but is of type"
  1044. f" {type(config.decoder_config)}."
  1045. )
  1046. self.conditioning_encoder = ClvpConditioningEncoder(config)
  1047. self.speech_decoder_model = ClvpForCausalLM(config.decoder_config)
  1048. self.text_encoder_model = ClvpEncoder(config.text_config)
  1049. self.speech_encoder_model = ClvpEncoder(config.speech_config)
  1050. self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
  1051. # Initialize weights and apply final processing
  1052. self.post_init()
  1053. # taken from the original repo,
  1054. # link : https://github.com/neonbjb/tortoise-tts/blob/4003544b6ff4b68c09856e04d3eff9da26d023c2/tortoise/api.py#L117
  1055. def fix_speech_decoder_output(self, speech_ids: torch.LongTensor) -> torch.LongTensor:
  1056. """
  1057. This method modifies the output of the decoder model, such as replacing the `eos_token_id` and changing the
  1058. last few tokens of each sequence.
  1059. Args:
  1060. speech_ids (`torch.LongTensor`):
  1061. This refers to the output of the decoder model.
  1062. """
  1063. decoder_fixing_codes = self.config.decoder_config.decoder_fixing_codes
  1064. speech_ids = speech_ids[:, 1:]
  1065. stop_token_indices = torch.where(speech_ids == self.speech_decoder_model.config.eos_token_id, 1, 0)
  1066. speech_ids = torch.masked_fill(speech_ids, mask=stop_token_indices.bool(), value=decoder_fixing_codes[0])
  1067. for i, each_seq_stop_token_index in enumerate(stop_token_indices):
  1068. # This means that no stop tokens were found so the sentence was still being generated, in that case we don't need
  1069. # to apply any padding so just skip to the next sequence of tokens.
  1070. if each_seq_stop_token_index.sum() == 0:
  1071. continue
  1072. stm = each_seq_stop_token_index.argmax()
  1073. speech_ids[i, stm:] = decoder_fixing_codes[0]
  1074. if stm - 3 < speech_ids.shape[1]:
  1075. speech_ids[i, -3:] = torch.tensor(
  1076. [decoder_fixing_codes[1:]], device=speech_ids.device, dtype=torch.long
  1077. )
  1078. return speech_ids
  1079. @can_return_tuple
  1080. @auto_docstring(
  1081. custom_intro="""
  1082. This method can be used to extract text_embeds from a text. The text embeddings obtained by applying the
  1083. projection layer to the pooled output of the CLVP text encoder model.
  1084. """
  1085. )
  1086. def get_text_features(
  1087. self,
  1088. input_ids: torch.LongTensor | None = None,
  1089. text_encoder_inputs_embeds: torch.FloatTensor | None = None,
  1090. attention_mask: torch.LongTensor | None = None,
  1091. **kwargs: Unpack[TransformersKwargs],
  1092. ) -> tuple | ClvpEncoderOutput:
  1093. r"""
  1094. text_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
  1095. inputs_embeds for the text encoder model passed in place of `input_ids`.
  1096. Examples:
  1097. ```python
  1098. >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration
  1099. >>> # Define the Text
  1100. >>> text = "This is an example text."
  1101. >>> # Define processor and model
  1102. >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
  1103. >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")
  1104. >>> # Generate processor output and text embeds
  1105. >>> processor_output = processor(text=text, return_tensors="pt")
  1106. >>> text_embeds = model.get_text_features(input_ids=processor_output["input_ids"])
  1107. ```
  1108. """
  1109. return self.text_encoder_model(
  1110. input_ids=input_ids,
  1111. inputs_embeds=text_encoder_inputs_embeds,
  1112. attention_mask=attention_mask,
  1113. **kwargs,
  1114. )
  1115. def get_speech_features(
  1116. self,
  1117. speech_ids: torch.LongTensor | None = None,
  1118. input_ids: torch.LongTensor | None = None,
  1119. input_features: torch.FloatTensor | None = None,
  1120. conditioning_encoder_inputs_embeds: torch.FloatTensor | None = None,
  1121. attention_mask: torch.Tensor | None = None,
  1122. generation_config: GenerationConfig | None = None,
  1123. **kwargs,
  1124. ) -> torch.FloatTensor:
  1125. r"""
  1126. This method can be used to extract speech_embeds. The speech embeddings are obtained by applying the speech
  1127. model on speech_ids. If speech_ids is not present but both input_ids and input_features are given then the
  1128. decoder model will be used to first generate the speech_ids and then applying the speech model.
  1129. Args:
  1130. speech_ids (`torch.LongTensor` of shape `(batch_size, num_speech_ids)`, *optional*):
  1131. Speech Tokens. Padding will be ignored by default should you provide it. If speech_ids are provided
  1132. then input_ids and input_features will be automatically ignored.
  1133. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1134. Input text Tokens. Processed from the [`ClvpTokenizer`]. If speech_ids is not provided, then input_ids
  1135. and input_features will be used.
  1136. conditioning_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
  1137. inputs_embeds for `ClvpConditioningEncoder`. Can be used in place of `input_ids`.
  1138. attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1139. Mask to avoid performing attention on padding speech token indices. Mask values selected in `[0, 1]`:
  1140. - 1 for tokens that are **not masked**,
  1141. - 0 for tokens that are **masked**.
  1142. [What are attention masks?](../glossary#attention-mask)
  1143. generation_config (`GenerationConfig`, *optional*):
  1144. generation config to control the generation of speech_ids if they are not provided.
  1145. Returns:
  1146. `torch.FloatTensor` of shape `(batch_size, output_dim)`:
  1147. The speech embeddings obtained by applying the projection layer to the pooled output of the CLVP Speech
  1148. Model.
  1149. Examples:
  1150. ```python
  1151. >>> import datasets
  1152. >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration
  1153. >>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library)
  1154. >>> text = "This is an example text."
  1155. >>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  1156. >>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050))
  1157. >>> audio = ds.sort("id")["audio"][0]
  1158. >>> audio_sample, sr = audio["array"], audio["sampling_rate"]
  1159. >>> # Define processor and model
  1160. >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
  1161. >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")
  1162. >>> # Generate processor output and model output
  1163. >>> processor_output = processor(raw_speech=audio_sample, sampling_rate=sr, text=text, return_tensors="pt")
  1164. >>> speech_embeds = model.get_speech_features(
  1165. ... input_ids=processor_output["input_ids"], input_features=processor_output["input_features"]
  1166. ... )
  1167. ```
  1168. """
  1169. if speech_ids is None:
  1170. if (input_ids is None and conditioning_encoder_inputs_embeds is None) or input_features is None:
  1171. raise ValueError(
  1172. "Either speech_ids or input_ids/conditioning_encoder_inputs_embeds and input_features must be provided."
  1173. )
  1174. if generation_config is None:
  1175. generation_config = self.generation_config
  1176. generation_config.update(**kwargs)
  1177. conditioning_embeds = self.conditioning_encoder(
  1178. input_features=input_features,
  1179. input_ids=input_ids,
  1180. inputs_embeds=conditioning_encoder_inputs_embeds,
  1181. attention_mask=attention_mask,
  1182. )
  1183. speech_ids = self.speech_decoder_model.generate(
  1184. conditioning_embeds=conditioning_embeds,
  1185. generation_config=generation_config,
  1186. )
  1187. speech_ids = self.fix_speech_decoder_output(speech_ids[0])
  1188. outputs = self.speech_encoder_model(
  1189. input_ids=speech_ids,
  1190. attention_mask=attention_mask,
  1191. )
  1192. return outputs[0]
  1193. @can_return_tuple
  1194. @auto_docstring
  1195. def forward(
  1196. self,
  1197. input_ids: torch.LongTensor | None = None,
  1198. input_features: torch.FloatTensor | None = None,
  1199. conditioning_encoder_inputs_embeds: torch.FloatTensor | None = None,
  1200. text_encoder_inputs_embeds: torch.FloatTensor | None = None,
  1201. attention_mask: torch.LongTensor | None = None,
  1202. return_loss: bool | None = None,
  1203. **kwargs: Unpack[TransformersKwargs],
  1204. ) -> tuple | ClvpOutput:
  1205. r"""
  1206. conditioning_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
  1207. inputs_embeds for `ClvpConditioningEncoder`. Can be used in place of `input_ids`.
  1208. text_encoder_inputs_embeds (`torch.FloatTensor`, *optional*):
  1209. inputs_embeds for the text encoder model passed in place of `input_ids`.
  1210. return_loss (`bool`, *optional*):
  1211. Whether or not to return the contrastive loss.
  1212. Examples:
  1213. ```python
  1214. >>> import datasets
  1215. >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration
  1216. >>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library)
  1217. >>> text = "This is an example text."
  1218. >>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  1219. >>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050))
  1220. >>> audio = ds.sort("id")["audio"][0]
  1221. >>> audio_sample, sr = audio["array"], audio["sampling_rate"]
  1222. >>> # Define processor and model
  1223. >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev")
  1224. >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev")
  1225. >>> # processor outputs and model outputs
  1226. >>> processor_output = processor(raw_speech=audio_sample, sampling_rate=sr, text=text, return_tensors="pt")
  1227. >>> outputs = model(
  1228. ... input_ids=processor_output["input_ids"],
  1229. ... input_features=processor_output["input_features"],
  1230. ... return_dict=True,
  1231. ... )
  1232. ```
  1233. """
  1234. conditioning_embeds = self.conditioning_encoder(
  1235. input_features=input_features,
  1236. input_ids=input_ids,
  1237. inputs_embeds=conditioning_encoder_inputs_embeds,
  1238. attention_mask=attention_mask,
  1239. )
  1240. decoder_outputs: CausalLMOutputWithCrossAttentions = self.speech_decoder_model(
  1241. inputs_embeds=conditioning_embeds,
  1242. **kwargs,
  1243. )
  1244. speech_ids = decoder_outputs.logits
  1245. # since we will get the embeds of shape `(batch_size, seq_len, embedding_dim)` during the forward pass
  1246. # we must convert it to tokens, to make it compaitable with speech_transformer
  1247. if speech_ids.ndim == 3:
  1248. speech_ids = speech_ids.argmax(2)
  1249. speech_ids = self.fix_speech_decoder_output(speech_ids)
  1250. speech_outputs: ClvpEncoderOutput = self.speech_encoder_model(
  1251. input_ids=speech_ids,
  1252. **kwargs,
  1253. )
  1254. text_outputs: ClvpEncoderOutput = self.text_encoder_model(
  1255. input_ids=input_ids,
  1256. inputs_embeds=text_encoder_inputs_embeds,
  1257. attention_mask=attention_mask,
  1258. **kwargs,
  1259. )
  1260. speech_embeds = speech_outputs.embeds
  1261. text_embeds = text_outputs.embeds
  1262. # normalized features
  1263. speech_embeds = speech_embeds / speech_embeds.norm(p=2, dim=-1, keepdim=True)
  1264. text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
  1265. # cosine similarity as logits
  1266. logit_scale = self.logit_scale.exp()
  1267. logits_per_text = torch.matmul(text_embeds, speech_embeds.t()) * logit_scale
  1268. logits_per_speech = logits_per_text.t()
  1269. loss = None
  1270. if return_loss:
  1271. loss = clvp_loss(logits_per_text)
  1272. return ClvpOutput(
  1273. loss=loss,
  1274. logits_per_speech=logits_per_speech,
  1275. logits_per_text=logits_per_text,
  1276. text_embeds=text_embeds,
  1277. speech_embeds=speech_embeds,
  1278. text_model_output=text_outputs.pooler_output,
  1279. speech_model_output=speech_outputs.pooler_output,
  1280. decoder_hidden_states=decoder_outputs.hidden_states,
  1281. text_encoder_hidden_states=text_outputs.hidden_states,
  1282. speech_encoder_hidden_states=speech_outputs.hidden_states,
  1283. )
  1284. @torch.no_grad()
  1285. def generate(
  1286. self,
  1287. input_ids: torch.LongTensor | None = None,
  1288. input_features: torch.FloatTensor | None = None,
  1289. attention_mask: torch.LongTensor | None = None,
  1290. generation_config: GenerationConfig | None = None,
  1291. pad_to_max_mel_tokens: int | None = None,
  1292. output_hidden_states: bool | None = None,
  1293. **kwargs,
  1294. ):
  1295. """
  1296. Generate method for `ClvpModelForConditionalGeneration`, this method calls the `generate` method of
  1297. `ClvpForCausalLM` and then uses those generated `speech_ids` to process `text_embeds` and `speech_embeds` using
  1298. `ClvpEncoder`.
  1299. Args:
  1300. input_ids (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1301. Input text Tokens. Processed from the [`ClvpTokenizer`].
  1302. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  1303. Mask to avoid performing attention on padding text token indices. Mask values selected in `[0, 1]`:
  1304. - 1 for tokens that are **not masked**,
  1305. - 0 for tokens that are **masked**.
  1306. [What are attention masks?](../glossary#attention-mask)
  1307. generation_config (`~generation.GenerationConfig`, *optional*):
  1308. The generation configuration to be used as base parametrization for the generation call. `**kwargs`
  1309. passed to generate matching the attributes of `generation_config` will override them. If
  1310. `generation_config` is not provided, the default will be used, which had the following loading
  1311. priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
  1312. configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
  1313. default values, whose documentation should be checked to parameterize generation.
  1314. pad_to_max_mel_tokens (`int`, *optional*):
  1315. Pads generated speech_ids to the specified value. This is to implement the same logic from the official
  1316. repo, link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L430
  1317. and to make sure the logits are same.
  1318. This does not affect generation quality so please don't consider using it since it is less efficient.
  1319. output_hidden_states (`bool`, *optional*):
  1320. Whether or not to return the hidden states of decoder model, text encoder and speech encoder models.
  1321. Returns:
  1322. `ClvpOutput` or tuple: A `ClvpOutput` (if `return_dict_in_generate=True` or when
  1323. `config.return_dict_in_generate=True`) or a tuple.
  1324. """
  1325. # If the input sequences are larger than (self.config.decoder_config.max_text_tokens - 3) then raise error,
  1326. # because we need to add 3 tokens ( 1 bos tokens and 2 eos tokens) to the input_ids in ClvpConditioningEncoder to
  1327. # properly sample
  1328. sequence_length = input_ids.shape[-1]
  1329. if sequence_length > (self.config.decoder_config.max_text_tokens - 3):
  1330. raise ValueError(
  1331. f"Maximum sequence length reached! Found input_ids of length {sequence_length}."
  1332. f"Please make sure that the maximum length of input_ids is {self.config.decoder_config.max_text_tokens - 3}"
  1333. )
  1334. if generation_config is None:
  1335. generation_config = self.generation_config
  1336. generation_config = copy.deepcopy(generation_config)
  1337. model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
  1338. generation_config.validate()
  1339. self._validate_model_kwargs(model_kwargs.copy())
  1340. # pad input_ids as specified in the original repo
  1341. # link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L380
  1342. input_ids, attention_mask = _pad_extra_bos_eos_tokens(
  1343. input_ids,
  1344. attention_mask,
  1345. add_bos_token=False,
  1346. bos_token_id=self.config.text_config.bos_token_id,
  1347. eos_token_id=self.config.text_config.eos_token_id,
  1348. )
  1349. conditioning_embeds = self.conditioning_encoder(
  1350. input_features=input_features,
  1351. input_ids=input_ids,
  1352. attention_mask=attention_mask,
  1353. )
  1354. decoder_outputs = self.speech_decoder_model.generate(
  1355. conditioning_embeds=conditioning_embeds,
  1356. generation_config=generation_config,
  1357. output_hidden_states=output_hidden_states,
  1358. )
  1359. if isinstance(decoder_outputs, ModelOutput):
  1360. speech_ids = decoder_outputs.sequences
  1361. # pad to pad_to_max_mel_tokens if given, to replicate the original repo logic
  1362. # link: https://github.com/neonbjb/tortoise-tts/blob/80f89987a5abda5e2b082618cd74f9c7411141dc/tortoise/api.py#L430
  1363. if pad_to_max_mel_tokens is not None:
  1364. padding_needed = pad_to_max_mel_tokens - speech_ids.shape[-1]
  1365. speech_ids = torch.nn.functional.pad(
  1366. speech_ids, (0, padding_needed), value=self.generation_config.eos_token_id
  1367. )
  1368. speech_ids = self.fix_speech_decoder_output(speech_ids)
  1369. speech_outputs: ClvpEncoderOutput = self.speech_encoder_model(
  1370. input_ids=speech_ids,
  1371. output_hidden_states=output_hidden_states,
  1372. return_dict=generation_config.return_dict_in_generate,
  1373. )
  1374. text_outputs: ClvpEncoderOutput = self.text_encoder_model(
  1375. input_ids=input_ids,
  1376. attention_mask=attention_mask,
  1377. output_hidden_states=output_hidden_states,
  1378. return_dict=generation_config.return_dict_in_generate,
  1379. )
  1380. speech_embeds = speech_outputs.embeds
  1381. text_embeds = text_outputs.embeds
  1382. # normalized features
  1383. speech_embeds = speech_embeds / speech_embeds.norm(p=2, dim=-1, keepdim=True)
  1384. text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
  1385. # cosine similarity as logits
  1386. logit_scale = self.logit_scale.exp()
  1387. logits_per_text = torch.matmul(text_embeds, speech_embeds.t()) * logit_scale
  1388. logits_per_speech = logits_per_text.t()
  1389. if not generation_config.return_dict_in_generate:
  1390. output = (
  1391. speech_ids,
  1392. logits_per_speech,
  1393. logits_per_text,
  1394. text_embeds,
  1395. speech_embeds,
  1396. text_outputs.pooler_output,
  1397. speech_outputs.pooler_output,
  1398. )
  1399. if output_hidden_states:
  1400. output += (
  1401. decoder_outputs[-1],
  1402. text_outputs.hidden_states,
  1403. speech_outputs.hidden_states,
  1404. )
  1405. return output
  1406. return ClvpOutput(
  1407. speech_ids=speech_ids,
  1408. logits_per_speech=logits_per_speech,
  1409. logits_per_text=logits_per_text,
  1410. text_embeds=text_embeds,
  1411. speech_embeds=speech_embeds,
  1412. text_model_output=text_outputs.pooler_output,
  1413. speech_model_output=speech_outputs.pooler_output,
  1414. decoder_hidden_states=decoder_outputs.hidden_states,
  1415. text_encoder_hidden_states=text_outputs.hidden_states,
  1416. speech_encoder_hidden_states=speech_outputs.hidden_states,
  1417. )
  1418. __all__ = [
  1419. "ClvpModelForConditionalGeneration",
  1420. "ClvpForCausalLM",
  1421. "ClvpModel",
  1422. "ClvpPreTrainedModel",
  1423. "ClvpEncoder",
  1424. "ClvpDecoder",
  1425. ]