repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
BrnoLM
BrnoLM-master/scripts/eval/eval-independent.py
#!/usr/bin/env python import argparse import logging import math import torch from brnolm.runtime.runtime_utils import init_seeds from brnolm.runtime.evaluation import IndependentLinesEvaluator def main(): logging.basicConfig(level=logging.INFO, format='[%(levelname)s::%(name)s] %(message)s') parser = argpa...
2,106
33.540984
166
py
BrnoLM
BrnoLM-master/scripts/eval/eval-noivecs-domain-adaptation.py
#!/usr/bin/env python import argparse import math import torch from brnolm.data_pipeline.split_corpus_dataset import DomainAdaptationSplitFFMultiTarget from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.runtime.runtime_utils import CudaStream, filelist_to_objects, init_seeds from brnolm.runtime.ru...
2,447
36.090909
96
py
BrnoLM
BrnoLM-master/scripts/eval/eval-chime-v2.py
#!/usr/bin/env python import argparse import logging import math import torch from safe_gpu.safe_gpu import GPUOwner from brnolm.runtime.runtime_utils import init_seeds from brnolm.runtime.evaluation import SubstitutionalEnblockEvaluator_v2 from brnolm.data_pipeline.aug_paper_pipeline import Corruptor if __name__ =...
2,866
41.161765
166
py
BrnoLM
BrnoLM-master/scripts/eval/eval-ivecs-domain-adaptation.py
#!/usr/bin/env python import argparse import math import torch from brnolm.smm_itf import ivec_appenders from brnolm.data_pipeline.split_corpus_dataset import DomainAdaptationSplitFFMultiTarget from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.smm_itf import smm_ivec_extractor from brnolm.runtime...
2,993
37.883117
96
py
BrnoLM
BrnoLM-master/scripts/eval/eval-multifile.py
#!/usr/bin/env python import argparse import math import torch from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.data_pipeline.reading import tokens_from_file from brnolm.data_pipeline.temporal_splitting import TemporalSplits from brnolm.runtime.runtime_utils import CudaStream, init_seeds, fileli...
2,075
36.071429
84
py
BrnoLM
BrnoLM-master/scripts/eval/eval-chime.py
#!/usr/bin/env python import argparse import logging import math import torch from brnolm.runtime.runtime_utils import init_seeds from brnolm.runtime.evaluation import SubstitutionalEnblockEvaluator from brnolm.data_pipeline.augmentation import Corruptor if __name__ == '__main__': logging.basicConfig(level=logg...
2,589
40.774194
166
py
BrnoLM
BrnoLM-master/scripts/eval/eval.py
#!/usr/bin/env python import argparse import logging import math import torch from safe_gpu.safe_gpu import GPUOwner from brnolm.runtime.runtime_utils import init_seeds from brnolm.runtime.evaluation import EnblockEvaluator def main(args): print(args) init_seeds(args.seed, args.cuda) print("loading mo...
1,975
31.933333
166
py
BrnoLM
BrnoLM-master/scripts/eval/eval-ivecs-oracle.py
#!/usr/bin/env python import argparse import math import torch from brnolm.data_pipeline.split_corpus_dataset import TokenizedSplitFFBase from brnolm.smm_itf import ivec_appenders from brnolm.smm_itf import smm_ivec_extractor from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.data_pipeline.temporal...
2,812
36.013158
90
py
BrnoLM
BrnoLM-master/scripts/oov-clustering/collect-embeddings.py
#!/usr/bin/env python import argparse import sys import torch from brnolm.oov_clustering.embeddings_io import str_from_embedding from brnolm.oov_clustering.embeddings_computation import tensor_from_words def embs_from_words(words, lm): words = ["</s>"] + words th_data = tensor_from_words(words, lm.vocab)[:...
1,868
30.15
93
py
BrnoLM
BrnoLM-master/scripts/oov-clustering/predict-embeddings.py
#!/usr/bin/env python import argparse import sys import torch from brnolm.oov_clustering.embeddings_io import str_from_embedding from brnolm.oov_clustering.embeddings_computation import tensor_from_words def relevant_prefix(transcript, word_of_interest): first_oov_oi_loc = transcript.index(word_of_interest) ...
2,076
28.253521
93
py
BrnoLM
BrnoLM-master/scripts/train/train-independent.py
#!/usr/bin/env python import argparse import math import random import torch import time from brnolm.data_pipeline.reading import get_independent_lines from brnolm.data_pipeline.threaded import OndemandDataProvider from brnolm.data_pipeline.multistream import Batcher from brnolm.runtime.runtime_utils import init_see...
5,205
38.439394
198
py
BrnoLM
BrnoLM-master/scripts/train/train-chime-robust-v6.py
#!/usr/bin/env python import argparse import logging import math import torch from brnolm.data_pipeline.reading import tokens_from_fn from brnolm.data_pipeline.threaded import OndemandDataProvider from brnolm.data_pipeline.aug_paper_pipeline import InputTargetCorruptor, form_input_targets, LazyBatcher, TemplSplitterC...
7,071
41.095238
174
py
BrnoLM
BrnoLM-master/scripts/train/train-multifile.py
#!/usr/bin/env python import argparse import random import torch from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.data_pipeline.reading import tokens_from_file from brnolm.data_pipeline.temporal_splitting import TemporalSplits from brnolm.runtime.runtime_utils import CudaStream, init_seeds, fi...
4,945
39.876033
112
py
BrnoLM
BrnoLM-master/scripts/train/logger.py
# Code referenced from https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514 from torch.utils.tensorboard import SummaryWriter class Logger(object): def __init__(self, log_dir, update_freq): """Create a summary writer logging to log_dir.""" self.writer = SummaryWriter(log_dir) se...
1,124
31.142857
86
py
BrnoLM
BrnoLM-master/scripts/train/train-ivecs-oracle.py
#!/usr/bin/env python import argparse import random import torch from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.data_pipeline.temporal_splitting import TemporalSplits from brnolm.data_pipeline.split_corpus_dataset import TokenizedSplitFFBase from brnolm.smm_itf import ivec_appenders from brnol...
5,252
37.911111
112
py
BrnoLM
BrnoLM-master/scripts/train/train-ivecs-partial.py
#!/usr/bin/env python import argparse import random import torch from brnolm.data_pipeline.multistream import BatchBuilder from brnolm.smm_itf import ivec_appenders from brnolm.smm_itf import smm_ivec_extractor from brnolm.runtime.runtime_utils import CudaStream, init_seeds, filelist_to_tokenized_splits, BatchFilte...
5,080
38.695313
121
py
BrnoLM
BrnoLM-master/scripts/train/train-flat.py
#!/usr/bin/env python import argparse import logging import math import sys import torch from safe_gpu.safe_gpu import GPUOwner from brnolm.data_pipeline.pipeline_factories import plain_factory, yaml_factory from brnolm.runtime.runtime_utils import init_seeds, epoch_summary from brnolm.runtime.runtime_multifile imp...
6,422
38.164634
114
py
BrnoLM
BrnoLM-master/scripts/train/train-no-epoch.py
#!/usr/bin/env python import argparse import logging import math import sys import torch from safe_gpu.safe_gpu import GPUOwner from brnolm import zoo from brnolm.data_pipeline.reading import tokenizer_factory from brnolm.data_pipeline.pipeline_factories import plain_factory_noepoch, yaml_factory_noepoch from brno...
7,559
36.058824
126
py
BrnoLM
BrnoLM-master/scripts/train/train.py
#!/usr/bin/env python import argparse import math import torch from logger import Logger from brnolm.data_pipeline.reading import tokens_from_fn from brnolm.data_pipeline.multistream import batchify from brnolm.data_pipeline.temporal_splitting import TemporalSplits from brnolm.runtime.runtime_utils import TransposeW...
5,079
37.484848
121
py
BrnoLM
BrnoLM-master/scripts/train/train-pero.py
#!/usr/bin/env python import argparse import torch from brnolm.data_pipeline.reading import tokens_from_fn from brnolm.data_pipeline.multistream import batchify from brnolm.data_pipeline.temporal_splitting import TemporalSplits from brnolm.runtime.runtime_utils import TransposeWrapper, init_seeds, epoch_summary from...
5,299
33.640523
121
py
BrnoLM
BrnoLM-master/scripts/rescoring/rescore-kaldi-latts-continuous.py
#!/usr/bin/env python3 import argparse import logging import torch import brnolm.language_models.vocab as vocab from brnolm.rescoring.segment_scoring import SegmentScorer from safe_gpu.safe_gpu import GPUOwner import typing import brnolm.kaldi_itf def translate_latt_to_model(word_ids, latt_vocab, model_vocab, mod...
4,702
35.742188
211
py
BrnoLM
BrnoLM-master/scripts/rescoring/rescore-nbest-continuous.py
#!/usr/bin/env python3 import argparse import logging import torch from brnolm.rescoring.segment_scoring import SegmentScorer from safe_gpu.safe_gpu import GPUOwner import typing import brnolm.kaldi_itf def select_hidden_state_to_pass(hidden_states): return hidden_states['1'] def spk_sess(segment_name): ...
3,427
31.961538
101
py
BrnoLM
BrnoLM-master/scripts/model-building/build-shallow-nn.py
#!/usr/bin/env python import argparse import torch from brnolm.language_models import ffnn_models, vocab, language_model from brnolm.language_models.decoders import FullSoftmaxDecoder if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch FFNN Language Model') parser.add_argument('-...
2,045
40.755102
96
py
BrnoLM
BrnoLM-master/scripts/model-building/build-transformer.py
#!/usr/bin/env python import argparse import torch from brnolm.language_models import transformer, vocab, language_model from brnolm.language_models.decoders import FullSoftmaxDecoder if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch LSTM Language Model') parser.add_argument('...
2,643
39.676923
113
py
BrnoLM
BrnoLM-master/scripts/model-building/build-lstm.py
#!/usr/bin/env python import argparse import torch from brnolm.language_models import lstm_model, vocab, language_model from brnolm.language_models.decoders import CustomLossFullSoftmaxDecoder from brnolm.language_models.encoders import FlatEmbedding if __name__ == '__main__': parser = argparse.ArgumentParser(d...
3,111
42.830986
113
py
BrnoLM
BrnoLM-master/scripts/model-building/build-lstmp.py
#!/usr/bin/env python import argparse import torch from brnolm.language_models import lstm_model, vocab, language_model from brnolm.language_models.decoders import FullSoftmaxDecoder if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch LSTM Language Model') parser.add_argument('-...
2,290
40.654545
89
py
BrnoLM
BrnoLM-master/scripts/model-building/build-shallow-nn-with-ivec.py
#!/usr/bin/env python import argparse import torch from brnolm.language_models import language_model, vocab, ffnn_models from brnolm.language_models.decoders import FullSoftmaxDecoder if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch FFNN Language Model') parser.add_argument('-...
2,187
41.901961
96
py
BrnoLM
BrnoLM-master/brnolm/multifile-ivec-unigram-ppl.py
#!/usr/bin/env python import argparse import math import runtime_utils import torch import language_model import smm_ivec_extractor def bows_to_ps(bows): uni_ps = bows.t() / bows.sum(dim=1) return uni_ps.t() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file-...
1,596
26.534483
68
py
BrnoLM
BrnoLM-master/brnolm/analyze-ivec-changes.py
#!/usr/bin/env python import argparse import io import math import sys import torch import split_corpus_dataset import ivec_appenders import smm_ivec_extractor from runtime_utils import filenames_file_to_filenames class DummyDict: def __getitem__(self, index): return 0 def euclidean_distance(a, b): ...
4,087
30.206107
127
py
BrnoLM
BrnoLM-master/brnolm/rmn-plotter.py
#!/usr/bin/env python import torch import argparse import plotting import numpy as np if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("model") args = parser.parse_args() with open(args.model, 'rb') as f: model = torch.load(f) cs_numpied = [c.weight.dat...
1,037
30.454545
102
py
BrnoLM
BrnoLM-master/brnolm/investigate-ivecs.py
#!/usr/bin/env python import argparse import torch import smm_ivec_extractor from runtime_utils import init_seeds, filenames_file_to_filenames if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch RNN/LSTM Language Model') parser.add_argument('--filelist', type=str, required=True,...
1,516
31.276596
83
py
BrnoLM
BrnoLM-master/brnolm/analysis.py
import torch def categorical_entropy(p, eps=1e-100): zeros = p <= eps log_p = p.log() log_p.masked_fill_(zeros, 0.0) # eliminates -inf for p[x] = 0.0 H_p = - torch.sum(p*log_p, dim=-1) return H_p / torch.log(torch.FloatTensor([2])) def categorical_cross_entropy(p, q, eps=1e-100): zeros...
651
23.148148
67
py
BrnoLM
BrnoLM-master/brnolm/srilm-debug2.py
#!/usr/bin/env python import argparse import math import sys import torch BATCH_SIZE = 1 def per_word_logprobs(words, lm): words_tensor = torch.tensor([lm.vocab[w] for w in words], requires_grad=False).view(1, -1) x = words_tensor[:, :-1] t = words_tensor[:, 1:] h0 = lm.model.init_hidden(x.size(0...
2,668
28.655556
138
py
BrnoLM
BrnoLM-master/brnolm/multifile-ml-unigram-tranfer-ppl.py
#!/usr/bin/env python import argparse import math import runtime_utils import vocab import torch import analysis def bows_to_ps(bows): uni_ps = bows.t() / bows.sum(dim=1) return uni_ps.t() def bows_to_ent(bows): uni_ps = bows_to_ps(bows) entropies = analysis.categorical_entropy(uni_ps) av...
1,914
26.357143
83
py
BrnoLM
BrnoLM-master/brnolm/multifile-ml-unigram-ppl.py
#!/usr/bin/env python import argparse import math import runtime_utils import vocab import torch import analysis def bows_to_ps(bows): uni_ps = bows.t() / bows.sum(dim=1) return uni_ps.t() def bows_to_ent(bows): uni_ps = bows_to_ps(bows) entropies = analysis.categorical_entropy(uni_ps) av...
1,368
24.351852
70
py
BrnoLM
BrnoLM-master/brnolm/analyze-ivec-distribution.py
#!/usr/bin/env python import argparse import io import math import sys import torch import numpy as np import split_corpus_dataset import ivec_appenders import smm_ivec_extractor from runtime_utils import filenames_file_to_filenames if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_arg...
1,245
26.086957
63
py
BrnoLM
BrnoLM-master/brnolm/lm-info.py
#!/usr/bin/env python import argparse import torch if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch RNN/LSTM Language Model') parser.add_argument('--vocab', action='store_true', help='print out the full vocab') parser.add_argument('load', help='where to load a model from') ...
523
29.823529
88
py
BrnoLM
BrnoLM-master/brnolm/oov_clustering/embeddings_computation.py
import torch def tensor_from_words(words, vocab): return torch.tensor([vocab[w] for w in words]).view(1, -1)
115
18.333333
62
py
BrnoLM
BrnoLM-master/brnolm/runtime/runtime_multifile.py
import torch from .runtime_utils import repackage_hidden from .tensor_reorganization import TensorReorganizer def prepare_inputs(inputs, do_transpose, use_ivecs, custom_batches): X = inputs[0] batch_size = X.size(0) if do_transpose: X = X.t() targets = inputs[1] if do_transpose: ...
3,869
25.506849
112
py
BrnoLM
BrnoLM-master/brnolm/runtime/model_statistics.py
def scaled_int_str(value): if value < 1000: return f'{value}' elif value < 1000000: return f'{value/1000:.1f}k' else: return f'{value/1000000:.1f}M' class ModelStatistics: def __init__(self, model): self.model = model def total_nb_params(self): return sum(p...
1,328
39.272727
130
py
BrnoLM
BrnoLM-master/brnolm/runtime/reporting.py
import pathlib import torch import math class ValidationWatcher: def __init__(self, val_fn, initial_val_loss, freq_in_tokens, workdir, lm, lr_control=None): self.val_losses = [initial_val_loss] self.validation_fn = val_fn self.lm = lm pathlib.Path(workdir).mkdir(parents=True, exis...
1,917
29.444444
95
py
BrnoLM
BrnoLM-master/brnolm/runtime/tensor_reorganization.py
import torch from typing import Dict, Any class Singleton(type): _instances: Dict[Any, Any] = {} # TODO what is the actual type? def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._in...
1,926
26.140845
99
py
BrnoLM
BrnoLM-master/brnolm/runtime/loggers.py
import sys import time import math import torch class BaseLogger(): def __init__(self, report_period, output_file=sys.stdout): self._start_time = time.time() self._nb_logs = 0 self._report_period = report_period self._of = output_file self._construction_time = time.time() ...
3,926
27.664234
182
py
BrnoLM
BrnoLM-master/brnolm/runtime/evaluation.py
import logging import math import numpy as np from dataclasses import dataclass from brnolm.data_pipeline.reading import get_independent_lines, tokens_from_fn from brnolm.data_pipeline.threaded import OndemandDataProvider from brnolm.data_pipeline.multistream import Batcher, batchify from brnolm.data_pipeline.temporal...
10,317
36.249097
156
py
BrnoLM
BrnoLM-master/brnolm/runtime/runtime_utils.py
import random import torch from brnolm.data_pipeline import split_corpus_dataset import sys import math class CudaStream(): def __init__(self, source): self._source = source def __iter__(self): for batch in self._source: yield tuple(x.cuda() for x in batch) class TransposeWrap...
3,493
27.876033
110
py
BrnoLM
BrnoLM-master/brnolm/rescoring/segment_scoring.py
from dataclasses import dataclass import logging import typing import torch from brnolm.language_models.language_model import split_batch_hidden_state, detach_hidden_state # for LSTMs def lstm_h0_provider(single_h, batch_size): h, c = single_h return (torch.stack([h]*batch_size, axis=1), torch.stack([c]*batc...
5,188
39.539063
178
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/masked.py
from typing import List import torch def masked_tensor_from_sentences(sentences: List[List[int]], filler=0, device=torch.device('cpu'), target_all=False): try: sentences[0][0] except TypeError: raise ValueError("masked_tensor_from_sentences() consumes List of Lists (batch X time)") batch_...
1,467
35.7
117
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/split_corpus_dataset.py
import torch from brnolm.data_pipeline.temporal_splitting import TemporalSplits class TokenizedSplitFFBase(): def __init__(self, f, vocab, temporal_split_builder): """ Args: f (file): File with a document. vocab (Vocabulary): Vocabulary for translation word -> ...
3,756
33.787037
123
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/multistream.py
import torch class LineTooLongError(Exception): pass def batchify(data, bsz, cuda): """ For simple rearranging of 'single sentence' data. """ # Work out how cleanly we can divide the dataset into bsz parts. nbatch = data.size(0) // bsz # Trim off any extra elements that wouldn't cleanly fit ...
3,518
29.336207
100
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/augmentation.py
import torch class Substitutor: def __init__(self, rate, replacements_range): self.rate = rate self.replacements_range = replacements_range if not isinstance(replacements_range, int) or replacements_range < 0: raise ValueError(f"Replacements range needs to be a positive integer...
1,627
32.22449
108
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/reading.py
import torch def word_splitter(line): return line.split() def char_splitter(line, sentence_end_token=None): chars = list(line) if sentence_end_token is None: return chars else: return chars + [sentence_end_token] class WordIdProvider: def __init__(self, vocab): self.vo...
2,350
22.989796
119
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/flexible_pipeline.py
import random import torch class SequenceReadingHead: def __init__(self, seq, start=0): self.seq = seq self.pos = start def __next__(self): val = self.seq[self.pos] self.pos = (self.pos + 1) % len(self.seq) return val class FileReadingHead: def __init__(self, fn,...
3,484
29.304348
226
py
BrnoLM
BrnoLM-master/brnolm/data_pipeline/aug_paper_pipeline.py
import numpy as np import random import torch def form_input_targets(stream): return stream[:-1], stream[1:] class CleanStreamsProvider: def __init__(self, stream): self.stream = stream def provide(self): return self.stream[:-1], self.stream[1:] class Corruptor: def __init__(self,...
12,152
32.946927
276
py
BrnoLM
BrnoLM-master/brnolm/language_models/ffnn_models.py
import torch import torch.nn as nn import torch.nn.functional as F class BengioModel(nn.Module): """Container module with an encoder, a recurrent module, and a decoder.""" def __init__(self, ntoken, emb_size, in_len, nb_hidden, dropout=0.5): super().__init__() self.drop = nn.Dropout(dropout) ...
3,043
35.674699
106
py
BrnoLM
BrnoLM-master/brnolm/language_models/lstm_model.py
import torch import torch.nn as nn from typing import Tuple class LSTMLanguageModel(nn.Module): """Container module with an encoder, a recurrent module, and a decoder.""" def __init__(self, token_encoder, dim_input, dim_lstm, nb_layers, dropout=0.5): super(LSTMLanguageModel, self).__init__() ...
3,018
31.462366
93
py
BrnoLM
BrnoLM-master/brnolm/language_models/transformer.py
import torch from torch import nn import math from torch.nn import TransformerEncoder, TransformerEncoderLayer class PositionalEncoding(nn.Module): r"""Inject some information about the relative or absolute position of the tokens in the sequence. The positional encodings have the same dimension as ...
3,545
36.326316
98
py
BrnoLM
BrnoLM-master/brnolm/language_models/decoders.py
import torch class FullSoftmaxDecoder(torch.nn.Module): def __init__(self, nb_hidden, nb_output, init_range=0.1): super().__init__() self.projection = torch.nn.Linear(nb_hidden, nb_output) self.log_softmax = torch.nn.LogSoftmax(dim=-1) self.projection.weight.data.uniform_(-init_r...
2,752
31.011628
104
py
BrnoLM
BrnoLM-master/brnolm/language_models/language_model.py
import torch import pickle import zipfile from brnolm.data_pipeline.masked import masked_tensor_from_sentences # these helper functions are being developed against an LSTM implementation # It's ugly, but necessary for Chime. To be made nice later :-) def detach_hidden_state(h): if isinstance(h, tuple): ...
5,174
31.34375
96
py
BrnoLM
BrnoLM-master/brnolm/language_models/encoders.py
import torch.nn as nn class FlatEmbedding(nn.Module): def __init__(self, nb_tokens, dim_embs, init_range=0.1): super().__init__() self.embeddings = nn.Embedding(nb_tokens, dim_embs) nn.init.uniform_(self.embeddings.weight, -init_range, init_range) def forward(self, x): return ...
339
27.333333
73
py
BrnoLM
BrnoLM-master/brnolm/smm_itf/xtract-ivecs-example.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # author : KarelB # e-mail : ibenes AT fit.vutbr.cz import argparse import torch import .smm_ivec_extractor def bow_from_sentence(sentence, vocab): bow = torch.zeros((1, len(vocab))).float() for w in sentence.split(): bow[0, vocab[w]] += 1.0 retu...
1,172
25.066667
98
py
BrnoLM
BrnoLM-master/brnolm/smm_itf/smm_ivec_extractor.py
import io import tempfile import pickle import numpy as np import torch from smm import update_ws class IvecExtractor(): def __init__(self, model, nb_iters, lr, tokenizer): self._model = model self._nb_iters = nb_iters self._lr = lr self._tokenizer = tokenizer def __call__(s...
4,743
31.493151
111
py
robust_overfitting
robust_overfitting-master/generate_validation.py
import torch import torchvision import numpy as np np.random.seed(0) m = 50000 P = np.random.permutation(m) n = 1000 def cifar10(root): train_set = torchvision.datasets.CIFAR10(root=root, train=True, download=True) test_set = torchvision.datasets.CIFAR10(root=root, train=False, download=True) return { ...
967
25.162162
82
py
robust_overfitting
robust_overfitting-master/train_cifar_semisupervised_half.py
import argparse import logging import sys import time import math import pickle import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import os from wideresnet import WideResNet from preactresnet import PreActResNet18 from utils import * mu = torc...
19,326
39.860465
192
py
robust_overfitting
robust_overfitting-master/preactresnet.py
'''Pre-activation ResNet in PyTorch. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks. arXiv:1603.05027 ''' import torch import torch.nn as nn import torch.nn.functional as F class PreActBlock(nn.Module): '''Pre-activation version of the BasicBlock....
4,208
33.785124
102
py
robust_overfitting
robust_overfitting-master/utils.py
import numpy as np from collections import namedtuple import torch from torch import nn import torchvision device = torch.device("cuda" if torch.cuda.is_available() else "cpu") ################################################################ ## Components from https://github.com/davidcpage/cifar10-fast ## ###########...
4,043
32.421488
122
py
robust_overfitting
robust_overfitting-master/train_svhn.py
import argparse import logging import sys import time import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets, transforms import os from wideresnet import WideResNet from preactresnet import PreActResNet18 ...
13,458
37.127479
192
py
robust_overfitting
robust_overfitting-master/train_cifar.py
import argparse import logging import sys import time import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import os from wideresnet import WideResNet from preactresnet import PreActResNet18 from utils import * mu = torch.tensor(cifar...
18,952
40.202174
192
py
robust_overfitting
robust_overfitting-master/train_cifar100.py
import argparse import logging import sys import time import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets, transforms import os from wideresnet import WideResNet from preactresnet import PreActResNet18...
12,725
36.650888
192
py
robust_overfitting
robust_overfitting-master/wideresnet.py
import math import torch import torch.nn as nn import torch.nn.functional as F class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu1 = nn.ReLU(inplace=True) se...
3,685
42.880952
116
py
lagros
lagros-main/Codes/cartpole.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 11 21:27:54 2020 @author: hiroyasu """ import numpy as np import cvxpy as cp import scipy as sp from matplotlib import pyplot as plt from matplotlib import animation import control import time from tensorflow.keras.models import Sequential from te...
30,165
33.633754
117
py
lagros
lagros-main/Codes/test.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 8 16:52:25 2021 @author: hiroyasu """ import numpy as np import cvxpy as cp from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation import control import time from tensorflow.keras.models imp...
65,740
37.648442
194
py
lagros
lagros-main/Codes/multi_agent_leo.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 7 14:46:55 2020 @author: hiroyasu """ import numpy as np import cvxpy as cp from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation import control import time from tensorflow.keras.models impo...
68,117
37.902342
194
py
lagros
lagros-main/Codes/multi_agent_sc_obs.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 10 11:56:53 2020 @author: hiroyasu """ import numpy as np import cvxpy as cp from matplotlib import pyplot as plt from matplotlib import animation import control import time from tensorflow.keras.models import Sequential from tensorflow.keras.laye...
61,172
38.364865
135
py
lagros
lagros-main/Codes/classncm.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2020 Hiroyasu Tsukamoto https://hirotsukamoto.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restricti...
47,298
37.865242
80
py
awesome-align
awesome-align-master/setup.py
from setuptools import setup, find_packages import codecs setup( name='awesome_align', install_requires=[ 'tokenizers>=0.5.2', 'torch>=1.2.0', 'tqdm', 'numpy', 'boto3', 'filelock', 'requests' ], version='0.1.7', author='NeuLab', author_ema...
811
25.193548
71
py
awesome-align
awesome-align-master/awesome_align/configuration_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
17,149
47.583569
193
py
awesome-align
awesome-align-master/awesome_align/modeling_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
80,266
48.578135
472
py
awesome-align
awesome-align-master/awesome_align/modeling.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # Modifications copyright (C) 2020 Zi-Yi Dou # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
31,151
41.499318
228
py
awesome-align
awesome-align-master/awesome_align/tokenization_bert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
27,055
41.341158
183
py
awesome-align
awesome-align-master/awesome_align/train_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Modifications copyright (C) 2020 Zi-Yi Dou # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at...
9,383
41.654545
130
py
awesome-align
awesome-align-master/awesome_align/sparsemax.py
""" An implementation of entmax (Peters et al., 2019). See https://arxiv.org/pdf/1905.05702 for detailed description. This builds on previous work with sparsemax (Martins & Astudillo, 2016). See https://arxiv.org/pdf/1602.02068. """ # Author: Ben Peters # Author: Vlad Niculae <vlad@vene.ro> # License: MIT import torc...
9,917
33.922535
78
py
awesome-align
awesome-align-master/awesome_align/file_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ import fnmatch import json import logging import os import shutil import sys import tarfile import tempfile from contextlib import context...
17,924
34.921844
144
py
awesome-align
awesome-align-master/awesome_align/activations.py
import math import torch import torch.nn.functional as F def swish(x): return x * torch.sigmoid(x) def _gelu_python(x): """ Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightl...
1,415
26.230769
111
py
awesome-align
awesome-align-master/awesome_align/run_train.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # Modifications copyright (C) 2020, Zi-Yi Dou # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compl...
42,790
47.188063
313
py
awesome-align
awesome-align-master/awesome_align/run_align.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # Modifications copyright (C) 2020 Zi-Yi Dou # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
12,446
40.768456
297
py
awesome-align
awesome-align-master/awesome_align/tokenization_utils.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
93,064
47.270228
372
py
head2head
head2head-master/test.py
import time import os import numpy as np import torch from torch.autograd import Variable from collections import OrderedDict from options.test_options import TestOptions from data.data_loader import CreateDataLoader from models.models import create_model import util.util as util from util.visualizer import Visualizer ...
4,117
38.980583
135
py
head2head
head2head-master/demo.py
import time import os import numpy as np import torch import torchvision import cv2 import dlib from torch.autograd import Variable from collections import OrderedDict from PIL import Image from multiprocessing import Process, Queue from torch.multiprocessing import Process as torchProcess from torch.multiprocessing im...
14,204
44.528846
116
py
head2head
head2head-master/train.py
import time import os import numpy as np import torch from torch.autograd import Variable from collections import OrderedDict import fractions from options.train_options import TrainOptions from data.data_loader import CreateDataLoader from models.models import create_model import util.util as util from util.visualizer...
10,970
50.027907
156
py
head2head
head2head-master/options/base_options.py
import argparse import os from util import util import torch class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser() self.initialized = False def initialize(self): self.parser.add_argument('--max_n_sequences', type=int, default=None, help='Maximum number of sub...
5,556
65.154762
205
py
head2head
head2head-master/models/base_model.py
import os import torch import sys class BaseModel(torch.nn.Module): def name(self): return 'BaseModel' def initialize(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.Tensor = torch.cuda.FloatTensor if self.gpu_ids else torch.Tensor ...
3,151
34.022222
122
py
head2head
head2head-master/models/flownet.py
import numpy as np import torch import sys from .base_model import BaseModel class FlowNet(BaseModel): def name(self): return 'FlowNet' def initialize(self, opt): BaseModel.initialize(self, opt) # flownet 2 from .flownet2_pytorch import models as flownet2_models from ....
2,596
39.578125
105
py
head2head
head2head-master/models/networks.py
import torch import torch.nn as nn from torch.nn import init import functools from torch.nn.parameter import Parameter from torch.autograd import Variable import numpy as np import torch.nn.functional as F from torchvision import models def get_norm_layer(norm_type='instance'): if norm_type == 'batch': nor...
15,375
39.893617
139
py
head2head
head2head-master/models/models.py
import torch.nn as nn from .head2head_model import Head2HeadModelG def create_model(opt): modelG = Head2HeadModelG() modelG.initialize(opt) if opt.isTrain and len(opt.gpu_ids): modelG = nn.DataParallel(modelG, device_ids=opt.gpu_ids) from .head2head_model import Head2HeadModelD from...
676
32.85
66
py
head2head
head2head-master/models/head2head_model.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import os import sys import math from collections import OrderedDict from torch.autograd import Variable import util.util as util from .base_model import BaseModel from . import networks from .flownet2_pytorch.networks.resample2d_pac...
15,353
46.09816
151
py
head2head
head2head-master/models/flownet2_pytorch/main.py
#!/usr/bin/env python import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.autograd import Variable from tensorboardX import SummaryWriter import argparse, os, sys, subprocess import setproctitle, colorama import numpy as np from tqdm import tqdm from glob import glob from os.path imp...
23,190
51.114607
233
py
head2head
head2head-master/models/flownet2_pytorch/losses.py
''' Portions of this code copyright 2017, Clement Pinard ''' # freda (todo) : adversarial loss import torch import torch.nn as nn import math def EPE(input_flow, target_flow): return torch.norm(target_flow-input_flow,p=2,dim=1).mean() class L1(nn.Module): def __init__(self): super(L1, self).__init_...
2,739
30.136364
136
py
head2head
head2head-master/models/flownet2_pytorch/datasets.py
import torch import torch.utils.data as data import os, math, random from os.path import * import numpy as np from glob import glob import utils.frame_utils as frame_utils from scipy.misc import imread, imresize class StaticRandomCrop(object): def __init__(self, image_size, crop_size): self.th, self.tw ...
13,305
32.857506
145
py
head2head
head2head-master/models/flownet2_pytorch/models.py
import torch import torch.nn as nn from torch.nn import init import math import numpy as np from .networks.resample2d_package.resample2d import Resample2d from .networks.channelnorm_package.channelnorm import ChannelNorm from .networks import FlowNetC from .networks import FlowNetS from .networks import FlowNetSD fr...
18,156
38.300866
165
py
head2head
head2head-master/models/flownet2_pytorch/convert.py
#!/usr/bin/env python2.7 import caffe from caffe.proto import caffe_pb2 import sys, os import torch import torch.nn as nn import argparse, tempfile import numpy as np parser = argparse.ArgumentParser() parser.add_argument('caffe_model', help='input model in hdf5 or caffemodel format') parser.add_argument('prototxt_...
4,703
33.335766
99
py