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
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/spike_dhs.py
import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.fusion import * from torch.autograd import Function from torch import Tensor from collections import namedtuple from ...activation_based import layer from ..neuron import LIFNode from torch.nn.functional import interpolate from ..surrogate import...
24,737
37.592824
138
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/train_imagenet_example.py
import torch from spikingjelly.activation_based import surrogate, neuron, functional from spikingjelly.activation_based.model import spiking_resnet, train_classify class SResNetTrainer(train_classify.Trainer): def preprocess_train_sample(self, args, x: torch.Tensor): # define how to process train sample b...
2,202
45.87234
200
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/parametric_lif_net.py
import torch import torch.nn as nn from copy import deepcopy from .. import layer # Incorporating Learnable Membrane Time Constant to Enhance Learning of Spiking Neural Networks https://arxiv.org/abs/2007.05785 __all__ = ['MNISTNet', 'FashionMNISTNet', 'NMNISTNet', 'CIFAR10Net', 'CIFAR10DVSNet', 'DVSGestureNet'] cla...
6,807
28.344828
128
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/spiking_resnet.py
import torch import torch.nn as nn from copy import deepcopy try: from torchvision.models.utils import load_state_dict_from_url except ImportError: from torchvision._internally_replaced_utils import load_state_dict_from_url from .. import layer __all__ = ['SpikingResNet', 'spiking_resnet18', 'spiking_resnet3...
18,386
42.883055
135
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/train_classify.py
import datetime import os import time import warnings from .tv_ref_classify import presets, transforms, utils import torch import torch.utils.data import torchvision from .tv_ref_classify.sampler import RASampler from torch import nn from torch.utils.data.dataloader import default_collate from torchvision.transforms.fu...
34,412
45.566982
194
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/tv_ref_classify/sampler.py
import math import torch import torch.distributed as dist class RASampler(torch.utils.data.Sampler): """Sampler that restricts data loading to a subset of the dataset for distributed, with repeated augmentation. It ensures that different each augmented version of a sample will be visible to a differe...
2,395
37.031746
103
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/tv_ref_classify/presets.py
import torch from torchvision.transforms import autoaugment, transforms from torchvision.transforms.functional import InterpolationMode class ClassificationPresetTrain: def __init__( self, crop_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), interpolation=Inter...
2,252
33.136364
100
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/tv_ref_classify/utils.py
import copy import datetime import errno import hashlib import os import time from collections import defaultdict, deque, OrderedDict import torch import torch.distributed as dist class SmoothedValue: """Track a series of values and provide access to smoothed values over a window or the global series average...
14,077
33.169903
120
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/tv_ref_classify/__init__.py
# https://github.com/pytorch/vision/tree/release/0.12/references/classification
79
79
79
py
spikingjelly
spikingjelly-master/spikingjelly/activation_based/model/tv_ref_classify/transforms.py
import math from typing import Tuple import torch from torch import Tensor from torchvision.transforms import functional as F class RandomMixup(torch.nn.Module): """Randomly apply Mixup to the provided batch and targets. The class implements the data augmentations as described in the paper `"mixup: Beyon...
6,608
36.551136
108
py
spikingjelly
spikingjelly-master/spikingjelly/timing_based/neuron.py
import torch import torch.nn as nn import torch.nn.functional as F import math class Tempotron(nn.Module): def __init__(self, in_features, out_features, T, tau=15.0, tau_s=15.0 / 4, v_threshold=1.0): ''' :param in_features: 输入数量,含义与nn.Linear的in_features参数相同 :param out_features: 输出数量,含义与nn.L...
4,629
43.095238
138
py
spikingjelly
spikingjelly-master/spikingjelly/timing_based/encoding.py
import torch import torch.nn as nn import torch.nn.functional as F class GaussianTuning: def __init__(self, n, m, x_min: torch.Tensor, x_max: torch.Tensor): ''' :param n: 特征的数量,int :param m: 编码一个特征所使用的神经元数量,int :param x_min: n个特征的最小值,shape=[n]的tensor :param x_max: n个特征的最大值,s...
2,256
42.403846
115
py
spikingjelly
spikingjelly-master/spikingjelly/timing_based/examples/tempotron_mnist.py
import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data import torchvision from torch.utils.tensorboard import SummaryWriter import spikingjelly.timing_based.encoding as encoding import spikingjelly.timing_based.neuron as neuron from tqdm import tqdm parser =...
6,356
37.762195
167
py
spikingjelly
spikingjelly-master/docs/source/conf.py
# sphinx-apidoc -o ./docs/source ./spikingjelly # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -----------------------...
3,190
34.853933
184
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/plot1.py
import torch from matplotlib import pyplot as plt plt.style.use(['science','muted']) def reset_v(h, s): return h * (1 - s) x = torch.arange(-1, 1.01, 0.01) figure = plt.figure(dpi=200) fig0 = plt.subplot(1, 2, 1) plt.xlabel('$x$') plt.ylabel('$y$') plt.title('$\\Theta(x)$ and $\\sigma(\\alpha x)$') plt.plot(x, (x...
1,337
38.352941
111
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/4_conv_fashion_mnist/plot_logs.py
from matplotlib import pyplot as plt import numpy as np from spikingjelly.activation_based.examples.conv_fashion_mnist import Net from spikingjelly import visualizing import torch import torch.nn as nn import torchvision def plot_log(csv_file, title, x_label, y_label, figsize=(12, 8), plot_max=False): log_data = np...
3,691
45.734177
144
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/11_cext_neuron_with_lbl/plot_bar.py
import numpy as np from matplotlib import pyplot as plt def plot_bar_and_text(x, y, width, label): plt.bar(x, y, width=width, label=label) for i in range(x.shape[0]): plt.text(x[i], y[i] + 0.2, str(round(y[i], 2)), ha='center') plt.style.use(['science']) fig = plt.figure(figsize=(8, 4), dpi=250) csv_ar...
2,072
48.357143
138
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/14_classify_dvsg/plot_logs.py
from matplotlib import pyplot as plt import numpy as np from spikingjelly import visualizing import torch import torch.nn as nn import torchvision def plot_log(csv_file, title, x_label, y_label, figsize=(12, 8), plot_max=False): log_data = np.loadtxt(csv_file, delimiter=',', skiprows=1, usecols=(1, 2)) x = log_...
1,909
36.45098
141
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/5_ann2snn/polt012.py
import torch from spikingjelly.activation_based import neuron from spikingjelly import visualizing from matplotlib import pyplot as plt import numpy as np plt.style.use(['science', 'muted']) plt.rcParams['figure.dpi'] = 200 if_node = neuron.IFNode(v_reset=None, monitor_state=True) T = 128 x = torch.arange(-0.2, 1.2, 0....
1,076
25.268293
86
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/15_recurrent_connection_and_stateful_synapse/plot_logs.py
from matplotlib import pyplot as plt import numpy as np from spikingjelly import visualizing import torch import torch.nn as nn import torchvision def plot_log(csv_file, title, x_label, y_label, plot_max=False, label=None): log_data = np.loadtxt(csv_file, delimiter=',', skiprows=1, usecols=(1, 2)) x = log_data[...
1,850
32.654545
109
py
spikingjelly
spikingjelly-master/docs/source/_static/tutorials/activation_based/15_recurrent_connection_and_stateful_synapse/save_gif.py
import torch import torch.nn.functional as F import torchvision.transforms from torchvision.datasets import FashionMNIST from matplotlib import pyplot as plt train_set = FashionMNIST('D:/datasets/FashionMNIST', train=True, transform=torchvision.transforms.ToTensor()) to_img = torchvision.transforms.ToPILImage() image...
822
38.190476
109
py
spikingjelly
spikingjelly-master/docs/source/_static/logo/demo.py
from matplotlib import pyplot as plt import torch from spikingjelly.activation_based import neuron from spikingjelly import visualizing import numpy as np import matplotlib with torch.no_grad(): # Requires SciencePlots package: https://github.com/garrettj403/SciencePlots plt.style.use(['science']) if_node = neuro...
3,737
33.934579
168
py
implicit_q_learning
implicit_q_learning-master/actor.py
from typing import Tuple import jax import jax.numpy as jnp from common import Batch, InfoDict, Model, Params, PRNGKey def update(key: PRNGKey, actor: Model, critic: Model, value: Model, batch: Batch, temperature: float) -> Tuple[Model, InfoDict]: v = value(batch.observations) q1, q2 = critic(ba...
986
30.83871
76
py
implicit_q_learning
implicit_q_learning-master/learner.py
"""Implementations of algorithms for continuous control.""" from typing import Optional, Sequence, Tuple import jax import jax.numpy as jnp import numpy as np import optax import policy import value_net from actor import update as awr_update_actor from common import Batch, InfoDict, Model, PRNGKey from critic import...
5,114
36.065217
107
py
implicit_q_learning
implicit_q_learning-master/policy.py
import functools from typing import Optional, Sequence, Tuple import flax.linen as nn import jax import jax.numpy as jnp import numpy as np from tensorflow_probability.substrates import jax as tfp tfd = tfp.distributions tfb = tfp.bijectors from common import MLP, Params, PRNGKey, default_init LOG_STD_MIN = -10.0 L...
2,998
34.702381
79
py
implicit_q_learning
implicit_q_learning-master/common.py
import collections import os from typing import Any, Callable, Dict, Optional, Sequence, Tuple import flax import flax.linen as nn import jax import jax.numpy as jnp import optax Batch = collections.namedtuple( 'Batch', ['observations', 'actions', 'rewards', 'masks', 'next_observations']) def default_init(s...
3,226
30.637255
78
py
implicit_q_learning
implicit_q_learning-master/value_net.py
from typing import Callable, Sequence, Tuple import jax.numpy as jnp from flax import linen as nn from common import MLP class ValueCritic(nn.Module): hidden_dims: Sequence[int] @nn.compact def __call__(self, observations: jnp.ndarray) -> jnp.ndarray: critic = MLP((*self.hidden_dims, 1))(observ...
1,360
30.651163
77
py
implicit_q_learning
implicit_q_learning-master/evaluation.py
from typing import Dict import flax.linen as nn import gym import numpy as np def evaluate(agent: nn.Module, env: gym.Env, num_episodes: int) -> Dict[str, float]: stats = {'return': [], 'length': []} for _ in range(num_episodes): observation, done = env.reset(), False while not...
617
22.769231
71
py
implicit_q_learning
implicit_q_learning-master/critic.py
from typing import Tuple import jax.numpy as jnp from common import Batch, InfoDict, Model, Params def loss(diff, expectile=0.8): weight = jnp.where(diff > 0, expectile, (1 - expectile)) return weight * (diff**2) def update_v(critic: Model, value: Model, batch: Batch, expectile: float) -> Tup...
1,574
29.882353
78
py
backtranslated-imdb
backtranslated-imdb-master/cache_backtranslations.py
import textblob import itertools import glob import time from tqdm import tqdm_notebook, tqdm # from fastai.text import * # from fastai.core import save_texts import pickle from pathlib import Path import pathlib import fire import shutil def pickle_save(obj, path): with open(path, 'wb') as f: pickle.dump...
4,140
29.674074
116
py
abr_control
abr_control-main/abr_control/utils/transformations.py
# pylint: skip-file # -*- coding: utf-8 -*- # transformations.py # Copyright (c) 2006-2015, Christoph Gohlke # Copyright (c) 2006-2015, The Regents of the University of California # Produced at the Laboratory for Fluorescence Dynamics # All rights reserved. # # Redistribution and use in source and binary forms, with ...
65,920
35.541574
88
py
GRU4REC-pytorch
GRU4REC-pytorch-master/main.py
import argparse import torch import lib import numpy as np import os import datetime parser = argparse.ArgumentParser() parser.add_argument('--hidden_size', default=100, type=int) #Literature uses 100 / 1000 --> better is 100 parser.add_argument('--num_layers', default=3, type=int) #1 hidden layer parser.add_argument(...
7,099
46.972973
176
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/model.py
from torch import nn import torch class GRU4REC(nn.Module): def __init__(self, input_size, hidden_size, output_size, num_layers=1, final_act='tanh', dropout_hidden=.5, dropout_input=0, batch_size=50, embedding_dim=-1, use_cuda=False): super(GRU4REC, self).__init__() self.input_size...
4,363
40.561905
116
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/dataset.py
import pandas as pd import numpy as np import torch class Dataset(object): def __init__(self, path, sep=',', session_key='SessionID', item_key='ItemID', time_key='Time', n_sample=-1, itemmap=None, itemstamp=None, time_sort=False): # Read csv self.df = pd.read_csv(path, sep=sep, dtype={session_key:...
5,210
40.688
159
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/lossfunction.py
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F class LossFunction(nn.Module): def __init__(self, loss_type='TOP1', use_cuda=False): """ An abstract loss function that can supports custom loss functions compatible with PyTorch.""" super(LossFu...
3,480
33.127451
115
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/evaluation.py
import lib import numpy as np import torch from tqdm import tqdm class Evaluation(object): def __init__(self, model, loss_func, use_cuda, k=20): self.model = model self.loss_func = loss_func self.topk = k self.device = torch.device('cuda' if use_cuda else 'cpu') def eval(self, ...
1,477
37.894737
149
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/trainer.py
import os import lib import time import torch import numpy as np from tqdm import tqdm class Trainer(object): def __init__(self, model, train_data, eval_data, optim, use_cuda, loss_func, batch_size, args): self.model = model self.train_data = train_data self.eval_data = eval_data s...
2,872
36.802632
166
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/optimizer.py
import torch.optim as optim class Optimizer: def __init__(self, params, optimizer_type='Adagrad', lr=.05, momentum=0, weight_decay=0, eps=1e-6): ''' An abstract optimizer class for handling various kinds of optimizers. You can specify the optimizer type and related paramet...
1,717
43.051282
112
py
GRU4REC-pytorch
GRU4REC-pytorch-master/lib/metric.py
import torch def get_recall(indices, targets): #recall --> wether next item in session is within top K=20 recommended items or not """ Calculates the recall score for the given predictions and targets Args: indices (Bxk): torch.LongTensor. top-k indices predicted by the model. targets (B):...
1,833
31.175439
117
py
CEFR-SP
CEFR-SP-main/src/model_base.py
import torch, transformers import numpy as np from torch import nn from torch.utils.data import DataLoader import pytorch_lightning as pl from transformers import AutoTokenizer, AutoModel from sklearn.metrics import f1_score from util import mean_pooling, token_embeddings_filtering_padding, read_corpus, CEFRDataset, ev...
8,222
44.683333
121
py
CEFR-SP
CEFR-SP-main/src/split_dataset.py
from transformers import AutoTokenizer, AutoModel import torch import torch.nn.functional as F from util import mean_pooling import numpy as np import tqdm def read_cefr_corpus(corpus_path): levels, sents = [], [] lv_indices = {0: [], 1: [], 2: [], 3: [], 4: [], 5: []} with open(corpus_path) as f: ...
5,429
43.876033
114
py
CEFR-SP
CEFR-SP-main/src/model.py
import torch, random, itertools, tqdm import numpy as np from torch import nn from torch.utils.data import DataLoader from util import mean_pooling, read_corpus, CEFRDataset, convert_numeral_to_six_levels from model_base import LevelEstimaterBase class LevelEstimaterClassification(LevelEstimaterBase): def __init_...
10,665
44.004219
120
py
CEFR-SP
CEFR-SP-main/src/util.py
import torch, scipy import numpy as np from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.metrics import classification_report import seaborn as sns import matplotlib.pyplot as plt class TextDataset(torch.utils.data.Dataset): def __init__(self, encodings): self.e...
3,759
33.495413
115
py
CEFR-SP
CEFR-SP-main/src/baseline.py
import torch import numpy as np from torch import nn from util import mean_pooling, convert_numeral_to_six_levels from model_base import LevelEstimaterBase class BaselineClassification(LevelEstimaterBase): def __init__(self, corpus_path, test_corpus_path, pretrained_model, problem_type, attach_wlv, num_labels, ...
3,805
41.288889
126
py
CEFR-SP
CEFR-SP-main/src/level_estimator.py
import random import tqdm import torch, glob, os, argparse from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.callbacks.early_stopping import EarlyStopping from pytorch_lightning.callbacks import LearningRateMonitor from...
9,197
60.731544
117
py
Parrot_Paraphraser
Parrot_Paraphraser-main/parrot/filters.py
import torch class Adequacy(): def __init__(self, model_tag='prithivida/parrot_adequacy_model'): from transformers import AutoModelForSequenceClassification, AutoTokenizer self.adequacy_model = AutoModelForSequenceClassification.from_pretrained(model_tag) self.tokenizer = AutoTokenizer.from_pretrained...
5,950
41.507143
108
py
WarpGAN
WarpGAN-master/align/mtcnntf/detect_face.py
""" Tensorflow implementation of the face detection / alignment algorithm found at https://github.com/kpzhang93/MTCNN_face_detection_alignment """ # MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docu...
31,697
39.534527
150
py
SoftCTC
SoftCTC-main/soft_ctc/soft_ctc_loss_cuda.py
import torch import importlib import numpy as np import sys from soft_ctc.models import BatchConnections soft_ctc_cuda = None static_cuda_path = "soft_ctc.libs.cuda.soft_ctc_cuda" dynamic_cuda_path = "soft_ctc.libs.cuda_" + torch.version.cuda.split(".")[0] + ".soft_ctc_cuda" try: soft_ctc_cuda = importlib.import...
3,848
41.296703
317
py
SoftCTC
SoftCTC-main/soft_ctc/soft_ctc_loss_opencl.py
import torch import numpy as np import importlib import sys from soft_ctc.models import BatchConnections static_opencl_path = "soft_ctc.libs.opencl.soft_ctc_opencl" try: soft_ctc_opencl = importlib.import_module(static_opencl_path) except: print("Error: Unable to load precompiled OpenCL SoftCTC library.", fi...
3,550
42.304878
328
py
SoftCTC
SoftCTC-main/soft_ctc/multi_ctc_loss.py
import torch from torch.nn.modules.loss import _Loss class MultiCTCLoss(_Loss): def __init__(self, blank=0, zero_infinity=True): super().__init__(reduction='none') self.blank = blank self.zero_infinity = zero_infinity self.ctc_loss = torch.nn.CTCLoss(blank=self.blank, reduction='no...
842
34.125
110
py
SoftCTC
SoftCTC-main/soft_ctc/soft_ctc_loss.py
import torch from soft_ctc.models import BatchConnections class SoftCTCLoss(torch.autograd.Function): def __init__(self, norm_step=10, zero_infinity=True): self._norm_step = norm_step self._zero_infinity = zero_infinity def __call__(self, logits, connections: BatchConnections, labels): ...
4,473
31.656934
126
py
SoftCTC
SoftCTC-main/soft_ctc/models/batch_connections.py
import torch import numpy as np from typing import Optional, List, Dict from soft_ctc.models.connections import Connections, convert_confusion_network_to_connections class BatchConnections(): def __init__(self, forward, backward, forward_start, forward_end, backward_start, backward_end): self.forward = f...
6,531
36.54023
114
py
LSAE
LSAE-main/train_lsae.py
import argparse import math import random import os import cv2 from functools import partial import numpy as np import torch from torch import nn, autograd, optim from torch.nn import functional as F from torch.utils import data import torch.distributed as dist from torchvision import transforms, utils from tqdm impor...
24,311
33.002797
142
py
LSAE
LSAE-main/model.py
import math from packaging import version import torch from torch import nn from torch.nn import functional as F from stylegan2.model import StyledConv, Blur, EqualLinear, EqualConv2d, ScaledLeakyReLU from stylegan2.op import FusedLeakyReLU from models.resnet import resnet50 class EqualConvTranspose2d(nn.Module): ...
32,552
29.652542
114
py
LSAE
LSAE-main/dataset.py
import os import pdb import numpy as np from PIL import Image, ImageChops from sklearn.model_selection import train_test_split import torch from torchvision import transforms from torch.utils import data from torch.utils.data import Dataset import cv2 from tqdm import tqdm import pdb class CXR14Dataset(Dataset): ...
8,672
33.692
152
py
LSAE
LSAE-main/train_texencoder_cxr14.py
import argparse import math import random import os import numpy as np from sklearn.metrics import roc_auc_score import torch from torch import nn, autograd, optim from torch.nn import functional as F from torch.utils import data import torch.distributed as dist from torchvision import transforms, utils from tqdm impo...
10,920
30.202857
121
py
LSAE
LSAE-main/stylegan2/non_leaking.py
import math import torch from torch.nn import functional as F from op import upfirdn2d SYM6 = ( 0.015404109327027373, 0.0034907120842174702, -0.11799011114819057, -0.048311742585633, 0.4910559419267466, 0.787641141030194, 0.3379294217276218, -0.07263752278646252, -0.0210602925123...
10,140
24.41604
87
py
LSAE
LSAE-main/stylegan2/ppl.py
import argparse import torch from torch.nn import functional as F import numpy as np from tqdm import tqdm import lpips from model import Generator def normalize(x): return x / torch.sqrt(x.pow(2).sum(-1, keepdim=True)) def slerp(a, b, t): a = normalize(a) b = normalize(b) d = (a * b).sum(-1, keep...
2,992
27.504762
85
py
LSAE
LSAE-main/stylegan2/projector.py
import argparse import math import os import torch from torch import optim from torch.nn import functional as F from torchvision import transforms from PIL import Image from tqdm import tqdm import lpips from model import Generator def noise_regularize(noises): loss = 0 for noise in noises: size = ...
5,943
26.646512
90
py
LSAE
LSAE-main/stylegan2/calc_inception.py
import argparse import pickle import os import torch from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import transforms from torchvision.models import inception_v3, Inception3 import numpy as np from tqdm import tqdm from inception import InceptionV3 f...
3,724
30.837607
88
py
LSAE
LSAE-main/stylegan2/inception.py
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models try: from torchvision.models.utils import load_state_dict_from_url except ImportError: from torch.utils.model_zoo import load_url as load_state_dict_from_url # Inception weights ported to Pytorch from # http://do...
11,623
36.376206
126
py
LSAE
LSAE-main/stylegan2/generate.py
import argparse import torch from torchvision import utils from model import Generator from tqdm import tqdm def generate(args, g_ema, device, mean_latent): with torch.no_grad(): g_ema.eval() for i in tqdm(range(args.pics)): sample_z = torch.randn(args.sample, args.latent, device=device...
1,656
28.589286
99
py
LSAE
LSAE-main/stylegan2/model.py
import math import random import functools import operator import torch from torch import nn from torch.nn import functional as F from torch.autograd import Function from .op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d class PixelNorm(nn.Module): def __init__(self): super().__init__() def fo...
18,345
26.058997
100
py
LSAE
LSAE-main/stylegan2/dataset.py
from io import BytesIO import os import lmdb from PIL import Image from torch.utils.data import Dataset class MultiResolutionDataset(Dataset): def __init__(self, path, transform, resolution=256): self.env = lmdb.open( path, max_readers=32, readonly=True, loc...
1,584
26.327586
80
py
LSAE
LSAE-main/stylegan2/fid.py
import argparse import pickle import torch from torch import nn import numpy as np from scipy import linalg from tqdm import tqdm from model import Generator from calc_inception import load_patched_inception_v3 @torch.no_grad() def extract_feature_from_samples( generator, inception, truncation, truncation_laten...
3,148
28.157407
88
py
LSAE
LSAE-main/stylegan2/distributed.py
import math import pickle import torch from torch import distributed as dist from torch.utils.data.sampler import Sampler def get_rank(): if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() def synchronize(): if not dist.is_available(...
2,715
20.385827
76
py
LSAE
LSAE-main/stylegan2/train.py
import argparse import math import random import os import numpy as np import torch from torch import nn, autograd, optim from torch.nn import functional as F from torch.utils import data import torch.distributed as dist from torchvision import transforms, utils from tqdm import tqdm try: import wandb except Imp...
14,121
29.7
89
py
LSAE
LSAE-main/stylegan2/convert_weight.py
import argparse import os import sys import pickle import math import torch import numpy as np from torchvision import utils from model import Generator, Discriminator def convert_modconv(vars, source_name, target_name, flip=False): weight = vars[source_name + "/weight"].value().eval() mod_weight = vars[sou...
7,934
27.238434
88
py
LSAE
LSAE-main/stylegan2/lpips/base_model.py
import os import numpy as np import torch from torch.autograd import Variable from pdb import set_trace as st from IPython import embed class BaseModel(): def __init__(self): pass; def name(self): return 'BaseModel' def initialize(self, use_gpu=True, gpu_ids=[0]): self.use...
1,618
26.440678
77
py
LSAE
LSAE-main/stylegan2/lpips/pretrained_networks.py
from collections import namedtuple import torch from torchvision import models as tv from IPython import embed class squeezenet(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True): super(squeezenet, self).__init__() pretrained_features = tv.squeezenet1_1(pretrained=pretrained...
6,533
34.901099
109
py
LSAE
LSAE-main/stylegan2/lpips/networks_basic.py
from __future__ import absolute_import import sys import torch import torch.nn as nn import torch.nn.init as init from torch.autograd import Variable import numpy as np from pdb import set_trace as st from skimage import color from IPython import embed from . import pretrained_networks as pn import lpips as util de...
7,483
38.808511
134
py
LSAE
LSAE-main/stylegan2/lpips/__init__.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from skimage.measure import compare_ssim import torch from torch.autograd import Variable from lpips import dist_model class PerceptualLoss(torch.nn.Module): def __init__(self, model='...
5,720
34.534161
172
py
LSAE
LSAE-main/stylegan2/lpips/dist_model.py
from __future__ import absolute_import import sys import numpy as np import torch from torch import nn import os from collections import OrderedDict from torch.autograd import Variable import itertools from .base_model import BaseModel from scipy.ndimage import zoom import fractions import functools import skimage.tr...
11,773
40.312281
177
py
LSAE
LSAE-main/stylegan2/op/upfirdn2d.py
import os import torch from torch.nn import functional as F from torch.autograd import Function from torch.utils.cpp_extension import load module_path = os.path.dirname(__file__) upfirdn2d_op = load( "upfirdn2d", sources=[ os.path.join(module_path, "upfirdn2d.cpp"), os.path.join(module_path, ...
5,672
27.223881
108
py
LSAE
LSAE-main/stylegan2/op/fused_act.py
import os import torch from torch import nn from torch.nn import functional as F from torch.autograd import Function from torch.utils.cpp_extension import load module_path = os.path.dirname(__file__) fused = load( "fused", sources=[ os.path.join(module_path, "fused_bias_act.cpp"), os.path.joi...
2,694
26.5
83
py
crfill
crfill-master/test.py
import numpy as np import cv2 import torch import data from options.test_options import TestOptions import models opt = TestOptions().parse() dataloader = data.create_dataloader(opt) model = models.create_model(opt) model.eval() # test num = 0 psnr_total = 0 for i, data_i in enumerate(dataloader): if i * opt.ba...
801
24.870968
56
py
crfill
crfill-master/demo.py
import pdb import cv2 import os from collections import OrderedDict import numpy as np from werkzeug.utils import secure_filename from flask import Flask, url_for, render_template, request, redirect, send_from_directory from PIL import Image import base64 import io import random from options.test_options import Test...
5,329
37.623188
116
py
crfill
crfill-master/train.py
import pdb import sys import torch import numpy as np from collections import OrderedDict from options.train_options import TrainOptions import data from util.iter_counter import IterationCounter from logger import Logger from torchvision.utils import make_grid from trainers import create_trainer # parse options opt =...
4,864
38.233871
92
py
crfill
crfill-master/options/base_options.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import pdb import sys import argparse import os from util import util import torch import models import data import pickle class BaseOptions():...
8,189
46.068966
283
py
crfill
crfill-master/models/arrange_model.py
import pdb import torch from models.inpaint_model import InpaintModel import util.util as util class ArrangeModel(InpaintModel): @staticmethod def modify_commandline_options(parser, is_train): InpaintModel.modify_commandline_options(parser, is_train) parser.add_argument('--load_base_g', type=st...
5,774
42.75
96
py
crfill
crfill-master/models/__init__.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import importlib import torch def find_model_using_name(model_name): # Given the option --model [modelname], # the file "models/modeln...
1,417
30.511111
156
py
crfill
crfill-master/models/inpaint_model.py
import pdb import torch import models.networks as networks import util.util as util from models.create_mask import MaskCreator import random import numpy as np class InpaintModel(torch.nn.Module): @staticmethod def modify_commandline_options(parser, is_train): networks.modify_commandline_options(parse...
11,242
40.640741
121
py
crfill
crfill-master/models/networks/loss.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import torch import torch.nn as nn import torch.nn.functional as F # Defines the GAN loss which uses either LSGAN or the regular GAN. # When L...
4,283
39.415094
105
py
crfill
crfill-master/models/networks/utils.py
import torch import torch.nn as nn import torch.nn.functional as F import pdb import numpy as np from torch.nn.functional import normalize class gen_conv(nn.Conv2d): def __init__(self, cin, cout, ksize, stride=1, rate=1, activation=nn.ELU()): """Define conv for generator Args: cin: In...
11,245
40.962687
155
py
crfill
crfill-master/models/networks/inpaint_d.py
import torch import torch.nn as nn import torch.nn.functional as F import pdb import numpy as np from torch.nn.functional import normalize from models.networks.base_network import BaseNetwork from models.networks.utils import dis_conv class DeepFillDiscriminator(BaseNetwork): def __init__(self, opt): super...
1,255
31.205128
69
py
crfill
crfill-master/models/networks/inpaint_g.py
import torch import torch.nn as nn import torch.nn.functional as F import pdb import numpy as np from torch.nn.functional import normalize from models.networks.base_network import BaseNetwork from models.networks.utils import gen_conv, gen_deconv, dis_conv from models.networks.splitcam import ReduceContextAttentionP1, ...
16,072
37.178147
89
py
crfill
crfill-master/models/networks/__init__.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import torch from models.networks.base_network import BaseNetwork from models.networks.loss import * from models.networks.discriminator import *...
1,689
29.178571
105
py
crfill
crfill-master/models/networks/splitcam.py
import torch import torch.nn as nn import torch.nn.functional as F from models.networks.utils import batch_conv2d, batch_transposeconv2d import pdb def hardmax(similar): val_max, id_max = torch.max(similar, 1) num = similar.size(1) sb = torch.Tensor(range(num)).long().to(similar.device) id_max = id_ma...
11,824
45.372549
120
py
crfill
crfill-master/models/networks/base_network.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import torch.nn as nn from torch.nn import init class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init_...
2,609
39.153846
107
py
crfill
crfill-master/util/util.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import re import pdb import importlib import torch from argparse import Namespace import numpy as np from PIL import Image import os import argp...
10,380
32.814332
139
py
crfill
crfill-master/data/base_dataset.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import torch.utils.data as data from PIL import Image import torchvision.transforms as transforms import numpy as np import random class BaseD...
4,080
30.635659
108
py
crfill
crfill-master/data/valimage_dataset.py
import torchvision.transforms as transforms import torch from data.base_dataset import get_params, get_transform, BaseDataset from PIL import Image from data.image_folder import make_dataset import os import pdb class ValImageDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train)...
3,245
39.074074
90
py
crfill
crfill-master/data/image_folder.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ ############################################################################### # Code from # https://github.com/pytorch/vision/blob/master/torc...
3,137
30.69697
105
py
crfill
crfill-master/data/__init__.py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import importlib import torch.utils.data from data.base_dataset import BaseDataset def find_dataset_using_name(dataset_name): # Given the ...
2,822
33.012048
105
py
crfill
crfill-master/data/testimage_dataset.py
import torchvision.transforms as transforms import torch from data.base_dataset import get_params, get_transform, BaseDataset from PIL import Image from data.image_folder import make_dataset import os class TestImageDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train): ...
2,801
35.38961
84
py
crfill
crfill-master/trainers/stylegan2_trainer.py
import pdb import torch from models.networks.sync_batchnorm import DataParallelWithCallback import models #from models.pix2pix_model import Pix2PixModel class StyleGAN2Trainer(): def __init__(self, opt): self.opt = opt self.pix2pix_model = models.create_model(opt) if len(opt.gpu_ids) > 0: ...
4,294
35.398305
82
py
crfill
crfill-master/trainers/__init__.py
import importlib def find_trainer_using_name(model_name): model_filename = "trainers." + model_name + "_trainer" modellib = importlib.import_module(model_filename) # In the file, the class called ModelNameModel() will # be instantiated. It has to be a subclass of torch.nn.Module, # and it is case-...
941
31.482759
156
py
meta-ot
meta-ot-main/plot_world_pair.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import pickle as pkl import numpy as np from matplotlib import pyplot as plt plt.style.use('bmh') import os import jax import jax.numpy as jnp from ott.core import quad_problems, problems, sinkhorn # from ott.tools import ...
3,184
30.534653
114
py
meta-ot
meta-ot-main/train_color_meta.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # https://github.com/iamalexkorotin/Wasserstein2GenerativeNetworks/blob/master/notebooks/W2GN_color_transfer.ipynb import hydra from hydra.utils import instantiate import csv import copy import glob import os import random import functools ...
16,280
40.113636
176
py
meta-ot
meta-ot-main/create_video_color.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. import argparse import copy from omegaconf import OmegaConf import pandas as pd import jax import jax.numpy as jnp import torch from torch import nn import numpy as np from meta_ot.data import ImageSampler, ImagePairSampler from meta_ot impo...
5,474
32.384146
176
py