code
stringlengths
17
6.64M
class ProgressMeter(object): def __init__(self, num_batches, meters, prefix=''): self.batch_fmtstr = self._get_batch_fmtstr(num_batches) self.meters = meters self.prefix = prefix def display(self, batch): entries = [(self.prefix + self.batch_fmtstr.format(batch))] ent...
def accuracy(output, target, topk=(1,)): 'Computes the accuracy over the k top predictions for the specified values of k' with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(ta...
class Trainer(): def __init__(self, model, mode, loss_function, optimizer, lr_scheduler, train_dataloader, val_dataloader, device, epochs, output_dir, metrics_config, multi_gpu=False): self.model = model self.mode = mode self.output_dir = output_dir self.logs_dir = os.path.join(ou...
def read_yaml(yaml_path): with open(yaml_path, 'r') as f: yaml_file = yaml.load(f, Loader=yaml.Loader) return yaml_file
def mkdir(path): if (not os.path.exists(path)): return os.makedirs(path)
def mkdirs(paths): if (isinstance(paths, list) and (not isinstance(paths, str))): for path in paths: mkdir(path) else: mkdir(paths)
def path_exists(path): if os.path.exists(path): return True else: raise ValueError('Path provided does not exist.')
def read_schema(schema_name): with open(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'schemas', (schema_name + '.json')))) as schema: return json.load(schema)
def validate_config(instance, schema_name, defaults=True): with open(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'schemas', (schema_name + '.json')))) as schema: if defaults: default_validator = extend_schema_with_default(Draft7Validator) try: def...
def extend_schema_with_default(validator_class): validate_properties = validator_class.VALIDATORS['properties'] def set_defaults(validator, properties, instance, schema): for (property_, subschema) in properties.items(): if (('default' in subschema) and (not isinstance(instance, list))): ...
class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3) self.relu1 = nn.ReLU() self.pool1 = nn.MaxPool2d(kernel_size=2) self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_si...
def tflog2pandas(path: str) -> pd.DataFrame: 'convert single tensorflow log file to pandas DataFrame\n Parameters\n ----------\n path : str\n path to tensorflow log file\n Returns\n -------\n pd.DataFrame\n converted dataframe\n ' DEFAULT_SIZE_GUIDANCE = {'compressedHistogra...
def sorting_function(x1, x2): x1_s = x1.split('_') x2_s = x2.split('_') if (int(x1_s[1]) < int(x2_s[1])): return (- 1) elif (int(x1_s[1]) > int(x2_s[1])): return 1 elif (x1_s[0] <= x2_s[0]): return (- 1) else: return 1
def get_layer_alignment(dir_logs, net='resnet'): layers_paths = [folder for folder in os.listdir(dir_logs)] event_paths = [] layers_alignment = {} for l_p in layers_paths: if ('layer_alignment' in l_p): log_path = glob.glob(os.path.join(dir_logs, l_p, 'event*')) if (len...
def get_layer_weights(dir_logs, net='resnet', normalization=None): layers_paths = [folder for folder in os.listdir(dir_logs)] event_paths = [] layers_alignment = {} for l_p in layers_paths: if ('weight_difference' in l_p): log_path = glob.glob(os.path.join(dir_logs, l_p, 'event*'))...
def mkdir(path): if (not os.path.exists(path)): return os.makedirs(path)
def plot_multiple_lists(ydata, xdata, x_axis_name, y_axis_name, title, save_dir, figname, cmap='winter'): n = len(ydata) cmap_ = plt.cm.get_cmap(cmap) colors = iter(cmap_(np.linspace(0, 1, n))) colors_cmap = cmap_(np.arange(cmap_.N)) Z = [[0, 0], [0, 0]] levels = range(0, n, 1) CS3 = plt.c...
class FGSM(Attack): "\n FGSM in the paper 'Explaining and harnessing adversarial examples'\n [https://arxiv.org/abs/1412.6572]\n Distance Measure : Linf\n Arguments:\n model (nn.Module): model to attack.\n eps (float): maximum perturbation. (Default: 0.007)\n Shape:\n - images:...
class PGD(Attack): "\n PGD in the paper 'Towards Deep Learning Models Resistant to Adversarial Attacks'\n [https://arxiv.org/abs/1706.06083]\n Distance Measure : Linf\n Arguments:\n model (nn.Module): model to attack.\n eps (float): maximum perturbation. (Default: 0.3)\n alpha (fl...
class TPGD(Attack): "\n PGD based on KL-Divergence loss in the paper 'Theoretically Principled Trade-off between Robustness and Accuracy'\n [https://arxiv.org/abs/1901.08573]\n Distance Measure : Linf\n Arguments:\n model (nn.Module): model to attack.\n eps (float): strength of the attac...
@pytest.fixture(scope='session') def config_bp_path(): return os.path.abspath(os.path.join('tests', 'fixtures', 'config_files', 'config_bp.yaml'))
@pytest.fixture(scope='session') def config_usf_reproducible_path(): return os.path.abspath(os.path.join('tests', 'fixtures', 'config_files', 'config_usf_reproducible.yaml'))
def test_benchmark(config_bp_path): benchmark = Benchmark(config_bp_path) benchmark.run() current_files = os.listdir('tests/tmp/mnist/le_net/backpropagation_test/') expected_files = ['best_acc.txt', 'config.yaml', 'latest_model.pth', 'results.csv', 'results.json', 'model_best_acc.pth', 'logs'] for...
def test_benchmark_command_line_reproducibility_cpu(config_usf_reproducible_path): cmd = ['python', 'benchmark.py', '--config', config_usf_reproducible_path] subprocess.run(cmd) results_1 = pd.read_json('tests/tmp/mnist/le_net/usf_test/results.json') cmd = ['python', 'benchmark.py', '--config', config...
@pytest.fixture(scope='session') def mode_types(): return ['backpropagation', 'fa', 'dfa', 'usf', 'brsf', 'frsf']
class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 20, 3) self.relu = nn.ReLU() self.fc = nn.Linear(20, 10) def forward(self, x): out = self.relu(self.conv1(x)) out = F.avg_pool2d(out, out.size()[3]) ret...
@pytest.fixture(scope='function') def dummy_net(): return Model()
@pytest.fixture(scope='function') def dummy_net_constructor(): return Model
@pytest.fixture(scope='session') def datasets_available(): return ['mnist', 'cifar10', 'cifar10_benchmark', 'cifar100', 'fashion_mnist', 'imagenet']
def test_datasets_implemented(datasets_available): for dataset_name in datasets_available: assert DatasetSelector(dataset_name).get_dataset()
@pytest.fixture(scope='session') def model_architectures(): return [('le_net_mnist', (1, 1, 32, 32)), ('le_net_cifar', (1, 3, 32, 32)), ('resnet18', (1, 3, 128, 128)), ('resnet20', (1, 3, 128, 128)), ('resnet56', (1, 3, 128, 128))]
def check_model(model, input_size): model_ = model() if (('mode' in model_.__dict__) and (model_.mode == 'dfa')): _ = model_.forward(torch.rand(input_size), targets=torch.LongTensor([1]), loss_function=torch.nn.CrossEntropyLoss()) else: _ = model_(torch.rand(input_size))
def test_backpropagation_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.backpropagation.__dict__[arch], input_size)
def test_fa_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.fa.__dict__[arch], input_size)
def test_dfa_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.dfa.__dict__[arch], input_size)
def test_usf_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.usf.__dict__[arch], input_size)
def test_brsf_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.brsf.__dict__[arch], input_size)
def test_frsf_models(model_architectures): for (arch, input_size) in model_architectures: check_model(models.frsf.__dict__[arch], input_size)
def test_biomodule_convert(dummy_net_constructor, mode_types): for mode in mode_types: dummy_net = dummy_net_constructor() if (mode == 'dfa'): with pytest.raises(ValueError, match='Model `output_dim` is required for Direct Feedback Alignment \\(dfa\\) mode'): BioModule(...
def test_module_converter_convert_dummy_net(dummy_net_constructor, mode_types): for mode in mode_types: dummy_net = dummy_net_constructor() layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1} w1 = dummy_net.conv1.weight.data w2 = dummy_net.fc.weight.data...
def test_module_converter_convert_dummy_net_copy_weights(dummy_net_constructor, mode_types): for mode in mode_types: dummy_net = dummy_net_constructor() layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1} w1 = dummy_net.conv1.weight.data w2 = dummy_net.f...
def test_module_converter_convert_dummy_net_layer_config(dummy_net_constructor, mode_types): for mode in mode_types: dummy_net = dummy_net_constructor() layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1} w1 = dummy_net.conv1.weight.data w2 = dummy_net.f...
def main(): mode = argv[1] e = Evaluator() if (mode == 'wikt'): e.read_all_wiktionary() e.compare_with_triangles_stdin() elif (mode == 'feat'): e.write_labels(argv[2]) e.featurize_and_uniq_triangles_stdin()
def scan_stdin(args): stats = {'punct': 0, 'punct ok': 0, 'sum': 0, 'invalid': 0} for l in stdin: stats['sum'] += 1 try: (wc1, w1, wc2, w2) = l.decode('utf8').strip().split('\t')[0:4] if args['punct']: if (abs((len(punct_re.findall(w1)) - len(punct_re.fi...
def read_unigrams(fn): with open(fn) as f: for l in f: (wc, c, cnt) = l.decode('utf8').split('\t') unigrams[wc][c] = int(cnt) sum_[wc] += int(cnt)
def main(): args = docopt(__doc__, version='Wikt2Dict - Find anomalies 1.0') if args['unigram']: read_unigrams(args['<unigram_file>']) scan_stdin(args)
def read_pairs(wc_filter=None, input_files=None, use_stdin=False): tri = defaultdict(set) if use_stdin: for l in stdin: add_pair(l, tri, wc_filter) elif input_files: for fn in input_files: with open(fn) as f: for l in f: add_pair(...
def add_pair(l, tri, wc_filter): try: (wc1, w1, wc2, w2) = l.decode('utf8').strip().split('\t')[0:4] if (wc_filter and ((not (wc1 in wc_filter)) or (not (wc2 in wc_filter)))): return tri[(wc1, w1)].add((wc2, w2)) tri[(wc2, w2)].add((wc1, w1)) except ValueError: ...
def find_k_long_polygons(pairs, k): if (k == 1): for word in pairs.keys(): (yield [word]) else: for polygon in find_k_long_polygons(pairs, (k - 1)): for word in pairs[polygon[(- 1)]]: if (not (word in polygon[1:])): (yield (polygon + ...
def find_and_print_polygons(pairs, found=None, k=4, mode='polygons'): for polygon in find_k_long_polygons(pairs, (k + 1)): if (polygon[0] == polygon[(- 1)]): output(pairs, found=polygon, mode=mode)
def find_k_clicks(pairs, k): if (k == 1): for word in pairs.keys(): (yield [word]) else: for click in find_k_clicks(pairs, (k - 1)): if (len(click) > (k - 1)): continue for word in pairs[click[(- 1)]]: if (word in click): ...
def find_and_print_clicks(pairs, k=4): for click in find_k_clicks(pairs, k): output(pairs, found=sorted(click), mode='clicks')
def output(pairs, found, mode): (edge_density, new_pairs) = edge_density_and_new_pairs(pairs, found) if ((mode == 'clicks') and (edge_density == 1.0)): if arguments['--illustrate']: print(' --> '.join((', '.join([i, j]) for (i, j) in found)).encode('utf8')) else: print(...
def edge_density_and_new_pairs(pairs, cycle): new_pairs = list() all_pairs = list() for (i, e1) in enumerate(cycle): for e2 in cycle[(i + 1):(- 1)]: all_pairs.append(sorted([e1, e2])) if ((not (e2 in pairs[e1])) and (not (e1 in pairs[e2]))): new_pairs.append...
def main(): if arguments['--wc-filter']: with open(arguments['--wc-filter']) as f: wc_filter = set([wc.strip() for wc in f]) else: wc_filter = None k = int(arguments['--k']) if arguments['<input>']: pairs = read_pairs(wc_filter, input_files=arguments['<input>']) ...
def read_table(fn): mapping = defaultdict(set) with open(fn) as f: for l in f: fd = l.decode('utf8').strip().split('\t') id_ = int(fd[0]) for (i, lang) in enumerate(['en', 'hu', 'la', 'pl']): if (fd[(i + 1)] == '#'): continue ...
def read_words(fn): words = set() with open(fn) as f: for l in f: fd = l.decode('utf8').strip().split('\t') if (len(fd) >= 2): words.add((fd[0], fd[1])) if (len(fd) >= 4): words.add((fd[2], fd[3])) return words
def find_translations(words): iter_no = 0 for l in stdin: iter_no += 1 if ((iter_no % 1000000) == 0): stderr.write('{}\n'.format(iter_no)) try: fd = l.decode('utf8').strip().split('\t') pair1 = (fd[0], fd[1]) pair2 = (fd[2], fd[3]) ...
def add_orig_bindings(mapping, translations): for ((wc, word), ids) in mapping.iteritems(): for id_ in ids: translations[id_][wc].add(word)
def find_translations_to_table(mapping): iter_no = 0 translations = defaultdict((lambda : defaultdict(set))) add_orig_bindings(mapping, translations) for l in stdin: iter_no += 1 if ((iter_no % 1000000) == 0): stderr.write('{}\n'.format(iter_no)) try: fd...
def main(): mode = (argv[2] if (len(argv) > 2) else 'direct') if (mode == 'direct'): words = read_words(argv[1]) find_translations(words) elif (mode == 'collect'): table = read_table(argv[1]) find_translations_to_table(table)
def main(): if ((len(argv) > 2) and (not (argv[2] == 'all'))): filter_wc = set([wc.strip() for wc in argv[2:]]) else: filter_wc = None cfg_fn = argv[1] logger = logging.getLogger('wikt2dict') cfg = ConfigHandler('general', cfg_fn) logger = LogHandler(cfg) with open(cfg['wik...
def main(): unigrams = defaultdict((lambda : defaultdict(int))) for l in stdin: try: (wc1, w1, wc2, w2) = l.decode('utf8').strip().split('\t')[0:4] for c in w1: unigrams[wc1][c] += 1 for c in w2: unigrams[wc2][c] += 1 except V...
class SectionAndArticleParser(ArticleParser): '\n Class for parsing Wiktionaries that have translation tables\n in foreign articles too and section-level parsing is required.\n e.g. dewiktionary has a translation section in the article\n about the English word dog. Therefore, we need to recognize\n ...
class LangnamesArticleParser(ArticleParser): '\n Class for parsing Wiktionaries that use simple lists for translations\n instead of templates ' def __init__(self, wikt_cfg, parser_cfg, filter_langs=None): ArticleParser.__init__(self, wikt_cfg, parser_cfg, filter_langs) self.read_langnam...
class DefaultArticleParser(ArticleParser): def extract_translations(self, title, text): translations = list() for tr in self.cfg.trad_re.finditer(text): wc = tr.group(self.cfg.wc_field) if ((not wc) or (not wc.strip()) or (not (wc in self.wikt_cfg.wikicodes))): ...
def err(msg): ' Prints a message to stderr, terminating it with a newline ' sys.stderr.write((msg + '\n'))
class Article(): ' Stores the contents of a Wikipedia article ' def __init__(self, title, markup, is_redirect): self.title = title self.markup = markup self.is_redirect = is_redirect
class WikiParser(): 'Parses the Wikipedia XML and extracts the relevant data,\n such as sentences and vocabulary' def __init__(self, callback, ignore_redirects=True): self.callback = callback self.ignore_redirects = ignore_redirects self.buffer_size = ((10 * 1024) * 1024) ...
class Triangulator(object): def __init__(self, triangle_wc): self.wikicodes = set(triangle_wc) self.cfg = config.WiktionaryConfig() self.pairs = defaultdict((lambda : defaultdict((lambda : defaultdict((lambda : defaultdict(list))))))) self.triangles = defaultdict(list) sel...
class Wiktionary(object): def __init__(self, cfg): self.cfg = cfg self.init_parsers() self.pairs = list() def init_parsers(self): self.parsers = list() for (parser_cl, parser_cfg) in self.cfg.parsers: self.parsers.append(parser_cl(self.cfg, parser_cfg)) ...
def load_clip_cpu(backbone_name): model_path = 'path_to_CLIP_ViT-B-16_pre-trained_parameters' try: model = torch.jit.load(model_path, map_location='cpu').eval() state_dict = None except RuntimeError: state_dict = torch.load(model_path, map_location='cpu') model = clip.build_mod...
def transform_center(): interp_mode = Image.BICUBIC tfm_test = [] tfm_test += [Resize(224, interpolation=interp_mode)] tfm_test += [CenterCrop((224, 224))] tfm_test += [ToTensor()] normalize = Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) tfm...
def get_videos(vidname, read_path): allframes = [] videoins = (read_path + vidname) vvv = cv2.VideoCapture(videoins) if (not vvv.isOpened()): print('Video is not opened! {}'.format(videoins)) else: fps = vvv.get(cv2.CAP_PROP_FPS) totalFrameNumber = vvv.get(cv2.CAP_PROP_FRAM...
@lru_cache() def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
@lru_cache() def bytes_to_unicode(): "\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B toke...
def get_pairs(word): 'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n ' pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def whitespace_clean(text): text = re.sub('\\s+', ' ', text) text = text.strip() return text
class SimpleTokenizer(object): def __init__(self, bpe_path: str=default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') merges = merges[1:(((49152 - 25...
def setup_path(args): prefix = args.prefix postfix = args.postfix openset = args.openset temporal = args.temporal tfmlayers = args.tfm_layers batchsize = args.batchsize numFrames = args.numFrames iters = args.num_iterations verbose = (args.verbose if args.verbose else 'none') d...
def setup_dataloader(args): if (args.dataset == 'HMDB51-feature-30fps-center'): feature_root = '../feat/HMDB' else: raise ValueError('Unknown dataset.') if args.dataset.startswith('HMDB'): (trainactions, valactions) = ([], []) trn_dataset = readFeatureHMDB51(root=feature_ro...
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) device = ('cuda' if torch.cuda.is_available() else 'cpu') [logPath, modelPath] = cg.setup_path(args) args.model_path = modelPath logger = SummaryWriter(logdir=logPath) args.return_intermediate_text_feature = 0 [trn_...
def convert_to_token(xh): xh_id = clip.tokenize(xh).cpu().data.numpy() return xh_id
def text_prompt(dataset='HMDB51', clipbackbone='ViT-B/16', device='cpu'): (actionlist, actionprompt, actiontoken) = ([], {}, []) numC = {'HMDB51-feature-30fps-center': 51} (clipmodel, _) = clip.load(clipbackbone, device=device, jit=False) for paramclip in clipmodel.parameters(): paramclip.requ...
def set_learning_rate(optimizer, lr): for g in optimizer.param_groups: g['lr'] = lr
def readtxt(metapath, datapath): (vidDir, vidLabel) = ([], []) f = open(metapath, 'rb') path = f.readlines() f.close() for p in path: psplit = p.decode('utf-8').strip('\n').split(',') vidDir += [os.path.join(datapath, psplit[0])] vidLabel += [[int(psplit[1]), psplit[2], int...
def save_checkpoint(state, is_best=0, gap=1, filename='checkpoint.pth.tar', keep_all=False): torch.save(state, filename) last_epoch_path = os.path.join(os.path.dirname(filename), ('checkpoint_iter%s.pth.tar' % str((state['iteration'] - gap)))) if (not keep_all): try: os.remove(last_epo...
class _RepeatSampler(object): ' Sampler that repeats forever.\n Args:\n sampler (Sampler)\n ' def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: (yield from iter(self.sampler))
class FastDataLoader(torch.utils.data.dataloader.DataLoader): 'for reusing cpu workers, to save time' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__()...
def save(file: Path, **kwargs) -> None: 'Save a list of arrays as a npz file.' print(f"-> Saving to '{file}'...") np.savez_compressed(file, **kwargs)
def export_ddad(mode, save_stem: ty.N[str]=None, overwrite: bool=False) -> None: 'Export the ground truth LiDAR depth images for SYNS.\n\n :param save_stem: (Optional[str]) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing exported files.\n ' print(f'...
def save(file: Path, **kwargs) -> None: 'Save a list of arrays as a npz file.' print(f"-> Saving to '{file}'...") np.savez_compressed(file, **kwargs)
def export_diode(mode: str, scene: str, save_stem: ty.N[str]=None, overwrite: bool=False) -> None: "Export the ground truth LiDAR depth images for SYNS.\n\n :param mode: (str) Split mode to use. {'val'}\n :param scene: (str) Scene type to use. {'outdoor', 'indoor'}\n :param save_stem: (Optional[str]) Exp...
def save(file: Path, **kwargs) -> None: 'Save a list of arrays as a npz file.' print(f''' -> Saving to "{file}"...''') np.savez_compressed(file, **kwargs)
def export_kitti(depth_split: str, mode: str, use_velo_depth: bool=False, save_stem: Optional[str]=None, overwrite: bool=False) -> None: "Export the ground truth LiDAR depth images for a given Kitti test split.\n\n :param depth_split: (str) Kitti depth split to load.\n :param mode: (str) Split mode to use. ...
def save(file: Path, **kwargs) -> None: 'Save a list of arrays as a npz file.' print(f'-> Saving to "{file}"...') np.savez_compressed(file, **kwargs)
def export_mannequin(mode: str, save_stem: ty.N[str]=None, overwrite: bool=False) -> None: 'Export the ground truth LiDAR depth images for SYNS.\n\n :param mode: (str) Split mode to use.\n :param save_stem: (Optional[str]) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, o...
def save(file: Path, **kwargs) -> None: 'Save a list of arrays as a npz file.' print(f''' -> Saving to "{file}"...''') np.savez_compressed(file, **kwargs)
def export_nyud(mode: str, save_stem: str, overwrite: bool=False) -> None: "Export the ground truth LiDAR depth images for NYUD.\n\n :param mode: (str) Split mode to use. {'test'}\n :param save_stem: (str) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing...