id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
11,062
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging The provided ...
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...
11,063
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging The provided ...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
11,064
import argparse import json import torch from PIL import Image import requests import timm from huggingface_hub import hf_hub_download from transformers import AutoFeatureExtractor, SwinConfig, SwinForImageClassification def get_swin_config(swin_name): def convert_state_dict(orig_state_dict, model): def convert_swin_c...
null
11,065
import collections.abc import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_utils import PreTrainedModel...
Partitions the given input into windows.
11,066
import collections.abc import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_utils import PreTrainedModel...
Merges windows to produce higher resolution features.
11,067
import collections.abc import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_utils import PreTrainedModel...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discu...
11,068
import collections.abc import math from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACT2FN from ...modeling_tf_utils import ( TFPreTrainedModel, TFSequenceClassific...
Partitions the given input into windows.
11,069
import collections.abc import math from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACT2FN from ...modeling_tf_utils import ( TFPreTrainedModel, TFSequenceClassific...
Merges windows to produce higher resolution features.
11,070
import collections.abc import math from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACT2FN from ...modeling_tf_utils import ( TFPreTrainedModel, TFSequenceClassific...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
11,071
import collections.abc import math from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACT2FN from ...modeling_tf_utils import ( TFPreTrainedModel, TFSequenceClassific...
From tensorflow addons https://github.com/tensorflow/addons/blob/8cec33fcaaf1cf90aec7bdd55a0fcdbb251ce5c2/tensorflow_addons/utils/keras_utils.py#L71
11,072
import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging def convert_rembert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path): # Initialise PyTorch model config = RemBertConfig.from_json...
null
11,073
import math import os from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseMod...
Load tf checkpoints in a pytorch model.
11,074
import warnings from dataclasses import dataclass from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...modeling_utils import PreTrainedModel from ...utils import ( ModelOutput, add_code_sample_docstrings, ...
Load tf checkpoints in a pytorch model
11,075
import glob import os import pickle import re from collections import Counter, OrderedDict from typing import List, Optional, Tuple import numpy as np from ...tokenization_utils import PreTrainedTokenizer from ...utils import ( cached_file, is_sacremoses_available, is_torch_available, logging, requi...
Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and dots with ' @.@ '. Args: text_array: An already tokenized text as list. Returns: A list of strings with tokenized numbers. Example: ```python >>> tokenize_numbers(["$", "5,000", "1.73", "m"]) ["$", "5", "@,...
11,076
import glob import os import pickle import re from collections import Counter, OrderedDict from typing import List, Optional, Tuple import numpy as np from ...tokenization_utils import PreTrainedTokenizer from ...utils import ( cached_file, is_sacremoses_available, is_torch_available, logging, requi...
Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'. Args: text: A string where the number should be detokenized. Returns: A detokenized string. Example: ```python >>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m") "$ 5,000 1.73 m" ```
11,077
import glob import os import pickle import re from collections import Counter, OrderedDict from typing import List, Optional, Tuple import numpy as np from ...tokenization_utils import PreTrainedTokenizer from ...utils import ( cached_file, is_sacremoses_available, is_torch_available, logging, requi...
null
11,078
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, V...
null
11,079
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN, gelu from ...modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseM...
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor
11,080
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassific...
Copy/paste/tweak roberta's weights to our BERT structure.
11,081
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def count_parameters(state_dict): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items()) d...
Copy/paste/tweak model's weights to transformers design.
11,082
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def count_parameters(state_dict): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum(...
Copy/paste/tweak model's weights to transformers design.
11,083
import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `load_vocab_and_emoji` fun...
Loads a vocabulary file and emoji file into a dictionary.
11,084
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...modeling_outp...
null
11,085
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...modeling_outp...
add bias to x, apply dropout and residual connection Args: x (Tensor): main path of output bias (Tensor): None or attn_bias of the last attention layer residual (Optional[Tensor]): residual value prob (float): dropout probability training (bool): whether in training mode or not Returns: Tensor: dropout(x + bias) + resi...
11,086
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import torch import timm from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitFeatureExtractor, LevitForImageClassificationWithTeacher from transformers.utils import l...
null
11,087
import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, mobilebert_config_file, pytorch_dump_path): # Initialise PyTorch model config = MobileB...
null
11,088
import math import os import warnings from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutp...
Load tf checkpoints in a pytorch model.
11,091
import math from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import gelu from ...modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWith...
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's *utils.make_positions*. Args: input_ids (`torch.LongTensor`): Indices of input sequence tokens in the vocabulary. Returns: torch.Tensor
11,092
import decimal import numpy as np import torch from torch import nn from torch.autograd import Function from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `get_percentile_min_max` function. Write a Python function `def get_percentile_min_max(input, lower_percent...
Calculate the percentile max and min values in a given tensor Args: input (`torch.Tensor`): The target tensor to calculate percentile max and min. lower_percentile (`float`): If 0.1, means we return the value of the smallest 0.1% value in the tensor as percentile min. upper_percentile (`float`): If 99.9, means we retur...
11,093
import decimal import numpy as np import torch from torch import nn from torch.autograd import Function from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `linear_quantize` function. Write a Python function `def linear_quantize(input, scale, zero_point, inplace=...
Quantize single-precision input tensor to integers with the given scaling factor and zeropoint. Args: input (`torch.Tensor`): Single-precision input tensor to be quantized. scale (`torch.Tensor`): Scaling factor for quantization. zero_pint (`torch.Tensor`): Shift for quantization. inplace (`bool`, *optional*, defaults ...
11,094
import decimal import numpy as np import torch from torch import nn from torch.autograd import Function from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `symmetric_linear_quantization_params` function. Write a Python function `def symmetric_linear_quantization...
Compute the scaling factor with the given quantization range for symmetric quantization. Args: saturation_min (`torch.Tensor`): Lower bound for quantization range. saturation_max (`torch.Tensor`): Upper bound for quantization range. per_channel (`bool`, *optional*, defaults to `False`): Whether to or not use channel-wi...
11,095
import decimal import numpy as np import torch from torch import nn from torch.autograd import Function from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `batch_frexp` function. Write a Python function `def batch_frexp(inputs, max_bit=31)` to solve the followin...
Decompose the scaling factor into mantissa and twos exponent. Args: scaling_factor (`torch.Tensor`): Target scaling factor to decompose. Returns: ``Tuple(torch.Tensor, torch.Tensor)`: mantisa and exponent
11,096
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN, gelu from ...modeling_utils import PreTrainedModel from ...pytorch_...
Computes global attention mask by putting attention on all tokens before `sep_token_id` if `before_sep_token is True` else after `sep_token_id`.
11,097
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN, gelu from ...modeling_utils import PreTrainedModel from ...pytorch_...
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor
11,100
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class LightningModel(pl.LightningModule): def __init__(self, model): def forward(self): def convert_longformer_qa_checkpoint_to_pytorch( longformer_mod...
null
11,101
import warnings from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_utils import ( TFMaskedLanguageModelingLoss, TFModelInputType, TFMultipleChoiceLoss, TFPreTrainedMode...
Computes global attention mask by putting attention on all tokens before `sep_token_id` if `before_sep_token is True` else after `sep_token_id`.
11,102
import argparse import json from pathlib import Path import torch from PIL import Image import requests from huggingface_hub import cached_download, hf_hub_url from transformers import DPTConfig, DPTFeatureExtractor, DPTForDepthEstimation, DPTForSemanticSegmentation from transformers.utils import logging def get_dpt_co...
Copy/paste/tweak model's weights to our DPT structure.
11,103
import argparse import json from pathlib import Path import torch from PIL import Image import requests from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, ConvNextFeatureExtractor, ConvNextForImageClassification from transformers.utils import logging def get_convnext_config(checkpoint_...
Copy/paste/tweak model's weights to our ConvNext structure.
11,104
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discu...
11,105
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from ...modeling_utils import PreTrainedModel from ...utils im...
null
11,106
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from ...modeling_utils import PreTrainedModel from ...utils im...
null
11,107
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np import regex as re from ...utils import is_tf_available, is_torch_available, logging from ...tokenization_utils import AddedToken, PreTrainedTokenizer The provided code snippet includ...
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...
11,108
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np import regex as re from ...utils import is_tf_available, is_torch_available, logging from ...tokenization_utils import AddedToken, PreTrainedTokenizer The provided code snippet includ...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
11,109
import copy import math import random from typing import Any, Dict, List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, ...
Shift input ids one token to the right, and wrap the last non pad token (the <LID> token) Note that MBart does not have a single `decoder_start_token_id` in contrast to other Bart-like models.
11,110
import copy import math import random from typing import Any, Dict, List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, ...
Make causal mask used for bi-directional self-attention.
11,111
import copy import math import random from typing import Any, Dict, List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, ...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,112
import argparse import torch from torch import nn from transformers import PLBartConfig, PLBartForConditionalGeneration, PLBartForSequenceClassification def remove_ignore_keys_(state_dict): ignore_keys = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder....
null
11,113
import random from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) from ...
Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero, meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`. Args: input_tensor (`torch.FloatTensor`): Input tensor, of which the average must be computed. weights (`torch.FloatTensor`, *optional*): Weights...
11,114
import random from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) from ...
Make causal mask used for bi-directional self-attention.
11,115
import random from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) from ...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,116
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
null
11,117
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
null
11,118
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
null
11,119
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
Expands attention_mask from `[batch_size, seq_len]` to `[batch_size, 1, target_seq_len, source_seq_len]`.
11,120
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
null
11,121
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
null
11,122
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class).
11,123
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs (`torch.FloatTensor` of arbitrary shape): The predictions for each example. targets (`torch.FloatTensor` with the same shape as `inputs`) A tensor storing the binary classification label for each element in the `inputs` (0 for th...
11,124
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format. Returns: `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
11,125
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
Converts a PyTorch tensor of bounding boxes of center format (center_x, center_y, width, height) to corners format (x_0, y_0, x_1, y_1).
11,126
import copy import math import warnings from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ...activations import ACT2FN...
null
11,127
import argparse import json from pathlib import Path import torch from PIL import Image import requests from huggingface_hub import cached_download, hf_hub_url from transformers import DeformableDetrConfig, DeformableDetrFeatureExtractor, DeformableDetrForObjectDetection from transformers.utils import logging logger = ...
Copy/paste/tweak model's weights to our Deformable DETR structure.
11,128
import os def load_cuda_kernels(): from torch.utils.cpp_extension import load root = os.path.join(os.path.dirname(os.path.realpath(__file__)), "custom_kernel") src_files = [ os.path.join(root, filename) for filename in [ "vision.cpp", os.path.join("cpu", "ms_deform_...
null
11,129
import pathlib import warnings from typing import Dict, List, Optional, Tuple, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...image_utils import ImageFeatureExtractionMixin, is_torch_tensor from ...utils import TensorType, is_torch_ava...
Converts a PyTorch tensor of bounding boxes of center format (center_x, center_y, width, height) to corners format (x_0, y_0, x_1, y_1).
11,130
import pathlib import warnings from typing import Dict, List, Optional, Tuple, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...image_utils import ImageFeatureExtractionMixin, is_torch_tensor from ...utils import TensorType, is_torch_ava...
Converts a NumPy array of bounding boxes of shape (number of bounding boxes, 4) of corners format (x_0, y_0, x_1, y_1) to center format (center_x, center_y, width, height).
11,131
import pathlib import warnings from typing import Dict, List, Optional, Tuple, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...image_utils import ImageFeatureExtractionMixin, is_torch_tensor from ...utils import TensorType, is_torch_ava...
Compute the bounding boxes around the provided panoptic segmentation masks. The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensor, with the boxes in corner (xyxy) format.
11,132
import pathlib import warnings from typing import Dict, List, Optional, Tuple, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...image_utils import ImageFeatureExtractionMixin, is_torch_tensor from ...utils import TensorType, is_torch_ava...
null
11,133
import pathlib import warnings from typing import Dict, List, Optional, Tuple, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...image_utils import ImageFeatureExtractionMixin, is_torch_tensor from ...utils import TensorType, is_torch_ava...
null
11,134
import argparse import json from pathlib import Path import torch from PIL import Image import requests import timm from huggingface_hub import hf_hub_download from transformers import AutoFeatureExtractor, Swinv2Config, Swinv2ForImageClassification def get_swinv2_config(swinv2_name): config = Swinv2Config() na...
null
11,135
import collections.abc import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...model...
Partitions the given input into windows.
11,136
import collections.abc import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...model...
Merges windows to produce higher resolution features.
11,137
import collections.abc import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...model...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discu...
11,138
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNo...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discu...
11,139
import argparse import json from collections import OrderedDict from pathlib import Path import torch from PIL import Image import requests from huggingface_hub import hf_hub_download from transformers import PoolFormerConfig, PoolFormerFeatureExtractor, PoolFormerForImageClassification from transformers.utils import l...
Copy/paste/tweak model's weights to our PoolFormer structure.
11,140
import importlib import re import warnings from collections import OrderedDict from typing import List, Union from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...utils import CONFIG_NAME, logging CONFIG_MAPPING_NAMES = OrderedDict( [ ...
Converts a config class name to the corresponding model type
11,141
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CO...
null
11,142
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CO...
Loads the tokenizer configuration from a pretrained model tokenizer configuration. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-lev...
11,143
import importlib from collections import OrderedDict from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...utils import copy_func, logging from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings def...
null
11,144
import importlib from collections import OrderedDict from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...utils import copy_func, logging from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings CLAS...
null
11,145
import importlib from collections import OrderedDict from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...utils import copy_func, logging from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings def...
null
11,146
import importlib from collections import OrderedDict from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...utils import copy_func, logging from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings def...
null
11,147
import importlib import json import os from collections import OrderedDict from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...tokenization_utils import PreTrainedTokenizer from ...to...
null
11,148
import importlib import json import os from collections import OrderedDict from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...tokenization_utils import PreTrainedTokenizer from ...to...
Loads the tokenizer configuration from a pretrained model tokenizer configuration. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-lev...
11,149
import importlib import inspect import json from collections import OrderedDict from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils import TOKENIZER_CONFIG_FILE fro...
null
11,150
import numpy as np from ...utils import logging from ..t5.modeling_flax_t5 import FlaxT5EncoderModel, FlaxT5ForConditionalGeneration, FlaxT5Model from .configuration_mt5 import MT5Config The provided code snippet includes necessary dependencies for implementing the `shift_tokens_right` function. Write a Python functio...
Shift input ids one token to the right.
11,151
import collections import copy import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging The provided code snippet includes necessary depen...
Loads a vocabulary file into a dictionary.
11,152
import collections import copy import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging The provided code snippet includes necessary depen...
Runs basic whitespace cleaning and splitting on a piece of text.
11,153
import argparse import json from pathlib import Path import torch from PIL import Image import requests from huggingface_hub import hf_hub_download from transformers import YolosConfig, YolosFeatureExtractor, YolosForObjectDetection from transformers.utils import logging def read_in_q_k_v(state_dict: dict, config: Yol...
null
11,154
import argparse import json from pathlib import Path import torch from PIL import Image import requests from huggingface_hub import hf_hub_download from transformers import YolosConfig, YolosFeatureExtractor, YolosForObjectDetection from transformers.utils import logging def get_yolos_config(yolos_name: str) -> YolosCo...
Copy/paste/tweak model's weights to our YOLOS structure.
11,160
import collections.abc import math from dataclasses import dataclass from typing import Dict, List, Optional, Set, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling from ...mo...
Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class).
11,161
import collections.abc import math from dataclasses import dataclass from typing import Dict, List, Optional, Set, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling from ...mo...
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs (`torch.FloatTensor` of arbitrary shape): The predictions for each example. targets (`torch.FloatTensor` with the same shape as `inputs`) A tensor storing the binary classification label for each element in the `inputs` (0 for th...
11,162
import collections.abc import math from dataclasses import dataclass from typing import Dict, List, Optional, Set, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling from ...mo...
Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format. Returns: `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
11,163
import collections.abc import math from dataclasses import dataclass from typing import Dict, List, Optional, Set, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling from ...mo...
null
11,164
import copy import math import random from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOu...
Shift input ids one token to the right.
11,165
import copy import math import random from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOu...
Make causal mask used for bi-directional self-attention.
11,166
import copy import math import random from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOu...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,169
import argparse import json import sys from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import torch import torch.nn as nn from torch import Tensor from huggingface_hub import cached_download, hf_hub_download from transformers import AutoFeatureExtr...
null
11,170
import math from collections import OrderedDict from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutputWithNoAttenti...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discu...
11,171
import json import os import random from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...file_utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available from ...tokenization_utils import AddedToken, PreTrainedTokenizer from...
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...
11,172
import json import os import random from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...file_utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available from ...tokenization_utils import AddedToken, PreTrainedTokenizer from...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).