id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
10,958
import math import sys from dataclasses import dataclass from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.nn import LayerNorm from ...deepspeed import is_deepspeed_available from ...modeling_outputs i...
null
10,959
import math import sys from dataclasses import dataclass from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.nn import LayerNorm from ...deepspeed import is_deepspeed_available from ...modeling_outputs i...
null
10,960
import math import sys from dataclasses import dataclass from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.nn import LayerNorm from ...deepspeed import is_deepspeed_available from ...modeling_outputs i...
Softmax, but without automatic casting to fp32 when the input is of type bfloat16
10,961
import math import sys from dataclasses import dataclass from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.nn import LayerNorm from ...deepspeed import is_deepspeed_available from ...modeling_outputs i...
null
10,962
import math import sys from dataclasses import dataclass from functools import partial from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.nn import LayerNorm from ...deepspeed import is_deepspeed_available from ...modeling_outputs i...
Helper to convert B x L mask of valid positions to axial mask used in row column attentions. Input: mask: B x L tensor of booleans Output: mask: B x L x L tensor of booleans
10,963
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `rot_matmul` function. Write a Python function `def rot_matmul(a: torch.Tensor, b...
Performs matrix multiplication of two rotation matrix tensors. Written out by hand to avoid AMP downcasting. Args: a: [*, 3, 3] left multiplicand b: [*, 3, 3] right multiplicand Returns: The product ab
10,964
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `rot_vec_mul` function. Write a Python function `def rot_vec_mul(r: torch.Tensor,...
Applies a rotation to a vector. Written out by hand to avoid transfer to avoid AMP downcasting. Args: r: [*, 3, 3] rotation matrices t: [*, 3] coordinate tensors Returns: [*, 3] rotated coordinates
10,965
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def identity_rot_mats( batch_dims: Tuple[int], dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, requires_grad: bool =...
null
10,966
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def identity_trans( batch_dims: Tuple[int], dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, requires_grad: bool = Tr...
null
10,967
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def identity_quats( batch_dims: Tuple[int], dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, requires_grad: bool = Tr...
null
10,968
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch _qtr_ind_dict = {key: ind for ind, key in enumerate(_qtr_keys)} def _to_mat(pairs): mat = np.zeros((4, 4)) for pair in pairs: key, value = pair ...
null
10,969
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def _get_quat(quat_key, dtype, device): return torch.tensor(_CACHED_QUATS[quat_key], dtype=dtype, device=device) The provided code snippet includes necessar...
Converts a quaternion to a rotation matrix. Args: quat: [*, 4] quaternions Returns: [*, 3, 3] rotation matrices
10,970
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def rot_to_quat( rot: torch.Tensor, ): if rot.shape[-2:] != (3, 3): raise ValueError("Input rotation is incorrectly shaped") rot = [[rot[.....
null
10,971
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def _get_quat(quat_key, dtype, device): return torch.tensor(_CACHED_QUATS[quat_key], dtype=dtype, device=device) The provided code snippet includes necessar...
Multiply a quaternion by another quaternion.
10,972
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def _get_quat(quat_key, dtype, device): return torch.tensor(_CACHED_QUATS[quat_key], dtype=dtype, device=device) The provided code snippet includes necessar...
Multiply a quaternion by a pure-vector quaternion.
10,973
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def invert_rot_mat(rot_mat: torch.Tensor): return rot_mat.transpose(-1, -2)
null
10,974
from __future__ import annotations from functools import lru_cache from typing import Any, Callable, Optional, Sequence, Tuple import numpy as np import torch def invert_quat(quat: torch.Tensor): quat_prime = quat.clone() quat_prime[..., 1:] *= -1 inv = quat_prime / torch.sum(quat**2, dim=-1, keepdim=True)...
null
10,975
import dataclasses import re import string from typing import Any, Mapping, Optional, Sequence import numpy as np from . import residue_constants PICO_TO_ANGSTROM = 0.01 class Protein: def from_proteinnet_string(proteinnet_str: str) -> Protein: tag_re = r"(\[[A-Z]+\]\n)" tags = [tag.strip() for tag in re.split...
null
10,976
import dataclasses import re import string from typing import Any, Mapping, Optional, Sequence import numpy as np from . import residue_constants class Protein: """Protein structure representation.""" # Cartesian coordinates of atoms in angstroms. The atom types correspond to # residue_constants.atom_types,...
Add pdb headers to an existing PDB string. Useful during multi-chain recycling
10,977
import dataclasses import re import string from typing import Any, Mapping, Optional, Sequence import numpy as np from . import residue_constants class Protein: """Protein structure representation.""" # Cartesian coordinates of atoms in angstroms. The atom types correspond to # residue_constants.atom_types,...
Converts a `Protein` instance to a PDB string. Args: prot: The protein to convert to PDB. Returns: PDB string.
10,978
import dataclasses import re import string from typing import Any, Mapping, Optional, Sequence import numpy as np from . import residue_constants class Protein: """Protein structure representation.""" # Cartesian coordinates of atoms in angstroms. The atom types correspond to # residue_constants.atom_types,...
Computes an ideal atom mask. `Protein.atom_mask` typically is defined according to the atoms that are reported in the PDB. This function computes a mask according to heavy atoms that should be present in the given sequence of amino acids. Args: prot: `Protein` whose fields are `numpy.ndarray` objects. Returns: An ideal...
10,979
import dataclasses import re import string from typing import Any, Mapping, Optional, Sequence import numpy as np from . import residue_constants FeatureDict = Mapping[str, np.ndarray] ModelOutput = Mapping[str, Any] class Protein: """Protein structure representation.""" # Cartesian coordinates of atoms in ang...
Assembles a protein from a prediction. Args: features: Dictionary holding model inputs. result: Dictionary holding model outputs. b_factors: (Optional) B-factors to use for the protein. chain_index: (Optional) Chain indices for multi-chain predictions remark: (Optional) Remark about the prediction parents: (Optional) L...
10,980
import logging import math from functools import partial from typing import Any, Callable, Dict, Optional, Sequence, Tuple import torch from .tensor_utils import tensor_tree_map, tree_map def _fetch_dims(tree): shapes = [] tree_type = type(tree) if tree_type is dict: for v in tree.values(): ...
Implements the "chunking" procedure described in section 1.11.8. Layer outputs and inputs are assumed to be simple "pytrees," consisting only of (arbitrarily nested) lists, tuples, and dicts with torch.Tensor leaves. Args: layer: The layer to be applied chunk-wise inputs: A (non-nested) dictionary of keyworded inputs. ...
10,981
import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def make_atom14_masks(protein): def tree_map(fn, tree, leaf_type): tensor_tree_map = partial(tree_map, leaf_type=torch.Tensor) def make_atom14_masks_np(batch): batch = tree_map(lambda n: tor...
null
10,982
from typing import Dict, Optional, Tuple import torch def _calculate_expected_aligned_error( alignment_confidence_breaks: torch.Tensor, aligned_distance_error_probs: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: bin_centers = _calculate_bin_centers(alignment_confidence_breaks) return ( t...
Computes aligned confidence metrics from logits. Args: logits: [*, num_res, num_res, num_bins] the logits output from PredictedAlignedErrorHead. max_bin: Maximum bin value no_bins: Number of bins Returns: aligned_confidence_probs: [*, num_res, num_res, num_bins] the predicted aligned error probabilities over bins for e...
10,983
from typing import Dict, Optional, Tuple import torch def _calculate_bin_centers(boundaries: torch.Tensor): step = boundaries[1] - boundaries[0] bin_centers = boundaries + step / 2 bin_centers = torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1)], dim=0) return bin_centers def compute_tm( ...
null
10,984
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather def pseudo_beta_fn(aatype, all_atom_positions, all_atom_masks): is_gly = aatype == rc.restype_order["G"] ca_idx = rc.atom_order["CA"] cb_idx = rc.atom_o...
null
10,985
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather def batched_gather(data, inds, dim=0, no_batch_dims=0): ranges = [] for i, s in enumerate(data.shape[:no_batch_dims]): r = torch.arange(s) r...
null
10,986
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather def build_template_angle_feat(template_feats): template_aatype = template_feats["template_aatype"] torsion_angles_sin_cos = template_feats["template_torsion...
null
10,987
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather class Rigid: """ A class representing a rigid transformation. Little more than a wrapper around two objects: a Rotation object and a [*, 3] translation ...
null
10,988
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather def build_extra_msa_feat(batch): msa_1hot = nn.functional.one_hot(batch["extra_msa"], 23) msa_feat = [ msa_1hot, batch["extra_has_deletion"]...
null
10,989
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather class Rotation: def __init__( self, rot_mats: Optional[torch.Tensor] = None, quats: Optional[torch.Tensor] = None, ...
null
10,990
import torch import torch.nn as nn from . import residue_constants as rc from .rigid_utils import Rigid, Rotation from .tensor_utils import batched_gather class Rigid: """ A class representing a rigid transformation. Little more than a wrapper around two objects: a Rotation object and a [*, 3] translation ...
null
10,991
from functools import partial from typing import List import torch import torch.nn as nn def add(m1, m2, inplace): # The first operation in a checkpoint can't be in-place, but it's # nice to have in-place addition during inference. Thus... if not inplace: m1 = m1 + m2 else: m1 += m2 ...
null
10,992
from functools import partial from typing import List import torch import torch.nn as nn def permute_final_dims(tensor: torch.Tensor, inds: List[int]): zero_index = -1 * len(inds) first_inds = list(range(len(tensor.shape[:zero_index]))) return tensor.permute(first_inds + [zero_index + i for i in inds])
null
10,993
from functools import partial from typing import List import torch import torch.nn as nn def flatten_final_dims(t: torch.Tensor, no_dims: int): return t.reshape(t.shape[:-no_dims] + (-1,))
null
10,994
from functools import partial from typing import List import torch import torch.nn as nn def masked_mean(mask, value, dim, eps=1e-4): mask = mask.expand(*value.shape) return torch.sum(mask * value, dim=dim) / (eps + torch.sum(mask, dim=dim))
null
10,995
from functools import partial from typing import List import torch import torch.nn as nn def pts_to_distogram(pts, min_bin=2.3125, max_bin=21.6875, no_bins=64): boundaries = torch.linspace(min_bin, max_bin, no_bins - 1, device=pts.device) dists = torch.sqrt(torch.sum((pts.unsqueeze(-2) - pts.unsqueeze(-3)) ** ...
null
10,996
from functools import partial from typing import List import torch import torch.nn as nn def dict_multimap(fn, dicts): first = dicts[0] new_dict = {} for k, v in first.items(): all_v = [d[k] for d in dicts] if type(v) is dict: new_dict[k] = dict_multimap(fn, all_v) else:...
null
10,997
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np atom_order = {atom_type: i for i, atom_type in enumerate(atom_types)} def map_structure_with_atom_order(in_list: List, first_call: bool = True): # Maps strings in a nested list...
null
10,998
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np The provided code snippet includes necessary dependencies for implementing the `sequence_to_onehot` function. Write a Python function `def sequence_to_onehot(sequence: str, mapping...
Maps the given sequence into a one-hot encoded matrix. Args: sequence: An amino acid sequence. mapping: A dictionary mapping amino acids to integers. map_unknown_to_x: If True, any amino acid that is not in the mapping will be mapped to the unknown amino acid 'X'. If the mapping doesn't contain amino acid 'X', an error...
10,999
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np residue_atoms = { "ALA": ["C", "CA", "CB", "N", "O"], "ARG": ["C", "CA", "CB", "CG", "CD", "CZ", "N", "NE", "O", "NH1", "NH2"], "ASP": ["C", "CA", "CB", "CG", "N", "O", ...
Returns [num_res_types, num_atom_types] mask array.
11,000
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np chi_angles_atoms = { "ALA": [], # Chi5 in arginine is always 0 +- 5 degrees, so ignore it. "ARG": [ ["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"], ...
Define chi-angle rigid groups via one-hot representations.
11,001
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np chi_angles_atoms = { "ALA": [], # Chi5 in arginine is always 0 +- 5 degrees, so ignore it. "ARG": [ ["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"], ...
Fill the arrays above.
11,002
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np van_der_waals_radius = { "C": 1.7, "N": 1.55, "O": 1.52, "S": 1.8, } def load_stereo_chemical_props() -> Tuple[ Mapping[str, List[Bond]], Mapping[str, List[B...
compute upper and lower bounds for bonds to assess violations.
11,003
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np residue_atom_renaming_swaps = { "ASP": {"OD1": "OD2"}, "GLU": {"OE1": "OE2"}, "PHE": {"CD1": "CD2", "CE1": "CE2"}, "TYR": {"CD1": "CD2", "CE1": "CE2"}, } restype_nam...
null
11,004
import collections import copy import functools from importlib import resources from typing import List, Mapping, Tuple import numpy as np restypes_with_x = restypes + ["X"] def aatype_to_str_sequence(aatype): return "".join([restypes_with_x[aatype[i]] for i in range(len(aatype))])
null
11,005
import collections import os import unicodedata from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `load_vocab` function....
Loads a vocabulary file into a dictionary.
11,006
import collections import os import unicodedata from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `whitespace_tokenize` ...
Runs basic whitespace cleaning and splitting on a piece of text.
11,009
import warnings from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import ( TFBaseModelOutput, TFMaskedLMOutput, TFMultipleChoiceModelOutput, TFQuestionAn...
null
11,010
import warnings from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import ( TFBaseModelOutput, TFMaskedLMOutput, TFMultipleChoiceModelOutput, TFQuestionAn...
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
11,011
import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path, base_model): # Initialise PyTorch model config = FunnelConf...
null
11,012
import os from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, MaskedLMOutput, ...
Load tf checkpoints in a pytorch model.
11,013
import os from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, MaskedLMOutput, ...
null
11,014
import os from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, MaskedLMOutput, ...
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
11,015
import math import random from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, Seq2SeqLMOutput, ...
Shift input ids one token to the right.
11,016
import math import random from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, Seq2SeqLMOutput, ...
Make causal mask used for bi-directional self-attention.
11,017
import math import random from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, Seq2SeqLMOutput, ...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,018
import json import os from typing import List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging from .english_normalizer import EnglishTextNormalizer The provided code snippet includes necessary dependencies for implementing the `b...
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,019
import json import os from typing import List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging from .english_normalizer import EnglishTextNormalizer The provided code snippet includes necessary dependencies for implementing the `g...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
11,020
import re from fractions import Fraction from typing import Iterator, List, Match, Optional, Union from ...utils import is_more_itertools_available import unicodedata import regex ADDITIONAL_DIACRITICS = { "œ": "oe", "Œ": "OE", "ø": "o", "Ø": "O", "æ": "ae", "Æ": "AE", "ß": "ss", "ẞ": "S...
Replace any other markers, symbols, and punctuations with a space, and drop any diacritics (category 'Mn' and some manual mappings)
11,021
import re from fractions import Fraction from typing import Iterator, List, Match, Optional, Union from ...utils import is_more_itertools_available import unicodedata import regex The provided code snippet includes necessary dependencies for implementing the `remove_symbols` function. Write a Python function `def remo...
Replace any other markers, symbols, punctuations with a space, keeping diacritics
11,022
import math import random from typing import Dict, Optional, Tuple import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import ( TFBaseModelOutput, TFBaseModelOutputWithPastAndCrossAttentions, TFSeq2SeqLMOutput, TFSeq2SeqModelOutput, ) from ...modeling_tf_u...
null
11,023
import math import random from typing import Dict, Optional, Tuple import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import ( TFBaseModelOutput, TFBaseModelOutputWithPastAndCrossAttentions, TFSeq2SeqLMOutput, TFSeq2SeqModelOutput, ) from ...modeling_tf_u...
Make causal mask used for bi-directional self-attention.
11,024
import math import random from typing import Dict, Optional, Tuple import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import ( TFBaseModelOutput, TFBaseModelOutputWithPastAndCrossAttentions, TFSeq2SeqLMOutput, TFSeq2SeqModelOutput, ) from ...modeling_tf_u...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,025
import math import os from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np 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 ( B...
Load tf checkpoints in a pytorch model.
11,026
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, big_bird_config_file, pytorch_dump_path, is_trivia_qa): # Initialise PyTorch model ...
null
11,027
import collections.abc 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 ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docst...
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,028
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoFeatureExtractor, CvtConfig, CvtForImageClassification def embeddings(idx): """ The function helps in renaming embedding layer weights. Args: ...
Fucntion to convert the microsoft cvt checkpoint to huggingface checkpoint
11,029
import argparse import os import numpy as np import torch from packaging import version from torch import nn import gluonnlp as nlp import mxnet as mx from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from tra...
Convert the original Bort checkpoint (based on MXNET and Gluonnlp) to our BERT structure-
11,030
import argparse import torch from transformers import NystromformerConfig, NystromformerForMaskedLM def convert_checkpoint_helper(config, orig_state_dict): for key in orig_state_dict.copy().keys(): val = orig_state_dict.pop(key) if ("pooler" in key) or ("sen_class" in key) or ("conv.bias" in key): ...
null
11,031
from typing import Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import TFBaseModelOutputWithPast, TFCausalLMOutputWithPast from ...modeling_tf_utils import ( DUMMY_INPUTS, TFCausalLanguageModelingLoss, TFModelIn...
Make causal mask used for bi-directional self-attention.
11,032
from typing import Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import TFBaseModelOutputWithPast, TFCausalLMOutputWithPast from ...modeling_tf_utils import ( DUMMY_INPUTS, TFCausalLanguageModelingLoss, TFModelIn...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,033
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging def load_checkpoint(checkpoint_path): """Checkpoint path should end in model.pt""" sd = torch.load(checkpoint_path, map_location="cpu") if "model" in sd.keys(): s...
Copy/paste/tweak model's weights to our BERT structure.
11,034
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 ( BaseModelOutputWithPast, CausalLMOutputWithPast, ...
Make causal mask used for bi-directional self-attention.
11,035
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 ( BaseModelOutputWithPast, CausalLMOutputWithPast, ...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,036
import math import os import warnings 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_outputs import ( Base...
Load tf checkpoints in a pytorch model.
11,037
import argparse import os import re import zipfile import torch from transformers import MegatronBertConfig def recursive_print(name, val, spaces=0): # Format the message. if name is None: msg = None else: fmt = "." * max(0, spaces - 2) + "# {:" + str(50 - spaces) + "s}" msg = fmt.f...
null
11,038
import argparse import os import re import zipfile import torch from transformers import MegatronBertConfig def fix_query_key_value_ordering(param, checkpoint_version, num_splits, num_heads, hidden_size): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with lat...
null
11,039
import argparse from torch import nn from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophe...
Copy/paste/tweak prohpetnet's weights to our prophetnet structure.
11,040
import copy import math import warnings from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import LayerNorm from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput from ...modeling_ut...
null
11,041
import copy import math import warnings from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import LayerNorm from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput from ...modeling_ut...
This function computes the bias for the predict stream
11,042
import copy import math import warnings from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import LayerNorm from ...activations import ACT2FN from ...modeling_outputs import BaseModelOutput from ...modeling_ut...
This function computes both main and predict relative position buckets. For more detail, see paper.
11,043
import collections import os import unicodedata from typing import Iterable, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `whitespace_...
Runs basic whitespace cleaning and splitting on a piece of text.
11,044
import collections import os import unicodedata from typing import Iterable, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `load_vocab`...
Loads a vocabulary file into a dictionary.
11,045
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( Wav2Vec2ConformerConfig, Wav2Vec2ConformerForCTC, Wav2Vec2ConformerForPreTraining, Wav2Vec2CTCTokenizer, Wav2Vec2FeatureExtractor, Wav2Vec2Processor, logging, ) lo...
Copy/paste/tweak model's weights to transformers design.
11,046
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...deepspeed import is_deepspeed_zero3_enabled from ...modeling_outputs ...
Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: shape: The shape for which to comp...
11,047
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...deepspeed import is_deepspeed_zero3_enabled from ...modeling_outputs ...
Sample `num_negatives` vectors from feature vectors.
11,048
import dataclasses import math import random from typing import Optional, Tuple, Union import numpy as np import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWith...
Shift input ids one token to the right.
11,049
import dataclasses import math import random from typing import Optional, Tuple, Union import numpy as np import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWith...
Make causal mask used for bi-directional self-attention.
11,050
import dataclasses import math import random from typing import Optional, Tuple, Union import numpy as np import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWith...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,051
import math import random from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from ...activations import ACT2FN from ...deepspeed import is_deepspeed_zero3_enabled from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_mo...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,052
import argparse import torch from transformers import GPT2Config, GPT2Model, load_tf_weights_in_gpt2 from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging def convert_gpt2_checkpoint_to_pytorch(gpt2_checkpoint_path, gpt2_config_file, pytorch_dump_folder_path): # Construct model if gpt2_config_file ...
null
11,053
import math import os from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.cuda.amp import autocast from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...modeling_outpu...
Load tf checkpoints in a pytorch model
11,056
import random from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import TFBaseModelOutputWithPastAndCrossAttentions from ...modeling_tf_utils import ( TFModelInputTyp...
null
11,057
import random from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import TFBaseModelOutputWithPastAndCrossAttentions from ...modeling_tf_utils import ( TFModelInputTyp...
Make causal mask used for bi-directional self-attention.
11,058
import random from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import tensorflow as tf from ...activations_tf import get_tf_activation from ...modeling_tf_outputs import TFBaseModelOutputWithPastAndCrossAttentions from ...modeling_tf_utils import ( TFModelInputTyp...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
11,059
import math import random from dataclasses import dataclass 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 ( BaseModelO...
Shift input ids one token to the right.
11,060
import math import random from dataclasses import dataclass 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 ( BaseModelO...
Make causal mask used for bi-directional self-attention.
11,061
import math import random from dataclasses import dataclass 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 ( BaseModelO...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.