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 |
|---|---|---|---|---|---|---|
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/reversible.py | import torch
import torch.nn as nn
from torch.autograd.function import Function
from torch.utils.checkpoint import get_device_states, set_device_states
# following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html
class Deterministic(nn.Module):
def __init... | 5,434 | 32.343558 | 120 | py |
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/recorder.py | from torch import nn
from reformer_pytorch.reformer_pytorch import LSHAttention, LSHSelfAttention
from collections import defaultdict
class Recorder(nn.Module):
def __init__(self, net):
super().__init__()
self.iter = 0
self.recordings = defaultdict(list)
self.net = net
self.... | 1,662 | 26.716667 | 81 | py |
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/autopadder.py | import math
import torch
from torch import nn
import torch.nn.functional as F
from reformer_pytorch.reformer_pytorch import Reformer, ReformerLM, LSHSelfAttention
def pad_to_multiple(tensor, seqlen, multiple, dim=-1):
m = seqlen / multiple
if m.is_integer():
return tensor
remainder = math.ceil(m) ... | 2,056 | 35.732143 | 136 | py |
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/reformer_enc_dec.py | import re
from torch import nn
from reformer_pytorch.reformer_pytorch import ReformerLM
from reformer_pytorch.generative_tools import TrainingWrapper
ENC_PREFIX = 'enc_'
DEC_PREFIX = 'dec_'
def group_dict_by_key(cond, d):
return_val = [dict(),dict()]
for key in d.keys():
match = bool(cond(key))
... | 2,978 | 42.173913 | 121 | py |
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/reformer_pytorch.py | import math
import torch
import torch.nn as nn
from torch.nn import Identity
import torch.nn.functional as F
from torch.autograd import Function
from functools import partial, reduce, wraps
from itertools import chain
from operator import mul
from local_attention import LocalAttention
from axial_positional_embedding i... | 32,377 | 41.602632 | 757 | py |
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/generative_tools.py | from functools import partial
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from reformer_pytorch.reformer_pytorch import ReformerLM
from reformer_pytorch.autopadder import Autopadder
def top_p(logits, thres = 0.9):
sorted_logits, sorted_indices = tor... | 3,321 | 33.604167 | 138 | py |
reformer-pytorch | reformer-pytorch-master/reformer_pytorch/__init__.py | from reformer_pytorch.reformer_pytorch import LSHAttention, LSHSelfAttention, Reformer, ReformerLM
from reformer_pytorch.reformer_enc_dec import ReformerEncDec
from reformer_pytorch.recorder import Recorder
from reformer_pytorch.autopadder import Autopadder
| 258 | 50.8 | 98 | py |
reformer-pytorch | reformer-pytorch-master/examples/enwik8_simple/train.py | from reformer_pytorch import ReformerLM
from reformer_pytorch.generative_tools import TrainingWrapper
import random
import tqdm
import gzip
import numpy as np
import torch
import torch.optim as optim
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
# constants
NUM_BATCHES = int(1... | 3,049 | 25.068376 | 81 | py |
reformer-pytorch | reformer-pytorch-master/examples/enwik8_deepspeed/train.py | import deepspeed
from reformer_pytorch import ReformerLM
from reformer_pytorch.generative_tools import TrainingWrapper
import argparse
import random
import tqdm
import gzip
import numpy as np
import torch
import torch.optim as optim
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset... | 3,856 | 29.132813 | 157 | py |
reformer-pytorch | reformer-pytorch-master/pretraining/self-supervised.py | import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader, random_split
from tqdm import tqdm
from reformer_pytorch import Reformer, ReformerLM
from transformers import BertTokenizer, PreTrainedTokenizer
from fairseq.optim.adafactor import Adafactor
... | 15,496 | 41.809392 | 118 | py |
curriculumagent | curriculumagent-master/curriculumagent/baseline/evaluate.py | #!/usr/bin/env python3
# Copyright (c) 2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the Mozilla Public License, version 2.0 was not distributed with this file,
# you can obtain one at http://mozilla.o... | 4,642 | 36.144 | 123 | py |
curriculumagent | curriculumagent-master/curriculumagent/junior/junior_student.py | """In this file, a neural network is developed to fit the dataset generated by Tutor.
Depending on the observation space and action space, the tutor model can/has to be
adjusted.
The Junior model returns a one-hot encoded output, based on the number of actions.
Credit: The junior is a more general approach of the ori... | 19,532 | 36.41954 | 122 | py |
curriculumagent | curriculumagent-master/curriculumagent/submission/my_agent.py | """ This file is the advanced agent constisting of a model that can cover different action spaces, rllib
training, scaling and other additional features.
To submit your own agent, just specify the model and action_space_path and if you want a scaler that
you previously trained with. The MyAgent will import the model a... | 14,099 | 37.108108 | 118 | py |
curriculumagent | curriculumagent-master/curriculumagent/senior/senior_student.py | import json
import logging
import os
import pickle
import random
from pathlib import Path
from typing import Union, List, Optional
import ray
import tensorflow as tf
from ray._raylet import ObjectRef
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.models import ModelCatalog
from ray.rllib.utils import ch... | 10,849 | 41.382813 | 120 | py |
curriculumagent | curriculumagent-master/curriculumagent/senior/rllib_execution/senior_model_rllib.py | """This file constist of two custom models, which transfer the junior weights into the Rllib experiment.
"""
import warnings
from pathlib import Path
from typing import List, Tuple
import numpy as np
import tensorflow as tf
from gymnasium.spaces import Discrete, Box
from ray.rllib.models.tf.tf_modelv2 import TFModelV... | 6,529 | 38.817073 | 125 | py |
curriculumagent | curriculumagent-master/tests/test_junior/test_junior.py | import os
import shutil
from pathlib import Path
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import ReLU # , LeakyRalu
from curriculumagent.junior.junior_student import Junior, load_dataset, train, validate
class TestJunior:
"""
Test Suite for the Junior model and the data loade... | 8,319 | 32.548387 | 104 | py |
curriculumagent | curriculumagent-master/tests/test_baseline/test_baselineagent.py | import os
import shutil
import grid2op
import pytest
import ray
import tensorflow as tf
from grid2op.Agent import BaseAgent
from lightsim2grid import LightSimBackend
from tensorflow.keras.models import Sequential
from curriculumagent.baseline import CurriculumAgent
from curriculumagent.submission.my_agent import MyAg... | 9,696 | 35.592453 | 105 | py |
curriculumagent | curriculumagent-master/tests/test_senior/test_senior_student.py | import os
import pickle
import shutil
import pytest
import ray
import tensorflow as tf
from ray._raylet import ObjectRef
from ray.rllib.algorithms import Algorithm
from sklearn.base import BaseEstimator
from curriculumagent.senior.rllib_execution.senior_env_rllib import SeniorEnvRllib
from curriculumagent.senior.seni... | 12,871 | 37.08284 | 101 | py |
curriculumagent | curriculumagent-master/tests/test_senior/test_senior_model.py | import numpy as np
import pytest
import tensorflow as tf
from gymnasium.spaces import Box, Discrete
from curriculumagent.senior.rllib_execution.senior_model_rllib import Grid2OpCustomModel
class TestAdvancedCustomModel:
def test_load_model(self, custom_config):
"""
First test, whether the model ... | 7,823 | 41.754098 | 116 | py |
curriculumagent | curriculumagent-master/tests/test_submission/test_my_agent.py | import types
import grid2op
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.python.training.tracking.tracking import AutoTrackable
from curriculumagent.submission.my_agent import MyAgent
class TestAdvancedAgent:
"""
Test suite of the advanced submission agent
"""
def test_i... | 5,256 | 29.04 | 103 | py |
curriculumagent | curriculumagent-master/paper_data_MPGTTA/scripts_paper/hps_junior_nni.py | """
In this file, the code for the hyper-parameter search of the junior model is provided.
It is optimized to run the NNI framework @https://nni.readthedocs.io/en/stable/
In order to run this code via NNI, you have to start it via the terminal.
NNI then automatically runs through the parameters and selects the best opt... | 3,931 | 30.709677 | 108 | py |
GPflowOpt | GPflowOpt-master/doc/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# GPflowOpt documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 30 20:34:41 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# ... | 5,534 | 29.412088 | 98 | py |
CAMB | CAMB-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# MyProj documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 18 20:57:49 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | 9,848 | 31.50495 | 100 | py |
CS_ELMo | CS_ELMo-master/src/main.py | import os
import re
import json
import argparse
import random
import numpy as np
import torch
import experiments.experiment_langid as experiment_lid
import experiments.experiment_ner as experiment_ner
import experiments.experiment_pos as experiment_pos
from types import SimpleNamespace as Namespace
PROJ_DIR = os.pat... | 5,425 | 41.724409 | 140 | py |
CS_ELMo | CS_ELMo-master/src/dataset.py | import os
import string
from torch.utils.data import DataLoader, Dataset
class CSDataset(Dataset):
def __init__(self, dataset_path, tok_index=0, lid_index=1, ner_index=None, pos_index=None, debug=False):
assert os.path.exists(dataset_path), 'File path not found: {}'.format(dataset_path)
self.has_... | 11,547 | 34.532308 | 108 | py |
CS_ELMo | CS_ELMo-master/src/utilities.py | import re
import numpy as np
import random
import os
import subprocess
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import sklearn
import warnings
import json
from modeling.seqtagger import SequenceTagger
from sklearn.metrics import classification_report, precision_recall_fs... | 10,081 | 39.653226 | 139 | py |
CS_ELMo | CS_ELMo-master/src/trainer.py | import os
import time
import torch
import torch.nn as nn
import copy
import numpy as np
import utilities as utils
from utilities import running_fmeasure, sklearn_fmeasure
from utilities import save_model
from torch.utils.data import DataLoader
def to_tensor(labels, label2index, pad_value=0, return_mask=False, device... | 13,315 | 41.273016 | 144 | py |
CS_ELMo | CS_ELMo-master/src/experiments/experiment_pos.py | import os
import re
import json
import random
import numpy as np
import torch
import torch.nn as nn
import utilities as utils
from collections import Counter
from modeling.seqtagger import SequenceTagger
from trainer import Trainer
from dataset import CSDataset
from allennlp.modules import ConditionalRandomField
def... | 7,582 | 45.521472 | 131 | py |
CS_ELMo | CS_ELMo-master/src/experiments/experiment_ner.py | import os
import re
import json
import torch
import torch.nn as nn
import utilities as utils
from collections import Counter
from modeling.seqtagger import SequenceTagger
from trainer import Trainer
from dataset import CSDataset
from allennlp.modules import ConditionalRandomField
def main(args):
# ==============... | 6,851 | 45.612245 | 131 | py |
CS_ELMo | CS_ELMo-master/src/modeling/seqtagger.py | import torch
import torch.nn as nn
import numpy as np
from flair.embeddings import WordEmbeddings, StackedEmbeddings, FlairEmbeddings
from flair.data import Sentence
from modeling.attention import NgramEnhancer
from modeling.elmo import Elmo, batch_to_ids
from allennlp.modules import ConditionalRandomField
ELMO_SETT... | 18,175 | 50.2 | 272 | py |
CS_ELMo | CS_ELMo-master/src/modeling/attention.py | import torch
import torch.nn as nn
def stable_softmax(scores, mask=None, epsilon=1e-9):
"""
:param scores: tensor of shape (batch_size, sequence_length)
:param mask: (optional) binary tensor in case of padded sequences, shape: (batch_size, sequence_length)
:param epsilon: epsilon to be added to the no... | 8,764 | 38.660633 | 128 | py |
CS_ELMo | CS_ELMo-master/src/modeling/elmo.py | import json
import logging
from typing import Union, List, Dict, Any
import warnings
import torch
from torch.nn.modules import Dropout
import numpy
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
import h5py
from overrides import overrides
from allennlp.common.file_u... | 34,407 | 45.185235 | 142 | py |
advbench | advbench-main/advbench/command_launchers.py |
import subprocess
import time
import torch
def local_launcher(commands):
for cmd in commands:
subprocess.call(cmd, shell=True)
def dummy_launcher(commands):
for cmd in commands:
print(f'Dummy launcher: {cmd}')
def multi_gpu_launcher(commands):
n_gpus = torch.cuda.device_count()
pro... | 1,119 | 23.888889 | 66 | py |
advbench | advbench-main/advbench/optimizers.py | import torch.optim as optim
import torch
class PrimalDualOptimizer:
def __init__(self, parameters, margin, eta):
self.parameters = parameters
self.margin = margin
self.eta = eta
def step(self, cost):
self.parameters['dual_var'] = self.relu(self.parameters['dual_var'] + self.eta... | 436 | 24.705882 | 110 | py |
advbench | advbench-main/advbench/networks.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from collections import OrderedDict
def Classifier(input_shape, num_classes, hparams):
if input_shape[0] == 1:
# return SmallCNN()
return MNISTNet(input_shape, num_classes)
elif input_shape[0]... | 4,850 | 34.669118 | 104 | py |
advbench | advbench-main/advbench/datasets.py | import torch
from torch.utils.data import Subset, ConcatDataset, TensorDataset
import torchvision.transforms as transforms
from torchvision.datasets import CIFAR10 as CIFAR10_
from torchvision.datasets import MNIST as TorchvisionMNIST
from torchvision.datasets import SVHN as SVHN_
SPLITS = ['train', 'val', 'test']
DAT... | 6,297 | 31.632124 | 97 | py |
advbench | advbench-main/advbench/attacks.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.laplace import Laplace
class Attack(nn.Module):
def __init__(self, classifier, hparams, device):
super(Attack, self).__init__()
self.classifier = classifier
self.hparams = hparams
self.device... | 7,067 | 43.175 | 148 | py |
advbench | advbench-main/advbench/evalulation_methods.py | import torch
import torch.nn.functional as F
from advbench import attacks
class Evaluator:
# Sub-class should over-ride
NAME = ''
def __init__(self, algorithm, device, test_hparams):
self.algorithm = algorithm
self.device = device
self.test_hparams = test_hparams
def calc... | 8,108 | 32.647303 | 99 | py |
advbench | advbench-main/advbench/algorithms.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
import pandas as pd
import numpy as np
import torch.optim as optim
from advbench import networks
from advbench import optimizers
from advbench import attacks
from advbench.lib import meters
ALGORITHMS = [
'ERM',... | 22,949 | 41.657993 | 122 | py |
advbench | advbench-main/advbench/scripts/train.py | import argparse
import torch
from torch.utils.data import DataLoader
import os
import json
import pandas as pd
import time
import collections
from humanfriendly import format_timespan
from advbench import datasets
from advbench import algorithms
from advbench import evalulation_methods
from advbench import hparams_reg... | 8,410 | 35.411255 | 95 | py |
advbench | advbench-main/advbench/lib/misc.py | import torch
import hashlib
import sys
import os
import json
from functools import wraps
from time import time
import pandas as pd
import torch.nn.functional as F
import numpy as np
from advbench.lib import meters
def timing(f):
@wraps(f)
def wrap(*args, **kw):
ts = time()
result = f(*args, **... | 4,178 | 29.50365 | 103 | py |
LiveQ | LiveQ-master/liveq-dashboard/dashboard/server.py | ################################################################
# LiveQ - An interactive volunteering computing batch system
# Copyright (C) 2013 Ioannis Charalampidis
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the ... | 1,994 | 29.692308 | 81 | py |
visualize_atari | visualize_atari-master/saliency.py | # Visualizing and Understanding Atari Agents | Sam Greydanus | 2017 | MIT License
from __future__ import print_function
import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously ;)
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
from sci... | 3,722 | 47.986842 | 109 | py |
visualize_atari | visualize_atari-master/overfit_atari.py | # Visualizing and Understanding Atari Agents | Sam Greydanus | 2017 | MIT License
from __future__ import print_function
import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously ;)
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import gym, sys
import nump... | 2,073 | 41.326531 | 106 | py |
visualize_atari | visualize_atari-master/policy.py | # Visualizing and Understanding Atari Agents | Sam Greydanus | 2017 | MIT License
from __future__ import print_function
import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously ;)
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
impor... | 1,770 | 41.166667 | 98 | py |
visualize_atari | visualize_atari-master/make_movie.py | # Visualizing and Understanding Atari Agents | Sam Greydanus | 2017 | MIT License
from __future__ import print_function
import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously
import matplotlib.pyplot as plt
import matplotlib as mpl ; mpl.use("Agg")
import matplotlib.animation as manimat... | 4,337 | 53.911392 | 128 | py |
visualize_atari | visualize_atari-master/rollout.py | # Visualizing and Understanding Atari Agents | Sam Greydanus | 2017 | MIT License
from __future__ import print_function
import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously ;)
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
impor... | 1,802 | 39.977273 | 100 | py |
MAESTROeX | MAESTROeX-main/sphinx_docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# MAESTROeX documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 25 18:42:54 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# ... | 7,732 | 28.628352 | 79 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/baseline_config.py | class Defaults(object):
window_size = 7
hidden_sizes = [300]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'sgd' # 'adam'
learning_rate = 0.1 # 1e-4
epochs = 20
iobes = True # Map tags to IOBES on input
max_tokens = None # Max dataset size in tokens
encodi... | 1,050 | 41.04 | 69 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/multi-output_MT-var-dataset.py | #!/usr/bin/env python
from __future__ import print_function
from logging import info
import random
import numpy as np
import datetime
from ltlib.evaluation import conll_summary, per_type_summary, is_iob_tagging
from keras.models import Model
from keras.layers import Input, Embedding, merge, Flatten, Dense
from kera... | 9,676 | 39.320833 | 153 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/MT-dependent.py | #!/usr/bin/env python
from __future__ import print_function
from logging import info
import random
import numpy as np
import datetime
from ltlib.evaluation import conll_summary, per_type_summary, is_iob_tagging
from keras.models import Model
from keras.layers import Input, Embedding, merge, Flatten, Dense
from kera... | 7,786 | 39.984211 | 150 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/multi-output_MT.py | #!/usr/bin/env python
from __future__ import print_function
from logging import info
import random
import numpy as np
import datetime
from ltlib.evaluation import conll_summary, per_type_summary, is_iob_tagging
from keras.models import Model
from keras.layers import Input, Embedding, merge, Flatten, Dense
from kera... | 8,810 | 39.232877 | 119 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/single_task.py | #!/usr/bin/env python
from __future__ import print_function
import random
from logging import info
from keras.models import Model
from keras.layers import Input, Embedding, Flatten, Dense
from keras.layers import Reshape, Convolution2D, Dropout
from ltlib import filelog
from ltlib import conlldata
from ltlib import... | 3,285 | 31.86 | 84 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/baseline.py | #!/usr/bin/env python
from __future__ import print_function
from logging import info
from keras.models import Model
from keras.layers import Input, Embedding, merge, Flatten, Dense
from keras.layers import Dropout
from ltlib import filelog
from ltlib import conlldata
from ltlib import viterbi
from ltlib.features i... | 2,362 | 30.092105 | 69 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/ltlib/callbacks.py | from sys import stdout
from logging import info
from datetime import datetime
from abc import ABCMeta, abstractmethod
from keras.callbacks import Callback
from evaluation import per_type_summary, conll_summary, is_iob_tagging
from util import unique
from defaults import defaults
class LtlCallback(Callback):
"""... | 6,986 | 32.591346 | 77 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/ltlib/features.py | import re
import numpy as np
import wordvecdata
from logging import warn
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from bidict import IncBidict
def uniform(shape, scale=0.05):
# TODO move to more sensible place, avoid redundancy with
# keras.initializations.uniform
retu... | 10,940 | 34.293548 | 77 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/ltlib/optimizers.py | from keras import optimizers
DEFAULT_OPTIMIZER = 'adam'
def get_optimizer(config):
"""Return optimizer specified by configuration."""
config = vars(config)
name = config.get('optimizer', DEFAULT_OPTIMIZER)
optimizer = optimizers.get(name) # Default parameters
lr = config.get('learning_rate')
... | 405 | 28 | 60 | py |
MTL-Bioinformatics-2016 | MTL-Bioinformatics-2016-master/models/ltlib/layers.py | import numpy as np
from keras import backend as K
from keras import initializations
from keras.layers import Layer, Input, Embedding, merge
class FixedEmbedding(Layer):
"""Embedding with fixed weights.
Modified from keras/layers/embeddings.py in Keras (http://keras.io).
WARNING: this is experimental and... | 4,834 | 36.773438 | 82 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/dataset/dqn_dataset.py | import os
import gzip
from pathlib import Path
from typing import List
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from tov_vicreg.utils.pytorch_utils import *
class DQNReplayDataset(Dataset):
"""
A dataset of observations from a one che... | 8,283 | 30.142857 | 83 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/models/main.py | # inspired by: https://github.com/facebookresearch/moco-v3/blob/main/moco
import argparse
import math
import os
from pathlib import Path
import random
import shutil
import time
import warnings
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import ... | 14,600 | 38.462162 | 123 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/models/load_models.py | import os
import torch
from torch import nn
import torchvision.models as torchvision_models
import tov_vicreg.models.networks.vit as vits
from tov_vicreg.models.networks.resnet import ResnetCNN
import tov_vicreg.utils.pytorch_utils as pytorch_utils
def load_model(arch, pretrained_weights=None, patch_size=8, num_cla... | 4,059 | 39.19802 | 131 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/models/builder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from tov_vicreg.models.load_models import load_model
class TOVVICReg(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.log = {}
self.backbone = load_model(args.arch, patch_size=args.pa... | 5,048 | 36.4 | 147 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/models/optimizer.py | # from: https://github.com/facebookresearch/moco-v3/blob/main/moco/optimizer.py
import torch
class LARS(torch.optim.Optimizer):
"""
LARS optimizer, no rate scaling or weight decay for parameters <= 1D.
"""
def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001):
... | 1,524 | 37.125 | 113 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/models/networks/resnet.py | from torch import nn
import numpy as np
def fixup_init(layer, num_layers):
nn.init.normal_(layer.weight, mean=0, std=np.sqrt(
2 / (layer.weight.shape[0] * np.prod(layer.weight.shape[2:]))) * num_layers ** (-0.25))
class InvertedResidual(nn.Module):
def __init__(self, in_channels, out_channels, stride... | 5,586 | 37.006803 | 95 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/models/networks/vit.py | import math
from functools import partial
import torch
import torch.nn as nn
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
# Cut & paste from PyTorch official master until it's in a few official releases - RW
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
... | 10,503 | 37.057971 | 112 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/utils/experiments_utils.py | from collections import deque
import random
from pathlib import Path
import numpy as np
import torch
from torchvision import transforms
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.manifold import TSNE, Isomap
import matplotlib.pyplot as plt
from matplotlib import cm, colors as m... | 8,027 | 36.166667 | 140 | py |
TOV-VICReg | TOV-VICReg-main/tov_vicreg/utils/pytorch_utils.py | import torch
device = None
def init_gpu(use_gpu=True, gpu_id=0):
global device
if torch.cuda.is_available() and use_gpu:
device = torch.device("cuda:" + str(gpu_id))
print("Using GPU id {}".format(gpu_id))
else:
device = torch.device("cpu")
print("GPU not detected. Default... | 642 | 19.741935 | 63 | py |
ped | ped-main/model.py | import numpy as np
import torch
import torch.nn as nn
import torch.autograd as autograd
from lib.solvers import anderson
import matplotlib.pyplot as plt
EPS = 1e-03 # Avoid division by zero with continuous Bernoulli
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class DeepEncoderLayerFC(nn.Mo... | 12,969 | 35.846591 | 98 | py |
ped | ped-main/script_synthetic.py | import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from lib.plotters import matplotlib_config
from model import DeepPED
from model import DeepDEQAutoencoder
from mo... | 13,528 | 35.964481 | 107 | py |
ped | ped-main/lib/radam.py | import math
import torch
from torch.optim.optimizer import Optimizer, required
class RAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
self.buffer = [[None, None, None] for i... | 8,090 | 36.985915 | 116 | py |
ped | ped-main/lib/layer_utils.py | import torch
import torch.nn.functional as F
import torch.nn as nn
def list2vec(z1_list):
"""Convert list of tensors to a vector"""
bsz = z1_list[0].size(0)
return torch.cat([elem.reshape(bsz, -1, 1) for elem in z1_list], dim=1)
def vec2list(z1, cutoffs):
"""Convert a vector back to a list, via the ... | 1,332 | 35.027027 | 95 | py |
ped | ped-main/lib/optimizations.py | from torch.nn.parameter import Parameter
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.autograd import Variable
##############################################################################################################
#
# Temporal DropConnect in a feed-forward setting
#
###########... | 11,133 | 37.93007 | 121 | py |
ped | ped-main/lib/solvers.py | # Modified based on the DEQ repo.
import torch
from torch import nn
import torch.nn.functional as functional
from torch.autograd import Function
import numpy as np
import pickle
import sys
import os
from scipy.optimize import root
import time
from termcolor import colored
def _safe_norm(v):
if not torch.isfinit... | 11,850 | 36.742038 | 132 | py |
ped | ped-main/lib/jacobian.py | import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
def jac_loss_estimate(f0, z0, vecs=2, create_graph=True):
"""Estimating tr(J^TJ)=tr(JJ^T) via Hutchinson estimator
Args:
f0 (torch.Tensor): Output of the function f (whose J is to be analyzed)
z0 (torch.Tens... | 1,863 | 40.422222 | 130 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/main.py | from __future__ import print_function
from miscc.config import cfg, cfg_from_file
from datasets import TextDataset
from trainer import condGANTrainer as trainer
import os
import sys
import time
import random
import pprint
import datetime
import dateutil.tz
import argparse
import numpy as np
import torch
import torch... | 5,482 | 33.923567 | 90 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/masks.py | import torch
def mask_correlated_samples(args):
mask = torch.ones((args.batch_size * 2, args.batch_size * 2), dtype=bool)
mask = mask.fill_diagonal_(0)
for i in range(args.batch_size):
mask[i, args.batch_size + i] = 0
mask[args.batch_size + i, i] = 0
return mask
def mask_correlated_sam... | 562 | 30.277778 | 77 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/pretrain_DAMSM.py | from __future__ import print_function
from miscc.utils import mkdir_p
from miscc.utils import build_super_images
from miscc.losses import sent_loss, words_loss
from miscc.config import cfg, cfg_from_file
from datasets import TextDataset
from datasets import prepare_data
from model import RNN_ENCODER, CNN_ENCODER
im... | 13,050 | 34.083333 | 102 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/model.py | import torch
import torch.nn as nn
import torch.nn.parallel
from torch.autograd import Variable
from torchvision import models
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from miscc.config import cfg
from GlobalAtte... | 25,027 | 34.652422 | 104 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/GlobalAttention.py | """
Global attention takes a matrix and a query metrix.
Based on each query vector q, it computes a parameterized convex combination of the matrix
based.
H_1 H_2 H_3 ... H_n
q q q q
| | | |
\ | | /
.....
\ | /
a
Constructs a unit mapping... | 6,815 | 34.873684 | 96 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/datasets.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from nltk.tokenize import RegexpTokenizer
from collections import defaultdict
from miscc.config import cfg
import torch
import torch.utils.data as data
from torch.autog... | 13,771 | 34.864583 | 116 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/spectral.py | import torch
from torch.optim.optimizer import Optimizer, required
from torch.autograd import Variable
import torch.nn.functional as F
from torch import nn
from torch import Tensor
from torch.nn import Parameter
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __... | 2,250 | 32.102941 | 83 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/nt_xent.py | import torch
import torch.nn as nn
class NT_Xent(nn.Module):
def __init__(self, batch_size, temperature, mask, device):
super(NT_Xent, self).__init__()
self.batch_size = batch_size
self.temperature = temperature
self.mask = mask
self.device = device
self.criterion ... | 1,339 | 36.222222 | 159 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/trainer.py | from __future__ import print_function
from six.moves import range
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torchvision
from PIL import Image
from miscc.config import cfg
from miscc.utils import mkdir_p
from miscc.ut... | 29,111 | 42.975831 | 110 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/miscc/losses.py | import torch
import torch.nn as nn
import numpy as np
from miscc.config import cfg
from GlobalAttention import func_attention
# ##################Loss for matching text-image###################
def cosine_similarity(x1, x2, dim=1, eps=1e-8):
"""Returns cosine similarity between x1 and x2, computed along dim.
... | 9,225 | 37.441667 | 117 | py |
T2I_CL | T2I_CL-main/DM-GAN+CL/code/miscc/utils.py | import os
import errno
import numpy as np
from torch.nn import init
import torch
import torch.nn as nn
from PIL import Image, ImageDraw, ImageFont
from copy import deepcopy
import skimage.transform
from miscc.config import cfg
# For visualization ################################################
COLOR_DIC = {0:[128... | 11,370 | 34.095679 | 96 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/main.py | from __future__ import print_function
from miscc.config import cfg, cfg_from_file
from datasets import TextDataset
from trainer import condGANTrainer as trainer
import os
import sys
import time
import random
import pprint
import datetime
import dateutil.tz
import argparse
import numpy as np
import torch
import torch... | 5,165 | 33.671141 | 90 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/masks.py | import torch
def mask_correlated_samples(args):
mask = torch.ones((args.batch_size * 2, args.batch_size * 2), dtype=bool)
mask = mask.fill_diagonal_(0)
for i in range(args.batch_size):
mask[i, args.batch_size + i] = 0
mask[args.batch_size + i, i] = 0
return mask
| 296 | 28.7 | 77 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/pretrain_DAMSM.py | from __future__ import print_function
from miscc.utils import mkdir_p
from miscc.utils import build_super_images
from miscc.losses import sent_loss, words_loss
from miscc.config import cfg, cfg_from_file
from datasets import TextDataset
from datasets import prepare_data
from model import RNN_ENCODER, CNN_ENCODER
im... | 13,050 | 34.083333 | 102 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/model.py | import torch
import torch.nn as nn
import torch.nn.parallel
from torch.autograd import Variable
import torchvision.models as models
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from miscc.config import cfg
from Globa... | 21,632 | 33.338095 | 84 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/GlobalAttention.py | """
Global attention takes a matrix and a query metrix.
Based on each query vector q, it computes a parameterized convex combination of the matrix
based.
H_1 H_2 H_3 ... H_n
q q q q
| | | |
\ | | /
.....
\ | /
a
Constructs a unit mapping... | 4,236 | 31.098485 | 96 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/datasets.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from nltk.tokenize import RegexpTokenizer
from collections import defaultdict
from miscc.config import cfg
import torch
import torch.utils.data as data
from torch.autog... | 13,757 | 35.205263 | 116 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/nt_xent.py | import torch
import torch.nn as nn
class NT_Xent(nn.Module):
def __init__(self, batch_size, temperature, mask, device):
super(NT_Xent, self).__init__()
self.batch_size = batch_size
self.temperature = temperature
self.mask = mask
self.device = device
self.criterion ... | 1,339 | 36.222222 | 159 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/trainer.py | from __future__ import print_function
from six.moves import range
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from PIL import Image
from miscc.config import cfg
from miscc.utils import mkdir_p
from miscc.utils import build_su... | 28,328 | 43.057543 | 118 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/miscc/losses.py | import torch
import torch.nn as nn
import numpy as np
from miscc.config import cfg
from GlobalAttention import func_attention
# ##################Loss for matching text-image###################
def cosine_similarity(x1, x2, dim=1, eps=1e-8):
"""Returns cosine similarity between x1 and x2, computed along dim.
... | 8,228 | 36.575342 | 98 | py |
T2I_CL | T2I_CL-main/AttnGAN+CL/code/miscc/utils.py | import os
import errno
import numpy as np
from torch.nn import init
import torch
import torch.nn as nn
from PIL import Image, ImageDraw, ImageFont
from copy import deepcopy
import skimage.transform
from miscc.config import cfg
# For visualization ################################################
COLOR_DIC = {0:[128... | 11,364 | 34.07716 | 96 | py |
adversarial_ntk_evolution | adversarial_ntk_evolution-master/test_functions.py | import jax
import haiku as hk
import jax.numpy as jnp
from jax.example_libraries import optimizers
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import numpy as np
import neural_tangents as nt
import functools
import operator
import optax
import copy
im... | 9,229 | 39.482456 | 221 | py |
adversarial_ntk_evolution | adversarial_ntk_evolution-master/run_exp.py | import jax
import haiku as hk
import jax.numpy as jnp
from jax.example_libraries import optimizers
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import numpy as np
import neural_tangents as nt
import functools
import operator
import optax
import copy
im... | 13,392 | 50.511538 | 287 | py |
adversarial_ntk_evolution | adversarial_ntk_evolution-master/calculate_kernel.py | import jax
import haiku as hk
import jax.numpy as jnp
from jax.example_libraries import optimizers
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import numpy as np
import neural_tangents as nt
import functools
import operator
import optax
import copy
im... | 4,382 | 42.39604 | 217 | py |
adversarial_ntk_evolution | adversarial_ntk_evolution-master/visualize_ntk_features.py | import jax
import haiku as hk
import jax.numpy as jnp
from jax.example_libraries import optimizers
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import numpy as np
import neural_tangents as nt
import functools
import operator
import optax
import copy
im... | 7,034 | 46.533784 | 253 | py |
adversarial_ntk_evolution | adversarial_ntk_evolution-master/utils.py | import functools
import jax
import operator
import numpy as np
class bind(functools.partial):
"""
An improved version of partial which accepts Ellipsis (...) as a placeholder
"""
def __call__(self, *args, **keywords):
keywords = {**self.keywords, **keywords}
iargs = iter(args)
a... | 1,061 | 29.342857 | 120 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.