code
stringlengths
17
6.64M
def tensor2segment(tensor, tgt_dur, sample_rate=16000): src_dur = (len(tensor) / sample_rate) random_shift = random.uniform(0, (src_dur - tgt_dur)) (audio_tensor, _) = apply_effects_tensor(tensor.unsqueeze(0), sample_rate, [['pad', f'{tgt_dur}', f'{tgt_dur}'], ['trim', f'{(tgt_dur + random_shift)}', f'{tg...
class SWS2013Testset(Dataset): 'SWS 2013 testset.' def __init__(self, split, **kwargs): assert (split in ['dev', 'eval']) scoring_root = Path(kwargs['sws2013_scoring_root']) audio_names = parse_ecf(((scoring_root / f'sws2013_{split}') / 'sws2013.ecf.xml')) query_names = parse_...
def parse_ecf(ecf_path): 'Find audio paths from sws2013.ecf.xml.' root = ET.parse(str(ecf_path)).getroot() audio_names = [] for excerpt in root.findall('excerpt'): audio_name = excerpt.attrib['audio_filename'].replace('Audio/', '').replace('.wav', '') audio_names.append(audio_name) ...
def parse_tlist(tlist_path): 'Find audio paths from sws2013_eval.tlist.xml.' root = ET.parse(str(tlist_path)).getroot() audio_names = [] for term in root.findall('term'): audio_names.append(term.attrib['termid']) return audio_names
class DownstreamExpert(PhoneExpert): '\n Basically the same as the phone linear expert\n ' def __init__(self, upstream_dim, downstream_expert, **kwargs): super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs) delattr(self, 'model') model_cls = eval(sel...
def timit_posteriorgram_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 timit_posteriorgram_url(ckpt, refresh=False, *args, **kwargs): '\n The model from URL\n ckpt (str): URL\n ' return timit_posteriorgram_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
def timit_posteriorgram(refresh=False, *args, **kwargs): '\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n ' kwargs['ckpt'] = 'https://www.dropbox.com/s/fb2hkvetp26wges/convbank.ckpt?dl=1' return timit_posteriorgram_url(*args, refresh=refresh, ...
class ConvBank(nn.Module): def __init__(self, input_dim, output_class_num, kernels, cnn_size, hidden_size, dropout, **kwargs): super(ConvBank, self).__init__() self.drop_p = dropout self.in_linear = nn.Linear(input_dim, hidden_size) latest_size = hidden_size self.cnns = nn...
class UpstreamExpert(nn.Module): def __init__(self, ckpt, **kwargs): super(UpstreamExpert, self).__init__() ckpt = torch.load(ckpt, map_location='cpu') args = ckpt['Args'] self.upstream = getattr(s3prl.hub, args.upstream)() self.featurizer = Featurizer(self.upstream, 'last...
class DownstreamExpert(PhoneExpert): '\n Basically the same as the phone linear expert\n ' def __init__(self, upstream_dim, downstream_expert, **kwargs): super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs) delattr(self, 'model') self.model = Model(i...
class Model(nn.Module): def __init__(self, input_dim, output_class_num, hidden_size, dropout, **kwargs): super(Model, self).__init__() self.in_linear = nn.Linear(input_dim, hidden_size) self.out_linear = nn.Linear(hidden_size, output_class_num) self.drop = nn.Dropout(dropout) ...
class PhoneDataset(Dataset): def __init__(self, split, bucket_size, data_root, phone_path, bucket_file, sample_rate=16000, train_dev_seed=1337, **kwargs): super(PhoneDataset, self).__init__() self.data_root = data_root self.phone_path = phone_path self.sample_rate = sample_rate ...
class Model(nn.Module): def __init__(self, input_dim, output_class_num, **kwargs): super(Model, self).__init__() self.linear = nn.Linear(input_dim, output_class_num) def forward(self, features): predicted = self.linear(features) return predicted
class DownstreamExpert(PhoneExpert): '\n Basically the same as the phone linear expert\n ' def __init__(self, upstream_dim, downstream_expert, **kwargs): super(DownstreamExpert, self).__init__(upstream_dim, downstream_expert, **kwargs) delattr(self, 'model') self.model = Model(i...
class SpeakerClassifiDataset(Dataset): def __init__(self, mode, file_path, meta_data, max_timestep=None): self.root = file_path self.speaker_num = 1251 self.meta_data = meta_data self.max_timestep = max_timestep self.usage_list = open(self.meta_data, 'r').readlines() ...
class DownstreamExpert(nn.Module): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n ' def __init__(self, upstream_dim, downstream_expert, expdir, **kwargs): super(DownstreamExpert, self).__init__() self.upstream_dim = u...
class DownstreamExpert(SpeakerExpert): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n ' def __init__(self, upstream_dim, downstream_expert, expdir, **kwargs): super(DownstreamExpert, self).__init__(upstream_dim, downstream_ex...
class SpeakerVerifi_train(Dataset): def __init__(self, vad_config, file_path, meta_data, max_timestep=None): self.roots = file_path self.root_key = list(self.roots.keys()) self.max_timestep = max_timestep self.vad_c = vad_config self.dataset = [] self.all_speakers ...
class SpeakerVerifi_dev(Dataset): def __init__(self, vad_config, segment_config, file_path, meta_data): self.root = file_path self.meta_data = meta_data self.segment_config = segment_config self.vad_c = vad_config self.pair_dict = self.preprocessing() cache_path = ...
class SpeakerVerifi_test(Dataset): def __init__(self, vad_config, segment_config, file_path, meta_data): self.root = file_path self.meta_data = meta_data self.segment_config = segment_config self.vad_c = vad_config self.pair_dict = self.preprocessing() cache_path =...
class DownstreamExpert(nn.Module): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n\n Note 1.\n dataloaders should output in the following format:\n\n [[wav1, wav2, ...], your_other_contents, ...]\n\n where wav1, wav2 ....
def EER(labels, scores): '\n labels: (N,1) value: 0,1\n\n scores: (N,1) value: -1 ~ 1\n\n ' (fpr, tpr, thresholds) = roc_curve(labels, scores) s = interp1d(fpr, tpr) a = (lambda x: ((1.0 - x) - interp1d(fpr, tpr)(x))) eer = brentq(a, 0.0, 1.0) thresh = interp1d(fpr, thresholds)(eer) ...
def eer_yist_f(labels, scores): '\n Args:\n labels: (N,1) with value being 0 or 1\n scores: (N,1) within [-1, 1]\n\n Returns:\n equal_error_rates\n threshold\n ' joints = sorted(zip(scores, labels), key=(lambda x: x[0])) (sorted_scores, sorted_labels) = zip(*joints) ...
def _count_labels(counted_so_far, label, label_to_count=0): return ((counted_so_far + 1) if (label == label_to_count) else counted_so_far)
def compute_metrics(input_x_speaker, ylabel): wav1 = [] wav2 = [] for i in range(len(ylabel)): wav1.append(input_x_speaker[i].unsqueeze(0)) wav2.append(input_x_speaker[(len(ylabel) + i)].unsqueeze(0)) wav1 = torch.stack(wav1) wav2 = torch.stack(wav2) ylabel = torch.stack(ylabel...
class DownstreamExpert(nn.Module): '\n Used to handle downstream-specific operations\n eg. downstream forward, metric computation, contents to log\n\n Note 1.\n dataloaders should output in the following format:\n\n [[wav1, wav2, ...], your_other_contents, ...]\n\n where wav1, wav2 ....
def collect_speaker_ids(roots, speaker_num): all_speaker = [] for key in list(roots.keys()): all_speaker.extend([f.path for f in os.scandir(roots[key]) if f.is_dir()]) ids = [[speaker.split('/')[(- 3)], speaker.split('/')[(- 1)]] for speaker in all_speaker] vox1 = [] vox2 = [] for id i...
def construct_dev_speaker_id_txt(dev_speakers, dev_txt_name): f = open(dev_txt_name, 'w') for dev in dev_speakers: f.write(dev) f.write('\n') f.close() return
def sample_wavs_and_dump_txt(root, dev_ids, numbers, meta_data_name): wav_list = [] count_positive = 0 for _ in range(numbers): prob = random.random() if (prob > 0.5): dev_id_pair = random.sample(dev_ids, 2) sample1 = '/'.join(random.choice(find_files(os.path.join(r...
def EER(labels, scores): '\n labels: (N,1) value: 0,1\n\n scores: (N,1) value: -1 ~ 1\n\n ' (fpr, tpr, thresholds) = roc_curve(labels, scores) s = interp1d(fpr, tpr) a = (lambda x: ((1.0 - x) - interp1d(fpr, tpr)(x))) eer = brentq(a, 0.0, 1.0) thresh = interp1d(fpr, thresholds)(eer) ...
def eer_yist_f(labels, scores): '\n Args:\n labels: (N,1) with value being 0 or 1\n scores: (N,1) within [-1, 1]\n\n Returns:\n equal_error_rates\n threshold\n ' joints = sorted(zip(scores, labels), key=(lambda x: x[0])) (sorted_scores, sorted_labels) = zip(*joints) ...
def _count_labels(counted_so_far, label, label_to_count=0): return ((counted_so_far + 1) if (label == label_to_count) else counted_so_far)
def compute_metrics(input_x_speaker, ylabel): wav1 = [] wav2 = [] for i in range(len(ylabel)): wav1.append(input_x_speaker[i].unsqueeze(0)) wav2.append(input_x_speaker[(len(ylabel) + i)].unsqueeze(0)) wav1 = torch.stack(wav1) wav2 = torch.stack(wav2) ylabel = torch.stack(ylabel...
def options(only_registered_ckpt: bool=False): all_options = [] for (name, value) in globals().items(): torch_hubconf_policy = ((not name.startswith('_')) and callable(value)) if (torch_hubconf_policy and (name != 'options')): if (only_registered_ckpt and (name.endswith('_local') o...
def main(): try: cls = getattr(problem, sys.argv[1]) except: available_problems = [name for name in dir(problem) if ((not name.startswith('_')) and isinstance(getattr(problem, name), type))] print(traceback.format_exc()) print(f'''Usage: 1. s3prl-main [PROBLEM] -h 2. python3 -m...
def accuracy(xs, ys, item_same_fn=None): if isinstance(xs, (tuple, list)): assert isinstance(ys, (tuple, list)) return _accuracy_impl(xs, ys, item_same_fn) elif isinstance(xs, dict): assert isinstance(ys, dict) keys = sorted(list(xs.keys())) xs = [xs[k] for k in keys] ...
def _accuracy_impl(xs, ys, item_same_fn=None): item_same_fn = (item_same_fn or (lambda x, y: (x == y))) same = [int(item_same_fn(x, y)) for (x, y) in zip(xs, ys)] return (sum(same) / len(same))
def ter(hyps: List[Union[(str, List[str])]], refs: List[Union[(str, List[str])]]) -> float: 'Token error rate calculator.\n\n Args:\n hyps (List[Union[str, List[str]]]): List of hypotheses.\n refs (List[Union[str, List[str]]]): List of references.\n\n Returns:\n float: Averaged token er...
def wer(hyps: List[str], refs: List[str]) -> float: 'Word error rate calculator.\n\n Args:\n hyps (List[str]): List of hypotheses.\n refs (List[str]): List of references.\n\n Returns:\n float: Averaged word error rate overall utterances.\n ' hyps = [h.split(' ') for h in hyps] ...
def per(hyps: List[str], refs: List[str]) -> float: 'Phoneme error rate calculator.\n\n Args:\n hyps (List[str]): List of hypotheses.\n refs (List[str]): List of references.\n\n Returns:\n float: Averaged phoneme error rate overall utterances.\n ' return wer(hyps, refs)
def cer(hyps: List[str], refs: List[str]) -> float: 'Character error rate calculator.\n\n Args:\n hyps (List[str]): List of hypotheses.\n refs (List[str]): List of references.\n\n Returns:\n float: Averaged character error rate overall utterances.\n ' return ter(hyps, refs)
def compute_eer(labels: List[int], scores: List[float]): 'Compute equal error rate.\n\n Args:\n scores (List[float]): List of hypotheses.\n labels (List[int]): List of references.\n\n Returns:\n eer (float): Equal error rate.\n treshold (float): The treshold to accept a target tr...
def compute_minDCF(labels: List[int], scores: List[float], p_target: float=0.01, c_miss: int=1, c_fa: int=1): 'Compute MinDCF.\n Computes the minimum of the detection cost function. The comments refer to\n equations in Section 3 of the NIST 2016 Speaker Recognition Evaluation Plan.\n\n Args:\n sc...
def clean(ref: str) -> str: ref = re.sub('B\\-(\\S+) ', '', ref) ref = re.sub(' E\\-(\\S+)', '', ref) return ref
def parse(hyp: str, ref: str) -> Tuple[(str, str, str, str)]: gex = re.compile('B\\-(\\S+) (.+?) E\\-\\1') hyp = re.sub(' +', ' ', hyp) ref = re.sub(' +', ' ', ref) hyp_slots = gex.findall(hyp) ref_slots = gex.findall(ref) ref_slots = ';'.join([':'.join([x[1], x[0]]) for x in ref_slots]) i...
def get_slot_dict(hyp: str, ref: str) -> Tuple[(Dict[(str, List[str])], Dict[(str, List[str])])]: (ref_text, hyp_text, ref_slots, hyp_slots) = parse(hyp, ref) ref_slots = ref_slots.split(';') hyp_slots = hyp_slots.split(';') (ref_dict, hyp_dict) = ({}, {}) if (ref_slots[0] != ''): for ref_...
def slot_type_f1(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: F1s = [] for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) if ((len(hyp_dict.keys()) == 0) and (len(ref_dict.keys()) == 0)): F1 = 1.0 elif (len(hyp_dict....
def slot_value_cer(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: (value_hyps, value_refs) = ([], []) for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) unique_slots = list(ref_dict.keys()) for slot in unique_slots: fo...
def slot_value_wer(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: value_hyps = [] value_refs = [] for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) unique_slots = list(ref_dict.keys()) for slot in unique_slots: fo...
def slot_edit_f1(hypothesis: List[str], groundtruth: List[str], loop_over_all_slot: bool, **kwargs) -> float: slot2F1 = {} for (p, t) in zip(hypothesis, groundtruth): (ref_dict, hyp_dict) = get_slot_dict(p, t) unique_slots = list(ref_dict.keys()) if loop_over_all_slot: uniq...
def slot_edit_f1_full(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=True, **kwargs)
def slot_edit_f1_part(hypothesis: List[str], groundtruth: List[str], **kwargs) -> float: return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=False, **kwargs)
class BeamDecoder(object): 'Beam decoder powered by flashlight.\n\n Args:\n token (str, optional): Path to dictionary file. Defaults to "".\n lexicon (str, optional): Path to lexicon file. Defaults to "".\n lm (str, optional): Path to KenLM file. Defaults to "".\n nbest (int, option...
class FrameLevel(nn.Module): "\n The common frame-to-frame probing model\n\n Args:\n input_size (int): input size\n output_size (int): output size\n hidden_sizes (List[int]): a list of hidden layers' hidden size.\n by default is [256] to project all different input sizes to t...
class UtteranceLevel(nn.Module): "\n Args:\n input_size (int): input_size\n output_size (int): output_size\n hidden_sizes (List[int]): a list of hidden layers' hidden size.\n by default is [256] to project all different input sizes to the same dimension.\n set empty l...
class HearFullyConnectedPrediction(torch.nn.Module): '\n The specific prediction head used in the Hear Benchmark.\n Modified from: https://github.com/hearbenchmark/hear-eval-kit/blob/855964977238e89dfc76394aa11c37010edb6f20/heareval/predictions/task_predictions.py#L142\n\n Args:\n input_size (int)...
class AbsUpstream(nn.Module): '\n The upstream model should follow this interface. Please subclass it.\n ' @property def num_layer(self) -> int: '\n number of hidden states\n ' raise NotImplementedError @property def hidden_sizes(self) -> List[int]: '\...
class AbsFeaturizer(nn.Module): "\n The featurizer should follow this interface. Please subclass it.\n The featurizer's mission is to reduce (standardize) the multiple hidden\n states from :obj:`AbsUpstream` into a single hidden state, so that\n the downstream model can use it as a conventional repres...
class AbsFrameModel(nn.Module): '\n The frame-level model interface.\n ' @property def input_size(self) -> int: raise NotImplementedError @property def output_size(self) -> int: raise NotImplementedError def forward(self, x: torch.FloatTensor, x_len: torch.LongTensor) ...
class AbsUtteranceModel(nn.Module): '\n The utterance-level model interface, which pools the temporal dimension.\n ' @property def input_size(self) -> int: raise NotImplementedError @property def output_size(self) -> int: raise NotImplementedError def forward(self, x: ...
class FrameLevelLinear(FrameLevel): '\n The frame-level linear probing model used in SUPERB Benchmark\n ' def __init__(self, input_size: int, output_size: int, hidden_size: int=256): super().__init__(input_size, output_size, hidden_sizes=[hidden_size])
class MeanPoolingLinear(UtteranceLevel): '\n The utterance-level linear probing model used in SUPERB Benchmark\n ' def __init__(self, input_size: int, output_size: int, hidden_size: int=256): super().__init__(input_size, output_size, hidden_sizes=[hidden_size])
class MeanPooling(nn.Module): '\n Computes Temporal Average Pooling (MeanPooling over time) Module\n ' def __init__(self, input_size: int): super().__init__() self._in_size = input_size @property def input_size(self) -> int: return self._in_size @property def o...
class TemporalStatisticsPooling(nn.Module): '\n TemporalStatisticsPooling\n Paper: X-vectors: Robust DNN Embeddings for Speaker Recognition\n Link: http://www.danielpovey.com/files/2018_icassp_xvectors.pdf\n ' def __init__(self, input_size: int): super().__init__() self._input_siz...
class SelfAttentivePooling(nn.Module): '\n SelfAttentivePooling\n Paper: Self-Attentive Speaker Embeddings for Text-Independent Speaker Verification\n Link: https://danielpovey.com/files/2018_interspeech_xvector_attention.pdf\n ' def __init__(self, input_size: int): super().__init__() ...
class AttentiveStatisticsPooling(nn.Module): '\n AttentiveStatisticsPooling\n Paper: Attentive Statistics Pooling for Deep Speaker Embedding\n Link: https://arxiv.org/pdf/1803.10963.pdf\n ' def __init__(self, input_size: int): super().__init__() self._indim = input_size se...
class PredictorIdentity(nn.Module): '\n This nn module is used as a predictor placeholder for certain SSL problems.\n ' def __init__(self, **kwargs): super(PredictorIdentity, self).__init__() def forward(self, output: Output): '\n Args:\n output (s3prl.Output): An...
class PredictorMockingjay(nn.Module): '\n The predictor model for SSL pre-training tasks.\n Currently supporting SSL problems of Mockingjay, Tera, and Audio Albert.\n ' def __init__(self, config, output_dim, input_dim=None, **kwargs): '\n Args:\n config (TransformerConfig):...
class softmax(nn.Module): '\n The standard softmax loss in an unified interface for all speaker-related softmax losses\n ' def __init__(self, input_size: int, output_size: int): super().__init__() self._indim = input_size self._outdim = output_size self.fc = nn.Linear(in...
class amsoftmax(nn.Module): '\n AMSoftmax\n\n Args:\n input_size (int): The input feature size\n output_size (int): The output feature size\n margin (float): Hyperparameter denotes the margin to the decision boundry\n scale (float): Hyperparameter that scales the cosine value\n ...
class TDNN(nn.Module): '\n TDNN as defined by https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf.\n\n Context size and dilation determine the frames selected\n (although context size is not really defined in the traditional sense).\n\n For example:\n\n context size 5 and dilatio...
class XVectorBackbone(nn.Module): '\n The TDNN layers the same as in https://danielpovey.com/files/2018_odyssey_xvector_lid.pdf.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 1500) The size of the speaker embe...
class _SEModule(nn.Module): def __init__(self, channels, bottleneck=128): super().__init__() self.se = nn.Sequential(nn.AdaptiveAvgPool1d(1), nn.Conv1d(channels, bottleneck, kernel_size=1, padding=0), nn.ReLU(), nn.Conv1d(bottleneck, channels, kernel_size=1, padding=0), nn.Sigmoid()) def for...
class _Bottle2neck(nn.Module): def __init__(self, inplanes, planes, kernel_size=None, dilation=None, scale=8): super().__init__() width = int(math.floor((planes / scale))) self.conv1 = nn.Conv1d(inplanes, (width * scale), kernel_size=1) self.bn1 = nn.BatchNorm1d((width * scale)) ...
class ECAPA_TDNN(nn.Module): '\n ECAPA-TDNN model as in https://arxiv.org/abs/2005.07143.\n\n Reference code: https://github.com/TaoRuijie/ECAPA-TDNN.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 1536) The...
class SpeakerEmbeddingExtractor(nn.Module): '\n The speaker embedding extractor module.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 1500) The size of the speaker embedding\n backbone (str): (default, ...
class _UtteranceExtractor(nn.Module): def __init__(self, input_size, output_size): super().__init__() self._indim = input_size self._outdim = output_size self.linear1 = nn.Linear(input_size, output_size) self.linear2 = nn.Linear(output_size, output_size) self.act_f...
class SuperbXvector(nn.Module): '\n The Xvector used in the SUPERB Benchmark with the exact default arguments.\n\n Args:\n input_size (int): The input feature size, usually is the output size of upstream models\n output_size (int): (default, 512) The size of the speaker embedding\n hidd...
class TransformerConfig(object): '\n Configuration class to store the configuration of a `TransformerModel`.\n ' def __init__(self, hidden_size: int=768, num_hidden_layers: int=3, num_attention_heads: int=12, intermediate_size: int=3072, hidden_act: str='gelu', hidden_dropout_prob: float=0.1, attention...
def prune_linear_layer(layer, index, dim=0): '\n Prune a linear layer (a model parameters) to keep only entries in index.\n Return the pruned layer as a new layer with requires_grad=True.\n Used to remove heads.\n ' index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index...
def gelu(x): "\n Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n "...
def swish(x): return (x * torch.sigmoid(x))
class TransformerLayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): '\n Construct a layernorm module in the TF style (epsilon inside the square root).\n ' super(TransformerLayerNorm, self).__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) ...
class TransformerInputRepresentations(nn.Module): '\n Construct the input representation from spectrogram, and position encodings.\n ' def __init__(self, config, input_dim): super(TransformerInputRepresentations, self).__init__() self.hidden_size = config.hidden_size self.spec_t...
class TransformerSelfAttention(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False): super(TransformerSelfAttention, self).__init__() if ((config.hidden_size % config.num_attention_heads) != 0): raise ValueError(('The hidden size (%d) is not a m...
class TransformerSelfOutput(nn.Module): def __init__(self, config): super(TransformerSelfOutput, self).__init__() self.pre_layer_norm = config.pre_layer_norm self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) ...
class TransformerAttention(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False): super(TransformerAttention, self).__init__() self.output_attentions = output_attentions self.pre_layer_norm = config.pre_layer_norm self.self = TransformerSelfA...
class TransformerIntermediate(nn.Module): def __init__(self, config): super(TransformerIntermediate, self).__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act...
class TransformerOutput(nn.Module): def __init__(self, config): super(TransformerOutput, self).__init__() self.pre_layer_norm = config.pre_layer_norm self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) ...
class TransformerLayer(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False): super(TransformerLayer, self).__init__() self.output_attentions = output_attentions self.pre_layer_norm = config.pre_layer_norm self.attention = TransformerAttentio...
class TransformerEncoder(nn.Module): def __init__(self, config, output_attentions=False, keep_multihead_output=False, **kwargs): super(TransformerEncoder, self).__init__() if (type(config) is dict): config = TransformerConfig(**config) self.output_attentions = output_attention...
class TransformerInitModel(nn.Module): '\n An abstract class to handle weights initialization.\n ' def __init__(self, config, output_attentions, *inputs, **kwargs): super(TransformerInitModel, self).__init__() self.config = config self.output_attentions = output_attentions ...
class TransformerMockingjay(TransformerInitModel): '\n The Transformer model.\n Currently supporting upstreams models of Mockingjay, Tera, and Audio Albert.\n ' def __init__(self, config, input_dim, output_attentions=False, keep_multihead_output=False, with_input_module=True): '\n Arg...
class VqApcLayer(nn.Module): '\n The Vq Layer.\n Currently used in the upstream model of VQ-APC (nn/rnn_apc.py).\n Defines a VQ layer that follows an RNN layer.\n ' def __init__(self, input_size, codebook_size, code_dim, gumbel_temperature): '\n Args:\n input_size (int):...
def get_optimizer(model_params, total_steps, optimizer_config): optimizer_config = copy.deepcopy(optimizer_config) optimizer_name = optimizer_config.pop('name') optimizer = eval(f'get_{optimizer_name}')(model_params, total_steps=total_steps, **optimizer_config) return optimizer
def get_grouped_parameters(model_params): named_params = [] for m in model_params: named_params += list(m.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] grouped_parameters = [{'params': [p for (n, p) in named_params if (not any(((nd in n) for nd in no_decay)))], ...
def get_BertAdam_with_schedule(model_params, lr=0.0002, total_steps=20000, warmup_proportion=0.07, **kwargs): grouped_parameters = get_grouped_parameters(model_params) optimizer = BertAdam(grouped_parameters, lr=lr, warmup=warmup_proportion, t_total=total_steps) return optimizer
def get_AdamW_with_schedule(model_params, lr=0.0002, total_steps=20000, warmup_proportion=0.07, **kwargs): grouped_parameters = get_grouped_parameters(model_params) optimizer = Lamb(grouped_parameters, lr=lr, warmup=warmup_proportion, t_total=total_steps, adam=True, correct_bias=True, **kwargs) return opt...
def get_Lamb_with_schedule(model_params, lr=0.0002, total_steps=20000, warmup_proportion=0.07, **kwargs): grouped_parameters = get_grouped_parameters(model_params) optimizer = Lamb(grouped_parameters, lr=lr, warmup=warmup_proportion, t_total=total_steps, adam=False, correct_bias=False, **kwargs) return op...