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 |
|---|---|---|---|---|---|---|
ACDC | ACDC-main/utils/jsd_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class LabelSmoothingCrossEntropy(nn.Module):
"""
NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.1):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
... | 2,281 | 37.677966 | 96 | py |
ACDC | ACDC-main/utils/datasets.py | """
Dataset loading utilities
"""
import os
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import sklearn.datasets as sklearn_datasets
from torch.utils.data import TensorDataset
from utils.auto_augmentation import auto_augment_policy, AutoAugment
from utils.random_au... | 7,263 | 36.637306 | 120 | py |
ACDC | ACDC-main/utils/aug_mix_dataset.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.utils.data as data
import os
import re
import torch
import tarfile
from PIL import Image
IMG_EXTENSIONS = ['.png', '.jpg', '.jpeg']
def natural_key(string_):
"""See http://www.codinghorror... | 7,051 | 34.796954 | 109 | py |
ACDC | ACDC-main/utils/random_erasing.py | import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
# NOTE I've seen CUDA illegal memory access errors being caused by the normal_()
# paths, flip the order so normal is run on CPU if this becomes a problem
# Issue has been fixed i... | 4,302 | 47.348315 | 95 | py |
ACDC | ACDC-main/utils/flop_utils.py | import copy
import torch
from utils.checkpoints import get_unwrapped_model
def get_macs(dataset, model):
from torchprofile import profile_macs
from utils.datasets import classification_get_input_shape
inputs = torch.randn(classification_get_input_shape(dataset))
macs = profile_macs(model, inputs)
... | 7,614 | 30.995798 | 120 | py |
ACDC | ACDC-main/utils/masking_utils.py | """
Utility functions and classes to work with pruning.
In the end, outside modules should primarily:
* use get_wrapped_model,
* potentially add functionality to Wrapped layer,
and not worry about the rest.
TODO: decide where this module belongs organically in terms of logic.
E.g. it can be under utils or pruners... | 12,506 | 31.655352 | 140 | py |
InfoMotif | InfoMotif-master/train.py | import numpy as np
import scipy.sparse as spsparse
import torch
import torch.nn as nn
import os
from models.model import motif_emb
from utils import data_process
import networkx as nx
from scipy.sparse import csr_matrix
import torch.nn.functional as F
import argparse
PARSER = argparse.ArgumentParser(description='Parsi... | 9,782 | 40.987124 | 111 | py |
InfoMotif | InfoMotif-master/models/model.py | import torch
import torch.nn as nn
from layers.gcn import GCN
from layers.combined_DGI import combinedDGI
from layers.encoder_attention import Encoder_attention
class motif_emb(nn.Module):
def __init__(self, n_in, n_h, n_h2, n_motif, n_class, activation="prelu", dropout=0.5):
super(motif_emb, self).__init... | 1,724 | 35.702128 | 91 | py |
InfoMotif | InfoMotif-master/layers/combined_DGI.py | import torch
import torch.nn as nn
from dgi import DGI
import numpy as np
from layers.gcn import GCN
# noinspection PyCallingNonCallable
class combinedDGI(nn.Module):
def __init__(self, n_h, n_h2, n_motif, activation):
super(combinedDGI, self).__init__()
self.dgi_list = nn.ModuleList([DGI(n_h, n_h... | 993 | 29.121212 | 94 | py |
InfoMotif | InfoMotif-master/layers/discriminator.py | import torch
import torch.nn as nn
# noinspection PyCallingNonCallable
class Discriminator(nn.Module):
def __init__(self, n_h):
super(Discriminator, self).__init__()
self.f_k = nn.Bilinear(n_h, n_h, 1)
for m in self.modules():
self.weights_init(m)
def weights_init(self, m)... | 946 | 27.69697 | 65 | py |
InfoMotif | InfoMotif-master/layers/encoder_attention.py | import torch
import torch.nn as nn
class Encoder_attention(nn.Module):
def __init__(self, n_h):
super(Encoder_attention, self).__init__()
self.linear = nn.Linear(n_h, 1)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
"""Output: X """
x1 = self.linear(x).squeeze... | 524 | 26.631579 | 96 | py |
InfoMotif | InfoMotif-master/layers/readout.py | import torch
import torch.nn as nn
# Applies an average on seq, of shape (batch, nodes, features)
# While taking into account the masking of msk
class AvgReadout(nn.Module):
def __init__(self):
super(AvgReadout, self).__init__()
def forward(self, seq, msk):
if msk is None:
return ... | 456 | 25.882353 | 62 | py |
InfoMotif | InfoMotif-master/layers/gcn.py | import torch
import torch.nn as nn
class GCN(nn.Module):
def __init__(self, in_ft, out_ft, act, bias=True):
super(GCN, self).__init__()
self.fc = nn.Linear(in_ft, out_ft, bias=False)
self.act = nn.PReLU() if act == 'prelu' else act
if bias:
self.bias = nn.Parameter(tor... | 1,076 | 28.108108 | 80 | py |
InfoMotif | InfoMotif-master/layers/attention.py | import torch
import torch.nn as nn
class Attention(nn.Module):
def __init__(self, n_h):
super(Attention, self).__init__()
self.linear = nn.Linear(n_h * 2, 1)
self.softmax = nn.Softmax(dim=2)
def forward(self, x):
curr_node = x[:, :, 0, :].unsqueeze(2).expand_as(x)
sta... | 639 | 26.826087 | 96 | py |
InfoMotif | InfoMotif-master/layers/dgi.py | import torch
import torch.nn as nn
import numpy as np
from gcn import GCN
from readout import AvgReadout
from discriminator import Discriminator
from attention import Attention
# noinspection PyCallingNonCallable
class DGI(nn.Module):
def __init__(self, n_in, n_h, activation):
super(DGI, self).__init__()
... | 1,473 | 30.361702 | 129 | py |
InfoMotif | InfoMotif-master/utils/data_process.py | import numpy as np
import networkx as nx
import networkx.algorithms.isomorphism as iso
import itertools
import os.path
import subprocess
import torch.nn.functional as F
import pickle
import os
import scipy.sparse as sp
import torch
import json
import scipy.io as sio
mapping = {"Case_Based": 0, "Genetic_Algorithms": 1,... | 11,685 | 33.269795 | 106 | py |
s2e-coref | s2e-coref-master/coref_bucket_batch_sampler.py | import logging
from itertools import islice
from typing import List, Iterable, Tuple, Iterator, Sequence
import random
import math
from torch.utils import data
from data import CorefExample
from torch.utils.data import DataLoader
logger = logging.getLogger(__name__)
def add_noise_to_value(value: int, noise_param: f... | 2,616 | 32.987013 | 102 | py |
s2e-coref | s2e-coref-master/modeling.py | import torch
from torch.nn import Module, Linear, LayerNorm, Dropout
from transformers import BertPreTrainedModel, LongformerModel
from transformers.modeling_bert import ACT2FN
from utils import extract_clusters, extract_mentions_to_predicted_clusters_from_clusters, mask_tensor
from data import PAD_ID_FOR_COREF
class... | 13,574 | 53.3 | 150 | py |
s2e-coref | s2e-coref-master/training.py | import json
import os
import logging
import random
import numpy as np
from torch.utils.tensorboard import SummaryWriter
import torch
from torch.utils.data import DataLoader
from coref_bucket_batch_sampler import BucketBatchSampler
# from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm, trange
from t... | 11,815 | 48.647059 | 172 | py |
s2e-coref | s2e-coref-master/utils.py | import json
import os
from collections import namedtuple, Counter
import pickle
from datetime import datetime
from time import time
import git
import numpy as np
import torch
NULL_ID_FOR_COREF = 0
def flatten_list_of_lists(lst):
return [elem for sublst in lst for elem in sublst]
def extract_clusters(gold_cluste... | 2,252 | 29.863014 | 112 | py |
s2e-coref | s2e-coref-master/data.py | import json
import logging
import os
import pickle
from collections import namedtuple, defaultdict
import torch
from utils import flatten_list_of_lists
from torch.utils.data import Dataset
from transformers import RobertaTokenizer
CorefExample = namedtuple("CorefExample", ["token_ids", "clusters"])
SPEAKER_START = ... | 8,884 | 45.276042 | 166 | py |
s2e-coref | s2e-coref-master/run_coref.py | from __future__ import absolute_import, division, print_function
import glob
import logging
import os
import pickle
import shutil
import git
import torch
from transformers import AutoConfig, AutoTokenizer, CONFIG_MAPPING, LongformerConfig, RobertaConfig
from modeling import S2E
from data import get_dataset
from cli ... | 6,151 | 37.691824 | 136 | py |
s2e-coref | s2e-coref-master/eval.py | import json
import os
import logging
import random
from collections import OrderedDict, defaultdict
import numpy as np
import torch
from coref_bucket_batch_sampler import BucketBatchSampler
from data import get_dataset
from metrics import CorefEvaluator, MentionEvaluator
from utils import extract_clusters, extract_ment... | 7,258 | 48.380952 | 172 | py |
HiFuse | HiFuse-main/test.py | import os
import json
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
from main_model import main_model as create_model
def main():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"using {device} device.")
num_classes = ... | 2,088 | 30.651515 | 84 | py |
HiFuse | HiFuse-main/utils.py | import os
import sys
import json
import pickle
import random
import math
from PIL import Image
import torch
from tqdm import tqdm
import matplotlib.pyplot as plt
from torch.utils.data import Dataset
def read_train_data(root: str):
random.seed(0)
assert os.path.exists(root), "dataset root: {} does not exist.".f... | 8,143 | 31.83871 | 125 | py |
HiFuse | HiFuse-main/main_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import numpy as np
from typing import Optional
def drop_path_f(x, drop_prob: float = 0., training: bool = False):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks... | 33,756 | 41.73038 | 113 | py |
HiFuse | HiFuse-main/train.py | import os
import argparse
import torch
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
from utils import MyDataSet
from main_model import HiFuse_Small as create_model
from utils import read_train_data, read_val_data, create_lr_scheduler, get_params_groups... | 7,481 | 43.272189 | 115 | py |
3d-isometry-robust | 3d-isometry-robust-master/attack.py | from __future__ import print_function
import open3d as o3d #do not import open3d befor torch
import argparse
import os
import csv
import numpy as np
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from utils im... | 16,301 | 39.251852 | 136 | py |
3d-isometry-robust | 3d-isometry-robust-master/thompson_sample.py | import numpy as np
import torch
import torch.nn.functional as F
import isometry_init
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def logits_info(obj, label, model):
correct = 0
logits, _ = model(obj)
prob = F.softmax(logits, dim=1)
rates, indices = prob.sort(1, descending=Tr... | 2,752 | 31.77381 | 172 | py |
3d-isometry-robust | 3d-isometry-robust-master/utils.py | import time
import sys
import math
import os
import torch
import torch.nn as nn
import torch.nn.init as init
import csv
import statistics as stat
_, term_width = os.popen('stty size', 'r').read().split()
term_width = int(term_width)
TOTAL_BAR_LENGTH = 86.
last_time = time.time()
begin_time = last_time
def progress_ba... | 3,837 | 26.028169 | 74 | py |
3d-isometry-robust | 3d-isometry-robust-master/train.py | from __future__ import print_function
import argparse
import os
import csv
import numpy as np
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from data.data_class import ModelNet40, ShapeNetPart
from data.tran... | 12,775 | 40.615635 | 145 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/dgcnn.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Yue Wang
@Contact: yuewangx@mit.edu
@File: model.py
@Time: 2018/10/13 6:35 PM
"""
import os
import sys
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def knn(x, k):
inner = -2*torch.matmul(x... | 4,211 | 32.967742 | 181 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/pointnet.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
class STNkd(nn.Module):
def __init__(self, k=64):
super(STNkd, self).__init__()
self.con... | 5,863 | 31.94382 | 128 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/pointnet2.py | import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
from models.pointnet_util import PointNetSetAbstractionMsg,PointNetSetAbstraction,PointNetFeaturePropagation
class PointNet2ClsMsg(nn.Module):
def __init__(self, num_classes=40):
super(PointNet2ClsMsg, self).__init__()
... | 8,089 | 45.228571 | 139 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/pointcnn.py | import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, 'models'))
import torch
from torch import nn
from ptcnn_utils.model import RandPointCNN
from ptcnn_utils.util_funcs import knn_indices_func_gpu, knn_indices_func_cpu
from ptcnn_utils.ut... | 1,477 | 29.791667 | 96 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/pointnet_util.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
def timeit(tag, t):
print("{}: {}s".format(tag, time() - t))
return time()
def pc_normalize(pc):
l = pc.shape[0]
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.s... | 11,165 | 34.447619 | 104 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn.py | import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "rscnn_utils"))
import torch
import torch.nn as nn
from torch.autograd import Variable
import pytorch_utils as pt_utils
from pointnet2_modules import PointnetSAModule, PointnetSAModuleMS... | 3,716 | 32.1875 | 112 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/build_ffi.py | import glob
import torch
import os.path as osp
from torch.utils.ffi import create_extension
import sys, argparse, shutil
base_dir = osp.dirname(osp.abspath(__file__))
def parse_args():
parser = argparse.ArgumentParser(
description="Arguments for building pointnet2 ffi extension"
)
parser.add_argu... | 1,419 | 24.818182 | 72 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/pointnet2_utils.py | import torch
from torch.autograd import Variable
from torch.autograd import Function
import torch.nn.functional as F
import torch.nn as nn
import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
from linalg_utils import pdist2, PDist2Order
from collections import namedtuple
import... | 12,232 | 25.944934 | 103 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/linalg_utils.py | import torch
import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
from enum import Enum
PDist2Order = Enum('PDist2Order', 'd_first d_second')
def pdist2(
X: torch.Tensor,
Z: torch.Tensor = None,
order: PDist2Order = PDist2Order.d_second
) -> torch.Ten... | 2,256 | 26.52439 | 83 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/pointnet2_modules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
import pointnet2_utils
import pytorch_utils as pt_utils
from typing import List
import numpy as np
import time
import math
class _PointnetSAModuleBase(nn.Mod... | 9,474 | 33.32971 | 176 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/pytorch_utils/__init__.py | from .pytorch_utils import *
| 29 | 14 | 28 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/pytorch_utils/pytorch_utils.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.autograd.function import InplaceFunction
from itertools import repeat
import numpy as np
import shutil, os
from typing import List, Tuple
from scipy.stats import t as student_t
import statistics as stats
im... | 22,812 | 28.93832 | 141 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/rscnn_utils/_ext/pointnet2/__init__.py | import torch
from functools import wraps
try:
import cffi
except ImportError:
raise ImportError("torch.utils.ffi requires the cffi package")
if cffi.__version_info__ < (1, 4, 0):
raise ImportError("torch.utils.ffi requires cffi version >= 1.4, but "
"got " + '.'.join(map(str, cffi.__... | 2,743 | 33.3 | 87 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/ptcnn_utils/util_layers.py | import torch.nn as nn
from typing import Callable, Union, Tuple
from util_funcs import UFloatTensor
def EndChannels(f, make_contiguous = False):
""" Class decorator to apply 2D convolution along end channels. """
class WrappedLayer(nn.Module):
def __init__(self):
super(WrappedLayer, self... | 5,744 | 36.064516 | 102 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/ptcnn_utils/model.py | """
Author: Austin J. Garrett
PyTorch implementation of the PointCNN paper, as specified in:
https://arxiv.org/pdf/1801.07791.pdf
Original paper by: Yangyan Li, Rui Bu, Mingchao Sun, Baoquan Chen
"""
import os, sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
# External Modules
im... | 10,575 | 41.135458 | 106 | py |
3d-isometry-robust | 3d-isometry-robust-master/models/ptcnn_utils/util_funcs.py | # External Modules
import torch
from torch import cuda, FloatTensor, LongTensor
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors
from typing import Union
# Types to allow for both CPU and GPU models.
UFloatTensor = Union[FloatTensor, cuda.FloatTensor]
ULongTensor = Unio... | 2,631 | 38.283582 | 83 | py |
3d-isometry-robust | 3d-isometry-robust-master/data/transforms_3d.py | import numpy as np
import torch
class compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, pointcloud):
for t in self.transforms:
pointcloud = t(pointcloud)
return pointcloud
def __repr__(self):
format_string = self... | 3,723 | 35.509804 | 107 | py |
3d-isometry-robust | 3d-isometry-robust-master/data/data_class.py | import os
import h5py
import numpy as np
import glob
from torch.utils.data import Dataset
import json
from plyfile import PlyData, PlyElement
def load_data_s3dis(partition, point_num, data_dir='/mnt/dataset/s3dis/classification'):
h5_name = os.path.join(data_dir, partition + '_' + str(point_num) + '.hdf5')
all... | 5,757 | 33.479042 | 114 | py |
ZITS_inpainting | ZITS_inpainting-main/FTR_inference.py | import argparse
import os
import random
from shutil import copyfile
import cv2
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from src.FTR_trainer import ZITS
from src.config import Config
def main_worker(gpu, args):
rank = args.node_rank * args.gpus + gpu
... | 2,826 | 30.065934 | 90 | py |
ZITS_inpainting | ZITS_inpainting-main/single_image_test.py | import argparse
import os
import random
from shutil import copyfile
import cv2
import numpy as np
import torch
from src.lsm_hawp.detector import WireframeDetector
from src.FTR_trainer import ZITS
from src.config import Config
from skimage.color import rgb2gray
import torchvision.transforms.functional as FF
import torc... | 12,843 | 37.570571 | 117 | py |
ZITS_inpainting | ZITS_inpainting-main/TSR_train.py | import argparse
import logging
import os
import sys
import torch
from datasets.dataset_TSR import ContinuousEdgeLineDatasetMask, ContinuousEdgeLineDatasetMaskFinetune
from src.TSR_trainer import TrainerConfig, TrainerForContinuousEdgeLine, TrainerForEdgeLineFinetune
from src.models.TSR_model import EdgeLineGPT256RelBCE... | 6,722 | 54.561983 | 125 | py |
ZITS_inpainting | ZITS_inpainting-main/FTR_train.py | import argparse
import os
import random
from shutil import copyfile
import cv2
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from src.FTR_trainer import ZITS, LaMa
from src.config import Config
def main_worker(gpu, args):
rank = args.node_rank * args.gpus + ... | 3,072 | 29.425743 | 98 | py |
ZITS_inpainting | ZITS_inpainting-main/TSR_inference.py | import argparse
import os
import time
import cv2
import numpy as np
import torch
from tqdm import tqdm
from datasets.dataset_TSR import ContinuousEdgeLineDatasetMask
from src.models.TSR_model import EdgeLineGPTConfig, EdgeLineGPT256RelBCE
from src.utils import set_seed, SampleEdgeLineLogits
if __name__ == '__main__'... | 3,326 | 45.208333 | 118 | py |
ZITS_inpainting | ZITS_inpainting-main/lsm_hawp_inference.py | from src.lsm_hawp.lsm_hawp_model import LSM_HAWP
from glob import glob
import torch
import os
import argparse
parser = argparse.ArgumentParser(description='HAWP Testing')
parser.add_argument("--ckpt_path", type=str, required=True, help='ckpt path of HAWP')
parser.add_argument("--input_path", type=str, required=True, ... | 870 | 35.291667 | 94 | py |
ZITS_inpainting | ZITS_inpainting-main/src/TSR_trainer.py | import math
import os
import time
import cv2
import numpy as np
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm
try:
from apex import amp
except ImportErro... | 23,478 | 50.376368 | 143 | py |
ZITS_inpainting | ZITS_inpainting-main/src/inpainting_metrics.py | import os
from glob import glob
import cv2
import numpy as np
import torch
from scipy import linalg
from skimage.color import rgb2gray
from skimage.measure import compare_ssim
from torch.autograd import Variable
from torch.nn.functional import adaptive_avg_pool2d
from tqdm import tqdm
from src.models.inception import... | 11,475 | 38.30137 | 120 | py |
ZITS_inpainting | ZITS_inpainting-main/src/utils.py | import os
import random
import sys
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision.transforms.functional as FF
from PIL import Image
from torch.optim.lr_scheduler import LambdaLR
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(se... | 13,123 | 33.627968 | 119 | py |
ZITS_inpainting | ZITS_inpainting-main/src/FTR_trainer.py | import time
import torch
from torch.utils.data import DataLoader, RandomSampler
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm
from datasets.dataset_FTR import *
from src.models.FTR_model import *
from .inpainting_metrics import get_inpainting_metrics
from .utils import Progbar, cre... | 29,025 | 50.373451 | 140 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/inception.py | import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
class InceptionV3(nn.Module):
"""Pretrained InceptionV3 network returning feature maps"""
# Index of default block of inception to return,
# corresponds to output of final average pooling
DEFAULT_BLOCK_INDEX = 3
... | 4,872 | 34.057554 | 87 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/TSR_model.py | import logging
import torch
import torch.nn as nn
from torch.nn import functional as F
from .transformer import BlockAxial, my_Block_2
logger = logging.getLogger(__name__)
class EdgeLineGPTConfig:
""" base GPT config, params common to all GPT versions """
embd_pdrop = 0.1
resid_pdrop = 0.1
attn_pdr... | 8,162 | 36.273973 | 120 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/layers.py | import torch
import torch.nn as nn
class GateConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, transpose=False):
super(GateConv, self).__init__()
self.out_channels = out_channels
if transpose:
self.gate_conv = nn.ConvTranspose2d(... | 3,365 | 37.689655 | 139 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/LaMa.py | import numpy as np
from .ffc import *
from .layers import *
class ResnetBlock_remove_IN(nn.Module):
def __init__(self, dim, dilation=1):
super(ResnetBlock_remove_IN, self).__init__()
self.ffc1 = FFC_BN_ACT(dim, dim, 3, 0.75, 0.75, stride=1, padding=1, dilation=dilation, groups=1, bias=False,
... | 11,913 | 33.04 | 118 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/transformer.py | import logging
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
logger = logging.getLogger(__name__)
def gelu(x):
"""Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
... | 9,295 | 36.184 | 104 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/FTR_model.py | import os
from src.losses.adversarial import NonSaturatingWithR1
from src.losses.feature_matching import masked_l1_loss, feature_matching_loss
from src.losses.perceptual import ResNetPL
from src.models.LaMa import *
from src.models.TSR_model import *
from src.models.upsample import StructureUpsampling
from src.utils i... | 26,744 | 47.189189 | 121 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ffc.py | import torch
import torch.nn as nn
class FourierUnit(nn.Module):
def __init__(self, in_channels, out_channels, groups=1, spectral_pos_encoding=False, fft_norm='ortho'):
# bn_layer not used
super(FourierUnit, self).__init__()
self.groups = groups
self.fft_norm = fft_norm
s... | 7,710 | 39.371728 | 120 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/upsample.py | import torch.nn as nn
import torch.nn.functional as F
class StructureUpsampling(nn.Module):
def __init__(self):
super().__init__()
self.convs = nn.Sequential(nn.ReflectionPad2d(3),
nn.Conv2d(1, 64, kernel_size=7, stride=1, padding=0),
... | 1,169 | 40.785714 | 89 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/base.py | """Modified from https://github.com/CSAILVision/semantic-segmentation-pytorch"""
import os
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.io import loadmat
from torch.nn.modules import BatchNorm2d
from . import mobilenet
from . import resnet
NUM_CLASS = 150
base_pa... | 23,089 | 35.826156 | 138 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/resnet.py | """Modified from https://github.com/CSAILVision/semantic-segmentation-pytorch"""
import math
import torch.nn as nn
from torch.nn import BatchNorm2d
from .utils import load_url
__all__ = ['ResNet', 'resnet50']
model_urls = {
'resnet50': 'http://sceneparsing.csail.mit.edu/model/pretrained_resnet/resnet50-imagen... | 5,502 | 29.403315 | 98 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/utils.py | """Modified from https://github.com/CSAILVision/semantic-segmentation-pytorch"""
import os
import sys
import numpy as np
import torch
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
def load_url(url, model_dir='./pretrained', map_location=None):
if not os.... | 1,229 | 29 | 80 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/mobilenet.py | """
This MobileNetV2 implementation is modified from the following repository:
https://github.com/tonylins/pytorch-mobilenet-v2
"""
import math
import torch.nn as nn
from .segm_lib.nn import SynchronizedBatchNorm2d
from .utils import load_url
BatchNorm2d = SynchronizedBatchNorm2d
__all__ = ['mobilenetv2']
model... | 4,934 | 30.634615 | 100 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/nn/modules/replicate.py | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | 3,226 | 32.968421 | 115 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/nn/modules/unittest.py | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... | 835 | 26.866667 | 157 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/nn/modules/batchnorm.py | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... | 13,812 | 40.984802 | 127 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/nn/modules/tests/test_sync_batchnorm.py | # -*- coding: utf-8 -*-
# File : test_sync_batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
import unittest
import torch
import torch.nn as nn
from sync_batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2... | 3,570 | 31.171171 | 109 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/nn/modules/tests/test_numeric_batchnorm.py | # -*- coding: utf-8 -*-
# File : test_numeric_batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
import unittest
import torch
import torch.nn as nn
from sync_batchnorm.unittest import TorchTestCase
from torch.autograd i... | 1,614 | 27.839286 | 85 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/nn/parallel/data_parallel.py | # -*- coding: utf8 -*-
import collections
import torch
import torch.cuda as cuda
import torch.nn as nn
from torch.nn.parallel._functions import Gather
__all__ = ['UserScatteredDataParallel', 'user_scattered_collate', 'async_copy_to']
def async_copy_to(obj, dev, main_stream=None):
if torch.is_tensor(obj):
... | 3,399 | 29.088496 | 82 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/utils/th.py | import collections
import numpy as np
import torch
from torch.autograd import Variable
__all__ = ['as_variable', 'as_numpy', 'mark_volatile']
def as_variable(obj):
if isinstance(obj, Variable):
return obj
if isinstance(obj, collections.Sequence):
return [as_variable(v) for v in obj]
elif ... | 1,238 | 27.813953 | 60 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/utils/data/sampler.py | import torch
class Sampler(object):
"""Base class for all Samplers.
Every Sampler subclass has to provide an __iter__ method, providing a way
to iterate over indices of dataset elements, and a __len__ method that
returns the length of the returned iterators.
"""
def __init__(self, data_sourc... | 3,761 | 27.5 | 88 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/utils/data/dataloader.py | import torch
import torch.multiprocessing as multiprocessing
from torch._C import _set_worker_signal_handlers, \
_remove_worker_pids, _error_if_any_worker_fails
try:
from torch._C import _set_worker_pids
except:
from torch._C import _update_worker_pids as _set_worker_pids
from .sampler import SequentialSamp... | 16,207 | 37.046948 | 102 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/utils/data/dataset.py | import bisect
import warnings
from torch import randperm
from torch._utils import _accumulate
class Dataset(object):
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and ``__getitem__``,... | 3,465 | 28.12605 | 118 | py |
ZITS_inpainting | ZITS_inpainting-main/src/models/ade20k/segm_lib/utils/data/distributed.py | import math
import torch
from torch.distributed import get_world_size, get_rank
from .sampler import Sampler
class DistributedSampler(Sampler):
"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParalle... | 1,966 | 31.245902 | 86 | py |
ZITS_inpainting | ZITS_inpainting-main/src/lsm_hawp/stacked_hg.py | """
Hourglass network inserted in the pre-activated Resnet
Use lr=0.01 for current version
(c) Nan Xue (HAWP)
(c) Yichao Zhou (LCNN)
(c) YANG, Wei
"""
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck2D(nn.Module):
expansion = 2
def __init__(self, inplanes, planes, stride=1, downsample=N... | 5,897 | 31.949721 | 116 | py |
ZITS_inpainting | ZITS_inpainting-main/src/lsm_hawp/lsm_hawp_model.py | import torch
from .detector import WireframeDetector
from tqdm import tqdm
import torchvision.transforms as transforms
import os
import numpy as np
from skimage import io
from torchvision.transforms import functional as F
from skimage.transform import resize
import pickle
class ResizeImage(object):
def __init__(s... | 5,136 | 38.821705 | 112 | py |
ZITS_inpainting | ZITS_inpainting-main/src/lsm_hawp/detector.py | import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .model_config import get_config
from .multi_task_head import MultitaskHead
from .stacked_hg import HourglassNet, Bottleneck2D
def build_hg(cfg):
inplanes = cfg.MODEL.HGNETS.INPLANES
num_feats = cfg.MODEL.OUT_FEATURE_CHA... | 9,647 | 37.903226 | 121 | py |
ZITS_inpainting | ZITS_inpainting-main/src/lsm_hawp/multi_task_head.py | import torch
import torch.nn as nn
class MultitaskHead(nn.Module):
def __init__(self, input_channels, num_class, head_size):
super(MultitaskHead, self).__init__()
m = int(input_channels / 4)
heads = []
for output_channels in sum(head_size, []):
heads.append(
... | 745 | 30.083333 | 75 | py |
ZITS_inpainting | ZITS_inpainting-main/src/losses/feature_matching.py | from typing import List
import torch
import torch.nn.functional as F
def masked_l2_loss(pred, target, mask, weight_known, weight_missing):
per_pixel_l2 = F.mse_loss(pred, target, reduction='none')
pixel_weights = mask * weight_missing + (1 - mask) * weight_known
return (pixel_weights * per_pixel_l2).mean... | 1,313 | 37.647059 | 109 | py |
ZITS_inpainting | ZITS_inpainting-main/src/losses/adversarial.py | from typing import Tuple, Dict, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class BaseAdversarialLoss:
def pre_generator_step(self, real_batch: torch.Tensor, fake_batch: torch.Tensor,
generator: nn.Module, discriminator: nn.Module):
"""
P... | 7,902 | 46.041667 | 111 | py |
ZITS_inpainting | ZITS_inpainting-main/src/losses/perceptual.py | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from ..models.ade20k import ModelBuilder
def check_and_warn_input_range(tensor, min_value, max_value, name):
actual_min = tensor.min()
actual_max = tensor.max()
if actual_min < min_value or actual_max >... | 4,424 | 34.97561 | 116 | py |
ZITS_inpainting | ZITS_inpainting-main/datasets/dataset_TSR.py | import os
import random
import sys
from glob import glob
import cv2
import numpy as np
import torchvision.transforms.functional as F
from skimage.color import rgb2gray
from skimage.feature import canny
from torch.utils.data import Dataset
import pickle
import skimage.draw
sys.path.append('..')
def to_int(x):
re... | 8,813 | 38.348214 | 126 | py |
ZITS_inpainting | ZITS_inpainting-main/datasets/dataset_FTR.py | import glob
import os
import pickle
import random
import cv2
import numpy as np
import skimage.draw
import torch
import torchvision.transforms.functional as F
from skimage.color import rgb2gray
from skimage.feature import canny
from torch.utils.data import DataLoader
def to_int(x):
return tuple(map(int, x))
cl... | 18,590 | 38.471338 | 125 | py |
relative-entropy | relative-entropy-main/setup.py | from setuptools import setup, find_packages
install_requires = [
'jax>=0.4.3',
'jax-md>=0.2.5',
'optax>=0.0.9',
'dm-haiku>=0.0.9',
'sympy',
'cloudpickle',
'chex',
'jax-sgmc',
]
extras_requires = {
'all': ['mdtraj<=1.9.6', 'matplotlib'],
}
with open('README.md', 'rt') as f:
... | 1,344 | 27.020833 | 71 | py |
relative-entropy | relative-entropy-main/examples/alanine_dipeptide/visualization.py | """Plot functions to visualize free energy surface of alanine dipeptide."""
from jax import numpy as jnp
from matplotlib.animation import FuncAnimation
import matplotlib.colors as clr
import matplotlib.pyplot as plt
import numpy as onp
from scipy.interpolate import interp1d
def plot_scatter_forces(predicted, referenc... | 13,593 | 37.729345 | 80 | py |
relative-entropy | relative-entropy-main/examples/alanine_dipeptide/alanine_simulation.py | """Forward simulation of alanine dipeptide."""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import warnings
warnings.filterwarnings('ignore') # disable warnings about float64 usage
import cloudpickle as pickle
from pathlib import Path
import time
from jax import vmap, random, tree_util, numpy as jnp
from jax_... | 6,160 | 36.567073 | 80 | py |
relative-entropy | relative-entropy-main/examples/alanine_dipeptide/alanine_force_matching.py | """Training a CG model for alanine dipeptide via force matching."""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import warnings
warnings.filterwarnings('ignore') # disable warnings about float64 usage
import cloudpickle as pickle
from pathlib import Path
from jax import random
from jax_md import space
import... | 3,476 | 32.114286 | 80 | py |
relative-entropy | relative-entropy-main/examples/alanine_dipeptide/alanine_relative_entropy.py | """Training a CG model of alanine dipeptide via relative entropy minimization.
"""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import warnings
warnings.filterwarnings('ignore') # disable warnings about float64 usage
from pathlib import Path
from jax import random
import optax
from chemtrain import trainers,... | 3,016 | 31.095745 | 78 | py |
relative-entropy | relative-entropy-main/examples/water/CG_water_simulation.py | """Runs a CG water simulation in Jax M.D with loaded parameters.
Trajectory generation for postprocessing and analysis of simulations.
"""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import warnings
warnings.filterwarnings('ignore') # disable warnings about float64 usage
from pathlib import Path
import time
... | 5,613 | 38.258741 | 80 | py |
relative-entropy | relative-entropy-main/examples/water/CG_water_relative_entropy.py | """Training a CG water model via relative entropy minimization."""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import warnings
warnings.filterwarnings('ignore') # disable warnings about float64 usage
from pathlib import Path
from jax import numpy as jnp
import numpy as onp
import optax
from chemtrain import... | 2,583 | 28.033708 | 78 | py |
relative-entropy | relative-entropy-main/examples/water/CG_water_force_matching.py | """Train a CG water model via force matching."""
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import warnings
warnings.filterwarnings('ignore') # disable warnings about float64 usage
import cloudpickle as pickle
from pathlib import Path
from jax import random, numpy as jnp
from jax_md import space
import matp... | 3,414 | 31.216981 | 77 | py |
relative-entropy | relative-entropy-main/chemtrain/sparse_graph.py | """Functions to extract the sparse directional graph representation of a
molecular state.
The :class:`SparseDirectionalGraph` is the input to
:class:`~chemtrain.neural_networks.DimeNetPP`.
"""
import inspect
from typing import Optional, Callable, Tuple
import chex
from jax import numpy as jnp, vmap, lax
from jax_md i... | 16,032 | 43.290055 | 122 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.