File size: 6,521 Bytes
fe9c851 | 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 | import torch
import argparse
import time
import math
import warnings
from pathlib import Path
from config import (
AUDIO_OFFSET, NUM_AUDIO_TOKENS, END_OF_SPEECH_TOKEN_ID,
START_OF_SPEECH_TOKEN_ID, CODEC_SAMPLE_RATE, CODEC_FRAME_RATE,
)
from tokenizer import TTSTokenizer
MAX_INPUT_TOKENS = 180
def _split_text(text, tokenizer, max_len=MAX_INPUT_TOKENS):
"""Pack whole sentences; split words only when one sentence exceeds the cap.
The limit includes the two encoder boundary tokens.
"""
import re
if max_len < 3:
raise ValueError('max_len must leave room for text and two boundary tokens.')
max_len = min(max_len, MAX_INPUT_TOKENS)
text = tokenizer.normalize_text(text)
sentences = re.split(r'(?<=[.!?])\s+', text)
chunks = []
current = ""
for sent in sentences:
candidate = (current + " " + sent).strip() if current else sent
enc_len = len(tokenizer.build_encoder_input(candidate))
if enc_len <= max_len:
current = candidate
else:
if current:
chunks.append(current)
# If single sentence is too long, split by words
if len(tokenizer.build_encoder_input(sent)) > max_len:
words = sent.split()
current = ""
for w in words:
cand = (current + " " + w).strip() if current else w
if len(tokenizer.build_encoder_input(cand)) <= max_len:
current = cand
else:
if current:
chunks.append(current)
# A URL or unspaced word can exceed the encoder limit too.
current = ''
for ch in w:
if len(tokenizer.build_encoder_input(current + ch)) > max_len:
chunks.append(current)
current = ch
else:
current += ch
else:
current = sent
if current:
chunks.append(current)
return chunks
def _apply_repetition_penalty(logits, token_ids, penalty):
"""Reduce repeated-token scores regardless of the logit's sign."""
if penalty != 1.0 and token_ids:
indices = sorted(set(token_ids[-100:]))
scores = logits[:, indices]
logits[:, indices] = torch.where(scores < 0, scores * penalty, scores / penalty)
return logits
@torch.no_grad()
def generate(model, tokenizer, text,
max_new_tokens=512, temperature=0.7, top_k=250,
top_p=0.95, rep_penalty=1.1, device="cuda"):
"""
Generate audio tokens from text.
Args:
model: TTSEncoderDecoder
tokenizer: TTSTokenizer
text: input text string
max_new_tokens: max decoder steps
temperature: sampling temperature
top_k: top-k filtering
top_p: nucleus sampling threshold
rep_penalty: repetition penalty on recent tokens
device: cuda/cpu
Returns:
torch.Tensor of MioCodec codes [num_frames], or None
"""
if not math.isfinite(temperature) or temperature <= 0:
raise ValueError('temperature must be finite and positive.')
if not 0 < top_p <= 1 or not math.isfinite(rep_penalty) or rep_penalty <= 0:
raise ValueError('top_p must be in (0, 1] and rep_penalty must be positive.')
if not isinstance(top_k, int) or top_k < 0 or not isinstance(max_new_tokens, int) or max_new_tokens < 1:
raise ValueError('top_k must be a non-negative integer and max_new_tokens a positive integer.')
if not tokenizer.encode_text(text):
raise ValueError('Text contains no supported characters.')
# 1. Encode text (one shot, bidirectional)
enc_ids = tokenizer.build_encoder_input(text).unsqueeze(0).to(device)
if enc_ids.shape[1] > min(MAX_INPUT_TOKENS, model.config.max_text_len):
raise ValueError('Text exceeds the input token limit; split it with _split_text first.')
enc_mask = torch.ones_like(enc_ids)
enc_out = model.encode(enc_ids, enc_mask) # [1, T_enc, d_model]
# 3. Start decoder with <sos>
dec_ids = torch.tensor([[START_OF_SPEECH_TOKEN_ID]], device=device)
past = None
generated_tokens = []
for step in range(max_new_tokens):
inp = dec_ids[:, -1:] if past is not None else dec_ids
dec_out = model.decoder(
input_ids=inp,
encoder_output=enc_out,
encoder_mask=enc_mask,
past_key_values=past,
use_cache=True,
)
past = dec_out["past_key_values"]
logits = dec_out["logits"][:, -1, :]
# Mask: only allow audio tokens + end_of_speech
mask = torch.full_like(logits, float("-inf"))
mask[:, AUDIO_OFFSET:AUDIO_OFFSET + NUM_AUDIO_TOKENS] = 0
mask[:, END_OF_SPEECH_TOKEN_ID] = 0
logits = logits + mask
# Repetition penalty on recent tokens
_apply_repetition_penalty(logits, generated_tokens, rep_penalty)
logits = logits / temperature
# Top-k
if top_k > 0:
kth = torch.topk(logits, min(top_k, logits.shape[-1])).values[:, -1:]
logits[logits < kth] = float("-inf")
# Top-p (nucleus)
if top_p < 1.0:
sorted_l, sorted_i = torch.sort(logits, descending=True)
cum = torch.cumsum(torch.softmax(sorted_l, -1), -1)
remove = cum > top_p
remove[:, 1:] = remove[:, :-1].clone()
remove[:, 0] = False
logits[remove.scatter(1, sorted_i, remove)] = float("-inf")
next_tok = torch.multinomial(torch.softmax(logits, -1), 1)
tok_id = next_tok.item()
if tok_id == END_OF_SPEECH_TOKEN_ID:
break
generated_tokens.append(tok_id)
dec_ids = torch.cat([dec_ids, next_tok], dim=-1)
else:
warnings.warn('Reached max_new_tokens before end of speech; audio may be truncated. Use shorter text chunks.', RuntimeWarning)
if not generated_tokens:
return None
result = torch.tensor(generated_tokens, dtype=torch.long)
audio_mask = (result >= AUDIO_OFFSET) & (result < AUDIO_OFFSET + NUM_AUDIO_TOKENS)
return result[audio_mask] - AUDIO_OFFSET
|