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 |
|---|---|---|---|---|---|---|
CANTM | CANTM-main/GateMIcateLib/models/bertSimple.py | from transformers import BertModel
from .miscLayer import BERT_Embedding, CLSAW_TopicModel_Base, WVHidden
import os
import torch.nn.functional as F
import torch
import torch.nn as nn
class BERT_Simple(CLSAW_TopicModel_Base):
def __init__(self, config, **kwargs):
super().__init__(config=config)
se... | 1,100 | 25.853659 | 71 | py |
CANTM | CANTM-main/GateMIcateLib/models/bertPure.py | from transformers import BertModel
from .miscLayer import BERT_Embedding, CLSAW_TopicModel_Base, WVHidden
import os
import torch.nn.functional as F
import torch
import torch.nn as nn
class BERT_Simple(CLSAW_TopicModel_Base):
def __init__(self, config, **kwargs):
super().__init__(config=config)
se... | 1,102 | 25.902439 | 72 | py |
CANTM | CANTM-main/GateMIcateLib/models/NVDM.py | import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class NVDM(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super().__... | 3,804 | 31.801724 | 117 | py |
CANTM | CANTM-main/GateMIcateLib/models/NVDM_ori.py | import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class ORINVDM(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super()... | 2,445 | 28.46988 | 117 | py |
CANTM | CANTM-main/GateMIcateLib/readers/ReaderBase.py | import random
import math
import json
import torch
class CLSReaderBase:
def __init__(self, postProcessor=None, shuffle=False, config=None):
self.label_count_dict = {}
self.label_weights_list = None
self._readConfigs(config)
self.shuffle = shuffle
self.postProcessor = postPro... | 3,290 | 31.584158 | 92 | py |
CANTM | CANTM-main/GateMIcateLib/readers/WVmisInfoReader.py | import random
import math
import json
import torch
from .ReaderBase import CLSReaderBase
class WVmisInfoDataIter(CLSReaderBase):
def __init__(self, merged_json, label_field='category', **kwargs):
super().__init__(**kwargs)
self.label_field = label_field
self._initReader(merged_json)
... | 1,266 | 29.902439 | 70 | py |
CANTM | CANTM-main/GateMIcateLib/readers/tsvBinaryFolderReader.py | import random
import math
import json
import torch
import glob
import os
from .ReaderBase import CLSReaderBase
class TsvBinaryFolderReader(CLSReaderBase):
def __init__(self, input_dir, pos_folder='positive', neg_folder='negative', text_filed=1, id_field=0, **kwargs):
super().__init__(**kwargs)
sel... | 1,959 | 34.636364 | 117 | py |
CANTM | CANTM-main/GateMIcateLib/readers/aclImdbReader.py | import random
import math
import json
import torch
import glob
import os
from .ReaderBase import CLSReaderBase
class ACLimdbReader(CLSReaderBase):
def __init__(self, input_dir, **kwargs):
super().__init__(**kwargs)
pos_dir = os.path.join(input_dir,'pos')
neg_dir = os.path.join(input_dir,'ne... | 1,338 | 29.431818 | 69 | py |
coderec_programming_states | coderec_programming_states-main/action_prediction/generate_features.py | from requests import session
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import json
import copy
import json
from tqdm import tqdm
import pickle
import logging
from tree_sitter import Language, Parser
logging.basicConfig(level=logging.INFO)
import argparse
import math
from get_code_label imp... | 13,075 | 41.732026 | 349 | py |
coderec_programming_states | coderec_programming_states-main/action_prediction/action_prediction_xgb.py |
from requests import session
import matplotlib.pyplot as plt
import pandas as pd
import json
import copy
import numpy as np, scipy.stats as st
import json
from tqdm import tqdm
import pickle
import logging
import argparse
import math
from xgboost import XGBClassifier
# logistic regression
from sklearn.linear_model im... | 8,716 | 41.940887 | 176 | py |
triple-descent-paper | triple-descent-paper-master/nn-numeric/main.py | import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import scipy
from collections import defaultdict
from utils import rot
from utils import get_data, hinge_regression, hinge_classification
from model import FullyConnected
import argparse
def train_and_test(model, tr_data, te_data, cr... | 6,525 | 40.303797 | 165 | py |
triple-descent-paper | triple-descent-paper-master/nn-numeric/utils.py | # some useful functions
import os
import shutil
import math
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
import numpy as np
def hinge_regression(output, target, epsilon=.1, type='quadratic'):
power = 1 if type=='linear' else 2
delta = (output-target).abs()-epsilon
loss =... | 6,540 | 38.167665 | 124 | py |
triple-descent-paper | triple-descent-paper-master/nn-numeric/model.py | import torch
import torch.nn.functional as F
import torch.nn as nn
class MulConstant(nn.Module):
def __init__(self, constant=10):
super(MulConstant, self).__init__()
self.constant = constant
def forward(self, x):
return x * self.constant
def backward(self, g): # is this necessary?... | 2,314 | 34.615385 | 149 | py |
triple-descent-paper | triple-descent-paper-master/nn-numeric/run.py | import os
import time
import subprocess
import itertools
import collections
import argparse
import torch
import numpy as np
from utils import copy_py, who_am_i
def create_script(params):
script = '''#!/bin/bash
#SBATCH --gres=gpu:1
#SBATCH --mem=10GB
#SBATCH --nodes=1
#SBATCH --output={name}.out
#SBATCH --job-na... | 2,016 | 27.814286 | 298 | py |
reco-gym | reco-gym-master/setup.py | import pathlib
from setuptools import setup, find_packages
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="recogym",
version="0.1.2.4",
description="Ope... | 1,140 | 24.355556 | 84 | py |
reco-gym | reco-gym-master/leaderboard_entries/pytorch_CB_log.py | from recogym import build_agent_init
from recogym.agents import PyTorchMLRAgent, pytorch_mlr_args
pytorch_mlr_args['n_epochs'] = 30
pytorch_mlr_args['learning_rate'] = 0.01
pytorch_mlr_args['logIPS'] = True
agent = build_agent_init('PyTorchMLRAgent', PyTorchMLRAgent, {**pytorch_mlr_args})
| 292 | 31.555556 | 82 | py |
reco-gym | reco-gym-master/leaderboard_entries/pytorch_CB.py | from recogym import build_agent_init
from recogym.agents import PyTorchMLRAgent, pytorch_mlr_args
pytorch_mlr_args['n_epochs'] = 30
pytorch_mlr_args['learning_rate'] = 0.01
agent = build_agent_init('PyTorchMLRAgent', PyTorchMLRAgent, {**pytorch_mlr_args})
| 257 | 35.857143 | 82 | py |
reco-gym | reco-gym-master/leaderboard_entries/pytorch_likelihood.py | from recogym import build_agent_init
from recogym.agents import PyTorchMLRAgent, pytorch_mlr_args
pytorch_mlr_args['n_epochs'] = 30
pytorch_mlr_args['learning_rate'] = 0.01,
pytorch_mlr_args['ll_IPS'] = False,
pytorch_mlr_args['alpha'] = 1.0
agent = build_agent_init('PyTorchMLRAgent', PyTorchMLRAgent, {**pytorch_mlr_a... | 326 | 35.333333 | 82 | py |
reco-gym | reco-gym-master/recogym/agents/pytorch_mlr.py | import numpy as np
#import tensorflow as tf
import torch
from torch.autograd import Variable
from torch.nn import functional as F
from scipy.special import expit
from recogym.agents import (
AbstractFeatureProvider,
Model,
ModelBasedAgent,
ViewsFeaturesProvider
)
from ..envs.configuration import Config... | 52,651 | 38.030393 | 128 | py |
reco-gym | reco-gym-master/recogym/agents/organic_mf.py | import numpy as np
import torch
from ..envs.configuration import Configuration
from .abstract import Agent
# Default Arguments ----------------------------------------------------------
organic_mf_square_args = {
'num_products': 10,
'embed_dim': 5,
'mini_batch_size': 32,
'loss_function': torch.nn.Cros... | 3,630 | 30.034188 | 81 | py |
reco-gym | reco-gym-master/recogym/agents/nn_ips.py | import numpy as np
import torch
import torch.optim as optim
from numpy.random.mtrand import RandomState
from torch import nn
from .abstract import AbstractFeatureProvider, ViewsFeaturesProvider, Model, ModelBasedAgent
from ..envs.configuration import Configuration
nn_ips_args = {
'num_products': 10,
'number_... | 4,794 | 29.935484 | 98 | py |
reco-gym | reco-gym-master/recogym/agents/bandit_mf.py | import torch
import numpy as np
from torch import nn, optim, Tensor
from ..envs.configuration import Configuration
from .abstract import Agent
# Default Arguments.
bandit_mf_square_args = {
'num_products': 10,
'embed_dim': 5,
'mini_batch_size': 32,
'loss_function': nn.BCEWithLogitsLoss(),
'optim_... | 4,211 | 32.165354 | 75 | py |
reco-gym | reco-gym-master/recogym/agents/__init__.py |
from .abstract import (
Agent,
FeatureProvider,
AbstractFeatureProvider,
ViewsFeaturesProvider,
Model,
ModelBasedAgent
)
from .bayesian_poly_vb import BayesianAgentVB
from .bandit_mf import BanditMFSquare, bandit_mf_square_args
from .bandit_count import BanditCount, bandit_count_args
from .ra... | 878 | 31.555556 | 85 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/main.py | import numpy as np, os, time, random
from envs_repo.constructor import EnvConstructor
from models.constructor import ModelConstructor
from core.params import Parameters
import argparse, torch
from algos.erl_trainer import ERL_Trainer
parser = argparse.ArgumentParser()
####################### COMMANDLINE - ARGUMENTS ... | 2,890 | 50.625 | 110 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/core/utils.py |
from torch import nn
from torch.autograd import Variable
import random, pickle, copy, argparse
import numpy as np, torch, os
from torch import distributions
import torch.nn.functional as F
class Tracker(): #Tracker
def __init__(self, save_folder, vars_string, project_string):
self.vars_string = vars_stri... | 6,665 | 23.780669 | 121 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/core/buffer.py |
import numpy as np
import random
import torch
from torch.multiprocessing import Manager
class Buffer():
"""Cyclic Buffer stores experience tuples from the rollouts
Parameters:
capacity (int): Maximum number of experiences to hold in cyclic buffer
"""
def __init__(self, capacity, buffer_gpu=False):
self.c... | 1,624 | 27.017241 | 135 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/core/runner.py |
from core import utils as utils
import numpy as np
import torch
# Rollout evaluate an agent in a complete game
@torch.no_grad()
def rollout_worker(id, type, task_pipe, result_pipe, store_data, model_bucket, env_constructor):
env = env_constructor.make_env()
np.random.seed(id) ###make sure the random seeds... | 1,834 | 32.981481 | 111 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/core/params.py | import os
from torch.utils.tensorboard import SummaryWriter
class Parameters:
def __init__(self, parser):
"""Parameter class stores all parameters for policy gradient
Parameters:
None
Returns:
None
"""
#Env args
self.env_name = vars(parser.... | 2,717 | 36.75 | 111 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/models/discrete_models.py | import torch, random
import torch.nn as nn
from torch.distributions import Normal, RelaxedOneHotCategorical, Categorical
import torch.nn.functional as F
class CategoricalPolicy(nn.Module):
"""Critic model
Parameters:
args (object): Parameter class
"""
def __init__(self, state_dim... | 4,229 | 24.178571 | 109 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/models/constructor.py | import torch
class ModelConstructor:
def __init__(self, state_dim, action_dim, hidden_size, actor_seed=None, critic_seed=None):
"""
A general Environment Constructor
"""
self.state_dim = state_dim
self.action_dim = action_dim
self.hidden_size = hidden_size
s... | 1,629 | 29.754717 | 94 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/models/continous_models.py |
import torch
import torch.nn as nn
from torch.distributions import Normal, RelaxedOneHotCategorical
from core.utils import weights_init_
import torch.nn.functional as F
def weights_init_(m, lin_gain=1.0, bias_gain=0.1):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight, gain=lin_gain)
... | 3,612 | 26.792308 | 84 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/algos/sac.py | import os
import torch
import torch.nn.functional as F
from torch.optim import Adam
from core.utils import soft_update, hard_update
class SAC(object):
def __init__(self, args, model_constructor):
self.gamma = args.gamma
self.tau = args.tau
self.alpha = args.alpha
self.writer = arg... | 3,599 | 43.444444 | 143 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/algos/erl_trainer.py |
import numpy as np, os, time, random, torch, sys
from algos.neuroevolution import SSNE
from core import utils
from core.runner import rollout_worker
from torch.multiprocessing import Process, Pipe, Manager
from core.buffer import Buffer
import torch
class ERL_Trainer:
def __init__(self, args, model_constructor, en... | 8,262 | 38.347619 | 217 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/algos/neuroevolution.py | import random
import numpy as np
import math
import core.utils as utils
class SSNE:
def __init__(self, args):
self.gen = 0
self.args = args;
self.population_size = self.args.pop_size
self.writer = args.writer
#RL TRACKERS
self.rl_policy = None
self.selection_stats = {'elite': 0, 'selected': 0, 'discar... | 8,888 | 30.299296 | 144 | py |
Evolutionary-Reinforcement-Learning | Evolutionary-Reinforcement-Learning-master/algos/ddqn.py | import os, random
import torch
import torch.nn.functional as F
from torch.optim import Adam
from core.utils import soft_update, hard_update
class DDQN(object):
def __init__(self, args, model_constructor):
self.gamma = args.gamma
self.tau = args.tau
self.alpha = args.alpha
self.dev... | 2,338 | 36.725806 | 112 | py |
MAX-Toxic-Comment-Classifier | MAX-Toxic-Comment-Classifier-master/core/bert_pytorch.py | #
# Copyright 2018-2019 IBM Corp. 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 required by applicable law... | 8,564 | 43.378238 | 112 | py |
MAX-Toxic-Comment-Classifier | MAX-Toxic-Comment-Classifier-master/core/model.py | #
# Copyright 2018-2019 IBM Corp. 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 required by applicable law... | 4,848 | 39.07438 | 116 | py |
Vita-CLIP | Vita-CLIP-main/training/VitaCLIP_text_encoder.py | import torch
import torch.nn as nn
import copy
from collections import OrderedDict
from typing import Union, List
from pkg_resources import packaging
from VitaCLIP_text_encoder_utils import SimpleTokenizer as _Tokenizer
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
return x * torch.sigm... | 11,343 | 37.454237 | 137 | py |
Vita-CLIP | Vita-CLIP-main/training/checkpoint.py | #!/usr/bin/env python
import argparse
import os
import torch
import torch.distributed as dist
def setup_arg_parser(parser: argparse.ArgumentParser):
parser.add_argument('--checkpoint_dir', type=str,
help='checkpoint output path')
parser.add_argument('--auto_resume', action='store_tru... | 3,710 | 35.742574 | 125 | py |
Vita-CLIP | Vita-CLIP-main/training/VitaCLIP_vision_encoder.py | from typing import Tuple
import numpy as np
from einops import rearrange
import torch
import torch.nn as nn
import torch.nn.functional as F
from operator import mul
from functools import reduce
import math
from VitaCLIP_vision_encoder_utils import QuickGELU, LayerNorm, TransformerEncoderLayer, ImagePatchEmbed2D
c... | 4,541 | 34.209302 | 129 | py |
Vita-CLIP | Vita-CLIP-main/training/VitaCLIP_model.py | #!/usr/bin/env python
from typing import Tuple
import numpy as np
import torch
import torch.nn as nn
from VitaCLIP_vision_encoder import CLIPVisionEncoder
from VitaCLIP_text_encoder import CLIPTextEncoder, TextPromptLearner
class VitaCLIP(nn.Module):
def __init__(
self,
# load weights
... | 5,576 | 32.8 | 100 | py |
Vita-CLIP | Vita-CLIP-main/training/VitaCLIP_vision_encoder_utils.py | #!/usr/bin/env python
from collections import OrderedDict
from typing import Tuple
import torch
import torch.nn as nn
from operator import mul
from functools import reduce
import math
'''
QuickGELU and LayerNorm w/ fp16 from official CLIP repo
(https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca16573... | 7,573 | 34.064815 | 133 | py |
Vita-CLIP | Vita-CLIP-main/training/train.py | #!/usr/bin/env python
import argparse
from datetime import datetime
import builtins
import torch
import torch.distributed as dist
import sys
sys.path.append('./')
import video_dataset
import checkpoint
from VitaCLIP_model import VitaCLIP
from collections import OrderedDict
def setup_print(is_master: bool):
""... | 13,336 | 42.161812 | 120 | py |
Vita-CLIP | Vita-CLIP-main/video_dataset/dataloader.py | #!/usr/bin/env python
import argparse
from typing import Dict
import torch
import torch.distributed as dist
from .dataset import VideoDataset, DummyDataset
def setup_arg_parser(parser: argparse.ArgumentParser):
parser.add_argument('--train_list_path', type=str,
help='path to training dat... | 6,717 | 41.518987 | 138 | py |
Vita-CLIP | Vita-CLIP-main/video_dataset/transform.py | #!/usr/bin/env python3
# Originate from: https://github.com/facebookresearch/SlowFast/blob/fee19d699c49a81f33b890c5ff592bbb11aa5c54/slowfast/datasets/transform.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import math
import numpy as np
# import cv2
import random
import tor... | 27,344 | 33.18125 | 139 | py |
Vita-CLIP | Vita-CLIP-main/video_dataset/dataset.py | #!/usr/bin/env python
import os, sys
from typing import Optional
import av
import io
import numpy as np
import torch
from torchvision import transforms
from .transform import create_random_augment, random_resized_crop
class VideoDataset(torch.utils.data.Dataset):
def __init__(
self, list_path: str, dat... | 7,185 | 36.821053 | 115 | py |
Vita-CLIP | Vita-CLIP-main/video_dataset/random_erasing.py | #!/usr/bin/env python
# Originates from: https://github.com/facebookresearch/SlowFast/blob/fee19d699c49a81f33b890c5ff592bbb11aa5c54/slowfast/datasets/random_erasing.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This implementation is based on
https://github.com/rwightman/pytorch-image... | 7,056 | 37.353261 | 145 | py |
Vita-CLIP | Vita-CLIP-main/video_dataset/rand_augment.py | #!/usr/bin/env python
# Originates from: https://github.com/facebookresearch/SlowFast/blob/fee19d699c49a81f33b890c5ff592bbb11aa5c54/slowfast/datasets/rand_augment.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This implementation is based on
https://github.com/rwightman/pytorch-image-m... | 16,366 | 29.478585 | 143 | py |
dstc9-SIMMC | dstc9-SIMMC-master/tools/simmc_dataset.py | import json
import pdb
import re
import string
import torch
from nltk.tokenize import WordPunctTokenizer
from torch.utils.data import Dataset
"""
The dialog intents have the shapes:
DA:<DIALOG_ACT>:<ACTIVITY>:<OBJECT> or DA:<DIALOG_ACT>:<ACTIVITY>:<OBJECT>.<attribute>
Examples:
DA:INFORM:GET:CLOTHING.embellishment
... | 22,029 | 47.955556 | 193 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/preprocessing.py | import argparse
import datetime
import math
import os
import pdb
import random
import sys
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
sys.path.append('.')
from config import special_toks
from tools.simmc_dataset import SIMMCDatasetForResponseGeneration
from transformers import... | 16,410 | 42.762667 | 160 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/eval.py | import argparse
import json
import os
import pdb
import sys
import time
import string
import torch
from torch.utils.data import DataLoader
sys.path.append('.')
from config import special_toks, train_conf
from dataset import FastDataset
from models import BlindStatelessLSTM, MultiAttentiveTransformer
from tools.simmc... | 8,110 | 32.795833 | 133 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/train.py | import argparse
import datetime
import json
import math
import os
import pdb
import pickle
import random
import sys
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
from config import model_conf, special_toks, train_conf
from dataset import FastDataset
from models import BlindStatel... | 15,568 | 42.733146 | 186 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/dataset/processed_dataset.py | import pdb
import random
import numpy as np
import torch
from torch.utils.data import Dataset
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
class FastDataset(Dataset):
"""Dataset with preprocessed data for response generation subtask
self.data.keys() = dict_keys(['dial_ids',... | 4,071 | 43.26087 | 165 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/models/bert.py | import pdb
import torch
import torch.nn as nn
from transformers import BertConfig, BertModel
class BertEncoder(nn.Module):
def __init__(self, pretrained, freeze=False):
super(BertEncoder, self).__init__()
configuration = BertConfig()
self.bert = BertModel(config=configuration).from_pretr... | 728 | 29.375 | 79 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/models/embednets.py | import pdb
import numpy as np
import torch
import torch.nn as nn
from spellchecker import SpellChecker
class ItemEmbeddingNetwork(nn.Module):
"""Base class for word embedding layer initialization and weights loading
Args:
nn (torch.nn.Module): inherits from torch.nn.Module
"""
def __init__(s... | 5,715 | 39.828571 | 150 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/models/old_encoder.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class SingleEncoder(nn.Module):
def __init__(self,
input_size,
hidden_size,
dropout_prob,
... | 10,368 | 36.981685 | 140 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/models/decoder.py | import math
import pdb
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
#the value with which to mask the attention
# DO NOT USE '-INF' BECAUSE IT WILL GENERATE NaN AFTER SOFTMAX FOR PADDING ROWS (filled with all 0's)
_MASKING_VALUE=-1e30
class Decoder(nn.Module):
def __init... | 17,844 | 42.630807 | 168 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/models/matransformer.py | import math
import pdb
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .embednets import ItemEmbeddingNetwork, WordEmbeddingNetwork
from .decoder import Decoder
from .old_encoder import SingleEncoder
from .bert import BertEncoder
from transformers import BertTokenizer #todo r... | 18,570 | 51.312676 | 155 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/models/blindstateless.py | import pdb
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .embednets import WordEmbeddingNetwork
class BlindStatelessLSTM(nn.Module):
"""Implementation of a blind and stateless LSTM for ac... | 7,099 | 42.82716 | 156 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_response_generation/utilities/dataparallelv2.py | from torch.nn.parallel._functions import Scatter
from torch.nn.parallel import DataParallel
import torch
import math
# This code was copied from torch.nn.parallel and adapted for DataParallel to chunk lists instead of duplicating them
# (this is really all this code is here for)
def scatter(inputs, target_gpus, dim=... | 2,498 | 41.355932 | 117 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/preprocessing.py | import argparse
import datetime
import math
import os
import pdb
import random
import sys
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
import sys
sys.path.append('.')
from config import TrainConfig
from tools.simmc_dataset import SIMMCDatasetForActionPrediction
class Collate... | 8,706 | 38.220721 | 117 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/eval.py | import argparse
import json
import os
import pdb
import sys
import torch
from torch.utils.data import DataLoader
sys.path.append('.')
from config import TrainConfig
from dataset import FastDataset
from models import BlindStatefulLSTM, BlindStatelessLSTM, MMStatefulLSTM
from tools.simmc_dataset import SIMMCDatasetFor... | 7,874 | 35.971831 | 120 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/train.py | import argparse
import datetime
import math
import os
import pdb
import random
import sys
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
from config import TrainConfig
from models import BlindStatefulLSTM, BlindStatelessLSTM, MMStatefulLSTM
from utilities import Logger, plotting_l... | 13,757 | 44.556291 | 146 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/dataset/processed_dataset.py | import numpy as np
import torch
from torch.utils.data import Dataset
import pdb
class FastDataset(Dataset):
"""Dataset with preprocessed data for response generation subtask
self.data.keys() = dict_keys(['dial_ids', 'turns', 'utterances', 'histories', 'actions',
'attribut... | 2,625 | 39.4 | 113 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/models/embednets.py | import pdb
import numpy as np
import torch
import torch.nn as nn
from spellchecker import SpellChecker
class ItemEmbeddingNetwork(nn.Module):
"""Base class for word embedding layer initialization and weights loading
Args:
nn (torch.nn.Module): inherits from torch.nn.Module
"""
def __init__(s... | 4,777 | 35.753846 | 124 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/models/blindstateless.py | import pdb
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .embednets import WordEmbeddingNetwork
class BlindStatelessLSTM(nn.Module):
"""Implementation of a blind and stateless LSTM for ac... | 6,218 | 42.795775 | 156 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/models/mmstateful.py | import pdb
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .embednets import WordEmbeddingNetwork, ItemEmbeddingNetwork
import numpy as np
def get_positional_embeddings(n_position, emb_dim):
"""Create positional em... | 15,354 | 45.814024 | 154 | py |
dstc9-SIMMC | dstc9-SIMMC-master/mm_action_prediction/models/blindstateful.py | import pdb
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .embednets import WordEmbeddingNetwork
class BlindStatefulLSTM(nn.Module):
_HIDDEN_SIZE = 300
def __init__(self, word_embeddings_path, word2id, num_ac... | 11,586 | 45.163347 | 154 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/translate.py | # -*- coding: utf-8 -*-
import logging
import torch
import os
from beaver.data import build_dataset
from beaver.infer import beam_search
from beaver.model import NMTModel
from beaver.utils import parseopt, get_device, calculate_bleu
logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO)
opt = pa... | 2,389 | 33.142857 | 111 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/train.py | # -*- coding: utf-8 -*-
import logging
import torch
import torch.cuda
from beaver.data import build_dataset
from beaver.infer import beam_search
from beaver.loss import WarmAdam, LabelSmoothingLoss
from beaver.model import NMTModel
from beaver.utils import Saver
from beaver.utils import calculate_bleu
from beaver.uti... | 5,407 | 42.264 | 176 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/tools/model_average.py | # -*- coding: utf-8 -*-
import os
import torch
import sys
def main():
if len(sys.argv) != 3:
print("python model_average.py model_path n")
exit()
model_path = sys.argv[1]
n = int(sys.argv[2]) # last n model to be averaged
fs = [os.path.join(model_path, f) for f in os.listdir(model... | 941 | 29.387097 | 114 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/loss/optimizers.py | # -*- coding: utf-8 -*-
import torch.nn as nn
import torch.optim as optim
class WarmAdam(object):
def __init__(self, params, lr, hidden_size, warm_up, n_step):
self.original_lr = lr
self.n_step = n_step
self.hidden_size = hidden_size
self.warm_up_step = warm_up
self.optimi... | 1,529 | 36.317073 | 87 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/utils/saver.py | import json
import torch
import os
import datetime
class Saver(object):
def __init__(self, opt):
self.ckpt_names = []
self.model_path = opt.model_path + datetime.datetime.now().strftime("-%y%m%d-%H%M%S")
self.max_to_keep = opt.max_to_keep
os.mkdir(self.model_path)
with op... | 1,626 | 38.682927 | 122 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/utils/__init__.py | # -*- coding: utf-8 -*-
import torch.cuda
from beaver.utils.metric import calculate_bleu, file_bleu
from beaver.utils.saver import Saver
def get_device():
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def printing_opt(opt):
return "\n".join(... | 405 | 21.555556 | 105 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/data/field.py | # -*- coding: utf-8 -*-
from typing import List
import torch
EOS_TOKEN = "<eos>"
BOS_TOKEN = "<bos>"
UNK_TOKEN = "<unk>"
PAD_TOKEN = "<pad>"
class Field(object):
def __init__(self, bos: bool, eos: bool, pad: bool, unk: bool):
self.bos_token = BOS_TOKEN if bos else None
self.eos_token = EOS_TOKEN... | 2,418 | 25.582418 | 115 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/data/dataset.py | # -*- coding: utf-8 -*-
import random
from collections import namedtuple
from typing import Dict
import torch
from beaver.data.field import Field
Batch = namedtuple("Batch", ['source', 'summary_cn', 'summary_en', 'batch_size'])
Example = namedtuple("Example", ['source', 'summary_cn', 'summary_en'])
class SumTrans... | 2,812 | 35.532468 | 121 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/infer/beam.py | # -*- coding: utf-8 -*-
import torch
class Beam(object):
def __init__(self, beam_size, pad, bos, eos, device, lp):
self.size = beam_size
self.alpha = lp
self.scores = torch.full([beam_size], -1e20).float().to(device)
self.scores[0] = 0.
self.hypotheses = torch.full([1, ... | 1,652 | 32.06 | 118 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/infer/translator.py | # -*- coding: utf-8 -*-
import torch
from beaver.infer.beam import Beam
def beam_search(opt, model, src, fields):
batch_size = src.size(0)
beam_size = opt.beam_size
encoder = model.encoder
src = src.repeat(1, beam_size).view(batch_size * beam_size, -1)
src_pad = src.eq(fields["source"].pad_id)... | 2,185 | 33.698413 | 122 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/model/embeddings.py | # -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
def positional_encoding(dim, max_len=5000):
pe = torch.zeros(max_len, dim)
position = torch.arange(0, max_len).unsqueeze(1)
div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim)))
pe[:, 0::... | 1,313 | 31.04878 | 110 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/model/transformer.py | # -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
class FeedForward(nn.Module):
def __init__(self, hidden_size, inner_size, dropout):
super(FeedForward, self).__init__()
self.linear_in = nn.Linear(hidden_size, inner_size, bias=False)
self.linear_out = nn.Linear(inner_... | 6,591 | 35.622222 | 120 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task/beaver/model/nmt_model.py | # -*- coding: utf-8 -*-
from typing import Dict
import torch
import torch.nn as nn
from beaver.model.embeddings import Embedding
from beaver.model.transformer import Decoder, Encoder
class Generator(nn.Module):
def __init__(self, hidden_size: int, tgt_vocab_size: int):
self.vocab_size = tgt_vocab_size
... | 4,603 | 39.743363 | 100 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/translate.py | # -*- coding: utf-8 -*-
import logging
import torch
import os
from beaver.data import build_dataset
from beaver.infer import beam_search
from beaver.model import NMTModel
from beaver.utils import parseopt, get_device, calculate_bleu
logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO)
opt = pa... | 2,194 | 30.811594 | 111 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/train.py | # -*- coding: utf-8 -*-
import logging
import torch
import torch.cuda
from beaver.data import build_dataset
from beaver.infer import beam_search
from beaver.loss import WarmAdam, LabelSmoothingLoss
from beaver.model import NMTModel
from beaver.utils import Saver
from beaver.utils import calculate_bleu
from beaver.uti... | 3,303 | 32.714286 | 102 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/tools/model_average.py | # -*- coding: utf-8 -*-
import os
import torch
import sys
def main():
if len(sys.argv) != 3:
print("python model_average.py model_path n")
exit()
model_path = sys.argv[1]
n = int(sys.argv[2]) # last n model to be averaged
fs = [os.path.join(model_path, f) for f in os.listdir(model... | 941 | 29.387097 | 114 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/loss/optimizers.py | # -*- coding: utf-8 -*-
import torch.nn as nn
import torch.optim as optim
class WarmAdam(object):
def __init__(self, params, lr, hidden_size, warm_up, n_step):
self.original_lr = lr
self.n_step = n_step
self.hidden_size = hidden_size
self.warm_up_step = warm_up
self.optimi... | 1,529 | 36.317073 | 87 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/utils/saver.py | import json
import torch
import os
import datetime
class Saver(object):
def __init__(self, opt):
self.ckpt_names = []
self.model_path = opt.model_path + datetime.datetime.now().strftime("-%y%m%d-%H%M%S")
self.max_to_keep = opt.max_to_keep
os.mkdir(self.model_path)
with op... | 1,063 | 34.466667 | 113 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/utils/__init__.py | # -*- coding: utf-8 -*-
import torch.cuda
from beaver.utils.metric import calculate_bleu, file_bleu
from beaver.utils.saver import Saver
def get_device():
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def printing_opt(opt):
return "\n".join(... | 405 | 21.555556 | 105 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/data/field.py | # -*- coding: utf-8 -*-
from typing import List
import torch
EOS_TOKEN = "<eos>"
BOS_TOKEN = "<bos>"
UNK_TOKEN = "<unk>"
PAD_TOKEN = "<pad>"
class Field(object):
def __init__(self, bos: bool, eos: bool, pad: bool, unk: bool):
self.bos_token = BOS_TOKEN if bos else None
self.eos_token = EOS_TOKEN... | 2,466 | 25.815217 | 115 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/data/dataset.py | # -*- coding: utf-8 -*-
import random
from collections import namedtuple
from typing import Dict
import torch
from beaver.data.field import Field
Batch = namedtuple("Batch", ['src', 'tgt', 'batch_size'])
Example = namedtuple("Example", ['src', 'tgt'])
class TranslationDataset(object):
def __init__(self,
... | 2,164 | 29.069444 | 89 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/infer/beam.py | # -*- coding: utf-8 -*-
import torch
class Beam(object):
def __init__(self, beam_size, pad, bos, eos, device, lp):
self.size = beam_size
self.alpha = lp
self.scores = torch.full([beam_size], -1e20).float().to(device)
self.scores[0] = 0.
self.hypotheses = torch.full([1, ... | 1,652 | 32.06 | 118 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/infer/translator.py | # -*- coding: utf-8 -*-
import torch
from beaver.infer.beam import Beam
def beam_search(opt, model, src, fields):
batch_size = src.size(0)
beam_size = opt.beam_size
device = src.device
num_words = model.generator.vocab_size
encoder = model.encoder
decoder = model.decoder
generator = mod... | 1,903 | 32.403509 | 98 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/model/embeddings.py | # -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
def positional_encoding(dim, max_len=5000):
pe = torch.zeros(max_len, dim)
position = torch.arange(0, max_len).unsqueeze(1)
div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim)))
pe[:, 0::... | 1,313 | 31.04878 | 110 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/model/transformer.py | # -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
class FeedForward(nn.Module):
def __init__(self, hidden_size, inner_size, dropout):
super(FeedForward, self).__init__()
self.linear_in = nn.Linear(hidden_size, inner_size, bias=False)
self.linear_out = nn.Linear(inner_... | 6,591 | 35.622222 | 120 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-base/beaver/model/nmt_model.py | # -*- coding: utf-8 -*-
from typing import Dict
import torch
import torch.nn as nn
from beaver.model.embeddings import Embedding
from beaver.model.transformer import Decoder, Encoder
class Generator(nn.Module):
def __init__(self, hidden_size: int, tgt_vocab_size: int):
self.vocab_size = tgt_vocab_size
... | 3,231 | 34.516484 | 100 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task+/translate.py | # -*- coding: utf-8 -*-
import logging
import torch
import os
from beaver.data import build_dataset
from beaver.infer import beam_search
from beaver.model import NMTModel
from beaver.utils import parseopt, get_device, calculate_bleu
logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO)
opt = pa... | 2,731 | 33.582278 | 122 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task+/train.py | # -*- coding: utf-8 -*-
import logging
import torch
import torch.cuda
from beaver.data import build_dataset
from beaver.infer import beam_search
from beaver.loss import WarmAdam, LabelSmoothingLoss
from beaver.model import NMTModel
from beaver.utils import Saver
from beaver.utils import calculate_bleu
from beaver.uti... | 5,295 | 40.700787 | 187 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task+/tools/model_average.py | # -*- coding: utf-8 -*-
import os
import torch
import sys
def main():
if len(sys.argv) != 3:
print("python model_average.py model_path n")
exit()
model_path = sys.argv[1]
n = int(sys.argv[2]) # last n model to be averaged
fs = [os.path.join(model_path, f) for f in os.listdir(model... | 941 | 29.387097 | 114 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task+/beaver/loss/optimizers.py | # -*- coding: utf-8 -*-
import torch.nn as nn
import torch.optim as optim
class WarmAdam(object):
def __init__(self, params, lr, hidden_size, warm_up, n_step):
self.original_lr = lr
self.n_step = n_step
self.hidden_size = hidden_size
self.warm_up_step = warm_up
self.optimi... | 1,529 | 36.317073 | 87 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task+/beaver/utils/saver.py | import json
import torch
import os
import datetime
class Saver(object):
def __init__(self, opt):
self.ckpt_names = []
self.model_path = opt.model_path + datetime.datetime.now().strftime("-%y%m%d-%H%M%S")
self.max_to_keep = opt.max_to_keep
os.mkdir(self.model_path)
with op... | 1,647 | 40.2 | 140 | py |
NCLS-Corpora | NCLS-Corpora-master/code/beaver-2task+/beaver/utils/__init__.py | # -*- coding: utf-8 -*-
import torch.cuda
from beaver.utils.metric import calculate_bleu, file_bleu
from beaver.utils.saver import Saver
def get_device():
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
def printing_opt(opt):
return "\n".join(... | 405 | 21.555556 | 105 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.