id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
17,714 | import numpy as np
import torch
import torch.nn.functional as F
from torch.distributions import Normal
def to_one_hot(tensor, n, fill_with=1.0):
# we perform one hot encore with respect to the last axis
one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_()
if tensor.is_cuda:
one_hot = one_hot.cu... | Sample from (discretized) mixture of gaussian distributions Args: y (Tensor): B x C x T log_scale_min (float): Log scale minimum value Returns: Tensor: sample in range of [-1, 1]. |
17,715 | import humanfriendly
import numpy as np
import torch
def get_human_readable_count(number: int) -> str:
"""Return human_readable_count
Originated from:
https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/core/memory.py
Abbreviates an integer number with K, M, B, T for thou... | null |
17,716 | import os
import librosa
import torch
import numpy as np
from fairseq import checkpoint_utils
from tqdm import tqdm
import torch
def load_hubert_model(hps):
# Load model
ckpt_path = hps.hubert_file
print("Load Hubert Model...")
models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
... | null |
17,717 | import os
import librosa
import torch
import numpy as np
from fairseq import checkpoint_utils
from tqdm import tqdm
import torch
The provided code snippet includes necessary dependencies for implementing the `repeat_expand_2d` function. Write a Python function `def repeat_expand_2d(content, target_len)` to solve the f... | content : [hubert_dim(256), src_len] target: [hubert_dim(256), target_len] |
17,718 | import os
import librosa
import torch
import numpy as np
from fairseq import checkpoint_utils
from tqdm import tqdm
import torch
The provided code snippet includes necessary dependencies for implementing the `get_mapped_features` function. Write a Python function `def get_mapped_features(raw_content_features, mapping_... | Content Vector: frameshift = 20ms, hop_size = 480 in 24k Now it's only used for mapping to bigvgan's mels (sr = 24k, hop_size = 256, frameshift ~= 10.7 ms) |
17,719 | import os
import librosa
import torch
import numpy as np
from fairseq import checkpoint_utils
from tqdm import tqdm
import torch
def content_vector_encoder(model, audio_path, default_sampling_rate=16000):
"""
# content vector default sr: 16000
"""
wav16k, sr = librosa.load(audio_path, sr=default_samplin... | null |
17,720 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numbers
import re
import six
The provided code snippet includes necessary dependencies for implementing the `_cast_to_type_if_compatible` function. Write a Python function `def _cast_to_type_... | Cast hparam to the provided type, if compatible. Args: name: Name of the hparam to be cast. param_type: The type of the hparam. value: The value to be cast, if compatible. Returns: The result of casting `value` to `param_type`. Raises: ValueError: If the type of `value` is not compatible with param_type. * If `param_ty... |
17,721 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numbers
import re
import six
PARAM_RE = re.compile(
r"""
(?P<name>[a-zA-Z][\w\.]*) # variable name: "var" or "x"
(\[\s*(?P<index>\d+)\s*\])? # (optional) index: "1" or None
\s*... | Parses hyperparameter values from a string into a python map. `values` is a string containing comma-separated `name=value` pairs. For each pair, the value of the hyperparameter named `name` is set to `value`. If a hyperparameter name appears multiple times in `values`, a ValueError is raised (e.g. 'a=1,a=2', 'a[1]=1,a[... |
17,722 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import torchaudio
def extract_world_features(waveform, frameshift=10):
# waveform: (1, seq)
# x: (seq,)
x = np.array(waveform, dtype=np.double)
_f0, t = pw.dio(x, fs, fr... | null |
17,723 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import torchaudio
def get_mcep_params(fs):
"""Hyperparameters of transformation between SP and MCEP
Reference:
https://github.com/CSTR-Edinburgh/merlin/blob/master/misc/sc... | null |
17,724 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import torchaudio
def get_mcep_params(fs):
def mcep2sp(x, mcsize, fs):
fft_size, alpha = get_mcep_params(fs)
x = torch.as_tensor(x, dtype=torch.float)
tmp = diffsptk.MelGene... | null |
17,725 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import torchaudio
def f0_statistics(f0_features, path):
print("\nF0 statistics...")
total_f0 = []
for f0 in tqdm(f0_features):
total_f0 += [f for f in f0 if f != 0]
... | null |
17,726 | import torchaudio
import pyworld as pw
import numpy as np
import torch
import diffsptk
import os
from tqdm import tqdm
import pickle
import torchaudio
def world_synthesis(f0, sp, ap, fs, frameshift):
y = pw.synthesize(
f0, sp, ap, fs, frame_period=frameshift
) # synthesize an utterance using the param... | null |
17,727 | import librosa
import numpy as np
import torch
import parselmouth
import torchcrepe
import pyworld as pw
The provided code snippet includes necessary dependencies for implementing the `f0_to_coarse` function. Write a Python function `def f0_to_coarse(f0, pitch_bin, f0_min, f0_max)` to solve the following problem:
Conv... | Convert f0 (Hz) to pitch (mel scale), and then quantize the mel-scale pitch to the range from [1, 2, 3, ..., pitch_bin-1] Reference: https://en.wikipedia.org/wiki/Mel_scale Args: f0 (array or Tensor): Hz pitch_bin (int): the vocabulary size f0_min (int): the minimum f0 (Hz) f0_max (int): the maximum f0 (Hz) Returns: qu... |
17,728 | import librosa
import numpy as np
import torch
import parselmouth
import torchcrepe
import pyworld as pw
def get_log_f0(f0):
f0[np.where(f0 == 0)] = 1
log_f0 = np.log(f0)
return log_f0 | null |
17,729 | import librosa
import numpy as np
import torch
import parselmouth
import torchcrepe
import pyworld as pw
The provided code snippet includes necessary dependencies for implementing the `get_f0_features_using_harvest` function. Write a Python function `def get_f0_features_using_harvest(audio, mel_len, fs, hop_length, f0... | Using harvest to extract the f0 feature. Args: audio mel_len fs hop_length f0_min f0_max Returns: f0: numpy array of shape (frame_len,) |
17,730 | import librosa
import numpy as np
import torch
import parselmouth
import torchcrepe
import pyworld as pw
The provided code snippet includes necessary dependencies for implementing the `get_f0_features_using_crepe` function. Write a Python function `def get_f0_features_using_crepe( audio, mel_len, fs, hop_length, h... | Using torchcrepe to extract the f0 feature. Args: audio mel_len fs hop_length hop_length_new f0_min f0_max threshold(default=0.3) Returns: f0: numpy array of shape (frame_len,) |
17,731 | import librosa
import numpy as np
import torch
import parselmouth
import torchcrepe
import pyworld as pw
def get_cents(f0_hz):
"""
F_{cent} = 1200 * log2 (F/440)
Reference:
APSIPA'17, Perceptual Evaluation of Singing Quality
"""
voiced_f0 = f0_hz[f0_hz != 0]
return 1200 * np.log2(voiced_... | f0_hz: (,T) |
17,732 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `gaussian_normalize_mel_channel` function. Write a Python function `def gaussian_normalize_mel_channel(mel, mu, sigma)` to solve the following problem:
Shift to Standorm Normal Distribution Args: mel: (n_mels... | Shift to Standorm Normal Distribution Args: mel: (n_mels, frame_len) mu: (n_mels,), mean value sigma: (n_mels,), sd value Return: Tensor like mel |
17,733 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `de_gaussian_normalize_mel_channel` function. Write a Python function `def de_gaussian_normalize_mel_channel(mel, mu, sigma)` to solve the following problem:
Args: mel: (n_mels, frame_len) mu: (n_mels,), mean... | Args: mel: (n_mels, frame_len) mu: (n_mels,), mean value sigma: (n_mels,), sd value Return: Tensor like mel |
17,734 | import numpy as np
import torch
def decompress(audio_compressed, bits):
mu = 2**bits - 1
audio = np.sign(audio_compressed) / mu * ((1 + mu) ** np.abs(audio_compressed) - 1)
return audio | null |
17,735 | import numpy as np
import torch
def label_to_audio(quant, bits):
classes = 2**bits
audio = 2 * quant / (classes - 1.0) - 1.0
return audio | null |
17,736 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `label_to_onehot` function. Write a Python function `def label_to_onehot(x, bits)` to solve the following problem:
Converts a class vector (integers) to binary class matrix. Args: x: class vector to be conver... | Converts a class vector (integers) to binary class matrix. Args: x: class vector to be converted into a matrix (integers from 0 to num_classes). num_classes: total number of classes. Returns: A binary matrix representation of the input. The classes axis is placed last. |
17,737 | import torch
import torch.nn.functional as F
import numpy as np
from scipy.signal import get_window
from librosa.util import pad_center, tiny
from librosa.filters import mel as librosa_mel_fn
import torch
import numpy as np
import librosa.util as librosa_util
from scipy.signal import get_window
The provided code snipp... | # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms. Parameters ---------- window : string, tuple, number, callable, or list-like Window specification, as in `get_win... |
17,738 | import torch
import torch.nn.functional as F
import numpy as np
from scipy.signal import get_window
from librosa.util import pad_center, tiny
from librosa.filters import mel as librosa_mel_fn
import torch
import numpy as np
import librosa.util as librosa_util
from scipy.signal import get_window
The provided code snipp... | PARAMS ------ magnitudes: spectrogram magnitudes stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods |
17,739 | import torch
import torch.nn.functional as F
import numpy as np
from scipy.signal import get_window
from librosa.util import pad_center, tiny
from librosa.filters import mel as librosa_mel_fn
import torch
import numpy as np
import librosa.util as librosa_util
from scipy.signal import get_window
The provided code snipp... | PARAMS ------ C: compression factor |
17,740 | import torch
import torch.nn.functional as F
import numpy as np
from scipy.signal import get_window
from librosa.util import pad_center, tiny
from librosa.filters import mel as librosa_mel_fn
import torch
import numpy as np
import librosa.util as librosa_util
from scipy.signal import get_window
The provided code snipp... | PARAMS ------ C: compression factor used to compress |
17,741 | import os
import subprocess
from multiprocessing import Pool
from tqdm import tqdm
import torchaudio
from pathlib import Path
def remove_empty_dirs(path):
"""remove empty directories in a given path"""
# Check if the given path is a directory
if not os.path.isdir(path):
print(f"{path} is not a direc... | process wav files in parallel |
17,742 | import os
import subprocess
from multiprocessing import Pool
from tqdm import tqdm
import torchaudio
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `get_wav_files` function. Write a Python function `def get_wav_files(dataset_path)` to solve the following problem... | get all wav files in the dataset |
17,743 | import os
import subprocess
from multiprocessing import Pool
from tqdm import tqdm
import torchaudio
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `filter_wav_files_by_length` function. Write a Python function `def filter_wav_files_by_length(wav_files, max_len_... | filter wav files by length |
17,744 | import torch
def check_nan(logger, loss, y_pred, y_gt):
if torch.any(torch.isnan(loss)):
logger.info("out has nan: ", torch.any(torch.isnan(y_pred)))
logger.info("y_gt has nan: ", torch.any(torch.isnan(y_gt)))
logger.info("out: ", y_pred)
logger.info("y_gt: ", y_gt)
logger.i... | null |
17,745 | import os
import json
import numpy as np
from tqdm import tqdm
import torch
import torchaudio
from utils.io import save_audio
from utils.audio import load_audio_torch
def save_audio(path, waveform, fs, add_silence=False, turn_up=False, volume_peak=0.9):
"""Save audio to path with processing (turn up volume, add s... | Merge the given wav_files (may have overlaps) into a long audio fs: The sampling rate of the wav files. output_path: The output path to save the merged audio. overlap_duration (float, optional): Each segment has "overlap duration" (second) overlap with its previous and next segment. Defaults to 1.0. |
17,746 | import pathlib
import soundfile as sf
import numpy as np
import json
import multiprocessing
import tqdm
def cut_book(task):
"""process each book in the dataset"""
path_book, root_out, target_len_sec, extension = task
speaker = pathlib.Path(path_book.parent.name)
for i, meta_file_path in enumerate(path_b... | Main function to cut segments from audio files |
17,747 | import os
import numpy as np
import torch
import torchaudio
The provided code snippet includes necessary dependencies for implementing the `async_load_audio` function. Write a Python function `async def async_load_audio(path, sample_rate: int = 24000)` to solve the following problem:
r""" Args: path: The source loadin... | r""" Args: path: The source loading path. sample_rate: The target sample rate, will automatically resample if necessary. Returns: waveform: The waveform object. Should be [1 x sequence_len]. |
17,748 | import os
import numpy as np
import torch
import torchaudio
The provided code snippet includes necessary dependencies for implementing the `async_save_audio` function. Write a Python function `async def async_save_audio( path, waveform, sample_rate: int = 24000, add_silence: bool = False, volume_pe... | r""" Args: path: The target saving path. waveform: The waveform object. Should be [n_channel x sequence_len]. sample_rate: Sample rate. add_silence: If ``true``, concat 0.05s silence to beginning and end. volume_peak: Turn up volume for larger number, vice versa. |
17,749 | import torch
from tqdm import tqdm
import numpy as np
from transformers import Wav2Vec2FeatureExtractor
from transformers import AutoModel
import torchaudio
import torchaudio.transforms as T
from sklearn.preprocessing import StandardScaler
The provided code snippet includes necessary dependencies for implementing the ... | # mert default sr: 24000 |
17,750 | import torch
from tqdm import tqdm
import numpy as np
from transformers import Wav2Vec2FeatureExtractor
from transformers import AutoModel
import torchaudio
import torchaudio.transforms as T
from sklearn.preprocessing import StandardScaler
def mert_features_normalization(raw_mert_features):
normalized_mert_feature... | null |
17,751 | import torch
from tqdm import tqdm
import numpy as np
from transformers import Wav2Vec2FeatureExtractor
from transformers import AutoModel
import torchaudio
import torchaudio.transforms as T
from sklearn.preprocessing import StandardScaler
def get_mapped_mert_features(raw_mert_features, mapping_features, fast_mapping=... | null |
17,752 | import torch
from tqdm import tqdm
import numpy as np
from transformers import Wav2Vec2FeatureExtractor
from transformers import AutoModel
import torchaudio
import torchaudio.transforms as T
from sklearn.preprocessing import StandardScaler
def load_mert_model(hps):
print("Loading MERT Model: ", hps.mert_model)
... | null |
17,753 | import os
import pathlib
import string
import time
from multiprocessing import Pool, Value, Lock
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
import torch
import whisper
def asr_wav_files(file_list, gpu_id, total_files, model_id):
"""Transcribe wav files in a list"""
device = f"cuda:{gpu_id... | Transcribe wav files in a directory |
17,754 | import torch
from librosa.filters import mel as librosa_mel_fn
def spectral_normalize_torch(magnitudes):
output = dynamic_range_compression_torch(magnitudes)
return output
mel_basis = {}
hann_window = {}
The provided code snippet includes necessary dependencies for implementing the `mel_spectrogram_torch` func... | TODO: to merge this funtion with the extract_mel_features below |
17,755 | import time
import progressbar
from simtk import openmm, unit
from simtk.openmm import app
from openmmtools.integrators import LangevinIntegrator
output_prefix = 'output/'
with open(output_prefix + equilibrated_pdb_filename, 'w') as outfile:
app.PDBFile.writeFile(
pdb.topology,
context.getState(getP... | null |
17,756 | import time
import progressbar
from simtk import openmm, unit
from simtk.openmm import app
from openmmtools.integrators import LangevinIntegrator
output_prefix = 'output/'
with open(output_prefix + equilibrated_pdb_filename, 'w') as outfile:
app.PDBFile.writeFile(
pdb.topology,
context.getState(getP... | null |
17,757 | import math
from typing import Optional
import mlx.core as mx
import mlx.nn as nn
from .config import UNetConfig
def upsample_nearest(x, scale: int = 2):
B, H, W, C = x.shape
x = mx.broadcast_to(x[:, :, None, :, None, :], (B, H, scale, W, scale, C))
x = x.reshape(B, H * scale, W * scale, C)
return x | null |
17,758 | import mlx.core as mx
from .config import DiffusionConfig
def _linspace(a, b, num):
x = mx.arange(0, num) / (num - 1)
return (b - a) * x + a | null |
17,759 | import mlx.core as mx
from .config import DiffusionConfig
The provided code snippet includes necessary dependencies for implementing the `_interp` function. Write a Python function `def _interp(y, x_new)` to solve the following problem:
Interpolate the function defined by (arange(0, len(y)), y) at positions x_new.
He... | Interpolate the function defined by (arange(0, len(y)), y) at positions x_new. |
17,760 | import json
from functools import partial
from typing import Optional
import mlx.core as mx
from huggingface_hub import hf_hub_download
from mlx.utils import tree_unflatten
from .clip import CLIPTextModel
from .config import AutoencoderConfig, CLIPTextModelConfig, DiffusionConfig, UNetConfig
from .tokenizer import Toke... | Load the stable diffusion UNet from Hugging Face Hub. |
17,761 | import json
from functools import partial
from typing import Optional
import mlx.core as mx
from huggingface_hub import hf_hub_download
from mlx.utils import tree_unflatten
from .clip import CLIPTextModel
from .config import AutoencoderConfig, CLIPTextModelConfig, DiffusionConfig, UNetConfig
from .tokenizer import Toke... | Load the stable diffusion text encoder from Hugging Face Hub. |
17,762 | import json
from functools import partial
from typing import Optional
import mlx.core as mx
from huggingface_hub import hf_hub_download
from mlx.utils import tree_unflatten
from .clip import CLIPTextModel
from .config import AutoencoderConfig, CLIPTextModelConfig, DiffusionConfig, UNetConfig
from .tokenizer import Toke... | Load the stable diffusion autoencoder from Hugging Face Hub. |
17,763 | import json
from functools import partial
from typing import Optional
import mlx.core as mx
from huggingface_hub import hf_hub_download
from mlx.utils import tree_unflatten
from .clip import CLIPTextModel
from .config import AutoencoderConfig, CLIPTextModelConfig, DiffusionConfig, UNetConfig
from .tokenizer import Toke... | Load the stable diffusion config from Hugging Face Hub. |
17,764 | import json
from functools import partial
from typing import Optional
import mlx.core as mx
from huggingface_hub import hf_hub_download
from mlx.utils import tree_unflatten
from .clip import CLIPTextModel
from .config import AutoencoderConfig, CLIPTextModelConfig, DiffusionConfig, UNetConfig
from .tokenizer import Toke... | null |
17,765 | import argparse
import copy
import glob
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import torch
from mixtral import Mixtral, ModelArgs
from mlx.utils import tree_flatten, tree_map, tree_unflatten
def convert(tf, config):
def convert_single(k, v):... | null |
17,766 | import argparse
import copy
import glob
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import torch
from mixtral import Mixtral, ModelArgs
from mlx.utils import tree_flatten, tree_map, tree_unflatten
class ModelArgs(BaseModelArgs):
def __post_init__... | null |
17,767 | import argparse
import glob
import json
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_map, tree_unflatten
from sentencepiece import SentencePieceProcessor
class ModelArgs:
class Mixtral(nn.Module):... | null |
17,768 | import argparse
import glob
import json
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_map, tree_unflatten
from sentencepiece import SentencePieceProcessor
class Mixtral(nn.Module):
def __init__... | null |
17,769 | import argparse
import copy
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import torch
from mistral import Mistral, ModelArgs
from mlx.utils import tree_flatten, tree_map, tree_unflatten
def quantize(weights, config, args):
quantized_config = copy.d... | null |
17,770 | import argparse
import json
import time
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_unflatten
from sentencepiece import SentencePieceProcessor
class ModelArgs:
dim: int
n_layers: int
... | null |
17,771 | import argparse
import json
import time
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_unflatten
from sentencepiece import SentencePieceProcessor
class Mistral(nn.Module):
def __init__(self, arg... | null |
17,772 | import argparse
import glob
import json
import time
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
from decoder import SpeculativeDecoder
from mlx.utils import tree_unflatten
from model import Model
from transformers import T5Config
class Model(nn.Module):
def __init__(self, config: T5Config):
... | null |
17,773 | import numpy as np
from transformers import T5ForConditionalGeneration
def replace_key(key: str) -> str:
for old, new in SHARED_REPLACEMENT_PATTERNS:
key = key.replace(old, new)
if key.startswith("encoder."):
for old, new in ENCODER_REPLACEMENT_PATTERNS:
key = key.replace(old, new)
... | null |
17,774 | from typing import List, Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
import numpy as np
from mlx.utils import tree_map, tree_unflatten
from transformers import AutoTokenizer, T5Config
The provided code snippet includes necessary dependencies for implementing the `_relative_position_bucket` function. Writ... | Adapted from HF Tensorflow: https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py Translate relative position to a bucket number for relative attention. The relative position is defined as memory_position - query_position, i.e. the distance in tokens from the attending position... |
17,775 | from typing import List, Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
import numpy as np
from mlx.utils import tree_map, tree_unflatten
from transformers import AutoTokenizer, T5Config
def create_additive_causal_mask(N: int, offset: int = 0):
rinds = mx.arange(offset + N)
linds = mx.arange(offset,... | null |
17,776 | import sentencepiece as spm
import sentencepiece.sentencepiece_model_pb2 as model
def spm_tokenizer(metadata):
tokens = metadata["tokenizer.ggml.tokens"]
bos = metadata["tokenizer.ggml.bos_token_id"].item()
eos = metadata["tokenizer.ggml.eos_token_id"].item()
unk = metadata["tokenizer.ggml.unknown_toke... | null |
17,777 | from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import utils
from huggingface_hub import snapshot_download
from mlx.utils import tree_flatten, tree_unflatten
class ModelArgs:
hidden_size: in... | null |
17,778 | from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import utils
from huggingface_hub import snapshot_download
from mlx.utils import tree_flatten, tree_unflatten
class Model(nn.Module):
def __in... | null |
17,779 | import argparse
import time
import mlx.core as mx
import models
def generate(
model: models.Model,
tokenizer: models.GGUFTokenizer,
prompt: str,
max_tokens: int,
temp: float = 0.0,
):
prompt = tokenizer.encode(prompt)
tic = time.time()
tokens = []
skip = 0
for token, n in zip(
... | null |
17,780 | import argparse
import glob
import json
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_unflatten
from sentencepiece import SentencePieceProcessor
def tic():
return time.time()
def toc(msg,... | null |
17,781 | import argparse
import glob
import json
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Tuple
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_unflatten
from sentencepiece import SentencePieceProcessor
class ModelArgs:
dim: int
n_layers: in... | null |
17,782 | import argparse
import collections
import copy
import glob
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import torch
from llama import Llama, ModelArgs, sanitize_config
from mlx.utils import tree_flatten, tree_map, tree_unflatten
def torch_to_mx(a: torch.Tensor, *, dtype:... | null |
17,783 | import argparse
import collections
import copy
import glob
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import torch
from llama import Llama, ModelArgs, sanitize_config
from mlx.utils import tree_flatten, tree_map, tree_unflatten
def torch_to_mx(a: torch.Tensor, *, dtype:... | null |
17,784 | import argparse
import collections
import copy
import glob
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import torch
from llama import Llama, ModelArgs, sanitize_config
from mlx.utils import tree_flatten, tree_map, tree_unflatten
class ModelArgs(BaseModelArgs):
model... | null |
17,785 | import argparse
import collections
import copy
import glob
import json
import shutil
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import torch
from llama import Llama, ModelArgs, sanitize_config
from mlx.utils import tree_flatten, tree_map, tree_unflatten
def make_shards(weights: dict, max_file_s... | null |
17,786 | import argparse
import glob
import json
import shutil
from pathlib import Path
from typing import Optional
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import yaml
from mlx.utils import tree_flatten, tree_map
from .utils import (
fetch_from_hub,
get_model_path,
save_config,
save_weights,... | Configures and returns the argument parser for the script. Returns: argparse.ArgumentParser: Configured argument parser. |
17,787 | import argparse
import glob
import json
import shutil
from pathlib import Path
from typing import Optional
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import yaml
from mlx.utils import tree_flatten, tree_map
from .utils import (
fetch_from_hub,
get_model_path,
save_config,
save_weights,... | null |
17,788 | import copy
import glob
import importlib
import json
import logging
import shutil
import time
from pathlib import Path
from textwrap import dedent
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import mlx.core as mx
import mlx.nn as nn
from huggingface_hub import snapshot_download
from ... | Generate text from the model. Args: model (nn.Module): The language model. tokenizer (PreTrainedTokenizer): The tokenizer. prompt (str): The string prompt. temp (float): The temperature for sampling (default 0). max_tokens (int): The maximum number of tokens (default 100). verbose (bool): If ``True``, print tokens and ... |
17,789 | import copy
import glob
import importlib
import json
import logging
import shutil
import time
from pathlib import Path
from textwrap import dedent
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
import mlx.core as mx
import mlx.nn as nn
from huggingface_hub import snapshot_download
from ... | null |
17,790 | import argparse
import glob
import json
import shutil
from pathlib import Path
from typing import Any, Dict, Union
from mlx.utils import tree_flatten, tree_unflatten
from .tuner.lora import LoRALinear
from .tuner.utils import apply_lora_layers, dequantize
from .utils import (
fetch_from_hub,
get_model_path,
... | null |
17,791 | import argparse
from .utils import convert
The provided code snippet includes necessary dependencies for implementing the `configure_parser` function. Write a Python function `def configure_parser() -> argparse.ArgumentParser` to solve the following problem:
Configures and returns the argument parser for the script. R... | Configures and returns the argument parser for the script. Returns: argparse.ArgumentParser: Configured argument parser. |
17,792 | import os
from typing import Dict
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_unflatten
from .lora import LoRALinear
The provided code snippet includes necessary dependencies for implementing the `dequantize` function. Write a Python function `def dequantize(model: nn.Module) -> nn.Module` to ... | Dequantize the quantized linear layers in the model. Args: model (nn.Module): The model with quantized linear layers. Returns: nn.Module: The model with dequantized layers. |
17,793 | import os
from typing import Dict
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_unflatten
from .lora import LoRALinear
class LoRALinear(nn.Module):
def from_linear(
linear: nn.Linear,
r: int = 8,
alpha: float = 16,
dropout: float = 0.0,
scale: float = ... | Remove the LoRA layers from the model. Args: model (nn.Module): The model with LoRA layers. Returns: nn.Module: The model without LoRA layers. |
17,794 | import time
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
import mlx.core as mx
import mlx.nn as nn
import numpy as np
from mlx.utils import tree_flatten
def iterate_batches(dataset, tokenizer, batch_size, max_seq_length, train=False):
# Sort by length:
idx = s... | null |
17,795 | import argparse
import json
import time
import uuid
import warnings
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import List, Literal, NamedTuple, Optional, Union
import mlx.core as mx
import mlx.nn as nn
from transformers import PreTrainedTokenizer
from .utils import generate_step, load
class... | Determines whether the token generation should stop based on predefined conditions. Args: tokens (List[int]): The current sequence of generated tokens. stop_id_sequences (List[List[[int]]): A list of integer lists, each representing a sequence of token IDs. If the end of the `tokens` list matches any of these sequences... |
17,796 | import argparse
import json
import time
import uuid
import warnings
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import List, Literal, NamedTuple, Optional, Union
import mlx.core as mx
import mlx.nn as nn
from transformers import PreTrainedTokenizer
from .utils import generate_step, load
def ... | null |
17,797 | import argparse
import json
import time
import uuid
import warnings
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import List, Literal, NamedTuple, Optional, Union
import mlx.core as mx
import mlx.nn as nn
from transformers import PreTrainedTokenizer
from .utils import generate_step, load
class... | null |
17,798 | import argparse
import json
import math
import re
import types
from pathlib import Path
import mlx.optimizers as optim
import numpy as np
import yaml
from mlx.utils import tree_flatten
from .tuner.trainer import TrainingArgs, TrainingCallback, evaluate, train
from .tuner.utils import linear_to_lora_layers
from .utils i... | null |
17,799 | import argparse
import json
import math
import re
import types
from pathlib import Path
import mlx.optimizers as optim
import numpy as np
import yaml
from mlx.utils import tree_flatten
from .tuner.trainer import TrainingArgs, TrainingCallback, evaluate, train
from .tuner.utils import linear_to_lora_layers
from .utils i... | null |
17,800 | import argparse
import mlx.core as mx
from .utils import generate, load
DEFAULT_PROMPT = "hello"
DEFAULT_MAX_TOKENS = 100
DEFAULT_TEMP = 0.6
DEFAULT_TOP_P = 1.0
DEFAULT_SEED = 0
The provided code snippet includes necessary dependencies for implementing the `setup_arg_parser` function. Write a Python function `def setu... | Set up and return the argument parser. |
17,801 | import argparse
import mlx.core as mx
from .utils import generate, load
def colorprint(color, s):
def colorprint_by_t0(s, t0):
if t0 > 0.95:
color = "white"
elif t0 > 0.70:
color = "green"
elif t0 > 0.30:
color = "yellow"
else:
color = "red"
colorprint(color, s) | null |
17,802 | from functools import partial
import mlx.core as mx
import mlx.nn as nn
def rms_norm(x, weight, eps):
x = x.astype(mx.float32)
x = x * mx.rsqrt(x.square().mean(-1, keepdims=True) + eps)
return weight * x.astype(weight.dtype) | null |
17,803 | from functools import partial
import mlx.core as mx
import mlx.nn as nn
The provided code snippet includes necessary dependencies for implementing the `ln_norm` function. Write a Python function `def ln_norm(x, eps, weight=None, bias=None)` to solve the following problem:
Layer normalization for input tensor x. Args: ... | Layer normalization for input tensor x. Args: x (np.ndarray): Input tensor. eps (float, optional): Small value to avoid division by zero. weight (np.ndarray, optional): Weight tensor for normalization. bias (np.ndarray, optional): Bias tensor for normalization. Returns: np.ndarray: Normalized tensor. |
17,804 | from dataclasses import dataclass
from functools import partial
from typing import Dict, Optional, Tuple, Union
import mlx.core as mx
import mlx.nn as nn
from .base import BaseModelArgs
def rms_norm(x, weight, eps):
x = x.astype(mx.float32)
x = x * mx.rsqrt(x.square().mean(-1, keepdims=True) + eps)
return ... | null |
17,805 | import argparse
import time
from functools import partial
import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
import resnet
from dataset import get_cifar10
def train_epoch(model, train_iter, optimizer, epoch):
def train_step(model, inp, tgt):
output = model(inp)
loss = mx.mean(... | null |
17,806 | import argparse
import time
from functools import partial
import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
import resnet
from dataset import get_cifar10
def eval_fn(model, inp, tgt):
return mx.mean(mx.argmax(model(inp), axis=1) == tgt)
def test_epoch(model, test_iter, epoch):
accs = []
... | null |
17,807 | import numpy as np
from mlx.data.datasets import load_cifar10
def get_cifar10(batch_size, root=None):
tr = load_cifar10(root=root)
mean = np.array([0.485, 0.456, 0.406]).reshape((1, 1, 3))
std = np.array([0.229, 0.224, 0.225]).reshape((1, 1, 3))
def normalize(x):
x = x.astype("float32") / 255... | null |
17,808 | from typing import Any
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_flatten
class Block(nn.Module):
"""
Implements a ResNet block with two convolutional layers and a skip connection.
As per the paper, CIFAR-10 uses Shortcut type-A skip connections. (See paper for details)
"""
... | null |
17,809 | from typing import Any
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_flatten
class Block(nn.Module):
"""
Implements a ResNet block with two convolutional layers and a skip connection.
As per the paper, CIFAR-10 uses Shortcut type-A skip connections. (See paper for details)
"""
... | null |
17,810 | from typing import Any
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_flatten
class Block(nn.Module):
"""
Implements a ResNet block with two convolutional layers and a skip connection.
As per the paper, CIFAR-10 uses Shortcut type-A skip connections. (See paper for details)
"""
... | null |
17,811 | from typing import Any
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_flatten
class Block(nn.Module):
"""
Implements a ResNet block with two convolutional layers and a skip connection.
As per the paper, CIFAR-10 uses Shortcut type-A skip connections. (See paper for details)
"""
... | null |
17,812 | from typing import Any
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_flatten
class Block(nn.Module):
"""
Implements a ResNet block with two convolutional layers and a skip connection.
As per the paper, CIFAR-10 uses Shortcut type-A skip connections. (See paper for details)
"""
... | null |
17,813 | from typing import Any
import mlx.core as mx
import mlx.nn as nn
from mlx.utils import tree_flatten
class Block(nn.Module):
"""
Implements a ResNet block with two convolutional layers and a skip connection.
As per the paper, CIFAR-10 uses Shortcut type-A skip connections. (See paper for details)
"""
... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.