mlinmg commited on
Commit
3daa1cc
·
verified ·
1 Parent(s): b98aee3

Delete xttsv2_gpt2

Browse files
xttsv2_gpt2/config.json DELETED
@@ -1,44 +0,0 @@
1
- {
2
- "activation_function": "gelu",
3
- "architectures": [
4
- "XttsGPT"
5
- ],
6
- "attn_pdrop": 0.1,
7
- "audio_config": {
8
- "mel_channels": 80,
9
- "output_sample_rate": 24000,
10
- "sample_rate": 22050
11
- },
12
- "auto_map": {
13
- "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
14
- "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
15
- "AutoTokenizer": "AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast"
16
- },
17
- "decoder_input_dim": 1024,
18
- "enable_redaction": false,
19
- "gpt_batch_size": 1,
20
- "gpt_max_audio_tokens": 605,
21
- "hidden_size": 1024,
22
- "initializer_range": 0.02,
23
- "kv_cache": true,
24
- "layer_norm_epsilon": 1e-05,
25
- "max_audio_tokens": 605,
26
- "max_prompt_tokens": 70,
27
- "max_text_tokens": 402,
28
- "model_type": "xtts_gpt",
29
- "n_inner": 4096,
30
- "num_attention_heads": 16,
31
- "num_audio_tokens": 1026,
32
- "num_hidden_layers": 30,
33
- "number_text_tokens": 6681,
34
- "reorder_and_upcast_attn": false,
35
- "scale_attn_by_inverse_layer_idx": false,
36
- "start_audio_token": 1024,
37
- "start_text_token": null,
38
- "stop_audio_token": 1025,
39
- "stop_text_token": null,
40
- "transformers_version": "4.46.0",
41
- "use_masking_gt_prompt_approach": true,
42
- "use_perceiver_resampler": true,
43
- "vocab_size": 6681
44
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
xttsv2_gpt2/gpt2_model.safetensors DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:104d92b2297c243b64d1417bd5cfda015faca0a670e9bc90088eed0e844f8e35
3
- size 1522497936
 
 
 
 
xttsv2_gpt2/gpt_config.py DELETED
@@ -1,143 +0,0 @@
1
- from dataclasses import asdict, dataclass
2
- from typing import Dict, Optional, List
3
- from transformers.configuration_utils import PretrainedConfig
4
- from transformers.utils import logging
5
-
6
- logger = logging.get_logger(__name__)
7
-
8
-
9
- @dataclass
10
- class GPTAudioConfig:
11
- """Configuration for GPT audio processing parameters"""
12
- mel_channels: int = 80
13
- sample_rate: int = 22050
14
- output_sample_rate: int = 24000
15
-
16
- @dataclass
17
- class XTTSAudioConfig:
18
- """Configuration for audio processing parameters"""
19
- sample_rate: int = 22050
20
- output_sample_rate: int = 24000
21
- mel_channels: int = 80
22
- hop_length: int = 256
23
- win_length: int = 1024
24
- n_fft: int = 1024
25
- fmin: int = 0
26
- fmax: int = 8000
27
- power: float = 1.0
28
- mel_norms_file: Optional[str] = None
29
-
30
-
31
- class XTTSGPTConfig(PretrainedConfig):
32
- """Configuration class for the GPT component of XTTS."""
33
- model_type = "xtts_gpt"
34
-
35
- def __init__(
36
- self,
37
- # Model architecture
38
- hidden_size: int = 1024, # gpt_n_model_channels in original
39
- n_inner: int = 4096,
40
- num_hidden_layers: int = 30, # gpt_layers in original
41
- num_attention_heads: int = 16, # gpt_n_heads in original
42
-
43
- # Tokenizer settings
44
- vocab_size: int = 6681, # gpt_number_text_tokens in original
45
- number_text_tokens: int = 6681, # Explicit text token vocabulary size
46
- start_text_token: Optional[int] = None,
47
- stop_text_token: Optional[int] = None,
48
-
49
- # Audio token settings
50
- num_audio_tokens: int = 1026, # gpt_num_audio_tokens in original
51
- start_audio_token: int = 1024, # gpt_start_audio_token in original
52
- stop_audio_token: int = 1025, # gpt_stop_audio_token in original
53
-
54
- # Sequence length settings
55
- max_audio_tokens: int = 605, # gpt_max_audio_tokens in original
56
- max_text_tokens: int = 402, # gpt_max_text_tokens in original
57
- max_prompt_tokens: int = 70, # gpt_max_prompt_tokens in original
58
- gpt_max_audio_tokens: int = 605, # Used for generation
59
-
60
- # Model behavior settings
61
- use_masking_gt_prompt_approach: bool = True, # gpt_use_masking_gt_prompt_approach in original
62
- use_perceiver_resampler: bool = True, # gpt_use_perceiver_resampler in original
63
- kv_cache: bool = True,
64
- enable_redaction: bool = False,
65
-
66
- # GPT batch settings
67
- gpt_batch_size: int = 1,
68
-
69
- # Audio processing
70
- audio_config: Optional[Dict] = None,
71
-
72
- # Architecture specifics
73
- layer_norm_epsilon: float = 1e-5,
74
- initializer_range: float = 0.02,
75
- add_cross_attention: bool = False,
76
- scale_attn_by_inverse_layer_idx: bool = False,
77
- reorder_and_upcast_attn: bool = False,
78
-
79
- # Size settings for the decoder
80
- decoder_input_dim: int = 1024,
81
- architectures=["XttsGPT"],
82
- auto_map={
83
- "AutoConfig": "AstraMindAI/xtts2-gpt--gpt_config.XTTSGPTConfig",
84
- "AutoModelForCausalLM": "AstraMindAI/xtts2-gpt--xtts2_gpt_modeling.XttsGPT",
85
- },
86
- activation_function: str = "gelu",
87
- attn_pdrop: float = 0.1,
88
- **kwargs
89
- ):
90
- super().__init__(**kwargs)
91
- self.architectures = architectures
92
- self.auto_map = auto_map
93
- self.audio_config = GPTAudioConfig(
94
- **audio_config if audio_config is not None else {}
95
- )
96
- self.activation_function = activation_function
97
- self.attn_pdrop = attn_pdrop
98
- self.hidden_size = hidden_size
99
- self.n_inner = n_inner
100
- self.num_hidden_layers = num_hidden_layers
101
- self.num_attention_heads = num_attention_heads
102
-
103
- self.vocab_size = vocab_size
104
- self.number_text_tokens = number_text_tokens
105
- self.start_text_token = start_text_token
106
- self.stop_text_token = stop_text_token
107
-
108
- self.num_audio_tokens = num_audio_tokens
109
- self.start_audio_token = start_audio_token
110
- self.stop_audio_token = stop_audio_token
111
-
112
- self.max_audio_tokens = max_audio_tokens
113
- self.max_text_tokens = max_text_tokens
114
- self.max_prompt_tokens = max_prompt_tokens
115
- self.gpt_max_audio_tokens = gpt_max_audio_tokens
116
-
117
- self.use_masking_gt_prompt_approach = use_masking_gt_prompt_approach
118
- self.use_perceiver_resampler = use_perceiver_resampler
119
- self.kv_cache = kv_cache
120
- self.enable_redaction = enable_redaction
121
-
122
- self.gpt_batch_size = gpt_batch_size
123
-
124
- self.layer_norm_epsilon = layer_norm_epsilon
125
- self.initializer_range = initializer_range
126
- self.add_cross_attention = add_cross_attention
127
- self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
128
- self.reorder_and_upcast_attn = reorder_and_upcast_attn
129
-
130
- self.decoder_input_dim = decoder_input_dim
131
-
132
- def to_dict(self) -> Dict:
133
- """Convert the config to a dictionary."""
134
- output = super().to_dict()
135
- output["audio_config"] = asdict(self.audio_config)
136
- return output
137
-
138
- @classmethod
139
- def from_dict(cls, config_dict: Dict, *args, **kwargs) -> "XTTSGPTConfig":
140
- """Create a config from a dictionary."""
141
- return cls(**config_dict)
142
-
143
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
xttsv2_gpt2/special_tokens_map.json DELETED
@@ -1,6 +0,0 @@
1
- {
2
- "bos_token": "[START]",
3
- "eos_token": "[STOP]",
4
- "pad_token": "[PAD]",
5
- "unk_token": "[UNK]"
6
- }
 
 
 
 
 
 
 
xttsv2_gpt2/tokenizer.json DELETED
The diff for this file is too large to render. See raw diff
 
xttsv2_gpt2/tokenizer.py DELETED
@@ -1,887 +0,0 @@
1
- import os
2
- import re
3
- import textwrap
4
- from typing import List, Optional, Union, Dict, Any
5
- from functools import cached_property
6
-
7
- import pypinyin
8
- import torch
9
- from hangul_romanize import Transliter
10
- from hangul_romanize.rule import academic
11
- from num2words import num2words
12
- from spacy.lang.ar import Arabic
13
- from spacy.lang.en import English
14
- from spacy.lang.es import Spanish
15
- from spacy.lang.ja import Japanese
16
- from spacy.lang.zh import Chinese
17
- from transformers import PreTrainedTokenizerFast, BatchEncoding
18
- from transformers.tokenization_utils_base import TruncationStrategy, PaddingStrategy
19
- from tokenizers import Tokenizer
20
- from tokenizers.pre_tokenizers import WhitespaceSplit
21
- from tokenizers.processors import TemplateProcessing
22
-
23
- from TTS.tts.layers.xtts.zh_num2words import TextNorm as zh_num2words
24
-
25
- import cutlet
26
-
27
- # Funzioni di preprocessing del testo
28
-
29
- def get_spacy_lang(lang):
30
- if lang == "zh":
31
- return Chinese()
32
- elif lang == "ja":
33
- return Japanese()
34
- elif lang == "ar":
35
- return Arabic()
36
- elif lang == "es":
37
- return Spanish()
38
- else:
39
- # For most languages, English does the job
40
- return English()
41
-
42
- def split_sentence(text, lang, text_split_length=250):
43
- """Preprocess the input text and split into sentences based on language."""
44
- text_splits = []
45
- if text_split_length is not None and len(text) >= text_split_length:
46
- text_splits.append("")
47
- nlp = get_spacy_lang(lang)
48
- nlp.add_pipe("sentencizer")
49
- doc = nlp(text)
50
- for sentence in doc.sents:
51
- if len(text_splits[-1]) + len(str(sentence)) <= text_split_length:
52
- text_splits[-1] += " " + str(sentence)
53
- text_splits[-1] = text_splits[-1].lstrip()
54
- elif len(str(sentence)) > text_split_length:
55
- for line in textwrap.wrap(
56
- str(sentence),
57
- width=text_split_length,
58
- drop_whitespace=True,
59
- break_on_hyphens=False,
60
- tabsize=1,
61
- ):
62
- text_splits.append(str(line))
63
- else:
64
- text_splits.append(str(sentence))
65
-
66
- if len(text_splits) > 1 and text_splits[0] == "":
67
- del text_splits[0]
68
- else:
69
- text_splits = [text.lstrip()]
70
-
71
- return text_splits
72
-
73
- _whitespace_re = re.compile(r"\s+")
74
-
75
- # List of (regular expression, replacement) pairs for abbreviations:
76
- _abbreviations = {
77
- "en": [
78
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
79
- for x in [
80
- ("mrs", "misess"),
81
- ("mr", "mister"),
82
- ("dr", "doctor"),
83
- ("st", "saint"),
84
- ("co", "company"),
85
- ("jr", "junior"),
86
- ("maj", "major"),
87
- ("gen", "general"),
88
- ("drs", "doctors"),
89
- ("rev", "reverend"),
90
- ("lt", "lieutenant"),
91
- ("hon", "honorable"),
92
- ("sgt", "sergeant"),
93
- ("capt", "captain"),
94
- ("esq", "esquire"),
95
- ("ltd", "limited"),
96
- ("col", "colonel"),
97
- ("ft", "fort"),
98
- ]
99
- ],
100
- "es": [
101
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
102
- for x in [
103
- ("sra", "señora"),
104
- ("sr", "señor"),
105
- ("dr", "doctor"),
106
- ("dra", "doctora"),
107
- ("st", "santo"),
108
- ("co", "compañía"),
109
- ("jr", "junior"),
110
- ("ltd", "limitada"),
111
- ]
112
- ],
113
- "fr": [
114
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
115
- for x in [
116
- ("mme", "madame"),
117
- ("mr", "monsieur"),
118
- ("dr", "docteur"),
119
- ("st", "saint"),
120
- ("co", "compagnie"),
121
- ("jr", "junior"),
122
- ("ltd", "limitée"),
123
- ]
124
- ],
125
- "de": [
126
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
127
- for x in [
128
- ("fr", "frau"),
129
- ("dr", "doktor"),
130
- ("st", "sankt"),
131
- ("co", "firma"),
132
- ("jr", "junior"),
133
- ]
134
- ],
135
- "pt": [
136
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
137
- for x in [
138
- ("sra", "senhora"),
139
- ("sr", "senhor"),
140
- ("dr", "doutor"),
141
- ("dra", "doutora"),
142
- ("st", "santo"),
143
- ("co", "companhia"),
144
- ("jr", "júnior"),
145
- ("ltd", "limitada"),
146
- ]
147
- ],
148
- "it": [
149
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
150
- for x in [
151
- # ("sig.ra", "signora"),
152
- ("sig", "signore"),
153
- ("dr", "dottore"),
154
- ("st", "santo"),
155
- ("co", "compagnia"),
156
- ("jr", "junior"),
157
- ("ltd", "limitata"),
158
- ]
159
- ],
160
- "pl": [
161
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
162
- for x in [
163
- ("p", "pani"),
164
- ("m", "pan"),
165
- ("dr", "doktor"),
166
- ("sw", "święty"),
167
- ("jr", "junior"),
168
- ]
169
- ],
170
- "ar": [
171
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
172
- for x in [
173
- # There are not many common abbreviations in Arabic as in English.
174
- ]
175
- ],
176
- "zh": [
177
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
178
- for x in [
179
- # Chinese doesn't typically use abbreviations in the same way as Latin-based scripts.
180
- ]
181
- ],
182
- "cs": [
183
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
184
- for x in [
185
- ("dr", "doktor"), # doctor
186
- ("ing", "inženýr"), # engineer
187
- ("p", "pan"), # Could also map to pani for woman but no easy way to do it
188
- # Other abbreviations would be specialized and not as common.
189
- ]
190
- ],
191
- "ru": [
192
- (re.compile("\\b%s\\b" % x[0], re.IGNORECASE), x[1])
193
- for x in [
194
- ("г-жа", "госпожа"), # Mrs.
195
- ("г-н", "господин"), # Mr.
196
- ("д-р", "доктор"), # doctor
197
- # Other abbreviations are less common or specialized.
198
- ]
199
- ],
200
- "nl": [
201
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
202
- for x in [
203
- ("dhr", "de heer"), # Mr.
204
- ("mevr", "mevrouw"), # Mrs.
205
- ("dr", "dokter"), # doctor
206
- ("jhr", "jonkheer"), # young lord or nobleman
207
- # Dutch uses more abbreviations, but these are the most common ones.
208
- ]
209
- ],
210
- "tr": [
211
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
212
- for x in [
213
- ("b", "bay"), # Mr.
214
- ("byk", "büyük"), # büyük
215
- ("dr", "doktor"), # doctor
216
- # Add other Turkish abbreviations here if needed.
217
- ]
218
- ],
219
- "hu": [
220
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
221
- for x in [
222
- ("dr", "doktor"), # doctor
223
- ("b", "bácsi"), # Mr.
224
- ("nőv", "nővér"), # nurse
225
- # Add other Hungarian abbreviations here if needed.
226
- ]
227
- ],
228
- "ko": [
229
- (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
230
- for x in [
231
- # Korean doesn't typically use abbreviations in the same way as Latin-based scripts.
232
- ]
233
- ],
234
- }
235
-
236
- def expand_abbreviations_multilingual(text, lang="en"):
237
- if lang in _abbreviations:
238
- for regex, replacement in _abbreviations[lang]:
239
- text = re.sub(regex, replacement, text)
240
- return text
241
-
242
- _symbols_multilingual = {
243
- "en": [
244
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
245
- for x in [
246
- ("&", " and "),
247
- ("@", " at "),
248
- ("%", " percent "),
249
- ("#", " hash "),
250
- ("$", " dollar "),
251
- ("£", " pound "),
252
- ("°", " degree "),
253
- ]
254
- ],
255
- "es": [
256
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
257
- for x in [
258
- ("&", " y "),
259
- ("@", " arroba "),
260
- ("%", " por ciento "),
261
- ("#", " numeral "),
262
- ("$", " dolar "),
263
- ("£", " libra "),
264
- ("°", " grados "),
265
- ]
266
- ],
267
- "fr": [
268
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
269
- for x in [
270
- ("&", " et "),
271
- ("@", " arobase "),
272
- ("%", " pour cent "),
273
- ("#", " dièse "),
274
- ("$", " dollar "),
275
- ("£", " livre "),
276
- ("°", " degrés "),
277
- ]
278
- ],
279
- "de": [
280
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
281
- for x in [
282
- ("&", " und "),
283
- ("@", " at "),
284
- ("%", " prozent "),
285
- ("#", " raute "),
286
- ("$", " dollar "),
287
- ("£", " pfund "),
288
- ("°", " grad "),
289
- ]
290
- ],
291
- "pt": [
292
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
293
- for x in [
294
- ("&", " e "),
295
- ("@", " arroba "),
296
- ("%", " por cento "),
297
- ("#", " cardinal "),
298
- ("$", " dólar "),
299
- ("£", " libra "),
300
- ("°", " graus "),
301
- ]
302
- ],
303
- "it": [
304
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
305
- for x in [
306
- ("&", " e "),
307
- ("@", " chiocciola "),
308
- ("%", " per cento "),
309
- ("#", " cancelletto "),
310
- ("$", " dollaro "),
311
- ("£", " sterlina "),
312
- ("°", " gradi "),
313
- ]
314
- ],
315
- "pl": [
316
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
317
- for x in [
318
- ("&", " i "),
319
- ("@", " małpa "),
320
- ("%", " procent "),
321
- ("#", " krzyżyk "),
322
- ("$", " dolar "),
323
- ("£", " funt "),
324
- ("°", " stopnie "),
325
- ]
326
- ],
327
- "ar": [
328
- # Arabic
329
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
330
- for x in [
331
- ("&", " و "),
332
- ("@", " على "),
333
- ("%", " في المئة "),
334
- ("#", " رقم "),
335
- ("$", " دولار "),
336
- ("£", " جنيه "),
337
- ("°", " درجة "),
338
- ]
339
- ],
340
- "zh": [
341
- # Chinese
342
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
343
- for x in [
344
- ("&", " 和 "),
345
- ("@", " 在 "),
346
- ("%", " 百分之 "),
347
- ("#", " 号 "),
348
- ("$", " 美元 "),
349
- ("£", " 英镑 "),
350
- ("°", " 度 "),
351
- ]
352
- ],
353
- "cs": [
354
- # Czech
355
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
356
- for x in [
357
- ("&", " a "),
358
- ("@", " na "),
359
- ("%", " procento "),
360
- ("#", " křížek "),
361
- ("$", " dolar "),
362
- ("£", " libra "),
363
- ("°", " stupně "),
364
- ]
365
- ],
366
- "ru": [
367
- # Russian
368
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
369
- for x in [
370
- ("&", " и "),
371
- ("@", " собака "),
372
- ("%", " процентов "),
373
- ("#", " номер "),
374
- ("$", " доллар "),
375
- ("£", " фунт "),
376
- ("°", " градус "),
377
- ]
378
- ],
379
- "nl": [
380
- # Dutch
381
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
382
- for x in [
383
- ("&", " en "),
384
- ("@", " bij "),
385
- ("%", " procent "),
386
- ("#", " hekje "),
387
- ("$", " dollar "),
388
- ("£", " pond "),
389
- ("°", " graden "),
390
- ]
391
- ],
392
- "tr": [
393
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
394
- for x in [
395
- ("&", " ve "),
396
- ("@", " at "),
397
- ("%", " yüzde "),
398
- ("#", " diyez "),
399
- ("$", " dolar "),
400
- ("£", " sterlin "),
401
- ("°", " derece "),
402
- ]
403
- ],
404
- "hu": [
405
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
406
- for x in [
407
- ("&", " és "),
408
- ("@", " kukac "),
409
- ("%", " százalék "),
410
- ("#", " kettőskereszt "),
411
- ("$", " dollár "),
412
- ("£", " font "),
413
- ("°", " fok "),
414
- ]
415
- ],
416
- "ko": [
417
- # Korean
418
- (re.compile(r"%s" % re.escape(x[0]), re.IGNORECASE), x[1])
419
- for x in [
420
- ("&", " 그리고 "),
421
- ("@", " 에 "),
422
- ("%", " 퍼센트 "),
423
- ("#", " 번호 "),
424
- ("$", " 달러 "),
425
- ("£", " 파운드 "),
426
- ("°", " 도 "),
427
- ]
428
- ],
429
- }
430
-
431
- def expand_symbols_multilingual(text, lang="en"):
432
- if lang in _symbols_multilingual:
433
- for regex, replacement in _symbols_multilingual[lang]:
434
- text = re.sub(regex, replacement, text)
435
- text = text.replace(" ", " ") # Ensure there are no double spaces
436
- return text.strip()
437
-
438
- _ordinal_re = {
439
- "en": re.compile(r"([0-9]+)(st|nd|rd|th)"),
440
- "es": re.compile(r"([0-9]+)(º|ª|er|o|a|os|as)"),
441
- "fr": re.compile(r"([0-9]+)(º|ª|er|re|e|ème)"),
442
- "de": re.compile(r"([0-9]+)(st|nd|rd|th|º|ª|\.(?=\s|$))"),
443
- "pt": re.compile(r"([0-9]+)(º|ª|o|a|os|as)"),
444
- "it": re.compile(r"([0-9]+)(º|°|ª|o|a|i|e)"),
445
- "pl": re.compile(r"([0-9]+)(º|ª|st|nd|rd|th)"),
446
- "ar": re.compile(r"([0-9]+)(ون|ين|ث|ر|ى)"),
447
- "cs": re.compile(r"([0-9]+)\.(?=\s|$)"), # In Czech, a dot is often used after the number to indicate ordinals.
448
- "ru": re.compile(r"([0-9]+)(-й|-я|-е|-ое|-ье|-го)"),
449
- "nl": re.compile(r"([0-9]+)(de|ste|e)"),
450
- "tr": re.compile(r"([0-9]+)(\.|inci|nci|uncu|üncü|\.)"),
451
- "hu": re.compile(r"([0-9]+)(\.|adik|edik|odik|edik|ödik|ödike|ik)"),
452
- "ko": re.compile(r"([0-9]+)(번째|번|차|째)"),
453
- }
454
- _number_re = re.compile(r"[0-9]+")
455
- _currency_re = {
456
- "USD": re.compile(r"((\$[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+\$))"),
457
- "GBP": re.compile(r"((£[0-9\.\,]*[0-9]+)|([0-9\.\,]*[0-9]+£))"),
458
- "EUR": re.compile(r"(([0-9\.\,]*[0-9]+€)|((€[0-9\.\,]*[0-9]+)))"),
459
- }
460
-
461
- _comma_number_re = re.compile(r"\b\d{1,3}(,\d{3})*(\.\d+)?\b")
462
- _dot_number_re = re.compile(r"\b\d{1,3}(\.\d{3})*(\,\d+)?\b")
463
- _decimal_number_re = re.compile(r"([0-9]+[.,][0-9]+)")
464
-
465
- def _remove_commas(m):
466
- text = m.group(0)
467
- if "," in text:
468
- text = text.replace(",", "")
469
- return text
470
-
471
- def _remove_dots(m):
472
- text = m.group(0)
473
- if "." in text:
474
- text = text.replace(".", "")
475
- return text
476
-
477
- def _expand_decimal_point(m, lang="en"):
478
- amount = m.group(1).replace(",", ".")
479
- return num2words(float(amount), lang=lang if lang != "cs" else "cz")
480
-
481
- def _expand_currency(m, lang="en", currency="USD"):
482
- amount = float((re.sub(r"[^\d.]", "", m.group(0).replace(",", "."))))
483
- full_amount = num2words(amount, to="currency", currency=currency, lang=lang if lang != "cs" else "cz")
484
-
485
- and_equivalents = {
486
- "en": ", ",
487
- "es": " con ",
488
- "fr": " et ",
489
- "de": " und ",
490
- "pt": " e ",
491
- "it": " e ",
492
- "pl": ", ",
493
- "cs": ", ",
494
- "ru": ", ",
495
- "nl": ", ",
496
- "ar": ", ",
497
- "tr": ", ",
498
- "hu": ", ",
499
- "ko": ", ",
500
- }
501
-
502
- if amount.is_integer():
503
- last_and = full_amount.rfind(and_equivalents.get(lang, ", "))
504
- if last_and != -1:
505
- full_amount = full_amount[:last_and]
506
-
507
- return full_amount
508
-
509
- def _expand_ordinal(m, lang="en"):
510
- return num2words(int(m.group(1)), ordinal=True, lang=lang if lang != "cs" else "cz")
511
-
512
- def _expand_number(m, lang="en"):
513
- return num2words(int(m.group(0)), lang=lang if lang != "cs" else "cz")
514
-
515
- def expand_numbers_multilingual(text, lang="en"):
516
- if lang == "zh":
517
- text = zh_num2words()(text)
518
- else:
519
- if lang in ["en", "ru"]:
520
- text = re.sub(_comma_number_re, _remove_commas, text)
521
- else:
522
- text = re.sub(_dot_number_re, _remove_dots, text)
523
- try:
524
- text = re.sub(_currency_re["GBP"], lambda m: _expand_currency(m, lang, "GBP"), text)
525
- text = re.sub(_currency_re["USD"], lambda m: _expand_currency(m, lang, "USD"), text)
526
- text = re.sub(_currency_re["EUR"], lambda m: _expand_currency(m, lang, "EUR"), text)
527
- except Exception as e:
528
- pass
529
- if lang != "tr":
530
- text = re.sub(_decimal_number_re, lambda m: _expand_decimal_point(m, lang), text)
531
- if lang in _ordinal_re:
532
- text = re.sub(_ordinal_re[lang], lambda m: _expand_ordinal(m, lang), text)
533
- text = re.sub(_number_re, lambda m: _expand_number(m, lang), text)
534
- return text
535
-
536
- def lowercase(text):
537
- return text.lower()
538
-
539
- def collapse_whitespace(text):
540
- return re.sub(_whitespace_re, " ", text)
541
-
542
- def multilingual_cleaners(text, lang):
543
- text = text.replace('"', "")
544
- if lang == "tr":
545
- text = text.replace("İ", "i")
546
- text = text.replace("Ö", "ö")
547
- text = text.replace("Ü", "ü")
548
- text = lowercase(text)
549
- text = expand_numbers_multilingual(text, lang)
550
- text = expand_abbreviations_multilingual(text, lang)
551
- text = expand_symbols_multilingual(text, lang=lang)
552
- text = collapse_whitespace(text)
553
- return text
554
-
555
- def basic_cleaners(text):
556
- """Basic pipeline that lowercases and collapses whitespace without transliteration."""
557
- text = lowercase(text)
558
- text = collapse_whitespace(text)
559
- return text
560
-
561
- def chinese_transliterate(text):
562
- return "".join(
563
- [p[0] for p in pypinyin.pinyin(text, style=pypinyin.Style.TONE3, heteronym=False, neutral_tone_with_five=True)]
564
- )
565
-
566
- def japanese_cleaners(text, katsu):
567
- text = katsu.romaji(text)
568
- text = lowercase(text)
569
- return text
570
-
571
- def korean_transliterate(text, transliter):
572
- return transliter.translit(text)
573
-
574
- # Fast Tokenizer Class
575
-
576
- class XTTSTokenizerFast(PreTrainedTokenizerFast):
577
- """
578
- Fast Tokenizer implementation for XTTS model using HuggingFace's PreTrainedTokenizerFast
579
- """
580
-
581
- def __init__(
582
- self,
583
- vocab_file: str = None,
584
- tokenizer_object: Optional[Tokenizer] = None,
585
- unk_token: str = "[UNK]",
586
- pad_token: str = "[PAD]",
587
- bos_token: str = "[START]",
588
- eos_token: str = "[STOP]",
589
- auto_map: dict = {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", None]},
590
- clean_up_tokenization_spaces: bool = True,
591
- **kwargs
592
- ):
593
- if tokenizer_object is None and vocab_file is not None:
594
- tokenizer_object = Tokenizer.from_file(vocab_file)
595
-
596
- if tokenizer_object is not None:
597
- # Configure the tokenizer
598
- tokenizer_object.pre_tokenizer = WhitespaceSplit()
599
- tokenizer_object.post_processor = TemplateProcessing(
600
- single=f"{bos_token} $A {eos_token}",
601
- special_tokens=[
602
- (bos_token, tokenizer_object.token_to_id(bos_token)),
603
- (eos_token, tokenizer_object.token_to_id(eos_token)),
604
- ],
605
- )
606
-
607
- super().__init__(
608
- tokenizer_object=tokenizer_object,
609
- unk_token=unk_token,
610
- pad_token=pad_token,
611
- bos_token=bos_token,
612
- eos_token=eos_token,
613
- clean_up_tokenization_spaces=clean_up_tokenization_spaces,
614
- **kwargs
615
- )
616
-
617
- # Character limits per language
618
- self.char_limits = {
619
- "en": 250, "de": 253, "fr": 273, "es": 239,
620
- "it": 213, "pt": 203, "pl": 224, "zh": 82,
621
- "ar": 166, "cs": 186, "ru": 182, "nl": 251,
622
- "tr": 226, "ja": 71, "hu": 224, "ko": 95,
623
- }
624
-
625
- # Initialize language tools
626
- self._katsu = None
627
- self._korean_transliter = Transliter(academic)
628
-
629
- # Ensure pad_token_id is set
630
- if self.pad_token_id is None:
631
- self.pad_token_id = self.tokenizer.token_to_id(self.pad_token)
632
-
633
- @cached_property
634
- def katsu(self):
635
- if self._katsu is None:
636
- self._katsu = cutlet.Cutlet()
637
- return self._katsu
638
-
639
- def preprocess_text(self, text: str, lang: str) -> str:
640
- """Apply text preprocessing for language"""
641
- base_lang = lang.split("-")[0] # remove region
642
- if base_lang in {"ar", "cs", "de", "en", "es", "fr", "hu", "it",
643
- "nl", "pl", "pt", "ru", "tr", "zh", "ko"}:
644
- text = multilingual_cleaners(text, base_lang)
645
- if base_lang == "zh":
646
- text = chinese_transliterate(text)
647
- if base_lang == "ko":
648
- text = korean_transliterate(text, self._korean_transliter)
649
- elif base_lang == "ja":
650
- text = japanese_cleaners(text, self.katsu)
651
- else:
652
- text = basic_cleaners(text)
653
- return text
654
-
655
- def batch_encode_with_split(self, texts: Union[str, List[str]], lang: Union[str, List[str]],
656
- **kwargs) -> torch.Tensor:
657
- """
658
- Split texts into smaller chunks based on language character limits and encode them using HuggingFace fast tokenizer.
659
- """
660
- # Convert single inputs to lists
661
- if isinstance(texts, str):
662
- texts = [texts]
663
- if isinstance(lang, str):
664
- lang = [lang]
665
- # Ensure lang list matches texts list
666
- if len(lang) == 1 and len(texts) > 1:
667
- lang = lang * len(texts)
668
-
669
- # Check if texts and lang have the same length
670
- if len(texts) != len(lang):
671
- raise ValueError(f"Number of texts ({len(texts)}) does not match number of languages ({len(lang)}).")
672
-
673
- batch_chunks = []
674
- max_splits = 0
675
-
676
- # For each text, split into chunks based on character limit
677
- for text, text_lang in zip(texts, lang):
678
- # Get language character limit
679
- base_lang = text_lang.split("-")[0]
680
- char_limit = self.char_limits.get(base_lang, 250)
681
-
682
- # Clean and preprocess
683
- text = self.preprocess_text(text, text_lang)
684
-
685
- # Split text into sentences/chunks based on language
686
- chunks = split_sentence(text, base_lang, text_split_length=char_limit)
687
-
688
- # Format each chunk
689
- formatted_chunks = []
690
- for chunk in chunks:
691
- lang_code = "zh-cn" if base_lang == "zh" else base_lang
692
- formatted_chunk = f"[{lang_code}]{chunk}"
693
- formatted_chunk = formatted_chunk.replace(" ", "[SPACE]")
694
- formatted_chunks.append(formatted_chunk)
695
-
696
- batch_chunks.append(formatted_chunks)
697
- max_splits = max(max_splits, len(formatted_chunks))
698
-
699
- # Flatten all chunks to a single list for batch encoding
700
- all_chunks = [chunk for chunks in batch_chunks for chunk in chunks]
701
-
702
- # Ensure the tokenizer is a fast tokenizer
703
- if not self.is_fast:
704
- raise ValueError("The tokenizer must be a fast tokenizer.")
705
-
706
- # Encode all chunks using the fast tokenizer
707
- encoding: BatchEncoding = self(
708
- all_chunks,
709
- add_special_tokens=False,
710
- padding=True,
711
- return_tensors='pt',
712
- **kwargs
713
- )
714
-
715
- # The 'input_ids' tensor will have shape [total_chunks, max_sequence_length]
716
- input_ids = encoding['input_ids'] # Tensor of shape [total_chunks, sequence_length]
717
-
718
- # Now, we need to organize this tensor back into the desired shape
719
- # We'll use 'batch_indices' to keep track of which chunks belong to which text
720
- batch_indices = []
721
- idx = 0
722
- for chunks in batch_chunks:
723
- batch_indices.append((idx, idx + len(chunks)))
724
- idx += len(chunks)
725
-
726
- # Determine max sequence length and add space for special tokens
727
- max_seq_length = input_ids.size(1) + 2 # +2 for BOS and EOS tokens
728
-
729
- # Prepare the final tensor
730
- batch_size = len(texts)
731
- padded_batch = torch.full(
732
- (batch_size, max_splits, max_seq_length),
733
- fill_value=self.pad_token_id,
734
- dtype=torch.long
735
- )
736
-
737
- # Populate the final tensor with BOS and EOS tokens
738
- for i, (start, end) in enumerate(batch_indices):
739
- chunks_input_ids = input_ids[start:end]
740
- num_chunks = chunks_input_ids.size(0)
741
-
742
- for j in range(num_chunks):
743
- sequence = chunks_input_ids[j]
744
- # find the length of the sequence
745
- seq_len = (sequence != self.pad_token_id).sum().item()
746
-
747
- # insert BOS
748
- padded_batch[i, j, 0] = self.bos_token_id
749
- # insert sequence
750
- padded_batch[i, j, 1:seq_len + 1] = sequence[:seq_len]
751
- # insert EOS
752
- padded_batch[i, j, seq_len + 1] = self.eos_token_id
753
-
754
- return padded_batch
755
-
756
- def _batch_encode_plus(
757
- self,
758
- batch_text_or_text_pairs,
759
- add_special_tokens: bool = True,
760
- padding_strategy=PaddingStrategy.DO_NOT_PAD,
761
- truncation_strategy=TruncationStrategy.DO_NOT_TRUNCATE,
762
- max_length: Optional[int] = None,
763
- stride: int = 0,
764
- is_split_into_words: bool = False,
765
- pad_to_multiple_of: Optional[int] = None,
766
- return_tensors: Optional[str] = None,
767
- return_token_type_ids: Optional[bool] = None,
768
- return_attention_mask: Optional[bool] = None,
769
- return_overflowing_tokens: bool = False,
770
- return_special_tokens_mask: bool = False,
771
- return_offsets_mapping: bool = False,
772
- return_length: bool = False,
773
- verbose: bool = True,
774
- **kwargs
775
- ) -> Dict[str, Any]:
776
- """
777
- Override batch encoding to handle language-specific preprocessing
778
- """
779
- lang = kwargs.pop("lang", ["en"] * len(batch_text_or_text_pairs))
780
- if isinstance(lang, str):
781
- lang = [lang]
782
- # Ensure lang list matches texts list
783
- if len(lang) == 1 and len(batch_text_or_text_pairs) > 1:
784
- lang = lang * len(batch_text_or_text_pairs)
785
-
786
- # Check if batch_text_or_text_pairs and lang have the same length
787
- if len(batch_text_or_text_pairs) != len(lang):
788
- raise ValueError(f"Number of texts ({len(batch_text_or_text_pairs)}) does not match number of languages ({len(lang)}).")
789
-
790
- # Preprocess each text in the batch with its corresponding language
791
- processed_texts = []
792
- for text, text_lang in zip(batch_text_or_text_pairs, lang):
793
- if isinstance(text, str):
794
- # Check length and preprocess
795
- #self.check_input_length(text, text_lang)
796
- processed_text = self.preprocess_text(text, text_lang)
797
-
798
- # Format text with language tag and spaces
799
- base_lang = text_lang.split("-")[0]
800
- lang_code = "zh-cn" if base_lang == "zh" else base_lang
801
- processed_text = f"[{lang_code}]{processed_text}"
802
- processed_text = processed_text.replace(" ", "[SPACE]")
803
-
804
- processed_texts.append(processed_text)
805
- else:
806
- processed_texts.append(text)
807
-
808
- # Call the parent class's encoding method with processed texts
809
- return super()._batch_encode_plus(
810
- processed_texts,
811
- add_special_tokens=add_special_tokens,
812
- padding_strategy=padding_strategy,
813
- truncation_strategy=truncation_strategy,
814
- max_length=max_length,
815
- stride=stride,
816
- is_split_into_words=is_split_into_words,
817
- pad_to_multiple_of=pad_to_multiple_of,
818
- return_tensors=return_tensors,
819
- return_token_type_ids=return_token_type_ids,
820
- return_attention_mask=return_attention_mask,
821
- return_overflowing_tokens=return_overflowing_tokens,
822
- return_special_tokens_mask=return_special_tokens_mask,
823
- return_offsets_mapping=return_offsets_mapping,
824
- return_length=return_length,
825
- verbose=verbose,
826
- **kwargs
827
- )
828
-
829
-
830
- def __call__(
831
- self,
832
- text: Union[str, List[str]],
833
- lang: Union[str, List[str]] = "en",
834
- add_special_tokens: bool = True,
835
- padding: Union[bool, str, PaddingStrategy] = False,
836
- truncation: Union[bool, str, TruncationStrategy] = False,
837
- max_length: Optional[int] = None,
838
- stride: int = 0,
839
- return_tensors: Optional[str] = None,
840
- return_token_type_ids: Optional[bool] = None,
841
- return_attention_mask: Optional[bool] = True,
842
- **kwargs
843
- ):
844
- """
845
- Main tokenization method
846
- """
847
- # Convert single string to list for batch processing
848
- if isinstance(text, str):
849
- text = [text]
850
- if isinstance(lang, str):
851
- lang = [lang]
852
- # Ensure lang list matches texts list
853
- if len(lang) == 1 and len(text) > 1:
854
- lang = lang * len(text)
855
-
856
- # Ensure text and lang lists have same length
857
- if len(text) != len(lang):
858
- raise ValueError(f"Number of texts ({len(text)}) does not match number of languages ({len(lang)}).")
859
-
860
- # Convert padding strategy
861
- if isinstance(padding, bool):
862
- padding_strategy = PaddingStrategy.LONGEST if padding else PaddingStrategy.DO_NOT_PAD
863
- else:
864
- padding_strategy = PaddingStrategy(padding)
865
-
866
- # Convert truncation strategy
867
- if isinstance(truncation, bool):
868
- truncation_strategy = TruncationStrategy.LONGEST_FIRST if truncation else TruncationStrategy.DO_NOT_TRUNCATE
869
- else:
870
- truncation_strategy = TruncationStrategy(truncation)
871
-
872
- # Use the batch encoding method
873
- encoded = self._batch_encode_plus(
874
- text,
875
- add_special_tokens=add_special_tokens,
876
- padding_strategy=padding_strategy,
877
- truncation_strategy=truncation_strategy,
878
- max_length=max_length,
879
- stride=stride,
880
- return_tensors=return_tensors,
881
- return_token_type_ids=return_token_type_ids,
882
- return_attention_mask=return_attention_mask,
883
- lang=lang,
884
- **kwargs
885
- )
886
-
887
- return encoded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
xttsv2_gpt2/tokenizer_config.json DELETED
@@ -1,192 +0,0 @@
1
- {
2
- "added_tokens_decoder": {
3
- "0": {
4
- "content": "[STOP]",
5
- "lstrip": false,
6
- "normalized": false,
7
- "rstrip": false,
8
- "single_word": false,
9
- "special": true
10
- },
11
- "1": {
12
- "content": "[UNK]",
13
- "lstrip": false,
14
- "normalized": false,
15
- "rstrip": false,
16
- "single_word": false,
17
- "special": true
18
- },
19
- "2": {
20
- "content": "[SPACE]",
21
- "lstrip": false,
22
- "normalized": false,
23
- "rstrip": false,
24
- "single_word": false,
25
- "special": true
26
- },
27
- "259": {
28
- "content": "[en]",
29
- "lstrip": false,
30
- "normalized": false,
31
- "rstrip": false,
32
- "single_word": false,
33
- "special": true
34
- },
35
- "260": {
36
- "content": "[de]",
37
- "lstrip": false,
38
- "normalized": false,
39
- "rstrip": false,
40
- "single_word": false,
41
- "special": true
42
- },
43
- "261": {
44
- "content": "[START]",
45
- "lstrip": false,
46
- "normalized": false,
47
- "rstrip": false,
48
- "single_word": false,
49
- "special": true
50
- },
51
- "262": {
52
- "content": "[fr]",
53
- "lstrip": false,
54
- "normalized": false,
55
- "rstrip": false,
56
- "single_word": false,
57
- "special": true
58
- },
59
- "267": {
60
- "content": "[ru]",
61
- "lstrip": false,
62
- "normalized": false,
63
- "rstrip": false,
64
- "single_word": false,
65
- "special": true
66
- },
67
- "284": {
68
- "content": "[es]",
69
- "lstrip": false,
70
- "normalized": false,
71
- "rstrip": false,
72
- "single_word": false,
73
- "special": true
74
- },
75
- "285": {
76
- "content": "[it]",
77
- "lstrip": false,
78
- "normalized": false,
79
- "rstrip": false,
80
- "single_word": false,
81
- "special": true
82
- },
83
- "286": {
84
- "content": "[pt]",
85
- "lstrip": false,
86
- "normalized": false,
87
- "rstrip": false,
88
- "single_word": false,
89
- "special": true
90
- },
91
- "293": {
92
- "content": "[cs]",
93
- "lstrip": false,
94
- "normalized": false,
95
- "rstrip": false,
96
- "single_word": false,
97
- "special": true
98
- },
99
- "294": {
100
- "content": "[pl]",
101
- "lstrip": false,
102
- "normalized": false,
103
- "rstrip": false,
104
- "single_word": false,
105
- "special": true
106
- },
107
- "295": {
108
- "content": "[tr]",
109
- "lstrip": false,
110
- "normalized": false,
111
- "rstrip": false,
112
- "single_word": false,
113
- "special": true
114
- },
115
- "297": {
116
- "content": "[nl]",
117
- "lstrip": false,
118
- "normalized": false,
119
- "rstrip": false,
120
- "single_word": false,
121
- "special": true
122
- },
123
- "5022": {
124
- "content": "[ar]",
125
- "lstrip": false,
126
- "normalized": false,
127
- "rstrip": false,
128
- "single_word": false,
129
- "special": true
130
- },
131
- "5023": {
132
- "content": "[zh-cn]",
133
- "lstrip": false,
134
- "normalized": false,
135
- "rstrip": false,
136
- "single_word": false,
137
- "special": true
138
- },
139
- "5412": {
140
- "content": "[ja]",
141
- "lstrip": false,
142
- "normalized": false,
143
- "rstrip": false,
144
- "single_word": false,
145
- "special": true
146
- },
147
- "5753": {
148
- "content": "[hu]",
149
- "lstrip": false,
150
- "normalized": false,
151
- "rstrip": false,
152
- "single_word": false,
153
- "special": true
154
- },
155
- "6152": {
156
- "content": "[ko]",
157
- "lstrip": false,
158
- "normalized": false,
159
- "rstrip": false,
160
- "single_word": false,
161
- "special": true
162
- },
163
- "6680": {
164
- "content": "[hi]",
165
- "lstrip": false,
166
- "normalized": false,
167
- "rstrip": false,
168
- "single_word": false,
169
- "special": true
170
- },
171
- "6681": {
172
- "content": "[PAD]",
173
- "lstrip": false,
174
- "normalized": false,
175
- "rstrip": false,
176
- "single_word": false,
177
- "special": true
178
- }
179
- },
180
- "auto_map": {"AutoTokenizer": ["AstraMindAI/xtts2-gpt--tokenizer.XTTSTokenizerFast", null]},
181
- "bos_token": "[START]",
182
- "clean_up_tokenization_spaces": true,
183
- "eos_token": "[STOP]",
184
- "max_length": null,
185
- "model_max_length": 1000000000000000019884624838656,
186
- "pad_to_multiple_of": null,
187
- "pad_token": "[PAD]",
188
- "pad_token_type_id": 0,
189
- "padding_side": "right",
190
- "tokenizer_class": "XTTSTokenizerFast",
191
- "unk_token": "[UNK]"
192
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
xttsv2_gpt2/xtts2_gpt_modeling.py DELETED
@@ -1,505 +0,0 @@
1
- import functools
2
- import math
3
- import random
4
- import uuid
5
- from array import array
6
-
7
- import numpy as np
8
- import torch
9
- import torch.nn as nn
10
- from typing import List, Optional, Union, Iterable, Tuple, Mapping, Dict
11
-
12
- from torch import Tensor
13
- from transformers import PretrainedConfig, GPT2Config
14
- from vllm.attention import AttentionMetadata
15
- from vllm.config import CacheConfig, MultiModalConfig
16
- from vllm.distributed import get_pp_group
17
- from vllm.inputs import InputContext, INPUT_REGISTRY, DecoderOnlyInputs, token_inputs
18
- from vllm.model_executor.layers.logits_processor import LogitsProcessor
19
- from vllm.model_executor.layers.quantization import QuantizationConfig
20
- from vllm.model_executor.layers.sampler import Sampler, SamplerOutput
21
- from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding, ParallelLMHead
22
- from vllm.model_executor.model_loader.weight_utils import default_weight_loader
23
- from vllm.model_executor.models.gpt2 import GPT2Block
24
- from vllm.model_executor.models.utils import make_layers, make_empty_intermediate_tensors_factory
25
- from vllm.model_executor.sampling_metadata import SamplingMetadata
26
- from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalInputs
27
- from vllm.sequence import IntermediateTensors, SequenceData, VLLM_TOKEN_ID_ARRAY_TYPE
28
- from vllm.model_executor.models.interfaces import SupportsMultiModal, SupportsPP
29
-
30
-
31
-
32
- class LearnedPositionEmbeddings(nn.Module):
33
- def __init__(self, seq_len, model_dim, init=0.02, relative=False, supports_pp=False):
34
- super().__init__()
35
- # nn.Embedding
36
- self.emb = VocabParallelEmbedding(seq_len, model_dim) if supports_pp else nn.Embedding(seq_len, model_dim)
37
- # Initializing this way is standard for GPT-2
38
- self.emb.weight.data.normal_(mean=0.0, std=init)
39
- self.relative = relative
40
- self.seq_len = seq_len
41
-
42
- def forward(self, x):
43
- sl = x.shape[1]
44
- if self.relative:
45
- start = random.randint(sl, self.seq_len) - sl
46
- return self.emb(torch.arange(start, start + sl, device=x.device))
47
- else:
48
- return self.emb(torch.arange(0, sl, device=x.device))
49
-
50
- def get_fixed_embedding(self, ind: torch.Tensor, dev: torch.device) -> torch.Tensor:
51
- """Get position embeddings with batch support.
52
-
53
- Handles both single and batched inputs, returning embeddings that can be
54
- directly added to input embeddings of the same shape.
55
-
56
- Args:
57
- ind: Position indices tensor. Can be single or batched
58
- Shape: [..., seq_len] or [seq_len]
59
- dev: Target device for the embeddings
60
-
61
- Returns:
62
- Position embeddings tensor matching input shape plus embedding dimension
63
- Shape: [batch_size, seq_len, model_dim] or [1, 1, model_dim]
64
-
65
- Example:
66
- >>> pos_emb = LearnedPositionEmbeddings(100, 64)
67
- >>> # Batched input
68
- >>> batch_indices = torch.zeros((3, 5)) # batch_size=3, seq_len=5
69
- >>> embeddings = pos_emb.get_fixed_embedding(batch_indices, 'cuda')
70
- >>> embeddings.shape # Returns: [3, 5, 64]
71
- """
72
- if ind.shape[0] > 1:
73
- pos_embeddings = []
74
- for index in ind:
75
- # Create embeddings for each position in the sequence
76
- pos_embeddings.append(self.emb(index))
77
-
78
- # Shape: [1, seq_len, model_dim] -> [batch_size, seq_len, model_dim]
79
- return torch.stack(pos_embeddings, dim=0)
80
- else:
81
- # Handle single input
82
- # Shape: [1, 1, model_dim]
83
- return self.emb(torch.tensor([ind], device=dev)).unsqueeze(0)
84
-
85
-
86
- def get_xtts_max_audio_tokens(ctx: InputContext) -> int:
87
- """Calculate maximum audio tokens based on text context and audio duration."""
88
- # Based on GPT config and XTTSv2 settings
89
- return 608
90
-
91
-
92
- def dummy_seq_data_for_xtts(
93
- ctx: InputContext,
94
- seq_len: int,
95
- audio_count: int,
96
- ) -> SequenceData:
97
- """Create dummy sequence data for XTTS profiling."""
98
- # Calculate audio token space needed
99
- max_audio_token_conditioning = ctx.model_config.hf_config.max_prompt_tokens # in xtts prompt = voice conditioning
100
- audio_placeholder = array(
101
- VLLM_TOKEN_ID_ARRAY_TYPE,
102
- [1]
103
- ) * max_audio_token_conditioning
104
-
105
- # Add separator between chunks
106
- audio_token_ids = (audio_placeholder + array(VLLM_TOKEN_ID_ARRAY_TYPE, [1])) * audio_count
107
-
108
- # Fill remaining sequence with padding
109
- other_token_ids = array(VLLM_TOKEN_ID_ARRAY_TYPE, [1]) * (seq_len - len(audio_token_ids))
110
- # not -1 since we add the start audio token
111
-
112
- return SequenceData(
113
- audio_token_ids +
114
- other_token_ids
115
- )
116
-
117
- def dummy_conditioning_for_xtts(
118
- ctx: InputContext,
119
- seq_len: int,
120
- audio_count: int,
121
- ) -> dict:
122
- """Create dummy conditioning data for XTTS."""
123
- return {
124
- "audio": {
125
- "embeds":[
126
- torch.zeros(
127
- (seq_len, ctx.model_config.hf_config.hidden_size),
128
- dtype=ctx.model_config.dtype) for _ in range(audio_count)
129
- ],
130
- "is_logits_only_mode": False,
131
- }
132
- }
133
-
134
-
135
- def dummy_data_for_xtts(
136
- ctx: InputContext,
137
- seq_len: int,
138
- mm_counts: Mapping[str, int],
139
- ) -> Tuple[SequenceData, dict]:
140
- """Create complete dummy data for XTTS profiling."""
141
- audio_count = mm_counts["audio"]
142
- seq_data = dummy_seq_data_for_xtts(ctx, seq_len, audio_count)
143
- cond_data = dummy_conditioning_for_xtts(ctx, seq_len, audio_count)
144
- return seq_data, cond_data
145
-
146
-
147
- def input_mapper_for_xtts(ctx: InputContext, data: Union[Dict, List[Tensor]]) -> MultiModalInputs:
148
- """Map input data to XTTS format."""
149
-
150
- assert isinstance(data, dict), "XTTS MultiModal input data must be a dictionary with keys: 'embeds', 'is_logits_only_mode'"
151
-
152
- embeds = data.get("embeds")
153
- is_logits_only_mode = data.get("is_logits_only_mode", False)
154
-
155
- # Each item should be a torch tensor
156
- for audio_input in embeds:
157
- if not isinstance(audio_input, Tensor):
158
- raise NotImplementedError(f"Unsupported data type: {type(audio_input)}")
159
-
160
- return MultiModalInputs({"cond_latents": embeds,
161
- "is_logits_only_mode": is_logits_only_mode,
162
- })
163
-
164
-
165
- def input_processor_for_xtts2_gpt(ctx: InputContext, inputs: DecoderOnlyInputs):
166
- """
167
- We'll accomodate for the extra contditioning token and for the start audio token,
168
- we actually insert a -1 repeated for the differecne in length between the conditioning and the tokenized text
169
- and then we add 1 for the start audio token
170
- Args:
171
- ctx:
172
- inputs:
173
-
174
- Returns:
175
-
176
- """
177
- multi_modal_data = inputs.get("multi_modal_data")
178
- audio_dict = multi_modal_data['audio']
179
- audio = audio_dict.get('embeds')
180
-
181
- is_last_decoding_pass = audio_dict.get("is_logits_only_mode", False)
182
-
183
- prompt_token_ids = inputs.get("prompt_token_ids")
184
-
185
- if not is_last_decoding_pass:
186
- # we fill everything with 0 since we don't actually needs text token ids, it would mess up in the sampling step
187
- new_token_ids = [1] * (audio.shape[0] + 1) # +1 for the start audio generation token
188
- else:
189
- new_token_ids = ([1] * audio.shape[0]) + prompt_token_ids
190
- # the encoding had already been done externally to reuse the embeddings for later use but we
191
- # account for the new token that will be added before generation
192
- new_prompt = None
193
- return token_inputs(prompt_token_ids=new_token_ids,
194
- prompt=new_prompt,
195
- multi_modal_data=multi_modal_data)
196
-
197
-
198
- @MULTIMODAL_REGISTRY.register_input_mapper("audio", input_mapper_for_xtts)
199
- @MULTIMODAL_REGISTRY.register_max_multimodal_tokens("audio", get_xtts_max_audio_tokens)
200
- @INPUT_REGISTRY.register_dummy_data(dummy_data_for_xtts)
201
- @INPUT_REGISTRY.register_input_processor(input_processor_for_xtts2_gpt)
202
- class XttsGPT(nn.Module, SupportsMultiModal, SupportsPP):
203
- def __init__(
204
- self,
205
- config: PretrainedConfig,
206
- multimodal_config: MultiModalConfig,
207
- cache_config: Optional[CacheConfig] = None,
208
- quant_config: Optional[QuantizationConfig] = None,
209
- ):
210
- super().__init__()
211
- self.config = config
212
- self.quant_config = quant_config
213
-
214
- # Core GPT components
215
- self.gpt = GPT2Model(
216
- config,
217
- cache_config,
218
- quant_config,
219
- prefix="gpt"
220
- )
221
- self.final_norm = nn.LayerNorm(config.hidden_size, bias=True, eps=config.layer_norm_epsilon)
222
- # Output head for mel tokens
223
- self.mel_head = ParallelLMHead(
224
- config.num_audio_tokens,
225
- config.hidden_size,
226
- bias=True,
227
- quant_config=quant_config,
228
- prefix="mel_head"
229
- )
230
- self.audio_start_generation_token = config.start_audio_token
231
-
232
- # Initialize logits processor and sampler
233
- logit_scale = getattr(config, "logit_scale", 1.0)
234
- self.logits_processor = LogitsProcessor(config.num_audio_tokens,
235
- config.num_audio_tokens,
236
- logit_scale)
237
- self.sampler = Sampler()
238
-
239
- @staticmethod
240
- def check_is_logits_only_mode(is_logits_only_mode):
241
-
242
- # First check if it's a boolean
243
- if isinstance(is_logits_only_mode, bool):
244
- return is_logits_only_mode
245
-
246
- # Then check if it's a tensor
247
- if torch.is_tensor(is_logits_only_mode):
248
- # if it's a scalar tensor, return the value
249
- if is_logits_only_mode.numel() == 1:
250
- return bool(is_logits_only_mode.item())
251
- # for non-scalar tensors, check if all elements are the same
252
- return is_logits_only_mode.any()
253
-
254
- # Fallback
255
- return bool(is_logits_only_mode)
256
-
257
- def _calculate_start_token_indices(self, cond_latents: List[torch.Tensor]) -> List[int]:
258
- """Calcola gli indici dove inserire i token di start.
259
-
260
- Args:
261
- cond_latents: Lista di tensori di condizionamento
262
-
263
- Returns:
264
- Lista di indici dove inserire i token di start
265
- """
266
- indices = []
267
- current_idx = 0
268
-
269
- for cond_latent in cond_latents:
270
- # Aggiungi la lunghezza del segmento corrente
271
- current_idx += cond_latent.shape[0]
272
- # Aggiungi l'indice per il token di start dopo questo segmento
273
- indices.append(current_idx)
274
- # Incrementa per il token di start che verrà aggiunto
275
- current_idx += 1
276
-
277
- return indices
278
-
279
- # noinspection PyMethodOverriding
280
- def forward(
281
- self,
282
- input_ids: torch.Tensor,
283
- positions: torch.Tensor,
284
- kv_caches: List[torch.Tensor],
285
- attn_metadata: AttentionMetadata,
286
- intermediate_tensors: Optional["IntermediateTensors"] = None,
287
- cond_latents: Optional[torch.Tensor] = None,
288
- is_logits_only_mode: bool = False,
289
- **kwargs,
290
- ) -> Union[torch.Tensor, "IntermediateTensors"]:
291
- """Forward pass following VLLM pattern."""
292
- # it is not the first iter either if the cond latents are emtpy or if the kv_caches are not empty
293
- is_first_iteration = (input_ids==1).all()
294
-
295
- #assert len(input_ids) == 1 or (cond_latents is not None and not is_first_iteration), "Conditioning data (voice conditioning+text_embeddings) is required for XTTS"
296
-
297
- is_logits_only_mode = self.check_is_logits_only_mode(is_logits_only_mode)
298
-
299
- if is_first_iteration:
300
- # we add it to enable the model to start the generation
301
- input_ids[-1] = self.audio_start_generation_token
302
-
303
- hidden_states = self.gpt(
304
- input_ids=input_ids,
305
- position_ids=positions,
306
- kv_caches=kv_caches,
307
- attn_metadata=attn_metadata,
308
- intermediate_tensors=intermediate_tensors,
309
- # this is the conditioning input ( voice conditioning + text_embeds )
310
- input_embeds=cond_latents,
311
- is_first_iteration=is_first_iteration,
312
- is_logits_only_mode=is_logits_only_mode
313
- )
314
-
315
- return hidden_states
316
-
317
- def compute_logits(
318
- self,
319
- hidden_states: torch.Tensor,
320
- sampling_metadata: SamplingMetadata,
321
- ) -> Optional[torch.Tensor]:
322
-
323
- # normalize the hidden states
324
- hidden_states = self.final_norm(hidden_states)
325
-
326
- # Check if we need to collect hidden states
327
- sampling_params = sampling_metadata.seq_groups[0].sampling_params
328
- if hasattr(sampling_params, 'hidden_state_collector'):
329
- # Call the collector directly with the hidden states
330
- sampling_params.hidden_state_collector(hidden_states, None) # The request_id is already bound
331
-
332
- # Compute logits using the mel_head
333
- logits = self.logits_processor(self.mel_head, hidden_states, sampling_metadata)
334
- return logits
335
-
336
- def sample(
337
- self,
338
- logits: torch.Tensor,
339
- sampling_metadata: SamplingMetadata,
340
- ) -> Optional[SamplerOutput]:
341
- next_tokens = self.sampler(logits, sampling_metadata)
342
- return next_tokens
343
-
344
- def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
345
- """Load weights following VLLM pattern."""
346
- params_dict = dict(self.named_parameters(remove_duplicate=False))
347
- loaded_names = set()
348
- for name, loaded_weight in weights:
349
- if name not in params_dict:
350
- #print(f"Skipping loading of {name} bc it is not found") # used to check if all weights were loaded
351
- continue
352
-
353
- param = params_dict[name]
354
- if "c_attn" in name or "c_proj" in name or "c_fc" in name:
355
- if name.endswith(".weight"):
356
- loaded_weight = loaded_weight.t()
357
-
358
- weight_loader = getattr(param, "weight_loader", default_weight_loader)
359
- weight_loader(param, loaded_weight)
360
- loaded_names.add(name)
361
- # used to check if all weights were loaded
362
- assert set(params_dict.keys()) - loaded_names == set(), \
363
- (f"Missing weights: {set(params_dict.keys()) - loaded_names}, "
364
- f"this probably means you are using an incompatible model ")
365
-
366
- class GPT2Model(nn.Module):
367
-
368
- def __init__(
369
- self,
370
- config: GPT2Config,
371
- cache_config: Optional[CacheConfig] = None,
372
- quant_config: Optional[QuantizationConfig] = None,
373
- prefix: str = "",
374
- ):
375
- super().__init__()
376
- self.config = config
377
- assert not config.add_cross_attention
378
- assert not config.scale_attn_by_inverse_layer_idx
379
- assert not config.reorder_and_upcast_attn
380
- self.embed_dim = config.hidden_size
381
- self.wte = VocabParallelEmbedding(config.num_audio_tokens, self.embed_dim)
382
- self.wpe = (
383
- LearnedPositionEmbeddings(config.max_audio_tokens + 3, config.decoder_input_dim)
384
- if config.max_audio_tokens != -1
385
- else functools.partial(config.null_position_embeddings, dim=config.decoder_input_dim)
386
- )
387
- self.start_layer, self.end_layer, self.h = make_layers(
388
- config.num_hidden_layers,
389
- lambda prefix: GPT2Block(
390
- config, cache_config, quant_config, prefix=prefix),
391
- prefix=f"{prefix}.h")
392
- self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
393
- self.make_empty_intermediate_tensors = (
394
- make_empty_intermediate_tensors_factory(["hidden_states"],
395
- config.hidden_size))
396
-
397
-
398
- def forward(
399
- self,
400
- input_ids: torch.Tensor,
401
- position_ids: torch.Tensor,
402
- kv_caches: List[torch.Tensor],
403
- attn_metadata: AttentionMetadata,
404
- intermediate_tensors: Optional[IntermediateTensors],
405
- # we pass this so that we can concatenate the text and conditioning input
406
- input_embeds: Optional[torch.Tensor] = None,
407
- is_first_iteration: bool = False,
408
- is_logits_only_mode: bool = False,
409
- ) -> Union[torch.Tensor, IntermediateTensors]:
410
-
411
- if get_pp_group().is_first_rank:
412
- # if we are not doing the final conversion from token to latent and it is first pass(prefill)
413
- if is_first_iteration and not is_logits_only_mode:
414
- input_ids = input_ids[-1].reshape(1, 1)
415
- elif is_logits_only_mode:
416
- # we remove the contidioning input and keep just the audio token
417
- if isinstance(input_embeds, list):
418
- starting_idx = []
419
- for input_embed in input_embeds:
420
- starting_idx.append(input_embed.shape[0])
421
- ending_ids = attn_metadata.seq_lens # list
422
-
423
- # First sequence: from starting_idx[0] to ending_ids[0]
424
- cumulative_starts = [starting_idx[0]] # First starts at its own index
425
- cumulative_ends = [ending_ids[0]] # First ends at its ending_id
426
-
427
- # For subsequent sequences:
428
- # Start = previous_end + current_start
429
- # End = previous_end + current_end
430
- for i in range(1, len(starting_idx)):
431
- next_start = cumulative_ends[i - 1] + starting_idx[i]
432
- next_end = cumulative_ends[i - 1] + ending_ids[i]
433
- cumulative_starts.append(next_start)
434
- cumulative_ends.append(next_end)
435
-
436
- ids_for_unpacking = [end-start for start, end in zip(cumulative_starts, cumulative_ends)]
437
-
438
- input_ids = torch.cat([
439
- input_ids[start:end].reshape(1, -1)
440
- for start, end in zip(cumulative_starts, cumulative_ends)
441
- ], dim=-1)
442
- position_ids = torch.cat([
443
- position_ids[start:end].reshape(1, -1)
444
- for start, end in zip(cumulative_starts, cumulative_ends)
445
- ], dim= -1).squeeze(0)
446
- else:
447
- input_ids = input_ids[input_embeds.shape[1]:].reshape(1, -1)
448
- position_ids = position_ids[input_embeds.shape[1]:]#.reshape(1, -1)
449
- else:
450
- input_ids = input_ids
451
-
452
- audio_inputs_embeds = self.wte(input_ids).squeeze(0)
453
-
454
- # weird but they to it like this in the xtts2 model
455
- position_embeds = self.wpe.get_fixed_embedding(
456
- position_ids, input_ids.device
457
- ) if not is_first_iteration \
458
- else self.wpe(audio_inputs_embeds.reshape(-1, 1)) # we need to reshape to 2D tensor or useless?
459
-
460
- hidden_states = audio_inputs_embeds + position_embeds
461
-
462
- if isinstance(input_embeds, list) and is_logits_only_mode:
463
- hidden_states = list(hidden_states.split(ids_for_unpacking, dim=0))
464
-
465
- if is_first_iteration or is_logits_only_mode:
466
- # We concat the text and audio conditioning input in the sequence dimension
467
- if isinstance(input_embeds, list):
468
- input_embeds = [input_embed.view(-1, input_embed.shape[-1]) for input_embed in input_embeds]
469
- else:
470
- input_embeds = input_embeds.view(-1, input_embeds.shape[-1]) # we ensure we have a 2D tensor
471
-
472
- if not isinstance(input_embeds, list) and input_embeds.shape[0] == attn_metadata.num_prefill_tokens:
473
- # this is during profiling, wee need to remove the last token
474
- # the attn_metadata.num_prefill_tokens(prompt len) should be == to input_embeds.shape[0] - 1
475
- # to account for the start audio gen embedding that will be cat to the text embeddings
476
- input_embeds = input_embeds[:-1]
477
-
478
- if is_first_iteration or is_logits_only_mode:
479
- # we concatenate the conditioning input to the text conditioning input
480
- if isinstance(input_embeds, list):
481
- hidden_states = torch.cat([
482
- tensor for pair in zip(input_embeds, [hidden_states] * len(input_embeds)
483
- if not isinstance(hidden_states, list) else hidden_states)
484
- for tensor in pair
485
- ], dim=0)
486
- else:
487
- hidden_states = torch.cat([input_embeds, hidden_states], dim=0)
488
-
489
- #flatten the hidden state
490
- hidden_states = hidden_states.view(-1, self.embed_dim)
491
- else:
492
- assert intermediate_tensors is not None
493
- hidden_states = intermediate_tensors["hidden_states"]
494
-
495
- for i in range(self.start_layer, self.end_layer):
496
- layer = self.h[i]
497
- hidden_states = layer(hidden_states,
498
- kv_caches[i - self.start_layer],
499
- attn_metadata)
500
-
501
- if not get_pp_group().is_last_rank:
502
- return IntermediateTensors({"hidden_states": hidden_states})
503
-
504
- hidden_states = self.ln_f(hidden_states)
505
- return hidden_states