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 |
|---|---|---|---|---|---|---|
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/utils/__init__.py | from torch_ac.utils.dictlist import DictList
from torch_ac.utils.penv import ParallelEnv | 88 | 43.5 | 44 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
import torch_ac
# Function from https://github.com/ikostrikov/pytorch-a2c-ppo-acktr/blob/master/model.py
def init_params(m):
classname = m.__class__.__name__
if classname.find("Linear") !... | 3,419 | 30.090909 | 104 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/scripts/evaluate.py | import argparse
import time
import torch
from torch_ac.utils.penv import ParallelEnv
import utils
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--env", required=True,
help="name of the environment (REQUIRED)")
parser.add_argument("--model", required=True,
... | 3,823 | 32.54386 | 117 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/scripts/train.py | import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import utils
from model import ACModel
import numpy as np
# Parse arguments
parser = argparse.ArgumentParser()
## General parameters
parser.add_argument("--algo", required=True,
help="algorit... | 8,994 | 39.15625 | 174 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/scripts/visualize.py | import argparse
import time
import numpy
import torch
import utils
import csv
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--env", required=True,
help="name of the environment to be run (REQUIRED)")
parser.add_argument("--model", required=True,
h... | 3,584 | 32.194444 | 101 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/utils/storage.py | import csv
import os
import torch
import logging
import sys
import utils
def create_folders_if_necessary(path):
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
def get_storage_dir():
if "RL_STORAGE" in os.environ:
return os.environ["RL_STORAGE"]
r... | 1,478 | 20.128571 | 54 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/utils/format.py | import os
import json
import numpy
import re
import torch
import torch_ac
import gym
import utils
def get_obss_preprocessor(obs_space):
# Check if obs_space is an image space
if isinstance(obs_space, gym.spaces.Box):
obs_space = {"image": obs_space.shape}
def preprocess_obss(obss, device=Non... | 2,574 | 30.790123 | 96 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/utils/agent.py | import torch
import utils
from model import ACModel
class Agent:
"""An agent.
It is able:
- to choose an action given an observation,
- to analyze the feedback (i.e. reward and done state) of its action."""
def __init__(self, obs_space, action_space, model_dir,
device=None, arg... | 1,957 | 33.350877 | 100 | py |
RE3 | RE3-master/a2c_re3/rl-starter-files/rl-starter-files/utils/other.py | import random
import numpy
import torch
import collections
def seed(seed):
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def synthesize(array):
d = collections.OrderedDict()
d["mean"] = numpy.mean(arra... | 434 | 18.772727 | 40 | py |
RE3 | RE3-master/rad_re3/utils.py | import math
import os
import random
from collections import deque
import numpy as np
import scipy.linalg as sp_la
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
from skimage.util.shape import view_as_windows
from torch import distributions as pyd
class eval_mode(object):
def __ini... | 6,950 | 28.705128 | 137 | py |
RE3 | RE3-master/rad_re3/logger.py | import csv
import json
import os
import shutil
from collections import defaultdict
import numpy as np
import torch
import torchvision
from termcolor import colored
from torch.utils.tensorboard import SummaryWriter
COMMON_TRAIN_FORMAT = [
("episode", "E", "int"),
("step", "S", "int"),
("episode_reward", "... | 8,039 | 33.212766 | 87 | py |
RE3 | RE3-master/rad_re3/replay_buffer.py | import numpy as np
import kornia
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
import hydra
import utils
import random
class ReplayBuffer(object):
"""Buffer to store environment transitions."""
def __init__(
self,
obs_shape,
action_shape,
sta... | 5,254 | 34.268456 | 87 | py |
RE3 | RE3-master/rad_re3/train.py | import copy
import math
import os
import pickle as pkl
import sys
import time
import numpy as np
import dmc2gym
import hydra
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
from logger import Logger
from replay_buffer import ReplayBuffer
from video import VideoRecorder
torch.backends.... | 6,249 | 30.407035 | 115 | py |
RE3 | RE3-master/rad_re3/re3.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
import math
import utils
import hydra
import kornia
import os
class Encoder(nn.Module):
"""Convolutional encoder for image-based observations."""
def __init__(self, image_size, feature_dim, k, channel):
... | 16,349 | 32.367347 | 88 | py |
BIF | BIF-main/main.py | import logging
import os
import sys
import numpy as np
import torch
import utils
import experiments
def main():
args = utils.get_args()
if os.path.exists(args.save_dir) == False:
os.makedirs(args.save_dir)
fmt = '%(asctime)s %(name)s:%(levelname)s: %(message)s'
formatter = logging.Formatte... | 1,374 | 23.553571 | 103 | py |
BIF | BIF-main/bayes_forgetters/bif_forgetter.py | import torch
class bifForgetter():
''' Implementation of Bayesian inference forgetting (BIF) forgetter.
It will first calculate the following function I(target):
I(target) = -H_theta^(-1) @ G_theta
and then remove the influence from model parameter as follow:
theta_new = theta + (-1) *... | 4,599 | 33.074074 | 113 | py |
BIF | BIF-main/bayes_forgetters/vi_forgetter.py | from .bif_forgetter import bifForgetter
class viForgetter(bifForgetter):
def __init__(self, model, params, cpu, iter_T, scaling):
super(viForgetter, self).__init__(
model, params, cpu, iter_T, scaling)
class vbnnForgetter(bifForgetter):
''' variational Bayesian neural network forgetter
... | 1,502 | 31.673913 | 68 | py |
BIF | BIF-main/bayes_forgetters/sgmcmc_forgetter.py | from .bif_forgetter import bifForgetter
class sgmcmcForgetter(bifForgetter):
''' bifForgetter for SGMCMC
Args:
optimizer (torch.optim): sgmcmc optimizer that used to
sample (update) model parameter (i.e., params) for
estimating the expectation terms in I(target... | 3,142 | 35.976471 | 114 | py |
BIF | BIF-main/models/normal_models.py | import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
from . import bayes_nn
from .bayes_nn import normalLinear as Linear
from .bayes_nn import normalConv2d as Conv2d
# from .bayes_nn import normalBatchNorm2d as BatchNorm2d
class normalArch(nn.Module):
def __init__(self):
s... | 2,094 | 29.808824 | 66 | py |
BIF | BIF-main/models/gmm.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class VariationalGMM(nn.Module):
def __init__(self, kk, dim, std, n):
super(VariationalGMM, self).__init__()
self.kk = kk
self.dim = dim
self.n = n
... | 3,121 | 29.910891 | 90 | py |
BIF | BIF-main/models/mcmc_models.py | import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
from . import bayes_nn
from .bayes_nn import mcmcLinear as Linear
from .bayes_nn import mcmcConv2d as Conv2d
class mcmcArch(nn.Module):
def __init__(self):
super(mcmcArch, self).__init__()
self.__dict__['_mcmc_m... | 2,068 | 28.985507 | 64 | py |
BIF | BIF-main/models/bayes_nn/mcmc_modules.py | import numpy as np
import torch
import torch.nn as nn
class mcmcModule(nn.Module):
def log_prior(self):
res = - (self.weight ** 2).sum() / (2 * self.prior_sig**2)
if self.bias is not None:
res += - (self.bias ** 2).sum() / (2 * self.prior_sig**2)
return res
class mcmcLinear(n... | 660 | 26.541667 | 69 | py |
BIF | BIF-main/models/bayes_nn/normal_modules.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch._six import container_abcs
from itertools import repeat
class normalModule(nn.Module):
''' This is the base module to support Bayesian neural network (BNN)
with mean-field... | 6,148 | 35.60119 | 120 | py |
BIF | BIF-main/experiments/gmm_simulation.py | from datetime import datetime
import pickle
import logging
import numpy as np
import torch
import bayes_forgetters
import models
import utils
from .base_experiment import BaseExperiment
logger = logging.getLogger()
class GMMForgetter(bayes_forgetters.viForgetter):
def _fun(self, z):
x = z[0]
if... | 10,250 | 32.720395 | 107 | py |
BIF | BIF-main/experiments/base_experiment.py | import pickle
import logging
import numpy as np
import torch
import models
import utils
logger = logging.getLogger()
class BaseExperiment():
def __init__(self, args):
self.save_dir = args.save_dir
self.burn_in_steps = args.burn_in_steps
self.eval_freq = args.eval_freq
self.cpu =... | 4,804 | 32.838028 | 82 | py |
BIF | BIF-main/experiments/deep_learning.py | from datetime import datetime
import logging
import pickle
import numpy as np
import torch
import torch.nn.functional as F
import bayes_forgetters
import models
import utils
from .base_experiment import BaseExperiment
logger = logging.getLogger()
class viForgetter(bayes_forgetters.vbnnForgetter):
def _fun(self... | 12,456 | 33.893557 | 100 | py |
BIF | BIF-main/utils/data.py | ''' We manually implemented data loader in order to support
fast-data-removing from dataset. Specifically, in our simulation experiments, to remove a particular example, we do not need
to actually remove the target example from RAM, but to remove
the corresponding index is sufficient, which can reduce
unnecessary IO ti... | 4,086 | 29.274074 | 124 | py |
BIF | BIF-main/utils/generic.py | import torch
import torchvision.transforms as transforms
from . import sgmcmc_optim
from . import datasets
class AverageMeter():
def __init__(self):
self.cnt = 0
self.sum = 0
self.mean = 0
def update(self, val, cnt):
self.cnt += cnt
self.sum += val * cnt
self.... | 2,896 | 29.494737 | 77 | py |
BIF | BIF-main/utils/datasets/torchvision_datasets.py | import torchvision
def MNIST(root='./path', train=True, transform=None):
return torchvision.datasets.MNIST(root=root, train=train,
transform=transform, download=True)
def FashionMNIST(root='./path', train=True, transform=None):
return torchvision.datasets.FashionMNIST(root=root, train=... | 568 | 39.642857 | 68 | py |
BIF | BIF-main/utils/datasets/__init__.py | from .gmm_datasets import GMM2d
from .torchvision_datasets import MNIST, FashionMNIST, CIFAR10 | 94 | 46.5 | 62 | py |
BIF | BIF-main/utils/sgmcmc_optim/sgld.py | import numpy as np
import torch
''' References:
[1] https://www.ics.uci.edu/~welling/publications/papers/stoclangevin_v6.pdf
[2] https://github.com/pytorch/pytorch/blob/master/torch/optim/sgd.py
'''
class SGLD(torch.optim.Optimizer):
def __init__(self, params, lr):
defaults = dict(lr=lr)
su... | 983 | 26.333333 | 80 | py |
BIF | BIF-main/utils/sgmcmc_optim/sghmc.py | import numpy as np
import torch
''' References:
[1] https://arxiv.org/pdf/1402.4102.pdf
[2] https://github.com/pytorch/pytorch/blob/master/torch/optim/sgd.py
'''
class SGHMC(torch.optim.Optimizer):
def __init__(self, params, lr, alpha, lr_decay=1.0):
defaults = dict(lr=lr, alpha=alpha, lr_decay=lr... | 1,529 | 30.22449 | 84 | py |
pytorch-deform-conv | pytorch-deform-conv-master/scaled_mnist.py | from __future__ import absolute_import, division
# %env CUDA_VISIBLE_DEVICES=0
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch_deform_conv.layers import ConvOffset2D
from torch_deform_conv.cnn import get_cnn, get_deform_cnn
fro... | 3,702 | 27.05303 | 81 | py |
pytorch-deform-conv | pytorch-deform-conv-master/tests/test_deform_conv.py | import numpy as np
import torch
from torch.autograd import Variable
from scipy.ndimage.interpolation import map_coordinates
from torch_deform_conv.deform_conv import (
th_map_coordinates,
sp_batch_map_coordinates, th_batch_map_coordinates,
sp_batch_map_offsets, th_batch_map_offsets
)
def test_th_map_coor... | 2,120 | 33.209677 | 78 | py |
pytorch-deform-conv | pytorch-deform-conv-master/torch_deform_conv/deform_conv.py | from __future__ import absolute_import, division
import torch
from torch.autograd import Variable
import numpy as np
from scipy.ndimage.interpolation import map_coordinates as sp_map_coordinates
def th_flatten(a):
"""Flatten tensor"""
return a.contiguous().view(a.nelement())
def th_repeat(a, repeats, axis... | 6,144 | 31.342105 | 142 | py |
pytorch-deform-conv | pytorch-deform-conv-master/torch_deform_conv/cnn.py | from __future__ import absolute_import, division
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch_deform_conv.layers import ConvOffset2D
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
# conv11
self.conv11 = nn.Conv2d(1, 32, 3, pa... | 3,415 | 26.328 | 89 | py |
pytorch-deform-conv | pytorch-deform-conv-master/torch_deform_conv/layers.py | from __future__ import absolute_import, division
import torch
import torch.nn as nn
import numpy as np
from torch_deform_conv.deform_conv import th_batch_map_offsets, th_generate_grid
class ConvOffset2D(nn.Conv2d):
"""ConvOffset2D
Convolutional layer responsible for learning the 2D offsets and output the
... | 3,001 | 32.730337 | 108 | py |
pytorch-deform-conv | pytorch-deform-conv-master/torch_deform_conv/mnist.py | from __future__ import absolute_import, division
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
def get_mnist_dataset():
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255
... | 920 | 26.909091 | 70 | py |
3dcertify | 3dcertify-master/verify_segmentation.py | import argparse
import itertools
from functools import partial
import numpy as np
import onnx
import torch
from tqdm import tqdm
from data_processing import datasets
from pointnet.segmentation_model import PointNetSegmentation
from relaxations import taylor
from relaxations.interval import Interval
from relaxations.r... | 7,424 | 45.40625 | 182 | py |
3dcertify | 3dcertify-master/eval_rotation.py | import argparse
import logging
import os
import sys
from typing import Tuple
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from data_processing import datasets
from pointnet.model import PointNet
from util import rotation
from util.math import set_... | 7,784 | 41.774725 | 123 | py |
3dcertify | 3dcertify-master/train_lirpa.py | import argparse
import multiprocessing
import random
import time
import torch.optim as optim
from auto_LiRPA.eps_scheduler import LinearScheduler, AdaptiveScheduler, SmoothedScheduler, FixedScheduler
from auto_LiRPA.perturbations import *
from auto_LiRPA.utils import MultiAverageMeter
from torch.nn import CrossEntropy... | 10,054 | 46.429245 | 136 | py |
3dcertify | 3dcertify-master/train_classification.py | import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from data_processing import datasets
from pointnet import attacks
from pointnet.model import Point... | 6,882 | 37.452514 | 147 | py |
3dcertify | 3dcertify-master/train_segmentation.py | import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from data_processing import datasets
from pointnet import attacks
from pointnet.segmentation_model... | 6,763 | 37.651429 | 168 | py |
3dcertify | 3dcertify-master/verify_lirpa.py | import argparse
import numpy as np
import torch
from auto_LiRPA.perturbations import *
from tqdm import tqdm
from auto_LiRPA import BoundedModule, BoundedTensor
from data_processing import datasets
from lirpa_integration import SemanticTransformation
from pointnet.model import PointNet
from relaxations.interval impor... | 4,261 | 36.385965 | 171 | py |
3dcertify | 3dcertify-master/verify_deepg_segmentation.py | import argparse
import numpy as np
import onnx
import torch
from tqdm import tqdm
from data_processing import datasets
from pointnet.segmentation_model import PointNetSegmentation
from relaxations.deepg_bounds import load_spec
from transformations.rotation import RotationZ
from util import onnx_converter
from util.ar... | 5,154 | 40.910569 | 150 | py |
3dcertify | 3dcertify-master/verify_transformation.py | import argparse
import itertools
from functools import partial
import numpy as np
import onnx
import onnxruntime
import torch
from tqdm import tqdm
from data_processing import datasets
from pointnet.model import PointNet
from relaxations import taylor
from relaxations.interval import Interval
from relaxations.refine_... | 7,878 | 43.264045 | 184 | py |
3dcertify | 3dcertify-master/eval_perturbation.py | import argparse
import logging
import os
import sys
from typing import Tuple
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from data_processing import datasets
from pointnet import attacks
from pointnet.model import PointNet
from util import rotati... | 6,413 | 39.339623 | 119 | py |
3dcertify | 3dcertify-master/verify_perturbation.py | import argparse
from timeit import default_timer as timer
import numpy as np
import onnx
import onnxruntime
import torch
from data_processing import datasets
from pointnet.model import PointNet
from relaxations.interval import Interval
from util import onnx_converter
from util.argparse import absolute_path
from util.... | 4,654 | 37.471074 | 132 | py |
3dcertify | 3dcertify-master/verify_deepg.py | import argparse
import numpy as np
import onnx
import onnxruntime
import torch
from tqdm import tqdm
from data_processing import datasets
from pointnet.model import PointNet
from relaxations.deepg_bounds import load_spec
from util import onnx_converter
from util.argparse import absolute_path
from util.experiment impo... | 4,797 | 36.484375 | 125 | py |
3dcertify | 3dcertify-master/lirpa_integration.py | import numpy as np
import torch
from auto_LiRPA.perturbations import Perturbation
from auto_LiRPA.utils import LinearBound
from relaxations import taylor
class SemanticTransformation(Perturbation):
def __init__(self, transformation, params):
super().__init__()
self.transformation = transformatio... | 3,564 | 46.533333 | 129 | py |
3dcertify | 3dcertify-master/util/math.py | import random
import numpy as np
import torch
DEFAULT_SEED = 1823453073
def set_random_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def mean_point_iou(prediction, actual):
sum_iou = 0.0
classes = np.unique(actual)
for cl in classes:
cl_prediction ... | 1,032 | 26.184211 | 98 | py |
3dcertify | 3dcertify-master/util/onnx_converter.py | import onnx
import torch.nn as nn
import torch.onnx
from util import translate_onnx
def __export(model: nn.Module, num_points: int, file):
dummy_batch_size = 1
input_features = 3
dummy_input = torch.randn(dummy_batch_size, input_features, num_points)
torch.onnx.export(model, (dummy_input,), file, ver... | 589 | 27.095238 | 75 | py |
3dcertify | 3dcertify-master/util/rotation.py | import numpy as np
import torch
from scipy.spatial.transform import Rotation
def rotation_matrix_z(theta: float) -> np.ndarray:
rotation: Rotation = Rotation.from_euler('z', theta)
return rotation.as_matrix()
def rotation_matrix_so3(theta: np.ndarray) -> np.ndarray:
assert len(theta) == 3
rotation: ... | 1,900 | 38.604167 | 119 | py |
3dcertify | 3dcertify-master/data_processing/transformers.py | import os
import h5py
import numpy as np
import torch
from torch.utils.data import Dataset
from util import rotation
class HDF5Loader(Dataset):
# source: https://shapenet.cs.stanford.edu/media/modelnet40_ply_hdf5_2048.zip
def __init__(self, data_dir, train=True, num_points=1024, transform=None):
tr... | 8,888 | 28.729097 | 116 | py |
3dcertify | 3dcertify-master/data_processing/datasets.py | import os.path
from torch_geometric import datasets
from torchvision.transforms import transforms
from data_processing import transformers
__DATASET_ROOT = "./data/"
def modelnet40(num_points: int = 1024, split: str = 'train', rotate: str = 'z', add_noise: bool = None) -> datasets.modelnet.ModelNet:
dataset_ro... | 3,676 | 35.77 | 134 | py |
3dcertify | 3dcertify-master/pointnet/loss.py | import torch
def orthogonal_normalizer(matrix):
# Expected shape: (batch_size, n, n)
assert matrix.size()[1] == matrix.size()[2]
matrix_size = matrix.size()[1]
batch_size = matrix.size()[0]
identity = torch.eye(n=matrix_size, device=matrix.device)
identity = identity.expand(batch_size, matrix... | 670 | 38.470588 | 111 | py |
3dcertify | 3dcertify-master/pointnet/model.py | import torch
import torch.nn as nn
class TNet(nn.Module):
def __init__(self, number_points, num_features):
super(TNet, self).__init__()
self.num_features = num_features
self.mlp1 = nn.Sequential(
nn.Conv1d(in_channels=num_features, out_channels=64, kernel_size=1),
... | 7,496 | 37.25 | 120 | py |
3dcertify | 3dcertify-master/pointnet/attacks.py | import torch
import torch.nn as nn
class Domain:
def project(self, x: torch.Tensor) -> torch.Tensor:
pass
def random_point(self) -> torch.Tensor:
pass
class EpsBox(Domain):
def __init__(self, points: torch.Tensor, eps: float):
super(EpsBox, self).__init__()
self.points... | 3,192 | 29.701923 | 102 | py |
3dcertify | 3dcertify-master/pointnet/segmentation_model.py | import torch
import torch.nn as nn
def mlp_block(in_channels: int, out_channels: int) -> nn.Module:
return nn.Sequential(
nn.Conv1d(in_channels, out_channels, kernel_size=1),
nn.BatchNorm1d(out_channels),
nn.ReLU()
)
class PointNetSegmentation(nn.Module):
def __init__(self, numb... | 5,471 | 36.22449 | 119 | py |
nkca | nkca-main/src/nkca/model.py | import abc
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from nkca import session
from . import distribution as distr
from .primitives import Block, SinusoidalPosEmb, UNet
def _noise_schedule_continuous(noise_level: torch.T... | 10,059 | 32.421927 | 90 | py |
nkca | nkca-main/src/nkca/distribution.py | import dataclasses
import numpy as np
import torch
from .util import iterable_dataclass
class Distribution:
pass
@iterable_dataclass
@dataclasses.dataclass
class Categorical(Distribution):
logits: torch.Tensor
@iterable_dataclass
@dataclasses.dataclass
class Normal(Distribution):
mu: torch.Tensor
... | 2,023 | 23.987654 | 87 | py |
nkca | nkca-main/src/nkca/sampling.py | from typing import Any, Callable, Iterator
import torch
from tqdm import tqdm
from . import distribution as distr
from .util import to_device
def run_markov_chain(
noise_kernel: Callable[
[torch.Tensor, torch.Tensor, torch.Tensor],
tuple[distr.Distribution, Any],
],
x0: torch.Tensor,
... | 1,008 | 30.53125 | 78 | py |
nkca | nkca-main/src/nkca/datasets.py | import os
import numpy as np
import torch
import torch.utils.data as data
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from torchvision.datasets import ImageFolder
from .util import map_tree
class TransformedDataset(data.Dataset):
def __init__(self, dataset, transform=None):... | 2,113 | 23.581395 | 68 | py |
nkca | nkca-main/src/nkca/primitives.py | """
Implements U-Net with residual blocks and linear self-attention. Borrows heavily
from Hoogeboom et al. (2021):
https://github.com/ehoogeboom/multinomial_diffusion/blob/main/segmentation_diffusion/layers/layers.py
"""
import math
import torch
import torch.nn as nn
import torchvision.transforms.functional as TF
fro... | 6,477 | 29.130233 | 101 | py |
nkca | nkca-main/src/nkca/util.py | import dataclasses
from contextlib import contextmanager
from copy import deepcopy
from typing import Any, Callable, OrderedDict
import attr
import torch
import torch.nn as nn
def zip_dicts(*ds):
return {k: tuple(d[k] for d in ds) for k in ds[0]}
def map_tree(fn: Callable, x1: Any, *xs: Any) -> Any:
match ... | 2,072 | 24.592593 | 81 | py |
nkca | nkca-main/src/nkca_cli/sample.py | import datetime
import itertools as it
import os
import sys
import fire
import functorch as ft
import imageio as ii
import numpy as np
import torch
import torch.nn as nn
from effecthandlers_logging import TextLogger, log_info
from tabulate import tabulate
from torchvision.utils import make_grid
from tqdm import tqdm
... | 9,856 | 34.974453 | 87 | py |
nkca | nkca-main/src/nkca_cli/datasets.py | import torch
from nkca import datasets, session
def to_image(x: torch.Tensor) -> torch.Tensor:
"""Converts data to floating point image with values in [0,1]"""
if not session.get("discrete"):
return torch.clamp((x + 1) / 2, 0, 1)
num_classes = session.get("num_classes")
return x.float() / (nu... | 933 | 27.30303 | 74 | py |
nkca | nkca-main/src/nkca_cli/interactive.py | import sys
import fire
import functorch as ft
import numpy as np
import pygame
import torch
import torch.nn as nn
import torch.nn.functional as F
from effecthandlers_logging import TextLogger, log_info
from tabulate import tabulate
from torchvision.utils import make_grid
from nkca import session
from nkca.sampling im... | 4,589 | 29 | 88 | py |
nkca | nkca-main/src/nkca_cli/metrics.py | import datetime
import itertools as it
import os
import sys
from typing import Any
import attr
import fire
import functorch as ft
import torch
import torch.nn as nn
from effecthandlers_logging import TextLogger, log_info
from tabulate import tabulate
from torch.utils.data import DataLoader
from torchmetrics.image.fid ... | 5,916 | 25.653153 | 85 | py |
nkca | nkca-main/src/nkca_cli/train.py | import datetime
import itertools as it
import os
import sys
from copy import deepcopy
import fire
import functorch as ft
import torch
import torch.nn as nn
import torchvision.transforms as T
from effecthandlers_logging import TextLogger, log_info
from tabulate import tabulate
from torch.utils.data import DataLoader
fr... | 10,240 | 34.807692 | 88 | py |
BoB | BoB-main/dataloader.py | # Copyright 2021 Haoyu Song
# 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 agreed to in writing, sof... | 6,646 | 31.743842 | 87 | py |
BoB | BoB-main/bertoverbert.py | # Copyright 2021 Haoyu Song
# 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 agreed to in writing, sof... | 31,629 | 47.290076 | 273 | py |
BoB | BoB-main/xlibs/modeling_encoder_decoder.py | # Revised by Haoyu Song 2020
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | 27,952 | 49.456679 | 422 | py |
BoB | BoB-main/xlibs/modeling_longformer.py | # coding=utf-8
# Copyright 2020 The Allen Institute for AI team and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | 96,221 | 46.540514 | 222 | py |
BoB | BoB-main/xlibs/convert_mbart_original_checkpoint_to_pytorch.py | import argparse
import torch
from transformers import BartForConditionalGeneration, MBartConfig
from .convert_bart_original_pytorch_checkpoint_to_pytorch import remove_ignore_keys_
def convert_fairseq_mbart_checkpoint_from_disk(checkpoint_path, hf_config_path="facebook/mbart-large-en-ro"):
state_dict = torch.l... | 1,489 | 39.27027 | 117 | py |
BoB | BoB-main/xlibs/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | 22,610 | 41.263551 | 119 | py |
BoB | BoB-main/xlibs/modeling_mmbt.py | # coding=utf-8
# Copyright (c) Facebook, Inc. and its affiliates.
# Copyright (c) HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | 19,243 | 46.166667 | 122 | py |
BoB | BoB-main/xlibs/modeling_marian.py | # coding=utf-8
# Copyright 2020 Marian Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | 2,699 | 41.1875 | 117 | py |
BoB | BoB-main/xlibs/tokenization_dpr.py | # coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | 19,702 | 49.912145 | 152 | py |
BoB | BoB-main/xlibs/configuration_utils.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 29,872 | 51.779152 | 153 | py |
BoB | BoB-main/xlibs/convert_longformer_original_pytorch_lightning_to_pytorch.py | # coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | 3,040 | 33.954023 | 117 | py |
BoB | BoB-main/xlibs/modeling_distilbert.py | # coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
#
# 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.or... | 38,875 | 40.051742 | 127 | py |
BoB | BoB-main/xlibs/modeling_layoutlm.py | # coding=utf-8
# Copyright 2018 The Microsoft Research Asia LayoutLM Team Authors and the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/... | 37,722 | 40.272429 | 159 | py |
BoB | BoB-main/xlibs/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | 3,678 | 30.991304 | 111 | py |
BoB | BoB-main/xlibs/modeling_outputs.py | from dataclasses import dataclass
from typing import List, Optional, Tuple
import torch
from .file_utils import ModelOutput
@dataclass
class BaseModelOutput(ModelOutput):
"""
Base class for model's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (:obj:`torch.FloatT... | 51,438 | 62.192875 | 205 | py |
BoB | BoB-main/xlibs/modeling_flax_auto.py | # coding=utf-8
# Copyright 2018 The Google Flax Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | 9,180 | 48.627027 | 142 | py |
BoB | BoB-main/xlibs/modeling_utils.py | # Revised by Haoyu Song
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except ... | 81,335 | 46.985841 | 197 | py |
BoB | BoB-main/xlibs/testing_utils.py | import inspect
import logging
import os
import re
import shutil
import sys
import tempfile
import unittest
from distutils.util import strtobool
from io import StringIO
from pathlib import Path
from .file_utils import (
_datasets_available,
_faiss_available,
_flax_available,
_sentencepiece_available,
... | 30,605 | 30.947808 | 119 | py |
BoB | BoB-main/xlibs/modeling_bert.py | # Revised by Haoyu Song
# 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... | 69,586 | 39.81349 | 168 | py |
BoB | BoB-main/xlibs/convert_graph_to_onnx.py | from argparse import ArgumentParser
from os import listdir, makedirs
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from packaging.version import Version, parse
from transformers import is_tf_available, is_torch_available
from transformers.file_utils import ModelOutput
from transformers.pipel... | 17,898 | 35.603272 | 121 | py |
BoB | BoB-main/xlibs/modeling_gpt2.py | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and 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 copy of the License... | 46,947 | 42.150735 | 180 | py |
BoB | BoB-main/xlibs/modeling_flaubert.py | # coding=utf-8
# Copyright 2019-present CNRS, Facebook Inc. and the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... | 17,505 | 39.429561 | 120 | py |
BoB | BoB-main/xlibs/tokenization_utils_base.py | # coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | 147,166 | 46.952753 | 252 | py |
BoB | BoB-main/xlibs/modeling_openai.py | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and 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 copy of the License... | 35,992 | 41.747031 | 168 | py |
BoB | BoB-main/xlibs/pipelines.py | # coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | 125,281 | 42.185798 | 183 | py |
BoB | BoB-main/xlibs/modeling_rag.py | # coding=utf-8
# Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | 78,787 | 51.736278 | 204 | py |
BoB | BoB-main/xlibs/modeling_squeezebert.py | # coding=utf-8
# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | 41,581 | 39.331717 | 122 | py |
BoB | BoB-main/xlibs/trainer_callback.py | # coding=utf-8
# 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.org/licenses/LICENSE-2.0
#
# Unless required by ap... | 20,005 | 40.853556 | 119 | py |
BoB | BoB-main/xlibs/modeling_electra.py | # coding=utf-8
# Copyright 2019 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | 54,415 | 39.822206 | 168 | py |
BoB | BoB-main/xlibs/trainer_pt_utils.py | # coding=utf-8
# 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.org/licenses/LICENSE-2.0
#
# Unless required by ap... | 15,307 | 41.170799 | 120 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.