code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTok...
28
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowerCamelCase : List[Any] = { "configuration_m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config", "...
28
1
'''simple docstring''' import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on imp...
334
'''simple docstring''' import requests UpperCamelCase = '''https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=''' def SCREAMING_SNAKE_CASE( __lowercase ) -> None: # fetching a list of articles in json format A: Tuple = requests.get(_NE...
334
1
'''simple docstring''' from __future__ import annotations from functools import lru_cache from math import ceil lowerCAmelCase__ = 100 lowerCAmelCase__ = set(range(3, NUM_PRIMES, 2)) primes.add(2) lowerCAmelCase__ = 42 for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime ...
104
from __future__ import annotations def _lowerCamelCase( lowercase__ , lowercase__ ) -> bool: '''simple docstring''' __lowercase= get_failure_array(lowercase__ ) # 2) Step through text searching for pattern __lowercase, __lowercase= 0, 0 # index into text, pattern wh...
295
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, loggi...
354
def _a ( UpperCAmelCase ) -> int: """simple docstring""" if not isinstance(UpperCAmelCase , UpperCAmelCase ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) lowerCamelCase__ : List[str] = 0 while number:...
265
0
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD...
96
"""simple docstring""" from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record lowercase__ = """\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language ...
96
1
"""simple docstring""" import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def _snake_case ...
352
"""simple docstring""" import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowercase_ ( unittest.TestCase ): '''simple docstr...
271
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _A : Tuple =logging.get_logger(__name__) class _lowercase ( A__ ...
41
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, To...
126
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel...
126
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _a : List[Any] = logging.get_logger(__name__) class __A ( SCREAMING_SNAKE_CASE_ ,...
126
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 ...
334
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, r...
334
1
import os import re import shutil import sys import tempfile import unittest import black lowercase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that wi...
194
import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS...
194
1
'''simple docstring''' def __lowerCAmelCase (__lowerCAmelCase = 4_000_000 ): _UpperCAmelCase : Optional[Any] = [0, 1] _UpperCAmelCase : int = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i ...
234
'''simple docstring''' from __future__ import annotations import math class UpperCamelCase_ : def __init__( self , A ) -> None: UpperCAmelCase : Optional[int] = size # approximate the overall size of segment tree with given value UpperCAmelCase :...
265
0
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": _UpperCAmelCase = pd.read_csv("""sample_data.csv""", header=None) _UpperCAmelCase ...
192
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _UpperC...
192
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCamelCase = { '''configuration_vision_text_dual_encoder''': ['''VisionTextDualEncoderConfig'''], '''...
131
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ):...
271
0
def UpperCamelCase_( lowerCamelCase_ ) -> set: _lowercase : Any = set() # edges = list of graph's edges _lowercase : int = get_edges(lowerCamelCase_ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add h...
84
from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase) -...
84
1
"""simple docstring""" from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class A_ ( A__ ): """simple docstring""" ...
126
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase = logging.get_logger(__name__) lowerCAmel...
126
1
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration UpperCamelCase = 50_0000 UpperCamelCase , UpperCamelCase = os.path.split(__file__) UpperCamelCase = os.path.join(RESULTS_B...
221
from maths.prime_factors import prime_factors def _A ( lowerCAmelCase_ : int ): """simple docstring""" if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): lowerCAmelCase__ = F'Input value of [number={number}] must be an int...
221
1
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> set: """simple docstring""" _UpperCamelCase = set() # edges = list of graph's edges _UpperCamelCase = get_edges(__snake_case ) # While there are still elements in ed...
194
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a = { """configuration_autoformer""": [ """AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", ...
194
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ ={ 'configuration_rembert': ['REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Rem...
90
import argparse import os import re import packaging.version lowercase__ ='examples/' lowercase__ ={ 'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__ve...
90
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : str = logging.get_logger(__name__) A_ : str = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ...
192
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Optional[int] = {'configuration_ibert': ['IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'IBertConfig', 'IBertOnnxConfig']} try: if not is_torch_available(): raise OptionalDependenc...
192
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeIma...
363
"""simple docstring""" UpperCAmelCase: str = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.g...
336
0
"""simple docstring""" from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) __UpperCAmelCase = 2_99_79_24_58 # Symbols __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = symbols('ct x y z') ...
84
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def _snake_case ( ) -> Generator[int, None, None]: '''simple docstring''' lowerCAmelCase_ :dict[int, int] = {} lowerCAmelCase_ :int ...
84
1
"""simple docstring""" from collections.abc import Iterable from typing import Any class lowerCAmelCase__ : def __init__( self : List[Any] , snake_case__ : int | None = None ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = value Uppe...
351
"""simple docstring""" import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch...
298
0
"""simple docstring""" from __future__ import annotations def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if (direction == 1 and array[indexa] > array[indexa]) or ...
221
"""simple docstring""" from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np ...
221
1
'''simple docstring''' import socket def _A ( ) -> Union[str, Any]: _lowercase : Any = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) _lowercase : Optional[Any] = socket.gethostname() _lowercase : Union[str, Any] ...
199
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TR...
199
1
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_commo...
90
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __A ...
90
1
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = (UnCLIPScheduler,) def SCREAMING_SNAKE_CASE_ (self : Optional[int]...
273
from __future__ import annotations from typing import Any class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0) ->None: '''simple docstr...
273
1
def A ( a_ = 1_000_000 ) -> int: __UpperCamelCase : List[Any] =limit + 1 __UpperCamelCase : Any =[0] * limit for first_term in range(1 ,a_ ): for n in range(a_ ,a_ ,a_ ): ...
71
import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils impo...
336
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dim...
357
def __lowerCamelCase ( UpperCAmelCase_ : int = 100 ): """simple docstring""" a :List[Any] = 0 a :List[Any] = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_int...
281
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _SCREAMING_SNAKE_CASE = (PNDMScheduler,) _SCREAMING_SNAK...
159
'''simple docstring''' def __lowerCAmelCase ( snake_case__ ): return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(snake_case__ ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__('''doctest''').testmod(...
298
0
from PIL import Image def UpperCamelCase_( _snake_case : Image , _snake_case : float ): """simple docstring""" def brightness(_snake_case : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: ...
308
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) _lowerCAmelCase : ...
308
1
# using dfs for finding eulerian path traversal def a_ ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int]=None ): '''simple docstring''' _low...
199
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( ...
199
1
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor _lowercase : Union[str, Any] =logging.get_logger(__name__) class snake_case__ (A__ ): """simple docstring""" def __init__( se...
365
import torch from diffusers import StableDiffusionPipeline _lowercase : Optional[int] ="path-to-your-trained-model" _lowercase : Union[str, Any] =StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("cuda") _lowercase : Any ="A photo of sks...
266
0
def __SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] UpperCAmelCase = 6 UpperCAmelCase = 1 UpperCAmelCase = 1901 UpperCAmelCase = 0 while year < 200...
273
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokeniz...
273
1
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowercase__ : Optional[Any] = logging.get_logger(__name__) class _UpperCAmelCase : ...
360
"""simple docstring""" import math import sys def __lowercase ( _a ): if number != int(_a ): raise ValueError('''the value of input must be a natural number''' ) if number < 0: raise ValueError('''the value of input must not be a negative number''' ) if number == ...
155
0
"""simple docstring""" import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "vocab_file": "vocab.txt...
86
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def lowerCAmelC...
281
0
'''simple docstring''' def lowerCamelCase ( lowerCAmelCase : Any , lowerCAmelCase : Any ): """simple docstring""" return int(input_a == input_a == 0 ) def lowerCamelCase ( ): """simple docstring""" print('Truth Table of NOR Gate:' ) print('| ...
354
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowerCAmelCase :Tuple = logging.get_logger(__name__) class _lowerCamelCase ( lowercase__ ): '''simple docstring''' def __init__( self : Any , ...
275
0
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.I...
308
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logg...
308
1
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. __UpperCAmelCase = 2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be...
42
import json import os import torch from diffusers import UNetaDModel os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True) def __lowerCamelCase ( __magi...
42
1
from ..utils import DummyObject, requires_backends class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["sentencepiece"] def __init__( self : int , *snake_case : Optional[Any] , **snake_case : Tuple ) -> Optional[Any]: """simple docs...
175
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, T...
266
0
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available():...
20
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, ...
20
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtraction...
321
"""simple docstring""" import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_chec...
155
0
import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this ...
362
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_...
208
0
'''simple docstring''' class _lowercase : def __init__( self: Dict , UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: List[Any] ): lowerCamelCase__ : Dict = name l...
41
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __lowercase (_UpperCA...
275
0
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require...
119
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_...
119
1
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( __A ) -> list[int]: # This function is recursive _snake_case = len(__A ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: ...
42
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase : List[str] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2Stru...
42
1
import math class _snake_case : def A__ ( self : str, __lowercase : list[list[float]], __lowercase : list[int] ): lowercase__ = 0.0 lowercase__ = 0.0 for i in range(len(__lowercase ) ): da += math.pow((sample[i] - weights[0][i])...
224
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging lowercase_ = logging.get_logger(__name__) def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ): lowercase__ = r"\w+[.]\d+" low...
224
1
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...
20
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _snake_case( SCREAMING_SNAKE_CASE__ ) -> Tuple: lowercase : U...
20
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json' ...
351
"""simple docstring""" def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(UpperCAmelCase , n - 1 , UpperCAmelCase ) * a) % mod else: ...
303
0
'''simple docstring''' 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 try: from cookiecutter.main import cookiecutter lowerCam...
206
'''simple docstring''' import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffuse...
208
0
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRU...
14
import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def lowerCamelCase ( a_ , a_ , a_ , a_ , a_ ) -> List[Any]: # load base model lowerCAmelCase_ = StableD...
14
1
def UpperCamelCase ( snake_case__ : int , snake_case__ : int ) -> str: if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) UpperCamelCase : Optional[int] = str(bin(snake_case__ ) )[2:] # remove the leading "0b" UpperCamelCa...
119
import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import loggi...
119
1
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import Acceler...
353
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { 'huggingface/autoformer-tourism-monthly': 'https://huggingface.co/huggingface/autoformer-touri...
189
0
"""simple docstring""" import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('dataset_size' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('input_in_memory_max_size' , ['default', 0, 100 * 2**20, ...
224
"""simple docstring""" import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging lowercase__ : Optional[Any] = logging.get_logger(__name__) ...
224
1
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging _lowerCamelCase = logging.get_logger(__name__) def a__ ( _SCREAMING_SNAKE_CASE : Union[str, Any]=None , _...
354
'''simple docstring''' from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def a__ ( ) -> tuple[list[int], int]: """simple docstring""" UpperCAmelCase_ : Tuple = [randint(-10_00 ...
67
0
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ['image_processor', 'tokenizer'] ...
104
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBer...
303
0
"""simple docstring""" A_ : Dict = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def lowerCamelCase_ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ...
370
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ : List[str] = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if n...
316
0
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATU...
14
import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common ...
14
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sa...
357
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ "microsoft/unispeech-sat-base-100h-libri-ft": ( "https://huggingface.co/mi...
237
0
def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if number > 0: raise ValueError('''input must be a negative integer''' ) __UpperCamelCase :str = len(bin(SCREAMING_SNAKE_CASE )[3:] ) __UpperCamelCase :Optional[Any] = bin(abs(SCREAMING_SNAKE_CASE ) -...
43
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from...
189
0
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = 42...
354
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): ...
296
0
import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # n...
343
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, ...
67
0
"""simple docstring""" import warnings from functools import wraps from typing import Callable def lowerCAmelCase (__UpperCamelCase : Callable ): """simple docstring""" @wraps(__UpperCamelCase ) def _inner_fn(*__UpperCamelCase : Any , **__UpperCamelCase : List[Any...
85
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __lowercase = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-...
85
1
'''simple docstring''' import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tens...
56
"""simple docstring""" import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL UpperCamelCase : Union[str, Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def ...
316
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "uclanlp/visualbert-vqa": "https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json", "uclanlp/visual...
26
def _a ( a :list ) -> list: if len(a ) <= 1: return lst a = 1 while i < len(a ): if lst[i - 1] <= lst[i]: i += 1 else: a , a = lst[i], lst[i - 1] i -= 1 if i == 0: a = 1 return lst if __name__ == "__main_...
26
1
"""simple docstring""" class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] ): lowerCAmelCase = {} def __lowercase ( self : Optional[int] ): print(self.vertex ) for i in self.vertex: pri...
155
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=UpperCamelCase__ ): __lowercase = ["""note_seq"""] def __init__( self :Optional[Any] , *lowercase_ :List[Any] , **lowercase_ :List[str] ...
237
0
'''simple docstring''' import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py a_ = 'src/diffusers' # Matches is_xxx_available() a_ = re.compile(R'is\_([a-z_]*)_avail...
354
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property fro...
222
0
'''simple docstring''' import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _lowerCamelCase ( lowercase : Any , ...
63
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Un...
296
0
from __future__ import annotations import typing from collections.abc import Iterable import numpy as np a =typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 a =typing.Union[np.floataa, int, float] # noqa: UP007 def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ...
354
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> bool: if len(lowerCamelCase__ ) == 0: return False __lowerCamelCase : List[Any] = len(lowerCamelCase__ ) // 2 if a_list[midpoint] == item: retu...
113
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class _snake_case ( lowercase_ ): lower...
85
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE : Tuple = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"...
85
1
'''simple docstring''' # Imports import numpy as np class a__: def __init__( self : Dict , __snake_case : Union[str, Any]=None , __snake_case : Tuple=None , __snake_case : Optional[Any]=None , __snake_case : int=None , __sn...
96
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase: Optional[int] = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig']...
96
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ], ...
26
import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils impor...
26
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Tuple = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP...
114
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : float , _UpperCamelCase : float ) -> float: """simple docstring""" if mass < 0: raise ValueError('The mass of a body cannot be negative' ) return 0.5 * mass * abs(_UpperCamelCase ...
114
1
'''simple docstring''' def snake_case_ ( _lowerCAmelCase : Optional[Any] = 50 ) -> int: UpperCAmelCase : int = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): ...
23
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) _UpperCAmelCase : List[str] = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", ...
222
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """...
215
"""simple docstring""" import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configura...
215
1
"""simple docstring""" from __future__ import annotations from collections.abc import Callable __UpperCamelCase : Optional[Any] = list[list[float | int]] def __SCREAMING_SNAKE_CASE ( A_ , A_ ): lowerCAmelCase__ : List[str] = len(SCREAMING_SNAKE_CASE_ ) lowerCAme...
106
"""simple docstring""" # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is...
113
0
import argparse import os import torch from transformers.utils import WEIGHTS_NAME _snake_case = ['''small''', '''medium''', '''large'''] _snake_case = '''lm_head.decoder.weight''' _snake_case = '''lm_head.weight''' def _UpperCamelCase ( snake_case__, sn...
342
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration _snake_case = [ # tf -> hf ('''/''', '''.'''), ('''layer_''', '''layers.'''), ('''kernel''', ...
342
1
"""simple docstring""" import socket def _snake_case ( ): _lowerCamelCase : List[Any] = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) _lowerCamelCase : Union[str, Any] = socket.gethostname() _lowerCamelCase : Li...
96
"""simple docstring""" # Imports import numpy as np class lowerCAmelCase__ : '''simple docstring''' def __init__( self , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None ): self.set_m...
96
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __snake_case : Dict = {'''configuration_mra''': ['''MRA_PRETRAINED_CONFIG_A...
357
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case : Dict = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} tr...
122
0
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be consid...
114
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils i...
114
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_lowercase): snake_case__ = ['''keras_nlp'''] def __init__( self : Any , *__UpperCamelCase : Union[str, Any] , **__UpperCamelCase : int )...
357
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionSch...
54
0
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins A_ : Dict = ["""tests.fixtures.files""", """tests.fixtures.hub""", """tests.fixtures.fsspec"""] def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ )-> Optional[int]: '...
215
'''simple docstring''' import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from tr...
215
1
from __future__ import annotations class UpperCAmelCase_ : '''simple docstring''' def __init__( self , _A , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = text, pattern __SCREA...
118
def __lowercase ( a__ ) -> int: __SCREAMING_SNAKE_CASE = [[0 for _ in range(a__ )] for _ in range(m + 1 )] for i in range(m + 1 ): __SCREAMING_SNAKE_CASE = 1 for n in range(m + 1 ): for k in range(1 ...
118
1
from scipy.stats import spearmanr import datasets __magic_name__: str = "\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correla...
342
from __future__ import annotations def UpperCamelCase ( _A ): # This function is recursive """simple docstring""" __magic_name__ : str = len(_A ) # If the array contains only one element, we return it (it's the stop condition of # recursion) ...
342
1
"""simple docstring""" def __A ( a_ :int) -> bool: if number < 0: raise ValueError('''number must not be negative''') return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
188
"""simple docstring""" import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import ...
188
1
'''simple docstring''' import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCamelCase__ ( lowerCAm...
70
_A = [0, 2, 4, 6, 8] _A = [1, 3, 5, 7, 9] def lowerCamelCase__ ( a__ : int , a__ : int , a__ : list[int] , a__ : int ) -> int: if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return ...
122
0
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device ...
164
'''simple docstring''' # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path UpperCamelCase__ : Optional[Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_...
164
1
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common im...
97
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy a__ : Union[str, Any] = log...
54
0
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed ...
123
'''simple docstring''' import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device fr...
123
1
from collections import deque from .hash_table import HashTable class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self : Dict , *__magic_name__ : Optional[int] , **__magic_name__ : Dict ) -> Optional[Any]:...
118
import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCamelCase (...
118
1
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import ...
143
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import A...
143
1
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def UpperCAmelCase__ ( _A : str ): '''simple docstring''' a__, a__ =analyze_text(_A ) a__ =list(''' ''' + ascii_lowercase ) # what is our tot...
188
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
188
1
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeli...
182
"""simple docstring""" import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('dataset_size' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('input_in_memory_max_size' , ['default', 0, 100 * 2**20, 900 * 2**20] ) def __lowerCAme...
182
1
'''simple docstring''' def _A ( lowercase__ = 100 ): lowercase__ = set() lowercase__ = 0 lowercase__ = n + 1 # maximum limit for a in range(2 , lowercase__ ): for b in range(2 , lowercase_...
164
'''simple docstring''' import heapq as hq import math from collections.abc import Iterator class A : def __init__( self , lowerCamelCase__ ) -> Optional[Any]: '''simple docstring''' lowercase__ = str(id_ ) lowercase__ ...
164
1
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFMode...
94
def lowerCAmelCase__ ( lowerCamelCase_ : str ,lowerCamelCase_ : str): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = len(lowerCamelCase_) lowerCAmelCase__ : str = len(lowerCamelCase_) lowerCAmelCase__ : Union[str, Any] ...
94
1
from collections.abc import Callable class a : """simple docstring""" def __init__( self : str , lowerCamelCase : Callable | None = None ) -> None: # Stores actual heap items. __snake_case : list = [] # Store...
123
import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : Union[str, Any] = "▁" _snake_ca...
123
1
from __future__ import annotations def __lowercase ( _UpperCamelCase ) ->Tuple: # This function is recursive """simple docstring""" lowercase : Dict = len(__SCREAMING_SNAKE_CASE ) # If the array contains only one element, we return it (it's the...
370
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy...
173
0
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class __snake_case : def __init__( self ) -> Dict: '''simple docstring''' snake_case__ : List[str] = '' snake_case__ ...
143
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer ...
143
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CAS...
357
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup _SCREAMING_SNAKE_CASE = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.195...
81
0
import numpy as np from PIL import Image def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Any = np.array(_lowercase ) if arr.shape[0] != arr.shape[1]: raise ValueError('''The input array is not a square matrix''' ) ...
182
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : List[Any] = {'configuration_glpn': ['GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GLPNConfig']} try: if not is_vision_available(): ...
182
1
from collections.abc import Sequence def UpperCamelCase (lowercase_: Sequence[float] , lowercase_: float ) -> float: return sum(c * (x**i) for i, c in enumerate(lowercase_ ) ) def UpperCamelCase (lowercase_: Sequence[float] , lowercase_: float ) -> float: A__ : ...
355
from __future__ import annotations def UpperCamelCase (lowercase_: float , lowercase_: float , lowercase_: float ) -> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError...
141
0