videopython-chatterbox 0.1.7.post1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. chatterbox/__init__.py +14 -0
  2. chatterbox/models/__init__.py +0 -0
  3. chatterbox/models/s3gen/__init__.py +2 -0
  4. chatterbox/models/s3gen/configs.py +10 -0
  5. chatterbox/models/s3gen/const.py +2 -0
  6. chatterbox/models/s3gen/decoder.py +333 -0
  7. chatterbox/models/s3gen/f0_predictor.py +55 -0
  8. chatterbox/models/s3gen/flow.py +198 -0
  9. chatterbox/models/s3gen/flow_matching.py +246 -0
  10. chatterbox/models/s3gen/hifigan.py +474 -0
  11. chatterbox/models/s3gen/matcha/decoder.py +443 -0
  12. chatterbox/models/s3gen/matcha/flow_matching.py +129 -0
  13. chatterbox/models/s3gen/matcha/text_encoder.py +413 -0
  14. chatterbox/models/s3gen/matcha/transformer.py +316 -0
  15. chatterbox/models/s3gen/s3gen.py +362 -0
  16. chatterbox/models/s3gen/transformer/__init__.py +0 -0
  17. chatterbox/models/s3gen/transformer/activation.py +84 -0
  18. chatterbox/models/s3gen/transformer/attention.py +330 -0
  19. chatterbox/models/s3gen/transformer/convolution.py +145 -0
  20. chatterbox/models/s3gen/transformer/embedding.py +294 -0
  21. chatterbox/models/s3gen/transformer/encoder_layer.py +236 -0
  22. chatterbox/models/s3gen/transformer/positionwise_feed_forward.py +115 -0
  23. chatterbox/models/s3gen/transformer/subsampling.py +383 -0
  24. chatterbox/models/s3gen/transformer/upsample_encoder.py +318 -0
  25. chatterbox/models/s3gen/utils/class_utils.py +71 -0
  26. chatterbox/models/s3gen/utils/intmeanflow.py +36 -0
  27. chatterbox/models/s3gen/utils/mask.py +194 -0
  28. chatterbox/models/s3gen/utils/mel.py +85 -0
  29. chatterbox/models/s3gen/xvector.py +428 -0
  30. chatterbox/models/s3tokenizer/__init__.py +30 -0
  31. chatterbox/models/s3tokenizer/s3tokenizer.py +168 -0
  32. chatterbox/models/t3/__init__.py +1 -0
  33. chatterbox/models/t3/inference/alignment_stream_analyzer.py +181 -0
  34. chatterbox/models/t3/inference/t3_hf_backend.py +116 -0
  35. chatterbox/models/t3/llama_configs.py +73 -0
  36. chatterbox/models/t3/modules/cond_enc.py +97 -0
  37. chatterbox/models/t3/modules/learned_pos_emb.py +32 -0
  38. chatterbox/models/t3/modules/perceiver.py +212 -0
  39. chatterbox/models/t3/modules/t3_config.py +41 -0
  40. chatterbox/models/t3/t3.py +490 -0
  41. chatterbox/models/tokenizers/__init__.py +1 -0
  42. chatterbox/models/tokenizers/tokenizer.py +313 -0
  43. chatterbox/models/utils.py +4 -0
  44. chatterbox/models/voice_encoder/__init__.py +1 -0
  45. chatterbox/models/voice_encoder/config.py +18 -0
  46. chatterbox/models/voice_encoder/melspec.py +78 -0
  47. chatterbox/models/voice_encoder/voice_encoder.py +274 -0
  48. chatterbox/mtl_tts.py +317 -0
  49. chatterbox/tts.py +272 -0
  50. chatterbox/tts_turbo.py +296 -0
  51. chatterbox/vc.py +104 -0
  52. videopython_chatterbox-0.1.7.post1.dist-info/METADATA +154 -0
  53. videopython_chatterbox-0.1.7.post1.dist-info/RECORD +56 -0
  54. videopython_chatterbox-0.1.7.post1.dist-info/WHEEL +4 -0
  55. videopython_chatterbox-0.1.7.post1.dist-info/licenses/LICENSE +21 -0
  56. videopython_chatterbox-0.1.7.post1.dist-info/licenses/NOTICE +29 -0
@@ -0,0 +1,212 @@
1
+ # Copyright (c) 2025 Resemble AI
2
+ # Author: Manmay Nakhashi
3
+ # MIT License
4
+ import math
5
+
6
+ import torch
7
+ from torch import nn
8
+ import torch.nn.functional as F
9
+ from einops import rearrange
10
+
11
+
12
+ class RelativePositionBias(nn.Module):
13
+ def __init__(self, scale, causal=False, num_buckets=32, max_distance=128, heads=8):
14
+ super().__init__()
15
+ self.scale = scale
16
+ self.causal = causal
17
+ self.num_buckets = num_buckets
18
+ self.max_distance = max_distance
19
+ self.relative_attention_bias = nn.Embedding(num_buckets, heads)
20
+
21
+ @staticmethod
22
+ def _relative_position_bucket(relative_position, causal=True, num_buckets=32, max_distance=128):
23
+ ret = 0
24
+ n = -relative_position
25
+ if not causal:
26
+ num_buckets //= 2
27
+ ret += (n < 0).long() * num_buckets
28
+ n = torch.abs(n)
29
+ else:
30
+ n = torch.max(n, torch.zeros_like(n))
31
+
32
+ max_exact = num_buckets // 2
33
+ is_small = n < max_exact
34
+
35
+ val_if_large = max_exact + (
36
+ torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)
37
+ ).long()
38
+ val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1))
39
+
40
+ ret += torch.where(is_small, n, val_if_large)
41
+ return ret
42
+
43
+ def forward(self, qk_dots):
44
+ i, j, device = *qk_dots.shape[-2:], qk_dots.device
45
+ q_pos = torch.arange(i, dtype=torch.long, device=device)
46
+ k_pos = torch.arange(j, dtype=torch.long, device=device)
47
+ rel_pos = k_pos[None, :] - q_pos[:, None]
48
+ rp_bucket = self._relative_position_bucket(rel_pos, causal=self.causal, num_buckets=self.num_buckets,
49
+ max_distance=self.max_distance)
50
+ values = self.relative_attention_bias(rp_bucket)
51
+ bias = rearrange(values, 'i j h -> () h i j')
52
+ return qk_dots + (bias * self.scale)
53
+
54
+
55
+ class AttentionQKV(nn.Module):
56
+ def __init__(self, n_heads, head_dim, dropout_rate=0.1, scale=None, flash=False):
57
+ super().__init__()
58
+ self.n_heads = n_heads
59
+ self.head_dim = head_dim
60
+ self.scale = scale if scale is not None else head_dim ** -0.5
61
+ self.flash = flash
62
+ self.dropout_rate = dropout_rate
63
+ self.dropout = nn.Dropout(dropout_rate)
64
+ self.flash_config = self.setup_flash_config() if flash else None
65
+
66
+ def setup_flash_config(self):
67
+ # Setup flash attention configuration
68
+ flash_config = {
69
+ 'enable_flash': True,
70
+ 'enable_math': True,
71
+ 'enable_mem_efficient': True
72
+ }
73
+ return flash_config
74
+
75
+ def forward(self, q, k, v, mask=None):
76
+ q, k, v = [self.split_heads(tensor) for tensor in [q, k, v]]
77
+ if self.flash:
78
+ out = self.flash_attention(q, k, v, mask=mask)
79
+ else:
80
+ out = self.scaled_dot_product_attention(q, k, v, mask=mask)
81
+
82
+ return self.combine_heads(out)
83
+
84
+ def scaled_dot_product_attention(self, q, k, v, mask=None):
85
+ sim = torch.einsum("bhlt,bhls->bhts", q, k) * self.scale
86
+ if mask is not None:
87
+ sim = sim.masked_fill(mask == 0, float('-inf'))
88
+ attn = torch.softmax(sim, dim=-1)
89
+ attn = self.dropout(attn)
90
+ return torch.einsum("bhts,bhls->bhlt", attn, v)
91
+
92
+ def flash_attention(self, q, k, v, mask=None):
93
+ config = self.flash_config if self.flash_config else {}
94
+ with torch.backends.cuda.sdp_kernel(**config):
95
+ out = F.scaled_dot_product_attention(
96
+ q, k, v,
97
+ attn_mask=mask,
98
+ dropout_p=self.dropout_rate if self.training else 0.
99
+ )
100
+ return out
101
+
102
+ def split_heads(self, x):
103
+ bs, length, _ = x.shape
104
+ x = x.view(bs, length, self.n_heads, self.head_dim)
105
+ return x.permute(0, 2, 1, 3)
106
+
107
+ def combine_heads(self, x):
108
+ bs, _, length, _ = x.shape
109
+ x = x.permute(0, 2, 1, 3).contiguous()
110
+ return x.view(bs, length, -1)
111
+
112
+
113
+ class AttentionBlock2(nn.Module):
114
+ """
115
+ An attention block that allows spatial positions to attend to each other,
116
+ using AttentionQKV and separate linear transformations for Q, K, and V.
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ channels,
122
+ num_heads=1,
123
+ num_head_channels=-1,
124
+ relative_pos_embeddings=False,
125
+ flash_attention=True,
126
+ dropout_rate=0.2,
127
+ scale=None
128
+ ):
129
+ super().__init__()
130
+ self.channels = channels
131
+
132
+ if num_head_channels == -1:
133
+ self.num_heads = num_heads
134
+ else:
135
+ assert (
136
+ channels % num_head_channels == 0
137
+ ), f"channels {channels} is not divisible by num_head_channels {num_head_channels}"
138
+ self.num_heads = channels // num_head_channels
139
+
140
+ self.norm = nn.LayerNorm(channels)
141
+
142
+ # Separate linear layers for Q, K, and V
143
+ self.to_q = nn.Linear(channels, channels)
144
+ self.to_k = nn.Linear(channels, channels)
145
+ self.to_v = nn.Linear(channels, channels)
146
+
147
+ self.attention = AttentionQKV(self.num_heads, channels // self.num_heads, dropout_rate=dropout_rate, flash=flash_attention, scale=scale)
148
+
149
+ self.proj_out = nn.Linear(channels, channels)
150
+
151
+ if relative_pos_embeddings:
152
+ self.relative_pos_embeddings = RelativePositionBias(scale=(channels // self.num_heads) ** .5, causal=False, heads=num_heads, num_buckets=32, max_distance=64)
153
+ else:
154
+ self.relative_pos_embeddings = None
155
+
156
+ def forward(self, x1, x2, mask=None):
157
+ b1, c1, *spatial1 = x1.shape
158
+ b2, c2, *spatial2 = x2.shape
159
+
160
+ x1_norm = self.norm(x1)
161
+ x2_norm = self.norm(x2)
162
+
163
+ q = self.to_q(x1_norm)
164
+ k = self.to_k(x2_norm)
165
+ v = self.to_v(x2_norm)
166
+
167
+ h = self.attention(q, k, v, mask=mask)
168
+ h = self.proj_out(h)
169
+
170
+ return (x1 + h).reshape(b1, c1, *spatial1)
171
+
172
+
173
+ class Perceiver(nn.Module):
174
+ """Inspired by https://arxiv.org/abs/2103.03206"""
175
+ def __init__(self, pre_attention_query_token=32, pre_attention_query_size=1024, embedding_dim=1024, num_attn_heads=4):
176
+ """
177
+ Initialize the perceiver module.
178
+
179
+ :param pre_attention_query_token: Number of query tokens for pre-attention
180
+ :param pre_attention_query_size: Size of each query token
181
+ :param embedding_dim: Dimension of the embedding space
182
+ :param num_attn_heads: Number of attention heads
183
+ """
184
+ super().__init__()
185
+
186
+ # Initialize the pre-attention query parameter
187
+ self.pre_attention_query = torch.nn.Parameter(
188
+ torch.empty(1, pre_attention_query_token, pre_attention_query_size)
189
+ )
190
+
191
+ # Calculate the variance for uniform initialization
192
+ query_variance = math.sqrt(3.0) * math.sqrt(2.0 / (pre_attention_query_token + pre_attention_query_token))
193
+
194
+ # Initialize the pre-attention query with uniform distribution
195
+ self.pre_attention_query.data.uniform_(-query_variance, query_variance)
196
+
197
+ # Initialize the attention block
198
+ self.attn = AttentionBlock2(embedding_dim, num_attn_heads)
199
+
200
+ def forward(self, h):
201
+ """
202
+ Forward pass of the perceiver module.
203
+ :param h: Input tensor
204
+ :return: Output after applying attention mechanisms
205
+ """
206
+ # Expand the pre-attention query to match the batch size of the input
207
+ query_ = self.pre_attention_query.expand(h.shape[0], -1, -1)
208
+ # Apply the first attention mechanism (cross-attention)
209
+ pre_att = self.attn(query_, h)
210
+ # Apply the second attention mechanism (self-attention)
211
+ attn = self.attn(pre_att, pre_att)
212
+ return attn
@@ -0,0 +1,41 @@
1
+ from ..llama_configs import LLAMA_CONFIGS
2
+
3
+
4
+ class T3Config:
5
+ def __init__(self, text_tokens_dict_size=704):
6
+ self.start_text_token = 255
7
+ self.stop_text_token = 0
8
+ self.text_tokens_dict_size = text_tokens_dict_size
9
+ self.max_text_tokens = 2048
10
+
11
+ self.start_speech_token = 6561
12
+ self.stop_speech_token = 6562
13
+ self.speech_tokens_dict_size = 8194
14
+ self.max_speech_tokens = 4096
15
+
16
+ self.llama_config_name = "Llama_520M"
17
+ self.input_pos_emb = "learned"
18
+ self.speech_cond_prompt_len = 150
19
+
20
+ self.encoder_type = "voice_encoder"
21
+ self.speaker_embed_size = 256
22
+ self.use_perceiver_resampler = True
23
+ self.emotion_adv = True
24
+
25
+ @property
26
+ def n_channels(self):
27
+ return LLAMA_CONFIGS[self.llama_config_name]["hidden_size"]
28
+
29
+ @property
30
+ def is_multilingual(self):
31
+ return self.text_tokens_dict_size == 2454
32
+
33
+ @classmethod
34
+ def english_only(cls):
35
+ """Create configuration for English-only TTS model."""
36
+ return cls(text_tokens_dict_size=704)
37
+
38
+ @classmethod
39
+ def multilingual(cls):
40
+ """Create configuration for multilingual TTS model."""
41
+ return cls(text_tokens_dict_size=2454)