File size: 26,291 Bytes
bf0e490 61985dd bf0e490 56b5e49 bf0e490 56b5e49 bf0e490 61985dd bf0e490 61985dd bf0e490 61985dd bf0e490 837fcf3 bf0e490 61985dd bf0e490 61985dd 4686692 61985dd 61faf9d 61985dd bf0e490 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 |
---
library_name: transformers
tags:
- voice-cloning
- audio
- unsloth
- orpheus
- snac
- hypaai
- lora
- merged
license: apache-2.0
datasets:
- hypaai/Hypa_Fleurs
- MrDragonFox/Elise
- canopylabs/zac-sample-dataset
- google/fleurs
language:
- ig
- yo
- ha
- en
base_model:
- canopylabs/orpheus-3b-0.1-ft
pipeline_tag: text-to-speech
---
# Hypa_Orpheus-3b-0.1-ft (merged 16-bit)
A 16-bit quantized and merged, memory-efficient fine-tuned version of [`canopylabs/orpheus-3b-0.1-ft`](https://huggingface.co/canopylabs/orpheus-3b-0.1-ft), optimized with Unsloth and LoRA, for expressive multilingual TTS, especially in low-resource African languages. This model provides the following capabilities:
* Text-to-Speech generation
* Speech synthesis for under-represented accents
* Voice cloning & emotion synthesis
* Research on multilingual low-resource voice AI
Check out the model at [`HypaChat`](https://hypachat.com/)
---
## Model Details
### Model Summary
This model was trained on a parallel text-speech dataset totaling over 300 hours (75k samples) of Nigerian-accented and low-resource language audio (Igbo, Yoruba, Hausa). A key part of the dataset comes from AfroVoices' transcription of real-world YouTube data (denoted as Random speaker, ~100+ hrs).
To preserve and enhance multilingual capabilities while avoiding catastrophic forgetting, we included synthetic speech-text data sampled from the original 8 Orpheus voices using the default emotional prompts.
The final training set also included new speakers like:
* Eniola (40 hrs) – Female, bold, clear
* Moyo (40 hrs) – Female, professional, articulate
* Lovelyn (35 hrs) – Female, warm, shy
* Precious (30 hrs) – Female, friendly, gentle
This model sets state-of-the-art performance on low-resource Multilingual TTS tasks across African languages (see training stats below).
### Base Model Details
The default Orpheus-TTS model released by [`Canopy Labs`](https://canopylabs.ai/releases/orpheus_can_speak_any_language) supports the below voices and emotions:
Voices: `tara`, `leah`, `jess`, `leo`, `dan`, `mia`, `zac`, and `zoe`.
Emotions: `<laugh>`, `<chuckle>`, `<sigh>`, `<cough>`, `<sniffle>`, `<groan>`, `<yawn>`, and `<gasp>`.
Through synthetic data generation and addition, our finetuned model also maintains these voices and emotions. Please visit the default model's card for mor info on voices and emotions.
### Our Model Sample Generations
🎧 Listen to samples generated by Hypa Orpheus-TTS
<div style="margin-top: 20px;">
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th style="border: 1px solid #ddd; padding: 8px; width: 30%;">Text Input</th>
<th style="border: 1px solid #ddd; padding: 8px; width: 40%;">Audio Output</th>
<th style="border: 1px solid #ddd; padding: 8px; width: 10%;">Language</th>
<th style="border: 1px solid #ddd; padding: 8px; width: 10%;">Voice</th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">I am cooking for guests tomorrow and need to know how to make aioli. Can you give me a step-by-step recipe.</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Emmanuel_English.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">English</td>
<td style="border: 1px solid #ddd; padding: 8px;">Emmanuel</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">Ina dafa abinci don bakin gobe kuma ina bukatar sanin yadda ake yin ailoli. Za ka iya ba ni girke-gireken matakan daya bayan daya?</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Emmanuel_Hausa.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">Hausa</td>
<td style="border: 1px solid #ddd; padding: 8px;">Emmanuel</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">Ina dafa abinci don bakin gobe kuma ina bukatar sanin yadda ake yin ailoli. Za ka iya ba ni girke-gireken matakan daya bayan daya?</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Eniola_Hausa.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">Hausa</td>
<td style="border: 1px solid #ddd; padding: 8px;">Eniola</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">Èmi máa se oúnjẹ fún àwọn àlejò l'ọ́la mo sì nílò láti mọ bí wọn ti ńṣe aioli. Ṣe o lè fún mi ni àwọn ìlànà ìdáná ẹlẹ́sẹẹsẹ?</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Eniola_Yoruba.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">Yoruba</td>
<td style="border: 1px solid #ddd; padding: 8px;">Eniola</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">I am cooking for guests tomorrow and need to know how to make aioli. Can you give me a step-by-step recipe.</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Eniola_English.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">English</td>
<td style="border: 1px solid #ddd; padding: 8px;">Eniola</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">M na-esi nri maka ndị ọbịa echi ma achọ ịmata otú esi esi aioli. Ị nwere ike inye m usoro ntụziaka?</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Eniola_Igbo.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">Igbo</td>
<td style="border: 1px solid #ddd; padding: 8px;">Eniola</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">M na-esi nri maka ndị ọbịa echi ma achọ ịmata otú esi esi aioli. Ị nwere ike inye m usoro ntụziaka?</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Lovelyn_Igbo.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">Igbo</td>
<td style="border: 1px solid #ddd; padding: 8px;">Lovelyn</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">I am cooking for guests tomorrow and need to know how to make aioli. Can you give me a step-by-step recipe.</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<audio controls style="width: 100%;">
<source src="https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit/resolve/main/assets/Lovelyn_English.wav" type="audio/wav">
</audio>
</td>
<td style="border: 1px solid #ddd; padding: 8px;">English</td>
<td style="border: 1px solid #ddd; padding: 8px;">Lovelyn</td>
</tr>
</tbody>
</table>
</div>
---
## Training Details
### Training Summary
* Base model: canopylabs/orpheus-3b-0.1-ft
* Training engine: Unsloth + LoRA
* LoRA config: r=1024, alpha=1024, dropout=0.0, full attention + FFN adaptation
* Quantization: 4-bit (bnb) for training; final model is highly memory-efficient
* Total steps: 18,014 (1 epoch)
* Batch size: 1 × 4 (grad accum)
* GPU: A100 40GB (max 55% VRAM used)
<div style="margin-top: 20px;">
<table style="border-collapse: collapse;">
<thead>
<tr>
<th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Step</th>
<th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Training Loss</th>
<th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Validation Loss</th>
</tr>
</thead>
<tbody>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">5,000</td>
<td style="border: 1px solid #ddd; padding: 8px;">3.9496</td>
<td style="border: 1px solid #ddd; padding: 8px;">3.8790</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">10,000</td>
<td style="border: 1px solid #ddd; padding: 8px;">3.8863</td>
<td style="border: 1px solid #ddd; padding: 8px;">3.79497</td>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">15,000</td>
<td style="border: 1px solid #ddd; padding: 8px;">3.8544</td>
<td style="border: 1px solid #ddd; padding: 8px;">3.75323</td>
</tr>
</tbody>
</table>
</div>
### Dataset Summary
* Sources:
* ✅ Manually aligned YouTube transcriptions (aka Random)
* ✅ Synthetic voice generation from Orpheus TTS
* ✅ Parallel text-audio pairs for African-English, Igbo, Yoruba, Hausa
* Total Hours: 300+ (multi-accent)
* Key Speakers: 45+ unique voices (see speaker distribution chart below)

We plan to open-source the full dataset shortly similar to the [Hypa_Fleurs](https://huggingface.co/datasets/hypaai/Hypa_Fleurs) initiative.
---
## Licensing and Citation
This model is released under an [Open Source License](./LICENSE) (apache-2.0). Please refer to the LICENSE file for full details.
When using this model in your work, please cite both this model as well as the base [`canopylabs/orpheus-3b-0.1-ft`](https://huggingface.co/canopylabs/orpheus-3b-0.1-ft) model as follows:
```bibtex
@misc{canopylabsorpheus,
title={Orpheus-3b-0.1-ft: A Multilingual Text-to-Speech Model},
author={Canopy Labs},
year={2025},
publisher={Hugging Face},
howpublished={\url{https://huggingface.co/canopylabs/orpheus-3b-0.1-ft}},
note={Fine-tuned version of Orpheus for expressive TTS}
}
@misc{hypaorpheus4bit,
title={Hypa_Orpheus-3b-0.1-ft (LoRA-4bit)},
author={Hypa AI},
year={2025},
note={Fine-tuned Orpheus TTS on African languages},
url={https://huggingface.co/hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-bnb-4bit}
}
```
---
## Acknowledgements
- **Canopy Labs Team:** For creating the foundational model and opensourcing it.
- **AfroVoices Experts:** For their translation expertise and high-quality datasets.
- **Community Support:** We thank all supporters, contributors, and users.
---
## Contact and Contributions
For any questions, issues, or contributions, please open an issue in this repository or contact [hypa.ai.ng@gmail.com](mailto:hypa.ai.ng@gmail.com). Contributions are welcome!
---
## Closing Remarks
By making Hypa_Orpheus available, we hope to empower research and development in multilingual speech technologies for African languages.
Hypa AI remains steadfast in its mission to pioneer intelligent solutions that are not just technologically advanced but are also culturally aware, ensuring that the future of AI is as diverse and inclusive as the world it serves.
AfroVoices, a subsidiary of Hypa AI, is dedicated to amplifying African voices, languages, and cultures in the intelligence age. Focused on bridging the digital representation gap, AfroVoices curates datasets and resources for African languages, promoting inclusivity and cultural appreciation in AI technologies. Their mission goes beyond technological innovation, aiming to celebrate the richness of African linguistic diversity on a global stage.
---
## Usage
### Unsloth Inference
Download the nedded packages.
```python
%%capture
import os
if "COLAB_" not in "".join(os.environ.keys()):
!pip install unsloth
else:
# Do this only in Colab notebooks! Otherwise use pip install unsloth
!pip install --no-deps bitsandbytes accelerate xformers==0.0.29.post3 peft trl==0.15.2 triton cut_cross_entropy unsloth_zoo
!pip install sentencepiece protobuf datasets huggingface_hub hf_transfer
!pip install --no-deps unsloth
!pip install snac
```
Download the models (both the SNAC encoder/decoder as well as our finetuned Hypa_Orpheus).
```python
import torch
from snac import SNAC
from unsloth import FastLanguageModel
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-merged_16bit",
max_seq_length= 2048, # Choose any for long context!
dtype = dtype,
load_in_4bit = load_in_4bit,
#token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
snac_model = snac_model.to("cuda")
```
Create your text prompt, select the voice, and pass through the Model.
```python
prompts = [
"""Mo nífẹ̀ẹ́sí láti ṣe Ph.D sùgbọ́n mi ò ì tíì pinnu ẹ̀ka tí màá ṣe. Àwọn anfaani tí óń dé oríṣiríṣi àwọn olùgbọ́ káàkiri àgbáyé wo ni mo ní""",
]
chosen_voice = "Eniola" # None for single-speaker
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
snac_model.to("cpu")# Moving snac_model cuda to cpu
prompts_ = [(f"{chosen_voice}: " + p) if chosen_voice else p for p in prompts]
all_input_ids = []
for prompt in prompts_:
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
all_input_ids.append(input_ids)
start_token = torch.tensor([[ 128259]], dtype=torch.int64) # Start of human
end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64) # End of text, End of human
all_modified_input_ids = []
for input_ids in all_input_ids:
modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1) # SOH SOT Text EOT EOH
all_modified_input_ids.append(modified_input_ids)
all_padded_tensors = []
all_attention_masks = []
max_length = max([modified_input_ids.shape[1] for modified_input_ids in all_modified_input_ids])
for modified_input_ids in all_modified_input_ids:
padding = max_length - modified_input_ids.shape[1]
padded_tensor = torch.cat([torch.full((1, padding), 128263, dtype=torch.int64), modified_input_ids], dim=1)
attention_mask = torch.cat([torch.zeros((1, padding), dtype=torch.int64), torch.ones((1, modified_input_ids.shape[1]), dtype=torch.int64)], dim=1)
all_padded_tensors.append(padded_tensor)
all_attention_masks.append(attention_mask)
all_padded_tensors = torch.cat(all_padded_tensors, dim=0)
all_attention_masks = torch.cat(all_attention_masks, dim=0)
input_ids = all_padded_tensors.to("cuda")
attention_mask = all_attention_masks.to("cuda")
generated_ids = model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
max_new_tokens=1200,
do_sample=True,
temperature=0.6,
top_p=0.95,
repetition_penalty=1.1,
num_return_sequences=1,
eos_token_id=128258,
use_cache = True
)
token_to_find = 128257
token_to_remove = 128258
token_indices = (generated_ids == token_to_find).nonzero(as_tuple=True)
if len(token_indices[1]) > 0:
last_occurrence_idx = token_indices[1][-1].item()
cropped_tensor = generated_ids[:, last_occurrence_idx+1:]
else:
cropped_tensor = generated_ids
mask = cropped_tensor != token_to_remove
processed_rows = []
for row in cropped_tensor:
masked_row = row[row != token_to_remove]
processed_rows.append(masked_row)
code_lists = []
for row in processed_rows:
row_length = row.size(0)
new_length = (row_length // 7) * 7
trimmed_row = row[:new_length]
trimmed_row = [t - 128266 for t in trimmed_row]
code_lists.append(trimmed_row)
def redistribute_codes(code_list):
layer_1 = []
layer_2 = []
layer_3 = []
for i in range((len(code_list)+1)//7):
layer_1.append(code_list[7*i])
layer_2.append(code_list[7*i+1]-4096)
layer_3.append(code_list[7*i+2]-(2*4096))
layer_3.append(code_list[7*i+3]-(3*4096))
layer_2.append(code_list[7*i+4]-(4*4096))
layer_3.append(code_list[7*i+5]-(5*4096))
layer_3.append(code_list[7*i+6]-(6*4096))
codes = [torch.tensor(layer_1).unsqueeze(0),
torch.tensor(layer_2).unsqueeze(0),
torch.tensor(layer_3).unsqueeze(0)]
# codes = [c.to("cuda") for c in codes]
audio_hat = snac_model.decode(codes)
return audio_hat
my_samples = []
for code_list in code_lists:
samples = redistribute_codes(code_list)
my_samples.append(samples)
from IPython.display import display, Audio
if len(prompts) != len(my_samples):
raise Exception("Number of prompts and samples do not match")
else:
for i in range(len(my_samples)):
print(prompts[i])
samples = my_samples[i]
display(Audio(samples.detach().squeeze().to("cpu").numpy(), rate=24000))
# Clean up to save RAM
del my_samples,samples
```
### Standard Inference
Download the nedded packages.
```python
%%capture
!pip install snac ipywebrtc
```
Download the Models (SNAC & Hypa_Orpheus)
```python
import torch
from transformers import AutoModelForCausalLM, Trainer, TrainingArguments, AutoTokenizer
from snac import SNAC
# Loads the pre-trained SNAC model and moves it to the CPU.
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
snac_model = snac_model #.to("cpu")
print("We have loaded the Encoder/Decoder model to the cpu, to use vram - use the gpu for faster inference")
# Loading the Orpheus Model and Tokenizer, moving the model to the GPU for faster inference
model_name = "hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-merged_16bit"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
model.cuda()
tokenizer = AutoTokenizer.from_pretrained(model_name)
```
Create Prompt(s) and Select Voice & Emotions as needed.
```python
# List of supported voices in Orpheus-TTS
voices = [
"Eniola", "tara", # Female, conversational, clear
"Moyo", "leah", # Female, warm, gentle
"Gift", "jess", # Female, energetic, youthful
"Prince", "leo", # Male, authoritative, deep
"Emmanuel", "dan", # Male, friendly, casual
"Cynthia", "mia", # Female, professional, articulate
"Kolade", "zac", # Male, enthusiastic, dynamic
"Lovelyn", "zoe" # Female, calm, soothing
]
# List of supported emotion tags in Orpheus-TTS
emotions = [
"<laugh>", # Laughter
"<chuckle>", # Soft chuckle
"<sigh>", # Sighing
"<cough>", # Coughing
"<sniffle>", # Sniffling
"<groan>", # Groaning
"<yawn>", # Yawning
"<gasp>" # Gasping
]
# Creating Prompts
prompts = [
"Hey there my name is Eniola 9000, and I'm a speech generation model that can sound like a person.",
# "I've also been taught to understand and produce paralinguistic things like sighing, or chuckling, or yawning!",
# "I live in San Francisco, and have, uhm let's see, 3 billion 7 hundred ... well, lets just say a lot of parameters.",
]
chosen_voice = "Eniola" # "tara" # see github for other voices
prompts = [f"{chosen_voice}: " + p for p in prompts] # Creating the prompts (as a batch)
print(prompts)
```
Tokenize prompt(s) into inputIDs, pad, and create attention masks.
```python
# Tokenizing each prompt into input IDs.
all_input_ids = []
for prompt in prompts:
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
all_input_ids.append(input_ids)
# Adds special tokens to mark the beginning and end of each prompt
start_token = torch.tensor([[128259]], dtype=torch.int64) # Start of human
end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64) # End of text, End of human
all_modified_input_ids = []
for input_ids in all_input_ids:
modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1) # SOH SOT Text EOT EOH
all_modified_input_ids.append(modified_input_ids)
# Padding All sequences to same length and creating corresponding attention masks
all_padded_tensors = []
all_attention_masks = []
max_length = max([modified_input_ids.shape[1] for modified_input_ids in all_modified_input_ids])
for modified_input_ids in all_modified_input_ids:
padding = max_length - modified_input_ids.shape[1]
# Left Padding
padded_tensor = torch.cat([torch.full((1, padding), 128263, dtype=torch.int64), modified_input_ids], dim=1)
attention_mask = torch.cat([torch.zeros((1, padding), dtype=torch.int64), torch.ones((1, modified_input_ids.shape[1]), dtype=torch.int64)], dim=1)
all_padded_tensors.append(padded_tensor)
all_attention_masks.append(attention_mask)
all_padded_tensors = torch.cat(all_padded_tensors, dim=0)
all_attention_masks = torch.cat(all_attention_masks, dim=0)
# Moving all padded sequences to GPU for Faster computation
input_ids = all_padded_tensors.to("cuda")
attention_mask = all_attention_masks.to("cuda")
```
Generate Output Tokens from the and Parse output tokens as speech
```python
print("*** Model.generate is slow - see vllm implementation on github for realtime streaming and inference")
print("*** Increase/decrease inference params for more expressive less stable generations")
# Generating Output Tokens
with torch.no_grad():
generated_ids = model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
max_new_tokens=1200,
do_sample=True,
temperature=0.6,
top_p=0.95,
repetition_penalty=1.1,
num_return_sequences=1,
eos_token_id=128258,
)
# Processing Generated Tokens (Parse Output as speech)
token_to_find = 128257 # Start of Audio token (relevant output)
token_to_remove = 128258 # End/ Terminal Token (End of Audio/ relevant output)
token_indices = (generated_ids == token_to_find).nonzero(as_tuple=True)
print(token_indices)
# Slices the tensor to exclude unwanted tokens.
if len(token_indices[1]) > 0:
last_occurrence_idx = token_indices[1][-1].item()
cropped_tensor = generated_ids[:, last_occurrence_idx+1:]
else:
cropped_tensor = generated_ids
# mask = cropped_tensor != token_to_remove
# Storing the cleaned-up token sequences#
processed_rows = []
for row in cropped_tensor:
masked_row = row[row != token_to_remove]
processed_rows.append(masked_row)
# Preparing (Audio Codes) the token sequences for audio decoding by trimming and adjusting token values.
code_lists = []
for row in processed_rows:
row_length = row.size(0) # Determines the length of the token sequence.
new_length = (row_length // 7) * 7 # Ensures the sequence length is a multiple of 7, as required by the decoder.
trimmed_row = row[:new_length]
trimmed_row = [t - 128266 for t in trimmed_row] # Adjusts token values to match the expected input range for the decoder.
code_lists.append(trimmed_row)
```
Decode Outputs with SNAC Decoder
```python
# Processes the token sequences into the format expected by the SNAC decoder:
def redistribute_codes(code_list):
""" Reorganizes the flattened token list into three separate layers, adjusting each token's value to align with the decoder's expectations"""
layer_1 = [] # Coarsest layer
layer_2 = [] # Intermediate layer
layer_3 = [] # Finest layer
num_groups = (len(code_list) + 1) // 7 #Calculate the number of complete 7-token groups in the code_list
for i in range(num_groups):
idx = 7 * i # starting index for the current group
# Layer 1 receives the first token of the group
layer_1.append(code_list[idx])
# Layer 2 receives the second token, adjusted by subtracting 4096
layer_2.append(code_list[idx + 1] - 4096)
# Layer 3 receives the third and fourth tokens, adjusted by subtracting 8192 and 12288 respectively
layer_3.append(code_list[idx+2]-(2*4096))
layer_3.append(code_list[idx+3]-(3*4096))
# Layer 2 receives the fifth token, adjusted by subtracting 16384
layer_2.append(code_list[idx+4]-(4*4096))
# Layer 3 receives the sixth and seventh tokens, adjusted by subtracting 20480 and 24576 respectively
layer_3.append(code_list[idx+5]-(5*4096))
layer_3.append(code_list[idx+6]-(6*4096))
codes = [
torch.tensor(layer_1).unsqueeze(0), # Shape: (1, len(layer_1))
torch.tensor(layer_2).unsqueeze(0), # Shape: (1, len(layer_2))
torch.tensor(layer_3).unsqueeze(0) # Shape: (1, len(layer_3))
] # Convert the lists to PyTorch tensors and add a batch dimension
audio_hat = snac_model.decode(codes) # Decode the structured codes into an audio waveform using the SNAC model
return audio_hat
my_samples = []
for code_list in code_lists:
samples = redistribute_codes(code_list) # Generates audio samples from the processed token sequences
my_samples.append(samples)
# Display Audio
from IPython.display import display, Audio
if len(prompts) != len(my_samples):
raise Exception("Number of prompts and samples do not match")
else:
for i in range(len(my_samples)):
print(prompts[i])
samples = my_samples[i]
display(Audio(samples.detach().squeeze().to("cpu").numpy(), rate=24000))
```
- **Repository:** [N/A]
- **Paper:** [N/A]
- **Demo:** [N/A]
This llama based model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
|