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 |
|---|---|---|---|---|---|---|
VLC-BERT | VLC-BERT-master/vqa/modules/resnet_vlbert_for_vqa.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from external.pytorch_pretrained_bert import BertTokenizer
from external.pytorch_pretrained_bert.modeling import BertPredictionHeadTransform
from common.module import Module
from common.fast_rcnn import FastRCNN
from common.visual_linguistic_b... | 16,341 | 47.064706 | 117 | py |
VLC-BERT | VLC-BERT-master/vqa/data/collate_batch.py | import torch
from common.utils.clip_pad import *
class BatchCollator(object):
def __init__(self, dataset, append_ind=False):
self.dataset = dataset
self.test_mode = self.dataset.test_mode
self.data_names = self.dataset.data_names
self.append_ind = append_ind
def __call__(self,... | 2,035 | 35.357143 | 115 | py |
VLC-BERT | VLC-BERT-master/vqa/data/build.py | import torch.utils.data
from .datasets import *
from . import samplers
from .transforms.build import build_transforms
from .collate_batch import BatchCollator
import pprint
DATASET_CATALOGS = {'vqa': VQA}
def build_dataset(dataset_name, *args, **kwargs):
assert dataset_name in DATASET_CATALOGS, "dataset not in ... | 4,336 | 42.37 | 106 | py |
VLC-BERT | VLC-BERT-master/vqa/data/datasets/vqa.py | import os
import json
import _pickle as cPickle
from PIL import Image
import re
import base64
import numpy as np
import csv
import sys
import time
import pprint
import logging
import torch
from torch.utils.data import Dataset
from external.pytorch_pretrained_bert import BertTokenizer
from common.utils.zipreader impor... | 21,774 | 45.527778 | 127 | py |
VLC-BERT | VLC-BERT-master/vqa/data/samplers/grouped_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import torch
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It enfo... | 4,846 | 40.42735 | 88 | py |
VLC-BERT | VLC-BERT-master/vqa/data/samplers/distributed.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Code is copy-pasted exactly as in torch.utils.data.distributed.
# FIXME remove this once c10d fixes the bug it has
import math
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
class DistributedSampler(S... | 2,568 | 37.924242 | 86 | py |
VLC-BERT | VLC-BERT-master/vqa/data/transforms/transforms.py | import random
import numpy as np
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, boxes, masks, im_info, flipped):
for t in self.transforms:
... | 4,104 | 30.821705 | 97 | py |
VLC-BERT | VLC-BERT-master/aokvqa/train_end2end.py | import _init_paths
import os
import argparse
import torch
import subprocess
from aokvqa.function.config import config, update_config
from aokvqa.function.train import train_net
from aokvqa.function.test import test_net
from external.PythonEvaluationTools.aokvqa_vqaEval import run_eval
def parse_args():
parser = ... | 2,328 | 34.830769 | 113 | py |
VLC-BERT | VLC-BERT-master/aokvqa/function/val.py | from collections import namedtuple
import torch
from common.trainer import to_cuda
@torch.no_grad()
def do_validation(net, val_loader, metrics, label_index_in_batch):
net.eval()
metrics.reset()
for nbatch, batch in enumerate(val_loader):
batch = to_cuda(batch)
label = batch[label_index_in_... | 528 | 26.842105 | 95 | py |
VLC-BERT | VLC-BERT-master/aokvqa/function/test.py | import os
import pprint
import shutil
import json
from tqdm import tqdm, trange
import numpy as np
import torch
import torch.nn.functional as F
from common.utils.load import smart_load_model_state_dict
from common.trainer import to_cuda
from common.utils.create_logger import create_logger
from aokvqa.data.build impor... | 3,526 | 40.494118 | 162 | py |
VLC-BERT | VLC-BERT-master/aokvqa/function/train.py | import os
import pprint
import shutil
import inspect
from tensorboardX import SummaryWriter
import numpy as np
import torch
import torch.nn
import torch.optim as optim
import torch.distributed as distributed
from torch.nn.parallel import DistributedDataParallel as DDP
from common.utils.create_logger import create_log... | 17,600 | 51.228487 | 147 | py |
VLC-BERT | VLC-BERT-master/aokvqa/modules/resnet_vlbert_for_aokvqa.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from external.pytorch_pretrained_bert import BertTokenizer
from external.pytorch_pretrained_bert.modeling import BertPredictionHeadTransform
from common.module import Module
from common.fast_rcnn import FastRCNN
from common.visual_linguistic_b... | 22,529 | 50.674312 | 156 | py |
VLC-BERT | VLC-BERT-master/aokvqa/data/collate_batch.py | import torch
from common.utils.clip_pad import *
class BatchCollator(object):
def __init__(self, dataset, append_ind=False):
self.dataset = dataset
self.test_mode = self.dataset.test_mode
self.data_names = self.dataset.data_names
self.append_ind = append_ind
def __call__(self,... | 2,295 | 37.266667 | 115 | py |
VLC-BERT | VLC-BERT-master/aokvqa/data/build.py | import torch.utils.data
from .datasets import *
from . import samplers
from .transforms.build import build_transforms
from .collate_batch import BatchCollator
import pprint
DATASET_CATALOGS = {'aokvqa': AOKVQA}
def build_dataset(dataset_name, *args, **kwargs):
assert dataset_name in DATASET_CATALOGS, "dataset n... | 4,753 | 44.27619 | 106 | py |
VLC-BERT | VLC-BERT-master/aokvqa/data/datasets/aokvqa.py | import os
import json
import _pickle as cPickle
from PIL import Image
import re
import base64
import numpy as np
import csv
import sys
import time
import logging
import pickle5 as pickle
import torch
from torch.utils.data import Dataset
from external.pytorch_pretrained_bert import BertTokenizer
from common.utils.zipr... | 21,774 | 42.812877 | 171 | py |
VLC-BERT | VLC-BERT-master/aokvqa/data/samplers/grouped_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import torch
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It enfo... | 4,846 | 40.42735 | 88 | py |
VLC-BERT | VLC-BERT-master/aokvqa/data/samplers/distributed.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Code is copy-pasted exactly as in torch.utils.data.distributed.
# FIXME remove this once c10d fixes the bug it has
import math
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
class DistributedSampler(S... | 2,568 | 37.924242 | 86 | py |
VLC-BERT | VLC-BERT-master/aokvqa/data/transforms/transforms.py | import random
import numpy as np
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, boxes, masks, im_info, flipped):
for t in self.transforms:
... | 4,104 | 30.821705 | 97 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# 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/LICENS... | 6,803 | 40.742331 | 116 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/optimization_openai.py | # coding=utf-8
# Copyright 2018 The Open AI Team Authors and The HugginFace Inc. team.
#
# 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
#
# U... | 5,661 | 39.156028 | 116 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/__main__.py | # coding: utf8
def main():
import sys
if (len(sys.argv) != 4 and len(sys.argv) != 5) or sys.argv[1] not in [
"convert_tf_checkpoint_to_pytorch",
"convert_openai_checkpoint",
"convert_transfo_xl_checkpoint",
"convert_gpt2_checkpoint",
]:
print(
"Should be used ... | 4,393 | 51.309524 | 145 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/convert_gpt2_checkpoint_to_pytorch.py | # coding=utf-8
# Copyright 2018 The HugginFace Inc. team.
#
# 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 ... | 3,046 | 40.739726 | 111 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/convert_openai_checkpoint_to_pytorch.py | # coding=utf-8
# Copyright 2018 The HugginFace Inc. team.
#
# 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 ... | 3,141 | 42.041096 | 118 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/modeling.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace 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 copy... | 60,198 | 48.18219 | 139 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/modeling_gpt2.py | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HugginFace 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 copy of the License ... | 29,887 | 42.632117 | 146 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/modeling_openai.py | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HugginFace 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 copy of the License ... | 37,647 | 45.421702 | 152 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/convert_transfo_xl_checkpoint_to_pytorch.py | # coding=utf-8
# Copyright 2018 The HugginFace Inc. team.
#
# 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 ... | 5,642 | 47.230769 | 121 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import json
import logging
import os
import shutil
im... | 8,280 | 32.124 | 112 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/convert_tf_checkpoint_to_pytorch.py | # coding=utf-8
# Copyright 2018 The HugginFace Inc. team.
#
# 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 ... | 2,538 | 39.301587 | 109 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/modeling_transfo_xl.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HugginFace 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 Licen... | 58,702 | 41.476845 | 131 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/tokenization_transfo_xl.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HugginFace 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 Licen... | 24,851 | 35.927192 | 109 | py |
VLC-BERT | VLC-BERT-master/external/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py | # coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HugginFace 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 Licen... | 16,113 | 38.985112 | 132 | py |
VLC-BERT | VLC-BERT-master/common/lr_scheduler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from bisect import bisect_right
import torch
# FIXME ideally this would be achieved with a CombinedLRScheduler,
# separating MultiStepLR with WarmupLR
# but the current LRScheduler design doesn't allow it
class WarmupMultiStepLR(torch.optim.lr_s... | 1,810 | 33.169811 | 80 | py |
VLC-BERT | VLC-BERT-master/common/fast_rcnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from common.backbone.resnet.resnet import *
from common.backbone.resnet.resnet import Bottleneck, BasicBlock
from common.backbone.resnet.resnet import model_urls
from common.lib.roi_pooling.roi_pool import ROI... | 10,223 | 49.117647 | 155 | py |
VLC-BERT | VLC-BERT-master/common/visual_linguistic_bert.py | import torch
import torch.nn as nn
from easydict import EasyDict as edict
from external.pytorch_pretrained_bert.modeling import BertLayerNorm, BertEncoder, BertPooler, ACT2FN, BertOnlyMLMHead
from common.commonsense_fusion import SimpleFusionLayer
# todo: add this to config
NUM_SPECIAL_WORDS = 1000
class BaseModel(n... | 28,112 | 49.56295 | 128 | py |
VLC-BERT | VLC-BERT-master/common/commonsense_fusion.py | import torch.nn as nn
def init_weights(m):
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
nn.init.uniform_(m.bias)
def prepare_mask(key_mask, query_mask):
len_k = key_mask.size(1)
len_q = query_mask.size(1)
padding_mask1 = query_mask.unsqueeze(1).expand(-1, len_k, -1)... | 2,409 | 35.515152 | 169 | py |
VLC-BERT | VLC-BERT-master/common/module.py | from collections import namedtuple
from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
class Module(nn.Module):
def __init__(self, config):
super(Module, self).__init__()
self.config = config
def init_weight(self):
raise NotImplementedError()
... | 1,786 | 26.921875 | 65 | py |
VLC-BERT | VLC-BERT-master/common/trainer.py | import os
import time
from collections import namedtuple
import torch
try:
from apex import amp
from apex.amp import _amp_state
except ImportError:
pass
#raise ImportError("Please install apex from https://www.github.com/nvidia/apex if you want to use fp16.")
# Parameter to pass to batch_end_callback
... | 7,611 | 37.251256 | 122 | py |
VLC-BERT | VLC-BERT-master/common/backbone/resnet/resnet.py | """
Modified from torchvision, but exposes features from different stages
"""
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
import warnings
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pyt... | 17,247 | 40.461538 | 135 | py |
VLC-BERT | VLC-BERT-master/common/callbacks/epoch_end_callbacks/checkpoint.py | import torch
class Checkpoint(object):
def __init__(self, prefix, frequent):
super(Checkpoint, self).__init__()
self.prefix = prefix
self.frequent = frequent
def __call__(self, epoch_num, net, optimizer, writer, validation_monitor=None):
checkpoint_dict = dict()
check... | 1,212 | 36.90625 | 83 | py |
VLC-BERT | VLC-BERT-master/common/nlp/misc.py | import torch
import random
def get_align_matrix(aligned_ids, sparse=False, device=None, dtype=torch.float32):
"""
Get aligned matrix for feature alignment in sentence embedding
:param aligned_ids: list, aligned_ids[k] means original index of k-th token
:param sparse: whether to return sparse matrix
... | 2,726 | 30.344828 | 104 | py |
VLC-BERT | VLC-BERT-master/common/nlp/time_distributed.py | """
A wrapper that unrolls the second (time) dimension of a tensor
into the first (batch) dimension, applies some other ``Module``,
and then rolls the time dimension back up.
"""
import torch
class TimeDistributed(torch.nn.Module):
"""
Given an input shaped like ``(batch_size, time_steps, [rest])`` and a ``M... | 2,245 | 42.192308 | 99 | py |
VLC-BERT | VLC-BERT-master/common/nlp/encoder_base.py | from typing import Tuple, Union, Optional, Callable
import torch
from torch.nn.utils.rnn import pack_padded_sequence, PackedSequence
# We have two types here for the state, because storing the state in something
# which is Iterable (like a tuple, below), is helpful for internal manipulation
# - however, the states are... | 18,404 | 52.502907 | 109 | py |
VLC-BERT | VLC-BERT-master/common/nlp/bert_encoder_wrapper.py | import torch
import torch.nn as nn
from external.pytorch_pretrained_bert.modeling import BertEncoder, BertLayerNorm
class BertEncoderWrapper(nn.Module):
def __init__(self, bert_config, input_size, output_all_encoded_layers=False):
super(BertEncoderWrapper, self).__init__()
self.bert_config = bert_... | 3,207 | 49.125 | 112 | py |
VLC-BERT | VLC-BERT-master/common/nlp/input_variational_dropout.py | import torch
class InputVariationalDropout(torch.nn.Dropout):
"""
Apply the dropout technique in Gal and Ghahramani, "Dropout as a Bayesian Approximation:
Representing Model Uncertainty in Deep Learning" (https://arxiv.org/abs/1506.02142) to a
3D tensor.
This module accepts a 3D tensor of shape ``... | 1,324 | 37.970588 | 98 | py |
VLC-BERT | VLC-BERT-master/common/nlp/roberta/utils.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import os
try:
from functools import lru_cache
except ImportError:
# Just a dummy decorator to get the checks to run on python2
# because honestly I don't want to support a byte-level un... | 40,379 | 45.736111 | 380 | py |
VLC-BERT | VLC-BERT-master/common/nlp/roberta/modeling_roberta.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... | 17,448 | 53.021672 | 134 | py |
VLC-BERT | VLC-BERT-master/common/nlp/bert/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... | 8,653 | 45.031915 | 130 | py |
VLC-BERT | VLC-BERT-master/common/metrics/eval_metric.py | import torch
import torch.distributed as distributed
class EvalMetric(object):
"""Base class for all evaluation metrics.
.. note::
This is a base class that provides common metric interfaces.
One should not use this class directly, but instead create new metric
classes that extend it.
... | 2,371 | 33.376812 | 80 | py |
VLC-BERT | VLC-BERT-master/common/metrics/vqa_metrics.py | import torch
from .eval_metric import EvalMetric
class LossLogger(EvalMetric):
def __init__(self, output_name, display_name=None,
allreduce=False, num_replicas=1):
self.output_name = output_name
if display_name is None:
display_name = output_name
super(LossLogg... | 1,174 | 31.638889 | 90 | py |
VLC-BERT | VLC-BERT-master/common/metrics/refcoco_metrics.py | import torch
from .eval_metric import EvalMetric
class LossLogger(EvalMetric):
def __init__(self, output_name, display_name=None,
allreduce=False, num_replicas=1):
self.output_name = output_name
if display_name is None:
display_name = output_name
super(LossLogg... | 2,715 | 33.379747 | 98 | py |
VLC-BERT | VLC-BERT-master/common/metrics/pretrain_metrics.py | import torch
from .eval_metric import EvalMetric
class LossLogger(EvalMetric):
def __init__(self, output_name, display_name=None,
allreduce=False, num_replicas=1):
self.output_name = output_name
if display_name is None:
display_name = output_name
super(LossLogg... | 3,263 | 35.266667 | 112 | py |
VLC-BERT | VLC-BERT-master/common/metrics/composite_eval_metric.py | import numpy as np
from .eval_metric import EvalMetric
import torch
class CompositeEvalMetric(EvalMetric):
"""Manages multiple evaluation metrics.
Args:
metrics (list of EvalMetric): List of child metrics.
name (str): Name of this metric instance for display.
"""
def __init__(self, met... | 2,153 | 29.771429 | 80 | py |
VLC-BERT | VLC-BERT-master/common/metrics/vcr_metrics.py | import torch
from .eval_metric import EvalMetric
class LossLogger(EvalMetric):
def __init__(self, output_name, display_name=None,
allreduce=False, num_replicas=1):
self.output_name = output_name
if display_name is None:
display_name = output_name
super(LossLogg... | 2,953 | 35.02439 | 90 | py |
VLC-BERT | VLC-BERT-master/common/utils/multi_task_dataloader.py | from functools import reduce
import operator
from typing import List
from torch.utils.data import DataLoader
import sys
INT_MAX = sys.maxsize
def prod(iterable):
if len(list(iterable)) > 0:
return reduce(operator.mul, iterable)
else:
return 1
class MultiTaskDataLoader(object):
"""
M... | 1,619 | 26.931034 | 102 | py |
VLC-BERT | VLC-BERT-master/common/utils/build_attn_annot_okvqa.py | import json
import random
import numpy as np
from external.pytorch_pretrained_bert import BertTokenizer
import string
from nltk.corpus import stopwords
#nltk.download('stopwords')
DATASET = 'okvqa'
EXP_NAME = 'semqo'
MAX_COMMONSENSE_LEN = 5
RANDOM_SEED = 12345
random.seed(RANDOM_SEED)
tokenizer = BertTokenizer.from_p... | 4,128 | 28.705036 | 113 | py |
VLC-BERT | VLC-BERT-master/common/utils/misc.py | import os
import numpy as np
import torch
import torch.nn.functional as F
import logging
def block_digonal_matrix(*blocks):
"""
Construct block diagonal matrix
:param blocks: blocks of block diagonal matrix
:param device
:param dtype
:return: block diagonal matrix
"""
assert len(blocks... | 5,958 | 36.71519 | 124 | py |
VLC-BERT | VLC-BERT-master/common/utils/flatten.py | import torch
class Flattener(torch.nn.Module):
def __init__(self):
"""
Flattens last 3 dimensions to make it only batch size, -1
"""
super(Flattener, self).__init__()
def forward(self, x):
return x.view(x.size(0), -1)
| 269 | 19.769231 | 65 | py |
VLC-BERT | VLC-BERT-master/common/utils/bbox.py | import torch
def nonlinear_transform(ex_rois, gt_rois):
"""
compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [k, 4] ([x1, y1, x2, y2])
:param gt_rois: [k, 4] (corresponding gt_boxes [x1, y1, x2, y2] )
:return: bbox_targets: [k, 4]
"""
assert ex_rois.shape[0] ... | 3,289 | 33.631579 | 113 | py |
VLC-BERT | VLC-BERT-master/common/utils/load.py | import torch
import os
def smart_load_model_state_dict(model, state_dict):
parsed_state_dict = {}
for k, v in state_dict.items():
if k not in model.state_dict():
if k.startswith('module.'):
k = k[len('module.'):]
else:
k = 'module.' + k
i... | 4,708 | 47.546392 | 104 | py |
VLC-BERT | VLC-BERT-master/common/utils/masked_softmax.py | import torch
def masked_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
"""
``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a softmax on just the non-masked portions of ``vector``. Passing
``None``... | 1,533 | 50.133333 | 111 | py |
VLC-BERT | VLC-BERT-master/common/utils/pad_sequence.py | import torch
def pad_sequence(sequence, lengths):
"""
:param sequence: [\sum b, .....] sequence
:param lengths: [b1, b2, b3...] that sum to \sum b
:return: [len(lengths), maxlen(b), .....] tensor
"""
output = sequence.new_zeros(len(lengths), max(lengths), *sequence.shape[1:])
start = 0
... | 480 | 25.722222 | 80 | py |
VLC-BERT | VLC-BERT-master/common/utils/build_attn_annot_aokvqa.py | import json
import random
import numpy as np
from external.pytorch_pretrained_bert import BertTokenizer
import string
from nltk.corpus import stopwords
#nltk.download('stopwords')
DATASET = 'aokvqa'
EXP_NAME = 'semqo'
MAX_COMMONSENSE_LEN = 5
RANDOM_SEED = 12345
random.seed(RANDOM_SEED)
tokenizer = BertTokenizer.from_... | 3,554 | 28.139344 | 115 | py |
VLC-BERT | VLC-BERT-master/common/utils/clip_pad.py | import torch
def clip_pad_images(tensor, pad_shape, pad=0):
"""
Clip clip_pad_images of the pad area.
:param tensor: [c, H, W]
:param pad_shape: [h, w]
:return: [c, h, w]
"""
if not isinstance(tensor, torch.Tensor):
tensor = torch.as_tensor(tensor)
H, W = tensor.shape[1:]
h... | 1,738 | 28.982759 | 93 | py |
VLC-BERT | VLC-BERT-master/common/utils/mask.py | from skimage.draw import polygon
import torch
def generate_instance_mask(seg_polys, box, mask_size=(14, 14), dtype=torch.float32, copy=True):
"""
Generate instance mask from polygon
:param seg_poly: torch.Tensor, (N, 2), (x, y) coordinate of N vertices of segmented foreground polygon
:param box: array... | 1,282 | 33.675676 | 106 | py |
VLC-BERT | VLC-BERT-master/common/lib/roi_pooling/roi_pool.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import C_ROIPooling
class _ROIPool(Function):
@staticmethod
def... | 2,174 | 28.794521 | 90 | py |
VLC-BERT | VLC-BERT-master/common/lib/roi_pooling/roi_align.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import C_ROIPooling
class _ROIAlign(Function):
@staticmethod
de... | 2,468 | 30.253165 | 98 | py |
VLC-BERT | VLC-BERT-master/common/lib/roi_pooling/setup.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#!/usr/bin/env python
import glob
import os
import torch
from setuptools import find_packages
from setuptools import setup
from torch.utils.cpp_extension import CUDA_HOME
from torch.utils.cpp_extension import CppExtension
from torch.utils.cpp_ext... | 1,799 | 26.272727 | 73 | py |
VLC-BERT | VLC-BERT-master/common/lib/roi_pooling/debug.py | import torch
from roi_pool import ROIPool
from roi_align import ROIAlign
align = ROIAlign(output_size=(3, 3), spatial_scale=1.0, sampling_ratio=1)
pool = ROIPool(output_size=(3, 3), spatial_scale=1.0)
device = torch.device("cuda:0")
feature = torch.arange(81*2*3).view((2,3,9,9)).float().to(device)
rois = torch.Tenso... | 463 | 24.777778 | 73 | py |
VLC-BERT | VLC-BERT-master/viz/bertviz/attention.py | import torch
from collections import defaultdict
def get_attention(model, model_type, tokenizer, sentence_a, sentence_b=None, include_queries_and_keys=False):
"""Compute representation of attention to pass to the d3 visualization
Args:
model: pytorch-transformers model
model_type: type of mo... | 8,283 | 43.778378 | 185 | py |
VLC-BERT | VLC-BERT-master/scripts/launch.py | r"""
`torch.distributed.launch` is a module that spawns up multiple distributed
training processes on each of the training nodes.
The utility can be used for single-node distributed training, in which one or
more processes per node will be spawned. The utility can be used for either
CPU training or GPU training. If the... | 9,500 | 46.268657 | 95 | py |
VLC-BERT | VLC-BERT-master/okvqa/train_end2end.py | import _init_paths
import os
import argparse
import torch
import subprocess
import json
from okvqa.function.config import config, update_config
from okvqa.function.train import train_net
from okvqa.function.test import test_net
from external.PythonEvaluationTools.okvqa_vqaEval import run_eval
def parse_args():
p... | 3,058 | 33.370787 | 113 | py |
VLC-BERT | VLC-BERT-master/okvqa/function/val.py | from collections import namedtuple
import torch
from common.trainer import to_cuda
@torch.no_grad()
def do_validation(net, val_loader, metrics, label_index_in_batch):
net.eval()
metrics.reset()
for nbatch, batch in enumerate(val_loader):
batch = to_cuda(batch)
label = batch[label_index_in_... | 528 | 26.842105 | 95 | py |
VLC-BERT | VLC-BERT-master/okvqa/function/test.py | import os
import pprint
import shutil
import json
from tqdm import tqdm, trange
import numpy as np
import torch
import torch.nn.functional as F
from common.utils.load import smart_load_model_state_dict
from common.trainer import to_cuda
from common.utils.create_logger import create_logger
from okvqa.data.build import... | 3,523 | 40.458824 | 162 | py |
VLC-BERT | VLC-BERT-master/okvqa/function/train.py | import os
import pprint
import shutil
import inspect
from tensorboardX import SummaryWriter
import numpy as np
import torch
import torch.nn
import torch.optim as optim
import torch.distributed as distributed
from torch.nn.parallel import DistributedDataParallel as DDP
from common.utils.create_logger import create_log... | 17,597 | 51.219585 | 147 | py |
VLC-BERT | VLC-BERT-master/okvqa/modules/resnet_vlbert_for_okvqa.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from external.pytorch_pretrained_bert import BertTokenizer
from external.pytorch_pretrained_bert.modeling import BertPredictionHeadTransform
from common.module import Module
from common.fast_rcnn import FastRCNN
from common.visual_linguistic_b... | 22,549 | 50.601831 | 156 | py |
VLC-BERT | VLC-BERT-master/okvqa/data/collate_batch.py | import torch
from common.utils.clip_pad import *
class BatchCollator(object):
def __init__(self, dataset, append_ind=False):
self.dataset = dataset
self.test_mode = self.dataset.test_mode
self.data_names = self.dataset.data_names
self.append_ind = append_ind
def __call__(self,... | 2,295 | 37.266667 | 115 | py |
VLC-BERT | VLC-BERT-master/okvqa/data/build.py | import torch.utils.data
from .datasets import *
from . import samplers
from .transforms.build import build_transforms
from .collate_batch import BatchCollator
import pprint
DATASET_CATALOGS = {'okvqa': OKVQA}
def build_dataset(dataset_name, *args, **kwargs):
assert dataset_name in DATASET_CATALOGS, "dataset not... | 4,750 | 44.247619 | 106 | py |
VLC-BERT | VLC-BERT-master/okvqa/data/datasets/okvqa.py | import os
import json
import _pickle as cPickle
from PIL import Image
import re
import base64
import numpy as np
import csv
import sys
import time
import logging
import pickle5 as pickle
import torch
from torch.utils.data import Dataset
from external.pytorch_pretrained_bert import BertTokenizer
from common.utils.zipr... | 22,450 | 42.935421 | 171 | py |
VLC-BERT | VLC-BERT-master/okvqa/data/samplers/grouped_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import torch
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It enfo... | 4,846 | 40.42735 | 88 | py |
VLC-BERT | VLC-BERT-master/okvqa/data/samplers/distributed.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Code is copy-pasted exactly as in torch.utils.data.distributed.
# FIXME remove this once c10d fixes the bug it has
import math
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
class DistributedSampler(S... | 2,568 | 37.924242 | 86 | py |
VLC-BERT | VLC-BERT-master/okvqa/data/transforms/transforms.py | import random
import numpy as np
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, boxes, masks, im_info, flipped):
for t in self.transforms:
... | 4,104 | 30.821705 | 97 | py |
HVAE | HVAE-master/setup.py | from distutils.core import setup
from setuptools import dist
dist.Distribution().fetch_build_eggs(['Cython', 'numpy<=1.19'])
import numpy
from Cython.Build import cythonize
required = [
"cython",
"numpy",
"torch",
"editdistance",
"scikit-learn",
"tqdm",
"pymoo"
]
setup(name='HVAE',
... | 606 | 20.678571 | 63 | py |
HVAE | HVAE-master/src/symbolic_regression.py | import argparse
import json
import random
import time
import numpy as np
import torch
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.optimize import minimize
from pymoo.core.problem import ElementwiseProblem
from pymoo.core.sampling import Sampling
from pymoo.core.crossover import Crossover
from pymoo.cor... | 6,382 | 37.920732 | 125 | py |
HVAE | HVAE-master/src/batch_model.py | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from tree import Node, BatchedNode
from symbol_library import SymType
class HVAE(nn.Module):
_symbols = None
def __init__(self, input_size, output_size, hidden_size=None):
super(HVAE, self).__init_... | 8,343 | 38.545024 | 111 | py |
HVAE | HVAE-master/src/batch_train.py | from argparse import ArgumentParser
import numpy as np
import torch
from torch.utils.data import Sampler, Dataset, DataLoader
from tqdm import tqdm
# from utils import tokens_to_tree, read_expressions
from utils import read_expressions_json
from batch_model import HVAE
from symbol_library import generate_symbol_libra... | 4,883 | 31.778523 | 112 | py |
HVAE | HVAE-master/src/tree.py | import torch
from torch.autograd import Variable
class Node:
_symbols = None
_s2c = None
def __init__(self, symbol=None, right=None, left=None):
self.symbol = symbol
self.right = right
self.left = left
self.target = None
self.prediction = None
def __str__(self... | 9,097 | 34.263566 | 117 | py |
HVAE | HVAE-master/src/model.py | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from tree import Node
from symbol_library import SymType
class HVAE(nn.Module):
_symbols = None
def __init__(self, input_size, output_size, hidden_size=None):
super(HVAE, self).__init__()
... | 7,496 | 39.090909 | 111 | py |
HVAE | HVAE-master/src/reconstruction_accuracy.py | from argparse import ArgumentParser
import numpy as np
import torch
from sklearn.model_selection import KFold
import editdistance
from utils import read_expressions, tokens_to_tree
from symbol_library import generate_symbol_library
from model import HVAE
from train import train_hvae
def one_fold(model, train, test,... | 3,214 | 38.691358 | 119 | py |
HVAE | HVAE-master/src/linear_interpolation.py | import torch
from model import HVAE
from utils import tokens_to_tree
from symbol_library import generate_symbol_library
def interpolateAB(model, exprA, exprB, steps=5):
tokensA = exprA.split(" ")
tokensB = exprB.split(" ")
treeA = tokens_to_tree(tokensA, s2t)
treeB = tokens_to_tree(tokensB, s2t)
... | 1,089 | 28.459459 | 89 | py |
HVAE | HVAE-master/src/train.py | from argparse import ArgumentParser
import numpy as np
import torch
from torch.utils.data import Sampler, Dataset, DataLoader
from tqdm import tqdm
from utils import tokens_to_tree, read_expressions, read_json
from model import HVAE
from symbol_library import generate_symbol_library
def collate_fn(batch):
retur... | 4,523 | 34.904762 | 112 | py |
AutoPruner | AutoPruner-master/ResNet50/50/fine_tune_compressed_model.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
fro... | 10,872 | 35.733108 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/main.py | # ************************************************************
# Author : Bumsoo Kim, 2017
# Github : https://github.com/meliketoy/fine-tuning.pytorch
#
# Korea University, Data-Mining Lab
# Deep Convolutional Network Fine tuning Implementation
#
# Description : main.py
# The main code for training classification netwo... | 14,783 | 42.354839 | 146 | py |
AutoPruner | AutoPruner-master/ResNet50/50/evaluate_network.py | import torch
import torch.backends.cudnn as cudnn
import os
import sys
import argparse
import time
from src_code.lmdbdataset import lmdbDataset
from src_code import Network_FT
parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training')
parser.add_argument('--batch_size', default=100, type=int... | 4,037 | 31.564516 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/fine_tune_again.py | import argparse
import os
import shutil
import time
import sys
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision import datasets, transforms
fro... | 10,815 | 35.789116 | 106 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/my_op_fc.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
class MyGAP_fc(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*4096 -> 1*4096
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backw... | 2,729 | 31.117647 | 76 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/my_op.py | import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.autograd import gradcheck
import numpy as np
import math
class MyGAP(torch.autograd.Function):
'''
Global Average Pooling with batchsize: N*512*14*14 -> 1*512*14*14
'''
@staticmethod
def forward(ctx, input):
... | 3,182 | 33.225806 | 93 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/Network_FT.py | import torch.nn as nn
import math
import torch
from . import my_op
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
... | 12,489 | 37.549383 | 111 | py |
AutoPruner | AutoPruner-master/ResNet50/50/src_code/lmdbdataset.py | import cv2
import numpy as np
import torchvision.transforms as transforms
import lmdb
import msgpack
from torch.utils.data import Dataset
from PIL import Image
class lmdbDataset(Dataset):
def __init__(self, location, is_train):
self.env = lmdb.open(location, subdir=False, max_readers=1, readonly=True, loc... | 2,431 | 34.246377 | 111 | py |
AutoPruner | AutoPruner-master/ResNet50/50/compress_model/new_model.py | import torch.nn as nn
import torch
import numpy as np
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, number_list, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(number_list[1], number_list[0], kernel_size=1, bias=False)
self.bn1 = ... | 8,768 | 35.235537 | 95 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.