id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
10,556
import inspect from typing import Callable, List, Optional, Set, Tuple, Union import torch from packaging import version from torch import _softmax_backward_data, nn from .utils import logging The provided code snippet includes necessary dependencies for implementing the `find_pruneable_heads_and_indices` function. Wr...
Finds the heads and their indices taking `already_pruned_heads` into account. Args: heads (`List[int]`): List of the indices of heads to prune. n_heads (`int`): The number of heads in the model. head_size (`int`): The size of each head. already_pruned_heads (`Set[int]`): A set of already pruned heads. Returns: `Tuple[S...
10,557
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand class TrainCommand(BaseTransformersC...
Factory function used to instantiate training command from provided command line arguments. Returns: TrainCommand
10,558
import json import os import subprocess import sys import warnings from argparse import ArgumentParser from contextlib import AbstractContextManager from typing import Dict, List, Optional import requests from ..utils import logging from . import BaseTransformersCLICommand The provided code snippet includes necessary ...
Write out the message in Line delimited JSON.
10,559
import json import os import subprocess import sys import warnings from argparse import ArgumentParser from contextlib import AbstractContextManager from typing import Dict, List, Optional import requests from ..utils import logging from . import BaseTransformersCLICommand logger = logging.get_logger(__name__) The pro...
Read Line delimited JSON from stdin.
10,560
import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand class AddNewModelCommand(BaseTransformersCLICommand): def register_subcommand(parser: ArgumentParse...
null
10,561
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand class ConvertCommand(BaseTransformersCLICommand): def register_subcommand(parser: ArgumentParser): """ Register this command to argparse so it's available for the transformer-cli ...
Factory function used to convert a model TF 1.0 checkpoint in a PyTorch checkpoint. Returns: ServeCommand
10,562
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand def try_infer_format_from_ext(path: str): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMAT...
null
10,563
import inspect import os from argparse import ArgumentParser, Namespace from importlib import import_module import numpy as np from packaging import version import huggingface_hub from .. import ( FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, ...
Factory function used to convert a model PyTorch checkpoint in a TensorFlow 2 checkpoint. Returns: ServeCommand
10,564
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand def Body(*x, **y): pass
null
10,565
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand class ServeCommand(BaseTransformersCLICommand): def register_subcommand(parser: ArgumentParser): ...
Factory function used to instantiate serving server from provided command line arguments. Returns: ServeCommand
10,566
from argparse import ArgumentParser from . import BaseTransformersCLICommand class DownloadCommand(BaseTransformersCLICommand): def register_subcommand(parser: ArgumentParser): download_parser = parser.add_parser("download") download_parser.add_argument( "--cache-dir", type=str, default=...
null
10,567
import subprocess from argparse import ArgumentParser from typing import List, Union from huggingface_hub.hf_api import HfFolder, create_repo, whoami from requests.exceptions import HTTPError from . import BaseTransformersCLICommand The provided code snippet includes necessary dependencies for implementing the `tabula...
Inspired by: - stackoverflow.com/a/8356620/593036 - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
10,568
import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_flax_available, is_tf_available, is_torch_available from . import BaseTransformersCLICommand class EnvironmentCommand(BaseTransformersCLICommand): def register_subcommand(parser: A...
null
10,569
import difflib import json import os import re from argparse import ArgumentParser, Namespace from dataclasses import dataclass from datetime import date from itertools import chain from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Pattern, Tuple, Union import transformers.models.auto as ...
Creates a new model module like a given model of the Transformers library. Args: model_type (`str`): The model type to duplicate (like "bert" or "gpt2") new_model_patterns (`ModelPatterns`): The patterns for the new model. add_copied_from (`bool`, *optional*, defaults to `True`): Whether or not to add "Copied from" sta...
10,570
import difflib import json import os import re from argparse import ArgumentParser, Namespace from dataclasses import dataclass from datetime import date from itertools import chain from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Pattern, Tuple, Union import transformers.models.auto as ...
null
10,571
import difflib import json import os import re from argparse import ArgumentParser, Namespace from dataclasses import dataclass from datetime import date from itertools import chain from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Pattern, Tuple, Union import transformers.models.auto as ...
Ask the user for the necessary inputs to add the new model.
10,572
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from .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_length`. K...
null
10,573
import collections from .utils import ExplicitEnum, is_torch_available, 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
10,574
import collections from .utils import ExplicitEnum, is_torch_available, 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 tensor contains any `nan`...
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...
10,575
import warnings from typing import Dict, List, Tuple from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors from tokenizers.models import BPE, Unigram, WordPiece from .utils import requires_backends def check_number_comma(piece: str) -> bool: return len(piece) < 2 or piece[-1] !...
null
10,576
import warnings from typing import Dict, List, Tuple from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors from tokenizers.models import BPE, Unigram, WordPiece from .utils import requires_backends SLOW_TO_FAST_CONVERTERS = { "AlbertTokenizer": AlbertConverter, "BartTokenize...
Utilities to convert a slow tokenizer instance in a fast tokenizer instance. Args: transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]): Instance of a slow tokenizer to convert in the backend tokenizer for [`~tokenization_utils_base.PreTrainedTokenizerFast`]. Return: A instance of [`~tokenizers.Toke...
10,577
import re from typing import Callable, List, Optional, Union import tensorflow as tf class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule): """ Applies a warmup schedule on a given learning rate decay schedule. Args: initial_learning_rate (`float`): The initial learning rate f...
Creates an optimizer with a learning rate schedule using a warmup phase followed by a linear decay. Args: init_lr (`float`): The desired learning rate at the end of the warmup phase. num_train_steps (`int`): The total number of training steps. num_warmup_steps (`int`): The number of warmup steps. min_lr_ratio (`float`,...
10,578
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logger = logging.get_logger(__name__) TOKENIZER_CLASSES = {name: getattr(transformers, name + "Fast") for name in SLOW_TO_FAST_CONVERTERS} def convert_slow_checkpoint_to_fast(tokenizer_n...
null
10,579
import os from typing import TYPE_CHECKING, List, Tuple, Union import numpy as np from packaging import version import requests from .utils import ( ExplicitEnum, is_jax_tensor, is_tf_tensor, is_torch_available, is_torch_tensor, is_vision_available, to_numpy, ) from .utils.constants import (...
null
10,580
import os from typing import TYPE_CHECKING, List, Tuple, Union import numpy as np from packaging import version import requests from .utils import ( ExplicitEnum, is_jax_tensor, is_tf_tensor, is_torch_available, is_torch_tensor, is_vision_available, to_numpy, ) from .utils.constants import (...
null
10,581
import os from typing import TYPE_CHECKING, List, Tuple, Union import numpy as np from packaging import version import requests from .utils import ( ExplicitEnum, is_jax_tensor, is_tf_tensor, is_torch_available, is_torch_tensor, is_vision_available, to_numpy, ) from .utils.constants import (...
Loads `image` to a PIL Image. Args: image (`str` or `PIL.Image.Image`): The image to convert to the PIL Image format. Returns: `PIL.Image.Image`: A PIL Image.
10,582
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,583
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,584
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,585
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,586
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,587
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,588
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
Parse the `logs` of either a `tf.keras.History` object returned by `model.fit()` or an accumulated logs `dict` passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`.
10,589
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
Parse the `log_history` of a Trainer to get the intermediate and final evaluation results.
10,590
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,591
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
Create a nice Markdown table from the results in `lines`.
10,592
import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.a...
null
10,593
import gc import json import os import re from functools import partial from pickle import UnpicklingError from typing import Any, Dict, Set, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp import msgpack.exceptions from flax.core.frozen_dict import FrozenDict, unfreeze from flax.serialization i...
null
10,594
import gc import json import os import re from functools import partial from pickle import UnpicklingError from typing import Any, Dict, Set, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp import msgpack.exceptions from flax.core.frozen_dict import FrozenDict, unfreeze from flax.serialization i...
Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no optimization made to make each sub-checkpoint as close as possible to the maxim...
10,595
import gc import json import os import re from functools import partial from pickle import UnpicklingError from typing import Any, Dict, Set, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp import msgpack.exceptions from flax.core.frozen_dict import FrozenDict, unfreeze from flax.serialization i...
null
10,596
import gc import json import os import re from functools import partial from pickle import UnpicklingError from typing import Any, Dict, Set, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp import msgpack.exceptions from flax.core.frozen_dict import FrozenDict, unfreeze from flax.serialization i...
null
10,597
import gc import json import os import re from functools import partial from pickle import UnpicklingError from typing import Any, Dict, Set, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp import msgpack.exceptions from flax.core.frozen_dict import FrozenDict, unfreeze from flax.serialization i...
null
10,598
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version The...
Create a schedule with a constant learning rate, using the learning rate set in optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_sche...
10,599
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version The...
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of st...
10,600
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version The...
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_w...
10,601
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version The...
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for ...
10,602
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version The...
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Opti...
10,603
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version The...
Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for whic...
10,604
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version TYPE...
Unified API to get any scheduler from its name. Args: name (`str` or `SchedulerType`): The name of the scheduler to use. optimizer (`torch.optim.Optimizer`): The optimizer that will be used during training. num_warmup_steps (`int`, *optional*): The number of warmup steps to do. This is not required by all schedulers (h...
10,605
import math import warnings from typing import Callable, Iterable, Optional, Tuple, Union import torch from torch import nn from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .trainer_utils import SchedulerType from .utils import logging from .utils.versions import require_version clas...
Get a proxy schedule for [`~optimization.Adafactor`] Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. initial_lr (`float`, *optional*, defaults to 0.0): Initial lr Return: [`~optimization.Adafactor`] proxy schedule object.
10,606
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or nested list/tuples/dict of tensors.
10,607
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Find the first dimension of a tensor in a nested list/tuple/dict of tensors.
10,608
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Numpify `tensors` (even if it's a nested list/tuple/dict of tensors).
10,609
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Detach `tensors` (even if it's a nested list/tuple/dict of tensors).
10,610
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,611
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,612
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,613
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,614
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Decorator to make all processes in distributed training wait for each local_master to do something. Args: local_rank (`int`): The rank of the local process.
10,615
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,616
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Create the same nested structure as `arrays` with a first dimension always at `num_samples`.
10,617
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.
10,618
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Truncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors).
10,619
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar lengths. To do this, the indices are: - randomly permuted - grouped in mega-batches of size `mega_batch_mult * batch_size` - sorted by length in each mega-batch The result is the concatenation of all mega-b...
10,620
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,621
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Log metrics in a specially formatted way Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predictmetrics: metrics dict Notes on memory reports: In order t...
10,622
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Save metrics into a json file for that split, e.g. `train_results.json`. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test`, `all` metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict combined (`bool`,...
10,623
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model Under distributed environment this is done only for a process with rank 0.
10,624
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Returns the names of the model parameters that are not inside a forbidden layer.
10,625
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
Gets a class from a module by its name. Args: module (`torch.nn.Module`): The module to get the class from. name (`str`): The name of the class.
10,626
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,627
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,628
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,629
import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import ...
null
10,630
import inspect import math from typing import Callable, Iterable, List, Optional, Tuple import numpy as np import torch from .utils import add_start_docstrings from .utils.logging import get_logger def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int): generated_ngrams = [{} for _ in range(...
Copied from fairseq for no_repeat_ngram in beam_search
10,631
import collections import json import math import re import string from ...models.bert import BasicTokenizer from ...utils import logging def find_best_thresh_v2(preds, scores, na_probs, qid_to_has_ans): num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) cur_score = num_no_ans best_score =...
null
10,632
import collections import json import math import re import string from ...models.bert import BasicTokenizer from ...utils import logging def get_raw_scores(examples, preds): """ Computes the exact and f1 scores from the examples and the model predictions """ exact_scores = {} f1_scores = {} for...
null
10,633
import collections import json import math import re import string from ...models.bert import BasicTokenizer from ...utils import logging logger = logging.get_logger(__name__) def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False): """Project the tokenized prediction back to the original tex...
Write final predictions to the json file and log-odds of null if needed.
10,634
import collections import json import math import re import string from ...models.bert import BasicTokenizer from ...utils import logging logger = logging.get_logger(__name__) def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False): """Project the tokenized prediction back to the original tex...
XLNet write prediction logic (more complex than Bert's). Write final predictions to the json file and log-odds of null if needed. Requires utils_squad_evaluate.py
10,635
import random import warnings from collections.abc import Mapping from dataclasses import dataclass from random import randint from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np from ..models.bert import BertTokenizer, BertTokenizerFast from ..tokenization_utils_base import...
Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - `label`: handles a single value (int or float) per object - `label_ids`: handles a list of values per object Does not do any additional preprocessing: property names of the input object ...
10,636
import random import warnings from collections.abc import Mapping from dataclasses import dataclass from random import randint from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np from ..models.bert import BertTokenizer, BertTokenizerFast from ..tokenization_utils_base import...
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
10,637
import random import warnings from collections.abc import Mapping from dataclasses import dataclass from random import randint from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np from ..models.bert import BertTokenizer, BertTokenizerFast from ..tokenization_utils_base import...
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
10,638
import random import warnings from collections.abc import Mapping from dataclasses import dataclass from random import randint from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np from ..models.bert import BertTokenizer, BertTokenizerFast from ..tokenization_utils_base import...
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
10,639
import random import warnings from collections.abc import Mapping from dataclasses import dataclass from random import randint from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union import numpy as np from ..models.bert import BertTokenizer, BertTokenizerFast from ..tokenization_utils_base import...
null
10,640
import json import os from functools import partial from multiprocessing import Pool, cpu_count import numpy as np from tqdm import tqdm from ...models.bert.tokenization_bert import whitespace_tokenize from ...tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase, TruncationStrategy from ...utils import...
Check if this is the 'max context' doc span for the token.
10,641
import json import os from functools import partial from multiprocessing import Pool, cpu_count import numpy as np from tqdm import tqdm from ...models.bert.tokenization_bert import whitespace_tokenize from ...tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase, TruncationStrategy from ...utils import...
null
10,642
import json import os from functools import partial from multiprocessing import Pool, cpu_count import numpy as np from tqdm import tqdm from ...models.bert.tokenization_bert import whitespace_tokenize from ...tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase, TruncationStrategy from ...utils import...
Converts a list of examples into a list of features that can be directly given as input to a model. It is model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs. Args: examples: list of [`~data.processors.squad.SquadExample`] tokenizer: an instance of a child of [`PreTraine...
10,643
import importlib.util import weakref from copy import deepcopy from functools import partialmethod from .dependency_versions_check import dep_version_check from .utils import is_accelerate_available, is_torch_available, logging _hf_deepspeed_config_weak_ref = None def set_hf_deepspeed_config(hf_deepspeed_config_obj): ...
null
10,644
import importlib.util import weakref from copy import deepcopy from functools import partialmethod from .dependency_versions_check import dep_version_check from .utils import is_accelerate_available, is_torch_available, logging _hf_deepspeed_config_weak_ref = None def unset_hf_deepspeed_config(): # useful for unit...
null
10,645
import importlib.util import weakref from copy import deepcopy from functools import partialmethod from .dependency_versions_check import dep_version_check from .utils import is_accelerate_available, is_torch_available, logging _hf_deepspeed_config_weak_ref = None def deepspeed_config(): if _hf_deepspeed_config_we...
null
10,646
import importlib.util import weakref from copy import deepcopy from functools import partialmethod from .dependency_versions_check import dep_version_check from .utils import is_accelerate_available, is_torch_available, logging logger = logging.get_logger(__name__) def deepspeed_optim_sched(trainer, hf_deepspeed_config...
Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args. If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made. Args: trainer: Trainer object num_training_steps: per single gpu resume_from_checkpoint: path to a checkpoint if ...
10,647
import importlib import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from huggingface_hub import HfFolder, model_info from .utils import HF_MODULES_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, cached_file, is_offline_mode, logging def get_class_in_module(class_name...
Extracts a class from a module file, present in the local folder or repository of a model. <Tip warning={true}> Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should therefore only be called on trusted repos. </Tip> Args: pretrained_model_name_or_path (`str` ...
10,648
import importlib import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from huggingface_hub import HfFolder, model_info from .utils import HF_MODULES_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, cached_file, is_offline_mode, logging logger = logging.get_logger(__name...
Save the modeling files corresponding to a custom model/configuration/tokenizer etc. in a given folder. Optionally adds the proper fields in a config. Args: obj (`Any`): The object for which to save the module files. folder (`str` or `os.PathLike`): The folder where to save. config (`PretrainedConfig` or dictionary, `o...
10,649
import math from collections import OrderedDict import torch from packaging import version from torch import Tensor, nn from .utils import logging ACT2FN = ClassInstantier(ACT2CLS) def get_activation(activation_string): if activation_string in ACT2FN: return ACT2FN[activation_string] else: rais...
null
10,650
import subprocess from typing import Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline The provided code snippet includes necessary dependencies for implementing the `ffmpeg_read` function. Write a Python function `def ffmpeg_rea...
Helper function to read an audio file through ffmpeg.
10,651
import platform import subprocess from typing import Optional, Tuple, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `ffmpeg_read` function. Write a Python function `def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.array` to solve the following problem...
Helper function to read an audio file through ffmpeg.
10,652
import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def ffmpeg_microphone( sampling_rate: int, chunk_length_s: float, format_for_conversion: str = "f32le", ): """ Helper function ro read raw microphone data. """ ar = f"{sampling_rate}" ac = "1" ...
Helper function to read audio from the microphone file through ffmpeg. This will output `partial` overlapping chunks starting from `stream_chunk_s` (if it is defined) until `chunk_length_s` is reached. It will make use of striding to avoid errors on the "sides" of the various chunks. Arguments: sampling_rate (`int`): T...
10,653
import re from typing import List, Optional, Tuple, Union import numpy as np from ..utils import ( ExplicitEnum, add_end_docstrings, is_pytesseract_available, is_torch_available, is_vision_available, logging, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline from .question_answering import s...
Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes.
10,654
import types import warnings from collections.abc import Iterable from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union import numpy as np from ..data import SquadExample, SquadFeatures, squad_convert_examples_to_features from ..modelcard import ModelCard from ..tokenization_utils import PreTrainedTokeni...
Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses `decode_spans()` to generate probabilities for each span to be the actual answer. Args: start (`np.ndarray`): Individual start logits for each token. end (`np.ndarray`): Individual end logits for each token. p_mask (`...
10,655
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline def sigmoid(_outputs): return 1.0 / (1.0 + np.exp(-_outputs))
null