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
genesis
genesis-master/datasets/sketchy_config.py
# =========================== A2I Copyright Header =========================== # # Copyright (c) 2003-2021 University of Oxford. All rights reserved. # Authors: Applied AI Lab, Oxford Robotics Institute, University of Oxford # https://ori.ox.ac.uk/labs/a2i/ # # This file is the property of the University of Ox...
3,099
32.333333
80
py
genesis
genesis-master/datasets/multid_config.py
# =========================== A2I Copyright Header =========================== # # Copyright (c) 2003-2021 University of Oxford. All rights reserved. # Authors: Applied AI Lab, Oxford Robotics Institute, University of Oxford # https://ori.ox.ac.uk/labs/a2i/ # # This file is the property of the University of Ox...
5,294
35.517241
80
py
genesis
genesis-master/utils/plotting.py
# =========================== A2I Copyright Header =========================== # # Copyright (c) 2003-2021 University of Oxford. All rights reserved. # Authors: Applied AI Lab, Oxford Robotics Institute, University of Oxford # https://ori.ox.ac.uk/labs/a2i/ # # This file is the property of the University of Ox...
1,419
36.368421
78
py
genesis
genesis-master/utils/misc.py
# =========================== A2I Copyright Header =========================== # # Copyright (c) 2003-2021 University of Oxford. All rights reserved. # Authors: Applied AI Lab, Oxford Robotics Institute, University of Oxford # https://ori.ox.ac.uk/labs/a2i/ # # This file is the property of the University of Ox...
9,348
33.498155
79
py
genesis
genesis-master/utils/geco.py
# =========================== A2I Copyright Header =========================== # # Copyright (c) 2003-2021 University of Oxford. All rights reserved. # Authors: Applied AI Lab, Oxford Robotics Institute, University of Oxford # https://ori.ox.ac.uk/labs/a2i/ # # This file is the property of the University of Ox...
1,968
36.865385
80
py
GPim
GPim-master/setup.py
__author__ = "Maxim Ziatdinov" __copyright__ = "Copyright Maxim Ziatdinov (2020)" __version__ = "0.3.9" __maintainer__ = "Maxim Ziatdinov" __email__ = "maxim.ziatdinov@ai4microcopy.com" __date__ = "11/25/2020" from setuptools import setup, find_packages import os module_dir = os.path.dirname(os.path.abspath(__file__)...
1,390
33.775
76
py
GPim
GPim-master/gpim/gprutils.py
""" gprutils.py =========== Utility functions for the analysis of sparse image and hyperspectral data with Gaussian processes. Author: Maxim Ziatdinov (email: maxim.ziatdinov@ai4microcopy.com) """ import copy import os import matplotlib.cm as cm import matplotlib.pyplot as plt import numpy as np import pyro import ...
34,554
35.799787
116
py
GPim
GPim-master/gpim/gpreg/skgpr.py
''' skgpr.py ====== Gaussian process regression model with a structured kernel interpolation or a spectral mixture kernel. Serves as a high-level wrapper for GPyTorch's (https://gpytorch.ai) Gaussian process modules with structred kernel interpolation and spectral mixture kernel methods. Author: Maxim Ziatdinov (email...
19,370
42.142539
97
py
GPim
GPim-master/gpim/gpreg/gpr.py
''' gpr.py ====== Gaussian process regression: model training, prediction and uncertainty exploration This module serves as a high-level wrapper for sparse Gaussian processes module from Pyro probabilistic programming library (https://pyro.ai/) for easy work with scientific image (2D) and hyperspectral (3D) data. Autho...
14,144
41.863636
103
py
GPim
GPim-master/gpim/gpreg/vgpr.py
''' vgpr.py ====== Gaussian process regression model for vector-valued functions. Serves as a high-level wrapper for GPyTorch's (https://gpytorch.ai) Gaussian processes with correlated and independent output dimensions. Author: Maxim Ziatdinov (email: maxim.ziatdinov@ai4microcopy.com) ''' import time import numpy as n...
14,802
40.698592
97
py
GPim
GPim-master/gpim/gpbayes/boptim.py
""" boptim.py =========== Utility functions for the Gaussian process-based Bayesian optimization for selecting the next query points in images and image-like data. Author: Maxim Ziatdinov (email: maxim.ziatdinov@ai4microcopy.com) """ import types import copy import torch import numpy as np from scipy import spatial ...
22,004
44.277778
103
py
GPim
GPim-master/gpim/kernels/pyro_kernels.py
''' pyro_kernels.py ====== Pyro kernels (some customized kernels TBA) ''' import pyro.contrib.gp as gp import pyro.distributions as dist import torch import warnings def get_kernel(kernel_type, input_dim, lengthscale, use_gpu=False, **kwargs): """ Initalizes one of the following kernels: RBF, Rational Qu...
2,930
29.216495
77
py
GPim
GPim-master/gpim/kernels/gpytorch_kernels.py
''' gpytorch_kernels.py ====== Gpytorch kernels (some customized kernels TBA) ''' import gpytorch import torch def get_kernel(kernel_type, input_dim, on_gpu=True, **kwargs): """ Initializes one of the following gpytorch kernels: RBF, Matern Args: kernel_type (str): Kernel type ('RBF'...
2,659
31.839506
79
py
GPim
GPim-master/docs/source/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
5,119
29.47619
79
py
SAT
SAT-master/test.py
import argparse import numpy as np import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.transforms import transforms from torch.utils.data import DataLoader import torchvision.utils as vutils from networks.wideresnet import WideResNet from ...
4,582
36.876033
158
py
SAT
SAT-master/test_roa.py
import argparse import numpy as np import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.transforms import transforms from torch.utils.data import DataLoader import torchvision.utils as vutils from networks.wideresnet import WideResNet from ...
3,568
36.568421
158
py
SAT
SAT-master/attack.py
import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.transforms import transforms from torch.utils.data import DataLoader from torch.autograd import Variable from torch.autograd.gradcheck import zero_gradients import copy import numpy as np ...
1,371
25.384615
94
py
SAT
SAT-master/test_common_corruptions.py
import argparse import numpy as np import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.transforms import transforms from torch.utils.data import DataLoader from networks.resnet_skip_att import * parser = argparse.ArgumentParser(description...
2,317
35.793651
139
py
SAT
SAT-master/networks/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...
4,503
35.032
78
py
SAT
SAT-master/ROA/ROA.py
# Coutsy of https://github.com/tongwu2020/phattacks # This file basically runs Rectangular Occlusion Attacks (ROA) see paper import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import os class ROA(object): ''' Make sticker ''' def __init...
8,083
40.035533
139
py
saliency
saliency-master/saliency/tf1/grad_cam_test.py
# Copyright 2021 Google Inc. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
4,483
37.324786
89
py
DCAN
DCAN-master/main.py
from options import args_parser import random import numpy as np import torch import csv import sys from dataloader import load_lookups, prepare_instance, MyDataset, my_collate from utils import early_stop, save_everything from models import pick_model import torch.optim as optim from collections import defaultdict fr...
5,163
39.031008
149
py
DCAN
DCAN-master/dataloader.py
import csv import torch import numpy as np from collections import defaultdict from transformers import AutoTokenizer from torch.utils.data import Dataset from elmo import elmo def load_vocab_dict(args, vocab_file): """ Load vocabulary dictionary from file: vocab_file """ vocab = set() with open(v...
6,914
34.829016
109
py
DCAN
DCAN-master/utils.py
import gensim.models import numpy as np from tqdm import tqdm import csv from scipy.sparse import csr_matrix import gensim.models.word2vec as w2v import gensim.models.fasttext as fasttext import codecs import re def reformat(code, is_diag): """ Put a period in the right place because the MIMIC-3 data file...
14,357
35.910026
158
py
DCAN
DCAN-master/models.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ from torch.nn.utils import weight_norm from math import floor import numpy as np import os from dataloader import build_pretrain_embedding, load_embeddings class WordRep(nn.Module): def __init__(self, args...
13,242
37.164265
134
py
DCAN
DCAN-master/train_test.py
import torch import numpy as np from utils import all_metrics, print_metrics import json import pickle def train(args, model, optimizer, epoch, gpu, data_loader): print("EPOCH %d" % epoch) device = torch.device('cuda:{}'.format(args.gpu)) if args.gpu != -1 else torch.device('cpu') losses = [] model.tr...
2,281
35.806452
141
py
diofant
diofant-master/docs/conf.py
""" Diofant documentation build configuration file. This file is execfile()d with the current directory set to its containing dir. The contents of this file are pickled, so don't put values in the namespace that aren't pickleable (module imports are okay, they're removed automatically). """ import inspect import os ...
6,973
31.741784
89
py
diofant
diofant-master/diofant/printing/latex.py
"""A Printer which converts an expression into its LaTeX equivalent.""" import itertools import re import mpmath.libmp as mlib from mpmath.libmp import prec_to_dps from ..core import Add, Integer, Mod, oo from ..core.alphabets import greeks from ..core.function import _coeff_isneg from ..core.operations import Assoc...
63,123
34.562817
155
py
private-transformers
private-transformers-main/setup.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
1,958
32.20339
89
py
private-transformers
private-transformers-main/private_transformers/privacy_engine.py
# Copyright (c) Xuechen Li. All Rights Reserved. # Copyright (c) Meta Platforms, Inc. and affiliates. # # 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/LI...
24,722
41.045918
121
py
private-transformers
private-transformers-main/private_transformers/transformers_support.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
32,588
43.76511
120
py
private-transformers
private-transformers-main/private_transformers/supported_layers_grad_samplers.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
15,231
43.932153
143
py
private-transformers
private-transformers-main/private_transformers/lora_utils.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
3,727
31.701754
116
py
private-transformers
private-transformers-main/private_transformers/autograd_grad_sample.py
# Copyright (c) Xuechen Li. All Rights Reserved. # Copyright (c) Meta Platforms, Inc. and affiliates. # # 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/LI...
7,602
36.638614
120
py
private-transformers
private-transformers-main/examples/classification/run_classification.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
35,067
39.077714
120
py
private-transformers
private-transformers-main/examples/classification/src/dataset.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
33,819
43.093872
120
py
private-transformers
private-transformers-main/examples/classification/src/common.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
814
39.75
93
py
private-transformers
private-transformers-main/examples/classification/src/models.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
15,400
37.989873
115
py
private-transformers
private-transformers-main/examples/classification/src/trainer.py
# coding=utf-8 # Copyright (c) Xuechen Li. All Rights Reserved. # Copyright 2020-present 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.o...
28,437
40.334302
120
py
private-transformers
private-transformers-main/examples/classification/spectral_analysis/rebuttal_plots_neurips_2022.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
5,233
31.918239
234
py
private-transformers
private-transformers-main/examples/classification/spectral_analysis/geometric_median.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
10,185
33.528814
120
py
private-transformers
private-transformers-main/examples/classification/spectral_analysis/rebuttal_neurips_2022.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
4,950
34.618705
110
py
private-transformers
private-transformers-main/examples/image_classification/main.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
4,296
34.512397
108
py
private-transformers
private-transformers-main/examples/table2text/run_language_modeling.py
# coding=utf-8 # Copyright (c) Xuechen Li. All Rights Reserved. # 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 co...
12,516
38.863057
114
py
private-transformers
private-transformers-main/examples/table2text/models.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
5,644
37.931034
119
py
private-transformers
private-transformers-main/examples/table2text/trainer.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
50,541
46.103448
119
py
private-transformers
private-transformers-main/examples/table2text/data_utils/language_modeling.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
15,291
36.116505
113
py
private-transformers
private-transformers-main/examples/table2text/data_utils/data_collator.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
10,548
43.889362
165
py
private-transformers
private-transformers-main/tests/test_privacy_engine.py
# Copyright (c) Xuechen Li. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
24,432
41.053356
120
py
HAPPIER
HAPPIER-main/happier/evaluate.py
import os import logging import argparse import torch import numpy as np from omegaconf import open_dict import happier.lib as lib import happier.engine as eng from happier.getter import Getter def print_metrics(metrics): for split, mtrc in metrics.items(): for k, v in mtrc.items(): if k == ...
6,029
34.680473
157
py
HAPPIER
HAPPIER-main/happier/getter.py
import torch from torch import optim import torchvision.transforms as T import happier.lib as lib from happier import losses from happier import datasets from happier import models from happier import engine from happier.models import schedulers class Getter: """ This class allows to create differents object...
6,762
41.534591
115
py
HAPPIER
HAPPIER-main/happier/run.py
import os from os.path import join import random import numpy as np from omegaconf import OmegaConf import hydra import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter import happier.lib as lib import happier.engine as eng from happier.getter import Getter def if_func(cond, x, y): ...
5,964
33.479769
113
py
HAPPIER
HAPPIER-main/happier/models/get_backbone.py
import torch.nn as nn import torchvision.models as models import happier.lib as lib def get_backbone(name, pretrained=True, **kwargs): if name == 'resnet34': lib.LOGGER.info("using ResNet-34") out_dim = 512 backbone = models.resnet34(pretrained=pretrained) backbone = nn.Sequential...
732
32.318182
65
py
HAPPIER
HAPPIER-main/happier/models/retrieval_net.py
import torch import torch.nn as nn import torch.nn.functional as F import happier.lib as lib from happier.models.get_pooling import get_pooling from happier.models.get_backbone import get_backbone def flatten(tens): if tens.ndim == 2: return tens.squeeze(1) if tens.ndim == 3: return tens.squ...
2,469
29.493827
115
py
HAPPIER
HAPPIER-main/happier/models/get_pooling.py
import torch.nn as nn def get_pooling(pool, cfg): name = cfg if isinstance(cfg, str) else cfg.name kwargs = {} if isinstance(cfg, str) else cfg.kwargs if name == 'default': return pool elif name == 'none': return nn.Identity() elif name == 'max': return nn.AdaptiveMaxPool2...
475
25.444444
55
py
HAPPIER
HAPPIER-main/happier/models/schedulers/cosine_annealing_lr.py
from torch.optim import lr_scheduler class CosineAnnealingLR(lr_scheduler.CosineAnnealingLR): def __repr__(self): repr = f"{self.__class__.__name__}(\n" repr = repr + f" T_max={self.T_max},\n" repr = repr + f" eta_min={self.eta_min},\n" repr = repr + ')' return repr
320
25.75
56
py
HAPPIER
HAPPIER-main/happier/datasets/base_dataset.py
import os from os.path import join, isfile import torch from torch.utils.data import Dataset from PIL import Image from tqdm import tqdm import happier.lib as lib import happier.engine as eng class BaseDataset(Dataset): RELEVANCE_BS = 256 CACHE_FILE = "HAPPIER_relevances_{mode}_{relevance_type}_{alpha}.trc...
4,398
31.109489
137
py
HAPPIER
HAPPIER-main/happier/datasets/samplers/m_per_class_sampler.py
""" adapted from : https://github.com/Andrew-Brown1/Smooth_AP/blob/master/src/datasets.py """ import copy import numpy as np from pytorch_metric_learning import samplers import happier.lib as lib def flatten(list_): return [item for sublist in list_ for item in sublist] class MPerClassSampler: def __init_...
3,721
26.776119
132
py
HAPPIER
HAPPIER-main/happier/datasets/samplers/hierarchical_sampler.py
from pytorch_metric_learning.samplers import HierarchicalSampler as PMLHierarchicalSampler import happier.lib as lib class HierarchicalSampler(PMLHierarchicalSampler): def __init__( self, dataset, batch_size, samples_per_class, batches_per_super_tuple=4, super_cla...
1,582
31.979167
90
py
HAPPIER
HAPPIER-main/happier/engine/checkpoint.py
import sys from os.path import join import torch import happier.lib as lib def checkpoint( log_dir, save_checkpoint, net, optimizer, scheduler, criterion, scaler, epoch, config, metrics, ): state_dict = {} if torch.cuda.device_count() > 1: state_dict["net_stat...
1,441
27.84
96
py
HAPPIER
HAPPIER-main/happier/engine/base_training_loop.py
import os import torch from tqdm import tqdm import happier.lib as lib def _calculate_loss_and_backward( config, net, batch, relevance_fn, criterion, optimizer, scaler, epoch, ): with torch.cuda.amp.autocast(enabled=(scaler is not None)): di = net(batch["image"].cuda()) ...
3,588
25.585185
102
py
HAPPIER
HAPPIER-main/happier/engine/accuracy_calculator.py
import os import torch from torch.utils.data import DataLoader, Dataset from tqdm import tqdm import happier.lib as lib from happier.engine.get_knn import get_knn from happier.engine.metrics import get_metrics_dict from happier.engine.compute_embeddings import compute_embeddings from happier.engine.overall_accuracy_...
8,360
36.493274
125
py
HAPPIER
HAPPIER-main/happier/engine/compute_relevance_on_the_fly.py
import torch import happier.lib as lib def relevance_for_batch( batch, alpha=1.0, check_for=None, type='decay', ): if type == 'map': relevances = get_relevances_map( batch, weights=alpha, ) elif type == 'pop': relevances = get_relevances_pop( ...
1,859
24.479452
91
py
HAPPIER
HAPPIER-main/happier/engine/get_knn.py
import os import numpy as np import torch import faiss import pytorch_metric_learning.utils.common_functions as c_f import happier.lib as lib def get_knn(references, queries, num_k, embeddings_come_from_same_source, with_faiss=False): with_faiss = lib.str_to_bool(os.getenv("WITH_FAISS", with_faiss)) num_k ...
1,836
28.629032
92
py
HAPPIER
HAPPIER-main/happier/engine/metrics.py
from functools import partial import torch # import numpy as np import happier.lib as lib def ap(sorted_rel, at_R=False, reduce=True, **kwargs): normalizing_factor = sorted_rel.sum(-1) relevance_mask = torch.ones(sorted_rel.shape, device=sorted_rel.device) if at_R: for i, R in enumerate(normali...
6,501
27.643172
108
py
HAPPIER
HAPPIER-main/happier/engine/compute_embeddings.py
import os import torch from tqdm import tqdm import happier.lib as lib def compute_embeddings( net, loader, convert_to_cuda=False, with_paths=False, ): features = [] mode = net.training net.eval() lib.LOGGER.info("Computing embeddings") for i, batch in enumerate(tqdm(loader, dis...
915
23.105263
93
py
HAPPIER
HAPPIER-main/happier/engine/train.py
from time import time import numpy as np import torch from torch.utils.data import DataLoader import happier.lib as lib from happier.engine.checkpoint import checkpoint from happier.engine.accuracy_calculator import evaluate from happier.engine.base_training_loop import base_training_loop def train( config, ...
4,537
30.734266
140
py
HAPPIER
HAPPIER-main/happier/lib/load_state.py
import torch from happier.lib.expand_path import expand_path def load_state(path, key=None): state = torch.load(expand_path(path), map_location='cpu') if key is not None: return state[key] return state def load_config(path): return load_state(path, 'config')
290
16.117647
61
py
HAPPIER
HAPPIER-main/happier/lib/freeze_batch_norm.py
import torch.nn as nn def freeze_batch_norm(model): for module in filter(lambda m: type(m) == nn.BatchNorm2d, model.modules()): module.eval() module.train = lambda _: None return model
211
22.555556
79
py
HAPPIER
HAPPIER-main/happier/lib/mask_logsumexp.py
import torch def mask_logsumexp(tens, mask): tens[~mask] = -float('inf') return torch.logsumexp(tens, dim=1)
119
16.142857
39
py
HAPPIER
HAPPIER-main/happier/lib/get_set_random_state.py
import random from functools import wraps import numpy as np import torch from .logger import LOGGER def random_seed(seed, backend=True): LOGGER.info(f"Training with seed {seed}") random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) if backend: ...
1,317
27.042553
69
py
HAPPIER
HAPPIER-main/happier/lib/create_label_matrix.py
from typing import Optional, Union import torch def create_label_matrix( labels: torch.Tensor, other_labels: Optional[torch.Tensor] = None, hierarchy_level: Optional[Union[int, str]] = None, dtype: torch.dtype = torch.float, ): if other_labels is None: other_labels = labels if (hiera...
609
29.5
89
py
HAPPIER
HAPPIER-main/happier/lib/create_relevance_matrix.py
import torch def create_relevance_matrix(label_matrix, relevance): return torch.gather(relevance, 1, label_matrix)
121
19.333333
53
py
HAPPIER
HAPPIER-main/happier/lib/get_gradient_norm.py
import torch def get_gradient_norm(net, norm_type=2): with torch.no_grad(): parameters = [p for p in net.parameters() if p.grad is not None and p.requires_grad] if len(parameters) == 0: return 0.0 else: device = parameters[0].grad.device return torch.nor...
426
34.583333
133
py
HAPPIER
HAPPIER-main/happier/lib/groupby_mean.py
import torch # from : https://discuss.pytorch.org/t/groupby-aggregate-mean-in-pytorch/45335/8 def groupby_mean(value: torch.Tensor, labels: torch.LongTensor) -> torch.Tensor: """Group-wise average for (sparse) grouped tensors Args: value (torch.Tensor): values to average (# samples, latent dimension)...
1,962
39.061224
115
py
HAPPIER
HAPPIER-main/happier/losses/cluster_loss.py
import math import torch import torch.nn as nn import torch.nn.functional as F import happier.lib as lib # adapted from : # https://github.com/azgo14/classification_metric_learning/blob/master/metric_learning/modules/losses.py class ClusterLoss(nn.Module): """ L2 normalize weights and apply temperature scal...
3,518
35.278351
120
py
HAPPIER
HAPPIER-main/happier/losses/csl_loss.py
import math import torch import torch.nn as nn import torch.nn.functional as F import happier.lib as lib class CSLLoss(nn.Module): def __init__( self, num_proxies, margins=[0.25, 0.35, 0.45], scale=32.0, embedding_size=512, reduce_type='sum', proxies_seed...
4,520
35.168
120
py
HAPPIER
HAPPIER-main/happier/losses/hap_loss.py
from functools import partial import torch import torch.nn as nn import happier.lib as lib from happier.losses.tools import reduce def heaviside(tens, val=1., target=None, general=None): return torch.heaviside(tens, values=torch.tensor(val, device=tens.device, dtype=tens.dtype)) def tau_sigmoid(tensor, tau, t...
9,961
36.878327
153
py
HAPPIER
HAPPIER-main/happier/losses/tools/avg_non_zero_reducer.py
import torch def avg_non_zero_reducer(losses): threshold_condition = losses > 0. num_past_filter = torch.sum(threshold_condition) if num_past_filter >= 1: loss = torch.mean(losses[threshold_condition]) else: loss = torch.sum(losses * 0) return loss
287
23
54
py
HAPPIER
HAPPIER-main/happier/losses/tools/__init__.py
import torch from .avg_non_zero_reducer import avg_non_zero_reducer __all__ = [ 'avg_non_zero_reducer', ] REDUCE_DICT = { 'none': torch.nn.Identity(), 'mean': torch.mean, 'sum': torch.sum, 'avg_non_zero': avg_non_zero_reducer, } def reduce(tens, reduce_type='mean'): return REDUCE_DICT[red...
336
15.047619
54
py
orconvqa-release
orconvqa-release-master/modeling.py
import os import logging import collections import torch from transformers import BertModel, BertPreTrainedModel, AlbertModel from transformers.modeling_bert import (BertEncoder, BertOutput, BertAttention, BertIntermediate, BertLayer, BertEmbeddings, ...
54,396
52.018519
139
py
orconvqa-release
orconvqa-release-master/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...
65,026
41.668635
123
py
orconvqa-release
orconvqa-release-master/train_retriever.py
#!/usr/bin/env python # coding: utf-8 # In[1]: from __future__ import absolute_import, division, print_function # import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"]="1" import argparse import logging import os import random import glob import timeit import json import fai...
37,293
43.663473
144
py
orconvqa-release
orconvqa-release-master/train_pipeline.py
#!/usr/bin/env python # coding: utf-8 # In[1]: from __future__ import absolute_import, division, print_function # import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"]="1,2" import argparse import logging import os import random import glob import timeit import json import l...
53,201
48.352505
151
py
orconvqa-release
orconvqa-release-master/retriever_utils.py
from __future__ import absolute_import, division, print_function import json import logging import math import collections import linecache import numpy as np from io import open from tqdm import tqdm from torch.utils.data import Dataset from transformers.tokenization_bert import BasicTokenizer, whitespace_tokenize ...
15,465
46.152439
130
py
pyLDLE
pyLDLE-main/ldle.py
import pdb import numpy as np import copy from scipy.spatial.distance import pdist, squareform from scipy.sparse.csgraph import laplacian, minimum_spanning_tree, breadth_first_order from scipy.sparse import coo_matrix, csr_matrix, diags from scipy.linalg import eigh, svd, qr from scipy.sparse.linalg import eigs, eigs...
60,817
39.599466
186
py
CUFAR
CUFAR-main/train_single_task.py
import os device = '0' os.environ["CUDA_VISIBLE_DEVICES"] = device import time import torch import torch.nn.functional as F from model.modules.ODE import * from src.metrics import get_MSE, get_MAE, get_MAPE from src.utils import get_dataloader, print_model_parm_nums from src.args import get_args from src.urbanpy_train_...
7,800
41.396739
131
py
CUFAR
CUFAR-main/train_finetune.py
import os device = '0' os.environ["CUDA_VISIBLE_DEVICES"] = device import time import torch import torch.nn.functional as F from src.metrics import get_MSE, get_MAE, get_MAPE from src.utils import get_dataloader, print_model_parm_nums from src.args import get_args from src.urbanpy_train_finetune import UrbanPy_finetune...
10,179
43.845815
139
py
CUFAR
CUFAR-main/train_joint.py
import os device = '0' os.environ["CUDA_VISIBLE_DEVICES"] = device import time import torch import torch.nn.functional as F from src.metrics import get_MSE, get_MAE, get_MAPE from src.utils import get_dataloader_joint, print_model_parm_nums from src.args import get_args from model.UrbanFM import UrbanFM from model.Urba...
7,078
38.547486
127
py
CUFAR
CUFAR-main/train_continual.py
import os device = '0' os.environ["CUDA_VISIBLE_DEVICES"] = device import time import torch from model.modules.AKR import continual from model.modules.memory_buffer import Buffer from src.metrics import get_MSE, get_MAE, get_MAPE from src.utils import get_dataloader, print_model_parm_nums from src.args import get_args ...
11,136
47.633188
139
py
CUFAR
CUFAR-main/src/urbanpy_train_finetune.py
import os import sys import warnings import numpy as np import random import warnings import time import torch import torch.nn as nn from src.metrics import get_MAE, get_MSE, get_MAPE from src.utils import print_model_parm_nums, get_lapprob_dataloader, get_gt_densities from model.UrbanPy import UrbanPy, weights_init_no...
10,817
45.034043
144
py
CUFAR
CUFAR-main/src/urbanpy_train_continual.py
import os import sys import warnings import numpy as np import random import warnings import time import torch import torch.nn as nn from src.metrics import get_MAE, get_MSE, get_MAPE from src.utils import print_model_parm_nums, get_lapprob_dataloader from model.UrbanPy import UrbanPy, weights_init_normal from model.mo...
11,592
48.122881
133
py
CUFAR
CUFAR-main/src/utils.py
import numpy as np import os import torch import torch.nn.functional as F from torch.utils.data import DataLoader def get_dataloader(args, datapath, dataset= "TaxiBJ", batch_size= 16, mode='train', task_id=0): cuda = True if torch.cuda.is_available() else False Tensor = torch.cuda.FloatTensor if cuda else tor...
10,058
46.672986
125
py
CUFAR
CUFAR-main/src/urbanpy_train_single_task.py
import os import warnings import numpy as np import warnings import time import torch import torch.nn as nn from src.metrics import get_MAE, get_MSE, get_MAPE from src.utils import print_model_parm_nums, get_lapprob_dataloader, get_gt_densities from model.UrbanPy import UrbanPy, weights_init_normal from model.modules.u...
9,075
45.54359
162
py
CUFAR
CUFAR-main/model/CUFAR.py
import torch import torch.nn as nn from einops import rearrange class mini_model(nn.Module): def __init__(self, n_channel, scale_factor, in_channel, kernel_size, padding, groups): super(mini_model, self).__init__() self.n_channels = n_channel self.scale_factor = scale_factor self.in...
7,109
43.716981
114
py
CUFAR
CUFAR-main/model/UrbanFM.py
import torch.nn as nn import torch.nn.functional as F import torch class N2_Normalization(nn.Module): def __init__(self, upscale_factor): super(N2_Normalization, self).__init__() self.upscale_factor = upscale_factor self.avgpool = nn.AvgPool2d(upscale_factor) self.upsample = nn.Upsa...
5,736
34.63354
110
py
CUFAR
CUFAR-main/model/UrbanODE.py
import torch.nn as nn import torch.nn.functional as F import torch from .modules.ODE import * from torchvision.models import vgg19 import math class N2_Normalization(nn.Module): def __init__(self, upscale_factor): # 4 super(N2_Normalization, self).__init__() self.upscale_factor = upscale_factor ...
16,947
37.343891
120
py
CUFAR
CUFAR-main/model/DeepLGR.py
import torch.nn as nn import torch.nn.functional as F import torch from torchvision.models import vgg19 import math class N2_Normalization(nn.Module): def __init__(self, upscale_factor): super(N2_Normalization, self).__init__() self.upscale_factor = upscale_factor self.avgpool = nn.AvgPool...
11,658
38.522034
124
py
CUFAR
CUFAR-main/model/UrbanPy.py
import torch.nn as nn import torch.nn.functional as F import torch from model.modules.urbanpy_layers import LocalConv import math def n2_normalization_func(x, scale_factor): out = F.avg_pool2d(x, scale_factor) * scale_factor ** 2 out = F.upsample(out, scale_factor=scale_factor) return torch.div(x, out + 1e...
8,888
38.331858
151
py
CUFAR
CUFAR-main/model/FODE.py
import torch.nn as nn import torch.nn.functional as F import torch from .modules.ODE import * class N2_Normalization(nn.Module): def __init__(self, upscale_factor): # 4 super(N2_Normalization, self).__init__() self.upscale_factor = upscale_factor self.avgpool = nn.AvgPool2d(upscale_factor)...
8,965
36.514644
135
py