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 |
|---|---|---|---|---|---|---|
iQPP | iQPP-main/QPP_Methods/Fine-Tuned_ViT/VitRegressorDataset.py | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import torch
import pandas as pd
import torch.nn as nn
import pandas as pd
import numpy as np
import pickle
from torchvision.models import vit_b_32
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
from torchvision.mo... | 6,578 | 28.502242 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Image_Difficulty/Model/ionescu-et-all.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torchvision
from PIL import Image
from torchvision import transforms
from torchvision.models import vgg16,VGG16_Weights
from torch.utils.data import Dataset,D... | 6,276 | 30.542714 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Image_Difficulty/Run/run_image_difficulty.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torch.nn as nn
impo... | 4,325 | 23.033333 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Random_Prior/uniform.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torch.nn as nn
impo... | 2,571 | 30.753086 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Random_Prior/normal.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torch.nn as nn
impo... | 2,578 | 30.45122 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Num_Objects_Over_Area/Model/objectness.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from torchvision.transforms import Resize
from torch.nn import Sequential
import warnings
import torch
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
from torchvision.models.detection import fasterrcnn_resnet50_f... | 2,452 | 29.6625 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Num_Objects_Over_Area/Run/run_objectness.py | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', required=True,help='Dataset on which you want to train the model',choices=['roxford5k','rparis6k','pascalvoc_700_medium','caltech101_700'])
parser.add_argument('--method', required=True,help='Retrieval method which you want to analyse',... | 3,709 | 33.672897 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/DataLoaders/Loaders.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import numpy as np
import torch
import pickle
import argparse
from PIL import Image
from torchvision.transforms import... | 7,669 | 30.306122 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/Models/DAE.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import numpy as np
import torch
import torch.nn as nn
# In[1]:
# -------------------------------------------------------- Model definiti... | 3,590 | 27.959677 | 139 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/Models/MAE.py | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import torch
import torch.nn as nn
import numpy as np
# In[5]:
class PatchEmbedding(nn.Module):
def __init__(self, img_size, patch_size, num_input_channels, embedding_dim):
super().__init__()
self.img_size = img_size
self.patch_size ... | 14,060 | 31.548611 | 183 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/Train/train_dae.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torch
import torch.nn as nn
impo... | 4,947 | 28.987879 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/Train/train_mae.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------- Imports --------------------------------------------------------------
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import warnings
import matplotlib.pyplot as plt
import argparse
import random
... | 5,361 | 37.028369 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/Run/run_mae.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torch.nn as nn
impo... | 4,121 | 25.088608 | 172 | py |
iQPP | iQPP-main/QPP_Methods/Autoencoders/Run/run_dae.py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# -------------------------------------------------------- Imports --------------------------------------------------------------
import os
import pandas as pd
import torch
import skimage.io as sk
import scipy.stats as stats
import numpy as np
import torch.nn as nn
impo... | 5,356 | 31.865031 | 172 | py |
ImageNet | ImageNet-master/main.py | import argparse
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data
from models import *
from data_loader import data_loader
from helper import AverageMeter, save_checkpoint, accuracy, adjust_learning_rate
model_names = [
'alexnet', 'squeezenet1_0', 'squee... | 9,690 | 37.304348 | 101 | py |
ImageNet | ImageNet-master/data_loader.py | import os
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
def data_loader(root, batch_size=256, workers=1, pin_memory=True):
traindir = os.path.join(root, 'ILSVRC2012_img_train')
valdir = os.path.join(root, 'ILSVRC2012_img_val')
normalize = transforms.Norm... | 1,345 | 26.469388 | 66 | py |
ImageNet | ImageNet-master/helper.py | import shutil
import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val... | 1,326 | 25.54 | 80 | py |
ImageNet | ImageNet-master/models/resnet.py | import os
import math
import torch
import torch.nn as nn
import torchvision.models
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']
# you need to download the models to ~/.torch/models
# model_urls = {
# 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
# ... | 6,929 | 30.788991 | 99 | py |
ImageNet | ImageNet-master/models/squeezenet.py | import os
import torch
import torch.nn as nn
import torch.nn.init as init
# you need to download the models to ~/.torch/models
# model_urls = {
# 'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth',
# 'squeezenet1_1': 'https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth... | 4,251 | 36.964286 | 94 | py |
ImageNet | ImageNet-master/models/vgg.py | import os
import math
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 'vgg19_bn', 'vgg19'
]
# you need to download the models to ~/.torch/models
# model_urls = {
# 'vgg11': 'https://download.pytorch.... | 6,887 | 32.275362 | 112 | py |
ImageNet | ImageNet-master/models/densenet.py | import os
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
# you need to download the models to ~/.torch/models
# model_urls = {
# 'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
# 'densenet169': 'https://download.py... | 8,671 | 43.932642 | 109 | py |
ImageNet | ImageNet-master/models/alexnet.py | import os
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
# you need to download the models to ~/.torch/models
# model_urls = {
# 'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
# }
models_dir = os.path.expanduser('~/.torch/models')
model_name = 'alexnet-owt... | 2,202 | 32.378788 | 90 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/attention_graph_encoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import MultiHeadAttention
class MultiHeadAttentionLayer(nn.Module):
"""Feed-Forward Sublayer: fully-connected Feed-Forward network,
built based on MHA vectors from MultiHeadAttention layer with skip-connections
Args:
... | 4,045 | 34.80531 | 119 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/environment.py | import torch
from utils import CAPACITIES
class AgentVRP:
VEHICLE_CAPACITY = 1.0
def __init__(self, input):
depot = input[0] # (batch_size, 2)
loc = input[1] # (batch_size, n_nodes, 2)
self.demand = input[2] # (batch_size, n_nodes)
self.batch_size, self.n_loc, _ = loc.shap... | 5,535 | 34.487179 | 106 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/utils.py | import pickle
import torch
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
import numpy as np
from datetime import datetime
import time
CAPACITIES = {10: 20.0, 20: 30.0, 50: 40.0, 100: 50.0}
def set_random_seed(seed):
torch.manual_seed(seed)
def creat... | 9,904 | 27.05949 | 99 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/test_models.py | from tqdm import tqdm
import torch
import numpy as np
import warnings
from functools import reduce
import timeit
import sys
import sys
sys.path.append("../adm/")
from utils import generate_data_onfly, FastTensorDataLoader, CAPACITIES
from attention_dynamic_model import set_decode_type
from reinforce_baseline import... | 3,903 | 28.353383 | 86 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
def scaled_attention(query, key, value, mask=None):
"""Function that performs scaled attention given q, k, v and mask.
q, k, v can have multiple batches and heads, defined across the first dimensions
and the last 2 dimensions f... | 4,696 | 42.091743 | 116 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/attention_dynamic_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
import math
import numpy as np
from attention_graph_encoder import GraphAttentionEncoder
from layers import scaled_attention
from environment import AgentVRP
from utils import get_dev_of_mod
def... | 13,469 | 38.043478 | 133 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/reinforce_baseline.py | import torch
from scipy.stats import ttest_rel
from tqdm import tqdm
import numpy as np
from attention_dynamic_model import AttentionDynamicModel
from attention_dynamic_model import set_decode_type
from utils import generate_data_onfly, FastTensorDataLoader, get_dev_of_mod, CAPACITIES
def copy_of_pt_model(model, emb... | 7,358 | 29.159836 | 138 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/train.py | from tqdm import tqdm
import pandas as pd
import torch
from attention_dynamic_model import set_decode_type
from reinforce_baseline import validate
from utils import generate_data_onfly, get_cur_time
from time import gmtime, strftime
from utils import FastTensorDataLoader
from uuid import uuid4
import os
class Itera... | 6,367 | 32.693122 | 110 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/adm/train_models.py | import torch
from attention_dynamic_model import AttentionDynamicModel, set_decode_type
from reinforce_baseline import RolloutBaseline
from train import train_model
from utils import generate_data_onfly, get_cur_time
import sys
def main():
# Params of model
GRAPH_SIZE = int(sys.argv[1])
SAMPLES = int(sys... | 1,896 | 26.1 | 80 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/lsh/test_models.py | import sys
import os
from setup_args_pkl import setup_args
graph_size = int(sys.argv[1])
setup_args(
graph_size=graph_size,
n_steps=1,
rand_init_steps=0,
perturb_nodes=10,
epochs=-1,
n_rollout=100,
)
import arguments
import pickle
from tqdm import tqdm
import torch
import numpy as np
import ti... | 5,333 | 28.147541 | 92 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/lsh/train_models.py | import sys
from setup_args_pkl import setup_args
graph_size = int(sys.argv[1])
epochs = int(sys.argv[2])
n_steps = int(sys.argv[3])
rand_init_steps = int(sys.argv[4])
perturb_nodes = int(sys.argv[5])
batch = int(sys.argv[6])
setup_args(
graph_size=graph_size,
n_steps=n_steps,
rand_init_steps=rand_init_ste... | 1,488 | 24.237288 | 83 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/lsh/lib/egate_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import softmax
from torch.distributions.categorical import Categorical
class GatConv(MessagePassing):
def __init__(
self, in_channels, out_channels, edge_channels, ne... | 7,549 | 31.264957 | 85 | py |
Combined-Deep-Constuctor-and-Perturbator | Combined-Deep-Constuctor-and-Perturbator-master/lsh/lib/utils_train_from_loaded_model.py | import numpy as np
import os
import random
import torch
from torch_geometric.data import Data, DataLoader
from lib.rms import RunningMeanStd
from arguments import args
import timeit
from time import gmtime, strftime
from uuid import uuid4
from vrp_env import create_batch_env
args = args()
DEVICE = str(args.device)
N... | 13,178 | 30.604317 | 108 | py |
imagededup | imagededup-master/setup.py | import sys
from setuptools import setup, find_packages, Extension
long_description = '''
imagededup is a python package that provides functionality to find duplicates in a collection of images using a variety
of algorithms. Additionally, an evaluation and experimentation framework, is also provided. Following details ... | 4,443 | 32.923664 | 119 | py |
imagededup | imagededup-master/mkdocs/autogen.py | # Heavily borrowed from the Auto-Keras project:
# https://github.com/jhfjhfj1/autokeras/blob/master/mkdocs/autogen.py
import ast
import os
import re
def delete_space(parts, start, end):
if start > end or end >= len(parts):
return None
count = 0
while count < len(parts[start]):
if parts[st... | 8,352 | 29.822878 | 147 | py |
imagededup | imagededup-master/imagededup/methods/cnn.py | from pathlib import Path, PurePath
import sys
from typing import Dict, List, Optional, Union
import warnings
from multiprocessing import cpu_count
import numpy as np
from PIL import Image
import torch
from imagededup.handlers.search.retrieval import get_cosine_similarity
from imagededup.utils.data_generator import im... | 23,196 | 41.957407 | 190 | py |
imagededup | imagededup-master/imagededup/utils/data_generator.py | from pathlib import PurePath
from typing import Dict, Callable, Optional, List, Tuple
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from imagededup.utils.image_utils import load_image
from imagededup.utils.general_utils import generate_files
class ImgDataset(Dataset):
def __in... | 2,015 | 30.015385 | 99 | py |
imagededup | imagededup-master/imagededup/utils/models.py | from PIL.Image import Image
from typing import Callable, NamedTuple, Optional
import torch
import torch.nn as nn
from torchvision import models
from torchvision.transforms import transforms
from torchvision.models import vit_b_16, EfficientNet_B4_Weights
from torchvision.models.vision_transformer import ViT_B_16_Weigh... | 5,147 | 40.184 | 239 | py |
imagededup | imagededup-master/tests/test_cnn.py | import sys
from multiprocessing import cpu_count
from pathlib import Path
import os
import json
import numpy as np
import torch
from PIL import Image
import pytest
from torchvision.transforms import transforms
from imagededup.methods.cnn import CNN
from imagededup.utils.image_utils import load_image
from imagededup.u... | 32,233 | 32.026639 | 141 | py |
imagededup | imagededup-master/tests/test_data_generator.py | from pathlib import Path, PurePath
from typing import List, Tuple
import torch
from imagededup.methods import CNN
from imagededup.utils.data_generator import img_dataloader
p = Path(__file__)
IMAGE_DIR = p.parent / 'data/base_images'
FORMATS_IMAGE_DIR = p.parent / 'data/formats_images'
NESTED_IMAGE_DIR = p.parent / ... | 2,160 | 32.246154 | 97 | py |
adgcl | adgcl-main/test_minmax_ogbg.py | import argparse
import logging
import random
import numpy as np
import torch
from ogb.graphproppred import Evaluator
from ogb.graphproppred import PygGraphPropPredDataset
from sklearn.linear_model import Ridge, LogisticRegression
from torch_geometric.data import DataLoader
from torch_geometric.transforms import Compos... | 9,866 | 40.457983 | 163 | py |
adgcl | adgcl-main/test_minmax_tu.py | import argparse
import logging
import random
import numpy as np
import torch
from sklearn.svm import LinearSVC, SVC
from torch_geometric.data import DataLoader
from torch_geometric.transforms import Compose
from torch_scatter import scatter
from datasets import TUDataset, TUEvaluator
from unsupervised.embedding_evalu... | 9,424 | 39.450644 | 181 | py |
adgcl | adgcl-main/test_transfer_finetune_chem.py | import argparse
import logging
import random
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import roc_auc_score
from torch_geometric.data import DataLoader
from tqdm import tqdm
from datasets import MoleculeDataset
from transfer.model import... | 9,198 | 38.650862 | 130 | py |
adgcl | adgcl-main/test_minmax_zinc.py | import argparse
import logging
import random
import numpy as np
import torch
from sklearn.linear_model import Ridge
from torch_geometric.data import DataLoader
from torch_geometric.transforms import Compose
from torch_scatter import scatter
from datasets import ZINC, ZINCEvaluator
from unsupervised.embedding_evaluati... | 9,892 | 40.567227 | 121 | py |
adgcl | adgcl-main/test_minmax_transfer_pretrain_bio.py | import argparse
import logging
import random
from pathlib import Path
import numpy as np
import torch
from torch_geometric.data import DataLoader
from torch_geometric.transforms import Compose
from torch_scatter import scatter
from tqdm import tqdm
from datasets import BioDataset
from transfer import BioGNN
from tran... | 7,332 | 37.594737 | 164 | py |
adgcl | adgcl-main/test_minmax_transfer_pretrain_chem.py | import argparse
import logging
import random
from pathlib import Path
import numpy as np
import torch
from torch_geometric.data import DataLoader
from torch_geometric.transforms import Compose
from torch_scatter import scatter
from tqdm import tqdm
from datasets import MoleculeDataset
from transfer.learning import GI... | 7,368 | 37.989418 | 165 | py |
adgcl | adgcl-main/test_transfer_finetune_bio.py | import argparse
import logging
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import roc_auc_score
from datasets import BioDataset
from transfer import BioGNN_graphpred
from transfer.utils import DataLoaderFinetune
from transfer.utils import bio_ra... | 9,396 | 40.214912 | 145 | py |
adgcl | adgcl-main/transfer/model_bio.py | import torch
import torch.nn.functional as F
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool, GlobalAttention
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.utils import add_self_loops, softmax
from torch_scatter im... | 12,081 | 32.283747 | 132 | py |
adgcl | adgcl-main/transfer/utils.py | import random
from collections import defaultdict
from itertools import compress
import numpy as np
import torch
import torch.utils.data
from rdkit.Chem.Scaffolds import MurckoScaffold
from sklearn.model_selection import StratifiedKFold
from torch_geometric.data import Data
class BatchMasking(Data):
r"""A plain ... | 22,604 | 39.22242 | 179 | py |
adgcl | adgcl-main/transfer/model.py | import torch
import torch.nn.functional as F
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool, GlobalAttention, Set2Set
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.utils import add_self_loops, softmax
from torch_s... | 13,359 | 33.25641 | 122 | py |
adgcl | adgcl-main/transfer/learning/gsimclr.py | import torch
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import global_mean_pool
class GSimCLR(torch.nn.Module):
def __init__(self, gnn):
super(GSimCLR, self).__init__()
self.gnn = gnn
self.pool = global_mean_pool
self.projection_head = Sequential(Linear(3... | 1,047 | 32.806452 | 97 | py |
adgcl | adgcl-main/transfer/learning/view_learner.py | import torch
from torch.nn import Sequential, Linear, ReLU
class ViewLearner(torch.nn.Module):
def __init__(self, gnn, mlp_edge_model_dim=64):
super(ViewLearner, self).__init__()
self.gnn = gnn
self.input_dim = gnn.emb_dim
self.mlp_edge_model = Sequential(
Linear(self.... | 1,048 | 28.138889 | 60 | py |
adgcl | adgcl-main/transfer/learning/ginfominmax.py | import torch
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import global_mean_pool
class GInfoMinMax(torch.nn.Module):
def __init__(self, gnn, proj_hidden_dim=300):
super(GInfoMinMax, self).__init__()
self.gnn = gnn
self.pool = global_mean_pool
self.input_... | 1,906 | 31.322034 | 107 | py |
adgcl | adgcl-main/unsupervised/utils.py | import copy
import numpy as np
import torch
from torch_geometric.data import Data
def initialize_edge_weight(data):
data.edge_weight = torch.ones(data.edge_index.shape[1], dtype=torch.float)
return data
def initialize_node_features(data):
num_nodes = int(data.edge_index.max()) + 1
data.x = torch.ones((num_nodes... | 7,894 | 32.172269 | 188 | py |
adgcl | adgcl-main/unsupervised/view_learner.py | import torch
from torch.nn import Sequential, Linear, ReLU
class ViewLearner(torch.nn.Module):
def __init__(self, encoder, mlp_edge_model_dim=64):
super(ViewLearner, self).__init__()
self.encoder = encoder
self.input_dim = self.encoder.out_node_dim
self.mlp_edge_model = Sequential(
Linear(self.input_dim... | 921 | 23.918919 | 61 | py |
adgcl | adgcl-main/unsupervised/embedding_evaluation.py | import numpy as np
import torch
from sklearn.model_selection import GridSearchCV, KFold
from sklearn.model_selection import train_test_split
from sklearn.multioutput import MultiOutputClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from torch_geometric.data import ... | 6,629 | 39.181818 | 142 | py |
adgcl | adgcl-main/unsupervised/convs/inits.py | import math
import torch
def uniform(size, tensor):
if tensor is not None:
bound = 1.0 / math.sqrt(size)
tensor.data.uniform_(-bound, bound)
def kaiming_uniform(tensor, fan, a):
if tensor is not None:
bound = math.sqrt(6 / ((1 + a**2) * fan))
tensor.data.uniform_(-bound, bou... | 1,273 | 21.75 | 69 | py |
adgcl | adgcl-main/unsupervised/convs/gine_conv.py | from typing import Callable, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.typing import OptPairTensor, Adj, OptTensor, Size
from torch_sparse import SparseTensor
from unsupervised.convs.inits import reset
class GI... | 2,041 | 34.206897 | 116 | py |
adgcl | adgcl-main/unsupervised/convs/wgin_conv.py | from typing import Callable, Union
import torch
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.typing import OptPairTensor, Adj, Size
from unsupervised.convs.inits import reset
class WGINConv(MessagePassing):
def __init__(self, nn: Callable, eps: float = 0., train_... | 1,324 | 26.604167 | 88 | py |
adgcl | adgcl-main/unsupervised/learning/ginfomax.py | import math
import torch
import torch.nn.functional as F
from torch import nn
def log_sum_exp(x, axis=None):
"""Log sum exp function
Args:
x: Input.
axis: Axis over which to perform sum.
Returns:
torch.Tensor: log sum exp
"""
x_max = torch.max(x, axis)[0]
y = torch.log((torch.exp(x - x_max)).sum(axis)) +... | 5,057 | 23.916256 | 79 | py |
adgcl | adgcl-main/unsupervised/learning/gsimclr.py | import torch
from torch.nn import Sequential, Linear, ReLU
class GSimCLR(torch.nn.Module):
def __init__(self, encoder, proj_hidden_dim=300):
super(GSimCLR, self).__init__()
self.encoder = encoder
self.input_proj_dim = self.encoder.out_graph_dim
self.proj_head = Sequential(Linear(self.input_proj_dim, proj_hi... | 1,452 | 29.914894 | 95 | py |
adgcl | adgcl-main/unsupervised/learning/ginfominmax.py | import torch
from torch.nn import Sequential, Linear, ReLU
class GInfoMinMax(torch.nn.Module):
def __init__(self, encoder, proj_hidden_dim=300):
super(GInfoMinMax, self).__init__()
self.encoder = encoder
self.input_proj_dim = self.encoder.out_graph_dim
self.proj_head = Sequential(Linear(self.input_proj_dim... | 1,630 | 26.644068 | 95 | py |
adgcl | adgcl-main/unsupervised/encoder/zinc_encoder.py | import numpy as np
import torch
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import global_add_pool
from unsupervised.convs import GINEConv
class ZINCEncoder(torch.nn.Module):
def __init__(self, num_atom_type, num_bond_type, emb_dim=100, num_gc_layers=5, drop... | 3,148 | 30.49 | 141 | py |
adgcl | adgcl-main/unsupervised/encoder/molecule_encoder.py | import numpy as np
import torch
import torch.nn.functional as F
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import global_add_pool
from unsupervised.convs import GINEConv
class MoleculeEncoder(torch.nn.Module):
def __init__... | 3,170 | 29.2 | 115 | py |
adgcl | adgcl-main/unsupervised/encoder/feed_forward_encoder.py | import torch
from torch.nn import Sequential, Linear, ReLU, Dropout
class FeedForwardNetwork(torch.nn.Module):
def __init__(self, in_features, out_features, num_fc_layers, dropout):
super(FeedForwardNetwork, self).__init__()
self.num_fc_layers = num_fc_layers
self.fcs = torch.nn.ModuleList()
for i in range... | 1,201 | 31.486486 | 106 | py |
adgcl | adgcl-main/unsupervised/encoder/tu_encoder.py | import numpy as np
import torch
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import global_add_pool
from unsupervised.convs.wgin_conv import WGINConv
class TUEncoder(torch.nn.Module):
def __init__(self, num_dataset_features, emb_dim=300, num_gc_layers=5, drop... | 2,758 | 28.98913 | 133 | py |
adgcl | adgcl-main/datasets/zinc.py | import os
import os.path as osp
import pickle
import shutil
import numpy as np
import torch
from torch_geometric.data import (InMemoryDataset, Data, download_url,
extract_zip)
from tqdm import tqdm
class ZINC(InMemoryDataset):
url = 'https://www.dropbox.com/s/feo9qle74kg48gy/mo... | 6,161 | 35.898204 | 116 | py |
adgcl | adgcl-main/datasets/transfer_mol_dataset.py | import os
import pickle
from itertools import repeat, chain
import networkx as nx
import numpy as np
import pandas as pd
import torch
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Descriptors
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
from torch.utils import da... | 68,942 | 34.228922 | 160 | py |
adgcl | adgcl-main/datasets/transfer_bio_dataset.py | from itertools import repeat
import networkx as nx
import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.data import InMemoryDataset
def nx_to_graph_data_obj(g, center_id, allowable_features_downstream=None,
allowable_features_pretrain=None,
... | 13,805 | 34.4 | 104 | py |
adgcl | adgcl-main/datasets/tu_dataset.py | import os
import os.path as osp
import shutil
import numpy as np
import torch
from sklearn.metrics import accuracy_score
from torch_geometric.data import InMemoryDataset, download_url, extract_zip
from torch_geometric.io import read_tu_data
class TUDataset(InMemoryDataset):
r"""A variety of graph kernel benchmar... | 8,925 | 40.324074 | 116 | py |
actnn | actnn-main/mem_speed_benchmark/scaled_resnet.py | from torchvision.models.resnet import _resnet, Bottleneck
def scaled_resnet(name):
n_layers = int(name.split('scaled_resnet_')[1])
assert n_layers >= 152
added_layers = n_layers - 152
add_1 = int(added_layers * (8 / (8 + 36)))
add_2 = added_layers - add_1
return _resnet('', Bottleneck, [3, 8 ... | 557 | 30 | 78 | py |
actnn | actnn-main/mem_speed_benchmark/train.py | """
Modified from https://github.com/utsaslab/MONeT/blob/master/examples/imagenet.py
"""
import argparse
import json
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
impor... | 21,832 | 37.303509 | 102 | py |
actnn | actnn-main/tests/test_minimax.py | import numpy as np
import torch
from actnn.ops import ext_minimax
from timeit_v2 import py_benchmark
def test_minimax_correctness():
print("========== Minimax Correctness Test ==========")
for dtype in ['float32', 'float16']:
print(f"test {dtype}...")
data_np = np.random.randn(1024, 256).as... | 1,849 | 28.83871 | 100 | py |
actnn | actnn-main/tests/dcgan_tutorial.py | # -*- coding: utf-8 -*-
"""
DCGAN Tutorial
==============
**Author**: `Nathan Inkawhich <https://github.com/inkawhich>`__
"""
######################################################################
# Introduction
# ------------
#
# This tutorial will give an introduction to DCGANs through an example. We
# will train ... | 29,814 | 39.454545 | 171 | py |
actnn | actnn-main/tests/test_conv_layer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from actnn import config, QConv1d, QConv2d, QConv3d, QConvTranspose2d, QConvTranspose3d
torch.manual_seed(0)
def test(layer, qlayer, x, y):
with torch.no_grad():
qlayer.weight.copy_(layer.weight)
qlayer.bias.cop... | 2,755 | 34.792208 | 109 | py |
actnn | actnn-main/tests/test_act_quantized_ops.py | """Test the activation quantized ops"""
import math
import numpy as np
import torch
from torch.nn import functional as F
from timeit_v2 import py_benchmark
from actnn import QScheme, QBNScheme, config, get_memory_usage, compute_tensor_bytes
from actnn.ops import ext_backward_func, ext_quantization
from actnn.ops im... | 27,508 | 41.321538 | 138 | py |
actnn | actnn-main/tests/test_linear.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from actnn import config, QLinear
torch.manual_seed(0)
# config.activation_compression_bits = [8]
config.compress_activation = False
model = nn.Linear(100, 10).cuda()
qmodel = QLinear(100, 10).cuda()
with torch.no_grad():
qmodel... | 761 | 22.090909 | 80 | py |
actnn | actnn-main/tests/trigger_error.py | """Trigger the autograd error"""
import torch
from torch import nn, autograd
class identity(autograd.Function):
@staticmethod
def forward(ctx, data):
# correct
#ctx.save_for_backward(data)
# correct
#ctx.save_for_backward(data + 1)
# RuntimeError: No grad accumulator f... | 590 | 20.888889 | 61 | py |
actnn | actnn-main/tests/test_backward_func.py | """Test calling c++ backward func from Python"""
import math
import numpy as np
import torch
from torch import nn, autograd
from torch.nn import init, functional as F
from torch.nn.modules.utils import _single, _pair, _triple
from actnn.cpp_extension.backward_func import (cudnn_convolution_backward,
cudnn_convolu... | 16,973 | 41.755668 | 121 | py |
actnn | actnn-main/actnn/setup.py | from setuptools import setup, Extension, find_packages
from torch.utils import cpp_extension
setup(name='actnn',
ext_modules=[
cpp_extension.CUDAExtension(
'actnn.cpp_extension.calc_precision',
['actnn/cpp_extension/calc_precision.cc']
),
cpp_extension.CU... | 953 | 35.692308 | 104 | py |
actnn | actnn-main/actnn/actnn/qscheme.py | import torch
import actnn
from actnn.conf import config
import actnn.cpp_extension.minimax as ext_minimax
import actnn.cpp_extension.calc_precision as ext_calc_precision
class QScheme(object):
num_samples = 1
num_layers = 0
batch = None
update_scale = True
layers = []
prev_layer = None
d... | 5,725 | 37.689189 | 112 | py |
actnn | actnn-main/actnn/actnn/qbnscheme.py | import torch
from actnn.conf import config
from actnn.qscheme import QScheme
import actnn.cpp_extension.minimax as ext_minimax
import actnn.cpp_extension.calc_precision as ext_calc_precision
class QBNScheme(QScheme):
layers = []
def __init__(self, group=0):
self.initial_bits = config.initial_bits
... | 2,266 | 36.163934 | 112 | py |
actnn | actnn-main/actnn/actnn/dataloader.py | r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter
To support these two classes, in `./_utils` we define many utility methods and
functions to be run in multiprocessing. E.g., the data loading worker loop is
in `./_utils/worker.py`.
"""
import threading
import itertools
import... | 48,351 | 49.157676 | 120 | py |
actnn | actnn-main/actnn/actnn/utils.py | import os
from collections import OrderedDict
import json
import torch
import numpy as np
import json
def swap_to_cpu(tensor):
tensor_cpu = torch.empty(tensor.shape, dtype=tensor.dtype, device='cpu', pin_memory=True)
tensor_cpu.copy_(tensor, non_blocking=True)
return tensor_cpu
def get_memory_usage(pri... | 2,215 | 26.02439 | 93 | py |
actnn | actnn-main/actnn/actnn/module.py | from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping, Dict
from collections import OrderedDict
import torch
import torch.nn as nn
from torch import Tensor, device, dtype
from actnn.layers import QConv1d, QConv2d, QConv3d, QConvTranspose1d, QConvTranspose2d, QConvTranspos... | 5,488 | 52.813725 | 114 | py |
actnn | actnn-main/actnn/actnn/layers.py | # The code is compatible with PyTorch 1.6/1.7
from typing import List, Optional
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed
from torch import Tensor
from torch.nn.modules.pooling import _size_2_t, _single, _pair, _triple, _MaxPoolNd, _AvgPoolNd
from actn... | 23,604 | 44.65764 | 120 | py |
actnn | actnn-main/actnn/actnn/ops.py | from collections import namedtuple
import os
import time
import numpy as np
import torch
from torch.autograd.function import Function
import torch.distributed as dist
import torch.nn.functional as F
from torch.nn.modules.utils import _single, _pair, _triple
from torch.utils.cpp_extension import load
from actnn.conf i... | 24,626 | 38.090476 | 140 | py |
actnn | actnn-main/actnn/actnn/conf.py | import ast
import os
import warnings
def set_optimization_level(level):
if level == 'L0': # Do nothing
config.compress_activation = False
config.adaptive_conv_scheme = config.adaptive_bn_scheme = False
elif level == 'L1': # 4-bit conv + 32-bit bn
config.activation_compression_bi... | 2,592 | 36.042857 | 88 | py |
actnn | actnn-main/actnn/actnn/_utils/collate.py | r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers to
collate samples fetched from dataset into Tensor(s).
These **needs** to be in global scope since Py2 doesn't support serializing
static methods.
"""
import torch
import re
from torch._six import container_abcs, string_classes, int_cla... | 3,660 | 41.08046 | 92 | py |
actnn | actnn-main/actnn/actnn/_utils/__init__.py | r"""Utility classes & functions for data loading. Code in this folder is mostly
used by ../dataloder.py.
A lot of multiprocessing is used in data loading, which only supports running
functions defined in global environment (py2 can't serialize static methods).
Therefore, for code tidiness we put these functions into d... | 1,501 | 31.652174 | 117 | py |
actnn | actnn-main/actnn/actnn/_utils/pin_memory.py | r""""Contains definitions of the methods used by the _BaseDataLoaderIter to put
fetched tensors into pinned memory.
These **needs** to be in global scope since Py2 doesn't support serializing
static methods.
"""
import torch
from torch._six import queue, container_abcs, string_classes
from . import MP_STATUS_CHECK_IN... | 2,085 | 33.766667 | 81 | py |
actnn | actnn-main/actnn/actnn/_utils/signal_handling.py | r""""Signal handling for multiprocessing data loading.
NOTE [ Signal handling in multiprocessing data loading ]
In cases like DataLoader, if a worker process dies due to bus error/segfault
or just hang, the main process will hang waiting for data. This is difficult
to avoid on PyTorch side as it can be caused by limi... | 3,080 | 41.791667 | 90 | py |
actnn | actnn-main/actnn/actnn/_utils/worker.py | r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers.
These **needs** to be in global scope since Py2 doesn't support serializing
static methods.
"""
import torch
import random
import os
from collections import namedtuple
from torch._six import queue
from torch._utils import ExceptionWrapp... | 8,571 | 40.410628 | 111 | py |
actnn | actnn-main/image_classification/main.py | import argparse
import random
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import actnn
from actnn import config, QScheme, QModule
try:
# from apex.parallel import DistributedDataParall... | 16,651 | 44.127371 | 155 | py |
actnn | actnn-main/image_classification/multiproc.py | import sys
import subprocess
import os
import socket
import time
from argparse import ArgumentParser, REMAINDER
import torch
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(description="PyTorch distributed training launch "
... | 4,169 | 33.75 | 86 | py |
actnn | actnn-main/image_classification/image_classification/resnet.py | import torch
import torch.nn as nn
from .preact_resnet import PreActBlock, PreActBottleneck, PreActResNet
from actnn import QConv2d, QLinear, QBatchNorm2d, QReLU, QSyncBatchNorm, QMaxPool2d, config
__all__ = ['ResNet', 'build_resnet', 'resnet_versions', 'resnet_configs']
# ResNetBuilder {{{
class ResNetBuilder(obje... | 16,082 | 32.092593 | 100 | py |
actnn | actnn-main/image_classification/image_classification/training.py | import time
import os
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from . import logger as log
from . import resnet as models
from . import utils
from .debug import get_var, get_var_during_training
from actnn import config, QScheme, QModule, get_memory_usage, compute_tensor_... | 17,134 | 37.247768 | 207 | py |
actnn | actnn-main/image_classification/image_classification/utils.py | import os
import numpy as np
import torch
import shutil
import torch.distributed as dist
def should_backup_checkpoint(args):
def _sbc(epoch):
return args.gather_checkpoints # and (epoch < 10 or epoch % 10 == 0)
return _sbc
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', checkpoint... | 2,458 | 24.884211 | 110 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.