id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
18,735
from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import math import copy import sys from io import open import itertools import numpy as np import tensorflow as tf from .configuration_distilbert import DistilBertConfig from .modeling_tf_utils import TFPreTrai...
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: `x` with the GELU activation applied.
18,736
from __future__ import absolute_import, division, print_function import argparse import os import sys from io import open import torch import transformers.tokenization_transfo_xl as data_utils from transformers import CONFIG_NAME, WEIGHTS_NAME from transformers import (TransfoXLConfig, TransfoXLLMHeadModel, ...
null
18,737
from __future__ import absolute_import, division, print_function import argparse import logging import numpy as np import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from transformers import (BertConfig, BertEncoder, ...
Copy/paste/tweak roberta's weights to our BERT structure.
18,738
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import math import os import sys from io import open import torch import torch.nn as nn from torch.nn import CrossEntropyLoss from torch.nn.parameter import Parameter from .modeling_utils imp...
Load tf pre-trained weights in a pytorch model (from NumPy arrays here)
18,739
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import math import os import sys from io import open import torch import torch.nn as nn from torch.nn import CrossEntropyLoss from torch.nn.parameter import Parameter from .modeling_utils imp...
null
18,740
from __future__ import absolute_import, division, print_function, unicode_literals import collections import json import logging import math import os import sys from io import open import torch import torch.nn as nn from torch.nn import CrossEntropyLoss from torch.nn.parameter import Parameter from .modeling_utils imp...
null
18,741
from __future__ import absolute_import, division, print_function import argparse import json from io import open import torch import numpy from transformers import CONFIG_NAME, WEIGHTS_NAME from transformers.tokenization_xlm import VOCAB_FILES_NAMES import logging VOCAB_FILES_NAMES = { 'vocab_file': 'vocab.json', ...
null
18,742
from __future__ import (absolute_import, division, print_function, unicode_literals) import logging import os import re import numpy logger = logging.getLogger(__name__) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): """ Load pytorch...
Load pytorch checkpoints in a TF 2.0 model
18,743
from __future__ import (absolute_import, division, print_function, unicode_literals) import logging import os import re import numpy def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): """ Load pytorch state_dict in a TF 2.0 model. ""...
Load pytorch checkpoints in a TF 2.0 model
18,744
from __future__ import (absolute_import, division, print_function, unicode_literals) import logging import os import re import numpy logger = logging.getLogger(__name__) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): """ Load TF 2.0 model in a pytorch mode...
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
18,745
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os import regex as re from io import open from .tokenization_gpt2 import GPT2Tokenizer def lru_cache(): return lambda func: func
null
18,746
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import argparse import tensorflow as tf from transformers import is_torch_available, cached_path from transformers import (load_pytorch_checkpoint_in_tf2_model, BertConfig, TFBertForPreTraining, TF...
null
18,747
from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import math import os import sys from io import open import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from .modeling_utils import PreTrainedModel, prune_linear_layer from .config...
Load tf checkpoints in a pytorch model.
18,748
from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import math import os import sys from io import open import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from .modeling_utils import PreTrainedModel, prune_linear_layer from .config...
Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see https://arxiv.org/abs/1606.0...
18,749
from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import math import os import sys from io import open import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from .modeling_utils import PreTrainedModel, prune_linear_layer from .config...
Implementation of the gelu activation function currently in Google Bert repo (identical to OpenAI GPT). Also see https://arxiv.org/abs/1606.08415
18,750
from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import math import os import sys from io import open import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from .modeling_utils import PreTrainedModel, prune_linear_layer from .config...
null
18,751
from __future__ import (absolute_import, division, print_function, unicode_literals) import copy import json import logging import os from io import open import six import torch from torch import nn from torch.nn import CrossEntropyLoss from torch.nn import functional as F from .configuration_ut...
Prune a Conv1D or nn.Linear layer (a model parameters) to keep only entries in index. Return the pruned layer as a new layer with requires_grad=True. Used to remove heads.
18,752
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import re import sys import unicodedata from io import open import sacremoses as sm from .tokenization_utils import PreTrainedTokenizer from .tokenization_bert import BasicTo...
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings)
18,753
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import re import sys import unicodedata from io import open import sacremoses as sm from .tokenization_utils import PreTrainedTokenizer from .tokenization_bert import BasicTo...
Lowercase and strips accents from a piece of text based on https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
18,754
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import re import sys import unicodedata from io import open import sacremoses as sm from .tokenization_utils import PreTrainedTokenizer from .tokenization_bert import BasicTo...
Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
18,755
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import re import sys import unicodedata from io import open import sacremoses as sm from .tokenization_utils import PreTrainedTokenizer from .tokenization_bert import BasicTo...
Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
18,756
from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import re import sys import unicodedata from io import open import sacremoses as sm from .tokenization_utils import PreTrainedTokenizer from .tokenization_bert import BasicTo...
Sennrich's WMT16 scripts for Romanian preprocessing, used by model `xlm-mlm-enro-1024`
18,757
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os import regex as re from io import open from .tokenization_utils import PreTrainedTokenizer def lru_cache(): return lambda func: func
null
18,758
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os import regex as re from io import open from .tokenization_utils import PreTrainedTokenizer The provided code snippet includes necessary dependencies for implement...
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. 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...
18,759
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os import regex as re from io import open from .tokenization_utils import PreTrainedTokenizer The provided code snippet includes necessary dependencies for implement...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
18,760
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging import os import unicodedata from io import open from .tokenization_utils import PreTrainedTokenizer The provided code snippet includes necessary dependencies for implementing the `load_vocab` function....
Loads a vocabulary file into a dictionary.
18,761
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging import os import unicodedata from io import open from .tokenization_utils import PreTrainedTokenizer The provided code snippet includes necessary dependencies for implementing the `_is_whitespace` funct...
Checks whether `chars` is a whitespace character.
18,762
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging import os import unicodedata from io import open from .tokenization_utils import PreTrainedTokenizer The provided code snippet includes necessary dependencies for implementing the `_is_control` function...
Checks whether `chars` is a control character.
18,763
from __future__ import absolute_import, division, print_function, unicode_literals import collections import logging import os import unicodedata from io import open from .tokenization_utils import PreTrainedTokenizer The provided code snippet includes necessary dependencies for implementing the `_is_punctuation` func...
Checks whether `chars` is a punctuation character.
18,764
def _get_ngrams(n, text): """Calcualtes n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ...
Calculates word n-grams for multiple sentences.
18,765
import glob import json import os import random import re import subprocess from collections import Counter from os.path import join as pjoin import torch from others.logging import logger from others.transformers import BertTokenizer from others.utils import clean from prepro.utils import _get_word_ngrams import argpa...
null
18,766
import os import numpy as np import torch from tensorboardX import SummaryWriter import distributed from models.reporter_ext import ReportMgr, Statistics from others.logging import logger from others.utils import test_rouge, rouge_results_to_str def _tally_parameters(model): n_params = sum([p.nelement() for p in mo...
Simplify `Trainer` creation based on user `opt`s* Args: opt (:obj:`Namespace`): user options (usually from argument parsing) model (:obj:`onmt.models.NMTModel`): the model to train fields (dict): dict of fields optim (:obj:`onmt.utils.Optimizer`): optimizer used during training data_type (str): string describing the ty...
18,767
import os import numpy as np import torch from tensorboardX import SummaryWriter import h5py import distributed from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset) from models.reporter import ReportMgr, Statistics from others.logging import l...
null
18,768
import os import numpy as np import torch from tensorboardX import SummaryWriter import h5py import distributed from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset, Dataset) from models.reporter import ReportMgr, Statistics from others.logging import l...
null
18,769
import bisect import os import gc import glob import random import torch from others.logging import logger def abs_batch_size_fn(new, count): src, tgt = new[0], new[1] global max_n_sents, max_n_tokens, max_size if count == 1: max_size = 0 max_n_sents=0 max_n_tokens=0 max_n_sents...
null
18,770
import bisect import os import gc import glob import random import torch from others.logging import logger def ext_batch_size_fn(new, count): if (len(new) == 4): pass src, labels = new[0], new[4] global max_n_sents, max_n_tokens, max_size if count == 1: max_size = 0 max_n_sents ...
null
18,771
from __future__ import print_function from datetime import datetime import time import math import sys from distributed import all_gather_list from others.logging import logger class ReportMgr(ReportMgrBase): def __init__(self, report_every, start_time=-1., tensorboard_writer=None): """ A report man...
null
18,772
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from models.reporter import Statistics def filter_shard_state(state, shard_size=None): """ ? """ for k, v in state.items(): if shard_size is None: yield k, v if v is not None: ...
Args: state: A dictionary which corresponds to the output of *LossCompute._make_shard_state(). The values for those keys are Tensor-like or None. shard_size: The maximum size of the shards yielded by the model. eval_only: If True, only yield the state, nothing else. Otherwise, yield shards. Yields: Each yielded shard i...
18,773
from __future__ import print_function import sys import time from datetime import datetime from others.logging import logger class ReportMgr(ReportMgrBase): def __init__(self, report_every, start_time=-1., tensorboard_writer=None): """ A report manager that writes statistics on standard output as we...
null
18,774
import torch import torch.optim as optim from torch.nn.utils import clip_grad_norm_ def use_gpu(opt): """ Creates a boolean if gpu used """ return (hasattr(opt, 'gpu_ranks') and len(opt.gpu_ranks) > 0) or \ (hasattr(opt, 'gpu') and opt.gpu > -1) class Optimizer(object): """ Controller...
Build optimizer
18,775
from __future__ import print_function import codecs import torch.nn as nn import torch.nn.functional as F import subprocess import os import math import json import torch from tensorboardX import SummaryWriter from others.utils import rouge_results_to_str, test_rouge, tile from translate.beam import GNMTGlobalScorer d...
null
18,776
import copy import torch import torch.nn as nn from others.transformers import BertModel, BertConfig from others.transformers import RobertaModel, RobertaConfig from torch.nn.init import xavier_uniform_ from models.decoder import TransformerDecoder from models.encoder import Classifier, ExtTransformerEncoder from model...
null
18,777
import math import torch import torch.nn as nn import torch import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `aeq` function. Write a Python function `def aeq(*args)` to solve the following problem: Assert all arguments have the same va...
Assert all arguments have the same value
18,778
import math import torch import torch.nn as nn import torch import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `sequence_mask` function. Write a Python function `def sequence_mask(lengths, max_len=None)` to solve the following problem: C...
Creates a boolean mask from sequence lengths.
18,779
import math import torch import torch.nn as nn import torch import torch.nn as nn import torch.nn.functional as F def gelu(x): return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
null
18,780
import torch import torch.nn as nn import numpy as np from models.encoder import PositionalEncoding from models.neural import MultiHeadedAttention, PositionwiseFeedForward, DecoderState class LearnedPositionalEmbedding(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. P...
null
18,781
from __future__ import absolute_import, division, print_function import csv import os import textwrap import numpy as np import six import datasets def _mnli_split_generator(name, data_dir, split, matched): return datasets.SplitGenerator( name=name, gen_kwargs={ "data_file": os.path.joi...
null
18,782
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import numpy as np from datasets import load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataColla...
null
18,783
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import f1_score, matthews_corrcoef import datasets def simple_accuracy(preds, labels): return (preds == labels).mean() def acc_and_f1(preds, labels): acc = simple_accuracy(preds, labels) f1 = f1_score(y_true=labels, y_pred=preds) return {...
null
18,784
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import f1_score, matthews_corrcoef import datasets def pearson_and_spearman(preds, labels): pearson_corr = pearsonr(preds, labels)[0] spearman_corr = spearmanr(preds, labels)[0] return { "pearson": pearson_corr, "spearmanr": s...
null
18,785
import argparse import os import ruamel_yaml as yaml import language_evaluation from torch.autograd import Variable import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader...
null
18,786
import argparse import os import ruamel_yaml as yaml import language_evaluation from torch.autograd import Variable import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader...
null
18,787
import numpy as np import io import os import time from collections import defaultdict, deque import datetime import torch import torch.distributed as dist def compute_acc(logits, label, reduction='mean'): ret = (torch.argmax(logits, dim=1) == label).float() if reduction == 'none': return ret.detach() ...
null
18,788
import numpy as np import io import os import time from collections import defaultdict, deque import datetime import torch import torch.distributed as dist def compute_n_params(model, return_str=True): tot = 0 for p in model.parameters(): w = 1 for x in p.shape: w *= x tot +...
null
18,789
import numpy as np import io import os import time from collections import defaultdict, deque import datetime import torch import torch.distributed as dist def is_main_process(): def save_on_master(*args, **kwargs): if is_main_process(): torch.save(*args, **kwargs)
null
18,790
import numpy as np import io import os import time from collections import defaultdict, deque 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_...
null
18,791
import argparse import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path from models.tokenization_bert import BertTokenizer import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.d...
null
18,792
import argparse import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path from models.tokenization_bert import BertTokenizer import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.d...
null
18,793
import cv2 import random, math import numpy as np from collections import Iterable import torch.nn.functional as F from torch.autograd import Variable def letterbox(img, mask, height, color=(123.7, 116.3, 103.5)): # resize a rectangular image to a padded square shape = img.shape[:2] # shape = [height, width] ...
null
18,794
import cv2 import random, math import numpy as np from collections import Iterable import torch.nn.functional as F from torch.autograd import Variable def wrap_points(targets, M, height, a): # n = targets.shape[0] # points = targets[:, 1:5].copy() points = targets.copy() # area0 = (points[:, 2] - points...
null
18,795
import torch import numpy as np import torch.nn.functional as F from utils.box_utils import bbox_iou, xywh2xyxy, xyxy2xywh, generalized_box_iou from utils.misc import get_world_size from icecream import ic from matplotlib import pyplot as plt def xywh2xyxy(x): x_c, y_c, w, h = x.unbind(-1) b = [(x_c - 0.5 * w)...
Compute the losses related to the bounding boxes, including the L1 regression loss and the GIoU loss
18,796
import torch from torchvision.ops.boxes import box_area def xyxy2xywh(x): x0, y0, x1, y1 = x.unbind(-1) b = [(x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0), (y1 - y0)] return torch.stack(b, dim=-1)
null
18,797
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision def get_world_size(): if not is_dist_avail_and_initialized(): return 1 ...
Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank
18,798
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision def get_world_size(): if not is_dist_avail_and_initialized(): return 1 ...
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.
18,799
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision import math def get_sha(): cwd = os.path.dirname(os.path.abspath(__file__)) ...
null
18,800
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision def _max_by_axis(the_list): # type: (List[List[int]]) -> List[int] maxes = ...
null
18,801
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision def is_main_process(): import math def save_on_master(*args, **kwargs): if is_...
null
18,802
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision def setup_for_distributed(is_master): """ This function disables printing w...
null
18,803
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision import math The provided code snippet includes necessary dependencies for implemen...
Equivalent to nn.functional.interpolate, but with support for empty batch sizes. This will eventually be supported natively by PyTorch, and this class can go away.
18,804
import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List import torch import torch.distributed as dist from torch import Tensor import torchvision import math def get_warmup_cosin_scheduler(optimizer,warmup_ep,all_ep,delta_min,de...
null
18,805
import argparse import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.distributed as dist import utils as public_utils fro...
null
18,806
import argparse import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.distributed as dist import utils as public_utils fro...
null
18,807
import argparse import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.distributed as dist import utils as public_utils fro...
null
18,808
import argparse import os import ruamel_yaml as yaml import language_evaluation import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torch.backends.cudnn as cudn...
null
18,809
import argparse import os import ruamel_yaml as yaml import language_evaluation import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torch.backends.cudnn as cudn...
null
18,810
import argparse import sys import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torch.backends.cudnn as cudnn import torch.d...
null
18,811
import argparse import sys import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torch.backends.cudnn as cudnn import torch.d...
null
18,812
import argparse import sys import os import ruamel_yaml as yaml import numpy as np import random import time import datetime import json from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torch.backends.cudnn as cudnn import torch.d...
null
18,813
from .cosine_lr import CosineLRScheduler from .tanh_lr import TanhLRScheduler from .step_lr import StepLRScheduler from .plateau_lr import PlateauLRScheduler class CosineLRScheduler(Scheduler): def __init__(self, optimizer: torch.optim.Optimizer, t_initial: int, ...
null
18,814
import json import numpy as np import time import logging import os import random from torch.utils.data import Dataset from PIL import Image from PIL import ImageFile import oss2 from io import BytesIO from dataset.utils import pre_caption def decode_int32(ann): ann = str(ann) server = str(int(ann[-1]) + 1) ...
null
18,815
import re from vqaTools.vqaEval import VQAEval import json import os import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import utils from tqdm import tqdm def pre_question(question,max_ques_words): question = re.sub( r"([,.'!?\"()*#:;~])", '', q...
null
18,816
import re from vqaTools.vqaEval import VQAEval import json import os import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import utils from tqdm import tqdm def pre_caption(caption,max_words): caption = re.sub( r"([,.'!?\"()*#:;~])", '', caption.l...
null
18,817
import re from vqaTools.vqaEval import VQAEval import json import os import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import utils from tqdm import tqdm class VQAEval: def __init__(self, vqa, vqaRes, n=2): self.n = n self.accuracy = {} self.evalQA =...
null
18,818
import re from vqaTools.vqaEval import VQAEval import json import os import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import utils from tqdm import tqdm import utils def collect_result(result, result_dir, filename, is_json=True, is_list=True): if is_json: re...
null
18,819
import re from vqaTools.vqaEval import VQAEval import json import os import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import utils from tqdm import tqdm def computeIoU(box1, box2): # each box is of [x1, y1, w, h] inter_x1 = max(box1[0], box2[0]) inter_y1 = max...
null
18,820
import cv2 import numpy as np def identity_func(img): return img
null
18,821
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `autocontrast_func` function. Write a Python function `def autocontrast_func(img, cutoff=0)` to solve the following problem: same output as PIL.ImageOps.autocontrast Here is the function: def autocontrast_fun...
same output as PIL.ImageOps.autocontrast
18,822
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `equalize_func` function. Write a Python function `def equalize_func(img)` to solve the following problem: same output as PIL.ImageOps.equalize PIL's implementation is different from cv2.equalize Here is the f...
same output as PIL.ImageOps.equalize PIL's implementation is different from cv2.equalize
18,823
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `rotate_func` function. Write a Python function `def rotate_func(img, degree, fill=(0, 0, 0))` to solve the following problem: like PIL, rotate by degree, not radians Here is the function: def rotate_func(img...
like PIL, rotate by degree, not radians
18,824
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `solarize_func` function. Write a Python function `def solarize_func(img, thresh=128)` to solve the following problem: same output as PIL.ImageOps.posterize Here is the function: def solarize_func(img, thresh...
same output as PIL.ImageOps.posterize
18,825
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `color_func` function. Write a Python function `def color_func(img, factor)` to solve the following problem: same output as PIL.ImageEnhance.Color Here is the function: def color_func(img, factor): ''' ...
same output as PIL.ImageEnhance.Color
18,826
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `contrast_func` function. Write a Python function `def contrast_func(img, factor)` to solve the following problem: same output as PIL.ImageEnhance.Contrast Here is the function: def contrast_func(img, factor)...
same output as PIL.ImageEnhance.Contrast
18,827
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `brightness_func` function. Write a Python function `def brightness_func(img, factor)` to solve the following problem: same output as PIL.ImageEnhance.Contrast Here is the function: def brightness_func(img, f...
same output as PIL.ImageEnhance.Contrast
18,828
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `sharpness_func` function. Write a Python function `def sharpness_func(img, factor)` to solve the following problem: The differences the this result and PIL are all on the 4 boundaries, the center areas are sam...
The differences the this result and PIL are all on the 4 boundaries, the center areas are same
18,829
import cv2 import numpy as np def shear_x_func(img, factor, fill=(0, 0, 0)): H, W = img.shape[0], img.shape[1] M = np.float32([[1, factor, 0], [0, 1, 0]]) out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) return out
null
18,830
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `translate_x_func` function. Write a Python function `def translate_x_func(img, offset, fill=(0, 0, 0))` to solve the following problem: same output as PIL.Image.transform Here is the function: def translate_...
same output as PIL.Image.transform
18,831
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `translate_y_func` function. Write a Python function `def translate_y_func(img, offset, fill=(0, 0, 0))` to solve the following problem: same output as PIL.Image.transform Here is the function: def translate_...
same output as PIL.Image.transform
18,832
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `posterize_func` function. Write a Python function `def posterize_func(img, bits)` to solve the following problem: same output as PIL.ImageOps.posterize Here is the function: def posterize_func(img, bits): ...
same output as PIL.ImageOps.posterize
18,833
import cv2 import numpy as np def shear_y_func(img, factor, fill=(0, 0, 0)): H, W = img.shape[0], img.shape[1] M = np.float32([[1, 0, 0], [factor, 1, 0]]) out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8) return out
null
18,834
import cv2 import numpy as np def cutout_func(img, pad_size, replace=(0, 0, 0)): replace = np.array(replace, dtype=np.uint8) H, W = img.shape[0], img.shape[1] rh, rw = np.random.random(2) pad_size = pad_size // 2 ch, cw = int(rh * H), int(rw * W) x1, x2 = max(ch - pad_size, 0), min(ch + pad_siz...
null