Download inference.py from beleata74/BgTTS-40M-Engram-Loop: direct link, hf CLI and curl.
- Browser
- Download file 6.52 kB
-
https://huggingface.co/beleata74/BgTTS-40M-Engram-Loop/resolve/main/inference.py
- Command line
-
hf download hf://beleata74/BgTTS-40M-Engram-Loop/inference.py
-
curl -L -o inference.py https://huggingface.co/beleata74/BgTTS-40M-Engram-Loop/resolve/main/inference.py
6.52 kB
| 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 | |
| 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 | |