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 |
|---|---|---|---|---|---|---|
ZeCon | ZeCon-main/CLIP/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Token... | 8,433 | 36.484444 | 149 | py |
ZeCon | ZeCon-main/CLIP/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have strid... | 17,242 | 38.822171 | 178 | py |
ZeCon | ZeCon-main/CLIP/tests/test_consistency.py | import numpy as np
import pytest
import torch
from PIL import Image
import clip
@pytest.mark.parametrize('model_name', clip.available_models())
def test_consistency(model_name):
device = "cpu"
jit_model, transform = clip.load(model_name, device=device, jit=True)
py_model, _ = clip.load(model_name, device... | 812 | 30.269231 | 73 | py |
ZeCon | ZeCon-main/guided_diffusion/setup.py | from setuptools import setup
setup(
name="guided-diffusion",
py_modules=["guided_diffusion"],
install_requires=["blobfile>=1.0.5", "torch", "tqdm"],
)
| 164 | 19.625 | 58 | py |
ZeCon | ZeCon-main/guided_diffusion/scripts/image_sample.py | """
Generate a large batch of image samples from a model and save them as a large
numpy array. This can be used to produce samples for FID evaluation.
"""
import argparse
import os
import numpy as np
import torch as th
import torch.distributed as dist
from guided_diffusion import dist_util, logger
from guided_diffus... | 3,398 | 30.183486 | 88 | py |
ZeCon | ZeCon-main/guided_diffusion/scripts/super_res_sample.py | """
Generate a large batch of samples from a super resolution model, given a batch
of samples from a regular model from image_sample.py.
"""
import argparse
import os
import blobfile as bf
import numpy as np
import torch as th
import torch.distributed as dist
from guided_diffusion import dist_util, logger
from guide... | 3,725 | 30.05 | 84 | py |
ZeCon | ZeCon-main/guided_diffusion/scripts/classifier_sample.py | """
Like image_sample.py, but use a noisy image classifier to guide the sampling
process towards more realistic images.
"""
import argparse
import os
import numpy as np
import torch as th
import torch.distributed as dist
import torch.nn.functional as F
from guided_diffusion import dist_util, logger
from guided_diffu... | 4,266 | 31.325758 | 88 | py |
ZeCon | ZeCon-main/guided_diffusion/scripts/classifier_train.py | """
Train a noised image classifier on ImageNet.
"""
import argparse
import os
import blobfile as bf
import torch as th
import torch.distributed as dist
import torch.nn.functional as F
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from guided_diffusion import ... | 7,313 | 31.220264 | 99 | py |
ZeCon | ZeCon-main/guided_diffusion/scripts/image_nll.py | """
Approximate the bits/dimension for an image model.
"""
import argparse
import os
import numpy as np
import torch.distributed as dist
from guided_diffusion import dist_util, logger
from guided_diffusion.image_datasets import load_data
from guided_diffusion.script_util import (
model_and_diffusion_defaults,
... | 2,934 | 29.257732 | 86 | py |
ZeCon | ZeCon-main/guided_diffusion/scripts/super_res_train.py | """
Train a super-resolution model.
"""
import argparse
import torch.nn.functional as F
from guided_diffusion import dist_util, logger
from guided_diffusion.image_datasets import load_data
from guided_diffusion.resample import create_named_schedule_sampler
from guided_diffusion.script_util import (
sr_model_and_... | 2,695 | 26.232323 | 87 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/resample.py | from abc import ABC, abstractmethod
import numpy as np
import torch as th
import torch.distributed as dist
def create_named_schedule_sampler(name, diffusion):
"""
Create a ScheduleSampler from a library of pre-defined samplers.
:param name: the name of the sampler.
:param diffusion: the diffusion ob... | 5,689 | 35.709677 | 87 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/losses.py | """
Helpers for various likelihood-based losses. These are ported from the original
Ho et al. diffusion models codebase:
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
"""
import numpy as np
import torch as th
def normal_kl(mean1, logvar1, mean2, logvar... | 2,534 | 31.5 | 109 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/image_datasets.py | import math
import random
from PIL import Image
import blobfile as bf
from mpi4py import MPI
import numpy as np
from torch.utils.data import DataLoader, Dataset
def load_data(
*,
data_dir,
batch_size,
image_size,
class_cond=False,
deterministic=False,
random_crop=False,
random_flip=Tr... | 5,930 | 34.303571 | 88 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/nn.py | """
Various utilities for neural networks.
"""
import math
import torch as th
import torch.nn as nn
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
class SiLU(nn.Module):
def forward(self, x):
return x * th.sigmoid(x)
class GroupNorm32(nn.GroupNorm):
def forward(self, x):
return super(... | 5,020 | 28.362573 | 88 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/fp16_util.py | """
Helpers to train with 16-bit precision.
"""
import numpy as np
import torch as th
import torch.nn as nn
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from . import logger
INITIAL_LOG_LOSS_SCALE = 20.0
def convert_module_to_f16(l):
"""
Convert primitive modules to float16.
... | 7,941 | 32.510549 | 114 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/unet.py | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .fp16_util import convert_module_to_f16, convert_module_to_f32
from .nn import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
... | 32,001 | 33.822633 | 124 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/gaussian_diffusion.py | """
This code started out as a PyTorch port of Ho et al's diffusion models:
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
"""
import enum
import math... | 36,586 | 38.130481 | 129 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/train_util.py | import copy
import functools
import os
import blobfile as bf
import torch as th
import torch.distributed as dist
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from . import dist_util, logger
from .fp16_util import MixedPrecisionTrainer
from .nn import update_em... | 10,604 | 34.115894 | 88 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/respace.py | import numpy as np
import torch as th
from .gaussian_diffusion import GaussianDiffusion
def space_timesteps(num_timesteps, section_counts):
"""
Create a list of timesteps to use from an original diffusion process,
given the number of timesteps we want to take from equally-sized portions
of the origin... | 5,193 | 39.263566 | 85 | py |
ZeCon | ZeCon-main/guided_diffusion/guided_diffusion/dist_util.py | """
Helpers for distributed training.
"""
import io
import os
import socket
import blobfile as bf
from mpi4py import MPI
import torch as th
import torch.distributed as dist
# Change this to reflect your cluster layout.
# The GPU for a given rank is (rank % GPUS_PER_NODE).
GPUS_PER_NODE = 8
SETUP_RETRY_COUNT = 3
d... | 2,424 | 24.797872 | 87 | py |
Few-NERD | Few-NERD-main/run_supervised.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 28,048 | 52.940385 | 184 | py |
Few-NERD | Few-NERD-main/train_demo.py | from transformers import BertTokenizer
from util.data_loader import get_loader
from util.framework import FewShotNERFramework
from util.word_encoder import BERTWordEncoder
from model.proto import Proto
from model.nnshot import NNShot
import sys
import torch
from torch import optim, nn
import numpy as np
import json
imp... | 8,044 | 42.02139 | 191 | py |
Few-NERD | Few-NERD-main/util/word_encoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import os
from torch import optim
from transformers import BertTokenizer, BertModel, BertForMaskedLM, BertForSequenceClassification, RobertaModel, RobertaTokenizer, RobertaForSequenceClassification
class BERTWordEncoder(n... | 1,047 | 42.666667 | 163 | py |
Few-NERD | Few-NERD-main/util/data_loader.py | import torch
import torch.utils.data as data
import os
from .fewshotsampler import FewshotSampler, FewshotSampleBase
import numpy as np
import json
def get_class_name(rawtag):
# get (finegrained) class name
if rawtag.startswith('B-') or rawtag.startswith('I-'):
return rawtag[2:]
else:
retur... | 13,114 | 39.353846 | 162 | py |
Few-NERD | Few-NERD-main/util/viterbi.py | import torch
import torch.nn as nn
START_ID = 0
O_ID = 1
class ViterbiDecoder:
"""
Generalized Viterbi decoding
"""
def __init__(self, n_tag, abstract_transitions, tau):
"""
We assume the batch size is 1, so no need to worry about PAD for now
n_tag: START, O, and I_Xs
... | 4,150 | 38.533333 | 93 | py |
Few-NERD | Few-NERD-main/util/framework.py | import os
import sklearn.metrics
import numpy as np
import sys
import time
from . import word_encoder
from . import data_loader
import torch
from torch import autograd, optim, nn
from torch.autograd import Variable
from torch.nn import functional as F
# from pytorch_pretrained_bert import BertAdam
from transformers imp... | 22,526 | 38.59051 | 158 | py |
Few-NERD | Few-NERD-main/model/nnshot.py | import sys
sys.path.append('..')
import util
import torch
from torch import autograd, optim, nn
from torch.autograd import Variable
from torch.nn import functional as F
class NNShot(util.framework.FewShotNERModel):
def __init__(self,word_encoder, dot=False, ignore_index=-1):
util.framework.FewShotNERM... | 3,140 | 40.88 | 123 | py |
Few-NERD | Few-NERD-main/model/proto.py | import sys
sys.path.append('..')
import util
import torch
from torch import autograd, optim, nn
from torch.autograd import Variable
from torch.nn import functional as F
class Proto(util.framework.FewShotNERModel):
def __init__(self,word_encoder, dot=False, ignore_index=-1):
util.framework.FewShotNERMo... | 3,166 | 39.088608 | 124 | py |
pycbc | pycbc-master/pycbc/results/str_utils.py | # Copyright (C) 2016 Collin Capano
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in t... | 9,027 | 34.968127 | 83 | py |
pycbc | pycbc-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# PyCBC documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 11 17:02:52 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | 11,336 | 31.484241 | 132 | py |
MAPS-mt | MAPS-mt-main/interactive.py | import os
import difflib
import logging
import argparse
import warnings
from typing import List
from langcodes import Language
from data.trigger_sents import SUPPORT_LANGS
from comet import load_from_checkpoint, download_model
from data import demo_ex_dict, kw_ex_dict, topic_ex_dict
from model.openai.translate import a... | 10,309 | 41.780083 | 186 | py |
MAPS-mt | MAPS-mt-main/scripts/knowledge-selection.py | import os
import torch
import json
import random
import logging
import argparse
import threading
import numpy as np
from sacrebleu.metrics import BLEU
from comet import load_from_checkpoint, download_model
comet_model_mapping = {
"wmt21-comet-qe-da": "wmt21-comet-qe-da/checkpoints/model.ckpt",
}
def seed_everythi... | 9,515 | 36.027237 | 155 | py |
MAPS-mt | MAPS-mt-main/scripts/compare.py | import os
from comet.cli.compare import *
import threading
import logging
from bleurt import score as bleurt_score
from sacrebleu.metrics import BLEU
comet_model_mapping = {
"wmt21-comet-qe-da": "wmt21-comet-qe-da/checkpoints/model.ckpt",
}
def wait_until_path_exist(path):
while not os.path.isdir(path):
... | 17,345 | 34.4 | 155 | py |
MAPS-mt | MAPS-mt-main/model/alpaca/translate.py | import os
import re
import torch
import argparse
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--model-name-or-path', ... | 4,295 | 44.221053 | 128 | py |
UNIXKD | UNIXKD-master/teacher.py | import os
import os.path as osp
import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
from torchv... | 5,083 | 33.821918 | 110 | py |
UNIXKD | UNIXKD-master/utils.py | import os
import logging
import numpy as np
import time
import torch
from torch.nn import init
import torch.nn.functional as F
import torch.utils.data as data
from PIL import Image
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
... | 2,691 | 24.638095 | 87 | py |
UNIXKD | UNIXKD-master/zoo.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
"""Paying More Attention to Attention: Improving the Performance of Convolutional Neural Networks
via Attention Transfer
code: https://github.com/szagoruyko/attention-transf... | 1,745 | 30.178571 | 101 | py |
UNIXKD | UNIXKD-master/student_v0.py | import os
import os.path as osp
import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import MultiStepLR
import torchvision.transforms as transforms
from tensor... | 9,632 | 36.628906 | 101 | py |
UNIXKD | UNIXKD-master/dataset/utils.py | import os
import os.path
import hashlib
import gzip
import errno
import tarfile
import zipfile
import torch
from torch.utils.model_zoo import tqdm
def gen_bar_updater():
pbar = tqdm(total=None)
def bar_update(count, block_size, total_size):
if pbar.total is None and total_size:
pbar.tota... | 8,765 | 29.975265 | 109 | py |
UNIXKD | UNIXKD-master/dataset/vision.py | import os
import torch
import torch.utils.data as data
class VisionDataset(data.Dataset):
_repr_indent = 4
def __init__(self, root, transforms=None, transform=None, target_transform=None):
if isinstance(root, torch._six.string_classes):
root = os.path.expanduser(root)
self.root = ... | 2,950 | 35.432099 | 86 | py |
UNIXKD | UNIXKD-master/models/resnet.py | from __future__ import absolute_import
'''Resnet for cifar dataset.
Ported form
https://github.com/facebook/fb.resnet.torch
and
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
(c) YANG, Wei
'''
import torch.nn as nn
import torch.nn.functional as F
import math
__all__ = ['resnet']
def con... | 7,841 | 29.161538 | 116 | py |
UNIXKD | UNIXKD-master/models/mobilenetv2.py | """
MobileNetV2 implementation used in
<Knowledge Distillation via Route Constrained Optimization>
"""
import torch
import torch.nn as nn
import math
__all__ = ['mobilenetv2_T_w', 'mobile_half']
BN = None
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False)... | 5,777 | 27.323529 | 115 | py |
UNIXKD | UNIXKD-master/models/vgg.py | '''VGG for CIFAR10. FC layers are removed.
(c) YANG, Wei
'''
import torch.nn as nn
import torch.nn.functional as F
import math
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30... | 6,971 | 28.417722 | 98 | py |
UNIXKD | UNIXKD-master/models/classifier.py | from __future__ import print_function
import torch.nn as nn
#########################################
# ===== Classifiers ===== #
#########################################
class LinearClassifier(nn.Module):
def __init__(self, dim_in, n_label=10):
super(LinearClassifier, self).__init__()
self.n... | 819 | 21.777778 | 51 | py |
UNIXKD | UNIXKD-master/models/resnetv2.py | '''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion... | 6,915 | 33.753769 | 106 | py |
UNIXKD | UNIXKD-master/models/ShuffleNetv1.py | '''ShuffleNet in PyTorch.
See the paper "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups):
super(ShuffleBlock, self).__init_... | 4,732 | 33.05036 | 126 | py |
UNIXKD | UNIXKD-master/models/util.py | from __future__ import print_function
import torch.nn as nn
import math
class Paraphraser(nn.Module):
"""Paraphrasing Complex Network: Network Compression via Factor Transfer"""
def __init__(self, t_shape, k=0.5, use_bn=False):
super(Paraphraser, self).__init__()
in_channel = t_shape[1]
... | 9,622 | 32.068729 | 107 | py |
UNIXKD | UNIXKD-master/models/ShuffleNetv2.py | '''ShuffleNetV2 in PyTorch.
See the paper "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups=2):
super(ShuffleBlock, self).__init__()
... | 7,074 | 32.530806 | 107 | py |
UNIXKD | UNIXKD-master/models/wrn.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Original Author: Wei Yang
"""
__all__ = ['wrn']
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)... | 5,519 | 31.280702 | 116 | py |
GraphLIME | GraphLIME-master/graphlime/__init__.py | __version__ = '1.2.0'
__all__ = [
'GraphLIME'
]
import numpy as np
from sklearn.linear_model import LassoLars
import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import k_hop_subgraph
class GraphLIME:
def __init__(self, model, hop=2, rho=0.1, cached=True):
se... | 3,882 | 29.81746 | 89 | py |
GraphLIME | GraphLIME-master/exp/noise_features/other_explainers.py | import copy
import numpy as np
from tqdm import tqdm
from sklearn.linear_model import Ridge
import torch
class LIME:
def __init__(self, model, num_samples, cached=True):
self.model = model
self.num_samples = num_samples
self.cached = cached
self.cached_result = None
self... | 4,242 | 30.902256 | 84 | py |
GraphLIME | GraphLIME-master/exp/noise_features/exp_noise_features.py | from os import sys, path as osp
sys.path.append(osp.dirname(osp.dirname(osp.dirname(__file__))))
import random
import argparse
import warnings
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch
from torch_geometric.nn import GNNExplainer
from models import GAT
from graphlime import... | 7,487 | 33.827907 | 120 | py |
GraphLIME | GraphLIME-master/exp/noise_features/utils.py | import os
import numpy as np
from tqdm import tqdm
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch_geometric.datasets import Planetoid
def prepare_data(args):
dataset = args.dataset.ti... | 5,089 | 28.766082 | 97 | py |
GraphLIME | GraphLIME-master/exp/noise_features/models.py | import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GATConv
class GCN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.5):
super(GCN, self).__init__()
self.dropout = dropout
self.conv1 = GCNConv(input_dim, hidd... | 1,699 | 32.333333 | 116 | py |
arl-eegmodels | arl-eegmodels-master/EEGModels.py | """
ARL_EEGModels - A collection of Convolutional Neural Network models for EEG
Signal Processing and Classification, using Keras and Tensorflow
Requirements:
(1) tensorflow == 2.X (as of this writing, 2.0 - 2.3 have been verified
as working)
To run the EEG/MEG ERP classification sample script, you w... | 18,033 | 43.74938 | 96 | py |
arl-eegmodels | arl-eegmodels-master/examples/ERP.py | """
Sample script using EEGNet to classify Event-Related Potential (ERP) EEG data
from a four-class classification task, using the sample dataset provided in
the MNE [1, 2] package:
https://martinos.org/mne/stable/manual/sample_dataset.html#ch-sample-data
The four classes used from this dataset are:
L... | 10,178 | 40.717213 | 86 | py |
Paddle | Paddle-master/python/paddle/trainer/config_parser.py | # Copyright (c) 2016 PaddlePaddle Authors. 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 applic... | 166,008 | 36.322167 | 111 | py |
Paddle | Paddle-master/python/paddle/utils/predefined_net.py | # Copyright (c) 2016 PaddlePaddle Authors. 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 applic... | 14,269 | 36.454068 | 80 | py |
Paddle | Paddle-master/python/paddle/utils/torch2paddle.py | # Copyright (c) 2016 PaddlePaddle Authors. 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 applic... | 2,946 | 30.688172 | 97 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/average-checkpoints.py | """This file is nearly word-for-word taken from the folder tools in OpenNMT"""
import pkg_resources
import argparse
import torch
import os
def average_checkpoints(checkpoint_files):
vocab = None
opt = None
avg_model = None
avg_generator = None
for i, checkpoint_file in enumerate(checkpoint_fi... | 1,847 | 33.867925 | 100 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/batch_translate.py | import subprocess
import functools
import argparse
import torch
import os
import re
partial_shell= = functools.partial(subprocess.run, shell=True,
stdout=subprocess.PIPE)
def shell(cmd):
"""Execute cmd as if from the command line"""
completed_process = partial_shell(cmd)
... | 434 | 23.166667 | 62 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/opts.py | """ Implementation of all available options """
from __future__ import print_function
import configargparse
from onmt.models.sru import CheckSRU
def config_opts(parser):
parser.add('-config', '--config', required=False,
is_config_file_arg=True, help='config file path')
parser.add('-save_config... | 42,843 | 51.893827 | 118 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/train_single.py | #!/usr/bin/env python
"""Training on a single process."""
import os
import torch
from onmt.inputters.inputter import build_dataset_iter, \
load_old_vocab, old_style_vocab, build_dataset_iter_multiple
from onmt.model_builder import build_model
from onmt.utils.optimizers import Optimizer
from onmt.utils.misc import... | 4,977 | 32.863946 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/model_builder.py | """
This file is for models creation, which consults options
and creates each encoder and decoder accordingly.
"""
import re
import torch
import torch.nn as nn
from torch.nn.init import xavier_uniform_
import onmt.inputters as inputters
import onmt.modules
from onmt.encoders import str2enc
from onmt.decoders import s... | 9,581 | 34.227941 | 81 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/trainer.py | """
This is the loadable seq2seq trainer library that is
in charge of training details, loss compute, and statistics.
See train.py for a use case of this library.
Note: To make this a general library, we implement *only*
mechanism things here(i.e. what to do), and leave the strategy
... | 18,735 | 39.292473 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/inputters/text_dataset.py | # -*- coding: utf-8 -*-
from functools import partial
import six
import torch
from torchtext.data import Field, RawField
from onmt.inputters.datareader_base import DataReaderBase
class TextDataReader(DataReaderBase):
def read(self, sequences, side, _dir=None):
"""Read text data from disk.
Args:... | 6,904 | 34.410256 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/inputters/dataset_base.py | # coding: utf-8
from itertools import chain, starmap
from collections import Counter
import torch
from torchtext.data import Dataset as TorchtextDataset
from torchtext.data import Example
from torchtext.vocab import Vocab
def _join_dicts(*args):
"""
Args:
dictionaries with disjoint keys.
Return... | 6,865 | 40.612121 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/inputters/inputter.py | # -*- coding: utf-8 -*-
import glob
import os
import codecs
import math
from collections import Counter, defaultdict
from itertools import chain, cycle
import torch
import torchtext.data
from torchtext.data import Field, RawField, LabelField
from torchtext.vocab import Vocab
from torchtext.data.utils import RandomShu... | 31,503 | 35.590012 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/inputters/audio_dataset.py | # -*- coding: utf-8 -*-
import os
from tqdm import tqdm
import torch
from torchtext.data import Field
from onmt.inputters.datareader_base import DataReaderBase
# imports of datatype-specific dependencies
try:
import torchaudio
import librosa
import numpy as np
except ImportError:
torchaudio, librosa,... | 8,459 | 36.93722 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/inputters/image_dataset.py | # -*- coding: utf-8 -*-
import os
import torch
from torchtext.data import Field
from onmt.inputters.datareader_base import DataReaderBase
# domain specific dependencies
try:
from PIL import Image
from torchvision import transforms
import cv2
except ImportError:
Image, transforms, cv2 = None, None, N... | 3,378 | 30.579439 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/inputters/vec_dataset.py | import os
import torch
from torchtext.data import Field
from onmt.inputters.datareader_base import DataReaderBase
try:
import numpy as np
except ImportError:
np = None
class VecDataReader(DataReaderBase):
"""Read feature vector data from disk.
Raises:
onmt.inputters.datareader_base.MissingD... | 5,447 | 35.32 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/sparse_losses.py | import torch
import torch.nn as nn
from torch.autograd import Function
from onmt.modules.sparse_activations import _threshold_and_support
from onmt.utils.misc import aeq
class SparsemaxLossFunction(Function):
@staticmethod
def forward(ctx, input, target):
"""
input (FloatTensor): ``(n, num_cl... | 2,804 | 35.428571 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/sparse_activations.py | """
An implementation of sparsemax (Martins & Astudillo, 2016). See
:cite:`DBLP:journals/corr/MartinsA16` for detailed description.
By Ben Peters and Vlad Niculae
"""
import torch
from torch.autograd import Function
import torch.nn as nn
def _make_ix_like(input, dim=0):
d = input.size(dim)
rho = torch.arang... | 2,649 | 26.040816 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/structured_attention.py | import torch.nn as nn
import torch
import torch.cuda
class MatrixTree(nn.Module):
"""Implementation of the matrix-tree theorem for computing marginals
of non-projective dependency parsing. This attention layer is used
in the paper "Learning Structured Text Representations"
:cite:`DBLP:journals/corr/Li... | 1,414 | 35.282051 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/util_class.py | """ Misc classes """
import torch
import torch.nn as nn
# At the moment this class is only used by embeddings.Embeddings look-up tables
class Elementwise(nn.ModuleList):
"""
A simple network container.
Parameters are a list of modules.
Inputs are a 3d Tensor whose last dimension is the same length
... | 1,486 | 29.346939 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/hierarchical_attention.py | from ..utils.misc import aeq
from .sparse_activations import sparsemax
from torch.nn.utils.rnn import pad_sequence
import torch
import onmt
class ContainsNaN(Exception):
pass
def _check_for_nan(tensor, msg=''):
if (tensor!=tensor).any():
raise ContainsNaN(msg)
def _check_sizes(tensor, *si... | 10,134 | 36.537037 | 94 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/conv_multi_step_attention.py | """ Multi Step Attention for CNN """
import torch
import torch.nn as nn
import torch.nn.functional as F
from onmt.utils.misc import aeq
SCALE_WEIGHT = 0.5 ** 0.5
def seq_linear(linear, x):
""" linear transform for 3-d tensor """
batch, hidden_size, length, _ = x.size()
h = linear(torch.transpose(x, 1, 2... | 2,865 | 34.382716 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/average_attn.py | # -*- coding: utf-8 -*-
"""Average Attention module."""
import torch
import torch.nn as nn
from onmt.modules.position_ffn import PositionwiseFeedForward
class AverageAttention(nn.Module):
"""
Average Attention module from
"Accelerating Neural Transformer via an Average Attention Network"
:cite:`DBLP... | 4,227 | 36.75 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/copy_generator.py | import torch
import torch.nn as nn
from onmt.utils.misc import aeq
from onmt.utils.loss import NMTLossCompute
def collapse_copy_scores(scores, batch, tgt_vocab, src_vocabs=None,
batch_dim=1, batch_offset=None):
"""
Given scores from an expanded dictionary
corresponeding to a batc... | 9,415 | 34.938931 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/self_attention.py | """
Custom reimplementation of torch.nn.MultiHeadAttention
It's actually the same module, with more or less flewibility at times,
and a more flexible use of the mask (different mask per element of the batch)
"""
from torch._jit_internal import weak_module, weak_script_method
from torch.nn.init import constant_
from to... | 5,556 | 43.103175 | 109 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/embeddings.py | """ Embeddings module """
import math
import warnings
import torch
import torch.nn as nn
from onmt.modules.util_class import Elementwise
class PositionalEncoding(nn.Module):
"""Sinusoidal positional encoding for non-recurrent neural networks.
Implementation based on "Attention Is All You Need"
:cite:`D... | 10,689 | 36.640845 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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
# This class is mainly used by decoder.py for RNNs but also
# by the CNN / transformer decoder when ... | 7,827 | 33.333333 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/glu.py | """Comes directly from fairseq"""
import torch, math
class Downsample(torch.nn.Module):
"""
Selects every nth element along the last dim, where n is the index
"""
def __init__(self, in_dim, step):
super().__init__()
self._step = step
self._in_dim = in_dim
if in... | 2,916 | 37.893333 | 92 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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 |
data-to-text-hierarchical | data-to-text-hierarchical-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 |
data-to-text-hierarchical | data-to-text-hierarchical-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): the hidden l... | 1,308 | 30.166667 | 73 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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 generate_relative_positions_matrix,\
relative_matmul
# from onmt.utils.misc import aeq
class MultiHeadedAttention(nn.Module):
"""Multi-Head Attention module from "Attention i... | 8,133 | 34.212121 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/modules/table_embeddings.py | import torch
class TableEmbeddings(torch.nn.Module):
"""
Now that I think about it, we can do more efficiently than rewritting the
onmt module. I will in the future but for now this code works as is,
so I won't chance breaking it!
These embeddings follow the table structure: a table is an uno... | 4,278 | 37.54955 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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 |
data-to-text-hierarchical | data-to-text-hierarchical-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 (onmt.encoders.EncoderBase): an encoder object
decoder (onmt.de... | 2,218 | 37.929825 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/models/model_saver.py | import os
import torch
from collections import deque
from onmt.utils.logging import logger
from copy import deepcopy
def build_model_saver(model_opt, opt, model, fields, optim):
model_saver = ModelSaver(opt.save_model,
model,
model_opt,
... | 4,230 | 30.340741 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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,302 | 36.27454 | 81 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/bin/average_models.py | #!/usr/bin/env python
import argparse
import torch
def average_models(model_files, fp32=False):
vocab = None
opt = None
avg_model = None
avg_generator = None
for i, model_file in enumerate(model_files):
m = torch.load(model_file, map_location='cpu')
model_weights = m['model']
... | 1,665 | 29.290909 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/bin/train.py | #!/usr/bin/env python
"""Train models."""
import os
import signal
import torch
import onmt.opts as opts
import onmt.utils.distributed
from onmt.utils.misc import set_random_seed
from onmt.utils.logging import init_logger, logger
from onmt.train_single import main as single_main
from onmt.utils.parse import ArgumentPa... | 6,849 | 31.77512 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/bin/preprocess.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Pre-process Data / features files and build vocabulary
"""
import codecs
import glob
import gc
import torch
from collections import Counter, defaultdict
from onmt.utils.logging import init_logger, logger
from onmt.utils.misc import split_corpus
import onmt.inputter... | 11,018 | 35.97651 | 76 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/decoders/transformer.py | """
Implementation of "Attention is All You Need"
"""
import torch
import torch.nn as nn
from onmt.decoders.decoder import DecoderBase
from onmt.modules import MultiHeadedAttention, AverageAttention
from onmt.modules.position_ffn import PositionwiseFeedForward
from onmt.utils.misc import sequence_mask
class Transfo... | 12,530 | 38.282132 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/decoders/decoder.py | import torch
import torch.nn as nn
from onmt.models.stacked_rnn import StackedLSTM, StackedGRU
from onmt.modules import context_gate_factory, GlobalAttention
from onmt.utils.rnn_factory import rnn_factory
from onmt.utils.misc import aeq
class DecoderBase(nn.Module):
"""Abstract class for decoders.
Args:
... | 15,510 | 34.172336 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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.decoders.decoder import DecoderBase
from... | 5,956 | 37.432258 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-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
from onmt.modules import ConvMultiStepAttention, GlobalAttention
from onmt.utils.cnn_factory import shape_transform, GatedConv
from onmt.decoders.decoder import DecoderBase
SCALE_WEIGHT = ... | 4,890 | 35.5 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/decoders/hierarchical_decoder.py | """Same as normal RNNDecoder but using hierarchical attention"""
import torch
from .decoder import RNNDecoderBase
from ..modules import HierarchicalAttention
from ..models.stacked_rnn import StackedLSTM, StackedGRU
from ..utils.rnn_factory import rnn_factory
from ..utils.misc import aeq, nwise, sequence_mask
from torc... | 10,819 | 36.439446 | 90 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.