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""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {"""configuration_encoder_decoder"""...
81
'''simple docstring''' def a_ ( lowerCamelCase : Optional[Any] ): return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8:...
4
0
import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models....
124
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def UpperCAmelCase ( a_ ) -> None: """simple docstring""" __A , __A = analyze_text(a_ ) __A = list(" " + ascii_...
124
1
import re from filelock import FileLock try: import nltk _lowerCamelCase : Union[str, Any] = True except (ImportError, ModuleNotFoundError): _lowerCamelCase : Dict = False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", q...
336
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
1
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutp...
140
from scipy.stats import spearmanr import datasets __lowerCamelCase : List[str] = """ The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive...
140
1
from collections import deque def snake_case_ ( snake_case ) -> List[Any]: lowercase__: str = len(snake_case ) lowercase__: Union[str, Any] = deque() lowercase__: Optional[int] = [False for _ in range(snake_case )] lowercase_...
196
def snake_case_ ( snake_case , snake_case ) -> str: if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) lowercase__: str = str(bin(snake_case ) ) binary_number += "0" * shift_amount ...
196
1
from __future__ import annotations def __magic_name__ ( __lowerCAmelCase : list[int] ) -> bool: return len(set(__lowerCAmelCase ) ) == len(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
367
import glob import os import random from string import ascii_lowercase, digits import cva SCREAMING_SNAKE_CASE__ : str = "" SCREAMING_SNAKE_CASE__ : Any = "" SCREAMING_SNAKE_CASE__ : Optional[Any] = "" SCREAMING_SNAKE_CASE__ : Optional[Any] ...
339
0
def lowerCAmelCase__ ( lowerCamelCase_ : str): '''simple docstring''' lowerCAmelCase__ : str = [int(lowerCamelCase_) for i in ip_va_address.split('''.''') if i.isdigit()] return len(lowerCamelCase_) == 4 and all(0 <= int(lowerCamelCase_) <= 254 for octet in octets) i...
129
def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = [] lowerCAmelCase__ : List[str] = 1 while len(lowerCamelCase_) < 1E6: constant.append(str(lowerCamelCase_)) i += 1 lowerCAmelCase__ : ...
129
1
def UpperCamelCase ( _A = 1, _A = 1000 ): """simple docstring""" __magic_name__ : Optional[int] = 1 __magic_name__ : Dict = 0 for divide_by_number in range(_A, digit + 1 ): __magic_name__ : ...
138
import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class snake_case__ ( tf.keras.layers.Layer ): def __init__( self , lo...
138
1
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import...
48
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {'configuration_mmbt': ['MMBTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAv...
48
1
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers....
366
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import L...
255
0
"""simple docstring""" import os import numpy import onnx def lowercase ( _snake_case : Any , _snake_case : List[Any] ) ->int: """simple docstring""" __snake_case : str = a.name __snake_case : Any = b.name __snake_case : in...
102
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils imp...
27
0
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def SCREAMING_SNAKE_CASE ( __UpperCamelCase = 8) -> str: a = ascii_letters + digits + punctuation return "".join(secre...
352
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() lowercase__ : Union[str, Any] = logging.get_logger(__name__) lowercase__ : Dict = [ ["attention", "attn"], ...
180
0
"""simple docstring""" import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @req...
77
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFI...
296
0
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(_SCREAMING_SNAKE_CASE...
352
'''simple docstring''' from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging __A : Dict = logging.get_logger(__name__) __A : int = { "snap-research/efficientformer-l1-300": ( "https://huggingface....
89
0
"""simple docstring""" def _snake_case ( _snake_case : int = 100 ): lowerCAmelCase : Union[str, Any] = (n * (n + 1) // 2) ** 2 lowerCAmelCase : List[str] = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"""{soluti...
60
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import (...
60
1
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ : Dict =get_tests_dir('''fixtures/spiece.model...
361
from __future__ import annotations from collections.abc import Generator def __lowercase ( ) -> Generator[int, None, None]: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = 2 while True: __SCREAMING_SNAKE_CASE = factor_map.pop(a...
118
0
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __UpperCAmelCase = (7_20, 12_80) # Height, Width __UpperCAmelCase = (0.4, 0.6) # if height or width lower than this scale, drop it....
84
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if imp...
84
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import...
371
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output...
273
0
'''simple docstring''' from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def UpperCAmelCase_ ( __lowercase : str ) -> None: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase ...
22
'''simple docstring''' from math import pow def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count +...
198
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) A_ : Union[str, Any] = ...
371
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 100 , )-> float: '''simple docstring''' _UpperCAmelCase : str...
349
0
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses...
338
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import ...
89
0
"""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 imp...
341
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets __A = datasets.logging.get_logger(__name__) __A = '\\n@InProceedings{moosavi2019minimum,\n auth...
341
1
"""simple docstring""" import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class snake_case ( unittest.TestCase ): def UpperCAmelCase__ ( self) ->Dict: a_ =...
243
"""simple docstring""" from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def UpperCamelCase ( UpperCAmelCase ) ->List[Any]: """simple docstring""" def is_in_circle(UpperCAmelCase , UpperCAmelCase ) -> bool: a_...
243
1
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCAmelCase ( a_ , unitt...
358
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__) class __lowerCAmelCase ( UpperCamelCase__): _lowercase : str ...
148
0
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from...
278
def __UpperCamelCase ( _A = 1000000 ): lowerCAmelCase_ = 1 lowerCAmelCase_ = 1 lowerCAmelCase_ = {1: 1} for inputa in range(2 , _A ): lowerCAmelCase_ = 0 lowerCAmelCase_ = inputa while True: ...
278
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json', } class lowerCamelCase__ ( __magic...
369
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common...
341
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : List[Any] = logging.get_logger(__name__) __lowerCAmelCase : Optional[int] = { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/ma...
88
import re import string import numpy as np import datasets UpperCAmelCase : List[str] = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" UpperCAmelCase : str = "\nArgs:\n predi...
252
0
'''simple docstring''' import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from t...
364
'''simple docstring''' import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING a : Union[str, An...
338
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A : Tuple = logging.get...
229
'''simple docstring''' def UpperCamelCase_ ( snake_case_ : list[int] , snake_case_ : list[int] ) -> tuple[float, float]: '''simple docstring''' if not len(snake_case_ ) == len(snake_case_ ) == 3: raise ValueError("""Please enter ...
229
1
UpperCamelCase__ : dict[str, float] = { "joule": 1.0, "kilojoule": 1_000, "megajoule": 1_000_000, "gigajoule": 1_000_000_000, "wattsecond": 1.0, "watthour": 3_600, "kilowatthour": 3_600_000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalor...
367
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''AT...
330
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def __UpperCAmelCase ( __a : str ) -> List[str]:...
235
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin ...
235
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE = { """configuration_altclip""": [ """ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AltCLIPConfig""", """AltCLIP...
165
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDCondi...
165
1
import argparse import os import re import packaging.version _UpperCAmelCase : Optional[int] = """examples/""" _UpperCAmelCase : List[str] = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), "...
50
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def _a ( UpperCAmelCase ) -> str: """simple docstring""" lower...
142
0
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): __snake_case : int = len(__lowerCamelCase ) __snake_case : int = len(__lowerCamelCase ) __snake_case : int = ( first_str_length if ...
134
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Any = logging.get_logger(__name__) _snake_case : Dict = { "facebook/s2t-wav2vec2-large-en-de": ( "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json" ...
134
1
'''simple docstring''' import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester fro...
321
'''simple docstring''' import math def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> float: if initial_intensity < 0: raise ValueError("""The value of intensity cannot be negative""" ) # handling of negative values of initia...
321
1
'''simple docstring''' import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelera...
220
'''simple docstring''' 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, ...
220
1
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_tor...
161
'''simple docstring''' import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, ...
161
1
'''simple docstring''' import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def lowerCAmelCase_ ( snake_case__ = 3 ): '''simple docstring''' if isinstance(snake_case__ , ...
358
'''simple docstring''' 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 if is_tf_available(): from ..models.auto.modeling_tf_au...
311
0
"""simple docstring""" import functools def _snake_case ( UpperCamelCase : str , UpperCamelCase : str ): UpperCAmelCase : str = len(UpperCamelCase ) UpperCAmelCase : int = len(UpperCamelCase ) @functools.cache def min_distance(UpperCamelCase : int ...
109
'''simple docstring''' import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, Ada...
75
0
import argparse import copy def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} with open(_UpperCAmelCase) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE = [] _list.append([line.split()...
327
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require...
327
1
'''simple docstring''' import argparse 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 from ...
229
'''simple docstring''' import numpy as np import qiskit def UpperCamelCase_ ( snake_case_ : int = 8 , snake_case_ : int | None = None ) -> str: '''simple docstring''' __lowerCAmelCase = np.random.default_rng(see...
229
1
from math import factorial, radians def __lowerCamelCase ( lowerCamelCase__ : float , lowerCamelCase__ : int = 18 , lowerCamelCase__ : int = 10 ): '''simple docstring''' lowerCamelCase = angle_in_degrees - ((angle...
355
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("""socket.socket""" ) @patch("""builtins.open""" ) def __lowerCamelCase ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Dict ): '''simple docstring''' low...
66
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class ...
253
import os def A_ ( a = "matrix.txt" ): """simple docstring""" with open(os.path.join(os.path.dirname(a ) , a ) ) as in_file: SCREAMING_SNAKE_CASE_ : Dict = in_file.read() SCREAMING_SNAKE_CASE_ : Dict = [[int(a ) fo...
253
1
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class snake_case__ : _snake_case : Union[str, Any] = 42 _snake_case : str = None _sn...
352
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__:int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:List[Any] = {"""vocab_file""": """vocab.json"""} SCREAMING_SNAKE...
268
0
"""simple docstring""" from __future__ import annotations def _UpperCAmelCase ( __lowerCamelCase : Optional[Any] ) -> list[int]: # This function is recursive _snake_case = len(UpperCamelCase_ ) # If the array contains only one element, we return it (it's the s...
288
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch...
176
0
import math def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Tuple: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(SCREAMING_SNAKE_CASE__ ) else: if x == 0: ...
351
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import ...
285
0
SCREAMING_SNAKE_CASE :int = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def _lowerCAmelCase ( )->None: '''simple docstring''' snake_case_ = input("Enter message: " ) snake_case_ = input("Enter key [alphanumeric]: " ) snake_case_ = inp...
159
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version SCREAMING_SNAKE_CASE...
15
0
'''simple docstring''' from __future__ import annotations def _A (lowerCAmelCase__ :list[int] , lowerCAmelCase__ :list[int] , lowerCAmelCase__ :int ) -> tuple[float, list[float]]: '''simple docstring''' _a = list(rang...
104
'''simple docstring''' import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class a ( unittest.TestCase ): def __UpperCAmelCase ( self ) -> int: _a = [ 'safety_checker/pytorch_model.bin...
104
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "micros...
45
"""simple docstring""" 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 OptionalDepe...
315
0
import math from collections.abc import Callable def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Callable[[float], float] , __magic_name__ : float , __magic_name__ : float ) -> float: """simple docstring""" UpperCamelCase :List[Any] = xa Up...
359
from string import ascii_uppercase UpperCAmelCase_ : str = {str(ord(c) - 55): c for c in ascii_uppercase} def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> str: """simple docstring""" if isinstance(__magic_name__ , ...
62
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowerCAmelCase_ = logging.get_logger(__name__) l...
8
'''simple docstring''' from __future__ import annotations import string from itertools import cycle, product from pathlib import Path UpperCamelCase_ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) UpperCamelCase_ = [ord(letter)...
251
0
"""simple docstring""" import math def UpperCamelCase_( _snake_case : List[Any] ): """simple docstring""" __a =[True] * n __a =False __a =False __a =True for i in range(3 , int(n**0.5 + 1 ) , 2 ...
358
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency _lowerCAmelCase : Tuple = { "E": 12.70, "T": 9.06, "A": 8.17, "O": 7.51, "I": 6.97, "N": 6.75, "S": 6.33, "H": 6.09, "R": 5.99, "D": 4.25, "L": 4.03, "C"...
308
0
import math def SCREAMING_SNAKE_CASE_ ( __A : int ) -> bool: """simple docstring""" a_ : Dict = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(__A ) def SCREAMING_SNAKE_...
32
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def __snake_case ( _UpperCAmelCase = "isbn/0140328726" ): __a = olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes if new_olid.count('''/''' )...
49
0
'''simple docstring''' import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import Batc...
156
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers impor...
156
1
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_...
11
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ...
193
0
from __future__ import annotations def snake_case__ ( SCREAMING_SNAKE_CASE_ : int | float | str , SCREAMING_SNAKE_CASE_ : int | float | str ): '''simple docstring''' if nth_term == "": return [""] lowercase__ : Dict = int(SCREAMING_SNAKE_CASE...
216
from __future__ import annotations from collections.abc import Callable def snake_case__ ( SCREAMING_SNAKE_CASE_ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE_ : int | float , SCREAMING_SNAKE_CASE_ : int | float , SCREAMING_SNAKE_CASE_ : int = 100 ...
216
1
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apach...
70
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import R...
252
0
import numpy as np import datasets lowerCAmelCase__ = ''' Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. ...
370
import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__=1 ): """simple docstring""" if n_shave_prefix_segments >= 0: return ".".join(path.split("." )[n_sha...
121
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { """tanreinama/GPTSAN-2.8B-spout_is_uniform""": ( """https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json"""...
171
"""simple docstring""" from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _A = 10 def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lo...
171
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a : int = { 'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'], 'tokenization_xlm': ['XLMToken...
72
'''simple docstring''' a : Dict = 6_5521 def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' snake_case_ = 1 snake_case_ = 0 for plain_chr in plain_text: snake_case_ = (a + ord(__UpperCAmelCase...
72
1
"""simple docstring""" import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --...
132
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( Autoencoder...
132
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_...
177
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClass...
177
1
'''simple docstring''' import logging from transformers.configuration_utils import PretrainedConfig lowerCAmelCase : Dict =logging.getLogger(__name__) class a_ ( __lowercase ): __A = """masked_bert""" def __init__( self : Un...
223
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : Dict = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/m...
270
0
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _a (lowerCAmelCase__ ): '''simple docstring''' def __init__( self ...
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
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class _lowerCAmelCase ( datasets.BuilderConfig ): """simpl...
344
'''simple docstring''' class _lowerCAmelCase : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Union[str, Any]: A_ : Optional[Any] = name A_ : Dict = value A_ : Union[str, Any] = weigh...
344
1
import numpy as np def A ( a_ ,a_ ,a_ = 1e-12 ,a_ = 100 ,) -> tuple[float, np.ndarray]: assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs a...
245
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ :Any = logging.get_logger(__name__) A_ :List[Any] = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/decision-transformer-gym-ho...
245
1
'''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 A_ : str = logging.get_logger(__name__) A_ : Optional[int] ...
215
"""simple docstring""" from typing import Any class lowerCamelCase : def __init__( self : Tuple , __UpperCAmelCase : Any ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ = data SCREAMING_SNAKE_CASE__ = None def __repr__(...
165
0
"""simple docstring""" import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHE...
353
"""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 _UpperCamelCase : Union[str, Any] = logging.get_logger(__name__)...
186
0
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = [] if len(SCREAMING_SNAKE_CASE__ ) == 1: return [nums.copy()] for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): snake_case_ = nums.pop(0 ) snake_case_ ...
8
def UpperCamelCase ( __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def UpperCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 ...
305
0
"""simple docstring""" from __future__ import annotations from random import random from typing import Generic, TypeVar UpperCAmelCase =TypeVar("KT") UpperCAmelCase =TypeVar("VT") class lowerCamelCase__ ( Generic[KT, VT] ): '''simple docstring''' def ...
368
"""simple docstring""" import math from numpy import inf from scipy.integrate import quad def _A ( _a : float ): """simple docstring""" if num <= 0: raise ValueError("""math domain error""" ) return quad(_a , 0 ...
77
0
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
75
'''simple docstring''' import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class _lowerCAmelCase ( __A ): """simple docstring""" def __init__( self , _lowerCamelC...
344
0
import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput from tran...
357
from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge __snake_case = [ '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the''' '''...
78
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
36
"""simple docstring""" import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename _a = """htt...
194
0
def snake_case_ ( lowerCAmelCase_ : Dict ): if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) ...
358
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as P...
306
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class a_ ( snake_case_ ):...
58
'''simple docstring''' 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) lowerc...
58
1
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, defa...
366
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets A_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel...
296
0
from itertools import permutations def __lowerCamelCase ( __a :tuple ) -> bool: """simple docstring""" if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False ...
274
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging A : Dict = logging.get_logger(__name__) def __lowerCamelCase ( __a :int=None , __a ...
274
1
'''simple docstring''' import warnings warnings.warn( '''memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ''' '''`from accelerate import find_executable_batch_size` to avoid this warning.''', FutureWarning, )
190
'''simple docstring''' import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel lowercase__ : Optional[int] = HfApi() lowercase__ : Dict = {} # fmt: off lowercase__ : List[str] = torch.tensor([ -0.7515, ...
190
1
"""simple docstring""" import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__=1 ): '''simple docstring''' if n_shave_prefix_segments >= 0: ...
294
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' print(F"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(UpperCamelCase__ ): prin...
294
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available _lowerCAmelCase = {"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvai...
371
'''simple docstring''' from random import randint, random def UpperCamelCase ( a , a , a , a = False , a = False , a = 5 , ) -> list: '''simple docstring''' __magic_name__ = [[-1] * number_of_cells] # Create a highway without a...
98
0
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriev...
195
import math def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> bool: assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are prime...
325
0
import random def SCREAMING_SNAKE_CASE ( snake_case_ : int ): snake_case__ : str = num - 1 snake_case__ : Tuple = 0 while s % 2 == 0: snake_case__ : int = s // 2 t += 1 for _ in range(5 ...
361
import os import pytest from attr import dataclass __lowerCamelCase : Any = """us-east-1""" # defaults region @dataclass class SCREAMING_SNAKE_CASE__ : """simple docstring""" a_ = 42 a_ = "arn:aws:iam::558105141721:role/sagemaker_execution_r...
286
0
def lowerCamelCase__ ( a , a ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) _A: Union[str, Any] = str(bin(a ) )[2:] # remove the leading "0b" _A: Union[str, Any] = str(bin(a ) )[2:...
121
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_im...
121
1
'''simple docstring''' def a_ ( __snake_case : list[int] , __snake_case : str ) -> list[int]: """simple docstring""" lowerCamelCase_ =int(__snake_case ) # Initialize Result lowerCamelCase_ =[] #...
6
'''simple docstring''' import os from typing import Dict, List, Tuple, TypeVar, Union a_ : Tuple = TypeVar("""T""") a_ : Dict = Union[List[T], Tuple[T, ...]] a_ : int = Union[T, List[T], Dict[str, T]] a_ : Optional[Any] = Union[str, bytes, os.PathLike]...
6
1
def lowerCamelCase_ ( _a : int , _a : int ): '''simple docstring''' return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
345
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRCont...
345
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCAmelCase : Optional[int] = { "configuration_canine": ["CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP", "CanineConfig"], "tokenization_canine": ["CanineT...
357
import inspect import unittest from transformers import MobileNetVaConfig 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_configuration_common import ConfigTester from ...test...
110
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''facebook/timesformer''': '''https://huggingface.co/facebook/timesformer/resolve/main/config.json''...
79
'''simple docstring''' from PIL import Image def __lowercase ( __lowercase , __lowercase ) -> Image: '''simple docstring''' _A = (259 * (level + 255)) / (255 * (259 - level)) def contrast(__lowercase ) -> int: return int(128 + fa...
79
1
'''simple docstring''' __A : List[str] = [ (1_000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def UpperCAmelCase ( lowerCamel...
354
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __A : Dict = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pyto...
8
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils i...
29
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCAmelCase ( a__ , a__ , a__=1024 , a__=1024 , a__=False , **a__ ) -> Optional[Any]: __...
6
0
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ = { """configuration_autoformer""": [ """AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", ...
360
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ = { """configuration_rember...
181
0
"""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 jus...
202
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
202
1
"""simple docstring""" from collections.abc import Sequence def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Sequence[int] | None = None ) -> int: if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) _lowerCAmelCase : Union[str, Any]...
126
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_avai...
126
1
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import C...
178
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, 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 impo...
178
1
def lowerCAmelCase_ ( _snake_case : int ) -> str: '''simple docstring''' __magic_name__ : Any = int(_snake_case ) if decimal in (0, 1): # Exit cases for the recursion return str(_snake_case ) __magic_name__ : List[Any] = divmod(_snake_c...
365
from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from ...
41
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridCon...
118
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in ...
81
0
'''simple docstring''' # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class ...
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == ...
0
1
'''simple docstring''' import sys def a ( __a ) -> List[str]: '''simple docstring''' UpperCamelCase__ :Optional[int] = len(lowerCAmelCase_ ) UpperCamelCase__ :Tuple = [[0 for x in range(lowerCAmelCase_ )] for x in range(lowerCAmelCase_ )] Up...
97
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : str = { '''configuration_roformer''': ['''ROFORM...
54
0
"""simple docstring""" import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING f...
56
"""simple docstring""" import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def _lowerca...
56
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase = { '''configuration_efficientformer''': [ '''EFFICIENTFORMER_PRETRAINED_...
141
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def __lowercase ( ) ->int: """simple docstring""" lowercase : Tuple = HfArgumentParser(_UpperCamelCase ) lowercase : List[str] = parser.parse_args_in...
337
0
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, ...
365
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random...
296
0