code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_bootstrap_units(random): """Test that results make sense when passing unit IDs to bootstrap.""" data = np.random.randn(50) ids = np.repeat(range(10), 5) bwerr = np.random.normal(0, 2, 10) bwerr = bwerr[ids] data_rm = data + bwerr seed = 77 boots_orig = algo.bootstrap(data_rm, s...
Test that results make sense when passing unit IDs to bootstrap.
test_bootstrap_units
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_string_func(): """Test that named numpy methods are the same as the numpy function.""" x = np.random.randn(100) res_a = algo.bootstrap(x, func="mean", seed=0) res_b = algo.bootstrap(x, func=np.mean, seed=0) assert np.array_equal(res_a, res_b) res_a = algo.bootstrap(x, func="...
Test that named numpy methods are the same as the numpy function.
test_bootstrap_string_func
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_reproducibility(random): """Test that bootstrapping uses the internal random state.""" data = np.random.randn(50) boots1 = algo.bootstrap(data, seed=100) boots2 = algo.bootstrap(data, seed=100) assert_array_equal(boots1, boots2) random_state1 = np.random.RandomState(200) ...
Test that bootstrapping uses the internal random state.
test_bootstrap_reproducibility
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def get_contour_coords(c, filter_empty=False): """Provide compatability for change in contour artist types.""" if isinstance(c, mpl.collections.LineCollection): # See https://github.com/matplotlib/matplotlib/issues/20906 return c.get_segments() elif isinstance(c, (mpl.collections.PathCollect...
Provide compatability for change in contour artist types.
get_contour_coords
python
mwaskom/seaborn
tests/test_distributions.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_distributions.py
BSD-3-Clause
def integrate(y, x): """"Simple numerical integration for testing KDE code.""" y = np.asarray(y) x = np.asarray(x) dx = np.diff(x) return (dx * y[:-1] + dx * y[1:]).sum() / 2
"Simple numerical integration for testing KDE code.
integrate
python
mwaskom/seaborn
tests/test_distributions.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_distributions.py
BSD-3-Clause
def example_method(self): """An example method. Parameters ---------- a : str A method parameter. """
An example method. Parameters ---------- a : str A method parameter.
example_method
python
mwaskom/seaborn
tests/test_docstrings.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_docstrings.py
BSD-3-Clause
def example_func(): """An example function. Parameters ---------- a : str A function parameter. """
An example function. Parameters ---------- a : str A function parameter.
example_func
python
mwaskom/seaborn
tests/test_docstrings.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_docstrings.py
BSD-3-Clause
def test_mask_limits(self): """Make sure masked cells are not used to calculate extremes""" kws = self.default_kws.copy() mask = self.x_norm > 0 kws['mask'] = mask p = mat._HeatMapper(self.x_norm, **kws) assert p.vmax == np.ma.array(self.x_norm, mask=mask).max() ...
Make sure masked cells are not used to calculate extremes
test_mask_limits
python
mwaskom/seaborn
tests/test_matrix.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_matrix.py
BSD-3-Clause
def has_verdana(): """Helper to verify if Verdana font is present""" # This import is relatively lengthy, so to prevent its import for # testing other tests in this module not requiring this knowledge, # import font_manager here import matplotlib.font_manager as mplfm try: verdana_font =...
Helper to verify if Verdana font is present
has_verdana
python
mwaskom/seaborn
tests/test_rcmod.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_rcmod.py
BSD-3-Clause
def _network(t=None, url="https://github.com"): """ Decorator that will skip a test if `url` is unreachable. Parameters ---------- t : function, optional url : str, optional """ if t is None: return lambda x: _network(x, url=url) def wrapper(*args, **kwargs): # att...
Decorator that will skip a test if `url` is unreachable. Parameters ---------- t : function, optional url : str, optional
_network
python
mwaskom/seaborn
tests/test_utils.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_utils.py
BSD-3-Clause
def test_to_utf8(s, exp): """Test the to_utf8 function: object to string""" u = utils.to_utf8(s) assert isinstance(u, str) assert u == exp
Test the to_utf8 function: object to string
test_to_utf8
python
mwaskom/seaborn
tests/test_utils.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_utils.py
BSD-3-Clause
def process(self, audio_data, last=False): """ Add audio data and process it params: audio_data: audio data in numpy array last: whether this is the last chunk of data returns: Processed audio data, returns None if no split point is found """ ...
Add audio data and process it params: audio_data: audio data in numpy array last: whether this is the last chunk of data returns: Processed audio data, returns None if no split point is found
process
python
THUDM/GLM-4-Voice
audio_process.py
https://github.com/THUDM/GLM-4-Voice/blob/master/audio_process.py
Apache-2.0
def _find_silence_boundary(self, audio): """ Find the starting point of silence boundary in audio """ # Convert audio to decibels db = librosa.amplitude_to_db(np.abs(audio), ref=np.max) # Find points below threshold silence_points = np.where(db < self.thr...
Find the starting point of silence boundary in audio
_find_silence_boundary
python
THUDM/GLM-4-Voice
audio_process.py
https://github.com/THUDM/GLM-4-Voice/blob/master/audio_process.py
Apache-2.0
def _find_silence_end(self, start_point): """ Find the end point of silence segment """ db = librosa.amplitude_to_db(np.abs(self.buffer[start_point:]), ref=np.max) silence_points = np.where(db >= self.threshold_db)[0] if len(silence_points) == 0: retu...
Find the end point of silence segment
_find_silence_end
python
THUDM/GLM-4-Voice
audio_process.py
https://github.com/THUDM/GLM-4-Voice/blob/master/audio_process.py
Apache-2.0
def __iter__(self): """ Return an iterator over the source dataset processed by the given processor. """ assert self.source is not None assert callable(self.f) return self.f(iter(self.source), *self.args, **self.kw)
Return an iterator over the source dataset processed by the given processor.
__iter__
python
THUDM/GLM-4-Voice
cosyvoice/dataset/dataset.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/dataset.py
Apache-2.0
def sample(self, data): """ Sample data according to rank/world_size/num_workers Args: data(List): input data list Returns: List: data list after sample """ data = list(range(len(data))) # force datalist even if self.parti...
Sample data according to rank/world_size/num_workers Args: data(List): input data list Returns: List: data list after sample
sample
python
THUDM/GLM-4-Voice
cosyvoice/dataset/dataset.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/dataset.py
Apache-2.0
def Dataset(data_list_file, data_pipeline, mode='train', shuffle=True, partition=True, tts_file='', prompt_utt2data=''): """ Construct dataset from arguments We have two shuffle stage in the Dataset. The first is global shuffle...
Construct dataset from arguments We have two shuffle stage in the Dataset. The first is global shuffle at shards tar/raw file level. The second is global shuffle at training samples level. Args: data_type(str): raw/shard tokenizer (BaseTokenizer): tokenizer to ...
Dataset
python
THUDM/GLM-4-Voice
cosyvoice/dataset/dataset.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/dataset.py
Apache-2.0
def parquet_opener(data, mode='train', tts_data={}): """ Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}] """ for sample in data: assert 'src' in samp...
Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}]
parquet_opener
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def filter(data, max_length=10240, min_length=10, token_max_length=200, token_min_length=1, min_output_input_ratio=0.0005, max_output_input_ratio=1, mode='train'): """ Filter sample according to feature and label length Inplace ope...
Filter sample according to feature and label length Inplace operation. Args:: data: Iterable[{key, wav, label, sample_rate}] max_length: drop utterance which is greater than max_length(10ms) min_length: drop utterance which is less than min_length(10ms) ...
filter
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def resample(data, resample_rate=22050, min_sample_rate=16000, mode='train'): """ Resample data. Inplace operation. Args: data: Iterable[{key, wav, label, sample_rate}] resample_rate: target resample rate Returns: Iterable[{key, wav, label, sample_rate}]...
Resample data. Inplace operation. Args: data: Iterable[{key, wav, label, sample_rate}] resample_rate: target resample rate Returns: Iterable[{key, wav, label, sample_rate}]
resample
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def compute_fbank(data, feat_extractor, mode='train'): """ Extract fbank Args: data: Iterable[{key, wav, label, sample_rate}] Returns: Iterable[{key, feat, label}] """ for sample in data: assert 'sample_rate' in sample ...
Extract fbank Args: data: Iterable[{key, wav, label, sample_rate}] Returns: Iterable[{key, feat, label}]
compute_fbank
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def parse_embedding(data, normalize, mode='train'): """ Parse utt_embedding/spk_embedding Args: data: Iterable[{key, wav, label, sample_rate}] Returns: Iterable[{key, feat, label}] """ for sample in data: sample['utt_embedding'] = torch.tensor(sample['utt_em...
Parse utt_embedding/spk_embedding Args: data: Iterable[{key, wav, label, sample_rate}] Returns: Iterable[{key, feat, label}]
parse_embedding
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def tokenize(data, get_tokenizer, allowed_special, mode='train'): """ Decode text to chars or BPE Inplace operation Args: data: Iterable[{key, wav, txt, sample_rate}] Returns: Iterable[{key, wav, txt, tokens, label, sample_rate}] """ tokenizer = get_tokenize...
Decode text to chars or BPE Inplace operation Args: data: Iterable[{key, wav, txt, sample_rate}] Returns: Iterable[{key, wav, txt, tokens, label, sample_rate}]
tokenize
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def shuffle(data, shuffle_size=10000, mode='train'): """ Local shuffle the data Args: data: Iterable[{key, feat, label}] shuffle_size: buffer size for shuffle Returns: Iterable[{key, feat, label}] """ buf = [] for sample in data: buf.append(s...
Local shuffle the data Args: data: Iterable[{key, feat, label}] shuffle_size: buffer size for shuffle Returns: Iterable[{key, feat, label}]
shuffle
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def sort(data, sort_size=500, mode='train'): """ Sort the data by feature length. Sort is used after shuffle and before batch, so we can group utts with similar lengths into a batch, and `sort_size` should be less than `shuffle_size` Args: data: Iterable[{key, feat, labe...
Sort the data by feature length. Sort is used after shuffle and before batch, so we can group utts with similar lengths into a batch, and `sort_size` should be less than `shuffle_size` Args: data: Iterable[{key, feat, label}] sort_size: buffer size for sort ...
sort
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def static_batch(data, batch_size=16): """ Static batch the data by `batch_size` Args: data: Iterable[{key, feat, label}] batch_size: batch size Returns: Iterable[List[{key, feat, label}]] """ buf = [] for sample in data: buf.append(sample) ...
Static batch the data by `batch_size` Args: data: Iterable[{key, feat, label}] batch_size: batch size Returns: Iterable[List[{key, feat, label}]]
static_batch
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def dynamic_batch(data, max_frames_in_batch=12000, mode='train'): """ Dynamic batch the data until the total frames in batch reach `max_frames_in_batch` Args: data: Iterable[{key, feat, label}] max_frames_in_batch: max_frames in one batch Returns: Iterab...
Dynamic batch the data until the total frames in batch reach `max_frames_in_batch` Args: data: Iterable[{key, feat, label}] max_frames_in_batch: max_frames in one batch Returns: Iterable[List[{key, feat, label}]]
dynamic_batch
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def padding(data, use_spk_embedding, mode='train'): """ Padding the data into training data Args: data: Iterable[List[{key, feat, label}]] Returns: Iterable[Tuple(keys, feats, labels, feats lengths, label lengths)] """ for sample in data: assert isinstance(s...
Padding the data into training data Args: data: Iterable[List[{key, feat, label}]] Returns: Iterable[Tuple(keys, feats, labels, feats lengths, label lengths)]
padding
python
THUDM/GLM-4-Voice
cosyvoice/dataset/processor.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/dataset/processor.py
Apache-2.0
def __init__( self, in_channels, out_channels, channels=(256, 256), dropout=0.05, attention_head_dim=64, n_blocks=1, num_mid_blocks=2, num_heads=4, act_fn="snake", ): """ This decoder requires an input with the same shap...
This decoder requires an input with the same shape of the target. So, if your text content is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
__init__
python
THUDM/GLM-4-Voice
cosyvoice/flow/decoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/decoder.py
Apache-2.0
def forward(self, x, mask, mu, t, spks=None, cond=None): """Forward pass of the UNet1DConditional model. Args: x (torch.Tensor): shape (batch_size, in_channels, time) mask (_type_): shape (batch_size, 1, time) t (_type_): shape (batch_size) spks (_type_, ...
Forward pass of the UNet1DConditional model. Args: x (torch.Tensor): shape (batch_size, in_channels, time) mask (_type_): shape (batch_size, 1, time) t (_type_): shape (batch_size) spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None...
forward
python
THUDM/GLM-4-Voice
cosyvoice/flow/decoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/decoder.py
Apache-2.0
def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None): """Forward diffusion Args: mu (torch.Tensor): output of encoder shape: (batch_size, n_feats, mel_timesteps) mask (torch.Tensor): output_mask shape: (batch_size, 1, me...
Forward diffusion Args: mu (torch.Tensor): output of encoder shape: (batch_size, n_feats, mel_timesteps) mask (torch.Tensor): output_mask shape: (batch_size, 1, mel_timesteps) n_timesteps (int): number of diffusion steps temperatur...
forward
python
THUDM/GLM-4-Voice
cosyvoice/flow/flow_matching.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/flow_matching.py
Apache-2.0
def solve_euler(self, x, t_span, mu, mask, spks, cond): """ Fixed euler solver for ODEs. Args: x (torch.Tensor): random noise t_span (torch.Tensor): n_timesteps interpolated shape: (n_timesteps + 1,) mu (torch.Tensor): output of encoder ...
Fixed euler solver for ODEs. Args: x (torch.Tensor): random noise t_span (torch.Tensor): n_timesteps interpolated shape: (n_timesteps + 1,) mu (torch.Tensor): output of encoder shape: (batch_size, n_feats, mel_timesteps) ma...
solve_euler
python
THUDM/GLM-4-Voice
cosyvoice/flow/flow_matching.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/flow_matching.py
Apache-2.0
def compute_loss(self, x1, mask, mu, spks=None, cond=None): """Computes diffusion loss Args: x1 (torch.Tensor): Target shape: (batch_size, n_feats, mel_timesteps) mask (torch.Tensor): target mask shape: (batch_size, 1, mel_timesteps) m...
Computes diffusion loss Args: x1 (torch.Tensor): Target shape: (batch_size, n_feats, mel_timesteps) mask (torch.Tensor): target mask shape: (batch_size, 1, mel_timesteps) mu (torch.Tensor): output of encoder shape: (batch_size,...
compute_loss
python
THUDM/GLM-4-Voice
cosyvoice/flow/flow_matching.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/flow_matching.py
Apache-2.0
def solve_euler(self, x, t_span, mu, mask, spks, cond): """ Fixed euler solver for ODEs. Args: x (torch.Tensor): random noise torch.Size([1, 80, 621]) t_span (torch.Tensor): n_timesteps interpolated shape: (n_timesteps + 1,) mu (torch.Tensor):...
Fixed euler solver for ODEs. Args: x (torch.Tensor): random noise torch.Size([1, 80, 621]) t_span (torch.Tensor): n_timesteps interpolated shape: (n_timesteps + 1,) mu (torch.Tensor): output of encoder shape: (batch_size, n_feats, mel...
solve_euler
python
THUDM/GLM-4-Voice
cosyvoice/flow/flow_matching_dit.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/flow_matching_dit.py
Apache-2.0
def pad_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0): """Pad for a convolution to make sure that the last window is full. Extra padding is added at the end. This is required to ensure that we can rebuild an output of the same length, as otherwise, even with padding, som...
Pad for a convolution to make sure that the last window is full. Extra padding is added at the end. This is required to ensure that we can rebuild an output of the same length, as otherwise, even with padding, some time steps might get removed. For instance, with total padding = 4, kernel size = 4, stri...
pad_for_conv1d
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/adp.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/adp.py
Apache-2.0
def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'constant', value: float = 0.): """Tiny wrapper around F.pad, just to allow for reflect padding on small input. If this is the case, we insert extra 0 padding to the right before the reflection happen. """ length = x.shape[-1] padd...
Tiny wrapper around F.pad, just to allow for reflect padding on small input. If this is the case, we insert extra 0 padding to the right before the reflection happen.
pad1d
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/adp.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/adp.py
Apache-2.0
def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]): """Remove padding from x, handling properly zero padding. Only for 1d!""" padding_left, padding_right = paddings assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right) assert (padding_left + padding_right) <= x.shape[-1]...
Remove padding from x, handling properly zero padding. Only for 1d!
unpad1d
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/adp.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/adp.py
Apache-2.0
def get_channels( self, channels_list: Optional[Sequence[Tensor]] = None, layer: int = 0 ) -> Optional[Tensor]: """Gets context channels at `layer` and checks that shape is correct""" use_context_channels = self.use_context_channels and self.has_context[layer] if not use_context_chan...
Gets context channels at `layer` and checks that shape is correct
get_channels
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/adp.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/adp.py
Apache-2.0
def get_mapping( self, time: Optional[Tensor] = None, features: Optional[Tensor] = None ) -> Optional[Tensor]: """Combines context time features and features into mapping""" items, mapping = [], None # Compute time features if self.use_context_time: assert_message...
Combines context time features and features into mapping
get_mapping
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/adp.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/adp.py
Apache-2.0
def sample_discrete_euler(model, x, steps, sigma_max=1, **extra_args): """Draws samples from a model given starting noise. Euler method""" # Make tensor of ones to broadcast the single t values ts = x.new_ones([x.shape[0]]) # Create the noise schedule t = torch.linspace(sigma_max, 0, steps + 1) ...
Draws samples from a model given starting noise. Euler method
sample_discrete_euler
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/sampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/sampling.py
Apache-2.0
def sample(model, x, steps, eta, **extra_args): """Draws samples from a model given starting noise. v-diffusion""" ts = x.new_ones([x.shape[0]]) # Create the noise schedule t = torch.linspace(1, 0, steps + 1)[:-1] alphas, sigmas = get_alphas_sigmas(t) # The sampling loop for i in trange(s...
Draws samples from a model given starting noise. v-diffusion
sample
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/sampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/sampling.py
Apache-2.0
def __init__(self, dim, bias=False, fix_scale=False): """ bias-less layernorm has been shown to be more stable. most newer models have moved towards rmsnorm, also bias-less """ super().__init__() if fix_scale: self.register_buffer("gamma", torch.ones(dim)) el...
bias-less layernorm has been shown to be more stable. most newer models have moved towards rmsnorm, also bias-less
__init__
python
THUDM/GLM-4-Voice
cosyvoice/flow/stable/transformer.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/transformer.py
Apache-2.0
def forward(self, x): """ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) F0_sampled (batchsize, length, 1) Sine_source (batchsize, length, 1) noise_source (batchsize, length 1) """ # source for harmonic branch with torch.no_grad(): s...
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) F0_sampled (batchsize, length, 1) Sine_source (batchsize, length, 1) noise_source (batchsize, length 1)
forward
python
THUDM/GLM-4-Voice
cosyvoice/hifigan/generator.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/hifigan/generator.py
Apache-2.0
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False): ''' Initialization. INPUT: - in_features: shape of the input - alpha: trainable parameter alpha is initialized to 1 by default, higher values = higher-frequency. ...
Initialization. INPUT: - in_features: shape of the input - alpha: trainable parameter alpha is initialized to 1 by default, higher values = higher-frequency. alpha will be trained along with the rest of your model.
__init__
python
THUDM/GLM-4-Voice
cosyvoice/transformer/activation.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/activation.py
Apache-2.0
def forward_qkv( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Transform query, key and value. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor ...
Transform query, key and value. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor (#batch, time2, size). value (torch.Tensor): Value tensor (#batch, time2, size). Returns: torch.Tensor: Transformed query tenso...
forward_qkv
python
THUDM/GLM-4-Voice
cosyvoice/transformer/attention.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/attention.py
Apache-2.0
def forward_attention( self, value: torch.Tensor, scores: torch.Tensor, mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool) ) -> torch.Tensor: """Compute attention context vector. Args: value (torch.Tensor): Transformed value, size ...
Compute attention context vector. Args: value (torch.Tensor): Transformed value, size (#batch, n_head, time2, d_k). scores (torch.Tensor): Attention score, size (#batch, n_head, time1, time2). mask (torch.Tensor): Mask, size (#batch, 1, time2)...
forward_attention
python
THUDM/GLM-4-Voice
cosyvoice/transformer/attention.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/attention.py
Apache-2.0
def forward( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool), pos_emb: torch.Tensor = torch.empty(0), cache: torch.Tensor = torch.zeros((0, 0, 0, 0)) ) -> Tuple[torch.Tensor, torch...
Compute scaled dot product attention. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor (#batch, time2, size). value (torch.Tensor): Value tensor (#batch, time2, size). mask (torch.Tensor): Mask tensor (#batch, 1, time...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/attention.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/attention.py
Apache-2.0
def rel_shift(self, x): """Compute relative positional encoding. Args: x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1). time1 means the length of query vector. Returns: torch.Tensor: Output tensor. """ zero_pad = torch.zeros((...
Compute relative positional encoding. Args: x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1). time1 means the length of query vector. Returns: torch.Tensor: Output tensor.
rel_shift
python
THUDM/GLM-4-Voice
cosyvoice/transformer/attention.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/attention.py
Apache-2.0
def forward( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool), pos_emb: torch.Tensor = torch.empty(0), cache: torch.Tensor = torch.zeros((0, 0, 0, 0)) ) -> Tuple[torch.Tensor, torch...
Compute 'Scaled Dot Product Attention' with rel. positional encoding. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor (#batch, time2, size). value (torch.Tensor): Value tensor (#batch, time2, size). mask (torch.Tensor...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/attention.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/attention.py
Apache-2.0
def __init__(self, channels: int, kernel_size: int = 15, activation: nn.Module = nn.ReLU(), norm: str = "batch_norm", causal: bool = False, bias: bool = True): """Construct an ConvolutionModule object. ...
Construct an ConvolutionModule object. Args: channels (int): The number of channels of conv layers. kernel_size (int): Kernel size of conv layers. causal (int): Whether use causal convolution or not
__init__
python
THUDM/GLM-4-Voice
cosyvoice/transformer/convolution.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/convolution.py
Apache-2.0
def forward( self, x: torch.Tensor, mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool), cache: torch.Tensor = torch.zeros((0, 0, 0)), ) -> Tuple[torch.Tensor, torch.Tensor]: """Compute convolution module. Args: x (torch.Tensor): Input tensor ...
Compute convolution module. Args: x (torch.Tensor): Input tensor (#batch, time, channels). mask_pad (torch.Tensor): used for batch padding (#batch, 1, time), (0, 0, 0) means fake mask. cache (torch.Tensor): left context cache, it is only used i...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/convolution.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/convolution.py
Apache-2.0
def forward( self, memory: torch.Tensor, memory_mask: torch.Tensor, ys_in_pad: torch.Tensor, ys_in_lens: torch.Tensor, r_ys_in_pad: torch.Tensor = torch.empty(0), reverse_weight: float = 0.0, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """For...
Forward decoder. Args: memory: encoded memory, float32 (batch, maxlen_in, feat) memory_mask: encoder memory mask, (batch, 1, maxlen_in) ys_in_pad: padded input token ids, int64 (batch, maxlen_out) ys_in_lens: input lengths of this batch (batch) r_ys_i...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/decoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/decoder.py
Apache-2.0
def forward_one_step( self, memory: torch.Tensor, memory_mask: torch.Tensor, tgt: torch.Tensor, tgt_mask: torch.Tensor, cache: Optional[List[torch.Tensor]] = None, ) -> Tuple[torch.Tensor, List[torch.Tensor]]: """Forward one step. This is only used...
Forward one step. This is only used for decoding. Args: memory: encoded memory, float32 (batch, maxlen_in, feat) memory_mask: encoded memory mask, (batch, 1, maxlen_in) tgt: input token ids, int64 (batch, maxlen_out) tgt_mask: input token mask, (batc...
forward_one_step
python
THUDM/GLM-4-Voice
cosyvoice/transformer/decoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/decoder.py
Apache-2.0
def tie_or_clone_weights(self, jit_mode: bool = True): """Tie or clone module weights (between word_emb and output_layer) depending of whether we are using TorchScript or not""" if not self.use_output_layer: return if jit_mode: logging.info("clone emb.weight t...
Tie or clone module weights (between word_emb and output_layer) depending of whether we are using TorchScript or not
tie_or_clone_weights
python
THUDM/GLM-4-Voice
cosyvoice/transformer/decoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/decoder.py
Apache-2.0
def forward( self, memory: torch.Tensor, memory_mask: torch.Tensor, ys_in_pad: torch.Tensor, ys_in_lens: torch.Tensor, r_ys_in_pad: torch.Tensor, reverse_weight: float = 0.0, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Forward decoder. ...
Forward decoder. Args: memory: encoded memory, float32 (batch, maxlen_in, feat) memory_mask: encoder memory mask, (batch, 1, maxlen_in) ys_in_pad: padded input token ids, int64 (batch, maxlen_out) ys_in_lens: input lengths of this batch (batch) r_ys_i...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/decoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/decoder.py
Apache-2.0
def forward( self, tgt: torch.Tensor, tgt_mask: torch.Tensor, memory: torch.Tensor, memory_mask: torch.Tensor, cache: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Compute decoded features. Args: ...
Compute decoded features. Args: tgt (torch.Tensor): Input tensor (#batch, maxlen_out, size). tgt_mask (torch.Tensor): Mask for input tensor (#batch, maxlen_out). memory (torch.Tensor): Encoded memory (#batch, maxlen_in, size). memo...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/decoder_layer.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/decoder_layer.py
Apache-2.0
def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) \ -> Tuple[torch.Tensor, torch.Tensor]: """Add positional encoding. Args: x (torch.Tensor): Input. Its shape is (batch, time, ...) offset (int, torch.tensor): pos...
Add positional encoding. Args: x (torch.Tensor): Input. Its shape is (batch, time, ...) offset (int, torch.tensor): position offset Returns: torch.Tensor: Encoded tensor. Its shape is (batch, time, ...) torch.Tensor: for compatibility to RelPositionalEnc...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/embedding.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/embedding.py
Apache-2.0
def position_encoding(self, offset: Union[int, torch.Tensor], size: int, apply_dropout: bool = True) -> torch.Tensor: """ For getting encoding in a streaming fashion Attention!!!!! we apply dropout only once at the wh...
For getting encoding in a streaming fashion Attention!!!!! we apply dropout only once at the whole utterance level in a none streaming way, but will call this function several times with increasing input size in a streaming scenario, so the dropout will be applied several times...
position_encoding
python
THUDM/GLM-4-Voice
cosyvoice/transformer/embedding.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/embedding.py
Apache-2.0
def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) \ -> Tuple[torch.Tensor, torch.Tensor]: """Compute positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Enc...
Compute positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Encoded tensor (batch, time, `*`). torch.Tensor: Positional embedding tensor (1, time, `*`).
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/embedding.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/embedding.py
Apache-2.0
def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) \ -> Tuple[torch.Tensor, torch.Tensor]: """ Just return zero vector for interface compatibility """ pos_emb = torch.zeros(1, x.size(1), self.d_model).to(x.device) return s...
Just return zero vector for interface compatibility
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/embedding.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/embedding.py
Apache-2.0
def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0): """Add positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Encoded tensor (batch, time, `*`). """ self.extend_pe(x) x = x ...
Add positional encoding. Args: x (torch.Tensor): Input tensor (batch, time, `*`). Returns: torch.Tensor: Encoded tensor (batch, time, `*`).
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/embedding.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/embedding.py
Apache-2.0
def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, inpu...
Args: input_size (int): input dim output_size (int): dimension of attention attention_heads (int): the number of heads of multi head attention linear_units (int): the hidden units number of position-wise feed forward num_blocks (int): ...
__init__
python
THUDM/GLM-4-Voice
cosyvoice/transformer/encoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/encoder.py
Apache-2.0
def forward( self, xs: torch.Tensor, xs_lens: torch.Tensor, decoding_chunk_size: int = 0, num_decoding_left_chunks: int = -1, ) -> Tuple[torch.Tensor, torch.Tensor]: """Embed positions in tensor. Args: xs: padded input tensor (B, T, D) ...
Embed positions in tensor. Args: xs: padded input tensor (B, T, D) xs_lens: input length (B) decoding_chunk_size: decoding chunk size for dynamic chunk 0: default for training, use random dynamic chunk. <0: for decoding, use full chunk. ...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/encoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/encoder.py
Apache-2.0
def forward_chunk( self, xs: torch.Tensor, offset: int, required_cache_size: int, att_cache: torch.Tensor = torch.zeros(0, 0, 0, 0), cnn_cache: torch.Tensor = torch.zeros(0, 0, 0, 0), att_mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool), ) -> Tuple...
Forward just one chunk Args: xs (torch.Tensor): chunk input, with shape (b=1, time, mel-dim), where `time == (chunk_size - 1) * subsample_rate + subsample.right_context + 1` offset (int): current offset in encoder output time stamp re...
forward_chunk
python
THUDM/GLM-4-Voice
cosyvoice/transformer/encoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/encoder.py
Apache-2.0
def forward_chunk_by_chunk( self, xs: torch.Tensor, decoding_chunk_size: int, num_decoding_left_chunks: int = -1, ) -> Tuple[torch.Tensor, torch.Tensor]: """ Forward input chunk by chunk with chunk_size like a streaming fashion Here we should pay special ...
Forward input chunk by chunk with chunk_size like a streaming fashion Here we should pay special attention to computation cache in the streaming style forward chunk by chunk. Three things should be taken into account for computation in the current network: 1. transforme...
forward_chunk_by_chunk
python
THUDM/GLM-4-Voice
cosyvoice/transformer/encoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/encoder.py
Apache-2.0
def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, inpu...
Construct TransformerEncoder See Encoder for the meaning of each parameter.
__init__
python
THUDM/GLM-4-Voice
cosyvoice/transformer/encoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/encoder.py
Apache-2.0
def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, inpu...
Construct ConformerEncoder Args: input_size to use_dynamic_chunk, see in BaseEncoder positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer. macaron_style (bool): Whether to use macaron style for positionwise layer. ...
__init__
python
THUDM/GLM-4-Voice
cosyvoice/transformer/encoder.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/encoder.py
Apache-2.0
def forward(self, x: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """Compute loss between x and target. The model outputs and data labels tensors are flatten to (batch*seqlen, class) shape and a mask is applied to the padding part which should not be calculated for loss. ...
Compute loss between x and target. The model outputs and data labels tensors are flatten to (batch*seqlen, class) shape and a mask is applied to the padding part which should not be calculated for loss. Args: x (torch.Tensor): prediction (batch, seqlen, class) t...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/label_smoothing_loss.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/label_smoothing_loss.py
Apache-2.0
def forward(self, xs: torch.Tensor) -> torch.Tensor: """Foward function. Args: xs: input tensor (B, L, D) Returns: output tensor, (B, L, D) """ B, L, D = xs.size( ) # batch size, sequence length, embedding dimension (idim) xs = xs.view(-1...
Foward function. Args: xs: input tensor (B, L, D) Returns: output tensor, (B, L, D)
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/positionwise_feed_forward.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/positionwise_feed_forward.py
Apache-2.0
def forward( self, x: torch.Tensor, x_mask: torch.Tensor, offset: Union[int, torch.Tensor] = 0 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Input x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): ...
Input x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Returns: torch.Tensor: linear input tensor (#batch, time', odim), where time' = time . torch.Tensor: linear input mas...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/subsampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/subsampling.py
Apache-2.0
def forward( self, x: torch.Tensor, x_mask: torch.Tensor, offset: Union[int, torch.Tensor] = 0 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tenso...
Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 2. torch.Tensor: Subsampled...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/subsampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/subsampling.py
Apache-2.0
def forward( self, x: torch.Tensor, x_mask: torch.Tensor, offset: Union[int, torch.Tensor] = 0 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tenso...
Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 4. torch.Tensor: Subsampled...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/subsampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/subsampling.py
Apache-2.0
def forward( self, x: torch.Tensor, x_mask: torch.Tensor, offset: Union[int, torch.Tensor] = 0 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor...
Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 6. torch.Tensor: Subsampled ...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/subsampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/subsampling.py
Apache-2.0
def forward( self, x: torch.Tensor, x_mask: torch.Tensor, offset: Union[int, torch.Tensor] = 0 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tenso...
Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 8. torch.Tensor: Subsampled...
forward
python
THUDM/GLM-4-Voice
cosyvoice/transformer/subsampling.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/transformer/subsampling.py
Apache-2.0
def pad_list(xs: List[torch.Tensor], pad_value: int): """Perform padding for the list of tensors. Args: xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)]. pad_value (float): Value for padding. Returns: Tensor: Padded tensor (B, Tmax, `*`). Examples: ...
Perform padding for the list of tensors. Args: xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)]. pad_value (float): Value for padding. Returns: Tensor: Padded tensor (B, Tmax, `*`). Examples: >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)] ...
pad_list
python
THUDM/GLM-4-Voice
cosyvoice/utils/common.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/common.py
Apache-2.0
def th_accuracy(pad_outputs: torch.Tensor, pad_targets: torch.Tensor, ignore_label: int) -> torch.Tensor: """Calculate accuracy. Args: pad_outputs (Tensor): Prediction tensors (B * Lmax, D). pad_targets (LongTensor): Target label tensors (B, Lmax). ignore_label (int): Ig...
Calculate accuracy. Args: pad_outputs (Tensor): Prediction tensors (B * Lmax, D). pad_targets (LongTensor): Target label tensors (B, Lmax). ignore_label (int): Ignore label id. Returns: torch.Tensor: Accuracy value (0.0 - 1.0).
th_accuracy
python
THUDM/GLM-4-Voice
cosyvoice/utils/common.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/common.py
Apache-2.0
def subsequent_mask( size: int, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size). This mask is used only in decoder which works in an auto-regressive mode. This means the current step could only do attention with its left steps....
Create mask for subsequent steps (size, size). This mask is used only in decoder which works in an auto-regressive mode. This means the current step could only do attention with its left steps. In encoder, fully attention is used when streaming is not necessary and the sequence is not long. In this c...
subsequent_mask
python
THUDM/GLM-4-Voice
cosyvoice/utils/mask.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py
Apache-2.0
def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int = -1, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: size (int): size ...
Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: size (int): size of mask chunk_size (int): size of chunk num_left_chunks (int): number of left chunks <0: use full chunk >=0: use num_left_chunks device ...
subsequent_chunk_mask
python
THUDM/GLM-4-Voice
cosyvoice/utils/mask.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py
Apache-2.0
def add_optional_chunk_mask(xs: torch.Tensor, masks: torch.Tensor, use_dynamic_chunk: bool, use_dynamic_left_chunk: bool, decoding_chunk_size: int, static_chunk_size: int, ...
Apply optional mask for encoder. Args: xs (torch.Tensor): padded input, (B, L, D), L for max length mask (torch.Tensor): mask for xs, (B, 1, L) use_dynamic_chunk (bool): whether to use dynamic chunk or not use_dynamic_left_chunk (bool): whether to use dynamic left chunk for ...
add_optional_chunk_mask
python
THUDM/GLM-4-Voice
cosyvoice/utils/mask.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py
Apache-2.0
def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor: """Make mask tensor containing indices of padded part. See description of make_non_pad_mask. Args: lengths (torch.Tensor): Batch of lengths (B,). Returns: torch.Tensor: Mask tensor containing indices of padded ...
Make mask tensor containing indices of padded part. See description of make_non_pad_mask. Args: lengths (torch.Tensor): Batch of lengths (B,). Returns: torch.Tensor: Mask tensor containing indices of padded part. Examples: >>> lengths = [5, 3, 2] >>> make_pad_mask(leng...
make_pad_mask
python
THUDM/GLM-4-Voice
cosyvoice/utils/mask.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/mask.py
Apache-2.0
def __init__(self, optimizer, *, max_steps, decay_rate=0.5, min_lr=0.0, last_epoch=-1, **kwargs): """ From Nemo: Implementation of the Noam Hold Annealing policy from th...
From Nemo: Implementation of the Noam Hold Annealing policy from the SqueezeFormer paper. Unlike NoamAnnealing, the peak learning rate can be explicitly set for this scheduler. The schedule first performs linear warmup, then holds the peak LR, then decays with s...
__init__
python
THUDM/GLM-4-Voice
cosyvoice/utils/scheduler.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/utils/scheduler.py
Apache-2.0
def _median_filter(inputs: torch.Tensor, filter_width: int) -> torch.Tensor: """ Applies a median filter of width `filter_width` along the last dimension of the input. The `inputs` tensor is assumed to be 3- or 4-dimensional. """ if filter_width <= 0 or filter_width % 2 != 1: raise ValueErr...
Applies a median filter of width `filter_width` along the last dimension of the input. The `inputs` tensor is assumed to be 3- or 4-dimensional.
_median_filter
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def _dynamic_time_warping(matrix: np.ndarray): """ Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate token-level timestamps. """ output_length, input_length = matrix.shape cost = np.ones((output_length + 1, input_length + 1), dtype=np.flo...
Measures similarity between two temporal sequences: the input audio and the output tokens. Used to generate token-level timestamps.
_dynamic_time_warping
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def _extract_token_timestamps(self, generate_outputs, alignment_heads, time_precision=0.02, num_frames=None): """ Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to map each output token to a position in the input audio. If `num_frames`...
Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to map each output token to a position in the input audio. If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW. Returns: ...
_extract_token_timestamps
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def generate( self, input_features: Optional[torch.Tensor] = None, generation_config: Optional[GenerationConfig] = None, logits_processor: Optional[LogitsProcessorList] = None, stopping_criteria: Optional[StoppingCriteriaList] = None, prefix_allowed_tokens_fn: Optional[Ca...
Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids. <Tip warning={true}> Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model's default generation configuration. You ca...
generate
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def replace_or_add(lst: List[int], num: int, itr: Iterator[int]): """short function to replace num with a itr in lst""" found = any(i in lst for i in itr) if found: lst = [num if i in itr else i for i in lst] else: lst.append(num) ...
short function to replace num with a itr in lst
replace_or_add
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def detect_language( self, input_features: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, encoder_outputs: Optional[Union[torch.FloatTensor, BaseModelOutput]] = None, generation_config: Optional[GenerationConfig] = None, num_segment...
Detects language from log-mel input features or encoder_outputs Parameters: input_features (`torch.Tensor` of shape `(batch_size, feature_size, sequence_length)`, *optional*): Float values of log-mel features extracted from the raw speech waveform. The raw speech waveform c...
detect_language
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def _retrieve_compression_ratio(tokens, vocab_size): """Compute byte length of zlib compressed token bytes vs. byte length of raw token bytes""" length = int(math.log2(vocab_size) / 8) + 1 token_bytes = b"".join([t.to_bytes(length, "little") for t in tokens.tolist()]) compression_ratio =...
Compute byte length of zlib compressed token bytes vs. byte length of raw token bytes
_retrieve_compression_ratio
python
THUDM/GLM-4-Voice
speech_tokenizer/generation_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/generation_whisper.py
Apache-2.0
def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, device: torch.device, min_dtype: float, cache_position: torch.Tensor, batch_size: int, ): """ Cre...
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. Args: attention_mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, ke...
_prepare_4d_causal_attention_mask_with_cache_position
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() shifted_input_ids[:, 0] = decoder_start_t...
Shift input ids one token to the right.
shift_tokens_right
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def _compute_mask_indices( shape: Tuple[int, int], mask_prob: float, mask_length: int, attention_mask: Optional[torch.LongTensor] = None, min_masks: int = 0, ) -> np.ndarray: """ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data A...
Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: shape: T...
_compute_mask_indices
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def compute_num_masked_span(input_length): """Given input length, compute how many spans should be masked""" num_masked_span = int(mask_prob * input_length / mask_length + epsilon) num_masked_span = max(num_masked_span, min_masks) # make sure num masked span <= sequence_length i...
Given input length, compute how many spans should be masked
compute_num_masked_span
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, layer_head_mask: torch.Tensor, output_attentions: bool = False, ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer o...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. ...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, layer_head_mask: Optional[torch.Tensor] = No...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. ...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, input_features, attention_mask=None, head_mask=None, output_attentions=None, output_hidden_states=None, return_dict=None, quantized_token_ids=None ): r""" Args: input_featur...
Args: input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`): Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a `.flac` or `.wav` audio file into an array of type ...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, input_ids=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, head_mask=None, cross_attn_head_mask=None, past_key_values=None, inputs_embeds=None, po...
Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`WhisperTokenizer`]. See [`Pre...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def _mask_input_features( self, input_features: torch.FloatTensor, attention_mask: Optional[torch.LongTensor] = None, ): """ Masks extracted features along time axis and/or along feature axis according to [SpecAugment](https://arxiv.org/abs/1904.08779). ...
Masks extracted features along time axis and/or along feature axis according to [SpecAugment](https://arxiv.org/abs/1904.08779).
_mask_input_features
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, input_features: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Op...
Returns: Example: ```python >>> import torch >>> from transformers import AutoFeatureExtractor, WhisperModel >>> from datasets import load_dataset >>> model = WhisperVQModel.from_pretrained("openai/whisper-base") >>> feature_extractor = AutoFeatur...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, input_features: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Op...
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the l...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None, head_mask: Optional[torch.Tensor] = None, cross_attn_head_mask: Optional[torch.Tensor]...
Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.enc...
forward
python
THUDM/GLM-4-Voice
speech_tokenizer/modeling_whisper.py
https://github.com/THUDM/GLM-4-Voice/blob/master/speech_tokenizer/modeling_whisper.py
Apache-2.0