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 |
|---|---|---|---|---|---|---|
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/merge_qrels.py | from utils import load_from_trec
import argparse
import torch
import csv
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--scores_path", type=str)
parser.add_argument("--qrels_path", type=str)
parser.add_argument("--save_path", type=str)
parser.add_argument("run"... | 1,581 | 28.296296 | 73 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/transform.py | # coding:utf-8
import torch
import argparse
import os
import tqdm
import copy
def transform_new_model(model_hf, layer_num):
model_new = {}
cnt = 0
for i in range(layer_num):
# encoder
target_k = "encoder.blocks.{}.self_attn.self_attn.project.weight".format(i)
source = [
... | 10,433 | 34.610922 | 88 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/utils.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import csv
import json
import warnings
from dataclasses import dataclass
from typing import Dict, List
import datasets
import torch
from transformers import PreTrainedTokenizer
@dataclass
class SimpleTrainPreProcessor:
query_file: str
collection... | 7,762 | 31.894068 | 134 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/ds_fix/engine.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
'''
import os
import time
import torch
import warnings
import torch.distributed as dist
from torch.nn.modules import Module
from torch.distributed.distributed_c10d import _get_global_rank
from tensorboardX import SummaryWriter
from deepspeed.runtime.zero.stage2 import ... | 62,693 | 40.740346 | 227 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/ds_fix/stage1.py | import math
import torch
import torch.distributed as dist
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from collections import defaultdict
from deepspeed.runtime.zero.utils import _initialize_parameter_parallel_groups
from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossSc... | 52,782 | 45.79344 | 155 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/InstructGPT/run_PopQA.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from tqdm import tqdm
import argparse
import os
import time
import json
import torch
import random
import numpy as np
import pandas as pd
import openai
openai.api_key = "YOUR_API_KEY"
seed = 633
torch.backends.cudnn.deterministic = True
random.seed(seed)
np.random.seed(seed)... | 18,470 | 34.521154 | 211 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/arguments.py | # coding=utf-8
"""argparser configuration"""
import argparse
import os
import torch
import deepspeed
def add_model_config_args(parser: argparse.ArgumentParser):
"""Model arguments"""
group = parser.add_argument_group("model", "model configuration")
group.add_argument(
"--model-config",
... | 15,323 | 29.344554 | 110 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/learning_rates.py | # coding=utf-8
"""PyTorch DataLoader for TFRecords"""
import torch
from torch.optim.lr_scheduler import _LRScheduler
import math
class AnnealingLR(_LRScheduler):
"""Anneals the learning rate from start to zero along a cosine curve."""
DECAY_STYLES = ['linear', 'cosine', 'exponential', 'constant', 'None', 'n... | 2,974 | 40.901408 | 176 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/utils.py | # coding=utf-8
"""Utilities for logging and serialization"""
import os
import random
import numpy as np
import torch
from fp16 import FP16_Optimizer
import mpu
import deepspeed
from apex.optimizers import FusedAdam as Adam
from fp16 import FP16_Module
from fp16 import FP16_Optimizer
from learning_rates import Annea... | 13,650 | 35.209549 | 126 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/generation_utils.py | # coding=utf-8
import os
import torch
import torch.nn.functional as F
from collections import defaultdict
from tokenization_t5 import EncDecTokenizer
class BeamHypotheses(object):
def __init__(
self, num_beams, max_length, length_penalty, early_stopping, tokenizer=None
):
"""
Initia... | 26,394 | 36.439716 | 139 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/train_t0.py | # coding=utf-8
"""Training Enc-Dec"""
import os
import torch
import json
import numpy as np
from arguments import get_args
from data_utils.T0Datasets import T0Dataset
from data_utils.data_config import (
DATA_GROUP_CONFIG,
DATA_NO_EVAL,
DATA_NO_VALID,
DATA_NO_TRAIN,
DATA_EVAL_GEN,
DATA_RETRI... | 36,843 | 34.022814 | 104 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/samplers.py | # coding=utf-8
"""Batch samplers that work with either random or sequential data samplers."""
import torch
from torch.utils import data
class RandomSampler(data.sampler.Sampler):
"""Based off of pytorch RandomSampler and DistributedSampler. Essentially
a RandomSampler, but this class lets the user set an e... | 5,911 | 38.677852 | 91 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/fp16util.py | # coding=utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import mpu
class tofp16(nn.Module):
"""
Utility module that implements::
def forward(self, input):
return input.half()
"""... | 7,072 | 35.647668 | 337 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/loss_scaler.py | import torch
import mpu
# item() is a recent addition, so this helps with backward compatibility.
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0]
class LossScaler:
"""
Class that manages a static loss scale. This class is intended to interact with
... | 9,150 | 40.035874 | 326 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/fp16.py | # coding=utf-8
"""Stable version of apex FP16 Optimizer"""
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from .loss_scaler import DynamicLossScaler, LossScaler
from .fp16util impo... | 31,108 | 49.338188 | 437 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/mappings.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""All-reduce the the input tensor across model parallel group."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
i... | 3,527 | 26.138462 | 76 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/initialize.py | # coding=utf-8
"""Model and data parallel groups."""
import torch
from .utils import ensure_divisibility
# Model parallel group that the current rank belongs to.
_MODEL_PARALLEL_GROUP = None
# Data parallel group that the current rank belongs to.
_DATA_PARALLEL_GROUP = None
def initialize_model_parallel(model_... | 4,274 | 33.475806 | 77 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/cross_entropy.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_world_size
from .utils import VocabUtility
class _VocabParallelCrossEntropy(torch.autograd.Function):
@staticmethod
def forward(ctx, voca... | 9,078 | 41.425234 | 101 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/utils.py | # coding=utf-8
import torch
def ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert numerator % denominator == 0, '{} is not divisible by {}'.format(
numerator, denominator)
def divide(numerator, denominator):
"""Ensure that numerat... | 2,102 | 34.644068 | 80 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/data.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_src_rank
_MAX_DATA_DIM = 4
def _check_data_types(keys, data, target_dtype):
"""Check that all the keys have the same target data type."""
... | 3,409 | 31.47619 | 80 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/grads.py | # coding=utf-8
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import torch
from torch._six import inf
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
def clip_grad_norm(parameters, max_norm, norm_type=2):
"""Clips... | 2,406 | 37.206349 | 79 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/layers.py | # coding=utf-8
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import math
import torch
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn.parameter import Parameter
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
f... | 12,967 | 39.652038 | 80 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/random.py | # coding=utf-8
#Modified by Samyam Rajbhandari
#Used to partition the activations stored for backward propagation
#Therefore reduces the memory consumption
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import contextlib
import torch.distributed as dist
import torch
fro... | 14,040 | 36.442667 | 151 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/transformer_enc_dec.py | from audioop import cross
import math
from numpy.lib.function_base import insert
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
# from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from .initialize import get_model_parallel_world_size
from .lay... | 35,723 | 41.427553 | 186 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/enc_dec_modeling.py | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import mpu
from .configuration_enc_dec import EncDecConfig
def init_method_normal(std):
"""Init method based on normal distribution.
This is only used for embeddings. The transformer has its
own initializer.
"""
def ... | 7,115 | 35.492308 | 186 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/distributed.py | # coding=utf-8
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
import mpu
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedD... | 4,286 | 42.30303 | 103 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/T0Datasets.py | import json
import re
import os
import torch
import math
import numpy as np
import pickle
from torch.utils.data import Dataset
from utils import print_rank_0, save_rank_0
from tokenization_t5 import EncDecTokenizer
from .data_config import DATA_GROUP_CONFIG, DATA_CONFIG
import datasets
from promptsource.templates impor... | 21,571 | 38.29326 | 122 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/loss.py | import torch
from torch import Tensor
from torch.nn import functional as F
from torch import distributed as dist
class SimpleContrastiveLoss:
def __call__(self, x: Tensor, y: Tensor, target: Tensor = None, reduction: str = 'mean'):
if target is None:
target_per_qry = y.size(0) // x.size(0)
... | 2,694 | 35.418919 | 118 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/utils.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import csv
import json
import warnings
from dataclasses import dataclass
from typing import Dict, List
import datasets
import torch
from transformers import PreTrainedTokenizer
try:
from opendelta import BitFitModel, AdapterModel, PrefixModel, LoraMo... | 8,668 | 32.087786 | 134 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/trainer/dense_trainer.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
from itertools import repeat
from typing import Any, Dict, List, Optional, Tuple, Union
import datasets
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
from transformers.file_utils import is_d... | 6,280 | 36.837349 | 111 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/trainer/reranker_trainer.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
import torch.nn as nn
from transformers.trainer import Trainer
from transformers.trainer_pt_utils import nested_detach
logger = logging.getLogger(__name__)
... | 2,539 | 32.866667 | 96 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/inference_dataset.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import os
from functools import lru_cache
from typing import List, Union, Callable
from datasets import load_dataset
from torch.utils.data import Dataset, IterableDataset
from transformers import PreTrainedTokenizer
from ..arguments import DataArguments
... | 9,674 | 32.947368 | 138 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/train_dataset.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import glob
import logging
import os
import random
from typing import Callable, Dict, List, Union
from datasets import load_dataset
from torch.utils.data import Dataset, IterableDataset
from transformers import BatchEncoding, PreTrainedTokenizer
from ..a... | 11,428 | 34.604361 | 121 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/reranking_model.py | import copy
import json
import logging
import os
from dataclasses import dataclass
from typing import Dict, Optional
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from transformers import (AutoModel, BatchEncoding, PreTrainedModel,
... | 6,685 | 35.736264 | 119 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/linear.py | import logging
import os
import json
import torch
import torch.nn as nn
from torch import Tensor
logger = logging.getLogger(__name__)
class LinearHead(nn.Module):
def __init__(
self,
input_dim: int = 768,
output_dim: int = 768,
):
super(LinearHead, self).__init__(... | 1,182 | 29.333333 | 75 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/dense_retrieval_model.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import copy
import importlib
import json
import logging
import os
from dataclasses import dataclass
from typing import Dict, Optional
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch import Ten... | 12,826 | 35.440341 | 98 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/retriever/reranker.py | import logging
import os
from contextlib import nullcontext
from typing import Dict
import torch
from torch.cuda import amp
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset, IterableDataset
from tqdm import tqdm
from transformers import PreTrainedTokenizer
from transformers.trainer... | 4,921 | 35.731343 | 115 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/retriever/dense_retriever.py | import gc
import glob
import logging
import os
import pickle
from contextlib import nullcontext
from typing import Dict, List
import faiss
import numpy as np
import torch
from torch.cuda import amp
from torch.utils.data import DataLoader, IterableDataset
from tqdm import tqdm
from ..arguments import InferenceArgument... | 10,514 | 38.382022 | 155 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_iemocap_gemaps_ccc.py | # Dimensional speech emotion recognition
# To evaluate loss function (MSE vs CCC)
# Coded by Bagus Tris Atmaja (bagus@ep.its.ac.id)
# changelog
# 2020-02-13: Modified from gemaps-paa hfs
# 2020-02-14: Use 'tanh' activation to lock the output range in [-1, 1]
# with RMSprop optimizer
import numpy as np
impo... | 4,905 | 34.042857 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_iemocap_gemaps_mse.py | # Dimensional speech emotion recognition
# To evaluate loss function (MSE vs CCC)
# Coded by Bagus Tris Atmaja (bagus@ep.its.ac.id)
# changelog
# 2020-02-13: Modified from gemaps-paa hfs
import numpy as np
import pickle
import pandas as pd
import keras.backend as K
from keras.models import Model
from keras.layers imp... | 4,769 | 34.333333 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_improv_gemaps_mse.py | # ser_improv_paa_ccc.py
# speech emotion recognition for MSP-IMPROV dataset with pyAudioAnalysis
# HFS features using CCC-based loss function
# coded by Bagus Tris Atmaja (bagus@ep.its.ac.id)
# changelog:
# 2020-02-13: Inital code, modified from deepMLP repo
import numpy as np
import pickle
import pandas as pd
impor... | 4,639 | 32.868613 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_iemocap_paa_ccc.py | # Dimensional speech emotion recognition from acoustic
# Changelog:
# 2019-09-01: initial version
# 2019-10-06: optimizer MTL parameters with linear search (in progress)
# 2020-12-25: modified fot ser_iemocap_loso_hfs.py
# feature is either std+mean or std+mean+silence (uncomment line 44)
# 2020-02-13: Modi... | 4,495 | 35.552846 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_improv_paa_ccc.py | # ser_improv_paa_ccc.py
# speech emotion recognition for MSP-IMPROV dataset with pyAudioAnalysis
# HFS features using CCC-based loss function
# coded by Bagus Tris Atmaja (bagus@ep.its.ac.id)
# changelog:
# 2020-02-13: Inital code, modified from deepMLP repo
import numpy as np
import pickle
import pandas as pd
impor... | 4,666 | 32.818841 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_improv_paa_mse.py | # ser_improv_paa_ccc.py
# speech emotion recognition for MSP-IMPROV dataset with pyAudioAnalysis
# HFS features using CCC-based loss function
# coded by Bagus Tris Atmaja (bagus@ep.its.ac.id)
# changelog:
# 2020-02-13: Inital code, modified from deepMLP repo
import numpy as np
import pickle
import pandas as pd
impor... | 4,663 | 32.797101 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_improv_gemaps_ccc.py | # ser_improv_paa_ccc.py
# speech emotion recognition for MSP-IMPROV dataset with pyAudioAnalysis
# HFS features using CCC-based loss function
# coded by Bagus Tris Atmaja (bagus@ep.its.ac.id)
# changelog:
# 2020-02-13: Inital code, modified from deepMLP repo
import numpy as np
import pickle
import pandas as pd
impor... | 4,545 | 32.426471 | 123 | py |
ccc_mse_ser | ccc_mse_ser-master/code/ser_iemocap_paa_mse.py | # CSL Paper: Dimensional speech emotion recognition from acoustic and text
# Changelog:
# 2019-09-01: initial version
# 2019-10-06: optimizer MTL parameters with linear search (in progress)
# 2012-12-25: modified fot ser_iemocap_loso_hfs.py
# feature is either std+mean or std+mean+silence (uncomment line 44... | 4,452 | 35.203252 | 123 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/distributed_sampler_no_evenly_divisible.py | import math
import torch
from torch.utils.data import Sampler
import torch.distributed as dist
class DistributedSamplerNoEvenlyDivisible(Sampler):
"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParall... | 2,659 | 35.438356 | 82 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_live_3d.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 17,345 | 34.4 | 148 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_main.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 28,993 | 47.976351 | 165 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_ldu.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 19,379 | 47.693467 | 180 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_test_kitti_ldu.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 11,451 | 40.492754 | 235 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/sparsification.py | import numpy as np
import torch
"""Calculate the sparsification error.
Calcualte the sparsification error for a given array according to a reference array.
Args:
unc_tensor: Flatten estimated uncertainty tensor.
pred_tensor: Flatten depth prediction tensor.
gt_tensor: Flatten ground... | 3,034 | 42.357143 | 192 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_dataloader.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 11,674 | 38.982877 | 122 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_eval.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 12,104 | 38.819079 | 143 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts_test.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 9,732 | 43.040724 | 116 | py |
LDU | LDU-main/monocular_depth_estimation/pytorch/bts.py | # Copyright (C) 2019 Jin Han Lee
#
# This file is a part of BTS.
# 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.
#
# Thi... | 17,122 | 50.575301 | 180 | py |
DelayResolvedRL | DelayResolvedRL-main/Gym(Stochastic)/agent.py | import tensorflow as tf
import numpy as np
import random
import copy
from statistics import mean
from collections import deque
GPUs = tf.config.experimental.list_physical_devices('GPU')
if GPUs:
try:
for gpu in GPUs:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError a... | 12,554 | 41.849829 | 112 | py |
DelayResolvedRL | DelayResolvedRL-main/W-Maze/DQN/agent.py | import tensorflow as tf
import numpy as np
import random
import copy
from statistics import mean
from collections import deque
GPUs = tf.config.experimental.list_physical_devices('GPU')
if GPUs:
try:
for gpu in GPUs:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError a... | 11,830 | 42.818519 | 134 | py |
DelayResolvedRL | DelayResolvedRL-main/Gym(Constant)/dqn_agents.py | from collections import deque
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D, Flatten
from copy import deepcopy
import random
from keras.optimizers import Adam
from keras import backend as K
import tensorflow as tf
import numpy as np
def reshape_state(state, is_atari_env, state_s... | 13,916 | 46.498294 | 142 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/translate.py | #!/usr/bin/env python
from __future__ import division
from builtins import bytes
import os
import argparse
import math
import codecs
import torch
import onmt
import onmt.IO
import opts
from itertools import takewhile, count
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_... | 4,516 | 32.708955 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/train.py | #!/usr/bin/env python
from __future__ import division
import os
import sys
import argparse
import torch
import torch.nn as nn
from torch import cuda
import onmt
import onmt.Models
import onmt.ModelConstructor
import onmt.modules
from onmt.Utils import aeq, use_gpu
import opts
parser = argparse.ArgumentParser(
d... | 10,352 | 31.556604 | 120 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/preprocess.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import codecs
import torch
import onmt
import onmt.IO
import opts
parser = argparse.ArgumentParser(
description='preprocess.py',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
opts.add_md_help_argument(parser)
# **Preprocess Options**
p... | 3,411 | 34.915789 | 77 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/tools/extract_embeddings.py | from __future__ import division
import torch
import argparse
from onmt.ModelConstructor import make_embeddings, \
make_encoder, make_decoder
parser = argparse.ArgumentParser(description='translate.py')
parser.add_argument('-model', required=True,
help='Path to model .... | 1,987 | 30.0625 | 70 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/test/test_models.py | import argparse
import copy
import unittest
import torch
from torch.autograd import Variable
import onmt
import opts
from onmt.ModelConstructor import make_embeddings, \
make_encoder, make_decoder
parser = argparse.ArgumentParser(description='train.py')
opts.model_opts(parser)
opts.train_... | 7,275 | 32.84186 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/test/test_preprocess.py | import argparse
import copy
import unittest
import onmt
import opts
import torchtext
from collections import Counter
parser = argparse.ArgumentParser(description='preprocess.py')
opts.preprocess_opts(parser)
opt = parser.parse_known_args()[0]
opt.train_src = 'data/src-train.txt'
opt.train_tgt = 'data/tgt-train.txt... | 3,317 | 30.009346 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/Loss.py | """
This file handles the details of the loss function during training.
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
import torch
import torch.nn as nn
from torch.autograd import Variable
import onmt
class LossComp... | 6,611 | 34.548387 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/Beam.py | from __future__ import division
import torch
import onmt
"""
Class for managing the internals of the beam search process.
Takes care of beams, back pointers, and scores.
"""
class Beam(object):
def __init__(self, size, n_best=1, cuda=False, vocab=None,
global_scorer=None):
self.size ... | 5,428 | 32.512346 | 77 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/Translator.py | import torch
from torch.autograd import Variable
import onmt
import onmt.Models
import onmt.ModelConstructor
import onmt.modules
import onmt.IO
from onmt.Utils import use_gpu
NOISE_TRANSELATE = False
class Translator(object):
def __init__(self, opt, dummy_opt={}):
# Add in default model arguments, poss... | 8,875 | 36.610169 | 122 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/IO.py | # -*- coding: utf-8 -*-
import codecs
from collections import Counter, defaultdict
from itertools import chain, count
import torch
import torchtext.data
import torchtext.vocab
PAD_WORD = '<blank>'
UNK = 0
BOS_WORD = '<s>'
EOS_WORD = '</s>'
def __getstate__(self):
return dict(self.__dict__, stoi=dict(self.stoi)... | 14,171 | 33.231884 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/ModelConstructor.py | """
This file is for models creation, which consults options
and creates each encoder and decoder accordingly.
"""
import torch.nn as nn
import onmt
import onmt.Models
import onmt.modules
from onmt.Models import NMTModel, MeanEncoder, RNNEncoder, \
StdRNNDecoder, InputFeedRNNDecoder
from onmt.m... | 7,331 | 37.589474 | 76 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/Trainer.py | from __future__ import division
"""
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
t... | 6,823 | 33.994872 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/Optim.py | import torch.optim as optim
from torch.nn.utils import clip_grad_norm
class Optim(object):
def set_parameters(self, params):
self.params = [p for p in params if p.requires_grad]
if self.method == 'sgd':
self.optimizer = optim.SGD(self.params, lr=self.lr)
elif self.method == 'a... | 2,490 | 33.123288 | 76 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/Models.py | from __future__ import division
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
import onmt
from onmt.Utils import aeq
class EncoderBase(nn.Module):
"""
EncoderBase ... | 18,492 | 36.209256 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/ConvMultiStepAttention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from onmt.Utils 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).contiguous().view(
batch * length, hid... | 2,610 | 34.767123 | 77 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/Transformer.py | """
Implementation of "Attention is All You Need"
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import onmt
from onmt.Models import EncoderBase
from onmt.Models import DecoderState
from onmt.Utils import aeq
MAX_SIZE = 5000
class PositionwiseFeedForward(nn.Module):
... | 11,553 | 36.391586 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/Embeddings.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from onmt.modules import BottleLinear, Elementwise
from onmt.Utils import aeq
class PositionalEncoding(nn.Module):
def __init__(self, dropout, dim, max_len=5000):
pe = torch.arange(0, max_len).unsqueeze(1).expand(max_len, dim)
... | 5,928 | 39.609589 | 77 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/CopyGenerator.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.cuda
import onmt
from onmt.Utils import aeq
class CopyGenerator(nn.Module):
"""
Generator module that additionally considers copying
words directly from the source.
"""
def __init__(self, opt, src_dict, tgt_dict):
... | 5,090 | 34.852113 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/StackedRNN.py | 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):
super(StackedLSTM, self).__init__()
self.dropout = nn... | 1,755 | 28.266667 | 66 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/MultiHeadedAttn.py | import math
import torch
import torch.nn as nn
from torch.autograd import Variable
from onmt.Utils import aeq
from onmt.modules.UtilClass import BottleLinear, \
BottleLayerNorm, BottleSoftmax
class MultiHeadedAttention(nn.Module):
''' Multi-Head Attention module from
"Attention is All... | 3,966 | 34.738739 | 74 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/Gate.py | """
Context gate is a decoder module that takes as input the previous word
embedding, the current decoder state and the attention state, and produces a
gate.
The gate can be used to select the input from the target side context
(decoder state), from the source context (attention state) or both.
"""
import torch
import ... | 3,596 | 38.527473 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/UtilClass.py | import torch
import torch.nn as nn
class Bottle(nn.Module):
def forward(self, input):
if len(input.size()) <= 2:
return super(Bottle, self).forward(input)
size = input.size()[:2]
out = super(Bottle, self).forward(input.view(size[0]*size[1], -1))
... | 2,769 | 30.123596 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/StructuredAttention.py | import torch.nn as nn
import torch
import torch.cuda
from torch.autograd import Variable
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 Representatio... | 1,556 | 33.6 | 77 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/Conv2Conv.py | """
Implementation of "Convolutional Sequence to Sequence Learning"
"""
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import onmt.modules
from onmt.modules.WeightNorm import WeightNormConv2d
from onmt.Models import EncoderBase
from o... | 8,557 | 35.57265 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/GlobalAttention.py | import torch
import torch.nn as nn
from onmt.modules.UtilClass import BottleLinear
from onmt.Utils import aeq
class GlobalAttention(nn.Module):
"""
Luong Attention.
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the ... | 6,419 | 32.968254 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/SRU.py | """
Implementation of "Training RNNs as Fast as CNNs".
TODO: turn to pytorch's implementation when it is available.
This implementation is adpoted from the author of the paper:
https://github.com/taolei87/sru/blob/master/cuda_functional.py.
"""
import subprocess
import platform
import os
import re
import argparse
impo... | 23,318 | 36.672052 | 79 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/WeightNorm.py | """
Implementation of "Weight Normalization: A Simple Reparameterization
to Accelerate Training of Deep Neural Networks"
As a reparameterization method, weight normalization is same
as BatchNormalization, but it doesn't depend on minibatch.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from tor... | 9,574 | 39.231092 | 78 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/OpenNMT/onmt/modules/ImageEncoder.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.cuda
from torch.autograd import Variable
class ImageEncoder(nn.Module):
"""
Encoder recurrent neural network for Images.
"""
def __init__(self, num_layers, bidirectional, rnn_size, dropout):
"""
Args:
... | 3,998 | 36.373832 | 76 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/source/Generation/seq2seq_translation_tutorial.py | # -*- coding: utf-8 -*-
"""
Translation with a Sequence to Sequence Network and Attention
*************************************************************
**Author**: `Sean Robertson <https://github.com/spro/practical-pytorch>`_
In this project we will be teaching a neural network to translate from
French to English.
::... | 31,375 | 33.939866 | 133 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/source/Generation/Evaluation.py | # coding: utf-8
######################################################################
# Evaluation
# ==========
#
# Evaluation is mostly the same as training, but there are no targets so
# we simply feed the decoder's predictions back to itself for each step.
# Every time it predicts a word we add it to the output str... | 4,187 | 34.794872 | 116 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/source/Generation/Seq2SeqModel.py | # coding: utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size, use_cuda, n_layers=1):
super(EncoderRNN, self).__init__()
self.n_layers = n_layers
self.hidden_siz... | 3,661 | 34.901961 | 112 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/source/Generation/Training.py | import time
import math
import random
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
from source.AuxiliaryTools.nn_tool import show_plot, variables_from_pair
SOS_token = 0
EOS_token = 1
teacher_forcing_ratio = 0.5
def train(input_variable, target_variable, encoder, de... | 4,278 | 33.788618 | 109 | py |
Seq2SeqDataAugmentationForLU | Seq2SeqDataAugmentationForLU-master/source/AuxiliaryTools/nn_tool.py | # coding: utf-8
from __future__ import unicode_literals, print_function, division
import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
SOS_token = 0
EOS_token = 1
teacher_forcing_ratio = 0.5
MAX_LENGTH = 10
def show_plot(points):
plt.figure()
fi... | 1,083 | 26.794872 | 72 | py |
EmpTransfo | EmpTransfo-master/train_full.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
import os
import math
import logging
from pprint import pformat
from argparse import ArgumentParser
from collections import ... | 15,365 | 59.496063 | 183 | py |
EmpTransfo | EmpTransfo-master/evaluate.py | # # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
import random
from argparse import ArgumentParser
from itertools import chain
from pprint import pforma... | 8,472 | 42.229592 | 156 | py |
EmpTransfo | EmpTransfo-master/utils.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import json
import logging
import os
import tarfile
import tempfile
import re
import torch
from pytorch_pretrained_bert ... | 8,740 | 37.676991 | 124 | py |
EmpTransfo | EmpTransfo-master/train_emotion_recognition.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
import os
import math
import logging
from pprint import pformat
from argparse import ArgumentParser
from collections import ... | 16,552 | 56.675958 | 183 | py |
EmpTransfo | EmpTransfo-master/interact.py | # # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
import random
from argparse import ArgumentParser
from itertools import chain
from pprint import pforma... | 6,871 | 41.419753 | 151 | py |
EmpTransfo | EmpTransfo-master/train.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
import os
import math
import logging
from pprint import pformat
from argparse import ArgumentParser
from collections import ... | 14,215 | 58.233333 | 183 | py |
EmpTransfo | EmpTransfo-master/train_multihead.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
import os
import math
import logging
from pprint import pformat
from argparse import ArgumentParser
from collections import ... | 17,664 | 55.800643 | 174 | py |
EmpTransfo | EmpTransfo-master/eval_emotion_recognition.py | # Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
import logging
from pprint import pformat
from collections import defaultdict
from itertools import chain
import torch
from... | 11,203 | 52.607656 | 182 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.