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(random): """Test that bootstrapping gives the right answer in dumb cases.""" a_ones = np.ones(10) n_boot = 5 out1 = algo.bootstrap(a_ones, n_boot=n_boot) assert_array_equal(out1, np.ones(n_boot)) out2 = algo.bootstrap(a_ones, n_boot=n_boot, func=np.median) assert_array_equ...
Test that bootstrapping gives the right answer in dumb cases.
test_bootstrap
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_length(random): """Test that we get a bootstrap array of the right shape.""" a_norm = np.random.randn(1000) out = algo.bootstrap(a_norm) assert len(out) == 10000 n_boot = 100 out = algo.bootstrap(a_norm, n_boot=n_boot) assert len(out) == n_boot
Test that we get a bootstrap array of the right shape.
test_bootstrap_length
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_range(random): """Test that bootstrapping a random array stays within the right range.""" a_norm = np.random.randn(1000) amin, amax = a_norm.min(), a_norm.max() out = algo.bootstrap(a_norm) assert amin <= out.min() assert amax >= out.max()
Test that bootstrapping a random array stays within the right range.
test_bootstrap_range
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_multiarg(random): """Test that bootstrap works with multiple input arrays.""" x = np.vstack([[1, 10] for i in range(10)]) y = np.vstack([[5, 5] for i in range(10)]) def f(x, y): return np.vstack((x, y)).max(axis=0) out_actual = algo.bootstrap(x, y, n_boot=2, func=f) ...
Test that bootstrap works with multiple input arrays.
test_bootstrap_multiarg
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_axis(random): """Test axis kwarg to bootstrap function.""" x = np.random.randn(10, 20) n_boot = 100 out_default = algo.bootstrap(x, n_boot=n_boot) assert out_default.shape == (n_boot,) out_axis = algo.bootstrap(x, n_boot=n_boot, axis=0) assert out_axis.shape, (n_boot, x....
Test axis kwarg to bootstrap function.
test_bootstrap_axis
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_seed(random): """Test that we can get reproducible resamples by seeding the RNG.""" data = np.random.randn(50) seed = 42 boots1 = algo.bootstrap(data, seed=seed) boots2 = algo.bootstrap(data, seed=seed) assert_array_equal(boots1, boots2)
Test that we can get reproducible resamples by seeding the RNG.
test_bootstrap_seed
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
def test_bootstrap_ols(random): """Test bootstrap of OLS model fit.""" def ols_fit(X, y): XtXinv = np.linalg.inv(np.dot(X.T, X)) return XtXinv.dot(X.T).dot(y) X = np.column_stack((np.random.randn(50, 4), np.ones(50))) w = [2, 4, 0, 3, 5] y_noisy = np.dot(X, w) + np.random.randn(50) ...
Test bootstrap of OLS model fit.
test_bootstrap_ols
python
mwaskom/seaborn
tests/test_algorithms.py
https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py
BSD-3-Clause
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 get_contour_color(c): """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_color() elif isinstance(c, (mpl.collections.PathCollection, mpl.contour.QuadCon...
Provide compatability for change in contour artist types.
get_contour_color
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 cosy_jsonl_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 s...
Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}]
cosy_jsonl_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 cosy_jsonl_opener_vq0918_nopool(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: ass...
Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}]
cosy_jsonl_opener_vq0918_nopool
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 cosy_jsonl_opener_vq0918_pool2(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: asse...
Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}]
cosy_jsonl_opener_vq0918_pool2
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 cosy_jsonl_opener_vq0918_pool4(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: asse...
Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}]
cosy_jsonl_opener_vq0918_pool4
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 cosy_jsonl_opener_vq0918_pool8(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: asse...
Give url or local file, return file descriptor Inplace operation. Args: data(Iterable[str]): url or local file list Returns: Iterable[{src, stream}]
cosy_jsonl_opener_vq0918_pool8
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 filter_speech_token(data, max_length=10240, min_length=10, token_max_length=5000, token_min_length=1, min_output_input_ratio=0.0005, max_output_input_ratio=30, mode='train'): """ Filter sample according to feature and label length ...
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_speech_token
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 padding_speech_token(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...
Padding the data into training data Args: data: Iterable[List[{key, feat, label}]] Returns: Iterable[Tuple(keys, feats, labels, feats lengths, label lengths)]
padding_speech_token
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_speech_token_spk(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: as...
Padding the data into training data Args: data: Iterable[List[{key, feat, label}]] Returns: Iterable[Tuple(keys, feats, labels, feats lengths, label lengths)]
padding_speech_token_spk
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 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_dit.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/flow_matching_dit.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 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_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 __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_use_mask.py
https://github.com/THUDM/GLM-4-Voice/blob/master/cosyvoice/flow/stable/transformer_use_mask.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 rel_shift(self, x: torch.Tensor) -> torch.Tensor: """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. """ ...
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 __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_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 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 position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor: """ For getting encoding in a streaming fashion Attention!!!!! we apply dropout only once at the whole utterance level in a none streaming way, b...
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 __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 __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]: """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 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 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