Spaces:
Running
on
L4
Running
on
L4
Upload folder using huggingface_hub
Browse files
fish_speech/inference_engine/reference_loader.py
CHANGED
|
@@ -95,11 +95,13 @@ class ReferenceLoader:
|
|
| 95 |
)
|
| 96 |
)
|
| 97 |
prompt_texts.append(ref.text)
|
| 98 |
-
self.ref_by_hash[audio_hashes[i]] = (prompt_tokens,
|
| 99 |
|
| 100 |
else:
|
| 101 |
# Reuse already encoded references
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
cache_used = True
|
| 104 |
|
| 105 |
if cache_used:
|
|
|
|
| 95 |
)
|
| 96 |
)
|
| 97 |
prompt_texts.append(ref.text)
|
| 98 |
+
self.ref_by_hash[audio_hashes[i]] = (prompt_tokens[-1], ref.text)
|
| 99 |
|
| 100 |
else:
|
| 101 |
# Reuse already encoded references
|
| 102 |
+
cached_token, cached_text = self.ref_by_hash[audio_hashes[i]]
|
| 103 |
+
prompt_tokens.append(cached_token)
|
| 104 |
+
prompt_texts.append(cached_text)
|
| 105 |
cache_used = True
|
| 106 |
|
| 107 |
if cache_used:
|
fish_speech/models/text2semantic/inference.py
CHANGED
|
@@ -3,10 +3,9 @@ import queue
|
|
| 3 |
import threading
|
| 4 |
import time
|
| 5 |
import traceback
|
| 6 |
-
from contextlib import nullcontext
|
| 7 |
from dataclasses import dataclass
|
| 8 |
from pathlib import Path
|
| 9 |
-
from typing import Literal, Optional, Tuple, Union
|
| 10 |
|
| 11 |
import click
|
| 12 |
import numpy as np
|
|
@@ -21,7 +20,6 @@ from fish_speech.content_sequence import (
|
|
| 21 |
TextPart,
|
| 22 |
VQPart,
|
| 23 |
)
|
| 24 |
-
from fish_speech.text import split_text
|
| 25 |
from fish_speech.tokenizer import IM_END_TOKEN
|
| 26 |
|
| 27 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
@@ -107,17 +105,17 @@ def decode_one_token_ar(
|
|
| 107 |
repetition_penalty: torch.Tensor,
|
| 108 |
audio_masks: torch.Tensor,
|
| 109 |
audio_parts: torch.Tensor,
|
| 110 |
-
previous_tokens: torch.Tensor = None,
|
| 111 |
) -> torch.Tensor:
|
| 112 |
# print(x, torch.count_nonzero(vq_masks))
|
| 113 |
-
|
| 114 |
x,
|
| 115 |
input_pos,
|
| 116 |
audio_masks=audio_masks,
|
| 117 |
audio_parts=audio_parts,
|
| 118 |
)
|
| 119 |
-
logits =
|
| 120 |
-
hidden_states =
|
| 121 |
|
| 122 |
codebooks = [
|
| 123 |
sample(
|
|
@@ -131,10 +129,11 @@ def decode_one_token_ar(
|
|
| 131 |
)[0]
|
| 132 |
]
|
| 133 |
|
| 134 |
-
#
|
| 135 |
for layer in model.fast_layers:
|
| 136 |
-
layer.attention
|
| 137 |
-
|
|
|
|
| 138 |
|
| 139 |
input_pos = torch.tensor([0], device=hidden_states.device, dtype=torch.long)
|
| 140 |
model.forward_generate_fast(hidden_states, input_pos)
|
|
@@ -168,11 +167,15 @@ def decode_one_token_ar(
|
|
| 168 |
codebooks.append(a)
|
| 169 |
|
| 170 |
codebooks = torch.stack(codebooks, dim=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
return codebooks.T
|
| 172 |
|
| 173 |
|
| 174 |
def decode_n_tokens(
|
| 175 |
-
model:
|
| 176 |
cur_token: torch.Tensor,
|
| 177 |
input_pos: torch.Tensor,
|
| 178 |
num_new_tokens: int,
|
|
@@ -221,6 +224,9 @@ def decode_n_tokens(
|
|
| 221 |
if cur_token[0, 0, -1] == model.tokenizer.get_token_id(IM_END_TOKEN):
|
| 222 |
break
|
| 223 |
|
|
|
|
|
|
|
|
|
|
| 224 |
return previous_tokens[:, : i + 1]
|
| 225 |
|
| 226 |
|
|
@@ -228,7 +234,7 @@ def decode_n_tokens(
|
|
| 228 |
@torch.inference_mode()
|
| 229 |
def generate(
|
| 230 |
*,
|
| 231 |
-
model:
|
| 232 |
prompt: torch.Tensor,
|
| 233 |
max_new_tokens: int,
|
| 234 |
audio_masks: torch.Tensor,
|
|
@@ -260,28 +266,51 @@ def generate(
|
|
| 260 |
max_new_tokens = T_new - T
|
| 261 |
|
| 262 |
device, dtype = prompt.device, prompt.dtype
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
codebook_dim = 1 + model.config.num_codebooks
|
| 271 |
-
|
|
|
|
|
|
|
| 272 |
empty = torch.empty(
|
| 273 |
(codebook_dim, model.config.max_seq_len), dtype=dtype, device=device
|
| 274 |
)
|
| 275 |
empty[:, :T] = prompt
|
| 276 |
seq = empty
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
|
|
|
| 280 |
)
|
| 281 |
-
top_p =
|
| 282 |
-
|
| 283 |
-
sampling_kwargs["repetition_penalty"], device=device, dtype=torch.bfloat16
|
| 284 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
prefill_decode = decode_one_token_ar
|
| 287 |
|
|
@@ -297,7 +326,9 @@ def generate(
|
|
| 297 |
)
|
| 298 |
seq[:, T : T + 1] = first_token
|
| 299 |
|
|
|
|
| 300 |
input_pos = torch.tensor([T], device=device, dtype=torch.int)
|
|
|
|
| 301 |
x = decode_n_tokens(
|
| 302 |
model,
|
| 303 |
first_token.view(1, codebook_dim, -1),
|
|
@@ -312,6 +343,10 @@ def generate(
|
|
| 312 |
)
|
| 313 |
seq = seq[:, : T + 1 + x.size(1)]
|
| 314 |
seq[:, T + 1 :] = x
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
return seq
|
| 316 |
|
| 317 |
|
|
@@ -328,19 +363,18 @@ def init_model(checkpoint_path, device, precision, compile=False):
|
|
| 328 |
else:
|
| 329 |
raise ValueError("Unsupported model type")
|
| 330 |
|
| 331 |
-
#
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
|
| 339 |
if compile:
|
| 340 |
logger.info("Compiling function...")
|
| 341 |
decode_one_token = torch.compile(
|
| 342 |
decode_one_token,
|
| 343 |
-
# mode="max-autotune-no-cudagraphs",
|
| 344 |
backend="inductor" if torch.cuda.is_available() else "aot_eager",
|
| 345 |
mode="reduce-overhead" if torch.cuda.is_available() else None,
|
| 346 |
fullgraph=True,
|
|
@@ -359,19 +393,19 @@ class GenerateResponse:
|
|
| 359 |
def generate_long(
|
| 360 |
*,
|
| 361 |
model,
|
| 362 |
-
device: str
|
| 363 |
-
decode_one_token:
|
| 364 |
text: str,
|
| 365 |
num_samples: int = 1,
|
| 366 |
max_new_tokens: int = 0,
|
| 367 |
-
top_p:
|
| 368 |
repetition_penalty: float = 1.1,
|
| 369 |
temperature: float = 0.8,
|
| 370 |
compile: bool = False,
|
| 371 |
iterative_prompt: bool = True,
|
| 372 |
chunk_length: int = 512,
|
| 373 |
-
prompt_text: Optional[str
|
| 374 |
-
prompt_tokens: Optional[torch.Tensor
|
| 375 |
):
|
| 376 |
assert 0 < top_p <= 1, "top_p must be in (0, 1]"
|
| 377 |
assert 0 < repetition_penalty < 2, "repetition_penalty must be in (0, 2)"
|
|
@@ -382,11 +416,13 @@ def generate_long(
|
|
| 382 |
prompt_text = [prompt_text]
|
| 383 |
prompt_tokens = [prompt_tokens]
|
| 384 |
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
|
|
|
| 388 |
|
| 389 |
-
|
|
|
|
| 390 |
|
| 391 |
model_size = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 392 |
tokenizer = model.tokenizer
|
|
@@ -420,14 +456,6 @@ def generate_long(
|
|
| 420 |
encoded = encoded.to(device=device)
|
| 421 |
logger.info(f"Encoded text: {text}")
|
| 422 |
|
| 423 |
-
# Move temperature, top_p, repetition_penalty to device
|
| 424 |
-
# This is important so that changing params doesn't trigger recompile
|
| 425 |
-
temperature = torch.tensor(temperature, device=device, dtype=torch.float)
|
| 426 |
-
top_p = torch.tensor(top_p, device=device, dtype=torch.float)
|
| 427 |
-
repetition_penalty = torch.tensor(
|
| 428 |
-
repetition_penalty, device=device, dtype=torch.float
|
| 429 |
-
)
|
| 430 |
-
|
| 431 |
for sample_idx in range(num_samples):
|
| 432 |
if torch.cuda.is_available():
|
| 433 |
torch.cuda.synchronize()
|
|
@@ -437,6 +465,7 @@ def generate_long(
|
|
| 437 |
prompt_length = encoded.size(1)
|
| 438 |
|
| 439 |
t0 = time.perf_counter()
|
|
|
|
| 440 |
y = generate(
|
| 441 |
model=model,
|
| 442 |
prompt=encoded,
|
|
@@ -470,26 +499,26 @@ def generate_long(
|
|
| 470 |
)
|
| 471 |
|
| 472 |
# Put the generated tokens
|
| 473 |
-
# since there is <im_end>, we remove last token
|
| 474 |
codes = y[1:, prompt_length:-1].clone()
|
| 475 |
assert (codes >= 0).all(), f"Negative code found"
|
| 476 |
|
| 477 |
decoded = y[:, prompt_length:].clone()
|
| 478 |
-
# But for global encoding, we should keep the <im_end> token
|
| 479 |
-
|
| 480 |
global_encoded.append(decoded.cpu())
|
| 481 |
assert (codes >= 0).all(), f"Negative code found: {codes}"
|
|
|
|
| 482 |
yield GenerateResponse(action="sample", codes=codes, text=text)
|
| 483 |
seg_idx += 1
|
| 484 |
|
| 485 |
-
#
|
|
|
|
|
|
|
| 486 |
yield GenerateResponse(action="next")
|
| 487 |
|
| 488 |
|
| 489 |
@dataclass
|
| 490 |
class WrappedGenerateResponse:
|
| 491 |
status: Literal["success", "error"]
|
| 492 |
-
response: Optional[GenerateResponse
|
| 493 |
|
| 494 |
|
| 495 |
@dataclass
|
|
@@ -534,9 +563,17 @@ def launch_thread_safe_queue(
|
|
| 534 |
response_queue.put(
|
| 535 |
WrappedGenerateResponse(status="success", response=chunk)
|
| 536 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
except Exception as e:
|
| 538 |
logger.error(traceback.format_exc())
|
| 539 |
response_queue.put(WrappedGenerateResponse(status="error", response=e))
|
|
|
|
|
|
|
|
|
|
| 540 |
|
| 541 |
threading.Thread(target=worker, daemon=True).start()
|
| 542 |
init_event.wait()
|
|
@@ -576,8 +613,8 @@ def launch_thread_safe_queue(
|
|
| 576 |
@click.option("--output-dir", type=Path, default="temp")
|
| 577 |
def main(
|
| 578 |
text: str,
|
| 579 |
-
prompt_text: Optional[
|
| 580 |
-
prompt_tokens: Optional[
|
| 581 |
num_samples: int,
|
| 582 |
max_new_tokens: int,
|
| 583 |
top_p: int,
|
|
@@ -595,7 +632,11 @@ def main(
|
|
| 595 |
os.makedirs(output_dir, exist_ok=True)
|
| 596 |
precision = torch.half if half else torch.bfloat16
|
| 597 |
|
| 598 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
raise ValueError(
|
| 600 |
f"Number of prompt text ({len(prompt_text)}) and prompt tokens ({len(prompt_tokens)}) should be the same"
|
| 601 |
)
|
|
@@ -616,8 +657,9 @@ def main(
|
|
| 616 |
|
| 617 |
logger.info(f"Time to load model: {time.time() - t0:.02f} seconds")
|
| 618 |
|
|
|
|
| 619 |
if prompt_tokens is not None:
|
| 620 |
-
|
| 621 |
|
| 622 |
torch.manual_seed(seed)
|
| 623 |
|
|
@@ -637,8 +679,8 @@ def main(
|
|
| 637 |
compile=compile,
|
| 638 |
iterative_prompt=iterative_prompt,
|
| 639 |
chunk_length=chunk_length,
|
| 640 |
-
prompt_text=prompt_text,
|
| 641 |
-
prompt_tokens=
|
| 642 |
)
|
| 643 |
|
| 644 |
idx = 0
|
|
|
|
| 3 |
import threading
|
| 4 |
import time
|
| 5 |
import traceback
|
|
|
|
| 6 |
from dataclasses import dataclass
|
| 7 |
from pathlib import Path
|
| 8 |
+
from typing import Callable, Literal, Optional, Tuple, Union
|
| 9 |
|
| 10 |
import click
|
| 11 |
import numpy as np
|
|
|
|
| 20 |
TextPart,
|
| 21 |
VQPart,
|
| 22 |
)
|
|
|
|
| 23 |
from fish_speech.tokenizer import IM_END_TOKEN
|
| 24 |
|
| 25 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
|
| 105 |
repetition_penalty: torch.Tensor,
|
| 106 |
audio_masks: torch.Tensor,
|
| 107 |
audio_parts: torch.Tensor,
|
| 108 |
+
previous_tokens: Optional[torch.Tensor] = None,
|
| 109 |
) -> torch.Tensor:
|
| 110 |
# print(x, torch.count_nonzero(vq_masks))
|
| 111 |
+
forward_result = model.forward_generate(
|
| 112 |
x,
|
| 113 |
input_pos,
|
| 114 |
audio_masks=audio_masks,
|
| 115 |
audio_parts=audio_parts,
|
| 116 |
)
|
| 117 |
+
logits = forward_result.logits # [:, -1:]
|
| 118 |
+
hidden_states = forward_result.hidden_states # [:, -1:]
|
| 119 |
|
| 120 |
codebooks = [
|
| 121 |
sample(
|
|
|
|
| 129 |
)[0]
|
| 130 |
]
|
| 131 |
|
| 132 |
+
# Only clear cache for fast_layers, avoid clearing main model cache
|
| 133 |
for layer in model.fast_layers:
|
| 134 |
+
if hasattr(layer, "attention") and hasattr(layer.attention, "kv_cache"):
|
| 135 |
+
layer.attention.kv_cache.k_cache.fill_(0)
|
| 136 |
+
layer.attention.kv_cache.v_cache.fill_(0)
|
| 137 |
|
| 138 |
input_pos = torch.tensor([0], device=hidden_states.device, dtype=torch.long)
|
| 139 |
model.forward_generate_fast(hidden_states, input_pos)
|
|
|
|
| 167 |
codebooks.append(a)
|
| 168 |
|
| 169 |
codebooks = torch.stack(codebooks, dim=1)
|
| 170 |
+
|
| 171 |
+
# Only delete references, let Python GC handle cleanup
|
| 172 |
+
del logits, hidden_states, forward_result
|
| 173 |
+
|
| 174 |
return codebooks.T
|
| 175 |
|
| 176 |
|
| 177 |
def decode_n_tokens(
|
| 178 |
+
model: DualARTransformer,
|
| 179 |
cur_token: torch.Tensor,
|
| 180 |
input_pos: torch.Tensor,
|
| 181 |
num_new_tokens: int,
|
|
|
|
| 224 |
if cur_token[0, 0, -1] == model.tokenizer.get_token_id(IM_END_TOKEN):
|
| 225 |
break
|
| 226 |
|
| 227 |
+
# Only clean up the large tensor
|
| 228 |
+
del cur_token
|
| 229 |
+
|
| 230 |
return previous_tokens[:, : i + 1]
|
| 231 |
|
| 232 |
|
|
|
|
| 234 |
@torch.inference_mode()
|
| 235 |
def generate(
|
| 236 |
*,
|
| 237 |
+
model: DualARTransformer,
|
| 238 |
prompt: torch.Tensor,
|
| 239 |
max_new_tokens: int,
|
| 240 |
audio_masks: torch.Tensor,
|
|
|
|
| 266 |
max_new_tokens = T_new - T
|
| 267 |
|
| 268 |
device, dtype = prompt.device, prompt.dtype
|
| 269 |
+
|
| 270 |
+
# Critical fix: Only set up cache on first run or when necessary
|
| 271 |
+
if not hasattr(model, "_cache_setup_done") or not model._cache_setup_done:
|
| 272 |
+
with torch.device(device):
|
| 273 |
+
model.setup_caches(
|
| 274 |
+
max_batch_size=1, # Fixed to 1, avoid dynamic changes
|
| 275 |
+
max_seq_len=model.config.max_seq_len,
|
| 276 |
+
dtype=next(model.parameters()).dtype,
|
| 277 |
+
)
|
| 278 |
+
model._cache_setup_done = True
|
| 279 |
|
| 280 |
codebook_dim = 1 + model.config.num_codebooks
|
| 281 |
+
|
| 282 |
+
# Create new tensor each time, but try to reuse memory
|
| 283 |
+
input_pos = torch.arange(0, T, device=device, dtype=torch.long)
|
| 284 |
empty = torch.empty(
|
| 285 |
(codebook_dim, model.config.max_seq_len), dtype=dtype, device=device
|
| 286 |
)
|
| 287 |
empty[:, :T] = prompt
|
| 288 |
seq = empty
|
| 289 |
|
| 290 |
+
# Use pre-created fixed parameter tensors
|
| 291 |
+
temperature = getattr(
|
| 292 |
+
model, "fixed_temperature", torch.tensor(0.8, device=device, dtype=torch.float)
|
| 293 |
)
|
| 294 |
+
top_p = getattr(
|
| 295 |
+
model, "fixed_top_p", torch.tensor(0.8, device=device, dtype=torch.float)
|
|
|
|
| 296 |
)
|
| 297 |
+
repetition_penalty = getattr(
|
| 298 |
+
model,
|
| 299 |
+
"fixed_repetition_penalty",
|
| 300 |
+
torch.tensor(1.1, device=device, dtype=torch.float),
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# If different parameter values are needed, directly modify existing tensors
|
| 304 |
+
temp_val = sampling_kwargs.get("temperature", 0.7)
|
| 305 |
+
top_p_val = sampling_kwargs.get("top_p", 0.7)
|
| 306 |
+
rep_val = sampling_kwargs.get("repetition_penalty", 1.5)
|
| 307 |
+
|
| 308 |
+
if abs(temperature.item() - temp_val) > 1e-6:
|
| 309 |
+
temperature.fill_(temp_val)
|
| 310 |
+
if abs(top_p.item() - top_p_val) > 1e-6:
|
| 311 |
+
top_p.fill_(top_p_val)
|
| 312 |
+
if abs(repetition_penalty.item() - rep_val) > 1e-6:
|
| 313 |
+
repetition_penalty.fill_(rep_val)
|
| 314 |
|
| 315 |
prefill_decode = decode_one_token_ar
|
| 316 |
|
|
|
|
| 326 |
)
|
| 327 |
seq[:, T : T + 1] = first_token
|
| 328 |
|
| 329 |
+
# Recreate input_pos
|
| 330 |
input_pos = torch.tensor([T], device=device, dtype=torch.int)
|
| 331 |
+
|
| 332 |
x = decode_n_tokens(
|
| 333 |
model,
|
| 334 |
first_token.view(1, codebook_dim, -1),
|
|
|
|
| 343 |
)
|
| 344 |
seq = seq[:, : T + 1 + x.size(1)]
|
| 345 |
seq[:, T + 1 :] = x
|
| 346 |
+
|
| 347 |
+
# Clean up temporary variables
|
| 348 |
+
del first_token, x, prompt, empty, input_pos
|
| 349 |
+
|
| 350 |
return seq
|
| 351 |
|
| 352 |
|
|
|
|
| 363 |
else:
|
| 364 |
raise ValueError("Unsupported model type")
|
| 365 |
|
| 366 |
+
# Pre-create fixed parameter tensors to avoid runtime creation
|
| 367 |
+
model.fixed_temperature = torch.tensor(0.7, device=device, dtype=torch.float)
|
| 368 |
+
model.fixed_top_p = torch.tensor(0.7, device=device, dtype=torch.float)
|
| 369 |
+
model.fixed_repetition_penalty = torch.tensor(1.5, device=device, dtype=torch.float)
|
| 370 |
+
|
| 371 |
+
# Mark whether cache has been initialized
|
| 372 |
+
model._cache_setup_done = False
|
| 373 |
|
| 374 |
if compile:
|
| 375 |
logger.info("Compiling function...")
|
| 376 |
decode_one_token = torch.compile(
|
| 377 |
decode_one_token,
|
|
|
|
| 378 |
backend="inductor" if torch.cuda.is_available() else "aot_eager",
|
| 379 |
mode="reduce-overhead" if torch.cuda.is_available() else None,
|
| 380 |
fullgraph=True,
|
|
|
|
| 393 |
def generate_long(
|
| 394 |
*,
|
| 395 |
model,
|
| 396 |
+
device: Union[str, torch.device],
|
| 397 |
+
decode_one_token: Callable,
|
| 398 |
text: str,
|
| 399 |
num_samples: int = 1,
|
| 400 |
max_new_tokens: int = 0,
|
| 401 |
+
top_p: float = 0.8,
|
| 402 |
repetition_penalty: float = 1.1,
|
| 403 |
temperature: float = 0.8,
|
| 404 |
compile: bool = False,
|
| 405 |
iterative_prompt: bool = True,
|
| 406 |
chunk_length: int = 512,
|
| 407 |
+
prompt_text: Optional[Union[str, list[str]]] = None,
|
| 408 |
+
prompt_tokens: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
|
| 409 |
):
|
| 410 |
assert 0 < top_p <= 1, "top_p must be in (0, 1]"
|
| 411 |
assert 0 < repetition_penalty < 2, "repetition_penalty must be in (0, 2)"
|
|
|
|
| 416 |
prompt_text = [prompt_text]
|
| 417 |
prompt_tokens = [prompt_tokens]
|
| 418 |
|
| 419 |
+
if use_prompt:
|
| 420 |
+
assert len(prompt_text) == len(
|
| 421 |
+
prompt_tokens
|
| 422 |
+
), "Prompt text and tokens must have the same length"
|
| 423 |
|
| 424 |
+
if prompt_tokens:
|
| 425 |
+
prompt_tokens = [i.cpu() for i in prompt_tokens]
|
| 426 |
|
| 427 |
model_size = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 428 |
tokenizer = model.tokenizer
|
|
|
|
| 456 |
encoded = encoded.to(device=device)
|
| 457 |
logger.info(f"Encoded text: {text}")
|
| 458 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
for sample_idx in range(num_samples):
|
| 460 |
if torch.cuda.is_available():
|
| 461 |
torch.cuda.synchronize()
|
|
|
|
| 465 |
prompt_length = encoded.size(1)
|
| 466 |
|
| 467 |
t0 = time.perf_counter()
|
| 468 |
+
|
| 469 |
y = generate(
|
| 470 |
model=model,
|
| 471 |
prompt=encoded,
|
|
|
|
| 499 |
)
|
| 500 |
|
| 501 |
# Put the generated tokens
|
|
|
|
| 502 |
codes = y[1:, prompt_length:-1].clone()
|
| 503 |
assert (codes >= 0).all(), f"Negative code found"
|
| 504 |
|
| 505 |
decoded = y[:, prompt_length:].clone()
|
|
|
|
|
|
|
| 506 |
global_encoded.append(decoded.cpu())
|
| 507 |
assert (codes >= 0).all(), f"Negative code found: {codes}"
|
| 508 |
+
|
| 509 |
yield GenerateResponse(action="sample", codes=codes, text=text)
|
| 510 |
seg_idx += 1
|
| 511 |
|
| 512 |
+
# Force GPU memory cleanup
|
| 513 |
+
del y, decoded, codes
|
| 514 |
+
|
| 515 |
yield GenerateResponse(action="next")
|
| 516 |
|
| 517 |
|
| 518 |
@dataclass
|
| 519 |
class WrappedGenerateResponse:
|
| 520 |
status: Literal["success", "error"]
|
| 521 |
+
response: Optional[Union[GenerateResponse, Exception]] = None
|
| 522 |
|
| 523 |
|
| 524 |
@dataclass
|
|
|
|
| 563 |
response_queue.put(
|
| 564 |
WrappedGenerateResponse(status="success", response=chunk)
|
| 565 |
)
|
| 566 |
+
|
| 567 |
+
# Only clear cache after complete request batch
|
| 568 |
+
if torch.cuda.is_available():
|
| 569 |
+
torch.cuda.empty_cache()
|
| 570 |
+
|
| 571 |
except Exception as e:
|
| 572 |
logger.error(traceback.format_exc())
|
| 573 |
response_queue.put(WrappedGenerateResponse(status="error", response=e))
|
| 574 |
+
# Clear cache on error
|
| 575 |
+
if torch.cuda.is_available():
|
| 576 |
+
torch.cuda.empty_cache()
|
| 577 |
|
| 578 |
threading.Thread(target=worker, daemon=True).start()
|
| 579 |
init_event.wait()
|
|
|
|
| 613 |
@click.option("--output-dir", type=Path, default="temp")
|
| 614 |
def main(
|
| 615 |
text: str,
|
| 616 |
+
prompt_text: Optional[tuple[str, ...]],
|
| 617 |
+
prompt_tokens: Optional[tuple[Path, ...]],
|
| 618 |
num_samples: int,
|
| 619 |
max_new_tokens: int,
|
| 620 |
top_p: int,
|
|
|
|
| 632 |
os.makedirs(output_dir, exist_ok=True)
|
| 633 |
precision = torch.half if half else torch.bfloat16
|
| 634 |
|
| 635 |
+
if (
|
| 636 |
+
prompt_text is not None
|
| 637 |
+
and prompt_tokens is not None
|
| 638 |
+
and len(prompt_text) != len(prompt_tokens)
|
| 639 |
+
):
|
| 640 |
raise ValueError(
|
| 641 |
f"Number of prompt text ({len(prompt_text)}) and prompt tokens ({len(prompt_tokens)}) should be the same"
|
| 642 |
)
|
|
|
|
| 657 |
|
| 658 |
logger.info(f"Time to load model: {time.time() - t0:.02f} seconds")
|
| 659 |
|
| 660 |
+
prompt_tokens_list = None
|
| 661 |
if prompt_tokens is not None:
|
| 662 |
+
prompt_tokens_list = [torch.from_numpy(np.load(p)) for p in prompt_tokens]
|
| 663 |
|
| 664 |
torch.manual_seed(seed)
|
| 665 |
|
|
|
|
| 679 |
compile=compile,
|
| 680 |
iterative_prompt=iterative_prompt,
|
| 681 |
chunk_length=chunk_length,
|
| 682 |
+
prompt_text=list(prompt_text) if prompt_text else None,
|
| 683 |
+
prompt_tokens=prompt_tokens_list,
|
| 684 |
)
|
| 685 |
|
| 686 |
idx = 0
|
fish_speech/text/__init__.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
from .clean import clean_text
|
| 2 |
-
from .spliter import split_text
|
| 3 |
|
| 4 |
-
__all__ = ["clean_text"
|
|
|
|
| 1 |
from .clean import clean_text
|
|
|
|
| 2 |
|
| 3 |
+
__all__ = ["clean_text"]
|
fish_speech/utils/schema.py
CHANGED
|
@@ -27,35 +27,6 @@ class ServeAudioPart(BaseModel):
|
|
| 27 |
audio: bytes
|
| 28 |
|
| 29 |
|
| 30 |
-
class ServeASRRequest(BaseModel):
|
| 31 |
-
# The audio should be an uncompressed PCM float16 audio
|
| 32 |
-
audios: list[bytes]
|
| 33 |
-
sample_rate: int = 44100
|
| 34 |
-
language: Literal["zh", "en", "ja", "auto"] = "auto"
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
class ServeASRTranscription(BaseModel):
|
| 38 |
-
text: str
|
| 39 |
-
duration: float
|
| 40 |
-
huge_gap: bool
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
class ServeASRSegment(BaseModel):
|
| 44 |
-
text: str
|
| 45 |
-
start: float
|
| 46 |
-
end: float
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
class ServeTimedASRResponse(BaseModel):
|
| 50 |
-
text: str
|
| 51 |
-
segments: list[ServeASRSegment]
|
| 52 |
-
duration: float
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
class ServeASRResponse(BaseModel):
|
| 56 |
-
transcriptions: list[ServeASRTranscription]
|
| 57 |
-
|
| 58 |
-
|
| 59 |
class ServeRequest(BaseModel):
|
| 60 |
# Raw content sequence dict that we can use with ContentSequence(**content)
|
| 61 |
content: dict
|
|
@@ -86,18 +57,6 @@ class ServeVQGANDecodeResponse(BaseModel):
|
|
| 86 |
audios: list[bytes]
|
| 87 |
|
| 88 |
|
| 89 |
-
class ServeStreamDelta(BaseModel):
|
| 90 |
-
role: Literal["system", "assistant", "user"] | None = None
|
| 91 |
-
part: ServeVQPart | ServeTextPart | None = None
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
class ServeStreamResponse(BaseModel):
|
| 95 |
-
sample_id: int = 0
|
| 96 |
-
delta: ServeStreamDelta | None = None
|
| 97 |
-
finish_reason: Literal["stop", "error"] | None = None
|
| 98 |
-
stats: dict[str, int | float | str] | None = None
|
| 99 |
-
|
| 100 |
-
|
| 101 |
class ServeReferenceAudio(BaseModel):
|
| 102 |
audio: bytes
|
| 103 |
text: str
|
|
|
|
| 27 |
audio: bytes
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
class ServeRequest(BaseModel):
|
| 31 |
# Raw content sequence dict that we can use with ContentSequence(**content)
|
| 32 |
content: dict
|
|
|
|
| 57 |
audios: list[bytes]
|
| 58 |
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
class ServeReferenceAudio(BaseModel):
|
| 61 |
audio: bytes
|
| 62 |
text: str
|
requirements.txt
CHANGED
|
@@ -34,4 +34,4 @@ silero-vad
|
|
| 34 |
tiktoken
|
| 35 |
numpy
|
| 36 |
huggingface_hub
|
| 37 |
-
git+https://
|
|
|
|
| 34 |
tiktoken
|
| 35 |
numpy
|
| 36 |
huggingface_hub
|
| 37 |
+
git+https://githubfast.com/descriptinc/descript-audio-codec
|