id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
18,328 | import collections
import os
import unicodedata
from typing import List, Optional, Tuple
from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils.file_utils import logging
The provided code snippet includes necessary dependencies for implementing the `whit... | Runs basic whitespace cleaning and splitting on a piece of text. |
18,329 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
from .modeling_sbert import SbertConfig, SbertModel, load_tf_weights_in_bert
def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
import tensorflow as tf
import re
def var_n... | Convert a basic backbone ckpt from tf to pt. :param tf_checkpoint_path: The tf checkpoint local dir. :param sbert_config_file: The sbert config file local dir. :param pytorch_dump_path: The local file path of the generated pytorch bin file. :return: None |
18,330 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
from .modeling_sbert import SbertConfig, load_tf_weights_in_bert
def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
import tensorflow as tf
import re
def var_name_replace(... | Convert a checkpoint from tf to pt. Only support backbones with a linear part called classifier. :param tf_checkpoint_path: The tf checkpoint local dir. :param sbert_config_file: The sbert config file local dir. :param pytorch_dump_path: The local file path of the generated pytorch bin file. :param module_clz: The mode... |
18,331 | from torch import nn
import torch
from ...utils import logging
logger = logging.get_logger(__name__)
def _symmetric_kl_div(logits1, logits2, attention_mask=None):
"""
Calclate two logits' the KL div value symmetrically.
:param logits1: The first logit.
:param logits2: The second logit.
:param attent... | Calculate the adv loss of the model. :param embedding: Original sentense embedding :param model: The model, or the forward function(including decoder/classifier), accept kwargs as input, output logits :param ori_logits: The original logits outputed from the model function :param ori_loss: The original loss :param adv_g... |
18,332 | from torch import nn
import torch
from ...utils import logging
logger = logging.get_logger(__name__)
def _symmetric_kl_div(logits1, logits2, attention_mask=None):
"""
Calclate two logits' the KL div value symmetrically.
:param logits1: The first logit.
:param logits2: The second logit.
:param attent... | Calculate the adv loss of the model. This function is used in the pair logits scenerio. :param embedding: Original sentense embedding :param model: The model, or the forward function(including decoder/classifier), accept kwargs as input, output logits :param start_logits: The original start logits outputed from the mod... |
18,333 | import os
import random
import time
import numpy as np
import torch
def get_log_constant(user_log):
return '[user log]' if user_log else '' | null |
18,334 | import os
import random
import time
import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `print_args` function. Write a Python function `def print_args(args)` to solve the following problem:
Print arguments.
Here is the function:
def print_args(args):
"""... | Print arguments. |
18,335 | import os
import random
import time
import numpy as np
import torch
def print_rank_0(message):
if torch.distributed.is_initialized():
if torch.distributed.get_rank() == 0:
print(message, flush=True)
else:
print(message, flush=True)
The provided code snippet includes necessary depend... | Simple GPU memory report. |
18,336 | import re
import os
import sys
from .compat import _report_compat_error
PT_SAMPLE_DOCSTRINGS = {
"SequenceClassification": PT_SEQUENCE_CLASSIFICATION_SAMPLE,
"QuestionAnswering": PT_QUESTION_ANSWERING_SAMPLE,
"TokenClassification": PT_TOKEN_CLASSIFICATION_SAMPLE,
"MultipleChoice": PT_MULTIPLE_CHOICE_SAM... | null |
18,337 | import re
import os
import sys
from .compat import _report_compat_error
def _prepare_output_docstrings(output_type, config_class):
"""
Prepares the return part of the docstring using `output_type`.
"""
docstrings = output_type.__doc__
# Remove the head of the docstring to keep the list of args only
... | null |
18,338 | import re
import os
import sys
from .compat import _report_compat_error
def add_start_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator | null |
18,339 | import re
import os
import sys
from .compat import _report_compat_error
def add_start_docstrings_to_model_forward(*docstr):
def docstring_decorator(fn):
class_name = f":class:`~transformers.{fn.__qualname__.split('.')[0]}`"
intro = f" The {class_name} forward method, overrides the :func:`__call__... | null |
18,340 | import re
import os
import sys
from .compat import _report_compat_error
def add_end_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = fn.__doc__ + "".join(docstr)
return fn
return docstring_decorator | null |
18,341 | import re
import os
import sys
from .compat import _report_compat_error
def _get_indent(t):
"""Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0]
The provided code snippet includes necessary dependencies for implementing ... | Convert output_args_doc to display properly. |
18,342 | import argparse
import json
import sys
import zipfile
import numpy as np
from collections import Counter, defaultdict
import copy
import math, re
The provided code snippet includes necessary dependencies for implementing the `my_lcs` function. Write a Python function `def my_lcs(string, sub)` to solve the following pr... | Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequence between the two strings Note: my... |
18,343 | import argparse
import json
import sys
import zipfile
import numpy as np
from collections import Counter, defaultdict
import copy
import math, re
def precook(s, n=4, out=False):
"""Takes a string as input and returns an object that can be given to
either cook_refs or cook_test. This is optional: cook_refs and c... | Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. |
18,344 | import argparse
import json
import sys
import zipfile
import numpy as np
from collections import Counter, defaultdict
import copy
import math, re
def precook(s, n=4, out=False):
"""Takes a string as input and returns an object that can be given to
either cook_refs or cook_test. This is optional: cook_refs and c... | Takes a test sentence and returns an object that encapsulates everything that BLEU needs to know about it. |
18,345 | import argparse
import json
import sys
import zipfile
import numpy as np
from collections import Counter, defaultdict
import copy
import math, re
def data_check(obj, task):
"""
Check data.
Raises:
Raises AssertionError when data is not legal.
"""
assert 'question_id' in obj, "Missing 'questi... | Read predict answers or reference answers from file. Args: file_name: the name of the file containing predict result or reference result. Returns: A dictionary mapping question_id to the result information. The result information itself is also a dictionary with has four keys: - question_type: type of the query. - yesn... |
18,346 | import argparse
import json
import sys
import zipfile
import numpy as np
from collections import Counter, defaultdict
import copy
import math, re
def compute_bleu_rouge(pred_dict, ref_dict, bleu_order=4):
"""
Compute bleu and rouge scores.
"""
assert set(pred_dict.keys()) == set(ref_dict.keys()), \
... | Computes metrics. |
18,347 | import argparse
import json
import sys
import zipfile
import numpy as np
from collections import Counter, defaultdict
import copy
import math, re
The provided code snippet includes necessary dependencies for implementing the `format_metrics` function. Write a Python function `def format_metrics(metrics, task, err_msg)... | Format metrics. 'err' field returns any error occured during evaluation. Args: metrics: A dict object contains metrics for different tasks. task: Task name. err_msg: Exception raised during evaluation. Returns: Formatted result. |
18,348 | import os
import random
import numpy as np
import torch
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP
from sofa.utils import mpu,print_rank_0
def _get_ckpt_name(mpu, checkpoints_path, tag):
mp_rank = 0 if mpu is None else mpu.get_model_parallel_rank()
ckpt_name = os.path.join(che... | null |
18,349 | import os
import random
import numpy as np
import torch
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP
from sofa.utils import mpu,print_rank_0
def get_checkpoint_name(checkpoints_path, iteration, release=False, zero=False):
if release:
d = 'release'
else:
d = 'iter... | null |
18,350 | import os
import random
import numpy as np
import torch
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP
from sofa.utils import mpu,print_rank_0
def load_checkpoint(model,
load_dir,
tag,
load_module_strict=True,
... | Load a model checkpoint. |
18,351 | import os
import random
import numpy as np
import torch
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP
from sofa.utils import mpu,print_rank_0
def load_weights(src, dst, dst2src=False):
"""
Loads weights from src to dst via in place copy.
src is a huggingface gpt2model, while ... | Loads weights from `oai` to `our` via in place copy. `oai` is a huggingface gpt2model, while `our` is one of our models. dst2src=True loads parameters from our models into huggingface's. ^dst2src=True is still untested |
18,352 | import torch
from .utils import ensure_divisibility
_MODEL_PARALLEL_GROUP = None
_DATA_PARALLEL_GROUP = None
def ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert numerator % denominator == 0, '{} is not divisible by {}'.format(
numerator, ... | Initialize model data parallel groups. Arguments: model_parallel_size: number of GPUs used to parallelize model. Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we use 2 GPUs to parallelize the model. The present function will create 4 model parallel groups and 2 data parallel grous as: 4 model parallel gr... |
18,353 | import torch
from .utils import ensure_divisibility
_MODEL_PARALLEL_GROUP = None
_DATA_PARALLEL_GROUP = None
The provided code snippet includes necessary dependencies for implementing the `model_parallel_is_initialized` function. Write a Python function `def model_parallel_is_initialized()` to solve the following prob... | Check if model and data parallel groups are initialized. |
18,354 | import torch
from .utils import ensure_divisibility
def get_data_parallel_group():
"""Get the data parallel group the caller rank belongs to."""
assert _DATA_PARALLEL_GROUP is not None, \
'data parallel group is not initialized'
return _DATA_PARALLEL_GROUP
The provided code snippet includes necessa... | Return world size for the data parallel group. |
18,355 | import torch
from .utils import ensure_divisibility
_MODEL_PARALLEL_GROUP = None
_DATA_PARALLEL_GROUP = None
The provided code snippet includes necessary dependencies for implementing the `destroy_model_parallel` function. Write a Python function `def destroy_model_parallel()` to solve the following problem:
Set the g... | Set the groups to none. |
18,356 | import math
import torch
import torch.nn.init as init
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from .initialize import get_model_parallel_world_size
from .layers import ColumnParallelLinear
from .layers import RowParallelLinear
from .mappings import gather_from_model_parallel_region
i... | null |
18,357 | import math
import torch
import torch.nn.init as init
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from .initialize import get_model_parallel_world_size
from .layers import ColumnParallelLinear
from .layers import RowParallelLinear
from .mappings import gather_from_model_parallel_region
i... | Init method based on N(0, sigma). |
18,358 | import math
import torch
import torch.nn.init as init
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from .initialize import get_model_parallel_world_size
from .layers import ColumnParallelLinear
from .layers import RowParallelLinear
from .mappings import gather_from_model_parallel_region
i... | Init method based on N(0, sigma/sqrt(2*num_layers). |
18,359 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
... | All-reduce the the input tensor across model parallel group. |
18,360 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
... | Split the tensor along its last dimension and keep the corresponding slice. |
18,361 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
... | Gather tensors and concatinate along the last dimension. |
18,362 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
class _CopyToModelParallelRegion(torch.autograd.Function):
"""Pass the input to the model parallel region."""
def forward(ctx, input_):
... | null |
18,363 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
class _ReduceFromModelParallelRegion(torch.autograd.Function):
"""All-redcue the input from the model parallel region."""
def forward(ctx, inp... | null |
18,364 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
class _ScatterToModelParallelRegion(torch.autograd.Function):
"""Split the input and keep only the corresponding chuck to the rank."""
def for... | null |
18,365 | import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
from deepspeed.utils.timer import SynchronizedWallClockTimer
class _GatherFromModelParallelRegion(torch.autograd.Function):
"""Gather the input from model parallel region and concatinate."""
def forward(... | null |
18,366 | import torch
from torch._six import inf
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
'model parallel group is no... | Clips gradient norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Arguments: parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a single Tensor that w... |
18,367 | import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_world_size
from .utils import VocabUtility
class _VocabParallelCrossEntropy(torch.autograd.Function):
def forward(ctx, vocab_parallel_logits, target):
# Co... | Helper function for the cross entropy. |
18,368 | import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_src_rank
def _check_data_types(keys, data, target_dtype):
"""Check that all the keys have the same target data type."""
for key in keys:
assert data[ke... | Broadcast data from rank zero of each model parallel group to the members of the same model parallel group. Arguments: keys: list of keys in the data disctionary to be broadcasted data: data dictionary of string keys and cpu tensor values. datatype: torch data type of all tensors in data associated with keys. |
18,369 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | null |
18,370 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | null |
18,371 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | Sets the random number generator state of the current GPU. Argumentss: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Cloning caused major performance issues for +4 GPU cases. |
18,372 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | Get cuda rng tracker. |
18,373 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG states are tracked: default state: This is for data parallelism and is the s... |
18,374 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | null |
18,375 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | null |
18,376 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
from .initialize import get_data_parallel_rank
from .initialize import get_model_parallel_rank
from .init... | Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint. |
18,377 | import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
from ..utils import print_rank_0
import torch.distributed as dist
PARTITION_ACTIVATIONS = False
from .initialize import get_data_parallel_rank
from .initialize import get_... | null |
18,378 | import math
import torch
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn.parameter import Parameter
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_world_size
from .mappings ... | Initialize affine weight for model parallel. Build the master weight on all processes and scatter the relevant chunk. |
18,379 | import os
import types
from typing import Iterable
import torch
from typing import Callable, Tuple
from tqdm import tqdm
import numpy as np
import math
from torch.distributions.bernoulli import Bernoulli
from torch.nn.utils import clip_grad_norm_
from torch.optim import Optimizer
from .compat import _report_compat_erro... | Apply child tuning to all trainer classes. :param mode: The child_tuning type. Support: "ChildTuning-F" or "ChildTuning-D" :param reserve_p: The reserved gradiant ratio. :return: None |
18,380 | import os
import types
from typing import Iterable
import torch
from typing import Callable, Tuple
from tqdm import tqdm
import numpy as np
import math
from torch.distributions.bernoulli import Bernoulli
from torch.nn.utils import clip_grad_norm_
from torch.optim import Optimizer
from .compat import _report_compat_erro... | Apply child tuning to a trainer instance. :param trainer: The trainer instance. :param mode: The child_tuning type. Support: "ChildTuning-F" or "ChildTuning-D" :param reserve_p: The reserved gradiant ratio. :return: None |
18,381 | import queue
import threading
import tensorflow as tf
import torch
import numpy as np
def convert_tf_example_to_torch_tensors(example):
def _multiproc_iter(dl, output_queue):
data_iter = iter(dl)
for item in data_iter:
tensors = convert_tf_example_to_torch_tensors(item)
output_queue.put(tensors... | null |
18,382 | from __future__ import (absolute_import, division, print_function, unicode_literals)
import json
import logging
import os
import shutil
import tempfile
from functools import wraps
from hashlib import sha256
import sys
from io import open
import boto3
import requests
from botocore.exceptions import ClientError
from tqdm... | Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. |
18,383 | from __future__ import (absolute_import, division, print_function, unicode_literals)
import json
import logging
import os
import shutil
import tempfile
from functools import wraps
from hashlib import sha256
import sys
from io import open
import boto3
import requests
from botocore.exceptions import ClientError
from tqdm... | Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and then return the path. |
18,384 | from __future__ import (absolute_import, division, print_function, unicode_literals)
import json
import logging
import os
import shutil
import tempfile
from functools import wraps
from hashlib import sha256
import sys
from io import open
import boto3
import requests
from botocore.exceptions import ClientError
from tqdm... | Wrapper function for s3 requests in order to create more helpful error messages. |
18,385 | from __future__ import (absolute_import, division, print_function, unicode_literals)
import json
import logging
import os
import shutil
import tempfile
from functools import wraps
from hashlib import sha256
import sys
from io import open
import boto3
import requests
from botocore.exceptions import ClientError
from tqdm... | Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. |
18,386 | from __future__ import (absolute_import, division, print_function, unicode_literals)
import json
import logging
import os
import shutil
import tempfile
from functools import wraps
from hashlib import sha256
import sys
from io import open
import boto3
import requests
from botocore.exceptions import ClientError
from tqdm... | null |
18,387 | import os
import time
from operator import itemgetter
from bisect import bisect_right
import json
import csv
import math
import random
from itertools import accumulate
from torch.utils import data
import pandas as pd
import numpy as np
import nltk
from nltk import tokenize
from .lazy_loader import lazy_array_loader, ex... | Split a dataset into subsets given proportions of how much to allocate per split. If a split is 0% returns None for that split. Purpose: Useful for creating train/val/test splits Arguments: ds (Dataset or array-like): Data to be split. split (1D array-like): proportions to split `ds`. `sum(splits) != 0` shuffle (boolea... |
18,388 | from collections import namedtuple
import random
import os
import csv
import torch
import nltk
from nltk import tokenize as nltk_tokenize
import sentencepiece as spm
from .wordpiece import BertTokenizer, PRETRAINED_VOCAB_ARCHIVE_MAP
from .tokenization_gpt2 import GPT2Tokenizer
import regex as re
class Tokenizer(object)... | Helper function to instantiate a tokenizer given common combinations of options. |
18,389 | from collections import namedtuple
import random
import os
import csv
import torch
import nltk
from nltk import tokenize as nltk_tokenize
import sentencepiece as spm
from .wordpiece import BertTokenizer, PRETRAINED_VOCAB_ARCHIVE_MAP
from .tokenization_gpt2 import GPT2Tokenizer
import regex as re
class CommandToken(obje... | null |
18,390 | from collections import namedtuple
import random
import os
import csv
import torch
import nltk
from nltk import tokenize as nltk_tokenize
import sentencepiece as spm
from .wordpiece import BertTokenizer, PRETRAINED_VOCAB_ARCHIVE_MAP
from .tokenization_gpt2 import GPT2Tokenizer
import regex as re
class TypeToken(object)... | null |
18,391 | from collections import namedtuple
import random
import os
import csv
import torch
import nltk
from nltk import tokenize as nltk_tokenize
import sentencepiece as spm
from .wordpiece import BertTokenizer, PRETRAINED_VOCAB_ARCHIVE_MAP
from .tokenization_gpt2 import GPT2Tokenizer
import regex as re
MAX_SENTENCEPIECE_SENTE... | Take corpus, split it into sentences, and extract word frequencies. Write frequencies to `filepath` as a tsv. Only write the first MAX_SENTENCEPIECE_SENTENCES most common words to the file. |
18,392 | import os
import mmap
import pickle as pkl
import time
from itertools import accumulate
import torch
from torch.multiprocessing import Lock
def get_lazy_path(path):
"""
Gets directory path where lazy files are stored.
"""
return os.path.splitext(path)[0]+'.lazy'
The provided code snippet includes neces... | Check if we've already made a lazy version of this file for the `data_type` field. |
18,393 | import os
import mmap
import pickle as pkl
import time
from itertools import accumulate
import torch
from torch.multiprocessing import Lock
def get_lazy_path(path):
"""
Gets directory path where lazy files are stored.
"""
return os.path.splitext(path)[0]+'.lazy'
The provided code snippet includes neces... | Make lazy version of `data_type` field of the file. Byte offsets corresponding to data indices are stored in a `.len.pkl` data file. |
18,394 | import os
import mmap
import pickle as pkl
import time
from itertools import accumulate
import torch
from torch.multiprocessing import Lock
The provided code snippet includes necessary dependencies for implementing the `split_strings` function. Write a Python function `def split_strings(strings, start, chr_lens)` to s... | Split strings based on string lengths and given start. |
18,395 | from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import logging
import os
import unicodedata
from io import open
from .file_utils import cached_path
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
The provided ... | Loads a vocabulary file into a dictionary. |
18,396 | from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import logging
import os
import unicodedata
from io import open
from .file_utils import cached_path
The provided code snippet includes necessary dependencies for implementing the `whitespace_tokenize` function. Write ... | Runs basic whitespace cleaning and splitting on a piece of text. |
18,397 | from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import logging
import os
import unicodedata
from io import open
from .file_utils import cached_path
The provided code snippet includes necessary dependencies for implementing the `_is_whitespace` function. Write a Pyt... | Checks whether `chars` is a whitespace character. |
18,398 | from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import logging
import os
import unicodedata
from io import open
from .file_utils import cached_path
The provided code snippet includes necessary dependencies for implementing the `_is_control` function. Write a Python... | Checks whether `chars` is a control character. |
18,399 | from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import logging
import os
import unicodedata
from io import open
from .file_utils import cached_path
The provided code snippet includes necessary dependencies for implementing the `_is_punctuation` function. Write a Py... | Checks whether `chars` is a punctuation character. |
18,400 | 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 .file_utils import cached_path
def lru_cache():
return lambda func: func | null |
18,401 | 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 .file_utils import cached_path
The provided code snippet includes necessary dependencies for implementing the `bytes_t... | Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This ... |
18,402 | 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 .file_utils import cached_path
The provided code snippet includes necessary dependencies for implementing the `get_pai... | Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). |
18,403 | import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from .loss_scaler import DynamicLossScaler, LossScaler
from .fp16util import model_grads_to_master_grads, master_params_to_model_params... | Convert fp32 `val` to fp16 |
18,404 | import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from .loss_scaler import DynamicLossScaler, LossScaler
from .fp16util import model_grads_to_master_grads, master_params_to_model_params... | Convert fp16 `val` to fp32 |
18,405 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
class tofp16(nn.Module):
"""
Utility module that implements::
def forward(self, input):
return input.half()
"""
... | Convert model to half precision in a batchnorm-safe way. Retained for legacy purposes. It is recommended to use FP16Model. |
18,406 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
def convert_module(module, dtype):
"""
Converts a module's immediate parameters and buffers to dtype.
"""
for param in module.parame... | Converts a network's parameters and buffers to dtype. |
18,407 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
def backwards_debug_hook(grad):
raise RuntimeError("master_params recieved a gradient in the backward pass!") | null |
18,408 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
The provided code snippet includes necessary dependencies for implementing the `prep_param_lists` function. Write a Python function `def prep_param... | Creates a list of FP32 master parameters for a given model, as in `Training Neural Networks with Mixed Precision: Real Examples`_. Args: model (torch.nn.Module): Existing Pytorch model flat_master (bool, optional, default=False): Flatten the master parameters into a single tensor, as a performance optimization. Returns... |
18,409 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
The provided code snippet includes necessary dependencies for implementing the `model_grads_to_master_grads` function. Write a Python function `def... | Copy model gradients to master gradients. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func... |
18,410 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
The provided code snippet includes necessary dependencies for implementing the `master_params_to_model_params` function. Write a Python function `d... | Copy master parameters to model parameters. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :fu... |
18,411 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from sofa.utils import mpu
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0] | null |
18,412 | import torch
from sofa.utils import mpu
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0] | null |
18,413 | import importlib
import os
from packaging import version
def _report_compat_error():
if "SOFA_BACKEND" not in os.environ:
os.environ["SOFA_BACKEND"] = "sofa"
sofa_backend = os.environ["SOFA_BACKEND"]
if sofa_backend not in ["huggingface", "easytexminer", "easynlp", "sofa"]:
raise RuntimeErro... | Inject custom pipeline into transformers pipeline :param name: The pipeline name :param pipeline_clz: The pipeline clz, should be the sub class of InferenceBase :param automodel_clz: The AutoModel class to get the proper model from. :return: None |
18,414 | import importlib
import os
from packaging import version
def _report_compat_error():
if "SOFA_BACKEND" not in os.environ:
os.environ["SOFA_BACKEND"] = "sofa"
sofa_backend = os.environ["SOFA_BACKEND"]
if sofa_backend not in ["huggingface", "easytexminer", "easynlp", "sofa"]:
raise RuntimeErro... | Inject some model package into the selected backend framework. :param name: The model name. :param full_name: The full name of the model :param config: The config class of the model. :param tokenizer: The tokenizer class of the model. :param tokenizer_fast: The tokenizer fast class of the model. :param kwargs: The spec... |
18,415 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,416 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,417 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,418 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,419 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,420 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
logger = logging.get_logger(__name__)
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback ... | null |
18,421 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
logger = logging.get_logger(__name__)
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback ... | null |
18,422 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,423 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,424 | import functools
import importlib.util
import numbers
import os
import sys
import tempfile
from pathlib import Path
from .file_utils import is_datasets_available
from .utils import logging
from .file_utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available
from .trainer_callback import ProgressCallback, TrainerCallba... | null |
18,425 | import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional
import torch
from .file_utils import add_start_docstrings
class MaxLengthCriteria(StoppingCriteria):
"""
This class can be used to stop generation whenever the full generated number of tokens exceeds `max_lengt... | null |
18,426 | import collections
from .file_utils import ExplicitEnum, is_torch_available
from .utils import logging
def get_abs_min_max(var, ctx):
abs_var = var.abs()
return f"{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}" | null |
18,427 | import collections
from .file_utils import ExplicitEnum, is_torch_available
from .utils import logging
The provided code snippet includes necessary dependencies for implementing the `detect_overflow` function. Write a Python function `def detect_overflow(var, ctx)` to solve the following problem:
Report whether the te... | Report whether the tensor contains any `nan` or `inf` entries. This is useful for detecting overflows/underflows and best to call right after the function that did some math that modified the tensor in question. This function contains a few other helper features that you can enable and tweak directly if you want to tra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.