code stringlengths 17 6.64M |
|---|
class UpstreamExpert(UpstreamBase):
'\n Extract baseline features from wavforms by torchaudio.compliance.kaldi or torchaudio preprocessor\n Support: spectrogram, fbank, mfcc, mel, linear\n '
def __init__(self, model_config, **kwargs):
super().__init__(**kwargs)
with open(model_config... |
def get_extracter(config):
transforms = [ExtractAudioFeature(**config.get('kaldi', {})), Delta(**config.get('delta', {})), CMVN(**config.get('cmvn', {}))]
extracter = nn.Sequential(*transforms)
output_dim = extracter(torch.randn((EXAMPLE_SEC * SAMPLE_RATE))).size((- 1))
return (extracter, output_dim, ... |
class ExtractAudioFeature(nn.Module):
def __init__(self, feat_type='fbank', **kwargs):
super(ExtractAudioFeature, self).__init__()
self.extract_fn = eval(f'torchaudio.compliance.kaldi.{feat_type}')
self.kwargs = kwargs[feat_type]
self.frame_shift = self.kwargs.get('frame_shift', 1... |
class Delta(nn.Module):
def __init__(self, order=2, **kwargs):
super(Delta, self).__init__()
self.order = order
self.compute_delta = transforms.ComputeDeltas(**kwargs)
def forward(self, x):
feats = [x]
for o in range(self.order):
feat = feats[(- 1)].transp... |
class CMVN(nn.Module):
def __init__(self, use_cmvn, eps=1e-10):
super(CMVN, self).__init__()
self.eps = eps
self.use_cmvn = use_cmvn
def forward(self, x):
if self.use_cmvn:
x = ((x - x.mean(dim=0, keepdim=True)) / (self.eps + x.std(dim=0, keepdim=True)))
r... |
def baseline_local(model_config, *args, **kwargs):
'\n Baseline feature\n model_config: PATH\n '
assert os.path.isfile(model_config)
return _UpstreamExpert(model_config, *args, **kwargs)
|
def baseline(*args, **kwargs):
'\n Baseline feature - Fbank, or Mel-scale spectrogram\n '
return fbank(*args, **kwargs)
|
def spectrogram(*args, **kwargs):
'\n Baseline feature - Linear-scale spectrogram\n '
kwargs['model_config'] = os.path.join(os.path.dirname(__file__), 'spectrogram.yaml')
return baseline_local(*args, **kwargs)
|
def fbank(*args, **kwargs):
'\n Baseline feature - Fbank, or Mel-scale spectrogram\n '
kwargs['model_config'] = os.path.join(os.path.dirname(__file__), 'fbank.yaml')
return baseline_local(*args, **kwargs)
|
def fbank_no_cmvn(*args, **kwargs):
'\n Baseline feature - Fbank, or Mel-scale spectrogram\n '
kwargs['model_config'] = os.path.join(os.path.dirname(__file__), 'fbank_no_cmvn.yaml')
return baseline_local(*args, **kwargs)
|
def mfcc(*args, **kwargs):
'\n Baseline feature - MFCC\n '
kwargs['model_config'] = os.path.join(os.path.dirname(__file__), 'mfcc.yaml')
return baseline_local(*args, **kwargs)
|
def mel(*args, **kwargs):
'\n Baseline feature - Mel\n '
kwargs['model_config'] = os.path.join(os.path.dirname(__file__), 'mel.yaml')
return baseline_local(*args, **kwargs)
|
def linear(*args, **kwargs):
'\n Baseline feature - Linear\n '
kwargs['model_config'] = os.path.join(os.path.dirname(__file__), 'linear.yaml')
return baseline_local(*args, **kwargs)
|
def load_yaml_config(path_to_config):
'Loads yaml configuration settings as an EasyDict object.'
path_to_config = Path(path_to_config)
assert path_to_config.is_file()
with open(path_to_config) as f:
yaml_contents = yaml.safe_load(f)
return Namespace(**yaml_contents)
|
class PrecomputedNorm(nn.Module):
'Normalization using Pre-computed Mean/Std.\n Args:\n stats: Precomputed (mean, std).\n axis: Axis setting used to calculate mean/variance.\n '
def __init__(self, stats, axis=[1, 2]):
super().__init__()
self.axis = axis
(self.mean,... |
class NetworkCommonMixIn():
'Common mixin for network definition.'
def load_weight(self, weight_file, device):
'Utility to load a weight file to a device.'
state_dict = torch.load(weight_file, map_location=device)
if ('state_dict' in state_dict):
state_dict = state_dict['s... |
class AudioNTT2020Task6(nn.Module, NetworkCommonMixIn):
'DCASE2020 Task6 NTT Solution Audio Embedding Network.'
def __init__(self, n_mels, d):
super().__init__()
self.features = nn.Sequential(nn.Conv2d(1, 64, 3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, stride=2), n... |
class AudioNTT2020(AudioNTT2020Task6):
'BYOL-A General Purpose Representation Network.\n This is an extension of the DCASE 2020 Task 6 NTT Solution Audio Embedding Network.\n '
def __init__(self, n_mels=64, d=512):
super().__init__(n_mels=n_mels, d=d)
def forward(self, x):
x = supe... |
def byol_a_2048(refresh=False, **kwds):
ckpt = _urls_to_filepaths('https://github.com/nttcslab/byol-a/raw/master/pretrained_weights/AudioNTT2020-BYOLA-64x96d2048.pth', refresh=refresh)
return _UpstreamExpert(ckpt, DEFAULT_CONFIG_PATH, 2048, **kwds)
|
def byol_a_1024(refresh=False, **kwds):
ckpt = _urls_to_filepaths('https://github.com/nttcslab/byol-a/raw/master/pretrained_weights/AudioNTT2020-BYOLA-64x96d1024.pth', refresh=refresh)
return _UpstreamExpert(ckpt, DEFAULT_CONFIG_PATH, 1024, **kwds)
|
def byol_a_512(refresh=False, **kwds):
ckpt = _urls_to_filepaths('https://github.com/nttcslab/byol-a/raw/master/pretrained_weights/AudioNTT2020-BYOLA-64x96d512.pth', refresh=refresh)
return _UpstreamExpert(ckpt, DEFAULT_CONFIG_PATH, 512, **kwds)
|
def default(val, def_val):
return (def_val if (val is None) else val)
|
def flatten(t):
return t.reshape(t.shape[0], (- 1))
|
def singleton(cache_key):
def inner_fn(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
instance = getattr(self, cache_key)
if (instance is not None):
return instance
instance = fn(self, *args, **kwargs)
setattr(self, cache_key, ... |
def get_module_device(module):
return next(module.parameters()).device
|
def set_requires_grad(model, val):
for p in model.parameters():
p.requires_grad = val
|
def loss_fn(x, y):
x = F.normalize(x, dim=(- 1), p=2)
y = F.normalize(y, dim=(- 1), p=2)
return (2 - (2 * (x * y).sum(dim=(- 1))))
|
class EMA():
def __init__(self, beta):
super().__init__()
self.beta = beta
def update_average(self, old, new):
if (old is None):
return new
return ((old * self.beta) + ((1 - self.beta) * new))
|
def update_moving_average(ema_updater, ma_model, current_model):
for (current_params, ma_params) in zip(current_model.parameters(), ma_model.parameters()):
(old_weight, up_weight) = (ma_params.data, current_params.data)
ma_params.data = ema_updater.update_average(old_weight, up_weight)
|
class MLP(nn.Module):
def __init__(self, dim, projection_size, hidden_size=4096, use_bn=True):
super().__init__()
self.lin1 = nn.Linear(dim, hidden_size)
self.lin2 = nn.Linear(hidden_size, projection_size)
self.use_bn = use_bn
self.bn = nn.BatchNorm1d(hidden_size)
... |
class NetWrapper(nn.Module):
def __init__(self, net, projection_size, projection_hidden_size, layer=(- 2)):
super().__init__()
self.net = net
self.layer = layer
self.projector = None
self.projection_size = projection_size
self.projection_hidden_size = projection_hi... |
class BYOL(nn.Module):
'BYOL training module that is:\n - Decoupled augmentations.\n - Accepts two augmented inputs independently.\n '
def __init__(self, net, image_size, hidden_layer=(- 1), projection_size=256, projection_hidden_size=4096, moving_average_decay=0.99, use_momentum=True, channels=1):
... |
def get_timestamp():
'ex) Outputs 202104220830'
return datetime.datetime.now().strftime('%y%m%d%H%M')
|
def load_yaml_config(path_to_config):
'Loads yaml configuration settings as an EasyDict object.'
path_to_config = Path(path_to_config)
assert path_to_config.is_file()
with open(path_to_config) as f:
yaml_contents = yaml.safe_load(f)
cfg = Namespace(**yaml_contents)
return cfg
|
def get_logger(name):
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M', level=logging.DEBUG)
logger = logging.getLogger(name)
return logger
|
class MelSpectrogramLibrosa():
'Mel spectrogram using librosa.'
def __init__(self, fs=16000, n_fft=1024, shift=160, n_mels=64, fmin=60, fmax=7800):
(self.fs, self.n_fft, self.shift, self.n_mels, self.fmin, self.fmax) = (fs, n_fft, shift, n_mels, fmin, fmax)
self.mfb = librosa.filters.mel(sr=f... |
class WaveInLMSOutDataset(Dataset):
'Wave in, log-mel spectrogram out, dataset class.\n\n Choosing librosa or torchaudio:\n librosa: Stable but slower.\n torchaudio: Faster but cannot reproduce the exact performance of pretrained weight,\n which might be caused by the difference with l... |
class AudioNTT2020Task6(nn.Module, NetworkCommonMixIn):
'DCASE2020 Task6 NTT Solution Audio Embedding Network.'
def __init__(self, n_mels, d):
super().__init__()
self.features = nn.Sequential(nn.Conv2d(1, 64, 3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, stride=2), n... |
class AudioNTT2020(AudioNTT2020Task6):
'BYOL-A General Purpose Representation Network.\n\n This is an extension of the DCASE 2020 Task 6 NTT Solution Audio Embedding Network.\n '
sample_rate = 16000
embedding_size = 2048
scene_embedding_size = embedding_size
timestamp_embedding_size = embedd... |
def group_dict_by_key(cond, d):
return_val = [dict(), dict()]
for key in d.keys():
match = bool(cond(key))
ind = int((not match))
return_val[ind][key] = d[key]
return (*return_val,)
|
def group_by_key_prefix_and_remove_prefix(prefix, d):
(kwargs_with_prefix, kwargs) = group_dict_by_key((lambda x: x.startswith(prefix)), d)
kwargs_without_prefix = dict(map((lambda x: (x[0][len(prefix):], x[1])), tuple(kwargs_with_prefix.items())))
return (kwargs_without_prefix, kwargs)
|
class LayerNorm(nn.Module):
'Layer normalization, but done in channel dimension #1'
def __init__(self, dim, eps=1e-05):
super().__init__()
self.eps = eps
self.g = nn.Parameter(torch.ones(1, dim, 1, 1))
self.b = nn.Parameter(torch.zeros(1, dim, 1, 1))
def forward(self, x):... |
class PreNorm(nn.Module):
'Pre-Normalization layer'
def __init__(self, dim, fn):
super().__init__()
self.norm = LayerNorm(dim)
self.fn = fn
def forward(self, x, **kwargs):
x = self.norm(x)
return self.fn(x, **kwargs)
|
class FeedForward(nn.Module):
'Convolutional projection in the transformer.'
def __init__(self, dim, mult=4, dropout=0.0):
super().__init__()
self.net = nn.Sequential(nn.Conv2d(dim, (dim * mult), 1), nn.GELU(), nn.Dropout(dropout), nn.Conv2d((dim * mult), dim, 1), nn.Dropout(dropout))
de... |
class DepthWiseConv2d(nn.Module):
'Depthwise convolutional layer'
def __init__(self, dim_in, dim_out, kernel_size, padding, stride, bias=True):
super().__init__()
self.net = nn.Sequential(nn.Conv2d(dim_in, dim_in, kernel_size=kernel_size, padding=padding, groups=dim_in, stride=stride, bias=bi... |
class Attention(nn.Module):
'Custom Attention layer'
def __init__(self, dim, proj_kernel, kv_proj_stride, heads=8, dim_head=64, dropout=0.0):
super().__init__()
inner_dim = (dim_head * heads)
padding = (proj_kernel // 2)
self.heads = heads
self.scale = (dim_head ** (- ... |
class Transformer(nn.Module):
'Custom Transformer layer.'
def __init__(self, dim, proj_kernel, kv_proj_stride, depth, heads, dim_head=64, mlp_mult=4, dropout=0.0):
super().__init__()
self.layers = nn.ModuleList([])
for _ in range(depth):
self.layers.append(nn.ModuleList([P... |
class CvT(nn.Module):
'Convolutional Transformer module.\n\n Adapted for self-supervised training\n\n Attributes\n ----------\n s{i}_emb_dim: int\n Embedding dimention at stage i\n\n s{i}_emb_kernel: int\n Convolutional kernel size at stage i\n\n s{i}_emb_stride: int\n Convo... |
def conv3x3(in_planes: int, out_planes: int, stride: int=1, groups: int=1, dilation: int=1, standardize_weights: bool=False) -> nn.Conv2d:
'3x3 convolution with padding'
conv = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
re... |
def conv1x1(in_planes: int, out_planes: int, stride: int=1, standardize_weights: bool=False) -> nn.Conv2d:
'1x1 convolution'
conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
return (weight_norm(conv) if standardize_weights else conv)
|
class BasicBlock(nn.Module):
expansion: int = 1
def __init__(self, inplanes: int, planes: int, stride: int=1, downsample: Optional[nn.Module]=None, groups: int=1, base_width: int=64, dilation: int=1, norm_layer: Optional[Callable[(..., nn.Module)]]=None, standardize_weights: bool=False) -> None:
supe... |
class Bottleneck(nn.Module):
expansion: int = 4
def __init__(self, inplanes: int, planes: int, stride: int=1, downsample: Optional[nn.Module]=None, groups: int=1, base_width: int=64, dilation: int=1, norm_layer: Optional[Callable[(..., nn.Module)]]=None, standardize_weights: bool=False) -> None:
supe... |
class ResNetish(nn.Module):
sample_rate = 16000
embedding_size = 2048
scene_embedding_size = embedding_size
timestamp_embedding_size = embedding_size
def __init__(self, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], num_classes: int=1000, zero_init_residual: bool=False, groups: ... |
def _resnetish(arch: str, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], pretrained: bool, progress: bool, **kwargs: Any) -> ResNetish:
model = ResNetish(block, layers, **kwargs)
return model
|
def resnetish10(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNetish:
'ResNet-10 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (... |
def resnetish18(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNetish:
'ResNet-18 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (... |
def resnetish34(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNetish:
'ResNet-34 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Adapted for Audio from\n `"CNN architectures for large-scale audio classification" <https://arxiv.o... |
def resnetish50(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNetish:
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n Adapted for Audio from\n `"CNN architectures for large-scale audio classification" <https://arxiv.o... |
class Lambda(nn.Module):
'[NOT USED] Custom tensorflow-like Lambda function layer.'
def __init__(self, function):
super(Lambda, self).__init__()
self.function = function
def forward(self, x: Tensor) -> Tensor:
return self.function(x)
|
class NetworkCommonMixIn():
'Common mixin for network definition.'
def load_weight(self, weight_file, device):
'Utility to load a weight file to a device.'
state_dict = torch.load(weight_file, map_location=device)
if ('state_dict' in state_dict):
state_dict = state_dict['s... |
class UpstreamExpert(nn.Module):
def __init__(self, ckpt: str=None, model_name: str=None, window_secs: float=1, hop_secs: float=0.05, model_config: str=None):
super().__init__()
self.model = serab.load_model(ckpt, model_name)
self.frame_duration = (window_secs * 1000)
self.hop_siz... |
def byol_s_default(refresh: bool=False, **kwds):
kwds['model_name'] = 'default'
kwds['ckpt'] = _urls_to_filepaths('https://github.com/GasserElbanna/serab-byols/raw/main/checkpoints/default2048_BYOLAs64x96-2105311814-e100-bs256-lr0003-rs42.pth', refresh=refresh)
return _UpstreamExpert(**kwds)
|
def byol_s_cvt(refresh: bool=False, **kwds):
kwds['model_name'] = 'cvt'
kwds['ckpt'] = _urls_to_filepaths('https://github.com/GasserElbanna/serab-byols/raw/main/checkpoints/cvt_s1-d1-e64_s2-d1-e256_s3-d1-e512_BYOLAs64x96-osandbyolaloss6373-e100-bs256-lr0003-rs42.pth', refresh=refresh)
return _UpstreamExpe... |
def byol_s_resnetish34(refresh: bool=False, **kwds):
kwds['model_name'] = 'resnetish34'
kwds['ckpt'] = _urls_to_filepaths('https://github.com/GasserElbanna/serab-byols/raw/main/checkpoints/resnetish34_BYOLAs64x96-2105271915-e100-bs256-lr0003-rs42.pth', refresh=refresh)
return _UpstreamExpert(**kwds)
|
def get_model(model_name: str='', cfg={}) -> torch.nn.Module:
'Define the model object.\n\n Parameters\n ----------\n model_name: str, the name for pretrained model\n cfg: dict, the cfg parameters\n\n Returns\n -------\n torch.nn.Module object or a tensorflow "trackable" object\n '
if ... |
def load_model(model_file_path: str='', model_name: str='default', cfg_path: str=None) -> torch.nn.Module:
'Load pre-trained DL models.\n\n Parameters\n ----------\n model_name: str, the name for pretrained model\n model_file_path: str, the path for pretrained model\n cfg_path: str, the path for ya... |
def get_timestamp_embeddings(audio_list: List, model: torch.nn.Module, frame_duration: float=TIMESTAMP_FRAME_DUR, hop_size: float=TIMESTAMP_HOP_SIZE, cfg_path: str=None) -> Tuple[(Tensor, Tensor)]:
'\n This function returns embeddings at regular intervals centered at timestamps. Both\n the embeddings and co... |
def get_scene_embeddings(audio_list: List, model: torch.nn.Module, cfg_path: str=None) -> Tensor:
'\n This function returns a single embedding for each audio clip. In this baseline\n implementation we simply summarize the temporal embeddings from\n get_timestamp_embeddings() using torch.mean().\n Args... |
def get_default_cpc_config():
parser = set_default_cpc_config(argparse.ArgumentParser())
return parser.parse_args([])
|
def set_default_cpc_config(parser):
group = parser.add_argument_group('Architecture configuration', description="The arguments defining the model's architecture.")
group.add_argument('--hiddenEncoder', type=int, default=256, help='Hidden dimension of the encoder network.')
group.add_argument('--hiddenGar'... |
class UpstreamExpert(UpstreamBase):
def __init__(self, ckpt, **kwargs):
super().__init__(**kwargs)
locArgs = get_default_cpc_config()
checkpoint = torch.load(ckpt, map_location='cpu')
loadArgs(locArgs, argparse.Namespace(**checkpoint['config']))
encoderNet = getEncoder(loc... |
def cpc_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def cpc_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return cpc_local(_urls_to_filepaths(ckpt), *args, **kwargs)
|
def modified_cpc(refresh=False, *args, **kwargs):
'\n The model from official repository\n '
kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/librilight/CPC_checkpoints/60k_epoch4-d0f474de.pt'
return cpc_url(*args, refresh=refresh, **kwargs)
|
def load_and_convert_fairseq_ckpt(fairseq_source: str, output_path: str):
(state, cfg) = load_fairseq_ckpt(fairseq_source)
output_state = {'task_cfg': cfg['task'], 'model_cfg': cfg['model'], 'model_weight': state['model']}
Path(output_path).parent.mkdir(exist_ok=True, parents=True)
torch.save(output_s... |
def load_converted_model(ckpt: str):
ckpt_state = torch.load(ckpt, map_location='cpu')
for required_key in ['task_cfg', 'model_cfg', 'model_weight']:
if (required_key not in ckpt_state):
raise ValueError(f'{ckpt} is not a valid checkpoint since the required key: {required_key} is missing')... |
class EMAModuleConfig():
ema_decay: float = field(default=0.9999, metadata={'help': 'decay for exponential moving average model'})
ema_fp32: bool = field(default=False, metadata={'help': 'If true, store EMA model in fp32 even if model is in fp16'})
|
class EMAModule():
'Exponential Moving Average of Fairseq Models'
def __init__(self, model, config: EMAModuleConfig, device=None, skip_keys=None):
'\n @param model model to initialize the EMA with\n @param config EMAConfig object with configuration like\n ema_decay, ema_update_fr... |
@dataclass
class Data2VecAudioConfig(Wav2Vec2Config):
loss_beta: float = field(default=0, metadata={'help': 'beta for smooth l1 loss. 0 means use l2 loss'})
loss_scale: Optional[float] = field(default=None, metadata={'help': 'scale the reconstruction loss by this constant. if None then scales by 1/sqrt(dim)'}... |
def get_annealed_rate(start, end, curr_step, total_steps):
r = (end - start)
pct_remaining = (1 - (curr_step / total_steps))
return (end - (r * pct_remaining))
|
class Data2VecAudioModel(torch.nn.Module):
def __init__(self, cfg: Data2VecAudioConfig):
super().__init__()
self.cfg = cfg
feature_enc_layers = eval(cfg.conv_feature_layers)
self.extractor_embed = feature_enc_layers[(- 1)][0]
self.ema = None
self.embed = cfg.encode... |
def data2vec_custom(ckpt: str, refresh: bool=False, **kwargs):
if ckpt.startswith('http'):
ckpt = _urls_to_filepaths(ckpt, refresh=refresh)
return _UpstreamExpert(ckpt, **kwargs)
|
def data2vec_local(*args, **kwargs):
return data2vec_custom(*args, **kwargs)
|
def data2vec_url(*args, **kwargs):
return data2vec_custom(*args, **kwargs)
|
def data2vec(refresh=False, *args, **kwargs):
'\n The default model - Base\n refresh (bool): whether to download ckpt/config again if existed\n '
return data2vec_base_960(*args, refresh=refresh, **kwargs)
|
def data2vec_base_960(refresh=False, *args, **kwargs):
'\n The Base model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/audio_base_ls.pt'
return data2vec_custom(*args, refresh=refresh, **kwarg... |
def data2vec_large_ll60k(refresh=False, *args, **kwargs):
'\n The Large model trained on Libri-light 60k hours of data\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/vox_pretrained.pt'
return d... |
class CMVN(torch.jit.ScriptModule):
__constants__ = ['mode', 'dim', 'eps']
def __init__(self, mode='global', dim=2, eps=1e-10):
super(CMVN, self).__init__()
if (mode != 'global'):
raise NotImplementedError('Only support global mean variance normalization.')
self.mode = mod... |
class FeatureExtractor(nn.Module):
'Feature extractor, transforming file path to Mel spectrogram'
def __init__(self, mode='fbank', num_mel_bins=80, decode_wav=False, apply_cmvn=True, **kwargs):
super(FeatureExtractor, self).__init__()
assert (mode == 'fbank'), 'Only Mel-spectrogram implemente... |
def create_transform():
return FeatureExtractor()
|
def decoar_custom(ckpt: str, refresh=False, *args, **kwargs):
if ckpt.startswith('http'):
ckpt = _urls_to_filepaths(ckpt, refresh=refresh)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def decoar_local(*args, **kwargs):
return decoar_custom(*args, **kwargs)
|
def decoar_url(*args, **kwargs):
return decoar_custom(*args, **kwargs)
|
def decoar(refresh=False, *args, **kwargs):
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/checkpoint_decoar.pt'
return decoar_url(*args, refresh=refresh, **kwargs)
|
def decoar2_custom(ckpt: str, refresh=False, *args, **kwargs):
if ckpt.startswith('http'):
ckpt = _urls_to_filepaths(ckpt, refresh=refresh)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def decoar2_local(*args, **kwargs):
"\n The model from local ckpt\n ckpt (str): PATH\n feature_selection (str): 'c' (default) or 'z'\n "
return decoar2_custom(*args, **kwargs)
|
def decoar2_url(*args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return decoar2_custom(*args, **kwargs)
|
def decoar2(*args, refresh=False, **kwargs):
'\n The apc standard model on 360hr\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/checkpoint_decoar2.pt'
return decoar2_url(*args, refresh=refresh,... |
class CMVN(torch.jit.ScriptModule):
__constants__ = ['mode', 'dim', 'eps']
def __init__(self, mode='global', dim=2, eps=1e-10):
super(CMVN, self).__init__()
if (mode != 'global'):
raise NotImplementedError('Only support global mean variance normalization.')
self.mode = mod... |
class FeatureExtractor(nn.Module):
'Feature extractor, transforming file path to Mel spectrogram'
def __init__(self, mode='fbank', num_mel_bins=80, decode_wav=False, apply_cmvn=True, **kwargs):
super(FeatureExtractor, self).__init__()
assert (mode == 'fbank'), 'Only Mel-spectrogram implemente... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.