Python
added heartmula support
DeepBeepMeep4fa45811821d
diff --git a/defaults/heartmula_oss_3b.json b/defaults/heartmula_oss_3b.jsonnew file mode 100644index 0000000..1b2d4bf--- /dev/null+++ b/defaults/heartmula_oss_3b.json@@ -0,0 +1,19 @@+{+ "model": {+ "name": "TTS HeartMuLa OSS 3B",+ "architecture": "heartmula_oss_3b",+ "description": "HeartMuLa open music generation conditioned on lyrics and tags.",+ "URLs": [+ "heartmula_oss_3b_bf16.safetensors",+ "heartmula_oss_3b_quanto_bf16_int8.safetensors"+ ]+ },+ "prompt": "[Verse]\nMorning light through the window pane\nI hum a tune to chase the rain\nSteady steps on a quiet street\nHeart and rhythm, gentle beat",+ "alt_prompt": "piano,happy,wedding",+ "negative_prompt": "",+ "audio_prompt_type": "",+ "repeat_generation": 1,+ "video_length": 0,+ "num_inference_steps": 0,+ "temperature": 1.0+}diff --git a/docs/FINETUNES.md b/docs/FINETUNES.mdindex a48960e..4a1bd86 100644--- a/docs/FINETUNES.md+++ b/docs/FINETUNES.md@@ -71,8 +71,10 @@ be able to reduce the number of generation steps to 10- *auto_quantize*: if set to True and no quantized model URL is provided, WanGP will perform on the fly quantization if the user expects a quantized model- *visible* : by default assumed to be true. If set to false the model will no longer be visible. This can be useful if you create a finetune to override a default model and hide it.- *image_outputs* : turn any model that generates a video into a model that generates images. In fact it will adapt the user interface for image generation and ask the model to generate a video with a single frame.+- *text_prompt_enhancer_instructions* : this allows you override the system prompt used by the Prompt Enhancer if only a Prompt about a text is requested- *video_prompt_enhancer_instructions* : this allows you override the system prompt used by the Prompt Enhancer when generating a Video with this finetune- *image_prompt_enhancer_instructions* : this allows you override the system prompt used by the Prompt Enhancer when generating an Image with this finetune+- *text_prompt_enhancer_max_tokens*: override for the maximum number of tokens generated by the prompt enhancer if only a Prompt about a text is requested (default 256)- *video_prompt_enhancer_max_tokens*: override for the maximum number of tokens generated by the prompt enhancer when generating a Video (default 256)- *image_prompt_enhancer_max_tokens*: override for the maximum number of tokens generated by the prompt enhancer when generating an Image (default 256)diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.mdindex 0208936..38b2264 100644--- a/docs/INSTALLATION.md+++ b/docs/INSTALLATION.md@@ -318,7 +318,7 @@ These kernels will offer optimized INT4 / FP4 dequantization.**Please Note FP4 support is hardware dependent and will work only with RTX 50xx / sm120+ GPUs**-### Light2xv NVP4 Kernels Wheels for Windows / Python 3.10 / Pytorch 2.9.1 / Cuda 13.8 (RTX 50xx / sm120+ only !)+### Light2xv NVP4 Kernels Wheels for Windows / Python 3.10 / Pytorch 2.9.1 / Cuda 12.8 (RTX 50xx / sm120+ only !)- Windows```pip install https://github.com/deepbeepmeep/kernels/releases/download/Light2xv/lightx2v_kernel-0.0.1+torch2.9.1-cp39-abi3-win_amd64.whldiff --git a/models/TTS/HeartMula/__init__.py b/models/TTS/HeartMula/__init__.pynew file mode 100644index 0000000..3fa467f--- /dev/null+++ b/models/TTS/HeartMula/__init__.py@@ -0,0 +1 @@+from .pipeline import HeartMuLaPipelinediff --git a/models/TTS/HeartMula/config/heartmula_3B.json b/models/TTS/HeartMula/config/heartmula_3B.jsonnew file mode 100644index 0000000..efefba5--- /dev/null+++ b/models/TTS/HeartMula/config/heartmula_3B.json@@ -0,0 +1,14 @@+{+ "architectures": [+ "HeartMuLa"+ ],+ "audio_num_codebooks": 8,+ "audio_vocab_size": 8197,+ "backbone_flavor": "llama-3B",+ "decoder_flavor": "llama-300M",+ "model_type": "heartmula",+ "muq_dim": 512,+ "text_vocab_size": 128256,+ "torch_dtype": "float32",+ "transformers_version": "4.45.1"+}diff --git a/models/TTS/HeartMula/heartcodec/__init__.py b/models/TTS/HeartMula/heartcodec/__init__.pynew file mode 100644index 0000000..8633c43--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/__init__.py@@ -0,0 +1,4 @@+from .configuration_heartcodec import HeartCodecConfig+from .modeling_heartcodec import HeartCodec++__all__ = ["HeartCodec", "HeartCodecConfig"]diff --git a/models/TTS/HeartMula/heartcodec/configuration_heartcodec.py b/models/TTS/HeartMula/heartcodec/configuration_heartcodec.pynew file mode 100644index 0000000..c66542c--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/configuration_heartcodec.py@@ -0,0 +1,71 @@+from typing import List++from transformers.configuration_utils import PretrainedConfig+++class HeartCodecConfig(PretrainedConfig):+ model_type = "heartcodec"++ def __init__(+ self,+ dim: int = 512,+ codebook_size: int = 8192,+ decay: float = 0.9,+ commitment_weight: float = 1.0,+ threshold_ema_dead_code: int = 2,+ use_cosine_sim: bool = False,+ codebook_dim: int = 32,+ num_quantizers: int = 8,+ attention_head_dim: int = 64,+ in_channels: int = 1024,+ norm_type: str = "ada_norm_single",+ num_attention_heads: int = 24,+ num_layers: int = 24,+ num_layers_2: int = 6,+ out_channels: int = 256,+ num_bands: int = 1,+ sample_rate: int = 48000,+ causal: bool = True,+ num_samples: int = 2,+ downsample_factors: List[int] = [3, 4, 4, 4, 5],+ downsample_kernel_sizes: List[int] = [6, 8, 8, 8, 10],+ upsample_factors: List[int] = [5, 4, 4, 4, 3],+ upsample_kernel_sizes: List[int] = [10, 8, 8, 8, 6],+ latent_hidden_dim: int = 128,+ default_kernel_size: int = 7,+ delay_kernel_size: int = 5,+ init_channel: int = 64,+ res_kernel_size: int = 7,+ **kwargs,+ ):+ super().__init__(**kwargs)+ self.dim = dim+ self.codebook_size = codebook_size+ self.decay = decay+ self.commitment_weight = commitment_weight+ self.threshold_ema_dead_code = threshold_ema_dead_code+ self.use_cosine_sim = use_cosine_sim+ self.codebook_dim = codebook_dim+ self.num_quantizers = num_quantizers++ self.attention_head_dim = attention_head_dim+ self.in_channels = in_channels+ self.norm_type = norm_type+ self.num_attention_heads = num_attention_heads+ self.num_layers = num_layers+ self.num_layers_2 = num_layers_2+ self.out_channels = out_channels++ self.num_bands = num_bands+ self.sample_rate = sample_rate+ self.causal = causal+ self.num_samples = num_samples+ self.downsample_factors = downsample_factors+ self.downsample_kernel_sizes = downsample_kernel_sizes+ self.upsample_factors = upsample_factors+ self.upsample_kernel_sizes = upsample_kernel_sizes+ self.latent_hidden_dim = latent_hidden_dim+ self.default_kernel_size = default_kernel_size+ self.delay_kernel_size = delay_kernel_size+ self.init_channel = init_channel+ self.res_kernel_size = res_kernel_sizediff --git a/models/TTS/HeartMula/heartcodec/modeling_heartcodec.py b/models/TTS/HeartMula/heartcodec/modeling_heartcodec.pynew file mode 100644index 0000000..2c38f23--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/modeling_heartcodec.py@@ -0,0 +1,195 @@+import math++import numpy as np+import torch+from transformers.modeling_utils import PreTrainedModel++from .configuration_heartcodec import HeartCodecConfig+from .models.flow_matching import FlowMatching+from .models.sq_codec import ScalarModel+++class HeartCodec(PreTrainedModel):+ config_class = HeartCodecConfig++ def __init__(self, config: HeartCodecConfig):+ super().__init__(config)++ self.config = config++ self.flow_matching = FlowMatching(+ dim=config.dim,+ codebook_size=config.codebook_size,+ decay=config.decay,+ commitment_weight=config.commitment_weight,+ threshold_ema_dead_code=config.threshold_ema_dead_code,+ use_cosine_sim=config.use_cosine_sim,+ codebook_dim=config.codebook_dim,+ num_quantizers=config.num_quantizers,+ attention_head_dim=config.attention_head_dim,+ in_channels=config.in_channels,+ norm_type=config.norm_type,+ num_attention_heads=config.num_attention_heads,+ num_layers=config.num_layers,+ num_layers_2=config.num_layers_2,+ out_channels=config.out_channels,+ )+ self.scalar_model = ScalarModel(+ num_bands=config.num_bands,+ sample_rate=config.sample_rate,+ causal=config.causal,+ num_samples=config.num_samples,+ downsample_factors=config.downsample_factors,+ downsample_kernel_sizes=config.downsample_kernel_sizes,+ upsample_factors=config.upsample_factors,+ upsample_kernel_sizes=config.upsample_kernel_sizes,+ latent_hidden_dim=config.latent_hidden_dim,+ default_kernel_size=config.default_kernel_size,+ delay_kernel_size=config.delay_kernel_size,+ init_channel=config.init_channel,+ res_kernel_size=config.res_kernel_size,+ )+ self.post_init()++ self.sample_rate = config.sample_rate++ @torch.inference_mode()+ def detokenize(+ self,+ codes,+ duration=29.76,+ num_steps=10,+ disable_progress=False,+ guidance_scale=1.25,+ abort_signal=None,+ ):+ if abort_signal and abort_signal():+ return None+ mm_manager = getattr(self, "_mm_manager", None)+ mm_id = getattr(self, "_mm_id", None)+ if mm_manager is None or mm_id is None:+ mm_manager = getattr(self.flow_matching, "_mm_manager", None)+ mm_id = getattr(self.flow_matching, "_mm_id", None)+ if mm_manager is not None and mm_id is not None:+ mm_manager.ensure_model_loaded(mm_id)+ codes = codes.unsqueeze(0).to(self.device)+ first_latent = torch.randn(+ codes.shape[0], int(duration * 25), 256, dtype=self.dtype+ ).to(self.device)+ first_latent_length = 0+ first_latent_codes_length = 0+ min_samples = int(duration * 12.5)+ hop_samples = min_samples // 93 * 80+ ovlp_samples = min_samples - hop_samples+ ovlp_frames = ovlp_samples * 2+ codes_len = codes.shape[-1]+ target_len = int(+ (codes_len - first_latent_codes_length) / 12.5 * self.sample_rate+ )++ if codes_len < min_samples:+ while codes.shape[-1] < min_samples:+ codes = torch.cat([codes, codes], -1)+ codes = codes[:, :, 0:min_samples]+ codes_len = codes.shape[-1]+ if (codes_len - ovlp_frames) % hop_samples > 0:+ len_codes = (+ math.ceil((codes_len - ovlp_samples) / float(hop_samples)) * hop_samples+ + ovlp_samples+ )+ while codes.shape[-1] < len_codes:+ codes = torch.cat([codes, codes], -1)+ codes = codes[:, :, 0:len_codes]+ latent_length = int(duration * 25)+ latent_list = []++ for sinx in range(0, codes.shape[-1] - hop_samples + 1, hop_samples):+ if abort_signal and abort_signal():+ return None+ codes_input = [codes[:, :, sinx : sinx + min_samples]]+ if sinx == 0 or ovlp_frames == 0:+ incontext_length = first_latent_length+ latents = self.flow_matching.inference_codes(+ codes_input,+ first_latent,+ latent_length,+ incontext_length,+ guidance_scale=guidance_scale,+ num_steps=num_steps,+ disable_progress=disable_progress,+ scenario="other_seg",+ abort_signal=abort_signal,+ )+ if latents is None:+ return None+ latent_list.append(latents)+ else:+ true_latent = latent_list[-1][:, -ovlp_frames:, :]+ len_add_to_latent = latent_length - true_latent.shape[1]+ incontext_length = true_latent.shape[1]+ true_latent = torch.cat(+ [+ true_latent,+ torch.randn(+ true_latent.shape[0],+ len_add_to_latent,+ true_latent.shape[-1],+ dtype=true_latent.dtype,+ device=true_latent.device,+ ),+ ],+ 1,+ )+ latents = self.flow_matching.inference_codes(+ codes_input,+ true_latent,+ latent_length,+ incontext_length,+ guidance_scale=guidance_scale,+ num_steps=num_steps,+ disable_progress=disable_progress,+ scenario="other_seg",+ abort_signal=abort_signal,+ )+ if latents is None:+ return None+ latent_list.append(latents)++ latent_list[0] = latent_list[0][:, first_latent_length:, :]+ min_samples = int(duration * self.sample_rate)+ hop_samples = min_samples // 93 * 80+ ovlp_samples = min_samples - hop_samples++ output = None+ for latent in latent_list:+ if abort_signal and abort_signal():+ return None+ latent = latent.reshape(+ latent.shape[0], latent.shape[1], 2, latent.shape[2] // 2+ ).permute(0, 2, 1, 3)+ latent = latent.reshape(+ latent.shape[0] * 2, latent.shape[2], latent.shape[3]+ )+ cur_output = (+ self.scalar_model.decode(latent.transpose(1, 2)).squeeze(0).squeeze(1)+ )++ cur_output = cur_output[:, 0:min_samples].detach().cpu()+ if cur_output.dim() == 3:+ cur_output = cur_output[0]++ if output is None:+ output = cur_output+ else:+ if ovlp_samples == 0:+ output = torch.cat([output, cur_output], -1)+ else:+ ov_win = torch.from_numpy(np.linspace(0, 1, ovlp_samples)[None, :])+ ov_win = torch.cat([ov_win, 1 - ov_win], -1)+ output[:, -ovlp_samples:] = (+ output[:, -ovlp_samples:] * ov_win[:, -ovlp_samples:]+ + cur_output[:, 0:ovlp_samples] * ov_win[:, 0:ovlp_samples]+ )+ output = torch.cat([output, cur_output[:, ovlp_samples:]], -1)+ output = output[:, 0:target_len]+ return outputdiff --git a/models/TTS/HeartMula/heartcodec/models/__init__.py b/models/TTS/HeartMula/heartcodec/models/__init__.pynew file mode 100644index 0000000..0e10082--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/models/__init__.py@@ -0,0 +1,5 @@+from .flow_matching import FlowMatching+from .sq_codec import ScalarModel+from .transformer import LlamaTransformer++__all__ = ["FlowMatching", "ScalarModel", "LlamaTransformer"]diff --git a/models/TTS/HeartMula/heartcodec/models/flow_matching.py b/models/TTS/HeartMula/heartcodec/models/flow_matching.pynew file mode 100644index 0000000..e2b9d95--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/models/flow_matching.py@@ -0,0 +1,218 @@+import torch+import torch.nn as nn+import torch.nn.functional as F+from tqdm import tqdm+from vector_quantize_pytorch import ResidualVQ++from .transformer import LlamaTransformer+++class FlowMatching(nn.Module):+ def __init__(+ self,+ dim: int = 512,+ codebook_size: int = 8192,+ decay: float = 0.9,+ commitment_weight: float = 1.0,+ threshold_ema_dead_code: int = 2,+ use_cosine_sim: bool = False,+ codebook_dim: int = 32,+ num_quantizers: int = 8,+ attention_head_dim: int = 64,+ in_channels: int = 1024,+ norm_type: str = "ada_norm_single",+ num_attention_heads: int = 24,+ num_layers: int = 24,+ num_layers_2: int = 6,+ out_channels: int = 256,+ ):+ super().__init__()++ self.vq_embed = ResidualVQ(+ dim=dim,+ codebook_size=codebook_size,+ decay=decay,+ commitment_weight=commitment_weight,+ threshold_ema_dead_code=threshold_ema_dead_code,+ use_cosine_sim=use_cosine_sim,+ codebook_dim=codebook_dim,+ num_quantizers=num_quantizers,+ )+ self.cond_feature_emb = nn.Linear(dim, dim)+ self.zero_cond_embedding1 = nn.Parameter(torch.randn(dim))+ self.estimator = LlamaTransformer(+ attention_head_dim=attention_head_dim,+ in_channels=in_channels,+ norm_type=norm_type,+ num_attention_heads=num_attention_heads,+ num_layers=num_layers,+ num_layers_2=num_layers_2,+ out_channels=out_channels,+ )++ self.latent_dim = out_channels++ @torch.no_grad()+ def inference_codes(+ self,+ codes,+ true_latents,+ latent_length,+ incontext_length,+ guidance_scale=2.0,+ num_steps=20,+ disable_progress=False,+ scenario="start_seg",+ abort_signal=None,+ ):+ if abort_signal and abort_signal():+ return None+ mm_manager = getattr(self, "_mm_manager", None)+ mm_id = getattr(self, "_mm_id", None)+ if mm_manager is None or mm_id is None:+ mm_manager = getattr(self.vq_embed, "_mm_manager", None)+ mm_id = getattr(self.vq_embed, "_mm_id", None)+ if mm_manager is None or mm_id is None:+ mm_manager = getattr(self.estimator, "_mm_manager", None)+ mm_id = getattr(self.estimator, "_mm_id", None)+ if mm_manager is not None and mm_id is not None:+ mm_manager.ensure_model_loaded(mm_id)+ codes_bestrq_emb = codes[0]++ batch_size = codes_bestrq_emb.shape[0]+ self.vq_embed.eval()+ vq_param = next(self.vq_embed.parameters(), None)+ vq_device = vq_param.device if vq_param is not None else codes_bestrq_emb.device+ if codes_bestrq_emb.device != vq_device:+ codes_bestrq_emb = codes_bestrq_emb.to(vq_device)+ codes = self.vq_embed.get_codes_from_indices(codes_bestrq_emb.transpose(1, 2))+ codes_summed = codes.sum(dim=0)+ project_out = self.vq_embed.project_out+ proj_manager = getattr(project_out, "_mm_manager", None)+ proj_id = getattr(project_out, "_mm_id", None)+ if proj_manager is not None and proj_id is not None:+ proj_manager.ensure_model_loaded(proj_id)+ proj_weight = getattr(project_out, "weight", None)+ if proj_weight is not None:+ if (+ codes_summed.device != proj_weight.device+ or codes_summed.dtype != proj_weight.dtype+ ):+ codes_summed = codes_summed.to(+ device=proj_weight.device, dtype=proj_weight.dtype+ )+ quantized_feature_emb = project_out(codes_summed)+ cond_param = next(self.cond_feature_emb.parameters(), None)+ cond_device = (+ cond_param.device if cond_param is not None else quantized_feature_emb.device+ )+ if quantized_feature_emb.device != cond_device:+ quantized_feature_emb = quantized_feature_emb.to(cond_device)+ quantized_feature_emb = self.cond_feature_emb(quantized_feature_emb)+ quantized_feature_emb = F.interpolate(+ quantized_feature_emb.permute(0, 2, 1), scale_factor=2, mode="nearest"+ ).permute(0, 2, 1)++ device = quantized_feature_emb.device+ if true_latents.device != device:+ true_latents = true_latents.to(device)+ dtype = true_latents.dtype+ num_frames = quantized_feature_emb.shape[1]+ latents = torch.randn(+ (batch_size, num_frames, self.latent_dim), device=device, dtype=dtype+ )+ latent_masks = torch.zeros(+ latents.shape[0], latents.shape[1], dtype=torch.int64, device=latents.device+ )+ latent_masks[:, 0:latent_length] = 2+ if scenario == "other_seg":+ latent_masks[:, 0:incontext_length] = 1++ zero_cond = self.zero_cond_embedding1.to(device)+ quantized_feature_emb = (latent_masks > 0.5).unsqueeze(+ -1+ ) * quantized_feature_emb + (latent_masks < 0.5).unsqueeze(+ -1+ ) * zero_cond.unsqueeze(+ 0+ )++ incontext_latents = (+ true_latents+ * ((latent_masks > 0.5) * (latent_masks < 1.5)).unsqueeze(-1).float()+ )+ incontext_length = ((latent_masks > 0.5) * (latent_masks < 1.5)).sum(-1)[0]++ additional_model_input = torch.cat([quantized_feature_emb], 1)+ temperature = 1.0+ t_span = torch.linspace(+ 0, 1, num_steps + 1, device=quantized_feature_emb.device+ )+ latents = self.solve_euler(+ latents * temperature,+ incontext_latents.to(dtype),+ incontext_length,+ t_span,+ additional_model_input,+ guidance_scale,+ abort_signal=abort_signal,+ disable_progress=disable_progress,+ )+ if latents is None:+ return None++ latents[:, 0:incontext_length, :] = incontext_latents[+ :, 0:incontext_length, :+ ]+ return latents++ def solve_euler(+ self,+ x,+ incontext_x,+ incontext_length,+ t_span,+ mu,+ guidance_scale,+ abort_signal=None,+ disable_progress=False,+ ):+ t = t_span[0]+ dt = t_span[1] - t_span[0]+ noise = x.clone()+ sol = []+ for step in tqdm(range(1, len(t_span)), disable=disable_progress):+ if abort_signal and abort_signal():+ return None+ x[:, 0:incontext_length, :] = (1 - (1 - 1e-6) * t) * noise[+ :, 0:incontext_length, :+ ] + t * incontext_x[:, 0:incontext_length, :]+ if guidance_scale > 1.0:+ dphi_dt = self.estimator(+ torch.cat(+ [+ torch.cat([x, x], 0),+ torch.cat([incontext_x, incontext_x], 0),+ torch.cat([torch.zeros_like(mu), mu], 0),+ ],+ 2,+ ),+ timestep=t.unsqueeze(-1).repeat(2),+ )+ dphi_dt_uncond, dhpi_dt_cond = dphi_dt.chunk(2, 0)+ dphi_dt = dphi_dt_uncond + guidance_scale * (+ dhpi_dt_cond - dphi_dt_uncond+ )+ else:+ dphi_dt = self.estimator(+ torch.cat([x, incontext_x, mu], 2), timestep=t.unsqueeze(-1)+ )++ x = x + dt * dphi_dt+ t = t + dt+ sol.append(x)+ if step < len(t_span) - 1:+ dt = t_span[step + 1] - t++ result = sol[-1]+ return resultdiff --git a/models/TTS/HeartMula/heartcodec/models/sq_codec.py b/models/TTS/HeartMula/heartcodec/models/sq_codec.pynew file mode 100644index 0000000..a0834be--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/models/sq_codec.py@@ -0,0 +1,526 @@+import numpy as np+import torch+import torch.nn as nn+import torch.nn.functional as F+from torch.autograd.function import InplaceFunction+from torch.nn.utils import remove_weight_norm+from torch.nn.utils.parametrizations import weight_norm+++def get_padding(kernel_size, dilation=1):+ return int((kernel_size * dilation - dilation) / 2)+++def snake(x, alpha):+ shape = x.shape+ x = x.reshape(shape[0], shape[1], -1)+ x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)+ x = x.reshape(shape)+ return x+++class Snake1d(nn.Module):+ def __init__(self, channels):+ super().__init__()+ self.alpha = nn.Parameter(torch.ones(1, channels, 1))++ def forward(self, x):+ return snake(x, self.alpha)+++class Conv1d(nn.Conv1d):+ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ kernel_size: int,+ stride: int = 1,+ dilation: int = 1,+ groups: int = 1,+ padding_mode: str = "zeros",+ bias: bool = True,+ padding=None,+ causal: bool = False,+ w_init_gain=None,+ ):+ self.causal = causal+ if padding is None:+ if causal:+ padding = 0+ self.left_padding = dilation * (kernel_size - 1)+ else:+ padding = get_padding(kernel_size, dilation)+ super().__init__(+ in_channels,+ out_channels,+ kernel_size,+ stride=stride,+ padding=padding,+ dilation=dilation,+ groups=groups,+ padding_mode=padding_mode,+ bias=bias,+ )+ if w_init_gain is not None:+ torch.nn.init.xavier_uniform_(+ self.weight, gain=torch.nn.init.calculate_gain(w_init_gain)+ )++ def forward(self, x):+ if self.causal:+ x = F.pad(x.unsqueeze(2), (self.left_padding, 0, 0, 0)).squeeze(2)+ return super().forward(x)+++class ConvTranspose1d(nn.ConvTranspose1d):+ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ kernel_size: int,+ stride: int = 1,+ output_padding: int = 0,+ groups: int = 1,+ bias: bool = True,+ dilation: int = 1,+ padding=None,+ padding_mode: str = "zeros",+ causal: bool = False,+ ):+ if padding is None:+ padding = 0 if causal else (kernel_size - stride) // 2+ if causal:+ assert padding == 0, "padding is not allowed in causal ConvTranspose1d."+ assert kernel_size == 2 * stride, (+ "kernel_size must be equal to 2*stride in causal ConvTranspose1d."+ )+ super().__init__(+ in_channels,+ out_channels,+ kernel_size,+ stride=stride,+ padding=padding,+ output_padding=output_padding,+ groups=groups,+ bias=bias,+ dilation=dilation,+ padding_mode=padding_mode,+ )+ self.causal = causal+ self.stride = stride++ def forward(self, x):+ x = super().forward(x)+ if self.causal:+ x = x[:, :, : -self.stride]+ return x+++class PreProcessor(nn.Module):+ def __init__(self, n_in, n_out, num_samples, kernel_size=7, causal=False):+ super().__init__()+ self.pooling = torch.nn.AvgPool1d(kernel_size=num_samples)+ self.conv = Conv1d(n_in, n_out, kernel_size=kernel_size, causal=causal)+ self.activation = nn.PReLU()++ def forward(self, x):+ output = self.activation(self.conv(x))+ output = self.pooling(output)+ return output+++class PostProcessor(nn.Module):+ def __init__(self, n_in, n_out, num_samples, kernel_size=7, causal=False):+ super().__init__()+ self.num_samples = num_samples+ self.conv = Conv1d(n_in, n_out, kernel_size=kernel_size, causal=causal)+ self.activation = nn.PReLU()++ def forward(self, x):+ x = torch.transpose(x, 1, 2)+ b, t, c = x.size()+ x = x.repeat(1, 1, self.num_samples).view(b, -1, c)+ x = torch.transpose(x, 1, 2)+ output = self.activation(self.conv(x))+ return output+++class ResidualUnit(nn.Module):+ def __init__(self, n_in, n_out, dilation, res_kernel_size=7, causal=False):+ super().__init__()+ self.conv1 = weight_norm(+ Conv1d(+ n_in,+ n_out,+ kernel_size=res_kernel_size,+ dilation=dilation,+ causal=causal,+ )+ )+ self.conv2 = weight_norm(Conv1d(n_in, n_out, kernel_size=1, causal=causal))+ self.activation1 = nn.PReLU()+ self.activation2 = nn.PReLU()++ def forward(self, x):+ output = self.activation1(self.conv1(x))+ output = self.activation2(self.conv2(output))+ return output + x+++class ResEncoderBlock(nn.Module):+ def __init__(+ self, n_in, n_out, stride, down_kernel_size, res_kernel_size=7, causal=False+ ):+ super().__init__()+ self.convs = nn.ModuleList(+ [+ ResidualUnit(+ n_in,+ n_out // 2,+ dilation=1,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out // 2,+ n_out // 2,+ dilation=3,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out // 2,+ n_out // 2,+ dilation=5,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out // 2,+ n_out // 2,+ dilation=7,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out // 2,+ n_out // 2,+ dilation=9,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ]+ )++ self.down_conv = DownsampleLayer(+ n_in, n_out, down_kernel_size, stride=stride, causal=causal+ )++ def forward(self, x):+ for conv in self.convs:+ x = conv(x)+ x = self.down_conv(x)+ return x+++class ResDecoderBlock(nn.Module):+ def __init__(+ self, n_in, n_out, stride, up_kernel_size, res_kernel_size=7, causal=False+ ):+ super().__init__()+ self.up_conv = UpsampleLayer(+ n_in,+ n_out,+ kernel_size=up_kernel_size,+ stride=stride,+ causal=causal,+ activation=None,+ )++ self.convs = nn.ModuleList(+ [+ ResidualUnit(+ n_out,+ n_out,+ dilation=1,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out,+ n_out,+ dilation=3,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out,+ n_out,+ dilation=5,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out,+ n_out,+ dilation=7,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ResidualUnit(+ n_out,+ n_out,+ dilation=9,+ res_kernel_size=res_kernel_size,+ causal=causal,+ ),+ ]+ )++ def forward(self, x):+ x = self.up_conv(x)+ for conv in self.convs:+ x = conv(x)+ return x+++class DownsampleLayer(nn.Module):+ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ kernel_size: int,+ stride: int = 1,+ causal: bool = False,+ activation=nn.PReLU(),+ use_weight_norm: bool = True,+ pooling: bool = False,+ ):+ super().__init__()+ self.pooling = pooling+ self.stride = stride+ self.activation = nn.PReLU()+ self.use_weight_norm = use_weight_norm+ if pooling:+ self.layer = Conv1d(in_channels, out_channels, kernel_size, causal=causal)+ self.pooling = nn.AvgPool1d(kernel_size=stride)+ else:+ self.layer = Conv1d(+ in_channels, out_channels, kernel_size, stride=stride, causal=causal+ )+ if use_weight_norm:+ self.layer = weight_norm(self.layer)++ def forward(self, x):+ x = self.layer(x)+ x = self.activation(x) if self.activation is not None else x+ if self.pooling:+ x = self.pooling(x)+ return x++ def remove_weight_norm(self):+ if self.use_weight_norm:+ remove_weight_norm(self.layer)+++class UpsampleLayer(nn.Module):+ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ kernel_size: int,+ stride: int = 1,+ causal: bool = False,+ activation=nn.PReLU(),+ use_weight_norm: bool = True,+ repeat: bool = False,+ ):+ super().__init__()+ self.repeat = repeat+ self.stride = stride+ self.activation = activation+ self.use_weight_norm = use_weight_norm+ if repeat:+ self.layer = Conv1d(in_channels, out_channels, kernel_size, causal=causal)+ else:+ self.layer = ConvTranspose1d(+ in_channels, out_channels, kernel_size, stride=stride, causal=causal+ )+ if use_weight_norm:+ self.layer = weight_norm(self.layer)++ def forward(self, x):+ x = self.layer(x)+ x = self.activation(x) if self.activation is not None else x+ if self.repeat:+ x = torch.transpose(x, 1, 2)+ b, t, c = x.size()+ x = x.repeat(1, 1, self.stride).view(b, -1, c)+ x = torch.transpose(x, 1, 2)+ return x++ def remove_weight_norm(self):+ if self.use_weight_norm:+ remove_weight_norm(self.layer)+++class round_func9(InplaceFunction):+ @staticmethod+ def forward(ctx, input):+ ctx.input = input+ return torch.round(9 * input) / 9++ @staticmethod+ def backward(ctx, grad_output):+ grad_input = grad_output.clone()+ return grad_input+++class ScalarModel(nn.Module):+ def __init__(+ self,+ num_bands,+ sample_rate,+ causal,+ num_samples,+ downsample_factors,+ downsample_kernel_sizes,+ upsample_factors,+ upsample_kernel_sizes,+ latent_hidden_dim,+ default_kernel_size,+ delay_kernel_size,+ init_channel,+ res_kernel_size,+ mode="pre_proj",+ ):+ super().__init__()+ self.encoder = []+ self.decoder = []+ self.vq = round_func9()+ self.mode = mode+ self.encoder.append(+ weight_norm(+ Conv1d(+ num_bands,+ init_channel,+ kernel_size=default_kernel_size,+ causal=causal,+ )+ )+ )+ if num_samples > 1:+ self.encoder.append(+ PreProcessor(+ init_channel,+ init_channel,+ num_samples,+ kernel_size=default_kernel_size,+ causal=causal,+ )+ )+ for i, down_factor in enumerate(downsample_factors):+ self.encoder.append(+ ResEncoderBlock(+ init_channel * np.power(2, i),+ init_channel * np.power(2, i + 1),+ down_factor,+ downsample_kernel_sizes[i],+ res_kernel_size,+ causal=causal,+ )+ )+ self.encoder.append(+ weight_norm(+ Conv1d(+ init_channel * np.power(2, len(downsample_factors)),+ latent_hidden_dim,+ kernel_size=default_kernel_size,+ causal=causal,+ )+ )+ )+ self.decoder.append(+ weight_norm(+ Conv1d(+ latent_hidden_dim,+ init_channel * np.power(2, len(upsample_factors)),+ kernel_size=delay_kernel_size,+ )+ )+ )+ for i, upsample_factor in enumerate(upsample_factors):+ self.decoder.append(+ ResDecoderBlock(+ init_channel * np.power(2, len(upsample_factors) - i),+ init_channel * np.power(2, len(upsample_factors) - i - 1),+ upsample_factor,+ upsample_kernel_sizes[i],+ res_kernel_size,+ causal=causal,+ )+ )+ if num_samples > 1:+ self.decoder.append(+ PostProcessor(+ init_channel,+ init_channel,+ num_samples,+ kernel_size=default_kernel_size,+ causal=causal,+ )+ )+ self.decoder.append(+ weight_norm(+ Conv1d(+ init_channel,+ num_bands,+ kernel_size=default_kernel_size,+ causal=causal,+ )+ )+ )+ self.encoder = nn.ModuleList(self.encoder)+ self.decoder = nn.ModuleList(self.decoder)++ def forward(self, x):+ for i, layer in enumerate(self.encoder):+ if i != len(self.encoder) - 1:+ x = layer(x)+ else:+ x = F.tanh(layer(x))+ x = self.vq.apply(x)+ for layer in self.decoder:+ x = layer(x)+ return x++ def inference(self, x):+ for i, layer in enumerate(self.encoder):+ if i != len(self.encoder) - 1:+ x = layer(x)+ else:+ x = F.tanh(layer(x))++ emb = x+ emb_quant = self.vq.apply(emb)+ x = emb_quant+ for layer in self.decoder:+ x = layer(x)+ return emb, emb_quant, x++ def encode(self, x):+ for i, layer in enumerate(self.encoder):+ if i != len(self.encoder) - 1:+ x = layer(x)+ else:+ x = F.tanh(layer(x))+ emb = x+ emb_quant = self.vq.apply(emb)+ return emb++ def decode(self, x):+ x = self.vq.apply(x)+ for layer in self.decoder:+ x = layer(x)+ return xdiff --git a/models/TTS/HeartMula/heartcodec/models/transformer.py b/models/TTS/HeartMula/heartcodec/models/transformer.pynew file mode 100644index 0000000..04f68c2--- /dev/null+++ b/models/TTS/HeartMula/heartcodec/models/transformer.py@@ -0,0 +1,487 @@+import math+from typing import Optional, Tuple++import torch+import torch.nn as nn+import torch.nn.functional as F+++class RMSNorm(nn.Module):+ def __init__(self, dim: int, eps: float = 1e-6):+ super().__init__()+ self.eps = eps+ self.weight = nn.Parameter(torch.ones(dim))++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ var = x.pow(2).mean(dim=-1, keepdim=True)+ x = x * torch.rsqrt(var + self.eps)+ return self.weight * x+++class RotaryEmbedding(nn.Module):+ def __init__(self, dim: int, base: int = 10000):+ super().__init__()+ self.dim = dim+ self.base = base+ self._cache = {}++ def get_sin_cos(self, seq_len: int, device, dtype):+ key = (seq_len, device, dtype)+ cached = self._cache.get(key, None)+ if cached is not None and cached[0].device == device:+ return cached+ inv_freq = 1.0 / (+ self.base+ ** (torch.arange(0, self.dim, 2, device=device, dtype=dtype) / self.dim)+ )+ t = torch.arange(seq_len, device=device, dtype=dtype)+ freqs = torch.einsum("i,j->ij", t, inv_freq)+ sin = freqs.sin()+ cos = freqs.cos()+ self._cache[key] = (sin, cos)+ return sin, cos++ def apply_rotary(+ self, x: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor+ ) -> torch.Tensor:+ x1, x2 = x[..., : self.dim // 2], x[..., self.dim // 2 : self.dim]+ x_rot = torch.stack((-x2, x1), dim=-1).reshape_as(x[..., : self.dim])+ return (x[..., : self.dim] * cos.unsqueeze(-1)).reshape_as(+ x[..., : self.dim]+ ) + (x_rot * sin.unsqueeze(-1)).reshape_as(x[..., : self.dim])+++class LlamaAttention(nn.Module):+ def __init__(+ self,+ dim: int,+ n_heads: int,+ head_dim: int,+ bias: bool = False,+ dropout: float = 0.0,+ rope_dim: Optional[int] = None,+ cross_attention_dim: Optional[int] = None,+ use_sdpa: bool = True,+ ):+ super().__init__()+ self.dim = dim+ self.n_heads = n_heads+ self.head_dim = head_dim+ self.inner_dim = n_heads * head_dim+ self.cross_attention_dim = cross_attention_dim+ self.q_proj = nn.Linear(dim, self.inner_dim, bias=bias)+ k_in = dim if cross_attention_dim is None else cross_attention_dim+ self.k_proj = nn.Linear(k_in, self.inner_dim, bias=bias)+ self.v_proj = nn.Linear(k_in, self.inner_dim, bias=bias)+ self.o_proj = nn.Linear(self.inner_dim, dim, bias=bias)+ self.dropout = dropout+ self.rope_dim = rope_dim if rope_dim is not None else head_dim+ self.rope = RotaryEmbedding(self.rope_dim)+ self.use_sdpa = use_sdpa+ self._has_sdpa = hasattr(F, "scaled_dot_product_attention")++ def _shape(self, x: torch.Tensor, b: int, t: int) -> torch.Tensor:+ return x.view(b, t, self.n_heads, self.head_dim).transpose(1, 2)++ def forward(+ self,+ x: torch.Tensor,+ encoder_hidden_states: Optional[torch.Tensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ b, t, _ = x.shape+ q = self._shape(self.q_proj(x), b, t)+ if encoder_hidden_states is None:+ k = self._shape(self.k_proj(x), b, t)+ v = self._shape(self.v_proj(x), b, t)+ else:+ _, tk, _ = encoder_hidden_states.shape+ k = self._shape(self.k_proj(encoder_hidden_states), b, tk)+ v = self._shape(self.v_proj(encoder_hidden_states), b, tk)++ rope_dim = min(self.rope_dim, self.head_dim)+ seq_len_for_rope = k.shape[-2]+ sin, cos = self.rope.get_sin_cos(+ seq_len_for_rope, device=x.device, dtype=x.dtype+ )++ def apply_rope_vec(tensor):+ head = tensor[..., :rope_dim]+ tail = tensor[..., rope_dim:]+ _, _, tt, _ = head.shape+ head = head.view(b, self.n_heads, tt, rope_dim // 2, 2)+ sin_ = sin.view(1, 1, tt, rope_dim // 2, 1)+ cos_ = cos.view(1, 1, tt, rope_dim // 2, 1)+ x1 = head[..., 0:1]+ x2 = head[..., 1:2]+ rot = torch.cat([x1 * cos_ - x2 * sin_, x1 * sin_ + x2 * cos_], dim=-1)+ rot = rot.view(b, self.n_heads, tt, rope_dim)+ return torch.cat([rot, tail], dim=-1)++ q = apply_rope_vec(q)+ k = apply_rope_vec(k)++ if self.use_sdpa and self._has_sdpa:+ s = k.shape[-2]+ attn_mask_sdpa = None+ if attention_mask is not None:+ m = attention_mask++ if m.dim() == 2 and m.shape == (b, s):+ m = m[:, None, None, :]+ elif m.dim() == 3 and m.shape[-2] == 1:+ m = m[:, None, :, :]+ elif m.dim() == 3 and m.shape[-2] == t:+ m = m[:, None, :, :]+ elif m.dim() == 4 and m.shape[1] == 1:+ pass+ attn_mask_sdpa = m++ out = F.scaled_dot_product_attention(+ q,+ k,+ v,+ attn_mask=attn_mask_sdpa,+ dropout_p=self.dropout if self.training else 0.0,+ is_causal=False,+ )+ out = out.transpose(1, 2).contiguous().view(b, t, self.inner_dim)+ return self.o_proj(out)++ attn_scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)+ if attention_mask is not None:+ attn_scores = attn_scores + attention_mask+ attn = attn_scores.softmax(dim=-1)+ attn = F.dropout(attn, p=self.dropout, training=self.training)+ out = torch.matmul(attn, v)+ out = out.transpose(1, 2).contiguous().view(b, t, self.inner_dim)+ return self.o_proj(out)+++class LlamaMLP(nn.Module):+ def __init__(+ self,+ dim: int,+ hidden_dim: Optional[int] = None,+ multiple_of: int = 256,+ dropout: float = 0.0,+ ):+ super().__init__()+ hidden_dim = hidden_dim or 4 * dim+ hidden_dim = int(2 * hidden_dim / 3)+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)+ self.gate = nn.Linear(dim, hidden_dim, bias=False)+ self.up = nn.Linear(dim, hidden_dim, bias=False)+ self.down = nn.Linear(hidden_dim, dim, bias=False)+ self.dropout = dropout++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x = F.silu(self.gate(x)) * self.up(x)+ x = F.dropout(x, p=self.dropout, training=self.training)+ return self.down(x)+++class LlamaTransformerBlock(nn.Module):+ def __init__(+ self,+ dim: int,+ n_heads: int,+ head_dim: int,+ mlp_multiple_of: int = 256,+ dropout: float = 0.0,+ attention_bias: bool = False,+ cross_attention_dim: Optional[int] = None,+ use_ada_layer_norm_single: bool = False,+ ):+ super().__init__()+ self.attn_norm = RMSNorm(dim, 1e-6)+ self.attn = LlamaAttention(+ dim,+ n_heads,+ head_dim,+ bias=attention_bias,+ dropout=dropout,+ rope_dim=head_dim,+ cross_attention_dim=None,+ )+ self.cross_attn = None+ if cross_attention_dim is not None:+ self.cross_attn_norm = RMSNorm(dim, 1e-6)+ self.cross_attn = LlamaAttention(+ dim,+ n_heads,+ head_dim,+ bias=attention_bias,+ dropout=dropout,+ rope_dim=head_dim,+ cross_attention_dim=cross_attention_dim,+ )+ self.mlp_norm = RMSNorm(dim, 1e-6)+ self.mlp = LlamaMLP(dim, multiple_of=mlp_multiple_of, dropout=dropout)+ self.use_ada_layer_norm_single = use_ada_layer_norm_single+ if self.use_ada_layer_norm_single:+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)++ def forward(+ self,+ x: torch.Tensor,+ encoder_hidden_states: Optional[torch.Tensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ timestep: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ if self.use_ada_layer_norm_single:+ batch_size = x.shape[0]+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)+ ).chunk(6, dim=1)++ norm_hidden_states = self.attn_norm(x)+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa+ h = self.attn(norm_hidden_states, attention_mask=attention_mask)+ h = gate_msa * h+ x = x + h++ norm_hidden_states = self.mlp_norm(x)+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp+ h = self.mlp(norm_hidden_states)+ h = gate_mlp * h+ x = x + h+ return x++ h = self.attn(self.attn_norm(x), attention_mask=attention_mask)+ x = x + h+ h = self.mlp(self.mlp_norm(x))+ x = x + h+ return x+++class ProjectLayer(nn.Module):+ def __init__(self, hidden_size, filter_size, kernel_size=1, dropout=0.0):+ super().__init__()+ self.kernel_size = kernel_size+ self.dropout = dropout+ self.ffn_1 = nn.Conv1d(+ hidden_size, filter_size, kernel_size, padding=kernel_size // 2+ )+ self.ffn_2 = nn.Linear(filter_size, filter_size)++ def forward(self, x):+ x = self.ffn_1(x.transpose(1, 2)).transpose(1, 2)+ x = x * self.kernel_size**-0.5+ x = self.ffn_2(x)+ return x+++class LlamaTransformer(nn.Module):+ def __init__(+ self,+ num_attention_heads: int,+ attention_head_dim: int,+ in_channels: int,+ out_channels: int,+ num_layers: int = 12,+ num_layers_2: int = 2,+ dropout: float = 0.0,+ cross_attention_dim: Optional[int] = None,+ norm_type: str = "layer_norm",+ ):+ super().__init__()+ inner_dim = num_attention_heads * attention_head_dim+ inner_dim_2 = inner_dim * 2+ self.in_channels = in_channels+ self.out_channels = out_channels+ self.inner_dim = inner_dim+ self.inner_dim_2 = inner_dim_2+ self.dropout = dropout++ self.proj_in = ProjectLayer(in_channels, inner_dim, kernel_size=3)++ use_ada_single = norm_type == "ada_norm_single"+ self.transformer_blocks = nn.ModuleList(+ [+ LlamaTransformerBlock(+ dim=inner_dim,+ n_heads=num_attention_heads,+ head_dim=attention_head_dim,+ dropout=dropout,+ attention_bias=False,+ cross_attention_dim=cross_attention_dim,+ use_ada_layer_norm_single=use_ada_single,+ )+ for _ in range(num_layers)+ ]+ )++ self.transformer_blocks_2 = nn.ModuleList(+ [+ LlamaTransformerBlock(+ dim=inner_dim_2,+ n_heads=num_attention_heads,+ head_dim=attention_head_dim * 2,+ dropout=dropout,+ attention_bias=False,+ cross_attention_dim=cross_attention_dim,+ use_ada_layer_norm_single=use_ada_single,+ )+ for _ in range(num_layers_2)+ ]+ )++ self.connection_proj = ProjectLayer(+ in_channels + inner_dim, inner_dim_2, kernel_size=3+ )+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)+ self.norm_out_2 = nn.LayerNorm(inner_dim_2, elementwise_affine=False, eps=1e-6)+ self.scale_shift_table = nn.Parameter(+ torch.randn(2, inner_dim) / inner_dim**0.5+ )+ self.scale_shift_table_2 = nn.Parameter(+ torch.randn(2, inner_dim_2) / inner_dim_2**0.5+ )+ self.proj_out = ProjectLayer(inner_dim_2, out_channels, kernel_size=3)+ self.adaln_single = AdaLayerNormSingleFlow(inner_dim)+ self.adaln_single_2 = AdaLayerNormSingleFlow(inner_dim_2)++ def forward(+ self,+ hidden_states: torch.Tensor,+ timestep: Optional[torch.LongTensor] = None,+ ):+ s = self.proj_in(hidden_states)++ embedded_timestep = None+ timestep_mod = None+ if self.adaln_single is not None and timestep is not None:+ timestep_mod, embedded_timestep = self.adaln_single(+ timestep, hidden_dtype=s.dtype+ )+ for blk in self.transformer_blocks:+ s = blk(s, timestep=timestep_mod)++ if embedded_timestep is None:+ embedded_timestep = torch.zeros(+ s.size(0), s.size(-1), device=s.device, dtype=s.dtype+ )++ shift, scale = (+ self.scale_shift_table[None] + embedded_timestep[:, None]+ ).chunk(2, dim=1)+ s = self.norm_out(s)+ s = s * (1 + scale) + shift++ x = torch.cat([hidden_states, s], dim=-1)+ x = self.connection_proj(x)++ embedded_timestep_2 = None+ timestep_mod_2 = None+ if self.adaln_single_2 is not None and timestep is not None:+ timestep_mod_2, embedded_timestep_2 = self.adaln_single_2(+ timestep, hidden_dtype=x.dtype+ )+ for blk in self.transformer_blocks_2:+ x = blk(x, timestep=timestep_mod_2)++ if embedded_timestep_2 is None:+ embedded_timestep_2 = torch.zeros(+ x.size(0), x.size(-1), device=x.device, dtype=x.dtype+ )++ shift_2, scale_2 = (+ self.scale_shift_table_2[None] + embedded_timestep_2[:, None]+ ).chunk(2, dim=1)+ x = self.norm_out_2(x)+ x = x * (1 + scale_2) + shift_2++ out = self.proj_out(x)+ return out+++class PixArtAlphaCombinedFlowEmbeddings(nn.Module):+ def __init__(self, embedding_dim: int, size_emb_dim: int):+ super().__init__()+ self.flow_t_size = 512+ self.outdim = size_emb_dim+ self.timestep_embedder = TimestepEmbedding(+ in_channels=self.flow_t_size, time_embed_dim=embedding_dim+ )++ def timestep_embedding(self, timesteps, max_period=10000, scale=1000):+ half = self.flow_t_size // 2+ freqs = torch.exp(+ -math.log(max_period)+ * torch.arange(start=0, end=half, device=timesteps.device)+ / half+ ).type(timesteps.type())+ args = timesteps[:, None] * freqs[None] * scale+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)+ if self.flow_t_size % 2:+ embedding = torch.cat(+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1+ )+ return embedding++ def forward(self, timestep, hidden_dtype):+ timesteps_proj = self.timestep_embedding(timestep)+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype))+ return timesteps_emb+++class AdaLayerNormSingleFlow(nn.Module):+ def __init__(self, embedding_dim: int):+ super().__init__()+ self.emb = PixArtAlphaCombinedFlowEmbeddings(+ embedding_dim, size_emb_dim=embedding_dim // 3+ )+ self.silu = nn.SiLU()+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)++ def forward(+ self,+ timestep: torch.Tensor,+ hidden_dtype: Optional[torch.dtype] = None,+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ embedded_timestep = self.emb(timestep, hidden_dtype=hidden_dtype)+ return self.linear(self.silu(embedded_timestep)), embedded_timestep+++class TimestepEmbedding(nn.Module):+ def __init__(self, in_channels: int, time_embed_dim: int):+ super().__init__()+ self.linear_1 = nn.Linear(in_channels, time_embed_dim)+ self.act = nn.SiLU()+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x = self.linear_1(x)+ x = self.act(x)+ x = self.linear_2(x)+ return x+++class Timesteps(nn.Module):+ def __init__(+ self,+ num_channels: int,+ flip_sin_to_cos: bool = True,+ downscale_freq_shift: float = 0,+ ):+ super().__init__()+ self.num_channels = num_channels+ self.flip_sin_to_cos = flip_sin_to_cos+ self.downscale_freq_shift = downscale_freq_shift++ def forward(self, timesteps: torch.Tensor) -> torch.Tensor:+ half_dim = self.num_channels // 2+ exponent = (+ -math.log(10000)+ * torch.arange(0, half_dim, device=timesteps.device)+ / (half_dim - self.downscale_freq_shift)+ )+ emb = torch.exp(exponent)[None, :] * timesteps[:, None]+ if self.flip_sin_to_cos:+ emb = torch.cat([torch.cos(emb), torch.sin(emb)], dim=-1)+ else:+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)+ if self.num_channels % 2 == 1:+ emb = torch.nn.functional.pad(emb, (0, 1))+ return embdiff --git a/models/TTS/HeartMula/heartmula/__init__.py b/models/TTS/HeartMula/heartmula/__init__.pynew file mode 100644index 0000000..7de5b4f--- /dev/null+++ b/models/TTS/HeartMula/heartmula/__init__.py@@ -0,0 +1,4 @@+from .configuration_heartmula import HeartMuLaConfig+from .modeling_heartmula import HeartMuLa++__all__ = ["HeartMuLa", "HeartMuLaConfig"]diff --git a/models/TTS/HeartMula/heartmula/configuration_heartmula.py b/models/TTS/HeartMula/heartmula/configuration_heartmula.pynew file mode 100644index 0000000..e3551ea--- /dev/null+++ b/models/TTS/HeartMula/heartmula/configuration_heartmula.py@@ -0,0 +1,23 @@+from transformers.configuration_utils import PretrainedConfig+++class HeartMuLaConfig(PretrainedConfig):+ model_type = "heartmula"++ def __init__(+ self,+ backbone_flavor: str = "llama-3B",+ decoder_flavor: str = "llama-300M",+ text_vocab_size: int = 128256,+ audio_vocab_size: int = 8197,+ audio_num_codebooks: int = 8,+ muq_dim: int = 512,+ **kwargs,+ ):+ super().__init__(**kwargs)+ self.backbone_flavor = backbone_flavor+ self.decoder_flavor = decoder_flavor+ self.text_vocab_size = text_vocab_size+ self.audio_vocab_size = audio_vocab_size+ self.audio_num_codebooks = audio_num_codebooks+ self.muq_dim = muq_dimdiff --git a/models/TTS/HeartMula/heartmula/llama_blocks.py b/models/TTS/HeartMula/heartmula/llama_blocks.pynew file mode 100644index 0000000..fcd03fb--- /dev/null+++ b/models/TTS/HeartMula/heartmula/llama_blocks.py@@ -0,0 +1,808 @@+from __future__ import annotations++import math+from typing import Optional, Tuple++import torch+from torch import nn+from torch.nn import functional as F++try:+ from flash_attn.flash_attn_interface import (+ flash_attn_with_kvcache,+ flash_attn_func,+ )+except Exception:+ flash_attn_with_kvcache = None+ flash_attn_func = None++#disabled flash to test sdpa+# flash_attn_with_kvcache = None+# flash_attn_func = None++_FLASH_ATTN_NOTICE_SHOWN = False+_FLASH_ATTN_FULL_NOTICE_SHOWN = False+++def scale_hidden_dim_for_mlp(dim: int, multiple_of: int = 256) -> int:+ hidden_dim = 4 * int(2 * dim / 3)+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)+ return hidden_dim+++class RMSNorm(nn.Module):+ def __init__(self, dim: int, eps: float = 1e-6) -> None:+ super().__init__()+ self.eps = eps+ self.scale = nn.Parameter(torch.ones(dim))++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x_fp32 = x.float()+ x_normed = (+ x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps)+ ).type_as(x)+ return x_normed * self.scale+++class FeedForward(nn.Module):+ def __init__(+ self,+ *,+ gate_proj: nn.Module,+ down_proj: nn.Module,+ up_proj: Optional[nn.Module] = None,+ activation: nn.Module = nn.SiLU(),+ ):+ super().__init__()+ self.w1 = gate_proj+ self.w2 = down_proj+ self.w3 = up_proj+ self.activation = activation++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ h = self.activation(self.w1(x))+ if self.w3 is not None:+ h = h * self.w3(x)+ h = self.w2(h)+ return h+++class Llama3ScaledRoPE(nn.Module):+ def __init__(+ self,+ dim: int,+ max_seq_len: int = 4096,+ base: int = 10_000,+ scale_factor: int = 8,+ low_freq_factor: int = 1,+ high_freq_factor: int = 4,+ old_context_len: int = 8192,+ ) -> None:+ super().__init__()+ self.dim = dim+ self.base = base+ self.max_seq_len = max_seq_len++ self.scale_factor = scale_factor+ self.low_freq_factor = low_freq_factor+ self.high_freq_factor = high_freq_factor+ self.old_context_len = old_context_len+ self.is_cache_built = False+ self.rope_init()++ def rope_init(self) -> None:+ freqs = 1.0 / (+ self.base+ ** (torch.arange(0, self.dim, 2)[: (self.dim // 2)].float() / self.dim)+ )++ if freqs.is_meta:+ return++ theta = self.apply_scaling(+ freqs,+ self.scale_factor,+ self.low_freq_factor,+ self.high_freq_factor,+ self.old_context_len,+ )+ self.register_buffer("theta", theta, persistent=False)+ self.build_rope_cache(self.max_seq_len)+ self.is_cache_built = True++ def build_rope_cache(self, max_seq_len: int = 4096) -> None:+ seq_idx = torch.arange(+ max_seq_len, dtype=self.theta.dtype, device=self.theta.device+ )+ idx_theta = torch.einsum("i, j -> ij", seq_idx, self.theta).float()+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)+ self.register_buffer("cache", cache, persistent=False)++ def ensure_device(self, device: torch.device) -> None:+ if not hasattr(self, "theta"):+ return+ if getattr(self.theta, "is_meta", False):+ return+ if self.theta.device == device:+ return+ non_blocking = device.type == "cuda"+ self.theta = self.theta.to(device, non_blocking=non_blocking)+ if hasattr(self, "cache"):+ self.cache = self.cache.to(device, non_blocking=non_blocking)++ def apply_scaling(+ self,+ freqs: torch.Tensor,+ scale_factor: int,+ low_freq_factor: int,+ high_freq_factor: int,+ old_context_len: int,+ ) -> torch.Tensor:+ low_freq_wavelen = old_context_len / low_freq_factor+ high_freq_wavelen = old_context_len / high_freq_factor+ new_freqs = []+ for freq in freqs:+ wavelen = 2 * math.pi / freq+ if wavelen < high_freq_wavelen:+ new_freqs.append(freq)+ elif wavelen > low_freq_wavelen:+ new_freqs.append(freq / scale_factor)+ else:+ smooth = (old_context_len / wavelen - low_freq_factor) / (+ high_freq_factor - low_freq_factor+ )+ new_freqs.append((1 - smooth) * freq / scale_factor + smooth * freq)+ return torch.tensor(new_freqs, dtype=freqs.dtype, device=freqs.device)++ def forward(+ self, x: torch.Tensor, *, input_pos: Optional[torch.Tensor] = None+ ) -> torch.Tensor:+ if not self.is_cache_built:+ raise RuntimeError("RoPE cache is not built.")++ seq_len = x.size(1)+ rope_cache = (+ self.cache[:seq_len] if input_pos is None else self.cache[input_pos]+ )+ xshaped = x.float().reshape(*x.shape[:-1], -1, 2)+ rope_cache = rope_cache.view(-1, xshaped.size(1), 1, xshaped.size(3), 2)++ x_out = torch.stack(+ [+ xshaped[..., 0] * rope_cache[..., 0]+ - xshaped[..., 1] * rope_cache[..., 1],+ xshaped[..., 1] * rope_cache[..., 0]+ + xshaped[..., 0] * rope_cache[..., 1],+ ],+ -1,+ )+ x_out = x_out.flatten(3)+ return x_out.type_as(x)+++class ExpandableKVCache(nn.Module):+ def __init__(+ self,+ batch_size: int,+ max_seq_len: int,+ num_heads: int,+ head_dim: int,+ dtype: torch.dtype,+ *,+ expand_step: int = 200,+ device: Optional[torch.device] = None,+ ) -> None:+ super().__init__()+ if expand_step <= 0:+ raise ValueError("expand_step must be > 0")+ self.batch_size = batch_size+ self.num_heads = num_heads+ self.head_dim = head_dim+ self.expand_step = expand_step+ self.limit = max_seq_len+ self._pos = 0++ init_len = expand_step+ if max_seq_len is not None:+ init_len = min(max_seq_len, expand_step)+ self.capacity = init_len++ k_cache = torch.empty(+ (batch_size, self.capacity, num_heads, head_dim),+ device=device,+ dtype=dtype,+ )+ v_cache = torch.empty_like(k_cache)+ self.register_buffer("k_cache", k_cache, persistent=False)+ self.register_buffer("v_cache", v_cache, persistent=False)++ @property+ def size(self) -> int:+ return self._pos++ def reset(self) -> None:+ self._pos = 0++ def _replace_buffer(self, name: str, tensor: torch.Tensor) -> None:+ if name in self._buffers:+ self._buffers.pop(name)+ self.register_buffer(name, tensor, persistent=False)++ def ensure_capacity(self, required_len: int) -> None:+ if required_len <= self.capacity:+ return+ if self.limit is not None and required_len > self.limit:+ raise RuntimeError(+ f"KV cache length {required_len} exceeds limit {self.limit}"+ )+ new_capacity = self.capacity+ while new_capacity < required_len:+ new_capacity += self.expand_step+ if self.limit is not None:+ new_capacity = min(new_capacity, self.limit)+ self._resize_cache(new_capacity)++ def _resize_cache(self, new_capacity: int) -> None:+ if new_capacity <= self.capacity:+ return+ device = self.k_cache.device+ dtype = self.k_cache.dtype+ bsz = self.k_cache.shape[0]++ if device.type == "cuda":+ k_cpu = self.k_cache[:, : self._pos].detach().cpu()+ v_cpu = self.v_cache[:, : self._pos].detach().cpu()+ self._buffers.pop("k_cache", None)+ self._buffers.pop("v_cache", None)+ k_new = torch.empty(+ (bsz, new_capacity, self.num_heads, self.head_dim),+ device=device,+ dtype=dtype,+ )+ v_new = torch.empty_like(k_new)+ if self._pos:+ k_new[:, : self._pos] = k_cpu.to(device)+ v_new[:, : self._pos] = v_cpu.to(device)+ k_cpu = None+ v_cpu = None+ else:+ k_new = torch.empty(+ (bsz, new_capacity, self.num_heads, self.head_dim),+ device=device,+ dtype=dtype,+ )+ v_new = torch.empty_like(k_new)+ if self._pos:+ k_new[:, : self._pos] = self.k_cache[:, : self._pos]+ v_new[:, : self._pos] = self.v_cache[:, : self._pos]++ self._replace_buffer("k_cache", k_new)+ self._replace_buffer("v_cache", v_new)+ self.capacity = new_capacity++ def ensure_device(self, device: torch.device, dtype: Optional[torch.dtype] = None) -> None:+ target_dtype = self.k_cache.dtype if dtype is None else dtype+ if self.k_cache.device == device and self.k_cache.dtype == target_dtype:+ return+ bsz = self.k_cache.shape[0]+ if device.type == "cuda":+ k_cpu = self.k_cache[:, : self._pos].detach().cpu()+ v_cpu = self.v_cache[:, : self._pos].detach().cpu()+ self._buffers.pop("k_cache", None)+ self._buffers.pop("v_cache", None)+ k_new = torch.empty(+ (bsz, self.capacity, self.num_heads, self.head_dim),+ device=device,+ dtype=target_dtype,+ )+ v_new = torch.empty_like(k_new)+ if self._pos:+ k_new[:, : self._pos] = k_cpu.to(device=device, dtype=target_dtype)+ v_new[:, : self._pos] = v_cpu.to(device=device, dtype=target_dtype)+ k_cpu = None+ v_cpu = None+ else:+ k_new = torch.empty(+ (bsz, self.capacity, self.num_heads, self.head_dim),+ device=device,+ dtype=target_dtype,+ )+ v_new = torch.empty_like(k_new)+ if self._pos:+ k_new[:, : self._pos] = self.k_cache[:, : self._pos].to(+ device=device, dtype=target_dtype+ )+ v_new[:, : self._pos] = self.v_cache[:, : self._pos].to(+ device=device, dtype=target_dtype+ )++ self._replace_buffer("k_cache", k_new)+ self._replace_buffer("v_cache", v_new)++ def update(+ self, k_val: torch.Tensor, v_val: torch.Tensor+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ bsz, seq_len, _, _ = k_val.shape+ if bsz > self.k_cache.shape[0]:+ raise ValueError(+ f"KV cache batch size {self.k_cache.shape[0]} is smaller than {bsz}"+ )+ required = self._pos + seq_len+ self.ensure_capacity(required)+ start = self._pos+ end = start + seq_len+ self.k_cache[:bsz, start:end] = k_val+ self.v_cache[:bsz, start:end] = v_val+ self._pos = end+ return self.k_cache, self.v_cache++ def advance(self, seq_len: int) -> None:+ self.ensure_capacity(self._pos + seq_len)+ self._pos += seq_len+++class MultiHeadAttention(nn.Module):+ def __init__(+ self,+ *,+ embed_dim: int,+ num_heads: int,+ num_kv_heads: int,+ head_dim: int,+ q_proj: nn.Module,+ k_proj: nn.Module,+ v_proj: nn.Module,+ output_proj: nn.Module,+ pos_embeddings: Optional[nn.Module] = None,+ max_seq_len: int = 4096,+ is_causal: bool = True,+ attn_dropout: float = 0.0,+ cache_expand_step: int = 200,+ ) -> None:+ super().__init__()+ if num_heads % num_kv_heads != 0:+ raise ValueError(+ f"num_heads ({num_heads}) must be divisible by num_kv_heads ({num_kv_heads})"+ )+ if embed_dim % num_heads != 0:+ raise ValueError(+ f"embed_dim ({embed_dim}) must be divisible by num_heads ({num_heads})"+ )+ if attn_dropout < 0 or attn_dropout > 1:+ raise ValueError("attn_dropout must be between 0.0 and 1.0")++ self.num_heads = num_heads+ self.num_kv_heads = num_kv_heads+ self.embed_dim = embed_dim+ self.attn_dropout = attn_dropout+ self.head_dim = head_dim+ self.max_seq_len = max_seq_len+ self.is_causal = is_causal++ self.kv_cache: Optional[ExpandableKVCache] = None+ self.q_proj = q_proj+ self.k_proj = k_proj+ self.v_proj = v_proj+ self.output_proj = output_proj+ self.pos_embeddings = pos_embeddings+ self.cache_enabled = False+ self.cache_expand_step = cache_expand_step+ self._flash_attn = flash_attn_with_kvcache+ self._flash_attn_func = flash_attn_func+ self._flash_kv_ready = False+ self._flash_full_ready = False+ self._flash_device = None+ self._flash_dtype = None++ def setup_cache(+ self, batch_size: int, dtype: torch.dtype, max_seq_len: int+ ) -> None:+ if self.kv_cache is not None:+ return+ device = self.q_proj.weight.device+ self.kv_cache = ExpandableKVCache(+ batch_size=batch_size,+ max_seq_len=max_seq_len,+ num_heads=self.num_heads,+ head_dim=self.head_dim,+ dtype=dtype,+ expand_step=self.cache_expand_step,+ device=device,+ )+ self.cache_enabled = True++ def reset_cache(self) -> None:+ if self.kv_cache is None:+ raise RuntimeError("Key value caches are not setup.")+ self.kv_cache.reset()++ def _apply_rope(+ self, qk_list: list[torch.Tensor], input_pos: Optional[torch.Tensor]+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ q,k = qk_list+ qk_list.clear()+ if self.pos_embeddings is not None:+ q = self.pos_embeddings(q, input_pos=input_pos)+ k = self.pos_embeddings(k, input_pos=input_pos)+ return q, k++ def _expand_kv(+ self, kv_list: list[torch.Tensor], q_per_kv: int+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ k,v = kv_list+ kv_list.clear()+ if self.num_heads != self.num_kv_heads:+ bsz, seq_len, _, _ = k.shape+ k = (+ k.view(bsz, seq_len, self.num_kv_heads, 1, self.head_dim)+ .expand(bsz, seq_len, self.num_kv_heads, q_per_kv, self.head_dim)+ .reshape(bsz, seq_len, self.num_heads, self.head_dim)+ )+ v = (+ v.view(bsz, seq_len, self.num_kv_heads, 1, self.head_dim)+ .expand(bsz, seq_len, self.num_kv_heads, q_per_kv, self.head_dim)+ .reshape(bsz, seq_len, self.num_heads, self.head_dim)+ )+ return k, v++ def _sdpa(+ self,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ mask: Optional[torch.Tensor],+ is_causal: bool,+ ) -> torch.Tensor:+ q = q.transpose(1, 2)+ k = k.transpose(1, 2)+ v = v.transpose(1, 2)++ attn_mask = None+ if mask is not None:+ if mask.device != q.device:+ mask = mask.to(q.device)+ attn_mask = mask+ if attn_mask.dim() == 3:+ attn_mask = attn_mask[:, None, :, :]+ if attn_mask.shape[-1] != k.shape[-2]:+ attn_mask = attn_mask[..., : k.shape[-2]]++ out = F.scaled_dot_product_attention(+ q,+ k,+ v,+ attn_mask=attn_mask,+ dropout_p=self.attn_dropout if self.training else 0.0,+ is_causal=is_causal,+ )+ return out.transpose(1, 2).contiguous()++ def _flash_full(+ self,+ q: torch.Tensor,+ k: torch.Tensor,+ v: torch.Tensor,+ *,+ is_causal: bool,+ ) -> torch.Tensor:+ global _FLASH_ATTN_FULL_NOTICE_SHOWN+ if not _FLASH_ATTN_FULL_NOTICE_SHOWN:+ print("\nHeartMuLa attention: using flash_attn_func.")+ _FLASH_ATTN_FULL_NOTICE_SHOWN = True+ return self._flash_attn_func(+ q,+ k,+ v,+ dropout_p=self.attn_dropout if self.training else 0.0,+ causal=is_causal,+ )++ def configure_flash(self, device: torch.device, dtype: torch.dtype) -> None:+ if self._flash_device == device and self._flash_dtype == dtype:+ return+ self._flash_device = device+ self._flash_dtype = dtype+ flash_ok = (+ device.type == "cuda"+ and dtype in (torch.float16, torch.bfloat16)+ and self.head_dim <= 256+ )+ kv_ready = self.kv_cache is not None and self.cache_enabled+ self._flash_kv_ready = (+ flash_ok and self._flash_attn is not None and kv_ready+ )+ self._flash_full_ready = flash_ok and self._flash_attn_func is not None++ def reset_flash(self) -> None:+ self._flash_kv_ready = False+ self._flash_full_ready = False+ self._flash_device = None+ self._flash_dtype = None++ def forward(+ self,+ x: torch.Tensor,+ y: Optional[torch.Tensor] = None,+ *,+ mask: Optional[torch.Tensor] = None,+ input_pos: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ bsz, s_x, _ = x.shape+ q = self.q_proj(x).view(bsz, s_x, self.num_heads, self.head_dim)+ if self.kv_cache is not None and self.cache_enabled:+ self.kv_cache.ensure_device(q.device, q.dtype)+ if mask is not None and s_x == 1:+ mask = None+ y = x if y is None else y+ s_y = y.shape[1]+ k = self.k_proj(y).view(bsz, s_y, self.num_kv_heads, self.head_dim)+ v = self.v_proj(y).view(bsz, s_y, self.num_kv_heads, self.head_dim)+ qk_list = [q, k]+ q= k = None+ q, k = self._apply_rope(qk_list, input_pos)+ kv_list = [k, v]+ k= v = None+ k, v = self._expand_kv(kv_list, self.num_heads // self.num_kv_heads)++ if s_x == 1:+ use_flash_kv = self._flash_kv_ready and mask is None+ if use_flash_kv:+ global _FLASH_ATTN_NOTICE_SHOWN+ if not _FLASH_ATTN_NOTICE_SHOWN:+ print("\nHeartMuLa attention: using flash_attn_with_kvcache.")+ _FLASH_ATTN_NOTICE_SHOWN = True+ self.kv_cache.ensure_capacity(self.kv_cache.size + s_y)+ cache_seqlens = torch.full(+ (bsz,),+ self.kv_cache.size,+ device=q.device,+ dtype=torch.int32,+ )+ attn_out = self._flash_attn(+ q=q,+ k_cache=self.kv_cache.k_cache,+ v_cache=self.kv_cache.v_cache,+ k=k,+ v=v,+ cache_seqlens=cache_seqlens,+ cache_leftpad=None,+ causal=True,+ )+ self.kv_cache.advance(s_y)+ else:+ if self.kv_cache is not None and self.cache_enabled:+ k_cache, v_cache = self.kv_cache.update(k, v)+ k = k_cache[:, : self.kv_cache.size]+ v = v_cache[:, : self.kv_cache.size]+ attn_out = self._sdpa(+ q,+ k,+ v,+ mask=mask,+ is_causal=False,+ )+ else:+ use_flash_full = self._flash_full_ready and mask is None+ if use_flash_full:+ if self.kv_cache is not None and self.cache_enabled:+ self.kv_cache.update(k, v)+ attn_out = self._flash_full(+ q,+ k,+ v,+ is_causal=self.is_causal,+ )+ else:+ if self.kv_cache is not None and self.cache_enabled:+ k_cache, v_cache = self.kv_cache.update(k, v)+ k = k_cache[:, : self.kv_cache.size]+ v = v_cache[:, : self.kv_cache.size]+ attn_out = self._sdpa(+ q,+ k,+ v,+ mask=mask,+ is_causal=self.is_causal if mask is None else False,+ )++ q = None+ k = None+ v = None+ mask = None+ attn_out = attn_out.reshape(bsz, s_x, -1)+ out = self.output_proj(attn_out)+ return out+++class TransformerSelfAttentionLayer(nn.Module):+ def __init__(+ self,+ attn: MultiHeadAttention,+ mlp: nn.Module,+ *,+ sa_norm: Optional[nn.Module] = None,+ mlp_norm: Optional[nn.Module] = None,+ ) -> None:+ super().__init__()+ self.attn = attn+ self.mlp = mlp+ self.sa_norm = sa_norm or nn.Identity()+ self.mlp_norm = mlp_norm or nn.Identity()++ def setup_caches(+ self,+ batch_size: int,+ dtype: torch.dtype,+ *,+ encoder_max_seq_len: int,+ decoder_max_seq_len: int,+ cache_expand_step: int = 200,+ ) -> None:+ self.attn.cache_expand_step = cache_expand_step+ self.attn.setup_cache(batch_size, dtype, max_seq_len=decoder_max_seq_len)++ def caches_are_setup(self) -> bool:+ return self.attn.kv_cache is not None++ def caches_are_enabled(self) -> bool:+ return self.attn.cache_enabled++ def reset_cache(self) -> None:+ self.attn.reset_cache()++ def forward(+ self,+ x: torch.Tensor,+ *,+ mask: Optional[torch.Tensor] = None,+ input_pos: Optional[torch.Tensor] = None,+ **kwargs,+ ) -> torch.Tensor:+ h = self.sa_norm(x)+ attn_out = self.attn(h, h, mask=mask, input_pos=input_pos)+ x = x.add_(attn_out)+ attn_out = None+ h = self.mlp_norm(x)+ mlp_out = self.mlp(h)+ x = x.add_(mlp_out)+ mlp_out = None+ return x+++class TransformerDecoder(nn.Module):+ def __init__(+ self,+ *,+ tok_embeddings: nn.Module,+ layers: nn.ModuleList,+ max_seq_len: int,+ num_heads: int,+ head_dim: int,+ norm: nn.Module,+ output: nn.Module,+ ) -> None:+ super().__init__()+ self.tok_embeddings = tok_embeddings+ self.layers = layers+ self.norm = norm+ self.output = output+ self.max_seq_len = max_seq_len+ self.num_heads = num_heads+ self.head_dim = head_dim+ self.decoder_max_cache_seq_len = None++ def setup_caches(+ self,+ batch_size: int,+ dtype: torch.dtype,+ *,+ encoder_max_seq_len: Optional[int] = None,+ decoder_max_seq_len: Optional[int] = None,+ cache_expand_step: int = 200,+ ) -> None:+ if decoder_max_seq_len is not None:+ self.decoder_max_cache_seq_len = decoder_max_seq_len+ else:+ self.decoder_max_cache_seq_len = self.max_seq_len++ for layer in self.layers:+ layer.setup_caches(+ batch_size,+ dtype,+ encoder_max_seq_len=encoder_max_seq_len or self.max_seq_len,+ decoder_max_seq_len=self.decoder_max_cache_seq_len,+ cache_expand_step=cache_expand_step,+ )++ def caches_are_setup(self) -> bool:+ return self.layers[0].caches_are_setup()++ def caches_are_enabled(self) -> bool:+ return self.layers[0].caches_are_enabled()++ def reset_caches(self) -> None:+ if not self.caches_are_enabled():+ raise RuntimeError("Key value caches are not setup.")+ for layer in self.layers:+ layer.reset_cache()++ def forward(+ self,+ x: torch.Tensor,+ *,+ mask: Optional[torch.Tensor] = None,+ input_pos: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ for layer in self.layers:+ x = layer(x, mask=mask, input_pos=input_pos)+ x = self.norm(x)+ return x+++def build_llama_decoder(+ *,+ vocab_size: int,+ num_layers: int,+ num_heads: int,+ num_kv_heads: int,+ embed_dim: int,+ max_seq_len: int,+ attn_dropout: float = 0.0,+ rope_base: int = 500_000,+ intermediate_dim: Optional[int] = None,+ norm_eps: float = 1e-5,+ scale_factor: int = 32,+) -> TransformerDecoder:+ head_dim = embed_dim // num_heads+ num_kv_heads = num_kv_heads if num_kv_heads else num_heads+ rope = Llama3ScaledRoPE(+ dim=head_dim,+ max_seq_len=max_seq_len,+ base=rope_base,+ scale_factor=scale_factor,+ )+ layers = []+ for _ in range(num_layers):+ self_attn = MultiHeadAttention(+ embed_dim=embed_dim,+ num_heads=num_heads,+ num_kv_heads=num_kv_heads,+ head_dim=head_dim,+ q_proj=nn.Linear(embed_dim, num_heads * head_dim, bias=False),+ k_proj=nn.Linear(embed_dim, num_kv_heads * head_dim, bias=False),+ v_proj=nn.Linear(embed_dim, num_kv_heads * head_dim, bias=False),+ output_proj=nn.Linear(embed_dim, embed_dim, bias=False),+ pos_embeddings=rope,+ max_seq_len=max_seq_len,+ attn_dropout=attn_dropout,+ )+ hidden_dim = (+ intermediate_dim+ if intermediate_dim is not None+ else scale_hidden_dim_for_mlp(embed_dim)+ )+ mlp = FeedForward(+ gate_proj=nn.Linear(embed_dim, hidden_dim, bias=False),+ down_proj=nn.Linear(hidden_dim, embed_dim, bias=False),+ up_proj=nn.Linear(embed_dim, hidden_dim, bias=False),+ )+ layer = TransformerSelfAttentionLayer(+ attn=self_attn,+ mlp=mlp,+ sa_norm=RMSNorm(dim=embed_dim, eps=norm_eps),+ mlp_norm=RMSNorm(dim=embed_dim, eps=norm_eps),+ )+ layers.append(layer)+ layers = nn.ModuleList(layers)++ tok_embeddings = nn.Identity()+ output_proj = nn.Identity()+ return TransformerDecoder(+ tok_embeddings=tok_embeddings,+ layers=layers,+ max_seq_len=max_seq_len,+ num_heads=num_heads,+ head_dim=head_dim,+ norm=RMSNorm(embed_dim, eps=norm_eps),+ output=output_proj,+ )diff --git a/models/TTS/HeartMula/heartmula/modeling_heartmula.py b/models/TTS/HeartMula/heartmula/modeling_heartmula.pynew file mode 100644index 0000000..0764206--- /dev/null+++ b/models/TTS/HeartMula/heartmula/modeling_heartmula.py@@ -0,0 +1,350 @@+import torch+import torch.nn as nn+from transformers.modeling_utils import PreTrainedModel++from .configuration_heartmula import HeartMuLaConfig+from .llama_blocks import Llama3ScaledRoPE, TransformerDecoder, build_llama_decoder+++def llama3_2_3B() -> TransformerDecoder:+ return build_llama_decoder(+ vocab_size=128_256,+ num_layers=28,+ num_heads=24,+ num_kv_heads=8,+ embed_dim=3072,+ max_seq_len=8192,+ intermediate_dim=8192,+ attn_dropout=0.0,+ norm_eps=1e-5,+ rope_base=500_000,+ scale_factor=32,+ )+++def llama3_2_300M() -> TransformerDecoder:+ return build_llama_decoder(+ vocab_size=128_256,+ num_layers=3,+ num_heads=8,+ num_kv_heads=4,+ embed_dim=3072,+ max_seq_len=2048,+ intermediate_dim=8192,+ attn_dropout=0.0,+ norm_eps=1e-5,+ rope_base=500_000,+ scale_factor=32,+ )+++def llama3_2_7B() -> TransformerDecoder:+ return build_llama_decoder(+ vocab_size=128_256,+ num_layers=32,+ num_heads=32,+ num_kv_heads=8,+ embed_dim=4096,+ max_seq_len=8192,+ intermediate_dim=14336,+ attn_dropout=0.0,+ norm_eps=1e-5,+ rope_base=500_000,+ scale_factor=32,+ )+++def llama3_2_400M() -> TransformerDecoder:+ return build_llama_decoder(+ vocab_size=128_256,+ num_layers=4,+ num_heads=8,+ num_kv_heads=4,+ embed_dim=3072,+ max_seq_len=2048,+ intermediate_dim=8192,+ attn_dropout=0.0,+ norm_eps=1e-5,+ rope_base=500_000,+ scale_factor=32,+ )+++FLAVORS = {+ "llama-3B": llama3_2_3B,+ "llama-300M": llama3_2_300M,+ "llama-7B": llama3_2_7B,+ "llama-400M": llama3_2_400M,+}+++def _prepare_transformer(model):+ if hasattr(model.tok_embeddings, "embedding_dim"):+ embed_dim = model.tok_embeddings.embedding_dim+ else:+ embed_dim = model.num_heads * model.head_dim+ model.tok_embeddings = nn.Identity()+ model.output = nn.Identity()+ return model, embed_dim+++def _create_causal_mask(seq_len: int, device: torch.device):+ return torch.tril(torch.ones(seq_len, seq_len, dtype=torch.bool, device=device))+++def _index_causal_mask(mask: torch.Tensor, input_pos: torch.Tensor):+ r = mask[input_pos, :]+ return r+++def _multinomial_sample_one_no_sync(probs):+ q = torch.empty_like(probs).exponential_(1)+ return torch.argmax(probs / q, dim=-1, keepdim=True).to(dtype=torch.int)+++def sample_topk(logits: torch.Tensor, topk: int, temperature: float):+ logits = logits / temperature++ filter_value = -float("Inf")+ indices_to_remove = logits < torch.topk(logits, topk)[0][..., -1, None]+ scores_processed = logits.masked_fill(indices_to_remove, filter_value)+ scores_processed = torch.nn.functional.log_softmax(scores_processed, dim=-1)+ probs = torch.nn.functional.softmax(scores_processed, dim=-1)++ sample_token = _multinomial_sample_one_no_sync(probs)+ return sample_token+++class HeartMuLa(PreTrainedModel):+ config_class = HeartMuLaConfig++ def __init__(self, config: HeartMuLaConfig):+ super().__init__(config)++ self.config = config+ self._interrupt_check = None++ self.backbone, backbone_dim = _prepare_transformer(+ FLAVORS[config.backbone_flavor]()+ )+ self.decoder, decoder_dim = _prepare_transformer(+ FLAVORS[config.decoder_flavor]()+ )+ self.text_embeddings = nn.Embedding(config.text_vocab_size, backbone_dim)+ self.audio_embeddings = nn.Embedding(+ config.audio_vocab_size * config.audio_num_codebooks, backbone_dim+ )+ self.unconditional_text_embedding = nn.Embedding(1, backbone_dim)++ self.projection = nn.Linear(backbone_dim, decoder_dim, bias=False)+ self.codebook0_head = nn.Linear(+ backbone_dim, config.audio_vocab_size, bias=False+ )+ self.audio_head = nn.Parameter(+ torch.empty(+ config.audio_num_codebooks - 1, decoder_dim, config.audio_vocab_size+ )+ )+ self.muq_linear = nn.Linear(config.muq_dim, backbone_dim)+ self.post_init()++ def setup_caches(self, max_batch_size: int):+ dtype = next(self.parameters()).dtype+ device = next(self.parameters()).device++ try:+ self.reset_caches()+ except RuntimeError:+ pass++ self.backbone.setup_caches(max_batch_size, dtype)+ self.decoder[0].setup_caches(+ max_batch_size,+ dtype,+ decoder_max_seq_len=self.config.audio_num_codebooks,+ )++ self.register_buffer(+ "backbone_causal_mask",+ _create_causal_mask(self.backbone.max_seq_len, device),+ )+ self.register_buffer(+ "decoder_causal_mask",+ _create_causal_mask(self.config.audio_num_codebooks, device),+ )++ def move_causal_masks(self, device: torch.device) -> None:+ non_blocking = device.type == "cuda"+ if hasattr(self, "backbone_causal_mask"):+ self.backbone_causal_mask = self.backbone_causal_mask.to(+ device, non_blocking=non_blocking+ )+ if hasattr(self, "decoder_causal_mask"):+ self.decoder_causal_mask = self.decoder_causal_mask.to(+ device, non_blocking=non_blocking+ )+ for module in self.modules():+ if isinstance(module, Llama3ScaledRoPE):+ module.ensure_device(device)++ def prepare_flash(self, device: torch.device, dtype: torch.dtype) -> None:+ for module in self.modules():+ if hasattr(module, "configure_flash"):+ module.configure_flash(device, dtype)++ def _check_interrupt(self) -> bool:+ if self._interrupt_check is None:+ return False+ return bool(self._interrupt_check())++ def generate_frame(+ self,+ tokens: torch.Tensor,+ tokens_mask: torch.Tensor,+ input_pos: torch.Tensor,+ temperature: float,+ topk: int,+ cfg_scale: float,+ continuous_segments: torch.Tensor = None,+ starts=None,+ ) -> torch.Tensor:+ if self._check_interrupt():+ return None+ b, _, _ = tokens.size()++ assert self.backbone.caches_are_enabled(), "backbone caches are not enabled"+ curr_backbone_mask = None++ uncond_mask = None+ if cfg_scale > 1.0 and b > 1:+ actual_b = b // 2+ uncond_mask = torch.cat(+ [+ torch.zeros(actual_b, dtype=torch.bool, device=tokens.device),+ torch.ones(actual_b, dtype=torch.bool, device=tokens.device),+ ]+ )++ embeds = self._embed_tokens(tokens, uncond_mask=uncond_mask)+ masked_embeds = embeds * tokens_mask.unsqueeze(-1)+ h = masked_embeds.sum(dim=2, dtype=embeds.dtype)+ if continuous_segments is not None:+ continuous_segments = self.muq_linear(continuous_segments)+ if uncond_mask is not None:+ uncond_embed = self.unconditional_text_embedding(+ torch.zeros(1, device=h.device, dtype=torch.long)+ )+ mask_expanded = uncond_mask.view(b, 1)+ mask_expanded = mask_expanded.expand_as(continuous_segments)+ continuous_segments = torch.where(+ mask_expanded, uncond_embed, continuous_segments+ )+ batch_indices = torch.arange(h.shape[0], device=h.device)+ h[batch_indices, starts] = continuous_segments+ h = self.backbone(h, input_pos=input_pos, mask=curr_backbone_mask)+ if self._check_interrupt():+ return None+ last_h = h[:, -1, :]+ c0_logits = self.codebook0_head(last_h)++ if cfg_scale > 1.0 and b > 1 and (b % 2 == 0):+ actual_b = b // 2+ cond_logits = c0_logits[:actual_b, :]+ uncond_logits = c0_logits[actual_b:, :]+ guided_logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale+ c0_sample = sample_topk(guided_logits, topk, temperature)+ c0_sample = c0_sample.repeat(2, 1)+ else:+ c0_sample = sample_topk(c0_logits, topk, temperature)++ c0_embed = self._embed_audio(0, c0_sample)++ self.decoder[0].reset_caches()+ curr_h = torch.cat([last_h.unsqueeze(1), c0_embed], dim=1)+ curr_sample_list = [c0_sample.clone()]+ curr_pos = (+ torch.arange(0, curr_h.size(1), device=curr_h.device)+ .unsqueeze(0)+ .repeat(curr_h.size(0), 1)+ )+ curr_h = curr_h.to(embeds.dtype)+ for i in range(1, self.config.audio_num_codebooks):+ if self._check_interrupt():+ return None+ curr_decoder_mask = None+ decoder_h = self.decoder[0](+ self.projection(curr_h), input_pos=curr_pos, mask=curr_decoder_mask+ )+ if self._check_interrupt():+ return None+ head_weight = self.audio_head[i - 1]+ ci_logits = torch.mm(decoder_h[:, -1, :].to(head_weight.dtype), head_weight)+ if cfg_scale > 1.0 and b > 1 and (b % 2 == 0):+ actual_b = b // 2+ cond_ci = ci_logits[:actual_b, :]+ uncond_ci = ci_logits[actual_b:, :]+ guided_ci = uncond_ci + (cond_ci - uncond_ci) * cfg_scale++ ci_sample = sample_topk(guided_ci, topk, temperature)+ ci_sample = ci_sample.repeat(2, 1)+ else:+ ci_sample = sample_topk(ci_logits, topk, temperature)+ ci_embed = self._embed_audio(i, ci_sample)+ curr_h = ci_embed+ curr_sample_list.append(ci_sample)+ curr_pos = curr_pos[:, -1:] + 1++ curr_sample = torch.cat(curr_sample_list, dim=1)++ return curr_sample++ def reset_caches(self):+ self.backbone.reset_caches()+ self.decoder[0].reset_caches()++ def release_caches(self):+ # Drop KV cache tensors to free memory between generations.+ for module in self.backbone.modules():+ if hasattr(module, "kv_cache"):+ module.kv_cache = None+ if hasattr(module, "cache_enabled"):+ module.cache_enabled = False+ if hasattr(module, "reset_flash"):+ module.reset_flash()+ for module in self.decoder[0].modules():+ if hasattr(module, "kv_cache"):+ module.kv_cache = None+ if hasattr(module, "cache_enabled"):+ module.cache_enabled = False+ if hasattr(module, "reset_flash"):+ module.reset_flash()++ def _embed_audio(self, codebook: int, tokens: torch.Tensor) -> torch.Tensor:+ return self.audio_embeddings(tokens + codebook * self.config.audio_vocab_size)++ def _embed_tokens(+ self, tokens: torch.Tensor, uncond_mask: torch.Tensor | None+ ) -> torch.Tensor:+ b, _, _ = tokens.size()+ text_tokens = tokens[:, :, -1]+ text_embeds = self.text_embeddings(text_tokens)++ if uncond_mask is not None:+ uncond_text_embed = self.unconditional_text_embedding(+ torch.zeros(1, device=text_embeds.device, dtype=torch.long)+ )+ mask_expanded = uncond_mask.view(b, 1, 1)+ mask_expanded = mask_expanded.expand_as(text_embeds)+ text_embeds = torch.where(mask_expanded, uncond_text_embed, text_embeds)++ text_embeds = text_embeds.unsqueeze(-2)++ audio_tokens = tokens[:, :, :-1]+ audio_tokens = audio_tokens + (+ self.config.audio_vocab_size+ * torch.arange(self.config.audio_num_codebooks, device=audio_tokens.device)+ )+ audio_embeds = self.audio_embeddings(audio_tokens.view(-1)).reshape(+ tokens.size(0), tokens.size(1), self.config.audio_num_codebooks, -1+ )+ return torch.cat([audio_embeds, text_embeds], dim=-2)diff --git a/models/TTS/HeartMula/pipeline.py b/models/TTS/HeartMula/pipeline.pynew file mode 100644index 0000000..54b2b7c--- /dev/null+++ b/models/TTS/HeartMula/pipeline.py@@ -0,0 +1,501 @@+from __future__ import annotations++import os+import json+import random+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Dict, Optional+import contextlib++import numpy as np+import torch+from tokenizers import Tokenizer+from tqdm import tqdm+from shared.utils import files_locator as fl++from .heartcodec.configuration_heartcodec import HeartCodecConfig+from .heartcodec.modeling_heartcodec import HeartCodec+from .heartmula.configuration_heartmula import HeartMuLaConfig+from .heartmula.modeling_heartmula import HeartMuLa+++def _resolve_paths(+ pretrained_path: Path, version: str, heartmula_weights_path: Optional[str] = None+):+ config_path = ( Path(__file__).resolve().parent / "config" / f"heartmula_{version}.json" )++ heartcodec_dir = fl.locate_folder("HeartMula")+ tokenizer_path = fl.locate_file( os.path.join("HeartMula", "tokenizer.json"))+ gen_config_path = fl.locate_file( os.path.join("HeartMula", "gen_config.json"))++ weights_path = heartmula_weights_path++ return (+ weights_path,+ Path(config_path),+ Path(heartcodec_dir),+ Path(tokenizer_path),+ Path(gen_config_path),+ )+++@dataclass+class HeartMuLaGenConfig:+ text_bos_id: int = 128000+ text_eos_id: int = 128001+ audio_eos_id: int = 8193+ empty_id: int = 0++ @classmethod+ def from_file(cls, path: str):+ with open(path, encoding="utf-8") as fp:+ data = fp.read()+ import json++ return cls(**json.loads(data))+++def _seed_everything(seed: int) -> None:+ random.seed(seed)+ np.random.seed(seed)+ torch.manual_seed(seed)+ torch.cuda.manual_seed_all(seed)+ torch.backends.cudnn.deterministic = True+ torch.backends.cudnn.benchmark = False+++class HeartMuLaPipeline:+ def __init__(+ self,+ ckpt_root: Optional[Path] = None,+ device: Optional[torch.device] = None,+ version: str = "3B",+ heartmula_dtype: Optional[torch.dtype] = None,+ heartcodec_dtype: Optional[torch.dtype] = None,+ heartmula_weights_path: Optional[str] = None,+ cfg_scale: float = 1.5,+ topk: int = 50,+ max_audio_length_ms: int = 120000,+ codec_steps: int = 10,+ codec_guidance_scale: float = 1.25,+ VAE_dtype = torch.float32,+ ):+ self.device = torch.device("cpu")+ self.mula_device = self.device+ self.codec_device = self.device+ self.mula_dtype = None+ self.codec_dtype = None++ self.cfg_scale = cfg_scale+ self.topk = topk+ self.max_audio_length_ms = max_audio_length_ms+ self.codec_steps = codec_steps+ self.codec_guidance_scale = codec_guidance_scale+ self.heartmula_weights_path = heartmula_weights_path+ self.VAE_dtype = VAE_dtype++ self.ckpt_root = Path(ckpt_root) if ckpt_root is not None else Path(+ fl.get_download_location()+ )+ self.version = version+ self._interrupt = False++ self._parallel_number = 8 + 1+ self._muq_dim = 512++ self._load_models()++ def _load_models(self):+ (+ mula_weights_path,+ mula_config_path,+ codec_path,+ tokenizer_path,+ gen_config_path,+ ) = _resolve_paths(+ self.ckpt_root,+ self.version,+ heartmula_weights_path=self.heartmula_weights_path,+ )+ from accelerate import init_empty_weights+ from mmgp import offload+ self.tokenizer = Tokenizer.from_file(str(tokenizer_path))+ self.gen_config = HeartMuLaGenConfig.from_file(str(gen_config_path))+ with open(mula_config_path, encoding="utf-8") as fp:+ mula_config = HeartMuLaConfig(**json.load(fp))++ with init_empty_weights():+ self.mula = HeartMuLa(mula_config)+ offload.load_model_data(+ self.mula,+ str(mula_weights_path),+ default_dtype=None,+ writable_tensors=False,+ )++ decoder = self.mula.decoder+ delattr(self.mula, "decoder")+ self.mula.decoder = [decoder]++ if hasattr(self.mula, "_interrupt_check"):+ self.mula._interrupt_check = self._abort_requested+ self.model = self.mula+ self.mula.eval()+ first_param = next(self.mula.parameters(), None)+ if first_param is not None:+ self.mula_dtype = first_param.dtype+ codec_weights_path = fl.locate_file(+ os.path.join("HeartMula", "HeartMula_codec.safetensors"), error_if_none=False+ )+ codec_weights_path = (+ Path(codec_weights_path)+ if codec_weights_path+ else Path(codec_path) / "HeartMula_codec.safetensors"+ )+ if not codec_weights_path.is_file():+ raise FileNotFoundError(+ f"Expected HeartCodec weights at {codec_weights_path} but not found."+ )+ codec_config_path = fl.locate_file(+ os.path.join("HeartMula", "codec_config.json"), error_if_none=False+ )+ codec_config_path = (+ Path(codec_config_path)+ if codec_config_path+ else Path(codec_path) / "codec_config.json"+ )+ if not codec_config_path.is_file():+ raise FileNotFoundError(+ f"Expected HeartCodec config at {codec_config_path} but not found."+ )+ with open(codec_config_path, encoding="utf-8") as fp:+ codec_config = HeartCodecConfig(**json.load(fp))+ with init_empty_weights():+ self.codec = HeartCodec(codec_config)+ self.codec._model_dtype = self.VAE_dtype+ offload.load_model_data(+ self.codec,+ str(codec_weights_path),+ default_dtype=self.VAE_dtype,+ writable_tensors=False,+ )+ self.codec.eval()+ first_param = next(self.codec.parameters(), None)+ if first_param is not None:+ self.codec_dtype = first_param.dtype++ self.sample_rate = getattr(self.codec, "sample_rate", 48000)++ def _get_mula_device(self) -> torch.device:+ if self.mula is None:+ return self.device+ text_embed = getattr(self.mula, "text_embeddings", None)+ if text_embed is not None and hasattr(text_embed, "weight"):+ return text_embed.weight.device+ first_param = next(self.mula.parameters(), None)+ return first_param.device if first_param is not None else self.device++ def _ensure_mula_loaded(self) -> None:+ if self.mula is None:+ return+ mm_manager = getattr(self.mula, "_mm_manager", None)+ mm_id = getattr(self.mula, "_mm_id", None)+ if mm_manager is None or mm_id is None:+ return+ mm_manager.ensure_model_loaded(mm_id)++ def _move_model_inputs(+ self, model_inputs: Dict[str, Any], device: torch.device+ ) -> Dict[str, Any]:+ non_blocking = device.type == "cuda"+ for key, value in model_inputs.items():+ if torch.is_tensor(value) and value.device != device:+ model_inputs[key] = value.to(device, non_blocking=non_blocking)+ return model_inputs++ def _abort_requested(self) -> bool:+ return bool(self._interrupt)++ def _read_text_or_file(self, value: str, label: str) -> str:+ if os.path.isfile(value):+ with open(value, encoding="utf-8") as fp:+ return fp.read()+ if not isinstance(value, str):+ raise ValueError(f"{label} must be a string, got {type(value)}")+ return value++ def _build_model_inputs(+ self, lyrics: str, tags: str, cfg_scale: float+ ) -> Dict[str, Any]:+ tags = tags.lower()+ if not tags.startswith("<tag>"):+ tags = f"<tag>{tags}"+ if not tags.endswith("</tag>"):+ tags = f"{tags}</tag>"++ tags_ids = self.tokenizer.encode(tags).ids+ if tags_ids[0] != self.gen_config.text_bos_id:+ tags_ids = [self.gen_config.text_bos_id] + tags_ids+ if tags_ids[-1] != self.gen_config.text_eos_id:+ tags_ids = tags_ids + [self.gen_config.text_eos_id]++ muq_embed = torch.zeros([self._muq_dim], dtype=self.mula_dtype)+ muq_idx = len(tags_ids)++ lyrics = lyrics.lower()+ lyrics_ids = self.tokenizer.encode(lyrics).ids+ if lyrics_ids[0] != self.gen_config.text_bos_id:+ lyrics_ids = [self.gen_config.text_bos_id] + lyrics_ids+ if lyrics_ids[-1] != self.gen_config.text_eos_id:+ lyrics_ids = lyrics_ids + [self.gen_config.text_eos_id]++ prompt_len = len(tags_ids) + 1 + len(lyrics_ids)++ tokens = torch.zeros([prompt_len, self._parallel_number], dtype=torch.long)+ tokens[: len(tags_ids), -1] = torch.tensor(tags_ids)+ tokens[len(tags_ids) + 1 :, -1] = torch.tensor(lyrics_ids)++ tokens_mask = torch.zeros_like(tokens, dtype=torch.bool)+ tokens_mask[:, -1] = True++ bs_size = 2 if cfg_scale != 1.0 else 1+ muq_idx_tensor = torch.full((bs_size,), muq_idx, dtype=torch.long)++ def _cfg_cat(tensor: torch.Tensor, cfg_scale: float):+ tensor = tensor.unsqueeze(0)+ if cfg_scale != 1.0:+ tensor = torch.cat([tensor, tensor], dim=0)+ return tensor++ return {+ "tokens": _cfg_cat(tokens, cfg_scale),+ "tokens_mask": _cfg_cat(tokens_mask, cfg_scale),+ "muq_embed": _cfg_cat(muq_embed, cfg_scale),+ "muq_idx": muq_idx_tensor,+ "pos": _cfg_cat(torch.arange(prompt_len, dtype=torch.long), cfg_scale),+ }++ def _forward(+ self,+ model_inputs: Dict[str, Any],+ max_audio_length_ms: int,+ temperature: float,+ topk: int,+ cfg_scale: float,+ callback=None,+ ):+ prompt_tokens = model_inputs["tokens"]+ mula_device = prompt_tokens.device+ prompt_tokens_mask = model_inputs["tokens_mask"]+ continuous_segment = model_inputs["muq_embed"]+ starts = model_inputs["muq_idx"]+ prompt_pos = model_inputs["pos"]+ frames = []++ bs_size = 2 if cfg_scale != 1.0 else 1+ self.mula.setup_caches(bs_size)+ self.mula.move_causal_masks(mula_device)+ flash_dtype = self.mula_dtype+ if flash_dtype is None:+ first_param = next(self.mula.parameters(), None)+ if first_param is not None:+ flash_dtype = first_param.dtype+ if flash_dtype is not None:+ self.mula.prepare_flash(mula_device, flash_dtype)+ if self._abort_requested():+ return None+ try:+ curr_token = self.mula.generate_frame(+ tokens=prompt_tokens,+ tokens_mask=prompt_tokens_mask,+ input_pos=prompt_pos,+ temperature=temperature,+ topk=topk,+ cfg_scale=cfg_scale,+ continuous_segments=continuous_segment,+ starts=starts,+ )+ if curr_token is None:+ return None+ frames.append(curr_token[0:1,])++ def _pad_audio_token(token: torch.Tensor):+ padded_token = (+ torch.ones(+ (token.shape[0], self._parallel_number),+ device=token.device,+ dtype=torch.long,+ )+ * self.gen_config.empty_id+ )+ padded_token[:, :-1] = token+ padded_token = padded_token.unsqueeze(1)+ padded_token_mask = torch.ones_like(+ padded_token, device=token.device, dtype=torch.bool+ )+ padded_token_mask[..., -1] = False+ return padded_token, padded_token_mask++ frame_duration_ms = 80 # 80 ms per audio token frame.+ max_audio_frames = max_audio_length_ms // frame_duration_ms+ progress_total_seconds = max(1, max_audio_length_ms // 1000)+ if callback is not None:+ callback(+ step_idx=-1,+ override_num_inference_steps=progress_total_seconds,+ denoising_extra=f"0s/{progress_total_seconds}s",+ progress_unit="seconds",+ )++ for i in tqdm(range(max_audio_frames)):+ if self._abort_requested():+ return None+ curr_token, curr_token_mask = _pad_audio_token(curr_token)+ curr_token = self.mula.generate_frame(+ tokens=curr_token,+ tokens_mask=curr_token_mask,+ input_pos=prompt_pos[..., -1:] + i + 1,+ temperature=temperature,+ topk=topk,+ cfg_scale=cfg_scale,+ continuous_segments=None,+ starts=None,+ )+ if curr_token is None:+ return None+ if torch.any(curr_token[0:1, :] >= self.gen_config.audio_eos_id):+ break+ frames.append(curr_token[0:1,])+ if i % 10 == 0 and callback is not None:+ generated_ms = len(frames) * frame_duration_ms+ generated_seconds_int = min(+ progress_total_seconds,+ generated_ms // 1000,+ )+ callback(+ step_idx=generated_seconds_int - 1,+ override_num_inference_steps=progress_total_seconds,+ denoising_extra=(+ f"{generated_seconds_int}s/{progress_total_seconds}s"+ ),+ progress_unit="second",+ )+ frames = torch.stack(frames).permute(1, 2, 0).squeeze(0)+ return {"frames": frames}+ finally:+ # Drop KV cache tensors as soon as we're done with generation.+ try:+ self.mula.move_causal_masks(torch.device("cpu"))+ self.mula.release_caches()+ torch.cuda.empty_cache()+ except Exception:+ pass++ def _decode(self, frames: torch.Tensor, callback=None):+ if self._abort_requested():+ return None+ wav = self.codec.detokenize(+ frames.to(self.codec_device),+ num_steps=self.codec_steps,+ guidance_scale=self.codec_guidance_scale,+ disable_progress=False,+ abort_signal=self._abort_requested,+ )+ if wav is None:+ return None+ if callback is not None:+ callback(step_idx=-1, force_refresh=True)+ return wav++ def generate(+ self,+ input_prompt: str,+ model_mode: Optional[str],+ audio_guide: Optional[str],+ *,+ alt_prompt: Optional[str] = None,+ temperature: float = 1.0,+ **kwargs,+ ):+ self._interrupt = False+ seed = kwargs.get("seed")+ if seed is not None:+ try:+ seed = int(seed)+ except (TypeError, ValueError):+ seed = None+ if seed is not None and seed >= 0:+ _seed_everything(seed)+ if self.mula is not None:+ self.mula_device = torch.device("cpu")+ text_embed = getattr(self.mula, "text_embeddings", None)+ if text_embed is not None and hasattr(text_embed, "weight"):+ self.mula_dtype = text_embed.weight.dtype+ else:+ first_param = next(self.mula.parameters(), None)+ if first_param is not None:+ self.mula_dtype = first_param.dtype+ if self.codec is not None:+ first_param = next(self.codec.parameters(), None)+ if first_param is not None:+ self.codec_device = first_param.device+ self.codec_dtype = first_param.dtype+ if not input_prompt or not input_prompt.strip():+ raise ValueError("Lyrics prompt cannot be empty for HeartMuLa generation.")+ if alt_prompt is None or not str(alt_prompt).strip():+ raise ValueError("Keywords prompt cannot be empty for HeartMuLa generation.")+ if audio_guide or kwargs.get("audio_guide2"):+ raise ValueError("HeartMuLa does not support reference audio yet.")++ lyrics = self._read_text_or_file(input_prompt, "Lyrics prompt")+ tags = self._read_text_or_file(str(alt_prompt), "Keywords prompt")+ if not lyrics.strip():+ raise ValueError("Lyrics prompt cannot be empty for HeartMuLa generation.")+ if not tags.strip():+ raise ValueError("Keywords prompt cannot be empty for HeartMuLa generation.")++ cfg_scale = float(kwargs.get("cfg_scale", self.cfg_scale))+ topk = int(kwargs.get("topk", self.topk))+ duration_seconds = kwargs.get("duration_seconds", None)+ if duration_seconds is not None:+ try:+ duration_seconds = float(duration_seconds)+ except (TypeError, ValueError):+ duration_seconds = None+ if duration_seconds is not None and duration_seconds > 0:+ max_audio_length_ms = int(round(duration_seconds * 1000.0))+ else:+ max_audio_length_ms = int(+ kwargs.get("max_audio_length_ms", self.max_audio_length_ms)+ )+ callback = kwargs.get("callback")++ model_inputs = self._build_model_inputs(lyrics, tags, cfg_scale=cfg_scale)+ self._ensure_mula_loaded()+ target_device = self._get_mula_device()+ if target_device.type != "cuda" and torch.cuda.is_available():+ target_device = torch.device("cuda")+ model_inputs = self._move_model_inputs(model_inputs, target_device)+ outputs = self._forward(+ model_inputs,+ max_audio_length_ms=max_audio_length_ms,+ temperature=float(temperature),+ topk=topk,+ cfg_scale=cfg_scale,+ callback=callback,+ )+ if outputs is None:+ return None+ wav = self._decode(outputs["frames"], callback=callback)+ if wav is None:+ return None+ return {"x": wav, "audio_sampling_rate": self.sample_rate}++ def release(self) -> None:+ if hasattr(self, "mula") and self.mula is not None:+ self.mula = None+ if hasattr(self, "model"):+ self.model = None+ if hasattr(self, "codec") and self.codec is not None:+ self.codec = Nonediff --git a/models/TTS/__init__.py b/models/TTS/__init__.pynew file mode 100644index 0000000..11fb3fe--- /dev/null+++ b/models/TTS/__init__.py@@ -0,0 +1 @@+from .tts_handler import family_handlerdiff --git a/models/chatterbox/__init__.py b/models/TTS/chatterbox/__init__.pysimilarity index 100%rename from models/chatterbox/__init__.pyrename to models/TTS/chatterbox/__init__.pydiff --git a/models/chatterbox/models/__init__.py b/models/TTS/chatterbox/models/__init__.pysimilarity index 100%rename from models/chatterbox/models/__init__.pyrename to models/TTS/chatterbox/models/__init__.pydiff --git a/models/chatterbox/models/s3gen/__init__.py b/models/TTS/chatterbox/models/s3gen/__init__.pysimilarity index 100%rename from models/chatterbox/models/s3gen/__init__.pyrename to models/TTS/chatterbox/models/s3gen/__init__.pydiff --git a/models/chatterbox/models/s3gen/configs.py b/models/TTS/chatterbox/models/s3gen/configs.pysimilarity index 100%rename from models/chatterbox/models/s3gen/configs.pyrename to models/TTS/chatterbox/models/s3gen/configs.pydiff --git a/models/chatterbox/models/s3gen/const.py b/models/TTS/chatterbox/models/s3gen/const.pysimilarity index 100%rename from models/chatterbox/models/s3gen/const.pyrename to models/TTS/chatterbox/models/s3gen/const.pydiff --git a/models/chatterbox/models/s3gen/decoder.py b/models/TTS/chatterbox/models/s3gen/decoder.pysimilarity index 100%rename from models/chatterbox/models/s3gen/decoder.pyrename to models/TTS/chatterbox/models/s3gen/decoder.pydiff --git a/models/chatterbox/models/s3gen/f0_predictor.py b/models/TTS/chatterbox/models/s3gen/f0_predictor.pysimilarity index 100%rename from models/chatterbox/models/s3gen/f0_predictor.pyrename to models/TTS/chatterbox/models/s3gen/f0_predictor.pydiff --git a/models/chatterbox/models/s3gen/flow.py b/models/TTS/chatterbox/models/s3gen/flow.pysimilarity index 100%rename from models/chatterbox/models/s3gen/flow.pyrename to models/TTS/chatterbox/models/s3gen/flow.pydiff --git a/models/chatterbox/models/s3gen/flow_matching.py b/models/TTS/chatterbox/models/s3gen/flow_matching.pysimilarity index 100%rename from models/chatterbox/models/s3gen/flow_matching.pyrename to models/TTS/chatterbox/models/s3gen/flow_matching.pydiff --git a/models/chatterbox/models/s3gen/hifigan.py b/models/TTS/chatterbox/models/s3gen/hifigan.pysimilarity index 100%rename from models/chatterbox/models/s3gen/hifigan.pyrename to models/TTS/chatterbox/models/s3gen/hifigan.pydiff --git a/models/chatterbox/models/s3gen/matcha/decoder.py b/models/TTS/chatterbox/models/s3gen/matcha/decoder.pysimilarity index 100%rename from models/chatterbox/models/s3gen/matcha/decoder.pyrename to models/TTS/chatterbox/models/s3gen/matcha/decoder.pydiff --git a/models/chatterbox/models/s3gen/matcha/flow_matching.py b/models/TTS/chatterbox/models/s3gen/matcha/flow_matching.pysimilarity index 100%rename from models/chatterbox/models/s3gen/matcha/flow_matching.pyrename to models/TTS/chatterbox/models/s3gen/matcha/flow_matching.pydiff --git a/models/chatterbox/models/s3gen/matcha/text_encoder.py b/models/TTS/chatterbox/models/s3gen/matcha/text_encoder.pysimilarity index 100%rename from models/chatterbox/models/s3gen/matcha/text_encoder.pyrename to models/TTS/chatterbox/models/s3gen/matcha/text_encoder.pydiff --git a/models/chatterbox/models/s3gen/matcha/transformer.py b/models/TTS/chatterbox/models/s3gen/matcha/transformer.pysimilarity index 100%rename from models/chatterbox/models/s3gen/matcha/transformer.pyrename to models/TTS/chatterbox/models/s3gen/matcha/transformer.pydiff --git a/models/chatterbox/models/s3gen/s3gen.py b/models/TTS/chatterbox/models/s3gen/s3gen.pysimilarity index 100%rename from models/chatterbox/models/s3gen/s3gen.pyrename to models/TTS/chatterbox/models/s3gen/s3gen.pydiff --git a/models/chatterbox/models/s3gen/transformer/__init__.py b/models/TTS/chatterbox/models/s3gen/transformer/__init__.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/__init__.pyrename to models/TTS/chatterbox/models/s3gen/transformer/__init__.pydiff --git a/models/chatterbox/models/s3gen/transformer/activation.py b/models/TTS/chatterbox/models/s3gen/transformer/activation.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/activation.pyrename to models/TTS/chatterbox/models/s3gen/transformer/activation.pydiff --git a/models/chatterbox/models/s3gen/transformer/attention.py b/models/TTS/chatterbox/models/s3gen/transformer/attention.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/attention.pyrename to models/TTS/chatterbox/models/s3gen/transformer/attention.pydiff --git a/models/chatterbox/models/s3gen/transformer/convolution.py b/models/TTS/chatterbox/models/s3gen/transformer/convolution.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/convolution.pyrename to models/TTS/chatterbox/models/s3gen/transformer/convolution.pydiff --git a/models/chatterbox/models/s3gen/transformer/embedding.py b/models/TTS/chatterbox/models/s3gen/transformer/embedding.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/embedding.pyrename to models/TTS/chatterbox/models/s3gen/transformer/embedding.pydiff --git a/models/chatterbox/models/s3gen/transformer/encoder_layer.py b/models/TTS/chatterbox/models/s3gen/transformer/encoder_layer.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/encoder_layer.pyrename to models/TTS/chatterbox/models/s3gen/transformer/encoder_layer.pydiff --git a/models/chatterbox/models/s3gen/transformer/positionwise_feed_forward.py b/models/TTS/chatterbox/models/s3gen/transformer/positionwise_feed_forward.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/positionwise_feed_forward.pyrename to models/TTS/chatterbox/models/s3gen/transformer/positionwise_feed_forward.pydiff --git a/models/chatterbox/models/s3gen/transformer/subsampling.py b/models/TTS/chatterbox/models/s3gen/transformer/subsampling.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/subsampling.pyrename to models/TTS/chatterbox/models/s3gen/transformer/subsampling.pydiff --git a/models/chatterbox/models/s3gen/transformer/upsample_encoder.py b/models/TTS/chatterbox/models/s3gen/transformer/upsample_encoder.pysimilarity index 100%rename from models/chatterbox/models/s3gen/transformer/upsample_encoder.pyrename to models/TTS/chatterbox/models/s3gen/transformer/upsample_encoder.pydiff --git a/models/chatterbox/models/s3gen/utils/class_utils.py b/models/TTS/chatterbox/models/s3gen/utils/class_utils.pysimilarity index 100%rename from models/chatterbox/models/s3gen/utils/class_utils.pyrename to models/TTS/chatterbox/models/s3gen/utils/class_utils.pydiff --git a/models/chatterbox/models/s3gen/utils/mask.py b/models/TTS/chatterbox/models/s3gen/utils/mask.pysimilarity index 100%rename from models/chatterbox/models/s3gen/utils/mask.pyrename to models/TTS/chatterbox/models/s3gen/utils/mask.pydiff --git a/models/chatterbox/models/s3gen/utils/mel.py b/models/TTS/chatterbox/models/s3gen/utils/mel.pysimilarity index 100%rename from models/chatterbox/models/s3gen/utils/mel.pyrename to models/TTS/chatterbox/models/s3gen/utils/mel.pydiff --git a/models/chatterbox/models/s3gen/xvector.py b/models/TTS/chatterbox/models/s3gen/xvector.pysimilarity index 100%rename from models/chatterbox/models/s3gen/xvector.pyrename to models/TTS/chatterbox/models/s3gen/xvector.pydiff --git a/models/chatterbox/models/s3tokenizer/__init__.py b/models/TTS/chatterbox/models/s3tokenizer/__init__.pysimilarity index 100%rename from models/chatterbox/models/s3tokenizer/__init__.pyrename to models/TTS/chatterbox/models/s3tokenizer/__init__.pydiff --git a/models/chatterbox/models/s3tokenizer/s3tokenizer.py b/models/TTS/chatterbox/models/s3tokenizer/s3tokenizer.pysimilarity index 100%rename from models/chatterbox/models/s3tokenizer/s3tokenizer.pyrename to models/TTS/chatterbox/models/s3tokenizer/s3tokenizer.pydiff --git a/models/chatterbox/models/t3/__init__.py b/models/TTS/chatterbox/models/t3/__init__.pysimilarity index 100%rename from models/chatterbox/models/t3/__init__.pyrename to models/TTS/chatterbox/models/t3/__init__.pydiff --git a/models/chatterbox/models/t3/inference/alignment_stream_analyzer.py b/models/TTS/chatterbox/models/t3/inference/alignment_stream_analyzer.pysimilarity index 100%rename from models/chatterbox/models/t3/inference/alignment_stream_analyzer.pyrename to models/TTS/chatterbox/models/t3/inference/alignment_stream_analyzer.pydiff --git a/models/chatterbox/models/t3/inference/t3_hf_backend.py b/models/TTS/chatterbox/models/t3/inference/t3_hf_backend.pysimilarity index 100%rename from models/chatterbox/models/t3/inference/t3_hf_backend.pyrename to models/TTS/chatterbox/models/t3/inference/t3_hf_backend.pydiff --git a/models/chatterbox/models/t3/llama_configs.py b/models/TTS/chatterbox/models/t3/llama_configs.pysimilarity index 100%rename from models/chatterbox/models/t3/llama_configs.pyrename to models/TTS/chatterbox/models/t3/llama_configs.pydiff --git a/models/chatterbox/models/t3/modules/cond_enc.py b/models/TTS/chatterbox/models/t3/modules/cond_enc.pysimilarity index 100%rename from models/chatterbox/models/t3/modules/cond_enc.pyrename to models/TTS/chatterbox/models/t3/modules/cond_enc.pydiff --git a/models/chatterbox/models/t3/modules/learned_pos_emb.py b/models/TTS/chatterbox/models/t3/modules/learned_pos_emb.pysimilarity index 100%rename from models/chatterbox/models/t3/modules/learned_pos_emb.pyrename to models/TTS/chatterbox/models/t3/modules/learned_pos_emb.pydiff --git a/models/chatterbox/models/t3/modules/perceiver.py b/models/TTS/chatterbox/models/t3/modules/perceiver.pysimilarity index 100%rename from models/chatterbox/models/t3/modules/perceiver.pyrename to models/TTS/chatterbox/models/t3/modules/perceiver.pydiff --git a/models/chatterbox/models/t3/modules/t3_config.py b/models/TTS/chatterbox/models/t3/modules/t3_config.pysimilarity index 100%rename from models/chatterbox/models/t3/modules/t3_config.pyrename to models/TTS/chatterbox/models/t3/modules/t3_config.pydiff --git a/models/chatterbox/models/t3/t3.py b/models/TTS/chatterbox/models/t3/t3.pysimilarity index 100%rename from models/chatterbox/models/t3/t3.pyrename to models/TTS/chatterbox/models/t3/t3.pydiff --git a/models/chatterbox/models/tokenizers/__init__.py b/models/TTS/chatterbox/models/tokenizers/__init__.pysimilarity index 100%rename from models/chatterbox/models/tokenizers/__init__.pyrename to models/TTS/chatterbox/models/tokenizers/__init__.pydiff --git a/models/chatterbox/models/tokenizers/tokenizer.py b/models/TTS/chatterbox/models/tokenizers/tokenizer.pysimilarity index 100%rename from models/chatterbox/models/tokenizers/tokenizer.pyrename to models/TTS/chatterbox/models/tokenizers/tokenizer.pydiff --git a/models/chatterbox/models/utils.py b/models/TTS/chatterbox/models/utils.pysimilarity index 100%rename from models/chatterbox/models/utils.pyrename to models/TTS/chatterbox/models/utils.pydiff --git a/models/chatterbox/models/voice_encoder/__init__.py b/models/TTS/chatterbox/models/voice_encoder/__init__.pysimilarity index 100%rename from models/chatterbox/models/voice_encoder/__init__.pyrename to models/TTS/chatterbox/models/voice_encoder/__init__.pydiff --git a/models/chatterbox/models/voice_encoder/config.py b/models/TTS/chatterbox/models/voice_encoder/config.pysimilarity index 100%rename from models/chatterbox/models/voice_encoder/config.pyrename to models/TTS/chatterbox/models/voice_encoder/config.pydiff --git a/models/chatterbox/models/voice_encoder/melspec.py b/models/TTS/chatterbox/models/voice_encoder/melspec.pysimilarity index 100%rename from models/chatterbox/models/voice_encoder/melspec.pyrename to models/TTS/chatterbox/models/voice_encoder/melspec.pydiff --git a/models/chatterbox/models/voice_encoder/voice_encoder.py b/models/TTS/chatterbox/models/voice_encoder/voice_encoder.pysimilarity index 100%rename from models/chatterbox/models/voice_encoder/voice_encoder.pyrename to models/TTS/chatterbox/models/voice_encoder/voice_encoder.pydiff --git a/models/chatterbox/mtl_tts.py b/models/TTS/chatterbox/mtl_tts.pysimilarity index 100%rename from models/chatterbox/mtl_tts.pyrename to models/TTS/chatterbox/mtl_tts.pydiff --git a/models/chatterbox/pipeline.py b/models/TTS/chatterbox/pipeline.pysimilarity index 100%rename from models/chatterbox/pipeline.pyrename to models/TTS/chatterbox/pipeline.pydiff --git a/models/chatterbox/tts.py b/models/TTS/chatterbox/tts.pysimilarity index 100%rename from models/chatterbox/tts.pyrename to models/TTS/chatterbox/tts.pydiff --git a/models/chatterbox/vc.py b/models/TTS/chatterbox/vc.pysimilarity index 100%rename from models/chatterbox/vc.pyrename to models/TTS/chatterbox/vc.pydiff --git a/models/TTS/tts_handler.py b/models/TTS/tts_handler.pynew file mode 100644index 0000000..bf84bb1--- /dev/null+++ b/models/TTS/tts_handler.py@@ -0,0 +1,537 @@+import os++import gradio as gr+import torch++from shared.utils import files_locator as fl+++_FALLBACK_SUPPORTED_LANGUAGES = {+ "ar": "Arabic",+ "da": "Danish",+ "de": "German",+ "el": "Greek",+ "en": "English",+ "es": "Spanish",+ "fi": "Finnish",+ "fr": "French",+ "he": "Hebrew",+ "hi": "Hindi",+ "it": "Italian",+ "ja": "Japanese",+ "ko": "Korean",+ "ms": "Malay",+ "nl": "Dutch",+ "no": "Norwegian",+ "pl": "Polish",+ "pt": "Portuguese",+ "ru": "Russian",+ "sv": "Swedish",+ "sw": "Swahili",+ "tr": "Turkish",+ "zh": "Chinese",+}+++def _get_supported_languages() -> dict:+ try:+ from .chatterbox.mtl_tts import SUPPORTED_LANGUAGES+ except Exception:+ return _FALLBACK_SUPPORTED_LANGUAGES+ return SUPPORTED_LANGUAGES+++def _get_language_choices() -> list[tuple[str, str]]:+ languages = _get_supported_languages()+ return [+ (f"{name} ({code})", code)+ for code, name in sorted(languages.items(), key=lambda item: item[1])+ ]++HEARTMULA_VERSION = "3B"++YUE_STAGE1_COT_REPO = "m-a-p/YuE-s1-7B-anneal-en-cot"+YUE_STAGE1_ICL_REPO = "m-a-p/YuE-s1-7B-anneal-en-icl"+YUE_STAGE2_REPO = "m-a-p/YuE-s2-1B-general"+YUE_STAGE1_FILES = [+ "config.json",+]+YUE_STAGE2_FILES = [+ "config.json",+]+++def _get_heartmula_local_config_path() -> str:+ return os.path.join(+ os.path.dirname(__file__),+ "HeartMula",+ "config",+ f"heartmula_{HEARTMULA_VERSION}.json",+ )+++def _get_chatterbox_model_def():+ return {+ "audio_only": True,+ "image_outputs": False,+ "sliding_window": False,+ "guidance_max_phases": 0,+ "no_negative_prompt": True,+ "image_prompt_types_allowed": "",+ "profiles_dir": ["chatterbox"],+ "audio_guide_label": "Voice to Replicate",+ "model_modes": {+ "choices": _get_language_choices(),+ "default": "en",+ "label": "Language",+ },+ "any_audio_prompt": True,+ "chatterbox_controls": True,+ }+++def _get_heartmula_model_def():+ return {+ "audio_only": True,+ "image_outputs": False,+ "sliding_window": False,+ "guidance_max_phases": 0,+ "no_negative_prompt": True,+ "image_prompt_types_allowed": "",+ "profiles_dir": ["heartmula_oss_3b"],+ "alt_prompt": {+ "label": "Keywords / Tags",+ "placeholder": "piano,happy,wedding",+ "lines": 2,+ },+ "text_prompt_enhancer_instructions": (+ "You are a lyric-writing assistant. Generate a clean song lyric prompt "+ "for a text-to-song model. Output only the lyric text with optional "+ "section headers in square brackets (e.g., [Verse], [Chorus], [Bridge], "+ "[Intro], [Outro]). Do not include explanations, bullet lists, or tags. "+ "Keep a consistent theme, POV, and rhyme or rhythm where natural. Use "+ "short lines that are easy to sing.\n\n"+ "Example:\n"+ "[Verse]\n"+ "Morning light through the window pane\n"+ "I hum a tune to chase the rain\n"+ "Steady steps on a quiet street\n"+ "Heart and rhythm, gentle beat\n"+ ),+ "duration_slider": {+ "label": "Duration of the Song (in seconds)",+ "min": 30,+ "max": 240,+ "increment": 0.1,+ "default": 120,+ },+ "heartmula_cfg_scale": 1.5,+ "heartmula_topk": 50,+ "heartmula_max_audio_length_ms": 120000,+ "heartmula_codec_guidance_scale": 1.25,+ "heartmula_codec_steps": 10,+ "compile": False, #["transformer", "transformer2"]+ }+++def _get_yue_model_def(model_def):+ use_audio_prompt = bool(model_def.get("yue_audio_prompt", False))+ yue_def = {+ "audio_only": True,+ "image_outputs": False,+ "sliding_window": False,+ "guidance_max_phases": 0,+ "no_negative_prompt": True,+ "image_prompt_types_allowed": "",+ "profiles_dir": ["yue"],+ "alt_prompt": {+ "label": "Genres / Tags",+ "placeholder": "pop, dreamy, warm vocal, female, nostalgic",+ "lines": 2,+ },+ "yue_max_new_tokens": 3000,+ "yue_run_n_segments": 2,+ "yue_stage2_batch_size": 4,+ "yue_segment_duration": 6,+ "yue_prompt_start_time": 0.0,+ "yue_prompt_end_time": 30.0,+ }+ if use_audio_prompt:+ yue_def.update(+ {+ "any_audio_prompt": True,+ "audio_prompt_choices": True,+ "audio_guide_label": "Vocal prompt",+ "audio_guide2_label": "Instrumental prompt",+ "audio_prompt_type_sources": {+ "selection": ["", "A", "AB"],+ "labels": {+ "": "Lyrics only",+ "A": "Mixed audio prompt",+ "AB": "Vocal + Instrumental prompts",+ },+ "letters_filter": "AB",+ "default": "",+ },+ }+ )+ return yue_def+++def _get_chatterbox_download_def():+ mandatory_files = [+ "ve.safetensors",+ "t3_mtl23ls_v2.safetensors",+ "s3gen.pt",+ "grapheme_mtl_merged_expanded_v1.json",+ "conds.pt",+ "Cangjie5_TC.json",+ ]+ return {+ "repoId": "ResembleAI/chatterbox",+ "sourceFolderList": [""],+ "targetFolderList": ["chatterbox"],+ "fileList": [mandatory_files],+ }+++def _get_heartmula_download_def():+ gen_files = [+ "gen_config.json",+ "tokenizer.json",+ "codec_config.json",+ "HeartMula_codec.safetensors",+ ]+ return [+ {+ "repoId": "DeepBeepMeep/TTS",+ "sourceFolderList": ["HeartMula"],+ "fileList": [gen_files],+ },+ ]+++def _get_yue_download_def(model_def):+ use_audio_prompt = bool(model_def.get("yue_audio_prompt", False))+ stage1_repo = YUE_STAGE1_ICL_REPO if use_audio_prompt else YUE_STAGE1_COT_REPO+ stage1_folder = os.path.basename(stage1_repo)+ stage2_folder = os.path.basename(YUE_STAGE2_REPO)+ xcodec_root = "xcodec_mini_infer"+ xcodec_source_folders = [+ "final_ckpt",+ "decoders",+ "models",+ "modules",+ "quantization",+ "RepCodec",+ "descriptaudiocodec",+ "vocos",+ "semantic_ckpts/hf_1_325000",+ ]+ xcodec_files = [+ ["config.yaml", "ckpt_00360000.pth"],+ ["config.yaml", "decoder_131000.pth", "decoder_151000.pth"],+ [],+ [],+ [],+ [],+ [],+ [],+ [],+ ]+ return [+ {+ "repoId": stage1_repo,+ "sourceFolderList": [""],+ "targetFolderList": [stage1_folder],+ "fileList": [YUE_STAGE1_FILES],+ },+ {+ "repoId": YUE_STAGE2_REPO,+ "sourceFolderList": [""],+ "targetFolderList": [stage2_folder],+ "fileList": [YUE_STAGE2_FILES],+ },+ {+ "repoId": stage1_repo,+ "sourceFolderList": [""],+ "targetFolderList": ["mm_tokenizer_v0.2_hf"],+ "fileList": [["tokenizer.model"]],+ },+ {+ "repoId": "m-a-p/xcodec_mini_infer",+ "sourceFolderList": [""],+ "targetFolderList": [xcodec_root],+ "fileList": [["vocoder.py", "post_process_audio.py"]],+ },+ {+ "repoId": "m-a-p/xcodec_mini_infer",+ "sourceFolderList": xcodec_source_folders,+ "targetFolderList": [xcodec_root] * len(xcodec_source_folders),+ "fileList": xcodec_files,+ },+ ]+++class family_handler:+ @staticmethod+ def query_supported_types():+ return ["chatterbox", "heartmula_oss_3b", "yue"]++ @staticmethod+ def query_family_maps():+ return {}, {}++ @staticmethod+ def query_model_family():+ return "tts"++ @staticmethod+ def query_family_infos():+ return {"tts": (200, "TTS")}++ @staticmethod+ def register_lora_cli_args(parser):+ parser.add_argument(+ "--lora-dir-tts",+ type=str,+ default=os.path.join("loras", "tts"),+ help="Path to a directory that contains TTS settings",+ )++ @staticmethod+ def get_lora_dir(base_model_type, args):+ return args.lora_dir_tts++ @staticmethod+ def query_model_def(base_model_type, model_def):+ if base_model_type == "heartmula_oss_3b":+ return _get_heartmula_model_def()+ if base_model_type == "yue":+ return _get_yue_model_def(model_def)+ return _get_chatterbox_model_def()++ @staticmethod+ def query_model_files(computeList, base_model_type, model_def=None):+ if base_model_type == "heartmula_oss_3b":+ return _get_heartmula_download_def()+ if base_model_type == "yue":+ return _get_yue_download_def(model_def or {})+ return _get_chatterbox_download_def()++ @staticmethod+ def load_model(+ model_filename,+ model_type,+ base_model_type,+ model_def,+ quantizeTransformer=False,+ text_encoder_quantization=None,+ dtype=None,+ VAE_dtype=None,+ mixed_precision_transformer=False,+ save_quantized=False,+ submodel_no_list=None,+ text_encoder_filename=None,+ profile = 0,+ **kwargs,+ ):+ ckpt_root = fl.get_download_location()+ if base_model_type == "heartmula_oss_3b":+ from .HeartMula.pipeline import HeartMuLaPipeline++ weights_candidate = None+ if isinstance(model_filename, (list, tuple)):+ if len(model_filename) > 0:+ weights_candidate = model_filename[0]+ else:+ weights_candidate = model_filename+ heartmula_weights_path = None+ if weights_candidate:+ heartmula_weights_path = fl.locate_file(+ weights_candidate, error_if_none=False+ )+ if heartmula_weights_path is None:+ heartmula_weights_path = weights_candidate+ pipeline = HeartMuLaPipeline(+ ckpt_root=ckpt_root,+ device=torch.device("cpu"),+ version=HEARTMULA_VERSION,+ VAE_dtype = VAE_dtype,+ heartmula_weights_path=heartmula_weights_path,+ cfg_scale=model_def.get("heartmula_cfg_scale", 1.5),+ topk=model_def.get("heartmula_topk", 50),+ max_audio_length_ms=model_def.get("heartmula_max_audio_length_ms", 120000),+ codec_steps=model_def.get("heartmula_codec_steps", 10),+ codec_guidance_scale=model_def.get(+ "heartmula_codec_guidance_scale", 1.25+ ),+ )++ pipeline.mula.decoder[0].layers._compile_me = False+ pipeline.mula.backbone.layers._compile_me = False+ pipe = {"transformer": pipeline.mula, "transformer2": pipeline.mula.decoder[0], "codec": pipeline.codec}+ pipe = { "pipe": pipe, "coTenantsMap" : {+ "transformer": ["transformer2"],+ "transformer2": ["transformer"],+ }+ }++ if int(profile) in (2,4,5):+ pipe["budgets"] = { "transformer2" : 200}++ return pipeline, pipe++ if base_model_type == "yue":+ from .yue.pipeline import YuePipeline++ if isinstance(model_filename, list):+ stage1_weights = model_filename[0] if len(model_filename) > 0 else ""+ stage2_weights = model_filename[1] if len(model_filename) > 1 else ""+ else:+ stage1_weights = model_filename or ""+ stage2_weights = ""++ pipeline = YuePipeline(+ stage1_weights_path=stage1_weights,+ stage2_weights_path=stage2_weights,+ use_audio_prompt=bool(model_def.get("yue_audio_prompt", False)),+ max_new_tokens=model_def.get("yue_max_new_tokens", 200),+ run_n_segments=model_def.get("yue_run_n_segments", 1),+ stage2_batch_size=model_def.get("yue_stage2_batch_size", 10),+ segment_duration=model_def.get("yue_segment_duration", 6),+ prompt_start_time=model_def.get("yue_prompt_start_time", 0.0),+ prompt_end_time=model_def.get("yue_prompt_end_time", 30.0),+ )++ pipe = {+ "transformer": pipeline.model_stage1,+ "transformer2": pipeline.model_stage2,+ "codec_model": pipeline.codec_model,+ "vocoder_vocal": pipeline.vocoder_vocal,+ "vocoder_inst": pipeline.vocoder_inst,+ }+ return pipeline, pipe++ from .chatterbox.pipeline import ChatterboxPipeline++ pipeline = ChatterboxPipeline(ckpt_root=ckpt_root, device="cpu")+ pipe = {+ "ve": pipeline.model.ve,+ "s3gen": pipeline.model.s3gen,+ "t3": pipeline.model.t3,+ "conds": pipeline.model.conds,+ }+ return pipeline, pipe++ @staticmethod+ def fix_settings(base_model_type, settings_version, model_def, ui_defaults):+ if "alt_prompt" not in ui_defaults:+ ui_defaults["alt_prompt"] = ""++ if base_model_type == "heartmula_oss_3b":+ defaults = {+ "audio_prompt_type": "",+ }+ elif base_model_type == "yue":+ defaults = {+ "audio_prompt_type": "",+ }+ else:+ defaults = {+ "audio_prompt_type": "A",+ "model_mode": "en",+ }+ for key, value in defaults.items():+ ui_defaults.setdefault(key, value)++ @staticmethod+ def update_default_settings(base_model_type, model_def, ui_defaults):+ if base_model_type == "heartmula_oss_3b":+ duration_def = model_def.get("duration_slider", {})+ ui_defaults.update(+ {+ "audio_prompt_type": "",+ "alt_prompt": "piano,happy,wedding",+ "repeat_generation": 1,+ "duration_seconds": duration_def.get("default", 120),+ "video_length": 0,+ "num_inference_steps": 0,+ "negative_prompt": "",+ "temperature": 1.0,+ "multi_prompts_gen_type": 2,+ "override_profile": 3.5,++ }+ )+ return+ if base_model_type == "yue":+ ui_defaults.update(+ {+ "audio_prompt_type": "",+ "alt_prompt": "pop, dreamy, warm vocal, female, nostalgic",+ "repeat_generation": 1,+ "video_length": 0,+ "num_inference_steps": 0,+ "negative_prompt": "",+ "temperature": 1.0,+ "multi_prompts_gen_type": 2,+ }+ )+ return++ ui_defaults.update(+ {+ "audio_prompt_type": "A",+ "model_mode": "en",+ "repeat_generation": 1,+ "video_length": 0,+ "num_inference_steps": 0,+ "negative_prompt": "",+ "exaggeration": 0.5,+ "temperature": 0.8,+ "pace": 0.5,+ "multi_prompts_gen_type": 2,+ }+ )++ @staticmethod+ def validate_generative_prompt(base_model_type, model_def, inputs, one_prompt):+ if base_model_type == "heartmula_oss_3b":+ alt_prompt = inputs.get("alt_prompt", "")+ if alt_prompt is None or len(str(alt_prompt).strip()) == 0:+ return "Keywords prompt cannot be empty for HeartMuLa."+ if inputs.get("audio_guide") is not None or inputs.get("audio_guide2") is not None:+ return "HeartMuLa does not support reference audio yet."+ return None+ if base_model_type == "yue":+ if one_prompt is None or len(str(one_prompt).strip()) == 0:+ return "Lyrics prompt cannot be empty for Yue."+ alt_prompt = inputs.get("alt_prompt", "")+ if alt_prompt is None or len(str(alt_prompt).strip()) == 0:+ return "Genres prompt cannot be empty for Yue."+ audio_prompt_type = inputs.get("audio_prompt_type", "") or ""+ if model_def.get("yue_audio_prompt", False):+ if "A" in audio_prompt_type:+ if inputs.get("audio_guide") is None:+ return "You must provide a vocal or mixed audio prompt for Yue ICL."+ if "B" in audio_prompt_type and inputs.get("audio_guide2") is None:+ return "You must provide an instrumental prompt for Yue ICL."+ start_time = float(inputs.get("yue_prompt_start_time", model_def.get("yue_prompt_start_time", 0.0)))+ end_time = float(inputs.get("yue_prompt_end_time", model_def.get("yue_prompt_end_time", 30.0)))+ if start_time >= end_time:+ return "Audio prompt start time must be less than end time."+ if end_time - start_time > 30:+ return "Audio prompt duration should not exceed 30 seconds."+ elif inputs.get("audio_guide") is not None or inputs.get("audio_guide2") is not None:+ return "Select an audio prompt type for Yue ICL or clear audio prompts."+ else:+ if inputs.get("audio_guide") is not None or inputs.get("audio_guide2") is not None:+ return "Yue base model does not support audio prompts. Please use Yue ICL."+ return None++ if len(one_prompt) > 300:+ gr.Info(+ "It is recommended to use a prompt that has less than 300 characters,"+ " otherwise you may get unexpected results."+ )diff --git a/models/TTS/yue/__init__.py b/models/TTS/yue/__init__.pynew file mode 100644index 0000000..c641769--- /dev/null+++ b/models/TTS/yue/__init__.py@@ -0,0 +1,3 @@+from .pipeline import YuePipeline++__all__ = ["YuePipeline"]diff --git a/models/TTS/yue/codecmanipulator.py b/models/TTS/yue/codecmanipulator.pynew file mode 100644index 0000000..fb43167--- /dev/null+++ b/models/TTS/yue/codecmanipulator.py@@ -0,0 +1,203 @@+import json+import numpy as np+import einops+++class CodecManipulator(object):+ r"""+ **mm tokenizer v0.1**+ see codeclm/hf/mm_tokenizer_v0.1_hf/id2vocab.json++ text tokens:+ llama tokenizer 0~31999++ special tokens: "32000": "<EOD>", "32001": "<SOA>", "32002": "<EOA>", "32003": "<SOI>", "32004": "<EOI>", "32005": "<SOV>", "32006": "<EOV>", "32007": "<s_local>", "32008": "<e_local>", "32009": "<s_global>", "32010": "<e_global>", "32011": "<semantic>", "32012": "<acoustic>", "32013": "<low_level>", "32014": "<dac_16k>", "32015": "<dac_44k>", "32016": "<xcodec>", "32017": "<placeholder>", "32018": "<semantic_mert>", "32019": "<semantic_hubert>", "32020": "<visual>", "32021": "<semanticodec>"++ mm tokens:+ dac_16k: 4 codebook, 1024 vocab, 32022 - 36117+ dac_44k: 9 codebook, 1024 vocab, 36118 - 45333+ xcodec: 12 codebook, 1024 vocab, 45334 - 57621+ semantic mert: 1024, 57622 - 58645+ semantic hubert: 512, 58646 - 59157+ visual: 64000, not included in v0.1+ semanticodec 100tps 16384: semantic=16384, 59158 - 75541, acoustic=8192, 75542 - 83733+ """+ def __init__(self, codec_type, quantizer_begin=None, n_quantizer=None, teacher_forcing=False, data_feature="codec"):+ self.codec_type = codec_type+ self.mm_v0_2_cfg = {+ "dac16k": {"codebook_size": 1024, "num_codebooks": 4, "global_offset": 32022, "sep": ["<dac_16k>"], "fps": 50},+ "dac44k": {"codebook_size": 1024, "num_codebooks": 9, "global_offset": 36118, "sep": ["<dac_44k>"]},+ "xcodec": {"codebook_size": 1024, "num_codebooks": 12, "global_offset": 45334, "sep": ["<xcodec>"], "fps": 50},+ "mert": {"codebook_size": 1024, "global_offset": 57622, "sep": ["<semantic_mert>"]},+ "hubert": {"codebook_size": 512, "global_offset": 58646, "sep": ["<semantic_hubert>"]},+ "semantic/s": {"codebook_size": 16384, "num_codebooks": 1, "global_offset": 59158, "sep": ["<semanticodec>", "<semantic>"]},+ "semantic/a": {"codebook_size": 8192, "num_codebooks": 1, "global_offset": 75542, "sep": ["<semanticodec>", "<acoustic>"]},+ "semanticodec": {"codebook_size": [16384, 8192], "num_codebooks": 2, "global_offset": 59158, "sep": ["<semanticodec>"], "fps": 50},+ "special_tokens": {+ '<EOD>': 32000, '<SOA>': 32001, '<EOA>': 32002, '<SOI>': 32003, '<EOI>': 32004, '<SOV>': 32005, '<EOV>': 32006, '<s_local>': 32007, '<e_local>': 32008, '<s_global>': 32009, '<e_global>': 32010, '<semantic>': 32011, '<acoustic>': 32012, '<stage_1>': 32013, '<dac_16k>': 32014, '<dac_44k>': 32015, '<xcodec>': 32016, '<stage_2>': 32017, '<semantic_mert>': 32018, '<semantic_hubert>': 32019, '<visual>': 32020, '<semanticodec>': 32021+ },+ "metadata": {+ "len": 83734,+ "text_range": [0, 31999],+ "special_range": [32000, 32021],+ "mm_range": [32022, 83733]+ },+ "codec_range": {+ "dac16k": [32022, 36117],+ "dac44k": [36118, 45333],+ "xcodec": [45334, 57621],+ # "hifi16k": [53526, 57621],+ "mert": [57622, 58645],+ "hubert": [58646, 59157],+ "semantic/s": [59158, 75541],+ "semantic/a": [75542, 83733],+ "semanticodec": [59158, 83733]+ }+ }+ self.sep = self.mm_v0_2_cfg[self.codec_type]["sep"]+ self.sep_ids = [self.mm_v0_2_cfg["special_tokens"][s] for s in self.sep]+ self.codebook_size = self.mm_v0_2_cfg[self.codec_type]["codebook_size"]+ self.num_codebooks = self.mm_v0_2_cfg[self.codec_type]["num_codebooks"]+ self.global_offset = self.mm_v0_2_cfg[self.codec_type]["global_offset"]+ self.fps = self.mm_v0_2_cfg[self.codec_type]["fps"] if "fps" in self.mm_v0_2_cfg[self.codec_type] else None++ self.quantizer_begin = quantizer_begin if quantizer_begin is not None else 0+ self.n_quantizer = n_quantizer if n_quantizer is not None else self.num_codebooks+ self.teacher_forcing = teacher_forcing+ self.data_feature = data_feature+++ def offset_tok_ids(self, x, global_offset=0, codebook_size=2048, num_codebooks=4):+ """+ x: (K, T)+ """+ if isinstance(codebook_size, int):+ assert x.max() < codebook_size, f"max(x)={x.max()}, codebook_size={codebook_size}"+ elif isinstance(codebook_size, list):+ for i, cs in enumerate(codebook_size):+ assert x[i].max() < cs, f"max(x)={x[i].max()}, codebook_size={cs}, layer_id={i}"+ else:+ raise ValueError(f"codebook_size={codebook_size}")+ assert x.min() >= 0, f"min(x)={x.min()}"+ assert x.shape[0] == num_codebooks or x.shape[0] == self.n_quantizer, \+ f"x.shape[0]={x.shape[0]}, num_codebooks={num_codebooks}, n_quantizer={self.n_quantizer}"++ _x = x.copy()+ _x = _x.astype(np.uint32)+ cum_offset = 0+ quantizer_begin = self.quantizer_begin+ quantizer_end = quantizer_begin+self.n_quantizer+ for k in range(self.quantizer_begin, quantizer_end): # k: quantizer_begin to quantizer_end - 1+ if isinstance(codebook_size, int):+ _x[k] += global_offset + k * codebook_size+ elif isinstance(codebook_size, list):+ _x[k] += global_offset + cum_offset+ cum_offset += codebook_size[k]+ else:+ raise ValueError(f"codebook_size={codebook_size}")+ return _x[quantizer_begin:quantizer_end]++ def unoffset_tok_ids(self, x, global_offset=0, codebook_size=2048, num_codebooks=4):+ """+ x: (K, T)+ """+ if isinstance(codebook_size, int):+ assert x.max() < global_offset + codebook_size * num_codebooks, f"max(x)={x.max()}, codebook_size={codebook_size}"+ elif isinstance(codebook_size, list):+ assert x.max() < global_offset + sum(codebook_size), f"max(x)={x.max()}, codebook_size={codebook_size}"+ assert x.min() >= global_offset, f"min(x)={x.min()}, global_offset={global_offset}"+ assert x.shape[0] == num_codebooks or x.shape[0] == self.n_quantizer, \+ f"x.shape[0]={x.shape[0]}, num_codebooks={num_codebooks}, n_quantizer={self.n_quantizer}"++ _x = x.copy()+ _x = _x.astype(np.uint32)+ cum_offset = 0+ quantizer_begin = self.quantizer_begin+ quantizer_end = quantizer_begin+self.n_quantizer+ for k in range(quantizer_begin, quantizer_end):+ if isinstance(codebook_size, int):+ _x[k-quantizer_begin] -= global_offset + k * codebook_size+ elif isinstance(codebook_size, list):+ _x[k-quantizer_begin] -= global_offset + cum_offset+ cum_offset += codebook_size[k]+ else:+ raise ValueError(f"codebook_size={codebook_size}")+ return _x++ def flatten(self, x):+ if len(x.shape) > 2:+ x = x.squeeze()+ assert x.shape[0] == self.num_codebooks or x.shape[0] == self.n_quantizer, \+ f"x.shape[0]={x.shape[0]}, num_codebooks={self.num_codebooks}, n_quantizer={self.n_quantizer}"+ return einops.rearrange(x, 'K T -> (T K)')++ def unflatten(self, x, n_quantizer=None):+ x = x.squeeze()+ assert len(x.shape) == 1+ assert x.shape[0] % self.num_codebooks == 0 or x.shape[0] % self.n_quantizer == 0, \+ f"x.shape[0]={x.shape[0]}, num_codebooks={self.num_codebooks}, n_quantizer={self.n_quantizer}"+ if n_quantizer!=self.num_codebooks:+ return einops.rearrange(x, '(T K) -> K T', K=n_quantizer)+ return einops.rearrange(x, '(T K) -> K T', K=self.num_codebooks)++ # def check_codec_type_from_path(self, path):+ # if self.codec_type == "hifi16k":+ # assert "academicodec_hifi_16k_320d_large_uni" in path++ def get_codec_type_from_range(self, ids):+ ids_range = [ids.min(), ids.max()]+ codec_range = self.mm_v0_2_cfg["codec_range"]+ for codec_type, r in codec_range.items():+ if ids_range[0] >= r[0] and ids_range[1] <= r[1]:+ return codec_type+ raise ValueError(f"ids_range={ids_range}, codec_range={codec_range}")++ def npy2ids(self, npy):+ if isinstance(npy, str):+ data = np.load(npy)+ elif isinstance(npy, np.ndarray):+ data = npy+ else:+ raise ValueError(f"not supported type: {type(npy)}")+ # data = data.squeeze()++ assert len(data.shape)==2, f'data shape: {data.shape} is not (n_codebook, seq_len)'+ data = self.offset_tok_ids(+ data,+ global_offset=self.global_offset,+ codebook_size=self.codebook_size,+ num_codebooks=self.num_codebooks,+ )+ data = self.flatten(data)+ codec_range = self.get_codec_type_from_range(data)+ assert codec_range == self.codec_type, f"get_codec_type_from_range(data)={codec_range}, self.codec_type={self.codec_type}"+ data = data.tolist()+ return data++ def ids2npy(self, token_ids):+ # make sure token_ids starts with codebook 0+ if isinstance(self.codebook_size, int):+ codebook_0_range = (self.global_offset + self.quantizer_begin*self.codebook_size, self.global_offset + (self.quantizer_begin+1)*self.codebook_size)+ elif isinstance(self.codebook_size, list):+ codebook_0_range = (self.global_offset, self.global_offset + self.codebook_size[0])+ assert token_ids[0] >= codebook_0_range[0] \+ and token_ids[0] < codebook_0_range[1], f"token_ids[0]={token_ids[self.quantizer_begin]}, codebook_0_range={codebook_0_range}"+ data = np.array(token_ids)+ data = self.unflatten(data, n_quantizer=self.n_quantizer)+ data = self.unoffset_tok_ids(+ data,+ global_offset=self.global_offset,+ codebook_size=self.codebook_size,+ num_codebooks=self.num_codebooks,+ )+ return data++ def npy_to_json_str(self, npy_path):+ data = self.npy2ids(npy_path)+ return json.dumps({"text": data, "src": npy_path, "codec": self.codec_type})++ def sep(self):+ return ''.join(self.sep)++ def sep_ids(self):+ return self.sep_idsdiff --git a/models/TTS/yue/generation_utils.py b/models/TTS/yue/generation_utils.pynew file mode 100644index 0000000..0a64309--- /dev/null+++ b/models/TTS/yue/generation_utils.py@@ -0,0 +1,4945 @@+# coding=utf-8+# Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.+# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import copy+import inspect+import os+import warnings+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union++import numpy as np+import torch+import torch.distributed as dist+from torch import nn+from torch.nn import functional as F++from transformers.cache_utils import (+ Cache,+ DynamicCache,+ EncoderDecoderCache,+ OffloadedCache,+ QuantizedCacheConfig,+ StaticCache,+)+from transformers.configuration_utils import PretrainedConfig+from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled+from transformers.integrations.fsdp import is_fsdp_managed_module+from transformers.modeling_outputs import CausalLMOutputWithPast, Seq2SeqLMOutput+from transformers.pytorch_utils import isin_mps_friendly+from transformers.tokenization_utils import ExtensionsTrie+from transformers.utils import (+ ModelOutput,+ is_accelerate_available,+ is_hqq_available,+ is_optimum_quanto_available,+ is_torchdynamo_compiling,+ logging,+)+from transformers.generation.beam_constraints import DisjunctiveConstraint, PhrasalConstraint+from transformers.generation.beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer+from transformers.generation.candidate_generator import (+ AssistedCandidateGenerator,+ AssistedCandidateGeneratorDifferentTokenizers,+ CandidateGenerator,+ EarlyExitCandidateGenerator,+ PromptLookupCandidateGenerator,+ _crop_past_key_values,+ _prepare_attention_mask,+ _prepare_token_type_ids,+)+from transformers.generation.configuration_utils import (+ NEED_SETUP_CACHE_CLASSES_MAPPING,+ QUANT_BACKEND_CLASSES_MAPPING,+ GenerationConfig,+ GenerationMode,+)+from transformers.generation.logits_process import (+ EncoderNoRepeatNGramLogitsProcessor,+ EncoderRepetitionPenaltyLogitsProcessor,+ EpsilonLogitsWarper,+ EtaLogitsWarper,+ ExponentialDecayLengthPenalty,+ ForcedBOSTokenLogitsProcessor,+ ForcedEOSTokenLogitsProcessor,+ HammingDiversityLogitsProcessor,+ InfNanRemoveLogitsProcessor,+ LogitNormalization,+ LogitsProcessorList,+ MinLengthLogitsProcessor,+ MinNewTokensLengthLogitsProcessor,+ MinPLogitsWarper,+ NoBadWordsLogitsProcessor,+ NoRepeatNGramLogitsProcessor,+ PrefixConstrainedLogitsProcessor,+ RepetitionPenaltyLogitsProcessor,+ SequenceBiasLogitsProcessor,+ SuppressTokensAtBeginLogitsProcessor,+ SuppressTokensLogitsProcessor,+ TemperatureLogitsWarper,+ TopKLogitsWarper,+ TopPLogitsWarper,+ TypicalLogitsWarper,+ UnbatchedClassifierFreeGuidanceLogitsProcessor,+)+from transformers.generation.stopping_criteria import (+ ConfidenceCriteria,+ EosTokenCriteria,+ MaxLengthCriteria,+ MaxTimeCriteria,+ StoppingCriteria,+ StoppingCriteriaList,+ StopStringCriteria,+)+++if TYPE_CHECKING:+ from transformers.modeling_utils import PreTrainedModel+ from transformers.tokenization_utils_base import PreTrainedTokenizerBase+ from transformers.generation.streamers import BaseStreamer++logger = logging.get_logger(__name__)++if is_accelerate_available():+ from accelerate.hooks import AlignDevicesHook, add_hook_to_module+++@dataclass+class GenerateDecoderOnlyOutput(ModelOutput):+ """+ Outputs of decoder-only generation models, when using non-beam methods.++ Args:+ sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter+ if all batches finished early due to the `eos_token_id`.+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.+ """++ sequences: torch.LongTensor = None+ scores: Optional[Tuple[torch.FloatTensor]] = None+ logits: Optional[Tuple[torch.FloatTensor]] = None+ attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None+++@dataclass+class GenerateEncoderDecoderOutput(ModelOutput):+ """+ Outputs of encoder-decoder generation models, when using non-beam methods.++ Args:+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter+ if all batches finished early due to the `eos_token_id`.+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):+ Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,+ sequence_length, sequence_length)`.+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of+ shape `(batch_size, sequence_length, hidden_size)`.+ decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.+ cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.+ decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.+ """++ sequences: torch.LongTensor = None+ scores: Optional[Tuple[torch.FloatTensor]] = None+ logits: Optional[Tuple[torch.FloatTensor]] = None+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None+ decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None+++@dataclass+class GenerateBeamDecoderOnlyOutput(ModelOutput):+ """+ Outputs of decoder-only generation models, when using beam methods.++ Args:+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter+ if all batches finished early due to the `eos_token_id`.+ sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):+ Final beam scores of the generated `sequences`.+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):+ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.+ beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape+ `(batch_size*num_return_sequences, sequence_length)`.+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.+ """++ sequences: torch.LongTensor = None+ sequences_scores: Optional[torch.FloatTensor] = None+ scores: Optional[Tuple[torch.FloatTensor]] = None+ logits: Optional[Tuple[torch.FloatTensor]] = None+ beam_indices: Optional[torch.LongTensor] = None+ attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None+++@dataclass+class GenerateBeamEncoderDecoderOutput(ModelOutput):+ """+ Outputs of encoder-decoder generation models, when using beam methods.++ Args:+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter+ if all batches finished early due to the `eos_token_id`.+ sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):+ Final beam scores of the generated `sequences`.+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):+ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.+ beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape+ `(batch_size*num_return_sequences, sequence_length)`.+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):+ Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,+ sequence_length, sequence_length)`.+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of+ shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.+ decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,+ sequence_length)`.+ cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.+ decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.+ """++ sequences: torch.LongTensor = None+ sequences_scores: Optional[torch.FloatTensor] = None+ scores: Optional[Tuple[torch.FloatTensor]] = None+ logits: Optional[Tuple[torch.FloatTensor]] = None+ beam_indices: Optional[torch.LongTensor] = None+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None+ decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None+++# TODO (joao): remove the equivalent classes and typing shortcuts below in v5+# Equivalent classes (kept for retrocompatibility purposes)+GreedySearchDecoderOnlyOutput = GenerateDecoderOnlyOutput+ContrastiveSearchDecoderOnlyOutput = GenerateDecoderOnlyOutput+SampleDecoderOnlyOutput = GenerateDecoderOnlyOutput++ContrastiveSearchEncoderDecoderOutput = GenerateEncoderDecoderOutput+GreedySearchEncoderDecoderOutput = GenerateEncoderDecoderOutput+SampleEncoderDecoderOutput = GenerateEncoderDecoderOutput++BeamSearchDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput+BeamSampleDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput++BeamSearchEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput+BeamSampleEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput++GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]+SampleOutput = Union[SampleEncoderDecoderOutput, SampleDecoderOnlyOutput]+BeamSearchOutput = Union[BeamSearchEncoderDecoderOutput, BeamSearchDecoderOnlyOutput]+BeamSampleOutput = Union[BeamSampleEncoderDecoderOutput, BeamSampleDecoderOnlyOutput]+ContrastiveSearchOutput = Union[ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput]++# Typing shortcuts+GenerateNonBeamOutput = Union[GenerateDecoderOnlyOutput, GenerateEncoderDecoderOutput]+GenerateBeamOutput = Union[GenerateBeamDecoderOnlyOutput, GenerateBeamEncoderDecoderOutput]+GenerateOutput = Union[GenerateNonBeamOutput, GenerateBeamOutput]+++class GenerationMixin:+ """+ A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].++ The class exposes [`~generation.GenerationMixin.generate`], which can be used for:+ - *greedy decoding* if `num_beams=1` and `do_sample=False`+ - *contrastive search* if `penalty_alpha>0` and `top_k>1`+ - *multinomial sampling* if `num_beams=1` and `do_sample=True`+ - *beam-search decoding* if `num_beams>1` and `do_sample=False`+ - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`+ - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`+ - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`+ - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`++ To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).+ """++ def prepare_inputs_for_generation(+ self,+ input_ids: torch.LongTensor,+ past_key_values: Optional[Cache] = None,+ attention_mask: Optional[torch.LongTensor] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ cache_position: Optional[torch.LongTensor] = None,+ **kwargs,+ ):+ """+ Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or+ slicing inputs given the existing cache.++ See the forward pass in the model documentation for expected arguments (different models might have different+ requirements for e.g. `past_key_values`). This function should work as is for most LLMs.+ """++ # 1. Handle BC:+ model_inputs = {}+ # - some models don't have `Cache` support (which implies they don't expect `cache_position` in `forward`)+ if self._supports_cache_class:+ model_inputs["cache_position"] = cache_position+ # - `cache_position` was not a mandatory input in `prepare_inputs_for_generation` for those models, and this+ # function may be called outside of `generate`. Handle most use cases by creating `cache_position` on the fly+ # (this alternative is not as robust as calling `generate` and letting it create `cache_position`)+ elif cache_position is None:+ past_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0+ cache_position = torch.arange(past_length, input_ids.shape[1], dtype=torch.long, device=input_ids.device)++ # 2. Generic cache-dependent input preparation+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens+ # Exception 1: when passing input_embeds, input_ids may be missing entries+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.+ # (we can't check exception 3 while compiling)+ if past_key_values is not None:+ model_inputs["past_key_values"] = past_key_values+ if (+ inputs_embeds is not None # Exception 1+ or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3+ ):+ input_ids = input_ids[:, -cache_position.shape[0] :]+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)+ input_ids = input_ids[:, cache_position]++ # 3. Prepare base model inputs+ input_ids_key = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step+ if not self.config.is_encoder_decoder:+ if inputs_embeds is not None and cache_position[0] == 0:+ model_inputs[input_ids_key] = None+ model_inputs["inputs_embeds"] = inputs_embeds+ else:+ # `clone` calls in this function ensure a consistent stride. See #32227+ model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)+ model_inputs["inputs_embeds"] = None+ else:+ model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)++ # 4. Create missing `position_ids` on the fly+ if (+ attention_mask is not None+ and kwargs.get("position_ids") is None+ and "position_ids" in set(inspect.signature(self.forward).parameters.keys())+ ):+ position_ids = attention_mask.long().cumsum(-1) - 1+ position_ids.masked_fill_(attention_mask == 0, 1)+ kwargs["position_ids"] = position_ids # placed in kwargs for further processing (see below)++ # 5. Slice model inputs if it's an input that should have the same length as `input_ids`+ for model_input_name in ["position_ids", "token_type_ids"]:+ model_input = kwargs.get(model_input_name)+ if model_input is not None:+ if past_key_values is not None:+ current_input_length = (+ model_inputs["inputs_embeds"].shape[1]+ if model_inputs["inputs_embeds"] is not None+ else model_inputs[input_ids_key].shape[1]+ )+ model_input = model_input[:, -current_input_length:]+ model_input = model_input.clone(memory_format=torch.contiguous_format)+ model_inputs[model_input_name] = model_input++ # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:+ if model_inputs["inputs_embeds"] is not None:+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape+ device = model_inputs["inputs_embeds"].device+ else:+ batch_size, sequence_length = model_inputs[input_ids_key].shape+ device = model_inputs[input_ids_key].device++ # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create+ # the 4D causal mask exists, it should be present in the base model (XXXModel class).+ base_model = getattr(self, self.base_model_prefix, None)+ if base_model is None:+ causal_mask_creation_function = getattr(+ self, "_prepare_4d_causal_attention_mask_with_cache_position", None+ )+ else:+ causal_mask_creation_function = getattr(+ base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None+ )+ if causal_mask_creation_function is None:+ logger.warning_once(+ f"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method "+ "defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're "+ "writing code, see Llama for an example implementation. If you're a user, please report this "+ "issue on GitHub."+ )+ else:+ attention_mask = causal_mask_creation_function(+ attention_mask,+ sequence_length=sequence_length,+ target_length=past_key_values.get_max_cache_shape(),+ dtype=self.dtype,+ device=device,+ cache_position=cache_position,+ batch_size=batch_size,+ config=self.config,+ past_key_values=past_key_values,+ )+ if attention_mask is not None:+ model_inputs["attention_mask"] = attention_mask++ # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).+ for key, value in kwargs.items():+ if key not in model_inputs:+ model_inputs[key] = value++ # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)+ model_inputs.pop("labels", None)+ return model_inputs++ def _prepare_model_inputs(+ self,+ inputs: Optional[torch.Tensor] = None,+ bos_token_id: Optional[torch.Tensor] = None,+ model_kwargs: Optional[Dict[str, torch.Tensor]] = None,+ ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:+ """+ This function extracts the model-specific `inputs` for generation.+ """+ # 1. retrieve all kwargs that are non-None or non-model input related.+ # some encoder-decoder models have different names for model and encoder+ if (+ self.config.is_encoder_decoder+ and hasattr(self, "encoder")+ and self.encoder.main_input_name != self.main_input_name+ ):+ input_name = self.encoder.main_input_name+ else:+ input_name = self.main_input_name++ model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}++ # 2. check whether model_input_name is passed as kwarg+ # if yes and `inputs` is None use kwarg inputs+ inputs_kwarg = model_kwargs.pop(input_name, None)+ if inputs_kwarg is not None and inputs is not None:+ raise ValueError(+ f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "+ f"Make sure to either pass {inputs} or {input_name}=..."+ )+ elif inputs_kwarg is not None:+ inputs = inputs_kwarg++ # 3. In the presence of `inputs_embeds` for text models:+ # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model+ # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with+ # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)+ # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and+ # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.+ if input_name == "input_ids" and "inputs_embeds" in model_kwargs:+ if not self.config.is_encoder_decoder:+ has_inputs_embeds_forwarding = "inputs_embeds" in set(+ inspect.signature(self.prepare_inputs_for_generation).parameters.keys()+ )+ if not has_inputs_embeds_forwarding:+ raise ValueError(+ f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "+ "doesn't have its forwarding implemented. See the GPT2 implementation for an example "+ "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"+ )+ # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of+ # the attention mask) can rely on the actual model input.+ model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(+ inputs, bos_token_id, model_kwargs=model_kwargs+ )+ else:+ if inputs is not None:+ raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")+ inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"++ # 4. if `inputs` is still None, try to create `input_ids` from BOS token+ inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)+ return inputs, input_name, model_kwargs++ def _maybe_initialize_input_ids_for_generation(+ self,+ inputs: Optional[torch.Tensor] = None,+ bos_token_id: Optional[torch.Tensor] = None,+ model_kwargs: Optional[Dict[str, torch.Tensor]] = None,+ ) -> torch.LongTensor:+ """Initializes input ids for generation, if necessary."""+ if inputs is not None:+ return inputs++ encoder_outputs = model_kwargs.get("encoder_outputs")+ if self.config.is_encoder_decoder and encoder_outputs is not None:+ # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding+ shape = encoder_outputs.last_hidden_state.size()[:-1]+ return torch.ones(shape, dtype=torch.long, device=self.device) * -100++ # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with+ # soft-prompting or in multimodal implementations built on top of decoder-only language models.+ batch_size = 1+ for value in model_kwargs.values():+ if isinstance(value, torch.Tensor):+ batch_size = value.shape[0]+ break++ if "inputs_embeds" in model_kwargs:+ return torch.ones((batch_size, 0), dtype=torch.long, device=self.device)++ if bos_token_id is None:+ raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")++ return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id++ def _prepare_attention_mask_for_generation(+ self,+ inputs_tensor: torch.Tensor,+ generation_config: GenerationConfig,+ model_kwargs: Dict[str, Any],+ ) -> torch.LongTensor:+ pad_token_id = generation_config._pad_token_tensor+ eos_token_id = generation_config._eos_token_tensor++ # `input_ids` may be present in the model kwargs, instead of being the main input (e.g. multimodal model)+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:+ inputs_tensor = model_kwargs["input_ids"]++ # No information for attention mask inference -> return default attention mask+ default_attention_mask = torch.ones(inputs_tensor.shape[:2], dtype=torch.long, device=inputs_tensor.device)+ if pad_token_id is None:+ return default_attention_mask++ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]+ if not is_input_ids:+ return default_attention_mask++ is_pad_token_in_inputs = (pad_token_id is not None) and (+ isin_mps_friendly(elements=inputs_tensor, test_elements=pad_token_id).any()+ )+ is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or ~(+ isin_mps_friendly(elements=eos_token_id, test_elements=pad_token_id).any()+ )+ can_infer_attention_mask = is_pad_token_in_inputs * is_pad_token_not_equal_to_eos_token_id+ attention_mask_from_padding = inputs_tensor.ne(pad_token_id).long()++ attention_mask = (+ attention_mask_from_padding * can_infer_attention_mask + default_attention_mask * ~can_infer_attention_mask+ )+ return attention_mask++ def _prepare_encoder_decoder_kwargs_for_generation(+ self,+ inputs_tensor: torch.Tensor,+ model_kwargs,+ model_input_name: Optional[str],+ generation_config: GenerationConfig,+ ) -> Dict[str, Any]:+ # 1. get encoder+ encoder = self.get_encoder()+ # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device+ # as the inputs.+ if hasattr(self, "hf_device_map"):+ if hasattr(encoder, "_hf_hook"):+ encoder._hf_hook.io_same_device = True+ else:+ add_hook_to_module(encoder, AlignDevicesHook(io_same_device=True))++ # 2. Prepare encoder args and encoder kwargs from model kwargs and generation config.+ irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]+ encoder_kwargs = {+ argument: value+ for argument, value in model_kwargs.items()+ if not any(argument.startswith(p) for p in irrelevant_prefix)+ }+ encoder_signature = set(inspect.signature(encoder.forward).parameters)+ encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature+ if not encoder_accepts_wildcard:+ encoder_kwargs = {+ argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature+ }+ encoder_kwargs["output_attentions"] = generation_config.output_attentions+ encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states++ # 3. make sure that encoder returns `ModelOutput`+ model_input_name = model_input_name if model_input_name is not None else self.main_input_name+ encoder_kwargs["return_dict"] = True+ encoder_kwargs[model_input_name] = inputs_tensor+ model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs) # type: ignore++ return model_kwargs++ def _prepare_decoder_input_ids_for_generation(+ self,+ batch_size: int,+ model_input_name: str,+ model_kwargs: Dict[str, torch.Tensor],+ decoder_start_token_id: torch.Tensor,+ device: torch.device = None,+ ) -> Tuple[torch.LongTensor, Dict[str, torch.Tensor]]:+ """Prepares `decoder_input_ids` for generation with encoder-decoder models"""+ # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,+ # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")+ elif "input_ids" in model_kwargs and model_input_name != "input_ids":+ decoder_input_ids = model_kwargs.pop("input_ids")+ else:+ decoder_input_ids = None++ # 2. `decoder_start_token_id` must have shape (batch_size, 1)+ if device is None:+ device = self.device+ if decoder_start_token_id.ndim == 1:+ if decoder_start_token_id.shape[0] != batch_size:+ raise ValueError(+ f"`decoder_start_token_id` expected to have length {batch_size} but got {decoder_start_token_id.shape[0]}"+ )+ decoder_start_token_id = decoder_start_token_id.view(-1, 1)+ else:+ decoder_start_token_id = (+ torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id+ )++ # 3. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.+ # no user input -> use decoder_start_token_id as decoder_input_ids+ if decoder_input_ids is None:+ decoder_input_ids = decoder_start_token_id+ # exception: Donut checkpoints have task-specific decoder starts and don't expect a BOS token. Note that the+ # original checkpoints can't be detected through `self.__class__.__name__.lower()`, needing custom logic.+ # See: https://github.com/huggingface/transformers/pull/31470+ elif "donut" in self.__class__.__name__.lower() or (+ self.config.model_type == "vision-encoder-decoder" and "donut" in self.config.encoder.model_type.lower()+ ):+ pass+ elif self.config.model_type in ["whisper"]:+ pass+ # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust+ # decoder_attention_mask if provided)+ elif (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item():+ decoder_input_ids = torch.cat([decoder_start_token_id, decoder_input_ids], dim=-1)+ if "decoder_attention_mask" in model_kwargs:+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]+ decoder_attention_mask = torch.cat(+ (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),+ dim=-1,+ )+ model_kwargs["decoder_attention_mask"] = decoder_attention_mask++ return decoder_input_ids, model_kwargs++ @staticmethod+ def _expand_inputs_for_generation(+ expand_size: int = 1,+ is_encoder_decoder: bool = False,+ input_ids: Optional[torch.LongTensor] = None,+ **model_kwargs,+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:+ """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""+ # Do not call torch.repeat_interleave if expand_size is 1 because it clones+ # the input tensor and thus requires more memory although no change is applied+ if expand_size == 1:+ return input_ids, model_kwargs++ def _expand_dict_for_generation(dict_to_expand):+ for key in dict_to_expand:+ if (+ key != "cache_position"+ and dict_to_expand[key] is not None+ and isinstance(dict_to_expand[key], torch.Tensor)+ ):+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)+ return dict_to_expand++ if input_ids is not None:+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)++ model_kwargs = _expand_dict_for_generation(model_kwargs)++ if is_encoder_decoder:+ if model_kwargs.get("encoder_outputs") is None:+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])++ return input_ids, model_kwargs++ def _extract_past_from_model_output(self, outputs: ModelOutput):+ past_key_values = None+ cache_name = "past_key_values"+ if "past_key_values" in outputs:+ past_key_values = outputs.past_key_values+ elif "mems" in outputs:+ past_key_values = outputs.mems+ elif "past_buckets_states" in outputs:+ past_key_values = outputs.past_buckets_states+ elif "cache_params" in outputs:+ past_key_values = outputs.cache_params+ cache_name = "cache_params"++ return cache_name, past_key_values++ def _update_model_kwargs_for_generation(+ self,+ outputs: ModelOutput,+ model_kwargs: Dict[str, Any],+ is_encoder_decoder: bool = False,+ num_new_tokens: int = 1,+ ) -> Dict[str, Any]:+ # update past_key_values keeping its naming used in model code+ cache_name, cache = self._extract_past_from_model_output(outputs)+ model_kwargs[cache_name] = cache+ if getattr(outputs, "state", None) is not None:+ model_kwargs["state"] = outputs.state++ # update token_type_ids with last value+ if "token_type_ids" in model_kwargs:+ token_type_ids = model_kwargs["token_type_ids"]+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)++ if not is_encoder_decoder:+ # update attention mask+ if "attention_mask" in model_kwargs:+ attention_mask = model_kwargs["attention_mask"]+ model_kwargs["attention_mask"] = torch.cat(+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1+ )+ else:+ # update decoder attention mask+ if "decoder_attention_mask" in model_kwargs:+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]+ model_kwargs["decoder_attention_mask"] = torch.cat(+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],+ dim=-1,+ )++ if model_kwargs.get("use_cache", True):+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens+ else:+ past_positions = model_kwargs.pop("cache_position")+ new_positions = torch.arange(+ past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype+ ).to(past_positions.device)+ model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))+ return model_kwargs++ def _reorder_cache(self, past_key_values, beam_idx):+ raise NotImplementedError(+ f"Make sure that a `_reorder_cache` function is correctly implemented in {self.__class__.__module__} to"+ f" enable beam search for {self.__class__}"+ )++ def _get_candidate_generator(+ self,+ generation_config: GenerationConfig,+ input_ids: torch.LongTensor,+ inputs_tensor: torch.Tensor,+ assistant_model: "PreTrainedModel",+ logits_processor: LogitsProcessorList,+ target_tokenizer: "PreTrainedTokenizerBase",+ assistant_tokenizer: "PreTrainedTokenizerBase",+ model_kwargs: Dict,+ ) -> CandidateGenerator:+ """+ Returns the candidate generator to be used in `assisted_generation`+ """+ different_tokenizers = all(v is not None for v in (assistant_model, target_tokenizer, assistant_tokenizer))++ if generation_config.assistant_early_exit is not None:+ candidate_generator = EarlyExitCandidateGenerator(+ input_ids=input_ids,+ assistant_model=self,+ generation_config=generation_config,+ model_kwargs=model_kwargs,+ inputs_tensor=inputs_tensor,+ logits_processor=logits_processor,+ )+ elif generation_config.prompt_lookup_num_tokens is not None:+ candidate_generator = PromptLookupCandidateGenerator(+ eos_token_id=generation_config._eos_token_tensor,+ num_output_tokens=generation_config.prompt_lookup_num_tokens,+ max_matching_ngram_size=generation_config.max_matching_ngram_size,+ max_length=generation_config.max_length,+ )+ elif different_tokenizers:+ candidate_generator = AssistedCandidateGeneratorDifferentTokenizers(+ input_ids=input_ids,+ assistant_model=assistant_model,+ generation_config=generation_config,+ model_kwargs=model_kwargs,+ inputs_tensor=inputs_tensor,+ logits_processor=logits_processor,+ target_tokenizer=target_tokenizer,+ assistant_tokenizer=assistant_tokenizer,+ )+ else:+ candidate_generator = AssistedCandidateGenerator(+ input_ids=input_ids,+ assistant_model=assistant_model,+ generation_config=generation_config,+ model_kwargs=model_kwargs,+ inputs_tensor=inputs_tensor,+ logits_processor=logits_processor,+ )+ return candidate_generator++ def _get_logits_processor(+ self,+ generation_config: GenerationConfig,+ input_ids_seq_length: int,+ encoder_input_ids: torch.LongTensor,+ prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],+ logits_processor: Optional[LogitsProcessorList],+ device: str = None,+ model_kwargs: Optional[Dict[str, Any]] = None,+ negative_prompt_ids: Optional[torch.Tensor] = None,+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,+ ) -> LogitsProcessorList:+ """+ This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]+ instances used to modify the scores of the language model head.+ """+ # instantiate processors list+ processors = LogitsProcessorList()++ if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1 and False:+ processors.append(+ UnbatchedClassifierFreeGuidanceLogitsProcessor(+ generation_config.guidance_scale,+ self,+ unconditional_ids=negative_prompt_ids,+ unconditional_attention_mask=negative_prompt_attention_mask,+ use_cache=generation_config.use_cache,+ )+ )+ if generation_config.sequence_bias is not None:+ processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))++ if generation_config.diversity_penalty is not None and generation_config.diversity_penalty > 0.0:+ processors.append(+ HammingDiversityLogitsProcessor(+ diversity_penalty=generation_config.diversity_penalty,+ num_beams=generation_config.num_beams,+ num_beam_groups=generation_config.num_beam_groups,+ )+ )+ if (+ generation_config.encoder_repetition_penalty is not None+ and generation_config.encoder_repetition_penalty != 1.0+ ):+ if len(encoder_input_ids.shape) == 2:+ processors.append(+ EncoderRepetitionPenaltyLogitsProcessor(+ penalty=generation_config.encoder_repetition_penalty,+ encoder_input_ids=encoder_input_ids,+ )+ )+ else:+ warnings.warn(+ "Passing `encoder_repetition_penalty` requires some form of `input_ids` to be passed to "+ "`generate`, ignoring the argument.",+ UserWarning,+ )+ if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:+ processors.append(RepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))+ if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:+ processors.append(NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))+ if (+ generation_config.encoder_no_repeat_ngram_size is not None+ and generation_config.encoder_no_repeat_ngram_size > 0+ ):+ if len(encoder_input_ids.shape) == 2:+ processors.append(+ EncoderNoRepeatNGramLogitsProcessor(+ generation_config.encoder_no_repeat_ngram_size,+ encoder_input_ids,+ )+ )+ else:+ warnings.warn(+ "Passing `encoder_no_repeat_ngram_size` requires some form of `input_ids` to be passed to "+ "`generate`, ignoring the argument.",+ UserWarning,+ )+ if generation_config.bad_words_ids is not None:+ processors.append(+ NoBadWordsLogitsProcessor(+ generation_config.bad_words_ids,+ generation_config._eos_token_tensor,+ )+ )+ if (+ generation_config.min_length is not None+ and generation_config._eos_token_tensor is not None+ and generation_config.min_length > 0+ ):+ processors.append(+ MinLengthLogitsProcessor(+ generation_config.min_length,+ generation_config._eos_token_tensor,+ device=device,+ )+ )+ if (+ generation_config.min_new_tokens is not None+ and generation_config._eos_token_tensor is not None+ and generation_config.min_new_tokens > 0+ ):+ processors.append(+ MinNewTokensLengthLogitsProcessor(+ input_ids_seq_length,+ generation_config.min_new_tokens,+ generation_config._eos_token_tensor,+ device=device,+ )+ )+ if prefix_allowed_tokens_fn is not None:+ processors.append(+ PrefixConstrainedLogitsProcessor(+ prefix_allowed_tokens_fn,+ generation_config.num_beams // generation_config.num_beam_groups,+ )+ )+ if generation_config.forced_bos_token_id is not None:+ processors.append(+ ForcedBOSTokenLogitsProcessor(+ generation_config.forced_bos_token_id,+ )+ )+ if generation_config.forced_eos_token_id is not None:+ processors.append(+ ForcedEOSTokenLogitsProcessor(+ generation_config.max_length,+ generation_config.forced_eos_token_id,+ device=device,+ )+ )+ if generation_config.remove_invalid_values is True:+ processors.append(InfNanRemoveLogitsProcessor())+ if generation_config.exponential_decay_length_penalty is not None:+ processors.append(+ ExponentialDecayLengthPenalty(+ generation_config.exponential_decay_length_penalty,+ generation_config._eos_token_tensor,+ input_ids_seq_length,+ )+ )+ if generation_config.suppress_tokens is not None:+ processors.append(+ SuppressTokensLogitsProcessor(+ generation_config.suppress_tokens,+ device=device,+ )+ )+ if generation_config.begin_suppress_tokens is not None:+ begin_index = input_ids_seq_length+ begin_index = (+ begin_index+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)+ else begin_index + 1+ )+ processors.append(+ SuppressTokensAtBeginLogitsProcessor(+ generation_config.begin_suppress_tokens,+ begin_index,+ device=device,+ )+ )+ forced_decoder_ids = getattr(generation_config, "forced_decoder_ids", None)+ if forced_decoder_ids is not None:+ # TODO (sanchit): move this exception to GenerationConfig.validate() when TF & FLAX are aligned with PT+ raise ValueError(+ "You have explicitly specified `forced_decoder_ids`. Please remove the `forced_decoder_ids` argument "+ "in favour of `input_ids` or `decoder_input_ids` respectively.",+ )++ # TODO (joao): find a strategy to specify the order of the processors+ processors = self._merge_criteria_processor_list(processors, logits_processor)++ # Processors previously known as `LogitsWarpers`, only applied with sampling strategies+ if generation_config.do_sample:+ # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a+ # better score (i.e. keep len(list(generation_config._eos_token_tensor)) + 1)+ if generation_config.num_beams > 1:+ if isinstance(generation_config._eos_token_tensor, list):+ min_tokens_to_keep = len(generation_config._eos_token_tensor) + 1+ elif isinstance(generation_config._eos_token_tensor, torch.Tensor):+ min_tokens_to_keep = generation_config._eos_token_tensor.shape[0] + 1+ else:+ min_tokens_to_keep = 2+ else:+ min_tokens_to_keep = 1++ # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files+ # all samplers can be found in `generation_utils_samplers.py`+ if generation_config.temperature is not None and generation_config.temperature != 1.0:+ processors.append(TemperatureLogitsWarper(generation_config.temperature))+ if generation_config.top_k is not None and generation_config.top_k != 0:+ processors.append(+ TopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep)+ )+ if generation_config.top_p is not None and generation_config.top_p < 1.0:+ processors.append(+ TopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep)+ )+ if generation_config.min_p is not None:+ # Applied after temperature scaling (see https://github.com/ggerganov/llama.cpp/pull/3841#issuecomment-2073826084)+ processors.append(+ MinPLogitsWarper(min_p=generation_config.min_p, min_tokens_to_keep=min_tokens_to_keep)+ )+ if generation_config.typical_p is not None and generation_config.typical_p < 1.0:+ processors.append(+ TypicalLogitsWarper(mass=generation_config.typical_p, min_tokens_to_keep=min_tokens_to_keep)+ )+ if generation_config.epsilon_cutoff is not None and 0.0 < generation_config.epsilon_cutoff < 1.0:+ processors.append(+ EpsilonLogitsWarper(+ epsilon=generation_config.epsilon_cutoff, min_tokens_to_keep=min_tokens_to_keep+ )+ )+ if generation_config.eta_cutoff is not None and 0.0 < generation_config.eta_cutoff < 1.0:+ processors.append(+ EtaLogitsWarper(+ epsilon=generation_config.eta_cutoff, min_tokens_to_keep=min_tokens_to_keep, device=device+ )+ )++ # Watermarking should be after all logits processing is finished (see #34630)+ if generation_config.watermarking_config is not None:+ processors.append(+ generation_config.watermarking_config.construct_processor(self.config.vocab_size, device)+ )++ # `LogitNormalization` should always be the last logit processor, when present+ if generation_config.renormalize_logits is True:+ processors.append(LogitNormalization())+ return processors++ def _get_stopping_criteria(+ self,+ generation_config: GenerationConfig,+ stopping_criteria: Optional[StoppingCriteriaList],+ tokenizer: Optional["PreTrainedTokenizerBase"] = None,+ **kwargs,+ ) -> StoppingCriteriaList:+ criteria = StoppingCriteriaList()+ if generation_config.max_length is not None:+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)+ criteria.append(+ MaxLengthCriteria(+ max_length=generation_config.max_length,+ max_position_embeddings=max_position_embeddings,+ )+ )+ if generation_config.max_time is not None:+ criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))+ if generation_config.stop_strings is not None:+ if tokenizer is None:+ raise ValueError(+ "There are one or more stop strings, either in the arguments to `generate` or in the "+ "model's generation config, but we could not locate a tokenizer. When generating with "+ "stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`."+ )+ criteria.append(StopStringCriteria(stop_strings=generation_config.stop_strings, tokenizer=tokenizer))+ if generation_config._eos_token_tensor is not None:+ criteria.append(EosTokenCriteria(eos_token_id=generation_config._eos_token_tensor))+ if (+ generation_config.is_assistant+ and generation_config.assistant_confidence_threshold is not None+ and generation_config.assistant_confidence_threshold > 0+ ):+ criteria.append(+ ConfidenceCriteria(assistant_confidence_threshold=generation_config.assistant_confidence_threshold)+ )+ criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)+ return criteria++ def _merge_criteria_processor_list(+ self,+ default_list: Union[LogitsProcessorList, StoppingCriteriaList],+ custom_list: Union[LogitsProcessorList, StoppingCriteriaList],+ ) -> Union[LogitsProcessorList, StoppingCriteriaList]:+ if len(custom_list) == 0:+ return default_list+ for default in default_list:+ for custom in custom_list:+ if type(custom) is type(default):+ object_type = "stopping criteria" if isinstance(custom, StoppingCriteria) else "logits processor"+ raise ValueError(+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"+ f" `.generate()`, but it has already been created with the values {default}. {default} has been"+ " created by passing the corresponding arguments to generate or by the model's config default"+ f" values. If you just want to change the default values of {object_type} consider passing"+ f" them as arguments to `.generate()` instead of using a custom {object_type}."+ )+ default_list.extend(custom_list)+ return default_list++ def compute_transition_scores(+ self,+ sequences: torch.Tensor,+ scores: Tuple[torch.Tensor],+ beam_indices: Optional[torch.Tensor] = None,+ normalize_logits: bool = False,+ ) -> torch.Tensor:+ """+ Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was+ used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.++ Parameters:+ sequences (`torch.LongTensor`):+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or+ shorter if all batches finished early due to the `eos_token_id`.+ scores (`tuple(torch.FloatTensor)`):+ Transition scores for each vocabulary token at each generation step. Beam transition scores consisting+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.+ beam_indices (`torch.LongTensor`, *optional*):+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape+ `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at+ generate-time.+ normalize_logits (`bool`, *optional*, defaults to `False`):+ Whether to normalize the logits (which, for legacy reasons, may be unnormalized).++ Return:+ `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing+ the transition scores (logits)++ Examples:++ ```python+ >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM+ >>> import numpy as np++ >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")+ >>> tokenizer.pad_token_id = tokenizer.eos_token_id+ >>> inputs = tokenizer(["Today is"], return_tensors="pt")++ >>> # Example 1: Print the scores for each token generated with Greedy Search+ >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)+ >>> transition_scores = model.compute_transition_scores(+ ... outputs.sequences, outputs.scores, normalize_logits=True+ ... )+ >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for+ >>> # encoder-decoder models, like BART or T5.+ >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]+ >>> generated_tokens = outputs.sequences[:, input_length:]+ >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):+ ... # | token | token string | log probability | probability+ ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")+ | 262 | the | -1.414 | 24.33%+ | 1110 | day | -2.609 | 7.36%+ | 618 | when | -2.010 | 13.40%+ | 356 | we | -1.859 | 15.58%+ | 460 | can | -2.508 | 8.14%++ >>> # Example 2: Reconstruct the sequence scores from Beam Search+ >>> outputs = model.generate(+ ... **inputs,+ ... max_new_tokens=5,+ ... num_beams=4,+ ... num_return_sequences=4,+ ... return_dict_in_generate=True,+ ... output_scores=True,+ ... )+ >>> transition_scores = model.compute_transition_scores(+ ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False+ ... )+ >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.+ >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the+ >>> # use case, you might want to recompute it with `normalize_logits=True`.+ >>> # Tip 2: the output length does NOT include the input length+ >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)+ >>> length_penalty = model.generation_config.length_penalty+ >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)+ >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))+ True+ ```"""+ # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent+ # to a beam search approach were the first (and only) beam is always selected+ if beam_indices is None:+ beam_indices = torch.arange(scores[0].shape[0]).view(-1, 1).to(sequences.device)+ beam_indices = beam_indices.expand(-1, len(scores))++ # 2. reshape scores as [batch_size*vocab_size, # generation steps] with # generation steps being+ # seq_len - input_length+ scores = torch.stack(scores).reshape(len(scores), -1).transpose(0, 1)++ # 3. Optionally normalize the logits (across the vocab dimension)+ if normalize_logits:+ scores = scores.reshape(-1, self.config.vocab_size, scores.shape[-1])+ scores = torch.nn.functional.log_softmax(scores, dim=1)+ scores = scores.reshape(-1, scores.shape[-1])++ # 4. cut beam_indices to longest beam length+ beam_indices_mask = beam_indices < 0+ max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max()+ beam_indices = beam_indices.clone()[:, :max_beam_length]+ beam_indices_mask = beam_indices_mask[:, :max_beam_length]++ # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards+ beam_indices[beam_indices_mask] = 0++ # 6. multiply beam_indices with vocab size to gather correctly from scores+ beam_sequence_indices = beam_indices * self.config.vocab_size++ # 7. Define which indices contributed to scores+ cut_idx = sequences.shape[-1] - max_beam_length+ indices = sequences[:, cut_idx:] + beam_sequence_indices++ # 8. Compute scores+ transition_scores = scores.gather(0, indices)++ # 9. Mask out transition_scores of beams that stopped early+ transition_scores[beam_indices_mask] = 0++ return transition_scores++ def _validate_model_class(self):+ """+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the+ right class to use.+ """+ # TODO(joao): remove this function in v4.50, i.e. when we remove the inheritance of `GenerationMixin` from+ # `PreTrainedModel`. With that inheritance removed, all model classes inheriting from `GenerationMixin` can+ # safely call `GenerationMixin.generate`+ if not is_torchdynamo_compiling() and not self.can_generate():+ terminations_with_generation_support = [+ "ForCausalLM",+ "ForConditionalGeneration",+ "ForSpeechSeq2Seq",+ "ForVision2Seq",+ ]+ raise TypeError(+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "+ "it doesn't have a language model head. Classes that support generation often end in one of these "+ f"names: {terminations_with_generation_support}."+ )++ def _validate_assistant(self, assistant_model, tokenizer, assistant_tokenizer):+ if assistant_model is None:+ return++ if self.config.is_encoder_decoder and not assistant_model.config.is_encoder_decoder:+ attributes_to_check = ["encoder_attention_heads", "encoder_ffn_dim", "encoder_layers"]+ attributes_to_check = [attr for attr in dir(assistant_model.config) if attr in attributes_to_check]+ are_equal = all(+ getattr(self.config, attr) == getattr(assistant_model.config, attr) for attr in attributes_to_check+ )+ if not are_equal:+ raise ValueError(+ "The main model and the assistant don't have compatible encoder-dependent input shapes. "+ "Ensure you load the assistant with the correct encoder-decoder class, e.g. `AutoModelForSpeechSeq2Seq` for Whisper."+ )++ doc_reference = (+ "(see https://huggingface.co/docs/transformers/en/generation_strategies#universal-assisted-decoding)"+ )+ if self.config.get_text_config().vocab_size == assistant_model.config.get_text_config().vocab_size:+ if assistant_tokenizer is not None:+ raise ValueError(+ f"`assistant_tokenizer` is not required when the main and assistant models use the same tokenizer. Please omit `assistant_tokenizer` from `generate()` {doc_reference}."+ )+ else:+ if tokenizer is None or assistant_tokenizer is None:+ raise ValueError(+ f"The main and assistant moedels have different tokenizers. Please provide `tokenizer` and `assistant_tokenizer` to `generate()` {doc_reference}."+ )++ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""+ # If a `Cache` instance is passed, checks whether the model is compatible with it+ if isinstance(model_kwargs.get("past_key_values", None), Cache) and not self._supports_cache_class:+ raise ValueError(+ f"{self.__class__.__name__} does not support an instance of `Cache` as `past_key_values`. Please "+ "check the model documentation for supported cache formats."+ )++ # Excludes arguments that are handled before calling any model function+ if self.config.is_encoder_decoder:+ for key in ["decoder_input_ids"]:+ model_kwargs.pop(key, None)++ unused_model_args = []+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)+ if "kwargs" in model_args or "model_kwargs" in model_args:+ model_args |= set(inspect.signature(self.forward).parameters)++ # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`+ if self.config.is_encoder_decoder:+ base_model = getattr(self, self.base_model_prefix, None)++ # allow encoder kwargs+ encoder = getattr(self, "encoder", None)+ # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.+ # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`+ # TODO: A better way to handle this.+ if encoder is None and base_model is not None:+ encoder = getattr(base_model, "encoder", None)++ if encoder is not None:+ encoder_model_args = set(inspect.signature(encoder.forward).parameters)+ model_args |= encoder_model_args++ # allow decoder kwargs+ decoder = getattr(self, "decoder", None)+ if decoder is None and base_model is not None:+ decoder = getattr(base_model, "decoder", None)++ if decoder is not None:+ decoder_model_args = set(inspect.signature(decoder.forward).parameters)+ model_args |= {f"decoder_{x}" for x in decoder_model_args}++ # allow assistant_encoder_outputs to be passed if we're doing assisted generating+ if "assistant_encoder_outputs" in model_kwargs:+ model_args |= {"assistant_encoder_outputs"}++ for key, value in model_kwargs.items():+ if value is not None and key not in model_args:+ unused_model_args.append(key)++ if unused_model_args and False:+ raise ValueError(+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"+ " generate arguments will also show up in this list)"+ )++ def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):+ """Performs validation related to the resulting generated length"""++ # Can't throw warnings/exceptions during compilation+ if is_torchdynamo_compiling():+ return++ # 1. Max length warnings related to poor parameterization+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:+ # 20 is the default max_length of the generation config+ warnings.warn(+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "+ "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "+ "generation.",+ UserWarning,+ )+ if input_ids_length >= generation_config.max_length:+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"+ raise ValueError(+ f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"+ " increasing `max_length` or, better yet, setting `max_new_tokens`."+ )++ # 2. Min length warnings due to unfeasible parameter combinations+ min_length_error_suffix = (+ " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "+ "increase the maximum length."+ )+ if has_default_max_length:+ min_length_error_suffix += (+ f" Note that `max_length` is set to {generation_config.max_length}, its default value."+ )+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:+ warnings.warn(+ f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,+ UserWarning,+ )+ if generation_config.min_new_tokens is not None:+ min_length = generation_config.min_new_tokens + input_ids_length+ if min_length > generation_config.max_length:+ warnings.warn(+ f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "+ f"added to the prompt length ({input_ids_length}), is larger than"+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,+ UserWarning,+ )++ def _prepare_generated_length(+ self,+ generation_config,+ has_default_max_length,+ has_default_min_length,+ model_input_name,+ input_ids_length,+ inputs_tensor,+ ):+ """Prepared max and min length in generation configs to avoid clashes between similar attributes"""++ if generation_config.max_new_tokens is not None:+ if not has_default_max_length and generation_config.max_length is not None:+ logger.warning(+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "+ "Please refer to the documentation for more information. "+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"+ )+ generation_config.max_length = generation_config.max_new_tokens + input_ids_length++ # if both `inputs_embeds` and `input_ids` are passed, we do not correct the length+ # otherwise we need total length [inputs-embeds-len + new-tokens-len] to not go beyond indicated `max_length``+ elif (+ model_input_name == "inputs_embeds"+ and input_ids_length != inputs_tensor.shape[1]+ and input_ids_length != 0+ and not self.config.is_encoder_decoder+ ):+ generation_config.max_length -= inputs_tensor.shape[1]+ elif has_default_max_length: # by default let's always generate 20 new tokens+ if generation_config.max_length == GenerationConfig().max_length:+ generation_config.max_length = generation_config.max_length + input_ids_length+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)+ if max_position_embeddings is not None:+ generation_config.max_length = min(generation_config.max_length, max_position_embeddings)++ # same for min length+ if generation_config.min_new_tokens is not None:+ if not has_default_min_length:+ logger.warning(+ f"Both `min_new_tokens` (={generation_config.min_new_tokens}) and `min_length`(="+ f"{generation_config.min_length}) seem to have been set. `min_new_tokens` will take precedence. "+ "Please refer to the documentation for more information. "+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"+ )+ generation_config.min_length = generation_config.min_new_tokens + input_ids_length++ elif (+ model_input_name == "inputs_embeds"+ and input_ids_length != inputs_tensor.shape[1]+ and not self.config.is_encoder_decoder+ ):+ generation_config.min_length = max(generation_config.min_length - inputs_tensor.shape[1], 0)++ return generation_config++ def _prepare_generation_config(+ self, generation_config: Optional[GenerationConfig], **kwargs: Dict+ ) -> Tuple[GenerationConfig, Dict]:+ """+ Prepares the base generation config, then applies any generation configuration options from kwargs. This+ function handles retrocompatibility with respect to configuration files.+ """+ # TODO joao: when we can detect `fullgraph=True` in `torch.compile` (https://github.com/pytorch/pytorch/pull/120400)+ # replace `is_torchdynamo_compiling` by the corresponding check. As it is, we are being too restrictive with+ # the parameterization in `fullgraph=False` so as to enable `fullgraph=True`.++ # priority: `generation_config` argument > `model.generation_config` (the default generation config)+ using_model_generation_config = False+ if generation_config is None:+ # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,+ # the following conditions must be met+ # 1) the generation config must have been created from the model config (`_from_model_config` field);+ # 2) the generation config must have seen no modification since its creation (the hash is the same);+ # 3) there are non-default generation parameters in the model config.+ # 4) the user must have set new generation parameters in the model config.+ # NOTE: `torch.compile` can't compile `hash`, this legacy support is disabled with compilation.+ if (+ not is_torchdynamo_compiling()+ and self.generation_config._from_model_config # 1)+ and self.generation_config._original_object_hash == hash(self.generation_config) # 2)+ and len(self.config._get_non_default_generation_parameters()) > 0 # 3)+ ):+ new_generation_config = GenerationConfig.from_model_config(self.config)+ if new_generation_config != self.generation_config: # 4)+ warnings.warn(+ "You have modified the pretrained model configuration to control generation. This is a"+ " deprecated strategy to control generation and will be removed in v5."+ " Please use and modify the model generation configuration (see"+ " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )",+ UserWarning,+ )+ self.generation_config = new_generation_config++ generation_config = self.generation_config+ using_model_generation_config = True++ # `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`+ # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an+ # exception will be raised in `_validate_model_kwargs`+ if not is_torchdynamo_compiling():+ generation_config = copy.deepcopy(generation_config)+ model_kwargs = generation_config.update(**kwargs)+ # If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model+ if not using_model_generation_config:+ if generation_config.bos_token_id is None:+ generation_config.bos_token_id = self.generation_config.bos_token_id+ if generation_config.eos_token_id is None:+ generation_config.eos_token_id = self.generation_config.eos_token_id+ if generation_config.pad_token_id is None:+ generation_config.pad_token_id = self.generation_config.pad_token_id+ if generation_config.decoder_start_token_id is None:+ generation_config.decoder_start_token_id = self.generation_config.decoder_start_token_id+ else:+ model_kwargs = kwargs++ return generation_config, model_kwargs++ def _get_initial_cache_position(self, input_ids, model_kwargs):+ """Calculates `cache_position` for the pre-fill stage based on `input_ids` and optionally past length"""+ # `torch.compile`-friendly `torch.arange` from a shape -- the lines below are equivalent to `torch.arange`+ if "inputs_embeds" in model_kwargs and not self.config.is_encoder_decoder:+ cache_position = torch.ones_like(model_kwargs["inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1+ elif "decoder_inputs_embeds" in model_kwargs and self.config.is_encoder_decoder:+ cache_position = (+ torch.ones_like(model_kwargs["decoder_inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1+ )+ else:+ cache_position = torch.ones_like(input_ids[0, :], dtype=torch.int64).cumsum(0) - 1++ past_length = 0+ if model_kwargs.get("past_key_values") is not None:+ cache = model_kwargs["past_key_values"]+ past_length = 0+ if not isinstance(cache, Cache):+ past_length = cache[0][0].shape[2]+ elif hasattr(cache, "get_seq_length") and cache.get_seq_length() is not None:+ past_length = cache.get_seq_length()++ # TODO(joao): this is not torch.compile-friendly, find a work-around. If the cache is not empty,+ # end-to-end compilation will yield bad results because `cache_position` will be incorrect.+ if not is_torchdynamo_compiling():+ cache_position = cache_position[past_length:]++ model_kwargs["cache_position"] = cache_position+ return model_kwargs++ def _get_cache(+ self, cache_implementation: str, batch_size: int, max_cache_len: int, device: torch.device, model_kwargs+ ) -> Cache:+ """+ Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a+ new `generate` call requires a larger cache or uses a different batch size.++ Returns the resulting cache object.+ """+ cache_cls: Cache = NEED_SETUP_CACHE_CLASSES_MAPPING[cache_implementation]+ requires_cross_attention_cache = (+ self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None+ )++ if hasattr(self, "_cache"):+ cache_to_check = self._cache.self_attention_cache if requires_cross_attention_cache else self._cache++ if cache_implementation == "sliding_window":+ max_cache_len = min(self.config.sliding_window, max_cache_len)++ need_new_cache = (+ not hasattr(self, "_cache")+ or (not isinstance(cache_to_check, cache_cls))+ or cache_to_check.max_batch_size != batch_size+ )+ if cache_implementation != "mamba":+ need_new_cache = need_new_cache or cache_to_check.max_cache_len < max_cache_len++ if requires_cross_attention_cache and hasattr(self, "_cache"):+ need_new_cache = (+ need_new_cache+ or self._cache.cross_attention_cache.max_cache_len != model_kwargs["encoder_outputs"][0].shape[1]+ )++ if need_new_cache:+ if hasattr(self.config, "_pre_quantization_dtype"):+ cache_dtype = self.config._pre_quantization_dtype+ else:+ if not is_torchdynamo_compiling():+ cache_dtype = self.dtype+ else:+ # NOTE: self.dtype is not compatible with torch.compile, as it calls `self.parameters()`.+ # Workaround: trust the lm_head, whose attribute name is somewhat consistent across generative+ # models. May cause trobles with non-text modalities.+ cache_dtype = self.get_output_embeddings().weight.dtype++ def get_layer_device_map(execution_device_map: Optional[dict] = None):+ num_hidden_layers = self.config.get_text_config().num_hidden_layers+ if execution_device_map is None:+ return None+ elif len(execution_device_map) == 1 and "" in execution_device_map:+ return {idx: execution_device_map[""] for idx in range(num_hidden_layers)}+ layer_device_map = {}+ for layer in execution_device_map:+ for idx in range(num_hidden_layers):+ if f".{idx}." in f"{layer}.":+ layer_device_map[idx] = execution_device_map[layer]+ break+ for idx in range(num_hidden_layers):+ if idx not in layer_device_map:+ raise RuntimeError(f"layer {idx} has not been mapped to a device.")+ return layer_device_map++ execution_device_map = None+ # Taken from dispatch_model from accelerate.+ # This is needed here if we don't want to make changes in accelerate in order to save execution_device+ # For offloaded case, we need to get the execution device, not just the device where it is offloaded+ if hasattr(self, "hf_device_map"):+ if set(self.hf_device_map.values()) == {"cpu"} or set(self.hf_device_map.values()) == {"cpu", "disk"}:+ main_device = "cpu"+ else:+ main_device = [d for d in self.hf_device_map.values() if d not in ["cpu", "disk"]][0]+ execution_device_map = {+ name: main_device if device in ["cpu", "disk"] else device+ for name, device in self.hf_device_map.items()+ }+ layer_device_map = get_layer_device_map(execution_device_map)++ cache_kwargs = {+ "config": self.config.get_text_config(),+ "max_batch_size": batch_size,+ "max_cache_len": max_cache_len,+ "device": device,+ "dtype": cache_dtype,+ "layer_device_map": layer_device_map,+ }+ self._cache = cache_cls(**cache_kwargs)+ if requires_cross_attention_cache:+ encoder_kwargs = cache_kwargs.copy()+ encoder_kwargs["max_cache_len"] = model_kwargs["encoder_outputs"][0].shape[1]+ self._cache = EncoderDecoderCache(self._cache, cache_cls(**encoder_kwargs))+ else:+ self._cache.reset()+ return self._cache++ def _supports_default_dynamic_cache(self) -> bool:+ """+ Return `True` if current model can use a `DynamicCache` instance when initializing the `past_key_values`.+ This is mostly the same as `_supports_cache_class` attribute, but add exception for `Jamba` model which+ uses its own `HybridMambaAttentionDynamicCache` and do not need to initialize the Cache in advance in+ order to save memory (because no back and forth `to_legacy_cache` and `from_legacy_cache` will be performed+ for `HybridMambaAttentionDynamicCache`).+ """+ return (+ self._supports_cache_class+ and "jamba" not in self.__class__.__name__.lower()+ and "zamba" not in self.__class__.__name__.lower()+ and "bamba" not in self.__class__.__name__.lower()+ )++ def _prepare_cache_for_generation(+ self,+ generation_config: GenerationConfig,+ model_kwargs: Dict,+ assistant_model: "PreTrainedModel",+ batch_size: int,+ max_cache_length: int,+ device: torch.device,+ ) -> bool:+ """+ Prepares the cache for generation (if applicable), given `generate`'s parameterization. If a cache is+ instantiated, writes it to `model_kwargs`, under the name expected by the model.+ """++ cache_name = "past_key_values" if "mamba" not in self.__class__.__name__.lower() else "cache_params"+ requires_cross_attention_cache = (+ self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None+ )++ # Quick escape route 1: if the user specifies a cache, we only need to:+ # a) check for conflicting `generate` arguments+ # b) convert to the new cache format (if the user passes a legacy cache and model supports it)+ user_defined_cache = model_kwargs.get(cache_name)+ if user_defined_cache is not None:+ if generation_config.cache_implementation is not None:+ raise ValueError(+ f"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a "+ "Cache object) is unsupported. Please use only one of the two."+ )+ if isinstance(user_defined_cache, tuple) and self._supports_default_dynamic_cache():+ model_kwargs[cache_name] = (+ DynamicCache.from_legacy_cache(user_defined_cache)+ if not requires_cross_attention_cache+ else EncoderDecoderCache.from_legacy_cache(user_defined_cache)+ )+ return++ # Quick escape route 2: if the user specifies no cache is to be used. (conflicting arguments are handled in+ # `generation_config.validate()`)+ if generation_config.use_cache is False:+ return++ # Quick escape route 3: model that only supports legacy caches = nothing to prepare+ if not self._supports_default_dynamic_cache():+ if generation_config.cache_implementation is not None:+ warnings.warn(+ "This model does not support `Cache` instances, it only supports the legacy cache format (tuple "+ f"of tuples). `cache_implementation` (set to {generation_config.cache_implementation}) will be "+ "ignored.",+ UserWarning,+ )+ return++ # Otherwise we NEED to prepare a cache, based on `generation_config.cache_implementation`++ # TODO(joao): support static caches in assisted generation. assisted generation needs to roll back caches,+ # which is only supported in dynamic caches atm+ if assistant_model is not None and generation_config.cache_implementation is not None:+ logger.warning_once(+ "An assistant model is provided, using a dynamic cache instead of a cache of type="+ f"'{generation_config.cache_implementation}'."+ )+ generation_config.cache_implementation = None++ if generation_config.cache_implementation is not None:+ if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:+ if generation_config.cache_implementation == "static" and not self._supports_static_cache:+ raise ValueError(+ "This model does not support `cache_implementation='static'`. Please check the following "+ "issue: https://github.com/huggingface/transformers/issues/28981"+ )+ model_kwargs[cache_name] = self._get_cache(+ cache_implementation=generation_config.cache_implementation,+ batch_size=max(generation_config.num_beams, generation_config.num_return_sequences) * batch_size,+ max_cache_len=max_cache_length,+ device=device,+ model_kwargs=model_kwargs,+ )+ elif generation_config.cache_implementation == "quantized":+ if not self._supports_quantized_cache:+ raise ValueError(+ "This model does not support the quantized cache. If you want your model to support quantized "+ "cache, please open an issue and tag @zucchini-nlp."+ )++ cache_config = (+ generation_config.cache_config+ if generation_config.cache_config is not None+ else QuantizedCacheConfig()+ )+ cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]++ if cache_config.backend == "quanto" and not is_optimum_quanto_available():+ raise ImportError(+ "You need to install optimum-quanto in order to use KV cache quantization with optimum-quanto backend. "+ "Please install it via with `pip install optimum-quanto`"+ )+ elif cache_config.backend == "HQQ" and not is_hqq_available():+ raise ImportError(+ "You need to install `HQQ` in order to use KV cache quantization with HQQ backend. "+ "Please install it via with `pip install hqq`"+ )++ model_kwargs[cache_name] = cache_class(cache_config)+ elif generation_config.cache_implementation == "offloaded":+ model_kwargs[cache_name] = OffloadedCache()++ # Use DynamicCache() instance by default. This will avoid back and forth from legacy format that+ # keeps copying the cache thus using much more memory+ else:+ model_kwargs[cache_name] = (+ DynamicCache()+ if not requires_cross_attention_cache+ else EncoderDecoderCache(DynamicCache(), DynamicCache())+ )++ def _supports_num_logits_to_keep(self) -> bool:+ """+ Return True if the current model supports the keyword argument `num_logits_to_keep` in forward()+ to save memory. Checking it in this way allows to avoid using a new model attribute.+ """+ return "num_logits_to_keep" in set(inspect.signature(self.forward).parameters.keys())++ def _prepare_special_tokens(+ self,+ generation_config: GenerationConfig,+ kwargs_has_attention_mask: Optional[bool] = None,+ device: Optional[Union[torch.device, str]] = None,+ ):+ """+ Prepares the special tokens for generation, overwriting the generation config with their processed versions+ converted to tensor.++ Note that `generation_config` is changed in place and stops being serializable after this method is called.+ That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the+ function). However, if called outside `generate`, consider creating a copy of `generation_config` first.+ """++ # Convert special tokens to tensors+ def _tensor_or_none(token, device=None):+ if token is None:+ return token++ device = device if device is not None else self.device+ if isinstance(token, torch.Tensor):+ return token.to(device)+ return torch.tensor(token, device=device, dtype=torch.long)++ bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)+ eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)+ pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)+ decoder_start_token_tensor = _tensor_or_none(generation_config.decoder_start_token_id, device=device)++ # for BC we also try to get `decoder_start_token_id` or `bos_token_id` (#30892)+ if self.config.is_encoder_decoder:+ decoder_start_token_tensor = (+ decoder_start_token_tensor if decoder_start_token_tensor is not None else bos_token_tensor+ )++ # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).+ if eos_token_tensor is not None and eos_token_tensor.ndim == 0:+ eos_token_tensor = eos_token_tensor.unsqueeze(0)++ # Set pad token if unset (and there are conditions to do so)+ if pad_token_tensor is None and eos_token_tensor is not None:+ if not is_torchdynamo_compiling():+ if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:+ logger.warning(+ "The attention mask and the pad token id were not set. As a consequence, you may observe "+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."+ )+ pad_token_tensor = eos_token_tensor[0]+ logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")++ # Sanity checks/warnings+ if self.config.is_encoder_decoder and decoder_start_token_tensor is None:+ raise ValueError(+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."+ )+ if not is_torchdynamo_compiling(): # Checks that depend on tensor-dependent control flow+ if (+ eos_token_tensor is not None+ and isin_mps_friendly(elements=eos_token_tensor, test_elements=pad_token_tensor).any()+ ):+ if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:+ logger.warning_once(+ "The attention mask is not set and cannot be inferred from input because pad token is same as "+ "eos token. As a consequence, you may observe unexpected behavior. Please pass your input's "+ "`attention_mask` to obtain reliable results."+ )+ if eos_token_tensor is not None and (+ torch.is_floating_point(eos_token_tensor) or (eos_token_tensor < 0).any()+ ):+ logger.warning(+ f"`eos_token_id` should consist of positive integers, but is {eos_token_tensor}. Your generation "+ "will not stop until the maximum length is reached. Depending on other flags, it may even crash."+ )++ # Update generation config with the updated special tokens tensors+ # NOTE: this must be written into a different attribute name than the one holding the original special tokens+ # (in their non-tensor form), in order to enable end-to-end compilation. See+ # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations+ generation_config._bos_token_tensor = bos_token_tensor+ generation_config._eos_token_tensor = eos_token_tensor+ generation_config._pad_token_tensor = pad_token_tensor+ generation_config._decoder_start_token_tensor = decoder_start_token_tensor++ @torch.no_grad()+ def generate(+ self,+ inputs: Optional[torch.Tensor] = None,+ generation_config: Optional[GenerationConfig] = None,+ logits_processor: Optional[LogitsProcessorList] = None,+ stopping_criteria: Optional[StoppingCriteriaList] = None,+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,+ synced_gpus: Optional[bool] = None,+ assistant_model: Optional["PreTrainedModel"] = None,+ streamer: Optional["BaseStreamer"] = None,+ negative_prompt_ids: Optional[torch.Tensor] = None,+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,+ **kwargs,+ ) -> Union[GenerateOutput, torch.LongTensor]:+ r"""++ Generates sequences of token ids for models with a language modeling head.++ <Tip warning={true}>++ Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the+ model's default generation configuration. You can override any `generation_config` by passing the corresponding+ parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.++ For an overview of generation strategies and code examples, check out the [following+ guide](../generation_strategies).++ </Tip>++ Parameters:+ inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):+ The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the+ method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`+ should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of+ `input_ids`, `input_values`, `input_features`, or `pixel_values`.+ generation_config ([`~generation.GenerationConfig`], *optional*):+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`+ passed to generate matching the attributes of `generation_config` will override them. If+ `generation_config` is not provided, the default will be used, which has the following loading+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s+ default values, whose documentation should be checked to parameterize generation.+ logits_processor (`LogitsProcessorList`, *optional*):+ Custom logits processors that complement the default logits processors built from arguments and+ generation config. If a logit processor is passed that is already created with the arguments or a+ generation config an error is thrown. This feature is intended for advanced users.+ stopping_criteria (`StoppingCriteriaList`, *optional*):+ Custom stopping criteria that complements the default stopping criteria built from arguments and a+ generation config. If a stopping criteria is passed that is already created with the arguments or a+ generation config an error is thrown. If your stopping criteria depends on the `scores` input, make+ sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is+ intended for advanced users.+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):+ If provided, this function constraints the beam search to allowed tokens only at each step. If not+ provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and+ `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned+ on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful+ for constrained generation conditioned on the prefix, as described in [Autoregressive Entity+ Retrieval](https://arxiv.org/abs/2010.00904).+ synced_gpus (`bool`, *optional*):+ Whether to continue running the while loop until max_length. Unless overridden, this flag will be set+ to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid+ deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.+ assistant_model (`PreTrainedModel`, *optional*):+ An assistant model that can be used to accelerate generation. The assistant model must have the exact+ same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model+ is much faster than running generation with the model you're calling generate from. As such, the+ assistant model should be much smaller.+ streamer (`BaseStreamer`, *optional*):+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.+ negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):+ The negative prompt needed for some processors such as CFG. The batch size must match the input batch+ size. This is an experimental feature, subject to breaking API changes in future versions.+ negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):+ Attention_mask for `negative_prompt_ids`.+ kwargs (`Dict[str, Any]`, *optional*):+ Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.++ Return:+ [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`+ or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.++ If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible+ [`~utils.ModelOutput`] types are:++ - [`~generation.GenerateDecoderOnlyOutput`],+ - [`~generation.GenerateBeamDecoderOnlyOutput`]++ If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible+ [`~utils.ModelOutput`] types are:++ - [`~generation.GenerateEncoderDecoderOutput`],+ - [`~generation.GenerateBeamEncoderDecoderOutput`]+ """++ if "guidance_scale" in kwargs:+ self._guidance_scale = kwargs.get("guidance_scale",1)+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call+ self._validate_model_class()+ tokenizer = kwargs.pop("tokenizer", None) # Pull this out first, we only use it for stopping criteria+ assistant_tokenizer = kwargs.pop("assistant_tokenizer", None) # only used for assisted generation++ generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)+ self._validate_model_kwargs(model_kwargs.copy())+ self._validate_assistant(assistant_model, tokenizer, assistant_tokenizer)++ # 2. Set generation parameters if not already defined+ if synced_gpus is None:+ synced_gpus = (is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)) and dist.get_world_size() > 1++ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()++ accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())+ requires_attention_mask = "encoder_outputs" not in model_kwargs+ kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None++ # 3. Define model inputs+ inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(+ inputs, generation_config.bos_token_id, model_kwargs+ )+ batch_size = inputs_tensor.shape[0]++ device = inputs_tensor.device+ self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=device)++ # decoder-only models must use left-padding for batched generation.+ if not self.config.is_encoder_decoder and not is_torchdynamo_compiling():+ # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`+ # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.+ if (+ generation_config._pad_token_tensor is not None+ and batch_size > 1+ and len(inputs_tensor.shape) == 2+ and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor) > 0+ ):+ logger.warning(+ "A decoder-only architecture is being used, but right-padding was detected! For correct "+ "generation results, please set `padding_side='left'` when initializing the tokenizer."+ )++ # 4. Define other model kwargs+ # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are+ # generating the first new token or not, and we only want to use the embeddings for the first new token)+ if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":+ generation_config.use_cache = True++ if not kwargs_has_attention_mask and requires_attention_mask and accepts_attention_mask:+ model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(+ inputs_tensor, generation_config, model_kwargs+ )+ elif kwargs_has_attention_mask:+ # TODO (joao): generalize this check with other types of inputs+ if model_input_name == "input_ids" and len(model_kwargs["attention_mask"].shape) > 2:+ raise ValueError("`attention_mask` passed to `generate` must be 2D.")++ if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:+ # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(+ inputs_tensor, model_kwargs, model_input_name, generation_config+ )++ # 5. Prepare `input_ids` which will be used for auto-regressive generation+ if self.config.is_encoder_decoder:+ input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(+ batch_size=batch_size,+ model_input_name=model_input_name,+ model_kwargs=model_kwargs,+ decoder_start_token_id=generation_config._decoder_start_token_tensor,+ device=inputs_tensor.device,+ )+ else:+ input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")++ if generation_config.token_healing:+ input_ids = self.heal_tokens(input_ids, tokenizer)++ if streamer is not None:+ streamer.put(input_ids.cpu())++ # 6. Prepare `max_length` depending on other stopping criteria.+ input_ids_length = input_ids.shape[-1]+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None+ has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None+ generation_config = self._prepare_generated_length(+ generation_config=generation_config,+ has_default_max_length=has_default_max_length,+ has_default_min_length=has_default_min_length,+ model_input_name=model_input_name,+ inputs_tensor=inputs_tensor,+ input_ids_length=input_ids_length,+ )++ # If the model supports `num_logits_to_keep` in forward(), set it to 1 to avoid computing the whole+ # logit matrix. This can save a lot of memory during the first forward pass. Note that assisted decoding+ # dynamically overrides this value as it can need more than the last token logits+ if self._supports_num_logits_to_keep() and "num_logits_to_keep" not in model_kwargs:+ model_kwargs["num_logits_to_keep"] = 1++ self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)++ # 7. Prepare the cache.+ # - `model_kwargs` may be updated in place with a cache as defined by the parameters in `generation_config`.+ # - different models have a different cache name expected by the model (default = "past_key_values")+ # - `max_length`, prepared above, is used to determine the maximum cache length+ # TODO (joao): remove `user_defined_cache` after v4.47 (remove default conversion to legacy format)+ cache_name = "past_key_values" if "mamba" not in self.__class__.__name__.lower() else "cache_params"+ user_defined_cache = model_kwargs.get(cache_name)+ max_cache_length = generation_config.max_length+ if (+ inputs_tensor.shape[1] != input_ids_length+ and model_input_name == "inputs_embeds"+ and not self.config.is_encoder_decoder+ ):+ max_cache_length += inputs_tensor.shape[1]+ self._prepare_cache_for_generation(+ generation_config, model_kwargs, assistant_model, batch_size, max_cache_length, device+ )++ # 8. determine generation mode+ generation_mode = generation_config.get_generation_mode(assistant_model)++ if streamer is not None and (generation_config.num_beams > 1):+ raise ValueError(+ "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."+ )++ if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type and False:+ warnings.warn(+ "You are calling .generate() with the `input_ids` being on a device type different"+ f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"+ f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."+ " Please make sure that you have put `input_ids` to the"+ f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"+ " running `.generate()`.",+ UserWarning,+ )++ # 9. prepare logits processors and stopping criteria+ prepared_logits_processor = self._get_logits_processor(+ generation_config=generation_config,+ input_ids_seq_length=input_ids_length,+ encoder_input_ids=inputs_tensor,+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,+ logits_processor=logits_processor,+ device=inputs_tensor.device,+ model_kwargs=model_kwargs,+ negative_prompt_ids=negative_prompt_ids,+ negative_prompt_attention_mask=negative_prompt_attention_mask,+ )+ prepared_stopping_criteria = self._get_stopping_criteria(+ generation_config=generation_config, stopping_criteria=stopping_criteria, tokenizer=tokenizer, **kwargs+ )++ # Set model_kwargs `use_cache` so we can use it later in forward runs+ model_kwargs["use_cache"] = generation_config.use_cache++ # 10. go into different generation modes+ if generation_mode == GenerationMode.ASSISTED_GENERATION:+ if generation_config.num_return_sequences > 1:+ raise ValueError(+ "num_return_sequences has to be 1 when doing assisted generate, "+ f"but is {generation_config.num_return_sequences}."+ )+ if batch_size > 1:+ raise ValueError("assisted generate is only supported for batch_size = 1")+ if not model_kwargs["use_cache"]:+ raise ValueError("assisted generate requires `use_cache=True`")+ if generation_config.cache_implementation in ["static", "hybrid", "sliding_window"]:+ raise ValueError("assisted generate is not supported with Static cache classes`")+ if self._is_stateful:+ # In assisted generation we need the ability to confirm whether the model would pick certain tokens,+ # which is not possible with stateful models (they can't reset to a previous subset of generated text)+ raise ValueError(+ f"assisted generation is not supported with stateful models, such as {self.__class__.__name__}"+ )++ # 11. Get the candidate generator, given the parameterization+ candidate_generator = self._get_candidate_generator(+ generation_config=generation_config,+ input_ids=input_ids,+ inputs_tensor=inputs_tensor,+ assistant_model=assistant_model,+ logits_processor=logits_processor,+ target_tokenizer=tokenizer,+ assistant_tokenizer=assistant_tokenizer,+ model_kwargs=model_kwargs,+ )++ # 12. run assisted generate+ result = self._assisted_decoding(+ input_ids,+ candidate_generator=candidate_generator,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ streamer=streamer,+ **model_kwargs,+ )+ elif generation_mode == GenerationMode.DOLA_GENERATION:+ if self._is_stateful:+ # DoLa decoding was not designed for stateful models, and would require some changes+ raise ValueError(+ f"dola decoding is not supported with stateful models, such as {self.__class__.__name__}"+ )+ result = self._dola_decoding(+ input_ids,+ dola_layers=generation_config.dola_layers,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ streamer=streamer,+ **model_kwargs,+ )++ elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:+ if not model_kwargs["use_cache"]:+ raise ValueError("Contrastive search requires `use_cache=True`")+ if self._is_stateful:+ # Just like assisted generation, we need to be able to rollback to a previous state (see comment above)+ raise ValueError(+ f"contrastive search is not supported with stateful models, such as {self.__class__.__name__}"+ )++ result = self._contrastive_search(+ input_ids,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ streamer=streamer,+ **model_kwargs,+ )++ elif generation_mode in (GenerationMode.SAMPLE, GenerationMode.GREEDY_SEARCH):+ # 11. expand input_ids with `num_return_sequences` additional sequences per batch+ input_ids, model_kwargs = self._expand_inputs_for_generation(+ input_ids=input_ids,+ expand_size=generation_config.num_return_sequences,+ is_encoder_decoder=self.config.is_encoder_decoder,+ **model_kwargs,+ )++ # 12. run sample (it degenerates to greedy search when `generation_config.do_sample=False`)+ result = self._sample(+ input_ids,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ streamer=streamer,+ **model_kwargs,+ )++ elif generation_mode in (GenerationMode.BEAM_SAMPLE, GenerationMode.BEAM_SEARCH):+ # 11. prepare beam search scorer+ beam_scorer = BeamSearchScorer(+ batch_size=batch_size,+ num_beams=generation_config.num_beams,+ device=inputs_tensor.device,+ length_penalty=generation_config.length_penalty,+ do_early_stopping=generation_config.early_stopping,+ num_beam_hyps_to_keep=generation_config.num_return_sequences,+ max_length=generation_config.max_length,+ )++ # 12. interleave input_ids with `num_beams` additional sequences per batch+ input_ids, model_kwargs = self._expand_inputs_for_generation(+ input_ids=input_ids,+ expand_size=generation_config.num_beams,+ is_encoder_decoder=self.config.is_encoder_decoder,+ **model_kwargs,+ )++ # 13. run beam sample+ result = self._beam_search(+ input_ids,+ beam_scorer,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ **model_kwargs,+ )++ elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:+ # 11. prepare beam search scorer+ beam_scorer = BeamSearchScorer(+ batch_size=batch_size,+ num_beams=generation_config.num_beams,+ device=inputs_tensor.device,+ length_penalty=generation_config.length_penalty,+ do_early_stopping=generation_config.early_stopping,+ num_beam_hyps_to_keep=generation_config.num_return_sequences,+ num_beam_groups=generation_config.num_beam_groups,+ max_length=generation_config.max_length,+ )+ # 12. interleave input_ids with `num_beams` additional sequences per batch+ input_ids, model_kwargs = self._expand_inputs_for_generation(+ input_ids=input_ids,+ expand_size=generation_config.num_beams,+ is_encoder_decoder=self.config.is_encoder_decoder,+ **model_kwargs,+ )+ # 13. run beam search+ result = self._group_beam_search(+ input_ids,+ beam_scorer,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ **model_kwargs,+ )++ elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:+ final_constraints = []+ if generation_config.constraints is not None:+ final_constraints = generation_config.constraints++ if generation_config.force_words_ids is not None:++ def typeerror():+ raise ValueError(+ "`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]` "+ f"of positive integers, but is {generation_config.force_words_ids}."+ )++ if (+ not isinstance(generation_config.force_words_ids, list)+ or len(generation_config.force_words_ids) == 0+ ):+ typeerror()++ for word_ids in generation_config.force_words_ids:+ if isinstance(word_ids[0], list):+ if not isinstance(word_ids, list) or len(word_ids) == 0:+ typeerror()+ if any(not isinstance(token_ids, list) for token_ids in word_ids):+ typeerror()+ if any(+ any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)+ for token_ids in word_ids+ ):+ typeerror()++ constraint = DisjunctiveConstraint(word_ids)+ else:+ if not isinstance(word_ids, list) or len(word_ids) == 0:+ typeerror()+ if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):+ typeerror()++ constraint = PhrasalConstraint(word_ids)+ final_constraints.append(constraint)++ # 11. prepare beam search scorer+ constrained_beam_scorer = ConstrainedBeamSearchScorer(+ constraints=final_constraints,+ batch_size=batch_size,+ num_beams=generation_config.num_beams,+ device=inputs_tensor.device,+ length_penalty=generation_config.length_penalty,+ do_early_stopping=generation_config.early_stopping,+ num_beam_hyps_to_keep=generation_config.num_return_sequences,+ max_length=generation_config.max_length,+ )+ # 12. interleave input_ids with `num_beams` additional sequences per batch+ input_ids, model_kwargs = self._expand_inputs_for_generation(+ input_ids=input_ids,+ expand_size=generation_config.num_beams,+ is_encoder_decoder=self.config.is_encoder_decoder,+ **model_kwargs,+ )+ # 13. run beam search+ result = self._constrained_beam_search(+ input_ids,+ constrained_beam_scorer=constrained_beam_scorer,+ logits_processor=prepared_logits_processor,+ stopping_criteria=prepared_stopping_criteria,+ generation_config=generation_config,+ synced_gpus=synced_gpus,+ **model_kwargs,+ )++ # Convert to legacy cache format if requested+ if (+ generation_config.return_legacy_cache is not False # Should check for `True` after v4.47+ and not is_torchdynamo_compiling()+ and hasattr(result, "past_key_values")+ and hasattr(result.past_key_values, "to_legacy_cache")+ and result.past_key_values.to_legacy_cache is not None+ ):+ # handle BC (convert by default if he user hasn't passed a cache AND the cache is of the default type)+ should_convert_cache = generation_config.return_legacy_cache+ is_user_defined_cache = user_defined_cache is not None+ is_default_cache_type = (+ type(result.past_key_values) == DynamicCache # noqa E721+ or (+ isinstance(result.past_key_values, EncoderDecoderCache)+ and type(result.past_key_values.self_attention_cache) == DynamicCache # noqa E721+ and type(result.past_key_values.cross_attention_cache) == DynamicCache # noqa E721+ )+ )+ if not is_user_defined_cache and is_default_cache_type:+ logger.warning_once(+ "From v4.47 onwards, when a model cache is to be returned, `generate` will return a `Cache` "+ "instance instead by default (as opposed to the legacy tuple of tuples format). If you want to "+ "keep returning the legacy format, please set `return_legacy_cache=True`."+ )+ should_convert_cache = True+ if should_convert_cache:+ result.past_key_values = result.past_key_values.to_legacy_cache()+ return result++ def _has_unfinished_sequences(+ self,+ this_peer_finished: bool,+ synced_gpus: bool,+ device: torch.device,+ cur_len: Optional[int] = None,+ max_length: Optional[int] = None,+ ) -> bool:+ """+ Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is+ fed through `this_peer_finished`. ZeRO stage 3-friendly.+ """+ # torch.compile does not support data-dependent control flow. This is a workaround to allow torch.compile,+ # although we lose the ability to stop when all sequences return an EOS token (and other stopping criteria)+ # TODO (joao): remove this when torch's support for control flow is not experimental (https://pytorch.org/docs/stable/generated/torch.cond.html)+ if is_torchdynamo_compiling():+ return cur_len < max_length+ else:+ if synced_gpus:+ # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.+ # The following logic allows an early break if all peers finished generating their sequence+ this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(device)+ # send 0.0 if we finished, 1.0 otherwise+ dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)+ # did all peers finish? the reduced sum will be 0.0 then+ if this_peer_finished_flag.item() == 0.0:+ return False+ elif this_peer_finished:+ return False+ return True++ def heal_tokens(+ self, input_ids: torch.LongTensor, tokenizer: Optional["PreTrainedTokenizerBase"] = None+ ) -> torch.LongTensor:+ r"""+ Generates sequences of token ids for models with a language modeling head.+ Parameters:+ input_ids (`torch.LongTensor`): The sequence used as a prompt for the generation.+ tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used to decode the input ids.+ Return:+ `torch.LongTensor` where each sequence has its tail token replaced with its appropriate extension.+ """+ if tokenizer is None:+ raise ValueError(+ " When generating with token healing, you must pass the model's tokenizer to the `tokenizer` "+ "argument of `generate`."+ )++ bos_token_id, pad_token_id = tokenizer.bos_token_id, tokenizer.pad_token_id+ vocab_trie = ExtensionsTrie(tokenizer.get_vocab())+ generation_config = GenerationConfig(max_new_tokens=1, pad_token_id=pad_token_id)++ # assumption: leading/trailing whitespace is not meaningful, so the prompts are+ # stripped before re-tokenizing to desensitize generation to whitespace artefacts+ prompts = [p.strip() for p in tokenizer.batch_decode(input_ids, skip_special_tokens=True)]+ input_ids = tokenizer(+ prompts,+ return_tensors="pt",+ padding=True,+ ).input_ids.to(input_ids.device)++ # replace bos with pad to not condition healing on it+ input_ids = torch.where(input_ids == bos_token_id, pad_token_id, input_ids)++ """+ the latter code assumes the input_ids is not empty,+ input_id has to be checked if contains elements+ """+ if input_ids.numel() == 0:+ return input_ids++ tail_ids = input_ids[:, -1].tolist()++ space_tok = tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids(" "))[0]+ # tail tokens are used for a prefix search, thus, whitespaces are replaced with+ # their tokenization (e.g. 'Ġ') to enable search for tokens prefixed with a whitespace+ tail_toks = (tokenizer.decode(t).replace(" ", space_tok) for t in tail_ids)++ for batch_idx, (tail_id, tail_tok) in enumerate(zip(tail_ids, tail_toks)):+ batch_ids = input_ids[batch_idx]+ if torch.all(batch_ids == pad_token_id).item():+ continue # skip empty sequences (all pad ids)++ # apply bias for alternatives (extensions) to the tail token+ """+ seq_bias key has to be tuple with int so have to use+ tokenizer function to convert str to int+ """+ seq_bias = {+ (tokenizer.convert_tokens_to_ids(alt_tok),): 10.0 for alt_tok in vocab_trie.extensions(prefix=tail_tok)+ }++ if len(seq_bias) == 1:+ continue # skip if there are no token alternatives to heal with++ # slightly favor original token to limit aggressive healing e.g. 'http' -> 'https'+ seq_bias[(tail_id,)] += 1.0+ generation_config.update(sequence_bias=seq_bias)++ trimmed_ids = batch_ids[:-1]++ """+ the latter code assumes trimmed_ids is not empty+ so have to check the its element count+ """+ if trimmed_ids.numel() == 0:+ continue++ # if the prompt is a single (non-pad) token, regenerate from bos+ if len(batch_ids[batch_ids != pad_token_id]) == 1:+ trimmed_ids[-1] = bos_token_id++ input_ids[batch_idx] = self.generate(trimmed_ids.unsqueeze(0), generation_config=generation_config)++ return input_ids++ def _dola_decoding(+ self,+ input_ids: torch.LongTensor,+ dola_layers: Union[str, List[int]],+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ streamer: "BaseStreamer",+ **model_kwargs,+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:+ r"""+ Generates sequences of token ids for models with a language modeling head using **dola decoding** and can be+ used for decoder-only text models.+ The method is based on the paper "DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language+ Models" (https://arxiv.org/abs/2309.03883) in ICLR 2024.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ dola_layers (`Union[str, List[int]]`):+ The candidate layers used in contrasting layers of DoLa. It can be either 1) 'low' or 'high', which+ means the lower part or higher part of the model layers, respectively, or 2) a list of layer indices+ to be used for candidate layers. The 0-th layer is the word embedding layer of the model.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`, *optional*):+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ streamer (`BaseStreamer`, *optional*):+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.+ model_kwargs:+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]+ or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """++ if self.config.is_encoder_decoder:+ raise ValueError("DoLa decoding is only available for decoder-only models.")+ # init values++ pad_token_id = generation_config._pad_token_tensor+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)+ do_sample = generation_config.do_sample++ # init attention / hidden states / scores tuples+ scores = () if (return_dict_in_generate and output_scores) else None+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # keep track of which sequences are already finished+ batch_size = input_ids.shape[0]+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ this_peer_finished = False++ # prepare layers for DoLa decoding+ final_layer = self.config.get_text_config().num_hidden_layers+ # if the model has tied word embeddings, we skip the word embeddings (0-th) layer and start from the 2nd layer,+ # as the early exit from word embeddings will become identity function+ # if the model is really shallow (<=2 layers), we use the 1st layer if it's not the final layer and the 0-th+ # layer otherwise. Notice that DoLa does not help shallow models much.+ if not self.config.tie_word_embeddings:+ start_layer = 0+ elif final_layer > 2:+ start_layer = 2+ elif final_layer == 2:+ start_layer = 1+ else:+ start_layer = 0++ # For `N`-layer models with `N <= 40` layers, the layers of `range(0, N // 2, 2)` and `range(N // 2, N, 2)`+ # are used for `'low'` and `'high'` layers, respectively.+ # For models with `N > 40` layers, the layers of `range(0, 20, 2)` and `range(N - 20, N, 2)` are used for+ # `'low'` and `'high'` layers, respectively.+ if isinstance(dola_layers, str) and dola_layers == "low":+ if start_layer == final_layer // 2:+ candidate_premature_layers = [start_layer]+ else:+ candidate_premature_layers = (+ list(range(start_layer, final_layer // 2, 2))+ if final_layer <= 40+ else list(range(start_layer, 20, 2))+ )+ elif isinstance(dola_layers, str) and dola_layers == "high":+ candidate_premature_layers = (+ list(range(final_layer // 2, final_layer, 2))+ if final_layer <= 40+ else list(range(final_layer - 20, final_layer, 2))+ )+ # Set the `dola_layers` to a list of integers for layer indices to contrast manually specified layers.+ elif isinstance(dola_layers, list):+ candidate_premature_layers = [i for i in dola_layers if i < final_layer]+ else:+ raise ValueError("dola_layers must be either 'low', 'high' or a list of integers.")++ lm_head = self.get_output_embeddings()+ if lm_head is None:+ raise ValueError("DoLa is not supported for models that don't have output embeddings.")++ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):+ # prepare model inputs+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)++ # forward pass to get next token+ outputs = self(+ **model_inputs,+ return_dict=True,+ output_attentions=output_attentions,+ output_hidden_states=True,+ )++ # .float() is needed to retain precision for later logits manipulations+ final_layer_next_token_logits = outputs.logits[:, -1, :].detach().clone().float()+ final_logits = outputs.logits[:, -1, :].float()+ candidate_premature_logits = {}+ for candidate_premature_layer in candidate_premature_layers:+ candidate_premature_logits[candidate_premature_layer] = lm_head(+ outputs.hidden_states[candidate_premature_layer][:, -1, :]+ ).to(final_logits.device)++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )+ if synced_gpus and this_peer_finished:+ continue++ next_token_logits = _dola_select_contrast(+ candidate_premature_layers, candidate_premature_logits, final_logits+ )+ next_token_logits = next_token_logits.to(input_ids.device)+ # pre-process distribution+ next_token_scores = logits_processor(input_ids, next_token_logits)++ # Store scores, attentions and hidden_states when required+ if return_dict_in_generate:+ if output_scores:+ scores += (next_token_scores,)+ if output_logits:+ raw_logits += (final_layer_next_token_logits,)+ if output_attentions:+ decoder_attentions += (+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)+ )+ if self.config.is_encoder_decoder:+ cross_attentions += (outputs.cross_attentions,)++ if output_hidden_states:+ decoder_hidden_states += (+ (outputs.decoder_hidden_states,)+ if self.config.is_encoder_decoder+ else (outputs.hidden_states,)+ )++ if do_sample: # sample+ probs = nn.functional.softmax(next_token_scores, dim=-1)+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)+ else: # argmax+ next_tokens = torch.argmax(next_token_scores, dim=-1)++ # finished sentences should have their next token be a padding token+ if has_eos_stopping_criteria:+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)++ # update generated ids, model inputs, and length for next step+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)+ if streamer is not None:+ streamer.put(next_tokens.cpu())++ # stop when each sentence is finished+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)+ this_peer_finished = unfinished_sequences.max() == 0++ if streamer is not None:+ streamer.end()++ if return_dict_in_generate:+ return GenerateDecoderOnlyOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return input_ids++ @torch.no_grad()+ def _contrastive_search(+ self,+ input_ids: torch.LongTensor,+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ streamer: Optional["BaseStreamer"],+ **model_kwargs,+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:+ r"""+ Generates sequences of token ids for models with a language modeling head using **contrastive search** and can+ be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`):+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ streamer (`BaseStreamer`, *optional*):+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.+ model_kwargs:+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]+ or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """+ # init values+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)+ top_k = generation_config.top_k+ penalty_alpha = generation_config.penalty_alpha+ pad_token_id = generation_config._pad_token_tensor+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate+ sequential = generation_config.low_memory++ # init attention / hidden states / scores tuples+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ scores = () if (return_dict_in_generate and output_scores) else None+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states+ if return_dict_in_generate and self.config.is_encoder_decoder:+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None+ encoder_hidden_states = (+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None+ )++ # keep track of which sequences are already finished+ batch_size = input_ids.shape[0]+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ # Create cosine_matrix_mask based on the attention_mask+ cosine_matrix_mask = torch.ones_like(input_ids, dtype=torch.long)+ if self.config.is_encoder_decoder:+ if "decoder_attention_mask" in model_kwargs and model_kwargs["decoder_attention_mask"] is not None:+ cosine_matrix_mask = model_kwargs["decoder_attention_mask"]+ else:+ cosine_matrix_mask = model_kwargs["attention_mask"]+ cosine_matrix_mask = cosine_matrix_mask.repeat_interleave(top_k, dim=0)++ this_peer_finished = False++ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):+ # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;+ # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step+ if model_kwargs.get("past_key_values") is None or (+ isinstance(model_kwargs["past_key_values"], (Cache, EncoderDecoderCache))+ and model_kwargs["past_key_values"].get_seq_length() == 0+ ):+ # prepare inputs+ model_kwargs["use_cache"] = True+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)++ # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save+ # the `encoder_outputs`+ outputs = self(+ **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions+ )++ # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with+ # previous tokens)+ if self.config.is_encoder_decoder:+ last_hidden_states = outputs.decoder_hidden_states[-1]+ else:+ last_hidden_states = outputs.hidden_states[-1]++ # next logit for contrastive search to select top-k candidate tokens+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for this first iteration+ # (the clone itself is always small)+ # .float() is needed to retain precision for later logits manipulations+ logit_for_next_step = outputs.logits[:, -1, :].clone().float()+ logit_for_next_step = logit_for_next_step.to(input_ids.device)++ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )++ if not sequential:+ # Expands model inputs top_k times, for batched forward passes (akin to beam search).+ _, model_kwargs = self._expand_inputs_for_generation(+ expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs+ )++ past_key_values = model_kwargs.get("past_key_values")+ if past_key_values is None:+ raise ValueError(+ f"{self.__class__.__name__} does not support caching and therefore **can't** be used "+ "for contrastive search."+ )+ elif (+ not isinstance(past_key_values[0], (tuple, torch.Tensor))+ or past_key_values[0][0].shape[0] != batch_size+ ):+ raise ValueError(+ f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "+ "used for contrastive search without further modifications."+ )++ # contrastive_search main logic start:+ # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by+ # degeneration penalty+ processed_logit_for_next_step = logits_processor(input_ids, logit_for_next_step)+ next_probs = nn.functional.softmax(processed_logit_for_next_step, dim=-1)++ top_k_probs, top_k_ids = torch.topk(next_probs, dim=-1, k=top_k)++ # Store scores, attentions and hidden_states when required+ if return_dict_in_generate:+ if output_logits:+ raw_logits += (logit_for_next_step,)+ if output_scores:+ scores += (processed_logit_for_next_step,)+ if output_attentions:+ decoder_attentions += (+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)+ )+ if self.config.is_encoder_decoder:+ cross_attentions += (outputs.cross_attentions,)++ if output_hidden_states:+ decoder_hidden_states += (+ (outputs.decoder_hidden_states,)+ if self.config.is_encoder_decoder+ else (outputs.hidden_states,)+ )++ # This is needed to properly delete outputs.logits which may be very large for this first iteration+ # Otherwise a reference to outputs.logits is kept all along until after the next call to self.forward()+ del outputs++ if not sequential:+ # Replicates the new past_key_values to match the `top_k` candidates+ past = model_kwargs["past_key_values"]+ # If it is a static cache, modify it in-place layer after layer to save memory+ if isinstance(past, DynamicCache) or (+ isinstance(past, EncoderDecoderCache) and isinstance(past.self_attention_cache, DynamicCache)+ ):+ past.batch_repeat_interleave(top_k)+ else:+ new_key_values = []+ for layer in past:+ items = []+ # item is either the key or the value matrix+ for item in layer:+ items.append(item.repeat_interleave(top_k, dim=0))+ new_key_values.append(tuple(items))++ past = tuple(new_key_values)++ model_kwargs["past_key_values"] = past++ if sequential:+ all_outputs = []+ for i in range(top_k):+ # compute the candidate tokens by the language model and collect their hidden_states+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids[:, i].view(-1, 1), **model_kwargs)++ outputs = self(+ **next_model_inputs,+ return_dict=True,+ output_hidden_states=True,+ output_attentions=output_attentions,+ )+ if isinstance(outputs["past_key_values"], DynamicCache) or (+ isinstance(outputs["past_key_values"], EncoderDecoderCache)+ and isinstance(outputs["past_key_values"].self_attention_cache, DynamicCache)+ ):+ # Remove past K-V from output since we don't need to stack later+ outputs["past_key_values"] = None+ # Remove last token from past K-V since we don't want to append it at this point+ model_kwargs["past_key_values"].crop(-1)++ all_outputs.append(outputs)+ outputs = stack_model_outputs(all_outputs, self.config.get_text_config())++ else:+ # compute the candidate tokens by the language model and collect their hidden_states+ # assembles top_k_ids into batch of size k+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)++ outputs = self(+ **next_model_inputs,+ return_dict=True,+ output_hidden_states=True,+ output_attentions=output_attentions,+ )++ # This is essential to avoid having a last reference to the big past K-V and double the necessary memory+ # in the next loop+ del next_model_inputs++ # name is different for encoder-decoder and decoder-only models+ if self.config.is_encoder_decoder:+ next_hidden = outputs.decoder_hidden_states[-1]+ full_hidden_states = outputs.decoder_hidden_states+ else:+ next_hidden = outputs.hidden_states[-1]+ full_hidden_states = outputs.hidden_states++ # .float() is needed to retain precision for later logits manipulations+ logits = outputs.logits[:, -1, :].float()+ context_hidden = last_hidden_states.repeat_interleave(top_k, dim=0)++ # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the+ # model confidence. Keeping `selected_idx` on CPU enables multi-device contrastive search and doesn't+ # introduce (noticeable) slowdowns on single-device runs.+ selected_idx = _ranking_fast(+ context_hidden, next_hidden, top_k_probs, cosine_matrix_mask, penalty_alpha, top_k+ )+ cosine_matrix_mask = torch.cat(+ [cosine_matrix_mask, cosine_matrix_mask.new_ones((cosine_matrix_mask.shape[0], 1))], dim=-1+ )+ selected_idx = selected_idx.to("cpu")++ # This will be used instead of the previous inneficient torch.stack(torch.split())+ augmented_idx = torch.tensor([x + i * top_k for i, x in enumerate(selected_idx)])++ # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing+ # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores+ # (model confidence minus degeneration penalty); (6) decoder hidden_states+ next_tokens = top_k_ids[range(len(top_k_ids)), selected_idx]+ next_hidden = torch.stack(torch.split(next_hidden.squeeze(dim=1), top_k))+ next_hidden = next_hidden[range(batch_size), selected_idx, :]+ last_hidden_states = torch.cat([last_hidden_states, next_hidden.unsqueeze(1)], dim=1)++ next_decoder_hidden_states = ()+ for layer in full_hidden_states:+ layer = torch.stack(torch.split(layer, top_k))[range(batch_size), selected_idx, :]+ next_decoder_hidden_states += (layer,)++ # generate past_key_values cache of only the selected token+ if sequential:+ next_model_input = self.prepare_inputs_for_generation(+ top_k_ids[:, selected_idx].view(-1, 1), **model_kwargs+ )++ selected_outputs = self(+ **next_model_input,+ return_dict=True,+ output_hidden_states=False,+ output_attentions=False,+ )+ next_past_key_values = selected_outputs["past_key_values"]++ else:+ _, next_past_key_values = self._extract_past_from_model_output(outputs)+ # Do it in-place layer per layer to save memory+ if isinstance(next_past_key_values, DynamicCache) or (+ isinstance(next_past_key_values, EncoderDecoderCache)+ and isinstance(next_past_key_values.self_attention_cache, DynamicCache)+ ):+ next_past_key_values.batch_select_indices(augmented_idx)+ else:+ new_key_values = []+ for layer in next_past_key_values:+ items = []+ # item is either the key or the value matrix+ for item in layer:+ items.append(item[augmented_idx, ...])+ new_key_values.append(tuple(items))++ next_past_key_values = tuple(new_key_values)++ logit_for_next_step = torch.stack(torch.split(logits, top_k))[range(batch_size), selected_idx, :]+ logit_for_next_step = logit_for_next_step.to(input_ids.device)++ # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration+ if self.config.is_encoder_decoder:+ next_step_cross_attentions = ()+ next_step_decoder_attentions = ()+ if output_attentions:+ for layer in outputs.cross_attentions:+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]+ next_step_cross_attentions += (layer,)+ for layer in outputs.decoder_attentions:+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]+ next_step_decoder_attentions += (layer,)+ outputs = Seq2SeqLMOutput(+ past_key_values=next_past_key_values,+ decoder_hidden_states=next_decoder_hidden_states,+ decoder_attentions=next_step_decoder_attentions or None,+ cross_attentions=next_step_cross_attentions or None,+ )+ else:+ next_step_attentions = ()+ if output_attentions:+ for layer in outputs.attentions:+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]+ next_step_attentions += (layer,)+ outputs = CausalLMOutputWithPast(+ past_key_values=next_past_key_values,+ hidden_states=next_decoder_hidden_states,+ attentions=next_step_attentions or None,+ )+ # contrastive_search main logic end++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )+ if synced_gpus and this_peer_finished:+ continue++ # finished sentences should have their next token be a padding token+ if has_eos_stopping_criteria:+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)++ # update generated ids, model inputs, and length for next step+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)+ if streamer is not None:+ streamer.put(next_tokens.cpu())++ # stop when each sentence is finished+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)+ this_peer_finished = unfinished_sequences.max() == 0++ if streamer is not None:+ streamer.end()++ if return_dict_in_generate:+ # Contrastive search works by forward looking at the next token, so we need to exclude it from+ # `past_key_values` to be consistent with the other decoding methods+ if model_kwargs.get("past_key_values") is not None:+ if isinstance(model_kwargs["past_key_values"], DynamicCache) or (+ isinstance(model_kwargs["past_key_values"], EncoderDecoderCache)+ and isinstance(model_kwargs["past_key_values"].self_attention_cache, DynamicCache)+ ):+ model_kwargs["past_key_values"].crop(-1)+ else:+ past_key_values = []+ for layer in model_kwargs["past_key_values"]:+ layer_past_key_values = []+ for item in layer:+ layer_past_key_values.append(item[..., :-1, :])+ past_key_values.append(tuple(layer_past_key_values))+ model_kwargs["past_key_values"] = tuple(past_key_values)++ if self.config.is_encoder_decoder:+ return GenerateEncoderDecoderOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ encoder_attentions=encoder_attentions,+ encoder_hidden_states=encoder_hidden_states,+ decoder_attentions=decoder_attentions,+ cross_attentions=cross_attentions,+ decoder_hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return GenerateDecoderOnlyOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return input_ids++ def _sample(+ self,+ input_ids: torch.LongTensor,+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ streamer: Optional["BaseStreamer"],+ **model_kwargs,+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:+ r"""+ Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and+ can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`):+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ streamer (`BaseStreamer`, *optional*):+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.+ model_kwargs:+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is+ an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:+ A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """+ # init values+ pad_token_id = generation_config._pad_token_tensor+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate+ max_length = generation_config.max_length+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)+ do_sample = generation_config.do_sample++ # init attention / hidden states / scores tuples+ scores = () if (return_dict_in_generate and output_scores) else None+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states+ if return_dict_in_generate and self.config.is_encoder_decoder:+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None+ encoder_hidden_states = (+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None+ )++ # keep track of which sequences are already finished+ batch_size, cur_len = input_ids.shape+ this_peer_finished = False+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ model_forward = self.__call__+ if isinstance(model_kwargs.get("past_key_values"), StaticCache):+ if self.device.type == "cuda":+ logger.warning_once("Using `torch.compile`.")+ os.environ["TOKENIZERS_PARALLELISM"] = "0"+ model_forward = self.get_compiled_call(generation_config.compile_config)++ is_prefill = True+ i = 0++ unconditional_guidance = getattr(self,"_guidance_scale", 0 )++ ####### Plan 9 from Deep Outer Space by DeepBeepMeep: X4 faster generation #######+ plan9 = self.config._attn_implementation == "flash_attention_2"++ unconditional_cache_position = 0+ unconditional_past_key_values = None++ if unconditional_guidance == 1:+ unconditional_guidance = 0++ if unconditional_guidance > 0 and not plan9:+ unconditional_past_key_values = DynamicCache()+ unconditional_cache_position = torch.ones_like(input_ids[0, -1:], dtype=torch.int64).cumsum(0) - 1++ session_cache = model_kwargs.pop("session_cache", None)+ callback = model_kwargs.pop("callback", None)++ prompt_length = input_ids.shape[1]+ if plan9:+ model_inputs = {}+ input_pos = prompt_length - 1+ if session_cache != None:+ real_max_length = session_cache["real_max_length"]+ else:+ real_max_length = max_length++ if unconditional_guidance > 0:+ if batch_size !=1:+ raise Exception("Conditional guidance only supported for the moment for batch size = 1")+ expanded_input_ids = torch.zeros( (2, real_max_length ), dtype= input_ids.dtype, device =input_ids.device )+ expanded_input_ids[0, :prompt_length] = input_ids+ expanded_input_ids[1, prompt_length -1 : prompt_length] = input_ids[0, -1:]+ input_ids = expanded_input_ids+ else:+ input_ids = torch.cat( [input_ids, torch.zeros( (batch_size, real_max_length -prompt_length ), dtype= input_ids.dtype, device =input_ids.device) ], 1 )++ if session_cache != None and "position_ids" in session_cache :+ position_ids = session_cache["position_ids"]+ start_positions = session_cache["start_positions"]+ seq_lengths = session_cache["seq_lengths"]+ start_length = session_cache["input_pos"]+ kv_cache = session_cache["kv_cache"]+ else:+ kv_cache = {}+ start_length = 0+ if unconditional_guidance > 0:+ position_ids = torch.zeros(2,max_length, dtype=torch.int32, device=input_ids.device)+ position_ids[0] = torch.arange(0, max_length, dtype=torch.int32, device=input_ids.device)+ position_ids[1, prompt_length-1:] = position_ids[0, : real_max_length -prompt_length + 1]+ start_positions = torch.tensor( [0 , prompt_length -1 ], dtype = position_ids.dtype, device= position_ids.device)+ seq_lengths = torch.tensor( [0, prompt_length -1], dtype = position_ids.dtype, device= position_ids.device)+ else:+ position_ids = torch.empty(batch_size,real_max_length, dtype=torch.int32, device=input_ids.device)+ position_ids[:] = torch.arange(0, real_max_length, dtype=torch.int32, device=input_ids.device)+ start_positions = torch.zeros(batch_size , dtype = position_ids.dtype, device= position_ids.device)+ seq_lengths = torch.zeros( batch_size, dtype = position_ids.dtype, device= position_ids.device)+++ # seq_lengths = seq_lengths[0:1]+ # start_positions = start_positions[0:1]+ # input_ids = input_ids[0:1]+ # position_ids = position_ids[0:1]++ model_inputs["position_ids"] = position_ids+ model_inputs["input_ids"] = input_ids+ model_inputs["start_positions"] = start_positions+ model_inputs["seq_lengths"] = seq_lengths+ model_inputs["real_max_length"] = real_max_length+ model_inputs["input_pos"] = input_pos+ model_inputs["kv_cache"] = kv_cache+ model_inputs["any_guidance"] = unconditional_guidance > 0+ model_inputs["plan9"] = True++ ###########################+ while self._has_unfinished_sequences(+ this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length+ ):+ if plan9:+ if is_prefill:+ truncated_position_ids = position_ids[:, start_length:prompt_length ]+ truncated_input_ids = input_ids[:, start_length:prompt_length ]+ else:+ truncated_position_ids = position_ids[:, input_pos:input_pos+1 ]+ truncated_input_ids = input_ids[:, input_pos:input_pos+1 ]+ model_inputs["position_ids"] = truncated_position_ids+ model_inputs["input_ids"] = truncated_input_ids+ else:+ # prepare model inputs+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)+ model_inputs["unconditional_guidance"] = unconditional_guidance+ if unconditional_guidance > 0:+ model_inputs["unconditional_guidance"] = unconditional_guidance+ model_inputs["unconditional_past_key_values"] = unconditional_past_key_values+ model_inputs["unconditional_cache_position"] = unconditional_cache_position++ # prepare variable output controls (note: some models won't accept all output controls)+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})++ if is_prefill:+ outputs = self(**model_inputs, return_dict=True)+ # torch.cuda.empty_cache()+ is_prefill = False+ else:+ outputs = model_forward(**model_inputs, return_dict=True)+ if i % 100 == 0:+ if callback !=None:+ callback(i, max_length-prompt_length)+ # print(f"Tokens: {i} out of {max_length-prompt_length}")+ i +=1+++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ ##############+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )+ if synced_gpus and this_peer_finished:+ continue+++ # pre-process distribution+ #####################+ if plan9:+ outputs = torch.nn.functional.log_softmax(outputs.logits, dim=-1)+ if unconditional_guidance > 0:+ scores = outputs[0, -1:]+ unconditional_scores = outputs[1, -1:]+ next_token_scores = unconditional_guidance * (scores - unconditional_scores) + unconditional_scores+ ref_inputs_ids = input_ids[0:1, : input_pos +1]+ del scores, unconditional_scores+ else:+ next_token_scores = outputs[:, -1, :]+ ref_inputs_ids = input_ids[:, : input_pos +1]+ next_token_scores = logits_processor(ref_inputs_ids, next_token_scores)+ else:+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration+ # (the clone itself is always small)+ next_token_logits = outputs.logits[:, -1, :].clone().float()+ next_token_logits = next_token_logits.to(input_ids.device)++ if unconditional_guidance > 0:+ scores = torch.nn.functional.log_softmax(next_token_logits, dim=-1)+ unconditional_logits = outputs["unconditional_logits"]+ unconditional_scores = torch.nn.functional.log_softmax(unconditional_logits[:, -1], dim=-1)+ next_token_scores = unconditional_guidance * (scores - unconditional_scores) + unconditional_scores+ next_token_scores = logits_processor(input_ids, next_token_scores)+ else:+ next_token_scores = logits_processor(input_ids, next_token_logits)+++ # Store scores, attentions and hidden_states when required+ if return_dict_in_generate:+ if output_scores:+ scores += (next_token_scores,)+ if output_logits:+ raw_logits += (next_token_logits,)+ if output_attentions:+ decoder_attentions += (+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)+ )+ if self.config.is_encoder_decoder:+ cross_attentions += (outputs.cross_attentions,)++ if output_hidden_states:+ decoder_hidden_states += (+ (outputs.decoder_hidden_states,)+ if self.config.is_encoder_decoder+ else (outputs.hidden_states,)+ )++ # token selection+ if do_sample:+ probs = nn.functional.softmax(next_token_scores, dim=-1)+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)+ else:+ next_tokens = torch.argmax(next_token_scores, dim=-1)+ del next_token_scores+ # finished sentences should have their next token be a padding token+ if has_eos_stopping_criteria:+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)+++ # print(f" P9 {plan9}, {cur_len} / {max_length}: {next_tokens} ")++ # update generated ids, model inputs, and length for next step+ if plan9:+ input_pos += 1+ # print(f"new input pos:{input_pos}")+ input_ids[:, input_pos: input_pos + 1] = next_tokens[:, None]+ seq_lengths = torch.full_like(seq_lengths , input_pos)+ model_inputs["seq_lengths"] = seq_lengths+ model_inputs["input_pos"] = input_pos+ if unconditional_guidance > 0:+ output_ids = input_ids[0:1, :input_pos + 1]+ else:+ output_ids = input_ids[:, :input_pos + 1]++ unfinished_sequences = unfinished_sequences & ~stopping_criteria(output_ids, outputs)+ else:+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)+ if streamer is not None:+ streamer.put(next_tokens.cpu())++ this_peer_finished = unfinished_sequences.max() == 0+ cur_len += 1++ # This is needed to properly delete outputs.logits which may be very large for first iteration+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration+ del outputs++ if streamer is not None:+ streamer.end()++ if return_dict_in_generate:+ if self.config.is_encoder_decoder:+ return GenerateEncoderDecoderOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ encoder_attentions=encoder_attentions,+ encoder_hidden_states=encoder_hidden_states,+ decoder_attentions=decoder_attentions,+ cross_attentions=cross_attentions,+ decoder_hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return GenerateDecoderOnlyOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ if plan9:+ if session_cache !=None:+ session_cache["position_ids"] = position_ids+ session_cache["start_positions"] = start_positions+ session_cache["seq_lengths"] = seq_lengths+ session_cache["real_max_length"] = real_max_length+ session_cache["input_pos"] = input_pos+ session_cache["kv_cache"] = kv_cache+ return output_ids+ else:+ return input_ids++ def _temporary_reorder_cache(self, past_key_values, beam_idx):+ """+ Temporary function to handle the different types of cache reordering processes while we roll out `Cache`.++ TODO: standardize cache formats and make all models compatible with `Cache`. It would remove the need+ for this function, with `Cache.reorder_cache` being the sole remaining code path+ """+ model_class = self.__class__.__name__.lower()+ # Exception 1: code path for models using the legacy cache format+ if isinstance(past_key_values, (tuple, list)):+ past_key_values = self._reorder_cache(past_key_values, beam_idx)+ # Exception 2: models with different cache formats. These are limited to `DynamicCache` until their+ # cache format is standardized, to avoid adding complexity to the codebase.+ elif "gptbigcode" in model_class:+ if not isinstance(past_key_values, (DynamicCache, EncoderDecoderCache)):+ raise ValueError(+ f"Using an unsupported cache format with {model_class}. Currently, it only supports the "+ "legacy tuple format or `DynamicCache`"+ )+ past_key_values = self._reorder_cache(past_key_values, beam_idx)+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)+ # Standard code path: use the `Cache.reorder_cache`+ else:+ past_key_values.reorder_cache(beam_idx)+ return past_key_values++ def _beam_search(+ self,+ input_ids: torch.LongTensor,+ beam_scorer: BeamScorer,+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ **model_kwargs,+ ) -> Union[GenerateBeamOutput, torch.LongTensor]:+ r"""+ Generates sequences of token ids for models with a language modeling head using **beam search decoding** and+ can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ beam_scorer (`BeamScorer`):+ An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and+ sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`:+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ model_kwargs:+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is+ an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """+ # init values+ pad_token_id = generation_config._pad_token_tensor+ eos_token_id = generation_config._eos_token_tensor+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate+ sequential = generation_config.low_memory+ do_sample = generation_config.do_sample++ batch_size = len(beam_scorer._beam_hyps)+ num_beams = beam_scorer.num_beams++ batch_beam_size, cur_len = input_ids.shape+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ if num_beams * batch_size != batch_beam_size:+ raise ValueError(+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."+ )++ # init attention / hidden states / scores tuples+ scores = () if (return_dict_in_generate and output_scores) else None+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ beam_indices = (+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None+ )+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states+ if return_dict_in_generate and self.config.is_encoder_decoder:+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None+ encoder_hidden_states = (+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None+ )++ # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens+ # of the first beam are considered to avoid sampling the exact same tokens across all beams.+ beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)+ beam_scores[:, 1:] = -1e9+ beam_scores = beam_scores.view((batch_size * num_beams,))++ this_peer_finished = False++ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder++ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)++ # prepare variable output controls (note: some models won't accept all output controls)+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})++ # if sequential is True, split the input to batches of batch_size and run sequentially+ if sequential:+ if any(+ model_name in self.__class__.__name__.lower()+ for model_name in [+ "fsmt",+ "reformer",+ "ctrl",+ "gpt_bigcode",+ "transo_xl",+ "xlnet",+ "cpm",+ "jamba",+ ]+ ):+ raise RuntimeError(+ f"Currently generation for {self.__class__.__name__} is not supported "+ f"for `low_memory beam_search`. Please open an issue on GitHub if you need this feature."+ )++ inputs_per_sub_batches = _split_model_inputs(+ model_inputs,+ split_size=batch_size,+ full_batch_size=batch_beam_size,+ config=self.config.get_text_config(),+ )+ outputs_per_sub_batch = [+ self(**inputs_per_sub_batch, return_dict=True) for inputs_per_sub_batch in inputs_per_sub_batches+ ]++ outputs = stack_model_outputs(outputs_per_sub_batch, self.config.get_text_config())++ else: # Unchanged original behavior+ outputs = self(**model_inputs, return_dict=True)++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )+ if synced_gpus and this_peer_finished:+ cur_len = cur_len + 1+ continue++ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration+ # (the clone itself is always small)+ # .float() is needed to retain precision for later logits manipulations+ next_token_logits = outputs.logits[:, -1, :].clone().float()+ next_token_logits = next_token_logits.to(input_ids.device)+ next_token_scores = nn.functional.log_softmax(+ next_token_logits, dim=-1+ ) # (batch_size * num_beams, vocab_size)++ next_token_scores_processed = logits_processor(input_ids, next_token_scores)+ next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(+ next_token_scores_processed+ )++ # Store scores, attentions and hidden_states when required+ if return_dict_in_generate:+ if output_scores:+ scores += (next_token_scores_processed,)+ if output_logits:+ raw_logits += (next_token_logits,)+ if output_attentions:+ decoder_attentions += (+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)+ )+ if self.config.is_encoder_decoder:+ cross_attentions += (outputs.cross_attentions,)+ if output_hidden_states:+ decoder_hidden_states += (+ (outputs.decoder_hidden_states,)+ if self.config.is_encoder_decoder+ else (outputs.hidden_states,)+ )++ # reshape for beam search+ vocab_size = next_token_scores.shape[-1]+ next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)++ # Beam token selection: pick 1 + eos_token_id.shape[0] next tokens for each beam so we have at least 1+ # non eos token per beam.+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0+ n_tokens_to_keep = max(2, 1 + n_eos_tokens) * num_beams+ if do_sample:+ probs = nn.functional.softmax(next_token_scores, dim=-1)+ next_tokens = torch.multinomial(probs, num_samples=n_tokens_to_keep)+ next_token_scores = torch.gather(next_token_scores, -1, next_tokens)+ next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)+ next_tokens = torch.gather(next_tokens, -1, _indices)+ else:+ next_token_scores, next_tokens = torch.topk(+ next_token_scores, n_tokens_to_keep, dim=1, largest=True, sorted=True+ )++ next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")+ next_tokens = next_tokens % vocab_size++ # stateless+ beam_outputs = beam_scorer.process(+ input_ids,+ next_token_scores,+ next_tokens,+ next_indices,+ pad_token_id=pad_token_id,+ eos_token_id=eos_token_id,+ beam_indices=beam_indices,+ decoder_prompt_len=decoder_prompt_len,+ )++ beam_scores = beam_outputs["next_beam_scores"]+ beam_next_tokens = beam_outputs["next_beam_tokens"]+ beam_idx = beam_outputs["next_beam_indices"]++ input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)++ # This is needed to properly delete outputs.logits which may be very large for first iteration+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory+ # (that way the memory peak does not include outputs.logits)+ del outputs++ if model_kwargs.get("past_key_values", None) is not None:+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(+ model_kwargs["past_key_values"], beam_idx+ )++ if return_dict_in_generate and output_scores:+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))++ # increase cur_len+ cur_len = cur_len + 1++ if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):+ this_peer_finished = True++ sequence_outputs = beam_scorer.finalize(+ input_ids,+ beam_scores,+ next_tokens,+ next_indices,+ pad_token_id=pad_token_id,+ eos_token_id=eos_token_id,+ max_length=stopping_criteria.max_length,+ beam_indices=beam_indices,+ decoder_prompt_len=decoder_prompt_len,+ )++ if return_dict_in_generate:+ if not output_scores:+ sequence_outputs["sequence_scores"] = None++ if self.config.is_encoder_decoder:+ return GenerateBeamEncoderDecoderOutput(+ sequences=sequence_outputs["sequences"],+ sequences_scores=sequence_outputs["sequence_scores"],+ scores=scores,+ logits=raw_logits,+ beam_indices=sequence_outputs["beam_indices"],+ encoder_attentions=encoder_attentions,+ encoder_hidden_states=encoder_hidden_states,+ decoder_attentions=decoder_attentions,+ cross_attentions=cross_attentions,+ decoder_hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return GenerateBeamDecoderOnlyOutput(+ sequences=sequence_outputs["sequences"],+ sequences_scores=sequence_outputs["sequence_scores"],+ scores=scores,+ logits=raw_logits,+ beam_indices=sequence_outputs["beam_indices"],+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return sequence_outputs["sequences"]++ def _group_beam_search(+ self,+ input_ids: torch.LongTensor,+ beam_scorer: BeamScorer,+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ **model_kwargs,+ ):+ r"""+ Generates sequences of token ids for models with a language modeling head using **diverse beam search+ decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ beam_scorer (`BeamScorer`):+ An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and+ sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`):+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ model_kwargs:+ Additional model specific kwargs that will be forwarded to the `forward` function of the model. If+ model is an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """+ # init values+ pad_token_id = generation_config._pad_token_tensor+ eos_token_id = generation_config._eos_token_tensor+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate++ num_beams = beam_scorer.num_beams+ num_beam_groups = beam_scorer.num_beam_groups+ num_sub_beams = num_beams // num_beam_groups+ batch_size = len(beam_scorer._beam_hyps) // num_beam_groups+ device = input_ids.device++ batch_beam_size, cur_len = input_ids.shape+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ if return_dict_in_generate and output_scores:+ beam_indices = [tuple(() for _ in range(num_sub_beams * batch_size)) for _ in range(num_beam_groups)]+ else:+ beam_indices = None++ if num_beams * batch_size != batch_beam_size:+ raise ValueError(+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."+ )++ # init attention / hidden states / scores tuples+ scores = () if (return_dict_in_generate and output_scores) else None+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states+ if return_dict_in_generate and self.config.is_encoder_decoder:+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None+ encoder_hidden_states = (+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None+ )++ # initialise score of first beam of each group with 0 and the rest with -1e9. This ensures that the beams in+ # the same group don't produce same tokens every time.+ beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device)+ beam_scores[:, ::num_sub_beams] = 0+ beam_scores = beam_scores.view((batch_size * num_beams,))++ this_peer_finished = False++ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):+ # predicted tokens in cur_len step+ current_tokens = torch.zeros(batch_size * num_beams, dtype=input_ids.dtype, device=device)++ # indices which will form the beams in the next time step+ reordering_indices = torch.zeros(batch_size * num_beams, dtype=torch.long, device=device)++ # do one decoder step on all beams of all sentences in batch+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)++ # prepare variable output controls (note: some models won't accept all output controls)+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})++ outputs = self(**model_inputs, return_dict=True)++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )+ if synced_gpus and this_peer_finished:+ cur_len = cur_len + 1+ continue++ if output_scores:+ processed_score = torch.zeros_like(outputs.logits[:, -1, :])+ if output_logits:+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration+ # (the clone itself is always small)+ raw_logit_score = outputs.logits[:, -1, :].clone()+ raw_logit_score = raw_logit_score.to(input_ids.device)++ for beam_group_idx in range(num_beam_groups):+ group_start_idx = beam_group_idx * num_sub_beams+ group_end_idx = min(group_start_idx + num_sub_beams, num_beams)+ group_size = group_end_idx - group_start_idx++ # indices of beams of current group among all sentences in batch+ batch_group_indices = []++ for batch_idx in range(batch_size):+ batch_group_indices.extend(+ [batch_idx * num_beams + idx for idx in range(group_start_idx, group_end_idx)]+ )+ group_input_ids = input_ids[batch_group_indices]++ # select outputs of beams of current group only+ # No need to clone() the logits here as they will not retain outputs.logits at the end of the loop+ # .float() is needed to retain precision for later logits manipulations+ next_token_logits = outputs.logits[batch_group_indices, -1, :].float()+ next_token_logits = next_token_logits.to(input_ids.device)++ next_token_scores = nn.functional.log_softmax(+ next_token_logits, dim=-1+ ) # (batch_size * group_size, vocab_size)+ vocab_size = next_token_scores.shape[-1]++ next_token_scores_processed = logits_processor(+ group_input_ids, next_token_scores, current_tokens=current_tokens, beam_group_idx=beam_group_idx+ )+ next_token_scores = next_token_scores_processed + beam_scores[batch_group_indices].unsqueeze(-1)+ next_token_scores = next_token_scores.expand_as(next_token_scores_processed)++ if output_scores:+ processed_score[batch_group_indices] = next_token_scores_processed++ # reshape for beam search+ next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size)++ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0+ next_token_scores, next_tokens = torch.topk(+ next_token_scores, max(2, 1 + n_eos_tokens) * group_size, dim=1, largest=True, sorted=True+ )++ next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")+ next_tokens = next_tokens % vocab_size++ # stateless+ process_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None+ beam_outputs = beam_scorer.process(+ group_input_ids,+ next_token_scores,+ next_tokens,+ next_indices,+ pad_token_id=pad_token_id,+ eos_token_id=eos_token_id,+ beam_indices=process_beam_indices,+ group_index=beam_group_idx,+ decoder_prompt_len=decoder_prompt_len,+ )+ beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"]+ beam_next_tokens = beam_outputs["next_beam_tokens"]+ beam_idx = beam_outputs["next_beam_indices"]++ if return_dict_in_generate and output_scores:+ beam_indices[beam_group_idx] = tuple(+ beam_indices[beam_group_idx][beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices[0]))+ )++ input_ids[batch_group_indices] = group_input_ids[beam_idx]+ group_input_ids = torch.cat([group_input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)+ current_tokens[batch_group_indices] = group_input_ids[:, -1]++ # (beam_idx // group_size) -> batch_idx+ # (beam_idx % group_size) -> offset of idx inside the group+ reordering_indices[batch_group_indices] = (+ num_beams * torch.div(beam_idx, group_size, rounding_mode="floor")+ + group_start_idx+ + (beam_idx % group_size)+ )++ # Store scores, attentions and hidden_states when required+ if return_dict_in_generate:+ if output_scores:+ scores += (processed_score,)+ if output_logits:+ raw_logits += (raw_logit_score,)+ if output_attentions:+ decoder_attentions += (+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)+ )+ if self.config.is_encoder_decoder:+ cross_attentions += (outputs.cross_attentions,)++ if output_hidden_states:+ decoder_hidden_states += (+ (outputs.decoder_hidden_states,)+ if self.config.is_encoder_decoder+ else (outputs.hidden_states,)+ )++ input_ids = torch.cat([input_ids, current_tokens.unsqueeze(-1)], dim=-1)++ # This is needed to properly delete outputs.logits which may be very large for first iteration+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory+ # (that way the memory peak does not include outputs.logits)+ del outputs++ if model_kwargs.get("past_key_values", None) is not None:+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(+ model_kwargs["past_key_values"], reordering_indices+ )++ # increase cur_len+ cur_len = cur_len + 1++ if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):+ this_peer_finished = True++ final_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None+ sequence_outputs = beam_scorer.finalize(+ input_ids,+ beam_scores,+ next_tokens,+ next_indices,+ pad_token_id=pad_token_id,+ eos_token_id=eos_token_id,+ max_length=stopping_criteria.max_length,+ beam_indices=final_beam_indices,+ decoder_prompt_len=decoder_prompt_len,+ )++ if return_dict_in_generate:+ if not output_scores:+ sequence_outputs["sequence_scores"] = None++ if self.config.is_encoder_decoder:+ return GenerateBeamEncoderDecoderOutput(+ sequences=sequence_outputs["sequences"],+ sequences_scores=sequence_outputs["sequence_scores"],+ scores=scores,+ logits=raw_logits,+ beam_indices=sequence_outputs["beam_indices"],+ encoder_attentions=encoder_attentions,+ encoder_hidden_states=encoder_hidden_states,+ decoder_attentions=decoder_attentions,+ cross_attentions=cross_attentions,+ decoder_hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return GenerateBeamDecoderOnlyOutput(+ sequences=sequence_outputs["sequences"],+ sequences_scores=sequence_outputs["sequence_scores"],+ scores=scores,+ logits=raw_logits,+ beam_indices=sequence_outputs["beam_indices"],+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return sequence_outputs["sequences"]++ def _constrained_beam_search(+ self,+ input_ids: torch.LongTensor,+ constrained_beam_scorer: ConstrainedBeamSearchScorer,+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ **model_kwargs,+ ) -> Union[GenerateBeamOutput, torch.LongTensor]:+ r"""+ Generates sequences of token ids for models with a language modeling head using **constrained beam search+ decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ constrained_beam_scorer (`ConstrainedBeamSearchScorer`):+ A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and+ sorted during generation, while satisfying a list of positive constraints. For more information, the+ documentation of [`ConstrainedBeamSearchScorer`] should be read.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`):+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ model_kwargs:+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is+ an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """+ # init values+ pad_token_id = generation_config._pad_token_tensor+ eos_token_id = generation_config._eos_token_tensor+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate++ batch_size = len(constrained_beam_scorer._beam_hyps)+ num_beams = constrained_beam_scorer.num_beams++ batch_beam_size, cur_len = input_ids.shape+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ if num_beams * batch_size != batch_beam_size:+ raise ValueError(+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."+ )++ # init attention / hidden states / scores tuples+ scores = () if (return_dict_in_generate and output_scores) else None+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ beam_indices = (+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None+ )+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states+ if return_dict_in_generate and self.config.is_encoder_decoder:+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None+ encoder_hidden_states = (+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None+ )++ # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens+ # of the first beam are considered to avoid sampling the exact same tokens across all beams.+ beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)+ beam_scores[:, 1:] = -1e9+ beam_scores = beam_scores.view((batch_size * num_beams,))++ this_peer_finished = False++ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)++ # prepare variable output controls (note: some models won't accept all output controls)+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})++ outputs = self(**model_inputs, return_dict=True)++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ )+ if synced_gpus and this_peer_finished:+ cur_len = cur_len + 1+ continue++ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration+ # (the clone itself is always small)+ # .float() is needed to retain precision for later logits manipulations+ next_token_logits = outputs.logits[:, -1, :].clone().float()+ next_token_logits = next_token_logits.to(input_ids.device)+ next_token_scores = nn.functional.log_softmax(+ next_token_logits, dim=-1+ ) # (batch_size * num_beams, vocab_size)++ next_token_scores_processed = logits_processor(input_ids, next_token_scores)++ next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(+ next_token_scores_processed+ )++ scores_for_all_vocab = next_token_scores.clone()++ # Store scores, attentions and hidden_states when required+ if return_dict_in_generate:+ if output_scores:+ scores += (next_token_scores,)+ if output_logits:+ raw_logits += (next_token_logits,)+ if output_attentions:+ decoder_attentions += (+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)+ )+ if self.config.is_encoder_decoder:+ cross_attentions += (outputs.cross_attentions,)++ if output_hidden_states:+ decoder_hidden_states += (+ (outputs.decoder_hidden_states,)+ if self.config.is_encoder_decoder+ else (outputs.hidden_states,)+ )++ # reshape for beam search+ vocab_size = next_token_scores.shape[-1]+ next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)++ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0+ next_token_scores, next_tokens = torch.topk(+ next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True+ )++ next_indices = (next_tokens / vocab_size).long()+ next_tokens = next_tokens % vocab_size++ # stateless+ beam_outputs = constrained_beam_scorer.process(+ input_ids,+ next_token_scores,+ next_tokens,+ next_indices,+ scores_for_all_vocab,+ pad_token_id=pad_token_id,+ eos_token_id=eos_token_id,+ beam_indices=beam_indices,+ decoder_prompt_len=decoder_prompt_len,+ )+ beam_scores = beam_outputs["next_beam_scores"]+ beam_next_tokens = beam_outputs["next_beam_tokens"]+ beam_idx = beam_outputs["next_beam_indices"]++ input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)++ # This is needed to properly delete outputs.logits which may be very large for first iteration+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory+ # (that way the memory peak does not include outputs.logits)+ del outputs++ if model_kwargs.get("past_key_values", None) is not None:+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(+ model_kwargs["past_key_values"], beam_idx+ )++ if return_dict_in_generate and output_scores:+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))++ # increase cur_len+ cur_len = cur_len + 1++ if constrained_beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):+ this_peer_finished = True++ sequence_outputs = constrained_beam_scorer.finalize(+ input_ids,+ beam_scores,+ next_tokens,+ next_indices,+ pad_token_id=pad_token_id,+ eos_token_id=eos_token_id,+ max_length=stopping_criteria.max_length,+ beam_indices=beam_indices,+ decoder_prompt_len=decoder_prompt_len,+ )++ if return_dict_in_generate:+ if not output_scores:+ sequence_outputs["sequence_scores"] = None+ if self.config.is_encoder_decoder:+ return GenerateBeamEncoderDecoderOutput(+ sequences=sequence_outputs["sequences"],+ sequences_scores=sequence_outputs["sequence_scores"],+ scores=scores,+ logits=raw_logits,+ beam_indices=sequence_outputs["beam_indices"],+ encoder_attentions=encoder_attentions,+ encoder_hidden_states=encoder_hidden_states,+ decoder_attentions=decoder_attentions,+ cross_attentions=cross_attentions,+ decoder_hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return GenerateBeamDecoderOnlyOutput(+ sequences=sequence_outputs["sequences"],+ sequences_scores=sequence_outputs["sequence_scores"],+ scores=scores,+ logits=raw_logits,+ beam_indices=sequence_outputs["beam_indices"],+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return sequence_outputs["sequences"]++ def _assisted_decoding(+ self,+ input_ids: torch.LongTensor,+ candidate_generator: CandidateGenerator,+ logits_processor: LogitsProcessorList,+ stopping_criteria: StoppingCriteriaList,+ generation_config: GenerationConfig,+ synced_gpus: bool,+ streamer: Optional["BaseStreamer"],+ **model_kwargs,+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:+ r"""+ Generates sequences of token ids for models with a language modeling head using **greedy decoding** or+ **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a+ candidate decoding strategy. Can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text+ models.++ Parameters:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ The sequence used as a prompt for the generation.+ candidate_generator (`CandidateGenerator`):+ A derived instance of [`CandidateGenerator`] that defines how candidate sequences are generated. For+ more information, the documentation of [`CandidateGenerator`] should be read.+ logits_processor (`LogitsProcessorList`):+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]+ used to modify the prediction scores of the language modeling head applied at each generation step.+ stopping_criteria (`StoppingCriteriaList`):+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]+ used to tell if the generation loop should stop.+ generation_config ([`~generation.GenerationConfig`]):+ The generation configuration to be used as parametrization of the decoding method.+ synced_gpus (`bool`):+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).+ streamer (`BaseStreamer`, *optional*):+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.+ model_kwargs:+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.++ Return:+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if+ `model.config.is_encoder_decoder=True`.+ """+ # init values+ do_sample = generation_config.do_sample+ output_attentions = generation_config.output_attentions+ output_hidden_states = generation_config.output_hidden_states+ output_scores = generation_config.output_scores+ output_logits = generation_config.output_logits+ return_dict_in_generate = generation_config.return_dict_in_generate++ # init attention / hidden states / scores tuples+ scores = () if (return_dict_in_generate and output_scores) else None+ raw_logits = () if (return_dict_in_generate and output_logits) else None+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None++ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states+ if return_dict_in_generate and self.config.is_encoder_decoder:+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None+ encoder_hidden_states = (+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None+ )++ # keep track of which sequences are already finished+ batch_size = input_ids.shape[0]+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)++ this_peer_finished = False+ is_first_iteration = True # to preserve the same API in the output as other generation methods+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):+ cur_len = input_ids.shape[-1]++ # 1. Fetch candidate sequences from a `CandidateGenerator` and move to the correct device+ candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)++ candidate_input_ids = candidate_input_ids.to(self.device)+ if candidate_logits is not None:+ candidate_logits = candidate_logits.to(self.device)++ candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]+ is_done_candidate = stopping_criteria(candidate_input_ids, None)++ # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain+ # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,+ # we use this forward pass to also pick the subsequent logits in the original model.++ # 2.1. Prepare the model inputs+ candidate_kwargs = copy.copy(model_kwargs)+ candidate_kwargs = _prepare_attention_mask(+ candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder+ )+ candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])+ if "cache_position" in candidate_kwargs:+ candidate_kwargs["cache_position"] = torch.cat(+ (+ candidate_kwargs["cache_position"],+ torch.arange(cur_len, cur_len + candidate_length, device=input_ids.device, dtype=torch.long),+ ),+ dim=0,+ )++ model_inputs = self.prepare_inputs_for_generation(candidate_input_ids, **candidate_kwargs)+ if "num_logits_to_keep" in model_inputs:+ model_inputs["num_logits_to_keep"] = candidate_length + 1++ # 2.2. Run a forward pass on the candidate sequence+ # prepare variable output controls (note: some models won't accept all output controls)+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})++ outputs = self(**model_inputs)++ # 2.3. Process the new logits+ # .float() is needed to retain precision for later logits manipulations+ new_logits = outputs.logits[:, -candidate_length - 1 :].float() # excludes the input prompt if present+ new_logits = new_logits.to(input_ids.device)+ next_token_logits = new_logits.clone()+ if len(logits_processor) > 0:+ for i in range(candidate_length + 1):+ new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])++ # 3. Select the accepted tokens. There are two possible cases:+ # Case 1: `do_sample=True` and we have logits for the candidates (originally from speculative decoding)+ # 👉 Apply algorithm 1 from the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf).+ if do_sample and candidate_logits is not None:+ valid_tokens, n_matches = _speculative_sampling(+ candidate_input_ids,+ candidate_logits,+ candidate_length,+ new_logits,+ is_done_candidate,+ )++ # Case 2: all other cases (originally from assisted generation) 👉 Compare the tokens selected from the+ # original model logits with the candidate tokens. We can keep the candidate tokens until the first+ # mismatch, or until the max length is reached.+ else:+ if do_sample:+ probs = new_logits.softmax(dim=-1)+ selected_tokens = torch.multinomial(probs[0, :, :], num_samples=1).squeeze(1)[None, :]+ else:+ selected_tokens = new_logits.argmax(dim=-1)++ candidate_new_tokens = candidate_input_ids[:, cur_len:]+ n_matches = ((~(candidate_new_tokens == selected_tokens[:, :-1])).cumsum(dim=-1) < 1).sum()++ # Ensure we don't generate beyond max_len or an EOS token+ if is_done_candidate and n_matches == candidate_length:+ n_matches -= 1+ valid_tokens = selected_tokens[:, : n_matches + 1]++ # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated+ # by the model after the last candidate match is also valid, as it is generated from a correct sequence.+ # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there+ # is no match.++ # 4.1. Get the valid continuation, after the matching tokens+ input_ids = torch.cat((input_ids, valid_tokens), dim=-1)+ if streamer is not None:+ streamer.put(valid_tokens.cpu())+ new_cur_len = input_ids.shape[-1]++ # 4.2. Discard past key values relative to unused assistant tokens+ new_cache_size = new_cur_len - 1+ outputs.past_key_values = _crop_past_key_values(self, outputs.past_key_values, new_cache_size)++ # 5. Update the candidate generation strategy if needed+ candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)++ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping+ model_kwargs = self._update_model_kwargs_for_generation(+ outputs,+ model_kwargs,+ is_encoder_decoder=self.config.is_encoder_decoder,+ num_new_tokens=n_matches + 1,+ )+ if synced_gpus and this_peer_finished:+ continue++ # Store scores, attentions and hidden_states when required+ # Assistant: modified to append one tuple element per token, as in the other generation methods.+ if return_dict_in_generate:+ newly_added_length = n_matches + 1+ if output_scores:+ scores += tuple(new_logits[:, i, :] for i in range(newly_added_length))+ if output_logits:+ raw_logits += tuple(next_token_logits[:, i, :] for i in range(newly_added_length))++ newly_added_length = new_cur_len if is_first_iteration else newly_added_length+ if output_attentions:+ if self.config.is_encoder_decoder:+ cross_attentions = _split_model_outputs(+ cross_attentions, outputs.cross_attentions, cur_len, newly_added_length+ )+ decoder_attentions = _split_model_outputs(+ decoder_attentions,+ outputs.decoder_attentions,+ cur_len,+ newly_added_length,+ is_decoder_attention=True,+ )+ # some (V)LLMs have hard requirement on SDPA and thus never return attn+ elif outputs.attentions[0] is not None:+ decoder_attentions = _split_model_outputs(+ decoder_attentions,+ outputs.attentions,+ cur_len,+ newly_added_length,+ is_decoder_attention=True,+ )+ if output_hidden_states:+ if self.config.is_encoder_decoder:+ decoder_hidden_states = _split_model_outputs(+ decoder_hidden_states, outputs.decoder_hidden_states, cur_len, newly_added_length+ )+ else:+ decoder_hidden_states = _split_model_outputs(+ decoder_hidden_states, outputs.hidden_states, cur_len, newly_added_length+ )++ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)+ this_peer_finished = unfinished_sequences.max() == 0+ is_first_iteration = False++ if streamer is not None:+ streamer.end()++ if (+ hasattr(candidate_generator, "assistant_model")+ and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"+ ):+ candidate_generator.assistant_model.generation_config.num_assistant_tokens = (+ candidate_generator.num_assistant_tokens+ )+ if return_dict_in_generate:+ if self.config.is_encoder_decoder:+ return GenerateEncoderDecoderOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ encoder_attentions=encoder_attentions,+ encoder_hidden_states=encoder_hidden_states,+ decoder_attentions=decoder_attentions,+ cross_attentions=cross_attentions,+ decoder_hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return GenerateDecoderOnlyOutput(+ sequences=input_ids,+ scores=scores,+ logits=raw_logits,+ attentions=decoder_attentions,+ hidden_states=decoder_hidden_states,+ past_key_values=model_kwargs.get("past_key_values"),+ )+ else:+ return input_ids+++def _speculative_sampling(+ candidate_input_ids,+ candidate_logits,+ candidate_length,+ new_logits,+ is_done_candidate,+):+ """+ Applies sampling as in the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf, algorithm 1). Returns+ the selected tokens, as well as the number of candidate matches.++ NOTE: Unless otherwise stated, the variable names match those in the paper.+ """+ new_candidate_input_ids = candidate_input_ids[:, -candidate_length:]+ # Gets the probabilities from the logits. q_i and p_i denote the assistant and model probabilities of the tokens+ # selected by the assistant, respectively.+ q = candidate_logits.softmax(dim=-1)+ q_i = q[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)+ p = new_logits.softmax(dim=-1)+ p_i = p[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)+ probability_ratio = p_i / q_i++ # When probability_ratio > 1 (i.e. q_i(x) < p_i(x), or "assistant probability of the candidate token is smaller+ # than the model probability for the same token"), keep the token. Otherwise reject with p = 1 - probability_ratio+ # (= keep with p = probability_ratio). Keep all the tokens until the first rejection+ r_i = torch.rand_like(probability_ratio)+ is_accepted = r_i <= probability_ratio+ n_matches = ((~is_accepted).cumsum(dim=-1) < 1).sum() # this is `n` in algorithm 1++ # Ensure we don't generate beyond max_len or an EOS token (not in algorithm 1, but needed for correct behavior)+ if is_done_candidate and n_matches == candidate_length:+ # Output length is assumed to be `n_matches + 1`. Since we won't generate another token with the target model+ # due to acceptance on EOS we fix `n_matches`+ n_matches -= 1+ valid_tokens = new_candidate_input_ids[:, : n_matches + 1]+ else:+ # Next token selection: if there is a rejection, adjust the distribution from the main model before sampling.+ gamma = candidate_logits.shape[1]+ p_n_plus_1 = p[:, n_matches, :]+ if n_matches < gamma:+ q_n_plus_1 = q[:, n_matches, :]+ p_prime = torch.clamp((p_n_plus_1 - q_n_plus_1), min=0)+ p_prime.div_(p_prime.sum())+ else:+ p_prime = p_n_plus_1+ t = torch.multinomial(p_prime, num_samples=1).squeeze(1)[None, :]++ # The selected tokens include the matches (if any) plus the next sampled tokens+ if n_matches > 0:+ valid_tokens = torch.cat((new_candidate_input_ids[:, :n_matches], t), dim=-1)+ else:+ valid_tokens = t++ return valid_tokens, n_matches+++def _split_model_outputs(outputs, new_outputs, cur_len, added_len, is_decoder_attention=False):+ """+ Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple+ where each member corresponds to a single generated token.+ """+ # Retrocompatibility: in our generation functions, the first iteration includes the attention/hidden states for the+ # prompt.+ if len(outputs) == 0:+ new_tuple = ()+ for layer in new_outputs:+ last_dim_size = cur_len if is_decoder_attention else layer.shape[-1]+ new_tuple += (layer[..., :cur_len, :last_dim_size],)+ outputs += (new_tuple,)+ # The first iteration contains the prompt + 1 generated token, let's update the length variables accordingly+ cur_len += 1+ added_len -= cur_len++ for i in range(added_len):+ new_tuple = ()+ for layer in new_outputs:+ last_dim_size = cur_len + i if is_decoder_attention else layer.shape[-1]+ new_tuple += (layer[..., i : i + 1, :last_dim_size],)+ outputs += (new_tuple,)+ return outputs+++def _ranking_fast(+ context_hidden: torch.FloatTensor,+ next_hidden: torch.FloatTensor,+ next_top_k_probs: torch.FloatTensor,+ cosine_matrix_mask: torch.LongTensor,+ alpha: float,+ beam_width: int,+) -> torch.FloatTensor:+ """+ Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described+ in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each+ row in the batch.+ """+ norm_context_hidden = context_hidden / context_hidden.norm(dim=2, keepdim=True)+ norm_next_hidden = next_hidden / next_hidden.norm(dim=2, keepdim=True)+ cosine_matrix = torch.matmul(norm_context_hidden, norm_next_hidden.transpose(1, 2)).squeeze(-1) # [B*K, S]++ # Penalize cosine_matrix based on the cosine_matrix_mask (ignore padding positions)+ # Using a large negative value for masked positions+ cosine_matrix_mask = cosine_matrix_mask.to(dtype=cosine_matrix.dtype)+ cosine_matrix_mask = (1 - cosine_matrix_mask) * torch.finfo(cosine_matrix.dtype).min+ cosine_matrix = cosine_matrix + cosine_matrix_mask++ degeneration_penalty, _ = torch.max(cosine_matrix, dim=-1) # [B*K]+ next_top_k_probs = next_top_k_probs.view(-1) # [B*K]+ contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty+ contrastive_score = torch.stack(torch.split(contrastive_score, beam_width)) # [B, K]+ _, selected_idx = contrastive_score.max(dim=-1) # [B]+ return selected_idx+++def _split(data, full_batch_size: int, num_hidden_layers: int, split_size: int = None):+ """+ Takes care of three cases:+ 1. data is a tensor: e.g. last_hidden_state, pooler_output etc. split them on the batch_size dim+ 2. data is a tuple: e.g. hidden_states, attentions etc. Keep the tuple as it is and split each tensor in it and+ return a list of tuples+ 3. data is a tuple of tuples, e.g. past_key_values. Keep the tuple as it is and split each tuple in it and+ return a list of tuples of tuples+ (see documentation of ModelOutput)+ """+ if data is None:+ return [None] * (full_batch_size // split_size)+ if isinstance(data, torch.Tensor):+ return [data[i : i + split_size] for i in range(0, full_batch_size, split_size)]+ # New cache format+ elif isinstance(data, DynamicCache) or (+ isinstance(data, EncoderDecoderCache) and isinstance(data.self_attention_cache, DynamicCache)+ ):+ return data.batch_split(full_batch_size, split_size, num_hidden_layers)+ elif isinstance(data, tuple):+ # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)+ if isinstance(data[0], tuple):+ return [+ tuple(tuple(tensor[i : i + split_size] for tensor in inner_tuple) for inner_tuple in data)+ for i in range(0, full_batch_size, split_size)+ ]++ else:+ return [+ tuple(sub_tensor[i : i + split_size] for sub_tensor in data)+ for i in range(0, full_batch_size, split_size)+ ]+ else:+ raise TypeError(f"Unexpected attribute type: {type(data)}")+++def _split_model_inputs(+ model_input: Union[ModelOutput, Dict], split_size: int, full_batch_size: int, config: PretrainedConfig+) -> List[Union[ModelOutput, Dict]]:+ """+ Split a ModelOutput object (or its subclasses) or Dict into a list of same-class objects based on a specified split+ size. The input object is dict when it was prepared for forward pass and ModelOutput when it was returned from+ previous forward pass.+ """+ # Edge case: if model_input is None, return a list of Nones+ # this happens with Whisper where encoder_outputs is None+ if model_input is None:+ return [model_input] * (full_batch_size // split_size)+ # Infer the class from the object+ model_output_cls = type(model_input)+ if (full_batch_size % split_size) != 0:+ raise ValueError("`full_batch_size` must be divisible by `split_size`")++ if split_size > full_batch_size:+ raise ValueError("`split_size` must be smaller or equal to `full_batch_size`")++ # Helper function to split tensors or tuples of tensors++ # Find all the dataclass fields (e.g., last_hidden_state, pooler_output etc.) and split them+ keys = (+ model_input.__dataclass_fields__.keys() if hasattr(model_input, "__dataclass_fields__") else model_input.keys()+ )+ # We only keep keys that are in the model_input+ keys = [k for k in keys if k in model_input]+ # Here we can have four types of values: tensors, tuples of tensors and booleans, and encoder_outputs which is a+ # ModelOutput object.+ # bool should not be split but replicated for each split+ bool_keys = [k for k in keys if isinstance(model_input[k], bool) or k == "cache_position"]+ keys_to_ignore = ["cache_position", "encoder_outputs", "num_logits_to_keep"]+ non_bool_keys = [k for k in keys if not isinstance(model_input[k], bool) and k not in keys_to_ignore]++ num_hidden_layers = config.get_text_config().num_hidden_layers++ # we split the tensors and tuples of tensors+ data_split_list = [+ {k: _split(model_input[k], full_batch_size, num_hidden_layers, split_size)[i] for k in non_bool_keys}+ for i in range(full_batch_size // split_size)+ ]+ # bool values are the same and replicated for each split+ bool_data = {k: model_input[k] for k in bool_keys}+ # encoder_outputs is a ModelOutput object and should be split by its own+ if "encoder_outputs" in model_input:+ encoder_outputs_split = _split_model_inputs(+ model_input["encoder_outputs"], split_size, full_batch_size, config.get_text_config()+ )+ data_split_list = [+ {**data_split, "encoder_outputs": encoder_outputs_split[i]} for i, data_split in enumerate(data_split_list)+ ]+ # num_logits_to_keep should be replicated for each split, similar to bool values+ if "num_logits_to_keep" in model_input:+ data_split_list = [+ {**data_split, "num_logits_to_keep": model_input["num_logits_to_keep"]} for data_split in data_split_list+ ]++ # Convert each dictionary in the list to an object of the inferred class+ split_model_inputs: List[Union[ModelOutput, Dict]] = [+ model_output_cls(**data_split, **bool_data) for data_split in data_split_list+ ]++ return split_model_inputs+++def stack_model_outputs(model_outputs: List[ModelOutput], config: PretrainedConfig) -> ModelOutput:+ """+ Stack a list of ModelOutput objects (or its subclasses) along the batch_size dimension. The function infers the+ specific ModelOutput subclass from the list provided.+ """+ if not model_outputs:+ raise ValueError("Input list is empty.")++ # Infer the class from the first object in the list+ model_output_cls = type(model_outputs[0])+ num_hidden_layers = config.get_text_config().num_hidden_layers++ # Ensure all objects are of the same type+ if not all(isinstance(obj, model_output_cls) for obj in model_outputs):+ raise ValueError("All elements in the list should be of the same type.")++ # Helper function to concat tensors or tuples of tensors+ def _concat(data):+ """+ Reverse of `_split` function above.+ """+ if any(data is None for data in data):+ return None+ if isinstance(data[0], torch.Tensor):+ return torch.cat(data, dim=0)+ # New cache format+ elif isinstance(data[0], DynamicCache):+ return DynamicCache.from_batch_splits(data, num_hidden_layers=num_hidden_layers)+ elif isinstance(data[0], EncoderDecoderCache):+ return EncoderDecoderCache.from_batch_splits(data, num_hidden_layers=num_hidden_layers)+ elif isinstance(data[0], tuple):+ # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)+ if isinstance(data[0][0], tuple):+ return tuple(+ tuple(torch.cat([attr[i][j] for attr in data], dim=0) for j in range(len(data[0][0])))+ for i in range(len(data[0]))+ )+ else:+ return tuple(torch.cat([attr[i] for attr in data], dim=0) for i in range(len(data[0])))+ elif isinstance(data[0], (int, float)):+ # If the elements are integers or floats, return a tensor+ return torch.tensor(data)+ else:+ raise TypeError(f"Unexpected attribute type: {type(data[0])}")++ # Use a dictionary comprehension to gather attributes from all objects and concatenate them+ concatenated_data = {+ k: _concat([getattr(model_output, k) for model_output in model_outputs])+ for k in model_output_cls.__dataclass_fields__.keys()+ }++ # Return a new object of the inferred class with the concatenated attributes+ return model_output_cls(**concatenated_data)+++def _relative_top_filter(+ scores: torch.FloatTensor,+ baseline_scores: torch.FloatTensor,+ relative_top: float = 0.1,+ filter_value: float = -float("Inf"),+ base_filter_value=-1e-3,+ min_tokens_to_keep: int = 1,+) -> torch.FloatTensor:+ """+ Reference: https://github.com/XiangLi1999/ContrastiveDecoding/blob/170e9142e92159c1237d731e240f5eb14aabf428/transformers/src/transformers/generation_logits_process.py#L235+ Apply filtering to only keep tokens with a probability above a certain threshold. The threshold is defined as `relative_top` * max probability in the distribution.+ """+ scores_normalized = scores.log_softmax(dim=-1)+ baseline_scores_normalized = baseline_scores.log_softmax(dim=-1)+ sorted_logits, sorted_indices = torch.sort(scores_normalized, descending=True)+ min_thresh = sorted_logits[..., min_tokens_to_keep - 1]+ probs_max = torch.max(scores_normalized, dim=-1).values+ probs_thresh = probs_max + np.log(relative_top)+ probs_thresh = torch.min(min_thresh, probs_thresh)+ probs_thresh = probs_thresh.unsqueeze(-1)+ baseline_scores_normalized[scores_normalized < probs_thresh] = base_filter_value+ scores_normalized[scores_normalized < probs_thresh] = filter_value+ return scores_normalized, baseline_scores_normalized+++def _dola_select_contrast(+ candidate_premature_layers: List[int],+ candidate_premature_logits: Dict[int, torch.FloatTensor],+ final_logits: torch.FloatTensor,+) -> torch.FloatTensor:+ if len(candidate_premature_layers) == 1:+ base_logits = candidate_premature_logits[candidate_premature_layers[0]]+ final_logits, base_logits = _relative_top_filter(final_logits, base_logits)+ logits = final_logits - base_logits+ return logits++ # 1. Stacking all premature_layers into a new dimension+ stacked_premature_layers = torch.stack([candidate_premature_logits[i] for i in candidate_premature_layers], dim=0)++ # 2. Calculate the softmax values for mature_layer and all premature_layers+ # shape: (batch_size, vocab_size)+ softmax_mature_layer = F.softmax(final_logits, dim=-1)+ # shape: (num_premature_layers, batch_size, vocab_size)+ softmax_premature_layers = F.softmax(stacked_premature_layers, dim=-1)++ # 3. Calculate the average distribution+ # shape: (num_premature_layers, batch_size, vocab_size)+ avg_dist = 0.5 * (softmax_mature_layer[None, :, :] + softmax_premature_layers)++ # 4. Calculate log-softmax for the KL divergence+ # shape: (batch_size, vocab_size)+ log_softmax_mature_layer = F.log_softmax(final_logits, dim=-1)+ # shape: (num_premature_layers, batch_size, vocab_size)+ log_softmax_premature_layers = F.log_softmax(stacked_premature_layers, dim=-1)++ # 5. Calculate the KL divergences and then the JS divergences+ # shape: (num_premature_layers, batch_size)+ kl1 = F.kl_div(log_softmax_mature_layer[None, :, :], avg_dist, reduction="none").mean(-1)+ # shape: (num_premature_layers, batch_size)+ kl2 = F.kl_div(log_softmax_premature_layers, avg_dist, reduction="none").mean(-1)+ js_divs = 0.5 * (kl1 + kl2) # shape: (num_premature_layers, batch_size)++ # 6. Reduce the batchmean+ js_divs = js_divs.mean(-1) # shape: (num_premature_layers,)+ premature_layer = candidate_premature_layers[int(js_divs.argmax().cpu().item())]++ base_logits = candidate_premature_logits[premature_layer]+ final_logits, base_logits = _relative_top_filter(final_logits, base_logits)+ logits = final_logits - base_logits+ return logitsdiff --git a/models/TTS/yue/llama_patched.py b/models/TTS/yue/llama_patched.pynew file mode 100644index 0000000..ad028d1--- /dev/null+++ b/models/TTS/yue/llama_patched.py@@ -0,0 +1,1293 @@+# coding=utf-8+# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.+#+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX+# and OPT implementations in this library. It has been modified from its+# original forms to accommodate minor architectural differences compared+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+from typing import Callable, List, Optional, Tuple, Union++import torch+import torch.utils.checkpoint+from torch import nn++from transformers.activations import ACT2FN+from transformers.cache_utils import Cache, DynamicCache, StaticCache+from .generation_utils import GenerationMixin+from transformers.modeling_attn_mask_utils import AttentionMaskConverter+from transformers.modeling_flash_attention_utils import FlashAttentionKwargs+from transformers.modeling_outputs import (+ BaseModelOutputWithPast,+ CausalLMOutputWithPast,+ QuestionAnsweringModelOutput,+ SequenceClassifierOutputWithPast,+ TokenClassifierOutput,+)+from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS+from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel+from transformers.processing_utils import Unpack+from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS+from transformers.utils import (+ LossKwargs,+ add_code_sample_docstrings,+ add_start_docstrings,+ add_start_docstrings_to_model_forward,+ logging,+ replace_return_docstrings,+)+from transformers.models.llama.configuration_llama import LlamaConfig+++try:+ import flash_attn+ from flash_attn.flash_attn_interface import _flash_attn_forward+ from flash_attn.flash_attn_interface import flash_attn_with_kvcache+except ImportError:+ flash_attn = None+ flash_attn_varlen_func = None+ _flash_attn_forward = None+++logger = logging.get_logger(__name__)++_CHECKPOINT_FOR_DOC = "meta-llama/Llama-2-7b-hf"+_CONFIG_FOR_DOC = "LlamaConfig"+++class LlamaRMSNorm(nn.Module):+ def __init__(self, hidden_size, eps=1e-6):+ """+ LlamaRMSNorm is equivalent to T5LayerNorm+ """+ super().__init__()+ self.weight = nn.Parameter(torch.ones(hidden_size))+ self.variance_epsilon = eps++ def forward(self, hidden_states):+ input_dtype = hidden_states.dtype+ hidden_states = hidden_states.to(torch.float32)+ variance = hidden_states.pow(2).mean(-1, keepdim=True)+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)+ return self.weight * hidden_states.to(input_dtype)++ def extra_repr(self):+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"+++ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)+++class LlamaRotaryEmbedding(nn.Module):+ def __init__(self, config: LlamaConfig, device=None):+ super().__init__()+ # BC: "rope_type" was originally "type"+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))+ else:+ self.rope_type = "default"+ self.max_seq_len_cached = config.max_position_embeddings+ self.original_max_seq_len = config.max_position_embeddings++ self.config = config+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]++ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)+ self.register_buffer("inv_freq", inv_freq, persistent=False)+ self.original_inv_freq = self.inv_freq++ def _dynamic_frequency_update(self, position_ids, device):+ """+ dynamic RoPE layers should recompute `inv_freq` in the following situations:+ 1 - growing beyond the cached sequence length (allow scaling)+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)+ """+ seq_len = torch.max(position_ids) + 1+ if seq_len > self.max_seq_len_cached: # growth+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation+ self.max_seq_len_cached = seq_len++ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)+ self.max_seq_len_cached = self.original_max_seq_len++ @torch.no_grad()+ def forward(self, x, position_ids):+ if "dynamic" in self.rope_type:+ self._dynamic_frequency_update(position_ids, device=x.device)++ # Core RoPE block+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)+ position_ids_expanded = position_ids[:, None, :].float()+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)+ device_type = x.device.type+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"+ with torch.autocast(device_type=device_type, enabled=False):+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)+ emb = torch.cat((freqs, freqs), dim=-1)+ cos = emb.cos()+ sin = emb.sin()++ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention+ cos = cos * self.attention_scaling+ sin = sin * self.attention_scaling++ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)+++def rotate_half(x):+ """Rotates half the hidden dims of the input."""+ x1 = x[..., : x.shape[-1] // 2]+ x2 = x[..., x.shape[-1] // 2 :]+ return torch.cat((-x2, x1), dim=-1)+++def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):+ """Applies Rotary Position Embedding to the query and key tensors.++ Args:+ q (`torch.Tensor`): The query tensor.+ k (`torch.Tensor`): The key tensor.+ cos (`torch.Tensor`): The cosine part of the rotary embedding.+ sin (`torch.Tensor`): The sine part of the rotary embedding.+ position_ids (`torch.Tensor`, *optional*):+ Deprecated and unused.+ unsqueeze_dim (`int`, *optional*, defaults to 1):+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.+ Returns:+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.+ """+ cos = cos.unsqueeze(unsqueeze_dim)+ sin = sin.unsqueeze(unsqueeze_dim)+ q_embed = (q * cos) + (rotate_half(q) * sin)+ k_embed = (k * cos) + (rotate_half(k) * sin)+ return q_embed, k_embed+++class LlamaMLP(nn.Module):+ def __init__(self, config):+ super().__init__()+ self.config = config+ self.hidden_size = config.hidden_size+ self.intermediate_size = config.intermediate_size+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)+ self.act_fn = ACT2FN[config.hidden_act]++ def forward(self, x):+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))+ return down_proj+++def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:+ """+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)+ """+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape+ if n_rep == 1:+ return hidden_states+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)+++def eager_attention_forward(+ module: nn.Module,+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attention_mask: Optional[torch.Tensor],+ scaling: float,+ dropout: float = 0.0,+ **kwargs,+):+ key_states = repeat_kv(key, module.num_key_value_groups)+ value_states = repeat_kv(value, module.num_key_value_groups)++ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling+ if attention_mask is not None:+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]+ attn_weights = attn_weights + causal_mask++ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)+ attn_output = torch.matmul(attn_weights, value_states)+ attn_output = attn_output.transpose(1, 2).contiguous()++ return attn_output, attn_weights+++class LlamaAttention(nn.Module):+ """Multi-headed attention from 'Attention Is All You Need' paper"""++ def __init__(self, config: LlamaConfig, layer_idx: int):+ super().__init__()+ self.config = config+ self.layer_idx = layer_idx+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads+ self.scaling = self.head_dim**-0.5+ self.attention_dropout = config.attention_dropout+ self.is_causal = True++ self.q_proj = nn.Linear(+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias+ )+ self.k_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.v_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.o_proj = nn.Linear(+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias+ )++ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],+ attention_mask: Optional[torch.Tensor],+ past_key_value: Optional[Cache] = None,+ cache_position: Optional[torch.LongTensor] = None,+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:++ input_shape = hidden_states.shape[:-1]+ hidden_shape = (*input_shape, -1, self.head_dim)++ plan9 = kwargs.get("plan9", False)++ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)+++ cos, sin = position_embeddings+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)+++ if plan9:+ query_states = query_states.transpose(1, 2)+ key_states = key_states.transpose(1, 2)+ value_states = value_states.transpose(1, 2)++ start_positions = kwargs["start_positions"]+ seq_lengths = kwargs["seq_lengths"]+ kv_cache = kwargs["kv_cache"]+ k_cache = kv_cache["k_list"][self.layer_idx]+ v_cache = kv_cache["v_list"][self.layer_idx]+ any_guidance = kwargs["any_guidance"]++ if query_states.shape[1] == 1 or not any_guidance:+ attn_output = flash_attn_with_kvcache(+ q= query_states,+ k_cache= k_cache,+ v_cache= v_cache,+ k= key_states,+ v= value_states,+ cache_seqlens= seq_lengths,+ cache_leftpad= start_positions,+ causal= True,+ )++ else:+ attn0 = flash_attn_with_kvcache(+ q= query_states[0: 1],+ k_cache= k_cache[0: 1],+ v_cache= v_cache[0: 1],+ k= key_states[0: 1],+ v= value_states[0: 1],+ cache_seqlens= seq_lengths[0: 1],+ cache_leftpad= start_positions[0: 1],+ causal= True,+ )++ attn1 = flash_attn_with_kvcache(+ q= query_states[1: 2, -1:, ... ],+ k_cache= k_cache[1: 2],+ v_cache= v_cache[1: 2],+ k= key_states[1: 2, -1:, ... ],+ v= value_states[1: 2, -1:, ... ],+ cache_seqlens= seq_lengths[1: 2],+ cache_leftpad= start_positions[1: 2],+ causal= True,+ )+ attn1ext = torch.zeros_like(attn0)+ attn1ext[:, -1:, ...] = attn1+ attn_output = torch.cat([attn0, attn1ext], 0)+ attn_weights = None+ else:+ if past_key_value is not None:+ # sin and cos are specific to RoPE models; cache_position needed for the static cache+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)++ attention_interface: Callable = eager_attention_forward+ if self.config._attn_implementation != "eager":+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):+ logger.warning_once(+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'+ )+ else:+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]++ attn_output, attn_weights = attention_interface(+ self,+ query_states,+ key_states,+ value_states,+ attention_mask,+ dropout=0.0 if not self.training else self.attention_dropout,+ scaling=self.scaling,+ **kwargs,+ )++ attn_output = attn_output.reshape(*input_shape, -1).contiguous()+ attn_output = self.o_proj(attn_output)+ return attn_output, attn_weights+++class LlamaDecoderLayer(nn.Module):+ def __init__(self, config: LlamaConfig, layer_idx: int):+ super().__init__()+ self.hidden_size = config.hidden_size++ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)++ self.mlp = LlamaMLP(config)+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_value: Optional[Cache] = None,+ output_attentions: Optional[bool] = False,+ use_cache: Optional[bool] = False,+ cache_position: Optional[torch.LongTensor] = None,+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC+ **kwargs: Unpack[FlashAttentionKwargs],+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:+ residual = hidden_states++ hidden_states = self.input_layernorm(hidden_states)++ # return (hidden_states,)+ # Self Attention+ hidden_states, self_attn_weights = self.self_attn(+ hidden_states=hidden_states,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_value=past_key_value,+ output_attentions=output_attentions,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **kwargs,+ )+ hidden_states = residual + hidden_states++ # Fully Connected+ residual = hidden_states+ hidden_states = self.post_attention_layernorm(hidden_states)+ hidden_states = self.mlp(hidden_states)+ hidden_states = residual + hidden_states++ outputs = (hidden_states,)+ if output_attentions:+ pass+ outputs += (self_attn_weights,)++ return outputs+++LLAMA_START_DOCSTRING = r"""+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads+ etc.)++ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage+ and behavior.++ Parameters:+ config ([`LlamaConfig`]):+ Model configuration class with all the parameters of the model. Initializing with a config file does not+ load the weights associated with the model, only the configuration. Check out the+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.+"""+++@add_start_docstrings(+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",+ LLAMA_START_DOCSTRING,+)+class LlamaPreTrainedModel(PreTrainedModel):+ config_class = LlamaConfig+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _no_split_modules = ["LlamaDecoderLayer"]+ _skip_keys_device_placement = ["past_key_values"]+ _supports_flash_attn_2 = True+ _supports_sdpa = True+ _supports_flex_attn = True+ _supports_cache_class = True+ _supports_quantized_cache = True+ _supports_static_cache = True++ def _init_weights(self, module):+ std = self.config.initializer_range+ if isinstance(module, nn.Linear):+ module.weight.data.normal_(mean=0.0, std=std)+ if module.bias is not None:+ module.bias.data.zero_()+ elif isinstance(module, nn.Embedding):+ module.weight.data.normal_(mean=0.0, std=std)+ if module.padding_idx is not None:+ module.weight.data[module.padding_idx].zero_()+++LLAMA_INPUTS_DOCSTRING = r"""+ Args:+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide+ it.++ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and+ [`PreTrainedTokenizer.__call__`] for details.++ [What are input IDs?](../glossary#input-ids)+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:++ - 1 for tokens that are **not masked**,+ - 0 for tokens that are **masked**.++ [What are attention masks?](../glossary#attention-mask)++ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and+ [`PreTrainedTokenizer.__call__`] for details.++ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see+ `past_key_values`).++ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more+ information on the default strategy.++ - 1 indicates the head is **not masked**,+ - 0 indicates the head is **masked**.+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,+ config.n_positions - 1]`.++ [What are position IDs?](../glossary#position-ids)+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.++ Two formats are allowed:+ - a [`~cache_utils.Cache`] instance, see our+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy+ cache format.++ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the+ legacy cache format will be returned.++ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`+ of shape `(batch_size, sequence_length)`.+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the+ model's internal embedding lookup matrix.+ use_cache (`bool`, *optional*):+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see+ `past_key_values`).+ output_attentions (`bool`, *optional*):+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned+ tensors for more detail.+ output_hidden_states (`bool`, *optional*):+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for+ more detail.+ return_dict (`bool`, *optional*):+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer+ the complete sequence length.+"""+++@add_start_docstrings(+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",+ LLAMA_START_DOCSTRING,+)+class LlamaModel(LlamaPreTrainedModel):+ """+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]++ Args:+ config: LlamaConfig+ """++ def __init__(self, config: LlamaConfig):+ super().__init__(config)+ self.padding_idx = config.pad_token_id+ self.vocab_size = config.vocab_size++ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)+ self.layers = nn.ModuleList(+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]+ )+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ self.rotary_emb = LlamaRotaryEmbedding(config=config)+ self.gradient_checkpointing = False++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.embed_tokens++ def set_input_embeddings(self, value):+ self.embed_tokens = value++ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)+ def forward(+ self,+ input_ids: torch.LongTensor = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[Cache] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ use_cache: Optional[bool] = None,+ output_attentions: Optional[bool] = None,+ output_hidden_states: Optional[bool] = None,+ return_dict: Optional[bool] = None,+ cache_position: Optional[torch.LongTensor] = None,+ unconditional_guidance = 0,+ unconditional_past_key_values: Optional[Cache] = None,+ unconditional_cache_position: Optional[torch.LongTensor] = None,+ prompt_length = 0,+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],+ ) -> Union[Tuple, BaseModelOutputWithPast]:+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions+ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )+ use_cache = use_cache if use_cache is not None else self.config.use_cache+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict+ plan9 =flash_attn_kwargs.get("plan9", False)+ if (input_ids is None) ^ (inputs_embeds is not None):+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")++ if inputs_embeds is None:+ inputs_embeds = self.embed_tokens(input_ids)++ if not plan9:+ if self.gradient_checkpointing and self.training and use_cache:+ logger.warning_once(+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."+ )+ use_cache = False++ if use_cache and past_key_values is None:+ past_key_values = DynamicCache()++ if cache_position is None:+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0+ cache_position = torch.arange(+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device+ )+++ if position_ids is None:+ position_ids = cache_position.unsqueeze(0)+++ hidden_states = inputs_embeds++ # create position embeddings to be shared across the decoder layers+ position_embeddings = self.rotary_emb(hidden_states, position_ids)++ causal_mask = self._update_causal_mask(+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions+ )++ if unconditional_guidance > 0 :+ unconditional_hidden_states = hidden_states[:, -1:, :]+ past_seen_tokens = unconditional_past_key_values.get_seq_length() if unconditional_past_key_values is not None else 0+ unconditional_position_ids = torch.full( (inputs_embeds.shape[0],1) , past_seen_tokens, dtype= torch.int64, device=inputs_embeds.device )+ unconditional_position_embeddings = self.rotary_emb(unconditional_hidden_states, unconditional_position_ids)++ else:+ kwargs = flash_attn_kwargs+ hidden_states = inputs_embeds+ position_embeddings = self.rotary_emb(hidden_states, position_ids)+ causal_mask = None+ kv_cache = kwargs["kv_cache"]+ if len(kv_cache) == 0:+ real_max_length = kwargs["real_max_length"]+ v_list = []+ k_list = []+ head_dim = self.config.head_dim+ num_key_value_heads = self.config.num_key_value_heads+ for _ in range(self.config.num_hidden_layers): #self.config.head_dim+ k_list.append( torch.zeros(hidden_states.shape[0], real_max_length, num_key_value_heads ,+ head_dim , dtype= hidden_states.dtype, device= hidden_states.device ) )+ v_list.append( torch.zeros(hidden_states.shape[0], real_max_length, num_key_value_heads ,+ head_dim , dtype= hidden_states.dtype, device= hidden_states.device ) )+ kv_cache["k_list"] = k_list+ kv_cache["v_list"] = v_list++++ # decoder layers+ all_hidden_states = () if output_hidden_states else None+ all_self_attns = () if output_attentions else None++ for decoder_layer in self.layers[: self.config.num_hidden_layers]:+ if output_hidden_states:+ all_hidden_states += (hidden_states,)++ if self.gradient_checkpointing and self.training:+ layer_outputs = self._gradient_checkpointing_func(+ decoder_layer.__call__,+ hidden_states,+ causal_mask,+ position_ids,+ past_key_values,+ output_attentions,+ use_cache,+ cache_position,+ position_embeddings,+ )+ else:+ layer_outputs = decoder_layer(+ hidden_states,+ attention_mask=causal_mask,+ position_ids=position_ids,+ past_key_value=past_key_values,+ output_attentions=output_attentions,+ use_cache=use_cache,+ cache_position=cache_position,+ position_embeddings=position_embeddings,+ **flash_attn_kwargs,+ )++ if unconditional_guidance > 0 :+ unconditional_layer_outputs = decoder_layer(+ unconditional_hidden_states,+ attention_mask=None,+ position_ids=unconditional_position_ids,+ past_key_value=unconditional_past_key_values,+ output_attentions=None,+ use_cache=use_cache,+ cache_position=unconditional_cache_position,+ position_embeddings=unconditional_position_embeddings,+ **flash_attn_kwargs,+ )+++ hidden_states = layer_outputs[0]+ if unconditional_guidance > 0 :+ unconditional_hidden_states = unconditional_layer_outputs[0]++ if output_attentions:+ all_self_attns += (layer_outputs[1],)++ hidden_states = self.norm(hidden_states)+ if unconditional_guidance > 0 :+ unconditional_hidden_states = self.norm(unconditional_hidden_states)++ # add hidden states from the last decoder layer+ if output_hidden_states:+ all_hidden_states += (hidden_states,)++ output = BaseModelOutputWithPast(+ last_hidden_state=hidden_states,+ past_key_values=past_key_values if use_cache else None,+ hidden_states=all_hidden_states,+ attentions=all_self_attns,+ )++ if unconditional_guidance > 0 :+ output["last_unconditional_hidden_state"] = unconditional_hidden_states+ output["unconditional_past_key_values"]= unconditional_past_key_values if use_cache else None,++ return output if return_dict else output.to_tuple()++ def _update_causal_mask(+ self,+ attention_mask: torch.Tensor,+ input_tensor: torch.Tensor,+ cache_position: torch.Tensor,+ past_key_values: Cache,+ output_attentions: bool,+ ):+ if self.config._attn_implementation == "flash_attention_2":+ #############+ if attention_mask is not None and (attention_mask == 0.0).any():+ return attention_mask+ return None++ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail+ # to infer the attention mask.+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0+ using_static_cache = isinstance(past_key_values, StaticCache)++ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:+ if AttentionMaskConverter._ignore_causal_mask_sdpa(+ attention_mask,+ inputs_embeds=input_tensor,+ past_key_values_length=past_seen_tokens,+ is_training=self.training,+ ):+ return None++ dtype, device = input_tensor.dtype, input_tensor.device+ sequence_length = input_tensor.shape[1]+ if using_static_cache:+ target_length = past_key_values.get_max_cache_shape()+ else:+ target_length = (+ attention_mask.shape[-1]+ if isinstance(attention_mask, torch.Tensor)+ else past_seen_tokens + sequence_length + 1+ )++ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(+ attention_mask,+ sequence_length=sequence_length,+ target_length=target_length,+ dtype=dtype,+ device=device,+ cache_position=cache_position,+ batch_size=input_tensor.shape[0],+ )++ if (+ self.config._attn_implementation == "sdpa"+ and attention_mask is not None+ and attention_mask.device.type == "cuda"+ and not output_attentions+ ):+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.+ # Details: https://github.com/pytorch/pytorch/issues/110213+ min_dtype = torch.finfo(dtype).min+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)++ return causal_mask++ @staticmethod+ def _prepare_4d_causal_attention_mask_with_cache_position(+ attention_mask: torch.Tensor,+ sequence_length: int,+ target_length: int,+ dtype: torch.dtype,+ device: torch.device,+ cache_position: torch.Tensor,+ batch_size: int,+ **kwargs,+ ):+ """+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.++ Args:+ attention_mask (`torch.Tensor`):+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape+ `(batch_size, 1, query_length, key_value_length)`.+ sequence_length (`int`):+ The sequence length being processed.+ target_length (`int`):+ The target length: when generating with static cache, the mask should be as long as the static cache,+ to account for the 0 padding, the part of the cache that is not filled yet.+ dtype (`torch.dtype`):+ The dtype to use for the 4D attention mask.+ device (`torch.device`):+ The device to plcae the 4D attention mask on.+ cache_position (`torch.Tensor`):+ Indices depicting the position of the input sequence tokens in the sequence.+ batch_size (`torch.Tensor`):+ Batch size.+ """+ if attention_mask is not None and attention_mask.dim() == 4:+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.+ causal_mask = attention_mask+ else:+ min_dtype = torch.finfo(dtype).min+ causal_mask = torch.full(+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device+ )+ if sequence_length != 1:+ causal_mask = torch.triu(causal_mask, diagonal=1)+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)+ if attention_mask is not None:+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit+ mask_length = attention_mask.shape[-1]+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]+ padding_mask = padding_mask == 0+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(+ padding_mask, min_dtype+ )++ return causal_mask+++class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...+++class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):+ _tied_weights_keys = ["lm_head.weight"]+ _tp_plan = {"lm_head": "colwise_rep"}++ def __init__(self, config):+ super().__init__(config)+ self.model = LlamaModel(config)+ self.vocab_size = config.vocab_size+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.model.embed_tokens++ def set_input_embeddings(self, value):+ self.model.embed_tokens = value++ def get_output_embeddings(self):+ return self.lm_head++ def set_output_embeddings(self, new_embeddings):+ self.lm_head = new_embeddings++ def set_decoder(self, decoder):+ self.model = decoder++ def get_decoder(self):+ return self.model++ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)+ def forward(+ self,+ input_ids: torch.LongTensor = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ labels: Optional[torch.LongTensor] = None,+ use_cache: Optional[bool] = None,+ output_attentions: Optional[bool] = None,+ output_hidden_states: Optional[bool] = None,+ return_dict: Optional[bool] = None,+ cache_position: Optional[torch.LongTensor] = None,+ num_logits_to_keep: int = 0,+ unconditional_guidance = 0,+ unconditional_past_key_values: Optional[Cache] = None,+ unconditional_cache_position: Optional[torch.LongTensor] = None,+ prompt_length = 0,+ **kwargs: Unpack[KwargsForCausalLM],+ ) -> Union[Tuple, CausalLMOutputWithPast]:+ r"""+ Args:+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.++ num_logits_to_keep (`int`, *optional*):+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.++ Returns:++ Example:++ ```python+ >>> from transformers import AutoTokenizer, LlamaForCausalLM++ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")++ >>> prompt = "Hey, are you conscious? Can you talk to me?"+ >>> inputs = tokenizer(prompt, return_tensors="pt")++ >>> # Generate+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."+ ```"""+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions+ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict++ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)+ outputs = self.model(+ input_ids=input_ids,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ cache_position=cache_position,+ unconditional_guidance=unconditional_guidance,+ unconditional_past_key_values = unconditional_past_key_values,+ unconditional_cache_position = unconditional_cache_position,+ prompt_length = prompt_length,+ **kwargs,+ )++ hidden_states = outputs[0]+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)++ if not return_dict:+ output = (logits,) + outputs[1:]+ return (loss,) + output if loss is not None else output++ ret = CausalLMOutputWithPast(+ loss=loss,+ logits=logits,+ past_key_values=outputs.past_key_values,+ hidden_states=outputs.hidden_states,+ attentions=outputs.attentions,+ )++ if unconditional_guidance > 0:+ unconditional_hidden_states = outputs["last_unconditional_hidden_state"]+ unconditional_past_key_values = outputs["unconditional_past_key_values"]+ unconditional_logits = self.lm_head(unconditional_hidden_states[:, -num_logits_to_keep:, :])+ ret["unconditional_logits"] = unconditional_logits+ ret["unconditional_past_key_values"] = unconditional_past_key_values+ return ret+@add_start_docstrings(+ """+ The LLaMa Model transformer with a sequence classification head on top (linear layer).++ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models+ (e.g. GPT-2) do.++ Since it does classification on the last token, it requires to know the position of the last token. If a+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in+ each row of the batch).+ """,+ LLAMA_START_DOCSTRING,+)+class LlamaForSequenceClassification(LlamaPreTrainedModel):+ def __init__(self, config):+ super().__init__(config)+ self.num_labels = config.num_labels+ self.model = LlamaModel(config)+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.model.embed_tokens++ def set_input_embeddings(self, value):+ self.model.embed_tokens = value++ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)+ def forward(+ self,+ input_ids: Optional[torch.LongTensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ labels: Optional[torch.LongTensor] = None,+ use_cache: Optional[bool] = None,+ output_attentions: Optional[bool] = None,+ output_hidden_states: Optional[bool] = None,+ return_dict: Optional[bool] = None,+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:+ r"""+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).+ """+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict++ transformer_outputs = self.model(+ input_ids,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )+ hidden_states = transformer_outputs[0]+ logits = self.score(hidden_states)++ if input_ids is not None:+ batch_size = input_ids.shape[0]+ else:+ batch_size = inputs_embeds.shape[0]++ if self.config.pad_token_id is None and batch_size != 1:+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")+ if self.config.pad_token_id is None:+ sequence_lengths = -1+ else:+ if input_ids is not None:+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1+ sequence_lengths = sequence_lengths % input_ids.shape[-1]+ sequence_lengths = sequence_lengths.to(logits.device)+ else:+ sequence_lengths = -1++ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)++ if not return_dict:+ output = (pooled_logits,) + transformer_outputs[1:]+ return ((loss,) + output) if loss is not None else output++ return SequenceClassifierOutputWithPast(+ loss=loss,+ logits=pooled_logits,+ past_key_values=transformer_outputs.past_key_values,+ hidden_states=transformer_outputs.hidden_states,+ attentions=transformer_outputs.attentions,+ )+++@add_start_docstrings(+ """+The Llama Model transformer with a span classification head on top for extractive question-answering tasks like+SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).+ """,+ LLAMA_START_DOCSTRING,+)+class LlamaForQuestionAnswering(LlamaPreTrainedModel):+ base_model_prefix = "transformer"++ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama+ def __init__(self, config):+ super().__init__(config)+ self.transformer = LlamaModel(config)+ self.qa_outputs = nn.Linear(config.hidden_size, 2)++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.transformer.embed_tokens++ def set_input_embeddings(self, value):+ self.transformer.embed_tokens = value++ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)+ def forward(+ self,+ input_ids: Optional[torch.LongTensor] = None,+ attention_mask: Optional[torch.FloatTensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ start_positions: Optional[torch.LongTensor] = None,+ end_positions: Optional[torch.LongTensor] = None,+ output_attentions: Optional[bool] = None,+ output_hidden_states: Optional[bool] = None,+ return_dict: Optional[bool] = None,+ **kwargs,+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:+ r"""+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):+ Labels for position (index) of the start of the labelled span for computing the token classification loss.+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence+ are not taken into account for computing the loss.+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):+ Labels for position (index) of the end of the labelled span for computing the token classification loss.+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence+ are not taken into account for computing the loss.+ """+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict++ outputs = self.transformer(+ input_ids,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )++ sequence_output = outputs[0]++ logits = self.qa_outputs(sequence_output)+ start_logits, end_logits = logits.split(1, dim=-1)+ start_logits = start_logits.squeeze(-1).contiguous()+ end_logits = end_logits.squeeze(-1).contiguous()++ loss = None+ if start_positions is not None and end_positions is not None:+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)++ if not return_dict:+ output = (start_logits, end_logits) + outputs[2:]+ return ((loss,) + output) if loss is not None else output++ return QuestionAnsweringModelOutput(+ loss=loss,+ start_logits=start_logits,+ end_logits=end_logits,+ hidden_states=outputs.hidden_states,+ attentions=outputs.attentions,+ )+++@add_start_docstrings(+ """+ The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states+ output) e.g. for Named-Entity-Recognition (NER) tasks.+ """,+ LLAMA_START_DOCSTRING,+)+class LlamaForTokenClassification(LlamaPreTrainedModel):+ def __init__(self, config):+ super().__init__(config)+ self.num_labels = config.num_labels+ self.model = LlamaModel(config)+ if getattr(config, "classifier_dropout", None) is not None:+ classifier_dropout = config.classifier_dropout+ elif getattr(config, "hidden_dropout", None) is not None:+ classifier_dropout = config.hidden_dropout+ else:+ classifier_dropout = 0.1+ self.dropout = nn.Dropout(classifier_dropout)+ self.score = nn.Linear(config.hidden_size, config.num_labels)++ # Initialize weights and apply final processing+ self.post_init()++ def get_input_embeddings(self):+ return self.model.embed_tokens++ def set_input_embeddings(self, value):+ self.model.embed_tokens = value++ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)+ @add_code_sample_docstrings(+ checkpoint=_CHECKPOINT_FOR_DOC,+ output_type=TokenClassifierOutput,+ config_class=_CONFIG_FOR_DOC,+ )+ def forward(+ self,+ input_ids: Optional[torch.LongTensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.LongTensor] = None,+ past_key_values: Optional[List[torch.FloatTensor]] = None,+ inputs_embeds: Optional[torch.FloatTensor] = None,+ labels: Optional[torch.LongTensor] = None,+ use_cache: Optional[bool] = None,+ output_attentions: Optional[bool] = None,+ output_hidden_states: Optional[bool] = None,+ return_dict: Optional[bool] = None,+ ) -> Union[Tuple, TokenClassifierOutput]:+ r"""+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).+ """+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict++ outputs = self.model(+ input_ids,+ attention_mask=attention_mask,+ position_ids=position_ids,+ past_key_values=past_key_values,+ inputs_embeds=inputs_embeds,+ use_cache=use_cache,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )+ sequence_output = outputs[0]+ sequence_output = self.dropout(sequence_output)+ logits = self.score(sequence_output)++ loss = None+ if labels is not None:+ loss = self.loss_function(logits, labels, self.config)++ if not return_dict:+ output = (logits,) + outputs[2:]+ return ((loss,) + output) if loss is not None else output++ return TokenClassifierOutput(+ loss=loss,+ logits=logits,+ hidden_states=outputs.hidden_states,+ attentions=outputs.attentions,+ )+++__all__ = [+ "LlamaForCausalLM",+ "LlamaModel",+ "LlamaPreTrainedModel",+ "LlamaForSequenceClassification",+ "LlamaForQuestionAnswering",+ "LlamaForTokenClassification",+]diff --git a/models/TTS/yue/mmtokenizer.py b/models/TTS/yue/mmtokenizer.pynew file mode 100644index 0000000..85046e2--- /dev/null+++ b/models/TTS/yue/mmtokenizer.py@@ -0,0 +1,367 @@+from abc import ABC+from abc import abstractmethod+++class AbstractTokenizer(ABC):+ """Abstract class for tokenizer."""++ def __init__(self, name):+ self.name = name+ super().__init__()++ @property+ @abstractmethod+ def vocab_size(self):+ pass++ @property+ @abstractmethod+ def vocab(self):+ """Dictionary from vocab text token to id token."""+ pass++ @property+ @abstractmethod+ def inv_vocab(self):+ """Dictionary from vocab id token to text token."""+ pass++ @abstractmethod+ def tokenize(self, text):+ pass++ def detokenize(self, token_ids):+ raise NotImplementedError('detokenizer is not implemented for {} '+ 'tokenizer'.format(self.name))++ @property+ def cls(self):+ raise NotImplementedError('CLS is not provided for {} '+ 'tokenizer'.format(self.name))++ @property+ def sep(self):+ raise NotImplementedError('SEP is not provided for {} '+ 'tokenizer'.format(self.name))++ @property+ def pad(self):+ raise NotImplementedError('PAD is not provided for {} '+ 'tokenizer'.format(self.name))++ @property+ def eod(self):+ raise NotImplementedError('EOD is not provided for {} '+ 'tokenizer'.format(self.name))++ @property+ def mask(self):+ raise NotImplementedError('MASK is not provided for {} '+ 'tokenizer'.format(self.name))+++class _SentencePieceTokenizer(AbstractTokenizer):+ """SentencePieceTokenizer-Megatron wrapper"""++ def __init__(self, model_file, vocab_extra_ids=0):+ name = 'SentencePieceTokenizer'+ super().__init__(name)++ import sentencepiece+ self.tokenizer = sentencepiece.SentencePieceProcessor(model_file=model_file)+ self._initalize(vocab_extra_ids)++ def _populate_vocab(self):+ self._vocab = {}+ self._inv_vocab = {}++ for i in range(len(self.tokenizer)):+ t = self.tokenizer.id_to_piece(i)+ self._inv_vocab[i] = t+ self._vocab[t] = i++ def _initalize(self, vocab_extra_ids):+ self._populate_vocab()+ self._special_tokens = {}+ self._inv_special_tokens = {}++ self._t5_tokens = []++ def _add_special_token(t):+ if t not in self._vocab:+ next_id = len(self._vocab)+ self._vocab[t] = next_id+ self._inv_vocab[next_id] = t+ self._special_tokens[t] = self._vocab[t]+ self._inv_special_tokens[self._vocab[t]] = t++ _add_special_token('<CLS>')+ self._cls_id = self._vocab['<CLS>']+ _add_special_token('<SEP>')+ self._sep_id = self._vocab['<SEP>']+ _add_special_token('<EOD>')+ self._eod_id = self._vocab['<EOD>']+ _add_special_token('<MASK>')+ self._mask_id = self._vocab['<MASK>']++ pad_id = self.tokenizer.pad_id()+ try:+ pad_token = self.tokenizer.id_to_piece(pad_id)+ except IndexError:+ pad_token = '<PAD>'+ _add_special_token(pad_token)+ self._pad_id = self._vocab[pad_token]++ bos_id = self.tokenizer.bos_id()+ try:+ bos_token = self.tokenizer.id_to_piece(bos_id)+ except IndexError:+ bos_token = '<BOS>'+ _add_special_token(bos_token)+ self._bos_id = self._vocab[bos_token]++ eos_id = self.tokenizer.eos_id()+ try:+ eos_token = self.tokenizer.id_to_piece(eos_id)+ except IndexError:+ eos_token = '<EOS>'+ _add_special_token(eos_token)+ self._eos_id = self._vocab[eos_token]++ for i in range(vocab_extra_ids):+ t = "<extra_id_{}>".format(i)+ _add_special_token(t)+ self._t5_tokens += [t]++ @property+ def vocab_size(self):+ return len(self._vocab)++ @property+ def vocab(self):+ return self._vocab++ @property+ def inv_vocab(self):+ return self._inv_vocab++ @property+ def decoder(self):+ return self._inv_vocab++ @property+ def encoder(self):+ return self._vocab++ # From:+ # https://github.com/NVIDIA/NeMo/blob/c8fa217e811d60d11d014827c7f3845ff6c99ae7/nemo/collections/common/tokenizers/sentencepiece_tokenizer.py#L89+ def tokenize(self, text):+ ids = []+ idx = 0++ while 1:+ indices = {}+ for token in self._special_tokens:+ try:+ indices[token] = text[idx:].index(token)+ except ValueError:+ continue+ if len(indices) == 0:+ break++ next_token = min(indices, key=indices.get)+ next_idx = idx + indices[next_token]++ ids.extend(self.tokenizer.encode_as_ids(text[idx:next_idx]))+ ids.append(self._special_tokens[next_token])+ idx = next_idx + len(next_token)++ ids.extend(self.tokenizer.encode_as_ids(text[idx:]))+ return ids++ # From:+ # https://github.com/NVIDIA/NeMo/blob/c8fa217e811d60d11d014827c7f3845ff6c99ae7/nemo/collections/common/tokenizers/sentencepiece_tokenizer.py#L125+ def detokenize(self, ids):+ text = ""+ last_i = 0++ for i, id in enumerate(ids):+ if id in self._inv_special_tokens:+ text += self.tokenizer.decode_ids(ids[last_i:i]) + " "+ text += self._inv_special_tokens[id] + " "+ last_i = i + 1++ text += self.tokenizer.decode_ids(ids[last_i:])+ return text++ @property+ def cls(self):+ return self._cls_id++ @property+ def sep(self):+ return self._sep_id++ @property+ def pad(self):+ return self._pad_id++ @property+ def bos_token_id(self):+ return self._bos_id++ @property+ def bos(self):+ return self._bos_id++ @property+ def eod(self):+ return self._eod_id++ @property+ def eos_token_id(self):+ return self._eos_id++ @property+ def eos(self):+ return self._eos_id++ @property+ def mask(self):+ return self._mask_id++ @property+ def additional_special_tokens_ids(self):+ return [self.vocab[k] for k in self._t5_tokens]++class _MMSentencePieceTokenizer(_SentencePieceTokenizer):+ """SentencePieceTokenizer-Megatron wrapper"""++ def __init__(self, model_file, vocab_extra_ids=0):+ super().__init__(model_file, vocab_extra_ids)+++ def _initalize(self, vocab_extra_ids):+ self._populate_vocab()+ self._special_tokens = {}+ self._inv_special_tokens = {}++ self._t5_tokens = []++ def _add_special_token(t):+ if t not in self._vocab:+ next_id = len(self._vocab)+ self._vocab[t] = next_id+ self._inv_vocab[next_id] = t+ self._special_tokens[t] = self._vocab[t]+ self._inv_special_tokens[self._vocab[t]] = t++ _add_special_token('<CLS>')+ self._cls_id = self._vocab['<CLS>']+ _add_special_token('<SEP>')+ self._sep_id = self._vocab['<SEP>']+ _add_special_token('<EOD>')+ self._eod_id = self._vocab['<EOD>']+ _add_special_token('<MASK>')+ self._mask_id = self._vocab['<MASK>']++ _add_special_token('<SOA>')+ self._soa_id = self._vocab['<SOA>']+ _add_special_token('<EOA>')+ self._eoa_id = self._vocab['<EOA>']+ _add_special_token('<SOV>')+ self._sov_id = self._vocab['<SOV>']+ _add_special_token('<EOV>')+ self._eov_id = self._vocab['<EOV>']+ _add_special_token('<SOI>')+ self._soi_id = self._vocab['<SOI>']+ _add_special_token('<EOI>')+ self._eoi_id = self._vocab['<EOI>']+ _add_special_token('<s_local>')+ self._s_local_id = self._vocab['<s_local>']+ _add_special_token('<e_local>')+ self._e_local_id = self._vocab['<e_local>']+ _add_special_token('<s_global>')+ self._s_global_id = self._vocab['<s_global>']+ _add_special_token('<e_global>')+ self._e_global_id = self._vocab['<e_global>']+ _add_special_token('<stage_1>')+ self._stage_1_id = self._vocab['<stage_1>']+ _add_special_token('<stage_2>')+ self._stage_2_id = self._vocab['<stage_2>']+ pad_id = self.tokenizer.pad_id()+ try:+ pad_token = self.tokenizer.id_to_piece(pad_id)+ except IndexError:+ pad_token = '<PAD>'+ _add_special_token(pad_token)+ self._pad_id = self._vocab[pad_token]++ bos_id = self.tokenizer.bos_id()+ try:+ bos_token = self.tokenizer.id_to_piece(bos_id)+ except IndexError:+ bos_token = '<BOS>'+ _add_special_token(bos_token)+ self._bos_id = self._vocab[bos_token]++ eos_id = self.tokenizer.eos_id()+ try:+ eos_token = self.tokenizer.id_to_piece(eos_id)+ except IndexError:+ eos_token = '<EOS>'+ _add_special_token(eos_token)+ self._eos_id = self._vocab[eos_token]++ for i in range(vocab_extra_ids):+ t = "<extra_id_{}>".format(i)+ _add_special_token(t)+ self._t5_tokens += [t]++ @property+ def soa(self):+ return self._soa_id++ @property+ def eoa(self):+ return self._eoa_id++ @property+ def sov(self):+ return self._sov_id++ @property+ def eov(self):+ return self._eov_id++ @property+ def soi(self):+ return self._soi_id++ @property+ def eoi(self):+ return self._eoi_id++ @property+ def s_local(self):+ return self._s_local_id++ @property+ def e_local(self):+ return self._e_local_id++ @property+ def s_global(self):+ return self._s_global_id++ @property+ def e_global(self):+ return self._e_global_id++ @property+ def stage_1(self):+ return self._stage_1_id++ @property+ def stage_2(self):+ return self._stage_2_iddiff --git a/models/TTS/yue/pipeline.py b/models/TTS/yue/pipeline.pynew file mode 100644index 0000000..442cf02--- /dev/null+++ b/models/TTS/yue/pipeline.py@@ -0,0 +1,883 @@+from __future__ import annotations++import importlib.util+import os+import random+import re+import sys+from typing import Optional++import numpy as np+import torch+import torchaudio+import torchaudio.functional as taF+from torchaudio.transforms import Resample+from tqdm import tqdm+from einops import rearrange+from transformers import LogitsProcessor, LogitsProcessorList+from omegaconf import OmegaConf++from mmgp import offload+from shared.utils import files_locator as fl+from .codecmanipulator import CodecManipulator+from .mmtokenizer import _MMSentencePieceTokenizer+from .llama_patched import LlamaForCausalLM+++def _flash_attn_available() -> bool:+ try:+ import flash_attn # noqa: F401+ except Exception:+ return False+ return True+++YUE_STAGE1_COT_REPO = "m-a-p/YuE-s1-7B-anneal-en-cot"+YUE_STAGE1_ICL_REPO = "m-a-p/YuE-s1-7B-anneal-en-icl"+YUE_STAGE2_REPO = "m-a-p/YuE-s2-1B-general"+YUE_TOKENIZER_FOLDER = "mm_tokenizer_v0.2_hf"+YUE_XCODEC_ROOT = "xcodec_mini_infer"+++class BlockTokenRangeProcessor(LogitsProcessor):+ def __init__(self, start_id: int, end_id: int):+ self.blocked_token_ids = list(range(start_id, end_id))++ def __call__(self, input_ids, scores):+ scores[:, self.blocked_token_ids] = -float("inf")+ return scores+++def _seed_everything(seed: int) -> None:+ random.seed(seed)+ np.random.seed(seed)+ torch.manual_seed(seed)+ torch.cuda.manual_seed_all(seed)+ torch.backends.cudnn.deterministic = True+ torch.backends.cudnn.benchmark = False+++def _read_text_or_file(value: str, label: str) -> str:+ if not value:+ return ""+ if os.path.isfile(value):+ with open(value, encoding="utf-8") as fp:+ return fp.read()+ if not isinstance(value, str):+ raise ValueError(f"{label} must be a string, got {type(value)}")+ return value+++def _split_lyrics(lyrics: str) -> list[str]:+ pattern = r"\[(\w+)\](.*?)\n(?=\[|\Z)"+ segments = re.findall(pattern, lyrics, re.DOTALL)+ structured_lyrics = [f"[{seg[0]}]\\n{seg[1].strip()}\\n\\n" for seg in segments]+ return structured_lyrics+++def _ensure_sys_path(path: str) -> None:+ if path and path not in sys.path:+ sys.path.append(path)+++def _load_module_from_path(module_name: str, path: str):+ spec = importlib.util.spec_from_file_location(module_name, path)+ if spec is None or spec.loader is None:+ raise ImportError(f"Unable to load module from {path}")+ module = importlib.util.module_from_spec(spec)+ sys.modules[module_name] = module+ spec.loader.exec_module(module)+ return module+++class YuePipeline:+ def __init__(+ self,+ stage1_weights_path: str,+ stage2_weights_path: str,+ *,+ use_audio_prompt: bool = False,+ max_new_tokens: int = 3000,+ run_n_segments: int = 2,+ stage2_batch_size: int = 4,+ segment_duration: int = 6,+ prompt_start_time: float = 0.0,+ prompt_end_time: float = 30.0,+ attn_implementation: Optional[str] = None,+ ) -> None:+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ self._interrupt = False++ assets = self._resolve_assets(+ stage1_weights_path,+ stage2_weights_path,+ use_audio_prompt,+ )+ stage1_weights_path = assets["stage1_weights"]+ stage1_config_path = assets["stage1_config"]+ stage2_weights_path = assets["stage2_weights"]+ stage2_config_path = assets["stage2_config"]+ tokenizer_path = assets["tokenizer_path"]+ xcodec_root = assets["xcodec_root"]+ xcodec_config_path = assets["xcodec_config"]+ xcodec_ckpt_path = assets["xcodec_ckpt"]+ vocoder_config_path = assets["vocoder_config"]+ vocoder_vocal_path = assets["vocoder_vocal"]+ vocoder_inst_path = assets["vocoder_inst"]++ self.stage1_weights_path = stage1_weights_path+ self.stage1_config_path = stage1_config_path+ self.stage2_weights_path = stage2_weights_path+ self.stage2_config_path = stage2_config_path++ self.max_new_tokens = int(max_new_tokens)+ self.run_n_segments = int(run_n_segments)+ self.stage2_batch_size = int(stage2_batch_size)+ self.segment_duration = int(segment_duration)+ self.prompt_start_time = float(prompt_start_time)+ self.prompt_end_time = float(prompt_end_time)++ if attn_implementation is None:+ attn_implementation = "flash_attention_2" if _flash_attn_available() else "sdpa"+ self.attn_implementation = attn_implementation+ print(f"[YUE] Attention backend: {self.attn_implementation}")++ self.mmtokenizer = _MMSentencePieceTokenizer(tokenizer_path)+ self.codectool = CodecManipulator("xcodec", 0, 1)+ self.codectool_stage2 = CodecManipulator("xcodec", 0, 8)++ self.model_stage1 = offload.fast_load_transformers_model(+ stage1_weights_path,+ modelClass=LlamaForCausalLM,+ defaultConfigPath=stage1_config_path,+ configKwargs={"attn_implementation": attn_implementation},+ default_dtype=torch.bfloat16,+ ignore_unused_weights=True,+ )+ self._set_attn_implementation(self.model_stage1, attn_implementation)+ self.model_stage1.eval()+ self.model_stage1._validate_model_kwargs = lambda *_args, **_kwargs: None+ self.model_stage1._offload_hooks = ["generate"]+ self.model = self.model_stage1++ self.model_stage2 = offload.fast_load_transformers_model(+ stage2_weights_path,+ modelClass=LlamaForCausalLM,+ defaultConfigPath=stage2_config_path,+ configKwargs={"attn_implementation": attn_implementation},+ default_dtype=torch.float16,+ ignore_unused_weights=True,+ )+ self._set_attn_implementation(self.model_stage2, attn_implementation)+ self.model_stage2.eval()+ self.model_stage2._validate_model_kwargs = lambda *_args, **_kwargs: None+ self.model_stage2._offload_hooks = ["generate"]+ self.model2 = self.model_stage2++ _ensure_sys_path(xcodec_root)+ _ensure_sys_path(os.path.join(xcodec_root, "descriptaudiocodec"))++ soundstream_path = os.path.join(xcodec_root, "models", "soundstream_hubert_new.py")+ soundstream_module = _load_module_from_path(+ "xcodec_soundstream_hubert_new", soundstream_path+ )+ SoundStream = soundstream_module.SoundStream+ sys.modules["models.soundstream_hubert_new"] = soundstream_module+ from vocoder import build_codec_model++ model_config = OmegaConf.load(xcodec_config_path)+ generator_name = model_config.generator.name+ generator_cls = getattr(soundstream_module, generator_name, None)+ if generator_cls is None:+ raise ValueError(f"Unsupported xcodec generator '{generator_name}'")++ prev_cwd = os.getcwd()+ os.chdir(os.path.dirname(xcodec_root))+ try:+ self.codec_model = generator_cls(**model_config.generator.config)+ finally:+ os.chdir(prev_cwd)+ parameter_dict = torch.load(+ xcodec_ckpt_path, map_location="cpu", weights_only=False+ )+ self.codec_model.load_state_dict(parameter_dict["codec_model"])+ self.codec_model.eval()+ self.codec_model._offload_hooks = ["encode", "decode", "get_embed"]++ self.vocoder_vocal, self.vocoder_inst = build_codec_model(+ vocoder_config_path, vocoder_vocal_path, vocoder_inst_path+ )+ self.vocoder_vocal.eval()+ self.vocoder_inst.eval()++ self.codec_fps = self.codectool.fps or 50+ self.codec_sample_rate = getattr(self.codec_model, "sample_rate", 16000)++ @staticmethod+ def _set_attn_implementation(model, attn_implementation: str) -> None:+ if not hasattr(model, "config"):+ return+ model.config._attn_implementation = attn_implementation+ model.config.attn_implementation = attn_implementation+ if hasattr(model, "generation_config"):+ model.generation_config._attn_implementation = attn_implementation+ model.generation_config.attn_implementation = attn_implementation++ @staticmethod+ def _resolve_assets(+ stage1_weights: str,+ stage2_weights: str,+ use_audio_prompt: bool,+ ) -> dict[str, str]:+ stage1_weights = stage1_weights or ""+ stage2_weights = stage2_weights or ""++ if stage1_weights:+ stage1_weights = fl.locate_file(stage1_weights, error_if_none=False) or stage1_weights+ if stage2_weights:+ stage2_weights = fl.locate_file(stage2_weights, error_if_none=False) or stage2_weights++ stage1_repo = YUE_STAGE1_ICL_REPO if use_audio_prompt else YUE_STAGE1_COT_REPO+ stage1_folder = os.path.basename(stage1_repo)+ stage2_folder = os.path.basename(YUE_STAGE2_REPO)++ stage1_dir = os.path.dirname(stage1_weights) if stage1_weights else ""+ stage2_dir = os.path.dirname(stage2_weights) if stage2_weights else ""++ stage1_config = os.path.join(stage1_dir, "config.json") if stage1_dir else ""+ stage2_config = os.path.join(stage2_dir, "config.json") if stage2_dir else ""++ stage1_config = fl.locate_file(stage1_config, error_if_none=False) or stage1_config+ stage2_config = fl.locate_file(stage2_config, error_if_none=False) or stage2_config++ if not stage1_config or not os.path.isfile(stage1_config):+ stage1_config = (+ fl.locate_file(os.path.join(stage1_folder, "config.json"), error_if_none=False)+ or stage1_config+ )+ if not stage2_config or not os.path.isfile(stage2_config):+ stage2_config = (+ fl.locate_file(os.path.join(stage2_folder, "config.json"), error_if_none=False)+ or stage2_config+ )++ tokenizer_path = None+ if stage1_weights:+ tokenizer_path = fl.locate_file(+ os.path.join(os.path.dirname(stage1_weights), "tokenizer.model"),+ error_if_none=False,+ )+ if tokenizer_path is None:+ tokenizer_path = fl.locate_file(+ os.path.join(YUE_TOKENIZER_FOLDER, "tokenizer.model"),+ error_if_none=False,+ )++ xcodec_root = fl.locate_folder(YUE_XCODEC_ROOT, error_if_none=False)++ xcodec_config = fl.locate_file(+ os.path.join(YUE_XCODEC_ROOT, "final_ckpt", "config.yaml"),+ error_if_none=False,+ )+ if xcodec_config is None and xcodec_root:+ xcodec_config = os.path.join(xcodec_root, "final_ckpt", "config.yaml")++ xcodec_ckpt = fl.locate_file(+ os.path.join(YUE_XCODEC_ROOT, "final_ckpt", "ckpt_00360000.pth"),+ error_if_none=False,+ )+ if xcodec_ckpt is None and xcodec_root:+ xcodec_ckpt = os.path.join(xcodec_root, "final_ckpt", "ckpt_00360000.pth")++ vocoder_config = fl.locate_file(+ os.path.join(YUE_XCODEC_ROOT, "decoders", "config.yaml"),+ error_if_none=False,+ )+ if vocoder_config is None and xcodec_root:+ vocoder_config = os.path.join(xcodec_root, "decoders", "config.yaml")++ vocoder_vocal = fl.locate_file(+ os.path.join(YUE_XCODEC_ROOT, "decoders", "decoder_131000.pth"),+ error_if_none=False,+ )+ if vocoder_vocal is None and xcodec_root:+ vocoder_vocal = os.path.join(xcodec_root, "decoders", "decoder_131000.pth")++ vocoder_inst = fl.locate_file(+ os.path.join(YUE_XCODEC_ROOT, "decoders", "decoder_151000.pth"),+ error_if_none=False,+ )+ if vocoder_inst is None and xcodec_root:+ vocoder_inst = os.path.join(xcodec_root, "decoders", "decoder_151000.pth")++ missing = []+ for name, value, is_dir in [+ ("stage1_weights", stage1_weights, False),+ ("stage1_config", stage1_config, False),+ ("stage2_weights", stage2_weights, False),+ ("stage2_config", stage2_config, False),+ ("tokenizer_path", tokenizer_path, False),+ ("xcodec_root", xcodec_root, True),+ ("xcodec_config", xcodec_config, False),+ ("xcodec_ckpt", xcodec_ckpt, False),+ ("vocoder_config", vocoder_config, False),+ ("vocoder_vocal", vocoder_vocal, False),+ ("vocoder_inst", vocoder_inst, False),+ ]:+ if not value:+ missing.append(name)+ elif is_dir and not os.path.isdir(value):+ missing.append(name)+ elif not is_dir and not os.path.isfile(value):+ missing.append(name)+ if missing:+ raise FileNotFoundError(f"Missing Yue assets: {missing}")++ return {+ "stage1_weights": stage1_weights,+ "stage1_config": stage1_config,+ "stage2_weights": stage2_weights,+ "stage2_config": stage2_config,+ "tokenizer_path": tokenizer_path,+ "xcodec_root": xcodec_root,+ "xcodec_config": xcodec_config,+ "xcodec_ckpt": xcodec_ckpt,+ "vocoder_config": vocoder_config,+ "vocoder_vocal": vocoder_vocal,+ "vocoder_inst": vocoder_inst,+ }++ def _check_abort(self) -> None:+ if self._interrupt:+ raise RuntimeError("Abort requested")++ def _load_audio_mono(self, filepath: str, sampling_rate: int) -> torch.Tensor:+ audio, sr = torchaudio.load(filepath)+ audio = torch.mean(audio, dim=0, keepdim=True)+ if sr != sampling_rate:+ resampler = Resample(orig_freq=sr, new_freq=sampling_rate)+ audio = resampler(audio)+ return audio++ def _encode_audio(self, audio_prompt: torch.Tensor, target_bw: float = 0.5) -> np.ndarray:+ if len(audio_prompt.shape) < 3:+ audio_prompt = audio_prompt.unsqueeze(0)+ with torch.no_grad():+ raw_codes = self.codec_model.encode(audio_prompt.to(self.device), target_bw=target_bw)+ raw_codes = raw_codes.transpose(0, 1)+ raw_codes = raw_codes.cpu().numpy().astype(np.int16)+ return raw_codes++ def _build_audio_prompt_ids(+ self,+ audio_prompt: Optional[str],+ audio_prompt2: Optional[str],+ prompt_start_time: float,+ prompt_end_time: float,+ use_dual_tracks: bool,+ ) -> list[int]:+ if use_dual_tracks:+ vocals_ids = self._load_audio_mono(audio_prompt, self.codec_sample_rate)+ instrumental_ids = self._load_audio_mono(audio_prompt2, self.codec_sample_rate)+ vocals_ids = self._encode_audio(vocals_ids, target_bw=0.5)+ instrumental_ids = self._encode_audio(instrumental_ids, target_bw=0.5)+ vocals_ids = self.codectool.npy2ids(vocals_ids[0])+ instrumental_ids = self.codectool.npy2ids(instrumental_ids[0])+ min_size = min(len(vocals_ids), len(instrumental_ids))+ vocals_ids = vocals_ids[0:min_size]+ instrumental_ids = instrumental_ids[0:min_size]+ ids_segment_interleaved = rearrange(+ [np.array(vocals_ids), np.array(instrumental_ids)], "b n -> (n b)"+ )+ audio_prompt_codec = ids_segment_interleaved[+ int(prompt_start_time * self.codec_fps * 2) : int(prompt_end_time * self.codec_fps * 2)+ ]+ audio_prompt_codec = audio_prompt_codec.tolist()+ else:+ audio_prompt_tensor = self._load_audio_mono(audio_prompt, self.codec_sample_rate)+ raw_codes = self._encode_audio(audio_prompt_tensor, target_bw=0.5)+ code_ids = self.codectool.npy2ids(raw_codes[0])+ audio_prompt_codec = code_ids[+ int(prompt_start_time * self.codec_fps) : int(prompt_end_time * self.codec_fps)+ ]++ audio_prompt_codec_ids = (+ [self.mmtokenizer.soa] + self.codectool.sep_ids + audio_prompt_codec + [self.mmtokenizer.eoa]+ )+ sentence_ids = (+ self.mmtokenizer.tokenize("[start_of_reference]")+ + audio_prompt_codec_ids+ + self.mmtokenizer.tokenize("[end_of_reference]")+ )+ return sentence_ids++ def _stage1_inference(+ self,+ genres: str,+ lyrics_input: str,+ run_n_segments: int,+ max_new_tokens: int,+ temperature: float,+ use_audio_prompt: bool,+ use_dual_tracks_prompt: bool,+ audio_prompt: Optional[str],+ audio_prompt2: Optional[str],+ prompt_start_time: float,+ prompt_end_time: float,+ callback=None,+ set_header_text=None,+ ):+ genres = genres.strip()+ lyrics = _split_lyrics(lyrics_input)+ if not lyrics:+ lyrics = [lyrics_input.strip()]+ full_lyrics = "\n".join(lyrics)+ prompt_texts = [+ f"Generate music from the given lyrics segment by segment.\\n[Genre] {genres}\\n{full_lyrics}"+ ]+ prompt_texts += lyrics++ top_p = 0.93+ repetition_penalty = 1.2+ start_of_segment = self.mmtokenizer.tokenize("[start_of_segment]")+ end_of_segment = self.mmtokenizer.tokenize("[end_of_segment]")++ run_n_segments = min(max(1, run_n_segments), len(lyrics))+ raw_output = None++ for i, p in enumerate(tqdm(prompt_texts[1 : run_n_segments + 1]), 1):+ self._check_abort()+ segment_label = f"Segment {i}/{run_n_segments}"+ def hf_callback(step_idx: int, total_tokens: int, label: str = segment_label):+ self._check_abort()+ if callback is not None:+ callback(+ step_idx=step_idx,+ override_num_inference_steps=total_tokens,+ pass_no=1,+ denoising_extra=label,+ )++ if set_header_text is not None:+ set_header_text(f"Stage 1: Segment {i} of {run_n_segments}")++ section_text = p.replace("[start_of_segment]", "").replace("[end_of_segment]", "")+ guidance_scale = 1.5 if i <= 1 else 1.2++ if i == 1:+ if use_audio_prompt or use_dual_tracks_prompt:+ sentence_ids = self._build_audio_prompt_ids(+ audio_prompt,+ audio_prompt2,+ prompt_start_time,+ prompt_end_time,+ use_dual_tracks_prompt,+ )+ head_id = self.mmtokenizer.tokenize(prompt_texts[0]) + sentence_ids+ else:+ head_id = self.mmtokenizer.tokenize(prompt_texts[0])+ prompt_ids = (+ head_id+ + start_of_segment+ + self.mmtokenizer.tokenize(section_text)+ + [self.mmtokenizer.soa]+ + self.codectool.sep_ids+ )+ else:+ prompt_ids = (+ end_of_segment+ + start_of_segment+ + self.mmtokenizer.tokenize(section_text)+ + [self.mmtokenizer.soa]+ + self.codectool.sep_ids+ )++ prompt_ids = torch.as_tensor(prompt_ids).unsqueeze(0).to(self.device)+ input_ids = torch.cat([raw_output, prompt_ids], dim=1) if i > 1 else prompt_ids+ max_context = 16384 - max_new_tokens - 1+ if input_ids.shape[-1] > max_context:+ input_ids = input_ids[:, -max_context:]++ with torch.no_grad():+ output_seq = self.model_stage1.generate(+ input_ids=input_ids,+ max_new_tokens=max_new_tokens,+ min_new_tokens=100,+ do_sample=True,+ top_p=top_p,+ temperature=temperature,+ repetition_penalty=repetition_penalty,+ eos_token_id=self.mmtokenizer.eoa,+ pad_token_id=self.mmtokenizer.eoa,+ logits_processor=LogitsProcessorList(+ [+ BlockTokenRangeProcessor(0, 32002),+ BlockTokenRangeProcessor(32016, 32017),+ ]+ ),+ guidance_scale=guidance_scale,+ callback=hf_callback,+ )++ if output_seq[0][-1].item() != self.mmtokenizer.eoa:+ tensor_eoa = torch.as_tensor([[self.mmtokenizer.eoa]]).to(self.device)+ output_seq = torch.cat((output_seq, tensor_eoa), dim=1)++ if i > 1:+ raw_output = torch.cat([raw_output, prompt_ids, output_seq[:, input_ids.shape[-1] :]], dim=1)+ else:+ raw_output = output_seq++ if raw_output is None:+ return None++ ids = raw_output[0].cpu().numpy()+ soa_idx = np.where(ids == self.mmtokenizer.soa)[0].tolist()+ eoa_idx = np.where(ids == self.mmtokenizer.eoa)[0].tolist()+ if len(soa_idx) != len(eoa_idx):+ raise ValueError(+ f"Invalid pairs of soa and eoa. Num of soa: {len(soa_idx)}, Num of eoa: {len(eoa_idx)}"+ )++ vocals = []+ instrumentals = []+ range_begin = 1 if use_audio_prompt or use_dual_tracks_prompt else 0+ for idx in range(range_begin, len(soa_idx)):+ codec_ids = ids[soa_idx[idx] + 1 : eoa_idx[idx]]+ if len(codec_ids) == 0:+ continue+ if codec_ids[0] == self.codectool.sep_ids[0]:+ codec_ids = codec_ids[1:]+ codec_ids = codec_ids[: 2 * (codec_ids.shape[0] // 2)]+ vocals_ids = self.codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[0])+ vocals.append(vocals_ids)+ instrumentals_ids = self.codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[1])+ instrumentals.append(instrumentals_ids)++ if not vocals or not instrumentals:+ return None++ vocals = np.concatenate(vocals, axis=1)+ instrumentals = np.concatenate(instrumentals, axis=1)+ return [vocals, instrumentals]++ def _stage2_generate(self, prompt, batch_size: int, segment_duration: int, callback=None):+ codec_ids = self.codectool.unflatten(prompt, n_quantizer=1)+ codec_ids = self.codectool.offset_tok_ids(+ codec_ids,+ global_offset=self.codectool.global_offset,+ codebook_size=self.codectool.codebook_size,+ num_codebooks=self.codectool.num_codebooks,+ ).astype(np.int32)++ if batch_size > 1:+ codec_list = []+ for i in range(batch_size):+ idx_begin = i * segment_duration * self.codec_fps+ idx_end = (i + 1) * segment_duration * self.codec_fps+ codec_list.append(codec_ids[:, idx_begin:idx_end])++ codec_ids = np.concatenate(codec_list, axis=0)+ prompt_ids = np.concatenate(+ [+ np.tile([self.mmtokenizer.soa, self.mmtokenizer.stage_1], (batch_size, 1)),+ codec_ids,+ np.tile([self.mmtokenizer.stage_2], (batch_size, 1)),+ ],+ axis=1,+ )+ else:+ prompt_ids = np.concatenate(+ [+ np.array([self.mmtokenizer.soa, self.mmtokenizer.stage_1]),+ codec_ids.flatten(),+ np.array([self.mmtokenizer.stage_2]),+ ]+ ).astype(np.int32)+ prompt_ids = prompt_ids[np.newaxis, ...]++ codec_ids = torch.as_tensor(codec_ids).to(self.device)+ prompt_ids = torch.as_tensor(prompt_ids).to(self.device)+ len_prompt = prompt_ids.shape[-1]++ block_list = LogitsProcessorList(+ [+ BlockTokenRangeProcessor(0, 46358),+ BlockTokenRangeProcessor(53526, self.mmtokenizer.vocab_size),+ ]+ )++ max_tokens = codec_ids.shape[1] * 8+ i = 0+ real_max_length = codec_ids.shape[1] * 8 + prompt_ids.shape[1]+ session_cache = {"real_max_length": real_max_length}++ for frames_idx in range(codec_ids.shape[1]):+ if i % 96 == 0 and callback is not None:+ callback(+ step_idx=i,+ override_num_inference_steps=real_max_length,+ pass_no=2,+ denoising_extra="Stage 2",+ )+ self._check_abort()++ cb0 = codec_ids[:, frames_idx : frames_idx + 1]+ prompt_ids = torch.cat([prompt_ids, cb0], dim=1)+ input_ids = prompt_ids++ with torch.no_grad():+ stage2_output = self.model_stage2.generate(+ input_ids=input_ids,+ min_new_tokens=7,+ max_new_tokens=7,+ eos_token_id=self.mmtokenizer.eoa,+ pad_token_id=self.mmtokenizer.eoa,+ logits_processor=block_list,+ session_cache=session_cache,+ )+ if stage2_output.shape[1] - prompt_ids.shape[1] != 7:+ raise ValueError(+ f"Stage2 output new tokens={stage2_output.shape[1] - prompt_ids.shape[1]}"+ )+ prompt_ids = stage2_output+ i += 8++ del session_cache++ if batch_size > 1:+ output = prompt_ids.cpu().numpy()[:, len_prompt:]+ output_list = [output[i] for i in range(batch_size)]+ output = np.concatenate(output_list, axis=0)+ else:+ output = prompt_ids[0].cpu().numpy()[len_prompt:]++ return output++ def _stage2_inference(+ self,+ stage1_output_set,+ batch_size: int,+ segment_duration: int,+ callback=None,+ set_header_text=None,+ ):+ stage2_result = []+ for i in tqdm(range(len(stage1_output_set))):+ self._check_abort()+ prefix = "Stage 2.1: Sampling Vocal track" if i == 0 else "Stage 2.2: Sampling Instrumental track"+ if set_header_text is not None:+ set_header_text(prefix)++ prompt = stage1_output_set[i].astype(np.int32)+ output_duration = prompt.shape[-1] // self.codec_fps // segment_duration * segment_duration+ num_batch = output_duration // segment_duration+ any_trail = output_duration * self.codec_fps != prompt.shape[-1]++ if num_batch <= batch_size:+ if set_header_text is not None:+ if any_trail:+ set_header_text(prefix + ", segment 1 of 2")+ else:+ set_header_text(prefix)+ output = self._stage2_generate(+ prompt[:, : output_duration * self.codec_fps],+ batch_size=num_batch,+ segment_duration=segment_duration,+ callback=callback,+ )+ else:+ segments = []+ num_segments = (num_batch // batch_size) + (1 if num_batch % batch_size != 0 else 0)+ max_segments = num_segments + 1 if any_trail else num_segments+ for seg in range(num_segments):+ if set_header_text is not None:+ set_header_text(prefix + f", segment {seg + 1} of {max_segments}")+ start_idx = seg * batch_size * segment_duration * self.codec_fps+ end_idx = min((seg + 1) * batch_size * segment_duration * self.codec_fps, output_duration * self.codec_fps)+ current_batch_size = (+ batch_size if seg != num_segments - 1 or num_batch % batch_size == 0 else num_batch % batch_size+ )+ segment = self._stage2_generate(+ prompt[:, start_idx:end_idx],+ batch_size=current_batch_size,+ segment_duration=segment_duration,+ callback=callback,+ )+ segments.append(segment)+ output = np.concatenate(segments, axis=0)++ if any_trail:+ if set_header_text is not None:+ set_header_text(prefix + f", segment {max_segments} of {max_segments}")+ ending = self._stage2_generate(+ prompt[:, output_duration * self.codec_fps :],+ batch_size=1,+ segment_duration=segment_duration,+ callback=callback,+ )+ output = np.concatenate([output, ending], axis=0)++ output = self.codectool_stage2.ids2npy(output)+ fixed_output = output.copy()+ for row_idx, line in enumerate(output):+ for col_idx, element in enumerate(line):+ if element < 0 or element > 1023:+ values, counts = np.unique(line, return_counts=True)+ fixed_output[row_idx, col_idx] = values[np.argmax(counts)]++ stage2_result.append(fixed_output)+ return stage2_result++ def _decode_track(self, codec_result: np.ndarray) -> torch.Tensor:+ with torch.no_grad():+ decoded = self.codec_model.decode(+ torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long)+ .unsqueeze(0)+ .permute(1, 0, 2)+ .to(self.device)+ )+ decoded = decoded.cpu().squeeze(0)+ return decoded++ def _vocoder_decode(self, decoder, codec_result: np.ndarray) -> torch.Tensor:+ compressed = torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long).unsqueeze(1)+ embeds = self.codec_model.get_embed(compressed.to(self.device))+ if not torch.is_tensor(embeds):+ embeds = torch.tensor(embeds)+ embeds = embeds.to(self.device)+ with torch.no_grad():+ out = decoder(embeds)+ return out.detach().cpu()++ def _replace_low_freq_with_energy_matched(+ self, wave_a: torch.Tensor, sr_a: int, wave_b: torch.Tensor, sr_b: int, cutoff_freq: float = 5500.0+ ) -> torch.Tensor:+ wave_a = wave_a.float()+ wave_b = wave_b.float()+ if sr_a != sr_b:+ resampler = Resample(orig_freq=sr_a, new_freq=sr_b)+ wave_a = resampler(wave_a)++ wave_a_low = taF.lowpass_biquad(wave_a, sample_rate=sr_b, cutoff_freq=cutoff_freq)+ wave_b_low = taF.lowpass_biquad(wave_b, sample_rate=sr_b, cutoff_freq=cutoff_freq)++ a_rms = wave_a_low.pow(2).mean().sqrt().item() + 1e-10+ b_rms = wave_b_low.pow(2).mean().sqrt().item() + 1e-10++ scale_factor = b_rms / a_rms+ wave_a_low_matched = wave_a_low * scale_factor++ wave_b_high = taF.highpass_biquad(wave_b, sample_rate=sr_b, cutoff_freq=cutoff_freq)++ min_length = min(wave_a_low_matched.size(1), wave_b_high.size(1))+ wave_a_low_matched = wave_a_low_matched[:, :min_length]+ wave_b_high = wave_b_high[:, :min_length]++ return wave_a_low_matched + wave_b_high++ def generate(+ self,+ input_prompt: str,+ model_mode: Optional[str],+ audio_guide: Optional[str],+ *,+ alt_prompt: Optional[str] = None,+ audio_guide2: Optional[str] = None,+ audio_prompt_type: str = "",+ temperature: float = 1.0,+ yue_max_new_tokens: Optional[int] = None,+ yue_run_n_segments: Optional[int] = None,+ yue_stage2_batch_size: Optional[int] = None,+ yue_segment_duration: Optional[int] = None,+ yue_prompt_start_time: Optional[float] = None,+ yue_prompt_end_time: Optional[float] = None,+ seed: int = -1,+ callback=None,+ set_header_text=None,+ **kwargs,+ ):+ self._interrupt = False+ lyrics_text = _read_text_or_file(input_prompt, "Lyrics prompt")+ if not lyrics_text.strip():+ raise ValueError("Lyrics prompt cannot be empty for Yue generation.")++ genres = _read_text_or_file(alt_prompt, "Genres prompt")+ if not genres.strip():+ raise ValueError("Genres prompt cannot be empty for Yue generation.")++ audio_prompt_type = audio_prompt_type or ""+ use_dual_tracks_prompt = "A" in audio_prompt_type and "B" in audio_prompt_type and audio_guide and audio_guide2+ use_audio_prompt = "A" in audio_prompt_type and not use_dual_tracks_prompt and audio_guide++ max_new_tokens = self.max_new_tokens if yue_max_new_tokens is None else int(yue_max_new_tokens)+ run_n_segments = self.run_n_segments if yue_run_n_segments is None else int(yue_run_n_segments)+ stage2_batch_size = (+ self.stage2_batch_size if yue_stage2_batch_size is None else int(yue_stage2_batch_size)+ )+ segment_duration = (+ self.segment_duration if yue_segment_duration is None else int(yue_segment_duration)+ )+ prompt_start_time = (+ self.prompt_start_time if yue_prompt_start_time is None else float(yue_prompt_start_time)+ )+ prompt_end_time = (+ self.prompt_end_time if yue_prompt_end_time is None else float(yue_prompt_end_time)+ )++ if seed is None or seed < 0:+ seed = random.randint(0, 999999999)+ _seed_everything(seed)++ stage1_output_set = self._stage1_inference(+ genres,+ lyrics_text,+ run_n_segments,+ max_new_tokens,+ float(temperature),+ use_audio_prompt,+ use_dual_tracks_prompt,+ audio_guide,+ audio_guide2,+ prompt_start_time,+ prompt_end_time,+ callback=callback,+ set_header_text=set_header_text,+ )+ if stage1_output_set is None:+ return None++ stage2_result = self._stage2_inference(+ stage1_output_set,+ batch_size=stage2_batch_size,+ segment_duration=segment_duration,+ callback=callback,+ set_header_text=set_header_text,+ )+ if stage2_result is None or len(stage2_result) < 2:+ return None++ vocal_codes, inst_codes = stage2_result[0], stage2_result[1]+ vocal_16k = self._decode_track(vocal_codes)+ inst_16k = self._decode_track(inst_codes)+ min_len = min(vocal_16k.shape[-1], inst_16k.shape[-1])+ mix_16k = vocal_16k[:, :min_len] + inst_16k[:, :min_len]++ vocal_hi = self._vocoder_decode(self.vocoder_vocal, vocal_codes)+ inst_hi = self._vocoder_decode(self.vocoder_inst, inst_codes)+ min_len_hi = min(vocal_hi.shape[-1], inst_hi.shape[-1])+ mix_hi = vocal_hi[:, :min_len_hi] + inst_hi[:, :min_len_hi]++ final_audio = self._replace_low_freq_with_energy_matched(+ mix_16k, 16000, mix_hi, 44100+ )+ final_audio = final_audio.clamp(-0.99, 0.99)+ return {"x": final_audio, "audio_sampling_rate": 44100}++ def release(self) -> None:+ for module in [self.model_stage1, self.model_stage2, self.codec_model]:+ if hasattr(module, "to"):+ module.to("cpu")+ for module in [self.vocoder_vocal, self.vocoder_inst]:+ if hasattr(module, "to"):+ module.to("cpu")diff --git a/models/_settings.json b/models/_settings.jsonindex b3f298d..94a7d20 100644--- a/models/_settings.json+++ b/models/_settings.json@@ -1,5 +1,6 @@{"prompt": "",+ "alt_prompt": "","multi_prompts_gen_type": 0,"image_mode":0,"image_prompt_type": "",@@ -24,6 +25,7 @@"resolution": "832x480","batch_size": 1,"video_length": 81,+ "duration_seconds": 0,"force_fps": "","num_inference_steps": 30,"seed": -1,diff --git a/models/chatterbox/chatterbox_handler.py b/models/chatterbox/chatterbox_handler.pydeleted file mode 100644index 821b21e..0000000--- a/models/chatterbox/chatterbox_handler.py+++ /dev/null@@ -1,161 +0,0 @@-import os-from shared.utils import files_locator as fl-import gradio as gr-try:- from .mtl_tts import SUPPORTED_LANGUAGES as _SUPPORTED_LANGUAGES-except ImportError: # pragma: no cover - fallback when package missing during startup- _SUPPORTED_LANGUAGES = {- "ar": "Arabic",- "da": "Danish",- "de": "German",- "el": "Greek",- "en": "English",- "es": "Spanish",- "fi": "Finnish",- "fr": "French",- "he": "Hebrew",- "hi": "Hindi",- "it": "Italian",- "ja": "Japanese",- "ko": "Korean",- "ms": "Malay",- "nl": "Dutch",- "no": "Norwegian",- "pl": "Polish",- "pt": "Portuguese",- "ru": "Russian",- "sv": "Swedish",- "sw": "Swahili",- "tr": "Turkish",- "zh": "Chinese",- }--LANGUAGE_CHOICES = [- (f"{name} ({code})", code) for code, name in sorted(_SUPPORTED_LANGUAGES.items(), key=lambda item: item[1])-]---class family_handler:- @staticmethod- def query_supported_types():- return ["chatterbox"]-- @staticmethod- def query_family_maps():- return {}, {}-- @staticmethod- def query_model_family():- return "tts"-- @staticmethod- def query_family_infos():- # The numeric weight controls ordering in the family dropdown.- return {"tts": (200, "TTS")}-- @staticmethod- def register_lora_cli_args(parser):- parser.add_argument(- "--lora-dir-tts",- type=str,- default=os.path.join("loras", "tts"),- help="Path to a directory that contains TTS settings"- )-- @staticmethod- def get_lora_dir(base_model_type, args):- return args.lora_dir_tts-- @staticmethod- def query_model_def(base_model_type, model_def):- extra_model_def = {- "audio_only": True,- "image_outputs": False,- "sliding_window": False,- "guidance_max_phases": 0,- "no_negative_prompt": True,- "image_prompt_types_allowed": "",- "profiles_dir": ["chatterbox"],- "audio_guide_label": "Voice to Replicate",- "model_modes": {- "choices": LANGUAGE_CHOICES,- "default": "en",- "label": "Language",- },- "any_audio_prompt": True,-- }- return extra_model_def-- @staticmethod- def query_model_files(computeList, base_model_type, model_def=None):- mandatory_files = [- "ve.safetensors",- "t3_mtl23ls_v2.safetensors",- "s3gen.pt",- "grapheme_mtl_merged_expanded_v1.json",- "conds.pt",- "Cangjie5_TC.json",- ]- return {- "repoId": "ResembleAI/chatterbox",- "sourceFolderList": [""],- "targetFolderList": ["chatterbox"],- "fileList": [mandatory_files],- }-- @staticmethod- def load_model(- model_filename,- model_type,- base_model_type,- model_def,- quantizeTransformer=False,- text_encoder_quantization=None,- dtype=None,- VAE_dtype=None,- mixed_precision_transformer=False,- save_quantized=False,- submodel_no_list=None,- text_encoder_filename = None,- ):- from .pipeline import ChatterboxPipeline-- ckpt_root = fl.get_download_location()- pipeline = ChatterboxPipeline(ckpt_root=ckpt_root, device ="cpu")- pipe = {"ve": pipeline.model.ve, "s3gen": pipeline.model.s3gen, "t3": pipeline.model.t3 , "conds": pipeline.model.conds}- return pipeline, pipe-- @staticmethod- def fix_settings(base_model_type, settings_version, model_def, ui_defaults):- defaults = {- "audio_prompt_type": "A",- "model_mode": "en",- }- for key, value in defaults.items():- ui_defaults.setdefault(key, value)-- @staticmethod- def update_default_settings(base_model_type, model_def, ui_defaults):- ui_defaults.update(- {- "audio_prompt_type": "A",- "model_mode": "en",- "repeat_generation": 1,- "video_length": 0,- "num_inference_steps": 0,- "negative_prompt": "",- "chatterbox_cfg_weight": 0.5,- "chatterbox_exaggeration": 0.5,- "chatterbox_temperature": 0.8,- "chatterbox_repetition_penalty": 2.0,- "chatterbox_min_p": 0.05,- "chatterbox_top_p": 1.0,- }- )--- @staticmethod- def validate_generative_prompt(base_model_type, model_def, inputs, one_prompt):- if len(one_prompt) > 300:- gr.Info("It is recommended to use a prompt that has less than 300 characters, otherwise you may get unexpected results.")diff --git a/plugins/wan2gp-about/plugin.py b/plugins/wan2gp-about/plugin.pyindex 782d4c8..0a4a487 100644--- a/plugins/wan2gp-about/plugin.py+++ b/plugins/wan2gp-about/plugin.py@@ -25,6 +25,7 @@ class AboutPlugin(WAN2GPPlugin):gr.Markdown("- <B>Alibaba Qwen Team</B> for their state of the art Qwen Image generators (https://github.com/QwenLM/Qwen-Image)")gr.Markdown("- <B>Lightricks</B> for their super fast LTX Video models (https://github.com/Lightricks/LTX-Video)")gr.Markdown("- <B>Resemble.AI</B> for the incredible ChatterBox (https://github.com/resemble-ai/chatterbox)")+ gr.Markdown("- <B>HeartMuLa Team</B> for the open music generation models (https://github.com/HeartMuLa/heartlib)")gr.Markdown("- <B>Remade_AI</B> : for their awesome Loras collection (https://huggingface.co/Remade-AI)")gr.Markdown("- <B>ByteDance</B> : for their great Wan and Flux extensions Lynx (https://github.com/bytedance/lynx), UMO (https://github.com/bytedance/UMO), USO (https://github.com/bytedance/USO) ")gr.Markdown("- <B>Hugging Face</B> for providing hosting for the models and developing must have open source libraries such as Tranformers, Diffusers, Accelerate and Gradio (https://huggingface.co/)")diff --git a/plugins/wan2gp-configuration/plugin.py b/plugins/wan2gp-configuration/plugin.pyindex 8f860f7..2c50ab5 100644--- a/plugins/wan2gp-configuration/plugin.py+++ b/plugins/wan2gp-configuration/plugin.py@@ -187,6 +187,12 @@ class ConfigTabPlugin(WAN2GPPlugin):value=mmaudio_persistence_default,label="MMAudio Model Persistence")+ self.rife_version_choice = gr.Dropdown(+ choices=[("RIFE HDv3 (default)", "v3"), ("RIFE v4.26 (latest)", "v4")],+ value=self.server_config.get("rife_version", "v3"),+ label="RIFE Temporal Upsampling Model",+ interactive=not self.args.lock_config+ )with gr.Tab("Outputs"):self.video_output_codec_choice = gr.Dropdown(choices=[("x265 CRF 28 (Balanced)", 'libx265_28'), ("x264 Level 8 (Balanced)", 'libx264_8'), ("x265 CRF 8 (High Quality)", 'libx265_8'), ("x264 Level 10 (High Quality)", 'libx264_10'), ("x264 Lossless", 'libx264_lossless')], value=self.server_config.get("video_output_codec", "libx264_8"), label="Video Codec")@@ -222,7 +228,7 @@ class ConfigTabPlugin(WAN2GPPlugin):self.text_encoder_quantization_choice, self.VAE_precision_choice, self.compile_choice,self.depth_anything_v2_variant_choice, self.vae_config_choice, self.boost_choice,self.profile_choice, self.preload_in_VRAM_choice, self.max_reserved_loras_choice,- self.enhancer_enabled_choice, self.enhancer_mode_choice, self.mmaudio_mode_choice, self.mmaudio_persistence_choice,+ self.enhancer_enabled_choice, self.enhancer_mode_choice, self.mmaudio_mode_choice, self.mmaudio_persistence_choice, self.rife_version_choice,self.video_output_codec_choice, self.image_output_codec_choice, self.audio_output_codec_choice,self.metadata_choice, self.embed_source_images_choice,self.video_save_path_choice, self.image_save_path_choice,@@ -271,7 +277,7 @@ class ConfigTabPlugin(WAN2GPPlugin):text_encoder_quantization_choice, VAE_precision_choice, compile_choice,depth_anything_v2_variant_choice, vae_config_choice, boost_choice,profile_choice, preload_in_VRAM_choice, max_reserved_loras_choice,- enhancer_enabled_choice, enhancer_mode_choice, mmaudio_mode_choice, mmaudio_persistence_choice,+ enhancer_enabled_choice, enhancer_mode_choice, mmaudio_mode_choice, mmaudio_persistence_choice, rife_version_choice,video_output_codec_choice, image_output_codec_choice, audio_output_codec_choice,metadata_choice, embed_source_images_choice,save_path_choice, image_save_path_choice,@@ -300,6 +306,7 @@ class ConfigTabPlugin(WAN2GPPlugin):"fit_canvas": fit_canvas_choice, "enhancer_enabled": enhancer_enabled_choice,"enhancer_mode": enhancer_mode_choice, "mmaudio_mode": mmaudio_mode_choice,"mmaudio_persistence": mmaudio_persistence_choice, "mmaudio_enabled": mmaudio_enabled_choice,+ "rife_version": rife_version_choice,"preload_in_VRAM": preload_in_VRAM_choice, "depth_anything_v2_variant": depth_anything_v2_variant_choice,"notification_sound_enabled": notification_sound_enabled_choice,"notification_sound_volume": notification_sound_volume_choice,@@ -336,7 +343,7 @@ class ConfigTabPlugin(WAN2GPPlugin):"attention_mode", "vae_config", "boost", "save_path", "image_save_path","metadata_type", "clear_file_list", "fit_canvas", "depth_anything_v2_variant","notification_sound_enabled", "notification_sound_volume", "mmaudio_mode",- "mmaudio_persistence", "mmaudio_enabled",+ "mmaudio_persistence", "mmaudio_enabled", "rife_version","max_frames_multiplier", "display_stats", "enable_4k_resolutions", "max_reserved_loras", "video_output_codec", "video_container","embed_source_images", "image_output_codec", "audio_output_codec", "checkpoints_paths","model_hierarchy_type", "UI_theme", "queue_color_scheme"@@ -359,6 +366,7 @@ class ConfigTabPlugin(WAN2GPPlugin):self.set_global("transformer_dtype_policy", new_server_config["transformer_dtype_policy"])self.set_global("transformer_types", new_server_config["transformer_types"])self.set_global("reload_needed", needs_reload)+ self.server_config.update(new_server_config)if "enhancer_enabled" in changes or "enhancer_mode" in changes:self.set_global("prompt_enhancer_image_caption_model", None)diff --git a/plugins/wan2gp-plugin-manager/plugin.py b/plugins/wan2gp-plugin-manager/plugin.pyindex 21ee49c..ee10a6e 100644--- a/plugins/wan2gp-plugin-manager/plugin.py+++ b/plugins/wan2gp-plugin-manager/plugin.py@@ -279,7 +279,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):with gr.Blocks() as plugin_blocks:with gr.Row(equal_height=False, variant='panel'):with gr.Column(scale=2, min_width=600):- gr.Markdown("### Installed Plugins (Drag to reorder tabs)")+ gr.Markdown("### Plugins Available Locally (Drag to reorder tabs)")self.plugins_html_display = gr.HTML()with gr.Row(elem_classes="save-buttons-container"):self.save_plugins_button = gr.Button("Save", variant="secondary", size="sm", scale=0, elem_classes="stylish-save-btn")diff --git a/postprocessing/rife/inference.py b/postprocessing/rife/inference.pyindex 491bba8..0fa92a4 100644--- a/postprocessing/rife/inference.py+++ b/postprocessing/rife/inference.py@@ -4,7 +4,8 @@ from torch.nn import functional as F# from .model.pytorch_msssim import ssim_matlabfrom .ssim import ssim_matlab-from .RIFE_HDv3 import Model+from .RIFE_HDv3 import Model as ModelV3+from .RIFE_V4 import Model as ModelV4def get_frame(frames, frame_no):if frame_no >= frames.shape[1]:@@ -33,8 +34,14 @@ def process_frames(model, device, frames, exp):_, h, w = lastframe.shapescale = 1fp16 = False+ supports_timestep = getattr(model, "supports_timestep", False)+ pad_mod = getattr(model, "pad_mod", 32)def make_inference(I0, I1, n):+ if n <= 0:+ return []+ if supports_timestep:+ return [model.inference(I0, I1, (i + 1) / (n + 1), scale) for i in range(n)]middle = model.inference(I0, I1, scale)if n == 1:return [middle]@@ -45,7 +52,7 @@ def process_frames(model, device, frames, exp):else:return [*first_half, *second_half]- tmp = max(32, int(32 / scale))+ tmp = max(pad_mod, int(pad_mod / scale))ph = ((h - 1) // tmp + 1) * tmppw = ((w - 1) // tmp + 1) * tmppadding = (0, pw - w, 0, ph - h)@@ -87,7 +94,10 @@ def process_frames(model, device, frames, exp):temp = frameI1 = frame.to(device, non_blocking=True).unsqueeze(0)I1 = pad_image(I1)- I1 = model.inference(I0, I1, scale)+ if supports_timestep:+ I1 = model.inference(I0, I1, 0.5, scale)+ else:+ I1 = model.inference(I0, I1, scale)I1_small = F.interpolate(I1, (32, 32), mode='bilinear', align_corners=False)ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])frame = I1[0][:, :h, :w]@@ -109,10 +119,13 @@ def process_frames(model, device, frames, exp):add_frame(output_frames, lastframe, h, w)return torch.cat( output_frames, dim=1)-def temporal_interpolation(model_path, frames, exp, device ="cuda"):+def temporal_interpolation(model_path, frames, exp, device ="cuda", rife_version="v3"):input_was_uint8 = frames.dtype == torch.uint8- model = Model()+ if rife_version == "v4":+ model = ModelV4()+ else:+ model = ModelV3()model.load_model(model_path, -1, device=device)model.eval()diff --git a/requirements.txt b/requirements.txtindex 73197f7..46888d2 100644--- a/requirements.txt+++ b/requirements.txt@@ -44,6 +44,8 @@ insightface @ https://github.com/deepbeepmeep/insightface/raw/refs/heads/master/insightface==0.7.3 ; sys_platform == "linux"facexlib==0.3.0taichi+vector_quantize_pytorch==1.27.19+# chumpy wheel hosted on GitHub to avoid sdist build isolation issuechumpy @ https://github.com/deepbeepmeep/chumpy/releases/download/v0.71/chumpy-0.71-py3-none-any.whlsmplfitter @ https://github.com/deepbeepmeep/smplfitter/releases/download/v0.2.10/smplfitter-0.2.10-py3-none-any.whl@@ -59,6 +61,7 @@ torchdiffeq>=0.2.5tensordict>=0.6.1mmgp==3.7.1peft==0.15.0+vector-quantize-pytorch==1.27.15matplotlibgguf==0.17.1diff --git a/shared/ffmpeg_setup.py b/shared/ffmpeg_setup.pyindex 5d11456..5655f61 100644--- a/shared/ffmpeg_setup.py+++ b/shared/ffmpeg_setup.py@@ -32,13 +32,21 @@ def download_ffmpeg(bin_directory: typing.Optional[typing.Union[str, Path]] = Nodef _ensure_bin_dir_on_path():current_path = os.environ.get("PATH", "")path_parts = current_path.split(os.pathsep) if current_path else []- dirs_to_add = []- # Add ffmpeg_bins and repo root to PATH++ def _normalize(p: str) -> str:+ p = os.path.normpath(p)+ return os.path.normcase(p) if os.name == "nt" else p++ prioritized = []+ seen = set()for d in [bin_dir, repo_root]:- if str(d) not in path_parts:- dirs_to_add.append(str(d))- if dirs_to_add:- os.environ["PATH"] = os.pathsep.join(dirs_to_add + path_parts)+ key = _normalize(str(d))+ if key not in seen:+ prioritized.append(str(d))+ seen.add(key)++ filtered = [p for p in path_parts if _normalize(p) not in seen]+ os.environ["PATH"] = os.pathsep.join(prioritized + filtered)def _ensure_library_path():if os.name == "nt":@@ -73,6 +81,10 @@ def download_ffmpeg(bin_directory: typing.Optional[typing.Union[str, Path]] = Nodef _binary_exists(name: str) -> bool:return _resolve_path(name) is not None+ def _local_binary_exists(name: str) -> bool:+ candidate = bin_dir / _candidate_name(name)+ return candidate.exists()+def _libs_present() -> bool:if os.name == "nt":return True@@ -93,8 +105,12 @@ def download_ffmpeg(bin_directory: typing.Optional[typing.Union[str, Path]] = Noif ffplay_path:os.environ["FFPLAY_BINARY"] = str(ffplay_path)- missing = [binary for binary in required_binaries if not _binary_exists(binary)]- libs_ok = _libs_present()+ if os.name == "nt":+ missing = [binary for binary in required_binaries if not _local_binary_exists(binary)]+ libs_ok = True+ else:+ missing = [binary for binary in required_binaries if not _binary_exists(binary)]+ libs_ok = _libs_present()if not missing and libs_ok:_set_env_vars()return@@ -218,9 +234,14 @@ def download_ffmpeg(bin_directory: typing.Optional[typing.Union[str, Path]] = Noprint(f"Failed to download FFmpeg binaries automatically: {exc}")return- if not all(_binary_exists(binary) for binary in required_binaries):- print("FFmpeg binaries are still missing after download; please install them manually.")- return+ if os.name == "nt":+ if not all(_local_binary_exists(binary) for binary in required_binaries):+ print("FFmpeg binaries are still missing after download; please install them manually.")+ return+ else:+ if not all(_binary_exists(binary) for binary in required_binaries):+ print("FFmpeg binaries are still missing after download; please install them manually.")+ return_ensure_bin_dir_on_path()_ensure_library_path()diff --git a/shared/utils/utils.py b/shared/utils/utils.pyindex 5e08ff9..5901108 100644--- a/shared/utils/utils.py+++ b/shared/utils/utils.py@@ -445,6 +445,7 @@ def fit_image_into_canvas(ref_img, image_size, canvas_tf_bg =127.5, device ="cpudef prepare_video_guide_and_mask( video_guides, video_masks, pre_video_guide, image_size, current_video_length = 81, latent_size = 4, any_mask = False, any_guide_padding = False, guide_inpaint_color = 127.5, keep_video_guide_frames = [], inject_frames = [], outpainting_dims = None, device ="cpu"):src_videos, src_masks = [], []inpaint_color_compressed = to_rgb_tensor(guide_inpaint_color, device=device, dtype=torch.float) / 127.5 - 1+ inpaint_color_compressed = inpaint_color_compressed.unsqueeze(1)prepend_count = pre_video_guide.shape[1] if pre_video_guide is not None else 0for guide_no, (cur_video_guide, cur_video_mask) in enumerate(zip(video_guides, video_masks)):src_video, src_mask = cur_video_guide, cur_video_maskdiff --git a/wgp.py b/wgp.pyindex 2ddb272..958fb00 100644--- a/wgp.py+++ b/wgp.py@@ -648,7 +648,7 @@ def validate_settings(state, model_type, single_prompt, inputs):gr.Info("You must enable a Control Video to use the Control Video Audio Track as an audio prompt")return ret()- if "B" in audio_prompt_type or "X" in audio_prompt_type:+ if ("B" in audio_prompt_type or "X" in audio_prompt_type) and not audio_only and not model_def.get("one_speaker_only", False):from models.wan.multitalk.multitalk import parse_speakers_locationsspeakers_bboxes, error = parse_speakers_locations(speakers_locations)if len(error) > 0:@@ -1679,7 +1679,7 @@ def update_generation_status(html_content):if(html_content):return gr.update(value=html_content)-family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.ltx2.ltx2_handler", "models.longcat.longcat_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.kandinsky5.kandinsky_handler", "models.z_image.z_image_handler", "models.chatterbox.chatterbox_handler"]+family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.ltx2.ltx2_handler", "models.longcat.longcat_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.kandinsky5.kandinsky_handler", "models.z_image.z_image_handler", "models.TTS.tts_handler"]def register_family_lora_args(parser):registered_families = set()@@ -2127,6 +2127,7 @@ if not Path(config_load_filename).is_file():"model_hierarchy_type": 1,"mmaudio_mode": 0,"mmaudio_persistence": 1,+ "rife_version": "v3",}with open(server_config_filename, "w", encoding="utf-8") as writer:@@ -2496,6 +2497,9 @@ def fix_settings(model_type, ui_defaults, min_settings_version = 0):image_prompt_type = image_prompt_type.replace("G","")ui_defaults["image_prompt_type"] = image_prompt_type+ if "alt_prompt" not in ui_defaults:+ ui_defaults["alt_prompt"] = ""+if "lset_name" in ui_defaults: del ui_defaults["lset_name"]audio_prompt_type = ui_defaults.get("audio_prompt_type", None)@@ -2719,6 +2723,7 @@ if not "embed_source_images" in server_config: server_config["embed_source_imageif not "enable_4k_resolutions" in server_config: server_config["enable_4k_resolutions"]= 0if not "max_reserved_loras" in server_config: server_config["max_reserved_loras"]= -1if not "image_output_codec" in server_config: server_config["image_output_codec"]= "jpeg_95"+if not "rife_version" in server_config: server_config["rife_version"] = "v3"preload_model_policy = server_config.get("preload_model_policy", [])@@ -2946,6 +2951,8 @@ def download_file(url,filename):from shared.utils.download import create_progress_hookurlretrieve(url,filename, create_progress_hook(filename))+RIFE_V4_FILENAME = "rife4.26.pkl"+RIFE_V3_FILENAME = "flownet.pkl"download_shared_done = Falsedef download_models(model_filename = None, model_type= None, file_type = 0, submodel_no = 1, force_path = None):def computeList(filename):@@ -2965,7 +2972,7 @@ def download_models(model_filename = None, model_type= None, file_type = 0, subm["config.json", "feature_extractor_config.json", "model.safetensors", "preprocessor_config.json", "special_tokens_map.json", "tokenizer_config.json", "vocab.json"],["config.json", "pytorch_model.bin", "preprocessor_config.json"],["model_bs_roformer_ep_317_sdr_12.9755.ckpt", "model_bs_roformer_ep_317_sdr_12.9755.yaml", "download_checks.json"],- ["pyannote_model_wespeaker-voxceleb-resnet34-LM.bin", "pytorch_model_segmentation-3.0.bin"], ["detface.pt"], [ "flownet.pkl" ] ]+ ["pyannote_model_wespeaker-voxceleb-resnet34-LM.bin", "pytorch_model_segmentation-3.0.bin"], ["detface.pt"], [ RIFE_V3_FILENAME if server_config.get("rife_version", "v3") == "v4" else RIFE_V4_FILENAME ] ]}process_files_def(**shared_def)@@ -3169,17 +3176,24 @@ def get_transformer_model(model, submodel_no = 1):else:raise Exception("no transformer found")-def init_pipe(pipe, kwargs, override_profile):+def compute_profile(override_profile):+ return override_profile if override_profile != -1 else default_profile++def init_pipe(pipe, kwargs, profile):preload =int(args.preload)if preload == 0:preload = server_config.get("preload_in_VRAM", 0)kwargs["extraModelsToQuantize"]= None- profile = override_profile if override_profile != -1 else default_profileif profile in (2, 4, 5):- budgets = { "transformer" : 100 if preload == 0 else preload, "text_encoder" : 100 if preload == 0 else preload, "*" : max(1000 if profile==5 else 3000 , preload) }+ default_transformer_budget = default_transformer2_budget= kwargs.get("budgets", 100)+ if isinstance(default_transformer_budget, dict):+ default_transformer_budget = default_transformer_budget.get("transformer", 100)+ default_transformer2_budget = default_transformer2_budget.get("transformer2", 100)++ budgets = { "transformer" : default_transformer_budget if preload == 0 else preload, "text_encoder" : 100 if preload == 0 else preload, "*" : max(1000 if profile==5 else 3000 , preload) }if "transformer2" in pipe:- budgets["transformer2"] = 100 if preload == 0 else preload+ budgets["transformer2"] = default_transformer2_budget if preload == 0 else preloadkwargs["budgets"] = budgetselif profile == 3:kwargs["budgets"] = { "*" : "70%" }@@ -3197,7 +3211,7 @@ def init_pipe(pipe, kwargs, override_profile):else:mmgp_profile = profile- return profile, mmgp_profile+ return mmgp_profiledef reset_prompt_enhancer():global prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer, enhancer_offloadobj@@ -3323,7 +3337,7 @@ def load_models(model_type, override_profile = -1, **model_kwargs):text_encoder_URLs= get_model_recursive_prop(model_type, "text_encoder_URLs", return_list= True)if text_encoder_URLs is not None:text_encoder_filename = get_model_filename(model_type=model_type, quantization= text_encoder_quantization, dtype_policy = transformer_dtype_policy, URLs=text_encoder_URLs)- if text_encoder_filename is not None:+ if text_encoder_filename is not None and len(text_encoder_filename):text_encoder_folder = model_def.get("text_encoder_folder", None)if text_encoder_filename is not None:download_models(text_encoder_filename, file_model_type, 2, -1, force_path =text_encoder_folder)@@ -3331,18 +3345,18 @@ def load_models(model_type, override_profile = -1, **model_kwargs):print(f"Loading Text Encoder '{text_encoder_filename}' ...")+ profile = compute_profile(override_profile)torch.set_default_device('cpu')wan_model, pipe = model_type_handler.load_model(local_model_file_list, model_type, base_model_type, model_def, quantizeTransformer = quantizeTransformer, text_encoder_quantization = text_encoder_quantization,- dtype = transformer_dtype, VAE_dtype = VAE_dtype, mixed_precision_transformer = mixed_precision_transformer, save_quantized = save_quantized, submodel_no_list = model_submodel_no_list, text_encoder_filename = text_encoder_filename, **model_kwargs )+ dtype = transformer_dtype, VAE_dtype = VAE_dtype, mixed_precision_transformer = mixed_precision_transformer, save_quantized = save_quantized, submodel_no_list = model_submodel_no_list, text_encoder_filename = text_encoder_filename, profile=profile, **model_kwargs )kwargs = {}if "pipe" in pipe:kwargs = pipepipe = kwargs.pop("pipe")if "coTenantsMap" not in kwargs: kwargs["coTenantsMap"] = {}-- profile, mmgp_profile = init_pipe(pipe, kwargs, override_profile)+ mmgp_profile = init_pipe(pipe, kwargs, profile)if server_config.get("enhancer_mode", 0) == 0:setup_prompt_enhancer(pipe, kwargs)loras_transformer = kwargs.pop("loras", [])@@ -3353,6 +3367,8 @@ def load_models(model_type, override_profile = -1, **model_kwargs):if len(compile) > 0 and hasattr(wan_model, "custom_compile"):wan_model.custom_compile(backend= "inductor", mode ="default")compile_modules = model_def.get("compile", compile) if len(compile) > 0 else ""+ if compile_modules == False:+ print("Pytorch compilation is not supported for this Model")# kwargs["pinnedMemory"] = "text_encoder"offloadobj = offload.profile(pipe, profile_no= mmgp_profile, compile = compile_modules, quantizeTransformer = False, loras = loras_transformer, perc_reserved_mem_max = perc_reserved_mem_max , vram_safety_coefficient = vram_safety_coefficient , convertWeightsFloatTo = transformer_dtype, **kwargs)if len(args.gpu) > 0:@@ -3436,7 +3452,7 @@ def build_callback(state, pipe, send_cmd, status, num_inference_steps, preview_mgen = get_gen_info(state)gen["num_inference_steps"] = num_inference_stepsstart_time = time.time()- def callback(step_idx = -1, latent = None, force_refresh = True, read_state = False, override_num_inference_steps = -1, pass_no = -1, preview_meta=preview_meta, denoising_extra =""):+ def callback(step_idx = -1, latent = None, force_refresh = True, read_state = False, override_num_inference_steps = -1, pass_no = -1, preview_meta=preview_meta, denoising_extra ="", progress_unit = None):in_pause = Falsewith gen_lock:process_status = gen.get("process_status", None)@@ -3501,6 +3517,8 @@ def build_callback(state, pipe, send_cmd, status, num_inference_steps, preview_mstatus_msg = merge_status_context(status, f"{phase} | {format_time(elapsed_time)}")if step_idx >= 0:progress_args = [(step_idx , num_inference_steps) , status_msg , num_inference_steps]+ if progress_unit:+ progress_args.append(progress_unit)else:progress_args = [0, status_msg]@@ -3983,6 +4001,12 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, audvideo_activated_loras_str = "<TABLE style='border:0px;padding:0px'>" + "".join(video_activated_loras) + "</TABLE>" if len(video_activated_loras) > 0 else ""values += misc_values + [video_prompt]labels += misc_labels + ["Text Prompt"]+ alt_prompt_def = model_def.get("alt_prompt", None)+ alt_prompt_label = alt_prompt_def.get("label") if isinstance(alt_prompt_def, dict) else None+ alt_prompt = html.escape(configs.get("alt_prompt", "")[:1024]).replace("\n", "<BR>")+ if alt_prompt_label and len(alt_prompt):+ values += [alt_prompt]+ labels += [alt_prompt_label]if len(enhanced_video_prompt):values += [enhanced_video_prompt]labels += ["Enhanced Text Prompt"]@@ -4616,6 +4640,12 @@ def perform_temporal_upsampling(sample, previous_last_frame, temporal_upsamplingoutput_fps = fpsif exp == 0:return sample, previous_last_frame, output_fps+ rife_version = server_config.get("rife_version", "v3")+ rife_model_path = None+ if rife_version == "v4":+ rife_model_path = fl.locate_file(RIFE_V4_FILENAME)+ else:+ rife_model_path = fl.locate_file(RIFE_V3_FILENAME)if previous_last_frame is not None and previous_last_frame.dtype != sample.dtype:if sample.dtype == torch.uint8:previous_last_frame = _video_tensor_to_uint8_chunk_inplace(previous_last_frame)@@ -4626,10 +4656,10 @@ def perform_temporal_upsampling(sample, previous_last_frame, temporal_upsamplingif previous_last_frame != None:sample = torch.cat([previous_last_frame, sample], dim=1)previous_last_frame = sample[:, -1:].clone()- sample = temporal_interpolation( fl.locate_file("flownet.pkl"), sample, exp, device=processing_device)+ sample = temporal_interpolation(rife_model_path, sample, exp, device=processing_device, rife_version=rife_version)sample = sample[:, 1:]else:- sample = temporal_interpolation( fl.locate_file("flownet.pkl"), sample, exp, device=processing_device)+ sample = temporal_interpolation(rife_model_path, sample, exp, device=processing_device, rife_version=rife_version)previous_last_frame = sample[:, -1:].clone()output_fps = output_fps * 2**exp@@ -4918,6 +4948,9 @@ def process_prompt_enhancer(model_def, prompt_enhancer, original_prompts, imageprompt_enhancer_instructions = model_def.get("image_prompt_enhancer_instructions" if is_image else "video_prompt_enhancer_instructions", None)text_encoder_max_tokens = model_def.get("image_prompt_enhancer_max_tokens" if is_image else "video_prompt_enhancer_max_tokens", 256)+ if not "I" in prompt_enhancer:+ prompt_enhancer_instructions = model_def.get("text_prompt_enhancer_instructions", prompt_enhancer_instructions)+ text_encoder_max_tokens = model_def.get("text_prompt_enhancer_max_tokens", text_encoder_max_tokens)from models.ltx_video.utils.prompt_enhance_utils import generate_cinematic_promptprompt_images = []@@ -4948,7 +4981,7 @@ def process_prompt_enhancer(model_def, prompt_enhancer, original_prompts, image)return prompts-def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, override_profile, progress=gr.Progress()):+def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, multi_prompts_gen_type, override_profile, progress=gr.Progress()):global enhancer_offloadobjprefix = "#!PROMPT!:"model_type = get_state_model_type(state)@@ -4967,12 +5000,17 @@ def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, overriif prompt.startswith(prefix):new_prompt = prompt[len(prefix):].strip()prompts_to_process.append(new_prompt)+ if multi_prompts_gen_type == 2:+ prompts_to_process = [new_prompt]+ breakskip_next_non_comment = Trueelse:if not prompt.startswith("#") and not skip_next_non_comment and len(prompt) > 0:prompts_to_process.append(prompt)skip_next_non_comment = False+ if multi_prompts_gen_type == 2:+ prompts_to_process= ["\n".join(prompts_to_process)]original_prompts = prompts_to_processnum_prompts = len(original_prompts)image_start = inputs["image_start"]@@ -5003,7 +5041,8 @@ def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, overriacquire_GPU_ressources(state, "prompt_enhancer", "Prompt Enhancer")if enhancer_offloadobj is None:- _, mmgp_profile = init_pipe(pipe, kwargs, override_profile)+ profile = compute_profile(override_profile)+ mmgp_profile = init_pipe(pipe, kwargs, profile)setup_prompt_enhancer(pipe, kwargs)enhancer_offloadobj = offload.profile(pipe, profile_no= mmgp_profile, **kwargs)@@ -5027,7 +5066,10 @@ def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, overrirelease_GPU_ressources(state, "prompt_enhancer")raise gr.Error(e)if enhanced_prompt is not None:- enhanced_prompt = enhanced_prompt[0].replace("\n", "").replace("\r", "")+ if multi_prompts_gen_type ==2:+ enhanced_prompt = enhanced_prompt[0]+ else:+ enhanced_prompt = enhanced_prompt[0].replace("\n", " ").replace("\r", "")enhanced_prompts.append(prefix + " " + one_prompt)enhanced_prompts.append(enhanced_prompt)@@ -5137,7 +5179,15 @@ def write_wav_file(file_path, audio_data, sampling_rate):import numpy as npimport soundfile as sf- audio = np.asarray(audio_data)+ if torch.is_tensor(audio_data):+ audio_data = audio_data.detach()+ if audio_data.is_cuda:+ audio_data = audio_data.cpu()+ if audio_data.dtype not in (torch.float32, torch.float64):+ audio_data = audio_data.float()+ audio = audio_data.numpy()+ else:+ audio = np.asarray(audio_data)if audio.ndim > 1 and audio.shape[0] == 1:audio = audio.squeeze(0)if audio.ndim == 2 and audio.shape[0] in (1, 2) and audio.shape[1] > audio.shape[0]:@@ -5219,9 +5269,11 @@ def generate_video(send_cmd,image_mode,prompt,+ alt_prompt,negative_prompt,resolution,video_length,+ duration_seconds,batch_size,seed,force_fps,@@ -5337,6 +5389,7 @@ def generate_video(model_def = get_model_def(model_type)is_image = image_mode > 0audio_only = model_def.get("audio_only", False)+ duration_def = model_def.get("duration_slider", None)set_video_prompt_type = model_def.get("set_video_prompt_type", None)if set_video_prompt_type is not None:@@ -6065,8 +6118,12 @@ def generate_video(prefix_video_for_model = prefix_videoif prefix_video is not None and prefix_video.dtype == torch.uint8:prefix_video_for_model = prefix_video.float().div_(127.5).sub_(1.0)+ extra_generate_kwargs = {}+ if audio_only and duration_def is not None:+ extra_generate_kwargs["duration_seconds"] = duration_secondssamples = wan_model.generate(input_prompt = prompt,+ alt_prompt = alt_prompt,image_start = image_start_tensor,image_end = image_end_tensor,input_frames = src_video,@@ -6155,6 +6212,7 @@ def generate_video(temperature=temperature,window_start_frame_no = window_start_frame,input_video_strength = input_video_strength,+ **extra_generate_kwargs,)except Exception as e:if len(control_audio_tracks) > 0 or len(source_audio_tracks) > 0:@@ -6410,7 +6468,7 @@ def generate_video(configs = prepare_inputs_dict("metadata", inputs, model_type)if sliding_window: configs["window_no"] = window_noconfigs["prompt"] = "\n".join(original_prompts)- if prompt_enhancer_image_caption_model != None and prompt_enhancer !=None and len(prompt_enhancer)>0:+ if prompt_enhancer_image_caption_model != None and prompt_enhancer !=None and len(prompt_enhancer)>0 and server_config.get("enhancer_mode", 0) != 1:configs["enhanced_prompt"] = "\n".join(prompts)configs["generation_time"] = round(end_time-start_time)# if sample_is_image: configs["is_image"] = True@@ -7401,6 +7459,8 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = Nonepop=[]if not model_def.get("audio_only", False):pop += [ "pace", "exaggeration", "temperature"]+ if model_def.get("duration_slider", None) is None:+ pop += ["duration_seconds"]if "force_fps" in inputs and len(inputs["force_fps"])== 0:pop += ["force_fps"]@@ -8043,9 +8103,11 @@ def save_inputs(lset_name,image_mode,prompt,+ alt_prompt,negative_prompt,resolution,video_length,+ duration_seconds,batch_size,seed,force_fps,@@ -8320,7 +8382,19 @@ def refresh_remove_background_sound(state, audio_prompt_type, remove_background_def refresh_audio_prompt_type_sources(state, audio_prompt_type, audio_prompt_type_sources):audio_prompt_type = del_in_sequence(audio_prompt_type, "XCPABK")audio_prompt_type = add_to_sequence(audio_prompt_type, audio_prompt_type_sources)- return audio_prompt_type, gr.update(visible = "A" in audio_prompt_type), gr.update(visible = "B" in audio_prompt_type), gr.update(visible = ("B" in audio_prompt_type or "X" in audio_prompt_type)), gr.update(visible= any_letters(audio_prompt_type, "ABXK")), gr.update(visible= any_letters(audio_prompt_type,"AB"))+ model_type = get_state_model_type(state)+ model_def = get_model_def(model_type)+ audio_only = model_def.get("audio_only", False) if model_def is not None else False+ speakers_visible = ("B" in audio_prompt_type or "X" in audio_prompt_type) and not audio_only+ remove_background_visible = any_letters(audio_prompt_type, "ABXK")+ return (+ audio_prompt_type,+ gr.update(visible="A" in audio_prompt_type),+ gr.update(visible="B" in audio_prompt_type),+ gr.update(visible=speakers_visible),+ gr.update(visible=remove_background_visible),+ gr.update(visible=any_letters(audio_prompt_type, "AB")),+ )def refresh_image_prompt_type_radio(state, image_prompt_type, image_prompt_type_radio):image_prompt_type = del_in_sequence(image_prompt_type, "VLTS")@@ -9330,7 +9404,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonelse:custom_guide = gr.File(value= ui_defaults.get("custom_guide", None), type="filepath", label= custom_guide_def.get("label","Custom Guide"), height=41, visible= True, file_types = custom_guide_def.get("file_types", ["*.*"]) )remove_background_sound = gr.Checkbox(label= "Remove Background Music" if audio_only else "Video Motion ignores Background Music (to get a better LipSync)", value="V" in audio_prompt_type_value, visible = any_audio_prompt and any_letters(audio_prompt_type_value, "ABXK") and not image_outputs)- with gr.Row(visible = any_audio_prompt and ("B" in audio_prompt_type_value or "X" in audio_prompt_type_value) and not image_outputs ) as speakers_locations_row:+ with gr.Row(visible = any_audio_prompt and any_multi_speakers and ("B" in audio_prompt_type_value or "X" in audio_prompt_type_value) and not image_outputs ) as speakers_locations_row:speakers_locations = gr.Text( ui_get("speakers_locations"), label="Speakers Locations separated by a Space. Each Location = Left:Right or a BBox Left:Top:Right:Bottom", visible= True)advanced_prompt = advanced_ui@@ -9382,9 +9456,43 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonlabel="Enhance Prompt using a LLM", scale = 5,visible= True, show_label= not on_demand_prompt_enhancer,)- with gr.Row(visible=audio_only) as chatter_row:+ alt_prompt_def = model_def.get("alt_prompt", None)+ alt_prompt_label = None+ alt_prompt_placeholder = ""+ alt_prompt_lines = 2+ if isinstance(alt_prompt_def, dict):+ alt_prompt_label = alt_prompt_def.get("label")+ alt_prompt_placeholder = alt_prompt_def.get("placeholder", "")+ alt_prompt_lines = alt_prompt_def.get("lines", 2)+ if alt_prompt_label:+ with gr.Row(visible=True) as alt_prompt_row:+ alt_prompt = gr.Textbox(+ label=alt_prompt_label,+ value=ui_get("alt_prompt", ""),+ lines=alt_prompt_lines,+ placeholder=alt_prompt_placeholder,+ )+ else:+ with gr.Row(visible=False) as alt_prompt_row:+ alt_prompt = gr.Textbox(value=ui_get("alt_prompt", ""), visible=False)+ chatterbox_controls = model_def.get("chatterbox_controls", False)+ with gr.Row(visible=audio_only and chatterbox_controls) as chatter_row:exaggeration = gr.Slider( 0.25, 2.0, value=ui_get("exaggeration"), step=0.01, label="Emotion Exaggeration (0.5 = Neutral)", show_reset_button= False)pace = gr.Slider( 0.2, 1, value=ui_get("pace"), step=0.01, label="Pace", show_reset_button= False)+ duration_def = model_def.get("duration_slider", None)+ if duration_def is None:+ duration_seconds = gr.Number(value=0, visible=False)+ else:+ duration_default = duration_def.get("default", 120)+ with gr.Row(visible=audio_only) as duration_row:+ duration_seconds = gr.Slider(+ duration_def.get("min", 30),+ duration_def.get("max", 240),+ value=ui_get("duration_seconds", duration_default),+ step=duration_def.get("increment", 0.1),+ label=duration_def.get("label", "Duration"),+ show_reset_button=False,+ )with gr.Row(visible=not audio_only) as resolution_row:fit_canvas = server_config.get("fit_canvas", 0)@@ -9968,7 +10076,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonsingle_hidden_trigger_btn = gr.Button("trigger_countdown", visible=False, elem_id="trigger_info_single_btn")extra_inputs = prompt_vars + [wizard_prompt, wizard_variables_var, wizard_prompt_activated_var, video_prompt_column, image_prompt_column, image_prompt_type_group, image_prompt_type_radio, image_prompt_type_endcheckbox,- prompt_column_advanced, prompt_column_wizard_vars, prompt_column_wizard, lset_name, save_lset_prompt_drop, advanced_row, speed_tab, audio_tab, mmaudio_col, quality_tab,+ prompt_column_advanced, prompt_column_wizard_vars, prompt_column_wizard, alt_prompt_row, lset_name, save_lset_prompt_drop, advanced_row, speed_tab, audio_tab, mmaudio_col, quality_tab,sliding_window_tab, misc_tab, prompt_enhancer_row, inference_steps_row, skip_layer_guidance_row, audio_guide_row, custom_guide_row, RIFLEx_setting_col,video_prompt_type_video_guide, video_prompt_type_video_guide_alt, video_prompt_type_video_mask, video_prompt_type_image_refs, video_prompt_type_video_custom_dropbox, video_prompt_type_video_custom_checkbox,apg_col, audio_prompt_type_sources, audio_prompt_type_remux, audio_prompt_type_remux_row, force_fps_col,@@ -10112,7 +10220,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non).then(fn=save_inputs,inputs =[target_state] + gen_inputs,outputs= None- ).then( fn=enhance_prompt, inputs =[state, prompt, prompt_enhancer, multi_images_gen_type, override_profile ] , outputs= [prompt, wizard_prompt])+ ).then( fn=enhance_prompt, inputs =[state, prompt, prompt_enhancer, multi_images_gen_type, multi_prompts_gen_type, override_profile ] , outputs= [prompt, wizard_prompt])# save_form_trigger.change(fn=validate_wizard_prompt,def set_save_form_event(trigger):