Managing AI model memory involves strategies to efficiently handle both short-term and long-term data storage and retrieval for AI models, particularly large language models (LLMs). This includes techniques like breaking down tasks into smaller prompts, using vector databases for long-term memory, and implementing mechanisms to prevent memory bloat.
Here's a breakdown of key strategies:
Understanding Memory Needs:
Short-term memory:
.
LLMs have a limited context window (number of tokens) for recent interactions. Strategies are needed to manage this efficiently.
Long-term memory:
.
Storing and retrieving past interactions, user preferences, and other relevant information is crucial for personalization and continuity.
Short-Term Memory Management:
Prompt Engineering:
Design prompts to be concise and avoid redundancy.
Chunking:
Break down large tasks into smaller, manageable prompts that fit within the context window.
Summarization:
Use summarization techniques to condense past conversations and reduce the amount of information stored in the short-term memory.
Memory Trimming:
Remove less relevant or older messages from the conversation history to stay within the context window.
Long-Term Memory Management:
Vector Databases:
.
Store embeddings (numerical representations of text) of past interactions in vector databases. This allows for similarity searches to retrieve relevant information for new queries.
Memory Storage:
.
Implement mechanisms to store and retrieve key information from past interactions, avoid duplication, and update/append new information.
Data Governance:
.
Establish policies for data collection, storage, usage, and access to ensure data quality and privacy.
Memory Decay:
.
Implement mechanisms to remove outdated or less frequently accessed information to prevent memory bloat.
Tools and Frameworks:
LangChain:
.
A framework that simplifies building memory-enabled AI agents by integrating memory, APIs, and reasoning workflows.
LangGraph:
.
Provides tools like Checkpointers for maintaining thread-specific context in short-term memory.
Redis:
.
A fast, in-memory data structure store that can be used to manage memory for AI agents.
Other Considerations:
Model Size:
If memory limitations are a significant issue, consider using a larger and more capable AI model.
Training Data:
Retraining models on better data can improve their ability to handle information and context.
Regular Testing:
Continuously monitor and test the performance of memory management strategies to ensure optimal efficiency.
Privacy:
Be mindful of data privacy regulations and implement appropriate measures to protect user information.
By implementing these strategies, you can effectively manage AI model memory, enabling more efficient, personalized, and context-aware interactions.
'the task'
please fix memory management in my script for the ai models it's loading, I want it to keep the model in memory until the application is exited but the current script keeps making my PC bluescreen. Please adjust the script and return the entire script fixed ty.
Assistant
User
Assistant
'the script'
import os
import tempfile
import torch
import traceback
import time
import gradio as gr
from huggingface_hub import snapshot_download
from models.vc.vevo.vevo_utils import VevoInferencePipeline, save_audio
====== Setup device ======
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
====== Download & prepare model checkpoints ======
def careful_join(*parts):
# Safe path join AND normalize slashes for WSL / Windows compat
return os.path.normpath(os.path.join(*parts))
print("[INFO] Initializing VevoInferencePipeline (this may take a while)...")
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
print("[INFO] Model ready!")
def vevo_tts(
src_text: str,
ref_wav_path: str,
ref_text: str = None,
src_language: str = "en",
ref_language: str = "en",
):
"""
Run the Vevo TTS model inference.
Returns the path to the generated wav audio and a status message.
"""
code
# Input validation
if not src_text or src_text.strip() == "":
return None, "Error: Source text is empty. Please enter text to synthesize."
if not ref_wav_path or ref_wav_path.strip() == "":
return None, "Error: Reference wav file is missing. Please upload a style reference wav audio file."
if not src_language or src_language.strip() == "":
return None, "Error: Source language code is empty. Please select source language."
ref_wav_path = os.path.normpath(ref_wav_path)
timbre_ref_wav_path = ref_wav_path
if torch.cuda.is_available():
torch.cuda.empty_cache()
fd_out, output_path = tempfile.mkstemp(suffix=".wav", prefix="vevo_tts_out_")
os.close(fd_out)
try:
inf_args = dict(
src_wav_path=None,
src_text=src_text,
style_ref_wav_path=ref_wav_path,
timbre_ref_wav_path=timbre_ref_wav_path,
src_text_language=src_language,
)
if ref_text and ref_text.strip() != "":
inf_args["style_ref_wav_text"] = ref_text
inf_args["style_ref_wav_text_language"] = ref_language if ref_language.strip() else "en"
gen_audio = inference_pipeline.inference_ar_and_fm(**inf_args)
print(f"[DEBUG] Generated audio shape: {gen_audio.shape}, dtype={gen_audio.dtype}")
# Pass tensor directly (detached, on cpu) to save_audio
gen_audio_tensor = gen_audio.cpu().detach().clone()
save_audio(gen_audio_tensor, output_path=output_path)
time.sleep(0.1)
return output_path, "✅ Inference complete!"
except Exception as e:
if os.path.exists(output_path):
try:
os.remove(output_path)
except:
pass
tb = traceback.format_exc()
err_msg = f"❌ Exception during inference:\n{str(e)}\n\nTraceback:\n{tb}"
return None, err_msg
====== Gradio UI ======
language_options = [
("English", "en"),
("Chinese", "zh"),
("Japanese", "ja"),
("Korean", "ko"),
# Add more languages if supported
]
with gr.Blocks() as demo:
gr.Markdown(
"""
# Vevo Zero-Shot TTS Demo
Upload a style reference wav audio and enter the text you want to synthesize.
"""
)
code
with gr.Row():
with gr.Column():
ref_wav_input = gr.Audio(
label="Style Reference Audio (wav)", type="filepath", interactive=True
)
src_text_input = gr.Textbox(
value="I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.",
lines=6,
label="Source Text (to synthesize)",
interactive=True,
)
ref_text_input = gr.Textbox(
value="Flip stood undecided, his ears strained to catch the slightest sound.",
lines=2,
label="Reference Text (optional)",
interactive=True,
)
src_language_input = gr.Dropdown(
choices=language_options,
value="en",
label="Source Text Language",
interactive=True,
)
ref_language_input = gr.Dropdown(
choices=language_options,
value="en",
label="Reference Text Language",
interactive=True,
)
run_button = gr.Button("Run Inference")
with gr.Column():
output_audio = gr.Audio(label="Generated Speech", type="filepath")
status = gr.Textbox(label="Status / Logs", interactive=False)
def run_inference_wrapper(ref_wav_path, src_text, ref_text, src_lang, ref_lang):
return vevo_tts(
src_text=src_text,
ref_wav_path=ref_wav_path,
ref_text=ref_text,
src_language=src_lang,
ref_language=ref_lang,
)
run_button.click(
run_inference_wrapper,
inputs=[ref_wav_input, src_text_input, ref_text_input, src_language_input, ref_language_input],
outputs=[output_audio, status],
)
if name == "main":
demo.launch(server_name="0.0.0.0", server_port=7860)
The main issue causing your PC to bluescreen is most likely related to how the model and GPU memory are handled in the script. The script currently loads the model once at startup into memory with the inference_pipeline global variable, which is the right approach to keep the model resident and not reload it repeatedly.
However, a few risks could cause resource exhaustion or GPU memory issues leading to system instability:
The script empties the CUDA cache on every inference call (torch.cuda.empty_cache() inside vevo_tts) which can cause unnecessary GPU memory fragmentation or conflicts.
Each inference might allocate big intermediate tensors — if they aren't properly released, memory might balloon over time.
Temporary files aren’t always cleaned up correctly on exceptions or errors.
The application does not restrict max GPU memory usage or disable excessive threading, which can impact system stability.
Possible issues with device switching or non-optimal tensor management.
How to fix and improve the script regarding memory management:
Load the model only once at startup and keep it in memory: The current script already does this.
Remove the torch.cuda.empty_cache() call inside the inference function — this call is seldom necessary and can cause instability in some environments.
Explicitly set the model and related tensors to device once and ensure no copying between CPU/GPU unless necessary. The existing inference_pipeline appears to take a device param.
Make sure temporary files are created and cleaned correctly (you mostly do this, but can improve cleanup on exceptions).
Add explicit garbage collection after inference to ensure any detached GPU tensors are collected.
Avoid using .clone() unnecessarily on large tensors.
Optionally restrict PyTorch threads to avoid possible CPU overloads.
Adjusted and annotated script sections below:
python
import os
import tempfile
import torch
import traceback
import time
import gc # Add garbage collector
import gradio as gr
from huggingface_hub import snapshot_download
from models.vc.vevo.vevo_utils import VevoInferencePipeline, save_audio
# ====== Setup device ======
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
print(f"[INFO] Using device: {device}")
# Optional: Limit number of threads (avoid CPU overload causing system instability)
torch.set_num_threads(2)
# ====== Download & prepare model checkpoints ======
def careful_join(*parts):
# Safe path join AND normalize slashes for WSL / Windows compat
return os.path.normpath(os.path.join(*parts))
print("[INFO] Downloading content/style tokenizer...")
tokenizer_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["tokenizer/vq8192/*"],
)
content_style_tokenizer_ckpt_path = careful_join(tokenizer_dir, "tokenizer/vq8192")
print("[INFO] Downloading autoregressive transformer...")
ar_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
)
ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
ar_ckpt_path = careful_join(ar_dir, "contentstyle_modeling/PhoneToVq8192")
print("[INFO] Downloading flow matching transformer...")
fmt_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
)
fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
fmt_ckpt_path = careful_join(fmt_dir, "acoustic_modeling/Vq8192ToMels")
print("[INFO] Downloading vocoder...")
vocoder_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vocoder/*"],
)
vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
vocoder_ckpt_path = careful_join(vocoder_dir, "acoustic_modeling/Vocoder")
print("[INFO] Initializing VevoInferencePipeline (this may take a while)...")
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
print("[INFO] Model ready and loaded in memory!")
def vevo_tts(
src_text: str,
ref_wav_path: str,
ref_text: str = None,
src_language: str = "en",
ref_language: str = "en",
):
"""
Run the Vevo TTS model inference.
Returns the path to the generated wav audio and a status message.
"""
# Input validation
if not src_text or src_text.strip() == "":
return None, "Error: Source text is empty. Please enter text to synthesize."
if not ref_wav_path or ref_wav_path.strip() == "":
return None, "Error: Reference wav file is missing. Please upload a style reference wav audio file."
if not src_language or src_language.strip() == "":
return None, "Error: Source language code is empty. Please select source language."
ref_wav_path = os.path.normpath(ref_wav_path)
timbre_ref_wav_path = ref_wav_path
# Removed torch.cuda.empty_cache() - not needed and can cause instability.
fd_out, output_path = tempfile.mkstemp(suffix=".wav", prefix="vevo_tts_out_")
os.close(fd_out)
try:
inf_args = dict(
src_wav_path=None,
src_text=src_text,
style_ref_wav_path=ref_wav_path,
timbre_ref_wav_path=timbre_ref_wav_path,
src_text_language=src_language,
)
if ref_text and ref_text.strip() != "":
inf_args["style_ref_wav_text"] = ref_text
inf_args["style_ref_wav_text_language"] = ref_language if ref_language.strip() else "en"
gen_audio = inference_pipeline.inference_ar_and_fm(**inf_args)
print(f"[DEBUG] Generated audio shape: {gen_audio.shape}, dtype={gen_audio.dtype}")
# Transfer tensor to CPU and no clone (clone is redundant)
gen_audio_cpu = gen_audio.cpu().detach()
save_audio(gen_audio_cpu, output_path=output_path)
# Explicitly delete tensors and run GC to free memory immediately
del gen_audio
del gen_audio_cpu
gc.collect()
if torch.cuda.is_available():
torch.cuda.synchronize()
# Optional minor cache cleanup but avoid full empty_cache calls
torch.cuda.ipc_collect()
time.sleep(0.1)
return output_path, "✅ Inference complete!"
except Exception as e:
if os.path.exists(output_path):
try:
os.remove(output_path)
except Exception:
pass
tb = traceback.format_exc()
err_msg = f"❌ Exception during inference:\n{str(e)}\n\nTraceback:\n{tb}"
return None, err_msg
# ====== Gradio UI ======
language_options = [
("English", "en"),
("Chinese", "zh"),
("Japanese", "ja"),
("Korean", "ko"),
# Add more languages if supported
]
with gr.Blocks() as demo:
gr.Markdown(
"""
# Vevo Zero-Shot TTS Demo
Upload a **style reference wav audio** and enter the **text** you want to synthesize.
"""
)
with gr.Row():
with gr.Column():
ref_wav_input = gr.Audio(
label="Style Reference Audio (wav)", type="filepath", interactive=True
)
src_text_input = gr.Textbox(
value="I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.",
lines=6,
label="Source Text (to synthesize)",
interactive=True,
)
ref_text_input = gr.Textbox(
value="Flip stood undecided, his ears strained to catch the slightest sound.",
lines=2,
label="Reference Text (optional)",
interactive=True,
)
src_language_input = gr.Dropdown(
choices=language_options,
value="en",
label="Source Text Language",
interactive=True,
)
ref_language_input = gr.Dropdown(
choices=language_options,
value="en",
label="Reference Text Language",
interactive=True,
)
run_button = gr.Button("Run Inference")
with gr.Column():
output_audio = gr.Audio(label="Generated Speech", type="filepath")
status = gr.Textbox(label="Status / Logs", interactive=False)
def run_inference_wrapper(ref_wav_path, src_text, ref_text, src_lang, ref_lang):
return vevo_tts(
src_text=src_text,
ref_wav_path=ref_wav_path,
ref_text=ref_text,
src_language=src_lang,
ref_language=ref_lang,
)
run_button.click(
run_inference_wrapper,
inputs=[ref_wav_input, src_text_input, ref_text_input, src_language_input, ref_language_input],
outputs=[output_audio, status],
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)
Summary of key fixes:
Removed torch.cuda.empty_cache() from each inference call. This call is usually unnecessary, might fragment CUDA memory, and can cause problems if overused.
Added explicit gc.collect() and CUDA synchronization after inference to clear intermediate tensors promptly.
Restricted PyTorch CPU threads to 2 to prevent CPU overload, which can cause blue screens on some systems.
Avoided unnecessary .clone() of the generated audio tensor, which also allocates memory.
Cleanup for temp files remains, improved error handling slightly.
Additional tips to prevent system blue screens:
Update GPU drivers and CUDA toolkit to latest stable versions.
Monitor GPU temperature and usage to ensure no overheating.
Run your script in isolated environments (e.g., Docker/VM) to narrow down hardware/software issues.
If you still face issues, try running with CPU only (device = torch.device("cpu")) to test stability.
If the problem persists after these adjustments, it's likely related to your system setup or driver issues, not the script itself. The above changes optimize GPU memory management inside the script and are the standard best practice.
the script keeps generating very short wav files like there's something wrong with the script, I'm going to send back the original script and I'll let you decide what's missing maybe we're forgetting something? either way if you change something return the entire script fixed tysm.
Copyright (c) 2023 Amphion.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
import os
from huggingface_hub import snapshot_download
from models.vc.vevo.vevo_utils import *
def vevo_tts(
src_text,
ref_wav_path,
timbre_ref_wav_path=None,
output_path=None,
ref_text=None,
src_language="en",
ref_language="en",
):
if timbre_ref_wav_path is None:
timbre_ref_wav_path = ref_wav_path
code
gen_audio = inference_pipeline.inference_ar_and_fm(
src_wav_path=None,
src_text=src_text,
style_ref_wav_path=ref_wav_path,
timbre_ref_wav_path=timbre_ref_wav_path,
style_ref_wav_text=ref_text,
src_text_language=src_language,
style_ref_wav_text_language=ref_language,
)
assert output_path is not None
save_audio(gen_audio, output_path=output_path)
if name == "main":
# ===== Device =====
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
code
# ===== Content-Style Tokenizer =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["tokenizer/vq8192/*"],
)
content_style_tokenizer_ckpt_path = os.path.join(local_dir, "tokenizer/vq8192")
# ===== Autoregressive Transformer =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
)
ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
ar_ckpt_path = os.path.join(local_dir, "contentstyle_modeling/PhoneToVq8192")
# ===== Flow Matching Transformer =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
)
fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
fmt_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vq8192ToMels")
# ===== Vocoder =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vocoder/*"],
)
vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
vocoder_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vocoder")
# ===== Inference =====
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
src_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences."
ref_wav_path = "./models/vc/vevo/wav/arabic_male.wav"
ref_text = "Flip stood undecided, his ears strained to catch the slightest sound."
# 1. Zero-Shot TTS (the style reference and timbre reference are same)
vevo_tts(
src_text,
ref_wav_path,
output_path="./models/vc/vevo/wav/output_vevotts1.wav",
ref_text=ref_text,
src_language="en",
ref_language="en",
)
# 2. Style and Timbre Controllable Zero-Shot TTS (the style reference and timbre reference are different)
vevo_tts(
src_text,
ref_wav_path,
timbre_ref_wav_path="./models/vc/vevo/wav/mandarin_female.wav",
output_path="./models/vc/vevo/wav/output_vevotts2.wav",
ref_text=ref_text,
src_language="en",
ref_language="en",
)
Thank you for sharing the original script.
Diagnosis
The original script snippet you provided is the minimal working example from the official repo that runs inference using VevoInferencePipeline.inference_ar_and_fm and saves the generated audio. This script assumes you have initialized inference_pipeline properly before calling vevo_tts.
Your previous script uses a Gradio UI and a similar approach but you mentioned it produces very short wav output. This usually happens when:
The input text isn't properly passed.
The reference audio is invalid or incompatible.
The pipeline is not fully or correctly initialized.
The inference step is cut short by an error or missing step inside the pipeline.
There's a mismatch in input parameters, or the loaded models/configs are corrupted.
What might be missing or causing the issue?
inference_pipeline initialization scope
You must ensure the inference_pipeline is constructed once at startup and fully ready before any inference calls.
Input parameter defaults
In your first script (with Gradio), the function vevo_tts has some added logic (e.g., force timbre_ref_wav_path = ref_wav_path if None). The original vevo_tts relies on the caller to ensure timbre_ref_wav_path is assigned correctly. Not passing it correctly may affect model behavior.
inference_ar_and_fm input parameter keys and values
According to the original script, these parameters should be passed exactly as the original, including possible None for src_wav_path if not used.
Saving audio
Make sure save_audio() works correctly and saves the full generated waveform.
File paths and audio formats
Reference wavs must be compatible (correct sample rate, channels, format).
In your original full script, there is an optional ref_text parameter passed both if exists or not. This can affect the output.
What I suggest based on your snippets:
Strictly follow the original function signature and usage.
Confirm the inference_pipeline is instantiated at a global scope once, as you already do.
Make sure you set timbre_ref_wav_path=ref_wav_path inside your function if None.
Pass the parameters to inference_ar_and_fm exactly, including possibly missing style_ref_wav_text or language keys only if non-empty.
Check the model configuration paths and ensure they match the ones used in the repo.
Remove unnecessary calls like torch.cuda.empty_cache() to avoid side effects.
Add error logging if inference returns very short tensors or empty outputs.
Here is a full fixed script combining your UI and original structure, with careful parameter passing and fixes:
python
Key potential improvements / fixes in this version:
Added timbre_ref_wav_path logic defaulting to ref_wav_path inside vevo_tts.
Ensured optional text and language keys are only passed when non-empty.
Added validation that the returned tensor is not empty.
Removed unnecessary tensor .clone() for memory efficiency.
Added explicit garbage collection + CUDA sync after each inference to keep memory stable.
Confirmed model initialized once at script start and reused for all inferences.
Kept torch.set_num_threads(2) to limit CPU load.
Added detailed error logging on exceptions.
Additional tips to debug the short wav problem:
Check your reference wav files (ref_wav_path) — they must be valid 16kHz or recommended sample rate and mono/stereo as expected by the model.
Try running the original minimal CLI example (without Gradio UI) to confirm your environment and models are correctly set up.
Check the length of the output tensor with print(gen_audio.shape) before saving.
Inspect audio with any WAV player or Python's scipy.io.wavfile.read to confirm duration.
If outputs are short, test different input texts, and make sure the text isn't empty or too short.
If still short outputs persist, it might be an issue with the trained models or your inputs, so testing with official examples and pretrained files from the repo is recommended.
Let me know if you want me to help you test or construct a minimal CLI-only example!
Not yet included in a published release.
import os
import tempfile
import torch
import traceback
import time
import gc
import gradio as gr
from huggingface_hub import snapshot_download
from models.vc.vevo.vevo_utils import VevoInferencePipeline, save_audio
# ====== Setup device ======
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
print(f"[INFO] Using device: {device}")
# Limit CPU threads to avoid resource exhaustion issues
torch.set_num_threads(2)
def careful_join(*parts):
return os.path.normpath(os.path.join(*parts))
# ====== Download & prepare model checkpoints ======
print("[INFO] Downloading content/style tokenizer...")
tokenizer_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["tokenizer/vq8192/*"],
)
content_style_tokenizer_ckpt_path = careful_join(tokenizer_dir, "tokenizer/vq8192")
print("[INFO] Downloading autoregressive transformer...")
ar_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
)
ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
ar_ckpt_path = careful_join(ar_dir, "contentstyle_modeling/PhoneToVq8192")
print("[INFO] Downloading flow matching transformer...")
fmt_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
)
fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
fmt_ckpt_path = careful_join(fmt_dir, "acoustic_modeling/Vq8192ToMels")
print("[INFO] Downloading vocoder...")
vocoder_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vocoder/*"],
)
vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
vocoder_ckpt_path = careful_join(vocoder_dir, "acoustic_modeling/Vocoder")
print("[INFO] Initializing VevoInferencePipeline (this may take a while)...")
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
print("[INFO] Model ready and loaded in memory!")
def vevo_tts(
src_text: str,
ref_wav_path: str,
ref_text: str = None,
src_language: str = "en",
ref_language: str = "en",
timbre_ref_wav_path: str = None,
):
"""
Run the Vevo TTS model inference.
Returns audio filepath and status message.
"""
if not src_text or src_text.strip() == "":
return None, "Error: Source text is empty. Please enter text to synthesize."
if not ref_wav_path or ref_wav_path.strip() == "":
return None, "Error: Reference wav file is missing. Please upload a style reference wav audio file."
if not src_language or src_language.strip() == "":
return None, "Error: Source language code is empty. Please select source language."
# Default timbre_ref_wav_path to ref_wav_path if None
if timbre_ref_wav_path is None:
timbre_ref_wav_path = ref_wav_path
ref_wav_path = os.path.normpath(ref_wav_path)
timbre_ref_wav_path = os.path.normpath(timbre_ref_wav_path)
fd_out, output_path = tempfile.mkstemp(suffix=".wav", prefix="vevo_tts_out_")
os.close(fd_out)
try:
inf_args = dict(
src_wav_path=None, # usually None for text input
src_text=src_text,
style_ref_wav_path=ref_wav_path,
timbre_ref_wav_path=timbre_ref_wav_path,
src_text_language=src_language,
)
# Conditionally add optional keys only if provided
if ref_text and ref_text.strip():
inf_args["style_ref_wav_text"] = ref_text
inf_args["style_ref_wav_text_language"] = ref_language if ref_language.strip() else "en"
gen_audio = inference_pipeline.inference_ar_and_fm(**inf_args)
if gen_audio is None or gen_audio.numel() == 0:
return None, "Error: Model returned empty audio output."
# Move tensor to CPU safely - avoid unnecessary clone which uses memory
gen_audio_cpu = gen_audio.cpu().detach()
save_audio(gen_audio_cpu, output_path=output_path)
del gen_audio, gen_audio_cpu
gc.collect()
if torch.cuda.is_available():
torch.cuda.synchronize()
torch.cuda.ipc_collect()
# Small sleep to ensure file system sync
time.sleep(0.1)
return output_path, "✅ Inference complete!"
except Exception as e:
# Cleanup temp file if any error occurred
if os.path.exists(output_path):
try:
os.remove(output_path)
except Exception:
pass
tb = traceback.format_exc()
err_msg = f"❌ Exception during inference:\n{str(e)}\n\nTraceback:\n{tb}"
return None, err_msg
# ====== Gradio UI ======
language_options = [
("English", "en"),
("Chinese", "zh"),
("Japanese", "ja"),
("Korean", "ko"),
# Add other languages if supported
]
with gr.Blocks() as demo:
gr.Markdown(
"""
# Vevo Zero-Shot TTS Demo
Upload a **style reference wav audio** and enter the **text** you want to synthesize.
"""
)
with gr.Row():
with gr.Column():
ref_wav_input = gr.Audio(
label="Style Reference Audio (wav)", type="filepath", interactive=True
)
src_text_input = gr.Textbox(
value="I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.",
lines=6,
label="Source Text (to synthesize)",
interactive=True,
)
ref_text_input = gr.Textbox(
value="Flip stood undecided, his ears strained to catch the slightest sound.",
lines=2,
label="Reference Text (optional)",
interactive=True,
)
src_language_input = gr.Dropdown(
choices=language_options,
value="en",
label="Source Text Language",
interactive=True,
)
ref_language_input = gr.Dropdown(
choices=language_options,
value="en",
label="Reference Text Language",
interactive=True,
)
run_button = gr.Button("Run Inference")
with gr.Column():
output_audio = gr.Audio(label="Generated Speech", type="filepath")
status = gr.Textbox(label="Status / Logs", interactive=False)
def run_inference_wrapper(ref_wav_path, src_text, ref_text, src_lang, ref_lang):
# Call vevo_tts with correct parameters
return vevo_tts(
src_text=src_text,
ref_wav_path=ref_wav_path,
ref_text=ref_text,
src_language=src_lang,
ref_language=ref_lang,
timbre_ref_wav_path=None, # let vevo_tts default this to ref_wav_path
)
run_button.click(
run_inference_wrapper,
inputs=[ref_wav_input, src_text_input, ref_text_input, src_language_input, ref_language_input],
outputs=[output_audio, status],
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)