code stringlengths 17 6.64M |
|---|
class EventBasedScore(SoundEventScore):
'\n event-based scores - the ground truth and system output are compared at\n event instance level;\n\n See https://tut-arg.github.io/sed_eval/generated/sed_eval.sound_event.EventBasedMetrics.html # noqa: E501\n for params.\n '
score_class = sed_eval.soun... |
class MeanAveragePrecision(ScoreFunction):
'\n Average Precision is calculated in macro mode which calculates\n AP at a class level followed by macro-averaging across the classes.\n '
name = 'mAP'
def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float:
assert... |
class DPrime(ScoreFunction):
'\n DPrime is calculated per class followed by averaging across the classes\n\n Code adapted from code provided by Eduoard Fonseca.\n '
name = 'd_prime'
def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float:
assert (predictions.n... |
class AUCROC(ScoreFunction):
'\n AUCROC (macro mode) is calculated per class followed by averaging across the\n classes\n '
name = 'aucroc'
def _compute(self, predictions: np.ndarray, targets: np.ndarray, **kwargs) -> float:
assert (predictions.ndim == 2)
assert (targets.ndim == ... |
class AutoregressiveReconstructionTask(Task):
'\n Attributes:\n upstream (torch.nn.Module): The upstream encoder (transformers, rnn, etc) that outputs `hidden_states`\n predictor (torch.nn.Module): The pre-training predictor that takes `hidden_states` as input and maps to the task target\n ... |
class Task(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def get_state(self):
return {}
def set_state(self, state: dict):
pass
def parse_cached_results(self, cached_results: List[dict]):
keys = list(cached_results[0].keys())
dol = defaultd... |
class FeatReconstructionTask(Task):
'\n Attributes:\n upstream (torch.nn.Module): The upstream encoder (transformers, rnn, etc) that outputs `hidden_states`\n predictor (torch.nn.Module): The pre-training predictor that takes `hidden_states` as input and maps to the task target\n loss (tor... |
class OneHotToCrossEntropyLoss(torch.nn.Module):
def __init__(self):
super().__init__()
self.loss = torch.nn.CrossEntropyLoss()
def forward(self, y_hat: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
assert torch.all((torch.sum(y, dim=1) == y.new_ones(y.shape[0])))
y = y.arg... |
class ScenePredictionTask(Task):
def __init__(self, model: torch.nn.Module, category: CategoryEncoder, prediction_type: str, scores: List[str]):
super().__init__()
self.model = model
self.label_to_idx = {str(category.decode(idx)): idx for idx in range(len(category))}
self.idx_to_l... |
class SpeakerClassifier(torch.nn.Module):
'\n Attributes:\n input_size: int\n output_size: int\n '
def __init__(self, input_size=3, output_size=4):
super().__init__()
self._input_size = input_size
self._output_size = output_size
@property
def input_size(se... |
class SpeakerVerification(Task):
'\n model.output_size should match len(categories)\n\n Args:\n model (SpeakerClassifier):\n actual model or a callable config for the model\n categories (dict[str]):\n each key in the Dictionary is the final prediction content in str.\n ... |
class Speech2TextCTCExample(nn.Module):
'An example speech-to-text task with CTC objective\n\n Args:\n input_size (int, optional): Input size. Defaults to 3.\n output_size (int, optional): Output size. Defaults to 4.\n '
def __init__(self, input_size=3, output_size=4):
super().__i... |
class Speech2TextCTCTask(Task):
'Speech-to-text task with CTC objective\n\n Args:\n model (Speech2TextCTCExample)\n tokenizer (Tokenizer): Text tokenizer.\n decoder (Union[BeamDecoder, dict], optional):\n Beam decoder or decoder\'s config. Defaults to None.\n log_metrics ... |
class CMVN(nn.Module):
__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 = mode
sel... |
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(audio_config):
feat_type = audio_config.pop('feat_type')
feat_dim = audio_config.pop('feat_dim')
decode_wav = audio_config.pop('decode_wav', False)
apply_cmvn = audio_config.pop('cmvn', True)
transforms = FeatureExtractor(feat_type, feat_dim, decode_wav, apply_cmvn, **audio_co... |
class UpstreamExpert(UpstreamBase):
def __init__(self, ckpt, **kwargs):
super().__init__(**kwargs)
ckpt = torch.load(ckpt, map_location='cpu')
config = ckpt['config']
(self.preprocessor, feat_dim) = create_transform(config['data']['audio'])
self.model = APC(feat_dim, **con... |
def apc_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 apc_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return apc_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def apc(refresh=False, *args, **kwargs):
'\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n '
return apc_360hr(*args, refresh=refresh, **kwargs)
|
def apc_360hr(refresh=False, *args, **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/leo19941227/apc_series/resolve/main/apc_360hr.ckpt'
return apc_url(*args, refresh=refresh, **kwarg... |
def apc_960hr(refresh=False, *args, **kwargs):
'\n The apc standard model on 960hr\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/leo19941227/apc_series/resolve/main/apc_960hr.ckpt'
return apc_url(*args, refresh=refresh, **kwarg... |
class VQLayer(nn.Module):
def __init__(self, input_size, codebook_size, code_dim, gumbel_temperature):
'\n Defines a VQ layer that follows an RNN layer.\n input_size: an int indicating the pre-quantized input feature size,\n usually the hidden size of RNN.\n codebook_size:... |
def ast(refresh: bool=False, window_secs: float=10.24, stride_secs: float=10.24, **kwds):
kwds['ckpt'] = _urls_to_filepaths('https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1', refresh=refresh)
return _UpstreamExpert(window_secs=window_secs, stride_secs=stride_secs, **kwds)
|
def audio_albert_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n feature_selection (int): -1 (default, the last layer) or an int in range(0, max_layer_num)\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def audio_albert_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return audio_albert_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def audio_albert(refresh=False, *args, **kwargs):
'\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n '
return audio_albert_960hr(*args, refresh=refresh, **kwargs)
|
def audio_albert_960hr(refresh=False, *args, **kwargs):
'\n The audio albert base model on 960hr\n refresh (bool): whether to download ckpt/config again if existed\n '
return audio_albert_logMelBase_T_share_AdamW_b32_1m_960hr_drop1(*args, refresh=refresh, **kwargs)
|
def audio_albert_logMelBase_T_share_AdamW_b32_1m_960hr_drop1(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 1M\n Unlabled Speech: 960hr\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/audio_albert/resol... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.