Spaces:
Paused
Paused
j commited on
Commit ·
f98c92f
1
Parent(s): af25078
update to upstream chatterbox implementation, fixes token filtering/clamping
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+1
- chatterbox/src/chatterbox/__init__.py+15
- chatterbox/src/chatterbox/__pycache__/__init__.cpython-311.pycDeleted
- chatterbox/src/chatterbox/__pycache__/tts.cpython-311.pycDeleted
- chatterbox/src/chatterbox/__pycache__/utils.cpython-311.pycDeleted
- chatterbox/src/chatterbox/__pycache__/vc.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/__init__.pyAdded
- chatterbox/src/chatterbox/models/s3gen/__pycache__/__init__.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/const.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/decoder.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/f0_predictor.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/flow.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/flow_matching.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/hifigan.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/s3gen.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/__pycache__/xvector.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/configs.pyAdded+10
- chatterbox/src/chatterbox/models/s3gen/flow.py+89-41
- chatterbox/src/chatterbox/models/s3gen/flow_matching.py+1-11
- chatterbox/src/chatterbox/models/s3gen/matcha/__pycache__/decoder.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/matcha/__pycache__/flow_matching.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/matcha/__pycache__/transformer.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/s3gen.py+2-9
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/__init__.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/activation.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/attention.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/convolution.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/embedding.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/encoder_layer.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/positionwise_feed_forward.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/subsampling.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/upsample_encoder.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/utils/__pycache__/class_utils.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/utils/__pycache__/mask.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/utils/__pycache__/mel.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3gen/utils/mel.py+8-4
- chatterbox/src/chatterbox/models/s3tokenizer/__pycache__/__init__.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/s3tokenizer/__pycache__/s3tokenizer.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/__pycache__/__init__.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/__pycache__/llama_configs.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/__pycache__/t3.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/inference/__pycache__/alignment_stream_analyzer.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/inference/__pycache__/t3_hf_backend.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/inference/alignment_stream_analyzer.py+56-32
- chatterbox/src/chatterbox/models/t3/modules/__pycache__/cond_enc.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/modules/__pycache__/learned_pos_emb.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/modules/__pycache__/perceiver.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/modules/__pycache__/t3_config.cpython-311.pycDeleted
- chatterbox/src/chatterbox/models/t3/modules/t3_config.py+30-16
- chatterbox/src/chatterbox/models/t3/t3.py+56-34
7 unmodified lines89101112137 unmodified linesapp_file: app.pypinned: falseshort_description: Expressive Zeroshot TTS---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference7 unmodified lines8910111213147 unmodified linesapp_file: app.pypinned: falseshort_description: Expressive Zeroshot TTSpython_version: 3.10---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
12from .tts import ChatterboxTTSfrom .vc import ChatterboxVC1234567891011121314151617try:from importlib.metadata import version, PackageNotFoundErrortry:__version__ = version("chatterbox-tts")except PackageNotFoundError:__version__ = "0.1.4" # Default fallback versionexcept ImportError:from importlib_metadata import version, PackageNotFoundError # For Python <3.8try:__version__ = version("chatterbox-tts")except PackageNotFoundError:__version__ = "0.1.4"from .tts import ChatterboxTTSfrom .vc import ChatterboxVCfrom .mtl_tts import ChatterboxMultilingualTTS, SUPPORTED_LANGUAGES
12345678910from ..utils import AttrDict
CFM_PARAMS = AttrDict({ "sigma_min": 1e-06, "solver": "euler", "t_scheduler": "cosine", "training_cfg_rate": 0.2, "inference_cfg_rate": 0.7, "reg_loss_type": "l1"})13 unmodified lines141516171819202122232425262728293031323334353637383940414243444528 unmodified lines7475767778798043 unmodified lines12412512612712812913022 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617737 unmodified lines21521621721821922022113 unmodified linesimport loggingimport randomfrom typing import Dict, Optionalimport torchimport torch.nn as nnfrom torch.nn import functional as Ffrom omegaconf import DictConfigfrom .utils.mask import make_pad_maskclass MaskedDiffWithXvec(torch.nn.Module):def __init__(self,input_size: int = 512,output_size: int = 80,spk_embed_dim: int = 192,output_type: str = "mel",vocab_size: int = 4096,input_frame_rate: int = 50,only_mask_loss: bool = True,encoder: torch.nn.Module = None,length_regulator: torch.nn.Module = None,decoder: torch.nn.Module = None,decoder_conf: Dict = {'in_channels': 240, 'out_channel': 80, 'spk_emb_dim': 80, 'n_spks': 1,'cfm_params': DictConfig({'sigma_min': 1e-06, 'solver': 'euler', 't_scheduler': 'cosine','training_cfg_rate': 0.2, 'inference_cfg_rate': 0.7, 'reg_loss_type': 'l1'}),'decoder_params': {'channels': [256, 256], 'dropout': 0.0, 'attention_head_dim': 64,'n_blocks': 4, 'num_mid_blocks': 12, 'num_heads': 8, 'act_fn': 'gelu'}},mel_feat_conf: Dict = {'n_fft': 1024, 'num_mels': 80, 'sampling_rate': 22050,'hop_size': 256, 'win_size': 1024, 'fmin': 0, 'fmax': 8000}):super().__init__()self.input_size = input_sizeself.output_size = output_size28 unmodified lines# concat text and prompt_textmask = (~make_pad_mask(token_len)).float().unsqueeze(-1).to(device)token = self.input_embedding(torch.clamp(token, min=0)) * mask# text encodeh, h_lengths = self.encoder(token, token_len)43 unmodified linestoken_len1, token_len2 = prompt_token.shape[1], token.shape[1]token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_lenmask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)token = self.input_embedding(torch.clamp(token, min=0)) * mask# text encodeh, h_lengths = self.encoder(token, token_len)22 unmodified linesclass CausalMaskedDiffWithXvec(torch.nn.Module):def __init__(self,input_size: int = 512,output_size: int = 80,spk_embed_dim: int = 192,output_type: str = "mel",vocab_size: int = 6561,input_frame_rate: int = 25,only_mask_loss: bool = True,token_mel_ratio: int = 2,pre_lookahead_len: int = 3,encoder: torch.nn.Module = None,decoder: torch.nn.Module = None,decoder_conf: Dict = {'in_channels': 240, 'out_channel': 80, 'spk_emb_dim': 80, 'n_spks': 1,'cfm_params': DictConfig({'sigma_min': 1e-06, 'solver': 'euler', 't_scheduler': 'cosine','training_cfg_rate': 0.2, 'inference_cfg_rate': 0.7, 'reg_loss_type': 'l1'}),'decoder_params': {'channels': [256, 256], 'dropout': 0.0, 'attention_head_dim': 64,'n_blocks': 4, 'num_mid_blocks': 12, 'num_heads': 8, 'act_fn': 'gelu'}},mel_feat_conf: Dict = {'n_fft': 1024, 'num_mels': 80, 'sampling_rate': 22050,'hop_size': 256, 'win_size': 1024, 'fmin': 0, 'fmax': 8000}):super().__init__()self.input_size = input_sizeself.output_size = output_size37 unmodified lines# concat text and prompt_texttoken, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_lenmask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)token = self.input_embedding(torch.clamp(token, min=0)) * mask# text encodeh, h_lengths = self.encoder(token, token_len)13 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666728 unmodified lines9697989910010110243 unmodified lines14614714814915015115215315415515615715822 unmodified lines18118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422537 unmodified lines26326426526626726826913 unmodified linesimport loggingimport randomfrom typing import Dict, Optionallogger = logging.getLogger(__name__)import torchimport torch.nn as nnfrom torch.nn import functional as Ffrom .utils.mask import make_pad_maskfrom .configs import CFM_PARAMSclass MaskedDiffWithXvec(torch.nn.Module):def __init__(self,input_size: int = 512,output_size: int = 80,spk_embed_dim: int = 192,output_type: str = "mel",vocab_size: int = 4096,input_frame_rate: int = 50,only_mask_loss: bool = True,encoder: torch.nn.Module = None,length_regulator: torch.nn.Module = None,decoder: torch.nn.Module = None,decoder_conf: Dict = {'in_channels': 240,'out_channel': 80,'spk_emb_dim': 80,'n_spks': 1,'cfm_params': CFM_PARAMS,'decoder_params': {'channels': [256, 256],'dropout': 0.0,'attention_head_dim': 64,'n_blocks': 4,'num_mid_blocks': 12,'num_heads': 8,'act_fn': 'gelu',}},mel_feat_conf: Dict = {'n_fft': 1024,'num_mels': 80,'sampling_rate': 22050,'hop_size': 256,'win_size': 1024,'fmin': 0,'fmax': 8000}):super().__init__()self.input_size = input_sizeself.output_size = output_size28 unmodified lines# concat text and prompt_textmask = (~make_pad_mask(token_len)).float().unsqueeze(-1).to(device)token = self.input_embedding(torch.clamp(token, min=0, max=self.input_embedding.num_embeddings-1)) * mask# text encodeh, h_lengths = self.encoder(token, token_len)43 unmodified linestoken_len1, token_len2 = prompt_token.shape[1], token.shape[1]token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_lenmask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)# Check for out-of-bounds token IDsvocab_size = self.input_embedding.num_embeddingsif token.max() >= vocab_size or token.min() < 0:logging.warning(f"S3Gen: Token IDs out of bounds: min={token.min().item()}, max={token.max().item()}, vocab_size={vocab_size}")token = self.input_embedding(torch.clamp(token, min=0, max=vocab_size-1)) * mask# text encodeh, h_lengths = self.encoder(token, token_len)22 unmodified linesclass CausalMaskedDiffWithXvec(torch.nn.Module):def __init__(self,input_size: int = 512,output_size: int = 80,spk_embed_dim: int = 192,output_type: str = "mel",vocab_size: int = 6561,input_frame_rate: int = 25,only_mask_loss: bool = True,token_mel_ratio: int = 2,pre_lookahead_len: int = 3,encoder: torch.nn.Module = None,decoder: torch.nn.Module = None,decoder_conf: Dict = {'in_channels': 240,'out_channel': 80,'spk_emb_dim': 80,'n_spks': 1,'cfm_params': CFM_PARAMS,'decoder_params': {'channels': [256, 256],'dropout': 0.0,'attention_head_dim': 64,'n_blocks': 4,'num_mid_blocks': 12,'num_heads': 8,'act_fn': 'gelu',}},mel_feat_conf: Dict = {'n_fft': 1024,'num_mels': 80,'sampling_rate': 22050,'hop_size': 256,'win_size': 1024,'fmin': 0,'fmax': 8000}):super().__init__()self.input_size = input_sizeself.output_size = output_size37 unmodified lines# concat text and prompt_texttoken, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_lenmask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)token = self.input_embedding(torch.clamp(token, min=0, max=self.input_embedding.num_embeddings-1)) * mask# text encodeh, h_lengths = self.encoder(token, token_len)
14 unmodified lines151617181920212223242526272829303114 unmodified linesimport torchimport torch.nn.functional as Ffrom .matcha.flow_matching import BASECFMfrom omegaconf import OmegaConfCFM_PARAMS = OmegaConf.create({"sigma_min": 1e-06,"solver": "euler","t_scheduler": "cosine","training_cfg_rate": 0.2,"inference_cfg_rate": 0.7,"reg_loss_type": "l1"})class ConditionalCFM(BASECFM):14 unmodified lines1516171819202114 unmodified linesimport torchimport torch.nn.functional as Ffrom .matcha.flow_matching import BASECFMfrom .configs import CFM_PARAMSclass ConditionalCFM(BASECFM):
18 unmodified lines192021222324255 unmodified lines31323334353648 unmodified lines858687888990919293949596979818 unmodified linesimport torchaudio as tafrom functools import lru_cachefrom typing import Optionalfrom omegaconf import DictConfigfrom ..s3tokenizer import S3_SR, SPEECH_VOCAB_SIZE, S3Tokenizerfrom .const import S3GEN_SR5 unmodified linesfrom .transformer.upsample_encoder import UpsampleConformerEncoderfrom .flow_matching import CausalConditionalCFMfrom .decoder import ConditionalDecoderdef drop_invalid_tokens(x):48 unmodified linesnum_heads=8,act_fn='gelu',)cfm_params = DictConfig({"sigma_min": 1e-06,"solver": 'euler',"t_scheduler": 'cosine',"training_cfg_rate": 0.2,"inference_cfg_rate": 0.7,"reg_loss_type": 'l1',})decoder = CausalConditionalCFM(spk_emb_dim=80,cfm_params=cfm_params,18 unmodified lines1920212223245 unmodified lines3031323334353648 unmodified lines8586878889909118 unmodified linesimport torchaudio as tafrom functools import lru_cachefrom typing import Optionalfrom ..s3tokenizer import S3_SR, SPEECH_VOCAB_SIZE, S3Tokenizerfrom .const import S3GEN_SR5 unmodified linesfrom .transformer.upsample_encoder import UpsampleConformerEncoderfrom .flow_matching import CausalConditionalCFMfrom .decoder import ConditionalDecoderfrom .configs import CFM_PARAMSdef drop_invalid_tokens(x):48 unmodified linesnum_heads=8,act_fn='gelu',)cfm_params = CFM_PARAMSdecoder = CausalConditionalCFM(spk_emb_dim=80,cfm_params=cfm_params,
1234567833 unmodified lines42434445464748495051"""mel-spectrogram extraction in Matcha-TTS"""from librosa.filters import mel as librosa_mel_fnimport torchimport numpy as np# NOTE: they decalred these global varsmel_basis = {}33 unmodified linesif len(y.shape) == 1:y = y[None, ]if torch.min(y) < -1.0:print("min value is ", torch.min(y))if torch.max(y) > 1.0:print("max value is ", torch.max(y))global mel_basis, hann_window # pylint: disable=global-statement,global-variable-not-assignedif f"{str(fmax)}_{str(y.device)}" not in mel_basis:123456789101133 unmodified lines4546474849505152535455"""mel-spectrogram extraction in Matcha-TTS"""import loggingfrom librosa.filters import mel as librosa_mel_fnimport torchimport numpy as nplogger = logging.getLogger(__name__)# NOTE: they decalred these global varsmel_basis = {}33 unmodified linesif len(y.shape) == 1:y = y[None, ]# Debug: Check for audio clipping (values outside [-1.0, 1.0] range)min_val = torch.min(y)max_val = torch.max(y)if min_val < -1.0 or max_val > 1.0:logger.warning(f"Audio values outside normalized range: min={min_val.item():.4f}, max={max_val.item():.4f}")global mel_basis, hann_window # pylint: disable=global-statement,global-variable-not-assignedif f"{str(fmax)}_{str(y.device)}" not in mel_basis:
9 unmodified lines10111213141533 unmodified lines4950515253545556575859606162636465666768691 unmodified line71727374757677787980818283848586878889909192939495969735 unmodified lines1331341351361371381391401411421431441451461471481491501511521531549 unmodified lineslogger = logging.getLogger(__name__)@dataclassclass AlignmentAnalysisResult:# was this frame detected as being part of a noisy beginning chunk with potential hallucinations?33 unmodified linesself.complete = Falseself.completed_at = None# Using `output_attentions=True` is incompatible with optimized attention kernels, so# using it for all layers slows things down too much. We can apply it to just one layer# by intercepting the kwargs and adding a forward hook (credit: jrm)self.last_aligned_attn = Noneself._add_attention_spy(tfmr, alignment_layer_idx)def _add_attention_spy(self, tfmr, alignment_layer_idx):"""Adds a forward hook to a specific attention layer to collect outputs.Using `output_attentions=True` is incompatible with optimized attention kernels, sousing it for all layers slows things down too much.(credit: jrm)"""def attention_forward_hook(module, input, output):"""See `LlamaAttention.forward`; the output is a 3-tuple: `attn_output, attn_weights, past_key_value`.1 unmodified line- When `output_attentions=True`, `LlamaSdpaAttention.forward` calls `LlamaAttention.forward`.- `attn_output` has shape [B, H, T0, T0] for the 0th entry, and [B, H, 1, T0+i] for the rest i-th."""step_attention = output[1].cpu() # (B, 16, N, N)self.last_aligned_attn = step_attention[0].mean(0) # (N, N)target_layer = tfmr.layers[alignment_layer_idx].self_attnhook_handle = target_layer.register_forward_hook(attention_forward_hook)# Backup original forwardoriginal_forward = target_layer.forwarddef patched_forward(self, *args, **kwargs):kwargs['output_attentions'] = Truereturn original_forward(*args, **kwargs)# TODO: how to unpatch it?target_layer.forward = MethodType(patched_forward, target_layer)def step(self, logits):"""Emits an AlignmentAnalysisResult into the output queue, and potentially modifies the logits to force an EOS."""# extract approximate alignment matrix chunk (1 frame at a time after the first chunk)aligned_attn = self.last_aligned_attn # (N, N)i, j = self.text_tokens_sliceif self.curr_frame_pos == 0:# first chunk has conditioning info, text tokens, and BOS token35 unmodified lineslast_text_token_duration = A[15:, -3:].sum()# Activations for the final token that last too long are likely hallucinations.long_tail = self.complete and (A[self.completed_at:, -3:].sum(dim=0).max() >= 10) # 400ms# If there are activations in previous tokens after generation has completed, assume this is a repetition error.repetition = self.complete and (A[self.completed_at:, :-5].max(dim=1).values.sum() > 5)# If a bad ending is detected, force emit EOS by modifying logits# NOTE: this means logits may be inconsistent with latents!if long_tail or repetition:logger.warn(f"forcing EOS token, {long_tail=}, {repetition=}")# (±2**15 is safe for all dtypes >= 16bit)logits = -(2**15) * torch.ones_like(logits)logits[..., self.eos_idx] = 2**15# Suppress EoS to prevent early terminationif cur_text_posn < S - 3: # FIXME: arbitrarylogits[..., self.eos_idx] = -2**15self.curr_frame_pos += 1return logits9 unmodified lines10111213141516171833 unmodified lines525354555657585960616263646566676869707172731 unmodified line757677787980818283848586878889909192939495969735 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771789 unmodified lineslogger = logging.getLogger(__name__)LLAMA_ALIGNED_HEADS = [(12, 15), (13, 11), (9, 2)]@dataclassclass AlignmentAnalysisResult:# was this frame detected as being part of a noisy beginning chunk with potential hallucinations?33 unmodified linesself.complete = Falseself.completed_at = None# Track generated tokens for repetition detectionself.generated_tokens = []# Using `output_attentions=True` is incompatible with optimized attention kernels, so# using it for all layers slows things down too much. We can apply it to just one layer# by intercepting the kwargs and adding a forward hook (credit: jrm)self.last_aligned_attns = []for i, (layer_idx, head_idx) in enumerate(LLAMA_ALIGNED_HEADS):self.last_aligned_attns += [None]self._add_attention_spy(tfmr, i, layer_idx, head_idx)def _add_attention_spy(self, tfmr, buffer_idx, layer_idx, head_idx):"""Adds a forward hook to a specific attention layer to collect outputs."""def attention_forward_hook(module, input, output):"""See `LlamaAttention.forward`; the output is a 3-tuple: `attn_output, attn_weights, past_key_value`.1 unmodified line- When `output_attentions=True`, `LlamaSdpaAttention.forward` calls `LlamaAttention.forward`.- `attn_output` has shape [B, H, T0, T0] for the 0th entry, and [B, H, 1, T0+i] for the rest i-th."""if isinstance(output, tuple) and len(output) > 1 and output[1] is not None:step_attention = output[1].cpu() # (B, n_heads, T0, Ti)self.last_aligned_attns[buffer_idx] = step_attention[0, head_idx] # (T0, Ti)target_layer = tfmr.layers[layer_idx].self_attn# Register hook and store the handletarget_layer.register_forward_hook(attention_forward_hook)if hasattr(tfmr, 'config') and hasattr(tfmr.config, 'output_attentions'):self.original_output_attentions = tfmr.config.output_attentionstfmr.config.output_attentions = Truedef step(self, logits, next_token=None):"""Emits an AlignmentAnalysisResult into the output queue, and potentially modifies the logits to force an EOS."""# extract approximate alignment matrix chunk (1 frame at a time after the first chunk)aligned_attn = torch.stack(self.last_aligned_attns).mean(dim=0) # (N, N)i, j = self.text_tokens_sliceif self.curr_frame_pos == 0:# first chunk has conditioning info, text tokens, and BOS token35 unmodified lineslast_text_token_duration = A[15:, -3:].sum()# Activations for the final token that last too long are likely hallucinations.long_tail = self.complete and (A[self.completed_at:, -3:].sum(dim=0).max() >= 5) # 200ms# If there are activations in previous tokens after generation has completed, assume this is a repetition error.alignment_repetition = self.complete and (A[self.completed_at:, :-5].max(dim=1).values.sum() > 5)# Track generated tokens for repetition detectionif next_token is not None:# Convert tensor to scalar if neededif isinstance(next_token, torch.Tensor):token_id = next_token.item() if next_token.numel() == 1 else next_token.view(-1)[0].item()else:token_id = next_tokenself.generated_tokens.append(token_id)# Keep only last 8 tokens to prevent memory issuesif len(self.generated_tokens) > 8:self.generated_tokens = self.generated_tokens[-8:]# Check for excessive token repetition (3x same token in a row)token_repetition = (# self.complete andlen(self.generated_tokens) >= 3 andlen(set(self.generated_tokens[-2:])) == 1)if token_repetition:repeated_token = self.generated_tokens[-1]logger.warning(f"🚨 Detected 2x repetition of token {repeated_token}")# Suppress EoS to prevent early terminationif cur_text_posn < S - 3 and S > 5: # Only suppress if text is longer than 5 tokenslogits[..., self.eos_idx] = -2**15# If a bad ending is detected, force emit EOS by modifying logits# NOTE: this means logits may be inconsistent with latents!if long_tail or alignment_repetition or token_repetition:logger.warning(f"forcing EOS token, {long_tail=}, {alignment_repetition=}, {token_repetition=}")# (±2**15 is safe for all dtypes >= 16bit)logits = -(2**15) * torch.ones_like(logits)logits[..., self.eos_idx] = 2**15self.curr_frame_pos += 1return logits
1 unmodified line234567891011121314151617181920212223242526271 unmodified lineclass T3Config:start_text_token = 255stop_text_token = 0text_tokens_dict_size = 704max_text_tokens = 2048start_speech_token = 6561stop_speech_token = 6562speech_tokens_dict_size = 8194max_speech_tokens = 4096llama_config_name = "Llama_520M"input_pos_emb = "learned"speech_cond_prompt_len = 150# For T3CondEncencoder_type = "voice_encoder"speaker_embed_size = 256use_perceiver_resampler = Trueemotion_adv = True@propertydef n_channels(self):return LLAMA_CONFIGS[self.llama_config_name]["hidden_size"]1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940411 unmodified lineclass T3Config:def __init__(self, text_tokens_dict_size=704):self.start_text_token = 255self.stop_text_token = 0self.text_tokens_dict_size = text_tokens_dict_sizeself.max_text_tokens = 2048self.start_speech_token = 6561self.stop_speech_token = 6562self.speech_tokens_dict_size = 8194self.max_speech_tokens = 4096self.llama_config_name = "Llama_520M"self.input_pos_emb = "learned"self.speech_cond_prompt_len = 150self.encoder_type = "voice_encoder"self.speaker_embed_size = 256self.use_perceiver_resampler = Trueself.emotion_adv = True@propertydef n_channels(self):return LLAMA_CONFIGS[self.llama_config_name]["hidden_size"]@propertydef is_multilingual(self):return self.text_tokens_dict_size == 2454@classmethoddef english_only(cls):"""Create configuration for English-only TTS model."""return cls(text_tokens_dict_size=704)@classmethoddef multilingual(cls):"""Create configuration for multilingual TTS model."""return cls(text_tokens_dict_size=2454)
2 unmodified lines345678910111213142 unmodified lines171819202122232425262728293031323310 unmodified lines4445464748495038 unmodified lines8990919293949596979899121 unmodified lines22122222322422522622722822923013 unmodified lines2442452462472482494 unmodified lines2542552562572582592602612622632642652662672682692702712728 unmodified lines28128228328428528628718 unmodified lines3063073083093103113129 unmodified lines3223233243253263273283293303313323333343353363373383393403413424 unmodified lines3473483493503513522 unmodified linesimport loggingfrom typing import Union, Optional, Listfrom tqdm import tqdmimport torchimport torch.nn.functional as Ffrom torch import nn, Tensorfrom transformers import LlamaModel, LlamaConfigfrom transformers.generation.logits_process import TopPLogitsWarper, RepetitionPenaltyLogitsProcessorfrom .modules.learned_pos_emb import LearnedPositionEmbeddings2 unmodified linesfrom .llama_configs import LLAMA_CONFIGSfrom .inference.t3_hf_backend import T3HuggingfaceBackendfrom .inference.alignment_stream_analyzer import AlignmentStreamAnalyzerlogger = logging.getLogger(__name__)class AttrDict(dict):def __init__(self, *args, **kwargs):super(AttrDict, self).__init__(*args, **kwargs)self.__dict__ = selfdef _ensure_BOT_EOT(text_tokens: Tensor, hp):B = text_tokens.size(0)assert (text_tokens == hp.start_text_token).int().sum() >= B, "missing start_text_token"10 unmodified linesdifferent PE embedding space for speech."""def __init__(self, hp=T3Config()):super().__init__()self.hp = hpself.cfg = LlamaConfig(**LLAMA_CONFIGS[hp.llama_config_name])38 unmodified linest3_cond: T3Cond,text_tokens: torch.LongTensor,speech_tokens: torch.LongTensor,):# prepare input embeddings (skip backbone tranformer embeddings)cond_emb = self.prepare_conditioning(t3_cond) # (B, len_cond, dim)text_emb = self.text_emb(text_tokens) # (B, len_text, dim)text_emb[1].zero_() # CFG uncondspeech_emb = self.speech_emb(speech_tokens) # (B, len_speech, dim)if self.hp.input_pos_emb == "learned":121 unmodified linesstop_on_eos=True,do_sample=True,temperature=0.8,top_p=0.8,length_penalty=1.0,repetition_penalty=2.0,cfg_weight=0,):"""Args:13 unmodified linest3_cond=t3_cond,text_tokens=text_tokens,speech_tokens=initial_speech_tokens,)# In order to use the standard HF generate method, we need to extend some methods to inject our custom logic4 unmodified lines# TODO? synchronize the expensive compile function# with self.compile_lock:if not self.compiled:# alignment_stream_analyzer = AlignmentStreamAnalyzer(# self.tfmr,# None,# text_tokens_slice=(len_cond, len_cond + text_tokens.size(-1)),# alignment_layer_idx=9, # TODO: hparam or something?# eos_idx=self.hp.stop_speech_token,# )patched_model = T3HuggingfaceBackend(config=self.cfg,llama=self.tfmr,speech_enc=self.speech_emb,speech_head=self.speech_head,# alignment_stream_analyzer=alignment_stream_analyzer,)self.patched_model = patched_modelself.compiled = True8 unmodified lines# max_new_tokens=max_new_tokens or self.hp.max_speech_tokens,# num_return_sequences=num_return_sequences,# temperature=temperature,# top_p=top_p,# length_penalty=length_penalty,# repetition_penalty=repetition_penalty,# do_sample=do_sample,18 unmodified lines# Instantiate the logits processors.top_p_warper = TopPLogitsWarper(top_p=top_p)repetition_penalty_processor = RepetitionPenaltyLogitsProcessor(penalty=repetition_penalty)# ---- Initial Forward Pass (no kv_cache yet) ----output = self.patched_model(9 unmodified lines# ---- Generation Loop using kv_cache ----for i in tqdm(range(max_new_tokens), desc="Sampling", dynamic_ncols=True):logits = output.logits[:, -1, :]# CFGlogits_cond = logits[0:1]logits_uncond = logits[1:2]logits = logits_cond + cfg_weight * (logits_cond - logits_uncond)logits = logits.squeeze(1)# Apply temperature scaling.if temperature != 1.0:logits = logits / temperature# Apply repetition penalty and top‑p filtering.logits = repetition_penalty_processor(generated_ids, logits)logits = top_p_warper(None, logits)# Convert logits to probabilities and sample the next token.probs = torch.softmax(logits, dim=-1)4 unmodified lines# Check for EOS token.if next_token.view(-1) == self.hp.stop_speech_token:break# Get embedding for the new token.2 unmodified lines3456789101112131415162 unmodified lines19202122232425262728293010 unmodified lines41424344454647484938 unmodified lines888990919293949596979899100121 unmodified lines22222322422522622722822923023123213 unmodified lines2462472482492502512524 unmodified lines2572582592602612622632642652662672682692702712722732742752762772782792808 unmodified lines28929029129229329429518 unmodified lines3143153163173183193203213229 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623634 unmodified lines3683693703713723733742 unmodified linesimport loggingfrom typing import Union, Optional, Listlogger = logging.getLogger(__name__)from tqdm import tqdmimport torchimport torch.nn.functional as Ffrom torch import nn, Tensorfrom transformers import LlamaModel, LlamaConfigfrom transformers.generation.logits_process import TopPLogitsWarper, RepetitionPenaltyLogitsProcessor, MinPLogitsWarperfrom .modules.learned_pos_emb import LearnedPositionEmbeddings2 unmodified linesfrom .llama_configs import LLAMA_CONFIGSfrom .inference.t3_hf_backend import T3HuggingfaceBackendfrom .inference.alignment_stream_analyzer import AlignmentStreamAnalyzerfrom ..utils import AttrDictlogger = logging.getLogger(__name__)def _ensure_BOT_EOT(text_tokens: Tensor, hp):B = text_tokens.size(0)assert (text_tokens == hp.start_text_token).int().sum() >= B, "missing start_text_token"10 unmodified linesdifferent PE embedding space for speech."""def __init__(self, hp=None):if hp is None:hp = T3Config.english_only() # Default to English-only config for backward compatibilitysuper().__init__()self.hp = hpself.cfg = LlamaConfig(**LLAMA_CONFIGS[hp.llama_config_name])38 unmodified linest3_cond: T3Cond,text_tokens: torch.LongTensor,speech_tokens: torch.LongTensor,cfg_weight: float = 0.0,):# prepare input embeddings (skip backbone tranformer embeddings)cond_emb = self.prepare_conditioning(t3_cond) # (B, len_cond, dim)text_emb = self.text_emb(text_tokens) # (B, len_text, dim)if cfg_weight > 0.0:text_emb[1].zero_() # CFG uncondspeech_emb = self.speech_emb(speech_tokens) # (B, len_speech, dim)if self.hp.input_pos_emb == "learned":121 unmodified linesstop_on_eos=True,do_sample=True,temperature=0.8,top_p=0.95,min_p=0.05,length_penalty=1.0,repetition_penalty=1.2,cfg_weight=0.5,):"""Args:13 unmodified linest3_cond=t3_cond,text_tokens=text_tokens,speech_tokens=initial_speech_tokens,cfg_weight=cfg_weight,)# In order to use the standard HF generate method, we need to extend some methods to inject our custom logic4 unmodified lines# TODO? synchronize the expensive compile function# with self.compile_lock:if not self.compiled:# Default to None for English models, only create for multilingualalignment_stream_analyzer = Noneif self.hp.is_multilingual:alignment_stream_analyzer = AlignmentStreamAnalyzer(self.tfmr,None,text_tokens_slice=(len_cond, len_cond + text_tokens.size(-1)),alignment_layer_idx=9, # TODO: hparam or something?eos_idx=self.hp.stop_speech_token,)assert alignment_stream_analyzer.eos_idx == self.hp.stop_speech_tokenpatched_model = T3HuggingfaceBackend(config=self.cfg,llama=self.tfmr,speech_enc=self.speech_emb,speech_head=self.speech_head,alignment_stream_analyzer=alignment_stream_analyzer,)self.patched_model = patched_modelself.compiled = True8 unmodified lines# max_new_tokens=max_new_tokens or self.hp.max_speech_tokens,# num_return_sequences=num_return_sequences,# temperature=temperature,# min_p=min_p,# length_penalty=length_penalty,# repetition_penalty=repetition_penalty,# do_sample=do_sample,18 unmodified lines# Instantiate the logits processors.top_p_warper = TopPLogitsWarper(top_p=top_p)min_p_warper = MinPLogitsWarper(min_p=min_p)top_p_warper = TopPLogitsWarper(top_p=top_p)repetition_penalty_processor = RepetitionPenaltyLogitsProcessor(penalty=float(repetition_penalty))# ---- Initial Forward Pass (no kv_cache yet) ----output = self.patched_model(9 unmodified lines# ---- Generation Loop using kv_cache ----for i in tqdm(range(max_new_tokens), desc="Sampling", dynamic_ncols=True):logits_step = output.logits[:, -1, :]# CFG combine → (1, V)cond = logits_step[0:1, :]uncond = logits_step[1:2, :]cfg = torch.as_tensor(cfg_weight, device=cond.device, dtype=cond.dtype)logits = cond + cfg * (cond - uncond)# Apply alignment stream analyzer integrity checksif self.patched_model.alignment_stream_analyzer is not None:if logits.dim() == 1: # guard in case something upstream squeezedlogits = logits.unsqueeze(0) # (1, V)# Pass the last generated token for repetition trackinglast_token = generated_ids[0, -1].item() if len(generated_ids[0]) > 0 else Nonelogits = self.patched_model.alignment_stream_analyzer.step(logits, next_token=last_token) # (1, V)# Apply repetition penaltyids_for_proc = generated_ids[:1, ...] # batch = 1logits = repetition_penalty_processor(ids_for_proc, logits) # expects (B,V)# Apply temperature scaling.if temperature != 1.0:logits = logits / temperature# Apply min_p and top_p filteringlogits = min_p_warper(ids_for_proc, logits)logits = top_p_warper(ids_for_proc, logits)# Convert logits to probabilities and sample the next token.probs = torch.softmax(logits, dim=-1)4 unmodified lines# Check for EOS token.if next_token.view(-1) == self.hp.stop_speech_token:logger.info(f"✅ EOS token detected! Stopping generation at step {i+1}")break# Get embedding for the new token.
README.md+1
chatterbox/src/chatterbox/__init__.py+15
chatterbox/src/chatterbox/__pycache__/__init__.cpython-311.pycDeleted
chatterbox/src/chatterbox/__pycache__/tts.cpython-311.pycDeleted
chatterbox/src/chatterbox/__pycache__/utils.cpython-311.pycDeleted
chatterbox/src/chatterbox/__pycache__/vc.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/__init__.pyAdded
chatterbox/src/chatterbox/models/s3gen/__pycache__/__init__.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/const.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/decoder.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/f0_predictor.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/flow.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/flow_matching.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/hifigan.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/s3gen.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/__pycache__/xvector.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/configs.pyAdded+10
chatterbox/src/chatterbox/models/s3gen/flow.py+89-41
chatterbox/src/chatterbox/models/s3gen/flow_matching.py+1-11
chatterbox/src/chatterbox/models/s3gen/matcha/__pycache__/decoder.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/matcha/__pycache__/flow_matching.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/matcha/__pycache__/transformer.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/s3gen.py+2-9
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/__init__.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/activation.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/attention.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/convolution.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/embedding.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/encoder_layer.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/positionwise_feed_forward.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/subsampling.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/transformer/__pycache__/upsample_encoder.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/utils/__pycache__/class_utils.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/utils/__pycache__/mask.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/utils/__pycache__/mel.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3gen/utils/mel.py+8-4
chatterbox/src/chatterbox/models/s3tokenizer/__pycache__/__init__.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/s3tokenizer/__pycache__/s3tokenizer.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/__pycache__/__init__.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/__pycache__/llama_configs.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/__pycache__/t3.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/inference/__pycache__/alignment_stream_analyzer.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/inference/__pycache__/t3_hf_backend.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/inference/alignment_stream_analyzer.py+56-32
chatterbox/src/chatterbox/models/t3/modules/__pycache__/cond_enc.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/modules/__pycache__/learned_pos_emb.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/modules/__pycache__/perceiver.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/modules/__pycache__/t3_config.cpython-311.pycDeleted
chatterbox/src/chatterbox/models/t3/modules/t3_config.py+30-16
chatterbox/src/chatterbox/models/t3/t3.py+56-34