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 |
|---|---|---|---|---|---|---|
ExHiRD-DKG | ExHiRD-DKG-master/onmt/modules/embeddings.py | """ Embeddings module """
import math
import torch
import torch.nn as nn
from onmt.modules.util_class import Elementwise
class PositionalEncoding(nn.Module):
"""
Implements the sinusoidal positional encoding for
non-recurrent neural networks.
Implementation based on "Attention Is All You Need"
... | 7,660 | 35.831731 | 79 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/modules/global_attention.py | """ Global attention modules (Luong / Bahdanau) """
import torch
import torch.nn as nn
import torch.nn.functional as F
from onmt.modules.sparse_activations import sparsemax
from onmt.utils.misc import aeq, sequence_mask
# add by wchen
from onmt.utils.invalid_sent_processor import valid_src_compress, recover_src
# Th... | 49,777 | 36.710606 | 118 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/modules/gate.py | """ ContextGate module """
import torch
import torch.nn as nn
def context_gate_factory(gate_type, embeddings_size, decoder_size,
attention_size, output_size):
"""Returns the correct ContextGate class"""
gate_types = {'source': SourceContextGate,
'target': TargetCont... | 3,635 | 38.521739 | 79 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/modules/weight_norm.py | """ Weights normalization modules """
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
def get_var_maybe_avg(namespace, var_name, training, polyak_decay):
""" utility for retrieving polyak averaged params
Update average
"""
v = getattr(namespace, ... | 9,775 | 38.578947 | 78 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/modules/position_ffn.py | """
Position feed-forward network from "Attention is All You Need"
"""
import torch.nn as nn
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int):... | 1,216 | 28.682927 | 76 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/modules/multi_headed_attn.py | """ Multi-Head Attention module """
import math
import torch
import torch.nn as nn
# from onmt.utils.misc import aeq
class MultiHeadedAttention(nn.Module):
"""
Multi-Head Attention module from
"Attention is All You Need"
:cite:`DBLP:journals/corr/VaswaniSPUJGKP17`.
Similar to standard `dot` atte... | 6,382 | 32.072539 | 71 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/models/stacked_rnn.py | """ Implementation of ONMT RNN for Input Feeding Decoding """
import torch
import torch.nn as nn
class StackedLSTM(nn.Module):
"""
Our own implementation of stacked LSTM.
Needed for the decoder, because we do input feeding.
"""
def __init__(self, num_layers, input_size, rnn_size, dropout):
... | 1,994 | 29.227273 | 66 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/models/model.py | """ Onmt NMT Model base class definition """
import torch.nn as nn
class NMTModel(nn.Module):
"""
Core trainable object in OpenNMT. Implements a trainable interface
for a simple, generic encoder + decoder model.
Args:
encoder (:obj:`EncoderBase`): an encoder object
decoder (:obj:`RNNDecod... | 12,016 | 41.613475 | 121 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/models/model_saver.py | import os
import torch
import torch.nn as nn
from collections import deque
from onmt.utils.logging import logger
def build_model_saver(model_opt, opt, model, fields, optim):
model_saver = ModelSaver(opt.save_model,
model,
model_opt,
... | 4,418 | 32.992308 | 121 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/models/sru.py | """ SRU Implementation """
# flake8: noqa
import subprocess
import platform
import os
import re
import configargparse
import torch
import torch.nn as nn
from torch.autograd import Function
from collections import namedtuple
# For command-line option parsing
class CheckSRU(configargparse.Action):
def __init__(sel... | 24,303 | 36.218989 | 81 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/decoders/transformer.py | """
Implementation of "Attention is All You Need"
"""
import torch
import torch.nn as nn
import numpy as np
import onmt
from onmt.modules.position_ffn import PositionwiseFeedForward
MAX_SIZE = 5000
class TransformerDecoderLayer(nn.Module):
"""
Args:
d_model (int): the dimension of keys/values/queries... | 9,320 | 34.041353 | 79 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/decoders/decoder.py | """ Base Class and function for Decoders """
import torch
import torch.nn as nn
import numpy as np
import onmt.models.stacked_rnn
from onmt.utils.misc import aeq
from onmt.utils.rnn_factory import rnn_factory
from onmt.utils.source_representation_queue import SourceReprentationQueue
class RNNDecoderBase(nn.Module)... | 126,761 | 45.212906 | 162 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/decoders/ensemble.py | """
Ensemble decoding.
Decodes using multiple models simultaneously,
combining their prediction distributions by averaging.
All models in the ensemble must share a target vocabulary.
"""
import torch
import torch.nn as nn
from onmt.encoders.encoder import EncoderBase
from onmt.models import NMTModel
import onmt.mode... | 5,273 | 36.404255 | 79 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/decoders/cnn_decoder.py | """
Implementation of the CNN Decoder part of
"Convolutional Sequence to Sequence Learning"
"""
import torch
import torch.nn as nn
import onmt.modules
from onmt.utils.cnn_factory import shape_transform, GatedConv
SCALE_WEIGHT = 0.5 ** 0.5
class CNNDecoder(nn.Module):
"""
Decoder built on CNN, based on :ci... | 4,819 | 35.240602 | 78 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/encoders/image_encoder.py | """ Image Encoder """
import torch.nn as nn
import torch.nn.functional as F
import torch
class ImageEncoder(nn.Module):
"""
A simple encoder convolutional -> recurrent neural network for
image src.
Args:
num_layers (int): number of encoder layers.
bidirectional (bool): bidirectional e... | 4,047 | 35.8 | 76 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/encoders/rnn_encoder.py | """Define RNN-based encoders."""
import torch.nn as nn
import torch.nn.functional as F
# add by wchen
import torch
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from onmt.encoders.encoder import EncoderBase
from onmt.utils.rnn_factory import ... | 29,126 | 41.896907 | 149 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/encoders/audio_encoder.py | """ Audio encoder """
import math
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from onmt.utils.rnn_factory import rnn_factory
class AudioEncoder(nn.Module):
"""
A simple encoder convolutional -> recurrent neur... | 4,964 | 40.375 | 77 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/encoders/encoder.py | """Base class for encoders and generic multi encoders."""
import torch.nn as nn
from onmt.utils.misc import aeq
class EncoderBase(nn.Module):
"""
Base encoder class. Specifies the interface used by different encoder types
and required by :obj:`onmt.Models.NMTModel`.
.. mermaid::
graph BT
... | 1,329 | 24.09434 | 79 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/encoders/transformer.py | """
Implementation of "Attention is All You Need"
"""
import torch.nn as nn
import onmt
from onmt.encoders.encoder import EncoderBase
# from onmt.utils.misc import aeq
from onmt.modules.position_ffn import PositionwiseFeedForward
class TransformerEncoderLayer(nn.Module):
"""
A single layer of the transforme... | 3,677 | 30.982609 | 75 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/encoders/cnn_encoder.py | """
Implementation of "Convolutional Sequence to Sequence Learning"
"""
import torch.nn as nn
from onmt.encoders.encoder import EncoderBase
from onmt.utils.cnn_factory import shape_transform, StackedCNN
SCALE_WEIGHT = 0.5 ** 0.5
class CNNEncoder(EncoderBase):
"""
Encoder built on CNN based on
:cite:`DBL... | 1,449 | 31.954545 | 67 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/translate/translation_server.py | #!/usr/bin/env python
""" REST Translation server """
from __future__ import print_function
import sys
import os
import configargparse
import time
import json
import threading
import re
import traceback
import torch
import onmt.opts
from onmt.utils.logging import init_logger
from onmt.translate.translator import buil... | 18,312 | 33.683712 | 79 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/translate/translation.py | """ Translation main class """
from __future__ import unicode_literals, print_function
import torch
import itertools
from torchtext.data import Field, NestedField
class HRTranslationBuilder(object):
"""
Build a word-based hierarchical translation from the batch output
of translator and the underlying dic... | 12,376 | 37.921384 | 117 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/translate/beam.py | from __future__ import division
import torch
from onmt.translate import penalties
class Beam(object):
"""
Class for managing the internals of the beam search process.
Takes care of beams, back pointers, and scores.
Args:
size (int): beam size
pad, bos, eos (int): indices of padding, be... | 8,929 | 35.748971 | 78 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/translate/penalties.py | from __future__ import division
import torch
class PenaltyBuilder(object):
"""
Returns the Length and Coverage Penalty function for Beam Search.
Args:
length_pen (str): option name of length pen
cov_pen (str): option name of cov pen
"""
def __init__(self, cov_pen, length_pen):
... | 2,269 | 27.024691 | 74 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/translate/translator.py | #!/usr/bin/env python
""" Translator Class and builder """
from __future__ import print_function
import configargparse
import codecs
import os
import math
import torch
from itertools import count
from onmt.utils.misc import tile
import onmt.model_builder
import onmt.translate.beam
import onmt.inputters as inputters
... | 84,994 | 38.495818 | 135 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/rnn_factory.py | """
RNN tools
"""
import torch.nn as nn
import onmt.models
def rnn_factory(rnn_type, **kwargs):
""" rnn factory, Use pytorch version when available. """
no_pack_padded_seq = False
if rnn_type == "SRU":
# SRU doesn't support PackedSequence.
no_pack_padded_seq = True
rnn = onmt.mode... | 432 | 23.055556 | 60 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/optimizers.py | """ Optimizers class """
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm_
from onmt.utils import use_gpu
import operator
import functools
from copy import copy
from math import sqrt
def build_optim(model, opt, checkpoint):
""" Build optimizer """
saved_optimizer_state_dict =... | 18,178 | 40.694954 | 86 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/loss.py | """
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import onmt
from onmt.modules.sparse_losses import SparsemaxLoss
from onmt.modules.sparse_activations... | 15,155 | 41.21727 | 139 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/misc.py | # -*- coding: utf-8 -*-
import torch
def aeq(*args):
"""
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments), \
"Not all arguments have the same value: " + str(args)
def sequence_mask(le... | 1,352 | 23.160714 | 70 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/invalid_sent_processor.py | """
Author: wchen@cse.cuhk.edu.hk
This includes
"""
import torch
from onmt.utils.misc import aeq
def valid_src_compress(src, sent_nums, sent_lens):
"""
Select all the valid sentences and remove the invalid ones.
:param sent_batch: [batch, s_num, s_len, *]
:param sent_nums: [batch]
:param sent_len... | 2,377 | 26.022727 | 73 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/cnn_factory.py | """
Implementation of "Convolutional Sequence to Sequence Learning"
"""
import torch
import torch.nn as nn
import torch.nn.init as init
import onmt.modules
SCALE_WEIGHT = 0.5 ** 0.5
def shape_transform(x):
""" Tranform the size of the tensors to fit for conv input. """
return torch.unsqueeze(torch.transpose... | 1,620 | 28.472727 | 78 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/statistics.py | """ Statistics calculation utility """
from __future__ import division
import time
import math
import sys
# from torch.distributed.deprecated import get_rank
from onmt.utils.distributed import all_gather_list
from onmt.utils.logging import logger
class Statistics(object):
"""
Accumulator for loss statistics.... | 6,296 | 34.178771 | 158 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/distributed.py | """ Pytorch Distributed utils
This piece of code was heavily inspired by the equivalent of Fairseq-py
https://github.com/pytorch/fairseq
"""
from __future__ import print_function
import math
import pickle
import torch.distributed
from onmt.utils.logging import logger
def is_master(opt, device_id):
ret... | 3,926 | 30.926829 | 77 | py |
ExHiRD-DKG | ExHiRD-DKG-master/onmt/utils/loss_old.py | """
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import onmt
from onmt.modules.sparse_losses import SparsemaxLoss
from onmt.modules.sparse_activations... | 12,165 | 37.378549 | 79 | py |
gnn-model-explainer | gnn-model-explainer-master/main.py | import pickle
import torch
import cv2
import numpy as np
from explainer import explain
from utils import math_utils
from utils import io_utils
use_cuda = torch.cuda.is_available()
# TODO: Is this still used?
#####
#
# 1) Load trained GNN model
# 2) Load a query computation graph
#
#####
MODEL_PATH = "gcn-vanilla... | 2,088 | 22.47191 | 81 | py |
gnn-model-explainer | gnn-model-explainer-master/models_pyg.py | import torch
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch_geometric.nn import GCNConv, GATConv
class GCNNet(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, label_dim, num_layers,
pred_hidden_dims=[], concat=True, bn=True, dropout=0.0, add_self=False, arg... | 1,644 | 36.386364 | 95 | py |
gnn-model-explainer | gnn-model-explainer-master/explainer_main.py | """ explainer_main.py
Main user interface for the explainer module.
"""
import argparse
import os
import sklearn.metrics as metrics
from tensorboardX import SummaryWriter
import pickle
import shutil
import torch
import models
import utils.io_utils as io_utils
import utils.parser_utils as parser_utils
from exp... | 10,138 | 30.883648 | 127 | py |
gnn-model-explainer | gnn-model-explainer-master/models.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F
import numpy as np
# GCN basic operation
class GraphConv(nn.Module):
def __init__(
self,
input_dim,
output_dim,
add_self=False,
normalize_embedding=False,
dropout=0.0,
... | 21,012 | 32.946688 | 120 | py |
gnn-model-explainer | gnn-model-explainer-master/explain_pyg.py | import gengraph
import random
import torch_geometric
from utils import featgen
import numpy as np
import utils.io_utils as io_utils
from configs import arg_parse
import torch
import torch.nn as nn
from torch.autograd import Variable
from models_pyg import GCNNet
import os
from torch_geometric.utils import from_networkx... | 3,730 | 33.229358 | 98 | py |
gnn-model-explainer | gnn-model-explainer-master/train.py | """ train.py
Main interface to train the GNNs that will be later explained.
"""
import argparse
import os
import pickle
import random
import shutil
import time
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as Figure... | 37,410 | 30.677392 | 119 | py |
gnn-model-explainer | gnn-model-explainer-master/explainer/explain.py | """ explain.py
Implementation of the explainer.
"""
import math
import time
import os
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import networkx as nx
import... | 36,363 | 35.992879 | 136 | py |
gnn-model-explainer | gnn-model-explainer-master/utils/train_utils.py | '''train_utils.py
Some training utilities.
'''
import torch.optim as optim
def build_optimizer(args, params, weight_decay=0.0):
filter_fn = filter(lambda p : p.requires_grad, params)
if args.opt == 'adam':
optimizer = optim.Adam(filter_fn, lr=args.lr, weight_decay=weight_decay)
elif args.opt =... | 1,040 | 42.375 | 114 | py |
gnn-model-explainer | gnn-model-explainer-master/utils/graph_utils.py | """graph_utils.py
Utility for sampling graphs from a dataset.
"""
import networkx as nx
import numpy as np
import torch
import torch.utils.data
class GraphSampler(torch.utils.data.Dataset):
""" Sample graphs and nodes in graph
"""
def __init__(
self,
G_list,
features="default"... | 5,669 | 34.886076 | 86 | py |
gnn-model-explainer | gnn-model-explainer-master/utils/io_utils.py | """ io_utils.py
Utilities for reading and writing logs.
"""
import os
import statistics
import re
import csv
import numpy as np
import pandas as pd
import scipy as sc
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import networkx as nx
import tensorboardX
import cv2
import ... | 24,650 | 30.972763 | 112 | py |
gnn-model-explainer | gnn-model-explainer-master/utils/math_utils.py | """ math_utils.py
Math utilities.
"""
import torch
def exp_moving_avg(x, decay=0.9):
'''Exponentially decaying moving average.
'''
shadow = x[0]
a = [shadow]
for v in x[1:]:
shadow -= (1-decay) * (shadow-v)
a.append(shadow)
return a
def tv_norm(input, tv_beta):
'''Tot... | 557 | 22.25 | 77 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/load_model.py | import torch
import os
from seq2sql_model_classes import Seq2SQL_v1
from transformers import RobertaConfig, RobertaModel, RobertaTokenizer
device = torch.device("cuda")
def get_roberta_model():
# Initializing a RoBERTa configuration
configuration = RobertaConfig()
# Initializing a model from the configu... | 3,413 | 34.936842 | 158 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/roberta_training.py | import torch
device = torch.device("cuda")
def get_where_column(conds):
"""
[ [where_column, where_operator, where_value],
[where_column, where_operator, where_value], ...
]
"""
where_column = []
for cond in conds:
where_column.append(cond[0])
return where_column
def get_wh... | 9,091 | 32.061818 | 131 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/seq2sql_model_internal_functions.py |
import os
import json
import random as rd
from copy import deepcopy
from matplotlib.pylab import *
import math
import torch
import torchvision.datasets as dsets
import torch.nn as nn
import torch.nn.functional as F
# import torch_xla
# import torch_xla.core.xla_model as xm
device = torch.device("cuda")
def enco... | 11,523 | 27.314496 | 158 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/seq2sql_model_training_functions.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from matplotlib.pylab import *
from copy import deepcopy
#import torch_xla
#import torch_xla.core.xla_model as xm
device = torch.device("cuda")
def Loss_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi):
"""
:para... | 15,593 | 28.202247 | 122 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/seq2sql_model_testing.py | import torch
#import torch_xla
#import torch_xla.core.xla_model as xm
device = torch.device("cuda")
def generate_sql_q(sql_i, tb):
sql_q = []
for b, sql_i1 in enumerate(sql_i):
tb1 = tb[b]
sql_q1 = generate_sql_q1(sql_i1, tb1)
sql_q.append(sql_q1)
return sql_q
def generate_sql_q1... | 6,048 | 33.764368 | 116 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/dev_function.py | from dbengine_sqlnet import DBEngine
import os
import seq2sql_model_training_functions
import corenlp_local
import load_data
import roberta_training
import infer_functions
import torch
from tqdm.notebook import tqdm
import seq2sql_model_testing
def train(seq2sql_model,roberta_model,model_optimizer,roberta_optimizer,... | 18,626 | 52.068376 | 227 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/load_data.py | import json
import torch
import os
import json
from matplotlib.pylab import *
def get_data(file_path: str,batch_size: int):
'''
Gets data from the dataset and creates a data loader
Arguments:
file_path: The path to the directory in which the dataset is contained
batch_size: Batch size to be used f... | 5,189 | 32.921569 | 157 | py |
RoBERTa-NL2SQL | RoBERTa-NL2SQL-main/seq2sql_model_classes.py | import os
import json
from copy import deepcopy
from matplotlib.pylab import *
import torch
import torch.nn as nn
import torch.nn.functional as F
from seq2sql_model_internal_functions import *
#import torch_xla
#import torch_xla.core.xla_model as xm
device = torch.device("cuda")
class Seq2SQL_v1(nn.Module):
def ... | 42,955 | 39.486334 | 127 | py |
mbpo_pytorch | mbpo_pytorch-main/model.py | import torch
torch.set_default_tensor_type(torch.cuda.FloatTensor)
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
import gzip
import itertools
device = torch.device('cuda')
num_train = 60000 # 60k train examples
num_test = 10000 # 10k test e... | 16,395 | 40.826531 | 141 | py |
mbpo_pytorch | mbpo_pytorch-main/predict_env.py | import numpy as np
class PredictEnv:
def __init__(self, model, env_name, model_type):
self.model = model
self.env_name = env_name
self.model_type = model_type
def _termination_fn(self, env_name, obs, act, next_obs):
# TODO
if env_name == "Hopper-v2":
assert... | 4,384 | 35.848739 | 126 | py |
mbpo_pytorch | mbpo_pytorch-main/main_mbpo.py | import argparse
import time
import gym
import torch
import numpy as np
from itertools import count
import logging
import os
import os.path as osp
import json
from sac.replay_memory import ReplayMemory
from sac.sac import SAC
from model import EnsembleDynamicsModel
from predict_env import PredictEnv
from sample_env i... | 14,840 | 46.720257 | 143 | py |
mbpo_pytorch | mbpo_pytorch-main/tf_models/constructor.py | import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from tf_models.fc import FC
from tf_models.bnn import BNN
def construct_model(obs_dim=11, act_dim=3, rew_dim=1, hidden_dim=200, num_networks=7, num_elites=5, session=None):
print('[ BNN ] Observation dim {} | Action dim: {} | Hidden... | 3,385 | 36.208791 | 124 | py |
mbpo_pytorch | mbpo_pytorch-main/sac/main.py | import argparse
import datetime
import gym
import numpy as np
import itertools
import torch
from sac.sac import SAC
from tensorboardX import SummaryWriter
from sac.replay_memory import ReplayMemory
parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')
parser.add_argument('--env-name', default=... | 6,109 | 42.333333 | 150 | py |
mbpo_pytorch | mbpo_pytorch-main/sac/sac.py | import os
import torch
import torch.nn.functional as F
from torch.optim import Adam
from sac.utils import soft_update, hard_update
from sac.model import GaussianPolicy, QNetwork, DeterministicPolicy
class SAC(object):
def __init__(self, num_inputs, action_space, args):
torch.autograd.set_detect_anomaly(T... | 6,025 | 44.651515 | 133 | py |
mbpo_pytorch | mbpo_pytorch-main/sac/utils.py | import math
import torch
def create_log_gaussian(mean, log_std, t):
quadratic = -((0.5 * (t - mean) / (log_std.exp())).pow(2))
l = mean.shape
log_z = log_std
z = l[-1] * math.log(2 * math.pi)
log_p = quadratic.sum(dim=-1) - log_z.sum(dim=-1) - 0.5 * z
return log_p
def logsumexp(inputs, dim=Non... | 965 | 32.310345 | 83 | py |
mbpo_pytorch | mbpo_pytorch-main/sac/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
LOG_SIG_MAX = 2
LOG_SIG_MIN = -20
epsilon = 1e-6
# Initialize Policy weights
def weights_init_(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight, gain=1)
torch.nn.init.co... | 5,085 | 32.682119 | 87 | py |
QuantumLocalization | QuantumLocalization-main/qnn_test.py | import time
import numpy as np
import glob
import os
import json
import pickle
import torch
import torch.nn.functional as F
import torchquantum as tq
import threading
from qiskit import IBMQ
from typing import Tuple
from collections import Counter
from torch.utils.data import DataLoader
from dataset import QuantumSensi... | 32,194 | 44.666667 | 149 | py |
QuantumLocalization | QuantumLocalization-main/dataset.py | '''the dataset
'''
import os
import numpy as np
from torch.utils.data import Dataset
class QuantumSensingDataset(Dataset):
def __init__(self, root_dir: str):
self.root_dir = root_dir
self.phase_dir = os.path.join(root_dir, 'phase')
self.label_dir = os.path.join(root_dir, 'label')
... | 1,124 | 32.088235 | 78 | py |
QuantumLocalization | QuantumLocalization-main/localization.py | '''
Quantum enhanced localization
'''
import math
import numpy as np
import json
import torch
import os
import pickle
import torchquantum as tq
from typing import Tuple
from bisect import bisect_left
from itertools import accumulate
from collections import Counter
from torch.utils.data import DataLoader
from utility i... | 47,489 | 48.059917 | 199 | py |
QuantumLocalization | QuantumLocalization-main/qnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchquantum as tq
import torchquantum.functional as tqf
import numpy as np
from qiskit import QuantumCircuit
from torch.utils.data import DataLoader
from dataset import QuantumSensingDataset
from torchquantum.plugins import (
append_fixed_ga... | 15,625 | 38.459596 | 130 | py |
QuantumLocalization | QuantumLocalization-main/qnn_train.py | import time
import numpy as np
import glob
import os
import json
import torch
import pickle
import torchquantum as tq
import torchquantum.functional as tqf
import torch.nn.functional as F
import torch.optim as optim
# import matplotlib.pyplot as plt
from torch import Tensor
from torchquantum.plugins.qiskit_plugin impor... | 23,520 | 40.483245 | 128 | py |
ADAM | ADAM-main/src/adam/jax/jax_like.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
from dataclasses import dataclass
from typing import Union
import jax.numpy as jnp
import numpy.typing ... | 6,229 | 29.841584 | 80 | py |
ADAM | ADAM-main/src/adam/jax/computations.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
import jax.numpy as jnp
import numpy as np
from jax import grad, jit, vmap
from adam.core.rbd_algorithm... | 7,356 | 34.370192 | 90 | py |
ADAM | ADAM-main/src/adam/jax/__init__.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
from .computations import KinDynComputations
from .jax_like import JaxLike
| 291 | 40.714286 | 80 | py |
ADAM | ADAM-main/src/adam/pytorch/torch_like.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
from dataclasses import dataclass
from typing import Union
import numpy.typing as ntp
import torch
fro... | 6,797 | 30.472222 | 88 | py |
ADAM | ADAM-main/src/adam/pytorch/computations.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
import numpy as np
import torch
from adam.core.rbd_algorithms import RBDAlgorithms
from adam.model impo... | 7,600 | 34.685446 | 92 | py |
ADAM | ADAM-main/src/adam/pytorch/__init__.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
from .computations import KinDynComputations
from .torch_like import TorchLike
| 295 | 41.285714 | 80 | py |
ADAM | ADAM-main/tests/test_pytorch_computations.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
import logging
import icub_models
import idyntree.swig as idyntree
import numpy as np
import pytest
imp... | 6,861 | 31.67619 | 88 | py |
ADAM | ADAM-main/tests/test_Jax_computations.py | # Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.
# This software may be modified and distributed under the terms of the
# GNU Lesser General Public License v2.1 or any later version.
import logging
import icub_models
import idyntree.swig as idyntree
import jax.numpy as jnp
import numpy... | 6,298 | 30.183168 | 86 | py |
filterpy | filterpy-master/docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# FilterPy documentation build configuration file, created by
# sphinx-quickstart on Sat Nov 22 14:54:37 2014.
#
# 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
# a... | 11,304 | 29.972603 | 80 | py |
Educational_QG | Educational_QG-main/evaluate.py | # Import packages
import os
import re
import string
from collections import Counter
import pandas as pd
import torch
import language_tool_python
from rouge_score import rouge_scorer
from nltk import word_tokenize, ngrams
from nltk.translate.bleu_score import sentence_bleu
import numpy as np
from tqdm import tqdm
from... | 22,183 | 43.279441 | 685 | py |
Educational_QG | Educational_QG-main/trainer_seq2seq_qa.py | # coding=utf-8
# Copyright 2021 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-2.0
#
# Unless require... | 5,572 | 42.20155 | 118 | py |
Educational_QG | Educational_QG-main/run_qa.py | #!/usr/bin/env python
# coding=utf-8
# Copyright 2021 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-... | 47,892 | 43.386469 | 123 | py |
Educational_QG | Educational_QG-main/qgmodel_t.py | import pytorch_lightning as pl
from transformers import T5ForConditionalGeneration, AdamW, T5TokenizerFast, FlaxT5ForConditionalGeneration, \
T5Tokenizer, AutoTokenizer
from config import SEP_TOKEN
# pre-train >>> fine-tune
#
class QGModel_t(pl.LightningModule):
def __init__(self):
super().__init__()... | 3,937 | 57.776119 | 173 | py |
Educational_QG | Educational_QG-main/qgmodel_t2.py | import pytorch_lightning as pl
from transformers import T5ForConditionalGeneration, AdamW, T5TokenizerFast, FlaxT5ForConditionalGeneration, \
T5Tokenizer, AutoTokenizer
from config import SEP_TOKEN
# pre-train >>> fine-tune
#
class QGModel_t2(pl.LightningModule):
def __init__(self):
super().__init__(... | 2,138 | 40.134615 | 146 | py |
Educational_QG | Educational_QG-main/utils.py | import numpy
from transformers import T5TokenizerFast as T5Tokenizer, T5ForConditionalGeneration, AutoTokenizer
from config import CONTEXT, QUESTION, ANSWER, SEP_TOKEN, SOURCE_MAX_TOKEN_LEN, TARGET_MAX_TOKEN_LEN
science_Atokenizer = AutoTokenizer.from_pretrained('./t_from_checkpoint_science_t5_pre')
science_model = T... | 6,851 | 36.856354 | 143 | py |
Educational_QG | Educational_QG-main/utils_qa.py | # 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-2.0
#
# Unless require... | 22,773 | 50.759091 | 135 | py |
Educational_QG | Educational_QG-main/sciq_only_fine-tune_model.py | # Import packages
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
# T5TokenizerFast
from transformers import ( AutoTokenizer as T5Tokenizer, AutoConfig, FlaxT5ForConditionalGeneration, AutoTok... | 6,703 | 30.622642 | 156 | py |
Educational_QG | Educational_QG-main/race_only_fine_tune_model.py | # Import packages
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
# T5TokenizerFast
from transformers import ( AutoTokenizer as T5Tokenizer, AutoConfig, FlaxT5ForConditionalGeneration, AutoTok... | 6,791 | 30.590698 | 156 | py |
Educational_QG | Educational_QG-main/fine-tune_model_leaf.py | # Import packages
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
# from transformers import (
# T5TokenizerFast as T5Tokenizer, AutoConfig, FlaxT5ForConditionalGeneration
# )
from transfo... | 6,535 | 29.830189 | 156 | py |
Educational_QG | Educational_QG-main/run_t5_mlm.py | #!/usr/bin/env python
# coding=utf-8
# Copyright 2021 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-... | 44,147 | 43.729483 | 209 | py |
Educational_QG | Educational_QG-main/run_seq2seq_qa.py | #!/usr/bin/env python
# coding=utf-8
# Copyright 2021 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-... | 31,351 | 43.470922 | 119 | py |
Educational_QG | Educational_QG-main/finetune_test.py | from transformers import T5ForConditionalGeneration, AutoTokenizer
model = T5ForConditionalGeneration.from_pretrained("./t_t5_pre/", from_flax=True)
tokenizer = AutoTokenizer.from_pretrained('./t_t5_pre/')
input_ids = tokenizer.encode("summarize: Hello, my dog is cute", return_tensors="pt") # Batch size 1
outputs = ... | 361 | 39.222222 | 101 | py |
Educational_QG | Educational_QG-main/qgmodel.py | import pytorch_lightning as pl
from transformers import T5ForConditionalGeneration, AdamW, T5TokenizerFast, FlaxT5ForConditionalGeneration, T5Tokenizer
from config import SEP_TOKEN
# pre-train >>> fine-tune
#
class QGModel(pl.LightningModule):
def __init__(self):
super().__init__()
MODEL_NAME = '... | 2,143 | 40.230769 | 120 | py |
Educational_QG | Educational_QG-main/sciq_sqaud_fine_tune_model.py | # Import packages
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
# T5TokenizerFast
from transformers import ( AutoTokenizer as T5Tokenizer, AutoConfig, FlaxT5ForConditionalGeneration, AutoTok... | 6,465 | 29.937799 | 156 | py |
Educational_QG | Educational_QG-main/old_scripts/convert.py | import jax
from jax import numpy as jnp
from transformers import FlaxRobertaForMaskedLM, RobertaForMaskedLM, FlaxT5ForConditionalGeneration
import jax.numpy as jnp
import jax
import flax
import flax.linen as nn
from flax.training import train_state, checkpoints
import optax
import numpy as np
def to_f32(t):
return... | 1,123 | 34.125 | 114 | py |
Educational_QG | Educational_QG-main/old_scripts/fine-tune_model_leaf_T.py | # Import packages
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from transformers import (
T5TokenizerFast as T5Tokenizer, AutoConfig, FlaxT5ForConditionalGeneration, T5TokenizerFast,
... | 6,475 | 29.838095 | 156 | py |
Educational_QG | Educational_QG-main/old_scripts/fine_tune_model_custom.py | # Import packages
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from transformers import (
T5TokenizerFast as T5Tokenizer, AutoConfig, FlaxT5ForConditionalGeneration
)
from qgmodel impo... | 6,534 | 30.119048 | 156 | py |
Capsule | Capsule-master/Capsule_Keras.py | #! -*- coding: utf-8 -*-
# refer: https://kexue.fm/archives/5112
from keras import activations
from keras import backend as K
from keras.engine.topology import Layer
def squash(x, axis=-1):
s_squared_norm = K.sum(K.square(x), axis, keepdims=True) + K.epsilon()
scale = K.sqrt(s_squared_norm)/ (0.5 + s_squared_... | 3,356 | 39.939024 | 112 | py |
Capsule | Capsule-master/capsule_test.py | #! -*- coding: utf-8 -*-
from Capsule_Keras import *
from keras import utils
from keras.datasets import mnist
from keras.models import Model
from keras.layers import *
from keras import backend as K
#准备训练数据
batch_size = 128
num_classes = 10
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = mnist.lo... | 3,481 | 31.240741 | 110 | py |
PVT | PVT-master/main_part_seg.py | from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR
from data import _ShapeNetDataset
from model.partpvt import pvt_partseg
import numpy as np
from torch.utils.data import DataLoader... | 12,051 | 43.637037 | 119 | py |
PVT | PVT-master/main_cls.py | from __future__ import print_function
import os
import argparse
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from data import ModelNetDataLoader
from model.pvt import pvt
import numpy as np
from torch.utils.data import DataLoader
from util import cal_loss, IOStream
imp... | 8,189 | 41.435233 | 119 | py |
PVT | PVT-master/main_semseg.py | from __future__ import print_function
import os
import argparse
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR
from data import S3DIS
from model.sempvt import pvt_semseg
import numpy as np
from torch.utils.data import DataLoader
from util import cal_loss, IOStrea... | 12,202 | 45.39924 | 124 | py |
PVT | PVT-master/data.py | import os
import glob
import h5py
import numpy as np
import torch
from torch.utils.data import Dataset
import json
def pc_normalize(pc):
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
pc = pc / m
return pc
def farthest_point_sample(xyz, npoint):
"""... | 13,225 | 40.202492 | 121 | py |
PVT | PVT-master/util.py | import torch
import torch.nn.functional as F
from torch import nn, Tensor
class CircleLoss(nn.Module):
def __init__(self, m: float, gamma: float) -> None:
super(CircleLoss, self).__init__()
self.m = m
self.gamma = gamma
self.soft_plus = nn.Softplus()
def forward(self, sp: Tenso... | 1,790 | 27.887097 | 96 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.