id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
10,053
import torch from torch import nn import torch.nn.functional as F from maskrcnn_benchmark.structures.image_list import to_image_list from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist from ..backbone import build_backbone from ..rpn import bu...
greenlight_map, batch_size x 256 (seq_len): 0 means this location cannot be calculated in the MLM loss -1 means this location cannot be masked!! 1 means this location can be masked and can be calculated in the MLM loss
10,054
from collections import OrderedDict import torch from torch import nn from maskrcnn_benchmark.modeling import registry from . import bert_model from . import rnn_model from . import clip_model from . import word_utils def build_rnn_backbone(cfg): body = rnn_model.RNNEnoder(cfg) model = nn.Sequential(OrderedDic...
null
10,055
from collections import OrderedDict import torch from torch import nn from maskrcnn_benchmark.modeling import registry from . import bert_model from . import rnn_model from . import clip_model from . import word_utils def build_clip_backbone(cfg): body = clip_model.CLIPTransformer(cfg) model = nn.Sequential(Or...
null
10,056
from collections import OrderedDict import torch from torch import nn from maskrcnn_benchmark.modeling import registry from . import bert_model from . import rnn_model from . import clip_model from . import word_utils def build_backbone(cfg): assert cfg.MODEL.LANGUAGE_BACKBONE.MODEL_TYPE in registry.LANGUAGE_BACKB...
null
10,057
import gzip import html import os from functools import lru_cache import ftfy import regex as re from typing import Union, List import torch def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
null
10,058
import gzip import html import os from functools import lru_cache import ftfy import regex as re from typing import Union, List import torch The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the followin...
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This ...
10,059
import gzip import html import os from functools import lru_cache import ftfy import regex as re from typing import Union, List import torch The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem:...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
10,060
import gzip import html import os from functools import lru_cache import ftfy import regex as re from typing import Union, List import torch def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
null
10,061
import gzip import html import os from functools import lru_cache import ftfy import regex as re from typing import Union, List import torch def whitespace_clean(text): text = re.sub(r'\s+', ' ', text) text = text.strip() return text
null
10,062
from .simple_tokenizer import SimpleTokenizer class SimpleTokenizer(object): def __init__(self, bpe_path: str = default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode("utf-8").split('...
null
10,063
import torch import itertools from .lr_scheduler import WarmupMultiStepLR, WarmupCosineAnnealingLR, WarmupReduceLROnPlateau def make_optimizer(cfg, model): def maybe_add_full_model_gradient_clipping(optim): # optim: the optimizer class # detectron2 doesn't have full model gradient clipping now cli...
null
10,064
import torch import itertools from .lr_scheduler import WarmupMultiStepLR, WarmupCosineAnnealingLR, WarmupReduceLROnPlateau class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler): def __init__( self, optimizer, milestones, gamma=0.1, warmup_factor=1.0 / 3, wa...
null
10,065
import os def try_to_find(file, return_dir=False, search_path=['./DATASET', './OUTPUT', './data', './MODEL']): if not file: return file if file.startswith('catalog://'): return file DATASET_PATH = ['./'] if 'DATASET' in os.environ: DATASET_PATH.append(os.environ['DATASET']) ...
null
10,066
import datetime import logging import time import os import re import torch from tqdm import tqdm from collections import defaultdict from maskrcnn_benchmark.data.datasets.evaluation import evaluate, im_detect_bbox_aug from ..utils.comm import is_main_process from ..utils.comm import all_gather from ..utils.comm import...
null
10,067
import time import pickle import logging import os import numpy as np import torch import torch.nn as nn from collections import OrderedDict from yaml import safe_dump from yacs.config import load_cfg, CfgNod from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.engine.inference import _accumulate_predictio...
null
10,068
import time import pickle import logging import os import numpy as np import torch import torch.nn as nn from collections import OrderedDict from yaml import safe_dump from yacs.config import load_cfg, CfgNod from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.engine.inference import _accumulate_predictio...
null
10,069
import time import pickle import logging import os import numpy as np import torch import torch.nn as nn from collections import OrderedDict from yaml import safe_dump from yacs.config import load_cfg, CfgNod from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.engine.inference import _accumulate_predictio...
null
10,070
import time import pickle import logging import os import numpy as np import torch import torch.nn as nn from collections import OrderedDict from yaml import safe_dump from yacs.config import load_cfg, CfgNod from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.engine.inference import _accumulate_predictio...
null
10,071
import cv2 import torch import re import numpy as np from typing import List, Union import nltk import inflect from transformers import AutoTokenizer from torchvision import transforms as T import pdb from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import ...
null
10,072
import cv2 import torch import re import numpy as np from typing import List, Union import nltk import inflect from transformers import AutoTokenizer from torchvision import transforms as T import pdb from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import ...
construct a map such that positive_map[i,j] = True iff box i is associated to token j
10,073
import cv2 import torch import re import numpy as np from typing import List, Union import nltk import inflect from transformers import AutoTokenizer from torchvision import transforms as T import pdb from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import ...
null
10,074
import cv2 import torch import re import numpy as np from typing import List, Union import nltk import inflect from transformers import AutoTokenizer from torchvision import transforms as T import pdb from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import ...
null
10,075
import cv2 import torch import numpy as np from torchvision import transforms as T from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer from maskrcnn_benchmark.structures.image_list import to_image_list from maskrcnn_benchmark.struc...
Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
10,076
import datetime import logging import time import random import torch import torch.distributed as dist from maskrcnn_benchmark.utils.comm import get_world_size, synchronize, broadcast_data from maskrcnn_benchmark.utils.metric_logger import MetricLogger from maskrcnn_benchmark.utils.ema import ModelEma def reduce_loss_d...
null
10,077
import torch import torch.nn as nn import torch.nn.functional as F import pdb import math from maskrcnn_benchmark.modeling.utils import cat, concat_box_prediction_layers, permute_and_flatten from timm.models.layers import DropPath from transformers.activations import ACT2FN def _make_conv(input_dim, output_dim, k, str...
null
10,078
import torch import torch.nn as nn import torch.nn.functional as F import pdb import math from maskrcnn_benchmark.modeling.utils import cat, concat_box_prediction_layers, permute_and_flatten from timm.models.layers import DropPath from transformers.activations import ACT2FN def _make_mlp(input_dim, output_dim, drop): ...
null
10,079
import torch import torch.nn as nn import torch.nn.functional as F import pdb import math from maskrcnn_benchmark.modeling.utils import cat, concat_box_prediction_layers, permute_and_flatten from timm.models.layers import DropPath from transformers.activations import ACT2FN def cat(tensors, dim=0): """ Efficie...
null
10,080
import torch import torch.nn as nn import torch.nn.functional as F import pdb import math from maskrcnn_benchmark.modeling.utils import cat, concat_box_prediction_layers, permute_and_flatten from timm.models.layers import DropPath from transformers.activations import ACT2FN The provided code snippet includes necessary...
L1-normalize columns of X
10,081
import torch import torch.nn as nn import torch.nn.functional as F import pdb import math from maskrcnn_benchmark.modeling.utils import cat, concat_box_prediction_layers, permute_and_flatten from timm.models.layers import DropPath from transformers.activations import ACT2FN def l2norm(X, dim, eps=1e-8): """L2-norma...
query: (n_context, queryL, d) context: (n_context, sourceL, d)
10,082
import PIL from torch.utils.collect_env import get_pretty_env_info def get_pil_version(): return "\n Pillow ({})".format(PIL.__version__) def collect_env_info(): env_str = get_pretty_env_info() env_str += get_pil_version() return env_str
null
10,083
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def flops_to_string(flops, units='GMac', precision=2): if units is None: if flops // 10**9 > 0: return str(round(flops / 10.**9, precision)) + ' GMac' el...
null
10,084
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def empty_flops_counter_hook(module, input, output): module.__flops__ += 0
null
10,085
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def upsample_flops_counter_hook(module, input, output): output_size = output[0] batch_size = output_size.shape[0] output_elements_count = batch_size for val in output_s...
null
10,086
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def relu_flops_counter_hook(module, input, output): active_elements_count = output.numel() module.__flops__ += int(active_elements_count)
null
10,087
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def linear_flops_counter_hook(module, input, output): input = input[0] # pytorch checks dimensions, so here we don't care much output_last_dim = output.shape[-1] bias_f...
null
10,088
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def pool_flops_counter_hook(module, input, output): input = input[0] module.__flops__ += int(np.prod(input.shape))
null
10,089
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def bn_flops_counter_hook(module, input, output): input = input[0] batch_flops = np.prod(input.shape) if module.affine: batch_flops *= 2 module.__flops__ += in...
null
10,090
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def conv_flops_counter_hook(conv_module, input, output): # Can have multiple inputs, getting the first one input = input[0] batch_size = input.shape[0] output_dims = l...
null
10,091
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def rnn_flops(flops, rnn_module, w_ih, w_hh, input_size): # matrix matrix mult ih state and internal state flops += w_ih.shape[0]*w_ih.shape[1] # matrix matrix mult hh state...
Takes into account batch goes at first position, contrary to pytorch common rule (but actually it doesn't matter). IF sigmoid and tanh are made hard, only a comparison FLOPS should be accurate
10,092
import sys from functools import partial import numpy as np import torch import torch.nn as nn from maskrcnn_benchmark.layers import * def rnn_flops(flops, rnn_module, w_ih, w_hh, input_size): # matrix matrix mult ih state and internal state flops += w_ih.shape[0]*w_ih.shape[1] # matrix matrix mult hh state...
null
10,093
import numpy as np import torch import torch.nn as nn from collections import OrderedDict def tf2th(conv_weights): """Possibly convert HWIO to OIHW.""" if conv_weights.ndim == 4: conv_weights = conv_weights.transpose([3, 2, 0, 1]) return torch.from_numpy(conv_weights) def _rename_conv_weights_for_de...
null
10,094
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,095
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,096
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,097
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,098
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,099
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,100
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,101
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,102
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,103
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,104
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,105
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,106
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_bench...
null
10,107
import pickle import time import functools import logging import torch import torch.distributed as dist import numpy as np def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank(): if not dist.is_availab...
Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as input_dict, after reduction.
10,108
import pickle import time import functools import logging import torch import torch.distributed as dist import numpy as np def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def reduce_sum(tensor): if get_world_...
null
10,109
import pickle import time import functools import logging import torch import torch.distributed as dist import numpy as np def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gat...
Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock.
10,111
import torch import maskrcnn_benchmark.utils.dist as dist def normalized_positive_map(positive_map): positive_map = positive_map.float() positive_map_num_pos = positive_map.sum(2) positive_map_num_pos[positive_map_num_pos == 0] = 1e-6 positive_map = positive_map / positive_map_num_pos.unsqueeze(-1) ...
null
10,112
import torch import maskrcnn_benchmark.utils.dist as dist def pad_tensor_given_dim_length(tensor, dim, length, padding_value=0, batch_first=True): new_size = list(tensor.size()[:dim]) + [length] + list(tensor.size()[dim + 1:]) out_tensor = tensor.data.new(*new_size).fill_(padding_value) if batch_first: ...
null
10,113
import torch import maskrcnn_benchmark.utils.dist as dist def pad_random_negative_tensor_given_length(positive_tensor, negative_padding_tensor, length=None): assert positive_tensor.shape[0] + negative_padding_tensor.shape[0] == length return torch.cat((positive_tensor, negative_padding_tensor), dim=0)
null
10,114
import torch import maskrcnn_benchmark.utils.dist as dist The provided code snippet includes necessary dependencies for implementing the `gather_tensors` function. Write a Python function `def gather_tensors(tensor)` to solve the following problem: Performs all_gather operation on the provided tensors. *** Warning ***...
Performs all_gather operation on the provided tensors. *** Warning ***: torch.distributed.all_gather has no gradient.
10,115
import torch import maskrcnn_benchmark.utils.dist as dist def convert_to_roi_format(boxes): concat_boxes = boxes.bbox device, dtype = concat_boxes.device, concat_boxes.dtype ids = torch.full((len(boxes), 1), 0, dtype=dtype, device=device) rois = torch.cat([ids, concat_boxes], dim=1) return rois
null
10,116
import os import sys from maskrcnn_benchmark.utils.comm import is_main_process from maskrcnn_benchmark.utils.comm import synchronize def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return ...
r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more digits of the SHA256 hash of the contents of t...
10,117
import functools import io import os import torch import torch.distributed as dist def get_world_size(): """ Returns: The number of processes in the process group """ if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size() The provided code snippet includes nec...
Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that all processes have the averaged results. Returns a dict with the same fields as input_dict, after reduction.
10,118
import functools import io import os import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_rank(): """ Returns: The rank of the current process within the global process group. """ if not is_dist_avail_and_initialized(): return 0 return dist.get_rank() Th...
Returns: The rank of the current process within the local (per-machine) process group.
10,119
import functools import io import os import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_world_size(): """ Returns: The number of processes in the process group """ if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size() The provid...
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
10,120
import functools import io import os import torch import torch.distributed as dist def is_main_process(): """Return true if the current process is the main one""" return get_rank() == 0 The provided code snippet includes necessary dependencies for implementing the `save_on_master` function. Write a Python func...
Utility function to save only from the main process
10,121
import functools import io import os import torch import torch.distributed as dist def setup_for_distributed(is_master): """ This function disables printing when not in master process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force =...
Initialize distributed training, if appropriate
10,122
import functools import io import os import datetime import torch import torch.distributed as dist def get_world_size(): """ Returns: The number of processes in the process group """ if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size() The provided code snip...
Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that all processes have the averaged results. Returns a dict with the same fields as input_dict, after reduction.
10,123
import functools import io import os import datetime import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_rank(): """ Returns: The rank of the current process within the global process group. """ if not is_dist_avail_and_initialized(): return 0 return dis...
Returns: The rank of the current process within the local (per-machine) process group.
10,124
import functools import io import os import datetime import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_world_size(): """ Returns: The number of processes in the process group """ if not is_dist_avail_and_initialized(): return 1 return dist.get_world_si...
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
10,125
import functools import io import os import datetime import torch import torch.distributed as dist def is_main_process(): """Return true if the current process is the main one""" return get_rank() == 0 The provided code snippet includes necessary dependencies for implementing the `save_on_master` function. Wri...
Utility function to save only from the main process
10,126
import functools import io import os import datetime import torch import torch.distributed as dist def setup_for_distributed(is_master): """ This function disables printing when not in master process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs):...
Initialize distributed training, if appropriate
10,127
import errno import os from .comm import is_main_process def mkdir(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise
null
10,128
import errno import os from .comm import is_main_process def is_main_process(): return get_rank() == 0 def save_config(cfg, path): if is_main_process(): with open(path, 'w') as f: f.write(cfg.dump())
null
10,129
from contextlib import contextmanager def nullcontext(enter_result=None, **kwargs): yield enter_result
null
10,130
from collections import OrderedDict, defaultdict import logging import math import torch from maskrcnn_benchmark.utils.imports import import_file def align_and_update_state_dicts(model_state_dict, loaded_state_dict, reshape_keys=['pos_bias_table'], use_weightmap=False): def strip_prefix_if_present(state_dict, prefix): ...
null
10,131
import numpy as np import torch import torch.nn as nn from collections import OrderedDict def _remove_bn_statics(state_dict): layer_keys = sorted(state_dict.keys()) remove_list = [] for key in layer_keys: if 'running_mean' in key or 'running_var' in key or 'num_batches_tracked' in key: r...
null
10,132
import torch def import_file(module_name, file_path, make_importable=False): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) if make_importable: sys.modules[module_name] = mo...
null
10,133
import torch def import_file(module_name, file_path, make_importable=None): module = imp.load_source(module_name, file_path) return module
null
10,134
import logging import os import sys def setup_logger(name, save_dir, distributed_rank): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # don't log results for the non-master process if distributed_rank > 0: return logger ch = logging.StreamHandler(stream=sys.stdout) ch....
null
10,135
import logging import pickle from collections import OrderedDict import torch from maskrcnn_benchmark.utils.model_serialization import load_state_dict from maskrcnn_benchmark.utils.registry import Registry def _rename_weights_for_resnet(weights, stage_names): original_keys = sorted(weights.keys()) layer_keys = ...
null
10,136
import logging import pickle from collections import OrderedDict import torch from maskrcnn_benchmark.utils.model_serialization import load_state_dict from maskrcnn_benchmark.utils.registry import Registry C2_FORMAT_LOADER = Registry() def load_c2_format(cfg, f): return C2_FORMAT_LOADER[cfg.MODEL.BACKBONE.CONV_BOD...
null
10,137
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import glob import pdb import torch from maskrcnn_benchmark.config import cfg, try_to_find from maskrcnn_benchmark.data import make_data_loader from maskrcnn_benchmark.solver import make_lr_scheduler from maskrcnn_benchmark.solver imp...
null
10,138
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import glob import pdb import torch from maskrcnn_benchmark.config import cfg, try_to_find from maskrcnn_benchmark.data import make_data_loader from maskrcnn_benchmark.solver import make_lr_scheduler from maskrcnn_benchmark.solver imp...
null
10,139
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import glob import pdb import torch from maskrcnn_benchmark.config import cfg, try_to_find from maskrcnn_benchmark.data import make_data_loader from maskrcnn_benchmark.solver import make_lr_scheduler from maskrcnn_benchmark.solver imp...
null
10,140
from __future__ import print_function, absolute_import, division import os, sys sys.path.append( os.path.normpath( os.path.join( os.path.dirname( __file__ ) , '..' , 'helpers' ) ) ) from csHelpers import * from cityscapesscripts.evaluation.instance import * from cityscapesscripts.helpers.csHelpers import * import cv2 f...
null
10,141
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import h5py import json import os import scipy.misc import sys import cityscapesscripts.evaluation.instances2dict_with_polygons as cs import detectron.util...
null
10,142
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import h5py import json import os import scipy.misc import sys import cityscapesscripts.evaluation.instances2dict_with_polygons as cs import detectron.util...
Convert to png and save json with path. This currently only contains the segmentation labels for objects+stuff in cocostuff - if we need to combine with other labels from original COCO that will be a TODO.
10,143
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import h5py import json import os import scipy.misc import sys import cityscapesscripts.evaluation.instances2dict_with_polygons as cs import detectron.util...
null
10,144
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import h5py import json import os import scipy.misc import sys import cityscapesscripts.evaluation.instances2dict_with_polygons as cs import detectron.util...
Convert from cityscapes format to COCO instance seg format - polygons
10,145
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import matplotlib.pyplot as plt import matplotlib.pylab as pylab import requests from io import BytesIO from PIL import Image import numpy as np from maskrcnn_benchmark.engine.predictor_glip import GLIPDemo import yaml import json imp...
null
10,146
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import matplotlib.pyplot as plt import matplotlib.pylab as pylab import requests from io import BytesIO from PIL import Image import numpy as np from maskrcnn_benchmark.engine.predictor_glip import GLIPDemo import yaml import json imp...
Initialize distributed training, if appropriate
10,147
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import matplotlib.pyplot as plt import matplotlib.pylab as pylab import requests from io import BytesIO from PIL import Image import numpy as np from maskrcnn_benchmark.engine.predictor_glip import GLIPDemo import yaml import json imp...
null
10,148
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import torch from maskrcnn_benchmark.config import cfg, try_to_find from maskrcnn_benchmark.data import make_data_loader from maskrcnn_benchmark.solver import make_lr_scheduler from maskrcnn_benchmark.solver import make_optimizer from...
null
10,149
from maskrcnn_benchmark.utils.env import setup_environment import argparse import os import torch from maskrcnn_benchmark.config import cfg, try_to_find from maskrcnn_benchmark.data import make_data_loader from maskrcnn_benchmark.solver import make_lr_scheduler from maskrcnn_benchmark.solver import make_optimizer from...
This function disables printing when not in master process
10,150
import argparse import dataclasses import glob import os import shutil import numpy as np from tqdm import tqdm def disable_torch_init(): """ Disable the redundant torch default initialization to accelerate model creation. """ import torch global torch_linear_init_backup global torch_layer_norm_...
Download weights from huggingface.
10,151
import argparse import dataclasses import glob import os import shutil import numpy as np from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `disable_hf_opt_init` function. Write a Python function `def disable_hf_opt_init()` to solve the following problem: Disable the ...
Disable the redundant default initialization to accelerate model creation.
10,152
import argparse import dataclasses import glob import os import shutil import numpy as np from tqdm import tqdm def download_opt_weights(model_name, path): from huggingface_hub import snapshot_download import torch print(f"Load the pre-trained pytorch weights of {model_name} from huggingface. " ...
null
10,153
import argparse import numpy as np import os import time import torch from flexgen.utils import GB, MB, KB def benchmark_func(func, number, repeat, warmup=3): for i in range(warmup): func() costs = [0] for i in range(repeat): torch.cuda.synchronize() tic = time.time() for i i...
null