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 |
|---|---|---|---|---|---|---|
CTranslate2 | CTranslate2-master/tools/benchmark/opennmt_ende_wmt14/opennmt_py/convertv2_v3.py | import torch
import imp
import argparse
import pyonmttok
from onmt.constants import DefaultTokens
from onmt.inputters.inputter import vocabs_to_dict
# with the two module = imp.load_source() below
# we ghost the old torchtext.data.field and depercated
# onmt.inputters.text_dataset
# however this require some functions... | 2,542 | 27.573034 | 79 | py |
CTranslate2 | CTranslate2-master/python/ctranslate2/specs/model_spec.py | """Specifications declare the expected variables layout of CTranslate2 models
that do not load a computation graph. The model converter should make sure that
each required variable of the specification is set.
"""
import abc
import ctypes
import json
import os
import shutil
import struct
from typing import Dict, List... | 23,334 | 31.319945 | 91 | py |
CTranslate2 | CTranslate2-master/python/ctranslate2/converters/transformers.py | import abc
import argparse
import gc
import itertools
import os
from typing import List, Optional
import numpy as np
try:
import huggingface_hub
import torch
import transformers
except ImportError:
pass
from ctranslate2.converters import utils
from ctranslate2.converters.converter import Converter
f... | 60,929 | 34.486313 | 143 | py |
CTranslate2 | CTranslate2-master/python/ctranslate2/converters/fairseq.py | import argparse
import os
from typing import Optional
from ctranslate2.converters import utils
from ctranslate2.converters.converter import Converter
from ctranslate2.specs import common_spec, transformer_spec
_SUPPORTED_MODELS = {
"bart",
"multilingual_transformer",
"transformer",
"transformer_align... | 12,420 | 34.898844 | 95 | py |
CTranslate2 | CTranslate2-master/python/ctranslate2/converters/utils.py | import numpy as np
def fuse_linear(spec, layers):
if not layers:
raise ValueError("Cannot fuse linear layers: at least one layer is required")
if isinstance(layers[0].weight, np.ndarray):
np_api = np
else:
import torch as np_api
spec.weight = np_api.concatenate([layer.weight ... | 3,041 | 28.533981 | 88 | py |
CTranslate2 | CTranslate2-master/python/ctranslate2/converters/opennmt_py.py | import argparse
from ctranslate2.converters import utils
from ctranslate2.converters.converter import Converter
from ctranslate2.specs import common_spec, transformer_spec
_SUPPORTED_ACTIVATIONS = {
"gelu": common_spec.Activation.GELU,
"fast_gelu": common_spec.Activation.GELUTanh,
"relu": common_spec.Acti... | 12,461 | 34.504274 | 92 | py |
CTranslate2 | CTranslate2-master/python/tests/test_storage_view.py | import sys
import numpy as np
import pytest
import test_utils
import ctranslate2
def _assert_same_array(a, b):
assert a["shape"] == b["shape"]
assert a["data"] == b["data"]
assert a["typestr"] == b["typestr"]
@pytest.mark.parametrize(
"dtype,name",
[
(np.int8, "int8"),
(np.int1... | 2,387 | 25.533333 | 80 | py |
CTranslate2 | CTranslate2-master/python/tests/test_spec.py | import numpy as np
import pytest
import test_utils
import ctranslate2
from ctranslate2.converters import utils as conversion_utils
from ctranslate2.specs import common_spec, transformer_spec
from ctranslate2.specs.model_spec import OPTIONAL, index_spec
def test_layer_spec_validate():
class SubSpec(ctranslate2.s... | 8,986 | 30.313589 | 87 | py |
CTranslate2 | CTranslate2-master/python/tests/test_transformers.py | import inspect
import json
import os
import shutil
import numpy as np
import pytest
import test_utils
import ctranslate2
@pytest.fixture
def clear_transformers_cache():
"""Clears the Transformers model cache after each test when running in a CI."""
yield
clear_transformers_cache_in_ci()
def clear_tran... | 31,550 | 33.747797 | 95 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/main.py | # @Author : bamtercelboo
# @Datetime : 2018/1/30 19:50
# @File : main_hyperparams.py.py
# @Last Modify Time : 2018/1/30 19:50
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : main_hyperparams.py.py
FUNCTION : main
"""
import pdb
import argparse
import datetime
import Config.config as configurable
fro... | 5,673 | 34.685535 | 136 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/test.py | # @Author : bamtercelboo
# @Datetime : 2018/8/24 15:27
# @File : test.py
# @Last Modify Time : 2018/8/24 15:27
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : test.py
FUNCTION : None
"""
import os
import sys
import torch
from DataUtils.utils import *
from DataUtils.Common import *
def load_test_mo... | 6,069 | 34.086705 | 107 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/trainer.py | # @Author : bamtercelboo
# @Datetime : 2018/8/26 8:30
# @File : trainer.py
# @Last Modify Time : 2018/8/26 8:30
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : trainer.py
FUNCTION : None
"""
import os, pdb
import seqeval.metrics
from seqeval.scheme import IOB2
import sys
import time
import numpy as... | 15,711 | 41.579946 | 146 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/mainHelp.py | # @Author : bamtercelboo
# @Datetime : 2018/9/3 10:50
# @File : mainHelp.py
# @Last Modify Time : 2018/9/3 10:50
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : mainHelp.py
FUNCTION : None
"""
import shutil, pdb
import time
from DataUtils.Alphabet import *
from DataUtils.Batch_Iterator import *
fro... | 9,548 | 37.817073 | 137 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/utils.py | # @Author : bamtercelboo
# @Datetime : 2018/8/24 9:58
# @File : utils.py
# @Last Modify Time : 2018/8/24 9:58
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : utils.py
FUNCTION : None
"""
import sys
import os
import torch
import numpy as np
class Best_Result:
"""
Best_Result
"""
... | 3,605 | 23.69863 | 63 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Load_Pretrained_Embed.py | # @Author : bamtercelboo
# @Datetime : 2018/08/27 09.59
# @File : Load_Pretrained_Embed.py
# @Last Modify Time : 2018/08/27 09.59
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Load_Pretrained_Embed.py
FUNCTION : loading pretrained word embedding
"""
import torch
import torch.nn as nn
import torch.... | 9,941 | 37.988235 | 142 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Embed_From_Pretrained.py | # @Author : bamtercelboo
# @Datetime : 2018/2/3 14:03
# @File : Embed_From_Pretrained.py
# @Last Modify Time : 2018/2/3 14:03
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Embed_From_Pretrained.py
FUNCTION : None
"""
import os
import sys
import torch
import torch.nn.init as init
import numpy as n... | 3,226 | 31.59596 | 85 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Batch_Iterator_torch.py | # @Author : bamtercelboo
# @Datetime : 2018/1/30 15:55
# @File : Batch_Iterator.py.py
# @Last Modify Time : 2018/1/30 15:55
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Batch_Iterator.py
FUNCTION : None
"""
import torch
from torch.autograd import Variable
import random
from DataUtils.Common imp... | 7,948 | 35.631336 | 135 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Alphabet.py | # @Author : bamtercelboo
# @Datetime : 2018/1/30 15:54
# @File : Alphabet.py
# @Last Modify Time : 2018/1/30 15:54
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Alphabet.py
FUNCTION : None
"""
import os
import sys
import torch
import random
import collections
from DataUtils.Common import seed_num... | 7,881 | 30.277778 | 98 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Batch_Iterator.py | # @Author : bamtercelboo
# @Datetime : 2018/1/30 15:55
# @File : Batch_Iterator.py.py
# @Last Modify Time : 2018/1/30 15:55
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Batch_Iterator.py
FUNCTION : None
"""
import torch
from torch.autograd import Variable
import random
import numpy as np
from Da... | 8,317 | 36.133929 | 137 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Embed.py | # @Author : bamtercelboo
# @Datetime : 2018/8/27 15:34
# @File : Embed.py
# @Last Modify Time : 2018/8/27 15:34
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Embed.py
FUNCTION : None
"""
import os
import sys
import time
import tqdm
import numpy as np
import torch
import torch.nn as nn
import torc... | 8,503 | 36.462555 | 118 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/DataUtils/Optim.py | # -*- coding: utf-8 -*-
import torch.optim
from torch.nn.utils.clip_grad import clip_grad_norm_
# Setup optimizer (should always come after model.cuda())
# iterable of dicts for per-param options where each dict
# is {'params' : [p1, p2, p3...]}.update(generic optimizer args)
# Example:
# optim.SGD([
# {'param... | 5,041 | 30.911392 | 79 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/models/BiLSTM.py | # @Author : bamtercelboo
# @Datetime : 2018/8/17 16:06
# @File : BiLSTM.py
# @Last Modify Time : 2018/8/17 16:06
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : BiLSTM.py
FUNCTION : None
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padde... | 2,184 | 28.931507 | 121 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/models/CRF.py | # @Author : bamtercelboo
# @Datetime : 2018/9/14 9:51
# @File : CRF.py
# @Last Modify Time : 2018/9/14 9:51
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : CRF.py
FUNCTION : None
REFERENCE : https://github.com/jiesutd/NCRFpp/blob/master/model/crf.py
"""
import torch
from torch.autograd.variable ... | 12,355 | 45.104478 | 198 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/models/modelHelp.py | # @Author : bamtercelboo
# @Datetime : 2018/9/15 19:09
# @File : modelHelp.py
# @Last Modify Time : 2018/9/15 19:09
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : modelHelp.py
FUNCTION : None
"""
import torch
import random
from DataUtils.Common import *
torch.manual_seed(seed_num)
random.seed(seed... | 948 | 26.114286 | 101 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/models/initialize.py | # @Author : bamtercelboo
# @Datetime : 2018/8/25 9:15
# @File : initialize.py
# @Last Modify Time : 2018/8/25 9:15
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : initialize.py
FUNCTION : None
"""
import numpy as np
import torch
import torch.nn as nn
def init_cnn_weight(cnn_layer, seed=1337):
... | 3,324 | 28.6875 | 86 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/models/Sequence_Label.py | # @Author : bamtercelboo
# @Datetime : 2018/9/14 8:43
# @File : Sequence_Label.py
# @Last Modify Time : 2018/9/14 8:43
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Sequence_Label.py
FUNCTION : None
"""
import torch
import torch.nn as nn
import random
import numpy as np
import time
from models.Bi... | 4,205 | 36.553571 | 125 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/models/BiLSTM_CNN.py | # @Author : bamtercelboo
# @Datetime : 2018/8/17 16:06
# @File : BiLSTM.py
# @Last Modify Time : 2018/8/17 16:06
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : BiLSTM.py
FUNCTION : None
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padde... | 3,897 | 33.192982 | 124 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/Dataloader/Instance.py | # coding=utf-8
# @Author : bamtercelboo
# @Datetime : 2018/1/30 15:56
# @File : Instance.py
# @Last Modify Time : 2018/1/30 15:56
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : Instance.py
FUNCTION : Data Instance
"""
import torch
import random
from DataUtils.Common import *
torch.manual_seed(see... | 646 | 16.486486 | 46 | py |
KazNERD | KazNERD-main/BiLSTM_CNN_CRF/Dataloader/DataLoader_NER.py | # @Author : bamtercelboo
# @Datetime : 2018/1/30 15:58
# @File : DataConll2003_Loader.py
# @Last Modify Time : 2018/1/30 15:58
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE :
FUNCTION :
"""
import os, pdb
import re
import random
import torch
from Dataloader.Instance import Instance
from DataUtils.Co... | 5,703 | 29.666667 | 95 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/test.py | import pickle
import sqlite3
from policy_gradients.agent import Trainer
import git
import numpy as np
import os
import copy
import random
import argparse
from policy_gradients import models
from policy_gradients.torch_utils import ZFilter
import sys
import json
import torch
import torch.optim as optim
from cox.store im... | 16,747 | 51.501567 | 213 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/get_best_pickle.py | import os
import numpy as np
import argparse
import uuid
from cox.store import Store
import pickle
from policy_gradients.torch_utils import *
import torch as ch
# Avoid HDF5 error
os.environ['HDF5_USE_FILE_LOCKING']='FALSE'
def get_alg_name(name):
name = os.path.basename(os.path.dirname(name))
if 'trpo' in na... | 6,513 | 38.719512 | 177 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/run.py | from policy_gradients.agent import Trainer
import git
import pickle
import random
import numpy as np
import os
import argparse
import traceback
from policy_gradients import models
import sys
import json
import torch
from cox.store import Store, schema_from_dict
# Tee object allows for logging to both stdout and to fi... | 20,877 | 47.440835 | 189 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/cox.git/cox/store.py | import pandas as pd
import torch as ch
import numpy as np
import dill as pickle
from uuid import uuid4
from .utils import *
import os
import warnings
from tensorboardX import SummaryWriter
TABLE_OBJECT_DIR = '.table_objects'
SAVE_DIR = 'save'
STORE_BASENAME = 'store.h5'
TENSORBOARD_DIR = 'tensorboard'
COX_DATA_KEY = '... | 14,666 | 32.486301 | 83 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/tests.py | from torch_utils import *
import torch as ch
if __name__ == '__main__':
def func(x):
f1 = x[0] * x[0] * x[1]
f2 = x[2]/(x[1] * x[0])
f3 = x[2]
f4 = x[0]
return ch.stack([f1, f2, f3, f4])
def J(x):
return ch.tensor([
[2 * x[0] * x[1], x[0]**2, 0],
... | 1,571 | 27.071429 | 87 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/convex_relaxation.py | import random, sys, time, multiprocessing
from auto_LiRPA import BoundedModule, BoundedTensor, BoundedParameter
from auto_LiRPA.perturbations import *
from policy_gradients.models import activation_with_name
forward_one = True
## Step 1: Initial original model as usual, see model details in models/sample_models.py
... | 8,749 | 37.888889 | 125 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/steps.py | import functools
import torch as ch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
import numpy as np
import math
import time
from tqdm import tqdm
from torch.nn.utils import parameters_to_vector as flatten
from torch.nn.utils import vector_to_para... | 45,502 | 45.0091 | 163 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/logging.py | import torch as ch
import numpy as np
from .torch_utils import *
from torch.nn.utils import parameters_to_vector as flatten
from torch.nn.utils import vector_to_parameters as assign
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import pairwise_distances
from .steps import value_loss_return... | 3,474 | 36.365591 | 117 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/custom_env.py | import os
import numpy as np
from PIL import Image
from gym.spaces.discrete import Discrete
from gym.spaces.box import Box as Continuous
import gym
import random
from .torch_utils import RunningStat, ZFilter, Identity, StateWithTime, RewardFilter
class Env:
'''
A wrapper around the OpenAI gym environment that ... | 5,671 | 42.630769 | 127 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/torch_utils.py | import torch as ch
from torch.distributions.categorical import Categorical
import numpy as np
'''
Common functions/utilities implemented in PyTorch
Sorted into categories:
- General functions
- Actor-critic helpers
- Policy gradient (PPO/TRPO) helpers
- Normalization helpers
- Neural network helpers
- Initialization he... | 17,231 | 29.771429 | 118 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/agent.py | import torch
import torch as ch
import copy
import tqdm
import sys
import time
import dill
import torch.nn as nn
import torch.optim as optim
import numpy as np
import random
from copy import deepcopy
import gym
from auto_LiRPA import BoundedModule
from auto_LiRPA.eps_scheduler import LinearScheduler
from auto_LiRPA.bou... | 69,824 | 47.557024 | 181 | py |
ATLA_robust_RL | ATLA_robust_RL-main/src/policy_gradients/models.py | import torch.nn as nn
import math
import functools
import torch as ch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
from .torch_utils import *
'''
Neural network models for estimating value and policy functions
Contains:
- Initialization utilitie... | 27,931 | 34.902314 | 137 | py |
GaPT | GaPT-main/tools/math_utils.py | from typing import Tuple
import numba as nb
import numpy as np
import torch as t
import copy
dtype_torch = t.float64
@nb.jit(nopython=True)
def nb_balance_ss(F: np.ndarray, iters: int) -> np.ndarray:
dim = F.shape[0]
dtype = F.dtype
d = np.ones((dim,), dtype=dtype)
for k in range(iters):
for i ... | 2,402 | 20.845455 | 109 | py |
GaPT | GaPT-main/base/regressor/base_regressor.py | import abc
import gpytorch
import torch
import numpy as np
import logging
import os
from tqdm import tqdm
from base.gpytgp.gppyt_model import GPYTModel
from base.data.data_loader import GPDataLoader
from base.gpytgp.gppyt_trainer import GPYTrainer
from torch import optim
from tools.misc import siso_binary_search, dista... | 10,898 | 44.224066 | 119 | py |
GaPT | GaPT-main/base/gapt/kalman/k_filters.py | """
the model used in the kalman Filter:
x[k+1] = Ax[k] + Gu[k] + w[k]
z[k] = Hx[k] + v[n]
where
x is the state vector, y the measurement, w the process noise and v the measurement noise.
The kalman filter assumes that w and v are zero-mean, independent random variables with known
variances:
- E[ww'] = Q
- E[vv'] = R
N... | 6,890 | 37.932203 | 112 | py |
GaPT | GaPT-main/base/gapt/kernels/base_kernel.py | import abc
import torch as t
from collections import namedtuple
ContinuousDiscreteModel = namedtuple("ContinuousDiscreteModel", ["P0", "F", "L", "H", "Q"])
class BaseKernel(metaclass=abc.ABCMeta):
def __init__(self, t0: float = 0., **_kwargs):
"""
Parameters:
-----------
t0: float,... | 715 | 24.571429 | 113 | py |
GaPT | GaPT-main/base/gapt/kernels/periodic/k_periodic.py | import numpy as np
import torch as t
import math
from typing import Tuple, Union, List
from scipy.special import factorial, comb
from base.gapt.kernels.base_kernel import BaseKernel, ContinuousDiscreteModel
class Periodic(BaseKernel):
"""
The periodic family of kernels. The canonical form (based on the
Sq... | 3,700 | 37.957895 | 104 | py |
GaPT | GaPT-main/base/gapt/kernels/rbf/k_rbf.py | import numpy as np
import torch
import torch as t
import math
from typing import Tuple
from tools.math_utils import solve_lyap_vec, balance_ss
from base.gapt.kernels.base_kernel import BaseKernel, ContinuousDiscreteModel
class RBF(BaseKernel):
"""
The radial basis function (RBF) or squared exponential kernels... | 3,003 | 31.652174 | 99 | py |
GaPT | GaPT-main/base/gapt/kernels/matern/base_matern.py | from base.gapt.kernels.base_kernel import BaseKernel
import numpy as np
import torch as t
from scipy.special import binom
import math
from typing import Tuple
class Matern(BaseKernel):
"""
This class inherit from the base class "BaseKernel"
implementing the Matern kernels-based methods
"""
def __... | 2,247 | 34.125 | 106 | py |
GaPT | GaPT-main/base/gapt/kernels/matern/k_matern32.py | import torch as t
import logging
from base.gapt.kernels.base_kernel import ContinuousDiscreteModel
from base.gapt.kernels.matern.base_matern import Matern
from tools.math_utils import solve_lyap_vec, balance_ss
class Matern32(Matern):
"""
The Matern 3/2 kernels. Functions drawn from a GP with this kernels are... | 1,693 | 40.317073 | 113 | py |
GaPT | GaPT-main/base/gapt/kernels/matern/k_matern52.py | import torch as t
import logging
from base.gapt.kernels.base_kernel import ContinuousDiscreteModel
from base.gapt.kernels.matern.base_matern import Matern
from tools.math_utils import solve_lyap_vec, balance_ss
class Matern52(Matern):
"""
The Matern 5/2 kernels. Functions drawn from a GP with this kernels are... | 1,631 | 39.8 | 113 | py |
GaPT | GaPT-main/base/gapt/kernels/matern/k_matern12.py | import torch as t
from base.gapt.kernels.base_kernel import ContinuousDiscreteModel
from base.gapt.kernels.matern.base_matern import Matern
class Matern12(Matern):
"""
The Matern 1/2 kernels. Functions drawn from a GP with this kernels are not
differentiable anywhere. The kernels equation is
k(r) = σ... | 1,069 | 35.896552 | 98 | py |
GaPT | GaPT-main/base/gpytgp/gppyt_model.py | import gpytorch
import torch
class GPYTModel(gpytorch.models.ExactGP):
"""
Base ExactGPModel:
- train_x: N x D training tensor data features
- train_y N x M training tensor data labels
- likelihood: gpytorch.likelihoods
- kernels: gpytorch.kernels
"""
def __init__(self,... | 788 | 29.346154 | 77 | py |
GaPT | GaPT-main/base/gpytgp/gppyt_trainer.py | """
PYTORCH TRAINERS IMPLEMENTATIONS
"""
import torch
import logging
from tqdm import tqdm
class GPYTrainer:
"""
Trainer class for finding the hyperparameters
of Gaussian processes implemented in GPytorch
"""
def __init__(self, loss, gp_model, likelihood, train_loader, optimizer, config, verbose... | 2,230 | 31.808824 | 119 | py |
GaPT | GaPT-main/base/data/data_loader.py | import logging
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from base.data.data_sampler import CustomSampler
from base.data.base_dataset import BaseDataset
class GPDataLoader(DataLoader):
"""
This dataloader is intended for training the Gpy... | 4,460 | 43.168317 | 118 | py |
GaPT | GaPT-main/base/data/base_dataset.py | from torch.utils.data import Dataset
from abc import ABC, abstractmethod
import numpy as np
from tools.dsp_utils import SigFilter, Tools
import torch
class BaseDataset(Dataset, ABC):
"""
Base class for all the Dataset. The format is compliant with the dataloader schemes commonly used in
Pytorch.
... | 2,227 | 29.108108 | 109 | py |
GaPT | GaPT-main/base/data/data_sampler.py | from torch.utils.data import Sampler
from typing import Iterator, Sequence
class CustomSampler(Sampler[int]):
r"""Samples elements from a given list of indices, without replacement.
Args:
indices (sequence): a sequence of indices
generator (Generator): Generator used in sampling.
"""
i... | 664 | 27.913043 | 75 | py |
GaPT | GaPT-main/experiments/timing/inference_time_miso_rt.py | """
The script will evaluate the computational time for one sample inference for both the GPyTorch and the
KF models.
miso
"""
import copy
import gc
import logging
import numpy
import time
import numpy as np
import pandas as pd
import torch.random
from tqdm import tqdm
import json
from pathlib import Path
from datetime... | 8,998 | 36.032922 | 113 | py |
GaPT | GaPT-main/experiments/timing/inference_time_siso_rt.py | """
The script will evaluate the computational time for one sample inference for both the GPyTorch and the
KF models.
miso
"""
import copy
import gc
import logging
import numpy
import time
import numpy as np
import pandas as pd
import torch.random
from tqdm import tqdm
import json
from pathlib import Path
from datetime... | 8,807 | 35.7 | 128 | py |
GaPT | GaPT-main/experiments/drag/residual_arpl_miso.py | """
Residual lenarning MISO
"""
import logging
import json
import numpy as np
import pandas as pd
from pathlib import Path
import torch
from datetime import datetime
import matplotlib
import matplotlib.pyplot as plt
from configs import OUTPUT_DIR
from base.data.data_loader import GPDataLoader
from configs.config_parse... | 21,062 | 43.064854 | 119 | py |
GaPT | GaPT-main/experiments/drag/residual_arpl_siso.py | """
Residual lenarning SISO
"""
import logging
import json
import sys
import yaml
import math
import numpy as np
import pandas as pd
from pathlib import Path
import torch
from datetime import datetime
import matplotlib
import matplotlib.pyplot as plt
from configs import OUTPUT_DIR
from base.data.data_loader import GP... | 18,215 | 40.4 | 117 | py |
GaPT | GaPT-main/model/datasets/arpl.py | import torch
import pandas as pd
from base.data.base_dataset import BaseDataset
class Arpl(BaseDataset):
"""
The Dataset class to handle the csv generated by acquisition by the ARPL lab,
NYU. The original data is stored in RosBags and the .csv files are generated
with the python script "arpl_stand_alo... | 2,153 | 44.829787 | 113 | py |
GaPT | GaPT-main/model/regressors/rbf.py | import gpytorch
from base.gapt.kalman import KalmanSISO, KalmanMISO
from base.gapt.kernels import RBF
from base.regressor import GPRegressor
import logging
class RBFModel(GPRegressor):
def __init__(self, id_model: str, input_dim: int = 1):
# Define the RBF model name, this is useful to handle multiple in... | 2,161 | 41.392157 | 114 | py |
GaPT | GaPT-main/model/regressors/materns.py | import gpytorch
from base.gapt.kalman import KalmanSISO, KalmanMISO
from base.gapt.kernels import Matern12, Matern32, Matern52
from base.regressor import GPRegressor
import logging
r"""
Below the classes for the Matérn family. According to the equation of the kernel and the implementation in Gpytorch
thr e smoothness p... | 6,874 | 46.743056 | 120 | py |
GaPT | GaPT-main/model/regressors/periodic.py | import logging
import gpytorch
from base.gapt.kalman import KalmanSISO, KalmanMISO
from base.gapt.kernels import Periodic
from base.regressor import GPRegressor
class PerRbfModel(GPRegressor):
def __init__(self, id_model: str, input_dim: int = 1):
# Define the RBF model name, this is useful to handle mult... | 3,446 | 49.691176 | 121 | py |
character-bert | character-bert-main/main.py | # Adapted from Huggingface's transformers library:
# https://github.com/allenai/allennlp/
""" Main script. """
import os
import logging
import argparse
import datetime
from collections import Counter
import torch
from torch.nn import CrossEntropyLoss
from transformers import (
BertConfig,
BertTokenizer,
... | 11,712 | 32.755043 | 97 | py |
character-bert | character-bert-main/download.py | # Adapted from:
# https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url
""" Download pre-trained models from Google drive. """
import os
import argparse
import tarfile
import logging
import requests
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(filename)... | 4,006 | 36.801887 | 115 | py |
character-bert | character-bert-main/utils/character_cnn.py | # Functions are imported/adapted from AllenAI's AllenNLP library:
# https://github.com/allenai/allennlp/
""" Indexer functions for ELMo-style character embeddings. """
from typing import Dict, List, Callable, Any
import torch
PADDING_VALUE = 0
def _make_bos_eos(
character: int,
padding_character: in... | 5,864 | 33.910714 | 100 | py |
character-bert | character-bert-main/utils/misc.py | """ Miscellaneous utils. """
import random
import logging
import torch
import numpy as np
def set_seed(seed_value):
""" Sets the random seed to a given value. """
random.seed(seed_value)
np.random.seed(seed_value)
torch.manual_seed(seed_value)
if torch.cuda.is_available():
torch.cuda.manua... | 391 | 23.5 | 50 | py |
character-bert | character-bert-main/utils/training.py | # Functions are adapted from Huggingface's transformers library:
# https://github.com/huggingface/transformers
""" Defines training and evaluation functions. """
import os
import logging
import datetime
import tqdm
import numpy as np
import sklearn.metrics as sklearn_metrics
import metrics.sequence_labelling as seqev... | 8,849 | 39.227273 | 106 | py |
character-bert | character-bert-main/utils/data.py | # Functions are adapted from Huggingface's transformers library:
# https://github.com/huggingface/transformers
""" Helper functions. """
import random
import logging
from collections import namedtuple
import tqdm
import numpy as np
import torch
from torch.utils.data import TensorDataset
def retokenize(examples, tok... | 13,028 | 41.029032 | 100 | py |
character-bert | character-bert-main/modeling/character_cnn.py | # Functions are imported/adapted from AllenAI's AllenNLP library:
# https://github.com/allenai/allennlp/
"""Defines the character embedding module (adapted from ELMo)"""
import json
from typing import Dict, Callable
import numpy
import torch
from utils.character_cnn import CharacterMapper, CharacterIndexer
class ... | 9,562 | 37.560484 | 104 | py |
character-bert | character-bert-main/modeling/character_bert.py | # Functions are adapted from Huggingface's transformers library:
# https://github.com/allenai/allennlp/
""" Defines the main CharacterBERT PyTorch class. """
import torch
from torch import nn
from transformers.modeling_bert import BertPreTrainedModel, BertEncoder, BertPooler
from modeling.character_cnn import Charact... | 9,516 | 44.754808 | 122 | py |
client-superstaq | client-superstaq-main/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
import os
import sys
from typing impo... | 2,428 | 35.253731 | 97 | py |
focal_calibration | focal_calibration-main/evaluate.py | import os
import sys
import torch
import random
import argparse
from torch import nn
import matplotlib.pyplot as plt
import torch.backends.cudnn as cudnn
# Import dataloaders
import Data.cifar10 as cifar10
import Data.cifar100 as cifar100
import Data.tiny_imagenet as tiny_imagenet
# Import network architectures
from ... | 7,842 | 34.328829 | 130 | py |
focal_calibration | focal_calibration-main/train_utils.py | '''
This module contains methods for training models with different loss functions.
'''
import torch
from torch.nn import functional as F
from torch import nn
from Losses.loss import cross_entropy, focal_loss, focal_loss_adaptive
from Losses.loss import mmce, mmce_weighted
from Losses.loss import brier_score
loss_f... | 3,176 | 30.77 | 135 | py |
focal_calibration | focal_calibration-main/temperature_scaling.py | '''
Code to perform temperature scaling. Adapted from https://github.com/gpleiss/temperature_scaling
'''
import torch
import numpy as np
from torch import nn, optim
from torch.nn import functional as F
from Metrics.metrics import ECELoss
class ModelWithTemperature(nn.Module):
"""
A thin decorator, which wrap... | 3,591 | 33.209524 | 113 | py |
focal_calibration | focal_calibration-main/train.py | '''
Script for training models.
'''
from torch import optim
import torch
import torch.utils.data
import argparse
import torch.backends.cudnn as cudnn
import random
import json
import sys
# Import dataloaders
import Data.cifar10 as cifar10
import Data.cifar100 as cifar100
import Data.tiny_imagenet as tiny_imagenet
# ... | 13,922 | 39.008621 | 149 | py |
focal_calibration | focal_calibration-main/Data/cifar100.py | """
Create train, valid, test iterators for CIFAR-100.
Train set size: 45000
Val set size: 5000
Test set size: 10000
"""
import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
def get_train_valid_loader(batch_size,... | 5,443 | 31.795181 | 82 | py |
focal_calibration | focal_calibration-main/Data/cifar10.py | """
Create train, valid, test iterators for CIFAR-10.
Train set size: 45000
Val set size: 5000
Test set size: 10000
"""
import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
def get_train_valid_loader(batch_size,
... | 5,395 | 31.70303 | 82 | py |
focal_calibration | focal_calibration-main/Data/svhn.py |
import os
import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
def get_train_valid_loader(batch_size,
augment,
random_... | 4,471 | 30.272727 | 76 | py |
focal_calibration | focal_calibration-main/Data/tiny_imagenet.py | """
Create train, val, test iterators for Tiny ImageNet.
Train set size: 100000
Val set size: 10000
Test set size: 10000
Number of classes: 200
Link: https://tiny-imagenet.herokuapp.com/
"""
import os
import torch
import numpy as numpy
from torchvision import datasets
from torchvision import transforms
from torch.uti... | 6,288 | 34.937143 | 117 | py |
focal_calibration | focal_calibration-main/Metrics/ood_test_utils.py | # Utility functions to get OOD detection ROC curves and AUROC scores
# Ideally should be agnostic of model architectures
import torch
import torch.nn.functional as F
from sklearn import metrics
def entropy(net_output):
p = F.softmax(net_output, dim=1)
logp = F.log_softmax(net_output, dim=1)
plogp = p * l... | 3,065 | 38.818182 | 143 | py |
focal_calibration | focal_calibration-main/Metrics/metrics.py | '''
Metrics to measure calibration of a trained deep neural network.
References:
[1] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks.
arXiv preprint arXiv:1706.04599, 2017.
'''
import math
import torch
import numpy as np
from torch import nn
from torch.nn import functiona... | 9,347 | 35.092664 | 119 | py |
focal_calibration | focal_calibration-main/Losses/brier_score.py | '''
Implementation of Brier Score.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class BrierScore(nn.Module):
def __init__(self):
super(BrierScore, self).__init__()
def forward(self, input, target):
if input.dim()>2:
inpu... | 895 | 32.185185 | 84 | py |
focal_calibration | focal_calibration-main/Losses/loss.py | '''
Implementation of the following loss functions:
1. Cross Entropy
2. Focal Loss
3. Cross Entropy + MMCE_weighted
4. Cross Entropy + MMCE
5. Brier Score
'''
from torch.nn import functional as F
from Losses.focal_loss import FocalLoss
from Losses.focal_loss_adaptive_gamma import FocalLossAdaptive
from Losses.mmce imp... | 1,228 | 27.581395 | 70 | py |
focal_calibration | focal_calibration-main/Losses/mmce.py | '''
Implementation of the MMCE (MMCE_m) and MMCE_weighted (MMCE_w).
Reference:
[1] A. Kumar, S. Sarawagi, U. Jain, Trainable Calibration Measures for Neural Networks from Kernel Mean Embeddings.
ICML, 2018.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable... | 6,583 | 46.028571 | 157 | py |
focal_calibration | focal_calibration-main/Losses/focal_loss.py | '''
Implementation of Focal Loss.
Reference:
[1] T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollar, Focal loss for dense object detection.
arXiv preprint arXiv:1708.02002, 2017.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(nn.Modu... | 1,084 | 32.90625 | 99 | py |
focal_calibration | focal_calibration-main/Losses/focal_loss_adaptive_gamma.py | '''
Implementation of Focal Loss with adaptive gamma.
Reference:
[1] T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollar, Focal loss for dense object detection.
arXiv preprint arXiv:1708.02002, 2017.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
fro... | 2,268 | 31.884058 | 99 | py |
focal_calibration | focal_calibration-main/Net/resnet_tiny_imagenet.py | '''
Pytorch implementation of ResNet models.
Reference:
[1] He, K., Zhang, X., Ren, S., Sun, J.: Deep residual learning for image recognition. In: CVPR, 2016.
'''
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
# --- HELPERS ---
def conv3x3(in_planes, out_planes, stride=1):
'''
... | 5,254 | 27.715847 | 109 | py |
focal_calibration | focal_calibration-main/Net/resnet.py | '''
Pytorch implementation of ResNet models.
Reference:
[1] He, K., Zhang, X., Ren, S., Sun, J.: Deep residual learning for image recognition. In: CVPR, 2016.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, plane... | 4,320 | 33.293651 | 102 | py |
focal_calibration | focal_calibration-main/Net/densenet.py | '''
Pytorch impplementation of DenseNet.
Reference:
[1] Gao Huang, Zhuang Liu, and Kilian Q. Weinberger. Densely connected convolutional networks.
arXiv preprint arXiv:1608.06993, 2016a.
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __in... | 3,725 | 33.183486 | 96 | py |
focal_calibration | focal_calibration-main/Net/wide_resnet.py | '''
Pytorch implementation of wide resnet.
Reference:
[1] S. Zagoruyko and N. Komodakis. Wide residual networks. arXiv preprint arXiv:1605.07146, 2016.
'''
import torch
import torch.nn as nn
import math
def conv3x3(in_planes, out_planes, stride=1):
" 3x3 convolution with padding "
return nn.Conv2d(in_planes... | 3,441 | 30.87037 | 109 | py |
LERG | LERG-main/explain.py | from lerg.perturbation_models import RandomPM, LIMERandomPM
from lerg.RG_explainers import LERG_LIME, LERG_R, LERG_SHAP, LERG_SHAP_log
from target_models import GPT
import torch
import tqdm
import sys
import json
import os
from datetime import datetime
from argparse import ArgumentParser
parser = ArgumentParser()
par... | 2,528 | 36.746269 | 136 | py |
LERG | LERG-main/eval.py | from target_models import GPT
from lerg.metrics import ppl_c, ppl_c_add
from lerg.visualize import plot_interactions
import tqdm
import sys
import json
import torch
import numpy as np
import os
from datetime import datetime
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("--explain_m... | 3,915 | 44.534884 | 164 | py |
LERG | LERG-main/target_models.py | import torch
import torch.nn.functional as F
from transformers import OpenAIGPTTokenizer, OpenAIGPTLMHeadModel
from transformers import GPT2Tokenizer, GPT2LMHeadModel
def get_sum_multi_head_attentions(multi_head_attentions):
return sum(torch.sum(x,1) for x in multi_head_attentions)
class GPT:
def __init__(sel... | 4,007 | 55.450704 | 135 | py |
LERG | LERG-main/lerg/RG_explainers.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.linear_model import Ridge
import numpy as np
import random
class Explainer():
"""
The base class for various explainers
arguments:
model_f:... | 8,905 | 39.666667 | 166 | py |
LERG | LERG-main/lerg/perturbation_models.py | import torch
import warnings
import math
import random
import numpy as np
import pdb
import scipy as sp
import sklearn
from transformers import BartTokenizer, BartForConditionalGeneration
import torch
def binomial_coef_dist(n):
dist = [math.comb(n, i+1) for i in range(n//2)]
total = sum(dist)
dist = [dens... | 4,757 | 33.230216 | 130 | py |
LERG | LERG-main/lerg/metrics.py | import torch
import numpy as np
import random
import pdb
from scipy.stats import skew
from collections import Counter
def get_expl(x, expl, ratio=0.2, remain_masks=False):
if expl is None:
x_entities = [tok for tok in x if random.random() < ratio] if not remain_masks else [tok if random.random() < ratio e... | 2,391 | 33.666667 | 171 | py |
GAN-STEM-Conv2MultiSlice | GAN-STEM-Conv2MultiSlice-master/fnn.py | from __future__ import print_function, division
import scipy
#from keras.datasets import mnist
from keras_contrib.layers.normalization import InstanceNormalization
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from ke... | 11,895 | 34.939577 | 130 | py |
GAN-STEM-Conv2MultiSlice | GAN-STEM-Conv2MultiSlice-master/FNN/fnn.py | from __future__ import print_function, division
import scipy
#from keras.datasets import mnist
from keras_contrib.layers.normalization import InstanceNormalization
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from ke... | 11,895 | 34.939577 | 130 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.