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_equal(out2, np.ones(n_boot))
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) out_wanted = np.array([[5, 10], [5, 10]]) assert_array_equal(out_actual, out_wanted)
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.shape[1])
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) * 20 y_lownoise = np.dot(X, w) + np.random.randn(50) n_boot = 500 w_boot_noisy = algo.bootstrap(X, y_noisy, n_boot=n_boot, func=ols_fit) w_boot_lownoise = algo.bootstrap(X, y_lownoise, n_boot=n_boot, func=ols_fit) assert w_boot_noisy.shape == (n_boot, 5) assert w_boot_lownoise.shape == (n_boot, 5) assert w_boot_noisy.std() > w_boot_lownoise.std()
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, seed=seed) boots_rm = algo.bootstrap(data_rm, units=ids, seed=seed) assert boots_rm.std() > boots_orig.std()
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="std", seed=0) res_b = algo.bootstrap(x, func=np.std, seed=0) assert np.array_equal(res_a, res_b) with pytest.raises(AttributeError): algo.bootstrap(x, func="not_a_method_name")
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) boots1 = algo.bootstrap(data, seed=random_state1) random_state2 = np.random.RandomState(200) boots2 = algo.bootstrap(data, seed=random_state2) assert_array_equal(boots1, boots2) with pytest.warns(UserWarning): # Deprecated, remove when removing random_seed boots1 = algo.bootstrap(data, random_seed=100) boots2 = algo.bootstrap(data, random_seed=100) assert_array_equal(boots1, boots2)
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.PathCollection, mpl.contour.QuadContourSet)): return [ p.vertices[:np.argmax(p.codes) + 1] for p in c.get_paths() if len(p) or not filter_empty ]
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.QuadContourSet)): if c.get_facecolor().size: return c.get_facecolor() else: return c.get_edgecolor()
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() assert p.vmin == np.ma.array(self.x_norm, mask=mask).min() mask = self.x_norm < 0 kws['mask'] = mask p = mat._HeatMapper(self.x_norm, **kws) assert p.vmin == np.ma.array(self.x_norm, mask=mask).min() 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 = mplfm.findfont('Verdana', fallback_to_default=False) except: # noqa # if https://github.com/matplotlib/matplotlib/pull/3435 # gets accepted return False # otherwise check if not matching the logic for a 'default' one try: unlikely_font = mplfm.findfont("very_unlikely_to_exist1234", fallback_to_default=False) except: # noqa # if matched verdana but not unlikely, Verdana must exist return True # otherwise -- if they match, must be the same default return verdana_font != unlikely_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): # attempt to connect try: f = urlopen(url) except (OSError, HTTPException): pytest.skip("No internet connection") else: f.close() return t(*args, **kwargs) return wrapper
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 new data to buffer self.buffer = np.concatenate([self.buffer, audio_data]) if len(self.buffer) > 0 else audio_data if last: result = self.buffer self.buffer = np.array([]) return self._to_wav_bytes(result) # Find silence boundary split_point = self._find_silence_boundary(self.buffer) if split_point is not None: # Modified: Extend split point to the end of silence silence_end = self._find_silence_end(split_point) result = self.buffer[:silence_end] self.buffer = self.buffer[silence_end:] return self._to_wav_bytes(result) return None
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.threshold_db)[0] if len(silence_points) == 0: return None # Calculate minimum silence samples min_silence_samples = int(self.min_silence_duration * self.sr) # Search backwards for continuous silence segment starting point for i in range(len(silence_points) - min_silence_samples, -1, -1): if i < 0: break if np.all(np.diff(silence_points[i:i+min_silence_samples]) == 1): return silence_points[i] return None
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: return len(self.buffer) return start_point + silence_points[0]
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.partition: if self.shuffle: random.Random(self.epoch).shuffle(data) if len(data) < self.world_size: data = data * math.ceil(self.world_size / len(data)) data = data[:self.world_size] data = data[self.rank::self.world_size] if len(data) < self.num_workers: data = data * math.ceil(self.num_workers / len(data)) data = data[:self.num_workers] data = data[self.worker_id::self.num_workers] return data
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 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 tokenize partition(bool): whether to do data partition in terms of rank """ assert mode in ['train', 'inference'] lists = read_lists(data_list_file) # import pdb # pdb.set_trace() if mode == 'inference': with open(tts_file) as f: tts_data = json.load(f) utt2lists = read_json_lists(prompt_utt2data) # filter unnecessary file in inference mode lists = list(set([utt2lists[utt] for utt in tts_data.keys() if utt2lists[utt] in lists])) dataset = DataList(lists,shuffle=shuffle,partition=partition) if mode == 'inference': # map partial arg tts_data in inference mode data_pipeline[0] = partial(data_pipeline[0], tts_data=tts_data) for func in data_pipeline: dataset = Processor(dataset, func, mode=mode) return dataset
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 tokenize partition(bool): whether to do data partition in terms of rank
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 sample url = sample['src'] try: df = pq.read_table(url).to_pandas() for i in range(len(df)): if mode == 'inference' and df.loc[i, 'utt'] not in tts_data: continue sample.update(dict(df.loc[i])) if mode == 'train': # NOTE do not return sample directly, must initialize a new dict yield {**sample} else: for index, text in enumerate(tts_data[df.loc[i, 'utt']]): yield {**sample, 'tts_index': index, 'tts_text': text} except Exception as ex: logging.warning('Failed to open {}, ex info {}'.format(url, ex))
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 sample cosy_jsonl_path = sample['src'] tar_file_path=cosy_jsonl_path.replace(".vq0907.jsonl",".tar") try: tar_data=Tar(Path(tar_file_path)) with open(cosy_jsonl_path, 'r') as f: for line in f: item=json.loads(line) cosy_token = item['cosy_token'] sample['speech_token']=torch.tensor(cosy_token) sample['speech'], sample['sample_rate']= torchaudio.load(io.BytesIO(tar_data.read(item['filename']))) # print(item['filename']) yield {**sample} except Exception as ex: logging.warning('Failed to open {}, ex info {}'.format(cosy_jsonl_path, ex))
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: assert 'src' in sample cosy_jsonl_path = sample['src'] tar_file_path=cosy_jsonl_path.replace(".vq0918-nopool.jsonl",".tar") try: tar_data=Tar(Path(tar_file_path)) with open(cosy_jsonl_path, 'r') as f: # cosy_data = [json.loads(line) for line in f] for line in f: item=json.loads(line) cosy_token = item['cosy_token'] sample['speech_token']=torch.tensor(cosy_token) sample['speech'], sample['sample_rate']= torchaudio.load(io.BytesIO(tar_data.read(item['filename']))) # print(item['filename']) yield {**sample} except Exception as ex: logging.warning('Failed to open {}, ex info {}'.format(cosy_jsonl_path, ex))
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: assert 'src' in sample cosy_jsonl_path = sample['src'] tar_file_path=cosy_jsonl_path.replace(".vq0918-pool2.jsonl",".tar") try: tar_data=Tar(Path(tar_file_path)) with open(cosy_jsonl_path, 'r') as f: for line in f: item=json.loads(line) cosy_token = item['cosy_token'] sample['speech_token']=torch.tensor(cosy_token) sample['speech'], sample['sample_rate']= torchaudio.load(io.BytesIO(tar_data.read(item['filename']))) yield {**sample} except Exception as ex: logging.warning('Failed to open {}, ex info {}'.format(cosy_jsonl_path, ex))
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: assert 'src' in sample cosy_jsonl_path = sample['src'] tar_file_path=cosy_jsonl_path.replace(".vq0918-pool4.jsonl",".tar") try: tar_data=Tar(Path(tar_file_path)) with open(cosy_jsonl_path, 'r') as f: # cosy_data = [json.loads(line) for line in f] for line in f: item=json.loads(line) cosy_token = item['cosy_token'] sample['speech_token']=torch.tensor(cosy_token) sample['speech'], sample['sample_rate']= torchaudio.load(io.BytesIO(tar_data.read(item['filename']))) # print(item['filename']) yield {**sample} except Exception as ex: logging.warning('Failed to open {}, ex info {}'.format(cosy_jsonl_path, ex))
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: assert 'src' in sample cosy_jsonl_path = sample['src'] tar_file_path=cosy_jsonl_path.replace(".vq0918-pool8.jsonl",".tar") try: tar_data=Tar(Path(tar_file_path)) with open(cosy_jsonl_path, 'r') as f: # cosy_data = [json.loads(line) for line in f] for line in f: item=json.loads(line) cosy_token = item['cosy_token'] sample['speech_token']=torch.tensor(cosy_token) sample['speech'], sample['sample_rate']= torchaudio.load(io.BytesIO(tar_data.read(item['filename']))) # print(item['filename']) yield {**sample} except Exception as ex: logging.warning('Failed to open {}, ex info {}'.format(cosy_jsonl_path, ex))
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 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) token_max_length: drop utterance which is greater than token_max_length, especially when use char unit for english modeling token_min_length: drop utterance which is less than token_max_length min_output_input_ratio: minimal ration of token_length / feats_length(10ms) max_output_input_ratio: maximum ration of token_length / feats_length(10ms) Returns: Iterable[{key, wav, label, sample_rate}] """ for sample in data: # sample['speech'], sample['sample_rate'] = torchaudio.load(BytesIO(sample['audio_data'])) # del sample['audio_data'] # sample['wav'] is torch.Tensor, we have 100 frames every second num_frames = sample['speech'].size(1) / sample['sample_rate'] * 100 if num_frames < min_length: continue if num_frames > max_length: continue if len(sample['text_token']) < token_min_length: continue if len(sample['text_token']) > token_max_length: continue if len(sample['speech_token']) == 0: continue if num_frames != 0: if len(sample['text_token']) / num_frames < min_output_input_ratio: continue if len(sample['text_token']) / num_frames > max_output_input_ratio: continue yield sample
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) token_max_length: drop utterance which is greater than token_max_length, especially when use char unit for english modeling token_min_length: drop utterance which is less than token_max_length min_output_input_ratio: minimal ration of token_length / feats_length(10ms) max_output_input_ratio: maximum ration of token_length / feats_length(10ms) Returns: Iterable[{key, wav, label, sample_rate}]
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 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) token_max_length: drop utterance which is greater than token_max_length, especially when use char unit for english modeling token_min_length: drop utterance which is less than token_max_length min_output_input_ratio: minimal ration of token_length / feats_length(10ms) max_output_input_ratio: maximum ration of token_length / feats_length(10ms) Returns: Iterable[{key, wav, label, sample_rate}] """ for sample in data: # sample['speech'], sample['sample_rate'] = torchaudio.load(BytesIO(sample['audio_data'])) # del sample['audio_data'] # sample['wav'] is torch.Tensor, we have 100 frames every second num_frames = sample['speech'].size(1) / sample['sample_rate'] * 100 if num_frames < min_length: continue if num_frames > max_length: continue if len(sample['speech_token']) < token_min_length: continue if len(sample['speech_token']) > token_max_length: continue if len(sample['speech_token']) == 0: continue if num_frames != 0: if len(sample['speech_token']) / num_frames < min_output_input_ratio: continue if len(sample['speech_token']) / num_frames > max_output_input_ratio: continue yield sample
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) token_max_length: drop utterance which is greater than token_max_length, especially when use char unit for english modeling token_min_length: drop utterance which is less than token_max_length min_output_input_ratio: minimal ration of token_length / feats_length(10ms) max_output_input_ratio: maximum ration of token_length / feats_length(10ms) Returns: Iterable[{key, wav, label, sample_rate}]
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}] """ for sample in data: assert 'sample_rate' in sample assert 'speech' in sample sample_rate = sample['sample_rate'] waveform = sample['speech'] if sample_rate != resample_rate: if sample_rate < min_sample_rate: continue sample['sample_rate'] = resample_rate sample['speech'] = torchaudio.transforms.Resample( orig_freq=sample_rate, new_freq=resample_rate)(waveform) max_val = sample['speech'].abs().max() if max_val > 1: sample['speech'] /= max_val yield sample
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 assert 'speech' in sample # assert 'utt' in sample # assert 'text_token' in sample waveform = sample['speech'] mat = feat_extractor(waveform).squeeze(dim=0).transpose(0, 1) sample['speech_feat'] = mat del sample['speech'] yield 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_embedding'], dtype=torch.float32) sample['spk_embedding'] = torch.tensor(sample['spk_embedding'], dtype=torch.float32) if normalize: sample['utt_embedding'] = F.normalize(sample['utt_embedding'], dim=0) sample['spk_embedding'] = F.normalize(sample['spk_embedding'], dim=0) yield sample
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_tokenizer() for sample in data: assert 'text' in sample sample['text_token'] = tokenizer.encode(sample['text'], allowed_special=allowed_special) if mode == 'inference': sample['tts_text_token'] = tokenizer.encode(sample['tts_text'], allowed_special=allowed_special) yield sample
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(sample) if len(buf) >= shuffle_size: random.shuffle(buf) for x in buf: yield x buf = [] # The sample left over random.shuffle(buf) for x in buf: yield x
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, label}] sort_size: buffer size for sort Returns: Iterable[{key, feat, label}] """ buf = [] for sample in data: buf.append(sample) if len(buf) >= sort_size: buf.sort(key=lambda x: x['speech_feat'].size(0)) for x in buf: yield x buf = [] # The sample left over buf.sort(key=lambda x: x['speech_feat'].size(0)) for x in buf: yield x
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 Returns: Iterable[{key, feat, label}]
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) if len(buf) >= batch_size: yield buf buf = [] if len(buf) > 0: yield buf
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: Iterable[List[{key, feat, label}]] """ buf = [] longest_frames = 0 for sample in data: assert 'speech_feat' in sample assert isinstance(sample['speech_feat'], torch.Tensor) new_sample_frames = sample['speech_feat'].size(0) longest_frames = max(longest_frames, new_sample_frames) frames_after_padding = longest_frames * (len(buf) + 1) if frames_after_padding > max_frames_in_batch: yield buf buf = [sample] longest_frames = new_sample_frames else: buf.append(sample) if len(buf) > 0: yield buf
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(sample, list) speech_feat_len = torch.tensor([x['speech_feat'].size(1) for x in sample], dtype=torch.int32) order = torch.argsort(speech_feat_len, descending=True) utts = [sample[i]['utt'] for i in order] speech_token = [torch.tensor(sample[i]['speech_token']) for i in order] speech_token_len = torch.tensor([i.size(0) for i in speech_token], dtype=torch.int32) speech_token = pad_sequence(speech_token, batch_first=True, padding_value=0) speech_feat = [sample[i]['speech_feat'] for i in order] speech_feat_len = torch.tensor([i.size(0) for i in speech_feat], dtype=torch.int32) speech_feat = pad_sequence(speech_feat, batch_first=True, padding_value=0) text = [sample[i]['text'] for i in order] text_token = [torch.tensor(sample[i]['text_token']) for i in order] text_token_len = torch.tensor([i.size(0) for i in text_token], dtype=torch.int32) text_token = pad_sequence(text_token, batch_first=True, padding_value=0) utt_embedding = torch.stack([sample[i]['utt_embedding'] for i in order], dim=0) spk_embedding = torch.stack([sample[i]['spk_embedding'] for i in order], dim=0) batch = { "utts": utts, "speech_token": speech_token, "speech_token_len": speech_token_len, "speech_feat": speech_feat, "speech_feat_len": speech_feat_len, "text": text, "text_token": text_token, "text_token_len": text_token_len, "utt_embedding": utt_embedding, "spk_embedding": spk_embedding, } if mode == 'inference': tts_text = [sample[i]['tts_text'] for i in order] tts_index = [sample[i]['tts_index'] for i in order] tts_text_token = [torch.tensor(sample[i]['tts_text_token']) for i in order] tts_text_token_len = torch.tensor([i.size(0) for i in tts_text_token], dtype=torch.int32) tts_text_token = pad_sequence(tts_text_token, batch_first=True, padding_value=-1) batch.update({'tts_text': tts_text, 'tts_index': tts_index, 'tts_text_token': tts_text_token, 'tts_text_token_len': tts_text_token_len}) if use_spk_embedding is True: batch["embedding"] = batch["spk_embedding"] else: batch["embedding"] = batch["utt_embedding"] yield batch
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 isinstance(sample, list) speech_feat_len = torch.tensor([x['speech_feat'].size(1) for x in sample], dtype=torch.int32) order = torch.argsort(speech_feat_len, descending=True) # utts = [sample[i]['utt'] for i in order] # speech_token = [torch.tensor(sample[i]['speech_token']) for i in order] try: speech_token = [sample[i]['speech_token'].clone().detach() for i in order] speech_token_len = torch.tensor([i.size(0) for i in speech_token], dtype=torch.int32) speech_token = pad_sequence(speech_token, batch_first=True, padding_value=0) speech_feat = [sample[i]['speech_feat'] for i in order] speech_feat_len = torch.tensor([i.size(0) for i in speech_feat], dtype=torch.int32) speech_feat = pad_sequence(speech_feat, batch_first=True, padding_value=0) batch = { "speech_token": speech_token, "speech_token_len": speech_token_len, "speech_feat": speech_feat, "speech_feat_len": speech_feat_len, } if mode == 'inference': tts_text = [sample[i]['tts_text'] for i in order] tts_index = [sample[i]['tts_index'] for i in order] tts_text_token = [torch.tensor(sample[i]['tts_text_token']) for i in order] tts_text_token_len = torch.tensor([i.size(0) for i in tts_text_token], dtype=torch.int32) tts_text_token = pad_sequence(tts_text_token, batch_first=True, padding_value=-1) batch.update({'tts_text': tts_text, 'tts_index': tts_index, 'tts_text_token': tts_text_token, 'tts_text_token_len': tts_text_token_len}) # if use_spk_embedding is True: # batch["embedding"] = batch["spk_embedding"] # else: # batch["embedding"] = batch["utt_embedding"] batch["embedding"]=torch.zeros((batch["speech_feat"].size(0),192),device=batch["speech_feat"].device) yield batch except Exception as ex: logging.warning(' ex info {}'.format(ex)) # assert False
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: assert isinstance(sample, list) speech_feat_len = torch.tensor([x['speech_feat'].size(1) for x in sample], dtype=torch.int32) order = torch.argsort(speech_feat_len, descending=True) # utts = [sample[i]['utt'] for i in order] # speech_token = [torch.tensor(sample[i]['speech_token']) for i in order] try: speech_token = [sample[i]['speech_token'].clone().detach() for i in order] speech_token_len = torch.tensor([i.size(0) for i in speech_token], dtype=torch.int32) speech_token = pad_sequence(speech_token, batch_first=True, padding_value=0) speech_feat = [sample[i]['speech_feat'] for i in order] speech_feat_len = torch.tensor([i.size(0) for i in speech_feat], dtype=torch.int32) speech_feat = pad_sequence(speech_feat, batch_first=True, padding_value=0) spk_embedding = torch.stack([sample[i]['spk_embedding'] for i in order], dim=0) batch = { "speech_token": speech_token, "speech_token_len": speech_token_len, "speech_feat": speech_feat, "speech_feat_len": speech_feat_len, "spk_embedding": spk_embedding, } if mode == 'inference': tts_text = [sample[i]['tts_text'] for i in order] tts_index = [sample[i]['tts_index'] for i in order] tts_text_token = [torch.tensor(sample[i]['tts_text_token']) for i in order] tts_text_token_len = torch.tensor([i.size(0) for i in tts_text_token], dtype=torch.int32) tts_text_token = pad_sequence(tts_text_token, batch_first=True, padding_value=-1) batch.update({'tts_text': tts_text, 'tts_index': tts_index, 'tts_text_token': tts_text_token, 'tts_text_token_len': tts_text_token_len}) # if use_spk_embedding is True: # batch["embedding"] = batch["spk_embedding"] # else: # batch["embedding"] = batch["utt_embedding"] # batch["embedding"]=torch.zeros((batch["speech_feat"].size(0),192),device=batch["speech_feat"].device) batch["embedding"] = batch["spk_embedding"] yield batch except Exception as ex: logging.warning(' ex info {}'.format(ex)) # assert False
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 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. """ super().__init__() channels = tuple(channels) self.in_channels = in_channels self.out_channels = out_channels self.time_embeddings = SinusoidalPosEmb(in_channels) time_embed_dim = channels[0] * 4 self.time_mlp = TimestepEmbedding( in_channels=in_channels, time_embed_dim=time_embed_dim, act_fn="silu", ) self.down_blocks = nn.ModuleList([]) self.mid_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) output_channel = in_channels for i in range(len(channels)): # pylint: disable=consider-using-enumerate input_channel = output_channel output_channel = channels[i] is_last = i == len(channels) - 1 resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim) transformer_blocks = nn.ModuleList( [ BasicTransformerBlock( dim=output_channel, num_attention_heads=num_heads, attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn, ) for _ in range(n_blocks) ] ) downsample = ( Downsample1D(output_channel) if not is_last else nn.Conv1d(output_channel, output_channel, 3, padding=1) ) self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample])) for i in range(num_mid_blocks): input_channel = channels[-1] out_channels = channels[-1] resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim) transformer_blocks = nn.ModuleList( [ BasicTransformerBlock( dim=output_channel, num_attention_heads=num_heads, attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn, ) for _ in range(n_blocks) ] ) self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks])) channels = channels[::-1] + (channels[0],) for i in range(len(channels) - 1): input_channel = channels[i] * 2 output_channel = channels[i + 1] is_last = i == len(channels) - 2 resnet = ResnetBlock1D( dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim, ) transformer_blocks = nn.ModuleList( [ BasicTransformerBlock( dim=output_channel, num_attention_heads=num_heads, attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn, ) for _ in range(n_blocks) ] ) upsample = ( Upsample1D(output_channel, use_conv_transpose=True) if not is_last else nn.Conv1d(output_channel, output_channel, 3, padding=1) ) self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample])) self.final_block = Block1D(channels[-1], channels[-1]) self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1) self.initialize_weights()
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_, optional): shape: (batch_size, condition_channels). Defaults to None. cond (_type_, optional): placeholder for future use. Defaults to None. Raises: ValueError: _description_ ValueError: _description_ Returns: _type_: _description_ """ t = self.time_embeddings(t) t = self.time_mlp(t) x = pack([x, mu], "b * t")[0] if spks is not None: spks = repeat(spks, "b c -> b c t", t=x.shape[-1]) x = pack([x, spks], "b * t")[0] if cond is not None: x = pack([x, cond], "b * t")[0] hiddens = [] masks = [mask] for resnet, transformer_blocks, downsample in self.down_blocks: mask_down = masks[-1] x = resnet(x, mask_down, t) x = rearrange(x, "b c t -> b t c").contiguous() attn_mask = torch.matmul(mask_down.transpose(1, 2).contiguous(), mask_down) for transformer_block in transformer_blocks: x = transformer_block( hidden_states=x, attention_mask=attn_mask, timestep=t, ) x = rearrange(x, "b t c -> b c t").contiguous() hiddens.append(x) # Save hidden states for skip connections x = downsample(x * mask_down) masks.append(mask_down[:, :, ::2]) masks = masks[:-1] mask_mid = masks[-1] for resnet, transformer_blocks in self.mid_blocks: x = resnet(x, mask_mid, t) x = rearrange(x, "b c t -> b t c").contiguous() attn_mask = torch.matmul(mask_mid.transpose(1, 2).contiguous(), mask_mid) for transformer_block in transformer_blocks: x = transformer_block( hidden_states=x, attention_mask=attn_mask, timestep=t, ) x = rearrange(x, "b t c -> b c t").contiguous() for resnet, transformer_blocks, upsample in self.up_blocks: mask_up = masks.pop() skip = hiddens.pop() x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0] x = resnet(x, mask_up, t) x = rearrange(x, "b c t -> b t c").contiguous() attn_mask = torch.matmul(mask_up.transpose(1, 2).contiguous(), mask_up) for transformer_block in transformer_blocks: x = transformer_block( hidden_states=x, attention_mask=attn_mask, timestep=t, ) x = rearrange(x, "b t c -> b c t").contiguous() x = upsample(x * mask_up) x = self.final_block(x, mask_up) output = self.final_proj(x * mask_up) return output * mask
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. cond (_type_, optional): placeholder for future use. Defaults to None. Raises: ValueError: _description_ ValueError: _description_ Returns: _type_: _description_
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, mel_timesteps) n_timesteps (int): number of diffusion steps temperature (float, optional): temperature for scaling noise. Defaults to 1.0. spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes Returns: sample: generated mel-spectrogram shape: (batch_size, n_feats, mel_timesteps) """ torch.manual_seed(42) z = torch.randn_like(mu) * temperature t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device) if self.t_scheduler == 'cosine': t_span = 1 - torch.cos(t_span * 0.5 * torch.pi) return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
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 temperature (float, optional): temperature for scaling noise. Defaults to 1.0. spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes Returns: sample: generated mel-spectrogram shape: (batch_size, n_feats, mel_timesteps)
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 shape: (batch_size, n_feats, mel_timesteps) mask (torch.Tensor): output_mask shape: (batch_size, 1, mel_timesteps) spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes """ t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0] # I am storing this because I can later plot it by putting a debugger here and saving it to a file # Or in future might add like a return_all_steps flag sol = [] for step in range(1, len(t_span)): dphi_dt = self.estimator(x, mask, mu, t, spks, cond) # Classifier-Free Guidance inference introduced in VoiceBox if self.inference_cfg_rate > 0: cfg_dphi_dt = self.estimator( x, mask, torch.zeros_like(mu), t, torch.zeros_like(spks) if spks is not None else None, torch.zeros_like(cond) ) dphi_dt = ((1.0 + self.inference_cfg_rate) * dphi_dt - self.inference_cfg_rate * cfg_dphi_dt) x = x + dt * dphi_dt t = t + dt sol.append(x) if step < len(t_span) - 1: dt = t_span[step + 1] - t return sol[-1]
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) mask (torch.Tensor): output_mask shape: (batch_size, 1, mel_timesteps) spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes
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) mu (torch.Tensor): output of encoder shape: (batch_size, n_feats, mel_timesteps) spks (torch.Tensor, optional): speaker embedding. Defaults to None. shape: (batch_size, spk_emb_dim) Returns: loss: conditional flow matching loss y: conditional flow shape: (batch_size, n_feats, mel_timesteps) """ b, _, t = mu.shape # random timestep t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype) if self.t_scheduler == 'cosine': t = 1 - torch.cos(t * 0.5 * torch.pi) # sample noise p(x_0) z = torch.randn_like(x1) y = (1 - (1 - self.sigma_min) * t) * z + t * x1 u = x1 - (1 - self.sigma_min) * z # during training, we randomly drop condition to trade off mode coverage and sample fidelity if self.training_cfg_rate > 0: cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate mu = mu * cfg_mask.view(-1, 1, 1) spks = spks * cfg_mask.view(-1, 1) cond = cond * cfg_mask.view(-1, 1, 1) pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond) loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1]) return loss, y
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, n_feats, mel_timesteps) spks (torch.Tensor, optional): speaker embedding. Defaults to None. shape: (batch_size, spk_emb_dim) Returns: loss: conditional flow matching loss y: conditional flow shape: (batch_size, n_feats, mel_timesteps)
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, mel_timesteps) n_timesteps (int): number of diffusion steps temperature (float, optional): temperature for scaling noise. Defaults to 1.0. spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes Returns: sample: generated mel-spectrogram shape: (batch_size, n_feats, mel_timesteps) """ z = torch.randn_like(mu) * temperature t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device) if self.t_scheduler == 'cosine': t_span = 1 - torch.cos(t_span * 0.5 * torch.pi) return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
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 temperature (float, optional): temperature for scaling noise. Defaults to 1.0. spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes Returns: sample: generated mel-spectrogram shape: (batch_size, n_feats, mel_timesteps)
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): output of encoder shape: (batch_size, n_feats, mel_timesteps) mask (torch.Tensor): output_mask shape: (batch_size, 1, mel_timesteps) spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes """ t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0] # I am storing this because I can later plot it by putting a debugger here and saving it to a file # Or in future might add like a return_all_steps flag sol = [] cfg_dropout_prob = 0.1 cfg_scale = 1.0 # cfg_dropout_prob = 0.0 # cfg_scale = 3.0 for step in range(1, len(t_span)): # dphi_dt = self.estimator(x, mask, mu, t, spks, cond) # pdb.set_trace() dphi_dt = self.estimator(x, # [bs, 80, 229] t[None], # (bs,) global_embed=spks, input_concat_cond=mu, mask=mask[0], # [bs, 229] cfg_dropout_prob=cfg_dropout_prob, cfg_scale=cfg_scale) # Classifier-Free Guidance inference introduced in VoiceBox if self.inference_cfg_rate > 0: # cfg_dphi_dt = self.estimator( # x, mask, # torch.zeros_like(mu), t, # torch.zeros_like(spks) if spks is not None else None, # torch.zeros_like(cond) # ) cfg_dphi_dt = self.estimator(x, # [bs, 80, 229] t[None], # (bs,) global_embed=torch.zeros_like(spks) if spks is not None else None, input_concat_cond=torch.zeros_like(mu), mask=mask[0], # [bs, 229] cfg_dropout_prob=cfg_dropout_prob, cfg_scale=cfg_scale) dphi_dt = ((1.0 + self.inference_cfg_rate) * dphi_dt - self.inference_cfg_rate * cfg_dphi_dt) x = x + dt * dphi_dt t = t + dt sol.append(x) if step < len(t_span) - 1: dt = t_span[step + 1] - t return sol[-1]
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_timesteps) mask (torch.Tensor): output_mask shape: (batch_size, 1, mel_timesteps) spks (torch.Tensor, optional): speaker ids. Defaults to None. shape: (batch_size, spk_emb_dim) cond: Not used but kept for future purposes
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) mu (torch.Tensor): output of encoder shape: (batch_size, n_feats, mel_timesteps) spks (torch.Tensor, optional): speaker embedding. Defaults to None. shape: (batch_size, spk_emb_dim) Returns: loss: conditional flow matching loss y: conditional flow shape: (batch_size, n_feats, mel_timesteps) """ b, _, t = mu.shape # random timestep t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype) if self.t_scheduler == 'cosine': t = 1 - torch.cos(t * 0.5 * torch.pi) # sample noise p(x_0) z = torch.randn_like(x1) y = (1 - (1 - self.sigma_min) * t) * z + t * x1 u = x1 - (1 - self.sigma_min) * z # during training, we randomly drop condition to trade off mode coverage and sample fidelity if self.training_cfg_rate > 0: cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate mu = mu * cfg_mask.view(-1, 1, 1) spks = spks * cfg_mask.view(-1, 1) cond = cond * cfg_mask.view(-1, 1, 1) # pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond) pred = self.estimator(y, # [bs, 80, 229] t.squeeze(1, 2), # (bs,) global_embed=spks, input_concat_cond=mu, mask=mask.squeeze(1), # [bs, 229] cfg_dropout_prob=0.1) loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1]) return loss, y
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, n_feats, mel_timesteps) spks (torch.Tensor, optional): speaker embedding. Defaults to None. shape: (batch_size, spk_emb_dim) Returns: loss: conditional flow matching loss y: conditional flow shape: (batch_size, n_feats, mel_timesteps)
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, some time steps might get removed. For instance, with total padding = 4, kernel size = 4, stride = 2: 0 0 1 2 3 4 5 0 0 # (0s are padding) 1 2 3 # (output frames of a convolution, last 0 is never used) 0 0 1 2 3 4 5 0 # (output of tr. conv., but pos. 5 is going to get removed as padding) 1 2 3 4 # once you removed padding, we are missing one time step ! """ extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total) return F.pad(x, (0, extra_padding))
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, stride = 2: 0 0 1 2 3 4 5 0 0 # (0s are padding) 1 2 3 # (output frames of a convolution, last 0 is never used) 0 0 1 2 3 4 5 0 # (output of tr. conv., but pos. 5 is going to get removed as padding) 1 2 3 4 # once you removed padding, we are missing one time step !
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] padding_left, padding_right = paddings assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right) if mode == 'reflect': max_pad = max(padding_left, padding_right) extra_pad = 0 if length <= max_pad: extra_pad = max_pad - length + 1 x = F.pad(x, (0, extra_pad)) padded = F.pad(x, paddings, mode, value) end = padded.shape[-1] - extra_pad return padded[..., :end] else: return F.pad(x, paddings, mode, value)
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] end = x.shape[-1] - padding_right return x[..., padding_left: end]
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_channels: return None assert exists(channels_list), "Missing context" # Get channels index (skipping zero channel contexts) channels_id = self.channels_ids[layer] # Get channels channels = channels_list[channels_id] message = f"Missing context for layer {layer} at index {channels_id}" assert exists(channels), message # Check channels num_channels = self.context_channels[layer] message = f"Expected context with {num_channels} channels at idx {channels_id}" assert channels.shape[1] == num_channels, message # STFT channels if requested channels = self.stft.encode1d(channels) if self.use_stft_context else channels # type: ignore # noqa return channels
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 = "use_context_time=True but no time features provided" assert exists(time), assert_message items += [self.to_time(time)] # Compute features if self.use_context_features: assert_message = "context_features exists but no features provided" assert exists(features), assert_message items += [self.to_features(features)] # Compute joint mapping if self.use_context_time or self.use_context_features: mapping = reduce(torch.stack(items), "n b m -> b m", "sum") mapping = self.to_mapping(mapping) return mapping
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) #alphas, sigmas = 1-t, t for t_curr, t_prev in tqdm(zip(t[:-1], t[1:])): # Broadcast the current timestep to the correct shape t_curr_tensor = t_curr * torch.ones( (x.shape[0],), dtype=x.dtype, device=x.device ) dt = t_prev - t_curr # we solve backwards in our formulation x = x + dt * model(x, t_curr_tensor, **extra_args) #.denoise(x, denoiser, t_curr_tensor, cond, uc) # If we are on the last timestep, output the denoised image return x
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(steps): # Get the model output (v, the predicted velocity) with torch.cuda.amp.autocast(): v = model(x, ts * t[i], **extra_args).float() # Predict the noise and the denoised image pred = x * alphas[i] - v * sigmas[i] eps = x * sigmas[i] + v * alphas[i] # If we are not on the last timestep, compute the noisy image for the # next timestep. if i < steps - 1: # If eta > 0, adjust the scaling factor for the predicted noise # downward according to the amount of additional noise to add ddim_sigma = eta * (sigmas[i + 1]**2 / sigmas[i]**2).sqrt() * \ (1 - alphas[i]**2 / alphas[i + 1]**2).sqrt() adjusted_sigma = (sigmas[i + 1]**2 - ddim_sigma**2).sqrt() # Recombine the predicted noise and predicted denoised image in the # correct proportions for the next step x = pred * alphas[i + 1] + eps * adjusted_sigma # Add the correct amount of fresh noise if eta: x += torch.randn_like(x) * ddim_sigma # If we are on the last timestep, output the denoised image return pred
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)) else: self.gamma = nn.Parameter(torch.ones(dim)) if bias: self.beta = nn.Parameter(torch.zeros(dim)) else: self.register_buffer("beta", torch.zeros(dim))
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)) else: self.gamma = nn.Parameter(torch.ones(dim)) if bias: self.beta = nn.Parameter(torch.zeros(dim)) else: self.register_buffer("beta", torch.zeros(dim))
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(): sine_wavs, uv, _ = self.l_sin_gen(x.transpose(1, 2)) sine_wavs = sine_wavs.transpose(1, 2) uv = uv.transpose(1, 2) sine_merge = self.l_tanh(self.l_linear(sine_wavs)) # source for noise branch, in the same shape as uv noise = torch.randn_like(uv) * self.sine_amp / 3 return sine_merge, noise, uv
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. alpha will be trained along with the rest of your model. ''' super(Snake, self).__init__() self.in_features = in_features # initialize alpha self.alpha_logscale = alpha_logscale if self.alpha_logscale: # log scale alphas initialized to zeros self.alpha = Parameter(torch.zeros(in_features) * alpha) else: # linear scale alphas initialized to ones self.alpha = Parameter(torch.ones(in_features) * alpha) self.alpha.requires_grad = alpha_trainable self.no_div_by_zero = 0.000000001
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 (#batch, time2, size). value (torch.Tensor): Value tensor (#batch, time2, size). Returns: torch.Tensor: Transformed query tensor, size (#batch, n_head, time1, d_k). torch.Tensor: Transformed key tensor, size (#batch, n_head, time2, d_k). torch.Tensor: Transformed value tensor, size (#batch, n_head, time2, d_k). """ n_batch = query.size(0) q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k) k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k) v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k) q = q.transpose(1, 2) # (batch, head, time1, d_k) k = k.transpose(1, 2) # (batch, head, time2, d_k) v = v.transpose(1, 2) # (batch, head, time2, d_k) return q, k, v
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 tensor, size (#batch, n_head, time1, d_k). torch.Tensor: Transformed key tensor, size (#batch, n_head, time2, d_k). torch.Tensor: Transformed value tensor, size (#batch, n_head, time2, d_k).
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 (#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) or (#batch, time1, time2), (0, 0, 0) means fake mask. Returns: torch.Tensor: Transformed value (#batch, time1, d_model) weighted by the attention score (#batch, time1, time2). """ n_batch = value.size(0) # NOTE(xcsong): When will `if mask.size(2) > 0` be True? # 1. onnx(16/4) [WHY? Because we feed real cache & real mask for the # 1st chunk to ease the onnx export.] # 2. pytorch training if mask.size(2) > 0: # time2 > 0 mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2) # For last chunk, time2 might be larger than scores.size(-1) mask = mask[:, :, :, :scores.size(-1)] # (batch, 1, *, time2) scores = scores.masked_fill(mask, -float('inf')) attn = torch.softmax(scores, dim=-1).masked_fill( mask, 0.0) # (batch, head, time1, time2) # NOTE(xcsong): When will `if mask.size(2) > 0` be False? # 1. onnx(16/-1, -1/-1, 16/0) # 2. jit (16/-1, -1/-1, 16/0, 16/4) else: attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2) p_attn = self.dropout(attn) x = torch.matmul(p_attn, value) # (batch, head, time1, d_k) x = (x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k) ) # (batch, time1, d_model) return self.linear_out(x) # (batch, time1, d_model)
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) or (#batch, time1, time2), (0, 0, 0) means fake mask. Returns: torch.Tensor: Transformed value (#batch, time1, d_model) weighted by the attention score (#batch, time1, 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.Tensor]: """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, time2) or (#batch, time1, time2). 1.When applying cross attention between decoder and encoder, the batch padding mask for input is in (#batch, 1, T) shape. 2.When applying self attention of encoder, the mask is in (#batch, T, T) shape. 3.When applying self attention of decoder, the mask is in (#batch, L, L) shape. 4.If the different position in decoder see different block of the encoder, such as Mocha, the passed in mask could be in (#batch, L, T) shape. But there is no such case in current CosyVoice. cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2), where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size` Returns: torch.Tensor: Output tensor (#batch, time1, d_model). torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2) where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size` """ q, k, v = self.forward_qkv(query, key, value) # NOTE(xcsong): # when export onnx model, for 1st chunk, we feed # cache(1, head, 0, d_k * 2) (16/-1, -1/-1, 16/0 mode) # or cache(1, head, real_cache_t, d_k * 2) (16/4 mode). # In all modes, `if cache.size(0) > 0` will alwayse be `True` # and we will always do splitting and # concatnation(this will simplify onnx export). Note that # it's OK to concat & split zero-shaped tensors(see code below). # when export jit model, for 1st chunk, we always feed # cache(0, 0, 0, 0) since jit supports dynamic if-branch. # >>> a = torch.ones((1, 2, 0, 4)) # >>> b = torch.ones((1, 2, 3, 4)) # >>> c = torch.cat((a, b), dim=2) # >>> torch.equal(b, c) # True # >>> d = torch.split(a, 2, dim=-1) # >>> torch.equal(d[0], d[1]) # True if cache.size(0) > 0: key_cache, value_cache = torch.split(cache, cache.size(-1) // 2, dim=-1) k = torch.cat([key_cache, k], dim=2) v = torch.cat([value_cache, v], dim=2) # NOTE(xcsong): We do cache slicing in encoder.forward_chunk, since it's # non-trivial to calculate `next_cache_start` here. new_cache = torch.cat((k, v), dim=-1) scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k) return self.forward_attention(v, scores, mask), new_cache
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, time2) or (#batch, time1, time2). 1.When applying cross attention between decoder and encoder, the batch padding mask for input is in (#batch, 1, T) shape. 2.When applying self attention of encoder, the mask is in (#batch, T, T) shape. 3.When applying self attention of decoder, the mask is in (#batch, L, L) shape. 4.If the different position in decoder see different block of the encoder, such as Mocha, the passed in mask could be in (#batch, L, T) shape. But there is no such case in current CosyVoice. cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2), where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size` Returns: torch.Tensor: Output tensor (#batch, time1, d_model). torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2) where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size`
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((*x.size()[:3], 1), device=x.device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=-1) x_padded = x_padded.view(*x.size()[:2], x.size(3) + 1, x.size(2)) x = x_padded[:, :, 1:].view_as(x)[ :, :, :, : x.size(-1) // 2 + 1 ] # only keep the positions from 0 to time2 return 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.
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.Tensor]: """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): Mask tensor (#batch, 1, time2) or (#batch, time1, time2), (0, 0, 0) means fake mask. pos_emb (torch.Tensor): Positional embedding tensor (#batch, time2, size). cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2), where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size` Returns: torch.Tensor: Output tensor (#batch, time1, d_model). torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2) where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size` """ q, k, v = self.forward_qkv(query, key, value) q = q.transpose(1, 2) # (batch, time1, head, d_k) # NOTE(xcsong): # when export onnx model, for 1st chunk, we feed # cache(1, head, 0, d_k * 2) (16/-1, -1/-1, 16/0 mode) # or cache(1, head, real_cache_t, d_k * 2) (16/4 mode). # In all modes, `if cache.size(0) > 0` will alwayse be `True` # and we will always do splitting and # concatnation(this will simplify onnx export). Note that # it's OK to concat & split zero-shaped tensors(see code below). # when export jit model, for 1st chunk, we always feed # cache(0, 0, 0, 0) since jit supports dynamic if-branch. # >>> a = torch.ones((1, 2, 0, 4)) # >>> b = torch.ones((1, 2, 3, 4)) # >>> c = torch.cat((a, b), dim=2) # >>> torch.equal(b, c) # True # >>> d = torch.split(a, 2, dim=-1) # >>> torch.equal(d[0], d[1]) # True if cache.size(0) > 0: key_cache, value_cache = torch.split(cache, cache.size(-1) // 2, dim=-1) k = torch.cat([key_cache, k], dim=2) v = torch.cat([value_cache, v], dim=2) # NOTE(xcsong): We do cache slicing in encoder.forward_chunk, since it's # non-trivial to calculate `next_cache_start` here. new_cache = torch.cat((k, v), dim=-1) n_batch_pos = pos_emb.size(0) p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k) p = p.transpose(1, 2) # (batch, head, time1, d_k) # (batch, head, time1, d_k) q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2) # (batch, head, time1, d_k) q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2) # compute attention score # first compute matrix a and matrix c # as described in https://arxiv.org/abs/1901.02860 Section 3.3 # (batch, head, time1, time2) matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1)) # compute matrix b and matrix d # (batch, head, time1, time2) matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1)) # NOTE(Xiang Lyu): Keep rel_shift since espnet rel_pos_emb is used if matrix_ac.shape != matrix_bd.shape: matrix_bd = self.rel_shift(matrix_bd) scores = (matrix_ac + matrix_bd) / math.sqrt( self.d_k) # (batch, head, time1, time2) return self.forward_attention(v, scores, mask), new_cache
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): Mask tensor (#batch, 1, time2) or (#batch, time1, time2), (0, 0, 0) means fake mask. pos_emb (torch.Tensor): Positional embedding tensor (#batch, time2, size). cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2), where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size` Returns: torch.Tensor: Output tensor (#batch, time1, d_model). torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2) where `cache_t == chunk_size * num_decoding_left_chunks` and `head * d_k == size`
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. """ zero_pad = torch.zeros((x.size()[0], x.size()[1], x.size()[2], 1), device=x.device, dtype=x.dtype) x_padded = torch.cat([zero_pad, x], dim=-1) x_padded = x_padded.view(x.size()[0], x.size()[1], x.size(3) + 1, x.size(2)) x = x_padded[:, :, 1:].view_as(x)[ :, :, :, : x.size(-1) // 2 + 1 ] # only keep the positions from 0 to time2 return 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.
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. 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 """ super().__init__() self.pointwise_conv1 = nn.Conv1d( channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias, ) # self.lorder is used to distinguish if it's a causal convolution, # if self.lorder > 0: it's a causal convolution, the input will be # padded with self.lorder frames on the left in forward. # else: it's a symmetrical convolution if causal: padding = 0 self.lorder = kernel_size - 1 else: # kernel_size should be an odd number for none causal convolution assert (kernel_size - 1) % 2 == 0 padding = (kernel_size - 1) // 2 self.lorder = 0 self.depthwise_conv = nn.Conv1d( channels, channels, kernel_size, stride=1, padding=padding, groups=channels, bias=bias, ) assert norm in ['batch_norm', 'layer_norm'] if norm == "batch_norm": self.use_layer_norm = False self.norm = nn.BatchNorm1d(channels) else: self.use_layer_norm = True self.norm = nn.LayerNorm(channels) self.pointwise_conv2 = nn.Conv1d( channels, channels, kernel_size=1, stride=1, padding=0, bias=bias, ) self.activation = activation
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 (#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 in causal convolution (#batch, channels, cache_t), (0, 0, 0) meas fake cache. Returns: torch.Tensor: Output tensor (#batch, time, channels). """ # exchange the temporal dimension and the feature dimension x = x.transpose(1, 2) # (#batch, channels, time) # mask batch padding if mask_pad.size(2) > 0: # time > 0 x.masked_fill_(~mask_pad, 0.0) if self.lorder > 0: if cache.size(2) == 0: # cache_t == 0 x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0) else: assert cache.size(0) == x.size(0) # equal batch assert cache.size(1) == x.size(1) # equal channel x = torch.cat((cache, x), dim=2) assert (x.size(2) > self.lorder) new_cache = x[:, :, -self.lorder:] else: # It's better we just return None if no cache is required, # However, for JIT export, here we just fake one tensor instead of # None. new_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device) # GLU mechanism x = self.pointwise_conv1(x) # (batch, 2*channel, dim) x = nn.functional.glu(x, dim=1) # (batch, channel, dim) # 1D Depthwise Conv x = self.depthwise_conv(x) if self.use_layer_norm: x = x.transpose(1, 2) x = self.activation(self.norm(x)) if self.use_layer_norm: x = x.transpose(1, 2) x = self.pointwise_conv2(x) # mask batch padding if mask_pad.size(2) > 0: # time > 0 x.masked_fill_(~mask_pad, 0.0) return x.transpose(1, 2), new_cache
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 in causal convolution (#batch, channels, cache_t), (0, 0, 0) meas fake cache. Returns: torch.Tensor: Output tensor (#batch, time, channels).
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]: """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_in_pad: not used in transformer decoder, in order to unify api with bidirectional decoder reverse_weight: not used in transformer decoder, in order to unify api with bidirectional decode Returns: (tuple): tuple containing: x: decoded token score before softmax (batch, maxlen_out, vocab_size) if use_output_layer is True, torch.tensor(0.0), in order to unify api with bidirectional decoder olens: (batch, ) NOTE(xcsong): We pass the `__call__` method of the modules instead of `forward` to the checkpointing API because `__call__` attaches all the hooks of the module. https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2 """ tgt = ys_in_pad maxlen = tgt.size(1) # tgt_mask: (B, 1, L) tgt_mask = ~make_pad_mask(ys_in_lens, maxlen).unsqueeze(1) tgt_mask = tgt_mask.to(tgt.device) # m: (1, L, L) m = subsequent_mask(tgt_mask.size(-1), device=tgt_mask.device).unsqueeze(0) # tgt_mask: (B, L, L) tgt_mask = tgt_mask & m x, _ = self.embed(tgt) if self.gradient_checkpointing and self.training: x = self.forward_layers_checkpointed(x, tgt_mask, memory, memory_mask) else: x = self.forward_layers(x, tgt_mask, memory, memory_mask) if self.normalize_before: x = self.after_norm(x) if self.use_output_layer: x = self.output_layer(x) olens = tgt_mask.sum(1) return x, torch.tensor(0.0), olens
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_in_pad: not used in transformer decoder, in order to unify api with bidirectional decoder reverse_weight: not used in transformer decoder, in order to unify api with bidirectional decode Returns: (tuple): tuple containing: x: decoded token score before softmax (batch, maxlen_out, vocab_size) if use_output_layer is True, torch.tensor(0.0), in order to unify api with bidirectional decoder olens: (batch, ) NOTE(xcsong): We pass the `__call__` method of the modules instead of `forward` to the checkpointing API because `__call__` attaches all the hooks of the module. https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2
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 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, (batch, maxlen_out) dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (include 1.2) cache: cached output list of (batch, max_time_out-1, size) Returns: y, cache: NN output value and cache per `self.decoders`. y.shape` is (batch, maxlen_out, token) """ x, _ = self.embed(tgt) new_cache = [] for i, decoder in enumerate(self.decoders): if cache is None: c = None else: c = cache[i] x, tgt_mask, memory, memory_mask = decoder(x, tgt_mask, memory, memory_mask, cache=c) new_cache.append(x) if self.normalize_before: y = self.after_norm(x[:, -1]) else: y = x[:, -1] if self.use_output_layer: y = torch.log_softmax(self.output_layer(y), dim=-1) return y, new_cache
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, (batch, maxlen_out) dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (include 1.2) cache: cached output list of (batch, max_time_out-1, size) Returns: y, cache: NN output value and cache per `self.decoders`. y.shape` is (batch, maxlen_out, token)
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 to output.weight") self.output_layer.weight = torch.nn.Parameter( self.embed[0].weight.clone()) else: logging.info("tie emb.weight with output.weight") self.output_layer.weight = self.embed[0].weight if getattr(self.output_layer, "bias", None) is not None: self.output_layer.bias.data = torch.nn.functional.pad( self.output_layer.bias.data, ( 0, self.output_layer.weight.shape[0] - self.output_layer.bias.shape[0], ), "constant", 0, )
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. 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_in_pad: padded input token ids, int64 (batch, maxlen_out), used for right to left decoder reverse_weight: used for right to left decoder Returns: (tuple): tuple containing: x: decoded token score before softmax (batch, maxlen_out, vocab_size) if use_output_layer is True, r_x: x: decoded token score (right to left decoder) before softmax (batch, maxlen_out, vocab_size) if use_output_layer is True, olens: (batch, ) """ l_x, _, olens = self.left_decoder(memory, memory_mask, ys_in_pad, ys_in_lens) r_x = torch.tensor(0.0) if reverse_weight > 0.0: r_x, _, olens = self.right_decoder(memory, memory_mask, r_ys_in_pad, ys_in_lens) return l_x, r_x, olens
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_in_pad: padded input token ids, int64 (batch, maxlen_out), used for right to left decoder reverse_weight: used for right to left decoder Returns: (tuple): tuple containing: x: decoded token score before softmax (batch, maxlen_out, vocab_size) if use_output_layer is True, r_x: x: decoded token score (right to left decoder) before softmax (batch, maxlen_out, vocab_size) if use_output_layer is True, olens: (batch, )
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 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, (batch, maxlen_out) dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (include 1.2) cache: cached output list of (batch, max_time_out-1, size) Returns: y, cache: NN output value and cache per `self.decoders`. y.shape` is (batch, maxlen_out, token) """ return self.left_decoder.forward_one_step(memory, memory_mask, tgt, tgt_mask, cache)
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, (batch, maxlen_out) dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (include 1.2) cache: cached output list of (batch, max_time_out-1, size) Returns: y, cache: NN output value and cache per `self.decoders`. y.shape` is (batch, maxlen_out, token)
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: 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). memory_mask (torch.Tensor): Encoded memory mask (#batch, maxlen_in). cache (torch.Tensor): cached tensors. (#batch, maxlen_out - 1, size). Returns: torch.Tensor: Output tensor (#batch, maxlen_out, size). torch.Tensor: Mask for output tensor (#batch, maxlen_out). torch.Tensor: Encoded memory (#batch, maxlen_in, size). torch.Tensor: Encoded memory mask (#batch, maxlen_in). """ residual = tgt if self.normalize_before: tgt = self.norm1(tgt) if cache is None: tgt_q = tgt tgt_q_mask = tgt_mask else: # compute only the last frame query keeping dim: max_time_out -> 1 assert cache.shape == ( tgt.shape[0], tgt.shape[1] - 1, self.size, ), "{cache.shape} == {(tgt.shape[0], tgt.shape[1] - 1, self.size)}" tgt_q = tgt[:, -1:, :] residual = residual[:, -1:, :] tgt_q_mask = tgt_mask[:, -1:, :] x = residual + self.dropout( self.self_attn(tgt_q, tgt, tgt, tgt_q_mask)[0]) if not self.normalize_before: x = self.norm1(x) if self.src_attn is not None: residual = x if self.normalize_before: x = self.norm2(x) x = residual + self.dropout( self.src_attn(x, memory, memory, memory_mask)[0]) if not self.normalize_before: x = self.norm2(x) residual = x if self.normalize_before: x = self.norm3(x) x = residual + self.dropout(self.feed_forward(x)) if not self.normalize_before: x = self.norm3(x) if cache is not None: x = torch.cat([cache, x], dim=1) return x, tgt_mask, memory, memory_mask
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). memory_mask (torch.Tensor): Encoded memory mask (#batch, maxlen_in). cache (torch.Tensor): cached tensors. (#batch, maxlen_out - 1, size). Returns: torch.Tensor: Output tensor (#batch, maxlen_out, size). torch.Tensor: Mask for output tensor (#batch, maxlen_out). torch.Tensor: Encoded memory (#batch, maxlen_in, size). torch.Tensor: Encoded memory mask (#batch, maxlen_in).
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): position offset Returns: torch.Tensor: Encoded tensor. Its shape is (batch, time, ...) torch.Tensor: for compatibility to RelPositionalEncoding """ self.pe = self.pe.to(x.device) pos_emb = self.position_encoding(offset, x.size(1), False) x = x * self.xscale + pos_emb return self.dropout(x), self.dropout(pos_emb)
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 RelPositionalEncoding
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 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. Args: offset (int or torch.tensor): start offset size (int): required size of position encoding Returns: torch.Tensor: Corresponding encoding """ # How to subscript a Union type: # https://github.com/pytorch/pytorch/issues/69434 if isinstance(offset, int): assert offset + size <= self.max_len pos_emb = self.pe[:, offset:offset + size] elif isinstance(offset, torch.Tensor) and offset.dim() == 0: # scalar assert offset + size <= self.max_len pos_emb = self.pe[:, offset:offset + size] else: # for batched streaming decoding on GPU assert torch.max(offset) + size <= self.max_len index = offset.unsqueeze(1) + \ torch.arange(0, size).to(offset.device) # B X T flag = index > 0 # remove negative offset index = index * flag pos_emb = F.embedding(index, self.pe[0]) # B X T X d_model if apply_dropout: pos_emb = self.dropout(pos_emb) return pos_emb
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. Args: offset (int or torch.tensor): start offset size (int): required size of position encoding Returns: torch.Tensor: Corresponding encoding
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: Encoded tensor (batch, time, `*`). torch.Tensor: Positional embedding tensor (1, time, `*`). """ self.pe = self.pe.to(x.device) x = x * self.xscale pos_emb = self.position_encoding(offset, x.size(1), False) return self.dropout(x), self.dropout(pos_emb)
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 self.dropout(x), pos_emb
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 * self.xscale pos_emb = self.position_encoding(size=x.size(1), offset=offset) return self.dropout(x), self.dropout(pos_emb)
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, but will call this function several times with increasing input size in a streaming scenario, so the dropout will be applied several times. Args: offset (int or torch.tensor): start offset size (int): required size of position encoding Returns: torch.Tensor: Corresponding encoding """ pos_emb = self.pe[ :, self.pe.size(1) // 2 - size + 1 : self.pe.size(1) // 2 + size, ] return pos_emb
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. Args: offset (int or torch.tensor): start offset size (int): required size of position encoding Returns: torch.Tensor: Corresponding encoding
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, input_layer: str = "conv2d", pos_enc_layer_type: str = "abs_pos", normalize_before: bool = True, static_chunk_size: int = 0, use_dynamic_chunk: bool = False, global_cmvn: torch.nn.Module = None, use_dynamic_left_chunk: bool = False, gradient_checkpointing: bool = False, ): """ 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): the number of decoder blocks dropout_rate (float): dropout rate attention_dropout_rate (float): dropout rate in attention positional_dropout_rate (float): dropout rate after adding positional encoding input_layer (str): input layer type. optional [linear, conv2d, conv2d6, conv2d8] pos_enc_layer_type (str): Encoder positional encoding layer type. opitonal [abs_pos, scaled_abs_pos, rel_pos, no_pos] normalize_before (bool): True: use layer_norm before each sub-block of a layer. False: use layer_norm after each sub-block of a layer. static_chunk_size (int): chunk size for static chunk training and decoding use_dynamic_chunk (bool): whether use dynamic chunk size for training or not, You can only use fixed chunk(chunk_size > 0) or dyanmic chunk size(use_dynamic_chunk = True) global_cmvn (Optional[torch.nn.Module]): Optional GlobalCMVN module use_dynamic_left_chunk (bool): whether use dynamic left chunk in dynamic chunk training key_bias: whether use bias in attention.linear_k, False for whisper models. gradient_checkpointing: rerunning a forward-pass segment for each checkpointed segment during backward. """ super().__init__() self._output_size = output_size self.global_cmvn = global_cmvn self.embed = COSYVOICE_SUBSAMPLE_CLASSES[input_layer]( input_size, output_size, dropout_rate, COSYVOICE_EMB_CLASSES[pos_enc_layer_type](output_size, positional_dropout_rate), ) self.normalize_before = normalize_before self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5) self.static_chunk_size = static_chunk_size self.use_dynamic_chunk = use_dynamic_chunk self.use_dynamic_left_chunk = use_dynamic_left_chunk self.gradient_checkpointing = gradient_checkpointing
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): the number of decoder blocks dropout_rate (float): dropout rate attention_dropout_rate (float): dropout rate in attention positional_dropout_rate (float): dropout rate after adding positional encoding input_layer (str): input layer type. optional [linear, conv2d, conv2d6, conv2d8] pos_enc_layer_type (str): Encoder positional encoding layer type. opitonal [abs_pos, scaled_abs_pos, rel_pos, no_pos] normalize_before (bool): True: use layer_norm before each sub-block of a layer. False: use layer_norm after each sub-block of a layer. static_chunk_size (int): chunk size for static chunk training and decoding use_dynamic_chunk (bool): whether use dynamic chunk size for training or not, You can only use fixed chunk(chunk_size > 0) or dyanmic chunk size(use_dynamic_chunk = True) global_cmvn (Optional[torch.nn.Module]): Optional GlobalCMVN module use_dynamic_left_chunk (bool): whether use dynamic left chunk in dynamic chunk training key_bias: whether use bias in attention.linear_k, False for whisper models. gradient_checkpointing: rerunning a forward-pass segment for each checkpointed segment during backward.
__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) 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. >0: for decoding, use fixed chunk size as set. num_decoding_left_chunks: number of left chunks, this is for decoding, the chunk size is decoding_chunk_size. >=0: use num_decoding_left_chunks <0: use all left chunks Returns: encoder output tensor xs, and subsampled masks xs: padded output tensor (B, T' ~= T/subsample_rate, D) masks: torch.Tensor batch padding mask after subsample (B, 1, T' ~= T/subsample_rate) NOTE(xcsong): We pass the `__call__` method of the modules instead of `forward` to the checkpointing API because `__call__` attaches all the hooks of the module. https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2 """ T = xs.size(1) masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T) if self.global_cmvn is not None: xs = self.global_cmvn(xs) xs, pos_emb, masks = self.embed(xs, masks) mask_pad = masks # (B, 1, T/subsample_rate) chunk_masks = add_optional_chunk_mask(xs, masks, self.use_dynamic_chunk, self.use_dynamic_left_chunk, decoding_chunk_size, self.static_chunk_size, num_decoding_left_chunks) if self.gradient_checkpointing and self.training: xs = self.forward_layers_checkpointed(xs, chunk_masks, pos_emb, mask_pad) else: xs = self.forward_layers(xs, chunk_masks, pos_emb, mask_pad) if self.normalize_before: xs = self.after_norm(xs) # Here we assume the mask is not changed in encoder layers, so just # return the masks before encoder layers, and the masks will be used # for cross attention with decoder later return xs, masks
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. >0: for decoding, use fixed chunk size as set. num_decoding_left_chunks: number of left chunks, this is for decoding, the chunk size is decoding_chunk_size. >=0: use num_decoding_left_chunks <0: use all left chunks Returns: encoder output tensor xs, and subsampled masks xs: padded output tensor (B, T' ~= T/subsample_rate, D) masks: torch.Tensor batch padding mask after subsample (B, 1, T' ~= T/subsample_rate) NOTE(xcsong): We pass the `__call__` method of the modules instead of `forward` to the checkpointing API because `__call__` attaches all the hooks of the module. https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2
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[torch.Tensor, torch.Tensor, torch.Tensor]: """ 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 required_cache_size (int): cache size required for next chunk compuation >=0: actual cache size <0: means all history cache is required att_cache (torch.Tensor): cache tensor for KEY & VALUE in transformer/conformer attention, with shape (elayers, head, cache_t1, d_k * 2), where `head * d_k == hidden-dim` and `cache_t1 == chunk_size * num_decoding_left_chunks`. cnn_cache (torch.Tensor): cache tensor for cnn_module in conformer, (elayers, b=1, hidden-dim, cache_t2), where `cache_t2 == cnn.lorder - 1` Returns: torch.Tensor: output of current input xs, with shape (b=1, chunk_size, hidden-dim). torch.Tensor: new attention cache required for next chunk, with dynamic shape (elayers, head, ?, d_k * 2) depending on required_cache_size. torch.Tensor: new conformer cnn cache required for next chunk, with same shape as the original cnn_cache. """ assert xs.size(0) == 1 # tmp_masks is just for interface compatibility tmp_masks = torch.ones(1, xs.size(1), device=xs.device, dtype=torch.bool) tmp_masks = tmp_masks.unsqueeze(1) if self.global_cmvn is not None: xs = self.global_cmvn(xs) # NOTE(xcsong): Before embed, shape(xs) is (b=1, time, mel-dim) xs, pos_emb, _ = self.embed(xs, tmp_masks, offset) # NOTE(xcsong): After embed, shape(xs) is (b=1, chunk_size, hidden-dim) elayers, cache_t1 = att_cache.size(0), att_cache.size(2) chunk_size = xs.size(1) attention_key_size = cache_t1 + chunk_size pos_emb = self.embed.position_encoding(offset=offset - cache_t1, size=attention_key_size) if required_cache_size < 0: next_cache_start = 0 elif required_cache_size == 0: next_cache_start = attention_key_size else: next_cache_start = max(attention_key_size - required_cache_size, 0) r_att_cache = [] r_cnn_cache = [] for i, layer in enumerate(self.encoders): # NOTE(xcsong): Before layer.forward # shape(att_cache[i:i + 1]) is (1, head, cache_t1, d_k * 2), # shape(cnn_cache[i]) is (b=1, hidden-dim, cache_t2) xs, _, new_att_cache, new_cnn_cache = layer( xs, att_mask, pos_emb, att_cache=att_cache[i:i + 1] if elayers > 0 else att_cache, cnn_cache=cnn_cache[i] if cnn_cache.size(0) > 0 else cnn_cache) # NOTE(xcsong): After layer.forward # shape(new_att_cache) is (1, head, attention_key_size, d_k * 2), # shape(new_cnn_cache) is (b=1, hidden-dim, cache_t2) r_att_cache.append(new_att_cache[:, :, next_cache_start:, :]) r_cnn_cache.append(new_cnn_cache.unsqueeze(0)) if self.normalize_before: xs = self.after_norm(xs) # NOTE(xcsong): shape(r_att_cache) is (elayers, head, ?, d_k * 2), # ? may be larger than cache_t1, it depends on required_cache_size r_att_cache = torch.cat(r_att_cache, dim=0) # NOTE(xcsong): shape(r_cnn_cache) is (e, b=1, hidden-dim, cache_t2) r_cnn_cache = torch.cat(r_cnn_cache, dim=0) return (xs, r_att_cache, r_cnn_cache)
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 required_cache_size (int): cache size required for next chunk compuation >=0: actual cache size <0: means all history cache is required att_cache (torch.Tensor): cache tensor for KEY & VALUE in transformer/conformer attention, with shape (elayers, head, cache_t1, d_k * 2), where `head * d_k == hidden-dim` and `cache_t1 == chunk_size * num_decoding_left_chunks`. cnn_cache (torch.Tensor): cache tensor for cnn_module in conformer, (elayers, b=1, hidden-dim, cache_t2), where `cache_t2 == cnn.lorder - 1` Returns: torch.Tensor: output of current input xs, with shape (b=1, chunk_size, hidden-dim). torch.Tensor: new attention cache required for next chunk, with dynamic shape (elayers, head, ?, d_k * 2) depending on required_cache_size. torch.Tensor: new conformer cnn cache required for next chunk, with same shape as the original cnn_cache.
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 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. transformer/conformer encoder layers output cache 2. convolution in conformer 3. convolution in subsampling However, we don't implement subsampling cache for: 1. We can control subsampling module to output the right result by overlapping input instead of cache left context, even though it wastes some computation, but subsampling only takes a very small fraction of computation in the whole model. 2. Typically, there are several covolution layers with subsampling in subsampling module, it is tricky and complicated to do cache with different convolution layers with different subsampling rate. 3. Currently, nn.Sequential is used to stack all the convolution layers in subsampling, we need to rewrite it to make it work with cache, which is not prefered. Args: xs (torch.Tensor): (1, max_len, dim) chunk_size (int): decoding chunk size """ assert decoding_chunk_size > 0 # The model is trained by static or dynamic chunk assert self.static_chunk_size > 0 or self.use_dynamic_chunk subsampling = self.embed.subsampling_rate context = self.embed.right_context + 1 # Add current frame stride = subsampling * decoding_chunk_size decoding_window = (decoding_chunk_size - 1) * subsampling + context num_frames = xs.size(1) att_cache: torch.Tensor = torch.zeros((0, 0, 0, 0), device=xs.device) cnn_cache: torch.Tensor = torch.zeros((0, 0, 0, 0), device=xs.device) outputs = [] offset = 0 required_cache_size = decoding_chunk_size * num_decoding_left_chunks # Feed forward overlap input step by step for cur in range(0, num_frames - context + 1, stride): end = min(cur + decoding_window, num_frames) chunk_xs = xs[:, cur:end, :] (y, att_cache, cnn_cache) = self.forward_chunk(chunk_xs, offset, required_cache_size, att_cache, cnn_cache) outputs.append(y) offset += y.size(1) ys = torch.cat(outputs, 1) masks = torch.ones((1, 1, ys.size(1)), device=ys.device, dtype=torch.bool) return ys, masks
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. transformer/conformer encoder layers output cache 2. convolution in conformer 3. convolution in subsampling However, we don't implement subsampling cache for: 1. We can control subsampling module to output the right result by overlapping input instead of cache left context, even though it wastes some computation, but subsampling only takes a very small fraction of computation in the whole model. 2. Typically, there are several covolution layers with subsampling in subsampling module, it is tricky and complicated to do cache with different convolution layers with different subsampling rate. 3. Currently, nn.Sequential is used to stack all the convolution layers in subsampling, we need to rewrite it to make it work with cache, which is not prefered. Args: xs (torch.Tensor): (1, max_len, dim) chunk_size (int): decoding chunk size
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, input_layer: str = "conv2d", pos_enc_layer_type: str = "abs_pos", normalize_before: bool = True, static_chunk_size: int = 0, use_dynamic_chunk: bool = False, global_cmvn: torch.nn.Module = None, use_dynamic_left_chunk: bool = False, key_bias: bool = True, selfattention_layer_type: str = "selfattn", activation_type: str = "relu", gradient_checkpointing: bool = False, ): """ Construct TransformerEncoder See Encoder for the meaning of each parameter. """ super().__init__(input_size, output_size, attention_heads, linear_units, num_blocks, dropout_rate, positional_dropout_rate, attention_dropout_rate, input_layer, pos_enc_layer_type, normalize_before, static_chunk_size, use_dynamic_chunk, global_cmvn, use_dynamic_left_chunk, gradient_checkpointing) activation = COSYVOICE_ACTIVATION_CLASSES[activation_type]() self.encoders = torch.nn.ModuleList([ TransformerEncoderLayer( output_size, COSYVOICE_ATTENTION_CLASSES[selfattention_layer_type](attention_heads, output_size, attention_dropout_rate, key_bias), PositionwiseFeedForward(output_size, linear_units, dropout_rate, activation), dropout_rate, normalize_before) for _ in range(num_blocks) ])
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, input_layer: str = "conv2d", pos_enc_layer_type: str = "rel_pos", normalize_before: bool = True, static_chunk_size: int = 0, use_dynamic_chunk: bool = False, global_cmvn: torch.nn.Module = None, use_dynamic_left_chunk: bool = False, positionwise_conv_kernel_size: int = 1, macaron_style: bool = True, selfattention_layer_type: str = "rel_selfattn", activation_type: str = "swish", use_cnn_module: bool = True, cnn_module_kernel: int = 15, causal: bool = False, cnn_module_norm: str = "batch_norm", key_bias: bool = True, gradient_checkpointing: bool = False, ): """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. selfattention_layer_type (str): Encoder attention layer type, the parameter has no effect now, it's just for configure compatibility. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. cnn_module_kernel (int): Kernel size of convolution module. causal (bool): whether to use causal convolution or not. key_bias: whether use bias in attention.linear_k, False for whisper models. """ super().__init__(input_size, output_size, attention_heads, linear_units, num_blocks, dropout_rate, positional_dropout_rate, attention_dropout_rate, input_layer, pos_enc_layer_type, normalize_before, static_chunk_size, use_dynamic_chunk, global_cmvn, use_dynamic_left_chunk, gradient_checkpointing) activation = COSYVOICE_ACTIVATION_CLASSES[activation_type]() # self-attention module definition encoder_selfattn_layer_args = ( attention_heads, output_size, attention_dropout_rate, key_bias, ) # feed-forward module definition positionwise_layer_args = ( output_size, linear_units, dropout_rate, activation, ) # convolution module definition convolution_layer_args = (output_size, cnn_module_kernel, activation, cnn_module_norm, causal) self.encoders = torch.nn.ModuleList([ ConformerEncoderLayer( output_size, COSYVOICE_ATTENTION_CLASSES[selfattention_layer_type]( *encoder_selfattn_layer_args), PositionwiseFeedForward(*positionwise_layer_args), PositionwiseFeedForward( *positionwise_layer_args) if macaron_style else None, ConvolutionModule( *convolution_layer_args) if use_cnn_module else None, dropout_rate, normalize_before, ) for _ in range(num_blocks) ])
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. selfattention_layer_type (str): Encoder attention layer type, the parameter has no effect now, it's just for configure compatibility. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. cnn_module_kernel (int): Kernel size of convolution module. causal (bool): whether to use causal convolution or not. key_bias: whether use bias in attention.linear_k, False for whisper models.
__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, input_layer: str = "conv2d", pos_enc_layer_type: str = "rel_pos", normalize_before: bool = True, static_chunk_size: int = 0, use_dynamic_chunk: bool = False, global_cmvn: torch.nn.Module = None, use_dynamic_left_chunk: bool = False, positionwise_conv_kernel_size: int = 1, macaron_style: bool = True, selfattention_layer_type: str = "rel_selfattn", activation_type: str = "swish", use_cnn_module: bool = True, cnn_module_kernel: int = 15, causal: bool = False, cnn_module_norm: str = "batch_norm", key_bias: bool = True, gradient_checkpointing: bool = False, block_size=25, ): """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. selfattention_layer_type (str): Encoder attention layer type, the parameter has no effect now, it's just for configure compatibility. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. cnn_module_kernel (int): Kernel size of convolution module. causal (bool): whether to use causal convolution or not. key_bias: whether use bias in attention.linear_k, False for whisper models. """ super().__init__(input_size, output_size, attention_heads, linear_units, num_blocks, dropout_rate, positional_dropout_rate, attention_dropout_rate, input_layer, pos_enc_layer_type, normalize_before, static_chunk_size, use_dynamic_chunk, global_cmvn, use_dynamic_left_chunk, gradient_checkpointing) activation = COSYVOICE_ACTIVATION_CLASSES[activation_type]() # self-attention module definition encoder_selfattn_layer_args = ( attention_heads, output_size, attention_dropout_rate, key_bias, block_size, ) # feed-forward module definition positionwise_layer_args = ( output_size, linear_units, dropout_rate, activation, ) # convolution module definition convolution_layer_args = (output_size, cnn_module_kernel, activation, cnn_module_norm, causal) self.encoders = torch.nn.ModuleList([ ConformerEncoderLayer( output_size, COSYVOICE_ATTENTION_CLASSES[selfattention_layer_type]( *encoder_selfattn_layer_args), PositionwiseFeedForward(*positionwise_layer_args), PositionwiseFeedForward( *positionwise_layer_args) if macaron_style else None, ConvolutionModule( *convolution_layer_args) if use_cnn_module else None, dropout_rate, normalize_before, ) for _ in range(num_blocks) ]) self.block_size=block_size
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. selfattention_layer_type (str): Encoder attention layer type, the parameter has no effect now, it's just for configure compatibility. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. cnn_module_kernel (int): Kernel size of convolution module. causal (bool): whether to use causal convolution or not. key_bias: whether use bias in attention.linear_k, False for whisper models.
__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. Args: x (torch.Tensor): prediction (batch, seqlen, class) target (torch.Tensor): target signal masked with self.padding_id (batch, seqlen) Returns: loss (torch.Tensor) : The KL loss, scalar float value """ assert x.size(2) == self.size batch_size = x.size(0) x = x.view(-1, self.size) target = target.view(-1) # use zeros_like instead of torch.no_grad() for true_dist, # since no_grad() can not be exported by JIT true_dist = torch.zeros_like(x) true_dist.fill_(self.smoothing / (self.size - 1)) ignore = target == self.padding_idx # (B,) total = len(target) - ignore.sum().item() target = target.masked_fill(ignore, 0) # avoid -1 index true_dist.scatter_(1, target.unsqueeze(1), self.confidence) kl = self.criterion(torch.log_softmax(x, dim=1), true_dist) denom = total if self.normalize_length else batch_size return kl.masked_fill(ignore.unsqueeze(1), 0).sum() / denom
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) target (torch.Tensor): target signal masked with self.padding_id (batch, seqlen) Returns: loss (torch.Tensor) : The KL loss, scalar float value
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, D) # (B*L, D) router = self.gate(xs) # (B*L, n_expert) logits, indices = torch.topk( router, self.n_expert_per_token ) # probs:(B*L, n_expert), indices: (B*L, n_expert) weights = torch.nn.functional.softmax( logits, dim=1, dtype=torch.float).to(dtype=xs.dtype) # (B*L, n_expert_per_token) output = torch.zeros_like(xs) # (B*L, D) for i, expert in enumerate(self.experts): mask = indices == i batch_idx, ith_expert = torch.where(mask) output[batch_idx] += weights[batch_idx, ith_expert, None] * expert( xs[batch_idx]) return output.view(B, L, D)
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 mask (#batch, 1, time). Returns: torch.Tensor: linear input tensor (#batch, time', odim), where time' = time . torch.Tensor: linear input mask (#batch, 1, time'), where time' = time . """ x = self.embed(x) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask
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 mask (#batch, 1, time'), where time' = time .
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 mask (#batch, 1, time). Returns: torch.Tensor: linear input tensor (#batch, time', odim), where time' = time . torch.Tensor: linear input mask (#batch, 1, time'), where time' = time . """ x = self.out(x) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask
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 mask (#batch, 1, time'), where time' = time .
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): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 2. torch.Tensor: Subsampled mask (#batch, 1, time'), where time' = time // 2. torch.Tensor: positional encoding """ time = x.size(1) x = x.transpose(1, 2) # (b, f, t) x = self.conv(x) x = x.transpose(1, 2) # (b, t, f) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask[:, :, (time + 1) % 2::2]
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 mask (#batch, 1, time'), where time' = time // 2. torch.Tensor: positional encoding
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): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 4. torch.Tensor: Subsampled mask (#batch, 1, time'), where time' = time // 4. torch.Tensor: positional encoding """ x = x.unsqueeze(1) # (b, c=1, t, f) x = self.conv(x) b, c, t, f = x.size() x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f)) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask[:, :, 2::2][:, :, 2::2]
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 mask (#batch, 1, time'), where time' = time // 4. torch.Tensor: positional encoding
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): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 6. torch.Tensor: Subsampled mask (#batch, 1, time'), where time' = time // 6. torch.Tensor: positional encoding """ x = x.unsqueeze(1) # (b, c, t, f) x = self.conv(x) b, c, t, f = x.size() x = self.linear(x.transpose(1, 2).contiguous().view(b, t, c * f)) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask[:, :, 2::2][:, :, 4::3]
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 mask (#batch, 1, time'), where time' = time // 6. torch.Tensor: positional encoding
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): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 8. torch.Tensor: Subsampled mask (#batch, 1, time'), where time' = time // 8. torch.Tensor: positional encoding """ x = x.unsqueeze(1) # (b, c, t, f) x = self.conv(x) b, c, t, f = x.size() x = self.linear(x.transpose(1, 2).contiguous().view(b, t, c * f)) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask[:, :, 2::2][:, :, 2::2][:, :, 2::2]
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 mask (#batch, 1, time'), where time' = time // 8. torch.Tensor: positional encoding
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 mask (#batch, 1, time). Returns: torch.Tensor: linear input tensor (#batch, time', odim), where time' = time . torch.Tensor: linear input mask (#batch, 1, time'), where time' = time . """ x = self.out(x) x, pos_emb = self.pos_enc(x, offset) return x, pos_emb, x_mask
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 mask (#batch, 1, time'), where time' = time .
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: >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)] >>> x [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])] >>> pad_list(x, 0) tensor([[1., 1., 1., 1.], [1., 1., 0., 0.], [1., 0., 0., 0.]]) """ max_len = max([len(item) for item in xs]) batchs = len(xs) ndim = xs[0].ndim if ndim == 1: pad_res = torch.zeros(batchs, max_len, dtype=xs[0].dtype, device=xs[0].device) elif ndim == 2: pad_res = torch.zeros(batchs, max_len, xs[0].shape[1], dtype=xs[0].dtype, device=xs[0].device) elif ndim == 3: pad_res = torch.zeros(batchs, max_len, xs[0].shape[1], xs[0].shape[2], dtype=xs[0].dtype, device=xs[0].device) else: raise ValueError(f"Unsupported ndim: {ndim}") pad_res.fill_(pad_value) for i in range(batchs): pad_res[i, :len(xs[i])] = xs[i] return pad_res
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)] >>> x [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])] >>> pad_list(x, 0) tensor([[1., 1., 1., 1.], [1., 1., 0., 0.], [1., 0., 0., 0.]])
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