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
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxF...
262
from typing import Union import fire import torch from tqdm import tqdm def lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ = "cpu" , lowerCAmelCase_ = None )-> None: lowerCAmelCase_ : str = torch.load(lowerCAmelCase_ , map_location=low...
262
1
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 UpperCAmelCase : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase : str = """\ @...
148
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = (PNDMScheduler,) _lowercase : str = (("""num_infe...
148
1
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def UpperCamelCase (lowercase_: dict ) -> tuple: return (data["dat...
192
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging A_ : str = logging.get_logger(__name__) A_ : Optional[Any] ...
192
1
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def lowerCamelCase ( a_ = "" ) -> dict[str, float]: lowerCAmelCase_ = url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' lowerCAmelCase_ = ...
14
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemant...
14
1
'''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__ : List[Any] ={ '''configuratio...
70
"""simple docstring""" import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transfor...
264
0
'''simple docstring''' 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 impo...
17
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __a = { 'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Layo...
17
1
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 LearnedClassifierFre...
30
import os def a ( ): '''simple docstring''' lowercase_ = os.path.join(os.path.dirname(snake_case__ ) , '''num.txt''' ) with open(snake_case__ ) as file_hand: return str(sum(int(snake_case__ ) for line in file_hand ) )[:10] ...
30
1
"""simple docstring""" def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def count_of_possible_combinations(SCREAMING_SNAKE_CASE__ ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_co...
355
import datasets lowercase_ = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and S...
194
0
"""simple docstring""" def lowercase_ ( ) -> List[Any]: '''simple docstring''' __lowerCamelCase : Union[str, Any] = 0 for i in range(1 , 1001 ): total += i**i return str(_UpperCamelCase )[-10:] if __name__ ...
135
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def __lowercase ( _UpperCamelCase = 8 ) ->str: """simple docstring""" lowercase : List[str] = ascii_letters + digits + punctuation ...
337
0
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): UpperCAmelCase : Optional[Any] = { """linear""": PIL.Image.Resampling.BILINEAR, ...
148
import unittest from transformers import AutoTokenizer, NystromformerConfig, 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, ids_tensor, random_atte...
148
1
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _a ( UpperCamelCase__ , UpperCamelCase__): """simple docstring""" @r...
149
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_co...
149
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { 'google/vivit-b-16x2-kinetics400': ( 'https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json' ), #...
368
'''simple docstring''' import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @requir...
43
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class _snake_case : def __init__( self , _lowerCamelCase): UpperCAmelCase__ : Any = data UpperCAmelCase__ ...
163
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import ...
163
1
from __future__ import annotations def a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" UpperCamelCase : List[Any] = get_failure_array(SCREAMING_SNAKE_CASE_ ) # 2) St...
315
from __future__ import annotations import collections import pprint from pathlib import Path def a ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" return "".join(sorted(SCREAMING_SNAKE_CASE_ ) ) def a ( SCREAMIN...
315
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a : Union[str, Any] = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfi...
105
'''simple docstring''' from __future__ import annotations from fractions import Fraction def __snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ): return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) ...
55
0
"""simple docstring""" import numpy as np def __UpperCAmelCase ( UpperCAmelCase_ : np.array ) -> np.array: '''simple docstring''' return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
95
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_rofo...
95
1
import unittest from transformers import 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 from ...test_modeling_common import ModelTesterMixin, ids_tensor from ....
287
def _a ( lowerCamelCase ): return " ".join( """""".join(word[::-1] ) if len(lowerCamelCase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("""Hey wollef sroirraw"""))
287
1
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowercase_ ( A__ ) -> ...
137
import unittest from transformers import LiltConfig, 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 from ...test_modeling_common import ModelTesterMixi...
137
1
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when sw...
74
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging A_ : str = logging.get_logger(__name__) # TODO: upload to AWS A_ : Optional[int] = { "yjernite/retribert-base-uncased": ( "https://huggingface....
165
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase : Optional[Any] = { "configuration_whisper": ["WHISPER_PRETRAINED...
358
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling...
99
0
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets....
88
'''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, ToTensor fr...
58
0
def UpperCamelCase ( __lowerCamelCase : int ): if n == 1 or not isinstance(__lowerCamelCase , __lowerCamelCase ): return 0 elif n == 2: return 1 else: snake_case : Optional[Any] = [0, 1] for i in...
10
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py __lowerCamelCase = """.""" if __name__ == "__main__": __lowerCamelCase = os.path.join(REPO_PATH, """utils/documentation_tests.txt""") ...
10
1
"""simple docstring""" from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from ...
91
"""simple docstring""" import datasets from .evaluate import evaluate A: Optional[Any] = "\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv p...
109
0
'''simple docstring''' 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(): ...
67
'''simple docstring''' 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 Ba...
67
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_torch_multi...
155
"""simple docstring""" from __future__ import annotations def lowercase (snake_case__ : list[int] ) -> list[int]: # This function is recursive '''simple docstring''' lowerCAmelCase = len(snake_case__ ) # If the array contains only...
155
1
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def snake_case_ ( __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CASE : np.ndarray , __SCREAMING_SNAKE_CAS...
264
'''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...
264
1
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.im...
193
from __future__ import annotations import math def UpperCamelCase__( UpperCamelCase__ : int )->bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, ...
193
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ = { 'configuration_xlm_roberta_xl': [ 'XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaXLConfig', 'XLMRobertaXL...
365
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer UpperCAmelCase_ = logging.getLogger(__name__) def lowerCAmelCase_ ( ) -> Any: UpperCamelCase__ : Dict = argparse.Arg...
247
0
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..u...
92
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ = get_tests_dir("""fixtures/spiece.mode...
92
1
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCAmelCase_ : Any = logging.getLogger(__name__) class lowerCAmelCase__ : '''simple docstri...
370
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ ...
318
0
def A_ ( A__ , A__ ) -> str: a__ : list[list[str]] = [[] for _ in range(A__ )] a__ : Optional[int] = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1 or len(A__ ) <= key: retur...
99
from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import P...
99
1
"""simple docstring""" import os import sys import transformers _a = '3' print('Python version:', sys.version) print('transformers version:', transformers.__version__) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) ...
370
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers im...
144
0
import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_m...
295
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enabl...
295
1
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_diffusers_config, renew_vae_at...
354
import baseaa def lowerCamelCase ( a_ ) -> bytes: return baseaa.baaencode(string.encode('utf-8' ) ) def lowerCamelCase ( a_ ) -> str: return baseaa.baadecode(a_ ).decode('utf-8' ) if __name__ == "__main__": lowerCamelC...
14
0
'''simple docstring''' from __future__ import annotations class snake_case__ : def __init__( self : List[Any] , _A : List[Any] ) -> Union[str, Any]: UpperCAmelCase_ : Optional[int] = TypeError( '''Matrices must be formed from a list...
304
'''simple docstring''' import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor ...
163
0
def A ( lowercase ) -> int: '''simple docstring''' if not isinstance(lowercase , lowercase ): UpperCamelCase = f'''Input value of [number={number}] must be an integer''' raise TypeError(lowercase ) if number < 1: UpperCamelCase = f'''Input value of [numb...
110
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import ...
110
1
from collections import namedtuple _lowerCamelCase : Tuple = namedtuple("""from_to""", """from_ to""") _lowerCamelCase : Dict = { """cubicmeter""": from_to(1, 1), """litre""": from_to(0.001, 1000), """kilolitre""": from_to(1, 1), """gallon""": from_to(0.00_454, 264...
14
"""simple docstring""" def UpperCamelCase ( _lowerCAmelCase : int, _lowerCAmelCase : int ) -> int: _UpperCAmelCase : str = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): _UpperCAmelCase : Dict = n - k # Calculat...
246
0
from math import ceil, sqrt def snake_case_ (__A : int = 1_0_0_0_0_0_0 ) -> int: __lowerCAmelCase : Optional[Any] = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __lowerCAmelCase : List[...
139
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __UpperCAmelCase = """2.13.1""" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("""3.7""...
139
1
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel UpperCAmelCase__ = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """atte...
289
"""simple docstring""" import math class a : def lowerCAmelCase_ ( self : Tuple , __lowerCAmelCase : list[list[float]] , __lowerCAmelCase : list[int] ): _UpperCAmelCase = 0.0 _UpperCAmelCase = 0.0 for i in range(len(__lowerCAm...
289
1
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEX...
81
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class a ( __lowerCAmelCase ): """simple docstring""" def __init__( self , *lowerCAmelC...
81
1
"""simple docstring""" import numpy # List of input, output pairs __UpperCAmelCase = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) __UpperCAmelCase = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) __UpperCAmelCa...
84
import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTeste...
244
0
import requests _UpperCAmelCase = """""" # <-- Put your OpenWeatherMap appid here! _UpperCAmelCase = """https://api.openweathermap.org/data/2.5/""" def UpperCamelCase ( __lowercase : str = "Chicago" ,__lowercase : str = APPID ): '''simple docstring''' ...
350
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked befor...
192
0
"""simple docstring""" def A_ ( _lowercase ): '''simple docstring''' snake_case_ :Any = [0] * len(_lowercase ) snake_case_ :List[str] = [] snake_case_ :int = [] snake_case_ :Union[str, Any] = 0 for values in graph.values(): ...
66
from heapq import heappop, heappush import numpy as np def snake_case( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , ) -> tuple[float | int, list[tuple[int, int]]]: '''simple docstring''' lowercase , lowercase : Op...
308
0
'''simple docstring''' import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig _lowercase : str = logging.get_logger(__name__) _lowercase : ...
91
'''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 UpperCamelCase__: __magic_name__ : List[str] __magic_name_...
91
1
'''simple docstring''' from __future__ import annotations from typing import TypedDict class UpperCAmelCase_ (UpperCamelCase_ ): """simple docstring""" lowerCamelCase : str lowerCamelCase : int def UpperCAmelCase__ ( UpperCAmelCase_ : List[str] ...
185
"""simple docstring""" from __future__ import annotations from typing import TypedDict class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str _SCREAMING_SNAKE_CASE :int def _lowercase ( __lowerCAmelCase ) -> list[str]: if not ...
132
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available lowerCAmelCase__ : Any = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"...
37
'''simple docstring''' import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorc...
37
1
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin A__ : Any = """ Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot...
185
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : List[str] ...
185
1
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 BatchEncoding from ...utils imp...
328
from functools import lru_cache def lowerCAmelCase_ ( UpperCamelCase_ ) -> set: UpperCamelCase_ = 2 UpperCamelCase_ = set() while i * i <= n: if n % i: i += 1 else: n //= i ...
328
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { "SCUT-DLVCLab/lilt-roberta-en-base": ( "https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.js...
252
import enum import shutil import sys UpperCAmelCase, UpperCAmelCase : Union[str, Any] = shutil.get_terminal_size() UpperCAmelCase : Dict = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} class __lowercase ( enum.Enum ): """simple docstring""" UpperCamel...
252
1
"""simple docstring""" import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...on...
241
"""simple docstring""" # 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/licen...
241
1
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 lowercase__ =logging.get_logger(__name__) lowercase__ ={ "facebook/data2vec-vision-base-ft": ...
216
# 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/LICENSE-2.0 # # Unless required ...
342
0
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require...
350
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = """▁""" __lowerCam...
10
0
import math import unittest def A_ ( a ): """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif numb...
253
'''simple docstring''' import math def __UpperCAmelCase ( a_: int ): return math.sqrt(a_ ) * math.sqrt(a_ ) == num def __UpperCAmelCase ( a_: int ): _UpperCAmelCase : Dict = 0 _UpperCAmelCase : List[str] = n while ...
145
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : str = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ]...
369
from collections import namedtuple import requests from lxml import html # type: ignore _lowerCamelCase : Dict = namedtuple("covid_data", "cases deaths recovered") def _UpperCAmelCase (UpperCamelCase_ : str = "https://www.worldometers.info/coronavirus/" ): '''simple docstring''' ...
159
0
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class lowercase_ ( a__ ): def __init__( self , a , a ): super().__init__() se...
80
'''simple docstring''' def _UpperCamelCase ( __A ) -> int: '''simple docstring''' UpperCamelCase__ = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _UpperCamelCase ( __A = 100 ) ...
80
1
from itertools import permutations def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 !=...
352
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: sna...
200
0
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__) lowerCamelCase__ = { "hustvl/yolos-small":...
302
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py a : L...
114
0
'''simple docstring''' import functools def _snake_case ( A , A ) -> int: # Validation if not isinstance(A , A ) or not all(isinstance(A , A ) for day in days ): raise ValueError('''The parameter days should be a list of integers''' ...
359
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_...
228
0
"""simple docstring""" import mpmath # for roots of unity import numpy as np class a__ : def __init__( self , _a=None , _a=None ): lowercase : Tuple = list(poly_a or [0] )[:] lowercase : List[str] = list(poly_b or [0]...
202
import math 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 # Copied f...
65
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__ : Optional[int] = logging.get_logger(__name__) A__ : Any = { 'shi-labs/dinat-mini-i...
350
"""simple docstring""" from __future__ import annotations from collections import namedtuple def _snake_case ( lowerCamelCase__ : float , lowerCamelCase__ : float , lowerCamelCase__ : float ) -> tuple: lowerCamelCase_ : Optional[Any] =...
209
0
'''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_...
37
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mas...
306
0
"""simple docstring""" import argparse import os import re import packaging.version UpperCAmelCase : Optional[Any] = 'examples/' UpperCAmelCase : List[Any] = { 'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")...
320
"""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 MaskGenerationPipeline from ...
320
1
"""simple docstring""" def __lowercase ( _a , _a ): if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) snake_case_ : Dict = str(bin(_a ) )[2:] # remove the leading "0b" snake_case_ : Optional[int] = str(bin(_a ) )[2...
264
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class ...
264
1
"""simple docstring""" import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def _snake_case ( lowerCamelCase__ : List[str] ) -> str: if "model" in orig_key: lowerCamelCase_ : Dict =orig_key.replace("model." , ""...
209
"""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...
209
1
'''simple docstring''' 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 impor...
27
"""simple docstring""" import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case_...
60
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, lo...
366
"""simple docstring""" import argparse import datetime def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Optional[Any] = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday',...
182
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, requir...
271
"""simple docstring""" from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMSchedu...
202
0
def lowerCAmelCase( __lowerCamelCase ): __a = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def lowerCAmelCase( __lowerCamelCase = 100 ): __a = 1 __a = 2 for i in range(2 , max...
197
from ..utils import DummyObject, requires_backends class a__ ( metaclass=__snake_case ): A__ : List[Any] = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> Any: requires_backends(...
197
1
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_av...
7
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy,...
7
1
def lowerCAmelCase_ ( _snake_case : Optional[int] ) -> Tuple: '''simple docstring''' __magic_name__ : str = len(lowercase__ ) for _ in range(lowercase__ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: _...
362
import re import string import numpy as np import datasets snake_case : Any = "\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" snake_case : Optional[Any] = "\nArgs:\n predict...
41
0
import argparse import os import re import packaging.version A__ : Dict = '''examples/''' A__ : Any = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^...
103
from pathlib import Path import fire def UpperCamelCase( __UpperCamelCase : str ,__UpperCamelCase : str ,__UpperCamelCase : int ): lowerCAmelCase_ : List[str] = Path(__UpperCamelCase ) lowerCAmelCase_ : Union[str, Any] = Path(__UpperCamelCase ) d...
103
1
import os import jsonlines import numpy as np from tqdm import tqdm snake_case_ = 2048 snake_case_ = 4096 snake_case_ = 42 snake_case_ = os.environ.pop('PROCESS_TRAIN', 'false') snake_case_ = {'null': 0, 'short': 1, '...
366
from __future__ import annotations snake_case_ = [True] * 1000001 snake_case_ = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): snake_case_ = False i += 1 def lowerCamelCase__ ( s...
238
0
import random from typing import Any def _UpperCAmelCase ( a__): '''simple docstring''' for _ in range(len(a__)): a_ : Tuple = random.randint(0 , len(a__) - 1) a_ : List[str] = random.randint(0 , len(a__) - 1) a_ , a_ : str ...
248
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_i...
248
1
"""simple docstring""" from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __UpperCamelCase = 0 __UpperCamelCase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0,...
38
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> bool: SCREAMING_SNAKE_CASE = int(number**0.5 ) return number == sq * sq def ...
38
1
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils i...
6
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Optional[int] = { 'configuration_whisper': ['WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Whisper...
6
1
"""simple docstring""" import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from tra...
253
"""simple docstring""" import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, ...
253
1
from typing import List import numpy as np def UpperCAmelCase ( a_ ) -> int: """simple docstring""" __A = {key: len(a_ ) for key, value in gen_kwargs.items() if isinstance(a_ , a_ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError...
15
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ...
80
0
import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def lowercase__ ( __snake_c...
145
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging ...
145
1
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 lowercase_ ( _...
184
"""simple docstring""" import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCAmelCase__ : List[str...
25
0
'''simple docstring''' 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_i...
101
'''simple docstring''' from functools import lru_cache @lru_cache def UpperCAmelCase__ ( UpperCAmelCase__ ) -> int: if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__m...
101
1
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 script from the ro...
169
"""simple docstring""" # 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/LICENS...
173
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor _a = logging.get_logger(__name__) class _lowerCAmelCase ( lowercase ): """simple docstring""" def __init__( self : int...
371
"""simple docstring""" import re from filelock import FileLock try: import nltk _a = True except (ImportError, ModuleNotFoundError): _a = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _A ( UpperCamelCase_ ...
144
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case__ : List[str] = { '''configuration_lxmert''': ['''LXMERT_PRETRAINED_CONFIG_A...
60
"""simple docstring""" 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 .to...
60
1
'''simple docstring''' import unittest from knapsack import knapsack as k class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" _snake_case = 0 _snake_case = [0] _sna...
160
'''simple docstring''' class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = name _snake_case = value _snake_case ...
160
1
'''simple docstring''' import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=(), __UpperCAmelCase=None, __UpperCAm...
56
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simp...
56
1
'''simple docstring''' from __future__ import annotations def UpperCAmelCase__ ( UpperCAmelCase__ ) -> list: if len(UpperCAmelCase__ ) == 0: return [] A_ , A_ = min(UpperCAmelCase__ ), max(UpperCAmelCase__ ) A_ = int(max_value - min_value ...
101
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCamelCase = { '''configuration_blenderbot''': [ ...
101
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 tor...
94
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExt...
236
0
import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __lowerCamelCase : Optional[int] = argparse.ArgumentParser( description=( '''Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadMod...
204
from __future__ import annotations __lowerCamelCase : Dict = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __lowerCamelCase : Union[str, Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def __SCREAMING_SNAKE_CASE ( __UpperCamelCas...
204
1
from __future__ import annotations def __snake_case ( _lowerCAmelCase : list[int] , _lowerCAmelCase : int ) -> bool: if len(__lowercase ) == 0: return False A_ : str = len(__lowercase ) // 2 if a_list[midpoint] == item: return True if ite...
300
import numpy as np def a_ ( __lowercase : np.array ) -> np.array: return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
282
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...
187
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins UpperCAmelCase = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def _snake_case ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : i...
187
1
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def __lowerCamelCase ( lowerCamelCase__ , lowerC...
130
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __lowerCamelCase ( ): """simple docstring""" lowercase__ : Dict = ArgumentParser( description=( ...
130
1
from functools import lru_cache @lru_cache def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int) -> int: '''simple docstring''' if num < 0: raise ValueError("Number should not be negative.") return 1 if num in (0, 1) else num * facto...
367
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase : Optional[int] = get_tests_dir('fix...
151
0
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __lowerCamelCase ( snake_case__ ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CAS...
306
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def __lowercase ( ): print('Making key files...' ) make_key_files('rsa' , 1_0_2_4 ) print('Key files generation succes...
240
0
import socket def lowerCamelCase__ ( ) -> str: __snake_case = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) __snake_case = socket.gethostname() __snake_case = 1_2312 sock.connect((host, port) ) sock.send(B'''Hello server!''' ) ...
356
# Algorithm for the pigeonhole sorting def lowerCamelCase__ ( snake_case_ : int ) -> Optional[int]: __snake_case = min(snake_case_ ) # min() finds the minimum value __snake_case = max(snake_case_ ) # max() finds the maximum value ...
238
0
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) snake_case : Optional[Any] = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, ...
94
import string import numpy def __lowerCamelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ): """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , UpperCAmelCase_ ) class _snake_case : SCREAMING_SNAKE_CASE__ = ...
94
1
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance UpperCamelCase_ =637_8137.0 UpperCamelCase_ =635_6752.31_4245 UpperCamelCase_ =6_378_137 def a_ ( _lowercase , _lowercase...
128
"""simple docstring""" from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils i...
128
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 ...
278
from typing import Union import fire import torch from tqdm import tqdm def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase = "cpu" ,lowercase = None ) -> None: snake_case : int = torch.load(lowercase ,map_location=lowercase ) for k, v in tqdm(state_...
124
0
'''simple docstring''' 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""", exi...
363
'''simple docstring''' def lowercase (): """simple docstring""" _lowerCAmelCase : Optional[int] = [3_1, 2_8, 3_1, 3_0, 3_1, 3_0, 3_1, 3_1, 3_0, 3_1, 3_0, 3_1] _lowerCAmelCase : int = 6 _...
25
0
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _lowercase ( unittest.TestCase ): """simple docstring""" def UpperCamelCase_ (self ): """simple docstring""" debug_launcher(t...
227
'''simple docstring''' 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 AutoImageProcessor, ViTImageProcessor from transformers.testing_utils imp...
265
0
'''simple docstring''' import math def UpperCAmelCase ( lowerCamelCase_ :int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of ...
8
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs i...
8
1