repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
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/tokenization.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...
14,453
37.854839
133
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/__init__.py
__version__ = "0.6.0" from .tokenization import BertTokenizer, BasicTokenizer, WordpieceTokenizer from .tokenization_openai import OpenAIGPTTokenizer from .tokenization_transfo_xl import (TransfoXLTokenizer, TransfoXLCorpus) from .tokenization_gpt2 import GPT2Tokenizer from .modeling import (BertConfig, BertModel, Ber...
1,286
50.48
88
py
VLC-BERT
VLC-BERT-master/external/pytorch_pretrained_bert/tokenization_gpt2.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...
8,544
40.280193
114
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/tokenization_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...
11,338
41.950758
129
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/__init__.py
0
0
0
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/__init__.py
from .resnet import resnet18, resnet34, resnet50, resnet101, resnet152
71
35
70
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/backbone/resnet/__init__.py
from .resnet import *
22
10.5
21
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/callbacks/epoch_end_callbacks/validation_monitor.py
import logging import shutil class ValidationMonitor(object): def __init__(self, val_func, val_loader, metrics, host_metric_name='Acc', label_index_in_batch=-1): super(ValidationMonitor, self).__init__() self.val_func = val_func self.val_loader = val_loader self.metrics = metrics ...
2,031
38.076923
124
py
VLC-BERT
VLC-BERT-master/common/callbacks/epoch_end_callbacks/__init__.py
0
0
0
py
VLC-BERT
VLC-BERT-master/common/callbacks/batch_end_callbacks/speedometer.py
# -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2016 by Contributors # Copyright (c) 2017 Microsoft # Licensed under The Apache-2.0 License [see LICENSE for details] # Modified by Yuwen Xiong # Modified by Dazhi Cheng # -------------------------------------...
4,461
42.320388
146
py
VLC-BERT
VLC-BERT-master/common/callbacks/batch_end_callbacks/__init__.py
0
0
0
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/__init__.py
0
0
0
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/tokenization_roberta.py
# coding=utf-8 # Copyright 2018 The Open AI 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/LICENSE-2.0 # # ...
8,303
40.313433
118
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/__init__.py
from .tokenization_roberta import RobertaTokenizer
51
25
50
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/nlp/bert/__init__.py
0
0
0
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/__init__.py
0
0
0
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/create_logger.py
# -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2017 Microsoft # Licensed under The Apache-2.0 License [see LICENSE for details] # Written by Bin Xiao # -------------------------------------------------------- import os import logging import time import er...
1,639
31.156863
89
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/__init__.py
0
0
0
py
VLC-BERT
VLC-BERT-master/common/utils/build_sbert_emb.py
from sentence_transformers import SentenceTransformer import json import pickle5 as pickle import os from tqdm import tqdm DATASET = 'aokvqa' EXP_NAME = 'semqo' MAX_COMMONSENSE_LEN = 5 BASE_SAVE_PATH = 'data/coco' USE_QUESTION = True def filename(exp_name): return (exp_name[:-1]+ "." + exp_name[-1]).lower() def...
5,182
40.464
123
py
VLC-BERT
VLC-BERT-master/common/utils/zipreader.py
import zipfile import os import io import time from PIL import Image class ZipReader(object): zip_bank = dict() def __init__(self): super(ZipReader, self).__init__() @staticmethod def get_zipfile(path): zip_bank = ZipReader.zip_bank if path in zip_bank: return zip...
2,772
31.244186
121
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/__init__.py
from .roi_align import ROIAlign from .roi_pool import ROIPool
61
30
31
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/_init_paths.py
import os import sys this_dir = os.path.abspath(os.path.dirname(__file__)) def add_path(path): if path not in sys.path: sys.path.insert(0, path) root_path = os.path.join(this_dir, '../') add_path(root_path)
224
15.071429
53
py
VLC-BERT
VLC-BERT-master/viz/bertviz/model_view.py
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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,180
33.078125
102
py
VLC-BERT
VLC-BERT-master/viz/bertviz/__init__.py
0
0
0
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/test.py
import _init_paths import os import argparse from copy import deepcopy from okvqa.function.config import config, update_config from okvqa.function.test import test_net def parse_args(): parser = argparse.ArgumentParser('Get Test Result of OK-VQA Network') parser.add_argument('--cfg', type=str, help='path to ...
1,531
32.304348
108
py
VLC-BERT
VLC-BERT-master/okvqa/_init_paths.py
import os import sys this_dir = os.path.abspath(os.path.dirname(__file__)) def add_path(path): if path not in sys.path: sys.path.insert(0, path) root_path = os.path.join(this_dir, '../') add_path(root_path)
224
15.071429
53
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/config.py
from easydict import EasyDict as edict import yaml _C = edict() config = _C # ------------------------------------------------------------------------------------- # # Common options # ------------------------------------------------------------------------------------- # _C.RNG_SEED = -1 _C.OUTPUT_PATH = '' _C.MODUL...
7,737
36.201923
108
py
VLC-BERT
VLC-BERT-master/okvqa/function/__init__.py
0
0
0
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/modules/__init__.py
from .resnet_vlbert_for_okvqa import ResNetVLBERT
52
12.25
49
py
VLC-BERT
VLC-BERT-master/okvqa/data/__init__.py
0
0
0
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/datasets/__init__.py
from .okvqa import OKVQA
26
8
24
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/samplers/__init__.py
from .distributed import DistributedSampler from .grouped_batch_sampler import GroupedBatchSampler
100
24.25
54
py
VLC-BERT
VLC-BERT-master/okvqa/data/transforms/__init__.py
from .transforms import Compose from .transforms import Resize from .transforms import RandomHorizontalFlip from .transforms import ToTensor from .transforms import Normalize from .build import build_transforms
212
25.625
44
py
VLC-BERT
VLC-BERT-master/okvqa/data/transforms/build.py
from . import transforms as T def build_transforms(cfg, mode='train'): assert mode in ['train', 'test', 'val'] min_size = cfg.SCALES[0] max_size = cfg.SCALES[1] assert min_size <= max_size if mode == 'train': flip_prob = cfg.TRAIN.FLIP_PROB elif mode == 'test': flip_prob = cfg...
1,034
23.069767
85
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
VLC-BERT
VLC-BERT-master/data/conceptual-captions/utils/gen_val_image_json.py
captions = [] urls = [] with open('Validation_GCC-1.1.0-Validation.tsv') as fp: for cnt, line in enumerate(fp): s = line.split('\t') captions.append(s[0].split(' ')) urls.append(s[1][:-1]) valids = set([]) with open('val_valid.txt') as fp: for cnt, line in enumerate(fp): ...
1,047
32.806452
121
py
VLC-BERT
VLC-BERT-master/data/conceptual-captions/utils/gen_train_image_json.py
captions = [] urls = [] with open('Train_GCC-training.tsv') as fp: for cnt, line in enumerate(fp): s = line.split('\t') captions.append(s[0].split(' ')) urls.append(s[1][:-1]) valids = set([]) with open('train_valid.txt') as fp: for cnt, line in enumerate(fp): valids.ad...
1,059
32.125
125
py
VLC-BERT
VLC-BERT-master/data/conceptual-captions/utils/gen_train4download.py
import os captions = [] urls = [] with open('Train_GCC-training.tsv') as fp: for cnt, line in enumerate(fp): s = line.split('\t') captions.append(s[0].split(' ')) urls.append(s[1][:-1]) with open('train4download.txt', 'w') as fp: for cnt, url in enumerate(urls): fp.wri...
454
25.764706
72
py