repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
fairseq
examples/speech_text_joint_to_text/criterions/multi_modality_cross_entropy.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from fairseq import utils from fairseq.criterions import register_criterion from fairseq.criterions.label_smoothed_cross_entropy ...
102
4,105
fairseq
examples/speech_text_joint_to_text/criterions/text_guide_cross_entropy_acc.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn.functional as F from fairseq import utils from fairseq.criterions import FairseqCriterion, register_c...
225
11,031
fairseq
examples/speech_text_joint_to_text/scripts/g2p_encode.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import itertools import logging import re import time from g2p_en import G2p logger = logging.getLogger(__name__) FAIL_SENT...
192
5,844
fairseq
examples/speech_text_joint_to_text/scripts/convert_model.py
.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import re from collections import OrderedDict import torch from fairseq.file_io import PathManager ...
72
1,866
fairseq
examples/speech_text_joint_to_text/data/pair_denoising_dataset.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import math import re import torch from fairseq.data import data_utils from fairseq.data.language_pair_dataset import LanguagePa...
319
11,448
fairseq
examples/speech_text_joint_to_text/models/s2t_dualinputwavtransformer.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from collections import OrderedDict, namedtuple import torch.nn as nn from fairseq import checkpoint_utils, utils from fairse...
527
21,145
fairseq
examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from collections import namedtuple import torch import torch.nn as nn from fairseq import checkpoint_utils from fairseq import...
1,094
45,047
fairseq
examples/speech_text_joint_to_text/models/s2t_dualinputxmtransformer.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import torch.nn as nn from fairseq import checkpoint_utils from fairseq import utils from fairseq.data.data_utils import lengths_...
585
21,461
fairseq
examples/speech_text_joint_to_text/models/joint_speech_text_pretrain_transformer.py
.py
#!/usr/bin/env python3 import logging from collections import OrderedDict, namedtuple from typing import Dict, Optional import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from fairseq import checkpoint_utils, utils from fairseq.file_io import PathManager from fairseq.models i...
699
28,546
fairseq
examples/discriminative_reranking_nmt/drnmt_rerank.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Score raw text with a trained model. """ from collections import namedtuple import logging from multiprocessing ...
365
11,312
fairseq
examples/discriminative_reranking_nmt/tasks/__init__.py
.py
from .discriminative_reranking_task import DiscriminativeRerankingNMTTask __all__ = [ "DiscriminativeRerankingNMTTask", ]
7
128
fairseq
examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field import itertools import logging import os import numpy as np import torch from fairseq.logging imp...
491
17,739
fairseq
examples/discriminative_reranking_nmt/criterions/discriminative_reranking_criterion.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from dataclasses import dataclass, field import torch import torch.nn.functional as F from fairseq import utils from fairseq.log...
140
5,024
fairseq
examples/discriminative_reranking_nmt/criterions/__init__.py
.py
from .discriminative_reranking_criterion import KLDivergenceRerankingCriterion __all__ = [ "KLDivergenceRerankingCriterion", ]
7
133
fairseq
examples/discriminative_reranking_nmt/scripts/prep_data.py
.py
#!/usr/bin/env python import argparse from multiprocessing import Pool from pathlib import Path import sacrebleu import sentencepiece as spm def read_text_file(filename): with open(filename, "r") as f: output = [line.strip() for line in f] return output def get_bleu(in_sent, target_sent): ble...
137
4,872
fairseq
examples/discriminative_reranking_nmt/models/discriminative_reranking_model.py
.py
from dataclasses import dataclass, field import os import torch import torch.nn as nn from fairseq import utils from fairseq.dataclass import ChoiceEnum, FairseqDataclass from fairseq.models import ( BaseFairseqModel, register_model, ) from fairseq.models.roberta.model import RobertaClassificationHead from ...
366
13,714
fairseq
examples/discriminative_reranking_nmt/models/__init__.py
.py
from .discriminative_reranking_model import DiscriminativeNMTReranker __all__ = [ "DiscriminativeNMTReranker", ]
7
119
fairseq
examples/latent_depth/latent_depth_src/multilingual_translation_latent_depth.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from fairseq.tasks import register_task from fairseq.tasks.multilingual_translation import MultilingualTranslationTask from fairseq.utils impo...
196
8,592
fairseq
examples/latent_depth/latent_depth_src/loss/latent_depth.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch from torch.nn.modules.loss import _Loss class LatentLayersKLLoss(_Loss): def __init__(self, args): sup...
100
3,802
fairseq
examples/latent_depth/latent_depth_src/modules/latent_layers.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn class LayerSelect(nn.Module): """Compute samples (from a Gumbel-Sigmoid distribution) which is used a...
76
2,605
fairseq
examples/latent_depth/latent_depth_src/models/latent_multilingual_transformer.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from fairseq.models import register_model, register_model_architecture from fairseq.models.multilingual_transformer import MultilingualTransfo...
77
3,211
fairseq
examples/latent_depth/latent_depth_src/models/latent_transformer.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict, Optional import torch.nn as nn from fairseq.models.fairseq_encoder import EncoderOut from fairseq.models.transf...
157
5,584
fairseq
fairseq_cli/generate.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Translate pre-processed data with a trained model. """ import ast import logging import math import os import sy...
418
15,805
fairseq
fairseq_cli/preprocess.py
.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Data pre-processing: build vocabularies and binarize training data. """ import logging import os import shutil impo...
394
12,218
fairseq
fairseq_cli/score.py
.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ BLEU scoring of generated translations against reference translations. """ import argparse import os import sys fr...
103
3,287
fairseq
fairseq_cli/train.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Train a new model on one or across multiple GPUs. """ import argparse import logging import math import os impor...
582
20,723
fairseq
fairseq_cli/hydra_validate.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import sys from itertools import chain import torch from hydra.core.hydra_config import Hy...
189
6,420
fairseq
fairseq_cli/eval_lm.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Evaluate the perplexity of a trained language model. """ import logging import math import os import sys from a...
348
11,960
fairseq
fairseq_cli/validate.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import sys from argparse import Namespace from itertools import chain import torch from om...
154
5,228
fairseq
fairseq_cli/interactive.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Translate raw text with a trained model. Batches data on-the-fly. """ import ast import fileinput import logging...
318
11,465
fairseq
fairseq_cli/hydra_train.py
.py
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import hydra import torch from hydra.core.hydra_config import HydraConfig from omegaconf i...
92
2,714
fish-speech
tools/run_webui.py
.py
import os from argparse import ArgumentParser from pathlib import Path import pyrootutils import torch from loguru import logger pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True) from fish_speech.inference_engine import TTSInferenceEngine from fish_speech.models.dac.inference import load_m...
108
3,377
fish-speech
tools/api_server.py
.py
import json import multiprocessing import os import re from argparse import Namespace from threading import Lock import pyrootutils import uvicorn from kui.asgi import ( Depends, FactoryClass, HTTPException, HttpRoute, Kui, OpenAPI, Routes, ) from kui.cors import CORSConfig from kui.openapi...
146
4,408
fish-speech
tools/api_client.py
.py
import argparse import base64 import time import wave import ormsgpack import pyaudio import requests from pydub import AudioSegment from pydub.playback import play from fish_speech.utils.file import audio_to_bytes, read_ref_text from fish_speech.utils.schema import ServeReferenceAudio, ServeTTSRequest def parse_ar...
240
7,704
fish-speech
tools/server/inference.py
.py
from http import HTTPStatus import numpy as np from kui.asgi import HTTPException from fish_speech.inference_engine import TTSInferenceEngine from fish_speech.utils.schema import ServeTTSRequest AMPLITUDE = 32768 # Needs an explaination def inference_wrapper(req: ServeTTSRequest, engine: TTSInferenceEngine): ...
46
1,352
fish-speech
tools/server/exception_handler.py
.py
import traceback from http import HTTPStatus from kui.asgi import HTTPException, JSONResponse class ExceptionHandler: async def http_exception_handler(self, exc: HTTPException): return JSONResponse( dict( statusCode=exc.status_code, message=exc.content, ...
28
729
fish-speech
tools/server/views.py
.py
import io import os import re import shutil import tempfile import time from http import HTTPStatus from pathlib import Path import numpy as np import ormsgpack import soundfile as sf import torch from kui.asgi import ( Body, HTTPException, HttpView, JSONResponse, Routes, StreamResponse, Up...
489
17,012
fish-speech
tools/server/model_utils.py
.py
import io import re import librosa import torch import torchaudio from cachetools import LRUCache, cached CACHE_MAXSIZE = 10000 MICRO_BATCH_SIZE = 8 ASR_SAMPLE_RATE = 16000 HUGE_GAP_THRESHOLD = 4000 @torch.no_grad() @torch.autocast(device_type="cuda", dtype=torch.half) def batch_encode(model, audios_list: list[byte...
87
2,643
fish-speech
tools/server/model_manager.py
.py
import torch from loguru import logger from fish_speech.inference_engine import TTSInferenceEngine from fish_speech.models.dac.inference import load_model as load_decoder_model from fish_speech.models.text2semantic.inference import launch_thread_safe_queue from fish_speech.utils.schema import ServeTTSRequest from tool...
94
2,974
fish-speech
tools/server/api_utils.py
.py
from argparse import ArgumentParser from http import HTTPStatus from typing import Annotated, Any import ormsgpack from baize.datastructures import ContentType from kui.asgi import ( HTTPException, HttpRequest, JSONResponse, request, ) from loguru import logger from pydantic import BaseModel from fish...
152
4,451
fish-speech
tools/webui/inference.py
.py
import html from functools import partial from typing import Any, Callable from fish_speech.i18n import i18n from fish_speech.utils.schema import ServeReferenceAudio, ServeTTSRequest def inference_wrapper( text, reference_id, reference_audio, reference_text, max_new_tokens, chunk_length, ...
90
2,109
fish-speech
tools/webui/__init__.py
.py
from typing import Callable import gradio as gr from fish_speech.i18n import i18n from tools.webui.variables import HEADER_MD, TEXTBOX_PLACEHOLDER def build_app(inference_fct: Callable, theme: str = "light") -> gr.Blocks: with gr.Blocks(theme=gr.themes.Base()) as app: gr.Markdown(HEADER_MD) # U...
156
6,167
fish-speech
tools/webui/variables.py
.py
from fish_speech.i18n import i18n HEADER_MD = f"""# Fish Speech {i18n("A text-to-speech model based on VQ-GAN and Llama developed by [Fish Audio](https://fish.audio).")} {i18n("You can find the source code [here](https://github.com/fishaudio/fish-speech) and models [here](https://huggingface.co/fishaudio/fish-spee...
15
605
fish-speech
tools/vqgan/extract_vq.py
.py
import os import subprocess as sp import sys import time from datetime import timedelta from functools import lru_cache from pathlib import Path from random import Random import click import numpy as np import torch import torchaudio from hydra import compose, initialize from hydra.utils import instantiate from loguru...
241
7,116
fish-speech
tools/vqgan/create_train_split.py
.py
import math from pathlib import Path from random import Random import click from loguru import logger from pydub import AudioSegment from tqdm import tqdm from fish_speech.utils.file import AUDIO_EXTENSIONS, list_files, load_filelist @click.command() @click.argument("root", type=click.Path(exists=True, path_type=Pa...
84
3,008
fish-speech
tools/llama/merge_lora.py
.py
import shutil from copy import deepcopy from pathlib import Path import click import hydra import torch from hydra import compose, initialize from hydra.utils import instantiate from loguru import logger from fish_speech.models.text2semantic.llama import BaseTransformer from fish_speech.models.text2semantic.lora impo...
97
3,369
fish-speech
tools/llama/eval_in_context.py
.py
import pyrootutils import torch import torch.nn.functional as F from matplotlib import pyplot as plt from transformers import AutoTokenizer # register eval resolver and root pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True) from torch.utils.data import DataLoader from fish_speech.datasets....
172
4,641
fish-speech
tools/llama/quantize.py
.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. import datetime import shutil # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import time from pathlib import Path import click import torch import torch.nn as nn import ...
498
16,589
fish-speech
tools/llama/build_dataset.py
.py
import itertools import os import re from collections import defaultdict from functools import partial from multiprocessing import Pool from pathlib import Path import click import numpy as np from loguru import logger from tqdm import tqdm from fish_speech.datasets.protos.text_data_pb2 import Semantics, Sentence, Te...
170
4,910
fish-speech
fish_speech/scheduler.py
.py
import math def get_cosine_schedule_with_warmup_lr_lambda( current_step: int, *, num_warmup_steps: int | float, num_training_steps: int, num_cycles: float = 0.5, final_lr_ratio: float = 0.0, ): if 0 < num_warmup_steps < 1: # float mode num_warmup_steps = int(num_warmup_steps * num...
41
1,101
fish-speech
fish_speech/train.py
.py
import os os.environ["USE_LIBUV"] = "0" import sys from typing import Optional import hydra import lightning as L import pyrootutils import torch from lightning import Callback, LightningDataModule, LightningModule, Trainer from lightning.pytorch.loggers import Logger from lightning.pytorch.strategies import DDPStrat...
142
4,470
fish-speech
fish_speech/content_sequence.py
.py
from dataclasses import dataclass, field from typing import List, Literal, Union import numpy as np import torch from fish_speech.tokenizer import ( IM_END_TOKEN, MODALITY_TOKENS, FishTokenizer, ) def restore_ndarray(obj, to_tensor: bool = False): if isinstance(obj, dict) and "__ndarray__" in obj: ...
404
14,345
fish-speech
fish_speech/tokenizer.py
.py
import json import logging from pathlib import Path from typing import TYPE_CHECKING, List, Union import torch from transformers import AutoTokenizer if TYPE_CHECKING: from transformers import PreTrainedTokenizerFast logger = logging.getLogger(__name__) # Constants definitions EOS_TOKEN = "<|endoftext|>" PAD_TO...
130
3,948
fish-speech
fish_speech/conversation.py
.py
from copy import deepcopy from dataclasses import dataclass, field from typing import Literal import torch from transformers import PreTrainedTokenizerFast from fish_speech.content_sequence import ( AudioPart, BasePart, ContentSequence, EncodedMessage, TextPart, VQPart, ) from fish_speech.toke...
175
5,602
fish-speech
fish_speech/text/clean.py
.py
import re SYMBOLS_MAPPING = { "‘": "'", "’": "'", } REPLACE_SYMBOL_REGEX = re.compile( "|".join(re.escape(p) for p in SYMBOLS_MAPPING.keys()) ) EMOJI_REGEX = re.compile( "[" "\U0001f600-\U0001f64f" # emoticons "\U0001f300-\U0001f5ff" # symbols & pictographs "\U0001f680-\U0001f6ff" # t...
38
832
fish-speech
fish_speech/text/__init__.py
.py
from .clean import clean_text __all__ = ["clean_text"]
4
56
fish-speech
fish_speech/i18n/scan.py
.py
import ast import glob import json from collections import OrderedDict from pathlib import Path from loguru import logger from .core import DEFAULT_LANGUAGE, I18N_FILE_PATH def extract_i18n_strings(node): i18n_strings = [] if ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) ...
123
3,751
fish-speech
fish_speech/i18n/__init__.py
.py
from .core import i18n __all__ = ["i18n"]
4
43
fish-speech
fish_speech/i18n/core.py
.py
import json import locale from pathlib import Path I18N_FILE_PATH = Path(__file__).parent / "locale" DEFAULT_LANGUAGE = "en_US" def load_language_list(language): with open(I18N_FILE_PATH / f"{language}.json", "r", encoding="utf-8") as f: language_list = json.load(f) return language_list class I18n...
41
1,036
fish-speech
fish_speech/inference_engine/reference_loader.py
.py
import io import re from hashlib import sha256 from pathlib import Path from typing import Callable, Literal, Tuple import torch import torchaudio from loguru import logger from fish_speech.models.dac.modded_dac import DAC from fish_speech.utils.file import ( AUDIO_EXTENSIONS, audio_to_bytes, list_files, ...
286
9,567
fish-speech
fish_speech/inference_engine/utils.py
.py
import io import wave from dataclasses import dataclass from typing import Literal, Optional, Tuple import numpy as np @dataclass class InferenceResult: code: Literal["header", "segment", "error", "final"] audio: Optional[Tuple[int, np.ndarray]] error: Optional[Exception] def wav_chunk_header( samp...
30
685
fish-speech
fish_speech/inference_engine/__init__.py
.py
import gc import queue from typing import Generator import numpy as np import torch from loguru import logger from fish_speech.inference_engine.reference_loader import ReferenceLoader from fish_speech.inference_engine.utils import InferenceResult, wav_chunk_header from fish_speech.inference_engine.vq_manager import V...
193
6,261
fish-speech
fish_speech/inference_engine/vq_manager.py
.py
from typing import Callable import torch from loguru import logger from fish_speech.models.dac.modded_dac import DAC class VQManager: def __init__(self): # Make Pylance happy (attribut/method not defined...) self.decoder_model: DAC self.load_audio: Callable def decode_vq_tokens(sel...
54
1,952
fish-speech
fish_speech/datasets/vqgan.py
.py
from dataclasses import dataclass from pathlib import Path from typing import Optional import librosa import numpy as np import torch from lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset from fish_speech.utils import RankedLogger logger = RankedLogger(__name__, rank_zero_only=Fa...
146
3,933
fish-speech
fish_speech/datasets/concat_repeat.py
.py
import bisect import random from typing import Iterable from torch.utils.data import Dataset, IterableDataset class ConcatRepeatDataset(Dataset): datasets: list[Dataset] cumulative_sizes: list[int] repeats: list[int] @staticmethod def cumsum(sequence, repeats): r, s = [], 0 for d...
54
1,498
fish-speech
fish_speech/datasets/semantic.py
.py
import random from dataclasses import dataclass from itertools import chain from pathlib import Path from random import Random from typing import Optional, Union import numpy as np import pyarrow.parquet as pq import torch import torch.nn.functional as F from datasets.download.streaming_download_manager import xopen f...
628
20,572
fish-speech
fish_speech/datasets/protos/text_data_stream.py
.py
import struct from .text_data_pb2 import TextData def read_pb_stream(f): while True: buf = f.read(4) if len(buf) == 0: break size = struct.unpack("I", buf)[0] buf = f.read(size) text_data = TextData() text_data.ParseFromString(buf) yield text_da...
37
781
fish-speech
fish_speech/utils/logger.py
.py
import logging from typing import Mapping, Optional from lightning_utilities.core.rank_zero import rank_prefixed_message, rank_zero_only class RankedLogger(logging.LoggerAdapter): """A multi-GPU-friendly python command line logger.""" def __init__( self, name: str = __name__, rank_ze...
56
2,467
fish-speech
fish_speech/utils/utils.py
.py
import random import warnings from importlib.util import find_spec from typing import Callable import numpy as np import torch from omegaconf import DictConfig from .logger import RankedLogger from .rich_utils import enforce_tags, print_config_tree log = RankedLogger(__name__, rank_zero_only=True) def extras(cfg: ...
137
4,283
fish-speech
fish_speech/utils/braceexpand.py
.py
""" Bash-style brace expansion Copied from: https://github.com/trendels/braceexpand/blob/main/src/braceexpand/__init__.py License: MIT """ import re import string from itertools import chain, product from typing import Iterable, Iterator, Optional __all__ = ["braceexpand", "alphabet", "UnbalancedBracesError"] class...
218
6,724
fish-speech
fish_speech/utils/rich_utils.py
.py
from pathlib import Path from typing import Sequence import rich import rich.syntax import rich.tree from hydra.core.hydra_config import HydraConfig from lightning.pytorch.utilities import rank_zero_only from omegaconf import DictConfig, OmegaConf, open_dict from rich.prompt import Prompt from fish_speech.utils impor...
101
3,105
fish-speech
fish_speech/utils/__init__.py
.py
from .braceexpand import braceexpand from .context import autocast_exclude_mps from .file import get_latest_checkpoint from .instantiators import instantiate_callbacks, instantiate_loggers from .logger import RankedLogger from .logging_utils import log_hyperparameters from .rich_utils import enforce_tags, print_config_...
25
706
fish-speech
fish_speech/utils/logging_utils.py
.py
from lightning.pytorch.utilities import rank_zero_only from fish_speech.utils import logger as log @rank_zero_only def log_hyperparameters(object_dict: dict) -> None: """Controls which config parts are saved by lightning loggers. Additionally saves: - Number of model parameters """ hparams = {}...
49
1,384
fish-speech
fish_speech/utils/instantiators.py
.py
from typing import List import hydra from omegaconf import DictConfig from pytorch_lightning import Callback from pytorch_lightning.loggers import Logger from .logger import RankedLogger log = RankedLogger(__name__, rank_zero_only=True) def instantiate_callbacks(callbacks_cfg: DictConfig) -> List[Callback]: ""...
51
1,514
fish-speech
fish_speech/utils/schema.py
.py
import base64 import os import queue from dataclasses import dataclass from typing import Literal import torch from pydantic import BaseModel, Field, conint, model_validator from pydantic.functional_validators import SkipValidation from typing_extensions import Annotated from fish_speech.content_sequence import TextP...
139
3,912
fish-speech
fish_speech/utils/context.py
.py
from contextlib import nullcontext import torch def autocast_exclude_mps( device_type: str, dtype: torch.dtype ) -> nullcontext | torch.autocast: return ( nullcontext() if torch.backends.mps.is_available() else torch.autocast(device_type, dtype) )
14
287
fish-speech
fish_speech/utils/file.py
.py
import os from pathlib import Path from typing import Union from loguru import logger from natsort import natsorted AUDIO_EXTENSIONS = { ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".aiff", ".aif", ".aifc", } VIDEO_EXTENSIONS = { ".mp4", ".avi", } def ge...
140
3,354
fish-speech
fish_speech/utils/spectrogram.py
.py
import torch import torchaudio.functional as F from torch import Tensor, nn from torchaudio.transforms import MelScale class LinearSpectrogram(nn.Module): def __init__( self, n_fft=2048, win_length=2048, hop_length=512, center=False, mode="pow2_sqrt", ): ...
125
3,325
fish-speech
fish_speech/callbacks/grad_norm.py
.py
from typing import Optional, Union import lightning.pytorch as pl import torch from lightning import LightningModule, Trainer from lightning.pytorch.callbacks import Callback from torch import Tensor, nn from torch.utils._foreach_utils import ( _group_tensors_by_device_and_dtype, _has_foreach_support, ) @tor...
114
3,436
fish-speech
fish_speech/callbacks/__init__.py
.py
from .grad_norm import GradNormMonitor from .progress_bar import GradAccumProgressBar __all__ = ["GradNormMonitor", "GradAccumProgressBar"]
5
141
fish-speech
fish_speech/callbacks/progress_bar.py
.py
from lightning.pytorch.callbacks import TQDMProgressBar class GradAccumProgressBar(TQDMProgressBar): """ Progress bar that accounts for gradient accumulation so the total reflects actual forward passes rather than optimizer steps. """ @property def total_train_batches(self): total = s...
17
518
fish-speech
fish_speech/models/dac/rvq.py
.py
import math import typing as tp from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from dac.nn.quantize import ResidualVectorQuantize from torch.nn.utils.parametrizations import weight_norm from torch.nn.utils.parametrize import remove_parametrizations def unpad1d(x:...
400
13,143
fish-speech
fish_speech/models/dac/inference.py
.py
from pathlib import Path import click import hydra import numpy as np import pyrootutils import soundfile as sf import torch import torchaudio from hydra import compose, initialize from hydra.utils import instantiate from loguru import logger from omegaconf import OmegaConf pyrootutils.setup_root(__file__, indicator=...
127
3,895
fish-speech
fish_speech/models/dac/modded_dac.py
.py
import math import typing as tp from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from audiotools import AudioSignal from audiotools.ml import BaseModel from dac.model.base import CodecMixin from dac.nn.layers import Snake1d, WNConv1d, WNConvTranspose1d from tor...
1,046
35,062
fish-speech
fish_speech/models/text2semantic/inference.py
.py
import os import queue import re import threading import time import traceback from copy import deepcopy from dataclasses import dataclass from pathlib import Path from typing import Callable, Literal, Optional, Tuple, Union import click import numpy as np import torch import torch._inductor.config from loguru import ...
967
31,250
fish-speech
fish_speech/models/text2semantic/lit_module.py
.py
from typing import Any, Optional import lightning as L import torch import torch.nn.functional as F from lightning.pytorch.utilities.types import OptimizerLRScheduler import fish_speech.utils as utils CODEBOOK_PAD_TOKEN_ID = 0 from fish_speech.models.text2semantic.llama import NaiveTransformer log = utils.RankedLog...
211
6,935
fish-speech
fish_speech/models/text2semantic/lora.py
.py
from dataclasses import dataclass, field import loralib as lora @dataclass class LoraConfig: r: int lora_alpha: float lora_dropout: float = 0.0 # Valid values: "attention", "mlp", "embeddings", "output", # "fast_attention", "fast_mlp", "fast_embeddings", "fast_output" # Unprefix...
119
4,084
fish-speech
fish_speech/models/text2semantic/llama.py
.py
import dataclasses import json import math from collections import OrderedDict from dataclasses import dataclass from pathlib import Path from typing import Optional import torch import torch.nn as nn from einops import rearrange from loguru import logger from torch import Tensor from torch.nn import functional as F f...
1,039
36,007
sglang
experimental/sgl-router/tests/scripts/generate_kv_events_hash_parity.py
.py
""" Generator + validator for KV-event block-hash parity fixtures. Two modes: python3 experimental/sgl-router/tests/scripts/generate_kv_events_hash_parity.py Regenerate the committed JSON fixture from the locally-replicated algorithm. Run this when changing block-hash logic or adding new shape cov...
238
7,963
sglang
experimental/sgl-router/tests/scripts/generate_parity_fixtures.py
.py
""" One-shot generator for tokenizer parity fixtures. Run manually when adding a model or changing a prompt shape: python3 -m venv /tmp/parity-fixture-venv /tmp/parity-fixture-venv/bin/pip install transformers /tmp/parity-fixture-venv/bin/python experimental/sgl-router/tests/scripts/generate_parity_fixture...
116
4,277
sglang
experimental/sgl-router/tests/e2e/test_tokenize_smoke.py
.py
""" Smoke test for /v1/tokenize and /v1/detokenize round-trip. """ from __future__ import annotations import httpx MODEL = "Qwen/Qwen3-0.6B" TEXT = "Hello, world!" def test_tokenize_round_trip(router: str) -> None: """POST /v1/tokenize then /v1/detokenize must recover the original text.""" # Tokenize t...
38
1,053
sglang
experimental/sgl-router/tests/e2e/test_chat_smoke.py
.py
""" Smoke tests for /v1/models and /v1/chat/completions (streaming + non-streaming). """ from __future__ import annotations import httpx import pytest MODEL = "Qwen/Qwen3-0.6B" def test_models(router: str) -> None: """GET /v1/models must list the configured model.""" resp = httpx.get(f"{router}/v1/models",...
65
2,038
sglang
experimental/sgl-router/tests/e2e/conftest.py
.py
"""Pytest fixtures for ``experimental/sgl-router/tests/e2e/``. Two flavors of fixtures coexist here: 1. **Session-scoped sanity fixtures** (``sglang_server`` + ``router``) — launch ONE SGLang worker + ONE router on fixed ports for the whole test session. Used by the lightweight ``test_chat_smoke.py`` / ...
311
10,135
sglang
experimental/sgl-router/tests/e2e/infra/model_pool.py
.py
"""Minimal SGLang worker spawner for sgl-router e2e tests. Adapted from SMG's e2e_test/infra/model_pool.py — the 1200-line original manages a pool of long-lived workers across many tests; here we only need a thin wrapper around ``sglang.launch_server`` that: - allocates GPU(s) for the worker (via ``CUDA_VISIBLE_DEV...
218
6,964
sglang
experimental/sgl-router/tests/e2e/infra/gateway.py
.py
"""Minimal sgl-router Gateway class for e2e tests. sgl-router is a Rust binary (`experimental/sgl-router/target/release/sgl-router`) configured entirely through CLI flags. This Gateway execs the binary with `--worker-urls <...>` (static discovery) plus the model + policy flags. Supported lifecycles: - Regular mode:...
378
13,977
sglang
experimental/sgl-router/tests/e2e/infra/model_specs.py
.py
"""Model specifications for sgl-router e2e tests. Adapted from SMG's e2e_test/infra/model_specs.py. The same dict-of-dicts shape (so test code reads the same) but the entries are narrower — sgl-router tests today target small/medium models only; the larger function-calling / reasoning models from SMG are out of scope....
78
2,636
sglang
experimental/sgl-router/tests/e2e/k8s_integration/test_discovery.py
.py
"""E2E: sgl-router K8s discovery — basic routing. Verifies that sgl-router, configured with the k8s EndpointSlice backend, discovers the 3 fake-worker replicas deployed by setup.sh and successfully routes chat-completion requests to them. """ from __future__ import annotations import httpx import pytest from conftes...
85
2,613
sglang
experimental/sgl-router/tests/e2e/k8s_integration/test_reconciliation.py
.py
"""K8s discovery reconciliation integration tests. Tests verify that: 1. The K8s EndpointSlice watcher correctly discovers new workers as Services and backing Deployments are updated. 2. Workers are removed from the router's registry after the backing EndpointSlice entries disappear (pod deleted / deployment sca...
164
5,596
sglang
experimental/sgl-router/tests/e2e/k8s_integration/fake_worker.py
.py
"""Minimal fake SGLang worker for kind E2E integration testing. Responds to: GET /health -> {"status": "ok"} GET /server_info -> {"served_model_name": MODEL_ID} GET /v1/models -> list with a single MODEL_ID model entry POST /v1/chat/completions -> echoes th...
74
1,898
sglang
experimental/sgl-router/tests/e2e/k8s_integration/test_cross_namespace.py
.py
"""Cross-namespace service discovery integration test. Validates that a sgl-router instance with cluster-wide RBAC and no namespace filter in its k8s discovery config watches EndpointSlices in all namespaces. Workers deployed in a second namespace (sgl-router-test-extra) must be discovered alongside those in the prima...
226
7,785