-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add VoiceClonePrompt.save()/load() for cross-session voice reuse #223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
zhu-han
merged 1 commit into
k2-fsa:master
from
HenryVarro666:voice-clone-prompt-save-load
Jul 15, 2026
+75
−2
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -113,12 +113,60 @@ def _autocast_flex_attention(module, query, key, value, *args, **kwargs): | |
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| _VOICE_CLONE_PROMPT_FORMAT_VERSION = 1 | ||
|
|
||
|
|
||
| @dataclass | ||
| class VoiceClonePrompt: | ||
| ref_audio_tokens: torch.Tensor # (C, T) | ||
| ref_text: str | ||
| ref_rms: float | ||
|
|
||
| def save(self, path: str) -> None: | ||
| """Save this prompt to ``path`` for reuse in a later session. | ||
|
|
||
| The file stores a plain dict with the audio tokens moved to CPU, so | ||
| it can be loaded with ``torch.load(weights_only=True)`` (the default | ||
| since torch 2.6) and is portable across devices. | ||
|
|
||
| Args: | ||
| path: Destination file path (e.g. ``"my_voice.pt"``). | ||
| """ | ||
| torch.save( | ||
| { | ||
| "format_version": _VOICE_CLONE_PROMPT_FORMAT_VERSION, | ||
| "ref_audio_tokens": self.ref_audio_tokens.detach().cpu(), | ||
| "ref_text": self.ref_text, | ||
| "ref_rms": float(self.ref_rms), | ||
| }, | ||
| path, | ||
| ) | ||
|
|
||
| @classmethod | ||
| def load(cls, path: str, map_location: str = "cpu") -> "VoiceClonePrompt": | ||
| """Load a prompt saved with :meth:`save`. | ||
|
|
||
| The returned prompt can be passed directly to | ||
| :meth:`OmniVoice.generate`; the audio tokens are moved to the model | ||
| device automatically during generation, so no manual ``.to(device)`` | ||
| is needed. | ||
|
|
||
| Args: | ||
| path: File path previously written by :meth:`save`. | ||
| map_location: Device to load the audio tokens onto. | ||
| Returns: | ||
| The restored :class:`VoiceClonePrompt`. | ||
| """ | ||
| data = torch.load(path, map_location=map_location, weights_only=True) | ||
| version = data.get("format_version") | ||
| if version != _VOICE_CLONE_PROMPT_FORMAT_VERSION: | ||
| raise ValueError(f"Unsupported VoiceClonePrompt format version: {version}") | ||
| return cls( | ||
| ref_audio_tokens=data["ref_audio_tokens"], | ||
| ref_text=data["ref_text"], | ||
| ref_rms=data["ref_rms"], | ||
| ) | ||
|
Comment on lines
+146
to
+168
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To make the
@classmethod
def load(
cls,
path: Union[str, os.PathLike],
map_location: Optional[Union[str, torch.device]] = "cpu",
) -> "VoiceClonePrompt":
"""Load a prompt saved with :meth:`save`.
The returned prompt can be passed directly to
:meth:`OmniVoice.generate`; the audio tokens are moved to the model
device automatically during generation, so no manual ``.to(device)``
is needed.
Args:
path: File path previously written by :meth:`save`.
map_location: Device to load the audio tokens onto.
Returns:
The restored :class:`VoiceClonePrompt`.
"""
data = torch.load(path, map_location=map_location, weights_only=True)
if not isinstance(data, dict):
raise ValueError(
f"Invalid VoiceClonePrompt file: expected a dictionary, got {type(data).__name__}"
)
version = data.get("format_version")
if version != _VOICE_CLONE_PROMPT_FORMAT_VERSION:
raise ValueError(f"Unsupported VoiceClonePrompt format version: {version}")
for key in ("ref_audio_tokens", "ref_text", "ref_rms"):
if key not in data:
raise ValueError(f"Invalid VoiceClonePrompt file: missing required key '{key}'")
return cls(
ref_audio_tokens=data["ref_audio_tokens"],
ref_text=data["ref_text"],
ref_rms=data["ref_rms"],
) |
||
|
|
||
|
|
||
| @dataclass | ||
| class OmniVoiceGenerationConfig: | ||
|
|
@@ -555,7 +603,8 @@ def generate( | |
| ref_text: Optional reference text for voice cloning mode. | ||
| ref_audio: Optional reference audio for voice cloning mode. | ||
| Can be a file path or a (waveform, sample_rate) tuple. | ||
| voice_clone_prompt: Reusable prompt from :meth:`create_voice_clone_prompt`. | ||
| voice_clone_prompt: Reusable prompt from :meth:`create_voice_clone_prompt` | ||
| or :meth:`VoiceClonePrompt.load`. | ||
| If provided, it overrides ``ref_text`` and ``ref_audio``. | ||
| instruct: Style instruction for voice design mode. | ||
| duration: Fixed output duration in seconds. If a single float, | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To improve usability and compatibility with standard Python path handling (such as
pathlib.Path), consider updating thepathparameter type hint to acceptUnion[str, os.PathLike]instead of juststr.