id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
8,385
import librosa import numpy as np from pycwt import wavelet from scipy.interpolate import interp1d def get_cont_lf0(f0, frame_period=5.0): uv, cont_f0_lpf = convert_continuos_f0(f0) # cont_f0_lpf = low_pass_filter(cont_f0_lpf, int(1.0 / (frame_period * 0.001)), cutoff=20) cont_lf0_lpf = np.log(cont_f0_lpf) return uv, cont_lf0_lpf def get_lf0_cwt(lf0): ''' input: signal of shape (N) output: Wavelet_lf0 of shape(10, N), scales of shape(10) ''' mother = wavelet.MexicanHat() dt = 0.005 dj = 1 s0 = dt * 2 J = 9 Wavelet_lf0, scales, _, _, _, _ = wavelet.cwt(np.squeeze(lf0), dt, dj, s0, J, mother) # Wavelet.shape => (J + 1, len(lf0)) Wavelet_lf0 = np.real(Wavelet_lf0).T return Wavelet_lf0, scales def norm_scale(Wavelet_lf0): Wavelet_lf0_norm = np.zeros((Wavelet_lf0.shape[0], Wavelet_lf0.shape[1])) mean = Wavelet_lf0.mean(0)[None, :] std = Wavelet_lf0.std(0)[None, :] Wavelet_lf0_norm = (Wavelet_lf0 - mean) / std return Wavelet_lf0_norm, mean, std def normalize_cwt_lf0(f0, mean, std): uv, cont_lf0_lpf = get_cont_lf0(f0) cont_lf0_norm = (cont_lf0_lpf - mean) / std Wavelet_lf0, scales = get_lf0_cwt(cont_lf0_norm) Wavelet_lf0_norm, _, _ = norm_scale(Wavelet_lf0) return Wavelet_lf0_norm
null
8,386
import librosa import numpy as np from pycwt import wavelet from scipy.interpolate import interp1d def get_cont_lf0(f0, frame_period=5.0): uv, cont_f0_lpf = convert_continuos_f0(f0) # cont_f0_lpf = low_pass_filter(cont_f0_lpf, int(1.0 / (frame_period * 0.001)), cutoff=20) cont_lf0_lpf = np.log(cont_f0_lpf) return uv, cont_lf0_lpf def get_lf0_cwt(lf0): ''' input: signal of shape (N) output: Wavelet_lf0 of shape(10, N), scales of shape(10) ''' mother = wavelet.MexicanHat() dt = 0.005 dj = 1 s0 = dt * 2 J = 9 Wavelet_lf0, scales, _, _, _, _ = wavelet.cwt(np.squeeze(lf0), dt, dj, s0, J, mother) # Wavelet.shape => (J + 1, len(lf0)) Wavelet_lf0 = np.real(Wavelet_lf0).T return Wavelet_lf0, scales def norm_scale(Wavelet_lf0): Wavelet_lf0_norm = np.zeros((Wavelet_lf0.shape[0], Wavelet_lf0.shape[1])) mean = Wavelet_lf0.mean(0)[None, :] std = Wavelet_lf0.std(0)[None, :] Wavelet_lf0_norm = (Wavelet_lf0 - mean) / std return Wavelet_lf0_norm, mean, std def get_lf0_cwt_norm(f0s, mean, std): uvs = list() cont_lf0_lpfs = list() cont_lf0_lpf_norms = list() Wavelet_lf0s = list() Wavelet_lf0s_norm = list() scaless = list() means = list() stds = list() for f0 in f0s: uv, cont_lf0_lpf = get_cont_lf0(f0) cont_lf0_lpf_norm = (cont_lf0_lpf - mean) / std Wavelet_lf0, scales = get_lf0_cwt(cont_lf0_lpf_norm) # [560,10] Wavelet_lf0_norm, mean_scale, std_scale = norm_scale(Wavelet_lf0) # [560,10],[1,10],[1,10] Wavelet_lf0s_norm.append(Wavelet_lf0_norm) uvs.append(uv) cont_lf0_lpfs.append(cont_lf0_lpf) cont_lf0_lpf_norms.append(cont_lf0_lpf_norm) Wavelet_lf0s.append(Wavelet_lf0) scaless.append(scales) means.append(mean_scale) stds.append(std_scale) return Wavelet_lf0s_norm, scaless, means, stds
null
8,387
import librosa import numpy as np from pycwt import wavelet from scipy.interpolate import interp1d def inverse_cwt_torch(Wavelet_lf0, scales): import torch b = ((torch.arange(0, len(scales)).float().to(Wavelet_lf0.device)[None, None, :] + 1 + 2.5) ** (-2.5)) lf0_rec = Wavelet_lf0 * b lf0_rec_sum = lf0_rec.sum(-1) lf0_rec_sum = (lf0_rec_sum - lf0_rec_sum.mean(-1, keepdim=True)) / lf0_rec_sum.std(-1, keepdim=True) return lf0_rec_sum def inverse_cwt(Wavelet_lf0, scales): b = ((np.arange(0, len(scales))[None, None, :] + 1 + 2.5) ** (-2.5)) lf0_rec = Wavelet_lf0 * b lf0_rec_sum = lf0_rec.sum(-1) lf0_rec_sum = (lf0_rec_sum - lf0_rec_sum.mean(-1, keepdims=True)) / lf0_rec_sum.std(-1, keepdims=True) return lf0_rec_sum def cwt2f0(cwt_spec, mean, std, cwt_scales): assert len(mean.shape) == 1 and len(std.shape) == 1 and len(cwt_spec.shape) == 3 import torch if isinstance(cwt_spec, torch.Tensor): f0 = inverse_cwt_torch(cwt_spec, cwt_scales) f0 = f0 * std[:, None] + mean[:, None] f0 = f0.exp() # [B, T] else: f0 = inverse_cwt(cwt_spec, cwt_scales) f0 = f0 * std[:, None] + mean[:, None] f0 = np.exp(f0) # [B, T] return f0
null
8,388
import os import traceback from multiprocessing import Queue, Process def chunked_worker(worker_id, map_func, args, results_queue=None, init_ctx_func=None): def chunked_multiprocess_run(map_func, args, num_workers=None, ordered=True, init_ctx_func=None, q_max_size=1000): args = zip(range(len(args)), args) args = list(args) n_jobs = len(args) if num_workers is None: num_workers = int(os.getenv('N_PROC', os.cpu_count())) results_queues = [] if ordered: for i in range(num_workers): results_queues.append(Queue(maxsize=q_max_size // num_workers)) else: results_queue = Queue(maxsize=q_max_size) for i in range(num_workers): results_queues.append(results_queue) workers = [] for i in range(num_workers): args_worker = args[i::num_workers] p = Process(target=chunked_worker, args=( i, map_func, args_worker, results_queues[i], init_ctx_func), daemon=True) workers.append(p) p.start() for n_finished in range(n_jobs): results_queue = results_queues[n_finished % num_workers] job_idx, res = results_queue.get() assert job_idx == n_finished or not ordered, (job_idx, n_finished) yield res for w in workers: w.join() w.close()
null
8,389
import os import traceback from multiprocessing import Queue, Process def multiprocess_run_tqdm(map_func, args, num_workers=None, ordered=True, init_ctx_func=None, multithread=False, desc=None): for i, res in tqdm(enumerate( multiprocess_run(map_func, args, num_workers, ordered, init_ctx_func, multithread)), total=len(args), desc=desc): yield i, res
null
8,390
import matplotlib.pyplot as plt import numpy as np import torch def spec_to_figure(spec, vmin=None, vmax=None): if isinstance(spec, torch.Tensor): spec = spec.cpu().numpy() fig = plt.figure(figsize=(12, 6)) plt.pcolor(spec.T, vmin=vmin, vmax=vmax) return fig
null
8,391
import matplotlib.pyplot as plt import numpy as np import torch LINE_COLORS = ['w', 'r', 'y', 'cyan', 'm', 'b', 'lime'] def spec_f0_to_figure(spec, f0s, figsize=None): max_y = spec.shape[1] if isinstance(spec, torch.Tensor): spec = spec.detach().cpu().numpy() f0s = {k: f0.detach().cpu().numpy() for k, f0 in f0s.items()} f0s = {k: f0 / 10 for k, f0 in f0s.items()} fig = plt.figure(figsize=(12, 6) if figsize is None else figsize) plt.pcolor(spec.T) for i, (k, f0) in enumerate(f0s.items()): plt.plot(f0.clip(0, max_y), label=k, c=LINE_COLORS[i], linewidth=1, alpha=0.8) plt.legend() return fig
null
8,392
import matplotlib.pyplot as plt import numpy as np import torch def dur_to_figure(dur_gt, dur_pred, txt): dur_gt = dur_gt.long().cpu().numpy() dur_pred = dur_pred.long().cpu().numpy() dur_gt = np.cumsum(dur_gt) dur_pred = np.cumsum(dur_pred) fig = plt.figure(figsize=(12, 6)) for i in range(len(dur_gt)): shift = (i % 8) + 1 plt.text(dur_gt[i], shift, txt[i]) plt.text(dur_pred[i], 10 + shift, txt[i]) plt.vlines(dur_gt[i], 0, 10, colors='b') # blue is gt plt.vlines(dur_pred[i], 10, 20, colors='r') # red is pred return fig
null
8,393
import matplotlib.pyplot as plt import numpy as np import torch def f0_to_figure(f0_gt, f0_cwt=None, f0_pred=None): fig = plt.figure() f0_gt = f0_gt.cpu().numpy() plt.plot(f0_gt, color='r', label='gt') if f0_cwt is not None: f0_cwt = f0_cwt.cpu().numpy() plt.plot(f0_cwt, color='b', label='cwt') if f0_pred is not None: f0_pred = f0_pred.cpu().numpy() plt.plot(f0_pred, color='green', label='pred') plt.legend() return fig
null
8,394
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `make_positions` function. Write a Python function `def make_positions(tensor, padding_idx)` to solve the following problem: Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. Here is the function: def make_positions(tensor, padding_idx): """Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. """ # The series of casts and type-conversions here are carefully # balanced to both work with ONNX export and XLA. In particular XLA # prefers ints, cumsum defaults to output longs, and ONNX doesn't know # how to handle the dtype kwarg in cumsum. mask = tensor.ne(padding_idx).int() return ( torch.cumsum(mask, dim=1).type_as(mask) * mask ).long() + padding_idx
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored.
8,395
from collections import defaultdict import torch import torch.nn.functional as F def sequence_mask(lengths, maxlen, dtype=torch.bool): if maxlen is None: maxlen = lengths.max() mask = ~(torch.ones((len(lengths), maxlen)).to(lengths.device).cumsum(dim=1).t() > lengths).t() mask.type(dtype) return mask
null
8,396
from collections import defaultdict import torch import torch.nn.functional as F def _get_full_incremental_state_key(module_instance, key): module_name = module_instance.__class__.__name__ # assign a unique ID to each module instance, so that incremental state is # not shared across module instances if not hasattr(module_instance, '_instance_id'): INCREMENTAL_STATE_INSTANCE_ID[module_name] += 1 module_instance._instance_id = INCREMENTAL_STATE_INSTANCE_ID[module_name] return '{}.{}.{}'.format(module_name, module_instance._instance_id, key) The provided code snippet includes necessary dependencies for implementing the `get_incremental_state` function. Write a Python function `def get_incremental_state(module, incremental_state, key)` to solve the following problem: Helper for getting incremental state for an nn.Module. Here is the function: def get_incremental_state(module, incremental_state, key): """Helper for getting incremental state for an nn.Module.""" full_key = _get_full_incremental_state_key(module, key) if incremental_state is None or full_key not in incremental_state: return None return incremental_state[full_key]
Helper for getting incremental state for an nn.Module.
8,397
from collections import defaultdict import torch import torch.nn.functional as F def _get_full_incremental_state_key(module_instance, key): module_name = module_instance.__class__.__name__ # assign a unique ID to each module instance, so that incremental state is # not shared across module instances if not hasattr(module_instance, '_instance_id'): INCREMENTAL_STATE_INSTANCE_ID[module_name] += 1 module_instance._instance_id = INCREMENTAL_STATE_INSTANCE_ID[module_name] return '{}.{}.{}'.format(module_name, module_instance._instance_id, key) The provided code snippet includes necessary dependencies for implementing the `set_incremental_state` function. Write a Python function `def set_incremental_state(module, incremental_state, key, value)` to solve the following problem: Helper for setting incremental state for an nn.Module. Here is the function: def set_incremental_state(module, incremental_state, key, value): """Helper for setting incremental state for an nn.Module.""" if incremental_state is not None: full_key = _get_full_incremental_state_key(module, key) incremental_state[full_key] = value
Helper for setting incremental state for an nn.Module.
8,398
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `fill_with_neg_inf` function. Write a Python function `def fill_with_neg_inf(t)` to solve the following problem: FP16-compatible function that fills a tensor with -inf. Here is the function: def fill_with_neg_inf(t): """FP16-compatible function that fills a tensor with -inf.""" return t.float().fill_(float('-inf')).type_as(t)
FP16-compatible function that fills a tensor with -inf.
8,399
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `fill_with_neg_inf2` function. Write a Python function `def fill_with_neg_inf2(t)` to solve the following problem: FP16-compatible function that fills a tensor with -inf. Here is the function: def fill_with_neg_inf2(t): """FP16-compatible function that fills a tensor with -inf.""" return t.float().fill_(-1e8).type_as(t)
FP16-compatible function that fills a tensor with -inf.
8,400
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_focus_rate` function. Write a Python function `def get_focus_rate(attn, src_padding_mask=None, tgt_padding_mask=None)` to solve the following problem: attn: bs x L_t x L_s Here is the function: def get_focus_rate(attn, src_padding_mask=None, tgt_padding_mask=None): ''' attn: bs x L_t x L_s ''' if src_padding_mask is not None: attn = attn * (1 - src_padding_mask.float())[:, None, :] if tgt_padding_mask is not None: attn = attn * (1 - tgt_padding_mask.float())[:, :, None] focus_rate = attn.max(-1).values.sum(-1) focus_rate = focus_rate / attn.sum(-1).sum(-1) return focus_rate
attn: bs x L_t x L_s
8,401
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_phone_coverage_rate` function. Write a Python function `def get_phone_coverage_rate(attn, src_padding_mask=None, src_seg_mask=None, tgt_padding_mask=None)` to solve the following problem: attn: bs x L_t x L_s Here is the function: def get_phone_coverage_rate(attn, src_padding_mask=None, src_seg_mask=None, tgt_padding_mask=None): ''' attn: bs x L_t x L_s ''' src_mask = attn.new(attn.size(0), attn.size(-1)).bool().fill_(False) if src_padding_mask is not None: src_mask |= src_padding_mask if src_seg_mask is not None: src_mask |= src_seg_mask attn = attn * (1 - src_mask.float())[:, None, :] if tgt_padding_mask is not None: attn = attn * (1 - tgt_padding_mask.float())[:, :, None] phone_coverage_rate = attn.max(1).values.sum(-1) # phone_coverage_rate = phone_coverage_rate / attn.sum(-1).sum(-1) phone_coverage_rate = phone_coverage_rate / (1 - src_mask.float()).sum(-1) return phone_coverage_rate
attn: bs x L_t x L_s
8,402
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_diagonal_focus_rate` function. Write a Python function `def get_diagonal_focus_rate(attn, attn_ks, target_len, src_padding_mask=None, tgt_padding_mask=None, band_mask_factor=5, band_width=50)` to solve the following problem: attn: bx x L_t x L_s attn_ks: shape: tensor with shape [batch_size], input_lens/output_lens diagonal: y=k*x (k=attn_ks, x:output, y:input) 1 0 0 0 1 0 0 0 1 y>=k*(x-width) and y<=k*(x+width):1 else:0 Here is the function: def get_diagonal_focus_rate(attn, attn_ks, target_len, src_padding_mask=None, tgt_padding_mask=None, band_mask_factor=5, band_width=50): ''' attn: bx x L_t x L_s attn_ks: shape: tensor with shape [batch_size], input_lens/output_lens diagonal: y=k*x (k=attn_ks, x:output, y:input) 1 0 0 0 1 0 0 0 1 y>=k*(x-width) and y<=k*(x+width):1 else:0 ''' # width = min(target_len/band_mask_factor, 50) width1 = target_len / band_mask_factor width2 = target_len.new(target_len.size()).fill_(band_width) width = torch.where(width1 < width2, width1, width2).float() base = torch.ones(attn.size()).to(attn.device) zero = torch.zeros(attn.size()).to(attn.device) x = torch.arange(0, attn.size(1)).to(attn.device)[None, :, None].float() * base y = torch.arange(0, attn.size(2)).to(attn.device)[None, None, :].float() * base cond = (y - attn_ks[:, None, None] * x) cond1 = cond + attn_ks[:, None, None] * width[:, None, None] cond2 = cond - attn_ks[:, None, None] * width[:, None, None] mask1 = torch.where(cond1 < 0, zero, base) mask2 = torch.where(cond2 > 0, zero, base) mask = mask1 * mask2 if src_padding_mask is not None: attn = attn * (1 - src_padding_mask.float())[:, None, :] if tgt_padding_mask is not None: attn = attn * (1 - tgt_padding_mask.float())[:, :, None] diagonal_attn = attn * mask diagonal_focus_rate = diagonal_attn.sum(-1).sum(-1) / attn.sum(-1).sum(-1) return diagonal_focus_rate, mask
attn: bx x L_t x L_s attn_ks: shape: tensor with shape [batch_size], input_lens/output_lens diagonal: y=k*x (k=attn_ks, x:output, y:input) 1 0 0 0 1 0 0 0 1 y>=k*(x-width) and y<=k*(x+width):1 else:0
8,403
from collections import defaultdict import torch import torch.nn.functional as F def softmax(x, dim): return F.softmax(x, dim=dim, dtype=torch.float32) The provided code snippet includes necessary dependencies for implementing the `select_attn` function. Write a Python function `def select_attn(attn_logits, type='best')` to solve the following problem: :param attn_logits: [n_layers, B, n_head, T_sp, T_txt] :return: Here is the function: def select_attn(attn_logits, type='best'): """ :param attn_logits: [n_layers, B, n_head, T_sp, T_txt] :return: """ encdec_attn = torch.stack(attn_logits, 0).transpose(1, 2) # [n_layers * n_head, B, T_sp, T_txt] encdec_attn = (encdec_attn.reshape([-1, *encdec_attn.shape[2:]])).softmax(-1) if type == 'best': indices = encdec_attn.max(-1).values.sum(-1).argmax(0) encdec_attn = encdec_attn.gather( 0, indices[None, :, None, None].repeat(1, 1, encdec_attn.size(-2), encdec_attn.size(-1)))[0] return encdec_attn elif type == 'mean': return encdec_attn.mean(0)
:param attn_logits: [n_layers, B, n_head, T_sp, T_txt] :return:
8,404
from collections import defaultdict import torch import torch.nn.functional as F def make_pad_mask(lengths, xs=None, length_dim=-1): """Make mask tensor containing indices of padded part. Args: lengths (LongTensor or List): Batch of lengths (B,). xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor. length_dim (int, optional): Dimension indicator of the above tensor. See the example. Returns: Tensor: Mask tensor containing indices of padded part. dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (including 1.2) Examples: With only lengths. >>> lengths = [5, 3, 2] >>> make_non_pad_mask(lengths) masks = [[0, 0, 0, 0 ,0], [0, 0, 0, 1, 1], [0, 0, 1, 1, 1]] With the reference tensor. >>> xs = torch.zeros((3, 2, 4)) >>> make_pad_mask(lengths, xs) tensor([[[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 1], [0, 0, 0, 1]], [[0, 0, 1, 1], [0, 0, 1, 1]]], dtype=torch.uint8) >>> xs = torch.zeros((3, 2, 6)) >>> make_pad_mask(lengths, xs) tensor([[[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1]], [[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]], [[0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8) With the reference tensor and dimension indicator. >>> xs = torch.zeros((3, 6, 6)) >>> make_pad_mask(lengths, xs, 1) tensor([[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1]], [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]], dtype=torch.uint8) >>> make_pad_mask(lengths, xs, 2) tensor([[[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1]], [[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]], [[0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1]]], dtype=torch.uint8) """ if length_dim == 0: raise ValueError("length_dim cannot be 0: {}".format(length_dim)) if not isinstance(lengths, list): lengths = lengths.tolist() bs = int(len(lengths)) if xs is None: maxlen = int(max(lengths)) else: maxlen = xs.size(length_dim) seq_range = torch.arange(0, maxlen, dtype=torch.int64) seq_range_expand = seq_range.unsqueeze(0).expand(bs, maxlen) seq_length_expand = seq_range_expand.new(lengths).unsqueeze(-1) mask = seq_range_expand >= seq_length_expand if xs is not None: assert xs.size(0) == bs, (xs.size(0), bs) if length_dim < 0: length_dim = xs.dim() + length_dim # ind = (:, None, ..., None, :, , None, ..., None) ind = tuple( slice(None) if i in (0, length_dim) else None for i in range(xs.dim()) ) mask = mask[ind].expand_as(xs).to(xs.device) return mask The provided code snippet includes necessary dependencies for implementing the `make_non_pad_mask` function. Write a Python function `def make_non_pad_mask(lengths, xs=None, length_dim=-1)` to solve the following problem: Make mask tensor containing indices of non-padded part. Args: lengths (LongTensor or List): Batch of lengths (B,). xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor. length_dim (int, optional): Dimension indicator of the above tensor. See the example. Returns: ByteTensor: mask tensor containing indices of padded part. dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (including 1.2) Examples: With only lengths. >>> lengths = [5, 3, 2] >>> make_non_pad_mask(lengths) masks = [[1, 1, 1, 1 ,1], [1, 1, 1, 0, 0], [1, 1, 0, 0, 0]] With the reference tensor. >>> xs = torch.zeros((3, 2, 4)) >>> make_non_pad_mask(lengths, xs) tensor([[[1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 0], [1, 1, 1, 0]], [[1, 1, 0, 0], [1, 1, 0, 0]]], dtype=torch.uint8) >>> xs = torch.zeros((3, 2, 6)) >>> make_non_pad_mask(lengths, xs) tensor([[[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]], [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0]], [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) With the reference tensor and dimension indicator. >>> xs = torch.zeros((3, 6, 6)) >>> make_non_pad_mask(lengths, xs, 1) tensor([[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]], dtype=torch.uint8) >>> make_non_pad_mask(lengths, xs, 2) tensor([[[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]], [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0]], [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) Here is the function: def make_non_pad_mask(lengths, xs=None, length_dim=-1): """Make mask tensor containing indices of non-padded part. Args: lengths (LongTensor or List): Batch of lengths (B,). xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor. length_dim (int, optional): Dimension indicator of the above tensor. See the example. Returns: ByteTensor: mask tensor containing indices of padded part. dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (including 1.2) Examples: With only lengths. >>> lengths = [5, 3, 2] >>> make_non_pad_mask(lengths) masks = [[1, 1, 1, 1 ,1], [1, 1, 1, 0, 0], [1, 1, 0, 0, 0]] With the reference tensor. >>> xs = torch.zeros((3, 2, 4)) >>> make_non_pad_mask(lengths, xs) tensor([[[1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 0], [1, 1, 1, 0]], [[1, 1, 0, 0], [1, 1, 0, 0]]], dtype=torch.uint8) >>> xs = torch.zeros((3, 2, 6)) >>> make_non_pad_mask(lengths, xs) tensor([[[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]], [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0]], [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) With the reference tensor and dimension indicator. >>> xs = torch.zeros((3, 6, 6)) >>> make_non_pad_mask(lengths, xs, 1) tensor([[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]], dtype=torch.uint8) >>> make_non_pad_mask(lengths, xs, 2) tensor([[[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]], [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0]], [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) """ return ~make_pad_mask(lengths, xs, length_dim)
Make mask tensor containing indices of non-padded part. Args: lengths (LongTensor or List): Batch of lengths (B,). xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor. length_dim (int, optional): Dimension indicator of the above tensor. See the example. Returns: ByteTensor: mask tensor containing indices of padded part. dtype=torch.uint8 in PyTorch 1.2- dtype=torch.bool in PyTorch 1.2+ (including 1.2) Examples: With only lengths. >>> lengths = [5, 3, 2] >>> make_non_pad_mask(lengths) masks = [[1, 1, 1, 1 ,1], [1, 1, 1, 0, 0], [1, 1, 0, 0, 0]] With the reference tensor. >>> xs = torch.zeros((3, 2, 4)) >>> make_non_pad_mask(lengths, xs) tensor([[[1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 0], [1, 1, 1, 0]], [[1, 1, 0, 0], [1, 1, 0, 0]]], dtype=torch.uint8) >>> xs = torch.zeros((3, 2, 6)) >>> make_non_pad_mask(lengths, xs) tensor([[[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]], [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0]], [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8) With the reference tensor and dimension indicator. >>> xs = torch.zeros((3, 6, 6)) >>> make_non_pad_mask(lengths, xs, 1) tensor([[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]], dtype=torch.uint8) >>> make_non_pad_mask(lengths, xs, 2) tensor([[[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0]], [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0]], [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0]]], dtype=torch.uint8)
8,405
from collections import defaultdict import torch import torch.nn.functional as F def get_mask_from_lengths(lengths): max_len = torch.max(lengths).item() ids = torch.arange(0, max_len).to(lengths.device) mask = (ids < lengths.unsqueeze(1)).bool() return mask
null
8,406
from collections import defaultdict import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `group_hidden_by_segs` function. Write a Python function `def group_hidden_by_segs(h, seg_ids, max_len)` to solve the following problem: :param h: [B, T, H] :param seg_ids: [B, T] :return: h_ph: [B, T_ph, H] Here is the function: def group_hidden_by_segs(h, seg_ids, max_len): """ :param h: [B, T, H] :param seg_ids: [B, T] :return: h_ph: [B, T_ph, H] """ B, T, H = h.shape h_gby_segs = h.new_zeros([B, max_len + 1, H]).scatter_add_(1, seg_ids[:, :, None].repeat([1, 1, H]), h) all_ones = h.new_ones(h.shape[:2]) cnt_gby_segs = h.new_zeros([B, max_len + 1]).scatter_add_(1, seg_ids, all_ones).contiguous() h_gby_segs = h_gby_segs[:, 1:] cnt_gby_segs = cnt_gby_segs[:, 1:] h_gby_segs = h_gby_segs / torch.clamp(cnt_gby_segs[:, :, None], min=1) return h_gby_segs, cnt_gby_segs
:param h: [B, T, H] :param seg_ids: [B, T] :return: h_ph: [B, T_ph, H]
8,407
from collections import defaultdict import torch import torch.nn.functional as F def mel2token_to_dur(mel2token, T_txt=None, max_dur=None): is_torch = isinstance(mel2token, torch.Tensor) has_batch_dim = True if not is_torch: mel2token = torch.LongTensor(mel2token) if T_txt is None: T_txt = mel2token.max() if len(mel2token.shape) == 1: mel2token = mel2token[None, ...] has_batch_dim = False B, _ = mel2token.shape dur = mel2token.new_zeros(B, T_txt + 1).scatter_add(1, mel2token, torch.ones_like(mel2token)) dur = dur[:, 1:] if max_dur is not None: dur = dur.clamp(max=max_dur) if not is_torch: dur = dur.numpy() if not has_batch_dim: dur = dur[0] return dur
null
8,408
from collections import defaultdict import torch import torch.nn.functional as F def expand_word2ph(word_encoding, ph2word): word_encoding = F.pad(word_encoding,[0,0,1,0]) ph2word_ = ph2word[:, :, None].repeat([1, 1, word_encoding.shape[-1]]) out = torch.gather(word_encoding, 1, ph2word_) # [B, T, H] return out
null
8,409
import os import subprocess def link_file(from_file, to_file): subprocess.check_call( f'ln -s "`realpath --relative-to="{os.path.dirname(to_file)}" "{from_file}"`" "{to_file}"', shell=True)
null
8,410
import os import subprocess def move_file(from_file, to_file): subprocess.check_call(f'mv "{from_file}" "{to_file}"', shell=True)
null
8,411
import os import subprocess def copy_file(from_file, to_file): subprocess.check_call(f'cp -r "{from_file}" "{to_file}"', shell=True)
null
8,412
import os import subprocess def remove_file(*fns): for f in fns: subprocess.check_call(f'rm -rf "{f}"', shell=True)
null
8,413
import librosa import numpy as np import torch def norm_f0(f0, uv, hparams): is_torch = isinstance(f0, torch.Tensor) if hparams['pitch_norm'] == 'standard': f0 = (f0 - hparams['f0_mean']) / hparams['f0_std'] if hparams['pitch_norm'] == 'log': f0 = torch.log2(f0) if is_torch else np.log2(f0) if uv is not None and hparams['use_uv']: f0[uv > 0] = 0 return f0 def norm_interp_f0(f0, hparams): is_torch = isinstance(f0, torch.Tensor) if is_torch: device = f0.device f0 = f0.data.cpu().numpy() uv = f0 == 0 f0 = norm_f0(f0, uv, hparams) if sum(uv) == len(f0): f0[uv] = 0 elif sum(uv) > 0: f0[uv] = np.interp(np.where(uv)[0], np.where(~uv)[0], f0[~uv]) uv = torch.FloatTensor(uv) f0 = torch.FloatTensor(f0) if is_torch: f0 = f0.to(device) return f0, uv
null
8,414
import librosa import numpy as np import torch def denorm_f0(f0, uv, hparams, pitch_padding=None, min=None, max=None): if hparams['pitch_norm'] == 'standard': f0 = f0 * hparams['f0_std'] + hparams['f0_mean'] if hparams['pitch_norm'] == 'log': f0 = 2 ** f0 if min is not None: f0 = f0.clamp(min=min) if max is not None: f0 = f0.clamp(max=max) if uv is not None and hparams['use_uv']: f0[uv > 0] = 0 if pitch_padding is not None: f0[pitch_padding] = 0 return f0
null
8,415
import argparse import yaml import sys def read_config_as_args(config_path,args=None,is_config_str=False): return_dict = {} if config_path is not None: if is_config_str: yml_config = yaml.load(config_path, Loader=yaml.FullLoader) else: with open(config_path, "r") as f: yml_config = yaml.load(f, Loader=yaml.FullLoader) if args != None: for k, v in yml_config.items(): if k in args.__dict__: args.__dict__[k] = v else: sys.stderr.write("Ignored unknown parameter {} in yaml.\n".format(k)) else: for k, v in yml_config.items(): return_dict[k] = v args = args if args != None else return_dict return argparse.Namespace(**args)
null
8,416
import torch import torch.nn as nn import torch.nn.functional as F from torchlibrosa.stft import Spectrogram, LogmelFilterBank class Cnn14(nn.Module): def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, fmax, classes_num, out_emb): super(Cnn14, self).__init__() window = 'hann' center = True pad_mode = 'reflect' ref = 1.0 amin = 1e-10 top_db = None # Spectrogram extractor self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, win_length=window_size, window=window, center=center, pad_mode=pad_mode, freeze_parameters=True) # Logmel feature extractor self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, freeze_parameters=True) self.bn0 = nn.BatchNorm2d(64) self.conv_block1 = ConvBlock(in_channels=1, out_channels=64) self.conv_block2 = ConvBlock(in_channels=64, out_channels=128) self.conv_block3 = ConvBlock(in_channels=128, out_channels=256) self.conv_block4 = ConvBlock(in_channels=256, out_channels=512) self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024) self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048) # out_emb is 2048 for best Cnn14 self.fc1 = nn.Linear(2048, out_emb, bias=True) self.fc_audioset = nn.Linear(out_emb, classes_num, bias=True) def forward(self, input, mixup_lambda=None): """ Input: (batch_size, data_length) """ x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins) x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins) x = x.transpose(1, 3) x = self.bn0(x) x = x.transpose(1, 3) x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg') x = F.dropout(x, p=0.2, training=self.training) x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg') x = F.dropout(x, p=0.2, training=self.training) x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg') x = F.dropout(x, p=0.2, training=self.training) x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg') x = F.dropout(x, p=0.2, training=self.training) x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg') x = F.dropout(x, p=0.2, training=self.training) x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg') x = F.dropout(x, p=0.2, training=self.training) x = torch.mean(x, dim=3) (x1, _) = torch.max(x, dim=2) x2 = torch.mean(x, dim=2) x = x1 + x2 x = F.dropout(x, p=0.5, training=self.training) x = F.relu_(self.fc1(x)) embedding = F.dropout(x, p=0.5, training=self.training) clipwise_output = torch.sigmoid(self.fc_audioset(x)) output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding} return output_dict def get_audio_encoder(name: str): if name == "Cnn14": return Cnn14 else: raise Exception('The audio encoder name {} is incorrect or not supported'.format(name))
null
8,417
import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm import numpy as np from .activations import Snake,SnakeBeta from .alias_free_torch import * import os from omegaconf import OmegaConf def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std)
null
8,418
import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm import numpy as np from .activations import Snake,SnakeBeta from .alias_free_torch import * import os from omegaconf import OmegaConf def get_padding(kernel_size, dilation=1): return int((kernel_size*dilation - dilation)/2)
null
8,419
import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm import numpy as np from .activations import Snake,SnakeBeta from .alias_free_torch import * import os from omegaconf import OmegaConf def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): loss += torch.mean(torch.abs(rl - gl)) return loss*2
null
8,420
import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm import numpy as np from .activations import Snake,SnakeBeta from .alias_free_torch import * import os from omegaconf import OmegaConf def discriminator_loss(disc_real_outputs, disc_generated_outputs): loss = 0 r_losses = [] g_losses = [] for dr, dg in zip(disc_real_outputs, disc_generated_outputs): r_loss = torch.mean((1-dr)**2) g_loss = torch.mean(dg**2) loss += (r_loss + g_loss) r_losses.append(r_loss.item()) g_losses.append(g_loss.item()) return loss, r_losses, g_losses
null
8,421
import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm import numpy as np from .activations import Snake,SnakeBeta from .alias_free_torch import * import os from omegaconf import OmegaConf def generator_loss(disc_outputs): loss = 0 gen_losses = [] for dg in disc_outputs: l = torch.mean((1-dg)**2) gen_losses.append(l) loss += l return loss, gen_losses
null
8,422
import torch import torch.nn as nn import torch.nn.functional as F import math if 'sinc' in dir(torch): sinc = torch.sinc else: # This code is adopted from adefossez's julius.core.sinc under the MIT License # https://adefossez.github.io/julius/julius/core.html # LICENSE is in incl_licenses directory. def sinc(x: torch.Tensor): """ Implementation of sinc, i.e. sin(pi * x) / (pi * x) __Warning__: Different to julius.sinc, the input is multiplied by `pi`! """ return torch.where(x == 0, torch.tensor(1., device=x.device, dtype=x.dtype), torch.sin(math.pi * x) / math.pi / x) def kaiser_sinc_filter1d(cutoff, half_width, kernel_size): # return filter [1,1,kernel_size] even = (kernel_size % 2 == 0) half_size = kernel_size // 2 #For kaiser window delta_f = 4 * half_width A = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95 if A > 50.: beta = 0.1102 * (A - 8.7) elif A >= 21.: beta = 0.5842 * (A - 21)**0.4 + 0.07886 * (A - 21.) else: beta = 0. window = torch.kaiser_window(kernel_size, beta=beta, periodic=False) # ratio = 0.5/cutoff -> 2 * cutoff = 1 / ratio if even: time = (torch.arange(-half_size, half_size) + 0.5) else: time = torch.arange(kernel_size) - half_size if cutoff == 0: filter_ = torch.zeros_like(time) else: filter_ = 2 * cutoff * window * sinc(2 * cutoff * time) # Normalize filter to have sum = 1, otherwise we will have a small leakage # of the constant component in the input signal. filter_ /= filter_.sum() filter = filter_.view(1, 1, kernel_size) return filter
null
8,423
import os import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from pathlib import Path import yaml import numpy as np from argparse import Namespace def get_padding(kernel_size, dilation=1): return int((kernel_size*dilation - dilation)/2)
null
8,424
import os import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from pathlib import Path import yaml import numpy as np from argparse import Namespace def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std)
null
8,425
import os import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from pathlib import Path import yaml import numpy as np from argparse import Namespace def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): loss += torch.mean(torch.abs(rl - gl)) return loss*2
null
8,426
import os import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from pathlib import Path import yaml import numpy as np from argparse import Namespace def discriminator_loss(disc_real_outputs, disc_generated_outputs): loss = 0 r_losses = [] g_losses = [] for dr, dg in zip(disc_real_outputs, disc_generated_outputs): r_loss = torch.mean((1-dr)**2) g_loss = torch.mean(dg**2) loss += (r_loss + g_loss) r_losses.append(r_loss.item()) g_losses.append(g_loss.item()) return loss, r_losses, g_losses
null
8,427
import os import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from pathlib import Path import yaml import numpy as np from argparse import Namespace def generator_loss(disc_outputs): loss = 0 gen_losses = [] for dg in disc_outputs: l = torch.mean((1-dg)**2) gen_losses.append(l) loss += l return loss, gen_losses
null
8,429
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat from ldm.util import instantiate_from_config def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True): if ddim_discr_method == 'uniform': c = num_ddpm_timesteps // num_ddim_timesteps ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) elif ddim_discr_method == 'quad': ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int) else: raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"') # assert ddim_timesteps.shape[0] == num_ddim_timesteps # add one to get the final alpha values right (the ones from first scale to data during sampling) steps_out = ddim_timesteps + 1 if verbose: print(f'Selected timesteps for ddim sampler: {steps_out}') return steps_out
null
8,438
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat from ldm.util import instantiate_from_config class GroupNorm32(nn.GroupNorm): def forward(self, x): return super().forward(x.float()).type(x.dtype) The provided code snippet includes necessary dependencies for implementing the `normalization` function. Write a Python function `def normalization(channels)` to solve the following problem: Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. Here is the function: def normalization(channels): """ Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. """ return GroupNorm32(32, channels)
Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization.
8,443
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from ldm.util import instantiate_from_config from ldm.modules.attention import LinearAttention The provided code snippet includes necessary dependencies for implementing the `get_timestep_embedding` function. Write a Python function `def get_timestep_embedding(timesteps, embedding_dim)` to solve the following problem: This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". Here is the function: def get_timestep_embedding(timesteps, embedding_dim): """ This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ assert len(timesteps.shape) == 1 half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) emb = emb.to(device=timesteps.device) emb = timesteps.float()[:, None] * emb[None, :] emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) if embedding_dim % 2 == 1: # zero pad emb = torch.nn.functional.pad(emb, (0,1,0,0)) return emb
This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need".
8,444
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from ldm.util import instantiate_from_config from ldm.modules.attention import LinearAttention def nonlinearity(x): # swish return x*torch.sigmoid(x)
null
8,445
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from ldm.util import instantiate_from_config from ldm.modules.attention import LinearAttention def Normalize(in_channels, num_groups=32): return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
null
8,446
import math import torch import torch.nn as nn import numpy as np from einops import rearrange from ldm.util import instantiate_from_config from ldm.modules.attention import LinearAttention class LinAttnBlock(LinearAttention): """to match AttnBlock usage""" def __init__(self, in_channels): super().__init__(dim=in_channels, heads=1, dim_head=in_channels) class AttnBlock(nn.Module): def __init__(self, in_channels): super().__init__() self.in_channels = in_channels self.norm = Normalize(in_channels) self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) def forward(self, x): h_ = x h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_) # compute attention b,c,h,w = q.shape q = q.reshape(b,c,h*w) q = q.permute(0,2,1) # b,hw,c k = k.reshape(b,c,h*w) # b,c,hw w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] w_ = w_ * (int(c)**(-0.5)) w_ = torch.nn.functional.softmax(w_, dim=2) # attend to values v = v.reshape(b,c,h*w) w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] h_ = h_.reshape(b,c,h,w) h_ = self.proj_out(h_) return x+h_ def make_attn(in_channels, attn_type="vanilla"): assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown' print(f"making attention of type '{attn_type}' with {in_channels} in_channels") if attn_type == "vanilla": return AttnBlock(in_channels) elif attn_type == "none": return nn.Identity(in_channels) else: return LinAttnBlock(in_channels)
null
8,447
from abc import abstractmethod from functools import partial import math from typing import Iterable import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from ldm.modules.attention import SpatialTransformer def convert_module_to_f16(x): pass
null
8,448
from abc import abstractmethod from functools import partial import math from typing import Iterable import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from ldm.modules.attention import SpatialTransformer def convert_module_to_f32(x): pass
null
8,449
from abc import abstractmethod from functools import partial import math from typing import Iterable import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from ldm.modules.attention import SpatialTransformer The provided code snippet includes necessary dependencies for implementing the `count_flops_attn` function. Write a Python function `def count_flops_attn(model, _x, y)` to solve the following problem: A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) Here is the function: def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) # We perform two matmuls with the same number of ops. # The first computes the weight matrix, the second computes # the combination of the value vectors. matmul_ops = 2 * b * (num_spatial ** 2) * c model.total_ops += th.DoubleTensor([matmul_ops])
A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, )
8,450
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from ldm.modules.diffusionmodules.util import checkpoint def uniq(arr): return{el: True for el in arr}.keys()
null
8,451
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from ldm.modules.diffusionmodules.util import checkpoint def exists(val): return val is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d
null
8,452
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from ldm.modules.diffusionmodules.util import checkpoint def max_neg_value(t): return -torch.finfo(t.dtype).max
null
8,453
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from ldm.modules.diffusionmodules.util import checkpoint def init_(tensor): dim = tensor.shape[-1] std = 1 / math.sqrt(dim) tensor.uniform_(-std, std) return tensor
null
8,454
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from ldm.modules.diffusionmodules.util import checkpoint The provided code snippet includes necessary dependencies for implementing the `zero_module` function. Write a Python function `def zero_module(module)` to solve the following problem: Zero out the parameters of a module and return it. Here is the function: def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
Zero out the parameters of a module and return it.
8,455
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from ldm.modules.diffusionmodules.util import checkpoint def Normalize(in_channels): return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
null
8,496
import os import math import random import numpy as np import torch import cv2 from torchvision.utils import make_grid from datetime import datetime def bgr2ycbcr(img, only_y=True): '''bgr version of rgb2ycbcr only_y: only return Y channel Input: uint8, [0, 255] float, [0, 1] ''' in_img_type = img.dtype img.astype(np.float32) if in_img_type != np.uint8: img *= 255. # convert if only_y: rlt = np.dot(img, [24.966, 128.553, 65.481]) / 255.0 + 16.0 else: rlt = np.matmul(img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) / 255.0 + [16, 128, 128] if in_img_type == np.uint8: rlt = rlt.round() else: rlt /= 255. return rlt.astype(in_img_type) def channel_convert(in_c, tar_type, img_list): # conversion among BGR, gray and y if in_c == 3 and tar_type == 'gray': # BGR to gray gray_list = [cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for img in img_list] return [np.expand_dims(img, axis=2) for img in gray_list] elif in_c == 3 and tar_type == 'y': # BGR to y y_list = [bgr2ycbcr(img, only_y=True) for img in img_list] return [np.expand_dims(img, axis=2) for img in y_list] elif in_c == 1 and tar_type == 'RGB': # gray/y to BGR return [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_list] else: return img_list
null
8,509
import functools import torch.nn as nn if __name__ == '__main__': import torch ## FEATURES disc_in_channels = 2048 disc_num_layers = 2 use_actnorm = False disc_ndf = 64 discriminator = NLayerDiscriminator1dFeats(input_nc=disc_in_channels, n_layers=disc_num_layers, use_actnorm=use_actnorm, ndf=disc_ndf).apply(weights_init) inputs = torch.rand((6, 2048, 212)) outputs = discriminator(inputs) print(outputs.shape) ## AUDIO disc_in_channels = 1 disc_num_layers = 3 use_actnorm = False disc_ndf = 64 discriminator = NLayerDiscriminator(input_nc=disc_in_channels, n_layers=disc_num_layers, use_actnorm=use_actnorm, ndf=disc_ndf).apply(weights_init) inputs = torch.rand((6, 1, 80, 848)) outputs = discriminator(inputs) print(outputs.shape) ## IMAGE disc_in_channels = 3 disc_num_layers = 3 use_actnorm = False disc_ndf = 64 discriminator = NLayerDiscriminator(input_nc=disc_in_channels, n_layers=disc_num_layers, use_actnorm=use_actnorm, ndf=disc_ndf).apply(weights_init) inputs = torch.rand((6, 3, 256, 256)) outputs = discriminator(inputs) print(outputs.shape) def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0)
null
8,510
import random import numpy as np import torch import torchvision from omegaconf import OmegaConf from torch.utils.data.dataloader import DataLoader from torchvision.models.inception import BasicConv2d, Inception3 from tqdm import tqdm from dataset import VGGSound from logger import LoggerWithTBoard from loss import WeightedCrossEntropy from metrics import metrics from transforms import Crop, StandardNormalizeAudio, ToTensor class Melception(Inception3): def __init__(self, num_classes, **kwargs): def forward(self, x): class VGGSound(torch.utils.data.Dataset): def __init__(self, split, specs_dir, transforms=None, splits_path='./data', meta_path='./data/vggsound.csv'): def __getitem__(self, idx): def __len__(self): def make_split_files(self): class LoggerWithTBoard(SummaryWriter): def __init__(self, cfg): def log_param_num(self, model): def log_iter_loss(self, loss, iter, phase): def log_epoch_loss(self, loss, epoch, phase): def log_epoch_metrics(self, metrics_dict, epoch, phase): def log_test_metrics(self, metrics_dict, hparams_dict, best_epoch): def log_best_model(self, model, loss, epoch, optimizer, metrics_dict): class WeightedCrossEntropy(nn.CrossEntropyLoss): def __init__(self, weights, **pytorch_ce_loss_args) -> None: def __call__(self, outputs, targets, to_weight=True): def metrics(targets, outputs, topk=(1, 5)): class StandardNormalizeAudio(object): def __init__(self, specs_dir, train_ids_path='./data/vggsound_train.txt', cache_path='./data/'): def __call__(self, item): def calculate_or_load_stats(self): class ToTensor(object): def __call__(self, item): class Crop(object): def __init__(self, cropped_shape=None, random_crop=False): def __call__(self, item): def train_inception_scorer(cfg): logger = LoggerWithTBoard(cfg) random.seed(cfg.seed) np.random.seed(cfg.seed) torch.manual_seed(cfg.seed) torch.cuda.manual_seed_all(cfg.seed) # makes iterations faster (in this case 30%) if your inputs are of a fixed size # https://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936/3 torch.backends.cudnn.benchmark = True meta_path = './data/vggsound.csv' train_ids_path = './data/vggsound_train.txt' cache_path = './data/' splits_path = cache_path transforms = [ StandardNormalizeAudio(cfg.mels_path, train_ids_path, cache_path), ] if cfg.cropped_size not in [None, 'None', 'none']: logger.print_logger.info(f'Using cropping {cfg.cropped_size}') transforms.append(Crop(cfg.cropped_size)) transforms.append(ToTensor()) transforms = torchvision.transforms.transforms.Compose(transforms) datasets = { 'train': VGGSound('train', cfg.mels_path, transforms, splits_path, meta_path), 'valid': VGGSound('valid', cfg.mels_path, transforms, splits_path, meta_path), 'test': VGGSound('test', cfg.mels_path, transforms, splits_path, meta_path), } loaders = { 'train': DataLoader(datasets['train'], batch_size=cfg.batch_size, shuffle=True, drop_last=True, num_workers=cfg.num_workers, pin_memory=True), 'valid': DataLoader(datasets['valid'], batch_size=cfg.batch_size, num_workers=cfg.num_workers, pin_memory=True), 'test': DataLoader(datasets['test'], batch_size=cfg.batch_size, num_workers=cfg.num_workers, pin_memory=True), } device = torch.device(cfg.device if torch.cuda.is_available() else 'cpu') model = Melception(num_classes=len(datasets['train'].target2label)) model = model.to(device) param_num = logger.log_param_num(model) if cfg.optimizer == 'adam': optimizer = torch.optim.Adam( model.parameters(), lr=cfg.learning_rate, betas=cfg.betas, weight_decay=cfg.weight_decay) elif cfg.optimizer == 'sgd': optimizer = torch.optim.SGD( model.parameters(), lr=cfg.learning_rate, momentum=cfg.momentum, weight_decay=cfg.weight_decay) else: raise NotImplementedError if cfg.cls_weights_in_loss: weights = 1 / datasets['train'].class_counts else: weights = torch.ones(len(datasets['train'].target2label)) criterion = WeightedCrossEntropy(weights.to(device)) # loop over the train and validation multiple times (typical PT boilerplate) no_change_epochs = 0 best_valid_loss = float('inf') early_stop_triggered = False for epoch in range(cfg.num_epochs): for phase in ['train', 'valid']: if phase == 'train': model.train() else: model.eval() running_loss = 0 preds_from_each_batch = [] targets_from_each_batch = [] prog_bar = tqdm(loaders[phase], f'{phase} ({epoch})', ncols=0) for i, batch in enumerate(prog_bar): inputs = batch['input'].to(device) targets = batch['target'].to(device) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize with torch.set_grad_enabled(phase == 'train'): # inception v3 if phase == 'train': outputs, aux_outputs = model(inputs) loss1 = criterion(outputs, targets) loss2 = criterion(aux_outputs, targets) loss = loss1 + 0.4*loss2 loss = criterion(outputs, targets, to_weight=True) else: outputs = model(inputs) loss = criterion(outputs, targets, to_weight=False) if phase == 'train': loss.backward() optimizer.step() # loss running_loss += loss.item() # for metrics calculation later on preds_from_each_batch += [outputs.detach().cpu()] targets_from_each_batch += [targets.cpu()] # iter logging if i % 50 == 0: logger.log_iter_loss(loss.item(), epoch*len(loaders[phase])+i, phase) # tracks loss in the tqdm progress bar prog_bar.set_postfix(loss=loss.item()) # logging loss epoch_loss = running_loss / len(loaders[phase]) logger.log_epoch_loss(epoch_loss, epoch, phase) # logging metrics preds_from_each_batch = torch.cat(preds_from_each_batch) targets_from_each_batch = torch.cat(targets_from_each_batch) metrics_dict = metrics(targets_from_each_batch, preds_from_each_batch) logger.log_epoch_metrics(metrics_dict, epoch, phase) # Early stopping if phase == 'valid': if epoch_loss < best_valid_loss: no_change_epochs = 0 best_valid_loss = epoch_loss logger.log_best_model(model, epoch_loss, epoch, optimizer, metrics_dict) else: no_change_epochs += 1 logger.print_logger.info( f'Valid loss hasnt changed for {no_change_epochs} patience: {cfg.patience}' ) if no_change_epochs >= cfg.patience: early_stop_triggered = True if early_stop_triggered: logger.print_logger.info(f'Training is early stopped @ {epoch}') break logger.print_logger.info('Finished Training') # loading the best model ckpt = torch.load(logger.best_model_path) model.load_state_dict(ckpt['model']) logger.print_logger.info(f'Loading the best model from {logger.best_model_path}') logger.print_logger.info((f'The model was trained for {ckpt["epoch"]} epochs. Loss: {ckpt["loss"]:.4f}')) # Testing the model model.eval() running_loss = 0 preds_from_each_batch = [] targets_from_each_batch = [] for i, batch in enumerate(loaders['test']): inputs = batch['input'].to(device) targets = batch['target'].to(device) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize with torch.set_grad_enabled(False): outputs = model(inputs) loss = criterion(outputs, targets, to_weight=False) # loss running_loss += loss.item() # for metrics calculation later on preds_from_each_batch += [outputs.detach().cpu()] targets_from_each_batch += [targets.cpu()] # logging metrics preds_from_each_batch = torch.cat(preds_from_each_batch) targets_from_each_batch = torch.cat(targets_from_each_batch) test_metrics_dict = metrics(targets_from_each_batch, preds_from_each_batch) test_metrics_dict['avg_loss'] = running_loss / len(loaders['test']) test_metrics_dict['param_num'] = param_num # TODO: I have no idea why tboard doesn't keep metrics (hparams) when # I run this experiment from cli: `python train_melception.py config=./configs/vggish.yaml` # while when I run it in vscode debugger the metrics are logger (wtf) logger.log_test_metrics(test_metrics_dict, dict(cfg), ckpt['epoch']) logger.print_logger.info('Finished the experiment')
null
8,511
from collections import namedtuple import numpy as np import torch import torch.nn as nn import sys from ldm.modules.losses_audio.vggishish.model import VGGishish from ldm.util import get_ckpt_path def normalize_tensor(x, eps=1e-10): norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True)) return x / (norm_factor+eps)
null
8,512
from collections import namedtuple import numpy as np import torch import torch.nn as nn import sys from ldm.modules.losses_audio.vggishish.model import VGGishish from ldm.util import get_ckpt_path def spatial_average(x, keepdim=True): return x.mean([2, 3], keepdim=keepdim)
null
8,513
import torch from torch import nn, einsum import torch.nn.functional as F from functools import partial from inspect import isfunction from collections import namedtuple from einops import rearrange, repeat, reduce def exists(val): return val is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d
null
8,524
import os import torch import torch.nn as nn import torch.nn.functional as F from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from .utils import do_mixup, interpolate, pad_framewise_output from .feature_fusion import iAFF, AFF, DAF The provided code snippet includes necessary dependencies for implementing the `init_layer` function. Write a Python function `def init_layer(layer)` to solve the following problem: Initialize a Linear or Convolutional layer. Here is the function: def init_layer(layer): """Initialize a Linear or Convolutional layer. """ nn.init.xavier_uniform_(layer.weight) if hasattr(layer, 'bias'): if layer.bias is not None: layer.bias.data.fill_(0.)
Initialize a Linear or Convolutional layer.
8,525
import os import torch import torch.nn as nn import torch.nn.functional as F from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from .utils import do_mixup, interpolate, pad_framewise_output from .feature_fusion import iAFF, AFF, DAF The provided code snippet includes necessary dependencies for implementing the `init_bn` function. Write a Python function `def init_bn(bn)` to solve the following problem: Initialize a Batchnorm layer. Here is the function: def init_bn(bn): """Initialize a Batchnorm layer. """ bn.bias.data.fill_(0.) bn.weight.data.fill_(1.)
Initialize a Batchnorm layer.
8,526
import os import torch import torch.nn as nn import torch.nn.functional as F from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from .utils import do_mixup, interpolate, pad_framewise_output from .feature_fusion import iAFF, AFF, DAF def create_pann_model(audio_cfg, enable_fusion=False, fusion_type='None'): try: ModelProto = eval(audio_cfg.model_name) model = ModelProto( sample_rate = audio_cfg.sample_rate, window_size = audio_cfg.window_size, hop_size =audio_cfg.hop_size, mel_bins = audio_cfg.mel_bins, fmin = audio_cfg.fmin, fmax = audio_cfg.fmax, classes_num = audio_cfg.class_num, enable_fusion = enable_fusion, fusion_type = fusion_type ) return model except: raise RuntimeError(f'Import Model for {audio_cfg.model_name} not found, or the audio cfg parameters are not enough.')
null
8,527
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
null
8,528
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem: Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. Here is the function: def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. """ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) cs = bs[:] n = 0 for b in range(2**8): if b not in bs: bs.append(b) cs.append(2**8+n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs))
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on.
8,529
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem: Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). Here is the function: def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
8,530
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
null
8,531
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch def whitespace_clean(text): text = re.sub(r'\s+', ' ', text) text = text.strip() return text
null
8,532
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch _tokenizer = SimpleTokenizer() The provided code snippet includes necessary dependencies for implementing the `tokenize` function. Write a Python function `def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor` to solve the following problem: Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The context length to use; all CLIP models use 77 as the context length Returns ------- A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] Here is the function: def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: """ Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The context length to use; all CLIP models use 77 as the context length Returns ------- A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] """ if isinstance(texts, str): texts = [texts] sot_token = _tokenizer.encoder["<start_of_text>"] eot_token = _tokenizer.encoder["<end_of_text>"] all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: tokens = tokens[:context_length] # Truncate result[i, :len(tokens)] = torch.tensor(tokens) return result
Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The context length to use; all CLIP models use 77 as the context length Returns ------- A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
8,533
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `freeze_batch_norm_2d` function. Write a Python function `def freeze_batch_norm_2d(module, module_match={}, name="")` to solve the following problem: Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and returned. Otherwise, the module is walked recursively and submodules are converted in place. Args: module (torch.nn.Module): Any PyTorch module. module_match (dict): Dictionary of full module names to freeze (all if empty) name (str): Full module name (prefix) Returns: torch.nn.Module: Resulting module Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 Here is the function: def freeze_batch_norm_2d(module, module_match={}, name=""): """ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and returned. Otherwise, the module is walked recursively and submodules are converted in place. Args: module (torch.nn.Module): Any PyTorch module. module_match (dict): Dictionary of full module names to freeze (all if empty) name (str): Full module name (prefix) Returns: torch.nn.Module: Resulting module Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 """ res = module is_match = True if module_match: is_match = name in module_match if is_match and isinstance( module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm) ): res = FrozenBatchNorm2d(module.num_features) res.num_features = module.num_features res.affine = module.affine if module.affine: res.weight.data = module.weight.data.clone().detach() res.bias.data = module.bias.data.clone().detach() res.running_mean.data = module.running_mean.data res.running_var.data = module.running_var.data res.eps = module.eps else: for child_name, child in module.named_children(): full_child_name = ".".join([name, child_name]) if name else child_name new_child = freeze_batch_norm_2d(child, module_match, full_child_name) if new_child is not child: res.add_module(child_name, new_child) return res
Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and returned. Otherwise, the module is walked recursively and submodules are converted in place. Args: module (torch.nn.Module): Any PyTorch module. module_match (dict): Dictionary of full module names to freeze (all if empty) name (str): Full module name (prefix) Returns: torch.nn.Module: Resulting module Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
8,534
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib dataset_split = { "audiocaps": ["train", "valid", "test"], "audioset": ["balanced_train", "unbalanced_train", "eval"], "BBCSoundEffects": ["train", "test"], "Clotho": ["train", "test", "valid"], "free_to_use_sounds": ["train", "test"], "paramount_motion": ["train", "test"], "sonniss_game_effects": ["train", "test"], "wesoundeffects": ["train", "test"], "MACS": ["train", "test"], "freesound": ["train", "test"], "FSD50K": ["train", "test", "valid"], "fsd50k_class_label": ["train", "test", "valid"], "esc50": ["train", "test"], "audiostock": ["train", "test"], "freesound_no_overlap_noesc50": ["train", "test"], "epidemic_sound_effects": ["train", "test"], "VGGSound": ["train", "test"], "urbansound8k_class_label": ["train", "test"], "audioset_t5": ["balanced_train", "unbalanced_train", "eval"], "epidemic_sound_effects_t5": ["train", "test"], "WavText5K": ["train", "test"], "esc50_no_overlap": ["train", "test"], "usd8k_no_overlap": ["train", "test"], "fsd50k_200_class_label": ["train", "test", "valid"] } from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `exist` function. Write a Python function `def exist(dataset_name, dataset_type)` to solve the following problem: Check if dataset exists Here is the function: def exist(dataset_name, dataset_type): """ Check if dataset exists """ if dataset_type in dataset_split[dataset_name]: return True else: return False
Check if dataset exists
8,535
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib dataset_split = { "audiocaps": ["train", "valid", "test"], "audioset": ["balanced_train", "unbalanced_train", "eval"], "BBCSoundEffects": ["train", "test"], "Clotho": ["train", "test", "valid"], "free_to_use_sounds": ["train", "test"], "paramount_motion": ["train", "test"], "sonniss_game_effects": ["train", "test"], "wesoundeffects": ["train", "test"], "MACS": ["train", "test"], "freesound": ["train", "test"], "FSD50K": ["train", "test", "valid"], "fsd50k_class_label": ["train", "test", "valid"], "esc50": ["train", "test"], "audiostock": ["train", "test"], "freesound_no_overlap_noesc50": ["train", "test"], "epidemic_sound_effects": ["train", "test"], "VGGSound": ["train", "test"], "urbansound8k_class_label": ["train", "test"], "audioset_t5": ["balanced_train", "unbalanced_train", "eval"], "epidemic_sound_effects_t5": ["train", "test"], "WavText5K": ["train", "test"], "esc50_no_overlap": ["train", "test"], "usd8k_no_overlap": ["train", "test"], "fsd50k_200_class_label": ["train", "test", "valid"] } from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `get_tar_path_from_dataset_name` function. Write a Python function `def get_tar_path_from_dataset_name( dataset_names, dataset_types, islocal, dataset_path, proportion=1, full_dataset=None )` to solve the following problem: Get tar path from dataset name and type Here is the function: def get_tar_path_from_dataset_name( dataset_names, dataset_types, islocal, dataset_path, proportion=1, full_dataset=None ): """ Get tar path from dataset name and type """ output = [] for n in dataset_names: if full_dataset is not None and n in full_dataset: current_dataset_types = dataset_split[n] else: current_dataset_types = dataset_types for s in current_dataset_types: tmp = [] if islocal: sizefilepath_ = f"{dataset_path}/{n}/{s}/sizes.json" if not os.path.exists(sizefilepath_): sizefilepath_ = f"./json_files/{n}/{s}/sizes.json" else: sizefilepath_ = f"./json_files/{n}/{s}/sizes.json" if not os.path.exists(sizefilepath_): continue sizes = json.load(open(sizefilepath_, "r")) for k in sizes.keys(): if islocal: tmp.append(f"{dataset_path}/{n}/{s}/{k}") else: tmp.append( f"pipe:aws s3 --cli-connect-timeout 0 cp s3://s-laion-audio/webdataset_tar/{n}/{s}/{k} -" ) if proportion != 1: tmp = random.sample(tmp, int(proportion * len(tmp))) output.append(tmp) return sum(output, [])
Get tar path from dataset name and type
8,536
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `get_tar_path_from_txts` function. Write a Python function `def get_tar_path_from_txts(txt_path, islocal, proportion=1)` to solve the following problem: Get tar path from txt path Here is the function: def get_tar_path_from_txts(txt_path, islocal, proportion=1): """ Get tar path from txt path """ if isinstance(txt_path, (list, tuple)): return sum( [ get_tar_path_from_txts( txt_path[i], islocal=islocal, proportion=proportion ) for i in range(len(txt_path)) ], [], ) if isinstance(txt_path, str): with open(txt_path) as f: lines = f.readlines() if islocal: lines = [ lines[i] .split("\n")[0] .replace("pipe:aws s3 cp s3://s-laion-audio/", "/mnt/audio_clip/") for i in range(len(lines)) ] else: lines = [ lines[i].split("\n")[0].replace(".tar", ".tar -") for i in range(len(lines)) ] if proportion != 1: print("Sampling tars with proportion of {}".format(proportion)) lines = random.sample(lines, int(proportion * len(lines))) return lines
Get tar path from txt path
8,537
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def get_mix_lambda(mixup_alpha, batch_size): mixup_lambdas = [ np.random.beta(mixup_alpha, mixup_alpha, 1)[0] for _ in range(batch_size) ] return np.array(mixup_lambdas).astype(np.float32)
null
8,538
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `do_mixup` function. Write a Python function `def do_mixup(x, mixup_lambda)` to solve the following problem: Args: x: (batch_size , ...) mixup_lambda: (batch_size,) Returns: out: (batch_size, ...) Here is the function: def do_mixup(x, mixup_lambda): """ Args: x: (batch_size , ...) mixup_lambda: (batch_size,) Returns: out: (batch_size, ...) """ out = ( x.transpose(0, -1) * mixup_lambda + torch.flip(x, dims=[0]).transpose(0, -1) * (1 - mixup_lambda) ).transpose(0, -1) return out
Args: x: (batch_size , ...) mixup_lambda: (batch_size,) Returns: out: (batch_size, ...)
8,539
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `interpolate` function. Write a Python function `def interpolate(x, ratio)` to solve the following problem: Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN. Args: x: (batch_size, time_steps, classes_num) ratio: int, ratio to interpolate Returns: upsampled: (batch_size, time_steps * ratio, classes_num) Here is the function: def interpolate(x, ratio): """Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN. Args: x: (batch_size, time_steps, classes_num) ratio: int, ratio to interpolate Returns: upsampled: (batch_size, time_steps * ratio, classes_num) """ (batch_size, time_steps, classes_num) = x.shape upsampled = x[:, :, None, :].repeat(1, 1, ratio, 1) upsampled = upsampled.reshape(batch_size, time_steps * ratio, classes_num) return upsampled
Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN. Args: x: (batch_size, time_steps, classes_num) ratio: int, ratio to interpolate Returns: upsampled: (batch_size, time_steps * ratio, classes_num)
8,540
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `pad_framewise_output` function. Write a Python function `def pad_framewise_output(framewise_output, frames_num)` to solve the following problem: Pad framewise_output to the same length as input frames. The pad value is the same as the value of the last frame. Args: framewise_output: (batch_size, frames_num, classes_num) frames_num: int, number of frames to pad Outputs: output: (batch_size, frames_num, classes_num) Here is the function: def pad_framewise_output(framewise_output, frames_num): """Pad framewise_output to the same length as input frames. The pad value is the same as the value of the last frame. Args: framewise_output: (batch_size, frames_num, classes_num) frames_num: int, number of frames to pad Outputs: output: (batch_size, frames_num, classes_num) """ pad = framewise_output[:, -1:, :].repeat( 1, frames_num - framewise_output.shape[1], 1 ) """tensor for padding""" output = torch.cat((framewise_output, pad), dim=1) """(batch_size, frames_num, classes_num)"""
Pad framewise_output to the same length as input frames. The pad value is the same as the value of the last frame. Args: framewise_output: (batch_size, frames_num, classes_num) frames_num: int, number of frames to pad Outputs: output: (batch_size, frames_num, classes_num)
8,541
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def process_ipc(index_path, classes_num, filename): # load data logging.info("Load Data...............") ipc = [[] for _ in range(classes_num)] with h5py.File(index_path, "r") as f: for i in tqdm(range(len(f["target"]))): t_class = np.where(f["target"][i])[0] for t in t_class: ipc[t].append(i) print(ipc) np.save(filename, ipc) logging.info("Load Data Succeed...............")
null
8,542
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib def save_to_dict(s, o_={}): sp = s.split(": ") o_.update({sp[0]: float(sp[1])}) return o_ from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `get_data_from_log` function. Write a Python function `def get_data_from_log(txt_path)` to solve the following problem: Output dictionary from out.txt log file Here is the function: def get_data_from_log(txt_path): """ Output dictionary from out.txt log file """ with open(txt_path) as f: lines = f.readlines() val_data = {} train_data = {} train_losses = [] train_losses_epoch = [] for i in range(len(lines)): if "| INFO |" in lines[i]: if "Eval Epoch" in lines[i]: if "val_loss" in lines[i]: # float(regex.sub("", lines[310].split(" ")[-1]).replace(" ", "")) line = lines[i].split("Eval Epoch: ")[-1] num_epoch = int(line.split(" ")[0].split(" ")[0]) d = { line.split(" ")[0] .split(" ")[1] .replace(":", ""): float(line.split(" ")[0].split(" ")[-1]) } for i in range(1, len(line.split(" "))): d = save_to_dict(line.split(" ")[i], d) val_data[num_epoch] = d elif "Train Epoch" in lines[i]: num_epoch = int(lines[i].split("Train Epoch: ")[1][0]) loss = float(lines[i].split("Loss: ")[-1].split(" (")[0]) train_losses.append(loss) train_losses_epoch.append(num_epoch) for i in range(len(train_losses)): train_data[i] = { "num_epoch": train_losses_epoch[i], "train_loss": train_losses[i], } return train_data, val_data
Output dictionary from out.txt log file
8,543
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def save_p(obj, filename): import pickle try: from deepdiff import DeepDiff except: os.system("pip install deepdiff") from deepdiff import DeepDiff with open(filename, "wb") as file: pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL) # highest protocol with open(filename, "rb") as file: z = pickle.load(file) assert ( DeepDiff(obj, z, ignore_string_case=True) == {} ), "there is something wrong with the saving process" return
null
8,544
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def save_json(data, name="data.json"): import json with open(name, 'w') as fp: json.dump(data, fp) return
null
8,545
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib def load_p(filename): import pickle with open(filename, "rb") as file: z = pickle.load(file) return z def load_json(name): import json with open(name, 'r') as fp: data = json.load(fp) return data from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def load_class_label(path): # https://stackoverflow.com/questions/48004243/how-to-share-large-read-only-dictionary-list-across-processes-in-multiprocessing # https://stackoverflow.com/questions/45693949/storing-strings-in-a-multiprocessing-sharedctypes-array out = None if path is not None: if pathlib.Path(path).suffix in [".pkl", ".pickle"]: out = load_p(path) elif pathlib.Path(path).suffix in [".json", ".txt"]: out = load_json(path) elif pathlib.Path(path).suffix in [".npy", ".npz"]: out = np.load(path) elif pathlib.Path(path).suffix in [".csv"]: import pandas as pd out = pd.read_csv(path) return out # if out is None: # return None # else: # key = Array(c_wchar, '\n'.join(list(out.keys())), lock=False) # val = Array('i', out.values(), lock=False) # return (key, val)
null
8,546
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def get_optimizer(params, lr, betas, eps, momentum, optimizer_name): if optimizer_name.lower() == "adamw": optimizer = optim.AdamW( params, lr=lr, betas=betas, eps=eps ) elif optimizer_name.lower() == "sgd": optimizer = optim.SGD( params, lr=lr, momentum=momentum ) elif optimizer_name.lower() == "adam": optimizer = optim.Adam( params, lr=lr, betas=betas, eps=eps ) else: raise ValueError("optimizer name is not correct") return optimizer
null
8,547
from transformers import BertTokenizer, BertModel tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel.from_pretrained("bert-base-uncased") from transformers import RobertaTokenizer, RobertaModel tokenizer = RobertaTokenizer.from_pretrained('roberta-base') model = RobertaModel.from_pretrained('roberta-base') from transformers import BartTokenizer, BartModel tokenizer = BartTokenizer.from_pretrained('facebook/bart-base') model = BartModel.from_pretrained('facebook/bart-base') def bert_embeddings(text): # text = "Replace me by any text you'd like." encoded_input = tokenizer(text, return_tensors='pt') output = model(**encoded_input) return output
null
8,548
from transformers import BertTokenizer, BertModel tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel.from_pretrained("bert-base-uncased") from transformers import RobertaTokenizer, RobertaModel tokenizer = RobertaTokenizer.from_pretrained('roberta-base') model = RobertaModel.from_pretrained('roberta-base') from transformers import BartTokenizer, BartModel tokenizer = BartTokenizer.from_pretrained('facebook/bart-base') model = BartModel.from_pretrained('facebook/bart-base') def Roberta_embeddings(text): # text = "Replace me by any text you'd like." encoded_input = tokenizer(text, return_tensors='pt') output = model(**encoded_input) return output
null
8,549
from transformers import BertTokenizer, BertModel tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel.from_pretrained("bert-base-uncased") from transformers import RobertaTokenizer, RobertaModel tokenizer = RobertaTokenizer.from_pretrained('roberta-base') model = RobertaModel.from_pretrained('roberta-base') from transformers import BartTokenizer, BartModel tokenizer = BartTokenizer.from_pretrained('facebook/bart-base') model = BartModel.from_pretrained('facebook/bart-base') def bart_embeddings(text): # text = "Replace me by any text you'd like." encoded_input = tokenizer(text, return_tensors='pt') output = model(**encoded_input) return output
null
8,550
import hashlib import os import urllib import warnings from tqdm import tqdm _PRETRAINED = { "RN50": _RN50, "RN50-quickgelu": _RN50_quickgelu, "RN101": _RN101, "RN101-quickgelu": _RN101_quickgelu, "RN50x4": _RN50x4, "RN50x16": _RN50x16, "ViT-B-32": _VITB32, "ViT-B-32-quickgelu": _VITB32_quickgelu, "ViT-B-16": _VITB16, "ViT-L-14": _VITL14, } The provided code snippet includes necessary dependencies for implementing the `list_pretrained` function. Write a Python function `def list_pretrained(as_str: bool = False)` to solve the following problem: returns list of pretrained models Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True Here is the function: def list_pretrained(as_str: bool = False): """ returns list of pretrained models Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True """ return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()]
returns list of pretrained models Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True
8,551
import hashlib import os import urllib import warnings from tqdm import tqdm _PRETRAINED = { "RN50": _RN50, "RN50-quickgelu": _RN50_quickgelu, "RN101": _RN101, "RN101-quickgelu": _RN101_quickgelu, "RN50x4": _RN50x4, "RN50x16": _RN50x16, "ViT-B-32": _VITB32, "ViT-B-32-quickgelu": _VITB32_quickgelu, "ViT-B-16": _VITB16, "ViT-L-14": _VITL14, } The provided code snippet includes necessary dependencies for implementing the `list_pretrained_model_tags` function. Write a Python function `def list_pretrained_model_tags(model: str)` to solve the following problem: return all pretrain tags for the specified model architecture Here is the function: def list_pretrained_model_tags(model: str): """ return all pretrain tags for the specified model architecture """ tags = [] if model in _PRETRAINED: tags.extend(_PRETRAINED[model].keys()) return tags
return all pretrain tags for the specified model architecture
8,552
import torch import torch.nn as nn import torch.nn.functional as F from itertools import repeat import collections.abc import math import warnings from torch.nn.init import _calculate_fan_in_and_fan_out import torch.utils.checkpoint as checkpoint import random from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from itertools import repeat from .utils import do_mixup, interpolate from .feature_fusion import iAFF, AFF, DAF def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable): return x return tuple(repeat(x, n)) return parse
null
8,553
import torch import torch.nn as nn import torch.nn.functional as F from itertools import repeat import collections.abc import math import warnings from torch.nn.init import _calculate_fan_in_and_fan_out import torch.utils.checkpoint as checkpoint import random from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from itertools import repeat from .utils import do_mixup, interpolate from .feature_fusion import iAFF, AFF, DAF The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python function `def drop_path(x, drop_prob: float = 0., training: bool = False)` to solve the following problem: Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. Here is the function: def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
8,554
import torch import torch.nn as nn import torch.nn.functional as F from itertools import repeat import collections.abc import math import warnings from torch.nn.init import _calculate_fan_in_and_fan_out import torch.utils.checkpoint as checkpoint import random from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from itertools import repeat from .utils import do_mixup, interpolate from .feature_fusion import iAFF, AFF, DAF def variance_scaling_(tensor, scale=1.0, mode='fan_in', distribution='normal'): fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor) if mode == 'fan_in': denom = fan_in elif mode == 'fan_out': denom = fan_out elif mode == 'fan_avg': denom = (fan_in + fan_out) / 2 variance = scale / denom if distribution == "truncated_normal": # constant is stddev of standard normal truncated to (-2, 2) trunc_normal_(tensor, std=math.sqrt(variance) / .87962566103423978) elif distribution == "normal": tensor.normal_(std=math.sqrt(variance)) elif distribution == "uniform": bound = math.sqrt(3 * variance) tensor.uniform_(-bound, bound) else: raise ValueError(f"invalid distribution {distribution}") def lecun_normal_(tensor): variance_scaling_(tensor, mode='fan_in', distribution='truncated_normal')
null
8,555
import torch import torch.nn as nn import torch.nn.functional as F from itertools import repeat import collections.abc import math import warnings from torch.nn.init import _calculate_fan_in_and_fan_out import torch.utils.checkpoint as checkpoint import random from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from itertools import repeat from .utils import do_mixup, interpolate from .feature_fusion import iAFF, AFF, DAF The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size)` to solve the following problem: Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) Here is the function: def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
8,556
import torch import torch.nn as nn import torch.nn.functional as F from itertools import repeat import collections.abc import math import warnings from torch.nn.init import _calculate_fan_in_and_fan_out import torch.utils.checkpoint as checkpoint import random from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from itertools import repeat from .utils import do_mixup, interpolate from .feature_fusion import iAFF, AFF, DAF The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_reverse(windows, window_size, H, W)` to solve the following problem: Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) Here is the function: def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
8,557
import torch import torch.nn as nn import torch.nn.functional as F from itertools import repeat import collections.abc import math import warnings from torch.nn.init import _calculate_fan_in_and_fan_out import torch.utils.checkpoint as checkpoint import random from torchlibrosa.stft import Spectrogram, LogmelFilterBank from torchlibrosa.augmentation import SpecAugmentation from itertools import repeat from .utils import do_mixup, interpolate from .feature_fusion import iAFF, AFF, DAF class HTSAT_Swin_Transformer(nn.Module): r"""HTSAT based on the Swin Transformer Args: spec_size (int | tuple(int)): Input Spectrogram size. Default 256 patch_size (int | tuple(int)): Patch size. Default: 4 path_stride (iot | tuple(int)): Patch Stride for Frequency and Time Axis. Default: 4 in_chans (int): Number of input image channels. Default: 1 (mono) num_classes (int): Number of classes for classification head. Default: 527 embed_dim (int): Patch embedding dimension. Default: 96 depths (tuple(int)): Depth of each HTSAT-Swin Transformer layer. num_heads (tuple(int)): Number of attention heads in different layers. window_size (int): Window size. Default: 8 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None drop_rate (float): Dropout rate. Default: 0 attn_drop_rate (float): Attention dropout rate. Default: 0 drop_path_rate (float): Stochastic depth rate. Default: 0.1 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False patch_norm (bool): If True, add normalization after patch embedding. Default: True use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False config (module): The configuration Module from config.py """ def __init__(self, spec_size=256, patch_size=4, patch_stride=(4,4), in_chans=1, num_classes=527, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[4, 8, 16, 32], window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, use_checkpoint=False, norm_before_mlp='ln', config = None, enable_fusion = False, fusion_type = 'None', **kwargs): super(HTSAT_Swin_Transformer, self).__init__() self.config = config self.spec_size = spec_size self.patch_stride = patch_stride self.patch_size = patch_size self.window_size = window_size self.embed_dim = embed_dim self.depths = depths self.ape = ape self.in_chans = in_chans self.num_classes = num_classes self.num_heads = num_heads self.num_layers = len(self.depths) self.num_features = int(self.embed_dim * 2 ** (self.num_layers - 1)) self.drop_rate = drop_rate self.attn_drop_rate = attn_drop_rate self.drop_path_rate = drop_path_rate self.qkv_bias = qkv_bias self.qk_scale = None self.patch_norm = patch_norm self.norm_layer = norm_layer if self.patch_norm else None self.norm_before_mlp = norm_before_mlp self.mlp_ratio = mlp_ratio self.use_checkpoint = use_checkpoint self.enable_fusion = enable_fusion self.fusion_type = fusion_type # process mel-spec ; used only once self.freq_ratio = self.spec_size // self.config.mel_bins window = 'hann' center = True pad_mode = 'reflect' ref = 1.0 amin = 1e-10 top_db = None self.interpolate_ratio = 32 # Downsampled ratio # Spectrogram extractor self.spectrogram_extractor = Spectrogram(n_fft=config.window_size, hop_length=config.hop_size, win_length=config.window_size, window=window, center=center, pad_mode=pad_mode, freeze_parameters=True) # Logmel feature extractor self.logmel_extractor = LogmelFilterBank(sr=config.sample_rate, n_fft=config.window_size, n_mels=config.mel_bins, fmin=config.fmin, fmax=config.fmax, ref=ref, amin=amin, top_db=top_db, freeze_parameters=True) # Spec augmenter self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, freq_drop_width=8, freq_stripes_num=2) # 2 2 self.bn0 = nn.BatchNorm2d(self.config.mel_bins) # split spctrogram into non-overlapping patches self.patch_embed = PatchEmbed( img_size=self.spec_size, patch_size=self.patch_size, in_chans=self.in_chans, embed_dim=self.embed_dim, norm_layer=self.norm_layer, patch_stride = patch_stride, enable_fusion=self.enable_fusion, fusion_type=self.fusion_type ) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.grid_size self.patches_resolution = patches_resolution # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, self.embed_dim)) trunc_normal_(self.absolute_pos_embed, std=.02) self.pos_drop = nn.Dropout(p=self.drop_rate) # stochastic depth dpr = [x.item() for x in torch.linspace(0, self.drop_path_rate, sum(self.depths))] # stochastic depth decay rule # build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer(dim=int(self.embed_dim * 2 ** i_layer), input_resolution=(patches_resolution[0] // (2 ** i_layer), patches_resolution[1] // (2 ** i_layer)), depth=self.depths[i_layer], num_heads=self.num_heads[i_layer], window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, qk_scale=self.qk_scale, drop=self.drop_rate, attn_drop=self.attn_drop_rate, drop_path=dpr[sum(self.depths[:i_layer]):sum(self.depths[:i_layer + 1])], norm_layer=self.norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint, norm_before_mlp=self.norm_before_mlp) self.layers.append(layer) self.norm = self.norm_layer(self.num_features) self.avgpool = nn.AdaptiveAvgPool1d(1) self.maxpool = nn.AdaptiveMaxPool1d(1) SF = self.spec_size // (2 ** (len(self.depths) - 1)) // self.patch_stride[0] // self.freq_ratio self.tscam_conv = nn.Conv2d( in_channels = self.num_features, out_channels = self.num_classes, kernel_size = (SF,3), padding = (0,1) ) self.head = nn.Linear(num_classes, num_classes) if (self.enable_fusion) and (self.fusion_type in ['daf_1d','aff_1d','iaff_1d']): self.mel_conv1d = nn.Sequential( nn.Conv1d(64, 64, kernel_size=5, stride=3, padding=2), nn.BatchNorm1d(64) ) if self.fusion_type == 'daf_1d': self.fusion_model = DAF() elif self.fusion_type == 'aff_1d': self.fusion_model = AFF(channels=64, type='1D') elif self.fusion_type == 'iaff_1d': self.fusion_model = iAFF(channels=64, type='1D') self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def no_weight_decay(self): return {'absolute_pos_embed'} def no_weight_decay_keywords(self): return {'relative_position_bias_table'} def forward_features(self, x, longer_idx = None): # A deprecated optimization for using a hierarchical output from different blocks frames_num = x.shape[2] x = self.patch_embed(x, longer_idx = longer_idx) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for i, layer in enumerate(self.layers): x, attn = layer(x) # for x x = self.norm(x) B, N, C = x.shape SF = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[0] ST = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[1] x = x.permute(0,2,1).contiguous().reshape(B, C, SF, ST) B, C, F, T = x.shape # group 2D CNN c_freq_bin = F // self.freq_ratio x = x.reshape(B, C, F // c_freq_bin, c_freq_bin, T) x = x.permute(0,1,3,2,4).contiguous().reshape(B, C, c_freq_bin, -1) # get latent_output fine_grained_latent_output = torch.mean(x, dim = 2) fine_grained_latent_output = interpolate(fine_grained_latent_output.permute(0,2,1).contiguous(), 8 * self.patch_stride[1]) latent_output = self.avgpool(torch.flatten(x,2)) latent_output = torch.flatten(latent_output, 1) # display the attention map, if needed x = self.tscam_conv(x) x = torch.flatten(x, 2) # B, C, T fpx = interpolate(torch.sigmoid(x).permute(0,2,1).contiguous(), 8 * self.patch_stride[1]) x = self.avgpool(x) x = torch.flatten(x, 1) output_dict = { 'framewise_output': fpx, # already sigmoided 'clipwise_output': torch.sigmoid(x), 'fine_grained_embedding': fine_grained_latent_output, 'embedding': latent_output } return output_dict def crop_wav(self, x, crop_size, spe_pos = None): time_steps = x.shape[2] tx = torch.zeros(x.shape[0], x.shape[1], crop_size, x.shape[3]).to(x.device) for i in range(len(x)): if spe_pos is None: crop_pos = random.randint(0, time_steps - crop_size - 1) else: crop_pos = spe_pos tx[i][0] = x[i, 0, crop_pos:crop_pos + crop_size,:] return tx # Reshape the wavform to a img size, if you want to use the pretrained swin transformer model def reshape_wav2img(self, x): B, C, T, F = x.shape target_T = int(self.spec_size * self.freq_ratio) target_F = self.spec_size // self.freq_ratio assert T <= target_T and F <= target_F, "the wav size should less than or equal to the swin input size" # to avoid bicubic zero error if T < target_T: x = nn.functional.interpolate(x, (target_T, x.shape[3]), mode="bicubic", align_corners=True) if F < target_F: x = nn.functional.interpolate(x, (x.shape[2], target_F), mode="bicubic", align_corners=True) x = x.permute(0,1,3,2).contiguous() x = x.reshape(x.shape[0], x.shape[1], x.shape[2], self.freq_ratio, x.shape[3] // self.freq_ratio) # print(x.shape) x = x.permute(0,1,3,2,4).contiguous() x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3], x.shape[4]) return x # Repeat the wavform to a img size, if you want to use the pretrained swin transformer model def repeat_wat2img(self, x, cur_pos): B, C, T, F = x.shape target_T = int(self.spec_size * self.freq_ratio) target_F = self.spec_size // self.freq_ratio assert T <= target_T and F <= target_F, "the wav size should less than or equal to the swin input size" # to avoid bicubic zero error if T < target_T: x = nn.functional.interpolate(x, (target_T, x.shape[3]), mode="bicubic", align_corners=True) if F < target_F: x = nn.functional.interpolate(x, (x.shape[2], target_F), mode="bicubic", align_corners=True) x = x.permute(0,1,3,2).contiguous() # B C F T x = x[:,:,:,cur_pos:cur_pos + self.spec_size] x = x.repeat(repeats = (1,1,4,1)) return x def forward(self, x: torch.Tensor, mixup_lambda = None, infer_mode = False, device=None):# out_feat_keys: List[str] = None): if self.enable_fusion and x["longer"].sum() == 0: # if no audio is longer than 10s, then randomly select one audio to be longer x["longer"][torch.randint(0, x["longer"].shape[0], (1,))] = True if not self.enable_fusion: x = x["waveform"].to(device=device, non_blocking=True) x = self.spectrogram_extractor(x) # (batch_size, 1, time_steps, freq_bins) x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins) x = x.transpose(1, 3) x = self.bn0(x) x = x.transpose(1, 3) if self.training: x = self.spec_augmenter(x) if self.training and mixup_lambda is not None: x = do_mixup(x, mixup_lambda) x = self.reshape_wav2img(x) output_dict = self.forward_features(x) else: longer_list = x["longer"].to(device=device, non_blocking=True) x = x["mel_fusion"].to(device=device, non_blocking=True) x = x.transpose(1, 3) x = self.bn0(x) x = x.transpose(1, 3) longer_list_idx = torch.where(longer_list)[0] if self.fusion_type in ['daf_1d','aff_1d','iaff_1d']: new_x = x[:,0:1,:,:].clone().contiguous() if len(longer_list_idx) > 0: # local processing fusion_x_local = x[longer_list_idx,1:,:,:].clone().contiguous() FB,FC,FT,FF = fusion_x_local.size() fusion_x_local = fusion_x_local.view(FB * FC, FT, FF) fusion_x_local = torch.permute(fusion_x_local, (0,2,1)).contiguous() fusion_x_local = self.mel_conv1d(fusion_x_local) fusion_x_local = fusion_x_local.view(FB,FC,FF,fusion_x_local.size(-1)) fusion_x_local = torch.permute(fusion_x_local, (0,2,1,3)).contiguous().flatten(2) if fusion_x_local.size(-1) < FT: fusion_x_local = torch.cat([fusion_x_local, torch.zeros((FB,FF,FT- fusion_x_local.size(-1)), device=device)], dim=-1) else: fusion_x_local = fusion_x_local[:,:,:FT] # 1D fusion new_x = new_x.squeeze(1).permute((0,2,1)).contiguous() new_x[longer_list_idx] = self.fusion_model(new_x[longer_list_idx], fusion_x_local) x = new_x.permute((0,2,1)).contiguous()[:,None,:,:] else: x = new_x elif self.fusion_type in ['daf_2d','aff_2d','iaff_2d','channel_map']: x = x # no change if self.training: x = self.spec_augmenter(x) if self.training and mixup_lambda is not None: x = do_mixup(x, mixup_lambda) x = self.reshape_wav2img(x) output_dict = self.forward_features(x, longer_idx = longer_list_idx) # if infer_mode: # # in infer mode. we need to handle different length audio input # frame_num = x.shape[2] # target_T = int(self.spec_size * self.freq_ratio) # repeat_ratio = math.floor(target_T / frame_num) # x = x.repeat(repeats=(1,1,repeat_ratio,1)) # x = self.reshape_wav2img(x) # output_dict = self.forward_features(x) # else: # if x.shape[2] > self.freq_ratio * self.spec_size: # if self.training: # x = self.crop_wav(x, crop_size=self.freq_ratio * self.spec_size) # x = self.reshape_wav2img(x) # output_dict = self.forward_features(x) # else: # # Change: Hard code here # overlap_size = (x.shape[2] - 1) // 4 # output_dicts = [] # crop_size = (x.shape[2] - 1) // 2 # for cur_pos in range(0, x.shape[2] - crop_size - 1, overlap_size): # tx = self.crop_wav(x, crop_size = crop_size, spe_pos = cur_pos) # tx = self.reshape_wav2img(tx) # output_dicts.append(self.forward_features(tx)) # clipwise_output = torch.zeros_like(output_dicts[0]["clipwise_output"]).float().to(x.device) # framewise_output = torch.zeros_like(output_dicts[0]["framewise_output"]).float().to(x.device) # for d in output_dicts: # clipwise_output += d["clipwise_output"] # framewise_output += d["framewise_output"] # clipwise_output = clipwise_output / len(output_dicts) # framewise_output = framewise_output / len(output_dicts) # output_dict = { # 'framewise_output': framewise_output, # 'clipwise_output': clipwise_output # } # else: # this part is typically used, and most easy one # x = self.reshape_wav2img(x) # output_dict = self.forward_features(x) # x = self.head(x) # We process the data in the dataloader part, in that here we only consider the input_T < fixed_T return output_dict def create_htsat_model(audio_cfg, enable_fusion=False, fusion_type='None'): try: assert audio_cfg.model_name in ["tiny", "base", "large"], "model name for HTS-AT is wrong!" if audio_cfg.model_name == "tiny": model = HTSAT_Swin_Transformer( spec_size=256, patch_size=4, patch_stride=(4,4), num_classes=audio_cfg.class_num, embed_dim=96, depths=[2,2,6,2], num_heads=[4,8,16,32], window_size=8, config = audio_cfg, enable_fusion = enable_fusion, fusion_type = fusion_type ) elif audio_cfg.model_name == "base": model = HTSAT_Swin_Transformer( spec_size=256, patch_size=4, patch_stride=(4,4), num_classes=audio_cfg.class_num, embed_dim=128, depths=[2,2,12,2], num_heads=[4,8,16,32], window_size=8, config = audio_cfg, enable_fusion = enable_fusion, fusion_type = fusion_type ) elif audio_cfg.model_name == "large": model = HTSAT_Swin_Transformer( spec_size=256, patch_size=4, patch_stride=(4,4), num_classes=audio_cfg.class_num, embed_dim=256, depths=[2,2,12,2], num_heads=[4,8,16,32], window_size=8, config = audio_cfg, enable_fusion = enable_fusion, fusion_type = fusion_type ) return model except: raise RuntimeError(f'Import Model for {audio_cfg.model_name} not found, or the audio cfg parameters are not enough.')
null
8,558
from collections import OrderedDict from dataclasses import dataclass from email.mime import audio from typing import Tuple, Union, Callable, Optional import numpy as np import torch import torch.nn.functional as F from torch import nn from .timm_model import TimmModel import logging from .utils import freeze_batch_norm_2d from .pann_model import create_pann_model from .htsat import create_htsat_model from transformers import BertModel, RobertaModel, BartModel from transformers.tokenization_utils_base import BatchEncoding def trace_model(model, batch_size=256, device=torch.device("cpu")): model.eval() audio_length = model.audio_cfg.audio_length example_audio = torch.ones((batch_size, audio_length), device=device) example_text = torch.zeros( (batch_size, model.context_length), dtype=torch.int, device=device ) model = torch.jit.trace_module( model, inputs=dict( forward=(example_audio, example_text), encode_text=(example_text,), encode_image=(example_audio,), ), ) model.audio_cfg.audio_length = audio_length # Question: what does this do? return model
null
8,559
from multiprocessing.sharedctypes import Value import torch import torch.distributed.nn from torch import distributed as dist, nn as nn from torch.nn import functional as F import numpy as np from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score def gather_features( audio_features, text_features, audio_features_mlp=None, text_features_mlp=None, local_loss=False, gather_with_grad=False, rank=0, world_size=1, use_horovod=False, mlp_loss=False ): if use_horovod: assert hvd is not None, 'Please install horovod' if gather_with_grad: all_audio_features = hvd.allgather(audio_features) all_text_features = hvd.allgather(text_features) if mlp_loss: all_audio_features_mlp = hvd.allgather(audio_features_mlp) all_text_features_mlp = hvd.allgather(text_features_mlp) else: with torch.no_grad(): all_audio_features = hvd.allgather(audio_features) all_text_features = hvd.allgather(text_features) if mlp_loss: all_audio_features_mlp = hvd.allgather(audio_features_mlp) all_text_features_mlp = hvd.allgather(text_features_mlp) if not local_loss: # ensure grads for local rank when all_* features don't have a gradient gathered_audio_features = list(all_audio_features.chunk(world_size, dim=0)) gathered_text_features = list(all_text_features.chunk(world_size, dim=0)) gathered_audio_features[rank] = audio_features gathered_text_features[rank] = text_features all_audio_features = torch.cat(gathered_audio_features, dim=0) all_text_features = torch.cat(gathered_text_features, dim=0) if mlp_loss: gathered_audio_features_mlp = list(all_audio_features_mlp.chunk(world_size, dim=0)) gathered_text_features_mlp = list(all_text_features_mlp.chunk(world_size, dim=0)) gathered_audio_features_mlp[rank] = audio_features_mlp gathered_text_features_mlp[rank] = text_features_mlp all_audio_features_mlp = torch.cat(gathered_audio_features_mlp, dim=0) all_text_features_mlp = torch.cat(gathered_text_features_mlp, dim=0) else: # We gather tensors from all gpus if gather_with_grad: all_audio_features = torch.cat(torch.distributed.nn.all_gather(audio_features), dim=0) all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0) if mlp_loss: all_audio_features_mlp = torch.cat(torch.distributed.nn.all_gather(audio_features_mlp), dim=0) all_text_features_mlp = torch.cat(torch.distributed.nn.all_gather(text_features_mlp), dim=0) else: gathered_audio_features = [torch.zeros_like(audio_features) for _ in range(world_size)] gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)] dist.all_gather(gathered_audio_features, audio_features) dist.all_gather(gathered_text_features, text_features) if mlp_loss: gathered_audio_features_mlp = [torch.zeros_like(audio_features_mlp) for _ in range(world_size)] gathered_text_features_mlp = [torch.zeros_like(text_features_mlp) for _ in range(world_size)] dist.all_gather(gathered_audio_features_mlp, audio_features_mlp) dist.all_gather(gathered_text_features_mlp, text_features_mlp) if not local_loss: # ensure grads for local rank when all_* features don't have a gradient gathered_audio_features[rank] = audio_features gathered_text_features[rank] = text_features if mlp_loss: gathered_audio_features_mlp[rank] = audio_features_mlp gathered_text_features_mlp[rank] = text_features_mlp all_audio_features = torch.cat(gathered_audio_features, dim=0) all_text_features = torch.cat(gathered_text_features, dim=0) if mlp_loss: all_audio_features_mlp = torch.cat(gathered_audio_features_mlp, dim=0) all_text_features_mlp = torch.cat(gathered_text_features_mlp, dim=0) if mlp_loss: return all_audio_features, all_text_features, all_audio_features_mlp, all_text_features_mlp else: return all_audio_features, all_text_features
null