- for p in group["params"]:
- state = self.state[p]
- ...
-
- you can do:
-
- with self.batched_params(group["params"]) as batches:
- for p, state, p_names in batches:
- ...
-
-
- Args:
- group: a parameter group, which is a list of parameters; should be
- one of self.param_groups.
- group_params_names: name for each parameter in group,
- which is List[str].
- """
- batches = defaultdict(list) # `batches` maps from tuple (dtype_as_str,*shape) to list of nn.Parameter
- batches_names = defaultdict(list) # `batches` maps from tuple (dtype_as_str,*shape) to list of str
-
- assert len(param_group) == len(group_params_names)
- for p, named_p in zip(param_group, group_params_names):
- key = (str(p.dtype), *p.shape)
- batches[key].append(p)
- batches_names[key].append(named_p)
-
- batches_names_keys = list(batches_names.keys())
- sorted_idx = sorted(range(len(batches_names)), key=lambda i: batches_names_keys[i])
- batches_names = [batches_names[batches_names_keys[idx]] for idx in sorted_idx]
- batches = [batches[batches_names_keys[idx]] for idx in sorted_idx]
-
- stacked_params_dict = dict()
-
- # turn batches into a list, in deterministic order.
- # tuples will contain tuples of (stacked_param, state, stacked_params_names),
- # one for each batch in `batches`.
- tuples = []
-
- for batch, batch_names in zip(batches, batches_names):
- p = batch[0]
- # we arbitrarily store the state in the
- # state corresponding to the 1st parameter in the
- # group. class Optimizer will take care of saving/loading state.
- state = self.state[p]
- p_stacked = torch.stack(batch)
- grad = torch.stack([torch.zeros_like(p) if p.grad is None else p.grad for p in batch])
- p_stacked.grad = grad
- stacked_params_dict[key] = p_stacked
- tuples.append((p_stacked, state, batch_names))
-
- yield tuples # <-- calling code will do the actual optimization here!
-
- for (stacked_params, _state, _names), batch in zip(tuples, batches):
- for i, p in enumerate(batch): # batch is list of Parameter
- p.copy_(stacked_params[i])
-
-
-class ScaledAdam(BatchedOptimizer):
- """
- Implements 'Scaled Adam', a variant of Adam where we scale each parameter's update
- proportional to the norm of that parameter; and also learn the scale of the parameter,
- in log space, subject to upper and lower limits (as if we had factored each parameter as
- param = underlying_param * log_scale.exp())
-
-
- Args:
- params: The parameters or param_groups to optimize (like other Optimizer subclasses)
- lr: The learning rate. We will typically use a learning rate schedule that starts
- at 0.03 and decreases over time, i.e. much higher than other common
- optimizers.
- clipping_scale: (e.g. 2.0)
- A scale for gradient-clipping: if specified, the normalized gradients
- over the whole model will be clipped to have 2-norm equal to
- `clipping_scale` times the median 2-norm over the most recent period
- of `clipping_update_period` minibatches. By "normalized gradients",
- we mean after multiplying by the rms parameter value for this tensor
- [for non-scalars]; this is appropriate because our update is scaled
- by this quantity.
- betas: beta1,beta2 are momentum constants for regular momentum, and moving sum-sq grad.
- Must satisfy 0 < beta <= beta2 < 1.
- scalar_lr_scale: A scaling factor on the learning rate, that we use to update the
- scale of each parameter tensor and scalar parameters of the mode..
- If each parameter were decomposed
- as p * p_scale.exp(), where (p**2).mean().sqrt() == 1.0, scalar_lr_scale
- would be a the scaling factor on the learning rate of p_scale.
- eps: A general-purpose epsilon to prevent division by zero
- param_min_rms: Minimum root-mean-square value of parameter tensor, for purposes of
- learning the scale on the parameters (we'll constrain the rms of each non-scalar
- parameter tensor to be >= this value)
- param_max_rms: Maximum root-mean-square value of parameter tensor, for purposes of
- learning the scale on the parameters (we'll constrain the rms of each non-scalar
- parameter tensor to be <= this value)
- scalar_max: Maximum absolute value for scalar parameters (applicable if your
- model has any parameters with numel() == 1).
- size_update_period: The periodicity, in steps, with which we update the size (scale)
- of the parameter tensor. This is provided to save a little time
- in the update.
- clipping_update_period: if clipping_scale is specified, this is the period
- """
-
- def __init__(
- self,
- params,
- lr=3e-02,
- clipping_scale=None,
- betas=(0.9, 0.98),
- scalar_lr_scale=0.1,
- eps=1.0e-08,
- param_min_rms=1.0e-05,
- param_max_rms=3.0,
- scalar_max=10.0,
- size_update_period=4,
- clipping_update_period=100,
- parameters_names=None,
- show_dominant_parameters=True,
- ):
- assert parameters_names is not None, (
- "Please prepare parameters_names,which is a List[List[str]]. Each List[str] is for a groupand each str is for a parameter"
- )
- defaults = dict(
- lr=lr,
- clipping_scale=clipping_scale,
- betas=betas,
- scalar_lr_scale=scalar_lr_scale,
- eps=eps,
- param_min_rms=param_min_rms,
- param_max_rms=param_max_rms,
- scalar_max=scalar_max,
- size_update_period=size_update_period,
- clipping_update_period=clipping_update_period,
- )
-
- super(ScaledAdam, self).__init__(params, defaults)
- assert len(self.param_groups) == len(parameters_names)
- self.parameters_names = parameters_names
- self.show_dominant_parameters = show_dominant_parameters
-
- def __setstate__(self, state):
- super(ScaledAdam, self).__setstate__(state)
-
- @torch.no_grad()
- def step(self, closure=None):
- """Performs a single optimization step.
-
- Arguments:
- closure (callable, optional): A closure that reevaluates the model
- and returns the loss.
- """
- loss = None
- if closure is not None:
- with torch.enable_grad():
- loss = closure()
-
- batch = True
-
- for group, group_params_names in zip(self.param_groups, self.parameters_names):
- with self.batched_params(group["params"], group_params_names) as batches:
- # batches is list of pairs (stacked_param, state). stacked_param is like
- # a regular parameter, and will have a .grad, but the 1st dim corresponds to
- # a stacking dim, it is not a real dim.
-
- if len(batches[0][1]) == 0: # if len(first state) == 0: not yet initialized
- clipping_scale = 1
- else:
- clipping_scale = self._get_clipping_scale(group, batches)
-
- for p, state, _ in batches:
- # Perform optimization step.
- # grad is not going to be None, we handled that when creating the batches.
- grad = p.grad
- if grad.is_sparse:
- raise RuntimeError("ScaledAdam optimizer does not support sparse gradients")
- # State initialization
- if len(state) == 0:
- self._init_state(group, p, state)
-
- self._step_one_batch(group, p, state, clipping_scale)
-
- return loss
-
- def _init_state(self, group: dict, p: Tensor, state: dict):
- """
- Initializes state dict for parameter 'p'. Assumes that dim 0 of tensor p
- is actually the batch dimension, corresponding to batched-together
- parameters of a given shape.
-
-
- Args:
- group: Dict to look up configuration values.
- p: The parameter that we are initializing the state for
- state: Dict from string to whatever state we are initializing
- """
- size_update_period = group["size_update_period"]
-
- state["step"] = 0
-
- kwargs = {"device": p.device, "dtype": p.dtype}
-
- # 'delta' implements conventional momentum. There are
- # several different kinds of update going on, so rather than
- # compute "exp_avg" like in Adam, we store and decay a
- # parameter-change "delta", which combines all forms of
- # update. this is equivalent to how it's done in Adam,
- # except for the first few steps.
- state["delta"] = torch.zeros_like(p, memory_format=torch.preserve_format)
-
- batch_size = p.shape[0]
- numel = p.numel() // batch_size
- numel = p.numel()
-
- if numel > 1:
- # "param_rms" just periodically records the scalar root-mean-square value of
- # the parameter tensor.
- # it has a shape like (batch_size, 1, 1, 1, 1)
- param_rms = (p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt()
- state["param_rms"] = param_rms
-
- state["scale_exp_avg_sq"] = torch.zeros_like(param_rms)
- state["scale_grads"] = torch.zeros(size_update_period, *param_rms.shape, **kwargs)
-
- # exp_avg_sq is the weighted sum of scaled gradients. as in Adam.
- state["exp_avg_sq"] = torch.zeros_like(p, memory_format=torch.preserve_format)
-
- def _get_clipping_scale(self, group: dict, tuples: List[Tuple[Tensor, dict, List[str]]]) -> float:
- """
- Returns a scalar factor <= 1.0 that dictates gradient clipping, i.e. we will scale the gradients
- by this amount before applying the rest of the update.
-
- Args:
- group: the parameter group, an item in self.param_groups
- tuples: a list of tuples of (param, state, param_names)
- where param is a batched set of parameters,
- with a .grad (1st dim is batch dim)
- and state is the state-dict where optimization parameters are kept.
- param_names is a List[str] while each str is name for a parameter
- in batched set of parameters "param".
- """
- assert len(tuples) >= 1
- clipping_scale = group["clipping_scale"]
- (first_p, first_state, _) = tuples[0]
- step = first_state["step"]
- if clipping_scale is None or step == 0:
- # no clipping. return early on step == 0 because the other
- # parameters' state won't have been initialized yet.
- return 1.0
- clipping_update_period = group["clipping_update_period"]
-
- tot_sumsq = torch.tensor(0.0, device=first_p.device)
- for p, state, param_names in tuples:
- grad = p.grad
- if grad.is_sparse:
- raise RuntimeError("ScaledAdam optimizer does not support sparse gradients")
- if p.numel() == p.shape[0]: # a batch of scalars
- tot_sumsq += (grad**2).sum() # sum() to change shape [1] to []
- else:
- tot_sumsq += ((grad * state["param_rms"]) ** 2).sum()
-
- tot_norm = tot_sumsq.sqrt()
- if "model_norms" not in first_state:
- first_state["model_norms"] = torch.zeros(clipping_update_period, device=p.device)
- first_state["model_norms"][step % clipping_update_period] = tot_norm
-
- if step % clipping_update_period == 0:
- # Print some stats.
- # We don't reach here if step == 0 because we would have returned
- # above.
- sorted_norms = first_state["model_norms"].sort()[0].to("cpu")
- quartiles = []
- for n in range(0, 5):
- index = min(
- clipping_update_period - 1,
- (clipping_update_period // 4) * n,
- )
- quartiles.append(sorted_norms[index].item())
-
- median = quartiles[2]
- threshold = clipping_scale * median
- first_state["model_norm_threshold"] = threshold
- percent_clipped = (
- first_state["num_clipped"] * 100.0 / clipping_update_period if "num_clipped" in first_state else 0.0
- )
- first_state["num_clipped"] = 0
- quartiles = " ".join(["%.3e" % x for x in quartiles])
- logging.info(
- f"Clipping_scale={clipping_scale}, grad-norm quartiles {quartiles}, threshold={threshold:.3e}, percent-clipped={percent_clipped:.1f}"
- )
-
- if step < clipping_update_period:
- return 1.0 # We have not yet estimated a norm to clip to.
- else:
- try:
- model_norm_threshold = first_state["model_norm_threshold"]
- except KeyError:
- logging.info(
- "Warning: model_norm_threshold not in state: possibly you changed config when restarting, adding clipping_scale option?"
- )
- return 1.0
- ans = min(1.0, (model_norm_threshold / (tot_norm + 1.0e-20)).item())
- if ans < 1.0:
- first_state["num_clipped"] += 1
- if ans < 0.1:
- logging.warning(f"Scaling gradients by {ans}, model_norm_threshold={model_norm_threshold}")
- if self.show_dominant_parameters:
- assert p.shape[0] == len(param_names)
- self._show_gradient_dominating_parameter(tuples, tot_sumsq)
- return ans
-
- def _show_gradient_dominating_parameter(self, tuples: List[Tuple[Tensor, dict, List[str]]], tot_sumsq: Tensor):
- """
- Show information of parameter which dominating tot_sumsq.
-
- Args:
- tuples: a list of tuples of (param, state, param_names)
- where param is a batched set of parameters,
- with a .grad (1st dim is batch dim)
- and state is the state-dict where optimization parameters are kept.
- param_names is a List[str] while each str is name for a parameter
- in batched set of parameters "param".
- tot_sumsq: sumsq of all parameters. Though it's could be calculated
- from tuples, we still pass it to save some time.
- """
- all_sumsq_orig = {}
- for p, state, batch_param_names in tuples:
- # p is a stacked batch parameters.
- batch_grad = p.grad
- if p.numel() == p.shape[0]: # a batch of scalars
- batch_sumsq_orig = batch_grad**2
- # Dummpy values used by following `zip` statement.
- batch_rms_orig = torch.ones(p.shape[0])
- else:
- batch_rms_orig = state["param_rms"]
- batch_sumsq_orig = ((batch_grad * batch_rms_orig) ** 2).sum(dim=list(range(1, batch_grad.ndim)))
-
- for name, sumsq_orig, rms, grad in zip(
- batch_param_names,
- batch_sumsq_orig,
- batch_rms_orig,
- batch_grad,
- ):
- proportion_orig = sumsq_orig / tot_sumsq
- all_sumsq_orig[name] = (proportion_orig, sumsq_orig, rms, grad)
-
- assert torch.isclose(
- sum([value[0] for value in all_sumsq_orig.values()]).cpu(),
- torch.tensor(1.0),
- )
- sorted_by_proportion = {
- k: v
- for k, v in sorted(
- all_sumsq_orig.items(),
- key=lambda item: item[1][0],
- reverse=True,
- )
- }
- dominant_param_name = next(iter(sorted_by_proportion))
- (
- dominant_proportion,
- dominant_sumsq,
- dominant_rms,
- dominant_grad,
- ) = sorted_by_proportion[dominant_param_name]
- logging.info(
- f"Parameter Dominating tot_sumsq {dominant_param_name}"
- f" with proportion {dominant_proportion:.2f},"
- f" where dominant_sumsq=(grad_sumsq*orig_rms_sq)"
- f"={dominant_sumsq:.3e},"
- f" grad_sumsq = {(dominant_grad**2).sum():.3e},"
- f" orig_rms_sq={(dominant_rms**2).item():.3e}"
- )
-
- def _step_one_batch(self, group: dict, p: Tensor, state: dict, clipping_scale: float):
- """
- Do the step for one parameter, which is actually going to be a batch of
- `real` parameters, with dim 0 as the batch dim.
- Args:
- group: dict to look up configuration values
- p: parameter to update (actually multiple parameters stacked together
- as a batch)
- state: state-dict for p, to look up the optimizer state
- """
- lr = group["lr"]
- size_update_period = group["size_update_period"]
- beta1 = group["betas"][0]
-
- grad = p.grad
- if clipping_scale != 1.0:
- grad = grad * clipping_scale
- step = state["step"]
- delta = state["delta"]
-
- delta.mul_(beta1)
- batch_size = p.shape[0]
- numel = p.numel() // batch_size
- if numel > 1:
- # Update the size/scale of p, and set param_rms
- scale_grads = state["scale_grads"]
- scale_grads[step % size_update_period] = (p * grad).sum(dim=list(range(1, p.ndim)), keepdim=True)
- if step % size_update_period == size_update_period - 1:
- param_rms = state["param_rms"] # shape: (batch_size, 1, 1, ..)
- param_rms.copy_((p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt())
- if step > 0:
- # self._size_update() learns the overall scale on the
- # parameter, by shrinking or expanding it.
- self._size_update(group, scale_grads, p, state)
-
- if numel == 1:
- # For parameters with 1 element we just use regular Adam.
- # Updates delta.
- self._step_scalar(group, p, state)
- else:
- self._step(group, p, state)
-
- state["step"] = step + 1
-
- def _size_update(
- self,
- group: dict,
- scale_grads: Tensor,
- p: Tensor,
- state: dict,
- ) -> None:
- """
- Called only where p.numel() > 1, this updates the scale of the parameter.
- If we imagine: p = underlying_param * scale.exp(), and we are doing
- gradient descent on underlying param and on scale, this function does the update
- on `scale`.
-
- Args:
- group: dict to look up configuration values
- scale_grads: a tensor of shape (size_update_period, batch_size, 1, 1,...) containing
- grads w.r.t. the scales.
- p: The parameter to update
- state: The state-dict of p
- """
-
- param_rms = state["param_rms"]
- beta1, beta2 = group["betas"]
- size_lr = group["lr"] * group["scalar_lr_scale"]
- param_min_rms = group["param_min_rms"]
- param_max_rms = group["param_max_rms"]
- eps = group["eps"]
- step = state["step"]
- batch_size = p.shape[0]
-
- size_update_period = scale_grads.shape[0]
- # correct beta2 for the size update period: we will have
- # faster decay at this level.
- beta2_corr = beta2**size_update_period
-
- scale_exp_avg_sq = state["scale_exp_avg_sq"] # shape: (batch_size, 1, 1, ..)
- scale_exp_avg_sq.mul_(beta2_corr).add_(
- (scale_grads**2).mean(dim=0), # mean over dim `size_update_period`
- alpha=1 - beta2_corr,
- ) # shape is (batch_size, 1, 1, ...)
-
- # The 1st time we reach here is when size_step == 1.
- size_step = (step + 1) // size_update_period
- bias_correction2 = 1 - beta2_corr**size_step
- # we don't bother with bias_correction1; this will help prevent divergence
- # at the start of training.
-
- denom = scale_exp_avg_sq.sqrt() + eps
-
- scale_step = -size_lr * (bias_correction2**0.5) * scale_grads.sum(dim=0) / denom
-
- is_too_small = param_rms < param_min_rms
- is_too_large = param_rms > param_max_rms
-
- # when the param gets too small, just don't shrink it any further.
- scale_step.masked_fill_(is_too_small, 0.0)
- # when it gets too large, stop it from getting any larger.
- scale_step.masked_fill_(is_too_large, -size_lr * size_update_period)
- delta = state["delta"]
- # the factor of (1-beta1) relates to momentum.
- delta.add_(p * scale_step, alpha=(1 - beta1))
-
- def _step(self, group: dict, p: Tensor, state: dict):
- """
- This function does the core update of self.step(), in the case where the members of
- the batch have more than 1 element.
-
- Args:
- group: A dict which will be used to look up configuration values
- p: The parameter to be updated
- grad: The grad of p
- state: The state-dict corresponding to parameter p
-
- This function modifies p.
- """
- grad = p.grad
- lr = group["lr"]
- beta1, beta2 = group["betas"]
- eps = group["eps"]
- param_min_rms = group["param_min_rms"]
- step = state["step"]
-
- exp_avg_sq = state["exp_avg_sq"]
- exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=(1 - beta2))
-
- this_step = state["step"] - (state["zero_step"] if "zero_step" in state else 0)
- bias_correction2 = 1 - beta2 ** (this_step + 1)
- if bias_correction2 < 0.99:
- # note: not in-place.
- exp_avg_sq = exp_avg_sq * (1.0 / bias_correction2)
-
- denom = exp_avg_sq.sqrt()
- denom += eps
- grad = grad / denom
-
- alpha = -lr * (1 - beta1) * state["param_rms"].clamp(min=param_min_rms)
-
- delta = state["delta"]
- delta.add_(grad * alpha)
- p.add_(delta)
-
- def _step_scalar(self, group: dict, p: Tensor, state: dict):
- """
- A simplified form of the core update for scalar tensors, where we cannot get a good
- estimate of the parameter rms.
- """
- beta1, beta2 = group["betas"]
- scalar_max = group["scalar_max"]
- eps = group["eps"]
- lr = group["lr"] * group["scalar_lr_scale"]
- grad = p.grad
-
- exp_avg_sq = state["exp_avg_sq"] # shape: (batch_size,)
- exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
-
- # bias_correction2 is like in Adam. Don't bother with bias_correction1;
- # slower update at the start will help stability anyway.
- bias_correction2 = 1 - beta2 ** (state["step"] + 1)
- denom = (exp_avg_sq / bias_correction2).sqrt() + eps
-
- delta = state["delta"]
- delta.add_(grad / denom, alpha=-lr * (1 - beta1))
- p.clamp_(min=-scalar_max, max=scalar_max)
- p.add_(delta)
diff --git a/GPT_SoVITS/AR/modules/patched_mha_with_cache.py b/GPT_SoVITS/AR/modules/patched_mha_with_cache.py
index 5bffcea6..7362cd64 100644
--- a/GPT_SoVITS/AR/modules/patched_mha_with_cache.py
+++ b/GPT_SoVITS/AR/modules/patched_mha_with_cache.py
@@ -1,428 +1,112 @@
-from torch.nn.functional import *
-from torch.nn.functional import (
- _mha_shape_check,
- _canonical_mask,
- _none_or_dtype,
- _in_projection_packed,
-)
-import torch
-# Tensor = torch.Tensor
-# from typing import Callable, List, Optional, Tuple, Union
-
-
-def multi_head_attention_forward_patched(
- query,
- key,
- value,
- embed_dim_to_check,
- num_heads,
- in_proj_weight,
- in_proj_bias,
- bias_k,
- bias_v,
- add_zero_attn,
- dropout_p: float,
- out_proj_weight,
- out_proj_bias,
- training=True,
- key_padding_mask=None,
- need_weights=True,
- attn_mask=None,
- use_separate_proj_weight=False,
- q_proj_weight=None,
- k_proj_weight=None,
- v_proj_weight=None,
- static_k=None,
- static_v=None,
- average_attn_weights=True,
- is_causal=False,
- cache=None,
-):
- r"""
- Args:
- query, key, value: map a query and a set of key-value pairs to an output.
- See "Attention Is All You Need" for more details.
- embed_dim_to_check: total dimension of the model.
- num_heads: parallel attention heads.
- in_proj_weight, in_proj_bias: input projection weight and bias.
- bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
- add_zero_attn: add a new batch of zeros to the key and
- value sequences at dim=1.
- dropout_p: probability of an element to be zeroed.
- out_proj_weight, out_proj_bias: the output projection weight and bias.
- training: apply dropout if is ``True``.
- key_padding_mask: if provided, specified padding elements in the key will
- be ignored by the attention. This is an binary mask. When the value is True,
- the corresponding value on the attention layer will be filled with -inf.
- need_weights: output attn_output_weights.
- Default: `True`
- Note: `needs_weight` defaults to `True`, but should be set to `False`
- For best performance when attention weights are not nedeeded.
- *Setting needs_weights to `True`
- leads to a significant performance degradation.*
- attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
- the batches while a 3D mask allows to specify a different mask for the entries of each batch.
- is_causal: If specified, applies a causal mask as attention mask, and ignores
- attn_mask for computing scaled dot product attention.
- Default: ``False``.
- .. warning::
- is_causal is provides a hint that the attn_mask is the
- causal mask.Providing incorrect hints can result in
- incorrect execution, including forward and backward
- compatibility.
- use_separate_proj_weight: the function accept the proj. weights for query, key,
- and value in different forms. If false, in_proj_weight will be used, which is
- a combination of q_proj_weight, k_proj_weight, v_proj_weight.
- q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
- static_k, static_v: static key and value used for attention operators.
- average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
- Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
- when ``need_weights=True.``. Default: True
-
-
- Shape:
- Inputs:
- - query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
- the embedding dimension.
- - key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
- the embedding dimension.
- - value: :math:`(S, E)` or :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
- the embedding dimension.
- - key_padding_mask: :math:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
- If a FloatTensor is provided, it will be directly added to the value.
- If a BoolTensor is provided, the positions with the
- value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
- - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
- 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
- S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
- positions. If a BoolTensor is provided, positions with ``True``
- are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
- is provided, it will be added to the attention weight.
- - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
- N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
- - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
- N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
-
- Outputs:
- - attn_output: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
- E is the embedding dimension.
- - attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
- attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
- :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
- :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
- head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
- """
- tens_ops = (
- query,
- key,
- value,
- in_proj_weight,
- in_proj_bias,
- bias_k,
- bias_v,
- out_proj_weight,
- out_proj_bias,
- )
- if has_torch_function(tens_ops):
- return handle_torch_function(
- multi_head_attention_forward,
- tens_ops,
- query,
- key,
- value,
- embed_dim_to_check,
- num_heads,
- in_proj_weight,
- in_proj_bias,
- bias_k,
- bias_v,
- add_zero_attn,
- dropout_p,
- out_proj_weight,
- out_proj_bias,
- training=training,
- key_padding_mask=key_padding_mask,
- need_weights=need_weights,
- attn_mask=attn_mask,
- is_causal=is_causal,
- use_separate_proj_weight=use_separate_proj_weight,
- q_proj_weight=q_proj_weight,
- k_proj_weight=k_proj_weight,
- v_proj_weight=v_proj_weight,
- static_k=static_k,
- static_v=static_v,
- average_attn_weights=average_attn_weights,
- cache=cache,
- )
-
- is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
-
- # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
- # is batched, run the computation and before returning squeeze the
- # batch dimension so that the output doesn't carry this temporary batch dimension.
- if not is_batched:
- # unsqueeze if the input is unbatched
- query = query.unsqueeze(1)
- key = key.unsqueeze(1)
- value = value.unsqueeze(1)
- if key_padding_mask is not None:
- key_padding_mask = key_padding_mask.unsqueeze(0)
-
- # set up shape vars
- tgt_len, bsz, embed_dim = query.shape
- src_len, _, _ = key.shape
-
- key_padding_mask = _canonical_mask(
- mask=key_padding_mask,
- mask_name="key_padding_mask",
- other_type=_none_or_dtype(attn_mask),
- other_name="attn_mask",
- target_type=query.dtype,
- )
-
- if is_causal and attn_mask is None:
- raise RuntimeError(
- "Need attn_mask if specifying the is_causal hint. "
- "You may use the Transformer module method "
- "`generate_square_subsequent_mask` to create this mask."
- )
-
- if is_causal and key_padding_mask is None and not need_weights:
- # when we have a kpm or need weights, we need attn_mask
- # Otherwise, we use the is_causal hint go as is_causal
- # indicator to SDPA.
- attn_mask = None
- else:
- attn_mask = _canonical_mask(
- mask=attn_mask,
- mask_name="attn_mask",
- other_type=None,
- other_name="",
- target_type=query.dtype,
- check_other=False,
- )
-
- if key_padding_mask is not None:
- # We have the attn_mask, and use that to merge kpm into it.
- # Turn off use of is_causal hint, as the merged mask is no
- # longer causal.
- is_causal = False
-
- assert embed_dim == embed_dim_to_check, (
- f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
- )
- if isinstance(embed_dim, torch.Tensor):
- # embed_dim can be a tensor when JIT tracing
- head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
- else:
- head_dim = embed_dim // num_heads
- assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
- if use_separate_proj_weight:
- # allow MHA to have different embedding dimensions when separate projection weights are used
- assert key.shape[:2] == value.shape[:2], (
- f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
- )
- else:
- assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
-
- #
- # compute in-projection
- #
- if not use_separate_proj_weight:
- assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
- q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
- else:
- assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
- assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
- assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
- if in_proj_bias is None:
- b_q = b_k = b_v = None
- else:
- b_q, b_k, b_v = in_proj_bias.chunk(3)
- q, k, v = _in_projection(
- query,
- key,
- value,
- q_proj_weight,
- k_proj_weight,
- v_proj_weight,
- b_q,
- b_k,
- b_v,
- )
- if cache != None:
- if cache["first_infer"] == 1:
- cache["k"][cache["stage"]] = k
- # print(0,cache["k"].shape)
- cache["v"][cache["stage"]] = v
- else: ###12个layer每个都要留自己的cache_kv
- # print(1,cache["k"].shape)
- cache["k"][cache["stage"]] = torch.cat(
- [cache["k"][cache["stage"]], k], 0
- ) ##本来时序是1,但是proj的时候可能transpose了所以时序到0维了
- cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]], v], 0)
- # print(2, cache["k"].shape)
- src_len = cache["k"][cache["stage"]].shape[0]
- k = cache["k"][cache["stage"]]
- v = cache["v"][cache["stage"]]
- # if attn_mask is not None:
- # attn_mask=attn_mask[-1:,]
- # print(attn_mask.shape,attn_mask)
- cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
- # print(2333,cache)
- # prep attention mask
-
- attn_mask = _canonical_mask(
- mask=attn_mask,
- mask_name="attn_mask",
- other_type=None,
- other_name="",
- target_type=q.dtype,
- check_other=False,
- )
-
- if attn_mask is not None:
- # ensure attn_mask's dim is 3
- if attn_mask.dim() == 2:
- correct_2d_size = (tgt_len, src_len)
- if attn_mask.shape != correct_2d_size:
- raise RuntimeError(
- f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
- )
- attn_mask = attn_mask.unsqueeze(0)
- elif attn_mask.dim() == 3:
- correct_3d_size = (bsz * num_heads, tgt_len, src_len)
- if attn_mask.shape != correct_3d_size:
- raise RuntimeError(
- f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
- )
- else:
- raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
-
- # add bias along batch dimension (currently second)
- if bias_k is not None and bias_v is not None:
- assert static_k is None, "bias cannot be added to static key."
- assert static_v is None, "bias cannot be added to static value."
- k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
- v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
- if attn_mask is not None:
- attn_mask = pad(attn_mask, (0, 1))
- if key_padding_mask is not None:
- key_padding_mask = pad(key_padding_mask, (0, 1))
- else:
- assert bias_k is None
- assert bias_v is None
-
- #
- # reshape q, k, v for multihead attention and make em batch first
- #
- q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
- if static_k is None:
- k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
- else:
- # TODO finish disentangling control flow so we don't do in-projections when statics are passed
- assert static_k.size(0) == bsz * num_heads, (
- f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
- )
- assert static_k.size(2) == head_dim, f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
- k = static_k
- if static_v is None:
- v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
- else:
- # TODO finish disentangling control flow so we don't do in-projections when statics are passed
- assert static_v.size(0) == bsz * num_heads, (
- f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
- )
- assert static_v.size(2) == head_dim, f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
- v = static_v
-
- # add zero attention along batch dimension (now first)
- if add_zero_attn:
- zero_attn_shape = (bsz * num_heads, 1, head_dim)
- k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
- v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
- if attn_mask is not None:
- attn_mask = pad(attn_mask, (0, 1))
- if key_padding_mask is not None:
- key_padding_mask = pad(key_padding_mask, (0, 1))
-
- # update source sequence length after adjustments
- src_len = k.size(1)
-
- # merge key padding and attention masks
- if key_padding_mask is not None:
- assert key_padding_mask.shape == (
- bsz,
- src_len,
- ), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
- key_padding_mask = (
- key_padding_mask.view(bsz, 1, 1, src_len).expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
- )
- if attn_mask is None:
- attn_mask = key_padding_mask
- else:
- attn_mask = attn_mask + key_padding_mask
-
- # adjust dropout probability
- if not training:
- dropout_p = 0.0
-
- #
- # (deep breath) calculate attention and out projection
- #
-
- if need_weights:
- B, Nt, E = q.shape
- q_scaled = q / math.sqrt(E)
-
- assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
-
- if attn_mask is not None:
- attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
- else:
- attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
- attn_output_weights = softmax(attn_output_weights, dim=-1)
- if dropout_p > 0.0:
- attn_output_weights = dropout(attn_output_weights, p=dropout_p)
-
- attn_output = torch.bmm(attn_output_weights, v)
-
- attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
- attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
- attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
-
- # optionally average attention weights over heads
- attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
- if average_attn_weights:
- attn_output_weights = attn_output_weights.mean(dim=1)
-
- if not is_batched:
- # squeeze the output if input was unbatched
- attn_output = attn_output.squeeze(1)
- attn_output_weights = attn_output_weights.squeeze(0)
- return attn_output, attn_output_weights
- else:
- # attn_mask can be either (L,S) or (N*num_heads, L, S)
- # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
- # in order to match the input for SDPA of (N, num_heads, L, S)
- if attn_mask is not None:
- if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
- attn_mask = attn_mask.unsqueeze(0)
- else:
- attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
-
- q = q.view(bsz, num_heads, tgt_len, head_dim)
- k = k.view(bsz, num_heads, src_len, head_dim)
- v = v.view(bsz, num_heads, src_len, head_dim)
-
- # with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
- attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
-
- attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
-
- attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
- attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
- if not is_batched:
- # squeeze the output if input was unbatched
- attn_output = attn_output.squeeze(1)
- return attn_output, None
+"""Packed-projection inference attention with per-layer KV caching."""
+
+import math
+
+import torch
+from torch.nn import functional as F
+
+
+def multi_head_attention_forward_patched(
+ query,
+ key,
+ value,
+ embed_dim_to_check,
+ num_heads,
+ in_proj_weight,
+ in_proj_bias,
+ out_proj_weight,
+ out_proj_bias,
+ key_padding_mask=None,
+ need_weights=True,
+ attn_mask=None,
+ average_attn_weights=True,
+ cache=None,
+):
+ is_batched = F._mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
+ if not is_batched:
+ query, key, value = query.unsqueeze(1), key.unsqueeze(1), value.unsqueeze(1)
+ if key_padding_mask is not None:
+ key_padding_mask = key_padding_mask.unsqueeze(0)
+
+ tgt_len, bsz, embed_dim = query.shape
+ src_len = key.shape[0]
+ key_padding_mask = F._canonical_mask(
+ mask=key_padding_mask, mask_name="key_padding_mask",
+ other_type=F._none_or_dtype(attn_mask), other_name="attn_mask", target_type=query.dtype,
+ )
+ attn_mask = F._canonical_mask(
+ mask=attn_mask, mask_name="attn_mask", other_type=None,
+ other_name="", target_type=query.dtype, check_other=False,
+ )
+ assert embed_dim == embed_dim_to_check, "unexpected attention embedding dimension"
+ head_dim = embed_dim // num_heads
+ assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
+ assert key.shape == value.shape, "key and value shapes must match"
+ q, k, v = F._in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
+ if cache is not None:
+ stage = cache["stage"]
+ if cache["first_infer"] == 1:
+ cache["k"][stage] = k
+ cache["v"][stage] = v
+ else:
+ k = cache["k"][stage] = torch.cat([cache["k"][stage], k], dim=0)
+ v = cache["v"][stage] = torch.cat([cache["v"][stage], v], dim=0)
+ src_len = k.shape[0]
+ cache["stage"] = (stage + 1) % cache["all_stage"]
+
+ attn_mask = F._canonical_mask(
+ mask=attn_mask, mask_name="attn_mask", other_type=None,
+ other_name="", target_type=q.dtype, check_other=False,
+ )
+ if attn_mask is not None:
+ if attn_mask.dim() == 2:
+ expected = (tgt_len, src_len)
+ if attn_mask.shape != expected:
+ raise RuntimeError(f"The 2D attn_mask shape is {attn_mask.shape}, expected {expected}")
+ attn_mask = attn_mask.unsqueeze(0)
+ elif attn_mask.dim() == 3:
+ expected = (bsz * num_heads, tgt_len, src_len)
+ if attn_mask.shape != expected:
+ raise RuntimeError(f"The 3D attn_mask shape is {attn_mask.shape}, expected {expected}")
+ else:
+ raise RuntimeError(f"attn_mask dimension {attn_mask.dim()} is not supported")
+
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
+ src_len = k.size(1)
+ if key_padding_mask is not None:
+ assert key_padding_mask.shape == (bsz, src_len), "unexpected key padding mask shape"
+ key_padding_mask = (
+ key_padding_mask.view(bsz, 1, 1, src_len)
+ .expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
+ )
+ attn_mask = key_padding_mask if attn_mask is None else attn_mask + key_padding_mask
+
+ if need_weights:
+ q_scaled = q / math.sqrt(q.size(-1))
+ weights = (torch.bmm(q_scaled, k.transpose(-2, -1)) if attn_mask is None
+ else torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1)))
+ weights = F.softmax(weights, dim=-1)
+ output = torch.bmm(weights, v)
+ output = output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
+ output = F.linear(output, out_proj_weight, out_proj_bias).view(tgt_len, bsz, embed_dim)
+ weights = weights.view(bsz, num_heads, tgt_len, src_len)
+ if average_attn_weights:
+ weights = weights.mean(dim=1)
+ if not is_batched:
+ output, weights = output.squeeze(1), weights.squeeze(0)
+ return output, weights
+
+ if attn_mask is not None:
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
+ attn_mask = attn_mask.unsqueeze(0)
+ else:
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
+ k = k.view(bsz, num_heads, src_len, head_dim)
+ v = v.view(bsz, num_heads, src_len, head_dim)
+ output = F.scaled_dot_product_attention(q, k, v, attn_mask, 0.0, False)
+ output = output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
+ output = F.linear(output, out_proj_weight, out_proj_bias).view(tgt_len, bsz, embed_dim)
+ return (output.squeeze(1) if not is_batched else output), None
diff --git a/GPT_SoVITS/AR/modules/patched_mha_with_cache_onnx.py b/GPT_SoVITS/AR/modules/patched_mha_with_cache_onnx.py
deleted file mode 100644
index 79077120..00000000
--- a/GPT_SoVITS/AR/modules/patched_mha_with_cache_onnx.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from torch.nn.functional import *
-from torch.nn.functional import (
- _canonical_mask,
-)
-
-
-def multi_head_attention_forward_patched(
- query,
- key,
- value,
- embed_dim_to_check,
- num_heads,
- in_proj_weight,
- in_proj_bias,
- bias_k,
- bias_v,
- add_zero_attn,
- dropout_p,
- out_proj_weight,
- out_proj_bias,
- training=True,
- key_padding_mask=None,
- need_weights=True,
- attn_mask=None,
- use_separate_proj_weight=False,
- q_proj_weight=None,
- k_proj_weight=None,
- v_proj_weight=None,
- static_k=None,
- static_v=None,
- average_attn_weights=True,
- is_causal=False,
- cache=None,
-):
- # set up shape vars
- _, _, embed_dim = query.shape
- attn_mask = _canonical_mask(
- mask=attn_mask,
- mask_name="attn_mask",
- other_type=None,
- other_name="",
- target_type=query.dtype,
- check_other=False,
- )
- head_dim = embed_dim // num_heads
-
- proj_qkv = linear(query, in_proj_weight, in_proj_bias)
- proj_qkv = proj_qkv.unflatten(-1, (3, query.size(-1))).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
- q, k, v = proj_qkv[0], proj_qkv[1], proj_qkv[2]
-
- if cache["first_infer"] == 1:
- cache["k"][cache["stage"]] = k
- cache["v"][cache["stage"]] = v
- else:
- cache["k"][cache["stage"]] = torch.cat([cache["k"][cache["stage"]][:-1], k], 0)
- cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]][:-1], v], 0)
- k = cache["k"][cache["stage"]]
- v = cache["v"][cache["stage"]]
- cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
-
- attn_mask = _canonical_mask(
- mask=attn_mask,
- mask_name="attn_mask",
- other_type=None,
- other_name="",
- target_type=q.dtype,
- check_other=False,
- )
- attn_mask = attn_mask.unsqueeze(0)
-
- q = q.view(-1, num_heads, head_dim).transpose(0, 1)
- k = k.view(-1, num_heads, head_dim).transpose(0, 1)
- v = v.view(-1, num_heads, head_dim).transpose(0, 1)
-
- dropout_p = 0.0
- attn_mask = attn_mask.unsqueeze(0)
- q = q.view(num_heads, -1, head_dim).unsqueeze(0)
- k = k.view(num_heads, -1, head_dim).unsqueeze(0)
- v = v.view(num_heads, -1, head_dim).unsqueeze(0)
- attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
- attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(-1, embed_dim)
- attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
- attn_output = attn_output.view(-1, 1, attn_output.size(1))
-
- return attn_output
diff --git a/GPT_SoVITS/AR/modules/scaling.py b/GPT_SoVITS/AR/modules/scaling.py
deleted file mode 100644
index aae14533..00000000
--- a/GPT_SoVITS/AR/modules/scaling.py
+++ /dev/null
@@ -1,320 +0,0 @@
-# Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
-#
-# See ../../../../LICENSE for clarification regarding multiple authors
-#
-# 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 random
-from typing import Optional
-from typing import Tuple
-
-import torch
-import torch.nn as nn
-from torch import Tensor
-
-
-class DoubleSwishFunction(torch.autograd.Function):
- """
- double_swish(x) = x * torch.sigmoid(x-1)
- This is a definition, originally motivated by its close numerical
- similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
-
- Memory-efficient derivative computation:
- double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
- double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
- Now, s'(x) = s(x) * (1-s(x)).
- double_swish'(x) = x * s'(x) + s(x).
- = x * s(x) * (1-s(x)) + s(x).
- = double_swish(x) * (1-s(x)) + s(x)
- ... so we just need to remember s(x) but not x itself.
- """
-
- @staticmethod
- def forward(ctx, x: Tensor) -> Tensor:
- requires_grad = x.requires_grad
- x_dtype = x.dtype
- if x.dtype == torch.float16:
- x = x.to(torch.float32)
-
- s = torch.sigmoid(x - 1.0)
- y = x * s
-
- if requires_grad:
- deriv = y * (1 - s) + s
- # notes on derivative of x * sigmoid(x - 1):
- # https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
- # min \simeq -0.043638. Take floor as -0.043637 so it's a lower bund
- # max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
- # the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
- # floors), should be expectation-preserving.
- floor = -0.043637
- ceil = 1.2
- d_scaled = (deriv - floor) * (255.0 / (ceil - floor)) + torch.rand_like(deriv)
- if __name__ == "__main__":
- # for self-testing only.
- assert d_scaled.min() >= 0.0
- assert d_scaled.max() < 256.0
- d_int = d_scaled.to(torch.uint8)
- ctx.save_for_backward(d_int)
- if x.dtype == torch.float16 or torch.is_autocast_enabled():
- y = y.to(torch.float16)
- return y
-
- @staticmethod
- def backward(ctx, y_grad: Tensor) -> Tensor:
- (d,) = ctx.saved_tensors
- # the same constants as used in forward pass.
- floor = -0.043637
- ceil = 1.2
- d = d * ((ceil - floor) / 255.0) + floor
- return y_grad * d
-
-
-class DoubleSwish(torch.nn.Module):
- def forward(self, x: Tensor) -> Tensor:
- """Return double-swish activation function which is an approximation to Swish(Swish(x)),
- that we approximate closely with x * sigmoid(x-1).
- """
- if torch.jit.is_scripting() or torch.jit.is_tracing():
- return x * torch.sigmoid(x - 1.0)
- return DoubleSwishFunction.apply(x)
-
-
-class ActivationBalancerFunction(torch.autograd.Function):
- @staticmethod
- def forward(
- ctx,
- x: Tensor,
- scale_factor: Tensor,
- sign_factor: Optional[Tensor],
- channel_dim: int,
- ) -> Tensor:
- if channel_dim < 0:
- channel_dim += x.ndim
- ctx.channel_dim = channel_dim
- xgt0 = x > 0
- if sign_factor is None:
- ctx.save_for_backward(xgt0, scale_factor)
- else:
- ctx.save_for_backward(xgt0, scale_factor, sign_factor)
- return x
-
- @staticmethod
- def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
- if len(ctx.saved_tensors) == 3:
- xgt0, scale_factor, sign_factor = ctx.saved_tensors
- for _ in range(ctx.channel_dim, x_grad.ndim - 1):
- scale_factor = scale_factor.unsqueeze(-1)
- sign_factor = sign_factor.unsqueeze(-1)
- factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
- else:
- xgt0, scale_factor = ctx.saved_tensors
- for _ in range(ctx.channel_dim, x_grad.ndim - 1):
- scale_factor = scale_factor.unsqueeze(-1)
- factor = scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
- neg_delta_grad = x_grad.abs() * factor
- return (
- x_grad - neg_delta_grad,
- None,
- None,
- None,
- )
-
-
-def _compute_scale_factor(
- x: Tensor,
- channel_dim: int,
- min_abs: float,
- max_abs: float,
- gain_factor: float,
- max_factor: float,
-) -> Tensor:
- if channel_dim < 0:
- channel_dim += x.ndim
- sum_dims = [d for d in range(x.ndim) if d != channel_dim]
- x_abs_mean = torch.mean(x.abs(), dim=sum_dims).to(torch.float32)
-
- if min_abs == 0.0:
- below_threshold = 0.0
- else:
- # below_threshold is 0 if x_abs_mean > min_abs, can be at most max_factor if
- # x_abs)_mean , min_abs.
- below_threshold = ((min_abs - x_abs_mean) * (gain_factor / min_abs)).clamp(min=0, max=max_factor)
-
- above_threshold = ((x_abs_mean - max_abs) * (gain_factor / max_abs)).clamp(min=0, max=max_factor)
-
- return below_threshold - above_threshold
-
-
-def _compute_sign_factor(
- x: Tensor,
- channel_dim: int,
- min_positive: float,
- max_positive: float,
- gain_factor: float,
- max_factor: float,
-) -> Tensor:
- if channel_dim < 0:
- channel_dim += x.ndim
- sum_dims = [d for d in range(x.ndim) if d != channel_dim]
- proportion_positive = torch.mean((x > 0).to(torch.float32), dim=sum_dims)
- if min_positive == 0.0:
- factor1 = 0.0
- else:
- # 0 if proportion_positive >= min_positive, else can be
- # as large as max_factor.
- factor1 = ((min_positive - proportion_positive) * (gain_factor / min_positive)).clamp_(min=0, max=max_factor)
-
- if max_positive == 1.0:
- factor2 = 0.0
- else:
- # 0 if self.proportion_positive <= max_positive, else can be
- # as large as -max_factor.
- factor2 = ((proportion_positive - max_positive) * (gain_factor / (1.0 - max_positive))).clamp_(
- min=0, max=max_factor
- )
- sign_factor = factor1 - factor2
- # require min_positive != 0 or max_positive != 1:
- assert not isinstance(sign_factor, float)
- return sign_factor
-
-
-class ActivationBalancer(torch.nn.Module):
- """
- Modifies the backpropped derivatives of a function to try to encourage, for
- each channel, that it is positive at least a proportion `threshold` of the
- time. It does this by multiplying negative derivative values by up to
- (1+max_factor), and positive derivative values by up to (1-max_factor),
- interpolated from 1 at the threshold to those extremal values when none
- of the inputs are positive.
-
- Args:
- num_channels: the number of channels
- channel_dim: the dimension/axis corresponding to the channel, e.g.
- -1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
- min_positive: the minimum, per channel, of the proportion of the time
- that (x > 0), below which we start to modify the derivatives.
- max_positive: the maximum, per channel, of the proportion of the time
- that (x > 0), above which we start to modify the derivatives.
- max_factor: the maximum factor by which we modify the derivatives for
- either the sign constraint or the magnitude constraint;
- e.g. with max_factor=0.02, the the derivatives would be multiplied by
- values in the range [0.98..1.02].
- sign_gain_factor: determines the 'gain' with which we increase the
- change in gradient once the constraints on min_positive and max_positive
- are violated.
- scale_gain_factor: determines the 'gain' with which we increase the
- change in gradient once the constraints on min_abs and max_abs
- are violated.
- min_abs: the minimum average-absolute-value difference from the mean
- value per channel, which we allow, before we start to modify
- the derivatives to prevent this.
- max_abs: the maximum average-absolute-value difference from the mean
- value per channel, which we allow, before we start to modify
- the derivatives to prevent this.
- min_prob: determines the minimum probability with which we modify the
- gradients for the {min,max}_positive and {min,max}_abs constraints,
- on each forward(). This is done randomly to prevent all layers
- from doing it at the same time. Early in training we may use
- higher probabilities than this; it will decay to this value.
- """
-
- def __init__(
- self,
- num_channels: int,
- channel_dim: int,
- min_positive: float = 0.05,
- max_positive: float = 0.95,
- max_factor: float = 0.04,
- sign_gain_factor: float = 0.01,
- scale_gain_factor: float = 0.02,
- min_abs: float = 0.2,
- max_abs: float = 100.0,
- min_prob: float = 0.1,
- ):
- super(ActivationBalancer, self).__init__()
- self.num_channels = num_channels
- self.channel_dim = channel_dim
- self.min_positive = min_positive
- self.max_positive = max_positive
- self.max_factor = max_factor
- self.min_abs = min_abs
- self.max_abs = max_abs
- self.min_prob = min_prob
- self.sign_gain_factor = sign_gain_factor
- self.scale_gain_factor = scale_gain_factor
-
- # count measures how many times the forward() function has been called.
- # We occasionally sync this to a tensor called `count`, that exists to
- # make sure it is synced to disk when we load and save the model.
- self.cpu_count = 0
- self.register_buffer("count", torch.tensor(0, dtype=torch.int64))
-
- def forward(self, x: Tensor) -> Tensor:
- if torch.jit.is_scripting() or not x.requires_grad or torch.jit.is_tracing():
- return _no_op(x)
-
- count = self.cpu_count
- self.cpu_count += 1
-
- if random.random() < 0.01:
- # Occasionally sync self.cpu_count with self.count.
- # count affects the decay of 'prob'. don't do this on every iter,
- # because syncing with the GPU is slow.
- self.cpu_count = max(self.cpu_count, self.count.item())
- self.count.fill_(self.cpu_count)
-
- # the prob of doing some work exponentially decreases from 0.5 till it hits
- # a floor at min_prob (==0.1, by default)
- prob = max(self.min_prob, 0.5 ** (1 + (count / 4000.0)))
-
- if random.random() < prob:
- sign_gain_factor = 0.5
- if self.min_positive != 0.0 or self.max_positive != 1.0:
- sign_factor = _compute_sign_factor(
- x,
- self.channel_dim,
- self.min_positive,
- self.max_positive,
- gain_factor=self.sign_gain_factor / prob,
- max_factor=self.max_factor,
- )
- else:
- sign_factor = None
-
- scale_factor = _compute_scale_factor(
- x.detach(),
- self.channel_dim,
- min_abs=self.min_abs,
- max_abs=self.max_abs,
- gain_factor=self.scale_gain_factor / prob,
- max_factor=self.max_factor,
- )
- return ActivationBalancerFunction.apply(
- x,
- scale_factor,
- sign_factor,
- self.channel_dim,
- )
- else:
- return _no_op(x)
-
-
-def BalancedDoubleSwish(d_model, channel_dim=-1, max_abs=10.0, min_prob=0.25) -> nn.Sequential:
- """
- ActivationBalancer -> DoubleSwish
- """
- balancer = ActivationBalancer(d_model, channel_dim=channel_dim, max_abs=max_abs, min_prob=min_prob)
- return nn.Sequential(
- balancer,
- DoubleSwish(),
- )
diff --git a/GPT_SoVITS/AR/modules/transformer.py b/GPT_SoVITS/AR/modules/transformer.py
index 1bf21cdb..ff168f8f 100644
--- a/GPT_SoVITS/AR/modules/transformer.py
+++ b/GPT_SoVITS/AR/modules/transformer.py
@@ -1,9 +1,7 @@
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
import copy
import numbers
-from functools import partial
from typing import Any
-from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
@@ -11,7 +9,6 @@ from typing import Union
import torch
from AR.modules.activation import MultiheadAttention
-from AR.modules.scaling import BalancedDoubleSwish
from torch import nn
from torch import Tensor
from torch.nn import functional as F
@@ -76,48 +73,14 @@ class LayerNorm(nn.Module):
return "{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}".format(**self.__dict__)
-class IdentityNorm(nn.Module):
- def __init__(
- self,
- d_model: int,
- eps: float = 1e-5,
- device=None,
- dtype=None,
- ) -> None:
- super(IdentityNorm, self).__init__()
-
- def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
- if isinstance(input, tuple):
- return input
-
- assert embedding is None
- return input
-
-
class TransformerEncoder(nn.Module):
- r"""TransformerEncoder is a stack of N encoder layers. Users can build the
- BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
-
- Args:
- encoder_layer: an instance of the TransformerEncoderLayer() class (required).
- num_layers: the number of sub-encoder-layers in the encoder (required).
- norm: the layer normalization component (optional).
- enable_nested_tensor: if True, input will automatically convert to nested tensor
- (and convert back on output). This will improve the overall performance of
- TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
-
- Examples::
- >>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
- >>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
- >>> src = torch.rand(10, 32, 512)
- >>> out = transformer_encoder(src)
- """
+ """Text-to-semantic encoder stack with an optional inference KV cache."""
__constants__ = ["norm"]
def __init__(self, encoder_layer, num_layers, norm=None):
super(TransformerEncoder, self).__init__()
- self.layers = _get_clones(encoder_layer, num_layers)
+ self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(num_layers)])
self.num_layers = num_layers
self.norm = norm
@@ -126,7 +89,6 @@ class TransformerEncoder(nn.Module):
src: Tensor,
mask: Optional[Tensor] = None,
src_key_padding_mask: Optional[Tensor] = None,
- return_layer_states: bool = False,
cache=None,
) -> Tensor:
r"""Pass the input through the encoder layers in turn.
@@ -135,28 +97,10 @@ class TransformerEncoder(nn.Module):
src: the sequence to the encoder (required).
mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
- return_layer_states: return layers' state (optional).
Shape:
see the docs in Transformer class.
"""
- if return_layer_states:
- layer_states = [] # layers' output
- output = src
- for mod in self.layers:
- output = mod(
- output,
- src_mask=mask,
- src_key_padding_mask=src_key_padding_mask,
- cache=cache,
- )
- layer_states.append(output[0])
-
- if self.norm is not None:
- output = self.norm(output)
-
- return layer_states, output
-
output = src
for mod in self.layers:
output = mod(
@@ -180,79 +124,25 @@ class TransformerEncoderLayer(nn.Module):
d_model: int,
nhead: int,
dim_feedforward: int = 2048,
- dropout: float = 0.1,
- activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
batch_first: bool = False,
norm_first: bool = False,
device=None,
dtype=None,
- linear1_self_attention_cls: nn.Module = nn.Linear,
- linear2_self_attention_cls: nn.Module = nn.Linear,
- linear1_feedforward_cls: nn.Module = nn.Linear,
- linear2_feedforward_cls: nn.Module = nn.Linear,
- layer_norm_cls: nn.Module = LayerNorm,
layer_norm_eps: float = 1e-5,
- adaptive_layer_norm=False,
) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super(TransformerEncoderLayer, self).__init__()
- # print(233333333333,d_model,nhead)
- # import os
- # os._exit(2333333)
self.self_attn = MultiheadAttention(
- d_model, # 512 16
+ d_model,
nhead,
- dropout=dropout,
batch_first=batch_first,
- linear1_cls=linear1_self_attention_cls,
- linear2_cls=linear2_self_attention_cls,
**factory_kwargs,
)
-
- # Implementation of Feedforward model
- self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward, **factory_kwargs)
- self.dropout = nn.Dropout(dropout)
- self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model, **factory_kwargs)
-
+ self.linear1 = nn.Linear(d_model, dim_feedforward, **factory_kwargs)
+ self.linear2 = nn.Linear(dim_feedforward, d_model, **factory_kwargs)
self.norm_first = norm_first
- self.dropout1 = nn.Dropout(dropout)
- self.dropout2 = nn.Dropout(dropout)
-
- # Legacy string support for activation function.
- if isinstance(activation, str):
- activation = _get_activation_fn(activation)
- elif isinstance(activation, partial):
- activation = activation(d_model)
- elif activation == BalancedDoubleSwish:
- activation = BalancedDoubleSwish(d_model)
-
- # # We can't test self.activation in forward() in TorchScript,
- # # so stash some information about it instead.
- # if activation is F.relu or isinstance(activation, torch.nn.ReLU):
- # self.activation_relu_or_gelu = 1
- # elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
- # self.activation_relu_or_gelu = 2
- # else:
- # self.activation_relu_or_gelu = 0
- self.activation = activation
-
- norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
- if layer_norm_cls == IdentityNorm:
- norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
- else:
- norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
-
- if adaptive_layer_norm:
- self.norm1 = AdaptiveLayerNorm(d_model, norm1)
- self.norm2 = AdaptiveLayerNorm(d_model, norm2)
- else:
- self.norm1 = norm1
- self.norm2 = norm2
-
- def __setstate__(self, state):
- super(TransformerEncoderLayer, self).__setstate__(state)
- if not hasattr(self, "activation"):
- self.activation = F.relu
+ self.norm1 = LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
+ self.norm2 = LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
def forward(
self,
@@ -309,10 +199,6 @@ class TransformerEncoderLayer(nn.Module):
key_padding_mask: Optional[Tensor],
cache=None,
) -> Tensor:
- # print(x.shape,attn_mask.shape,key_padding_mask)
- # torch.Size([1, 188, 512]) torch.Size([188, 188]) None
- # import os
- # os._exit(23333)
x = self.self_attn(
x,
x,
@@ -322,41 +208,8 @@ class TransformerEncoderLayer(nn.Module):
need_weights=False,
cache=cache,
)[0]
- return self.dropout1(x)
+ return x
# feed forward block
def _ff_block(self, x: Tensor) -> Tensor:
- x = self.linear2(self.dropout(self.activation(self.linear1(x))))
- return self.dropout2(x)
-
-
-class AdaptiveLayerNorm(nn.Module):
- r"""Adaptive Layer Normalization"""
-
- def __init__(self, d_model, norm) -> None:
- super(AdaptiveLayerNorm, self).__init__()
- self.project_layer = nn.Linear(d_model, 2 * d_model)
- self.norm = norm
- self.d_model = d_model
- self.eps = self.norm.eps
-
- def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
- if isinstance(input, tuple):
- input, embedding = input
- weight, bias = torch.split(
- self.project_layer(embedding),
- split_size_or_sections=self.d_model,
- dim=-1,
- )
- return (weight * self.norm(input) + bias, embedding)
-
- weight, bias = torch.split(
- self.project_layer(embedding),
- split_size_or_sections=self.d_model,
- dim=-1,
- )
- return weight * self.norm(input) + bias
-
-
-def _get_clones(module, N):
- return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
+ return self.linear2(F.relu(self.linear1(x)))
diff --git a/GPT_SoVITS/AR/modules/transformer_onnx.py b/GPT_SoVITS/AR/modules/transformer_onnx.py
deleted file mode 100644
index fa170254..00000000
--- a/GPT_SoVITS/AR/modules/transformer_onnx.py
+++ /dev/null
@@ -1,281 +0,0 @@
-# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
-import copy
-import numbers
-from functools import partial
-from typing import Any
-from typing import Callable
-from typing import List
-from typing import Optional
-from typing import Tuple
-from typing import Union
-
-import torch
-from AR.modules.activation_onnx import MultiheadAttention
-from AR.modules.scaling import BalancedDoubleSwish
-from torch import nn
-from torch import Tensor
-from torch.nn import functional as F
-
-_shape_t = Union[int, List[int], torch.Size]
-
-
-class LayerNorm(nn.Module):
- __constants__ = ["normalized_shape", "eps", "elementwise_affine"]
- normalized_shape: Tuple[int, ...]
- eps: float
- elementwise_affine: bool
-
- def __init__(
- self,
- normalized_shape: _shape_t,
- eps: float = 1e-5,
- elementwise_affine: bool = True,
- device=None,
- dtype=None,
- ) -> None:
- factory_kwargs = {"device": device, "dtype": dtype}
- super(LayerNorm, self).__init__()
- if isinstance(normalized_shape, numbers.Integral):
- # mypy error: incompatible types in assignment
- normalized_shape = (normalized_shape,) # type: ignore[assignment]
- self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type]
- self.eps = eps
- self.elementwise_affine = elementwise_affine
- if self.elementwise_affine:
- self.weight = nn.Parameter(torch.empty(self.normalized_shape, **factory_kwargs))
- self.bias = nn.Parameter(torch.empty(self.normalized_shape, **factory_kwargs))
- else:
- self.register_parameter("weight", None)
- self.register_parameter("bias", None)
-
- self.reset_parameters()
-
- def reset_parameters(self) -> None:
- if self.elementwise_affine:
- nn.init.ones_(self.weight)
- nn.init.zeros_(self.bias)
-
- def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
- if isinstance(input, tuple):
- input, embedding = input
- return (
- F.layer_norm(
- input,
- self.normalized_shape,
- self.weight,
- self.bias,
- self.eps,
- ),
- embedding,
- )
-
- assert embedding is None
- return F.layer_norm(input, self.normalized_shape, self.weight, self.bias, self.eps)
-
- def extra_repr(self) -> str:
- return "{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}".format(**self.__dict__)
-
-
-class IdentityNorm(nn.Module):
- def __init__(
- self,
- d_model: int,
- eps: float = 1e-5,
- device=None,
- dtype=None,
- ) -> None:
- super(IdentityNorm, self).__init__()
-
- def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
- if isinstance(input, tuple):
- return input
-
- assert embedding is None
- return input
-
-
-class TransformerEncoder(nn.Module):
- r"""TransformerEncoder is a stack of N encoder layers. Users can build the
- BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
-
- Args:
- encoder_layer: an instance of the TransformerEncoderLayer() class (required).
- num_layers: the number of sub-encoder-layers in the encoder (required).
- norm: the layer normalization component (optional).
- enable_nested_tensor: if True, input will automatically convert to nested tensor
- (and convert back on output). This will improve the overall performance of
- TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
-
- Examples::
- >>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
- >>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
- >>> src = torch.rand(10, 32, 512)
- >>> out = transformer_encoder(src)
- """
-
- __constants__ = ["norm"]
-
- def __init__(self, encoder_layer, num_layers, norm=None):
- super(TransformerEncoder, self).__init__()
- self.layers = _get_clones(encoder_layer, num_layers)
- self.num_layers = num_layers
- self.norm = norm
-
- def forward(
- self,
- src: Tensor,
- mask: Optional[Tensor] = None,
- src_key_padding_mask: Optional[Tensor] = None,
- return_layer_states: bool = False,
- cache=None,
- ) -> Tensor:
- output = src
- for mod in self.layers:
- output = mod(
- output,
- src_mask=mask,
- src_key_padding_mask=src_key_padding_mask,
- cache=cache,
- )
-
- if self.norm is not None:
- output = self.norm(output)
-
- return output
-
-
-class TransformerEncoderLayer(nn.Module):
- __constants__ = ["batch_first", "norm_first"]
-
- def __init__(
- self,
- d_model: int,
- nhead: int,
- dim_feedforward: int = 2048,
- dropout: float = 0.1,
- activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
- batch_first: bool = False,
- norm_first: bool = False,
- device=None,
- dtype=None,
- linear1_self_attention_cls: nn.Module = nn.Linear,
- linear2_self_attention_cls: nn.Module = nn.Linear,
- linear1_feedforward_cls: nn.Module = nn.Linear,
- linear2_feedforward_cls: nn.Module = nn.Linear,
- layer_norm_cls: nn.Module = LayerNorm,
- layer_norm_eps: float = 1e-5,
- adaptive_layer_norm=False,
- ) -> None:
- factory_kwargs = {"device": device, "dtype": dtype}
- super(TransformerEncoderLayer, self).__init__()
- self.self_attn = MultiheadAttention(
- d_model, # 512 16
- nhead,
- dropout=dropout,
- batch_first=batch_first,
- linear1_cls=linear1_self_attention_cls,
- linear2_cls=linear2_self_attention_cls,
- **factory_kwargs,
- )
- self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward, **factory_kwargs)
- self.dropout = nn.Dropout(dropout)
- self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model, **factory_kwargs)
- self.norm_first = norm_first
- self.dropout1 = nn.Dropout(dropout)
- self.dropout2 = nn.Dropout(dropout)
- if isinstance(activation, str):
- activation = _get_activation_fn(activation)
- elif isinstance(activation, partial):
- activation = activation(d_model)
- elif activation == BalancedDoubleSwish:
- activation = BalancedDoubleSwish(d_model)
- self.activation = activation
-
- norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
- if layer_norm_cls == IdentityNorm:
- norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
- else:
- norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
-
- if adaptive_layer_norm:
- self.norm1 = AdaptiveLayerNorm(d_model, norm1)
- self.norm2 = AdaptiveLayerNorm(d_model, norm2)
- else:
- self.norm1 = norm1
- self.norm2 = norm2
-
- def __setstate__(self, state):
- super(TransformerEncoderLayer, self).__setstate__(state)
- if not hasattr(self, "activation"):
- self.activation = F.relu
-
- def forward(
- self,
- src: Tensor,
- src_mask: Optional[Tensor] = None,
- src_key_padding_mask: Optional[Tensor] = None,
- cache=None,
- ) -> Tensor:
- x = src
- stage_embedding = None
- x = self.norm1(
- x + self._sa_block(x, src_mask, src_key_padding_mask, cache=cache),
- stage_embedding,
- )
- x = self.norm2(x + self._ff_block(x), stage_embedding)
-
- return x
-
- def _sa_block(
- self,
- x: Tensor,
- attn_mask: Optional[Tensor],
- key_padding_mask: Optional[Tensor],
- cache=None,
- ) -> Tensor:
- x = self.self_attn(
- x,
- x,
- x,
- attn_mask=attn_mask,
- key_padding_mask=key_padding_mask,
- need_weights=False,
- cache=cache,
- )
- return self.dropout1(x)
-
- def _ff_block(self, x: Tensor) -> Tensor:
- x = self.linear2(self.dropout(self.activation(self.linear1(x))))
- return self.dropout2(x)
-
-
-class AdaptiveLayerNorm(nn.Module):
- r"""Adaptive Layer Normalization"""
-
- def __init__(self, d_model, norm) -> None:
- super(AdaptiveLayerNorm, self).__init__()
- self.project_layer = nn.Linear(d_model, 2 * d_model)
- self.norm = norm
- self.d_model = d_model
- self.eps = self.norm.eps
-
- def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
- if isinstance(input, tuple):
- input, embedding = input
- weight, bias = torch.split(
- self.project_layer(embedding),
- split_size_or_sections=self.d_model,
- dim=-1,
- )
- return (weight * self.norm(input) + bias, embedding)
-
- weight, bias = torch.split(
- self.project_layer(embedding),
- split_size_or_sections=self.d_model,
- dim=-1,
- )
- return weight * self.norm(input) + bias
-
-
-def _get_clones(module, N):
- return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
diff --git a/GPT_SoVITS/AR/text_processing/__init__.py b/GPT_SoVITS/AR/text_processing/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/GPT_SoVITS/AR/text_processing/phonemizer.py b/GPT_SoVITS/AR/text_processing/phonemizer.py
deleted file mode 100644
index 1003040e..00000000
--- a/GPT_SoVITS/AR/text_processing/phonemizer.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/text_processing/phonemizer.py
-# reference: https://github.com/lifeiteng/vall-e
-import itertools
-import re
-from typing import Dict
-from typing import List
-
-import regex
-from gruut import sentences
-from gruut.const import Sentence
-from gruut.const import Word
-from AR.text_processing.symbols import SYMBOL_TO_ID
-
-
-class GruutPhonemizer:
- def __init__(self, language: str):
- self._phonemizer = sentences
- self.lang = language
- self.symbol_to_id = SYMBOL_TO_ID
- self._special_cases_dict: Dict[str] = {
- r"\.\.\.": "... ",
- ";": "; ",
- ":": ": ",
- ",": ", ",
- r"\.": ". ",
- "!": "! ",
- r"\?": "? ",
- "—": "—",
- "…": "… ",
- "«": "«",
- "»": "»",
- }
- self._punctuation_regexp: str = rf"([{''.join(self._special_cases_dict.keys())}])"
-
- def _normalize_punctuation(self, text: str) -> str:
- text = regex.sub(rf"\pZ+{self._punctuation_regexp}", r"\1", text)
- text = regex.sub(rf"{self._punctuation_regexp}(\pL)", r"\1 \2", text)
- text = regex.sub(r"\pZ+", r" ", text)
- return text.strip()
-
- def _convert_punctuation(self, word: Word) -> str:
- if not word.phonemes:
- return ""
- if word.phonemes[0] in ["‖", "|"]:
- return word.text.strip()
-
- phonemes = "".join(word.phonemes)
- # remove modifier characters ˈˌː with regex
- phonemes = re.sub(r"[ˈˌː͡]", "", phonemes)
- return phonemes.strip()
-
- def phonemize(self, text: str, espeak: bool = False) -> str:
- text_to_phonemize: str = self._normalize_punctuation(text)
- sents: List[Sentence] = [sent for sent in self._phonemizer(text_to_phonemize, lang="en-us", espeak=espeak)]
- words: List[str] = [self._convert_punctuation(word) for word in itertools.chain(*sents)]
- return " ".join(words)
-
- def transform(self, phonemes):
- # convert phonemes to ids
- # dictionary is in symbols.py
- return [self.symbol_to_id[p] for p in phonemes if p in self.symbol_to_id.keys()]
-
-
-if __name__ == "__main__":
- phonemizer = GruutPhonemizer("en-us")
- # text -> IPA
- phonemes = phonemizer.phonemize("Hello, wor-ld ?")
- print("phonemes:", phonemes)
- print("len(phonemes):", len(phonemes))
- phoneme_ids = phonemizer.transform(phonemes)
- print("phoneme_ids:", phoneme_ids)
- print("len(phoneme_ids):", len(phoneme_ids))
diff --git a/GPT_SoVITS/AR/text_processing/symbols.py b/GPT_SoVITS/AR/text_processing/symbols.py
deleted file mode 100644
index f7ef57fa..00000000
--- a/GPT_SoVITS/AR/text_processing/symbols.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/text_processing/symbols.py
-# reference: https://github.com/lifeiteng/vall-e
-PAD = "_"
-PUNCTUATION = ';:,.!?¡¿—…"«»“” '
-LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
-IPA_LETTERS = (
- "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
-)
-SYMBOLS = [PAD] + list(PUNCTUATION) + list(LETTERS) + list(IPA_LETTERS)
-SPACE_ID = SYMBOLS.index(" ")
-SYMBOL_TO_ID = {s: i for i, s in enumerate(SYMBOLS)}
-ID_TO_SYMBOL = {i: s for i, s in enumerate(SYMBOLS)}
diff --git a/GPT_SoVITS/AR/utils/__init__.py b/GPT_SoVITS/AR/utils/__init__.py
deleted file mode 100644
index 4a9cb4d5..00000000
--- a/GPT_SoVITS/AR/utils/__init__.py
+++ /dev/null
@@ -1,36 +0,0 @@
-import re
-
-
-def str2bool(str):
- return True if str.lower() == "true" else False
-
-
-def get_newest_ckpt(string_list):
- # 定义一个正则表达式模式,用于匹配字符串中的数字
- pattern = r"epoch=(\d+)-step=(\d+)\.ckpt"
-
- # 使用正则表达式提取每个字符串中的数字信息,并创建一个包含元组的列表
- extracted_info = []
- for string in string_list:
- match = re.match(pattern, string)
- if match:
- epoch = int(match.group(1))
- step = int(match.group(2))
- extracted_info.append((epoch, step, string))
- # 按照 epoch 后面的数字和 step 后面的数字进行排序
- sorted_info = sorted(extracted_info, key=lambda x: (x[0], x[1]), reverse=True)
- # 获取最新的 ckpt 文件名
- newest_ckpt = sorted_info[0][2]
- return newest_ckpt
-
-
-# 文本存在且不为空时 return True
-def check_txt_file(file_path):
- try:
- with open(file_path, "r") as file:
- text = file.readline().strip()
- assert text.strip() != ""
- return text
- except Exception:
- return False
- return False
diff --git a/GPT_SoVITS/AR/utils/initialize.py b/GPT_SoVITS/AR/utils/initialize.py
deleted file mode 100644
index ee7c7138..00000000
--- a/GPT_SoVITS/AR/utils/initialize.py
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env python3
-"""Initialize modules for espnet2 neural networks."""
-
-import torch
-from typeguard import check_argument_types
-
-
-def initialize(model: torch.nn.Module, init: str):
- """Initialize weights of a neural network module.
-
- Parameters are initialized using the given method or distribution.
-
- Custom initialization routines can be implemented into submodules
- as function `espnet_initialization_fn` within the custom module.
-
- Args:
- model: Target.
- init: Method of initialization.
- """
- assert check_argument_types()
- print("init with", init)
-
- # weight init
- for p in model.parameters():
- if p.dim() > 1:
- if init == "xavier_uniform":
- torch.nn.init.xavier_uniform_(p.data)
- elif init == "xavier_normal":
- torch.nn.init.xavier_normal_(p.data)
- elif init == "kaiming_uniform":
- torch.nn.init.kaiming_uniform_(p.data, nonlinearity="relu")
- elif init == "kaiming_normal":
- torch.nn.init.kaiming_normal_(p.data, nonlinearity="relu")
- else:
- raise ValueError("Unknown initialization: " + init)
- # bias init
- for name, p in model.named_parameters():
- if ".bias" in name and p.dim() == 1:
- p.data.zero_()
diff --git a/GPT_SoVITS/AR/utils/io.py b/GPT_SoVITS/AR/utils/io.py
deleted file mode 100644
index a6475cb6..00000000
--- a/GPT_SoVITS/AR/utils/io.py
+++ /dev/null
@@ -1,30 +0,0 @@
-import sys
-
-import torch
-import yaml
-
-
-def load_yaml_config(path):
- with open(path) as f:
- config = yaml.full_load(f)
- return config
-
-
-def save_config_to_yaml(config, path):
- assert path.endswith(".yaml")
- with open(path, "w") as f:
- f.write(yaml.dump(config))
- f.close()
-
-
-def write_args(args, path):
- args_dict = dict((name, getattr(args, name)) for name in dir(args) if not name.startswith("_"))
- with open(path, "a") as args_file:
- args_file.write("==> torch version: {}\n".format(torch.__version__))
- args_file.write("==> cudnn version: {}\n".format(torch.backends.cudnn.version()))
- args_file.write("==> Cmd:\n")
- args_file.write(str(sys.argv))
- args_file.write("\n==> args:\n")
- for k, v in sorted(args_dict.items()):
- args_file.write(" %s: %s\n" % (str(k), str(v)))
- args_file.close()
diff --git a/GPT_SoVITS/Accel/MLX/AR/backends/mlx_static.py b/GPT_SoVITS/Accel/MLX/AR/backends/mlx_static.py
deleted file mode 100644
index 16502649..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/backends/mlx_static.py
+++ /dev/null
@@ -1,130 +0,0 @@
-from __future__ import annotations
-
-import mlx.core as mx
-
-from ..structs_mlx import KVCache
-from ..t2s_model_abc_mlx import (
- AttentionABC,
- KVCacheHND,
- T2SDecoderABC,
- TransformerBlockABC,
- TransformerDecoderABC,
-)
-
-
-Array = mx.array
-
-
-class Attention(AttentionABC):
- def __init__(self, n_head: int, hidden_dim: int, max_seq_length: int):
- super().__init__(n_head, hidden_dim, max_seq_length)
- self.kv_class = KVCacheHND
-
- def __call__(self, x: Array, input_pos: Array, max_idx: int, kv_cache: KVCache, attn_mask: Array):
- bsz, seqlen, _ = x.shape
-
- qkv = self.in_proj(x)
-
- q, k, v = mx.split(qkv, 3, -1)
-
- q = q.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
- k = k.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
- v = v.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
-
- kv_cache = self.kv_class.update_cache(input_pos, k, v, kv_cache)
-
- k, v = kv_cache
-
- attn = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale, mask=attn_mask)
-
- attn = attn.transpose(0, 2, 1, 3).reshape(bsz, seqlen, -1)
-
- attn = self.out_proj(attn)
-
- return attn
-
-
-class TransformerBlock(TransformerBlockABC):
- def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
- super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
-
- self.attention = Attention(n_head, hidden_dim, max_seq_length)
-
-
-class TransformerDecoder(TransformerDecoderABC):
- def __init__(
- self,
- hidden_dim: int,
- n_layer: int,
- n_head: int,
- ffn_dim: int,
- vocab_size: int,
- max_seq_length: int,
- max_batch_size: int,
- ) -> None:
- super().__init__(
- hidden_dim,
- n_layer,
- n_head,
- ffn_dim,
- vocab_size,
- max_seq_length,
- max_batch_size,
- )
-
- self.layers = [
- TransformerBlock(
- n_head,
- ffn_dim,
- hidden_dim,
- max_seq_length,
- )
- for _ in range(n_layer)
- ]
-
-
-class T2SDecoder(T2SDecoderABC):
- def __init__(
- self,
- config: dict,
- max_seq_length: int = 1024,
- max_batch_size: int = 10,
- ) -> None:
- super().__init__(config, max_seq_length, max_batch_size)
-
- self.h = TransformerDecoder(
- self.hidden_dim, self.n_layer, self.n_head, self.ffn_dim, self.vocab_size, max_seq_length, max_batch_size
- )
-
- self.kv_class = KVCacheHND
-
- self.extra_buffer_factory = lambda max_bs, dec: {
- "attn_mask": mx.zeros((max_bs, dec.n_head, 1, dec.max_seq_length), dtype=mx.bool_)
- }
-
- def pre_forward_slots_hook(self, slots, runner):
- attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
- max_idx = runner.input_pos_buf[slots].long().max().item()
- return {"attn_mask": attn_mask_buf[slots], "max_idx": max_idx}
-
- def post_forward_slots_hook(self, slots, runner) -> None:
- attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
- pos = runner.input_pos_buf[slots].long()
- attn_mask_buf[slots, :, :, pos] = True
-
- def bind_session_hook(self, session, runner) -> None:
- slots = session.slot_indices
-
- prefill_len = session.prefill_len
- bsz = session.bsz
-
- range_tensor = mx.arange(self.max_seq_length).reshape(1, 1, 1, self.max_seq_length)
- prefill_len_expanded = prefill_len.reshape(bsz, 1, 1, 1)
- attn_mask = range_tensor < prefill_len_expanded
-
- runner.extra_buffers["attn_mask_buf"][slots] = attn_mask
-
- def unbind_session_hook(self, session, runner) -> None:
- slots = session.slot_indices
- attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
- attn_mask_buf[slots] = 0
diff --git a/GPT_SoVITS/Accel/MLX/AR/backends/mlx_varlen.py b/GPT_SoVITS/Accel/MLX/AR/backends/mlx_varlen.py
deleted file mode 100644
index 21381051..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/backends/mlx_varlen.py
+++ /dev/null
@@ -1,99 +0,0 @@
-from __future__ import annotations
-
-import mlx.core as mx
-
-from ..structs_mlx import KVCache
-from ..t2s_model_abc_mlx import (
- AttentionABC,
- KVCacheHND,
- T2SDecoderABC,
- TransformerBlockABC,
- TransformerDecoderABC,
-)
-
-
-Array = mx.array
-
-
-class Attention(AttentionABC):
- def __init__(self, n_head: int, hidden_dim: int, max_seq_length: int):
- super().__init__(n_head, hidden_dim, max_seq_length)
- self.kv_class = KVCacheHND
-
- def __call__(self, x: Array, input_pos: Array, max_idx: int, kv_cache: KVCache, attn_mask: Array):
- bsz, seqlen, _ = x.shape
-
- q, k, v = self.in_proj(x).split(3, axis=-1)
-
- q, k, v = map(lambda x: x.reshape(bsz, seqlen, self.n_head, self.head_dim), (q, k, v))
-
- q, k, v = map(lambda x: x.swapaxes(1, 2), (q, k, v))
-
- kv_cache = self.kv_class.update_cache(input_pos, k, v, kv_cache)
-
- q, k, v = map(lambda x: x[..., :max_idx, :], (q, *kv_cache))
-
- mask = attn_mask[..., :max_idx]
-
- attn = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale, mask=mask)
-
- attn = attn.swapaxes(1, 2).reshape(bsz, seqlen, -1)
-
- attn = self.out_proj(attn)
-
- return attn
-
-
-class TransformerBlock(TransformerBlockABC):
- def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
- super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
-
- self.attention = Attention(n_head, hidden_dim, max_seq_length)
-
-
-class TransformerDecoder(TransformerDecoderABC):
- def __init__(
- self,
- hidden_dim: int,
- n_layer: int,
- n_head: int,
- ffn_dim: int,
- vocab_size: int,
- max_seq_length: int,
- max_batch_size: int,
- ) -> None:
- super().__init__(
- hidden_dim,
- n_layer,
- n_head,
- ffn_dim,
- vocab_size,
- max_seq_length,
- max_batch_size,
- )
-
- self.layers = [
- TransformerBlock(
- n_head,
- ffn_dim,
- hidden_dim,
- max_seq_length,
- )
- for _ in range(n_layer)
- ]
-
-
-class T2SDecoder(T2SDecoderABC):
- def __init__(
- self,
- config: dict,
- max_seq_length: int = 1024,
- max_batch_size: int = 10,
- ) -> None:
- super().__init__(config, max_seq_length, max_batch_size)
-
- self.h = TransformerDecoder(
- self.hidden_dim, self.n_layer, self.n_head, self.ffn_dim, self.vocab_size, max_seq_length, max_batch_size
- )
-
- self.kv_class = KVCacheHND
diff --git a/GPT_SoVITS/Accel/MLX/AR/runner_mlx.py b/GPT_SoVITS/Accel/MLX/AR/runner_mlx.py
deleted file mode 100644
index 3ce065f4..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/runner_mlx.py
+++ /dev/null
@@ -1,324 +0,0 @@
-from __future__ import annotations
-
-import os
-import time
-from collections import deque
-from collections.abc import MutableSequence
-from typing import Optional, TypeVar
-
-import mlx.core as mx
-import torch
-
-from ...logger import timer
-
-from .sample_funcs_mlx import sample_naive_mlx as sample_naive
-from .structs_mlx import KVCache, T2SRequest, T2SSessionMLX as T2SSession
-from .t2s_model_abc_mlx import T2SDecoderABC
-
-
-T = TypeVar("T")
-Array = mx.array
-
-
-def _slice_arrays(obj: T, bsz: int) -> T:
- if isinstance(obj, Array):
- if obj.ndim > 0 and obj.shape[0] >= bsz:
- return obj[:bsz] # type: ignore
- return obj # type: ignore
- if isinstance(obj, list):
- return [_slice_arrays(o, bsz) for o in obj] # type: ignore
- if isinstance(obj, tuple):
- return tuple(_slice_arrays(o, bsz) for o in obj) # type: ignore
- if isinstance(obj, dict):
- return {k: _slice_arrays(v, bsz) for k, v in obj.items()} # type: ignore
- return obj
-
-
-def _synchronize_device(device: torch.device) -> None:
- device_type = device.type
- if device_type == "cuda":
- torch.cuda.synchronize()
- elif device_type == "mps":
- torch.mps.synchronize()
- elif device_type == "xpu":
- torch.xpu.synchronize()
- elif device_type == "mtia":
- torch.mtia.synchronize()
- elif device_type == "cpu":
- pass
-
-
-class ModelRunner:
- """Model-side executor handling prefill, decode"""
-
- def __init__(
- self,
- decoder: T2SDecoderABC,
- device: mx.Device,
- dtype: mx.Dtype,
- waiting_bind: deque[T2SSession],
- ):
- self.max_batch_size = decoder.max_batch_size
-
- self.decoder = decoder
- self.device = device
- self.dtype = dtype
-
- self.waiting_bind: deque[T2SSession] = waiting_bind
- self.slot_sessions: list[Optional[T2SSession]] = [None] * decoder.max_batch_size
- self.session_slots: dict[int, list[int]] = {}
- self.bound_sessions: list[T2SSession] = []
- self.sampler = sample_naive()
-
- extra_buffer_factory = decoder.extra_buffer_factory
- is_applicable = decoder.graph_applicable
-
- cuda_ok = (
- torch.cuda.is_available() and torch.version.cuda is not None and os.environ.get("CUDAGraph", "1") != "0"
- )
- self.graph_applicable = bool(cuda_ok and is_applicable)
-
- dtype_bias = decoder.bert_proj.bias.dtype
-
- # Shared runtime buffers for both eager and graph replay
- self.xy_pos_buf = mx.zeros((self.max_batch_size, 1, decoder.embedding_dim), dtype=dtype_bias)
- self.xy_dec_buf = mx.zeros_like(self.xy_pos_buf)
- self.input_pos_buf = mx.zeros((self.max_batch_size,), dtype=mx.int32)
- self.kv_cache_buf: MutableSequence[KVCache] = decoder.init_cache(self.max_batch_size)
-
- self.step_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
- self.prefill_len_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
- self.x_len_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
- self.prompt_len_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
- self.max_step_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
- self.completed_buf = mx.zeros((self.max_batch_size), dtype=mx.bool_)
- self.y_buf = mx.full((self.max_batch_size, decoder.max_seq_length), decoder.EOS, dtype=mx.int32)
-
- self.top_k_buf = mx.zeros(self.max_batch_size, dtype=mx.int32)
- self.top_p_buf = mx.zeros(self.max_batch_size, dtype=mx.float32)
- self.temperature_buf = mx.zeros(self.max_batch_size, dtype=mx.float32)
- self.repetition_penalty_buf = mx.zeros(self.max_batch_size, dtype=mx.float32)
-
- self.extra_buffers = extra_buffer_factory(self.max_batch_size, decoder)
-
- def prefill(self, request: T2SRequest) -> T2SSession:
- if len(request.x) > self.decoder.max_batch_size:
- raise ValueError(
- f"Request batch size {len(request.x)} exceeds decoder max batch size {self.decoder.max_batch_size}"
- )
-
- session = T2SSession(
- self.decoder,
- request,
- device=self.device,
- dtype=self.dtype,
- )
-
- kv_cache = self.decoder.init_cache(session.bsz)
-
- with timer("MLX.Prefill", debug=request.debug):
- xy_pos = self.decoder.embed(session.x, session.request.prompts, session.bert_feature)
- xy_dec = self.decoder.h.prefill(xy_pos, kv_cache, session.attn_mask)
- session.prefill_hidden = mx.take_along_axis(xy_dec, session.input_pos - 1, axis=1)
-
- session.kv_cache = kv_cache
-
- session.start_time = time.perf_counter()
- session.total_tokens = 0
- return session
-
- def free_slots(self) -> int:
- return sum(1 for s in self.slot_sessions if s is None)
-
- def _bind_waiting_sessions(self) -> None:
- while self.waiting_bind and self.free_slots() >= self.waiting_bind[0].bsz:
- session = self.waiting_bind[0]
- if self.bind_session(session):
- self.waiting_bind.popleft()
- else:
- break
-
- def _assign_slots(self, bsz: int) -> Optional[list[int]]:
- indices = [i for i, s in enumerate(self.slot_sessions) if s is None]
- if len(indices) < bsz:
- return None
- return indices[:bsz]
-
- def bind_session(self, session: T2SSession) -> bool:
- slots = self._assign_slots(session.bsz)
- if slots is None:
- return False
-
- for slot_idx in slots:
- self.slot_sessions[slot_idx] = session
-
- idx_array = mx.array(slots, dtype=mx.int64)
- take = slice(0, len(slots))
-
- # Input pos and step
- mx.put_along_axis(self.input_pos_buf, idx_array, session.input_pos[take], axis=0)
- self.step_buf[idx_array] = 0
-
- # Prefill hidden goes straight into xy_dec buffer
- mx.put_along_axis(self.xy_dec_buf, idx_array, session.prefill_hidden[take], axis=0)
-
- # KV Cache
- for (k_buf, v_buf), (k_src, v_src) in zip(self.kv_cache_buf, session.kv_cache):
- mx.put_along_axis(k_buf, idx_array, k_src[take], axis=0)
- mx.put_along_axis(v_buf, idx_array, v_src[take], axis=0)
-
- # Sampling params
- self.top_k_buf[idx_array] = session.request.top_k
- self.top_p_buf[idx_array] = session.request.top_p
- self.temperature_buf[idx_array] = session.request.temperature
- self.repetition_penalty_buf[idx_array] = session.request.repetition_penalty
- mx.put_along_axis(self.prefill_len_buf, idx_array, session.prefill_len[take], axis=0)
- mx.put_along_axis(self.x_len_buf, idx_array, session.x_lens[take], axis=0)
- self.prompt_len_buf[idx_array] = session.prompt_len
- max_steps = (
- session.max_decode_steps
- if session.request.early_stop_num == -1
- else min(session.max_decode_steps, session.request.early_stop_num)
- )
- self.max_step_buf[idx_array] = max_steps
- self.completed_buf[idx_array] = False
-
- # Token buffer
- self.y_buf[idx_array] = self.decoder.EOS
- self.y_buf[idx_array, : session.prompt_len] = session.y
-
- self.session_slots[session.id] = slots
- session.slot_indices = slots
- self.decoder.bind_session_hook(session, self)
- self.bound_sessions.append(session)
-
- return True
-
- def unbind_session(self, session: T2SSession) -> None:
- slots = self.session_slots.pop(session.id, [])
- for slot_idx in slots:
- self.slot_sessions[slot_idx] = None
- self.input_pos_buf[slots] = 0
- self.step_buf[slots] = 0
- self.completed_buf[slots] = False
- self.decoder.unbind_session_hook(session, self)
- if session in self.bound_sessions:
- self.bound_sessions.remove(session)
-
- def decode_step(self) -> list[T2SSession]:
- if not self.bound_sessions and not self.waiting_bind:
- return []
-
- decoder = self.decoder
- finished_sessions: list[T2SSession] = []
-
- forward_slots: list[int] = []
- prefill_slots: list[int] = []
- for slot_idx, session in enumerate(self.slot_sessions):
- if session is None:
- continue
- if self.step_buf[slot_idx].item() != 0:
- forward_slots.append(slot_idx)
-
- debug = any(session.request.debug for session in self.bound_sessions)
-
- try:
- if forward_slots:
- kwds = decoder.pre_forward_slots_hook(forward_slots, self)
- forward_len = max(forward_slots) + 1
- self.xy_dec_buf[:forward_len] = decoder.h(
- self.xy_pos_buf[:forward_len],
- self.input_pos_buf[:forward_len],
- _slice_arrays(self.kv_cache_buf, forward_len),
- **kwds,
- )
-
- # Bind any newly ready sessions after decode and before sampling
- if self.waiting_bind and self.free_slots() > 0:
- self._bind_waiting_sessions()
- if not debug:
- debug = any(session.request.debug for session in self.bound_sessions)
-
- for slot_idx, session in enumerate(self.slot_sessions):
- if session is None:
- continue
- if session.step_count == 0:
- prefill_slots.append(slot_idx)
-
- active_slots = forward_slots + prefill_slots
- idx_array = mx.array(active_slots, dtype=mx.int32)
- if not active_slots:
- return []
-
- logits_all = decoder.ar_predict_layer(self.xy_dec_buf[idx_array].squeeze(1))
-
- first_step_mask = mx.equal(self.step_buf[idx_array], 0).astype(mx.bool_)
-
- if mx.any(first_step_mask):
- logits_all[first_step_mask, -1] = float("-inf")
-
- samples: Array = self.sampler(
- logits=logits_all,
- valid_lens=self.input_pos_buf[idx_array] + self.prefill_len_buf[idx_array],
- previous_tokens=self.y_buf[idx_array],
- repetition_penalty=self.repetition_penalty_buf[idx_array],
- temperature=self.temperature_buf[idx_array],
- top_k=self.top_k_buf[idx_array],
- top_p=self.top_p_buf[idx_array],
- )
-
- argmax_token = mx.argmax(logits_all, axis=-1)
- eos_mask_all = mx.logical_or(mx.equal(argmax_token, decoder.EOS), mx.equal(samples.squeeze(1), decoder.EOS))
-
- samples_clamp = samples[:]
- samples_clamp[samples_clamp >= decoder.vocab_size - 1] = decoder.vocab_size - 2
-
- y_emb_all = decoder.ar_audio_embedding(samples_clamp)
- pos_offset = self.step_buf[idx_array] + self.prefill_len_buf[idx_array]
- next_xy_all = decoder.ar_audio_position(pos_offset, y_emb_all)
-
- sample_vals = samples.squeeze(1)
- write_pos = self.prompt_len_buf[idx_array] + self.step_buf[idx_array]
-
- # Only write for slots that are not already done and not EOS
- write_mask = (~self.completed_buf[idx_array]) & (~eos_mask_all)
- if mx.any(write_mask):
- write_slots = idx_array[write_mask]
- self.y_buf[write_slots, write_pos[write_mask]] = sample_vals[write_mask]
- self.input_pos_buf[write_slots] += 1
-
- new_step = self.step_buf[idx_array]
- new_step[write_mask] += 1
- forced_stop = new_step >= self.max_step_buf[idx_array]
- self.step_buf[idx_array] = new_step
-
- self.completed_buf[idx_array] |= eos_mask_all | forced_stop
-
- # Update next xy for continuing slots
- continue_mask = ~(self.completed_buf[idx_array])
- if mx.any(continue_mask):
- cont_slots = idx_array[continue_mask]
- cont_xy = next_xy_all[continue_mask]
- self.xy_pos_buf[cont_slots] = cont_xy
-
- # Sync back
- for slots in list(self.session_slots.values()):
- if not slots:
- continue
- session = self.slot_sessions[slots[0]]
- if session is None:
- continue
- session_step = int(self.step_buf[slots[0]].item())
- session.step_count = session_step
- session.total_tokens = int(session_step * session.bsz)
- session.completed = self.completed_buf[slots]
- if bool(mx.all(session.completed)):
- finished_sessions.append(session)
- self.unbind_session(session)
-
- decoder.post_forward_slots_hook(forward_slots, self)
-
- finally:
- pass
-
- return finished_sessions
diff --git a/GPT_SoVITS/Accel/MLX/AR/sample_funcs_mlx.py b/GPT_SoVITS/Accel/MLX/AR/sample_funcs_mlx.py
deleted file mode 100644
index 8dc4f11f..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/sample_funcs_mlx.py
+++ /dev/null
@@ -1,132 +0,0 @@
-from functools import partial
-from typing import Protocol
-
-import mlx.core as mx
-
-
-Array = mx.array
-
-
-class SampleProtocolMLX(Protocol):
- @staticmethod
- def __call__(
- logits: Array,
- valid_lens: Array,
- previous_tokens: Array,
- repetition_penalty: Array,
- temperature: Array,
- top_k: Array,
- top_p: Array,
- ) -> Array: ...
-
-
-def apply_repetition_penalty(logits: Array, previous_tokens: Array, valid_lens: Array, repetition_penalty: Array):
- _, T = previous_tokens.shape
-
- arange_t = mx.arange(T).reshape(1, -1)
- valid_mask = arange_t < valid_lens.reshape(-1, 1)
-
- safe_tokens = mx.where(
- valid_mask,
- previous_tokens,
- mx.zeros_like(previous_tokens),
- ) # [B, T]
-
- # [B, T]
- score = mx.take_along_axis(logits, safe_tokens, axis=1)
-
- rp = repetition_penalty.reshape(-1, 1)
-
- score = mx.where(
- score < 0,
- score * rp,
- score / rp,
- )
-
- score = mx.where(
- valid_mask,
- score,
- mx.take_along_axis(logits, safe_tokens, axis=1),
- )
-
- logits = mx.put_along_axis(logits, safe_tokens, score, axis=1)
-
- return logits
-
-
-@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
-def apply_greedy_sampling(logits: Array):
- return mx.argmax(logits, axis=-1, keepdims=True).astype(mx.int32)
-
-
-@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
-def apply_temperature(logits: Array, temperature: Array, temp_mask: Array):
- temp = temperature[:]
- temp[temp_mask] = 1
- return logits / temp
-
-
-@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
-def apply_top_k(logits: Array, top_k: Array):
- sorted_logits = -mx.sort(-logits)
- pivot = mx.take_along_axis(
- sorted_logits,
- (top_k - 1).reshape(-1, 1),
- axis=1,
- )
- logits = mx.where(logits < pivot, -mx.inf, logits)
- return logits
-
-
-@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
-def apply_top_p(logits: Array, top_p: Array):
- sorted_indices = mx.argsort(-logits, axis=-1)
- sorted_logits = mx.take_along_axis(logits, sorted_indices, axis=-1)
- cum_probs = mx.cumsum(mx.softmax(sorted_logits, axis=-1), axis=-1)
- sorted_indices_to_remove = cum_probs > top_p
- sorted_indices_to_remove[:, -1] = False
- indices_to_remove = mx.zeros_like(logits).astype(mx.bool_)
- indices_to_remove = mx.put_along_axis(indices_to_remove, sorted_indices, sorted_indices_to_remove, axis=1)
- logits = mx.where(indices_to_remove, -mx.inf, logits)
- return logits
-
-
-@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
-def apply_sampling(logits: Array, greedy_mask: Array):
- gumbel_noise = mx.random.gumbel(shape=logits.shape, dtype=logits.dtype)
- idx_next = mx.argmax(logits + gumbel_noise, axis=-1, keepdims=True).astype(mx.int32)
-
- if mx.any(greedy_mask):
- idx_greedy = mx.argmax(logits, axis=-1, keepdims=True).astype(mx.int32)
- idx_next = mx.where(greedy_mask.reshape(-1, 1), idx_greedy, idx_next)
- return idx_next
-
-
-class sample_naive_mlx(SampleProtocolMLX):
- @partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
- @staticmethod
- def __call__(
- logits: Array,
- valid_lens: Array,
- previous_tokens: Array,
- repetition_penalty: Array,
- temperature: Array,
- top_k: Array,
- top_p: Array,
- ) -> Array:
- if mx.any(mx.not_equal(repetition_penalty, 1.0)):
- logits = apply_repetition_penalty(logits, previous_tokens, valid_lens, repetition_penalty)
-
- greedy_mask = temperature <= 1e-5
- temp_mask = (temperature < 1.0) & (~greedy_mask)
-
- if mx.any(temp_mask):
- logits = apply_temperature(logits, temperature, temp_mask)
-
- if mx.any(top_k < 1025):
- logits = apply_top_k(logits, top_k)
-
- if mx.any(top_p < 1.0):
- logits = apply_top_p(logits, top_p)
-
- return apply_sampling(logits, greedy_mask)
diff --git a/GPT_SoVITS/Accel/MLX/AR/structs_mlx.py b/GPT_SoVITS/Accel/MLX/AR/structs_mlx.py
deleted file mode 100644
index a46d1507..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/structs_mlx.py
+++ /dev/null
@@ -1,183 +0,0 @@
-"""
-Modified From https://github.com/XXXXRT666/GPT-SoVITS
-"""
-
-from __future__ import annotations
-
-from collections.abc import MutableSequence
-from dataclasses import dataclass
-from typing import Optional, Protocol, Union
-
-import mlx.core as mx
-from rich.progress import Progress, TaskID
-
-from ...PyTorch.AR.structs import T2SEngineProtocol, T2SRequest, T2SRequestHandle, T2SResult, T2SStreamResponse
-
-
-Array = mx.array
-
-
-@dataclass
-class T2SRequestMLX:
- x: list[Array]
- x_lens: Array
- prompts: Array
- bert_feature: list[Array]
- valid_length: int
- top_k: int = 5
- top_p: float = 1
- early_stop_num: int = -1
- temperature: float = 1.0
- repetition_penalty: float = 1.35
- request_id: Union[str, int] = -1
- stream_interval: Optional[int] = None
- return_partial: bool = True
- debug: bool = False
-
- @classmethod
- def from_torch(cls, request: T2SRequest) -> T2SRequestMLX:
- x = list(map(lambda tensor: mx.array(tensor.cpu()), request.x)) # type: ignore
- x_lens = mx.array(request.x_lens.cpu()) # type: ignore
- prompts = mx.array(request.prompts.cpu()) # type: ignore
- bert_feature = list(map(lambda tensor: mx.array(tensor.cpu()), request.bert_feature)) # type: ignore
-
- return cls(
- x,
- x_lens,
- prompts,
- bert_feature,
- request.valid_length,
- request.top_k,
- request.top_p,
- request.early_stop_num,
- request.temperature,
- request.repetition_penalty,
- request.debug,
- )
-
-
-KVCache = tuple[Array, ...]
-
-
-class KVCacheProtocol(Protocol):
- @staticmethod
- def empty(kv_cache: KVCache) -> None: ...
-
- @staticmethod
- def update_cache(input_pos: Array, k_val: Array, v_val: Array, kv_cache: KVCache) -> KVCache: ...
-
- @staticmethod
- def prefill_kv(k_val: Array, v_val: Array, kv_cache: KVCache) -> None: ...
-
- @staticmethod
- def init_cache(batch_size: int, max_seq_length: int, n_heads: int, head_dim: int, dtype: mx.Dtype) -> KVCache: ...
-
-
-class T2SDecoderProtocol(Protocol):
- max_seq_length: int
- EOS: int
- n_head: int
-
- def embed(self, x: list[Array], y: Array, bert_features: list[Array]) -> Array: ...
-
-
-cpu = mx.Device(mx.cpu)
-
-
-class T2SSessionMLX:
- def __init__(
- self,
- decoder: T2SDecoderProtocol,
- request_torch: T2SRequest,
- device: mx.Device = cpu,
- dtype: mx.Dtype = mx.float32,
- ):
- with mx.stream(device):
- request = T2SRequestMLX.from_torch(request_torch)
-
- self.decoder = decoder
- self.request = request
- self.device = device
- self.dtype = dtype
-
- bsz = len(request.x)
- prompt_len = request.prompts.shape[-1]
- self.bsz = bsz
-
- self.step_count = 0
- self.request_id = request.request_id or id(self)
- self.stream_interval = request.stream_interval if request.stream_interval is not None else 0
- self.last_stream_step = 0
-
- # Cache in prefill
- self.kv_cache: MutableSequence[KVCache]
-
- # Forward args
- self.x = [i.astype(mx.int32) for i in request.x]
- self.x_lens = request.x_lens.astype(mx.int32)
- self.y = request.prompts.astype(mx.int32)
- self.prompt_len = prompt_len
- self.bert_feature = [i.astype(dtype) for i in request.bert_feature]
-
- self.prefill_len = self.x_lens + request.prompts.shape[1]
-
- self.input_pos = mx.zeros_like(self.prefill_len)
- self.input_pos += self.prefill_len
- if bsz == 1:
- self.input_pos = self.input_pos.squeeze(0) # 30% Performance Improvement in bsz=1
-
- self.max_decode_steps = min(int(decoder.max_seq_length - int(self.input_pos.max().item())), 640)
- self.max_decode_steps = max(1, self.max_decode_steps)
-
- # EOS
- self.completed = mx.array([False] * len(self.x)).astype(mx.bool_)
- self.y_results: list[Array] = [None] * len(self.x) # type: ignore
-
- max_len = int(self.prefill_len.max(-1))
- attn_mask = mx.zeros(shape=(bsz, max_len, max_len), dtype=mx.bool_)
-
- for bs in range(bsz):
- pos = int(self.x_lens[bs])
- seq_len = pos + prompt_len
-
- attn_mask[bs, :seq_len, :pos] = True
-
- ar_mask = ~mx.triu(
- x=mx.ones(
- shape=(
- prompt_len,
- prompt_len,
- ),
- dtype=mx.bool_,
- ),
- k=1,
- )
- attn_mask[bs, pos:seq_len, pos:seq_len] = ar_mask
-
- attn_mask = mx.expand_dims(attn_mask, 1)
- self.attn_mask = attn_mask
-
- self.prefill_hidden: Array
-
- self.start_time: float = 0.0
- self.total_tokens: int = 0
-
- self.progress_task: Optional[TaskID] = None
- self.progress: Optional[Progress] = None
-
- self.id: int = id(self)
- self.slot_indices: list[int] = []
-
-
-__all__ = [
- "T2SRequestMLX",
- "T2SSessionMLX",
- "KVCache",
- "KVCacheProtocol",
- "T2SDecoderProtocol",
- "T2SEngineProtocol",
- "T2SRequest",
- "T2SRequestHandle",
- "T2SResult",
- "T2SStreamResponse",
-]
diff --git a/GPT_SoVITS/Accel/MLX/AR/t2s_engine_mlx.py b/GPT_SoVITS/Accel/MLX/AR/t2s_engine_mlx.py
deleted file mode 100644
index 2725a6c5..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/t2s_engine_mlx.py
+++ /dev/null
@@ -1,371 +0,0 @@
-from __future__ import annotations
-
-import os
-import threading
-import time
-import traceback
-from collections import deque
-from importlib import import_module
-from queue import Empty, SimpleQueue
-from typing import Literal, Optional, Union
-
-import mlx.core as mx
-import torch
-from rich.progress import BarColumn, Progress, TextColumn
-
-from ...logger import SpeedColumnToken, Timer, console, logger
-
-from .runner_mlx import ModelRunner
-from .structs_mlx import (
- T2SEngineProtocol,
- T2SRequest,
- T2SRequestHandle,
- T2SResult,
- T2SSessionMLX as T2SSession,
- T2SStreamResponse,
-)
-from .t2s_model_abc_mlx import T2SDecoderABC
-
-
-timer = Timer("T2S Engine MLX")
-
-cpu = mx.Device(mx.cpu)
-
-empty_result = T2SResult(
- result=None,
- infer_speed=(0.0, 0.0),
- total_tokens=0,
- status="Error",
- exception=RuntimeError("Empty Result"),
-)
-
-
-def synchronize_device(device: torch.device) -> None:
- device_type = device.type
- if device_type == "cuda":
- torch.cuda.synchronize()
- elif device_type == "mps":
- torch.mps.synchronize()
- elif device_type == "xpu":
- torch.xpu.synchronize()
- elif device_type == "mtia":
- torch.mtia.synchronize()
- elif device_type == "cpu":
- pass
-
-
-class T2SEngine(T2SEngineProtocol):
- def __init__(
- self,
- decoder_model: T2SDecoderABC,
- device: Union[mx.Device, torch.device] = cpu,
- dtype: Union[torch.dtype, mx.Dtype] = torch.float32,
- start_background: bool = True,
- *args,
- **kwds,
- ) -> None:
- if isinstance(device, torch.device):
- device_type = device.type
- if device_type == "cpu":
- self.device = cpu
- elif device_type == "cuda" or device_type == "mps":
- self.device = mx.Device(mx.gpu)
- else:
- raise RuntimeError(f"Device {device} not supported")
- elif isinstance(device, mx.Device):
- self.device = device
- else:
- raise RuntimeError(f"Device {device} not supported")
-
- if dtype == torch.float32:
- self.dtype = mx.float16 if self.device.type == mx.gpu else mx.float32
- elif dtype == torch.float16:
- self.dtype = mx.float16
- elif dtype == torch.bfloat16:
- self.dtype = mx.bfloat16
- elif dtype == mx.float16 or dtype == mx.bfloat16 or dtype == mx.float32:
- self.dtype = dtype
- else:
- raise RuntimeError(f"Dtype {dtype} Not Supported")
-
- mx.set_default_device(self.device)
- decoder_model.set_dtype(self.dtype)
-
- self.decoder_model: T2SDecoderABC = decoder_model
- self.waiting_bind: deque[T2SSession] = deque()
-
- self.model_runner = ModelRunner(self.decoder_model, self.device, self.dtype, waiting_bind=self.waiting_bind)
-
- self.pending_requests: SimpleQueue[tuple[T2SRequest, T2SRequestHandle, bool]] = SimpleQueue()
- self.handles: dict[Union[str, int], T2SRequestHandle] = {}
- self._stop_event = threading.Event()
- self._request_counter = 0
- self._loop_thread: Optional[threading.Thread] = None
-
- if start_background:
- self._loop_thread = threading.Thread(target=self._background_loop, daemon=True)
- self._loop_thread.start()
-
- def add_request(
- self,
- request: T2SRequest,
- stream_interval: Optional[int] = None,
- show_progress: bool = False,
- ) -> T2SRequestHandle:
- if stream_interval is not None:
- request.stream_interval = stream_interval
- if request.request_id is None:
- self._request_counter += 1
- request.request_id = f"req-{self._request_counter}"
-
- handle = T2SRequestHandle(request_id=request.request_id)
- self.handles[request.request_id] = handle
- self.pending_requests.put((request, handle, show_progress))
-
- if self._loop_thread is None or not self._loop_thread.is_alive():
- self._loop_thread = threading.Thread(target=self._background_loop, daemon=True)
- self._loop_thread.start()
-
- return handle
-
- def stream_generate(self, request: T2SRequest, show_progress: bool = False):
- """Generator yielding streaming responses until completion."""
- handle = self.add_request(request, stream_interval=request.stream_interval, show_progress=show_progress)
- while True:
- resp = handle.queue.get()
- yield resp
- if resp.finished:
- break
-
- def generate(self, request: T2SRequest, show_progress: bool = False):
- """Blocking generate that consumes the streaming queue until finished."""
- final_result = empty_result
- for response in self.stream_generate(request, show_progress=show_progress):
- if response.finished:
- final_result = response.result or T2SResult(
- status="Error",
- exception=response.exception,
- request_id=request.request_id,
- )
- return final_result
-
- def shutdown(self):
- self._stop_event.set()
- if self._loop_thread is not None:
- self._loop_thread.join(timeout=1.0)
- self._loop_thread = None
-
- def _emit_stream(
- self,
- session: T2SSession,
- tokens: Optional[list[torch.Tensor]],
- finished: bool = False,
- result: Optional[T2SResult] = None,
- exception: Optional[Exception] = None,
- ):
- handle = self.handles.get(session.request_id)
- if handle is None:
- return
-
- step = -1 if finished else session.step_count
- payload = T2SStreamResponse(
- request_id=session.request_id,
- step=step,
- tokens=tokens,
- finished=finished,
- result=result,
- exception=exception,
- )
- handle.queue.put(payload)
- if finished:
- handle.done = True
- self.handles.pop(session.request_id, None)
-
- def _maybe_stream_partial(self, session: T2SSession):
- if session.stream_interval <= 0:
- return
- if session.step_count == 0 or session.step_count - session.last_stream_step < session.stream_interval:
- return
-
- start = session.prompt_len + session.last_stream_step
- end = session.prompt_len + session.step_count
- tokens = [torch.tensor(self.model_runner.y_buf[session.slot_indices[i], start:end]) for i in range(session.bsz)]
- self._emit_stream(session, tokens=tokens, finished=False)
- session.last_stream_step = session.step_count
-
- def _finalize_session(
- self,
- session: T2SSession,
- exception: Optional[Exception] = None,
- ):
- request = session.request
- infer_time = max(time.perf_counter() - session.start_time, 1e-6)
- infer_speed = (session.total_tokens / infer_time if session.total_tokens else 0.0, infer_time)
- status: Literal["Success", "Error"] = "Error" if exception else "Success"
-
- if exception:
- logger.error(f"T2S request {session.request_id} failed: {exception}")
- traceback.print_exc()
-
- runner = self.model_runner
- tokens_out = [
- torch.tensor(
- runner.y_buf[session.slot_indices[i], session.prompt_len : session.prompt_len + session.step_count]
- )
- for i in range(min(request.valid_length, session.bsz))
- ]
-
- result = T2SResult(
- result=tokens_out if not exception else None,
- infer_speed=infer_speed,
- total_tokens=session.total_tokens,
- status=status,
- exception=exception,
- traceback=traceback.format_exc() if exception else None,
- request_id=session.request_id,
- )
-
- self._emit_stream(
- session,
- tokens=tokens_out if result.result is not None else None,
- finished=True,
- result=result,
- exception=exception,
- )
-
- if session.progress_task is not None and session.progress is not None:
- try:
- session.progress.update(
- session.progress_task,
- completed=session.progress.tasks[session.progress_task].total,
- )
- session.progress.remove_task(session.progress_task)
- session.progress.stop()
- except Exception:
- pass
- session.progress = None
-
- def _drain_new_requests(self) -> bool:
- new_added = False
- while True:
- try:
- request, handle, show_progress = self.pending_requests.get_nowait()
- except Empty:
- break
-
- try:
- session = self.model_runner.prefill(request)
- except Exception as e:
- logger.error(f"Prefill failed for request {request.request_id}: {e}")
- error_result = T2SResult(
- status="Error",
- exception=e,
- traceback=traceback.format_exc(),
- request_id=request.request_id,
- )
- handle.queue.put(
- T2SStreamResponse(
- request_id=request.request_id or "unknown",
- step=-1,
- tokens=None,
- finished=True,
- result=error_result,
- exception=e,
- )
- )
- handle.done = True
- self.handles.pop(request.request_id, None)
- continue
-
- total_tokens = max(1, session.max_decode_steps * session.bsz)
- if show_progress:
- session.progress = Progress(
- TextColumn("[cyan]{task.description}"),
- BarColumn(),
- TextColumn("{task.completed}/{task.total} tokens"),
- SpeedColumnToken(show_speed=True),
- console=console,
- transient=True,
- )
- session.progress.start()
- session.progress_task = session.progress.add_task(f"T2S[{session.request_id}]", total=total_tokens)
- self.waiting_bind.append(session)
- new_added = True
- return new_added
-
- def _background_loop(self):
- torch.set_grad_enabled(False)
- while not self._stop_event.is_set():
- self._drain_new_requests()
-
- if not self.model_runner.bound_sessions:
- if not self.waiting_bind:
- time.sleep(0.001)
- continue
-
- try:
- finished_sessions = self.model_runner.decode_step()
- except Exception as e:
- for session in list(self.model_runner.bound_sessions):
- self._finalize_session(session, exception=e)
- self.model_runner.unbind_session(session)
- continue
-
- for session in list(self.model_runner.bound_sessions):
- self._maybe_stream_partial(session)
- if session.progress_task is not None and session.progress is not None:
- session.progress.update(session.progress_task, advance=session.bsz)
-
- if finished_sessions:
- for session in finished_sessions:
- self._finalize_session(session, exception=None)
-
- def __del__(self):
- self.shutdown()
-
- @staticmethod
- def load_decoder(
- weights_path: os.PathLike,
- max_batch_size: int = 1,
- backend: str = "MLX-Varlen",
- quantize_mode: Optional[Literal["Affine", "MXFP8"]] = None,
- compile: bool = False,
- ) -> T2SDecoderABC:
- logger.info(f"Loading Text2Semantic Weights from {weights_path} with {backend} Backend")
- dict_s1 = torch.load(weights_path, map_location="cpu", weights_only=True, mmap=True)
- config = dict_s1["config"]
-
- module_path = f".backends.{backend.lower().replace('-', '_')}"
- decoder_cls_name = "T2SDecoder"
- decoder_mod = import_module(module_path, package=__package__)
- decoder_cls: type[T2SDecoderABC] = getattr(decoder_mod, decoder_cls_name)
- decoder: T2SDecoderABC = decoder_cls(config, max_batch_size=max_batch_size)
- state_dict = dict_s1["weight"]
- state_dict_mlx = T2SEngine.replace_key(state_dict)
-
- decoder.load_weights(state_dict_mlx)
-
- if quantize_mode is not None:
- decoder.quantize(quantize_mode)
- logger.info(
- f"Quantized to {decoder.bits}-Bit with Group Size {decoder.group_size} by {quantize_mode} Quantization"
- )
-
- mx.eval(decoder)
- return decoder
-
- @staticmethod
- def replace_key(state_dict: dict[str, torch.Tensor]):
- state_dict_mlx: list[tuple[str, mx.array]] = []
- for key, value in state_dict.items():
- key = (
- key.replace("model.", "")
- .replace("in_proj_", "in_proj.")
- .replace("self_attn", "attention")
- .replace("linear", "feed_forward.linear")
- .replace("norm1", "attention_norm")
- .replace("norm2", "ffn_norm")
- )
- value_mlx = mx.array(value.to(torch.float32).cpu().numpy())
- state_dict_mlx.append((key, value_mlx))
- return state_dict_mlx
diff --git a/GPT_SoVITS/Accel/MLX/AR/t2s_model_abc_mlx.py b/GPT_SoVITS/Accel/MLX/AR/t2s_model_abc_mlx.py
deleted file mode 100644
index 7be5ce5b..00000000
--- a/GPT_SoVITS/Accel/MLX/AR/t2s_model_abc_mlx.py
+++ /dev/null
@@ -1,455 +0,0 @@
-"""
-Modified From https://github.com/XXXXRT666/GPT-SoVITS
-"""
-
-from __future__ import annotations
-
-import math
-from abc import ABC, abstractmethod
-from collections.abc import Callable, MutableSequence
-from typing import TYPE_CHECKING, Any, Literal, Optional
-
-import mlx.core as mx
-import mlx.nn as nn
-from mlx.core import Dtype
-
-from .structs_mlx import KVCache, KVCacheProtocol, T2SSessionMLX as T2SSession
-
-
-if TYPE_CHECKING:
- from .runner_mlx import ModelRunner
-
-
-Array = mx.array
-
-
-class TokenEmbedding(nn.Module):
- def __init__(
- self,
- embedding_dim: int,
- vocab_size: int,
- ):
- super().__init__()
-
- self.vocab_size = vocab_size
- self.embedding_dim = embedding_dim
-
- self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
-
- @property
- def weight(self):
- return self.word_embeddings.weight
-
- def embedding(self, index: int):
- return self.word_embeddings.weight[index]
-
- def __call__(self, x: Array):
- x = self.word_embeddings(x)
- return x
-
-
-class SinePositionalEmbedding(nn.Module):
- def __init__(
- self,
- embedding_dim: int,
- scale: bool = False,
- max_batch_size: int = 10,
- max_seq_length: int = 1024,
- ):
- super().__init__()
- self.embedding_dim = embedding_dim
- self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
- self.alpha = mx.ones(1)
- self.max_batch_size = max_batch_size
- self.max_seq_length = max_seq_length
-
- self.reverse = False
- self.pe: Optional[Array] = None
-
- def compute_pe(self, dtype: Dtype):
- """Compute the positional encodings."""
-
- if self.pe is not None and self.pe.dtype == dtype:
- return
-
- if self.reverse:
- position = mx.expand_dims(mx.arange(self.max_seq_length - 1, -1, -1.0), axis=1)
- else:
- position = mx.expand_dims(mx.arange(self.max_seq_length), axis=1)
- div_term = mx.exp(
- mx.arange(
- 0,
- self.embedding_dim,
- 2,
- )
- * -(math.log(10000.0) / self.embedding_dim)
- ).astype(dtype)
- pe = mx.zeros((self.max_batch_size, self.max_seq_length, self.embedding_dim)).astype(dtype)
-
- pe[:, :, 0::2] = mx.sin(position * div_term).astype(dtype)
- pe[:, :, 1::2] = mx.cos(position * div_term).astype(dtype)
-
- self.pe = pe
-
- def __call__(self, input_pos: Array, x: Array):
- """
- Args:
- input_pos (Array): [batch_size, ]
- x (Array): [batch_size, 1, embed_dim]
-
- Returns:
- embedded_x (Array): [batch_size, 1, embed_dim]
- """
- self.compute_pe(x.dtype)
- assert self.pe is not None
-
- batch_size = x.shape[0]
- pe_values = self.pe[mx.arange(batch_size), input_pos - 1] # (batch_size, embed_dim)
-
- return x * self.x_scale + self.alpha * mx.expand_dims(pe_values, 1) # (batch_size, 1, embed_dim)
-
- def prefill(self, x: Array):
- """
- Args:
- x (Array): [batch_size, seq_len, embed_dim]
-
- Returns:
- embedded_x (Array): [batch_size, seq_len, embed_dim]
- """
- self.compute_pe(x.dtype)
- assert self.pe is not None
-
- batch_size = x.shape[0]
- pe_values = self.pe[mx.arange(batch_size), : x.shape[-2]]
- return x * self.x_scale + self.alpha * pe_values
-
-
-class KVCacheHND(KVCacheProtocol):
- @staticmethod
- def empty(kv_cache):
- assert len(kv_cache) == 2
- k_cache, v_cache = kv_cache
-
- k_cache[:] = 0
- v_cache[:] = 0
-
- @staticmethod
- def update_cache(input_pos, k_val, v_val, kv_cache):
- # input_pos: [B, ], k_val: [B, H, 1, D]
- assert len(kv_cache) == 2
- k_out, v_out = kv_cache
- ip0 = input_pos - 1
-
- k_out[:] = mx.put_along_axis(k_out, ip0.reshape(-1, 1, 1, 1), k_val, axis=2)
- v_out[:] = mx.put_along_axis(v_out, ip0.reshape(-1, 1, 1, 1), v_val, axis=2)
-
- return k_out, v_out
-
- @staticmethod
- def prefill_kv(k_val, v_val, kv_cache):
- # k_val: [B, H, S, D]
- assert len(kv_cache) == 2
- k_cache, v_cache = kv_cache
-
- k_cache[..., : k_val.shape[2], :] = k_val
- v_cache[..., : v_val.shape[2], :] = v_val
-
- @staticmethod
- def init_cache(batch_size: int, max_seq_length: int, n_heads: int, head_dim: int, dtype: mx.Dtype) -> KVCache:
- cache_shape = (batch_size, n_heads, max_seq_length, head_dim)
-
- return (mx.zeros(cache_shape, dtype=dtype), mx.zeros(cache_shape, dtype=dtype))
-
-
-class AttentionABC(nn.Module, ABC):
- def __init__(self, n_head: int, hidden_dim: int, max_seq_length: int, *args, **kwds):
- super().__init__()
-
- self.n_head = n_head
- self.hidden_dim = hidden_dim
- assert hidden_dim % n_head == 0
- self.head_dim = hidden_dim // n_head
-
- self.max_seq_length = max_seq_length
-
- # key, query, value projections for all heads, but in a batch
- self.in_proj = nn.Linear(hidden_dim, hidden_dim * 3, bias=True)
- self.out_proj = nn.Linear(hidden_dim, hidden_dim, bias=True)
-
- self.scale = 1 / math.sqrt(self.head_dim)
-
- self.kv_class: KVCacheProtocol
-
- @abstractmethod
- def __call__(self, x: Array, input_pos: Array, kv_cache: KVCache, attn_mask: Array) -> Array: ...
-
- def prefill(self, x: Array, kv_cache: KVCache, attn_mask: Array):
- bsz, seqlen, _ = x.shape
-
- qkv = self.in_proj(x)
-
- q, k, v = mx.split(qkv, 3, -1)
-
- q = q.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
- k = k.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
- v = v.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
-
- self.kv_class.prefill_kv(k, v, kv_cache)
-
- attn = mx.fast.scaled_dot_product_attention(q, k, v, mask=attn_mask, scale=self.scale)
-
- attn = mx.nan_to_num(attn)
-
- attn = attn.transpose(0, 2, 1, 3).reshape(bsz, seqlen, -1)
-
- output = self.out_proj(attn)
-
- return output
-
-
-class FeedForward(nn.Module):
- def __init__(self, dim: int, hidden_dim: int) -> None:
- super().__init__()
-
- self.linear1 = nn.Linear(dim, hidden_dim, bias=True)
- self.linear2 = nn.Linear(hidden_dim, dim, bias=True)
-
- def __call__(self, x: Array):
- return self.linear2(nn.relu(self.linear1(x)))
-
-
-class TransformerBlockABC(nn.Module, ABC):
- def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int, *args, **kwds) -> None:
- super().__init__()
-
- self.hidden_dim = hidden_dim
- self.max_seq_length = max_seq_length
-
- self.attention: AttentionABC
-
- self.feed_forward = FeedForward(hidden_dim, ffn_dim)
- self.attention_norm = nn.LayerNorm(self.hidden_dim)
- self.ffn_norm = nn.LayerNorm(self.hidden_dim)
-
- def __call__(self, x: Array, input_pos: Array, kv_cache: KVCache, attn_mask: Array):
- h = self.attention_norm(
- x
- + self.attention(
- x,
- input_pos,
- kv_cache,
- attn_mask,
- )
- )
- out = self.ffn_norm(h + self.feed_forward(h))
- return out
-
- def prefill(self, x: Array, kv_cache: KVCache, attn_mask: Array):
- h = self.attention_norm(
- x
- + self.attention.prefill(
- x,
- kv_cache,
- attn_mask,
- )
- )
- out = self.ffn_norm(h + self.feed_forward(h))
-
- return out
-
-
-class TransformerDecoderABC(nn.Module, ABC):
- def __init__(
- self,
- hidden_dim: int,
- n_layer: int,
- n_head: int,
- ffn_dim: int,
- vocab_size: int,
- max_seq_length: int,
- max_batch_size: int,
- *args,
- **kwds,
- ) -> None:
- super().__init__()
-
- self.hidden_dim = hidden_dim
- self.n_head = n_head
- assert hidden_dim % n_head == 0
-
- self.head_dim = hidden_dim // n_head
- self.vocab_size = vocab_size
-
- self.n_layer = n_layer
-
- self.layers: MutableSequence[TransformerBlockABC]
-
- self.max_seq_length = max_seq_length
- self.max_batch_size = max_batch_size
-
- def __call__(
- self,
- x: Array,
- input_pos: Array,
- kv_caches: MutableSequence[KVCache],
- *args,
- **kwds,
- ):
- for layer, kv_cache in zip(self.layers, kv_caches):
- x = layer(
- x,
- input_pos,
- kv_cache,
- *args,
- **kwds,
- )
-
- return x
-
- def prefill(self, x: Array, kv_caches: MutableSequence[KVCache], mask: Array):
- for layer, kv_cache in zip(self.layers, kv_caches):
- x = layer.prefill(
- x,
- kv_cache,
- mask,
- )
- return x
-
-
-class T2SDecoderABC(nn.Module, ABC):
- def __init__(
- self,
- config: dict,
- max_seq_length: int = 1024,
- max_batch_size: int = 10,
- ) -> None:
- super().__init__()
-
- hidden_dim: int = config["model"]["hidden_dim"]
- embedding_dim: int = config["model"]["embedding_dim"]
- n_head: int = config["model"]["head"]
- n_layer: int = config["model"]["n_layer"]
- vocab_size: int = config["model"]["vocab_size"]
- phoneme_vocab_size: int = config["model"]["phoneme_vocab_size"]
- EOS: int = config["model"]["EOS"]
- ffn_dim: int = hidden_dim * 4
-
- self.n_layer = int(n_layer)
- self.hidden_dim = int(hidden_dim)
- self.n_head = int(n_head)
- assert hidden_dim % n_head == 0
-
- self.head_dim = int(hidden_dim // n_head)
- self.embedding_dim = int(embedding_dim)
- self.ffn_dim = int(ffn_dim)
- self.vocab_size = int(vocab_size)
- self.phoneme_vocab_size = int(phoneme_vocab_size)
- self.max_seq_length = max_seq_length
- self.max_batch_size = max_batch_size
- self.EOS = EOS
- assert self.EOS == self.vocab_size - 1
-
- self.bert_proj = nn.Linear(1024, self.embedding_dim)
- self.ar_predict_layer = nn.Linear(self.hidden_dim, self.vocab_size, bias=False)
- self.h: TransformerDecoderABC
-
- self.ar_text_embedding = TokenEmbedding(self.embedding_dim, self.phoneme_vocab_size)
- self.ar_text_position = SinePositionalEmbedding(
- self.embedding_dim,
- scale=False,
- max_batch_size=max_batch_size,
- max_seq_length=max_seq_length,
- )
- self.ar_audio_embedding = TokenEmbedding(self.embedding_dim, self.vocab_size)
- self.ar_audio_position = SinePositionalEmbedding(
- self.embedding_dim,
- scale=False,
- max_batch_size=max_batch_size,
- max_seq_length=max_seq_length,
- )
-
- self.kv_class: type[KVCacheProtocol]
- self.extra_buffer_factory: Callable[[int, T2SDecoderABC], dict[str, Array]] = lambda *_: {}
-
- self.bits: int = -1
- self.group_size: int = -1
-
- def init_cache(self, bsz: int = 0, *args, **kwds) -> MutableSequence[KVCache]:
- bsz = bsz or self.h.max_batch_size
- assert bsz <= self.h.max_batch_size
- seq_lens = self.h.max_seq_length
- dtype = self.bert_proj.bias.dtype
- cache: MutableSequence[KVCache] = [
- self.kv_class.init_cache(bsz, seq_lens, self.n_head, self.head_dim, dtype, *args, **kwds)
- for _ in range(self.n_layer)
- ]
- mx.eval(cache)
- return cache
-
- def embed(
- self,
- x: list[Array],
- y: Array,
- bert_features: list[Array],
- ):
- x_len: list[int] = [i.shape[0] for i in x]
- x_len_max = max(x_len)
- xy_pos = mx.zeros(
- (
- len(x),
- x_len_max + y.shape[1],
- self.embedding_dim,
- ),
- bert_features[0].dtype,
- )
-
- bert_features = list(map(lambda x: x.swapaxes(0, 1), bert_features))
-
- y_len = y.shape[1]
- y_emb = self.ar_audio_embedding(y)
- y_pos = self.ar_audio_position.prefill(y_emb)
-
- for bs, (x_, len_, bert_feature) in enumerate(zip(x, x_len, bert_features)):
- x_emb = self.ar_text_embedding(x_)
- bert = self.bert_proj(bert_feature)
- x_emb = x_emb + bert
- x_pos = self.ar_text_position.prefill(mx.expand_dims(x_emb, 0))
- xy_pos[[bs], :len_] = x_pos
- xy_pos[[bs], len_ : len_ + y_len] = y_pos
-
- mx.eval(xy_pos)
- return xy_pos
-
- # Slot-aware hooks for runner-managed buffers.
- @abstractmethod
- def pre_forward_slots_hook(self, slots: list[int], runner: ModelRunner) -> dict[str, Any]:
- return {}
-
- @abstractmethod
- def post_forward_slots_hook(self, slots: list[int], runner: ModelRunner) -> None:
- return
-
- @abstractmethod
- def bind_session_hook(self, session: T2SSession, runner: ModelRunner) -> None:
- return
-
- @abstractmethod
- def unbind_session_hook(self, session: T2SSession, runner: ModelRunner) -> None:
- return
-
- def quantize(self, mode: Optional[Literal["Affine", "MXFP8"]] = None) -> None:
- if mode is None:
- return
- if mode not in {"Affine", "MXFP8"}:
- raise ValueError(f"Unsupported quantization mode: {mode}")
- if mode == "Affine":
- self.bits = 8
- self.group_size = 32
- nn.quantize(self.h, group_size=self.group_size, bits=self.bits, mode="affine")
- elif mode == "MXFP8":
- self.bits = 4
- self.group_size = 32
- nn.quantize(self.h, group_size=self.group_size, bits=self.bits, mode="mxfp8")
-
- else:
- raise ValueError(f"Unsupported Quantization Mode for MLX: {mode}")
diff --git a/GPT_SoVITS/Accel/MLX/G2PW/model.py b/GPT_SoVITS/Accel/MLX/G2PW/model.py
deleted file mode 100644
index 527b82d8..00000000
--- a/GPT_SoVITS/Accel/MLX/G2PW/model.py
+++ /dev/null
@@ -1,246 +0,0 @@
-import math
-from pathlib import Path
-
-import mlx.core as mx
-import mlx.nn as nn
-import torch
-from transformers import BertConfig
-
-
-Array = mx.array
-Tensor = torch.Tensor
-
-
-class MultiHeadAttention(nn.Module):
- def __init__(
- self,
- dims: int,
- num_heads: int,
- ):
- super().__init__()
-
- assert dims % num_heads == 0, "The input feature dimensions should be divisible by the number of heads"
-
- self.num_heads = num_heads
- self.query_proj = nn.Linear(dims, dims)
- self.key_proj = nn.Linear(dims, dims)
- self.value_proj = nn.Linear(dims, dims)
- self.out_proj = nn.Linear(dims, dims)
-
- self.scale = math.sqrt(1 / dims)
-
- def __call__(self, x: Array):
- B, L, _ = x.shape
- queries = self.query_proj(x)
- keys = self.key_proj(x)
- values = self.value_proj(x)
-
- num_heads = self.num_heads
- queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
- keys = keys.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
- values = values.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
- output = mx.fast.scaled_dot_product_attention(queries, keys, values, scale=self.scale)
- output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
- return self.out_proj(output)
-
-
-class TransformerEncoderLayer(nn.Module):
- """
- A transformer encoder layer with (the original BERT) post-normalization.
- """
-
- def __init__(
- self,
- dims: int,
- num_heads: int,
- mlp_dims: int,
- layer_norm_eps: float = 1e-12,
- ):
- super().__init__()
-
- self.attention = MultiHeadAttention(dims, num_heads)
- self.attention_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
- self.ffn_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
- self.linear1 = nn.Linear(dims, mlp_dims)
- self.linear2 = nn.Linear(mlp_dims, dims)
- self.gelu = nn.GELU()
-
- def __call__(self, x: Array) -> Array:
- attention_out = self.attention(x)
- add_and_norm = self.attention_norm(x + attention_out)
-
- ff = self.linear1(add_and_norm)
- ff_gelu = self.gelu(ff)
- ff_out = self.linear2(ff_gelu)
- x = self.ffn_norm(ff_out + add_and_norm)
-
- return x
-
-
-class TransformerEncoder(nn.Module):
- def __init__(self, num_layers: int, dims: int, num_heads: int, mlp_dims: int):
- super().__init__()
- self.layers = [TransformerEncoderLayer(dims, num_heads, mlp_dims) for _ in range(num_layers)]
-
- def __call__(self, x: Array):
- for layer in self.layers:
- x = layer(x)
-
- return x
-
-
-class BertEmbeddings(nn.Module):
- def __init__(self, config: BertConfig):
- super().__init__()
- self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
- self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
- self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
- self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
-
- def __call__(self, input_ids: Array) -> Array:
- words = self.word_embeddings(input_ids)
- position = self.position_embeddings.weight[: input_ids.shape[1]]
- token_types = self.token_type_embeddings.weight[0]
-
- embeddings = position + words + token_types
- return self.norm(embeddings)
-
-
-class Bert(nn.Module):
- def __init__(self, config: BertConfig):
- super().__init__()
- self.embeddings = BertEmbeddings(config)
- self.encoder = TransformerEncoder(
- num_layers=config.num_hidden_layers,
- dims=config.hidden_size,
- num_heads=config.num_attention_heads,
- mlp_dims=config.intermediate_size,
- )
-
- def __call__(
- self,
- input_ids: Array,
- ) -> Array:
- x = self.embeddings(input_ids)
-
- y = self.encoder(x)
- return y
-
-
-class G2PW(nn.Module):
- def __init__(
- self,
- config,
- num_labels: int = 1305,
- num_chars: int = 3582,
- num_pos_tags: int = 11,
- ):
- super().__init__()
- self.config = config
- self.num_labels = num_labels
- self.num_chars = num_chars
- self.num_pos_tags = num_pos_tags
- target_size = self.num_labels
-
- self.bert = Bert(config)
- self.pos_classifier = nn.Linear(self.config.hidden_size, self.num_pos_tags)
- self.descriptor_bias = nn.Embedding(1, target_size)
- self.char_descriptor = nn.Embedding(self.num_chars, target_size)
- self.second_order_descriptor = nn.Embedding(self.num_chars * self.num_pos_tags, target_size)
- self.classifier = nn.Linear(self.config.hidden_size, self.num_labels)
-
- @mx.compile
- @staticmethod
- def _weighted_softmax(logits: Array, weights: Array, eps: float) -> Array:
- max_logits = mx.max(logits, axis=-1, keepdims=True)
- weighted_exp_logits = mx.exp(logits - max_logits) * weights
- norm = mx.sum(weighted_exp_logits, axis=-1, keepdims=True)
- probs = weighted_exp_logits / norm
- probs = mx.minimum(probs, 1 - eps)
- probs = mx.maximum(probs, eps)
-
- return probs
-
- def _get_char_pos_ids(self, char_ids: Array, pos_ids: Array):
- return char_ids * self.num_pos_tags + pos_ids
-
- def __call__(
- self,
- input_ids_torch: Tensor,
- phoneme_mask_torch: Tensor,
- char_ids_torch: Tensor,
- position_ids_torch: Tensor,
- eps: float = 1e-6,
- ):
- input_ids = mx.array(input_ids_torch.cpu()) # type: ignore
- phoneme_mask = mx.array(phoneme_mask_torch.cpu()) # type: ignore
- char_ids = mx.array(char_ids_torch.cpu()) # type: ignore
- position_ids = mx.array(position_ids_torch.cpu()) # type: ignore
-
- sequence_output = self.bert(input_ids=input_ids)
-
- orig_selected_hidden = mx.take_along_axis(
- sequence_output,
- position_ids.reshape(-1, 1, 1),
- axis=1,
- ).squeeze(1)
-
- pred_pos_ids = self.pos_classifier(orig_selected_hidden).argmax(axis=-1) # teacher mode while training
-
- bias_tensor = self.descriptor_bias(mx.zeros_like(char_ids))
-
- char_pos_ids = self._get_char_pos_ids(char_ids, pred_pos_ids)
-
- affect_hidden = bias_tensor + self.char_descriptor(char_ids) + self.second_order_descriptor(char_pos_ids)
-
- phoneme_mask = phoneme_mask * mx.sigmoid(affect_hidden)
-
- logits = self.classifier(orig_selected_hidden)
-
- probs: Array = self._weighted_softmax(logits, phoneme_mask, eps)
-
- pred_idx = probs.argmax(axis=1)
-
- return torch.tensor(pred_idx)
-
-
-def replace_key(key: str) -> str:
- key = key.replace(".layer.", ".layers.")
- key = key.replace(".self.key.", ".key_proj.")
- key = key.replace(".self.query.", ".query_proj.")
- key = key.replace(".self.value.", ".value_proj.")
- key = key.replace(".attention.output.dense.", ".attention.out_proj.")
- key = key.replace(".attention.output.LayerNorm.", ".attention_norm.")
- key = key.replace(".output.LayerNorm.", ".ffn_norm.")
- key = key.replace(".intermediate.dense.", ".linear1.")
- key = key.replace(".output.dense.", ".linear2.")
- key = key.replace(".LayerNorm.", ".norm.")
- key = key.replace("pooler.dense.", "pooler.")
- return key
-
-
-def load_g2pw_mlx(bert_model: str, weights_path: str, device: torch.device, dtype: torch.dtype) -> G2PW:
- if not Path(weights_path).exists():
- raise ValueError(f"No model weights found in {weights_path}")
-
- config = BertConfig.from_pretrained(bert_model)
-
- # create and update the model
- model = G2PW(config)
- state_dict = torch.load(weights_path, map_location="cpu")
- state_dict_mlx: list[tuple[str, Array]] = []
- for key, value in state_dict.items():
- key = replace_key(key)
- value_mlx = mx.array(value.to(torch.float32))
- state_dict_mlx.append((key, value_mlx))
- model.load_weights(state_dict_mlx)
- if dtype == torch.float16:
- model.set_dtype(mx.float16)
- elif dtype == torch.bfloat16:
- model.set_dtype(mx.bfloat16)
- elif dtype == torch.float32:
- model.set_dtype(mx.float16) if device.type != "cpu" else model.set_dtype(mx.float32)
- nn.quantize(model.bert.encoder, group_size=128, bits=4)
- mx.eval(model.parameters())
-
- return model
diff --git a/GPT_SoVITS/Accel/MLX/__init__.py b/GPT_SoVITS/Accel/MLX/__init__.py
deleted file mode 100644
index 0b57b428..00000000
--- a/GPT_SoVITS/Accel/MLX/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-import importlib.util
-
-
-backends: list[str]
-
-if importlib.util.find_spec("mlx") is not None:
- import mlx.utils as mxutils
-
- from .AR.sample_funcs_mlx import sample_naive_mlx
- from .AR.t2s_engine_mlx import T2SEngine as T2SEngineMLX
- from .G2PW.model import load_g2pw_mlx
-
- backends = ["mlx_static", "mlx_varlen"]
-else:
- backends = []
-
-quantization_methods_mlx = [None, "MXFP8", "Affine"]
-__all__ = ["T2SEngineMLX", "sample_naive_mlx", "backends", "quantization_methods_mlx", "load_g2pw_mlx", "mxutils"]
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/backends/torch_varlen.py b/GPT_SoVITS/Accel/PyTorch/AR/backends/torch_varlen.py
deleted file mode 100644
index 7769887f..00000000
--- a/GPT_SoVITS/Accel/PyTorch/AR/backends/torch_varlen.py
+++ /dev/null
@@ -1,152 +0,0 @@
-from collections.abc import Callable
-
-import torch
-from torch.nn import functional as F
-
-from ... import nn
-from ..structs import KVCache
-from ..t2s_model_abc import (
- AttentionABC,
- FeedForward,
- KVCacheHND,
- T2SDecoderABC,
- TransformerBlockABC,
- TransformerDecoderABC,
-)
-
-
-Tensor = torch.Tensor
-
-
-class Attention(AttentionABC):
- def __init__(self, n_head, hidden_dim, max_seq_length):
- super().__init__(n_head, hidden_dim, max_seq_length)
-
- # key, query, value projections for all heads, but in a batch
- self.in_proj = nn.Linear(hidden_dim, hidden_dim * 3, bias=True)
- self.out_proj = nn.Linear(hidden_dim, hidden_dim, bias=True)
-
- self.kv_class = KVCacheHND
-
- def __call__(self, x: Tensor, input_pos: Tensor, kv_cache: KVCache, attn_mask: Tensor, max_idx: Tensor):
- bsz, seqlen, _ = x.shape
-
- q, k, v = self.in_proj(x).chunk(3, dim=-1)
-
- q = q.view(bsz, seqlen, self.n_head, self.head_dim)
- k = k.view(bsz, seqlen, self.n_head, self.head_dim)
- v = v.view(bsz, seqlen, self.n_head, self.head_dim)
-
- q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
-
- k, v = self.kv_class.update(input_pos, k, v, kv_cache)
-
- q, k, v = map(lambda x: x[..., :max_idx, :], (q, k, v))
-
- mask = attn_mask[..., :max_idx]
-
- attn = F.scaled_dot_product_attention(q, k, v, mask)
-
- attn = attn.transpose(1, 2).contiguous().view(bsz, seqlen, self.hidden_dim)
-
- attn = self.out_proj(attn)
-
- return attn
-
-
-class TransformerBlock(TransformerBlockABC):
- def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
- super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
-
- self.attention = Attention(n_head, hidden_dim, max_seq_length)
- self.feed_forward = FeedForward(hidden_dim, ffn_dim)
- self.attention_norm = nn.LayerNorm([self.hidden_dim])
- self.ffn_norm = nn.LayerNorm([self.hidden_dim])
-
-
-class TransformerDecoder(TransformerDecoderABC):
- def __init__(
- self,
- hidden_dim,
- n_layer,
- n_head,
- ffn_dim,
- vocab_size,
- max_seq_length,
- max_batch_size,
- ) -> None:
- super().__init__(hidden_dim, n_layer, n_head, ffn_dim, vocab_size, max_seq_length, max_batch_size)
-
- self.layers = nn.ModuleList( # type: ignore
- TransformerBlock(n_head, ffn_dim, hidden_dim, max_seq_length) for _ in range(n_layer)
- )
-
-
-class T2SDecoder(T2SDecoderABC):
- def __init__(
- self,
- config,
- max_seq_length=1024,
- max_batch_size=10,
- ) -> None:
- super().__init__(config, max_seq_length, max_batch_size)
-
- self.h: TransformerDecoderABC = TransformerDecoder(
- self.hidden_dim,
- self.n_layer,
- self.n_head,
- self.ffn_dim,
- self.vocab_size,
- max_seq_length,
- max_batch_size,
- )
-
- self.kv_class = KVCacheHND
- self.device: torch.device
-
- self.extra_buffer_factory: Callable[[int, T2SDecoderABC], dict[str, Tensor]] = lambda max_bs, dec: {
- "attn_mask_buf": torch.zeros(
- (
- max_bs,
- dec.n_head,
- 1,
- dec.max_seq_length,
- ),
- device=dec.device,
- dtype=torch.bool,
- )
- }
-
- def capture(
- self,
- *args,
- **kwds,
- ):
- raise NotImplementedError("Cuda Graph Is Not Supported For Varlen Model")
-
- def pre_forward_slots_hook(self, slots, runner):
- attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
- max_idx = runner.input_pos_buf[slots].long().max().item()
- return {"attn_mask": attn_mask_buf[slots], "max_idx": max_idx}
-
- def post_forward_slots_hook(self, slots, runner) -> None:
- attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
- pos = runner.input_pos_buf[slots].long()
- attn_mask_buf[slots, :, :, pos] = True
-
- def bind_session_hook(self, session, runner) -> None:
- slots = session.slot_indices
-
- prefill_len = session.prefill_len
- bsz = session.bsz
-
- range_tensor = torch.arange(self.max_seq_length).view(1, 1, 1, self.max_seq_length)
- prefill_len_expanded = prefill_len.view(bsz, 1, 1, 1)
- attn_mask = range_tensor < prefill_len_expanded
-
- runner.extra_buffers["attn_mask_buf"][slots] = attn_mask
-
- def unbind_session_hook(self, session, runner) -> None:
- slots = session.slot_indices
- attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
- attn_mask_buf[slots].zero_()
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/export.py b/GPT_SoVITS/Accel/PyTorch/AR/export.py
deleted file mode 100644
index 3de53fc5..00000000
--- a/GPT_SoVITS/Accel/PyTorch/AR/export.py
+++ /dev/null
@@ -1,469 +0,0 @@
-import enum
-import os
-import os.path as osp
-import time
-from collections.abc import MutableSequence
-from pathlib import Path
-
-import torch
-import typer
-from torch.export import Dim
-from torch.nn import functional as F
-
-from ...logger import logger
-
-from .. import nn
-from .t2s_model_abc import AttentionABC, FeedForward, T2SDecoderABC, TransformerBlockABC, TransformerDecoderABC
-
-
-Tensor = torch.Tensor
-
-KVCache = tuple[Tensor, Tensor]
-
-app = typer.Typer(
- context_settings={"help_option_names": ["-h", "--help"]},
- add_completion=False,
-)
-
-
-class Stage(str, enum.Enum):
- embed = "embed"
- decode = "decode"
-
-
-class KVCacheONNX:
- @staticmethod
- def empty(kv_cache):
- assert len(kv_cache) == 2
- k_cache, v_cache = kv_cache
-
- k_cache[:] = 0
- v_cache[:] = 0
-
- @staticmethod
- def update_cache(
- input_pos: Tensor, k_val: Tensor, v_val: Tensor, kv_cache: tuple[Tensor, Tensor], cache_idx: Tensor
- ):
- # input_pos: [B, ], k_val: [B, H, 1, D]
- k_out, v_out = kv_cache
- ip0 = input_pos - 1
-
- k_out[cache_idx, :, ip0, None] = k_val
- v_out[cache_idx, :, ip0, None] = v_val
-
- return k_out, v_out
-
- @staticmethod
- def prefill_kv(k_val: Tensor, v_val: Tensor, kv_cache: tuple[Tensor, Tensor]):
- # k_val: [B, S, H, D]
- k_cache, v_cache = kv_cache
-
- k_cache[..., : k_val.shape[1], :] = k_val.transpose(1, 2)
- v_cache[..., : v_val.shape[1], :] = v_val.transpose(1, 2)
-
- @staticmethod
- def init_cache(batch_size: int, max_seq_length: int, n_heads: int, head_dim: int, dtype: torch.dtype):
- cache_shape = (batch_size, n_heads, max_seq_length, head_dim)
-
- return (torch.zeros(cache_shape, dtype=dtype), torch.zeros(cache_shape, dtype=dtype))
-
-
-class AttentionONNX(AttentionABC):
- def __init__(self, n_heads: int, head_dim: int, max_seq_length: int):
- super().__init__(n_heads, head_dim, max_seq_length)
-
- self.in_proj = nn.Linear(self.hidden_dim, self.hidden_dim * 3, bias=True)
- self.out_proj = nn.Linear(self.hidden_dim, self.hidden_dim, bias=True)
-
- def __call__(self, *args, **kwds): # type: ignore
- pass
-
- def onnx_prefill(self, x: Tensor, kv_cache: KVCache, attn_mask: Tensor) -> Tensor:
- bsz, seqlen, _ = x.shape
-
- torch._check(attn_mask.size(-2) == x.size(-2))
-
- q, k, v = self.in_proj(x.unsqueeze(0)).chunk(3, dim=-1)
-
- q, k, v = map(lambda x: x.contiguous().view(bsz, seqlen, self.n_head, self.head_dim), (q, k, v))
-
- KVCacheONNX.prefill_kv(k, v, kv_cache)
-
- q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
-
- attn = F.scaled_dot_product_attention(q, k, v, attn_mask)
-
- attn = attn.transpose(1, 2).contiguous().view(1, -1, self.hidden_dim)
-
- output = self.out_proj(attn)
-
- return output
-
- def onnx_decode(self, x: Tensor, input_pos: Tensor, kv_cache: KVCache, cache_idx: Tensor, attn_mask: Tensor):
- bsz, seqlen, _ = x.shape
-
- torch._check(attn_mask.size(-2) == 1)
-
- q, k, v = self.in_proj(x).chunk(3, dim=-1)
-
- q, k, v = map(lambda x: x.reshape(bsz, seqlen, self.n_head, self.head_dim), (q, k, v))
-
- q, k, v = map(lambda x: x.swapaxes(1, 2), (q, k, v))
-
- kv_cache = KVCacheONNX.update_cache(input_pos, k, v, kv_cache, cache_idx)
-
- max_idx = int(input_pos.max())
-
- q, k, v = map(lambda x: x[..., :max_idx, :], (q, *kv_cache))
-
- mask = attn_mask[..., :max_idx]
-
- attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
-
- attn = attn.swapaxes(1, 2).reshape(bsz, seqlen, self.hidden_dim)
-
- attn = self.out_proj(attn)
-
- return attn
-
-
-class TransformerBlockONNX(TransformerBlockABC):
- def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
- super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
-
- self.attention: AttentionONNX = AttentionONNX(n_head, hidden_dim, max_seq_length) # type: ignore
- self.feed_forward = FeedForward(hidden_dim, ffn_dim)
- self.attention_norm = nn.LayerNorm(self.hidden_dim)
- self.ffn_norm = nn.LayerNorm(self.hidden_dim)
-
- def onnx_prefill(self, x: Tensor, attn_mask: Tensor, kv_cache: KVCache):
- h = self.attention_norm(
- x
- + self.attention.onnx_prefill(
- x,
- kv_cache,
- attn_mask,
- )
- )
- out = self.ffn_norm(h + self.feed_forward(h))
-
- return out
-
- def onnx_decode(self, x: Tensor, input_pos: Tensor, kv_cache: KVCache, cache_idx: Tensor, attn_mask: Tensor):
- h = self.attention_norm(
- x
- + self.attention.onnx_decode(
- x,
- input_pos,
- kv_cache,
- cache_idx,
- attn_mask,
- )
- )
- out = self.ffn_norm(h + self.feed_forward(h))
- return out
-
-
-class TransformerDecoderONNX(TransformerDecoderABC):
- def __init__(
- self,
- hidden_dim: int,
- n_layer: int,
- n_head: int,
- ffn_dim: int,
- vocab_size: int,
- max_seq_length: int,
- max_batch_size: int,
- ) -> None:
- super().__init__(hidden_dim, n_layer, n_head, ffn_dim, vocab_size, max_seq_length, max_batch_size)
-
- self.layers: MutableSequence[TransformerBlockONNX] = nn.ModuleList( # type: ignore
- TransformerBlockONNX(n_head, ffn_dim, hidden_dim, max_seq_length) for _ in range(n_layer)
- )
-
- def onnx_prefill(self, x: Tensor, mask: Tensor, *kv_caches: KVCache):
- for layer, kv_cache in zip(self.layers, kv_caches):
- x = layer.onnx_prefill(
- x,
- mask,
- kv_cache,
- )
- return x
-
- def onnx_decode(
- self,
- input_pos: Tensor,
- x: Tensor,
- cache_idx: Tensor,
- attn_mask: Tensor,
- *kv_caches: KVCache,
- ):
- for layer, kv_cache in zip(self.layers, kv_caches):
- x = layer.onnx_decode(
- x,
- input_pos,
- kv_cache,
- cache_idx,
- attn_mask,
- )
-
- return x
-
-
-class T2SDecoderONNX(T2SDecoderABC):
- def __init__(self, config: dict, max_seq_length: int = 1024, max_batch_size: int = 10) -> None:
- super().__init__(config, max_seq_length, max_batch_size)
-
- self.bert_proj = nn.Linear(1024, self.embedding_dim)
- self.ar_predict_layer = nn.Linear(self.hidden_dim, self.vocab_size, bias=False)
-
- self.h = TransformerDecoderONNX(
- self.hidden_dim, self.n_layer, self.n_head, self.ffn_dim, self.vocab_size, max_seq_length, max_batch_size
- )
-
- def pre_forward(self, session) -> tuple[list[Tensor], dict[str, Tensor]]:
- return super().pre_forward(session)
-
- def post_forward(self, idx: int, session) -> None:
- return super().post_forward(idx, session)
-
- def embed_onnx_(
- self,
- x: Tensor,
- x_len: Tensor,
- y: torch.Tensor,
- bert_features: Tensor,
- ):
- B = x.shape[0]
- D = self.embedding_dim
- T_TOTAL = 500
- xy_pos = torch.zeros((B, T_TOTAL, D)).to(bert_features[0].dtype)
-
- bert_features = bert_features.transpose(1, 2)
-
- y.shape[1]
- y_emb = self.ar_audio_embedding(y)
- self.ar_audio_position.prefill(y_emb)
-
- for bs, x_, len_, bert_feature in zip(torch.arange(x.shape[0]), x, x_len, bert_features):
- x_emb = self.ar_text_embedding(x_[:len_])
-
- bert = self.bert_proj(bert_feature[:len_])
-
- print(bert.shape, bert_feature[:len_])
-
- return bert, bert_feature[:len_].unsqueeze(0)
-
- return bert[:20].unsqueeze(0), None
- x_emb = x_emb + bert
- self.ar_text_position.prefill(x_emb.unsqueeze(0))
-
- xy_pos[None, bs, :len_] = bert
- # xy_pos[None, bs, len_ : len_ + y_len] = y_pos
-
- return xy_pos[:, -1], None
-
- return xy_pos[: x.shape[0]], x_len
-
- def embed_onnx(
- self,
- x: torch.Tensor, # [B, Tx]
- x_len: torch.Tensor, # [B]
- y: torch.Tensor, # [1, Ty, D]
- bert_features: torch.Tensor, # [B, 1024, Tx]
- ):
- # [B, 1024, Tx] -> [B, Tx, 1024]
- bert_features = bert_features.transpose(1, 2)
-
- Ty = y.shape[1]
- Tx = x.shape[1]
- B = x.shape[0]
- D = self.embedding_dim
- T_TOTAL = 500
-
- # mask: [B, Tx], [j] Col < x_len[i]
- col = torch.arange(Tx, device=x.device).unsqueeze(0) # [1, Tx]
- mask_x = col < x_len.view(-1, 1) # [B, Tx]
- mask_x3 = mask_x.unsqueeze(-1) # [B, Tx, 1]
-
- torch._check((Ty >= 0) and (Ty <= 250), "y_len out of range")
- torch._check((Tx >= 0) and (Tx <= 250), "x_len out of range")
-
- y_emb = self.ar_audio_embedding(y) # [1, Ty, D]
- y_pos = self.ar_audio_position.prefill(y_emb) # [1, Ty, D]
-
- x_emb_full = self.ar_text_embedding(x) # [B, Tx, D]
- bert_full = self.bert_proj(bert_features[[0], : x_len[0]]) # [B, Tx, D]
-
- print(bert_full[0].shape, bert_features[0, : x_len[0]])
-
- return bert_full[0], bert_features[0, : x_len[0]]
-
- x_sum_full = x_emb_full + bert_full # [B, Tx, D]
- x_pos_full = self.ar_text_position.prefill(x_sum_full) # [B, Tx, D]
-
- xy_pos = torch.zeros((B, T_TOTAL, D), dtype=x_pos_full.dtype, device=x_pos_full.device)
-
- xy_pos[:, :Tx, :] = torch.where(
- mask_x3,
- bert_full[:, :Tx, :].to(xy_pos.dtype),
- xy_pos[:, :Tx, :],
- )
-
- return xy_pos[:, -1], None
-
- # Start From offset=x_len, Ty
- # [Ty] Index: offsets + [0..Ty-1]
- offsets = x_len.clamp(min=0, max=T_TOTAL - Ty) # [B]
- idx_y = offsets.unsqueeze(1) + torch.arange(Ty, device=x_pos_full.device) # [B, Ty]
- # scatter to dim=1
- # expand index to [B, Ty, D]
- idx_y3 = idx_y.unsqueeze(-1).expand(B, Ty, D)
- y_pos_b = y_pos.expand(B, Ty, D).to(xy_pos.dtype) # [B, Ty, D]
- xy_pos = xy_pos.scatter(1, idx_y3, y_pos_b)
-
- return xy_pos, x_len
-
-
-def torchscript_export(model: T2SDecoderONNX, stage="embed"):
- if stage == "embed":
- x = torch.randint(1, 600, (model.max_batch_size, 50))
- x_len = torch.randint(30, 50, (model.max_batch_size,))
- y = torch.randint(1, 600, (1, 200))
- bert_features = torch.rand((model.max_batch_size, 1024, 50))
-
- x_len[-1] = 50
-
- mask = torch.arange(x_len.max().item(), device=x.device).unsqueeze(0) < x_len.unsqueeze(1)
-
- x = x * mask
- bert_features = bert_features * mask.unsqueeze(1)
-
- try:
- a, c = model.embed_onnx_(x, x_len, y, bert_features)
- b, d = model.embed_onnx(x, x_len, y, bert_features)
- print("-" * 20)
- print(a - b, (a - b).sum(), (a - b).square().mean())
- # print(c - d, (c - d).sum(), (c - d).square().mean())
- exit()
- assert torch.allclose(a, b, atol=1e-6, rtol=1e-8), (a - b).square().mean()
-
- model.forward = model.embed_onnx
- scripted_model = torch.jit.script(model, example_inputs=[(x, x_len, y, bert_features)])
-
- onnx_program = torch.onnx.export(
- scripted_model,
- (x, x_len, y, bert_features),
- input_names=["text", "text_len", "prompt", "bert_features"],
- output_names=["xy_pos", "input_pos"],
- dynamic_axes={
- "text": {0: "Batch_Size", 1: "Sequence_Length_X"},
- "prompt": {0: "Batch_Size", 1: "Sequence_Length_Y"},
- "bert_features": {0: "Batch_Size", 1: "Sequence_Length_X"},
- },
- opset_version=21,
- training=False,
- do_constant_folding=True,
- external_data=False,
- )
- assert onnx_program
- onnx_program.save("onnx_export/AR_Embedding_TorchScript.onnx")
-
- except Exception:
- logger.bind(show_locals=False).exception("")
-
-
-def dynamo_export(model: T2SDecoderONNX, stage="embed"):
- if stage == "embed":
- x = torch.randint(1, 600, (model.max_batch_size, 50))
- x_len = torch.randint(30, 50, (model.max_batch_size,))
- y = torch.randint(1, 600, (1, 200))
- bert_features = torch.rand((model.max_batch_size, 1024, 50))
-
- x_len[-1] = 50
-
- mask = torch.arange(x_len.max().item(), device=x.device).unsqueeze(0) < x_len.unsqueeze(1)
-
- x = x * mask
- bert_features = (bert_features.transpose(1, 2) * mask.unsqueeze(-1)).transpose(1, 2)
-
- dynamic_shapes = [
- {
- 0: Dim("Batch_Size", min=1, max=4),
- 1: Dim("Sequence_Length_X", min=1, max=50),
- },
- {
- 0: Dim("Batch_Size", min=1, max=4),
- },
- {
- 1: Dim("Sequence_Length_Y", min=1, max=250),
- },
- {
- 0: Dim("Batch_Size", min=1, max=4),
- 2: Dim("Sequence_Length_X", min=1, max=50),
- },
- ]
- try:
- a = model.embed_onnx_(x, x_len, y, bert_features)[0]
- b = model.embed_onnx(x, x_len, y, bert_features)[0]
- print(a - b, (a - b).square().mean())
- exit()
- assert torch.allclose(a, b, atol=1e-6, rtol=1e-8), (a - b).square().mean()
-
- model.forward = model.embed_onnx
- onnx_program = torch.onnx.export(
- model,
- (x, x_len, y, bert_features),
- input_names=["text", "text_len", "prompt", "bert_features"],
- output_names=["xy_pos", "input_pos"],
- dynamo=True,
- dynamic_shapes=dynamic_shapes,
- opset_version=21,
- training=False,
- do_constant_folding=True,
- external_data=False,
- )
- assert onnx_program
- onnx_program.save("onnx_export/AR_Embedding_Dynamo.onnx")
- except Exception:
- logger.bind(show_locals=False).exception("")
-
-
-@app.command()
-def export(
- ckpt_path: Path = typer.Option( # noqa: B008
- ...,
- "--ckpt-path",
- file_okay=True,
- dir_okay=False,
- exists=True,
- readable=True,
- show_default=False,
- help="AR Checkpoint",
- ),
- dynamo: bool = typer.Option(False, is_flag=True, flag_value=True, help="Use Torch Dynamo"),
- stages: list[Stage] = typer.Option([Stage.embed], "--stages", help="Stage to export"), # noqa: B008
-):
- os.makedirs("onnx_export", exist_ok=True)
- dict_s1 = torch.load(ckpt_path, "cpu", mmap=True)
- condig = dict_s1["config"]
- model = T2SDecoderONNX(condig, 1500, 4)
- state_dict = dict_s1["weight"]
- model.load_state_dict(state_dict)
-
- for stage in stages:
- if dynamo:
- dynamo_export(model, stage)
- else:
- torchscript_export(model, stage)
-
-
-def get_prog_name() -> str:
- script_rel = ".".join(["GPT_SoVITS", "Accelerate", "PyTorch", osp.basename(__file__)]).strip(".py")
- return f"python -s -m {script_rel}"
-
-
-if __name__ == "__main__":
- t = time.perf_counter()
- app(prog_name=get_prog_name())
- logger.info(f"Exec Time: {time.perf_counter() - t:.2f} secs")
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/quantization.py b/GPT_SoVITS/Accel/PyTorch/AR/quantization.py
deleted file mode 100644
index 5d0c82b0..00000000
--- a/GPT_SoVITS/Accel/PyTorch/AR/quantization.py
+++ /dev/null
@@ -1,159 +0,0 @@
-from typing import Optional, cast
-
-import torch
-
-from .. import nn
-
-
-Tensor = torch.Tensor
-
-
-# based on ComfyUI's and MinusZoneAI's fp8_linear optimization
-def fp8_linear_forward(cls: nn.Linear, input: Tensor):
- weight_dtype = cls.weight.dtype
- base_dtype = input.dtype
- if weight_dtype in [torch.float8_e4m3fn, torch.float8_e5m2]:
- if len(input.shape) == 3:
- input_shape = input.shape
-
- scale_weight: Optional[Tensor] = getattr(cls, "scale_weight", None)
- if scale_weight is None:
- scale_weight = torch.ones((), device=input.device, dtype=torch.float32)
- else:
- scale_weight = scale_weight.to(input.device).squeeze()
-
- scale_input = torch.ones((), device=input.device, dtype=torch.float32)
-
- input = torch.clamp(input, min=-448, max=448, out=input)
- inn = (
- input.reshape(-1, input_shape[2]).to(torch.float8_e4m3fn).contiguous()
- ) # always e4m3fn because e5m2 * e5m2 is not supported
-
- bias = cls.bias if cls.bias is not None else None
-
- o = torch._scaled_mm(
- inn, cls.weight.t(), out_dtype=base_dtype, bias=bias, scale_a=scale_input, scale_b=scale_weight
- )
-
- return o.reshape((-1, input_shape[1], cls.weight.shape[0]))
- else:
- raise
- else:
- raise
-
-
-def convert_fp8_linear(
- module: nn.Module,
-):
- apply_fn = fp8_linear_forward
-
- for _, sub in list(module.named_modules()):
- if isinstance(sub, nn.Linear):
- if getattr(sub, "_fp8", False):
- continue
- sub.forward = apply_fn
- sub._fp8 = True
- return module
-
-
-def per_tensor_quantize(tensor: torch.Tensor) -> tuple[Tensor, Tensor]:
- """Quantize a tensor using per-tensor static scaling factor.
- Args:
- tensor: The input tensor.
- """
- finfo = torch.finfo(torch.float8_e4m3fn)
- # Calculate the scale as dtype max divided by absmax.
- # Since .abs() creates a new tensor, we use aminmax to get
- # the min and max first and then calculate the absmax.
- if tensor.numel() == 0:
- # Deal with empty tensors (triggered by empty MoE experts)
- min_val, max_val = (
- torch.tensor(0.0, dtype=tensor.dtype),
- torch.tensor(1.0, dtype=tensor.dtype),
- )
- else:
- min_val, max_val = tensor.aminmax()
- amax = min_val.abs().max(max_val.abs())
- scale = finfo.max / amax.clamp(min=1e-12)
- # scale and clamp the tensor to bring it to
- # the representative range of float8 data type
- # (as default cast is unsaturated)
- qweight = (tensor * scale).clamp(min=finfo.min, max=finfo.max)
- # Return both float8 data and the inverse scale (as float),
- # as both required as inputs to torch._scaled_mm
- qweight = qweight.to(torch.float8_e4m3fn)
- scale = scale.float().reciprocal()
- return qweight, scale
-
-
-def fp8_gemm(A, A_scale, B, B_scale, bias, out_dtype):
- cuda_compute_capability = torch.cuda.get_device_capability()
- if cuda_compute_capability >= (9, 0):
- output, _ = torch._scaled_mm(
- A,
- B.t(),
- out_dtype=out_dtype,
- scale_a=A_scale,
- scale_b=B_scale,
- bias=bias,
- )
- else:
- output = torch.nn.functional.linear(
- A.to(out_dtype) * A_scale,
- B.to(out_dtype) * B_scale.to(out_dtype),
- bias=bias,
- )
- return output
-
-
-class FP8DynamicLinear(nn.Module):
- def __init__(self, qweight: Tensor, scale: Tensor, bias: Tensor):
- super().__init__()
- self.weight = torch.nn.Parameter(qweight, requires_grad=False)
- self.weight_scale = torch.nn.Parameter(scale, requires_grad=False)
- self.bias = bias
-
- def __call__(self, x):
- qinput, x_scale = per_tensor_quantize(x)
- output = fp8_gemm(
- A=qinput,
- A_scale=x_scale,
- B=self.weight,
- B_scale=self.weight_scale,
- bias=self.bias,
- out_dtype=x.dtype,
- )
- return output
-
-
-def replace_all_linear_with_fp8(model: nn.Module):
- """
- Recursively replace every nn.Linear with FP8DynamicLinear in-place.
- """
-
- def _recursively_replace(parent: nn.Module):
- for child_name, child in list(parent.named_children()):
- child = cast(nn.Module, child)
- if isinstance(child, FP8DynamicLinear):
- continue
-
- if isinstance(child, nn.Linear):
- device = child.weight.device
-
- w = child.weight
-
- b = child.bias.clone()
-
- qw, qs = per_tensor_quantize(w)
-
- quant_linear = FP8DynamicLinear(qw, qs, b)
-
- quant_linear.to(device)
-
- setattr(parent, child_name, quant_linear)
-
- del child
- else:
- _recursively_replace(child)
-
- _recursively_replace(model)
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/runner.py b/GPT_SoVITS/Accel/PyTorch/AR/runner.py
index 490ebeee..df58fd30 100644
--- a/GPT_SoVITS/Accel/PyTorch/AR/runner.py
+++ b/GPT_SoVITS/Accel/PyTorch/AR/runner.py
@@ -10,11 +10,10 @@ from typing import Optional, TypeVar
import torch
from tools.acceleration import cuda_graph_available
-from ...logger import timer
from .sample_funcs import sample_naive
from .structs import KVCache, T2SRequest, T2SSession
-from .t2s_model_abc import T2SDecoderABC, TorchProfiler
+from .t2s_model_abc import T2SDecoderABC
T = TypeVar("T")
@@ -34,17 +33,6 @@ def _slice_tensors(obj: T, bsz: int) -> T:
return obj
-def _synchronize_device(device: torch.device) -> None:
- if device.type == "cuda":
- torch.cuda.synchronize()
- elif device.type == "mps":
- torch.mps.synchronize()
- elif device.type == "xpu":
- torch.xpu.synchronize()
- elif device.type == "mtia":
- torch.mtia.synchronize()
- elif device.type == "cpu":
- pass
class ModelRunner:
@@ -180,14 +168,11 @@ class ModelRunner:
kv_cache = self.decoder.init_cache(session.bsz)
- torch_profiler = TorchProfiler(request.debug)
- with torch_profiler.profiler(), timer("Torch.Prefill", debug=request.debug), torch.inference_mode():
- torch_profiler.start()
+ with torch.inference_mode():
xy_pos = self.decoder.embed(session.x, request.prompts, session.bert_feature)
xy_dec = self.decoder.h.prefill(xy_pos, kv_cache, session.attn_mask)
gather_index = (session.input_pos - 1).long().view(session.bsz, 1, 1)
session.prefill_hidden = torch.take_along_dim(xy_dec, gather_index, dim=1)
- torch_profiler.end()
session.kv_cache = kv_cache
@@ -290,118 +275,109 @@ class ModelRunner:
use_graph = self._should_use_graph() and bool(forward_slots)
- debug = any(session.request.debug for session in self.bound_sessions)
-
- try:
- with torch.inference_mode():
- if forward_slots:
- forward_len = max(forward_slots) + 1
- model_len = self._select_bsz(forward_len) if use_graph else forward_len
- kwds = decoder.pre_forward_slots_hook(list(range(model_len)), self)
- if use_graph:
- graph = self._acquire_graph(model_len)
- graph.replay()
- else:
- self.xy_dec_buf[:forward_len] = decoder.h(
- self.xy_pos_buf[:forward_len],
- self.input_pos_buf[:forward_len],
- _slice_tensors(self.kv_cache_buf, forward_len),
- **kwds,
- )
-
- # Bind any newly ready sessions after decode and before sampling
- if self.waiting_bind and self.free_slots() > 0:
- self._bind_waiting_sessions()
- if not debug:
- debug = any(session.request.debug for session in self.bound_sessions)
-
- for slot_idx, session in enumerate(self.slot_sessions):
- if session is None:
- continue
- if session.step_count == 0:
- prefill_slots.append(slot_idx)
-
- active_slots = forward_slots + prefill_slots
- if not active_slots:
- return []
-
- idx_tensor = torch.tensor(active_slots, device=self.device, dtype=torch.long)
-
- logits_all = decoder.ar_predict_layer(self.xy_dec_buf[idx_tensor].squeeze(1))
-
- first_step_mask = (self.step_buf[idx_tensor] == 0).bool()
-
- if torch.any(first_step_mask):
- logits_all[first_step_mask, -1] = float("-inf")
-
- sampler = self.sampler
-
- samples = sampler(
- logits=logits_all,
- valid_lens=self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor],
- previous_tokens=self.y_buf[idx_tensor],
- repetition_penalty=self.repetition_penalty_buf[idx_tensor],
- temperature=self.temperature_buf[idx_tensor],
- top_k=self.top_k_buf[idx_tensor],
- top_p=self.top_p_buf[idx_tensor],
- )
-
- argmax_token = torch.argmax(logits_all, dim=-1)
- eos_mask_all = torch.logical_or((argmax_token == decoder.EOS), (samples.squeeze(1) == decoder.EOS))
-
- y_emb_all = decoder.ar_audio_embedding(samples.clamp_max_(decoder.vocab_size - 2))
- pos_offset = self.step_buf[idx_tensor] + self.prompt_len_buf[idx_tensor] + 1
- next_xy_all = decoder.ar_audio_position(pos_offset, y_emb_all)
-
- sample_vals = samples.squeeze(1)
- write_pos = self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor]
-
- # Only write for slots that are not already done and not EOS
- write_mask = (~self.completed_buf[idx_tensor]) & (~eos_mask_all)
- if torch.any(write_mask):
- write_slots = idx_tensor[write_mask]
- self.y_buf[write_slots, write_pos[write_mask]] = sample_vals[write_mask]
- self.input_pos_buf[write_slots] += 1
-
- new_step = self.step_buf[idx_tensor].clone()
- new_step[write_mask] += 1
- forced_stop = new_step >= self.max_step_buf[idx_tensor]
- self.step_buf[idx_tensor] = new_step
- self.completed_buf[idx_tensor] |= eos_mask_all | forced_stop
- done_slots = idx_tensor[self.completed_buf[idx_tensor]]
- # Graph buckets also execute inactive rows, so their cache position must remain valid.
- self.input_pos_buf[done_slots] = 1
-
- # Update next xy for continuing slots
- continue_mask = ~(self.completed_buf[idx_tensor])
- if torch.any(continue_mask):
- cont_slots = idx_tensor[continue_mask]
- cont_xy = next_xy_all[continue_mask]
- self.xy_pos_buf[cont_slots] = cont_xy
-
- # Sync back
- for slots in list(self.session_slots.values()):
- if not slots:
- continue
- session = self.slot_sessions[slots[0]]
- if session is None:
- continue
- session.output_lengths = self.step_buf[slots].tolist()
- session.step_count = max(session.output_lengths)
- session.total_tokens = sum(session.output_lengths)
- session.completed = self.completed_buf[slots].clone()
- if bool(torch.all(session.completed)):
- session.y_results = [
- self.y_buf[slot, session.prompt_len : session.prompt_len + length].clone()
- for slot, length in zip(slots, session.output_lengths)
- ]
- finished_sessions.append(session)
- self.unbind_session(session)
-
- decoder.post_forward_slots_hook(forward_slots, self)
-
- finally:
- if debug:
- _synchronize_device(self.device)
+ with torch.inference_mode():
+ if forward_slots:
+ forward_len = max(forward_slots) + 1
+ model_len = self._select_bsz(forward_len) if use_graph else forward_len
+ kwds = decoder.pre_forward_slots_hook(list(range(model_len)), self)
+ if use_graph:
+ graph = self._acquire_graph(model_len)
+ graph.replay()
+ else:
+ self.xy_dec_buf[:forward_len] = decoder.h(
+ self.xy_pos_buf[:forward_len],
+ self.input_pos_buf[:forward_len],
+ _slice_tensors(self.kv_cache_buf, forward_len),
+ **kwds,
+ )
+
+ # Bind any newly ready sessions after decode and before sampling
+ if self.waiting_bind and self.free_slots() > 0:
+ self._bind_waiting_sessions()
+
+ for slot_idx, session in enumerate(self.slot_sessions):
+ if session is None:
+ continue
+ if session.step_count == 0:
+ prefill_slots.append(slot_idx)
+
+ active_slots = forward_slots + prefill_slots
+ if not active_slots:
+ return []
+
+ idx_tensor = torch.tensor(active_slots, device=self.device, dtype=torch.long)
+
+ logits_all = decoder.ar_predict_layer(self.xy_dec_buf[idx_tensor].squeeze(1))
+
+ first_step_mask = (self.step_buf[idx_tensor] == 0).bool()
+
+ if torch.any(first_step_mask):
+ logits_all[first_step_mask, -1] = float("-inf")
+
+ sampler = self.sampler
+
+ samples = sampler(
+ logits=logits_all,
+ valid_lens=self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor],
+ previous_tokens=self.y_buf[idx_tensor],
+ repetition_penalty=self.repetition_penalty_buf[idx_tensor],
+ temperature=self.temperature_buf[idx_tensor],
+ top_k=self.top_k_buf[idx_tensor],
+ top_p=self.top_p_buf[idx_tensor],
+ )
+
+ argmax_token = torch.argmax(logits_all, dim=-1)
+ eos_mask_all = torch.logical_or((argmax_token == decoder.EOS), (samples.squeeze(1) == decoder.EOS))
+
+ y_emb_all = decoder.ar_audio_embedding(samples.clamp_max_(decoder.vocab_size - 2))
+ pos_offset = self.step_buf[idx_tensor] + self.prompt_len_buf[idx_tensor] + 1
+ next_xy_all = decoder.ar_audio_position(pos_offset, y_emb_all)
+
+ sample_vals = samples.squeeze(1)
+ write_pos = self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor]
+
+ # Only write for slots that are not already done and not EOS
+ write_mask = (~self.completed_buf[idx_tensor]) & (~eos_mask_all)
+ if torch.any(write_mask):
+ write_slots = idx_tensor[write_mask]
+ self.y_buf[write_slots, write_pos[write_mask]] = sample_vals[write_mask]
+ self.input_pos_buf[write_slots] += 1
+
+ new_step = self.step_buf[idx_tensor].clone()
+ new_step[write_mask] += 1
+ forced_stop = new_step >= self.max_step_buf[idx_tensor]
+ self.step_buf[idx_tensor] = new_step
+ self.completed_buf[idx_tensor] |= eos_mask_all | forced_stop
+ done_slots = idx_tensor[self.completed_buf[idx_tensor]]
+ # Graph buckets also execute inactive rows, so their cache position must remain valid.
+ self.input_pos_buf[done_slots] = 1
+
+ # Update next xy for continuing slots
+ continue_mask = ~(self.completed_buf[idx_tensor])
+ if torch.any(continue_mask):
+ cont_slots = idx_tensor[continue_mask]
+ cont_xy = next_xy_all[continue_mask]
+ self.xy_pos_buf[cont_slots] = cont_xy
+
+ # Sync back
+ for slots in list(self.session_slots.values()):
+ if not slots:
+ continue
+ session = self.slot_sessions[slots[0]]
+ if session is None:
+ continue
+ session.output_lengths = self.step_buf[slots].tolist()
+ session.step_count = max(session.output_lengths)
+ session.total_tokens = sum(session.output_lengths)
+ session.completed = self.completed_buf[slots].clone()
+ if bool(torch.all(session.completed)):
+ session.y_results = [
+ self.y_buf[slot, session.prompt_len : session.prompt_len + length].clone()
+ for slot, length in zip(slots, session.output_lengths)
+ ]
+ finished_sessions.append(session)
+ self.unbind_session(session)
+
+ decoder.post_forward_slots_hook(forward_slots, self)
return finished_sessions
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/structs.py b/GPT_SoVITS/Accel/PyTorch/AR/structs.py
index 348b91fd..2e5c6cfd 100644
--- a/GPT_SoVITS/Accel/PyTorch/AR/structs.py
+++ b/GPT_SoVITS/Accel/PyTorch/AR/structs.py
@@ -50,7 +50,6 @@ class T2SRequest:
request_id: Union[str, int] = -1
stream_interval: Optional[int] = None
return_partial: bool = True
- debug: bool = False
max_decode_steps: Optional[int] = None
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py b/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py
index 52185b0d..a506277f 100644
--- a/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py
+++ b/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py
@@ -13,7 +13,7 @@ from typing import Literal, Optional, Union
import torch
from rich.progress import BarColumn, Progress, TextColumn
-from ...logger import SpeedColumnToken, Timer, console, logger
+from ...logger import SpeedColumnToken, console, logger
from .runner import ModelRunner
from .structs import (
@@ -27,8 +27,6 @@ from .structs import (
from .t2s_model_abc import T2SDecoderABC
-timer = Timer("T2S Engine Torch")
-
cpu = torch.device("cpu")
empty_result = T2SResult(
@@ -340,7 +338,6 @@ class T2SEngine(T2SEngineProtocol):
weights_path: os.PathLike,
max_batch_size: int = 1,
backend: str = "Flash-Attn-Varlen-CUDAGraph",
- quantize_mode: Optional[Literal["Int8", "FP8", "FP8_E4M3FN"]] = None,
max_seq_length: Optional[int] = None,
) -> T2SDecoderABC:
logger.info(f"Loading Text2Semantic Weights from {weights_path} with {backend} Backend")
@@ -360,8 +357,4 @@ class T2SEngine(T2SEngineProtocol):
state_dict = dict_s1["weight"]
decoder.load_state_dict(state_dict)
- if quantize_mode is not None:
- decoder.quantize(quantize_mode)
- logger.info(f"Quantized by {quantize_mode} Quantization")
-
return decoder.eval()
diff --git a/GPT_SoVITS/Accel/PyTorch/AR/t2s_model_abc.py b/GPT_SoVITS/Accel/PyTorch/AR/t2s_model_abc.py
index 6a8e30b2..1585d83a 100644
--- a/GPT_SoVITS/Accel/PyTorch/AR/t2s_model_abc.py
+++ b/GPT_SoVITS/Accel/PyTorch/AR/t2s_model_abc.py
@@ -5,19 +5,14 @@ Modified From https://github.com/XXXXRT666/GPT-SoVITS
from __future__ import annotations
import math
-import os
-import time
from abc import ABC, abstractmethod
from collections.abc import Callable, MutableSequence
-from contextlib import nullcontext
-from typing import TYPE_CHECKING, Any, Literal, Optional
+from typing import TYPE_CHECKING, Any, Optional
import torch
import torch.nn.functional as F
-from torch.profiler import ProfilerAction, tensorboard_trace_handler
from .. import nn
-from .quantization import replace_all_linear_with_fp8
from .structs import KVCache, KVCacheProtocol, T2SSession
@@ -422,9 +417,6 @@ class T2SDecoderABC(nn.Module, ABC):
self.graph_applicable: bool = False
self.extra_buffer_factory: Callable[[int, T2SDecoderABC], dict[str, torch.Tensor]] = lambda *_: {}
- self.bits: int
- self.group_size: int
-
self._register_load_state_dict_pre_hook(self.load_hook)
def load_hook(self, state_dict: dict[str, Tensor], prefix, *args):
@@ -534,95 +526,4 @@ class T2SDecoderABC(nn.Module, ABC):
mask[:bsz].zero_()
mask[:bsz, :, :, 0] = True
kwds["attn_mask"] = mask
- return args, kwds
-
- def quantize(self, mode: Optional[Literal["Int8", "FP8", "FP8_E4M3FN"]] = None) -> None:
- if mode is None:
- return
- if mode not in {"Int8", "FP8", "FP8_E4M3FN"}:
- raise ValueError(f"Unsupported quantization mode: {mode}")
- if mode == "Int8":
- self.bits = 8
- self.group_size = 32
- import torchao
-
- torchao.quantization.quantize_(self.h, torchao.quantization.Int8WeightOnlyConfig(self.group_size))
-
- elif mode == "FP8":
- self.bits = 8
- import torchao
-
- torchao.quantization.quantize_(self.h, torchao.quantization.Float8WeightOnlyConfig())
-
- elif mode == "FP8_E4M3FN":
- self.bits = 8
- replace_all_linear_with_fp8(self.h)
-
- else:
- raise ValueError(f"Unsupported Quantization Mode for PyTorch: {mode}")
-
-
-class TorchProfiler:
- def __init__(self, debug: bool, log_dir: str = "./profiler/torch") -> None:
- self.debug = debug and os.environ.get("TORCH_PROFILER") == "1"
- self.log_dir = log_dir + "/" + str(time.time())
- self.__profiler: torch.profiler.profile
-
- if self.debug and not os.path.exists(self.log_dir):
- os.makedirs(self.log_dir, exist_ok=True)
-
- self.tensorboard_handler = tensorboard_trace_handler(self.log_dir)
-
- def profiler_callback(self, prof: torch.profiler.profile):
- print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=30))
- print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=30))
- self.tensorboard_handler(prof)
-
- @staticmethod
- def three_step_schedule(step: int) -> ProfilerAction:
- if step == 0:
- return ProfilerAction.NONE
- elif step == 1:
- return ProfilerAction.RECORD
- elif step == 2:
- return ProfilerAction.RECORD_AND_SAVE
- else:
- return ProfilerAction.RECORD_AND_SAVE
-
- def start(self):
- if not self.debug:
- return
- assert self.__profiler is not None
- self.__profiler.step()
-
- def end(self):
- if not self.debug:
- return
- assert self.__profiler is not None
- self.__profiler.step()
-
- def profiler(self):
- if self.debug:
- activities_list = [torch.profiler.ProfilerActivity.CPU]
- if torch.cuda.is_available():
- activities_list.append(torch.profiler.ProfilerActivity.CUDA)
-
- self.__profiler = torch.profiler.profile(
- activities=activities_list,
- record_shapes=True,
- with_stack=True,
- with_modules=True,
- with_flops=True,
- profile_memory=True,
- schedule=self.three_step_schedule,
- on_trace_ready=self.profiler_callback,
- )
- return self.__profiler
- else:
- return nullcontext()
-
- def record(self, func_name: str):
- if self.debug:
- return torch.profiler.record_function(func_name)
- else:
- return nullcontext()
+ return args, kwds
diff --git a/GPT_SoVITS/Accel/PyTorch/G2PW/model.py b/GPT_SoVITS/Accel/PyTorch/G2PW/model.py
deleted file mode 100644
index ffc3a414..00000000
--- a/GPT_SoVITS/Accel/PyTorch/G2PW/model.py
+++ /dev/null
@@ -1,238 +0,0 @@
-import math
-from collections.abc import MutableSequence
-from pathlib import Path
-
-import torch
-from transformers import BertConfig
-
-from .. import nn
-from ..nn import functional as F
-
-
-Tensor = torch.Tensor
-
-
-class MultiHeadAttention(nn.Module):
- def __init__(
- self,
- dims: int,
- num_heads: int,
- ):
- super().__init__()
-
- assert dims % num_heads == 0, "The input feature dimensions should be divisible by the number of heads"
-
- self.num_heads = num_heads
- self.query_proj = nn.Linear(dims, dims)
- self.key_proj = nn.Linear(dims, dims)
- self.value_proj = nn.Linear(dims, dims)
- self.out_proj = nn.Linear(dims, dims)
- self.scale = math.sqrt(1 / dims)
-
- def __call__(self, x: Tensor):
- B, L, _ = x.shape
- queries = self.query_proj(x)
- keys = self.key_proj(x)
- values = self.value_proj(x)
-
- num_heads = self.num_heads
- queries = queries.view(B, L, num_heads, -1).transpose(1, 2)
- keys = keys.view(B, L, num_heads, -1).transpose(1, 2)
- values = values.view(B, L, num_heads, -1).transpose(1, 2)
- output = F.scaled_dot_product_attention(queries, keys, values, scale=self.scale)
- output = output.transpose(1, 2).reshape(B, L, -1)
- return self.out_proj(output)
-
-
-class TransformerEncoderLayer(nn.Module):
- """
- A transformer encoder layer with (the original BERT) post-normalization.
- """
-
- def __init__(
- self,
- dims: int,
- num_heads: int,
- mlp_dims: int,
- layer_norm_eps: float = 1e-12,
- ):
- super().__init__()
-
- self.attention = MultiHeadAttention(dims, num_heads)
- self.attention_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
- self.ffn_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
- self.linear1 = nn.Linear(dims, mlp_dims)
- self.linear2 = nn.Linear(mlp_dims, dims)
- self.gelu = nn.GELU()
-
- def __call__(self, x: Tensor):
- attention_out = self.attention(x)
- add_and_norm = self.attention_norm(x + attention_out)
-
- ff = self.linear1(add_and_norm)
- ff_gelu = self.gelu(ff)
- ff_out = self.linear2(ff_gelu)
- x = self.ffn_norm(ff_out + add_and_norm)
-
- return x
-
-
-class TransformerEncoder(nn.Module):
- def __init__(self, num_layers: int, dims: int, num_heads: int, mlp_dims: int):
- super().__init__()
- self.layers: MutableSequence[TransformerEncoderLayer] = nn.ModuleList(
- [TransformerEncoderLayer(dims, num_heads, mlp_dims) for _ in range(num_layers)]
- ) # type: ignore
-
- def __call__(self, x: Tensor):
- for layer in self.layers:
- x = layer(x)
-
- return x
-
-
-class BertEmbeddings(nn.Module):
- def __init__(self, config: BertConfig):
- super().__init__()
- self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
- self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
- self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
- self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.requires_grad_(False)
-
- def __call__(self, input_ids: Tensor):
- words = self.word_embeddings(input_ids)
- position = self.position_embeddings.weight[: input_ids.shape[1]]
- token_types = self.token_type_embeddings.weight[0]
-
- embeddings = position + words + token_types
- return self.norm(embeddings)
-
-
-class Bert(nn.Module):
- def __init__(self, config: BertConfig):
- super().__init__()
- self.embeddings = BertEmbeddings(config)
- self.encoder = TransformerEncoder(
- num_layers=config.num_hidden_layers,
- dims=config.hidden_size,
- num_heads=config.num_attention_heads,
- mlp_dims=config.intermediate_size,
- )
-
- def __call__(
- self,
- input_ids: Tensor,
- ):
- x = self.embeddings(input_ids)
-
- y = self.encoder(x)
- return y
-
-
-class G2PW(nn.Module):
- def __init__(
- self,
- config: BertConfig,
- num_labels: int = 1305,
- num_chars: int = 3582,
- num_pos_tags: int = 11,
- ):
- super().__init__()
- self.config = config
- self.num_labels = num_labels
- self.num_chars = num_chars
- self.num_pos_tags = num_pos_tags
- target_size = self.num_labels
-
- self.bert = Bert(config)
- self.pos_classifier = nn.Linear(self.config.hidden_size, self.num_pos_tags)
- self.descriptor_bias = nn.Embedding(1, target_size)
- self.char_descriptor = nn.Embedding(self.num_chars, target_size)
- self.second_order_descriptor = nn.Embedding(self.num_chars * self.num_pos_tags, target_size)
- self.classifier = nn.Linear(self.config.hidden_size, self.num_labels)
-
- def _weighted_softmax(self, logits: Tensor, weights: Tensor, eps: float):
- max_logits, _ = torch.max(logits, dim=-1, keepdim=True)
- weighted_exp_logits = torch.exp(logits - max_logits) * weights
- norm = torch.sum(weighted_exp_logits, dim=-1, keepdim=True)
- probs = weighted_exp_logits / norm
- probs = torch.clamp(probs, min=eps, max=1 - eps)
-
- return probs
-
- def _get_char_pos_ids(self, char_ids: Tensor, pos_ids: Tensor):
- return char_ids * self.num_pos_tags + pos_ids
-
- def __call__(
- self,
- input_ids: Tensor,
- phoneme_mask: Tensor,
- char_ids: Tensor,
- position_ids: Tensor,
- eps: float = 1e-6,
- ):
- input_ids = input_ids.to(self.device)
- phoneme_mask = phoneme_mask.to(self.device)
- char_ids = char_ids.to(self.device)
- position_ids = position_ids.to(self.device)
-
- sequence_output = self.bert(
- input_ids=input_ids,
- )
-
- orig_selected_hidden = torch.take_along_dim(
- sequence_output,
- position_ids.view(-1, 1, 1),
- dim=1,
- ).squeeze(1)
-
- pred_pos_ids = self.pos_classifier(orig_selected_hidden).argmax(dim=-1) # teacher mode while training
-
- bias_tensor = self.descriptor_bias(torch.zeros_like(char_ids))
-
- char_pos_ids = self._get_char_pos_ids(char_ids, pred_pos_ids)
-
- affect_hidden = bias_tensor + self.char_descriptor(char_ids) + self.second_order_descriptor(char_pos_ids)
-
- phoneme_mask = phoneme_mask * torch.sigmoid(affect_hidden)
-
- logits = self.classifier(orig_selected_hidden)
-
- probs = self._weighted_softmax(logits, phoneme_mask, eps)
-
- pred_idx = probs.argmax(dim=1)
-
- return pred_idx
-
-
-def replace_key(key: str) -> str:
- key = key.replace(".layer.", ".layers.")
- key = key.replace(".self.key.", ".key_proj.")
- key = key.replace(".self.query.", ".query_proj.")
- key = key.replace(".self.value.", ".value_proj.")
- key = key.replace(".attention.output.dense.", ".attention.out_proj.")
- key = key.replace(".attention.output.LayerNorm.", ".attention_norm.")
- key = key.replace(".output.LayerNorm.", ".ffn_norm.")
- key = key.replace(".intermediate.dense.", ".linear1.")
- key = key.replace(".output.dense.", ".linear2.")
- key = key.replace(".LayerNorm.", ".norm.")
- return key
-
-
-def load_g2pw_torch(bert_model: str, weights_path: str, device: torch.device, dtype: torch.dtype) -> G2PW:
- if not Path(weights_path).exists():
- raise ValueError(f"No model weights found in {weights_path}")
-
- config = BertConfig.from_pretrained(bert_model)
-
- # create and update the model
- model = G2PW(config)
- state_dict: dict[str, Tensor] = torch.load(weights_path, map_location="cpu")
- state_dict_torch: dict[str, Tensor] = {}
- for key, value in state_dict.items():
- key = replace_key(key)
- state_dict_torch[key] = value
- model.load_state_dict(state_dict_torch)
-
- return model.to(device, dtype)
diff --git a/GPT_SoVITS/Accel/PyTorch/__init__.py b/GPT_SoVITS/Accel/PyTorch/__init__.py
index cf6dc75c..b5ad3b92 100644
--- a/GPT_SoVITS/Accel/PyTorch/__init__.py
+++ b/GPT_SoVITS/Accel/PyTorch/__init__.py
@@ -1,15 +1,7 @@
-import importlib.util
import os
-from typing import Optional
import torch
-from .AR.sample_funcs import sample_naive
-from .AR.structs import T2SRequest, T2SResult
-from .AR.t2s_engine import T2SEngine as T2SEngineTorch
-from .G2PW.model import load_g2pw_torch
-
-
torch.set_grad_enabled(False)
if torch.__version__ >= "2.9.0":
@@ -26,47 +18,4 @@ torch.backends.cudnn.enabled = True
cpu_count = os.cpu_count() or 1
torch.set_num_threads(cpu_count)
-torch.set_num_interop_threads(cpu_count)
-
-backends = ["torch_varlen"]
-if torch.cuda.is_available() and torch.version.cuda is not None:
- backends.append("torch_static_cuda_graph")
- # if importlib.util.find_spec("sageattention") is not None:
- # for i in range(torch.cuda.device_count()):
- # major, minor = torch.cuda.get_device_capability(i)
- # sm_version = major + minor / 10.0
- # if sm_version >= 7.0:
- # backends.append("sage_attn_varlen_cuda_graph")
- if importlib.util.find_spec("flash_attn") is not None:
- for i in range(torch.cuda.device_count()):
- major, minor = torch.cuda.get_device_capability(i)
- sm_version = major + minor / 10.0
- if sm_version >= 7.5:
- backends.append("flash_attn_varlen_cuda_graph")
-
-BLACKWELL = False
-if torch.cuda.is_available() and torch.version.cuda is not None:
- for i in range(torch.cuda.device_count()):
- major, minor = torch.cuda.get_device_capability(i)
- sm_version = major + minor / 10.0
- if sm_version >= 9.0:
- BLACKWELL = True
-
-quantization_methods_torch: list[Optional[str]] = [None]
-if importlib.util.find_spec("torchao") is not None:
- quantization_methods_torch.append("Int8")
- if BLACKWELL:
- quantization_methods_torch.append("FP8")
-if BLACKWELL:
- quantization_methods_torch.append("FP8_E4M3FN")
-
-
-__all__ = [
- "T2SEngineTorch",
- "T2SRequest",
- "sample_naive",
- "T2SResult",
- "backends",
- "quantization_methods_torch",
- "load_g2pw_torch",
-]
+torch.set_num_interop_threads(cpu_count)
diff --git a/GPT_SoVITS/Accel/README.md b/GPT_SoVITS/Accel/README.md
deleted file mode 100644
index 8fe2e594..00000000
--- a/GPT_SoVITS/Accel/README.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Accel 通用运行说明
-
-本目录及配套修改代码统一用于 `gsvv5/py312` 和 `gsvv5/py39` 下的四套包。各自 runtime 保留:py312 为 Torch 2.7.1+cu118 / 2.7.1+cu128,py39 为 Torch 2.0.0+cu118 / 2.7.0+cu128。运行依赖不随源码统一而替换。
-
-## 目录与依赖
-
-- `GPT_SoVITS/Accel` 包含 PyTorch/MLX 后端、适配器、日志模块和 `vendor/cuda/bin/cudart64_12.dll`。
-- py312 的 FlashAttention 2.8.3 通过标准 pip 安装在各自 `runtime/Lib/site-packages`;不从外置测试目录导入。两套 py39 未安装 FlashAttention,对应控件自动隐藏。
-- `tools/acceleration.py` 负责能力选择,`tools/portable_runtime.py` 负责便携环境、DLL 搜索路径和 Transformers 兼容初始化。
-- 正常推理不依赖 `others`;测试、备份、网络 requirements 和补丁 ZIP 均放在 `others`。
-- 超分配置 `tools/AP_BWE_main/24kto48k/config.json` 保留。原版 BigVGAN/UVR 运行文件、模型权重及 runtime 未删除。
-
-## 自动推理路线
-
-Graph 和外部 FlashAttention 分别识别,按实际推理设备、精度与用户开关选择:
-
-| 启用 FlashAttention | 有效 CUDA Graph | 非流式 AR |
-| --- | --- | --- |
-| 是 | 是 | FlashAttention + Graph |
-| 是 | 否 | FlashAttention eager |
-| 否 | 是 | 纯 Torch SDPA Graph |
-| 否 | 否 | 原始普通 AR |
-
-主 WebUI 未勾选“启用并行推理版本”时,普通子 WebUI 固定逐句 `bs=1`,Accel 容量为 1,只捕获单批 Graph,不提供 batch size 或并行开关。勾选后启动快速子 WebUI,保留原 `batch_size` 滑块(1–200,默认 20),固定并行,Accel 容量随滑块调整。
-
-两个子 WebUI 都只提供 `CUDA Graph` 和 `flash_attn` 两个加速开关。启动时分别判断当前设备能力;支持时默认勾选、显示且可修改,不支持时默认关闭、隐藏且不可修改。用户可以独立关闭任一能力,`CUDAGraph=0` 仍禁用 Graph。真正 token 流式保留原实现,API 的 `parallel_infer` 参数保留。
-
-Graph 实际捕获失败时,Flash 继续 eager,纯 Torch Graph 回普通 AR;记录失败状态,避免反复捕获。权重加载和实际推理错误正常抛出,不隐藏为能力缺失。尊重传入 dtype,不强制 FP32 转 FP16。换权重、设备或精度时关闭旧引擎。
-
-## 中文 G2PW DLL 修复
-
-普通版 ONNX Runtime 1.18.0 需要 CUDA 11 / cuDNN 8,而 Torch 自带 cuDNN 9。配套 cuDNN 8 已安装在 `runtime/Lib/site-packages/nvidia/*/bin`。初始化现会注册存在的 DLL 目录,并加入当前进程 PATH,以支持 cuDNN 动态加载其组件 DLL。
-
-此处理也适用于 CUDA 12 环境的 Torch DLL。未修改系统 PATH、CUDA_PATH、库版本或 site-packages,未把 G2PW 改成 CPU。UVR5 的 `onnx_dereverb_By_FoxJoy` 创建 ONNX Runtime 会话前也调用同一 DLL 初始化,因此该模型可使用 CUDA/cuDNN。已经运行的推理窗口需要重新启动才能加载修改。
-
-## 兼容与安装
-
-Accel 源码采用 Python 3.9 兼容语法;旧 Torch 不支持的六项 `_inductor.config` 内部设置已移除,权重加载仅在支持时传 `mmap`。语法兼容不代表旧 py39 环境的全部功能已实测。
-
-以下五项不再设置:`preferred_blas_library`、`ExecutionTraceObserver`、`torch.compiler.disable` 包装、`allow_fp16_accumulation=True`、`allow_fp16_bf16_reduction_math_sdp(True)`。原有可选 Torch profiler/TensorBoard 保留,uvloop 是可选依赖。
-
-四份网络安装清单位于 `others/requirements-py312-win-flash_attention`,按 cu118/cu128 和国内 ModelScope/国外 Hugging Face 选择。适用于 Windows x64、CPython 3.12、Torch 2.7.1;先安装匹配 Torch,再使用清单。现有 FlashAttention cp312 Windows wheel 不能用于 Python 3.9 或 Linux。网络清单尚未在空白环境完成全部安装测试。
-
-## 通用补丁
-
-`gsvv5/py312/others/add_accel/GPT-SoVITS_add_accel.zip` 是四套包共用的唯一当前补丁。ZIP 保留项目相对路径,直接解压至目标项目根目录。四套 runtime 不互相覆盖。
-
-包含 Accel 完整发布内容(Python 源码、此说明及 vendor CUDA DLL),加上目录外新增 3 个、修改 9 个文件;其中 `tools/portable_runtime.py` 已包含最新 G2PW DLL 修复,`tools/uvr5/mdxnet.py` 已包含 FoxJoy ONNX CUDA DLL 修复。不包含 runtime、site-packages、FlashAttention wheel、模型权重、测试结果或 `__pycache__`。
-
-## 已完成的运行测试
-
-本机 RTX 3090,两套 Python 3.12 环境均完成适配器模式切换、无参考文本、v2 TTS 四种 Graph/并行组合;各完成八种能力缺失/捕获失败/流式切换场景,均产生音频。
-
-最新中文测试使用 `s1v3.ckpt` 与 `s2Gv2ProPlus.pth`:两套 G2PW 均使用 CUDAExecutionProvider,成功处理中文文本,并完成并行 Graph 和串行 eager 完整 TTS。
-
-py312 普通子 WebUI 已完成四种 Flash/Graph 开关组合及重新开启双开的真实合成,均为 `bs=1`;关闭两者时使用原始 AR。快速子 WebUI 保留默认 `bs=20` 滑块,已检查 1、20、40、200 的参数绑定;本轮未重复执行用户已确认成功的四环境并行 TTS。py312 控件默认双开,py39 缺 Flash 时正确隐藏该控件,CPU 下两个控件均默认关闭且隐藏。
-
-四套 runtime 均通过真实 `tools/uvr5/webui.py` 的 FoxJoy 去混响入口,性能记录每套含 278 次 `CUDAExecutionProvider` 节点执行、无 CPU 模型节点。人声与伴奏输出均为 44.1 kHz 双声道;py39 NVIDIA 的 MDX 初始化调用已补齐。测试输出位于各自 `others/<包名>/foxjoy_gpu_20261005_current`。
-
-未测试所有模型版本、其他 GPU、Linux/MLX;未试听或证明不同路线音质/输出等价。浏览器测试页停留在 Gradio 加载画面,控件与调用检查取自实际 Gradio 配置和入口函数,本轮不宣称浏览器端完整交互已通过。
-
-运行记录与报告位于 `others/<对应包名>`、`others/auto_acceleration_changes_20261005.md` 和 `others/onnx_chinese_fix_20261005.md`。历史分版结果保留在外置目录,不放进通用补丁。
diff --git a/GPT_SoVITS/Accel/__init__.py b/GPT_SoVITS/Accel/__init__.py
index 5d2dc387..e001160f 100644
--- a/GPT_SoVITS/Accel/__init__.py
+++ b/GPT_SoVITS/Accel/__init__.py
@@ -1,40 +1,9 @@
-from . import runtime
-from .logger import console, logger, tb
-
-from . import MLX, PyTorch
-from .MLX import quantization_methods_mlx
-from .PyTorch import T2SEngineTorch, T2SRequest, T2SResult, quantization_methods_torch
-from .PyTorch.AR.structs import T2SEngineProtocol
-
-
-import asyncio
-
-if runtime.os.name != "nt":
- try:
- import uvloop
- except ImportError:
- pass
- else:
- asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
-
-backends = PyTorch.backends + MLX.backends
-
-backends = [
- b.replace("_", "-").title().replace("Mlx", "MLX").replace("Mps", "MPS").replace("Cuda", "CUDA") for b in backends
-]
-
-
-__all__ = [
- "T2SEngineTorch",
- "T2SRequest",
- "T2SResult",
- "backends",
- "MLX",
- "PyTorch",
- "logger",
- "console",
- "tb",
- "T2SEngineProtocol",
- "quantization_methods_torch",
- "quantization_methods_mlx",
-]
+"""Optional PyTorch acceleration for the inference service."""
+
+import os
+
+from tools.portable_runtime import _prepare_dlls
+
+
+os.environ.setdefault("G2PW", "0")
+_prepare_dlls()
diff --git a/GPT_SoVITS/Accel/logger.py b/GPT_SoVITS/Accel/logger.py
index b03d852f..4db4cf1c 100644
--- a/GPT_SoVITS/Accel/logger.py
+++ b/GPT_SoVITS/Accel/logger.py
@@ -1,7 +1,4 @@
import sys
-import time
-from collections import defaultdict
-from contextlib import nullcontext
from typing import Optional
from loguru import logger
@@ -10,7 +7,7 @@ from rich.highlighter import Highlighter
from rich.logging import RichHandler
from rich.progress import Task, TextColumn
from rich.style import StyleType
-from rich.table import Column, Table
+from rich.table import Column
from rich.text import Text
from rich.traceback import Traceback, install
@@ -199,75 +196,3 @@ def tb(show_locals: bool = True):
__all__ = ["logger", "console", "tb", "SpeedColumnToken", "SpeedColumnIteration"]
-
-
-class Timer:
- def __init__(self, table_name: str = "Default Timer"):
- self.records: dict[str, list[float]] = defaultdict(list)
- self._stack: list[tuple[str, int]] = []
- self.table_name = table_name
-
- def __call__(self, category: str, debug=False):
- timer = self
-
- class _Ctx:
- def __enter__(self):
- timer._stack.append((category, time.perf_counter_ns()))
- return timer
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- end = time.perf_counter_ns()
- if not timer._stack:
- raise RuntimeError("Timer stack underflow: __exit__ without matching __enter__")
- cat, start = timer._stack.pop()
- if cat != category:
- raise RuntimeError(f"Mismatched timer context: expected '{cat}', got '{category}'")
- elapsed_sec = (end - start) / 1e9
- timer.records[cat].append(elapsed_sec)
- return False
-
- if debug:
- return _Ctx()
- else:
- return nullcontext()
-
- def clear(self):
- self.records.clear()
-
- def summary(self):
- if self.records.items():
- table = Table(title=self.table_name)
-
- table.add_column("Category", justify="left", style="cyan", no_wrap=True)
- table.add_column("Count", justify="right", style="magenta")
- table.add_column("Total (s)", justify="right", style="green")
- table.add_column("Average (s)", justify="right", style="yellow")
-
- for cat, times in self.records.items():
- total = sum(times)
- avg = total / len(times) if times else 0.0
- table.add_row(cat, str(len(times)), f"{total:.6f}", f"{avg:.6f}")
-
- console.print(table)
-
-
-timer = Timer()
-
-
-def format_sig(x: float, sig=4):
- if x > 10**sig:
- s = f"{x:.{sig + 1}g}"
- elif x < 1:
- s = f"{x:.{sig}f}"
- else:
- s = f"{x:.{sig}g}"
- if "e" in s or "E" in s:
- s = f"{float(s):f}"
- return s
-
-
-if __name__ == "__main__":
- try:
- raise RuntimeError()
- except Exception:
- logger.bind(show_locals=False).exception("TEST")
diff --git a/GPT_SoVITS/Accel/runtime.py b/GPT_SoVITS/Accel/runtime.py
deleted file mode 100644
index 1725140a..00000000
--- a/GPT_SoVITS/Accel/runtime.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from __future__ import annotations
-
-import os
-import sys
-from pathlib import Path
-
-
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
-ACCEL_ROOT = Path(__file__).resolve().parent
-VENDOR_ROOT = ACCEL_ROOT / "vendor"
-DLL_HANDLES = []
-
-os.environ.setdefault("G2PW", "0")
-if os.name == "nt":
- for directory in (
- VENDOR_ROOT / "cuda" / "bin",
- Path(sys.executable).resolve().parent / "Lib" / "site-packages" / "torch" / "lib",
- ):
- if directory.is_dir():
- DLL_HANDLES.append(os.add_dll_directory(str(directory)))
diff --git a/GPT_SoVITS/BigVGAN/README.md b/GPT_SoVITS/BigVGAN/README.md
deleted file mode 100644
index 2fa70cee..00000000
--- a/GPT_SoVITS/BigVGAN/README.md
+++ /dev/null
@@ -1,266 +0,0 @@
-## BigVGAN: A Universal Neural Vocoder with Large-Scale Training
-
-#### Sang-gil Lee, Wei Ping, Boris Ginsburg, Bryan Catanzaro, Sungroh Yoon
-
-[[Paper]](https://arxiv.org/abs/2206.04658) - [[Code]](https://github.com/NVIDIA/BigVGAN) - [[Showcase]](https://bigvgan-demo.github.io/) - [[Project Page]](https://research.nvidia.com/labs/adlr/projects/bigvgan/) - [[Weights]](https://huggingface.co/collections/nvidia/bigvgan-66959df3d97fd7d98d97dc9a) - [[Demo]](https://huggingface.co/spaces/nvidia/BigVGAN)
-
-[](https://paperswithcode.com/sota/speech-synthesis-on-libritts?p=bigvgan-a-universal-neural-vocoder-with-large)
-
-