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 |
|---|---|---|---|---|---|---|
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_xlm.py | # coding=utf-8
# Copyright 2019-present, 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
#
# Un... | 44,919 | 47.985823 | 151 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/tokenization_transfo_xl.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 Lice... | 21,459 | 36.583187 | 110 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_transfo_xl_utilities.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 Lice... | 13,568 | 39.747748 | 132 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/modeling_roberta.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... | 17,984 | 50.385714 | 134 | py |
bertviz | bertviz-master/bertviz/transformers_neuron_view/tokenization_utils.py | # coding=utf-8
# Copyright 2018 The Open AI 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
#
# ... | 31,323 | 46.75 | 380 | py |
bertviz | bertviz-master/bertviz/tests/test_attention.py | from bertviz.neuron_view import get_attention
from bertviz.transformers_neuron_view import BertTokenizer, BertModel, BertConfig, GPT2Model, GPT2Tokenizer, \
XLNetModel, XLNetTokenizer, BertForSequenceClassification, BertForQuestionAnswering, RobertaModel, RobertaTokenizer
import unittest
import torch
import os
cl... | 10,604 | 53.664948 | 165 | py |
metamodel-concepts-bert | metamodel-concepts-bert-main/evaluate_probing_local.py | """
This script is used to evaluate the probing ability of a RoBERTa language model.
It replaces token of interest by a <mask> token and attempts to predict the ground truth.
Reported metrics: Exact match, Recall@k, MRR@k and execution time.
"""
from transformers import RobertaForMaskedLM, RobertaTokenizerFast
import ... | 5,181 | 36.550725 | 99 | py |
metamodel-concepts-bert | metamodel-concepts-bert-main/run_mlm.py | #!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Team 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 at
#
# http://www.apache.org/licenses/LICENSE-... | 18,746 | 42.295612 | 119 | py |
metamodel-concepts-bert | metamodel-concepts-bert-main/evaluate_probing_construction.py | from collections import Counter
import argparse
import logging
import sys
import time
from pprint import pprint
from transformers import RobertaForMaskedLM, RobertaTokenizerFast
import torch
from tqdm import tqdm
logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser()
parser.add... | 4,354 | 35.291667 | 106 | py |
metamodel-concepts-bert | metamodel-concepts-bert-main/evaluate_probing_global.py | """
This script is used to evaluate the probing ability of a RoBERTa language model.
It replaces token of interest by a <mask> token and attempts to predict the ground truth.
Reported metrics: Exact match, Recall@k, MRR@k and execution time.
"""
from transformers import RobertaForMaskedLM, RobertaTokenizerFast
import ... | 6,558 | 36.267045 | 113 | py |
ECCT | ECCT-main/Codes.py | """
@author: Yoni Choukroun, choukroun.yoni@gmail.com
Error Correction Code Transformer
https://arxiv.org/abs/2203.14966
"""
import numpy as np
import torch
import os
def Read_pc_matrixrix_alist(fileName):
with open(fileName, 'r') as file:
lines = file.readlines()
columnNum, rowNum = np.fromstring(... | 4,595 | 38.282051 | 132 | py |
ECCT | ECCT-main/Main.py | """
Implementation of "Error Correction Code Transformer" (ECCT)
https://arxiv.org/abs/2203.14966
@author: Yoni Choukroun, choukroun.yoni@gmail.com
"""
from __future__ import print_function
import argparse
import random
import os
from torch.utils.data import DataLoader
from torch.utils import data
from datetime import ... | 10,522 | 43.588983 | 197 | py |
ECCT | ECCT-main/Model.py | """
@author: Yoni Choukroun, choukroun.yoni@gmail.com
Error Correction Code Transformer
https://arxiv.org/abs/2203.14966
"""
from torch.nn import LayerNorm
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import copy
import logging
from Codes import sign_to_bin
def clones(module, N):
... | 6,039 | 33.712644 | 174 | py |
NCMN | NCMN-master/main.py | import argparse
import os
import json
import math
import numpy as np
import cv2
from tqdm import tqdm
import torch
from ndadam import NDAdam
import torch.utils.data
import cvtransforms as T
import torchvision.datasets as datasets
from torch.autograd import Variable
import torch.nn.functional as F
import torchnet as tnt... | 7,442 | 34.783654 | 96 | py |
NCMN | NCMN-master/cvtransforms.py | """ OpenCV-based transforms
Operate on np.ndarrays only, no PIL or torch dependency
"""
from __future__ import division
import math
import random
import numpy as np
import numbers
import cv2
class Normalize(object):
"""Given mean: (R, G, B) and std: (R, G, B),
will normalize each channel of the np.ndarray... | 5,214 | 31.391304 | 94 | py |
NCMN | NCMN-master/resnet.py | import torch
import torch.nn.functional as F
from utils import conv_params, linear_params, bnparams, bnstats, \
flatten_params, flatten_stats, batch_norm
def resnet(depth, width, num_classes):
assert (depth - 4) % 6 == 0, 'depth should be 6n+4'
n = (depth - 4) // 6
widths = torch.Tensor([16, 32, 64]).... | 5,887 | 42.294118 | 111 | py |
NCMN | NCMN-master/ndadam.py | import math
import torch
from torch.optim import Optimizer
class NDAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,
weight_decay=0, vec_axes=None):
defaults = dict(lr=lr, betas=betas, eps=eps,
weight_decay=weight_decay, vec_axes=v... | 3,309 | 38.404762 | 119 | py |
NCMN | NCMN-master/utils.py | import torch
import torch.cuda.comm as comm
from torch.nn.init import kaiming_normal_
import torch.nn.functional as F
from torch.nn.parallel._functions import Broadcast
from torch.nn.parallel import scatter, parallel_apply, gather
from functools import partial
from torch.autograd import Variable
from nested_dict import... | 3,295 | 36.033708 | 112 | py |
BraggNN | BraggNN-main/main.py | from model import model_init, BraggNN
import torch, argparse, os, time, sys, shutil, logging
from util import str2bool, str2tuple, s2ituple
from torch.utils.data import DataLoader
from dataset import BraggNNDataset
import numpy as np
parser = argparse.ArgumentParser(description='Bragg peak finding for HEDM.')
parser.a... | 5,243 | 47.110092 | 139 | py |
BraggNN | BraggNN-main/model.py | import torch
def model_init(m):
if isinstance(m, torch.nn.Conv2d) or isinstance(m, torch.nn.Linear):
torch.nn.init.xavier_uniform_(m.weight)
torch.nn.init.zeros_(m.bias)
class NLB(torch.nn.Module):
def __init__(self, in_ch, relu_a=0.01):
self.inter_ch = torch.div(in_ch, 2, rounding_mod... | 3,140 | 37.304878 | 97 | py |
BraggNN | BraggNN-main/dataset.py | from torch.utils.data import Dataset
import numpy as np
import h5py, torch, random, logging
from skimage.feature import peak_local_max
from skimage import measure
def clean_patch(p, center):
w, h = p.shape
cc = measure.label(p > 0)
if cc.max() == 1:
return p
# logging.warn(f"{cc.max()} peaks l... | 4,046 | 40.721649 | 126 | py |
BraggNN | BraggNN-main/util.py | import numpy as np
import torch, argparse
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value exp... | 445 | 23.777778 | 67 | py |
BraggNN | BraggNN-main/main-hvd.py | #! /homes/zhengchun.liu/usr/miniconda3/envs/hvd/bin/python
from model import model_init, BraggNN
import torch, argparse, os, time, sys, shutil, logging
from util import str2bool, str2tuple, s2ituple
from torch.utils.data import DataLoader
from dataset import BraggNNDataset
import numpy as np
import horovod.torch as hv... | 6,413 | 47.961832 | 145 | py |
MultiPILOT | MultiPILOT-main/augment.py | '''This is the script used to create the augmentations.'''
import random
from deepaugment.deepaugment import DeepAugment
import numpy as np
import h5py
import argparse
from pandas import read_csv
from train_mf import DataTransform
from data import transforms2 as transforms
import torch
import os
import pickle
from... | 6,069 | 38.673203 | 186 | py |
MultiPILOT | MultiPILOT-main/train.py | import itertools
import logging
import pathlib
import random
import shutil
import time
import pandas
import os
import numpy as np
import torch
import torchvision
from tensorboardX import SummaryWriter
from torch.nn import functional as F
from skimage.metrics import peak_signal_noise_ratio
from sewar.full_ref import vif... | 31,835 | 43.094183 | 179 | py |
MultiPILOT | MultiPILOT-main/common/utils.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import json
import h5py
import pathlib
def get_vel_acc(x):
# calculate numerical derivatives of the trajectory
if len(x.shape) == 3:... | 1,542 | 29.86 | 91 | py |
MultiPILOT | MultiPILOT-main/models/subsampling_model.py | import torch
from torch import nn
from pytorch_nufft.nufft import nufft, nufft_adjoint
import numpy as np
import matplotlib.pylab as P
from WaveformProjection.run_projection import proj_handler
from models.rec_models.ACNN.models.acnn import AcnnModel
class Subsampling_Layer(nn.Module):
def initilaize_trajectory(sel... | 13,635 | 44.453333 | 200 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/unet_model.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
from torch import nn
from torch.nn import functional as F
class ConvBlock(nn.Module):
"""
A Convolutional Block that c... | 4,425 | 33.850394 | 98 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/complex_unet.py | import torch
from torch import nn
from torch.nn import functional as F
class ComplexConvBlock(nn.Module):
"""
A Convolutional Block that consists of two convolution layers each followed by
instance normalization, relu activation and dropout.
"""
def __init__(self, in_chans, out_chans, drop_prob):... | 18,865 | 39.484979 | 156 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/resnet_utils.py | import itertools
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
import torch
from scipy import special
from scipy.sparse import coo_matrix
from torch import Tensor
DTYPE_MAP = [
(torch.complex128, torch.float64),
(torch.complex64, torch.float32),
(torch.complex32, torch.float... | 50,515 | 30.513412 | 96 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/main.py | #coding:utf8
import ipdb;
import models
import time
from models.rec_models.ACNN.config import opt
from models.rec_models.ACNN import models as mds
from models.rec_models.ACNN.data.dataset import *
from torch.utils.data import DataLoader
from tqdm import tqdm
from torchnet import meter
from models.rec_models.ACNN.utils... | 14,586 | 40.206215 | 185 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/config.py | # coding:utf8
import warnings
import torch as t
import numpy as np
class DefaultConfig(object):
env = 'mri_34' # visdom environment
vis_port = 8098 # visdom port num
model = 'AcnnModel' # model used whose name should consist with the name in 'models/__init__.py'
train_data_root = '/data2/dutia/data1... | 1,624 | 30.25 | 101 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/common/utils.py | import json
import h5py
import torch
def to_tensor(data):
"""
Convert numpy array to PyTorch tensor. For complex arrays, the real and imaginary parts
are stacked along the last dimension.
Args:
data (np.array): Input numpy array
Returns:
torch.Tensor: PyTorch version of data
"""... | 3,992 | 30.690476 | 99 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/models/basic_module.py | #coding:utf8
import torch as t
import time
class BasicModule(t.nn.Module):
def __init__(self):
super(BasicModule,self).__init__()
self.model_name=str(type(self))
def load(self, path):
self.load_state_dict(t.load(path))
def save(self, name=None):
if name is None:
... | 857 | 22.833333 | 80 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/models/utils.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import json
import h5py
import torch
def to_tensor(data):
"""
Convert numpy array to PyTorch tensor. For complex arrays, the real and... | 3,979 | 29.615385 | 99 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/models/acnn.py | import torch
from .basic_module import BasicModule
from torch import nn
from torch.nn import functional as F
from models.rec_models.ACNN.common.utils import fft2, ifft2
from data import transforms
class ConvBlockBn(nn.Module):
"""
A Convolutional Block that consists of two convolution layers each followed by
... | 8,107 | 36.022831 | 258 | py |
MultiPILOT | MultiPILOT-main/models/rec_models/ACNN/data/dataset.py | # coding:utf8
import os
import torch as t
from PIL import Image
from torch.utils import data
from common.utils import *
import numpy as np
from torchvision import transforms as T
import ipdb
import scipy.io as sio
import cv2
class Mridata(data.Dataset):
def __init__(self, root, mask_smp_path, slice_num, transform... | 4,411 | 35.766667 | 139 | py |
MultiPILOT | MultiPILOT-main/pytorch_nufft/interp.py |
import torch
import numpy
from pytorch_nufft import util
def interpolate(input, width, kernel, coord, device):
ndim = coord.shape[-1]
batch_shape = input.shape[:-ndim]
batch_size = util.prod(batch_shape)
pts_shape = coord.shape[:-1]
npts = util.prod(pts_shape)
input = input.reshape([batch_s... | 3,466 | 31.707547 | 115 | py |
MultiPILOT | MultiPILOT-main/pytorch_nufft/nufft2.py | from pytorch_nufft import util
import pytorch_nufft.interp as interp
import numpy
import torch
from data import transforms2 as transforms
def nufft(input, coord, oversamp=1.25, width=4.0, n=128, device='cuda'):
ndim = coord.shape[-1]
beta = numpy.pi * (((width / oversamp) * (oversamp - 0.5)) ** 2 - 0.8) ** 0.... | 3,807 | 29.709677 | 105 | py |
MultiPILOT | MultiPILOT-main/pytorch_nufft/util.py |
import numpy
import torch
def prod(shape):
"""Computes product of shape.
Args:
shape (tuple or list): shape.
Returns:
Product.
"""
return numpy.prod(shape)
def _expand_shapes(*shapes):
shapes = [list(shape) for shape in shapes]
max_ndim = max(len(shape) for shape in shape... | 1,357 | 28.521739 | 76 | py |
MultiPILOT | MultiPILOT-main/pytorch_nufft/nufft.py | from pytorch_nufft import util
import pytorch_nufft.interp as interp
import numpy
import torch
from data import transforms
def _normalize_axes(axes, ndim):
if axes is None:
return tuple(range(ndim))
else:
return tuple(a % ndim for a in sorted(axes))
def _expand_shapes(*shapes):
shapes =... | 6,372 | 29.061321 | 105 | py |
MultiPILOT | MultiPILOT-main/data/mf_data.py | import pathlib
import random
import h5py
from torch.utils.data import Dataset
class SliceData(Dataset):
def __init__(self, root, transform, sample_rate=1):
"""
Args:
root (pathlib.Path): Path to the dataset.
transform (callable): A callable object that pre-processes the raw... | 2,326 | 45.54 | 131 | py |
MultiPILOT | MultiPILOT-main/data/mri_data.py | import pathlib
import random
import h5py
from torch.utils.data import Dataset
class SliceData(Dataset):
def __init__(self, root, transform, sample_rate=1):
"""
Args:
root (pathlib.Path): Path to the dataset.
transform (callable): A callable object that pre-processes the raw... | 2,282 | 45.591837 | 131 | py |
MultiPILOT | MultiPILOT-main/data/transforms2.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import torch
def to_tensor(data):
if np.iscomplexobj(data):
data = np.stack((data.real, data.imag), axis=-1)... | 7,303 | 28.451613 | 91 | py |
MultiPILOT | MultiPILOT-main/data/mri_mf_data.py | import pathlib
import random
from turtle import pd
import h5py
import torch
from torch.utils.data import Dataset
import ismrmrd.xsd
import data.transforms as transforms
import numpy as np
class SliceData(Dataset):
def __init__(self, files, transform, sample_rate=1, num_frames_per_example=10, clips_factors=None):
... | 3,156 | 43.464789 | 152 | py |
MultiPILOT | MultiPILOT-main/data/transforms.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import torch
def to_tensor(data):
if np.iscomplexobj(data):
data = np.stack((data.real, data.imag), axis=-1)... | 7,600 | 29.282869 | 100 | py |
MultiPILOT | MultiPILOT-main/WaveformProjection/projector_changed.py | import torch
from matplotlib import pyplot as plt
class Projector:
def __init__(self, num_iters, device, lipschitz_const=16, dstep=0.004, eps2=5e-1, eps_inf=10e-2, \
display_res=True):
''' num_iters - number of iterations the algorithm would run
lipshcitz_const - discretizatio... | 5,692 | 40.253623 | 118 | py |
MultiPILOT | MultiPILOT-main/WaveformProjection/Projector.py | import torch
from matplotlib import pyplot as plt
class Projector:
def __init__(self,num_iters, device, lipschitz_const=16, dstep=0.004, eps2 = 5e-1,eps_inf = 10e-2, \
display_res = True):
''' num_iters - number of iterations the algorithm would run
lipshcitz_const - discretiza... | 5,550 | 39.816176 | 131 | py |
MultiPILOT | MultiPILOT-main/WaveformProjection/utils.py | import torch
def projectOntoL1Ball(x,L,alpha):
'''Computes the projection of x on a weighted ball defined by {x, ||L.*x||_1 \leq \alpha}.
Returns projection z and threshold parameter sigma
'''
xf = x.flatten()
Lf = L.flatten()
n = torch.numel(x)
#Projection if solution is trivial
M ... | 2,915 | 29.375 | 114 | py |
MultiPILOT | MultiPILOT-main/WaveformProjection/run_projection.py | from WaveformProjection import utils
from WaveformProjection.Projector import Projector
from WaveformProjection.Constraints import Constraints
from WaveformProjection import Evaluator
from scipy import io
from WaveformProjection.utils import interpolate
from math import ceil,floor
import torch
from matplotlib import py... | 2,219 | 27.461538 | 113 | py |
MultiPILOT | MultiPILOT-main/WaveformProjection/Evaluator.py | from abc import ABC, abstractmethod
import torch
from WaveformProjection import utils
class Evaluator(ABC):
'''
abstract evaluator class - suite of constraint distance metrics
'''
def __init__(self,eps = 1e-10):
self.eps = eps
@abstractmethod
def norm(self,curve):
'''measure cur... | 2,627 | 31.85 | 83 | py |
MultiPILOT | MultiPILOT-main/deepaugment/build_features.py | # (C) 2019 Baris Ozmen <hbaristr@gmail.com>
import sys
import numpy as np
import keras
class DataOp:
@staticmethod
def load(dataset_name):
"""Loads dataset from keras and returns a sample out of it
Args:
dataset_name (str):
training_set_size (int):
validat... | 3,754 | 30.033058 | 86 | py |
MultiPILOT | MultiPILOT-main/deepaugment/image_generator.py | import keras
import numpy as np
import pandas as pd
import sys
from os.path import dirname, realpath
file_path = realpath(__file__)
dir_of_file = dirname(file_path)
sys.path.insert(0, dir_of_file)
from lib.cutout import cutout_numpy
from augmenter import augment_by_policy
AUG_TYPES = [
"crop",
"gaussian-b... | 5,724 | 27.625 | 107 | py |
MultiPILOT | MultiPILOT-main/deepaugment/run_full_model.py | # (C) 2019 Baris Ozmen <hbaristr@gmail.com>
import pathlib
import logging
import os
import datetime
import sys
from os.path import dirname, realpath
file_path = realpath(__file__)
dir_of_file = dirname(file_path)
parent_dir_of_file = dirname(dir_of_file)
sys.path.insert(0, dir_of_file)
now = datetime.datetime.now()... | 3,272 | 27.710526 | 142 | py |
MultiPILOT | MultiPILOT-main/deepaugment/childcnn.py | # (C) 2019 Baris Ozmen <hbaristr@gmail.com>
from keras import optimizers, Model
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.applications.mobilenetv2 import MobileNetV2
from keras.appli... | 8,783 | 31.533333 | 110 | py |
MultiPILOT | MultiPILOT-main/deepaugment/wide_res_net.py | # Copy-pasted from https://github.com/keras-team/keras-contrib/blob/master/keras_contrib/applications/wide_resnet.py
# -*- coding: utf-8 -*-
"""Wide Residual Network models for Keras.
# Reference
- [Wide Residual Networks](https://arxiv.org/abs/1605.07146)
"""
from __future__ import print_function
from __future__ impo... | 11,362 | 34.070988 | 146 | py |
MultiPILOT | MultiPILOT-main/deepaugment/deepaugment.py | # (C) 2019 Baris Ozmen <hbaristr@gmail.com>
import tensorflow as tf
import keras
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # tell tensorflow not to use all resources
session = tf.Session(config=config)
keras.backend.set_session(session)
import os
import sys
from os.path import dirname, realpa... | 9,961 | 36.451128 | 157 | py |
MultiPILOT | MultiPILOT-main/deepaugment/notebook.py | # (C) 2019 Baris Ozmen <hbaristr@gmail.com>
import pandas as pd
import numpy as np
def get_folder_path(path):
last = path.split("/")[-1]
return path.replace(last, "")
class Notebook:
def __init__(self, config):
self.df = pd.DataFrame()
self.store_path = config["notebook_path"]
def ... | 4,608 | 36.169355 | 98 | py |
GPT2-chitchat | GPT2-chitchat-master/data_parallel.py | from torch.nn.parallel import DataParallel
import torch
from torch.nn.parallel._functions import Scatter
from torch.nn.parallel.parallel_apply import parallel_apply
def scatter(inputs, target_gpus, chunk_sizes, dim=0):
r"""
Slices tensors into approximately equal chunks and
distributes them across given G... | 4,126 | 39.861386 | 84 | py |
GPT2-chitchat | GPT2-chitchat-master/pytorchtools.py | import numpy as np
import torch
from os.path import join
import os
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0, save_path="."):
"""
Args:
patience (int): How long... | 2,057 | 37.111111 | 111 | py |
GPT2-chitchat | GPT2-chitchat-master/dataset.py | from torch.utils.data import Dataset
import torch
class MyDataset(Dataset):
"""
"""
def __init__(self, input_list, max_len):
self.input_list = input_list
self.max_len = max_len
def __getitem__(self, index):
input_ids = self.input_list[index]
input_ids = input_ids[:se... | 479 | 20.818182 | 61 | py |
GPT2-chitchat | GPT2-chitchat-master/interact.py | import transformers
import torch
import os
import json
import random
import numpy as np
import argparse
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
from tqdm import tqdm
from torch.nn import DataParallel
import logging
from transformers import GPT2TokenizerFast, GPT2LMHeadModel, GPT2... | 8,257 | 44.125683 | 120 | py |
GPT2-chitchat | GPT2-chitchat-master/interact_mmi.py | import transformers
import torch
import os
import json
import random
import numpy as np
import argparse
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
from tqdm import tqdm
from torch.nn import DataParallel
import logging
from transformers.modeling_gpt2 import GPT2Config, GPT2LMHeadMode... | 11,111 | 46.084746 | 118 | py |
GPT2-chitchat | GPT2-chitchat-master/train.py | import argparse
import math
import time
import torch
import torch.nn.functional as F
import torch.optim as optim
import logging
from datetime import datetime
import os
from torch.utils.data import Dataset, DataLoader
from os.path import join, exists
from torch.nn import CrossEntropyLoss
from tqdm import tqdm
from torch... | 16,540 | 37.647196 | 134 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/ensemble_demo.py | from datetime import datetime
import time
import csv
import numpy as np
import torch
import torch.nn as nn
import occamnet.Bases as Bases
from occamnet.Losses import CrossEntropyLoss
from occamnet.Network import NetworkConstants
from occamnet.SparseSetters import SetNoSparse as SNS
def func(x, a, b):
return a*n... | 5,240 | 31.962264 | 161 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/lotka_volterra_demo.py | import argparse
from datetime import datetime
import time
import csv
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import odeint
import occamnet.Bases as Bases
from occamnet.Losses import CrossEntropyLoss
from occamnet.Network import NetworkConstants
from occamnet.Sp... | 5,158 | 31.651899 | 122 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/solow_demo.py | from datetime import datetime
import time
import csv
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import odeint
import occamnet.Bases as Bases
from occamnet.Losses import CrossEntropyLoss
from occamnet.Network import NetworkConstants
from occamnet.SparseSetters impo... | 6,274 | 36.35119 | 219 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/sir_demo.py | import argparse
from datetime import datetime
import time
import csv
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import odeint
import occamnet.Bases as Bases
from occamnet.Losses import CrossEntropyLoss
from occamnet.Network import NetworkConstants
from occamnet.Sp... | 5,247 | 31.8 | 122 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/occamnet/Bases.py | from abc import ABC,abstractmethod
import torch
import sympy as sp
import numpy as np
#Nan represents unfixed units. Not wrong units.
def checkNan(input):
return np.isnan(input[0])
#Inf represents wrong units that need to be propagated further
def checkInf(input):
return np.isinf(input[0])
def matchUnits(uni... | 15,952 | 24.939837 | 167 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/occamnet/SparseSetters.py | import torch
import math
from occamnet.Network import ActivationLayer
class SetPartialSparse:
def __init__(self, sparseInputs):
self.sparseInputs = sparseInputs
def getActivationsSparsity(self, inputSize, activationLists, outputSize):
numItems = [outputSize]
for i in range(len(activati... | 6,203 | 34.861272 | 111 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/occamnet/Network.py | import math
import time
import datetime
from functools import partial
import argparse
import pickle
import copy
from numpy.lib.npyio import save
import numpy as np
from matplotlib import rc, rcParams
from matplotlib import patches as patch
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch... | 35,058 | 38.614689 | 222 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/occamnet/Losses.py | import torch
import math
class CrossEntropyLoss:
def __init__(self, std, topNumber, activationWeight=0, constantWeight=0, anomWeight = 0.2, badUnitWeight = 1):
self.setStd(std)
self.topNumber = topNumber
self.weighting = torch.tensor([1.0/(n) for n in range(topNumber, 0, -1)])
self.... | 2,618 | 41.241935 | 171 | py |
OccamNet_SocialSci | OccamNet_SocialSci-main/occamnet/DataGenerators.py | import torch
class FunctionDataGenerator:
def __init__(self, batchSize, dataRange, function):
self.batchSize = batchSize
self.dataRange = dataRange
self.function = function
def getBatch(self):
x = (torch.rand([self.batchSize], dtype = torch.float)*(self.dataRange[1]-self.dataRa... | 4,375 | 36.084746 | 160 | py |
SLFIR | SLFIR-main/src/stage2/model.py | import torch.nn as nn
from Networks import InceptionV3_Network, Attention, Block_lstm
from torch import optim
import torch
import numpy as np
import torch.nn.functional as F
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
class SLF... | 7,216 | 47.436242 | 184 | py |
SLFIR | SLFIR-main/src/stage2/dataset.py | import torch
from glob import glob
import torch.utils.data as data
import torchvision.transforms as transforms
import os
from random import randint
from PIL import Image
import random
import torchvision.transforms.functional as F
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic ... | 4,759 | 42.272727 | 125 | py |
SLFIR | SLFIR-main/src/stage2/eval.py | from time import time
from eval_model import SLFIR_Model
import time
import torch
import numpy as np
import argparse
from dataset import *
from torch.utils.tensorboard import SummaryWriter
device = torch.device('cuda:2' if torch.cuda.is_available() else 'cpu')
np.random.seed(42)
torch.manual_seed(42)
torch.cuda.manual... | 2,863 | 34.8 | 116 | py |
SLFIR | SLFIR-main/src/stage2/Networks.py | import torch.nn as nn
import torchvision.models as backbone_
import torch.nn.functional as F
import torch
from torch.autograd import Variable
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
class InceptionV3_Network(nn.Module):
... | 5,574 | 36.668919 | 118 | py |
SLFIR | SLFIR-main/src/stage2/eval_model.py | import torch.nn as nn
from Networks import InceptionV3_Network, Attention, Block_lstm
from torch import optim
import torch
import numpy as np
import torch.nn.functional as F
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
class SLF... | 7,869 | 49.127389 | 184 | py |
SLFIR | SLFIR-main/src/stage2/train.py | from time import time
from model import SLFIR_Model
import time
import os
import torch
import numpy as np
import argparse
from dataset import *
from torch.utils.tensorboard import SummaryWriter
device = torch.device('cuda:2' if torch.cuda.is_available() else 'cpu')
np.random.seed(42)
torch.manual_seed(42)
torch.cuda.m... | 6,075 | 43.028986 | 141 | py |
SLFIR | SLFIR-main/src/stage1/model.py | import torch.nn as nn
from Networks import InceptionV3_Network, Attention, Linear
from torch import optim
import torch
import time
import torch.nn.functional as F
device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")
class SLFIR_Model(nn.Module):
def __init__(self, hp):
super(SLFIR_Mode... | 3,852 | 42.784091 | 122 | py |
SLFIR | SLFIR-main/src/stage1/dataset.py | import numpy as np
import torch
from glob import glob
import torch.utils.data as data
import torchvision.transforms as transforms
import os
from random import randint
from PIL import Image
import random
import torchvision.transforms.functional as F
device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")... | 4,534 | 40.227273 | 122 | py |
SLFIR | SLFIR-main/src/stage1/Networks.py | import torch.nn as nn
import torchvision.models as backbone_
import torch.nn.functional as F
import torch
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
class InceptionV3_Network(nn.Module):
def __init__(self):
super(In... | 3,454 | 31.904762 | 78 | py |
SLFIR | SLFIR-main/src/stage1/train.py | import torch
import time
from model import SLFIR_Model
from dataset import get_dataloader
device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")
import argparse
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
if _... | 3,025 | 43.5 | 150 | py |
lightning | lightning-master/setup.py | #!/usr/bin/env python
# Copyright The Lightning AI 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 l... | 7,933 | 45.397661 | 117 | py |
lightning | lightning-master/examples/fabric/dcgan/train_torch.py | """
DCGAN - Raw PyTorch Implementation
Code adapted from the official PyTorch DCGAN tutorial:
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
"""
import os
import random
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import... | 9,215 | 32.882353 | 111 | py |
lightning | lightning-master/examples/fabric/dcgan/train_fabric.py | """
DCGAN - Accelerated with Lightning Fabric
Code adapted from the official PyTorch DCGAN tutorial:
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
"""
import os
import time
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.... | 9,098 | 32.825279 | 111 | py |
lightning | lightning-master/examples/fabric/build_your_own_trainer/run.py | import torch
from torchmetrics.functional.classification.accuracy import accuracy
from trainer import MyCustomTrainer
import lightning as L
class MNISTModule(L.LightningModule):
def __init__(self) -> None:
super().__init__()
self.model = torch.nn.Sequential(
torch.nn.Conv2d(
... | 2,765 | 32.731707 | 107 | py |
lightning | lightning-master/examples/fabric/build_your_own_trainer/trainer.py | import os
from collections.abc import Mapping
from functools import partial
from typing import Any, cast, Iterable, List, Literal, Optional, Tuple, Union
import torch
from lightning_utilities import apply_to_collection
from tqdm import tqdm
import lightning as L
from lightning.fabric.accelerators import Accelerator
f... | 23,061 | 42.844106 | 120 | py |
lightning | lightning-master/examples/fabric/reinforcement_learning/train_torch.py | """
Proximal Policy Optimization (PPO) - Accelerated with Lightning Fabric
Author: Federico Belotti @belerico
Adapted from https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/ppo.py
Based on the paper: https://arxiv.org/abs/1707.06347
Requirements:
- gymnasium[box2d]>=0.27.1
- moviepy
- lightning
- torchmetrics
- ... | 10,962 | 38.293907 | 118 | py |
lightning | lightning-master/examples/fabric/reinforcement_learning/train_fabric_decoupled.py | """
Proximal Policy Optimization (PPO) - Accelerated with Lightning Fabric
Author: Federico Belotti @belerico
Adapted from https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/ppo.py
Based on the paper: https://arxiv.org/abs/1707.06347
Requirements:
- gymnasium[box2d]>=0.27.1
- moviepy
- lightning
- torchmetrics
- ... | 14,674 | 40.572238 | 118 | py |
lightning | lightning-master/examples/fabric/reinforcement_learning/train_fabric.py | """
Proximal Policy Optimization (PPO) - Accelerated with Lightning Fabric
Author: Federico Belotti @belerico
Adapted from https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/ppo.py
Based on the paper: https://arxiv.org/abs/1707.06347
Requirements:
- gymnasium[box2d]>=0.27.1
- moviepy
- lightning
- torchmetrics
- ... | 8,323 | 37.537037 | 118 | py |
lightning | lightning-master/examples/fabric/reinforcement_learning/rl/loss.py | import torch
import torch.nn.functional as F
from torch import Tensor
def policy_loss(advantages: torch.Tensor, ratio: torch.Tensor, clip_coef: float) -> torch.Tensor:
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef)
return torch.max(pg_loss1, pg_los... | 849 | 27.333333 | 97 | py |
lightning | lightning-master/examples/fabric/reinforcement_learning/rl/utils.py | import argparse
import math
import os
from distutils.util import strtobool
from typing import Optional, TYPE_CHECKING, Union
import gymnasium as gym
import torch
from torch.utils.tensorboard import SummaryWriter
if TYPE_CHECKING:
from rl.agent import PPOAgent, PPOLightningAgent
def parse_args():
parser = ar... | 6,576 | 34.939891 | 120 | py |
lightning | lightning-master/examples/fabric/reinforcement_learning/rl/agent.py | import math
from typing import Dict, Tuple
import gymnasium as gym
import torch
import torch.nn.functional as F
from rl.loss import entropy_loss, policy_loss, value_loss
from rl.utils import layer_init
from torch import Tensor
from torch.distributions import Categorical
from torchmetrics import MeanMetric
from lightn... | 9,269 | 36.228916 | 112 | py |
lightning | lightning-master/examples/fabric/kfold_cv/train_fabric.py | # Copyright The Lightning AI 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 law or agreed to in wri... | 7,416 | 37.035897 | 120 | py |
lightning | lightning-master/examples/fabric/language_model/train.py | import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, random_split
import lightning as L
from lightning.pytorch.demos import Transformer, WikiText2
def main():
L.seed_everything(42)
fabric = L.Fabric()
# Data
dataset = WikiText2()
train_dataloader, val_dataloader... | 2,445 | 31.184211 | 97 | py |
lightning | lightning-master/examples/fabric/image_classifier/train_torch.py | # Copyright The Lightning AI 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 law or agreed to in wri... | 5,623 | 35.75817 | 120 | py |
lightning | lightning-master/examples/fabric/image_classifier/train_fabric.py | # Copyright The Lightning AI 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 law or agreed to in wri... | 7,641 | 38.595855 | 120 | py |
lightning | lightning-master/examples/fabric/meta_learning/train_torch.py | """
MAML - Raw PyTorch implementation using the Learn2Learn library
Adapted from https://github.com/learnables/learn2learn/blob/master/examples/vision/distributed_maml.py
Original code author: Séb Arnold - learnables.net
Based on the paper: https://arxiv.org/abs/1703.03400
Requirements:
- learn2learn
- cherry-rl
- gy... | 5,982 | 32.055249 | 113 | py |
lightning | lightning-master/examples/fabric/meta_learning/train_fabric.py | """
MAML - Accelerated with Lightning Fabric
Adapted from https://github.com/learnables/learn2learn/blob/master/examples/vision/distributed_maml.py
Original code author: Séb Arnold - learnables.net
Based on the paper: https://arxiv.org/abs/1703.03400
Requirements:
- lightning>=1.9.0
- learn2learn
- cherry-rl
- gym<=0... | 5,563 | 32.926829 | 113 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.